servicesToptal commited on
Commit
18e8272
·
verified ·
1 Parent(s): 7c92282

Update dataset (part 2)

Browse files
Files changed (17) hide show
  1. README.md +1 -1
  2. harbor/tasks/manifest.json +1 -0
  3. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/Dockerfile +19 -0
  4. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/capture.py +28 -0
  5. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/capture_submission.py +157 -0
  6. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/docker-compose.yaml +11 -0
  7. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/sanitize.py +25 -0
  8. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/instruction.md +13 -0
  9. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/solution/reference.patch +755 -0
  10. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/solution/solve.sh +761 -0
  11. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/task.toml +26 -0
  12. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/Dockerfile +9 -0
  13. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/config.json +211 -0
  14. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/docker-compose.yaml +6 -0
  15. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/evidence.py +123 -0
  16. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/test.sh +3 -0
  17. harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/verify.py +235 -0
README.md CHANGED
@@ -297,7 +297,7 @@ empty change scores 0, and the reference fix scores 1.0 with every criterion
297
  equal to the task's original grading. The folder contains the reference fixes
298
  and the hidden graders, as the rows of this dataset do.
299
 
300
- 10 more (badger, bazel-remote, geode, kratos, microblogpub, open-xml-sdk, openfire, terser, umya, zettlr) are packaged and are being re-checked; they are added
301
  as each one passes.
302
 
303
  Nine tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
 
297
  equal to the task's original grading. The folder contains the reference fixes
298
  and the hidden graders, as the rows of this dataset do.
299
 
300
+ 9 more (badger, bazel-remote, geode, kratos, open-xml-sdk, openfire, terser, umya, zettlr) are packaged and are being re-checked; they are added
301
  as each one passes.
302
 
303
  Nine tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
harbor/tasks/manifest.json CHANGED
@@ -4,6 +4,7 @@
4
  "celery_retry_expires_countdown_contract",
5
  "coredns_rewrite_svcb_opt",
6
  "epicyon_deleted_post_announce_cache_contract",
 
7
  "rope_rename_all_reexport_owners_contract",
8
  "zod_json_schema_target_legality"
9
  ]
 
4
  "celery_retry_expires_countdown_contract",
5
  "coredns_rewrite_svcb_opt",
6
  "epicyon_deleted_post_announce_cache_contract",
7
+ "microblogpub_deleted_object_resurrect_lookup_contract",
8
  "rope_rename_all_reexport_owners_contract",
9
  "zod_json_schema_target_legality"
10
  ]
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-microblogpub:source-v4 AS sanitized
2
+ USER root
3
+ COPY sanitize.py capture.py capture_submission.py /opt/task-tools/
4
+ RUN HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 /opt/hudvenv/bin/python /opt/task-tools/sanitize.py
5
+ FROM scratch
6
+ COPY --from=sanitized / /
7
+ ENV PATH="/opt/agentvenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
8
+ ENV LANG="C.UTF-8"
9
+ ENV PYTHONUNBUFFERED="1"
10
+ ENV PYTHONNOUSERSITE="1"
11
+ ENV PYTHONPATH="/workspace/repo"
12
+ ENV PYTHONDONTWRITEBYTECODE="1"
13
+ ENV HOME="/tmp/agent-home"
14
+ ENV GOCACHE="/tmp/agent-home/.cache/go-build"
15
+ ENV HUD_TELEMETRY_ENABLED="false"
16
+ ENV HUD_CLI_ANALYTICS_ENABLED="0"
17
+ WORKDIR /workspace/repo
18
+ USER 1000:1000
19
+ CMD ["sleep", "infinity"]
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/capture.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture a patch against protected baseline history inside the agent sandbox."""
2
+
3
+ import json
4
+ import os
5
+ import shutil
6
+ import sys
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ sys.path.insert(0, "/opt/task-tools")
11
+ from capture_submission import capture_submission # noqa: E402
12
+
13
+ with tempfile.TemporaryDirectory(prefix="capture-") as directory:
14
+ git_dir = Path(directory) / "git"
15
+ shutil.copytree("/opt/task-tools/baseline.git", git_dir)
16
+ os.environ.update(
17
+ GIT_DIR=str(git_dir),
18
+ GIT_WORK_TREE="/workspace/repo",
19
+ GIT_CONFIG_NOSYSTEM="1",
20
+ GIT_CONFIG_GLOBAL="/dev/null",
21
+ )
22
+ print(
23
+ json.dumps(
24
+ capture_submission(
25
+ Path("/workspace/repo"), Path("/workspace/submissions/submitted.patch")
26
+ )
27
+ )
28
+ )
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/capture_submission.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture tracked and new SWE files without changing the agent's Git index."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import shlex
8
+ import subprocess
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+ MAX_SUBMISSION_BYTES = 32 * 1024 * 1024
13
+
14
+
15
+ def capture_submission(
16
+ repository: Path, output: Path, *, max_bytes: int = MAX_SUBMISSION_BYTES
17
+ ) -> dict[str, object]:
18
+ """Write a bounded binary patch including nonignored new files.
19
+
20
+ Parameters
21
+ ----------
22
+ repository : Path
23
+ Git checkout root. HEAD must remain the task's initial commit.
24
+ output : Path
25
+ Submission path outside the checkout. Replaces any prior submission.
26
+ max_bytes : int, default: 33554432
27
+ Maximum emitted patch size. Oversized submissions fail without a patch.
28
+
29
+ Returns
30
+ -------
31
+ dict
32
+ Patch size, SHA-256, base commit and capture format for trial evidence.
33
+
34
+ Raises
35
+ ------
36
+ ValueError
37
+ If paths or the limit are invalid, or the patch exceeds the limit.
38
+ OSError, subprocess.CalledProcessError, RuntimeError
39
+ If capture fails. No partial patch is published.
40
+
41
+ Notes
42
+ -----
43
+ Uses a temporary index to combine staged, unstaged and untracked changes.
44
+ Ignored untracked files are excluded. This is a capture bound, not a total
45
+ sandbox disk quota or a security boundary against a malicious Git runtime.
46
+ """
47
+ if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
48
+ raise ValueError("max_bytes must be a positive integer")
49
+ repository = repository.resolve(strict=True)
50
+ if output.is_symlink():
51
+ raise ValueError("Submission output must not be a symlink")
52
+ output = output.resolve()
53
+ if output.is_relative_to(repository):
54
+ raise ValueError("Submission output must be outside the repository")
55
+ output.parent.mkdir(parents=True, exist_ok=True)
56
+ output.unlink(missing_ok=True)
57
+ root = subprocess.check_output(
58
+ ["git", "rev-parse", "--show-toplevel"], cwd=repository, text=True
59
+ ).strip()
60
+ if Path(root).resolve() != repository:
61
+ raise ValueError("repository must be the Git checkout root")
62
+ base = subprocess.check_output(
63
+ ["git", "rev-parse", "--verify", "HEAD^{commit}"], cwd=repository, text=True
64
+ ).strip()
65
+ with tempfile.TemporaryDirectory(prefix="submission-", dir=output.parent) as directory:
66
+ temporary = Path(directory)
67
+ env = {**os.environ, "GIT_INDEX_FILE": str(temporary / "index")}
68
+ for arguments in (["read-tree", base], ["add", "--all", "--", "."]):
69
+ subprocess.run(["git", *arguments], cwd=repository, env=env, check=True)
70
+ patch = temporary / "patch"
71
+ size = 0
72
+ digest = hashlib.sha256()
73
+ with (
74
+ patch.open("wb") as stream,
75
+ tempfile.TemporaryFile() as errors,
76
+ subprocess.Popen(
77
+ [
78
+ "git",
79
+ "diff",
80
+ "--cached",
81
+ "--binary",
82
+ "--full-index",
83
+ "--no-renames",
84
+ "--no-ext-diff",
85
+ "--no-textconv",
86
+ "--no-color",
87
+ "--src-prefix=a/",
88
+ "--dst-prefix=b/",
89
+ base,
90
+ ],
91
+ cwd=repository,
92
+ env=env,
93
+ stdout=subprocess.PIPE,
94
+ stderr=errors,
95
+ ) as process,
96
+ ):
97
+ assert process.stdout is not None
98
+ try:
99
+ while chunk := process.stdout.read(65536):
100
+ size += len(chunk)
101
+ if size > max_bytes:
102
+ raise ValueError(f"Submission exceeds {max_bytes} bytes")
103
+ stream.write(chunk)
104
+ digest.update(chunk)
105
+ except BaseException:
106
+ process.kill()
107
+ process.wait()
108
+ raise
109
+ if process.wait():
110
+ errors.seek(0)
111
+ raise RuntimeError(
112
+ "Git patch capture failed: " + errors.read(4096).decode(errors="replace")
113
+ )
114
+ patch.replace(output)
115
+ return {
116
+ "bytes": size,
117
+ "sha256": digest.hexdigest(),
118
+ "base_commit": base,
119
+ "format": "git-binary-v1",
120
+ }
121
+
122
+
123
+ def submission_command(*, max_bytes: int = MAX_SUBMISSION_BYTES) -> str:
124
+ """Build the trusted command recorded before Harbor collects artifacts.
125
+
126
+ Parameters
127
+ ----------
128
+ max_bytes : int, default: 33554432
129
+ Maximum emitted patch bytes.
130
+
131
+ Returns
132
+ -------
133
+ str
134
+ Shell command carrying this exact helper into the solver runtime.
135
+
136
+ Raises
137
+ ------
138
+ ValueError
139
+ If the size limit is invalid.
140
+ """
141
+ if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
142
+ raise ValueError("max_bytes must be a positive integer")
143
+ return "python -c " + shlex.quote(Path(__file__).read_text()) + f" --max-bytes {max_bytes}"
144
+
145
+
146
+ def main() -> None:
147
+ """Capture the submission and print its identity as trial evidence."""
148
+ parser = argparse.ArgumentParser(description=__doc__)
149
+ parser.add_argument("--repository", type=Path, default=Path("/testbed"))
150
+ parser.add_argument("--output", type=Path, default=Path("/workspace/submitted.patch"))
151
+ parser.add_argument("--max-bytes", type=int, default=MAX_SUBMISSION_BYTES)
152
+ args = parser.parse_args()
153
+ print(json.dumps(capture_submission(args.repository, args.output, max_bytes=args.max_bytes)))
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/docker-compose.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ main:
3
+ pids_limit: 512
4
+ security_opt:
5
+ - no-new-privileges:true
6
+ volumes:
7
+ - type: tmpfs
8
+ target: /logs/verifier
9
+ tmpfs:
10
+ mode: 448
11
+ size: 1048576
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/environment/sanitize.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Remove private task assets and history when building the agent-only image."""
2
+
3
+ import asyncio
4
+ import os
5
+ import shutil
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ sys.path.insert(0, "/app")
10
+ from env import _setup # noqa: E402
11
+
12
+ asyncio.run(_setup())
13
+ # The new history contains only the public baseline. Preserve a root-owned
14
+ # copy so capture can ignore agent-controlled refs, hooks and Git configuration.
15
+ shutil.copytree("/workspace/repo/.git", "/opt/task-tools/baseline.git")
16
+ for path in Path("/opt/task-tools/baseline.git").rglob("*"):
17
+ os.chown(path, 0, 0)
18
+ path.chmod(0o755 if path.is_dir() else 0o644)
19
+ for name in ("/hud", "/app", "/root/.cache", "/root/.hud"):
20
+ if Path(name).exists():
21
+ shutil.rmtree(name)
22
+ # Capture runs on the base interpreter under one name, whatever the image calls it.
23
+ os.symlink(os.path.realpath(sys.executable), "/opt/task-tools/python")
24
+ Path("/workspace/submissions").mkdir()
25
+ os.chown("/workspace/submissions", 1000, 1000)
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/instruction.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Please make your changes directly in /workspace/repo.
2
+
3
+ Deleted posts keep coming back on our instance.
4
+
5
+ When a remote author deletes a post, their server sends us a Delete, but it often keeps serving the post for a while afterwards, and that is where the post comes back from.
6
+
7
+ I bookmarked a post by its id (or liked, boosted, or opened the reply form for it) after its author deleted it, and now it is back in the admin as a live post. A boost by someone I follow brings a deleted post back too, as a live post on my stream, and a boost that was already on my stream before the Delete keeps showing the post. Once a post is gone I can still like, boost or reply to it, and the like, boost or reply is made and sent out as if nothing happened. A post is gone once its author deleted it, or their whole account.
8
+
9
+ A Delete sent by an account that is not the post's author made us drop the author's real post when it arrived. With more than one Delete for a post on record, the post sometimes came back live and processing the author's post sometimes failed. A reply whose Delete reached us twice left its parent, ours or someone else's, at -1 replies.
10
+
11
+ Only a post's author can delete it: a Delete from anyone else changes nothing, and anything its author did not delete behaves exactly as today. Bookmarking a deleted post and opening the reply form for it keep working without an error; how you refuse a like, boost or reply to it is up to you. The test files the repository ships stay byte-for-byte as they are and green; tests of your own go in new files.
12
+
13
+ Finish with a final response when your changes are ready.
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/solution/reference.patch ADDED
@@ -0,0 +1,755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/app/admin.py b/app/admin.py
2
+ index 226b193..7205322 100644
3
+ --- a/app/admin.py
4
+ +++ b/app/admin.py
5
+ @@ -140,9 +140,19 @@ async def get_lookup(
6
+ status_code=302,
7
+ )
8
+
9
+ - actors_metadata = await get_actors_metadata(
10
+ - db_session, [ap_object.actor] # type: ignore
11
+ - )
12
+ + # Its server may still serve it after its author deleted it
13
+ + if await boxes.is_deleted_by_its_author(
14
+ + db_session,
15
+ + ap_object.ap_id,
16
+ + ap_object.actor.ap_id, # type: ignore
17
+ + ):
18
+ + logger.info(f"{ap_object.ap_id} was deleted by its author")
19
+ + ap_object = None
20
+ + error = ap.FetchErrorTypeEnum.NOT_FOUND
21
+ + else:
22
+ + actors_metadata = await get_actors_metadata(
23
+ + db_session, [ap_object.actor] # type: ignore
24
+ + )
25
+
26
+ return await templates.render_template(
27
+ db_session,
28
+ @@ -173,31 +183,41 @@ async def admin_new(
29
+ in_reply_to_object = await boxes.get_anybox_object_by_ap_id(
30
+ db_session, in_reply_to
31
+ )
32
+ + is_gone = False
33
+ if not in_reply_to_object:
34
+ logger.info(f"Saving unknwown object {in_reply_to}")
35
+ - raw_object = await ap.fetch(in_reply_to)
36
+ - await boxes.save_object_to_inbox(db_session, raw_object)
37
+ - await db_session.commit()
38
+ - in_reply_to_object = await boxes.get_anybox_object_by_ap_id(
39
+ - db_session, in_reply_to
40
+ - )
41
+ + try:
42
+ + raw_object = await ap.fetch(in_reply_to)
43
+ + except (ap.ObjectIsGoneError, ap.ObjectNotFoundError):
44
+ + # Its server stopped serving it after its author deleted it
45
+ + if not await boxes.is_deleted_at_its_origin(db_session, in_reply_to):
46
+ + raise
47
+ + logger.info(f"{in_reply_to} is gone")
48
+ + is_gone = True
49
+ + else:
50
+ + await boxes.save_object_to_inbox(db_session, raw_object)
51
+ + await db_session.commit()
52
+ + in_reply_to_object = await boxes.get_anybox_object_by_ap_id(
53
+ + db_session, in_reply_to
54
+ + )
55
+
56
+ # Add mentions to the initial note content
57
+ - if not in_reply_to_object:
58
+ + if not in_reply_to_object and not is_gone:
59
+ raise ValueError(f"Unknown object {in_reply_to=}")
60
+ - if in_reply_to_object.actor.ap_id != LOCAL_ACTOR.ap_id:
61
+ - content += f"{in_reply_to_object.actor.handle} "
62
+ - for tag in in_reply_to_object.tags:
63
+ - if tag.get("type") == "Mention" and tag["name"] != LOCAL_ACTOR.handle:
64
+ - try:
65
+ - mentioned_actor = await fetch_actor(db_session, tag["href"])
66
+ - content += f"{mentioned_actor.handle} "
67
+ - except Exception:
68
+ - logger.exception(f"Failed to lookup {mentioned_actor}")
69
+ -
70
+ - # Copy the content warning if any
71
+ - if in_reply_to_object.summary:
72
+ - content_warning = in_reply_to_object.summary
73
+ + if in_reply_to_object:
74
+ + if in_reply_to_object.actor.ap_id != LOCAL_ACTOR.ap_id:
75
+ + content += f"{in_reply_to_object.actor.handle} "
76
+ + for tag in in_reply_to_object.tags:
77
+ + if tag.get("type") == "Mention" and tag["name"] != LOCAL_ACTOR.handle:
78
+ + try:
79
+ + mentioned_actor = await fetch_actor(db_session, tag["href"])
80
+ + content += f"{mentioned_actor.handle} "
81
+ + except Exception:
82
+ + logger.exception(f"Failed to lookup {mentioned_actor}")
83
+ +
84
+ + # Copy the content warning if any
85
+ + if in_reply_to_object.summary:
86
+ + content_warning = in_reply_to_object.summary
87
+ elif with_content:
88
+ content += f"{with_content} "
89
+
90
+ @@ -1076,7 +1096,14 @@ async def admin_actions_bookmark(
91
+ inbox_object = await get_inbox_object_by_ap_id(db_session, ap_object_id)
92
+ if not inbox_object:
93
+ logger.info(f"Saving unknwown object {ap_object_id}")
94
+ - raw_object = await ap.fetch(ap_object_id)
95
+ + try:
96
+ + raw_object = await ap.fetch(ap_object_id)
97
+ + except (ap.ObjectIsGoneError, ap.ObjectNotFoundError):
98
+ + # Its server stopped serving it after its author deleted it
99
+ + if not await boxes.is_deleted_at_its_origin(db_session, ap_object_id):
100
+ + raise
101
+ + logger.info(f"{ap_object_id} is gone, nothing to bookmark")
102
+ + return RedirectResponse(redirect_url, status_code=302)
103
+ inbox_object = await boxes.save_object_to_inbox(db_session, raw_object)
104
+ inbox_object.is_bookmarked = True
105
+ await db_session.commit()
106
+ diff --git a/app/boxes.py b/app/boxes.py
107
+ index 109c210..8125c51 100644
108
+ --- a/app/boxes.py
109
+ +++ b/app/boxes.py
110
+ @@ -262,6 +262,9 @@ async def send_like(db_session: AsyncSession, ap_object_id: str) -> None:
111
+ if not inbox_object:
112
+ raise ValueError("Should never happen")
113
+
114
+ + if inbox_object.is_deleted:
115
+ + raise ValueError(f"Cannot like deleted object {ap_object_id}")
116
+ +
117
+ like_id = allocate_outbox_id()
118
+ like = {
119
+ "@context": ap.AS_CTX,
120
+ @@ -297,6 +300,9 @@ async def send_announce(db_session: AsyncSession, ap_object_id: str) -> None:
121
+ if not inbox_object:
122
+ raise ValueError("Should never happen")
123
+
124
+ + if inbox_object.is_deleted:
125
+ + raise ValueError(f"Cannot announce deleted object {ap_object_id}")
126
+ +
127
+ if inbox_object.visibility not in [
128
+ ap.VisibilityEnum.PUBLIC,
129
+ ap.VisibilityEnum.UNLISTED,
130
+ @@ -605,6 +611,8 @@ async def send_create(
131
+ in_reply_to_object = await get_anybox_object_by_ap_id(db_session, in_reply_to)
132
+ if not in_reply_to_object:
133
+ raise ValueError(f"Invalid in reply to {in_reply_to=}")
134
+ + if in_reply_to_object.is_deleted:
135
+ + raise ValueError(f"Cannot reply to deleted object {in_reply_to=}")
136
+ if not in_reply_to_object.ap_context:
137
+ logger.warning(f"Replied object {in_reply_to} has no context")
138
+ try:
139
+ @@ -1024,22 +1032,73 @@ async def get_inbox_object_by_ap_id(
140
+
141
+
142
+ async def get_inbox_delete_for_activity_object_ap_id(
143
+ - db_session: AsyncSession, activity_object_ap_id: str
144
+ + db_session: AsyncSession,
145
+ + activity_object_ap_id: str,
146
+ + object_actor_ap_id: str,
147
+ ) -> models.InboxObject | None:
148
+ + """Return the Delete received for an object, if its author sent one.
149
+ +
150
+ + Only the author of an object can delete it, a Delete sent by anyone else
151
+ + is ignored (and there may be more than one Delete for the same object)."""
152
+ return (
153
+ - await db_session.execute(
154
+ - select(models.InboxObject)
155
+ - .where(
156
+ - models.InboxObject.ap_type == "Delete",
157
+ - models.InboxObject.activity_object_ap_id == activity_object_ap_id,
158
+ + (
159
+ + await db_session.execute(
160
+ + select(models.InboxObject)
161
+ + .where(
162
+ + models.InboxObject.ap_type == "Delete",
163
+ + models.InboxObject.activity_object_ap_id == activity_object_ap_id,
164
+ + models.InboxObject.ap_actor_id == object_actor_ap_id,
165
+ + )
166
+ + .options(
167
+ + joinedload(models.InboxObject.actor),
168
+ + joinedload(models.InboxObject.relates_to_inbox_object),
169
+ + joinedload(models.InboxObject.relates_to_outbox_object),
170
+ + )
171
+ + .order_by(models.InboxObject.id)
172
+ )
173
+ - .options(
174
+ - joinedload(models.InboxObject.actor),
175
+ - joinedload(models.InboxObject.relates_to_inbox_object),
176
+ - joinedload(models.InboxObject.relates_to_outbox_object),
177
+ + )
178
+ + .unique()
179
+ + .scalars()
180
+ + .first()
181
+ + )
182
+ +
183
+ +
184
+ +async def is_deleted_by_its_author(
185
+ + db_session: AsyncSession,
186
+ + ap_id: str,
187
+ + actor_ap_id: str,
188
+ +) -> bool:
189
+ + return (
190
+ + await get_inbox_delete_for_activity_object_ap_id(db_session, ap_id, actor_ap_id)
191
+ + ) is not None
192
+ +
193
+ +
194
+ +async def is_deleted_at_its_origin(
195
+ + db_session: AsyncSession,
196
+ + ap_id: str,
197
+ +) -> bool:
198
+ + """Tell if a Delete for an object we cannot fetch anymore came from its
199
+ + author.
200
+ +
201
+ + Once its server stops serving it, the object (and so its author) is not
202
+ + known anymore: an object lives on its author's server, so only a Delete
203
+ + sent by an actor of the object's origin counts."""
204
+ + origin = urlparse(ap_id)
205
+ + for actor_ap_id in (
206
+ + await db_session.scalars(
207
+ + select(models.InboxObject.ap_actor_id).where(
208
+ + models.InboxObject.ap_type == "Delete",
209
+ + models.InboxObject.activity_object_ap_id == ap_id,
210
+ )
211
+ )
212
+ - ).scalar_one_or_none() # type: ignore
213
+ + ).all():
214
+ + actor_origin = urlparse(actor_ap_id)
215
+ + if (actor_origin.scheme, actor_origin.netloc) == (
216
+ + origin.scheme,
217
+ + origin.netloc,
218
+ + ):
219
+ + return True
220
+ + return False
221
+
222
+
223
+ async def get_outbox_object_by_ap_id(
224
+ @@ -1156,6 +1215,10 @@ async def _handle_delete_activity(
225
+ )
226
+ return
227
+
228
+ + if ap_object_to_delete.is_deleted:
229
+ + logger.info(f"{ap_object_to_delete.ap_id} is already deleted")
230
+ + return
231
+ +
232
+ logger.info(
233
+ f"Deleting {ap_object_to_delete.ap_type}/{ap_object_to_delete.ap_id}"
234
+ )
235
+ @@ -1423,6 +1486,16 @@ async def _revert_side_effect_for_deleted_object(
236
+ .values(is_deleted=True)
237
+ )
238
+
239
+ + # And take down the Announces we received for it (stream and inbox)
240
+ + await db_session.execute(
241
+ + update(models.InboxObject)
242
+ + .where(
243
+ + models.InboxObject.ap_type == "Announce",
244
+ + models.InboxObject.relates_to_inbox_object_id == deleted_ap_object.id,
245
+ + )
246
+ + .values(is_hidden_from_stream=True, is_deleted=True)
247
+ + )
248
+ +
249
+ # If it's a local replies, it was forwarded, so we also need to forward
250
+ # the Delete activity if possible
251
+ if (
252
+ @@ -1842,18 +1915,13 @@ async def _handle_create_activity(
253
+ delete_object = await get_inbox_delete_for_activity_object_ap_id(
254
+ db_session,
255
+ ro.ap_id,
256
+ + from_actor.ap_id,
257
+ )
258
+ if delete_object:
259
+ - if delete_object.actor.ap_id != from_actor.ap_id:
260
+ - logger.warning(
261
+ - f"Got a Delete for {ro.ap_id} from {delete_object.actor.ap_id}??"
262
+ - )
263
+ - return None
264
+ - else:
265
+ - logger.info("Already received a Delete for this object, deleting activity")
266
+ - create_activity.is_deleted = True
267
+ - await db_session.flush()
268
+ - return None
269
+ + logger.info("Already received a Delete for this object, deleting activity")
270
+ + create_activity.is_deleted = True
271
+ + await db_session.flush()
272
+ + return None
273
+
274
+ await _process_note_object(
275
+ db_session,
276
+ @@ -1889,6 +1957,14 @@ async def _handle_read_activity(
277
+ logger.info(f"{ro.ap_id} is already in the inbox, skipping processing")
278
+ return None
279
+
280
+ + # The object may still be served by its server after its author
281
+ + # deleted it
282
+ + if await is_deleted_by_its_author(
283
+ + db_session, ro.ap_id, wrapped_object_actor.ap_id
284
+ + ):
285
+ + logger.info(f"{ro.ap_id} was deleted by its author, skipping processing")
286
+ + return None
287
+ +
288
+ # Then process it likes it's coming from a forwarded activity
289
+ await _process_note_object(db_session, read_activity, wrapped_object_actor, ro)
290
+
291
+ @@ -2169,6 +2245,11 @@ async def _handle_announce_activity(
292
+ else:
293
+ announce_activity.is_hidden_from_stream = not is_from_following
294
+
295
+ + if relates_to_inbox_object.is_deleted:
296
+ + logger.info(f"{relates_to_inbox_object.ap_id} is deleted")
297
+ + announce_activity.is_hidden_from_stream = True
298
+ + announce_activity.is_deleted = True
299
+ +
300
+ else:
301
+ # Save it as an inbox object
302
+ if not announce_activity.activity_object_ap_id:
303
+ @@ -2201,6 +2282,9 @@ async def _handle_announce_activity(
304
+ db_session, announced_object
305
+ ),
306
+ is_hidden_from_stream=True,
307
+ + is_deleted=await is_deleted_by_its_author(
308
+ + db_session, announced_object.ap_id, announced_actor.ap_id
309
+ + ),
310
+ )
311
+ db_session.add(announced_inbox_object)
312
+ await db_session.flush()
313
+ @@ -2208,7 +2292,10 @@ async def _handle_announce_activity(
314
+ announce_activity.is_hidden_from_stream = (
315
+ not is_from_following
316
+ or announce_activity.actor.are_announces_hidden_from_stream
317
+ + or announced_inbox_object.is_deleted
318
+ )
319
+ + if announced_inbox_object.is_deleted:
320
+ + announce_activity.is_deleted = True
321
+
322
+
323
+ async def _handle_like_activity(
324
+ @@ -2602,6 +2689,11 @@ async def save_object_to_inbox(
325
+ activity_object_ap_id=ro.activity_object_ap_id,
326
+ og_meta=await opengraph.og_meta_from_note(db_session, ro),
327
+ is_hidden_from_stream=True,
328
+ + # The object may still be served by its server after its author
329
+ + # deleted it
330
+ + is_deleted=await is_deleted_by_its_author(
331
+ + db_session, ro.ap_id, obj_actor.ap_id
332
+ + ),
333
+ )
334
+
335
+ db_session.add(inbox_object)
336
+ diff --git a/tests/test_deleted_objects.py b/tests/test_deleted_objects.py
337
+ new file mode 100644
338
+ index 0000000..eeb7b38
339
+ --- /dev/null
340
+ +++ b/tests/test_deleted_objects.py
341
+ @@ -0,0 +1,414 @@
342
+ +from uuid import uuid4
343
+ +
344
+ +import httpx
345
+ +import pytest
346
+ +import respx
347
+ +from fastapi.testclient import TestClient
348
+ +from sqlalchemy import func
349
+ +from sqlalchemy import select
350
+ +from sqlalchemy.orm import Session
351
+ +
352
+ +from app import activitypub as ap
353
+ +from app import models
354
+ +from app.actor import LOCAL_ACTOR
355
+ +from app.config import generate_csrf_token
356
+ +from app.utils.datetime import now
357
+ +from tests import factories
358
+ +from tests.utils import generate_admin_session_cookies
359
+ +from tests.utils import mock_httpsig_checker
360
+ +from tests.utils import run_process_next_incoming_activity
361
+ +from tests.utils import setup_outbox_note
362
+ +from tests.utils import setup_remote_actor
363
+ +from tests.utils import setup_remote_actor_as_following
364
+ +
365
+ +
366
+ +def _remote_note(
367
+ + respx_mock: respx.MockRouter,
368
+ + base_url: str = "https://example.com",
369
+ +) -> tuple:
370
+ + # The remote server keeps serving the note even after it was deleted
371
+ + note_id = uuid4().hex
372
+ + served = {}
373
+ + respx_mock.get(f"{base_url}/note/{note_id}").mock(
374
+ + side_effect=lambda request: httpx.Response(200, json=served["note"])
375
+ + )
376
+ + ra = setup_remote_actor(respx_mock, base_url=base_url)
377
+ + served["note"] = factories.build_note_object(
378
+ + from_remote_actor=ra,
379
+ + outbox_public_id=note_id,
380
+ + content="note-" + uuid4().hex,
381
+ + )
382
+ + return ra, served["note"]
383
+ +
384
+ +
385
+ +def _send(client: TestClient, ra, activity: ap.RawObject) -> None:
386
+ + with mock_httpsig_checker(ra):
387
+ + response = client.post(
388
+ + "/inbox",
389
+ + headers={"Content-Type": ap.AS_CTX},
390
+ + json=activity,
391
+ + )
392
+ + assert response.status_code == 202
393
+ + run_process_next_incoming_activity()
394
+ +
395
+ +
396
+ +def _send_delete(client: TestClient, ra, ap_id: str) -> None:
397
+ + _send(client, ra, factories.build_delete_activity(ra, deleted_object_ap_id=ap_id))
398
+ +
399
+ +
400
+ +def _send_announce(client: TestClient, ra, ap_id: str) -> None:
401
+ + _send(
402
+ + client,
403
+ + ra,
404
+ + {
405
+ + "@context": ap.AS_CTX,
406
+ + "type": "Announce",
407
+ + "id": ra.ap_id + "/announce/" + uuid4().hex,
408
+ + "actor": ra.ap_id,
409
+ + "object": ap_id,
410
+ + "to": [ap.AS_PUBLIC],
411
+ + "cc": [],
412
+ + "published": now()
413
+ + .replace(microsecond=0)
414
+ + .isoformat()
415
+ + .replace("+00:00", "Z"),
416
+ + },
417
+ + )
418
+ +
419
+ +
420
+ +def _admin_action(client: TestClient, action: str, ap_object_id: str):
421
+ + return client.post(
422
+ + f"/admin/actions/{action}",
423
+ + data={
424
+ + "redirect_url": "http://testserver/",
425
+ + "ap_object_id": ap_object_id,
426
+ + "csrf_token": generate_csrf_token(),
427
+ + },
428
+ + cookies=generate_admin_session_cookies(),
429
+ + )
430
+ +
431
+ +
432
+ +def _inbox_object(db: Session, ap_id: str) -> models.InboxObject:
433
+ + db.expire_all()
434
+ + return db.execute(
435
+ + select(models.InboxObject).where(models.InboxObject.ap_id == ap_id)
436
+ + ).scalar_one()
437
+ +
438
+ +
439
+ +def _stream(client: TestClient) -> str:
440
+ + response = client.get("/admin/stream", cookies=generate_admin_session_cookies())
441
+ + assert response.status_code == 200
442
+ + return response.text
443
+ +
444
+ +
445
+ +def test_deleted_object__bookmark_does_not_resurrect_it(
446
+ + db: Session,
447
+ + client: TestClient,
448
+ + respx_mock: respx.MockRouter,
449
+ +) -> None:
450
+ + ra, note = _remote_note(respx_mock)
451
+ + _send_delete(client, ra, note["id"])
452
+ +
453
+ + response = _admin_action(client, "bookmark", note["id"])
454
+ +
455
+ + assert response.status_code == 302
456
+ + assert _inbox_object(db, note["id"]).is_deleted is True
457
+ +
458
+ +
459
+ +def test_deleted_object__reply_form_does_not_resurrect_it(
460
+ + db: Session,
461
+ + client: TestClient,
462
+ + respx_mock: respx.MockRouter,
463
+ +) -> None:
464
+ + ra, note = _remote_note(respx_mock)
465
+ + _send_delete(client, ra, note["id"])
466
+ +
467
+ + response = client.get(
468
+ + "/admin/new",
469
+ + params={"in_reply_to": note["id"]},
470
+ + cookies=generate_admin_session_cookies(),
471
+ + )
472
+ +
473
+ + assert response.status_code == 200
474
+ + assert _inbox_object(db, note["id"]).is_deleted is True
475
+ +
476
+ +
477
+ +def test_deleted_object__announce_after_delete_does_not_resurrect_it(
478
+ + db: Session,
479
+ + client: TestClient,
480
+ + respx_mock: respx.MockRouter,
481
+ +) -> None:
482
+ + ra, note = _remote_note(respx_mock)
483
+ + booster = setup_remote_actor(respx_mock, base_url="https://booster.example")
484
+ + setup_remote_actor_as_following(booster)
485
+ + _send_delete(client, ra, note["id"])
486
+ +
487
+ + _send_announce(client, booster, note["id"])
488
+ +
489
+ + assert _inbox_object(db, note["id"]).is_deleted is True
490
+ + assert note["content"] not in _stream(client)
491
+ +
492
+ +
493
+ +def test_deleted_object__read_after_delete_does_not_resurrect_it(
494
+ + db: Session,
495
+ + client: TestClient,
496
+ + respx_mock: respx.MockRouter,
497
+ +) -> None:
498
+ + ra, note = _remote_note(respx_mock)
499
+ + reader = setup_remote_actor(respx_mock, base_url="https://reader.example")
500
+ + setup_remote_actor_as_following(reader)
501
+ + _send_delete(client, ra, note["id"])
502
+ +
503
+ + # Honk propagates replies with a Read activity
504
+ + _send(
505
+ + client,
506
+ + reader,
507
+ + {
508
+ + "@context": ap.AS_CTX,
509
+ + "type": "Read",
510
+ + "id": reader.ap_id + "/read/" + uuid4().hex,
511
+ + "actor": reader.ap_id,
512
+ + "object": note["id"],
513
+ + "to": [ap.AS_PUBLIC],
514
+ + "cc": [],
515
+ + },
516
+ + )
517
+ +
518
+ + db.expire_all()
519
+ + assert not [
520
+ + inbox_object
521
+ + for inbox_object in db.execute(
522
+ + select(models.InboxObject).where(models.InboxObject.ap_id == note["id"])
523
+ + )
524
+ + .scalars()
525
+ + .all()
526
+ + if not inbox_object.is_deleted
527
+ + ]
528
+ + response = client.get("/admin/inbox", cookies=generate_admin_session_cookies())
529
+ + assert response.status_code == 200
530
+ + assert note["content"] not in response.text
531
+ +
532
+ +
533
+ +@pytest.mark.parametrize("delete_before_announce", [False, True])
534
+ +def test_deleted_object__announces_are_removed_from_the_stream(
535
+ + db: Session,
536
+ + client: TestClient,
537
+ + respx_mock: respx.MockRouter,
538
+ + delete_before_announce: bool,
539
+ +) -> None:
540
+ + ra, note = _remote_note(respx_mock)
541
+ + booster = setup_remote_actor(respx_mock, base_url="https://booster.example")
542
+ + setup_remote_actor_as_following(booster)
543
+ + _send(client, ra, factories.build_create_activity(note))
544
+ +
545
+ + if delete_before_announce:
546
+ + _send_delete(client, ra, note["id"])
547
+ + _send_announce(client, booster, note["id"])
548
+ + else:
549
+ + _send_announce(client, booster, note["id"])
550
+ + assert note["content"] in _stream(client)
551
+ + _send_delete(client, ra, note["id"])
552
+ +
553
+ + assert note["content"] not in _stream(client)
554
+ +
555
+ +
556
+ +def test_deleted_object__delete_from_another_actor_is_ignored(
557
+ + db: Session,
558
+ + client: TestClient,
559
+ + respx_mock: respx.MockRouter,
560
+ +) -> None:
561
+ + ra, note = _remote_note(respx_mock)
562
+ + other = setup_remote_actor(respx_mock, base_url="https://other.example")
563
+ + _send_delete(client, other, note["id"])
564
+ +
565
+ + _send(client, ra, factories.build_create_activity(note))
566
+ +
567
+ + assert _inbox_object(db, note["id"]).is_deleted is False
568
+ +
569
+ +
570
+ +@pytest.mark.parametrize("author_first", [False, True])
571
+ +def test_deleted_object__multiple_deletes(
572
+ + db: Session,
573
+ + client: TestClient,
574
+ + respx_mock: respx.MockRouter,
575
+ + author_first: bool,
576
+ +) -> None:
577
+ + ra, note = _remote_note(respx_mock)
578
+ + other = setup_remote_actor(respx_mock, base_url="https://other.example")
579
+ + for actor in [ra, other] if author_first else [other, ra]:
580
+ + _send_delete(client, actor, note["id"])
581
+ +
582
+ + response = _admin_action(client, "bookmark", note["id"])
583
+ + assert response.status_code == 302
584
+ + assert _inbox_object(db, note["id"]).is_deleted is True
585
+ +
586
+ + _send(client, ra, factories.build_create_activity(note))
587
+ + assert _inbox_object(db, note["id"]).is_deleted is True
588
+ + assert not [
589
+ + incoming_activity
590
+ + for incoming_activity in db.execute(select(models.IncomingActivity))
591
+ + .scalars()
592
+ + .all()
593
+ + if incoming_activity.error
594
+ + ]
595
+ +
596
+ +
597
+ +def test_deleted_object__delete_received_twice_for_a_reply(
598
+ + db: Session,
599
+ + client: TestClient,
600
+ + respx_mock: respx.MockRouter,
601
+ +) -> None:
602
+ + ra, note = _remote_note(respx_mock)
603
+ + outbox_note = setup_outbox_note(
604
+ + to=[ap.AS_PUBLIC], cc=[LOCAL_ACTOR.followers_collection_id]
605
+ + )
606
+ + _send(client, ra, factories.build_create_activity(note))
607
+ + replies = [
608
+ + factories.build_note_object(from_remote_actor=ra, in_reply_to=note["id"]),
609
+ + factories.build_note_object(
610
+ + from_remote_actor=ra, in_reply_to=outbox_note.ap_id
611
+ + ),
612
+ + ]
613
+ + for reply in replies:
614
+ + _send(client, ra, factories.build_create_activity(reply))
615
+ + assert _inbox_object(db, note["id"]).replies_count == 1
616
+ +
617
+ + for reply in replies:
618
+ + _send_delete(client, ra, reply["id"])
619
+ + _send_delete(client, ra, reply["id"])
620
+ +
621
+ + assert _inbox_object(db, note["id"]).replies_count == 0
622
+ + db.refresh(outbox_note)
623
+ + assert outbox_note.replies_count == 0
624
+ +
625
+ +
626
+ +@pytest.mark.parametrize("action", ["like", "announce", "reply"])
627
+ +def test_deleted_object__cannot_be_interacted_with(
628
+ + db: Session,
629
+ + client: TestClient,
630
+ + respx_mock: respx.MockRouter,
631
+ + action: str,
632
+ +) -> None:
633
+ + ra, note = _remote_note(respx_mock)
634
+ + _send(client, ra, factories.build_create_activity(note))
635
+ + _send_delete(client, ra, note["id"])
636
+ +
637
+ + with pytest.raises(ValueError):
638
+ + if action == "reply":
639
+ + client.post(
640
+ + "/admin/actions/new",
641
+ + data={
642
+ + "redirect_url": "http://testserver/",
643
+ + "content": "hello",
644
+ + "in_reply_to": note["id"],
645
+ + "visibility": ap.VisibilityEnum.PUBLIC.name,
646
+ + "csrf_token": generate_csrf_token(),
647
+ + },
648
+ + cookies=generate_admin_session_cookies(),
649
+ + )
650
+ + else:
651
+ + _admin_action(client, action, note["id"])
652
+ +
653
+ + assert db.scalar(select(func.count(models.OutboxObject.id))) == 0
654
+ + assert db.scalar(select(func.count(models.OutgoingActivity.id))) == 0
655
+ + assert _inbox_object(db, note["id"]).replies_count == 0
656
+ +
657
+ +
658
+ +def _gone_remote_note(respx_mock: respx.MockRouter) -> tuple:
659
+ + # The remote server serves the note until it answers 410 Gone for it
660
+ + note_id = uuid4().hex
661
+ + served: dict = {"gone": False}
662
+ +
663
+ + def _serve(request):
664
+ + if served["gone"]:
665
+ + return httpx.Response(410, json={"error": "Gone"})
666
+ + return httpx.Response(200, json=served["note"])
667
+ +
668
+ + respx_mock.get(f"https://example.com/note/{note_id}").mock(side_effect=_serve)
669
+ + ra = setup_remote_actor(respx_mock)
670
+ + served["note"] = factories.build_note_object(
671
+ + from_remote_actor=ra,
672
+ + outbox_public_id=note_id,
673
+ + content="note-" + uuid4().hex,
674
+ + )
675
+ + return ra, served
676
+ +
677
+ +
678
+ +def test_deleted_object__bookmark_works_once_its_server_says_gone(
679
+ + db: Session,
680
+ + client: TestClient,
681
+ + respx_mock: respx.MockRouter,
682
+ +) -> None:
683
+ + ra, served = _gone_remote_note(respx_mock)
684
+ + _send_delete(client, ra, served["note"]["id"])
685
+ + served["gone"] = True
686
+ +
687
+ + response = _admin_action(client, "bookmark", served["note"]["id"])
688
+ +
689
+ + assert response.status_code == 302
690
+ + db.expire_all()
691
+ + assert not db.execute(
692
+ + select(models.InboxObject).where(
693
+ + models.InboxObject.ap_id == served["note"]["id"]
694
+ + )
695
+ + ).scalar_one_or_none()
696
+ +
697
+ +
698
+ +def test_deleted_object__reply_form_works_once_its_server_says_gone(
699
+ + db: Session,
700
+ + client: TestClient,
701
+ + respx_mock: respx.MockRouter,
702
+ +) -> None:
703
+ + ra, served = _gone_remote_note(respx_mock)
704
+ + _send_delete(client, ra, served["note"]["id"])
705
+ + served["gone"] = True
706
+ +
707
+ + response = client.get(
708
+ + "/admin/new",
709
+ + params={"in_reply_to": served["note"]["id"]},
710
+ + cookies=generate_admin_session_cookies(),
711
+ + )
712
+ +
713
+ + assert response.status_code == 200
714
+ +
715
+ +
716
+ +@pytest.mark.parametrize("delete_before_announce", [False, True])
717
+ +def test_deleted_object__announces_are_removed_from_the_admin_inbox(
718
+ + db: Session,
719
+ + client: TestClient,
720
+ + respx_mock: respx.MockRouter,
721
+ + delete_before_announce: bool,
722
+ +) -> None:
723
+ + ra, note = _remote_note(respx_mock)
724
+ + booster = setup_remote_actor(respx_mock, base_url="https://booster.example")
725
+ + setup_remote_actor_as_following(booster)
726
+ + if delete_before_announce:
727
+ + _send_delete(client, ra, note["id"])
728
+ + _send_announce(client, booster, note["id"])
729
+ + else:
730
+ + _send(client, ra, factories.build_create_activity(note))
731
+ + _send_announce(client, booster, note["id"])
732
+ + _send_delete(client, ra, note["id"])
733
+ +
734
+ + response = client.get("/admin/inbox", cookies=generate_admin_session_cookies())
735
+ +
736
+ + assert response.status_code == 200
737
+ + assert note["content"] not in response.text
738
+ +
739
+ +
740
+ +def test_deleted_object__lookup_does_not_show_it(
741
+ + db: Session,
742
+ + client: TestClient,
743
+ + respx_mock: respx.MockRouter,
744
+ +) -> None:
745
+ + ra, note = _remote_note(respx_mock)
746
+ + _send_delete(client, ra, note["id"])
747
+ +
748
+ + response = client.get(
749
+ + "/admin/lookup",
750
+ + params={"query": note["id"]},
751
+ + cookies=generate_admin_session_cookies(),
752
+ + )
753
+ +
754
+ + assert response.status_code == 200
755
+ + assert note["content"] not in response.text
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/solution/solve.sh ADDED
@@ -0,0 +1,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -eu
3
+ cd /workspace/repo
4
+ git apply <<'REFERENCE_PATCH'
5
+ diff --git a/app/admin.py b/app/admin.py
6
+ index 226b193..7205322 100644
7
+ --- a/app/admin.py
8
+ +++ b/app/admin.py
9
+ @@ -140,9 +140,19 @@ async def get_lookup(
10
+ status_code=302,
11
+ )
12
+
13
+ - actors_metadata = await get_actors_metadata(
14
+ - db_session, [ap_object.actor] # type: ignore
15
+ - )
16
+ + # Its server may still serve it after its author deleted it
17
+ + if await boxes.is_deleted_by_its_author(
18
+ + db_session,
19
+ + ap_object.ap_id,
20
+ + ap_object.actor.ap_id, # type: ignore
21
+ + ):
22
+ + logger.info(f"{ap_object.ap_id} was deleted by its author")
23
+ + ap_object = None
24
+ + error = ap.FetchErrorTypeEnum.NOT_FOUND
25
+ + else:
26
+ + actors_metadata = await get_actors_metadata(
27
+ + db_session, [ap_object.actor] # type: ignore
28
+ + )
29
+
30
+ return await templates.render_template(
31
+ db_session,
32
+ @@ -173,31 +183,41 @@ async def admin_new(
33
+ in_reply_to_object = await boxes.get_anybox_object_by_ap_id(
34
+ db_session, in_reply_to
35
+ )
36
+ + is_gone = False
37
+ if not in_reply_to_object:
38
+ logger.info(f"Saving unknwown object {in_reply_to}")
39
+ - raw_object = await ap.fetch(in_reply_to)
40
+ - await boxes.save_object_to_inbox(db_session, raw_object)
41
+ - await db_session.commit()
42
+ - in_reply_to_object = await boxes.get_anybox_object_by_ap_id(
43
+ - db_session, in_reply_to
44
+ - )
45
+ + try:
46
+ + raw_object = await ap.fetch(in_reply_to)
47
+ + except (ap.ObjectIsGoneError, ap.ObjectNotFoundError):
48
+ + # Its server stopped serving it after its author deleted it
49
+ + if not await boxes.is_deleted_at_its_origin(db_session, in_reply_to):
50
+ + raise
51
+ + logger.info(f"{in_reply_to} is gone")
52
+ + is_gone = True
53
+ + else:
54
+ + await boxes.save_object_to_inbox(db_session, raw_object)
55
+ + await db_session.commit()
56
+ + in_reply_to_object = await boxes.get_anybox_object_by_ap_id(
57
+ + db_session, in_reply_to
58
+ + )
59
+
60
+ # Add mentions to the initial note content
61
+ - if not in_reply_to_object:
62
+ + if not in_reply_to_object and not is_gone:
63
+ raise ValueError(f"Unknown object {in_reply_to=}")
64
+ - if in_reply_to_object.actor.ap_id != LOCAL_ACTOR.ap_id:
65
+ - content += f"{in_reply_to_object.actor.handle} "
66
+ - for tag in in_reply_to_object.tags:
67
+ - if tag.get("type") == "Mention" and tag["name"] != LOCAL_ACTOR.handle:
68
+ - try:
69
+ - mentioned_actor = await fetch_actor(db_session, tag["href"])
70
+ - content += f"{mentioned_actor.handle} "
71
+ - except Exception:
72
+ - logger.exception(f"Failed to lookup {mentioned_actor}")
73
+ -
74
+ - # Copy the content warning if any
75
+ - if in_reply_to_object.summary:
76
+ - content_warning = in_reply_to_object.summary
77
+ + if in_reply_to_object:
78
+ + if in_reply_to_object.actor.ap_id != LOCAL_ACTOR.ap_id:
79
+ + content += f"{in_reply_to_object.actor.handle} "
80
+ + for tag in in_reply_to_object.tags:
81
+ + if tag.get("type") == "Mention" and tag["name"] != LOCAL_ACTOR.handle:
82
+ + try:
83
+ + mentioned_actor = await fetch_actor(db_session, tag["href"])
84
+ + content += f"{mentioned_actor.handle} "
85
+ + except Exception:
86
+ + logger.exception(f"Failed to lookup {mentioned_actor}")
87
+ +
88
+ + # Copy the content warning if any
89
+ + if in_reply_to_object.summary:
90
+ + content_warning = in_reply_to_object.summary
91
+ elif with_content:
92
+ content += f"{with_content} "
93
+
94
+ @@ -1076,7 +1096,14 @@ async def admin_actions_bookmark(
95
+ inbox_object = await get_inbox_object_by_ap_id(db_session, ap_object_id)
96
+ if not inbox_object:
97
+ logger.info(f"Saving unknwown object {ap_object_id}")
98
+ - raw_object = await ap.fetch(ap_object_id)
99
+ + try:
100
+ + raw_object = await ap.fetch(ap_object_id)
101
+ + except (ap.ObjectIsGoneError, ap.ObjectNotFoundError):
102
+ + # Its server stopped serving it after its author deleted it
103
+ + if not await boxes.is_deleted_at_its_origin(db_session, ap_object_id):
104
+ + raise
105
+ + logger.info(f"{ap_object_id} is gone, nothing to bookmark")
106
+ + return RedirectResponse(redirect_url, status_code=302)
107
+ inbox_object = await boxes.save_object_to_inbox(db_session, raw_object)
108
+ inbox_object.is_bookmarked = True
109
+ await db_session.commit()
110
+ diff --git a/app/boxes.py b/app/boxes.py
111
+ index 109c210..8125c51 100644
112
+ --- a/app/boxes.py
113
+ +++ b/app/boxes.py
114
+ @@ -262,6 +262,9 @@ async def send_like(db_session: AsyncSession, ap_object_id: str) -> None:
115
+ if not inbox_object:
116
+ raise ValueError("Should never happen")
117
+
118
+ + if inbox_object.is_deleted:
119
+ + raise ValueError(f"Cannot like deleted object {ap_object_id}")
120
+ +
121
+ like_id = allocate_outbox_id()
122
+ like = {
123
+ "@context": ap.AS_CTX,
124
+ @@ -297,6 +300,9 @@ async def send_announce(db_session: AsyncSession, ap_object_id: str) -> None:
125
+ if not inbox_object:
126
+ raise ValueError("Should never happen")
127
+
128
+ + if inbox_object.is_deleted:
129
+ + raise ValueError(f"Cannot announce deleted object {ap_object_id}")
130
+ +
131
+ if inbox_object.visibility not in [
132
+ ap.VisibilityEnum.PUBLIC,
133
+ ap.VisibilityEnum.UNLISTED,
134
+ @@ -605,6 +611,8 @@ async def send_create(
135
+ in_reply_to_object = await get_anybox_object_by_ap_id(db_session, in_reply_to)
136
+ if not in_reply_to_object:
137
+ raise ValueError(f"Invalid in reply to {in_reply_to=}")
138
+ + if in_reply_to_object.is_deleted:
139
+ + raise ValueError(f"Cannot reply to deleted object {in_reply_to=}")
140
+ if not in_reply_to_object.ap_context:
141
+ logger.warning(f"Replied object {in_reply_to} has no context")
142
+ try:
143
+ @@ -1024,22 +1032,73 @@ async def get_inbox_object_by_ap_id(
144
+
145
+
146
+ async def get_inbox_delete_for_activity_object_ap_id(
147
+ - db_session: AsyncSession, activity_object_ap_id: str
148
+ + db_session: AsyncSession,
149
+ + activity_object_ap_id: str,
150
+ + object_actor_ap_id: str,
151
+ ) -> models.InboxObject | None:
152
+ + """Return the Delete received for an object, if its author sent one.
153
+ +
154
+ + Only the author of an object can delete it, a Delete sent by anyone else
155
+ + is ignored (and there may be more than one Delete for the same object)."""
156
+ return (
157
+ - await db_session.execute(
158
+ - select(models.InboxObject)
159
+ - .where(
160
+ - models.InboxObject.ap_type == "Delete",
161
+ - models.InboxObject.activity_object_ap_id == activity_object_ap_id,
162
+ + (
163
+ + await db_session.execute(
164
+ + select(models.InboxObject)
165
+ + .where(
166
+ + models.InboxObject.ap_type == "Delete",
167
+ + models.InboxObject.activity_object_ap_id == activity_object_ap_id,
168
+ + models.InboxObject.ap_actor_id == object_actor_ap_id,
169
+ + )
170
+ + .options(
171
+ + joinedload(models.InboxObject.actor),
172
+ + joinedload(models.InboxObject.relates_to_inbox_object),
173
+ + joinedload(models.InboxObject.relates_to_outbox_object),
174
+ + )
175
+ + .order_by(models.InboxObject.id)
176
+ )
177
+ - .options(
178
+ - joinedload(models.InboxObject.actor),
179
+ - joinedload(models.InboxObject.relates_to_inbox_object),
180
+ - joinedload(models.InboxObject.relates_to_outbox_object),
181
+ + )
182
+ + .unique()
183
+ + .scalars()
184
+ + .first()
185
+ + )
186
+ +
187
+ +
188
+ +async def is_deleted_by_its_author(
189
+ + db_session: AsyncSession,
190
+ + ap_id: str,
191
+ + actor_ap_id: str,
192
+ +) -> bool:
193
+ + return (
194
+ + await get_inbox_delete_for_activity_object_ap_id(db_session, ap_id, actor_ap_id)
195
+ + ) is not None
196
+ +
197
+ +
198
+ +async def is_deleted_at_its_origin(
199
+ + db_session: AsyncSession,
200
+ + ap_id: str,
201
+ +) -> bool:
202
+ + """Tell if a Delete for an object we cannot fetch anymore came from its
203
+ + author.
204
+ +
205
+ + Once its server stops serving it, the object (and so its author) is not
206
+ + known anymore: an object lives on its author's server, so only a Delete
207
+ + sent by an actor of the object's origin counts."""
208
+ + origin = urlparse(ap_id)
209
+ + for actor_ap_id in (
210
+ + await db_session.scalars(
211
+ + select(models.InboxObject.ap_actor_id).where(
212
+ + models.InboxObject.ap_type == "Delete",
213
+ + models.InboxObject.activity_object_ap_id == ap_id,
214
+ )
215
+ )
216
+ - ).scalar_one_or_none() # type: ignore
217
+ + ).all():
218
+ + actor_origin = urlparse(actor_ap_id)
219
+ + if (actor_origin.scheme, actor_origin.netloc) == (
220
+ + origin.scheme,
221
+ + origin.netloc,
222
+ + ):
223
+ + return True
224
+ + return False
225
+
226
+
227
+ async def get_outbox_object_by_ap_id(
228
+ @@ -1156,6 +1215,10 @@ async def _handle_delete_activity(
229
+ )
230
+ return
231
+
232
+ + if ap_object_to_delete.is_deleted:
233
+ + logger.info(f"{ap_object_to_delete.ap_id} is already deleted")
234
+ + return
235
+ +
236
+ logger.info(
237
+ f"Deleting {ap_object_to_delete.ap_type}/{ap_object_to_delete.ap_id}"
238
+ )
239
+ @@ -1423,6 +1486,16 @@ async def _revert_side_effect_for_deleted_object(
240
+ .values(is_deleted=True)
241
+ )
242
+
243
+ + # And take down the Announces we received for it (stream and inbox)
244
+ + await db_session.execute(
245
+ + update(models.InboxObject)
246
+ + .where(
247
+ + models.InboxObject.ap_type == "Announce",
248
+ + models.InboxObject.relates_to_inbox_object_id == deleted_ap_object.id,
249
+ + )
250
+ + .values(is_hidden_from_stream=True, is_deleted=True)
251
+ + )
252
+ +
253
+ # If it's a local replies, it was forwarded, so we also need to forward
254
+ # the Delete activity if possible
255
+ if (
256
+ @@ -1842,18 +1915,13 @@ async def _handle_create_activity(
257
+ delete_object = await get_inbox_delete_for_activity_object_ap_id(
258
+ db_session,
259
+ ro.ap_id,
260
+ + from_actor.ap_id,
261
+ )
262
+ if delete_object:
263
+ - if delete_object.actor.ap_id != from_actor.ap_id:
264
+ - logger.warning(
265
+ - f"Got a Delete for {ro.ap_id} from {delete_object.actor.ap_id}??"
266
+ - )
267
+ - return None
268
+ - else:
269
+ - logger.info("Already received a Delete for this object, deleting activity")
270
+ - create_activity.is_deleted = True
271
+ - await db_session.flush()
272
+ - return None
273
+ + logger.info("Already received a Delete for this object, deleting activity")
274
+ + create_activity.is_deleted = True
275
+ + await db_session.flush()
276
+ + return None
277
+
278
+ await _process_note_object(
279
+ db_session,
280
+ @@ -1889,6 +1957,14 @@ async def _handle_read_activity(
281
+ logger.info(f"{ro.ap_id} is already in the inbox, skipping processing")
282
+ return None
283
+
284
+ + # The object may still be served by its server after its author
285
+ + # deleted it
286
+ + if await is_deleted_by_its_author(
287
+ + db_session, ro.ap_id, wrapped_object_actor.ap_id
288
+ + ):
289
+ + logger.info(f"{ro.ap_id} was deleted by its author, skipping processing")
290
+ + return None
291
+ +
292
+ # Then process it likes it's coming from a forwarded activity
293
+ await _process_note_object(db_session, read_activity, wrapped_object_actor, ro)
294
+
295
+ @@ -2169,6 +2245,11 @@ async def _handle_announce_activity(
296
+ else:
297
+ announce_activity.is_hidden_from_stream = not is_from_following
298
+
299
+ + if relates_to_inbox_object.is_deleted:
300
+ + logger.info(f"{relates_to_inbox_object.ap_id} is deleted")
301
+ + announce_activity.is_hidden_from_stream = True
302
+ + announce_activity.is_deleted = True
303
+ +
304
+ else:
305
+ # Save it as an inbox object
306
+ if not announce_activity.activity_object_ap_id:
307
+ @@ -2201,6 +2282,9 @@ async def _handle_announce_activity(
308
+ db_session, announced_object
309
+ ),
310
+ is_hidden_from_stream=True,
311
+ + is_deleted=await is_deleted_by_its_author(
312
+ + db_session, announced_object.ap_id, announced_actor.ap_id
313
+ + ),
314
+ )
315
+ db_session.add(announced_inbox_object)
316
+ await db_session.flush()
317
+ @@ -2208,7 +2292,10 @@ async def _handle_announce_activity(
318
+ announce_activity.is_hidden_from_stream = (
319
+ not is_from_following
320
+ or announce_activity.actor.are_announces_hidden_from_stream
321
+ + or announced_inbox_object.is_deleted
322
+ )
323
+ + if announced_inbox_object.is_deleted:
324
+ + announce_activity.is_deleted = True
325
+
326
+
327
+ async def _handle_like_activity(
328
+ @@ -2602,6 +2689,11 @@ async def save_object_to_inbox(
329
+ activity_object_ap_id=ro.activity_object_ap_id,
330
+ og_meta=await opengraph.og_meta_from_note(db_session, ro),
331
+ is_hidden_from_stream=True,
332
+ + # The object may still be served by its server after its author
333
+ + # deleted it
334
+ + is_deleted=await is_deleted_by_its_author(
335
+ + db_session, ro.ap_id, obj_actor.ap_id
336
+ + ),
337
+ )
338
+
339
+ db_session.add(inbox_object)
340
+ diff --git a/tests/test_deleted_objects.py b/tests/test_deleted_objects.py
341
+ new file mode 100644
342
+ index 0000000..eeb7b38
343
+ --- /dev/null
344
+ +++ b/tests/test_deleted_objects.py
345
+ @@ -0,0 +1,414 @@
346
+ +from uuid import uuid4
347
+ +
348
+ +import httpx
349
+ +import pytest
350
+ +import respx
351
+ +from fastapi.testclient import TestClient
352
+ +from sqlalchemy import func
353
+ +from sqlalchemy import select
354
+ +from sqlalchemy.orm import Session
355
+ +
356
+ +from app import activitypub as ap
357
+ +from app import models
358
+ +from app.actor import LOCAL_ACTOR
359
+ +from app.config import generate_csrf_token
360
+ +from app.utils.datetime import now
361
+ +from tests import factories
362
+ +from tests.utils import generate_admin_session_cookies
363
+ +from tests.utils import mock_httpsig_checker
364
+ +from tests.utils import run_process_next_incoming_activity
365
+ +from tests.utils import setup_outbox_note
366
+ +from tests.utils import setup_remote_actor
367
+ +from tests.utils import setup_remote_actor_as_following
368
+ +
369
+ +
370
+ +def _remote_note(
371
+ + respx_mock: respx.MockRouter,
372
+ + base_url: str = "https://example.com",
373
+ +) -> tuple:
374
+ + # The remote server keeps serving the note even after it was deleted
375
+ + note_id = uuid4().hex
376
+ + served = {}
377
+ + respx_mock.get(f"{base_url}/note/{note_id}").mock(
378
+ + side_effect=lambda request: httpx.Response(200, json=served["note"])
379
+ + )
380
+ + ra = setup_remote_actor(respx_mock, base_url=base_url)
381
+ + served["note"] = factories.build_note_object(
382
+ + from_remote_actor=ra,
383
+ + outbox_public_id=note_id,
384
+ + content="note-" + uuid4().hex,
385
+ + )
386
+ + return ra, served["note"]
387
+ +
388
+ +
389
+ +def _send(client: TestClient, ra, activity: ap.RawObject) -> None:
390
+ + with mock_httpsig_checker(ra):
391
+ + response = client.post(
392
+ + "/inbox",
393
+ + headers={"Content-Type": ap.AS_CTX},
394
+ + json=activity,
395
+ + )
396
+ + assert response.status_code == 202
397
+ + run_process_next_incoming_activity()
398
+ +
399
+ +
400
+ +def _send_delete(client: TestClient, ra, ap_id: str) -> None:
401
+ + _send(client, ra, factories.build_delete_activity(ra, deleted_object_ap_id=ap_id))
402
+ +
403
+ +
404
+ +def _send_announce(client: TestClient, ra, ap_id: str) -> None:
405
+ + _send(
406
+ + client,
407
+ + ra,
408
+ + {
409
+ + "@context": ap.AS_CTX,
410
+ + "type": "Announce",
411
+ + "id": ra.ap_id + "/announce/" + uuid4().hex,
412
+ + "actor": ra.ap_id,
413
+ + "object": ap_id,
414
+ + "to": [ap.AS_PUBLIC],
415
+ + "cc": [],
416
+ + "published": now()
417
+ + .replace(microsecond=0)
418
+ + .isoformat()
419
+ + .replace("+00:00", "Z"),
420
+ + },
421
+ + )
422
+ +
423
+ +
424
+ +def _admin_action(client: TestClient, action: str, ap_object_id: str):
425
+ + return client.post(
426
+ + f"/admin/actions/{action}",
427
+ + data={
428
+ + "redirect_url": "http://testserver/",
429
+ + "ap_object_id": ap_object_id,
430
+ + "csrf_token": generate_csrf_token(),
431
+ + },
432
+ + cookies=generate_admin_session_cookies(),
433
+ + )
434
+ +
435
+ +
436
+ +def _inbox_object(db: Session, ap_id: str) -> models.InboxObject:
437
+ + db.expire_all()
438
+ + return db.execute(
439
+ + select(models.InboxObject).where(models.InboxObject.ap_id == ap_id)
440
+ + ).scalar_one()
441
+ +
442
+ +
443
+ +def _stream(client: TestClient) -> str:
444
+ + response = client.get("/admin/stream", cookies=generate_admin_session_cookies())
445
+ + assert response.status_code == 200
446
+ + return response.text
447
+ +
448
+ +
449
+ +def test_deleted_object__bookmark_does_not_resurrect_it(
450
+ + db: Session,
451
+ + client: TestClient,
452
+ + respx_mock: respx.MockRouter,
453
+ +) -> None:
454
+ + ra, note = _remote_note(respx_mock)
455
+ + _send_delete(client, ra, note["id"])
456
+ +
457
+ + response = _admin_action(client, "bookmark", note["id"])
458
+ +
459
+ + assert response.status_code == 302
460
+ + assert _inbox_object(db, note["id"]).is_deleted is True
461
+ +
462
+ +
463
+ +def test_deleted_object__reply_form_does_not_resurrect_it(
464
+ + db: Session,
465
+ + client: TestClient,
466
+ + respx_mock: respx.MockRouter,
467
+ +) -> None:
468
+ + ra, note = _remote_note(respx_mock)
469
+ + _send_delete(client, ra, note["id"])
470
+ +
471
+ + response = client.get(
472
+ + "/admin/new",
473
+ + params={"in_reply_to": note["id"]},
474
+ + cookies=generate_admin_session_cookies(),
475
+ + )
476
+ +
477
+ + assert response.status_code == 200
478
+ + assert _inbox_object(db, note["id"]).is_deleted is True
479
+ +
480
+ +
481
+ +def test_deleted_object__announce_after_delete_does_not_resurrect_it(
482
+ + db: Session,
483
+ + client: TestClient,
484
+ + respx_mock: respx.MockRouter,
485
+ +) -> None:
486
+ + ra, note = _remote_note(respx_mock)
487
+ + booster = setup_remote_actor(respx_mock, base_url="https://booster.example")
488
+ + setup_remote_actor_as_following(booster)
489
+ + _send_delete(client, ra, note["id"])
490
+ +
491
+ + _send_announce(client, booster, note["id"])
492
+ +
493
+ + assert _inbox_object(db, note["id"]).is_deleted is True
494
+ + assert note["content"] not in _stream(client)
495
+ +
496
+ +
497
+ +def test_deleted_object__read_after_delete_does_not_resurrect_it(
498
+ + db: Session,
499
+ + client: TestClient,
500
+ + respx_mock: respx.MockRouter,
501
+ +) -> None:
502
+ + ra, note = _remote_note(respx_mock)
503
+ + reader = setup_remote_actor(respx_mock, base_url="https://reader.example")
504
+ + setup_remote_actor_as_following(reader)
505
+ + _send_delete(client, ra, note["id"])
506
+ +
507
+ + # Honk propagates replies with a Read activity
508
+ + _send(
509
+ + client,
510
+ + reader,
511
+ + {
512
+ + "@context": ap.AS_CTX,
513
+ + "type": "Read",
514
+ + "id": reader.ap_id + "/read/" + uuid4().hex,
515
+ + "actor": reader.ap_id,
516
+ + "object": note["id"],
517
+ + "to": [ap.AS_PUBLIC],
518
+ + "cc": [],
519
+ + },
520
+ + )
521
+ +
522
+ + db.expire_all()
523
+ + assert not [
524
+ + inbox_object
525
+ + for inbox_object in db.execute(
526
+ + select(models.InboxObject).where(models.InboxObject.ap_id == note["id"])
527
+ + )
528
+ + .scalars()
529
+ + .all()
530
+ + if not inbox_object.is_deleted
531
+ + ]
532
+ + response = client.get("/admin/inbox", cookies=generate_admin_session_cookies())
533
+ + assert response.status_code == 200
534
+ + assert note["content"] not in response.text
535
+ +
536
+ +
537
+ +@pytest.mark.parametrize("delete_before_announce", [False, True])
538
+ +def test_deleted_object__announces_are_removed_from_the_stream(
539
+ + db: Session,
540
+ + client: TestClient,
541
+ + respx_mock: respx.MockRouter,
542
+ + delete_before_announce: bool,
543
+ +) -> None:
544
+ + ra, note = _remote_note(respx_mock)
545
+ + booster = setup_remote_actor(respx_mock, base_url="https://booster.example")
546
+ + setup_remote_actor_as_following(booster)
547
+ + _send(client, ra, factories.build_create_activity(note))
548
+ +
549
+ + if delete_before_announce:
550
+ + _send_delete(client, ra, note["id"])
551
+ + _send_announce(client, booster, note["id"])
552
+ + else:
553
+ + _send_announce(client, booster, note["id"])
554
+ + assert note["content"] in _stream(client)
555
+ + _send_delete(client, ra, note["id"])
556
+ +
557
+ + assert note["content"] not in _stream(client)
558
+ +
559
+ +
560
+ +def test_deleted_object__delete_from_another_actor_is_ignored(
561
+ + db: Session,
562
+ + client: TestClient,
563
+ + respx_mock: respx.MockRouter,
564
+ +) -> None:
565
+ + ra, note = _remote_note(respx_mock)
566
+ + other = setup_remote_actor(respx_mock, base_url="https://other.example")
567
+ + _send_delete(client, other, note["id"])
568
+ +
569
+ + _send(client, ra, factories.build_create_activity(note))
570
+ +
571
+ + assert _inbox_object(db, note["id"]).is_deleted is False
572
+ +
573
+ +
574
+ +@pytest.mark.parametrize("author_first", [False, True])
575
+ +def test_deleted_object__multiple_deletes(
576
+ + db: Session,
577
+ + client: TestClient,
578
+ + respx_mock: respx.MockRouter,
579
+ + author_first: bool,
580
+ +) -> None:
581
+ + ra, note = _remote_note(respx_mock)
582
+ + other = setup_remote_actor(respx_mock, base_url="https://other.example")
583
+ + for actor in [ra, other] if author_first else [other, ra]:
584
+ + _send_delete(client, actor, note["id"])
585
+ +
586
+ + response = _admin_action(client, "bookmark", note["id"])
587
+ + assert response.status_code == 302
588
+ + assert _inbox_object(db, note["id"]).is_deleted is True
589
+ +
590
+ + _send(client, ra, factories.build_create_activity(note))
591
+ + assert _inbox_object(db, note["id"]).is_deleted is True
592
+ + assert not [
593
+ + incoming_activity
594
+ + for incoming_activity in db.execute(select(models.IncomingActivity))
595
+ + .scalars()
596
+ + .all()
597
+ + if incoming_activity.error
598
+ + ]
599
+ +
600
+ +
601
+ +def test_deleted_object__delete_received_twice_for_a_reply(
602
+ + db: Session,
603
+ + client: TestClient,
604
+ + respx_mock: respx.MockRouter,
605
+ +) -> None:
606
+ + ra, note = _remote_note(respx_mock)
607
+ + outbox_note = setup_outbox_note(
608
+ + to=[ap.AS_PUBLIC], cc=[LOCAL_ACTOR.followers_collection_id]
609
+ + )
610
+ + _send(client, ra, factories.build_create_activity(note))
611
+ + replies = [
612
+ + factories.build_note_object(from_remote_actor=ra, in_reply_to=note["id"]),
613
+ + factories.build_note_object(
614
+ + from_remote_actor=ra, in_reply_to=outbox_note.ap_id
615
+ + ),
616
+ + ]
617
+ + for reply in replies:
618
+ + _send(client, ra, factories.build_create_activity(reply))
619
+ + assert _inbox_object(db, note["id"]).replies_count == 1
620
+ +
621
+ + for reply in replies:
622
+ + _send_delete(client, ra, reply["id"])
623
+ + _send_delete(client, ra, reply["id"])
624
+ +
625
+ + assert _inbox_object(db, note["id"]).replies_count == 0
626
+ + db.refresh(outbox_note)
627
+ + assert outbox_note.replies_count == 0
628
+ +
629
+ +
630
+ +@pytest.mark.parametrize("action", ["like", "announce", "reply"])
631
+ +def test_deleted_object__cannot_be_interacted_with(
632
+ + db: Session,
633
+ + client: TestClient,
634
+ + respx_mock: respx.MockRouter,
635
+ + action: str,
636
+ +) -> None:
637
+ + ra, note = _remote_note(respx_mock)
638
+ + _send(client, ra, factories.build_create_activity(note))
639
+ + _send_delete(client, ra, note["id"])
640
+ +
641
+ + with pytest.raises(ValueError):
642
+ + if action == "reply":
643
+ + client.post(
644
+ + "/admin/actions/new",
645
+ + data={
646
+ + "redirect_url": "http://testserver/",
647
+ + "content": "hello",
648
+ + "in_reply_to": note["id"],
649
+ + "visibility": ap.VisibilityEnum.PUBLIC.name,
650
+ + "csrf_token": generate_csrf_token(),
651
+ + },
652
+ + cookies=generate_admin_session_cookies(),
653
+ + )
654
+ + else:
655
+ + _admin_action(client, action, note["id"])
656
+ +
657
+ + assert db.scalar(select(func.count(models.OutboxObject.id))) == 0
658
+ + assert db.scalar(select(func.count(models.OutgoingActivity.id))) == 0
659
+ + assert _inbox_object(db, note["id"]).replies_count == 0
660
+ +
661
+ +
662
+ +def _gone_remote_note(respx_mock: respx.MockRouter) -> tuple:
663
+ + # The remote server serves the note until it answers 410 Gone for it
664
+ + note_id = uuid4().hex
665
+ + served: dict = {"gone": False}
666
+ +
667
+ + def _serve(request):
668
+ + if served["gone"]:
669
+ + return httpx.Response(410, json={"error": "Gone"})
670
+ + return httpx.Response(200, json=served["note"])
671
+ +
672
+ + respx_mock.get(f"https://example.com/note/{note_id}").mock(side_effect=_serve)
673
+ + ra = setup_remote_actor(respx_mock)
674
+ + served["note"] = factories.build_note_object(
675
+ + from_remote_actor=ra,
676
+ + outbox_public_id=note_id,
677
+ + content="note-" + uuid4().hex,
678
+ + )
679
+ + return ra, served
680
+ +
681
+ +
682
+ +def test_deleted_object__bookmark_works_once_its_server_says_gone(
683
+ + db: Session,
684
+ + client: TestClient,
685
+ + respx_mock: respx.MockRouter,
686
+ +) -> None:
687
+ + ra, served = _gone_remote_note(respx_mock)
688
+ + _send_delete(client, ra, served["note"]["id"])
689
+ + served["gone"] = True
690
+ +
691
+ + response = _admin_action(client, "bookmark", served["note"]["id"])
692
+ +
693
+ + assert response.status_code == 302
694
+ + db.expire_all()
695
+ + assert not db.execute(
696
+ + select(models.InboxObject).where(
697
+ + models.InboxObject.ap_id == served["note"]["id"]
698
+ + )
699
+ + ).scalar_one_or_none()
700
+ +
701
+ +
702
+ +def test_deleted_object__reply_form_works_once_its_server_says_gone(
703
+ + db: Session,
704
+ + client: TestClient,
705
+ + respx_mock: respx.MockRouter,
706
+ +) -> None:
707
+ + ra, served = _gone_remote_note(respx_mock)
708
+ + _send_delete(client, ra, served["note"]["id"])
709
+ + served["gone"] = True
710
+ +
711
+ + response = client.get(
712
+ + "/admin/new",
713
+ + params={"in_reply_to": served["note"]["id"]},
714
+ + cookies=generate_admin_session_cookies(),
715
+ + )
716
+ +
717
+ + assert response.status_code == 200
718
+ +
719
+ +
720
+ +@pytest.mark.parametrize("delete_before_announce", [False, True])
721
+ +def test_deleted_object__announces_are_removed_from_the_admin_inbox(
722
+ + db: Session,
723
+ + client: TestClient,
724
+ + respx_mock: respx.MockRouter,
725
+ + delete_before_announce: bool,
726
+ +) -> None:
727
+ + ra, note = _remote_note(respx_mock)
728
+ + booster = setup_remote_actor(respx_mock, base_url="https://booster.example")
729
+ + setup_remote_actor_as_following(booster)
730
+ + if delete_before_announce:
731
+ + _send_delete(client, ra, note["id"])
732
+ + _send_announce(client, booster, note["id"])
733
+ + else:
734
+ + _send(client, ra, factories.build_create_activity(note))
735
+ + _send_announce(client, booster, note["id"])
736
+ + _send_delete(client, ra, note["id"])
737
+ +
738
+ + response = client.get("/admin/inbox", cookies=generate_admin_session_cookies())
739
+ +
740
+ + assert response.status_code == 200
741
+ + assert note["content"] not in response.text
742
+ +
743
+ +
744
+ +def test_deleted_object__lookup_does_not_show_it(
745
+ + db: Session,
746
+ + client: TestClient,
747
+ + respx_mock: respx.MockRouter,
748
+ +) -> None:
749
+ + ra, note = _remote_note(respx_mock)
750
+ + _send_delete(client, ra, note["id"])
751
+ +
752
+ + response = client.get(
753
+ + "/admin/lookup",
754
+ + params={"query": note["id"]},
755
+ + cookies=generate_admin_session_cookies(),
756
+ + )
757
+ +
758
+ + assert response.status_code == 200
759
+ + assert note["content"] not in response.text
760
+
761
+ REFERENCE_PATCH
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/task.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+ artifacts = ["/workspace/submissions/submitted.patch"]
3
+ [metadata]
4
+ task = "microblogpub_deleted_object_resurrect_lookup_contract"
5
+ validation_revision = "coding-rubric-v2"
6
+ [agent]
7
+ timeout_sec = 1800
8
+ user = "1000:1000"
9
+ [environment]
10
+ build_timeout_sec = 1800
11
+ cpus = 2
12
+ memory_mb = 8192
13
+ network_mode = "no-network"
14
+ [verifier]
15
+ timeout_sec = 7200
16
+ user = "0"
17
+ environment_mode = "separate"
18
+ [verifier.environment]
19
+ build_timeout_sec = 1800
20
+ cpus = 2
21
+ memory_mb = 8192
22
+ network_mode = "no-network"
23
+ [[verifier.collect]]
24
+ command = "/opt/task-tools/python -I /opt/task-tools/capture.py"
25
+ user = "0"
26
+ timeout_sec = 900
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-microblogpub:source-v4
2
+ USER root
3
+ RUN grep -q '^[^:]*:[^:]*:1000:' /etc/passwd || echo 'grader:x:1000:1000::/tmp/agent-home:/bin/sh' >> /etc/passwd; grep -q '^[^:]*:[^:]*:1000:' /etc/group || echo 'grader:x:1000:' >> /etc/group
4
+ ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
5
+ RUN rm -f /hud/gold.diff
6
+ COPY verify.py evidence.py config.json test.sh /tests/
7
+ RUN chmod 755 /tests/test.sh
8
+ WORKDIR /app
9
+ CMD ["sleep", "infinity"]
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/config.json ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "revision": "coding-rubric-v2",
3
+ "task_id": "microblogpub_deleted_object_resurrect_lookup_contract",
4
+ "arguments": {},
5
+ "grader_version": "0.6.15",
6
+ "source_image": "ec-swe-microblogpub:source-v4",
7
+ "source_image_id": "sha256:549597194eb51f2e5181db775223cfbad8eb3dfed90e2d269dccdc46b5646367",
8
+ "provenance": {
9
+ "repository": "tsileo/microblog.pub",
10
+ "environment_id": "cc707190-8931-4c68-93c3-209b61f3a502",
11
+ "build": 4,
12
+ "build_id": "93b58e6a-253b-4e8b-a1a3-29a55c571d03",
13
+ "hosted_task": "microblogpub_deleted_object_resurrect_lookup_contract-382616f8",
14
+ "task_version": 1,
15
+ "source_archive_sha256": "2915329d42f80ac608269a4b2b7b61990e88038326c20f9e1a112043d20adffc",
16
+ "hosted_revision_argument": "not recorded; the scenario does not read it"
17
+ },
18
+ "criteria": [
19
+ [
20
+ "r1_bookmark_does_not_bring_back_a_deleted_post",
21
+ 0.041,
22
+ true,
23
+ "bash",
24
+ 600
25
+ ],
26
+ [
27
+ "r2_boost_arriving_after_delete_does_not_bring_it_back",
28
+ 0.03,
29
+ false,
30
+ "bash",
31
+ 600
32
+ ],
33
+ [
34
+ "r3_boosts_already_on_stream_leave_with_the_post",
35
+ 0.03,
36
+ false,
37
+ "bash",
38
+ 600
39
+ ],
40
+ [
41
+ "r4_stranger_delete_does_not_drop_the_authors_post",
42
+ 0.03,
43
+ false,
44
+ "bash",
45
+ 600
46
+ ],
47
+ [
48
+ "r5_create_after_stranger_then_author_delete",
49
+ 0.03,
50
+ false,
51
+ "bash",
52
+ 600
53
+ ],
54
+ [
55
+ "r6_double_delete_keeps_inbox_parent_count",
56
+ 0.03,
57
+ false,
58
+ "bash",
59
+ 600
60
+ ],
61
+ [
62
+ "r7_like_of_a_deleted_post_sends_nothing",
63
+ 0.03,
64
+ false,
65
+ "bash",
66
+ 600
67
+ ],
68
+ [
69
+ "r8_read_does_not_bring_back_a_deleted_post",
70
+ 0.03,
71
+ false,
72
+ "bash",
73
+ 600
74
+ ],
75
+ [
76
+ "r8_read_after_stranger_then_author_delete",
77
+ 0.03,
78
+ false,
79
+ "bash",
80
+ 600
81
+ ],
82
+ [
83
+ "r8_read_after_a_tombstone_delete",
84
+ 0.03,
85
+ false,
86
+ "bash",
87
+ 600
88
+ ],
89
+ [
90
+ "r9_bookmark_works_once_the_server_says_gone",
91
+ 0.0457,
92
+ false,
93
+ "bash",
94
+ 600
95
+ ],
96
+ [
97
+ "r9_reply_form_works_once_the_server_says_gone",
98
+ 0.0457,
99
+ false,
100
+ "bash",
101
+ 600
102
+ ],
103
+ [
104
+ "r9_bookmark_works_once_the_server_says_not_found",
105
+ 0.09,
106
+ false,
107
+ "bash",
108
+ 600
109
+ ],
110
+ [
111
+ "r9_reply_form_works_once_the_server_says_not_found",
112
+ 0.09,
113
+ false,
114
+ "bash",
115
+ 600
116
+ ],
117
+ [
118
+ "r9_bookmark_works_once_gone_after_two_deletes",
119
+ 0.0456,
120
+ false,
121
+ "bash",
122
+ 600
123
+ ],
124
+ [
125
+ "r11_lookup_does_not_show_a_deleted_post",
126
+ 0.09,
127
+ false,
128
+ "bash",
129
+ 600
130
+ ],
131
+ [
132
+ "r11_lookup_after_stranger_then_author_delete",
133
+ 0.09,
134
+ false,
135
+ "bash",
136
+ 600
137
+ ],
138
+ [
139
+ "r11_lookup_after_author_then_stranger_delete",
140
+ 0.09,
141
+ false,
142
+ "bash",
143
+ 600
144
+ ],
145
+ [
146
+ "rule_undeleted_posts_behave_as_before",
147
+ 0.041,
148
+ true,
149
+ "bash",
150
+ 600
151
+ ],
152
+ [
153
+ "rule_stranger_delete_changes_nothing",
154
+ 0.041,
155
+ true,
156
+ "bash",
157
+ 600
158
+ ],
159
+ [
160
+ "gate_repo_suite_green_and_tests_untouched",
161
+ 0.02,
162
+ true,
163
+ "bash",
164
+ 900
165
+ ]
166
+ ],
167
+ "gates": [],
168
+ "reward_rule": "weighted_cap",
169
+ "local_hostname": false,
170
+ "fault_exit": 3,
171
+ "grader_readable": [],
172
+ "grader_writable": [],
173
+ "blocker_cap": 0.6,
174
+ "empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
175
+ "verifier_files": {
176
+ "/app/env.py": "786e3492cd374bda3063e4f581c4e8fbca2759d1d2a2337cc6791b53cfae1dd0",
177
+ "/app/tasks.py": "fde14896af0866a4efcb2c511a30e6b78f940ae01c52fd7489c3a37884cc1149",
178
+ "/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
179
+ "/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
180
+ "/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
181
+ "/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
182
+ "/app/task/prompt.md": "b5503c4ce52ac738d64c5cda7e702e6cf692e31b587d123fe258e80950a8293e",
183
+ "/hud/grader/run_grading.sh": "5f85557dbc19f9fe06312b2fd425cfcf2976f1db49d703f68acd3083168a96e7",
184
+ "/hud/grader/harness/cells.py": "d94fb228fc314de2182152112f5ca826688e53cad022b3a832af5535a62692bb",
185
+ "/hud/grader/harness/cells_test.py": "66c8240b133f7c0cae3134667310e861c66cf9ee19cbdb81d4b9defc5e598117",
186
+ "/hud/grader/harness/suite_gate.py": "9384bd33b513663cc46d0d4f06520c3d9eb163b3572922e40cde15dd38fce260"
187
+ },
188
+ "preflight": [
189
+ [
190
+ "/bin/bash",
191
+ "--version"
192
+ ],
193
+ [
194
+ "setpriv",
195
+ "--version"
196
+ ],
197
+ [
198
+ "git",
199
+ "--version"
200
+ ],
201
+ [
202
+ "bash",
203
+ "-c",
204
+ "bash -lc 'python --version' || python --version"
205
+ ],
206
+ [
207
+ "/opt/agentvenv/bin/python",
208
+ "--version"
209
+ ]
210
+ ]
211
+ }
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/docker-compose.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ services:
2
+ main:
3
+ network_mode: none
4
+ pids_limit: 512
5
+ security_opt:
6
+ - no-new-privileges:true
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/evidence.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate complete coding-rubric evidence without importing the grader library or Harbor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Any
7
+
8
+ REVISION = "coding-rubric-v2"
9
+
10
+
11
+ def _number(value: Any) -> float:
12
+ if isinstance(value, bool) or not isinstance(value, (float, int)):
13
+ raise ValueError("Expected numeric rubric evidence")
14
+ if not math.isfinite(value) or not 0 <= value <= 1:
15
+ raise ValueError("Rubric values must be finite and within [0, 1]")
16
+ return float(value)
17
+
18
+
19
+ def validate_report(report: dict[str, Any], config: dict[str, Any], digest: str) -> None:
20
+ """Check provenance, criterion coverage, weights, caps and command outcomes.
21
+
22
+ Parameters
23
+ ----------
24
+ report, config : dict
25
+ Fresh verifier evidence and the trusted prepared task configuration.
26
+ digest : str
27
+ SHA-256 of the submission collected by Harbor.
28
+
29
+ Raises
30
+ ------
31
+ ValueError
32
+ If evidence is missing, inconsistent or reports infrastructure failure.
33
+ """
34
+ if (
35
+ report.get("revision") != REVISION
36
+ or report.get("task_id") != config["task_id"]
37
+ or report.get("patch_sha256") != digest
38
+ or report.get("grader_version") != config["grader_version"]
39
+ ):
40
+ raise ValueError("Verifier evidence provenance mismatch")
41
+ result = report.get("result", {})
42
+ reward = _number(result.get("reward"))
43
+ # A rubric may flag its own result when a grader could not judge. That is
44
+ # admitted only together with proof, checked below, that the same grader
45
+ # reaches a verdict on the untouched repository.
46
+ fault_exit = config.get("fault_exit")
47
+ faults = {
48
+ row["name"]
49
+ for row in report.get("commands", [])
50
+ if fault_exit is not None and (row.get("info") or {}).get("exit_code") == fault_exit
51
+ }
52
+ flagged = result.get("isError", False)
53
+ if (flagged and not faults) or result.get("done", True) is not True:
54
+ raise ValueError("Grader returned an incomplete or failed evaluation")
55
+ status = report.get("status")
56
+ if status == "rejected_patch":
57
+ if reward != 0 or not report.get("patch_error") or result.get("subscores"):
58
+ raise ValueError("Invalid rejected-patch evidence")
59
+ return
60
+ if status == "empty_patch":
61
+ credited = any(_number(row["value"]) for row in result.get("subscores") or [])
62
+ if reward != 0 or digest != config["empty_sha256"] or report.get("commands") or credited:
63
+ raise ValueError("Invalid empty-patch evidence")
64
+ return
65
+ if status != "graded":
66
+ raise ValueError("Verifier did not complete")
67
+ scores = result.get("subscores")
68
+ expected = {row[0]: row for row in config["criteria"]}
69
+ if not isinstance(scores, list) or len(scores) != len(expected):
70
+ raise ValueError("Missing rubric criteria")
71
+ names = [row["name"] for row in scores]
72
+ if len(set(names)) != len(names) or set(names) != set(expected):
73
+ raise ValueError("Duplicate or unexpected rubric criteria")
74
+ raw = 0.0
75
+ values = {}
76
+ for score in scores:
77
+ name = score["name"]
78
+ value, weight = _number(score["value"]), _number(score["weight"])
79
+ if not math.isclose(weight, expected[name][1], abs_tol=1e-12):
80
+ raise ValueError("Criterion weights changed")
81
+ raw += value * weight
82
+ values[name] = value
83
+ commands = report.get("commands", [])
84
+ command_names = [row["name"] for row in commands]
85
+ expected_commands = set(expected) | set(config["gates"])
86
+ if len(command_names) != len(set(command_names)) or set(command_names) != expected_commands:
87
+ raise ValueError("Missing or duplicate grader command evidence")
88
+ for command in commands:
89
+ info = command.get("info") or {}
90
+ code = info.get("exit_code")
91
+ verdict = type(code) is int and (code in (0, 1) or command["name"] in faults)
92
+ if not verdict or info.get("timed_out"):
93
+ raise ValueError("Grader command failed outside its verdict contract")
94
+ if _number(command["value"]) != float(code == 0):
95
+ raise ValueError("Command exit code disagrees with score")
96
+ probes = {row["name"]: row for row in report.get("fault_probes") or []}
97
+ if set(probes) != faults or any(
98
+ row.get("timed_out") or row.get("exit_code") not in (0, 1) for row in probes.values()
99
+ ):
100
+ raise ValueError(
101
+ "A grader could not judge and the untouched repository does not explain it"
102
+ )
103
+ if any(values.get(name, 0) for name in faults):
104
+ raise ValueError("A criterion its grader could not judge is credited")
105
+ info = result.get("info") or {}
106
+ if info.get("aggregate_mismatch") or info.get("git_apply"):
107
+ raise ValueError("Grader reported inconsistent grading")
108
+ if config.get("reward_rule") == "authored":
109
+ # The task's own function decides the reward. It may take credit away
110
+ # (a cap, a criterion that pays only with progress) but never add any.
111
+ passed = {row["name"]: row["value"] for row in commands}
112
+ if any(values[name] > passed[name] for name in expected):
113
+ raise ValueError("A criterion is credited although its command failed")
114
+ if reward > raw + 1e-9:
115
+ raise ValueError("Grader reward exceeds its weighted criteria")
116
+ return
117
+ failed = {name for name, row in expected.items() if row[2] and values[name] < 1}
118
+ gate_failed = {
119
+ row["name"] for row in commands if row["name"] in config["gates"] and row["value"] < 1
120
+ }
121
+ expected_reward = min(raw, config["blocker_cap"]) if failed or gate_failed else raw
122
+ if not math.isclose(reward, expected_reward, abs_tol=1e-9):
123
+ raise ValueError("Grader reward disagrees with original weights and blocker cap")
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ /opt/hudvenv/bin/python /tests/verify.py
harbor/tasks/microblogpub_deleted_object_resurrect_lookup_contract/tests/verify.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the original trusted coding rubric in a fresh, offline verifier container."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import importlib
8
+ import importlib.metadata
9
+ import json
10
+ import os
11
+ import shlex
12
+ import shutil
13
+ import signal
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from evidence import REVISION, validate_report
20
+
21
+ OUT = Path("/logs/verifier")
22
+ PRIVATE = Path("/var/lib/task-evidence")
23
+ CONFIG = Path("/tests/config.json")
24
+ PATCH = Path("/workspace/submissions/submitted.patch")
25
+ GRADER_HOME = "/tmp/agent-home"
26
+
27
+
28
+ def _run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
29
+ return subprocess.run(command, text=True, capture_output=True, timeout=300, **kwargs)
30
+
31
+
32
+ def _preflight(config: dict[str, Any]) -> None:
33
+ if importlib.metadata.version("hud") != config["grader_version"]:
34
+ raise RuntimeError("Grader library version does not match the task")
35
+ for filename, expected in config["verifier_files"].items():
36
+ if hashlib.sha256(Path(filename).read_bytes()).hexdigest() != expected:
37
+ raise RuntimeError(f"Verifier source changed: {filename}")
38
+ for command in config["preflight"]:
39
+ completed = _run(command, cwd="/workspace/repo")
40
+ if completed.returncode:
41
+ raise RuntimeError(f"Prerequisite failed: {command}: {completed.stderr[-2000:]}")
42
+
43
+
44
+ def _readable_mode(path: Path) -> int:
45
+ # World-readable, keeping what is executable so: a grader may ship tools.
46
+ return 0o755 if path.is_dir() or path.stat().st_mode & 0o111 else 0o644
47
+
48
+
49
+ def _permissions() -> None:
50
+ # The orchestrator owns reports and rubric definitions. Grader commands,
51
+ # and so the candidate's code, run as uid 1000: the user the task installed
52
+ # its toolchain and caches for. They cannot read gold/vault or overwrite
53
+ # the rubric or the result files, which stay root's.
54
+ Path("/hud").chmod(0o711)
55
+ for root in (Path("/hud/grader"), Path("/hud/base"), Path("/hud/base-src")):
56
+ if root.exists():
57
+ root.chmod(0o755)
58
+ for path in root.rglob("*"):
59
+ if not path.is_symlink():
60
+ path.chmod(_readable_mode(path))
61
+ home = Path(GRADER_HOME)
62
+ home.mkdir(parents=True, exist_ok=True)
63
+ os.chown(home, 1000, 1000)
64
+ for directory in ("/hud/logs", "/hud/gocache", "/hud/grader/runner"):
65
+ path = Path(directory)
66
+ path.mkdir(parents=True, exist_ok=True)
67
+ for item in (path, *path.rglob("*")):
68
+ if not item.is_symlink():
69
+ os.chown(item, 1000, 1000)
70
+ item.chmod(_readable_mode(item))
71
+
72
+
73
+ def _hand_over_checkout() -> None:
74
+ # The original grader runs as root and may run the candidate's own suite in
75
+ # place, which writes into the tree. The rubric resets and re-applies the
76
+ # candidate as root, so give what root touched back to the grading user.
77
+ # Installed dependency trees are large and already that user's.
78
+ subprocess.run(
79
+ [
80
+ "find",
81
+ "/workspace/repo",
82
+ "-path",
83
+ "*/node_modules",
84
+ "-prune",
85
+ "-o",
86
+ "!",
87
+ "-user",
88
+ "1000",
89
+ "-exec",
90
+ "chown",
91
+ "-h",
92
+ "1000:1000",
93
+ "{}",
94
+ "+",
95
+ ],
96
+ check=True,
97
+ capture_output=True,
98
+ timeout=3600,
99
+ )
100
+
101
+
102
+ async def _grade(config: dict[str, Any], record: dict[str, Any]) -> None:
103
+ _preflight(config)
104
+ sys.path.insert(0, "/app")
105
+ task: Any = importlib.import_module("tasks")
106
+ await task._setup()
107
+ _permissions()
108
+ patch = PATCH.read_bytes()
109
+ if patch:
110
+ checked = _run(["git", "apply", "--check", str(PATCH)], cwd="/workspace/repo")
111
+ if checked.returncode:
112
+ record.update(
113
+ status="rejected_patch",
114
+ patch_error=checked.stderr[-4000:],
115
+ result={"reward": 0.0, "subscores": None},
116
+ )
117
+ return
118
+ _run(["git", "apply", str(PATCH)], cwd="/workspace/repo", check=True)
119
+ original = task.BashGrader
120
+ fault_exit = config.get("fault_exit")
121
+ faulted: list[tuple[tuple[Any, ...], dict[str, Any], str]] = []
122
+
123
+ class ObservedGrader:
124
+ @classmethod
125
+ async def grade(cls, *args: Any, **kwargs: Any) -> Any:
126
+ command = kwargs["command"]
127
+ _hand_over_checkout()
128
+ kwargs["command"] = (
129
+ "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs "
130
+ f"env HOME={GRADER_HOME} bash -lc " + shlex.quote(command)
131
+ )
132
+ score = await original.grade(*args, **kwargs)
133
+ snapshot = score.model_dump(mode="json")
134
+ record["commands"].append(snapshot)
135
+ (PRIVATE / "commands.json").write_text(json.dumps(record["commands"], indent=2))
136
+ info = snapshot.get("info") or {}
137
+ if info.get("timed_out") or type(info.get("exit_code")) is not int:
138
+ raise RuntimeError(f"Grader infrastructure failure: {snapshot['name']}")
139
+ if fault_exit is not None and info["exit_code"] == fault_exit:
140
+ # The grader says it could not judge. Whether the submission or
141
+ # the environment is the reason is settled after grading.
142
+ faulted.append((args, dict(kwargs), snapshot["name"]))
143
+ elif info["exit_code"] not in (0, 1):
144
+ raise RuntimeError(f"Grader command exit {info['exit_code']}: {snapshot['name']}")
145
+ return score
146
+
147
+ task.BashGrader = ObservedGrader
148
+ result = await task._grade(None)
149
+ if faulted:
150
+ # Ask the same commands about the untouched repository. A verdict there
151
+ # means the grader works here and the submission is what it could not
152
+ # judge, so the criterion stays unmet. No verdict there means the
153
+ # environment is at fault, and the attempt is invalid.
154
+ await task.repo_lib.git(task.REPO_DIR, "reset", "--hard", "HEAD")
155
+ await task.repo_lib.git(task.REPO_DIR, "clean", "-fd")
156
+ # Graders keep state between criteria, some of them a copy of the tree
157
+ # they judged. It describes the submission, so it goes too.
158
+ for leftover in Path(getattr(task, "LOGS_DIR", "/hud/logs")).iterdir():
159
+ if leftover.is_dir() and not leftover.is_symlink():
160
+ shutil.rmtree(leftover)
161
+ else:
162
+ leftover.unlink()
163
+ record["fault_probes"] = []
164
+ for args, kwargs, name in faulted:
165
+ _hand_over_checkout()
166
+ probe = (await original.grade(*args, **kwargs)).model_dump(mode="json")
167
+ info = probe.get("info") or {}
168
+ record["fault_probes"].append(
169
+ {
170
+ "name": name,
171
+ "exit_code": info.get("exit_code"),
172
+ "timed_out": info.get("timed_out"),
173
+ "stdout": (info.get("stdout") or "")[-2000:],
174
+ }
175
+ )
176
+ (PRIVATE / "fault_probes.json").write_text(json.dumps(record["fault_probes"], indent=2))
177
+ if info.get("timed_out") or info.get("exit_code") not in (0, 1):
178
+ raise RuntimeError(f"Grader cannot judge the untouched repository: {name}")
179
+ record["result"] = result.model_dump(mode="json")
180
+ # A rubric may answer an empty change without running any criterion.
181
+ record["status"] = "empty_patch" if not patch and not record["commands"] else "graded"
182
+
183
+
184
+ def _stop_candidate_processes() -> None:
185
+ # A candidate may fork. End its UID's processes before publishing evidence
186
+ # to a host bind mount, whose permissions may differ on Docker Desktop.
187
+ for directory in Path("/proc").iterdir():
188
+ if not directory.name.isdecimal():
189
+ continue
190
+ try:
191
+ status = (directory / "status").read_text()
192
+ uid = next(line.split()[1] for line in status.splitlines() if line.startswith("Uid:"))
193
+ if uid == "1000":
194
+ os.kill(int(directory.name), signal.SIGKILL)
195
+ except (FileNotFoundError, ProcessLookupError):
196
+ pass
197
+
198
+
199
+ def main() -> None:
200
+ """Persist structured evidence and publish reward only after validation."""
201
+ OUT.mkdir(parents=True, exist_ok=True)
202
+ PRIVATE.mkdir(parents=True, exist_ok=True, mode=0o700)
203
+ PRIVATE.chmod(0o700)
204
+ reward_path = OUT / "reward.txt"
205
+ reward_path.unlink(missing_ok=True)
206
+ config = json.loads(CONFIG.read_text())
207
+ shutil.copy2(CONFIG, OUT / "config.json")
208
+ record: dict[str, Any] = {
209
+ "revision": REVISION,
210
+ "task_id": config["task_id"],
211
+ "grader_version": importlib.metadata.version("hud"),
212
+ "commands": [],
213
+ "status": "error",
214
+ }
215
+ try:
216
+ if PATCH.is_symlink() or not PATCH.is_file() or PATCH.stat().st_size > 32 * 1024 * 1024:
217
+ raise ValueError("Missing, oversized or symlink submission")
218
+ record["patch_sha256"] = hashlib.sha256(PATCH.read_bytes()).hexdigest()
219
+ try:
220
+ asyncio.run(_grade(config, record))
221
+ finally:
222
+ _stop_candidate_processes()
223
+ reward_path.unlink(missing_ok=True)
224
+ validate_report(record, config, record["patch_sha256"])
225
+ (OUT / "report.json").write_text(json.dumps(record, indent=2))
226
+ reward_path.write_text(str(record["result"]["reward"]) + "\n")
227
+ except BaseException as error:
228
+ reward_path.unlink(missing_ok=True)
229
+ record.update(status="error", error={"type": type(error).__name__, "message": str(error)})
230
+ (OUT / "report.json").write_text(json.dumps(record, indent=2))
231
+ raise
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()