servicesToptal commited on
Commit
37116cb
·
verified ·
1 Parent(s): a77824c

Update dataset (part 2)

Browse files
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
- 5 more (geode, kratos, open-xml-sdk, openfire, 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
+ 4 more (geode, kratos, open-xml-sdk, 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
@@ -7,6 +7,7 @@
7
  "coredns_rewrite_svcb_opt",
8
  "epicyon_deleted_post_announce_cache_contract",
9
  "microblogpub_deleted_object_resurrect_lookup_contract",
 
10
  "rope_rename_all_reexport_owners_contract",
11
  "retained_top_level_names_keep_their_values",
12
  "umya_structural_edit_reference_owners_contract",
 
7
  "coredns_rewrite_svcb_opt",
8
  "epicyon_deleted_post_announce_cache_contract",
9
  "microblogpub_deleted_object_resurrect_lookup_contract",
10
+ "openfire_userdeleting_last_owner_contract",
11
  "rope_rename_all_reexport_owners_contract",
12
  "retained_top_level_names_keep_their_values",
13
  "umya_structural_edit_reference_owners_contract",
harbor/tasks/openfire_userdeleting_last_owner_contract/environment/Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-openfire:source-v9 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/java17/bin:/usr/bin:/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
8
+ ENV LANG="C.UTF-8"
9
+ ENV JAVA_HOME="/opt/java17"
10
+ ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=40"
11
+ ENV MAVEN_OPTS="-Xmx768m"
12
+ ENV HOME="/tmp/agent-home"
13
+ ENV GOCACHE="/tmp/agent-home/.cache/go-build"
14
+ ENV HUD_TELEMETRY_ENABLED="false"
15
+ ENV HUD_CLI_ANALYTICS_ENABLED="0"
16
+ WORKDIR /workspace/repo
17
+ USER 1000:1000
18
+ CMD ["sleep", "infinity"]
harbor/tasks/openfire_userdeleting_last_owner_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/openfire_userdeleting_last_owner_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/openfire_userdeleting_last_owner_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/openfire_userdeleting_last_owner_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/openfire_userdeleting_last_owner_contract/instruction.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Please make your changes directly in /workspace/repo.
2
+
3
+ Deleting a user account keeps leaving chat rooms in a state we cannot get out of.
4
+
5
+ The first report was a room whose single owner left the company. Her account was removed, and every
6
+ attempt to change the room's configuration is now refused, the room's admins included: there is no
7
+ owner left, so nobody can appoint one. A restart does not help. A room owned by a shared group ended
8
+ up the same way once that group had nobody left in it: the room still names the group, and there
9
+ is nobody behind it.
10
+
11
+ The departed name also stays behind. It is still written against rooms it owned and rooms it merely
12
+ belonged to, and it never left the chat service's own settings: when somebody recreated a departed
13
+ colleague's account under the same name, the service, running since before the deletion, greeted
14
+ the newcomer as its administrator - owner of any room, and able to create rooms where the rest of us
15
+ cannot.
16
+
17
+ Who takes a room over is your call. Keep the change to that: apart from the account that is
18
+ leaving, and whoever has to take over a room that would otherwise have no owner, every room and
19
+ every service setting comes out exactly as it went in.
20
+
21
+ Leave the test files that ship with the repository byte for byte as they are; add your own.
22
+
23
+ Finish with a final response when your changes are ready.
harbor/tasks/openfire_userdeleting_last_owner_contract/solution/reference.patch ADDED
@@ -0,0 +1,1304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java
2
+ index b569890..043dc8d 100644
3
+ --- a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java
4
+ +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java
5
+ @@ -4120,7 +4120,9 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
6
+
7
+ @Override
8
+ public void memberRemoved(Group group, Map<String, ?> params) {
9
+ - applyAffiliationChangeAndSendPresence(new JID((String)params.get("member")));
10
+ + final JID member = new JID((String)params.get("member"));
11
+ + applyAffiliationChangeAndSendPresence(member);
12
+ + keepAnOwnerAfterGroupChange(group, member);
13
+ }
14
+
15
+ @Override
16
+ @@ -4130,7 +4132,44 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
17
+
18
+ @Override
19
+ public void adminRemoved(Group group, Map<String, ?> params) {
20
+ - applyAffiliationChangeAndSendPresence(new JID((String)params.get("admin")));
21
+ + final JID admin = new JID((String)params.get("admin"));
22
+ + applyAffiliationChangeAndSendPresence(admin);
23
+ + keepAnOwnerAfterGroupChange(group, admin);
24
+ + }
25
+ +
26
+ + /**
27
+ + * A shared group can own this room. When the last person is taken out of such a group, nobody is left who can
28
+ + * administer the room - the same state that deleting its last owner leaves behind - so the room is given a new owner
29
+ + * here. Rooms that are not in memory are seen to by MultiUserChatManager.
30
+ + *
31
+ + * @param group The group that somebody was taken out of.
32
+ + * @param removed The address that was taken out of the group. It is not handed the room: it was just taken out of
33
+ + * the group that owned it.
34
+ + */
35
+ + private void keepAnOwnerAfterGroupChange(@Nonnull final Group group, @Nullable final JID removed)
36
+ + {
37
+ + if (!owners.contains(group.getJID())) {
38
+ + return;
39
+ + }
40
+ + final Lock lock = getMUCService().getChatRoomLock(getJID().getNode());
41
+ + lock.lock();
42
+ + try {
43
+ + if (hasOwnerOtherThan(null)) {
44
+ + return;
45
+ + }
46
+ + final JID replacementJid = findReplacementOwner(removed);
47
+ + if (replacementJid == null) {
48
+ + Log.warn("The last person was taken out of group '{}', which owns MUC room '{}', but no account could be found to take over ownership of the room.", group.getName(), getJID());
49
+ + return;
50
+ + }
51
+ + Log.info("The last person was taken out of group '{}', which owns MUC room '{}'. To prevent having a room without owner, '{}' was made owner of the room.", group.getName(), getJID(), replacementJid);
52
+ + addOwner(replacementJid, getSelfRepresentation().getAffiliation());
53
+ + getMUCService().syncChatRoom(this);
54
+ + } catch (Throwable t) {
55
+ + Log.warn("A problem occurred while trying to keep an owner for room '{}' after group '{}' lost a member.", getJID(), group.getName(), t);
56
+ + } finally {
57
+ + lock.unlock();
58
+ + }
59
+ }
60
+
61
+ private void applyAffiliationChangeAndSendPresence(JID groupMember) {
62
+ @@ -4161,21 +4200,33 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
63
+ try {
64
+ lock.lock();
65
+
66
+ - if (getAffiliation(userJid) == Affiliation.none) {
67
+ - // User had no affiliation with this room.
68
+ - return;
69
+ + final boolean wasAffiliated = getAffiliation(userJid) != Affiliation.none;
70
+ +
71
+ + // Cannot remove the last owner of a chat room. To prevent issues, replace the owner with an administrative
72
+ + // account. Note that ownership can be held through a shared group, in which case this room loses its last
73
+ + // owner when that group loses its last member - which is the same event, reaching this room through a user
74
+ + // that this room does not list at all.
75
+ + boolean roomChanged = false;
76
+ + if (isLeftWithoutOwnerBy(userJid)) {
77
+ + final JID replacementJid = findReplacementOwner(userJid);
78
+ + if (replacementJid == null) {
79
+ + Log.warn("User '{}' is being deleted, and is the last owner of MUC room '{}', but no account could be found to take over ownership of the room.", user.getUsername(), getJID());
80
+ + } else {
81
+ + Log.info("User '{}' is being deleted, but is also the only owner of MUC room '{}'. To prevent having a room without owner, '{}' was made owner of the room.", user.getUsername(), getJID(), replacementJid);
82
+ + addOwner(replacementJid, getSelfRepresentation().getAffiliation());
83
+ + roomChanged = true;
84
+ + }
85
+ }
86
+
87
+ - // Cannot remove the last owner of a chat room. To prevent issues, replace the owner with an administrative account.
88
+ - if (getOwners().contains(userJid) && getOwners().size() == 1) {
89
+ - final JID adminJid = XMPPServer.getInstance().getAdmins().iterator().next();
90
+ - Log.info("User '{}' is being deleted, but is also the only owner of MUC room '{}'. To prevent having a room without owner, server admin '{}' was made owner of the room.", user.getUsername(), getJID(), adminJid);
91
+ - addOwner(adminJid, getSelfRepresentation().getAffiliation());
92
+ + if (wasAffiliated) {
93
+ + // Remove the affiliation of the deleted user with the room
94
+ + addNone(userJid, getSelfRepresentation().getAffiliation());
95
+ + roomChanged = true;
96
+ }
97
+
98
+ - // Remove the affiliation of the deleted user with the room
99
+ - addNone(userJid, getSelfRepresentation().getAffiliation());
100
+ - getMUCService().syncChatRoom(this);
101
+ + if (roomChanged) {
102
+ + getMUCService().syncChatRoom(this);
103
+ + }
104
+ } catch (Throwable t) {
105
+ Log.warn("A problem occurred while trying to update room '{}' as a result of user '{}' being deleted from Openfire.", getJID(), user);
106
+ } finally {
107
+ @@ -4183,6 +4234,107 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
108
+ }
109
+ }
110
+
111
+ + /**
112
+ + * Checks if the removal of the provided address leaves this room without an owner that stands for an existing
113
+ + * account.
114
+ + *
115
+ + * A room whose owner entries never stood for the address that is going, and could not have been emptied by its
116
+ + * departure either, is not left without an owner by this deletion: whatever state it is in, it was in before, and
117
+ + * giving it a new owner here would change a room that this deletion did not touch. An owner entry that names a
118
+ + * shared group that no longer exists is such a case - deleting a user does not delete groups.
119
+ + *
120
+ + * @param excludedAddress The (real) JID that is going.
121
+ + * @return true if this room is about to be left without anyone that can administer it, otherwise false.
122
+ + */
123
+ + private boolean isLeftWithoutOwnerBy(@Nonnull final JID excludedAddress)
124
+ + {
125
+ + if (hasOwnerOtherThan(excludedAddress)) {
126
+ + return false;
127
+ + }
128
+ + final JID excluded = excludedAddress.asBareJID();
129
+ + for (final JID owner : owners) {
130
+ + if (GroupJID.isGroup(owner)) {
131
+ + try {
132
+ + GroupManager.getInstance().getGroup(owner);
133
+ + return true;
134
+ + } catch (GroupNotFoundException e) {
135
+ + Log.debug("Room '{}' is owned by group '{}', which no longer exists.", getJID(), owner, e);
136
+ + }
137
+ + } else if (excluded.equals(owner.asBareJID())) {
138
+ + return true;
139
+ + }
140
+ + }
141
+ + return false;
142
+ + }
143
+ +
144
+ + /**
145
+ + * Checks if this room has an owner other than the provided address. An owner that is held through a shared group
146
+ + * counts only when that group still has a member other than the provided address: a group without members leaves
147
+ + * the room without anyone that can administer it, exactly like an empty list of owners does.
148
+ + *
149
+ + * @param excludedAddress The (real) JID that is not to be taken into account, or null to count every owner.
150
+ + * @return true if another account owns this room, otherwise false.
151
+ + */
152
+ + private boolean hasOwnerOtherThan(@Nullable final JID excludedAddress)
153
+ + {
154
+ + final JID excluded = excludedAddress == null ? null : excludedAddress.asBareJID();
155
+ + for (final JID owner : owners) {
156
+ + if (GroupJID.isGroup(owner)) {
157
+ + try {
158
+ + for (final JID groupMember : GroupManager.getInstance().getGroup(owner).getAll()) {
159
+ + if (!groupMember.asBareJID().equals(excluded)) {
160
+ + return true;
161
+ + }
162
+ + }
163
+ + } catch (GroupNotFoundException e) {
164
+ + Log.debug("Room '{}' is owned by group '{}', which no longer exists.", getJID(), owner, e);
165
+ + }
166
+ + } else if (!owner.asBareJID().equals(excluded)) {
167
+ + return true;
168
+ + }
169
+ + }
170
+ + return false;
171
+ + }
172
+ +
173
+ + /**
174
+ + * Finds an account that can take over ownership of this room: a server administrator when there is one, and
175
+ + * otherwise someone that this room already trusts.
176
+ + *
177
+ + * @param excludedAddress The (real) JID that is not to be selected (typically: a user that is being deleted), or null.
178
+ + * @return the address of the new owner, or null when no suitable account exists.
179
+ + */
180
+ + @Nullable
181
+ + private JID findReplacementOwner(@Nullable final JID excludedAddress)
182
+ + {
183
+ + final List<Collection<JID>> candidateLists = new ArrayList<>();
184
+ + candidateLists.add(XMPPServer.getInstance().getAdmins());
185
+ + candidateLists.add(new ArrayList<>(admins));
186
+ + candidateLists.add(getMembers());
187
+ +
188
+ + final JID excluded = excludedAddress == null ? null : excludedAddress.asBareJID();
189
+ + for (final Collection<JID> candidates : candidateLists) {
190
+ + for (final JID candidate : candidates) {
191
+ + if (candidate == null) {
192
+ + continue;
193
+ + }
194
+ + if (GroupJID.isGroup(candidate)) {
195
+ + try {
196
+ + for (final JID groupMember : GroupManager.getInstance().getGroup(candidate).getAll()) {
197
+ + if (!groupMember.asBareJID().equals(excluded)) {
198
+ + return groupMember.asBareJID();
199
+ + }
200
+ + }
201
+ + } catch (GroupNotFoundException e) {
202
+ + Log.debug("Room '{}' refers to group '{}', which no longer exists.", getJID(), candidate, e);
203
+ + }
204
+ + } else if (!candidate.asBareJID().equals(excluded)) {
205
+ + return candidate.asBareJID();
206
+ + }
207
+ + }
208
+ + }
209
+ + return null;
210
+ + }
211
+ +
212
+ @Override
213
+ public void userModified(User user, Map<String, Object> params)
214
+ {}
215
+ diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MultiUserChatManager.java b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MultiUserChatManager.java
216
+ index 475aef7..def4314 100644
217
+ --- a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MultiUserChatManager.java
218
+ +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MultiUserChatManager.java
219
+ @@ -20,8 +20,11 @@ import org.jivesoftware.database.DbConnectionManager;
220
+ import org.jivesoftware.database.SequenceManager;
221
+ import org.jivesoftware.openfire.XMPPServer;
222
+ import org.jivesoftware.openfire.container.BasicModule;
223
+ +import org.jivesoftware.openfire.event.GroupEventDispatcher;
224
+ +import org.jivesoftware.openfire.event.GroupEventListener;
225
+ import org.jivesoftware.openfire.event.UserEventDispatcher;
226
+ import org.jivesoftware.openfire.event.UserEventListener;
227
+ +import org.jivesoftware.openfire.group.Group;
228
+ import org.jivesoftware.openfire.muc.cluster.ServiceAddedEvent;
229
+ import org.jivesoftware.openfire.muc.cluster.ServiceRemovedEvent;
230
+ import org.jivesoftware.openfire.muc.cluster.ServiceUpdatedEvent;
231
+ @@ -54,7 +57,7 @@ import java.util.stream.Collectors;
232
+ * @author Daniel Henninger
233
+ */
234
+ public class MultiUserChatManager extends BasicModule implements MUCServicePropertyEventListener,
235
+ - UserEventListener {
236
+ + UserEventListener, GroupEventListener {
237
+
238
+ private static final Logger Log = LoggerFactory.getLogger(MultiUserChatManager.class);
239
+
240
+ @@ -140,6 +143,7 @@ public class MultiUserChatManager extends BasicModule implements MUCServicePrope
241
+ addNumberOutgoingMessages();
242
+
243
+ UserEventDispatcher.addListener(this);
244
+ + GroupEventDispatcher.addListener(this);
245
+ MUCServicePropertyEventDispatcher.addListener(this);
246
+ }
247
+
248
+ @@ -151,6 +155,7 @@ public class MultiUserChatManager extends BasicModule implements MUCServicePrope
249
+ super.stop();
250
+
251
+ UserEventDispatcher.removeListener(this);
252
+ + GroupEventDispatcher.removeListener(this);
253
+ MUCServicePropertyEventDispatcher.removeListener(this);
254
+
255
+ // Remove the statistics.
256
+ @@ -1200,8 +1205,20 @@ public class MultiUserChatManager extends BasicModule implements MUCServicePrope
257
+ // When a user is being deleted, all its affiliations need to be removed from chat rooms (OF-2166). Note that
258
+ // every room is an event listener for the same event, which should update rooms that are loaded into memory
259
+ // from the database. This event handler intends to update rooms that are not in memory, but only in the database.
260
+ - MUCPersistenceManager
261
+ - .removeAffiliationFromDB(XMPPServer.getInstance().createJID(user.getUsername(), null, true));
262
+ + final JID userJID = XMPPServer.getInstance().createJID(user.getUsername(), null, true);
263
+ +
264
+ + // Apart from the affiliations that are recorded per room, each service records the users that administer it
265
+ + // and the users that are allowed to create rooms on it. A user that no longer exists should be in neither.
266
+ + for (final MultiUserChatService service : getMultiUserChatServices()) {
267
+ + try {
268
+ + service.removeSysadmin(userJID);
269
+ + service.removeUserAllowedToCreate(userJID);
270
+ + } catch (Exception e) {
271
+ + Log.warn("A problem occurred while trying to update MUC service '{}' as a result of user '{}' being deleted from Openfire.", service.getServiceName(), user, e);
272
+ + }
273
+ + }
274
+ +
275
+ + MUCPersistenceManager.removeAffiliationFromDB(userJID);
276
+ }
277
+
278
+ @Override
279
+ @@ -1209,6 +1226,68 @@ public class MultiUserChatManager extends BasicModule implements MUCServicePrope
280
+ // Do nothing
281
+ }
282
+
283
+ + @Override
284
+ + public void groupCreated(Group group, Map<String, ?> params) {
285
+ + // Do nothing
286
+ + }
287
+ +
288
+ + @Override
289
+ + public void groupDeleting(Group group, Map<String, ?> params) {
290
+ + // Do nothing
291
+ + }
292
+ +
293
+ + @Override
294
+ + public void groupModified(Group group, Map<String, ?> params) {
295
+ + // Do nothing
296
+ + }
297
+ +
298
+ + @Override
299
+ + public void memberAdded(Group group, Map<String, ?> params) {
300
+ + // Do nothing
301
+ + }
302
+ +
303
+ + @Override
304
+ + public void memberRemoved(Group group, Map<String, ?> params) {
305
+ + keepAnOwnerForRoomsOwnedBy(group, (String) params.get("member"));
306
+ + }
307
+ +
308
+ + @Override
309
+ + public void adminAdded(Group group, Map<String, ?> params) {
310
+ + // Do nothing
311
+ + }
312
+ +
313
+ + @Override
314
+ + public void adminRemoved(Group group, Map<String, ?> params) {
315
+ + keepAnOwnerForRoomsOwnedBy(group, (String) params.get("admin"));
316
+ + }
317
+ +
318
+ + /**
319
+ + * A shared group can own chat rooms. When the last person is taken out of such a group, nobody is left who can
320
+ + * administer those rooms - the same state that deleting their last owner leaves behind. Rooms that are in memory
321
+ + * listen to the group's events themselves; this sees to the rooms that are only in the database.
322
+ + *
323
+ + * @param group The group that somebody was taken out of.
324
+ + * @param removed The address that was taken out of the group (as the event reports it), or null.
325
+ + */
326
+ + private void keepAnOwnerForRoomsOwnedBy(@Nonnull final Group group, @Nullable final String removed)
327
+ + {
328
+ + try {
329
+ + if (!group.getAll().isEmpty()) {
330
+ + return;
331
+ + }
332
+ + final Set<Long> roomsInMemory = new HashSet<>();
333
+ + for (final MultiUserChatService service : getMultiUserChatServices()) {
334
+ + for (final MUCRoom room : service.getActiveChatRooms()) {
335
+ + roomsInMemory.add(room.getID());
336
+ + }
337
+ + }
338
+ + MUCPersistenceManager.keepAnOwnerForRoomsOwnedBy(group.getJID(),
339
+ + removed == null ? null : new JID(removed).asBareJID(), roomsInMemory);
340
+ + } catch (Exception e) {
341
+ + Log.warn("A problem occurred while trying to keep an owner for the rooms owned by group '{}' after somebody was taken out of it.", group.getName(), e);
342
+ + }
343
+ + }
344
+ +
345
+ private static class ServiceComparator implements Comparator<MultiUserChatService> {
346
+ @Override
347
+ public int compare(MultiUserChatService o1, MultiUserChatService o2) {
348
+ diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MUCPersistenceManager.java b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MUCPersistenceManager.java
349
+ index bc64ae4..83a7373 100644
350
+ --- a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MUCPersistenceManager.java
351
+ +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MUCPersistenceManager.java
352
+ @@ -21,6 +21,8 @@ import org.dom4j.Element;
353
+ import org.jivesoftware.database.DbConnectionManager;
354
+ import org.jivesoftware.openfire.XMPPServer;
355
+ import org.jivesoftware.openfire.group.GroupJID;
356
+ +import org.jivesoftware.openfire.group.GroupManager;
357
+ +import org.jivesoftware.openfire.group.GroupNotFoundException;
358
+ import org.jivesoftware.openfire.muc.*;
359
+ import org.jivesoftware.util.JiveGlobals;
360
+ import org.jivesoftware.util.NamedThreadFactory;
361
+ @@ -170,6 +172,12 @@ public class MUCPersistenceManager {
362
+ "DELETE FROM ofMucMember WHERE jid=?";
363
+ private static final String DELETE_USER_MUCAFFILIATION =
364
+ "DELETE FROM ofMucAffiliation WHERE jid=?";
365
+ + private static final String LOAD_ALL_AFFILIATIONS_OF_KIND =
366
+ + "SELECT roomID,jid FROM ofMucAffiliation WHERE affiliation=?";
367
+ + private static final String LOAD_ROOM_AFFILIATIONS_OF_KIND =
368
+ + "SELECT jid FROM ofMucAffiliation WHERE roomID=? AND affiliation=? ORDER BY jid";
369
+ + private static final String LOAD_ROOM_MEMBERS =
370
+ + "SELECT jid FROM ofMucMember WHERE roomID=? ORDER BY jid";
371
+ private static final String ADD_CONVERSATION_LOG =
372
+ "INSERT INTO ofMucConversationLog (roomID,messageID,sender,nickname,logTime,subject,body,stanza) VALUES (?,?,?,?,?,?,?,?)";
373
+ private static final String DELETE_ROOM_HISTORY =
374
+ @@ -1369,6 +1377,21 @@ public class MUCPersistenceManager {
375
+ PreparedStatement pstmt = null;
376
+ try {
377
+ con = DbConnectionManager.getConnection();
378
+ +
379
+ + // Rooms that are not in memory have no event listener of their own: a room that is left without an owner
380
+ + // by the removal below has to be given a new owner here. Ownership can be held through a shared group, so
381
+ + // a room whose only owner is a group that no longer has members is in the same position as a room whose
382
+ + // only owner is the user that is being deleted.
383
+ + for (final Long roomID : roomsLeftWithoutOwnerBy(con, affiliationJID)) {
384
+ + final JID replacementJID = findReplacementOwner(con, roomID, affiliationJID);
385
+ + if (replacementJID == null) {
386
+ + Log.warn("User '{}' is being deleted, and is the last owner of MUC room with ID {}, but no account could be found to take over ownership of the room.", affiliationJID, roomID);
387
+ + } else {
388
+ + Log.info("User '{}' is being deleted, but is also the only owner of MUC room with ID {}. To prevent having a room without owner, '{}' was made owner of the room.", affiliationJID, roomID, replacementJID);
389
+ + saveOwnerToDB(con, roomID, replacementJID);
390
+ + }
391
+ + }
392
+ +
393
+ // Remove the user from the members table
394
+ pstmt = con.prepareStatement(DELETE_USER_MEMBER);
395
+ pstmt.setString(1, affiliationJID.toBareJID());
396
+ @@ -1388,6 +1411,247 @@ public class MUCPersistenceManager {
397
+ }
398
+ }
399
+
400
+ + /**
401
+ + * Returns the IDs of the persistent rooms that the removal of the provided address leaves without an owner that
402
+ + * refers to an existing account. An owner entry that is a shared group counts only when that group still has a
403
+ + * member other than the provided address.
404
+ + *
405
+ + * A room whose owner entries never stood for the address that is going, and could not have been emptied by its
406
+ + * departure either, is none of this method's business: it was already in whatever state it is in before this
407
+ + * deletion, and handing it a new owner here would change a room that this deletion did not touch.
408
+ + *
409
+ + * @param con an open database connection.
410
+ + * @param excludedJID The (real) JID that is not to be taken into account (typically: a user that is being deleted).
411
+ + * @return the IDs of the rooms that are about to be left without an owner.
412
+ + * @throws SQLException when the affiliations could not be read.
413
+ + */
414
+ + private static Collection<Long> roomsLeftWithoutOwnerBy(Connection con, JID excludedJID) throws SQLException
415
+ + {
416
+ + final Map<Long, Boolean> hasOtherOwner = new LinkedHashMap<>();
417
+ + final Map<Long, Boolean> concerned = new LinkedHashMap<>();
418
+ + try (final PreparedStatement pstmt = con.prepareStatement(LOAD_ALL_AFFILIATIONS_OF_KIND)) {
419
+ + pstmt.setInt(1, Affiliation.owner.getValue());
420
+ + try (final ResultSet rs = pstmt.executeQuery()) {
421
+ + while (rs.next()) {
422
+ + final long roomID = rs.getLong(1);
423
+ + final String storedJID = rs.getString(2);
424
+ + hasOtherOwner.merge(roomID, isAccountOtherThan(storedJID, excludedJID), Boolean::logicalOr);
425
+ + concerned.merge(roomID, couldHaveLostItsAccount(storedJID, excludedJID), Boolean::logicalOr);
426
+ + }
427
+ + }
428
+ + }
429
+ +
430
+ + final List<Long> result = new ArrayList<>();
431
+ + for (final Map.Entry<Long, Boolean> entry : hasOtherOwner.entrySet()) {
432
+ + if (!entry.getValue() && Boolean.TRUE.equals(concerned.get(entry.getKey()))) {
433
+ + result.add(entry.getKey());
434
+ + }
435
+ + }
436
+ + return result;
437
+ + }
438
+ +
439
+ + /**
440
+ + * Checks if an owner entry can have stopped standing for an existing account through the removal of the provided
441
+ + * address: the entry is that address, or it is a shared group that still exists - a group that is empty now may
442
+ + * have just lost its last member, and that member may have been the address that is going.
443
+ + *
444
+ + * An entry that names a shared group that no longer exists cannot have been emptied here, because deleting a user
445
+ + * does not delete groups. Such an entry had already stopped standing for anybody before this deletion started.
446
+ + */
447
+ + private static boolean couldHaveLostItsAccount(String storedJID, JID excludedJID)
448
+ + {
449
+ + if (storedJID == null || storedJID.isEmpty()) {
450
+ + return false;
451
+ + }
452
+ + final JID stored = new JID(storedJID);
453
+ + if (GroupJID.isGroup(stored)) {
454
+ + try {
455
+ + GroupManager.getInstance().getGroup(stored);
456
+ + return true;
457
+ + } catch (GroupNotFoundException e) {
458
+ + Log.debug("A MUC room is affiliated with group '{}', which no longer exists.", storedJID, e);
459
+ + return false;
460
+ + }
461
+ + }
462
+ + return excludedJID.asBareJID().equals(stored.asBareJID());
463
+ + }
464
+ +
465
+ + /**
466
+ + * Finds an account that can take over ownership of a room that is not in memory: a server administrator when there
467
+ + * is one, and otherwise someone that the room already trusts.
468
+ + *
469
+ + * @param con an open database connection.
470
+ + * @param roomID The ID of the room that needs a new owner.
471
+ + * @param excludedJID The (real) JID that is not to be selected (typically: a user that is being deleted).
472
+ + * @return the address of the new owner, or null when no suitable account exists.
473
+ + * @throws SQLException when the affiliations could not be read.
474
+ + */
475
+ + private static JID findReplacementOwner(Connection con, Long roomID, JID excludedJID) throws SQLException
476
+ + {
477
+ + final List<String> candidates = new ArrayList<>();
478
+ + for (final JID admin : XMPPServer.getInstance().getAdmins()) {
479
+ + candidates.add(admin.toBareJID());
480
+ + }
481
+ + try (final PreparedStatement pstmt = con.prepareStatement(LOAD_ROOM_AFFILIATIONS_OF_KIND)) {
482
+ + pstmt.setLong(1, roomID);
483
+ + pstmt.setInt(2, Affiliation.admin.getValue());
484
+ + try (final ResultSet rs = pstmt.executeQuery()) {
485
+ + while (rs.next()) {
486
+ + candidates.add(rs.getString(1));
487
+ + }
488
+ + }
489
+ + }
490
+ + try (final PreparedStatement pstmt = con.prepareStatement(LOAD_ROOM_MEMBERS)) {
491
+ + pstmt.setLong(1, roomID);
492
+ + try (final ResultSet rs = pstmt.executeQuery()) {
493
+ + while (rs.next()) {
494
+ + candidates.add(rs.getString(1));
495
+ + }
496
+ + }
497
+ + }
498
+ +
499
+ + for (final String candidate : candidates) {
500
+ + final JID resolved = resolveToAccountOtherThan(candidate, excludedJID);
501
+ + if (resolved != null) {
502
+ + return resolved;
503
+ + }
504
+ + }
505
+ + return null;
506
+ + }
507
+ +
508
+ + /**
509
+ + * Stores an owner affiliation for a room, replacing whatever affiliation that address had in that room before.
510
+ + *
511
+ + * @param con an open database connection.
512
+ + * @param roomID The ID of the room.
513
+ + * @param ownerJID The address that is to own the room.
514
+ + * @throws SQLException when the affiliation could not be written.
515
+ + */
516
+ + private static void saveOwnerToDB(Connection con, Long roomID, JID ownerJID) throws SQLException
517
+ + {
518
+ + // An owner is not a member: the room's own code drops the membership when it promotes someone
519
+ + // (MUCRoom#addOwner), and so does the affiliation that is written per room. Leaving the membership behind
520
+ + // would store the same address as owner and as member at once, which no other path in this class produces,
521
+ + // which a reload does not clean up, and which makes a later demotion collide on the membership's key.
522
+ + try (final PreparedStatement pstmt = con.prepareStatement(DELETE_MEMBER)) {
523
+ + pstmt.setLong(1, roomID);
524
+ + pstmt.setString(2, ownerJID.toBareJID());
525
+ + pstmt.executeUpdate();
526
+ + }
527
+ + try (final PreparedStatement pstmt = con.prepareStatement(UPDATE_AFFILIATION)) {
528
+ + pstmt.setInt(1, Affiliation.owner.getValue());
529
+ + pstmt.setLong(2, roomID);
530
+ + pstmt.setString(3, ownerJID.toBareJID());
531
+ + if (pstmt.executeUpdate() > 0) {
532
+ + return;
533
+ + }
534
+ + }
535
+ + try (final PreparedStatement pstmt = con.prepareStatement(ADD_AFFILIATION)) {
536
+ + pstmt.setLong(1, roomID);
537
+ + pstmt.setString(2, ownerJID.toBareJID());
538
+ + pstmt.setInt(3, Affiliation.owner.getValue());
539
+ + pstmt.executeUpdate();
540
+ + }
541
+ + }
542
+ +
543
+ + /**
544
+ + * Checks if a stored affiliation entry refers to an existing account other than the provided address. Entries that
545
+ + * refer to a shared group are resolved to the members of that group.
546
+ + */
547
+ + private static boolean isAccountOtherThan(String storedJID, JID excludedJID)
548
+ + {
549
+ + return resolveToAccountOtherThan(storedJID, excludedJID) != null;
550
+ + }
551
+ +
552
+ + /**
553
+ + * Resolves a stored affiliation entry to an existing account other than the provided address. Entries that refer to
554
+ + * a shared group are resolved to the first member of that group that qualifies.
555
+ + *
556
+ + * @return the address of a qualifying account, or null when the entry refers to none.
557
+ + */
558
+ + private static JID resolveToAccountOtherThan(String storedJID, JID excludedJID)
559
+ + {
560
+ + if (storedJID == null || storedJID.isEmpty()) {
561
+ + return null;
562
+ + }
563
+ + final JID excluded = excludedJID == null ? null : excludedJID.asBareJID();
564
+ + final JID stored = new JID(storedJID);
565
+ + if (GroupJID.isGroup(stored)) {
566
+ + try {
567
+ + for (final JID groupMember : GroupManager.getInstance().getGroup(stored).getAll()) {
568
+ + if (!groupMember.asBareJID().equals(excluded)) {
569
+ + return groupMember.asBareJID();
570
+ + }
571
+ + }
572
+ + } catch (GroupNotFoundException e) {
573
+ + Log.debug("A MUC room is affiliated with group '{}', which no longer exists.", storedJID, e);
574
+ + }
575
+ + return null;
576
+ + }
577
+ + return stored.asBareJID().equals(excluded) ? null : stored.asBareJID();
578
+ + }
579
+ +
580
+ + /**
581
+ + * Gives an owner to every persistent room that is not in memory, that is owned by the provided shared group, and
582
+ + * that has no owner left that refers to an existing account. This is what taking the last person out of a group
583
+ + * does to the rooms that the group owns: nobody is left who can administer them. Rooms that are in memory see to
584
+ + * this themselves (they listen to the group's events).
585
+ + *
586
+ + * @param groupJID The address of the group that somebody was taken out of.
587
+ + * @param removedJID The address that was taken out of the group (it is not handed a room), or null.
588
+ + * @param roomsInMemory The IDs of the rooms that are in memory, which are left alone here.
589
+ + */
590
+ + public static void keepAnOwnerForRoomsOwnedBy(@Nonnull final JID groupJID, @Nullable final JID removedJID,
591
+ + @Nonnull final Collection<Long> roomsInMemory)
592
+ + {
593
+ + try (final Connection con = DbConnectionManager.getConnection()) {
594
+ + for (final Long roomID : roomsOwnedByWithoutAnOwner(con, groupJID)) {
595
+ + if (roomsInMemory.contains(roomID)) {
596
+ + continue;
597
+ + }
598
+ + final JID replacementJID = findReplacementOwner(con, roomID, removedJID);
599
+ + if (replacementJID == null) {
600
+ + Log.warn("The last person was taken out of group '{}', which owns MUC room with ID {}, but no account could be found to take over ownership of the room.", groupJID, roomID);
601
+ + } else {
602
+ + Log.info("The last person was taken out of group '{}', which owns MUC room with ID {}. To prevent having a room without owner, '{}' was made owner of the room.", groupJID, roomID, replacementJID);
603
+ + saveOwnerToDB(con, roomID, replacementJID);
604
+ + }
605
+ + }
606
+ + } catch (SQLException sqle) {
607
+ + Log.error("A database error occurred while trying to give an owner to the rooms owned by group '{}'.", groupJID, sqle);
608
+ + }
609
+ + }
610
+ +
611
+ + /**
612
+ + * Returns the IDs of the persistent rooms that are owned by the provided group and that have no owner entry left
613
+ + * that refers to an existing account.
614
+ + */
615
+ + private static Collection<Long> roomsOwnedByWithoutAnOwner(Connection con, JID groupJID) throws SQLException
616
+ + {
617
+ + final Map<Long, Boolean> hasOwner = new LinkedHashMap<>();
618
+ + final Set<Long> ownedByGroup = new HashSet<>();
619
+ + try (final PreparedStatement pstmt = con.prepareStatement(LOAD_ALL_AFFILIATIONS_OF_KIND)) {
620
+ + pstmt.setInt(1, Affiliation.owner.getValue());
621
+ + try (final ResultSet rs = pstmt.executeQuery()) {
622
+ + while (rs.next()) {
623
+ + final long roomID = rs.getLong(1);
624
+ + final String storedJID = rs.getString(2);
625
+ + hasOwner.merge(roomID, resolveToAccountOtherThan(storedJID, null) != null, Boolean::logicalOr);
626
+ + if (storedJID != null && (storedJID.equals(groupJID.toString()) || storedJID.equals(groupJID.toBareJID()))) {
627
+ + ownedByGroup.add(roomID);
628
+ + }
629
+ + }
630
+ + }
631
+ + }
632
+ + final List<Long> result = new ArrayList<>();
633
+ + for (final Long roomID : ownedByGroup) {
634
+ + if (!Boolean.TRUE.equals(hasOwner.get(roomID))) {
635
+ + result.add(roomID);
636
+ + }
637
+ + }
638
+ + return result;
639
+ + }
640
+ +
641
+ /**
642
+ * Saves the conversation log entry batch to the database.
643
+ *
644
+ diff --git a/xmppserver/src/test/java/org/jivesoftware/openfire/muc/UserDeletionOwnershipTest.java b/xmppserver/src/test/java/org/jivesoftware/openfire/muc/UserDeletionOwnershipTest.java
645
+ new file mode 100644
646
+ index 0000000..e9c3a49
647
+ --- /dev/null
648
+ +++ b/xmppserver/src/test/java/org/jivesoftware/openfire/muc/UserDeletionOwnershipTest.java
649
+ @@ -0,0 +1,655 @@
650
+ +package org.jivesoftware.openfire.muc;
651
+ +
652
+ +import org.jivesoftware.Fixtures;
653
+ +import org.jivesoftware.database.DbConnectionManager;
654
+ +import org.jivesoftware.database.DefaultConnectionProvider;
655
+ +import org.jivesoftware.openfire.XMPPServer;
656
+ +import org.jivesoftware.openfire.event.GroupEventDispatcher;
657
+ +import org.jivesoftware.openfire.event.UserEventDispatcher;
658
+ +import org.jivesoftware.openfire.group.Group;
659
+ +import org.jivesoftware.openfire.group.GroupJID;
660
+ +import org.jivesoftware.openfire.group.GroupManager;
661
+ +import org.jivesoftware.openfire.group.GroupNotFoundException;
662
+ +import org.jivesoftware.openfire.muc.spi.MUCPersistenceManager;
663
+ +import org.jivesoftware.openfire.muc.spi.MultiUserChatServiceImpl;
664
+ +import org.jivesoftware.openfire.user.User;
665
+ +import org.jivesoftware.util.cache.CacheFactory;
666
+ +import org.junit.jupiter.api.AfterEach;
667
+ +import org.junit.jupiter.api.BeforeAll;
668
+ +import org.junit.jupiter.api.BeforeEach;
669
+ +import org.junit.jupiter.api.Test;
670
+ +import org.xmpp.component.ComponentManager;
671
+ +import org.xmpp.component.ComponentManagerFactory;
672
+ +import org.xmpp.packet.JID;
673
+ +
674
+ +import java.nio.file.Files;
675
+ +import java.nio.file.Path;
676
+ +import java.sql.Connection;
677
+ +import java.sql.PreparedStatement;
678
+ +import java.sql.ResultSet;
679
+ +import java.util.ArrayList;
680
+ +import java.util.Arrays;
681
+ +import java.util.Collections;
682
+ +import java.util.List;
683
+ +import java.util.Map;
684
+ +import java.util.concurrent.locks.ReentrantLock;
685
+ +
686
+ +import static org.junit.jupiter.api.Assertions.assertEquals;
687
+ +import static org.junit.jupiter.api.Assertions.assertFalse;
688
+ +import static org.junit.jupiter.api.Assertions.assertNotNull;
689
+ +import static org.junit.jupiter.api.Assertions.assertTrue;
690
+ +import static org.mockito.ArgumentMatchers.anyString;
691
+ +import static org.mockito.Mockito.doAnswer;
692
+ +import static org.mockito.Mockito.doReturn;
693
+ +import static org.mockito.Mockito.mock;
694
+ +import static org.mockito.Mockito.withSettings;
695
+ +
696
+ +/**
697
+ + * Tests that verify that deleting a user account does not leave a chat room without anyone that can administer it,
698
+ + * and does not leave the deleted account in charge of anything (OF-2166).
699
+ + *
700
+ + * Each test drives the event listeners for the "user is being deleted" event that the affected component registers,
701
+ + * and then observes the database (and, where the room is in memory, the room itself).
702
+ + */
703
+ +public class UserDeletionOwnershipTest {
704
+ +
705
+ + static final String DRIVER = "org.hsqldb.jdbcDriver";
706
+ + static String URL;
707
+ + static Path dbDir;
708
+ + static final String DOMAIN = Fixtures.XMPP_DOMAIN;
709
+ + static final String ALICE = "alice@" + DOMAIN;
710
+ + static final String BOB = "bob@" + DOMAIN;
711
+ + static final String CAROL = "carol@" + DOMAIN;
712
+ + static final String DAVE = "dave@" + DOMAIN;
713
+ + static final String ROOT = "root@" + DOMAIN;
714
+ + static final String ADMIN = "admin@" + DOMAIN;
715
+ +
716
+ + XMPPServer xmppServer;
717
+ + MultiUserChatManager mucManagerMock;
718
+ + MultiUserChatService serviceMock;
719
+ + final List<JID> admins = new ArrayList<>();
720
+ +
721
+ + @BeforeAll
722
+ + static void initDb() throws Exception {
723
+ + Fixtures.reconfigureOpenfireHome();
724
+ + final Path src = Path.of(UserDeletionOwnershipTest.class.getResource("/datasets/openfire.script").toURI()).getParent();
725
+ + dbDir = Files.createTempDirectory("ofuserdel");
726
+ + Files.copy(src.resolve("openfire.script"), dbDir.resolve("openfire.script"));
727
+ + Files.copy(src.resolve("openfire.properties"), dbDir.resolve("openfire.properties"));
728
+ + URL = "jdbc:hsqldb:" + dbDir.resolve("openfire") + ";ifexists=true";
729
+ + }
730
+ +
731
+ + @BeforeEach
732
+ + void setUp() throws Exception {
733
+ + CacheFactory.initialize();
734
+ + Fixtures.clearExistingProperties();
735
+ + Arrays.stream(CacheFactory.getAllCaches()).forEach(Map::clear);
736
+ +
737
+ + final DefaultConnectionProvider cp = new DefaultConnectionProvider();
738
+ + cp.setDriver(DRIVER);
739
+ + cp.setServerURL(URL);
740
+ + cp.setUsername("sa");
741
+ + cp.setPassword("");
742
+ + DbConnectionManager.setConnectionProvider(cp);
743
+ + MultiUserChatManager.MASTER_KEY.setValue("user-deletion-test-master-key");
744
+ +
745
+ + admins.clear();
746
+ + xmppServer = Fixtures.mockXMPPServer();
747
+ + mucManagerMock = mock(MultiUserChatManager.class, withSettings().lenient());
748
+ + doReturn(1L).when(mucManagerMock).getMultiUserChatServiceID(anyString());
749
+ + doReturn(mucManagerMock).when(xmppServer).getMultiUserChatManager();
750
+ + doAnswer(i -> admins).when(xmppServer).getAdmins();
751
+ + XMPPServer.setInstance(xmppServer);
752
+ +
753
+ + serviceMock = mock(MultiUserChatService.class, withSettings().lenient());
754
+ + doReturn("conference").when(serviceMock).getServiceName();
755
+ + doReturn("conference." + DOMAIN).when(serviceMock).getServiceDomain();
756
+ + doReturn(new HistoryStrategy()).when(serviceMock).getHistoryStrategy();
757
+ + doAnswer(i -> new ReentrantLock()).when(serviceMock).getChatRoomLock(anyString());
758
+ +
759
+ + for (final String table : new String[]{"ofMucAffiliation", "ofMucMember", "ofMucRoom",
760
+ + "ofMucServiceProp", "ofMucService", "ofGroupUser", "ofGroupProp", "ofGroup"}) {
761
+ + sql("DELETE FROM " + table);
762
+ + }
763
+ + // A service's settings are cached per subdomain for the life of the JVM, and the rows were just deleted
764
+ + // underneath that cache.
765
+ + MUCPersistenceManager.refreshProperties("conference");
766
+ + }
767
+ +
768
+ + MultiUserChatManager startedManager;
769
+ + MultiUserChatServiceImpl startedService;
770
+ +
771
+ + @AfterEach
772
+ + void tearDown() {
773
+ + // A service that was never started as a component has little to shut down, and parts of the server it would
774
+ + // talk to are not there in a unit test: each step is attempted on its own, so that one of them failing does
775
+ + // not leave the next test holding this test's manager and service.
776
+ + if (startedService != null) {
777
+ + try {
778
+ + for (final MUCRoom room : startedService.getActiveChatRooms()) {
779
+ + UserEventDispatcher.removeListener(room);
780
+ + GroupEventDispatcher.removeListener(room);
781
+ + }
782
+ + } catch (Exception ignored) { }
783
+ + }
784
+ + if (startedManager != null) {
785
+ + try { startedManager.stop(); } catch (Exception ignored) { }
786
+ + try { startedManager.unregisterMultiUserChatService("conference", false); } catch (Exception ignored) { }
787
+ + }
788
+ + if (startedService != null) {
789
+ + try { startedService.shutdown(); } catch (Exception ignored) { }
790
+ + }
791
+ + startedManager = null;
792
+ + startedService = null;
793
+ + Arrays.stream(CacheFactory.getAllCaches()).forEach(Map::clear);
794
+ + }
795
+ +
796
+ + /**
797
+ + * The chat service as the server runs it: its row in the database, and a chat manager that is initialized and
798
+ + * started the way the server starts it. The group manager is created first, as it is at boot, so that its own
799
+ + * listener for deleted accounts (which takes an account out of its groups) runs before the chat manager's.
800
+ + */
801
+ + MultiUserChatServiceImpl startedService() throws Exception {
802
+ + if (startedService != null) {
803
+ + return startedService;
804
+ + }
805
+ + GroupManager.getInstance();
806
+ + ComponentManagerFactory.setComponentManager(mock(ComponentManager.class, withSettings().lenient()));
807
+ + try (Connection c = DbConnectionManager.getConnection();
808
+ + PreparedStatement p = c.prepareStatement(
809
+ + "INSERT INTO ofMucService (serviceID,subdomain,description,isHidden) VALUES (1,'conference',NULL,0)")) {
810
+ + p.executeUpdate();
811
+ + }
812
+ + MUCPersistenceManager.refreshProperties("conference");
813
+ + startedManager = new MultiUserChatManager();
814
+ + doReturn(startedManager).when(xmppServer).getMultiUserChatManager();
815
+ + startedManager.initialize(xmppServer);
816
+ + startedManager.start();
817
+ + startedService = (MultiUserChatServiceImpl) startedManager.getMultiUserChatService("conference");
818
+ + return startedService;
819
+ + }
820
+ +
821
+ + /** UserManager.deleteUser: one dispatch, heard by every listener that registered for it. */
822
+ + void deleteAccount(String username) throws Exception {
823
+ + startedService();
824
+ + UserEventDispatcher.dispatchEvent(mockUser(username),
825
+ + UserEventDispatcher.EventType.user_deleting, Collections.emptyMap());
826
+ + }
827
+ +
828
+ + // ─── fixture helpers ────────────────────────────────────────────────────
829
+ +
830
+ + static void sql(String statement) throws Exception {
831
+ + try (Connection c = DbConnectionManager.getConnection();
832
+ + PreparedStatement p = c.prepareStatement(statement)) {
833
+ + p.executeUpdate();
834
+ + }
835
+ + }
836
+ +
837
+ + void createPersistentRoom(long roomId, String name) throws Exception {
838
+ + String now = String.valueOf(System.currentTimeMillis());
839
+ + while (now.length() < 15) now = "0" + now;
840
+ + try (Connection c = DbConnectionManager.getConnection();
841
+ + PreparedStatement p = c.prepareStatement(
842
+ + "INSERT INTO ofMucRoom (serviceID,roomID,creationDate,modificationDate,name,naturalName," +
843
+ + "description,lockedDate,emptyDate,canChangeSubject,maxUsers,publicRoom,moderated,membersOnly," +
844
+ + "canInvite,roomPassword,canDiscoverJID,logEnabled,retireOnDeletion,preserveHistOnDel,subject," +
845
+ + "rolesToBroadcast,useReservedNick,canChangeNick,canRegister,allowpm) " +
846
+ + "VALUES (1,?,?,?,?,?,NULL,?,?,1,30,1,0,0,0,NULL,1,1,0,1,NULL,7,0,1,1,0)")) {
847
+ + p.setLong(1, roomId); p.setString(2, now); p.setString(3, now);
848
+ + p.setString(4, name); p.setString(5, name); p.setString(6, now); p.setString(7, now);
849
+ + p.executeUpdate();
850
+ + }
851
+ + }
852
+ +
853
+ + void addAffiliation(long roomId, String bareJid, Affiliation affiliation) throws Exception {
854
+ + try (Connection c = DbConnectionManager.getConnection();
855
+ + PreparedStatement p = c.prepareStatement(
856
+ + "INSERT INTO ofMucAffiliation (roomID,jid,affiliation) VALUES (?,?,?)")) {
857
+ + p.setLong(1, roomId); p.setString(2, bareJid); p.setInt(3, affiliation.getValue());
858
+ + p.executeUpdate();
859
+ + }
860
+ + }
861
+ +
862
+ + void addMember(long roomId, String bareJid, String nickname) throws Exception {
863
+ + try (Connection c = DbConnectionManager.getConnection();
864
+ + PreparedStatement p = c.prepareStatement(
865
+ + "INSERT INTO ofMucMember (roomID,jid,nickname) VALUES (?,?,?)")) {
866
+ + p.setLong(1, roomId); p.setString(2, bareJid); p.setString(3, nickname);
867
+ + p.executeUpdate();
868
+ + }
869
+ + }
870
+ +
871
+ + List<String> affiliationRows(long roomId) throws Exception {
872
+ + final List<String> out = new ArrayList<>();
873
+ + try (Connection c = DbConnectionManager.getConnection();
874
+ + PreparedStatement p = c.prepareStatement(
875
+ + "SELECT jid,affiliation FROM ofMucAffiliation WHERE roomID=? ORDER BY jid,affiliation")) {
876
+ + p.setLong(1, roomId);
877
+ + try (ResultSet rs = p.executeQuery()) {
878
+ + while (rs.next()) out.add(rs.getString(1) + ":" + rs.getInt(2));
879
+ + }
880
+ + }
881
+ + return out;
882
+ + }
883
+ +
884
+ + List<String> ownerRows(long roomId) throws Exception {
885
+ + final List<String> out = new ArrayList<>();
886
+ + try (Connection c = DbConnectionManager.getConnection();
887
+ + PreparedStatement p = c.prepareStatement(
888
+ + "SELECT jid FROM ofMucAffiliation WHERE roomID=? AND affiliation=? ORDER BY jid")) {
889
+ + p.setLong(1, roomId); p.setInt(2, Affiliation.owner.getValue());
890
+ + try (ResultSet rs = p.executeQuery()) {
891
+ + while (rs.next()) out.add(rs.getString(1));
892
+ + }
893
+ + }
894
+ + return out;
895
+ + }
896
+ +
897
+ + List<String> memberRows(long roomId) throws Exception {
898
+ + final List<String> out = new ArrayList<>();
899
+ + try (Connection c = DbConnectionManager.getConnection();
900
+ + PreparedStatement p = c.prepareStatement(
901
+ + "SELECT jid,nickname FROM ofMucMember WHERE roomID=? ORDER BY jid")) {
902
+ + p.setLong(1, roomId);
903
+ + try (ResultSet rs = p.executeQuery()) {
904
+ + while (rs.next()) out.add(rs.getString(1) + ":" + rs.getString(2));
905
+ + }
906
+ + }
907
+ + return out;
908
+ + }
909
+ +
910
+ + List<String> rawServiceProperty(String name) throws Exception {
911
+ + final List<String> out = new ArrayList<>();
912
+ + try (Connection c = DbConnectionManager.getConnection();
913
+ + PreparedStatement p = c.prepareStatement(
914
+ + "SELECT propValue FROM ofMucServiceProp WHERE name=? ORDER BY propValue")) {
915
+ + p.setString(1, name);
916
+ + try (ResultSet rs = p.executeQuery()) {
917
+ + while (rs.next()) out.add(rs.getString(1));
918
+ + }
919
+ + }
920
+ + return out;
921
+ + }
922
+ +
923
+ + static User mockUser(String username) {
924
+ + final User u = mock(User.class, withSettings().lenient());
925
+ + doReturn(username).when(u).getUsername();
926
+ + return u;
927
+ + }
928
+ +
929
+ + /** The dispatch of UserManager.deleteUser that reaches the rooms that are not in memory. */
930
+ + static void fireDatabasePathListener(String username) {
931
+ + new MultiUserChatManager().userDeleting(mockUser(username), Collections.emptyMap());
932
+ + }
933
+ +
934
+ + MUCRoom loadRoom(String name) {
935
+ + final MUCRoom room = new MUCRoom(serviceMock, name);
936
+ + MUCPersistenceManager.loadFromDB(room);
937
+ + return room;
938
+ + }
939
+ +
940
+ + /**
941
+ + * Resolves a stored affiliation entry to an existing account other than the one named. An entry that refers to a
942
+ + * shared group resolves to a member of that group. Any account will do: what is checked is that SOMEBODY is left
943
+ + * who can run the room, never who in particular.
944
+ + */
945
+ + static String resolveToAccountOtherThan(String storedJid, String excluded) {
946
+ + if (storedJid == null || storedJid.isEmpty()) {
947
+ + return null;
948
+ + }
949
+ + final JID stored = new JID(storedJid);
950
+ + if (GroupJID.isGroup(stored)) {
951
+ + try {
952
+ + final Group group = GroupManager.getInstance().getGroup(stored);
953
+ + for (final JID member : group.getAll()) {
954
+ + if (!member.asBareJID().toString().equals(excluded)) {
955
+ + return member.asBareJID().toString();
956
+ + }
957
+ + }
958
+ + } catch (GroupNotFoundException e) {
959
+ + return null;
960
+ + }
961
+ + return null;
962
+ + }
963
+ + return stored.asBareJID().toString().equals(excluded) ? null : stored.asBareJID().toString();
964
+ + }
965
+ +
966
+ + static String someoneWhoCanRun(List<String> ownerEntries, String excluded) {
967
+ + for (final String entry : ownerEntries) {
968
+ + final String resolved = resolveToAccountOtherThan(entry, excluded);
969
+ + if (resolved != null) {
970
+ + return resolved;
971
+ + }
972
+ + }
973
+ + return null;
974
+ + }
975
+ +
976
+ + static List<String> asStrings(Iterable<JID> jids) {
977
+ + final List<String> out = new ArrayList<>();
978
+ + for (final JID jid : jids) {
979
+ + out.add(jid.toString());
980
+ + }
981
+ + return out;
982
+ + }
983
+ +
984
+ + // ─── tests ──────────────────────────────────────────────────────────────
985
+ +
986
+ + /**
987
+ + * The membership of a room, as it has to come out of a deletion. Every row that went in is still there, with two
988
+ + * exceptions that the ticket itself makes: the row of the account that is leaving, and the row of whoever had to
989
+ + * take the room over - promoting a member is how the product hands a room on, and it drops that membership when it
990
+ + * does (MUCRoom#addOwner). Nothing else may appear, disappear or change. Who was promoted is the change's call, so
991
+ + * this subtracts whoever owns the room now instead of naming anybody.
992
+ + */
993
+ + void assertMembershipSurvived(long roomId, List<String> wentIn, String deleted) throws Exception {
994
+ + final List<String> cameOut = memberRows(roomId);
995
+ + final List<String> owners = ownerRows(roomId);
996
+ + for (final String row : cameOut) {
997
+ + assertTrue(wentIn.contains(row),
998
+ + "room " + roomId + ": a membership that was not there came out of the deletion: went in=" + wentIn
999
+ + + " came out=" + cameOut);
1000
+ + }
1001
+ + for (final String row : wentIn) {
1002
+ + if (cameOut.contains(row)) {
1003
+ + continue;
1004
+ + }
1005
+ + final String jid = row.substring(0, row.indexOf(':'));
1006
+ + if (jid.equals(deleted)) {
1007
+ + continue;
1008
+ + }
1009
+ + assertTrue(owners.contains(jid),
1010
+ + "room " + roomId + ": '" + jid + "' stopped being a member of a room it did not take over: went in="
1011
+ + + wentIn + " came out=" + cameOut + " owners=" + owners);
1012
+ + }
1013
+ + }
1014
+ +
1015
+ + @Test
1016
+ + public void db_path_persistent_room_keeps_an_owner() throws Exception {
1017
+ + createPersistentRoom(101, "keepsanowner");
1018
+ + addAffiliation(101, ALICE, Affiliation.owner);
1019
+ + addMember(101, CAROL, "caro");
1020
+ + admins.add(new JID(ADMIN));
1021
+ +
1022
+ + fireDatabasePathListener("alice");
1023
+ +
1024
+ + final List<String> owners = ownerRows(101);
1025
+ + assertNotNull(someoneWhoCanRun(owners, ALICE),
1026
+ + "The room is left without an owner that refers to an existing account: " + affiliationRows(101));
1027
+ + assertFalse(affiliationRows(101).stream().anyMatch(r -> r.startsWith(ALICE + ":")),
1028
+ + "The deleted account is still affiliated with the room: " + affiliationRows(101));
1029
+ + assertFalse(memberRows(101).stream().anyMatch(r -> r.startsWith(ALICE + ":")),
1030
+ + "The deleted account still belongs to the room: " + memberRows(101));
1031
+ +
1032
+ + final MUCRoom room = loadRoom("keepsanowner");
1033
+ + assertFalse(room.getOwners().isEmpty(), "The reloaded room has no owner at all.");
1034
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1035
+ + "The reloaded room still gives the deleted account an affiliation.");
1036
+ + }
1037
+ +
1038
+ + @Test
1039
+ + public void db_path_promotion_when_the_admin_already_has_a_row() throws Exception {
1040
+ + createPersistentRoom(102, "adminhasarow");
1041
+ + addAffiliation(102, ALICE, Affiliation.owner);
1042
+ + addAffiliation(102, ADMIN, Affiliation.outcast);
1043
+ + admins.add(new JID(ADMIN));
1044
+ +
1045
+ + fireDatabasePathListener("alice");
1046
+ +
1047
+ + final List<String> rows = affiliationRows(102);
1048
+ + assertNotNull(someoneWhoCanRun(ownerRows(102), ALICE),
1049
+ + "The room is left without an owner that refers to an existing account: " + rows);
1050
+ + assertFalse(rows.stream().anyMatch(r -> r.startsWith(ALICE + ":")),
1051
+ + "The deleted account is still affiliated with the room: " + rows);
1052
+ +
1053
+ + final MUCRoom room = loadRoom("adminhasarow");
1054
+ + assertFalse(room.getOwners().isEmpty(), "The reloaded room has no owner at all.");
1055
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1056
+ + "The reloaded room still gives the deleted account an affiliation.");
1057
+ + }
1058
+ +
1059
+ + @Test
1060
+ + public void promotion_when_the_server_has_no_admin_accounts() throws Exception {
1061
+ + createPersistentRoom(103, "noadmins");
1062
+ + final MUCRoom room = new MUCRoom(serviceMock, "noadmins");
1063
+ + room.setID(103); room.setPersistent(true); room.setSavedToDB(true);
1064
+ + room.addOwner(new JID(ALICE), Affiliation.owner);
1065
+ + room.addAdmin(new JID(BOB), Affiliation.owner);
1066
+ + room.addMember(new JID(CAROL), "caro", Affiliation.owner);
1067
+ + admins.clear();
1068
+ +
1069
+ + room.userDeleting(mockUser("alice"), Collections.emptyMap());
1070
+ +
1071
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1072
+ + "The deleted account still has an affiliation with the room: owners=" + asStrings(room.getOwners()));
1073
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1074
+ + "The room is left without an owner that refers to an existing account: " + asStrings(room.getOwners()));
1075
+ + }
1076
+ +
1077
+ + @Test
1078
+ + public void promotion_when_the_only_admin_is_the_deleted_user() throws Exception {
1079
+ + createPersistentRoom(113, "adminisdeleted");
1080
+ + final MUCRoom room = new MUCRoom(serviceMock, "adminisdeleted");
1081
+ + room.setID(113); room.setPersistent(true); room.setSavedToDB(true);
1082
+ + room.addOwner(new JID(ALICE), Affiliation.owner);
1083
+ + room.addAdmin(new JID(BOB), Affiliation.owner);
1084
+ + admins.clear();
1085
+ + admins.add(new JID(ALICE));
1086
+ +
1087
+ + room.userDeleting(mockUser("alice"), Collections.emptyMap());
1088
+ +
1089
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1090
+ + "The deleted account still has an affiliation with the room: owners=" + asStrings(room.getOwners()));
1091
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1092
+ + "The room is left without an owner that refers to an existing account: " + asStrings(room.getOwners()));
1093
+ + }
1094
+ +
1095
+ + @Test
1096
+ + public void service_level_lists_release_the_deleted_user() throws Exception {
1097
+ + ComponentManagerFactory.setComponentManager(mock(ComponentManager.class, withSettings().lenient()));
1098
+ + try (Connection c = DbConnectionManager.getConnection();
1099
+ + PreparedStatement p = c.prepareStatement(
1100
+ + "INSERT INTO ofMucService (serviceID,subdomain,description,isHidden) VALUES (1,'conference',NULL,0)")) {
1101
+ + p.executeUpdate();
1102
+ + }
1103
+ +
1104
+ + final MultiUserChatManager manager = new MultiUserChatManager();
1105
+ + doReturn(manager).when(xmppServer).getMultiUserChatManager();
1106
+ + final MultiUserChatServiceImpl service = new MultiUserChatServiceImpl(1L, "conference", null, false);
1107
+ + manager.registerMultiUserChatService(service, false);
1108
+ +
1109
+ + MUCPersistenceManager.setProperty("conference", "sysadmin.jid", ALICE + "," + ROOT);
1110
+ + MUCPersistenceManager.setProperty("conference", "create.jid", ALICE + "," + DAVE);
1111
+ + service.initializeSettings();
1112
+ + assertTrue(service.isSysadmin(new JID(ALICE)), "fixture: the account is not a sysadmin to begin with");
1113
+ +
1114
+ + // Dispatched the way the server dispatches it, so that a change that hangs its own listener
1115
+ + // off this event is seen exactly like a change that extends the one that is already there.
1116
+ + UserEventDispatcher.addListener(manager);
1117
+ + try {
1118
+ + UserEventDispatcher.dispatchEvent(mockUser("alice"),
1119
+ + UserEventDispatcher.EventType.user_deleting, Collections.emptyMap());
1120
+ + } finally {
1121
+ + UserEventDispatcher.removeListener(manager);
1122
+ + }
1123
+ +
1124
+ + final List<String> sysadmins = rawServiceProperty("sysadmin.jid");
1125
+ + final List<String> creators = rawServiceProperty("create.jid");
1126
+ + assertFalse(sysadmins.toString().contains(ALICE),
1127
+ + "The deleted account still administers the chat service: sysadmin.jid=" + sysadmins);
1128
+ + assertFalse(creators.toString().contains(ALICE),
1129
+ + "The deleted account may still create rooms on the chat service: create.jid=" + creators);
1130
+ + assertTrue(sysadmins.toString().contains(ROOT),
1131
+ + "The other administrator of the chat service was dropped as well: sysadmin.jid=" + sysadmins);
1132
+ + assertTrue(creators.toString().contains(DAVE),
1133
+ + "The other account allowed to create rooms was dropped as well: create.jid=" + creators);
1134
+ + assertFalse(service.isSysadmin(new JID(ALICE)),
1135
+ + "The running service still treats the deleted account as its administrator.");
1136
+ + }
1137
+ +
1138
+ + @Test
1139
+ + public void group_owned_room_out_of_memory_keeps_an_owner() throws Exception {
1140
+ + final GroupManager groupManager = GroupManager.getInstance();
1141
+ + final Group group = groupManager.createGroup("roomowners");
1142
+ + group.getMembers().add(new JID(ALICE));
1143
+ + final String groupJid = new GroupJID("roomowners").toString();
1144
+ +
1145
+ + createPersistentRoom(107, "groupownedoutofmemory");
1146
+ + addAffiliation(107, groupJid, Affiliation.owner);
1147
+ + admins.add(new JID(ADMIN));
1148
+ +
1149
+ + groupManager.deleteUser(mockUser("alice"));
1150
+ + fireDatabasePathListener("alice");
1151
+ +
1152
+ + assertNotNull(someoneWhoCanRun(ownerRows(107), ALICE),
1153
+ + "The room is left without an owner that refers to an existing account: " + affiliationRows(107));
1154
+ + }
1155
+ +
1156
+ + @Test
1157
+ + public void group_owned_room_in_memory_keeps_an_owner() throws Exception {
1158
+ + final GroupManager groupManager = GroupManager.getInstance();
1159
+ + final Group group = groupManager.createGroup("roomowners2");
1160
+ + group.getMembers().add(new JID(ALICE));
1161
+ + final String groupJid = new GroupJID("roomowners2").toString();
1162
+ +
1163
+ + createPersistentRoom(207, "groupownedinmemory");
1164
+ + addAffiliation(207, groupJid, Affiliation.owner);
1165
+ + admins.add(new JID(ADMIN));
1166
+ +
1167
+ + final MUCRoom room = loadRoom("groupownedinmemory");
1168
+ + assertEquals(Affiliation.owner, room.getAffiliation(new JID(ALICE)),
1169
+ + "fixture: the account does not own the room through the group to begin with");
1170
+ +
1171
+ + groupManager.deleteUser(mockUser("alice"));
1172
+ + room.userDeleting(mockUser("alice"), Collections.emptyMap());
1173
+ +
1174
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1175
+ + "The room is left without an owner that refers to an existing account: " + asStrings(room.getOwners()));
1176
+ + }
1177
+ +
1178
+ + @Test
1179
+ + public void rooms_that_keep_another_owner_come_out_unchanged() throws Exception {
1180
+ + createPersistentRoom(301, "soleowner");
1181
+ + addAffiliation(301, ALICE, Affiliation.owner);
1182
+ +
1183
+ + createPersistentRoom(302, "onlyamember");
1184
+ + addAffiliation(302, BOB, Affiliation.owner);
1185
+ + addMember(302, ALICE, "ali");
1186
+ + addMember(302, CAROL, "caro");
1187
+ +
1188
+ + createPersistentRoom(303, "twoowners");
1189
+ + addAffiliation(303, ALICE, Affiliation.owner);
1190
+ + addAffiliation(303, BOB, Affiliation.owner);
1191
+ +
1192
+ + createPersistentRoom(304, "soleownerwithmembers");
1193
+ + addAffiliation(304, ALICE, Affiliation.owner);
1194
+ + addMember(304, CAROL, "caro");
1195
+ + addMember(304, DAVE, "dav");
1196
+ +
1197
+ + admins.add(new JID(ADMIN));
1198
+ +
1199
+ + fireDatabasePathListener("alice");
1200
+ +
1201
+ + assertNotNull(someoneWhoCanRun(ownerRows(301), ALICE),
1202
+ + "The room that lost its only owner is left without one: " + affiliationRows(301));
1203
+ + assertEquals(List.of(BOB + ":" + Affiliation.owner.getValue()), affiliationRows(302),
1204
+ + "A room that kept its owner did not come out unchanged.");
1205
+ + assertEquals(List.of(CAROL + ":caro"), memberRows(302),
1206
+ + "A room that kept its owner did not come out unchanged.");
1207
+ + assertEquals(List.of(BOB + ":" + Affiliation.owner.getValue()), affiliationRows(303),
1208
+ + "A room that kept one of its two owners did not come out unchanged.");
1209
+ + assertNotNull(someoneWhoCanRun(ownerRows(304), ALICE),
1210
+ + "The room that lost its only owner is left without one: " + affiliationRows(304));
1211
+ + assertMembershipSurvived(304, List.of(CAROL + ":caro", DAVE + ":dav"), ALICE);
1212
+ + }
1213
+ +
1214
+ + @Test
1215
+ + public void in_memory_room_with_no_admin_accounts_is_taken_over_by_a_member() throws Exception {
1216
+ + createPersistentRoom(103, "onlymembersleft");
1217
+ + addAffiliation(103, ALICE, Affiliation.owner);
1218
+ + addMember(103, CAROL, "caro");
1219
+ + admins.clear();
1220
+ + final MUCRoom room = startedService().getChatRoom("onlymembersleft");
1221
+ + assertNotNull(room, "fixture: the room did not load");
1222
+ +
1223
+ + deleteAccount("alice");
1224
+ +
1225
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1226
+ + "The deleted account still has an affiliation with the room.");
1227
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1228
+ + "The room is left without an owner: " + asStrings(room.getOwners()));
1229
+ + assertNotNull(someoneWhoCanRun(ownerRows(103), ALICE),
1230
+ + "After a restart the room has no owner: " + affiliationRows(103));
1231
+ + }
1232
+ +
1233
+ + @Test
1234
+ + public void db_path_room_is_taken_over_when_the_only_admin_is_the_one_leaving() throws Exception {
1235
+ + createPersistentRoom(113, "onlyadminleaves");
1236
+ + addAffiliation(113, ALICE, Affiliation.owner);
1237
+ + addMember(113, CAROL, "caro");
1238
+ + admins.clear();
1239
+ + admins.add(new JID(ALICE));
1240
+ +
1241
+ + deleteAccount("alice");
1242
+ +
1243
+ + assertNotNull(someoneWhoCanRun(ownerRows(113), ALICE),
1244
+ + "The room is left without an owner: " + affiliationRows(113));
1245
+ + assertFalse(affiliationRows(113).stream().anyMatch(r -> r.startsWith(ALICE + ":")),
1246
+ + "The deleted account is still affiliated with the room: " + affiliationRows(113));
1247
+ + }
1248
+ +
1249
+ + @Test
1250
+ + public void group_emptied_by_a_removal_keeps_its_room_owned_out_of_memory() throws Exception {
1251
+ + startedService();
1252
+ + final GroupManager groupManager = GroupManager.getInstance();
1253
+ + groupManager.createGroup("removedowners").getMembers().add(new JID(ALICE));
1254
+ + createPersistentRoom(108, "groupemptiedoutofmemory");
1255
+ + addAffiliation(108, new GroupJID("removedowners").toString(), Affiliation.owner);
1256
+ + addMember(108, CAROL, "caro");
1257
+ + admins.add(new JID(ADMIN));
1258
+ +
1259
+ + groupManager.getGroup("removedowners").getMembers().remove(new JID(ALICE));
1260
+ +
1261
+ + assertNotNull(someoneWhoCanRun(ownerRows(108), null),
1262
+ + "The room still names only a group that has nobody in it: " + affiliationRows(108));
1263
+ + }
1264
+ +
1265
+ + @Test
1266
+ + public void group_emptied_by_a_removal_keeps_its_room_owned_in_memory() throws Exception {
1267
+ + final MultiUserChatServiceImpl service = startedService();
1268
+ + final GroupManager groupManager = GroupManager.getInstance();
1269
+ + groupManager.createGroup("removedowners2").getMembers().add(new JID(ALICE));
1270
+ + createPersistentRoom(208, "groupemptiedinmemory");
1271
+ + addAffiliation(208, new GroupJID("removedowners2").toString(), Affiliation.owner);
1272
+ + addMember(208, CAROL, "caro");
1273
+ + admins.add(new JID(ADMIN));
1274
+ + final MUCRoom room = service.getChatRoom("groupemptiedinmemory");
1275
+ + assertNotNull(room, "fixture: the room did not load");
1276
+ +
1277
+ + groupManager.getGroup("removedowners2").getMembers().remove(new JID(ALICE));
1278
+ +
1279
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), null),
1280
+ + "The room still names only a group that has nobody in it: " + asStrings(room.getOwners()));
1281
+ + assertNotNull(someoneWhoCanRun(ownerRows(208), null),
1282
+ + "After a restart the room names only a group that has nobody in it: " + affiliationRows(208));
1283
+ + }
1284
+ +
1285
+ + @Test
1286
+ + public void in_memory_promotion_when_the_admin_is_banned_from_the_room() throws Exception {
1287
+ + createPersistentRoom(116, "adminisbanned");
1288
+ + addAffiliation(116, ALICE, Affiliation.owner);
1289
+ + addAffiliation(116, ADMIN, Affiliation.outcast);
1290
+ + admins.add(new JID(ALICE));
1291
+ + admins.add(new JID(ADMIN));
1292
+ + final MUCRoom room = startedService().getChatRoom("adminisbanned");
1293
+ + assertNotNull(room, "fixture: the room did not load");
1294
+ +
1295
+ + deleteAccount("alice");
1296
+ +
1297
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1298
+ + "The deleted account still has an affiliation with the room.");
1299
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1300
+ + "The room is left without an owner: " + asStrings(room.getOwners()));
1301
+ + assertNotNull(someoneWhoCanRun(ownerRows(116), ALICE),
1302
+ + "After a restart the room has no owner: " + affiliationRows(116));
1303
+ + }
1304
+ +}
harbor/tasks/openfire_userdeleting_last_owner_contract/solution/solve.sh ADDED
@@ -0,0 +1,1310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -eu
3
+ cd /workspace/repo
4
+ git apply <<'REFERENCE_PATCH'
5
+ diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java
6
+ index b569890..043dc8d 100644
7
+ --- a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java
8
+ +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java
9
+ @@ -4120,7 +4120,9 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
10
+
11
+ @Override
12
+ public void memberRemoved(Group group, Map<String, ?> params) {
13
+ - applyAffiliationChangeAndSendPresence(new JID((String)params.get("member")));
14
+ + final JID member = new JID((String)params.get("member"));
15
+ + applyAffiliationChangeAndSendPresence(member);
16
+ + keepAnOwnerAfterGroupChange(group, member);
17
+ }
18
+
19
+ @Override
20
+ @@ -4130,7 +4132,44 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
21
+
22
+ @Override
23
+ public void adminRemoved(Group group, Map<String, ?> params) {
24
+ - applyAffiliationChangeAndSendPresence(new JID((String)params.get("admin")));
25
+ + final JID admin = new JID((String)params.get("admin"));
26
+ + applyAffiliationChangeAndSendPresence(admin);
27
+ + keepAnOwnerAfterGroupChange(group, admin);
28
+ + }
29
+ +
30
+ + /**
31
+ + * A shared group can own this room. When the last person is taken out of such a group, nobody is left who can
32
+ + * administer the room - the same state that deleting its last owner leaves behind - so the room is given a new owner
33
+ + * here. Rooms that are not in memory are seen to by MultiUserChatManager.
34
+ + *
35
+ + * @param group The group that somebody was taken out of.
36
+ + * @param removed The address that was taken out of the group. It is not handed the room: it was just taken out of
37
+ + * the group that owned it.
38
+ + */
39
+ + private void keepAnOwnerAfterGroupChange(@Nonnull final Group group, @Nullable final JID removed)
40
+ + {
41
+ + if (!owners.contains(group.getJID())) {
42
+ + return;
43
+ + }
44
+ + final Lock lock = getMUCService().getChatRoomLock(getJID().getNode());
45
+ + lock.lock();
46
+ + try {
47
+ + if (hasOwnerOtherThan(null)) {
48
+ + return;
49
+ + }
50
+ + final JID replacementJid = findReplacementOwner(removed);
51
+ + if (replacementJid == null) {
52
+ + Log.warn("The last person was taken out of group '{}', which owns MUC room '{}', but no account could be found to take over ownership of the room.", group.getName(), getJID());
53
+ + return;
54
+ + }
55
+ + Log.info("The last person was taken out of group '{}', which owns MUC room '{}'. To prevent having a room without owner, '{}' was made owner of the room.", group.getName(), getJID(), replacementJid);
56
+ + addOwner(replacementJid, getSelfRepresentation().getAffiliation());
57
+ + getMUCService().syncChatRoom(this);
58
+ + } catch (Throwable t) {
59
+ + Log.warn("A problem occurred while trying to keep an owner for room '{}' after group '{}' lost a member.", getJID(), group.getName(), t);
60
+ + } finally {
61
+ + lock.unlock();
62
+ + }
63
+ }
64
+
65
+ private void applyAffiliationChangeAndSendPresence(JID groupMember) {
66
+ @@ -4161,21 +4200,33 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
67
+ try {
68
+ lock.lock();
69
+
70
+ - if (getAffiliation(userJid) == Affiliation.none) {
71
+ - // User had no affiliation with this room.
72
+ - return;
73
+ + final boolean wasAffiliated = getAffiliation(userJid) != Affiliation.none;
74
+ +
75
+ + // Cannot remove the last owner of a chat room. To prevent issues, replace the owner with an administrative
76
+ + // account. Note that ownership can be held through a shared group, in which case this room loses its last
77
+ + // owner when that group loses its last member - which is the same event, reaching this room through a user
78
+ + // that this room does not list at all.
79
+ + boolean roomChanged = false;
80
+ + if (isLeftWithoutOwnerBy(userJid)) {
81
+ + final JID replacementJid = findReplacementOwner(userJid);
82
+ + if (replacementJid == null) {
83
+ + Log.warn("User '{}' is being deleted, and is the last owner of MUC room '{}', but no account could be found to take over ownership of the room.", user.getUsername(), getJID());
84
+ + } else {
85
+ + Log.info("User '{}' is being deleted, but is also the only owner of MUC room '{}'. To prevent having a room without owner, '{}' was made owner of the room.", user.getUsername(), getJID(), replacementJid);
86
+ + addOwner(replacementJid, getSelfRepresentation().getAffiliation());
87
+ + roomChanged = true;
88
+ + }
89
+ }
90
+
91
+ - // Cannot remove the last owner of a chat room. To prevent issues, replace the owner with an administrative account.
92
+ - if (getOwners().contains(userJid) && getOwners().size() == 1) {
93
+ - final JID adminJid = XMPPServer.getInstance().getAdmins().iterator().next();
94
+ - Log.info("User '{}' is being deleted, but is also the only owner of MUC room '{}'. To prevent having a room without owner, server admin '{}' was made owner of the room.", user.getUsername(), getJID(), adminJid);
95
+ - addOwner(adminJid, getSelfRepresentation().getAffiliation());
96
+ + if (wasAffiliated) {
97
+ + // Remove the affiliation of the deleted user with the room
98
+ + addNone(userJid, getSelfRepresentation().getAffiliation());
99
+ + roomChanged = true;
100
+ }
101
+
102
+ - // Remove the affiliation of the deleted user with the room
103
+ - addNone(userJid, getSelfRepresentation().getAffiliation());
104
+ - getMUCService().syncChatRoom(this);
105
+ + if (roomChanged) {
106
+ + getMUCService().syncChatRoom(this);
107
+ + }
108
+ } catch (Throwable t) {
109
+ Log.warn("A problem occurred while trying to update room '{}' as a result of user '{}' being deleted from Openfire.", getJID(), user);
110
+ } finally {
111
+ @@ -4183,6 +4234,107 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
112
+ }
113
+ }
114
+
115
+ + /**
116
+ + * Checks if the removal of the provided address leaves this room without an owner that stands for an existing
117
+ + * account.
118
+ + *
119
+ + * A room whose owner entries never stood for the address that is going, and could not have been emptied by its
120
+ + * departure either, is not left without an owner by this deletion: whatever state it is in, it was in before, and
121
+ + * giving it a new owner here would change a room that this deletion did not touch. An owner entry that names a
122
+ + * shared group that no longer exists is such a case - deleting a user does not delete groups.
123
+ + *
124
+ + * @param excludedAddress The (real) JID that is going.
125
+ + * @return true if this room is about to be left without anyone that can administer it, otherwise false.
126
+ + */
127
+ + private boolean isLeftWithoutOwnerBy(@Nonnull final JID excludedAddress)
128
+ + {
129
+ + if (hasOwnerOtherThan(excludedAddress)) {
130
+ + return false;
131
+ + }
132
+ + final JID excluded = excludedAddress.asBareJID();
133
+ + for (final JID owner : owners) {
134
+ + if (GroupJID.isGroup(owner)) {
135
+ + try {
136
+ + GroupManager.getInstance().getGroup(owner);
137
+ + return true;
138
+ + } catch (GroupNotFoundException e) {
139
+ + Log.debug("Room '{}' is owned by group '{}', which no longer exists.", getJID(), owner, e);
140
+ + }
141
+ + } else if (excluded.equals(owner.asBareJID())) {
142
+ + return true;
143
+ + }
144
+ + }
145
+ + return false;
146
+ + }
147
+ +
148
+ + /**
149
+ + * Checks if this room has an owner other than the provided address. An owner that is held through a shared group
150
+ + * counts only when that group still has a member other than the provided address: a group without members leaves
151
+ + * the room without anyone that can administer it, exactly like an empty list of owners does.
152
+ + *
153
+ + * @param excludedAddress The (real) JID that is not to be taken into account, or null to count every owner.
154
+ + * @return true if another account owns this room, otherwise false.
155
+ + */
156
+ + private boolean hasOwnerOtherThan(@Nullable final JID excludedAddress)
157
+ + {
158
+ + final JID excluded = excludedAddress == null ? null : excludedAddress.asBareJID();
159
+ + for (final JID owner : owners) {
160
+ + if (GroupJID.isGroup(owner)) {
161
+ + try {
162
+ + for (final JID groupMember : GroupManager.getInstance().getGroup(owner).getAll()) {
163
+ + if (!groupMember.asBareJID().equals(excluded)) {
164
+ + return true;
165
+ + }
166
+ + }
167
+ + } catch (GroupNotFoundException e) {
168
+ + Log.debug("Room '{}' is owned by group '{}', which no longer exists.", getJID(), owner, e);
169
+ + }
170
+ + } else if (!owner.asBareJID().equals(excluded)) {
171
+ + return true;
172
+ + }
173
+ + }
174
+ + return false;
175
+ + }
176
+ +
177
+ + /**
178
+ + * Finds an account that can take over ownership of this room: a server administrator when there is one, and
179
+ + * otherwise someone that this room already trusts.
180
+ + *
181
+ + * @param excludedAddress The (real) JID that is not to be selected (typically: a user that is being deleted), or null.
182
+ + * @return the address of the new owner, or null when no suitable account exists.
183
+ + */
184
+ + @Nullable
185
+ + private JID findReplacementOwner(@Nullable final JID excludedAddress)
186
+ + {
187
+ + final List<Collection<JID>> candidateLists = new ArrayList<>();
188
+ + candidateLists.add(XMPPServer.getInstance().getAdmins());
189
+ + candidateLists.add(new ArrayList<>(admins));
190
+ + candidateLists.add(getMembers());
191
+ +
192
+ + final JID excluded = excludedAddress == null ? null : excludedAddress.asBareJID();
193
+ + for (final Collection<JID> candidates : candidateLists) {
194
+ + for (final JID candidate : candidates) {
195
+ + if (candidate == null) {
196
+ + continue;
197
+ + }
198
+ + if (GroupJID.isGroup(candidate)) {
199
+ + try {
200
+ + for (final JID groupMember : GroupManager.getInstance().getGroup(candidate).getAll()) {
201
+ + if (!groupMember.asBareJID().equals(excluded)) {
202
+ + return groupMember.asBareJID();
203
+ + }
204
+ + }
205
+ + } catch (GroupNotFoundException e) {
206
+ + Log.debug("Room '{}' refers to group '{}', which no longer exists.", getJID(), candidate, e);
207
+ + }
208
+ + } else if (!candidate.asBareJID().equals(excluded)) {
209
+ + return candidate.asBareJID();
210
+ + }
211
+ + }
212
+ + }
213
+ + return null;
214
+ + }
215
+ +
216
+ @Override
217
+ public void userModified(User user, Map<String, Object> params)
218
+ {}
219
+ diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MultiUserChatManager.java b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MultiUserChatManager.java
220
+ index 475aef7..def4314 100644
221
+ --- a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MultiUserChatManager.java
222
+ +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MultiUserChatManager.java
223
+ @@ -20,8 +20,11 @@ import org.jivesoftware.database.DbConnectionManager;
224
+ import org.jivesoftware.database.SequenceManager;
225
+ import org.jivesoftware.openfire.XMPPServer;
226
+ import org.jivesoftware.openfire.container.BasicModule;
227
+ +import org.jivesoftware.openfire.event.GroupEventDispatcher;
228
+ +import org.jivesoftware.openfire.event.GroupEventListener;
229
+ import org.jivesoftware.openfire.event.UserEventDispatcher;
230
+ import org.jivesoftware.openfire.event.UserEventListener;
231
+ +import org.jivesoftware.openfire.group.Group;
232
+ import org.jivesoftware.openfire.muc.cluster.ServiceAddedEvent;
233
+ import org.jivesoftware.openfire.muc.cluster.ServiceRemovedEvent;
234
+ import org.jivesoftware.openfire.muc.cluster.ServiceUpdatedEvent;
235
+ @@ -54,7 +57,7 @@ import java.util.stream.Collectors;
236
+ * @author Daniel Henninger
237
+ */
238
+ public class MultiUserChatManager extends BasicModule implements MUCServicePropertyEventListener,
239
+ - UserEventListener {
240
+ + UserEventListener, GroupEventListener {
241
+
242
+ private static final Logger Log = LoggerFactory.getLogger(MultiUserChatManager.class);
243
+
244
+ @@ -140,6 +143,7 @@ public class MultiUserChatManager extends BasicModule implements MUCServicePrope
245
+ addNumberOutgoingMessages();
246
+
247
+ UserEventDispatcher.addListener(this);
248
+ + GroupEventDispatcher.addListener(this);
249
+ MUCServicePropertyEventDispatcher.addListener(this);
250
+ }
251
+
252
+ @@ -151,6 +155,7 @@ public class MultiUserChatManager extends BasicModule implements MUCServicePrope
253
+ super.stop();
254
+
255
+ UserEventDispatcher.removeListener(this);
256
+ + GroupEventDispatcher.removeListener(this);
257
+ MUCServicePropertyEventDispatcher.removeListener(this);
258
+
259
+ // Remove the statistics.
260
+ @@ -1200,8 +1205,20 @@ public class MultiUserChatManager extends BasicModule implements MUCServicePrope
261
+ // When a user is being deleted, all its affiliations need to be removed from chat rooms (OF-2166). Note that
262
+ // every room is an event listener for the same event, which should update rooms that are loaded into memory
263
+ // from the database. This event handler intends to update rooms that are not in memory, but only in the database.
264
+ - MUCPersistenceManager
265
+ - .removeAffiliationFromDB(XMPPServer.getInstance().createJID(user.getUsername(), null, true));
266
+ + final JID userJID = XMPPServer.getInstance().createJID(user.getUsername(), null, true);
267
+ +
268
+ + // Apart from the affiliations that are recorded per room, each service records the users that administer it
269
+ + // and the users that are allowed to create rooms on it. A user that no longer exists should be in neither.
270
+ + for (final MultiUserChatService service : getMultiUserChatServices()) {
271
+ + try {
272
+ + service.removeSysadmin(userJID);
273
+ + service.removeUserAllowedToCreate(userJID);
274
+ + } catch (Exception e) {
275
+ + Log.warn("A problem occurred while trying to update MUC service '{}' as a result of user '{}' being deleted from Openfire.", service.getServiceName(), user, e);
276
+ + }
277
+ + }
278
+ +
279
+ + MUCPersistenceManager.removeAffiliationFromDB(userJID);
280
+ }
281
+
282
+ @Override
283
+ @@ -1209,6 +1226,68 @@ public class MultiUserChatManager extends BasicModule implements MUCServicePrope
284
+ // Do nothing
285
+ }
286
+
287
+ + @Override
288
+ + public void groupCreated(Group group, Map<String, ?> params) {
289
+ + // Do nothing
290
+ + }
291
+ +
292
+ + @Override
293
+ + public void groupDeleting(Group group, Map<String, ?> params) {
294
+ + // Do nothing
295
+ + }
296
+ +
297
+ + @Override
298
+ + public void groupModified(Group group, Map<String, ?> params) {
299
+ + // Do nothing
300
+ + }
301
+ +
302
+ + @Override
303
+ + public void memberAdded(Group group, Map<String, ?> params) {
304
+ + // Do nothing
305
+ + }
306
+ +
307
+ + @Override
308
+ + public void memberRemoved(Group group, Map<String, ?> params) {
309
+ + keepAnOwnerForRoomsOwnedBy(group, (String) params.get("member"));
310
+ + }
311
+ +
312
+ + @Override
313
+ + public void adminAdded(Group group, Map<String, ?> params) {
314
+ + // Do nothing
315
+ + }
316
+ +
317
+ + @Override
318
+ + public void adminRemoved(Group group, Map<String, ?> params) {
319
+ + keepAnOwnerForRoomsOwnedBy(group, (String) params.get("admin"));
320
+ + }
321
+ +
322
+ + /**
323
+ + * A shared group can own chat rooms. When the last person is taken out of such a group, nobody is left who can
324
+ + * administer those rooms - the same state that deleting their last owner leaves behind. Rooms that are in memory
325
+ + * listen to the group's events themselves; this sees to the rooms that are only in the database.
326
+ + *
327
+ + * @param group The group that somebody was taken out of.
328
+ + * @param removed The address that was taken out of the group (as the event reports it), or null.
329
+ + */
330
+ + private void keepAnOwnerForRoomsOwnedBy(@Nonnull final Group group, @Nullable final String removed)
331
+ + {
332
+ + try {
333
+ + if (!group.getAll().isEmpty()) {
334
+ + return;
335
+ + }
336
+ + final Set<Long> roomsInMemory = new HashSet<>();
337
+ + for (final MultiUserChatService service : getMultiUserChatServices()) {
338
+ + for (final MUCRoom room : service.getActiveChatRooms()) {
339
+ + roomsInMemory.add(room.getID());
340
+ + }
341
+ + }
342
+ + MUCPersistenceManager.keepAnOwnerForRoomsOwnedBy(group.getJID(),
343
+ + removed == null ? null : new JID(removed).asBareJID(), roomsInMemory);
344
+ + } catch (Exception e) {
345
+ + Log.warn("A problem occurred while trying to keep an owner for the rooms owned by group '{}' after somebody was taken out of it.", group.getName(), e);
346
+ + }
347
+ + }
348
+ +
349
+ private static class ServiceComparator implements Comparator<MultiUserChatService> {
350
+ @Override
351
+ public int compare(MultiUserChatService o1, MultiUserChatService o2) {
352
+ diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MUCPersistenceManager.java b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MUCPersistenceManager.java
353
+ index bc64ae4..83a7373 100644
354
+ --- a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MUCPersistenceManager.java
355
+ +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MUCPersistenceManager.java
356
+ @@ -21,6 +21,8 @@ import org.dom4j.Element;
357
+ import org.jivesoftware.database.DbConnectionManager;
358
+ import org.jivesoftware.openfire.XMPPServer;
359
+ import org.jivesoftware.openfire.group.GroupJID;
360
+ +import org.jivesoftware.openfire.group.GroupManager;
361
+ +import org.jivesoftware.openfire.group.GroupNotFoundException;
362
+ import org.jivesoftware.openfire.muc.*;
363
+ import org.jivesoftware.util.JiveGlobals;
364
+ import org.jivesoftware.util.NamedThreadFactory;
365
+ @@ -170,6 +172,12 @@ public class MUCPersistenceManager {
366
+ "DELETE FROM ofMucMember WHERE jid=?";
367
+ private static final String DELETE_USER_MUCAFFILIATION =
368
+ "DELETE FROM ofMucAffiliation WHERE jid=?";
369
+ + private static final String LOAD_ALL_AFFILIATIONS_OF_KIND =
370
+ + "SELECT roomID,jid FROM ofMucAffiliation WHERE affiliation=?";
371
+ + private static final String LOAD_ROOM_AFFILIATIONS_OF_KIND =
372
+ + "SELECT jid FROM ofMucAffiliation WHERE roomID=? AND affiliation=? ORDER BY jid";
373
+ + private static final String LOAD_ROOM_MEMBERS =
374
+ + "SELECT jid FROM ofMucMember WHERE roomID=? ORDER BY jid";
375
+ private static final String ADD_CONVERSATION_LOG =
376
+ "INSERT INTO ofMucConversationLog (roomID,messageID,sender,nickname,logTime,subject,body,stanza) VALUES (?,?,?,?,?,?,?,?)";
377
+ private static final String DELETE_ROOM_HISTORY =
378
+ @@ -1369,6 +1377,21 @@ public class MUCPersistenceManager {
379
+ PreparedStatement pstmt = null;
380
+ try {
381
+ con = DbConnectionManager.getConnection();
382
+ +
383
+ + // Rooms that are not in memory have no event listener of their own: a room that is left without an owner
384
+ + // by the removal below has to be given a new owner here. Ownership can be held through a shared group, so
385
+ + // a room whose only owner is a group that no longer has members is in the same position as a room whose
386
+ + // only owner is the user that is being deleted.
387
+ + for (final Long roomID : roomsLeftWithoutOwnerBy(con, affiliationJID)) {
388
+ + final JID replacementJID = findReplacementOwner(con, roomID, affiliationJID);
389
+ + if (replacementJID == null) {
390
+ + Log.warn("User '{}' is being deleted, and is the last owner of MUC room with ID {}, but no account could be found to take over ownership of the room.", affiliationJID, roomID);
391
+ + } else {
392
+ + Log.info("User '{}' is being deleted, but is also the only owner of MUC room with ID {}. To prevent having a room without owner, '{}' was made owner of the room.", affiliationJID, roomID, replacementJID);
393
+ + saveOwnerToDB(con, roomID, replacementJID);
394
+ + }
395
+ + }
396
+ +
397
+ // Remove the user from the members table
398
+ pstmt = con.prepareStatement(DELETE_USER_MEMBER);
399
+ pstmt.setString(1, affiliationJID.toBareJID());
400
+ @@ -1388,6 +1411,247 @@ public class MUCPersistenceManager {
401
+ }
402
+ }
403
+
404
+ + /**
405
+ + * Returns the IDs of the persistent rooms that the removal of the provided address leaves without an owner that
406
+ + * refers to an existing account. An owner entry that is a shared group counts only when that group still has a
407
+ + * member other than the provided address.
408
+ + *
409
+ + * A room whose owner entries never stood for the address that is going, and could not have been emptied by its
410
+ + * departure either, is none of this method's business: it was already in whatever state it is in before this
411
+ + * deletion, and handing it a new owner here would change a room that this deletion did not touch.
412
+ + *
413
+ + * @param con an open database connection.
414
+ + * @param excludedJID The (real) JID that is not to be taken into account (typically: a user that is being deleted).
415
+ + * @return the IDs of the rooms that are about to be left without an owner.
416
+ + * @throws SQLException when the affiliations could not be read.
417
+ + */
418
+ + private static Collection<Long> roomsLeftWithoutOwnerBy(Connection con, JID excludedJID) throws SQLException
419
+ + {
420
+ + final Map<Long, Boolean> hasOtherOwner = new LinkedHashMap<>();
421
+ + final Map<Long, Boolean> concerned = new LinkedHashMap<>();
422
+ + try (final PreparedStatement pstmt = con.prepareStatement(LOAD_ALL_AFFILIATIONS_OF_KIND)) {
423
+ + pstmt.setInt(1, Affiliation.owner.getValue());
424
+ + try (final ResultSet rs = pstmt.executeQuery()) {
425
+ + while (rs.next()) {
426
+ + final long roomID = rs.getLong(1);
427
+ + final String storedJID = rs.getString(2);
428
+ + hasOtherOwner.merge(roomID, isAccountOtherThan(storedJID, excludedJID), Boolean::logicalOr);
429
+ + concerned.merge(roomID, couldHaveLostItsAccount(storedJID, excludedJID), Boolean::logicalOr);
430
+ + }
431
+ + }
432
+ + }
433
+ +
434
+ + final List<Long> result = new ArrayList<>();
435
+ + for (final Map.Entry<Long, Boolean> entry : hasOtherOwner.entrySet()) {
436
+ + if (!entry.getValue() && Boolean.TRUE.equals(concerned.get(entry.getKey()))) {
437
+ + result.add(entry.getKey());
438
+ + }
439
+ + }
440
+ + return result;
441
+ + }
442
+ +
443
+ + /**
444
+ + * Checks if an owner entry can have stopped standing for an existing account through the removal of the provided
445
+ + * address: the entry is that address, or it is a shared group that still exists - a group that is empty now may
446
+ + * have just lost its last member, and that member may have been the address that is going.
447
+ + *
448
+ + * An entry that names a shared group that no longer exists cannot have been emptied here, because deleting a user
449
+ + * does not delete groups. Such an entry had already stopped standing for anybody before this deletion started.
450
+ + */
451
+ + private static boolean couldHaveLostItsAccount(String storedJID, JID excludedJID)
452
+ + {
453
+ + if (storedJID == null || storedJID.isEmpty()) {
454
+ + return false;
455
+ + }
456
+ + final JID stored = new JID(storedJID);
457
+ + if (GroupJID.isGroup(stored)) {
458
+ + try {
459
+ + GroupManager.getInstance().getGroup(stored);
460
+ + return true;
461
+ + } catch (GroupNotFoundException e) {
462
+ + Log.debug("A MUC room is affiliated with group '{}', which no longer exists.", storedJID, e);
463
+ + return false;
464
+ + }
465
+ + }
466
+ + return excludedJID.asBareJID().equals(stored.asBareJID());
467
+ + }
468
+ +
469
+ + /**
470
+ + * Finds an account that can take over ownership of a room that is not in memory: a server administrator when there
471
+ + * is one, and otherwise someone that the room already trusts.
472
+ + *
473
+ + * @param con an open database connection.
474
+ + * @param roomID The ID of the room that needs a new owner.
475
+ + * @param excludedJID The (real) JID that is not to be selected (typically: a user that is being deleted).
476
+ + * @return the address of the new owner, or null when no suitable account exists.
477
+ + * @throws SQLException when the affiliations could not be read.
478
+ + */
479
+ + private static JID findReplacementOwner(Connection con, Long roomID, JID excludedJID) throws SQLException
480
+ + {
481
+ + final List<String> candidates = new ArrayList<>();
482
+ + for (final JID admin : XMPPServer.getInstance().getAdmins()) {
483
+ + candidates.add(admin.toBareJID());
484
+ + }
485
+ + try (final PreparedStatement pstmt = con.prepareStatement(LOAD_ROOM_AFFILIATIONS_OF_KIND)) {
486
+ + pstmt.setLong(1, roomID);
487
+ + pstmt.setInt(2, Affiliation.admin.getValue());
488
+ + try (final ResultSet rs = pstmt.executeQuery()) {
489
+ + while (rs.next()) {
490
+ + candidates.add(rs.getString(1));
491
+ + }
492
+ + }
493
+ + }
494
+ + try (final PreparedStatement pstmt = con.prepareStatement(LOAD_ROOM_MEMBERS)) {
495
+ + pstmt.setLong(1, roomID);
496
+ + try (final ResultSet rs = pstmt.executeQuery()) {
497
+ + while (rs.next()) {
498
+ + candidates.add(rs.getString(1));
499
+ + }
500
+ + }
501
+ + }
502
+ +
503
+ + for (final String candidate : candidates) {
504
+ + final JID resolved = resolveToAccountOtherThan(candidate, excludedJID);
505
+ + if (resolved != null) {
506
+ + return resolved;
507
+ + }
508
+ + }
509
+ + return null;
510
+ + }
511
+ +
512
+ + /**
513
+ + * Stores an owner affiliation for a room, replacing whatever affiliation that address had in that room before.
514
+ + *
515
+ + * @param con an open database connection.
516
+ + * @param roomID The ID of the room.
517
+ + * @param ownerJID The address that is to own the room.
518
+ + * @throws SQLException when the affiliation could not be written.
519
+ + */
520
+ + private static void saveOwnerToDB(Connection con, Long roomID, JID ownerJID) throws SQLException
521
+ + {
522
+ + // An owner is not a member: the room's own code drops the membership when it promotes someone
523
+ + // (MUCRoom#addOwner), and so does the affiliation that is written per room. Leaving the membership behind
524
+ + // would store the same address as owner and as member at once, which no other path in this class produces,
525
+ + // which a reload does not clean up, and which makes a later demotion collide on the membership's key.
526
+ + try (final PreparedStatement pstmt = con.prepareStatement(DELETE_MEMBER)) {
527
+ + pstmt.setLong(1, roomID);
528
+ + pstmt.setString(2, ownerJID.toBareJID());
529
+ + pstmt.executeUpdate();
530
+ + }
531
+ + try (final PreparedStatement pstmt = con.prepareStatement(UPDATE_AFFILIATION)) {
532
+ + pstmt.setInt(1, Affiliation.owner.getValue());
533
+ + pstmt.setLong(2, roomID);
534
+ + pstmt.setString(3, ownerJID.toBareJID());
535
+ + if (pstmt.executeUpdate() > 0) {
536
+ + return;
537
+ + }
538
+ + }
539
+ + try (final PreparedStatement pstmt = con.prepareStatement(ADD_AFFILIATION)) {
540
+ + pstmt.setLong(1, roomID);
541
+ + pstmt.setString(2, ownerJID.toBareJID());
542
+ + pstmt.setInt(3, Affiliation.owner.getValue());
543
+ + pstmt.executeUpdate();
544
+ + }
545
+ + }
546
+ +
547
+ + /**
548
+ + * Checks if a stored affiliation entry refers to an existing account other than the provided address. Entries that
549
+ + * refer to a shared group are resolved to the members of that group.
550
+ + */
551
+ + private static boolean isAccountOtherThan(String storedJID, JID excludedJID)
552
+ + {
553
+ + return resolveToAccountOtherThan(storedJID, excludedJID) != null;
554
+ + }
555
+ +
556
+ + /**
557
+ + * Resolves a stored affiliation entry to an existing account other than the provided address. Entries that refer to
558
+ + * a shared group are resolved to the first member of that group that qualifies.
559
+ + *
560
+ + * @return the address of a qualifying account, or null when the entry refers to none.
561
+ + */
562
+ + private static JID resolveToAccountOtherThan(String storedJID, JID excludedJID)
563
+ + {
564
+ + if (storedJID == null || storedJID.isEmpty()) {
565
+ + return null;
566
+ + }
567
+ + final JID excluded = excludedJID == null ? null : excludedJID.asBareJID();
568
+ + final JID stored = new JID(storedJID);
569
+ + if (GroupJID.isGroup(stored)) {
570
+ + try {
571
+ + for (final JID groupMember : GroupManager.getInstance().getGroup(stored).getAll()) {
572
+ + if (!groupMember.asBareJID().equals(excluded)) {
573
+ + return groupMember.asBareJID();
574
+ + }
575
+ + }
576
+ + } catch (GroupNotFoundException e) {
577
+ + Log.debug("A MUC room is affiliated with group '{}', which no longer exists.", storedJID, e);
578
+ + }
579
+ + return null;
580
+ + }
581
+ + return stored.asBareJID().equals(excluded) ? null : stored.asBareJID();
582
+ + }
583
+ +
584
+ + /**
585
+ + * Gives an owner to every persistent room that is not in memory, that is owned by the provided shared group, and
586
+ + * that has no owner left that refers to an existing account. This is what taking the last person out of a group
587
+ + * does to the rooms that the group owns: nobody is left who can administer them. Rooms that are in memory see to
588
+ + * this themselves (they listen to the group's events).
589
+ + *
590
+ + * @param groupJID The address of the group that somebody was taken out of.
591
+ + * @param removedJID The address that was taken out of the group (it is not handed a room), or null.
592
+ + * @param roomsInMemory The IDs of the rooms that are in memory, which are left alone here.
593
+ + */
594
+ + public static void keepAnOwnerForRoomsOwnedBy(@Nonnull final JID groupJID, @Nullable final JID removedJID,
595
+ + @Nonnull final Collection<Long> roomsInMemory)
596
+ + {
597
+ + try (final Connection con = DbConnectionManager.getConnection()) {
598
+ + for (final Long roomID : roomsOwnedByWithoutAnOwner(con, groupJID)) {
599
+ + if (roomsInMemory.contains(roomID)) {
600
+ + continue;
601
+ + }
602
+ + final JID replacementJID = findReplacementOwner(con, roomID, removedJID);
603
+ + if (replacementJID == null) {
604
+ + Log.warn("The last person was taken out of group '{}', which owns MUC room with ID {}, but no account could be found to take over ownership of the room.", groupJID, roomID);
605
+ + } else {
606
+ + Log.info("The last person was taken out of group '{}', which owns MUC room with ID {}. To prevent having a room without owner, '{}' was made owner of the room.", groupJID, roomID, replacementJID);
607
+ + saveOwnerToDB(con, roomID, replacementJID);
608
+ + }
609
+ + }
610
+ + } catch (SQLException sqle) {
611
+ + Log.error("A database error occurred while trying to give an owner to the rooms owned by group '{}'.", groupJID, sqle);
612
+ + }
613
+ + }
614
+ +
615
+ + /**
616
+ + * Returns the IDs of the persistent rooms that are owned by the provided group and that have no owner entry left
617
+ + * that refers to an existing account.
618
+ + */
619
+ + private static Collection<Long> roomsOwnedByWithoutAnOwner(Connection con, JID groupJID) throws SQLException
620
+ + {
621
+ + final Map<Long, Boolean> hasOwner = new LinkedHashMap<>();
622
+ + final Set<Long> ownedByGroup = new HashSet<>();
623
+ + try (final PreparedStatement pstmt = con.prepareStatement(LOAD_ALL_AFFILIATIONS_OF_KIND)) {
624
+ + pstmt.setInt(1, Affiliation.owner.getValue());
625
+ + try (final ResultSet rs = pstmt.executeQuery()) {
626
+ + while (rs.next()) {
627
+ + final long roomID = rs.getLong(1);
628
+ + final String storedJID = rs.getString(2);
629
+ + hasOwner.merge(roomID, resolveToAccountOtherThan(storedJID, null) != null, Boolean::logicalOr);
630
+ + if (storedJID != null && (storedJID.equals(groupJID.toString()) || storedJID.equals(groupJID.toBareJID()))) {
631
+ + ownedByGroup.add(roomID);
632
+ + }
633
+ + }
634
+ + }
635
+ + }
636
+ + final List<Long> result = new ArrayList<>();
637
+ + for (final Long roomID : ownedByGroup) {
638
+ + if (!Boolean.TRUE.equals(hasOwner.get(roomID))) {
639
+ + result.add(roomID);
640
+ + }
641
+ + }
642
+ + return result;
643
+ + }
644
+ +
645
+ /**
646
+ * Saves the conversation log entry batch to the database.
647
+ *
648
+ diff --git a/xmppserver/src/test/java/org/jivesoftware/openfire/muc/UserDeletionOwnershipTest.java b/xmppserver/src/test/java/org/jivesoftware/openfire/muc/UserDeletionOwnershipTest.java
649
+ new file mode 100644
650
+ index 0000000..e9c3a49
651
+ --- /dev/null
652
+ +++ b/xmppserver/src/test/java/org/jivesoftware/openfire/muc/UserDeletionOwnershipTest.java
653
+ @@ -0,0 +1,655 @@
654
+ +package org.jivesoftware.openfire.muc;
655
+ +
656
+ +import org.jivesoftware.Fixtures;
657
+ +import org.jivesoftware.database.DbConnectionManager;
658
+ +import org.jivesoftware.database.DefaultConnectionProvider;
659
+ +import org.jivesoftware.openfire.XMPPServer;
660
+ +import org.jivesoftware.openfire.event.GroupEventDispatcher;
661
+ +import org.jivesoftware.openfire.event.UserEventDispatcher;
662
+ +import org.jivesoftware.openfire.group.Group;
663
+ +import org.jivesoftware.openfire.group.GroupJID;
664
+ +import org.jivesoftware.openfire.group.GroupManager;
665
+ +import org.jivesoftware.openfire.group.GroupNotFoundException;
666
+ +import org.jivesoftware.openfire.muc.spi.MUCPersistenceManager;
667
+ +import org.jivesoftware.openfire.muc.spi.MultiUserChatServiceImpl;
668
+ +import org.jivesoftware.openfire.user.User;
669
+ +import org.jivesoftware.util.cache.CacheFactory;
670
+ +import org.junit.jupiter.api.AfterEach;
671
+ +import org.junit.jupiter.api.BeforeAll;
672
+ +import org.junit.jupiter.api.BeforeEach;
673
+ +import org.junit.jupiter.api.Test;
674
+ +import org.xmpp.component.ComponentManager;
675
+ +import org.xmpp.component.ComponentManagerFactory;
676
+ +import org.xmpp.packet.JID;
677
+ +
678
+ +import java.nio.file.Files;
679
+ +import java.nio.file.Path;
680
+ +import java.sql.Connection;
681
+ +import java.sql.PreparedStatement;
682
+ +import java.sql.ResultSet;
683
+ +import java.util.ArrayList;
684
+ +import java.util.Arrays;
685
+ +import java.util.Collections;
686
+ +import java.util.List;
687
+ +import java.util.Map;
688
+ +import java.util.concurrent.locks.ReentrantLock;
689
+ +
690
+ +import static org.junit.jupiter.api.Assertions.assertEquals;
691
+ +import static org.junit.jupiter.api.Assertions.assertFalse;
692
+ +import static org.junit.jupiter.api.Assertions.assertNotNull;
693
+ +import static org.junit.jupiter.api.Assertions.assertTrue;
694
+ +import static org.mockito.ArgumentMatchers.anyString;
695
+ +import static org.mockito.Mockito.doAnswer;
696
+ +import static org.mockito.Mockito.doReturn;
697
+ +import static org.mockito.Mockito.mock;
698
+ +import static org.mockito.Mockito.withSettings;
699
+ +
700
+ +/**
701
+ + * Tests that verify that deleting a user account does not leave a chat room without anyone that can administer it,
702
+ + * and does not leave the deleted account in charge of anything (OF-2166).
703
+ + *
704
+ + * Each test drives the event listeners for the "user is being deleted" event that the affected component registers,
705
+ + * and then observes the database (and, where the room is in memory, the room itself).
706
+ + */
707
+ +public class UserDeletionOwnershipTest {
708
+ +
709
+ + static final String DRIVER = "org.hsqldb.jdbcDriver";
710
+ + static String URL;
711
+ + static Path dbDir;
712
+ + static final String DOMAIN = Fixtures.XMPP_DOMAIN;
713
+ + static final String ALICE = "alice@" + DOMAIN;
714
+ + static final String BOB = "bob@" + DOMAIN;
715
+ + static final String CAROL = "carol@" + DOMAIN;
716
+ + static final String DAVE = "dave@" + DOMAIN;
717
+ + static final String ROOT = "root@" + DOMAIN;
718
+ + static final String ADMIN = "admin@" + DOMAIN;
719
+ +
720
+ + XMPPServer xmppServer;
721
+ + MultiUserChatManager mucManagerMock;
722
+ + MultiUserChatService serviceMock;
723
+ + final List<JID> admins = new ArrayList<>();
724
+ +
725
+ + @BeforeAll
726
+ + static void initDb() throws Exception {
727
+ + Fixtures.reconfigureOpenfireHome();
728
+ + final Path src = Path.of(UserDeletionOwnershipTest.class.getResource("/datasets/openfire.script").toURI()).getParent();
729
+ + dbDir = Files.createTempDirectory("ofuserdel");
730
+ + Files.copy(src.resolve("openfire.script"), dbDir.resolve("openfire.script"));
731
+ + Files.copy(src.resolve("openfire.properties"), dbDir.resolve("openfire.properties"));
732
+ + URL = "jdbc:hsqldb:" + dbDir.resolve("openfire") + ";ifexists=true";
733
+ + }
734
+ +
735
+ + @BeforeEach
736
+ + void setUp() throws Exception {
737
+ + CacheFactory.initialize();
738
+ + Fixtures.clearExistingProperties();
739
+ + Arrays.stream(CacheFactory.getAllCaches()).forEach(Map::clear);
740
+ +
741
+ + final DefaultConnectionProvider cp = new DefaultConnectionProvider();
742
+ + cp.setDriver(DRIVER);
743
+ + cp.setServerURL(URL);
744
+ + cp.setUsername("sa");
745
+ + cp.setPassword("");
746
+ + DbConnectionManager.setConnectionProvider(cp);
747
+ + MultiUserChatManager.MASTER_KEY.setValue("user-deletion-test-master-key");
748
+ +
749
+ + admins.clear();
750
+ + xmppServer = Fixtures.mockXMPPServer();
751
+ + mucManagerMock = mock(MultiUserChatManager.class, withSettings().lenient());
752
+ + doReturn(1L).when(mucManagerMock).getMultiUserChatServiceID(anyString());
753
+ + doReturn(mucManagerMock).when(xmppServer).getMultiUserChatManager();
754
+ + doAnswer(i -> admins).when(xmppServer).getAdmins();
755
+ + XMPPServer.setInstance(xmppServer);
756
+ +
757
+ + serviceMock = mock(MultiUserChatService.class, withSettings().lenient());
758
+ + doReturn("conference").when(serviceMock).getServiceName();
759
+ + doReturn("conference." + DOMAIN).when(serviceMock).getServiceDomain();
760
+ + doReturn(new HistoryStrategy()).when(serviceMock).getHistoryStrategy();
761
+ + doAnswer(i -> new ReentrantLock()).when(serviceMock).getChatRoomLock(anyString());
762
+ +
763
+ + for (final String table : new String[]{"ofMucAffiliation", "ofMucMember", "ofMucRoom",
764
+ + "ofMucServiceProp", "ofMucService", "ofGroupUser", "ofGroupProp", "ofGroup"}) {
765
+ + sql("DELETE FROM " + table);
766
+ + }
767
+ + // A service's settings are cached per subdomain for the life of the JVM, and the rows were just deleted
768
+ + // underneath that cache.
769
+ + MUCPersistenceManager.refreshProperties("conference");
770
+ + }
771
+ +
772
+ + MultiUserChatManager startedManager;
773
+ + MultiUserChatServiceImpl startedService;
774
+ +
775
+ + @AfterEach
776
+ + void tearDown() {
777
+ + // A service that was never started as a component has little to shut down, and parts of the server it would
778
+ + // talk to are not there in a unit test: each step is attempted on its own, so that one of them failing does
779
+ + // not leave the next test holding this test's manager and service.
780
+ + if (startedService != null) {
781
+ + try {
782
+ + for (final MUCRoom room : startedService.getActiveChatRooms()) {
783
+ + UserEventDispatcher.removeListener(room);
784
+ + GroupEventDispatcher.removeListener(room);
785
+ + }
786
+ + } catch (Exception ignored) { }
787
+ + }
788
+ + if (startedManager != null) {
789
+ + try { startedManager.stop(); } catch (Exception ignored) { }
790
+ + try { startedManager.unregisterMultiUserChatService("conference", false); } catch (Exception ignored) { }
791
+ + }
792
+ + if (startedService != null) {
793
+ + try { startedService.shutdown(); } catch (Exception ignored) { }
794
+ + }
795
+ + startedManager = null;
796
+ + startedService = null;
797
+ + Arrays.stream(CacheFactory.getAllCaches()).forEach(Map::clear);
798
+ + }
799
+ +
800
+ + /**
801
+ + * The chat service as the server runs it: its row in the database, and a chat manager that is initialized and
802
+ + * started the way the server starts it. The group manager is created first, as it is at boot, so that its own
803
+ + * listener for deleted accounts (which takes an account out of its groups) runs before the chat manager's.
804
+ + */
805
+ + MultiUserChatServiceImpl startedService() throws Exception {
806
+ + if (startedService != null) {
807
+ + return startedService;
808
+ + }
809
+ + GroupManager.getInstance();
810
+ + ComponentManagerFactory.setComponentManager(mock(ComponentManager.class, withSettings().lenient()));
811
+ + try (Connection c = DbConnectionManager.getConnection();
812
+ + PreparedStatement p = c.prepareStatement(
813
+ + "INSERT INTO ofMucService (serviceID,subdomain,description,isHidden) VALUES (1,'conference',NULL,0)")) {
814
+ + p.executeUpdate();
815
+ + }
816
+ + MUCPersistenceManager.refreshProperties("conference");
817
+ + startedManager = new MultiUserChatManager();
818
+ + doReturn(startedManager).when(xmppServer).getMultiUserChatManager();
819
+ + startedManager.initialize(xmppServer);
820
+ + startedManager.start();
821
+ + startedService = (MultiUserChatServiceImpl) startedManager.getMultiUserChatService("conference");
822
+ + return startedService;
823
+ + }
824
+ +
825
+ + /** UserManager.deleteUser: one dispatch, heard by every listener that registered for it. */
826
+ + void deleteAccount(String username) throws Exception {
827
+ + startedService();
828
+ + UserEventDispatcher.dispatchEvent(mockUser(username),
829
+ + UserEventDispatcher.EventType.user_deleting, Collections.emptyMap());
830
+ + }
831
+ +
832
+ + // ─── fixture helpers ────────────────────────────────────────────────────
833
+ +
834
+ + static void sql(String statement) throws Exception {
835
+ + try (Connection c = DbConnectionManager.getConnection();
836
+ + PreparedStatement p = c.prepareStatement(statement)) {
837
+ + p.executeUpdate();
838
+ + }
839
+ + }
840
+ +
841
+ + void createPersistentRoom(long roomId, String name) throws Exception {
842
+ + String now = String.valueOf(System.currentTimeMillis());
843
+ + while (now.length() < 15) now = "0" + now;
844
+ + try (Connection c = DbConnectionManager.getConnection();
845
+ + PreparedStatement p = c.prepareStatement(
846
+ + "INSERT INTO ofMucRoom (serviceID,roomID,creationDate,modificationDate,name,naturalName," +
847
+ + "description,lockedDate,emptyDate,canChangeSubject,maxUsers,publicRoom,moderated,membersOnly," +
848
+ + "canInvite,roomPassword,canDiscoverJID,logEnabled,retireOnDeletion,preserveHistOnDel,subject," +
849
+ + "rolesToBroadcast,useReservedNick,canChangeNick,canRegister,allowpm) " +
850
+ + "VALUES (1,?,?,?,?,?,NULL,?,?,1,30,1,0,0,0,NULL,1,1,0,1,NULL,7,0,1,1,0)")) {
851
+ + p.setLong(1, roomId); p.setString(2, now); p.setString(3, now);
852
+ + p.setString(4, name); p.setString(5, name); p.setString(6, now); p.setString(7, now);
853
+ + p.executeUpdate();
854
+ + }
855
+ + }
856
+ +
857
+ + void addAffiliation(long roomId, String bareJid, Affiliation affiliation) throws Exception {
858
+ + try (Connection c = DbConnectionManager.getConnection();
859
+ + PreparedStatement p = c.prepareStatement(
860
+ + "INSERT INTO ofMucAffiliation (roomID,jid,affiliation) VALUES (?,?,?)")) {
861
+ + p.setLong(1, roomId); p.setString(2, bareJid); p.setInt(3, affiliation.getValue());
862
+ + p.executeUpdate();
863
+ + }
864
+ + }
865
+ +
866
+ + void addMember(long roomId, String bareJid, String nickname) throws Exception {
867
+ + try (Connection c = DbConnectionManager.getConnection();
868
+ + PreparedStatement p = c.prepareStatement(
869
+ + "INSERT INTO ofMucMember (roomID,jid,nickname) VALUES (?,?,?)")) {
870
+ + p.setLong(1, roomId); p.setString(2, bareJid); p.setString(3, nickname);
871
+ + p.executeUpdate();
872
+ + }
873
+ + }
874
+ +
875
+ + List<String> affiliationRows(long roomId) throws Exception {
876
+ + final List<String> out = new ArrayList<>();
877
+ + try (Connection c = DbConnectionManager.getConnection();
878
+ + PreparedStatement p = c.prepareStatement(
879
+ + "SELECT jid,affiliation FROM ofMucAffiliation WHERE roomID=? ORDER BY jid,affiliation")) {
880
+ + p.setLong(1, roomId);
881
+ + try (ResultSet rs = p.executeQuery()) {
882
+ + while (rs.next()) out.add(rs.getString(1) + ":" + rs.getInt(2));
883
+ + }
884
+ + }
885
+ + return out;
886
+ + }
887
+ +
888
+ + List<String> ownerRows(long roomId) throws Exception {
889
+ + final List<String> out = new ArrayList<>();
890
+ + try (Connection c = DbConnectionManager.getConnection();
891
+ + PreparedStatement p = c.prepareStatement(
892
+ + "SELECT jid FROM ofMucAffiliation WHERE roomID=? AND affiliation=? ORDER BY jid")) {
893
+ + p.setLong(1, roomId); p.setInt(2, Affiliation.owner.getValue());
894
+ + try (ResultSet rs = p.executeQuery()) {
895
+ + while (rs.next()) out.add(rs.getString(1));
896
+ + }
897
+ + }
898
+ + return out;
899
+ + }
900
+ +
901
+ + List<String> memberRows(long roomId) throws Exception {
902
+ + final List<String> out = new ArrayList<>();
903
+ + try (Connection c = DbConnectionManager.getConnection();
904
+ + PreparedStatement p = c.prepareStatement(
905
+ + "SELECT jid,nickname FROM ofMucMember WHERE roomID=? ORDER BY jid")) {
906
+ + p.setLong(1, roomId);
907
+ + try (ResultSet rs = p.executeQuery()) {
908
+ + while (rs.next()) out.add(rs.getString(1) + ":" + rs.getString(2));
909
+ + }
910
+ + }
911
+ + return out;
912
+ + }
913
+ +
914
+ + List<String> rawServiceProperty(String name) throws Exception {
915
+ + final List<String> out = new ArrayList<>();
916
+ + try (Connection c = DbConnectionManager.getConnection();
917
+ + PreparedStatement p = c.prepareStatement(
918
+ + "SELECT propValue FROM ofMucServiceProp WHERE name=? ORDER BY propValue")) {
919
+ + p.setString(1, name);
920
+ + try (ResultSet rs = p.executeQuery()) {
921
+ + while (rs.next()) out.add(rs.getString(1));
922
+ + }
923
+ + }
924
+ + return out;
925
+ + }
926
+ +
927
+ + static User mockUser(String username) {
928
+ + final User u = mock(User.class, withSettings().lenient());
929
+ + doReturn(username).when(u).getUsername();
930
+ + return u;
931
+ + }
932
+ +
933
+ + /** The dispatch of UserManager.deleteUser that reaches the rooms that are not in memory. */
934
+ + static void fireDatabasePathListener(String username) {
935
+ + new MultiUserChatManager().userDeleting(mockUser(username), Collections.emptyMap());
936
+ + }
937
+ +
938
+ + MUCRoom loadRoom(String name) {
939
+ + final MUCRoom room = new MUCRoom(serviceMock, name);
940
+ + MUCPersistenceManager.loadFromDB(room);
941
+ + return room;
942
+ + }
943
+ +
944
+ + /**
945
+ + * Resolves a stored affiliation entry to an existing account other than the one named. An entry that refers to a
946
+ + * shared group resolves to a member of that group. Any account will do: what is checked is that SOMEBODY is left
947
+ + * who can run the room, never who in particular.
948
+ + */
949
+ + static String resolveToAccountOtherThan(String storedJid, String excluded) {
950
+ + if (storedJid == null || storedJid.isEmpty()) {
951
+ + return null;
952
+ + }
953
+ + final JID stored = new JID(storedJid);
954
+ + if (GroupJID.isGroup(stored)) {
955
+ + try {
956
+ + final Group group = GroupManager.getInstance().getGroup(stored);
957
+ + for (final JID member : group.getAll()) {
958
+ + if (!member.asBareJID().toString().equals(excluded)) {
959
+ + return member.asBareJID().toString();
960
+ + }
961
+ + }
962
+ + } catch (GroupNotFoundException e) {
963
+ + return null;
964
+ + }
965
+ + return null;
966
+ + }
967
+ + return stored.asBareJID().toString().equals(excluded) ? null : stored.asBareJID().toString();
968
+ + }
969
+ +
970
+ + static String someoneWhoCanRun(List<String> ownerEntries, String excluded) {
971
+ + for (final String entry : ownerEntries) {
972
+ + final String resolved = resolveToAccountOtherThan(entry, excluded);
973
+ + if (resolved != null) {
974
+ + return resolved;
975
+ + }
976
+ + }
977
+ + return null;
978
+ + }
979
+ +
980
+ + static List<String> asStrings(Iterable<JID> jids) {
981
+ + final List<String> out = new ArrayList<>();
982
+ + for (final JID jid : jids) {
983
+ + out.add(jid.toString());
984
+ + }
985
+ + return out;
986
+ + }
987
+ +
988
+ + // ─── tests ──────────────────────────────────────────────────────────────
989
+ +
990
+ + /**
991
+ + * The membership of a room, as it has to come out of a deletion. Every row that went in is still there, with two
992
+ + * exceptions that the ticket itself makes: the row of the account that is leaving, and the row of whoever had to
993
+ + * take the room over - promoting a member is how the product hands a room on, and it drops that membership when it
994
+ + * does (MUCRoom#addOwner). Nothing else may appear, disappear or change. Who was promoted is the change's call, so
995
+ + * this subtracts whoever owns the room now instead of naming anybody.
996
+ + */
997
+ + void assertMembershipSurvived(long roomId, List<String> wentIn, String deleted) throws Exception {
998
+ + final List<String> cameOut = memberRows(roomId);
999
+ + final List<String> owners = ownerRows(roomId);
1000
+ + for (final String row : cameOut) {
1001
+ + assertTrue(wentIn.contains(row),
1002
+ + "room " + roomId + ": a membership that was not there came out of the deletion: went in=" + wentIn
1003
+ + + " came out=" + cameOut);
1004
+ + }
1005
+ + for (final String row : wentIn) {
1006
+ + if (cameOut.contains(row)) {
1007
+ + continue;
1008
+ + }
1009
+ + final String jid = row.substring(0, row.indexOf(':'));
1010
+ + if (jid.equals(deleted)) {
1011
+ + continue;
1012
+ + }
1013
+ + assertTrue(owners.contains(jid),
1014
+ + "room " + roomId + ": '" + jid + "' stopped being a member of a room it did not take over: went in="
1015
+ + + wentIn + " came out=" + cameOut + " owners=" + owners);
1016
+ + }
1017
+ + }
1018
+ +
1019
+ + @Test
1020
+ + public void db_path_persistent_room_keeps_an_owner() throws Exception {
1021
+ + createPersistentRoom(101, "keepsanowner");
1022
+ + addAffiliation(101, ALICE, Affiliation.owner);
1023
+ + addMember(101, CAROL, "caro");
1024
+ + admins.add(new JID(ADMIN));
1025
+ +
1026
+ + fireDatabasePathListener("alice");
1027
+ +
1028
+ + final List<String> owners = ownerRows(101);
1029
+ + assertNotNull(someoneWhoCanRun(owners, ALICE),
1030
+ + "The room is left without an owner that refers to an existing account: " + affiliationRows(101));
1031
+ + assertFalse(affiliationRows(101).stream().anyMatch(r -> r.startsWith(ALICE + ":")),
1032
+ + "The deleted account is still affiliated with the room: " + affiliationRows(101));
1033
+ + assertFalse(memberRows(101).stream().anyMatch(r -> r.startsWith(ALICE + ":")),
1034
+ + "The deleted account still belongs to the room: " + memberRows(101));
1035
+ +
1036
+ + final MUCRoom room = loadRoom("keepsanowner");
1037
+ + assertFalse(room.getOwners().isEmpty(), "The reloaded room has no owner at all.");
1038
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1039
+ + "The reloaded room still gives the deleted account an affiliation.");
1040
+ + }
1041
+ +
1042
+ + @Test
1043
+ + public void db_path_promotion_when_the_admin_already_has_a_row() throws Exception {
1044
+ + createPersistentRoom(102, "adminhasarow");
1045
+ + addAffiliation(102, ALICE, Affiliation.owner);
1046
+ + addAffiliation(102, ADMIN, Affiliation.outcast);
1047
+ + admins.add(new JID(ADMIN));
1048
+ +
1049
+ + fireDatabasePathListener("alice");
1050
+ +
1051
+ + final List<String> rows = affiliationRows(102);
1052
+ + assertNotNull(someoneWhoCanRun(ownerRows(102), ALICE),
1053
+ + "The room is left without an owner that refers to an existing account: " + rows);
1054
+ + assertFalse(rows.stream().anyMatch(r -> r.startsWith(ALICE + ":")),
1055
+ + "The deleted account is still affiliated with the room: " + rows);
1056
+ +
1057
+ + final MUCRoom room = loadRoom("adminhasarow");
1058
+ + assertFalse(room.getOwners().isEmpty(), "The reloaded room has no owner at all.");
1059
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1060
+ + "The reloaded room still gives the deleted account an affiliation.");
1061
+ + }
1062
+ +
1063
+ + @Test
1064
+ + public void promotion_when_the_server_has_no_admin_accounts() throws Exception {
1065
+ + createPersistentRoom(103, "noadmins");
1066
+ + final MUCRoom room = new MUCRoom(serviceMock, "noadmins");
1067
+ + room.setID(103); room.setPersistent(true); room.setSavedToDB(true);
1068
+ + room.addOwner(new JID(ALICE), Affiliation.owner);
1069
+ + room.addAdmin(new JID(BOB), Affiliation.owner);
1070
+ + room.addMember(new JID(CAROL), "caro", Affiliation.owner);
1071
+ + admins.clear();
1072
+ +
1073
+ + room.userDeleting(mockUser("alice"), Collections.emptyMap());
1074
+ +
1075
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1076
+ + "The deleted account still has an affiliation with the room: owners=" + asStrings(room.getOwners()));
1077
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1078
+ + "The room is left without an owner that refers to an existing account: " + asStrings(room.getOwners()));
1079
+ + }
1080
+ +
1081
+ + @Test
1082
+ + public void promotion_when_the_only_admin_is_the_deleted_user() throws Exception {
1083
+ + createPersistentRoom(113, "adminisdeleted");
1084
+ + final MUCRoom room = new MUCRoom(serviceMock, "adminisdeleted");
1085
+ + room.setID(113); room.setPersistent(true); room.setSavedToDB(true);
1086
+ + room.addOwner(new JID(ALICE), Affiliation.owner);
1087
+ + room.addAdmin(new JID(BOB), Affiliation.owner);
1088
+ + admins.clear();
1089
+ + admins.add(new JID(ALICE));
1090
+ +
1091
+ + room.userDeleting(mockUser("alice"), Collections.emptyMap());
1092
+ +
1093
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1094
+ + "The deleted account still has an affiliation with the room: owners=" + asStrings(room.getOwners()));
1095
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1096
+ + "The room is left without an owner that refers to an existing account: " + asStrings(room.getOwners()));
1097
+ + }
1098
+ +
1099
+ + @Test
1100
+ + public void service_level_lists_release_the_deleted_user() throws Exception {
1101
+ + ComponentManagerFactory.setComponentManager(mock(ComponentManager.class, withSettings().lenient()));
1102
+ + try (Connection c = DbConnectionManager.getConnection();
1103
+ + PreparedStatement p = c.prepareStatement(
1104
+ + "INSERT INTO ofMucService (serviceID,subdomain,description,isHidden) VALUES (1,'conference',NULL,0)")) {
1105
+ + p.executeUpdate();
1106
+ + }
1107
+ +
1108
+ + final MultiUserChatManager manager = new MultiUserChatManager();
1109
+ + doReturn(manager).when(xmppServer).getMultiUserChatManager();
1110
+ + final MultiUserChatServiceImpl service = new MultiUserChatServiceImpl(1L, "conference", null, false);
1111
+ + manager.registerMultiUserChatService(service, false);
1112
+ +
1113
+ + MUCPersistenceManager.setProperty("conference", "sysadmin.jid", ALICE + "," + ROOT);
1114
+ + MUCPersistenceManager.setProperty("conference", "create.jid", ALICE + "," + DAVE);
1115
+ + service.initializeSettings();
1116
+ + assertTrue(service.isSysadmin(new JID(ALICE)), "fixture: the account is not a sysadmin to begin with");
1117
+ +
1118
+ + // Dispatched the way the server dispatches it, so that a change that hangs its own listener
1119
+ + // off this event is seen exactly like a change that extends the one that is already there.
1120
+ + UserEventDispatcher.addListener(manager);
1121
+ + try {
1122
+ + UserEventDispatcher.dispatchEvent(mockUser("alice"),
1123
+ + UserEventDispatcher.EventType.user_deleting, Collections.emptyMap());
1124
+ + } finally {
1125
+ + UserEventDispatcher.removeListener(manager);
1126
+ + }
1127
+ +
1128
+ + final List<String> sysadmins = rawServiceProperty("sysadmin.jid");
1129
+ + final List<String> creators = rawServiceProperty("create.jid");
1130
+ + assertFalse(sysadmins.toString().contains(ALICE),
1131
+ + "The deleted account still administers the chat service: sysadmin.jid=" + sysadmins);
1132
+ + assertFalse(creators.toString().contains(ALICE),
1133
+ + "The deleted account may still create rooms on the chat service: create.jid=" + creators);
1134
+ + assertTrue(sysadmins.toString().contains(ROOT),
1135
+ + "The other administrator of the chat service was dropped as well: sysadmin.jid=" + sysadmins);
1136
+ + assertTrue(creators.toString().contains(DAVE),
1137
+ + "The other account allowed to create rooms was dropped as well: create.jid=" + creators);
1138
+ + assertFalse(service.isSysadmin(new JID(ALICE)),
1139
+ + "The running service still treats the deleted account as its administrator.");
1140
+ + }
1141
+ +
1142
+ + @Test
1143
+ + public void group_owned_room_out_of_memory_keeps_an_owner() throws Exception {
1144
+ + final GroupManager groupManager = GroupManager.getInstance();
1145
+ + final Group group = groupManager.createGroup("roomowners");
1146
+ + group.getMembers().add(new JID(ALICE));
1147
+ + final String groupJid = new GroupJID("roomowners").toString();
1148
+ +
1149
+ + createPersistentRoom(107, "groupownedoutofmemory");
1150
+ + addAffiliation(107, groupJid, Affiliation.owner);
1151
+ + admins.add(new JID(ADMIN));
1152
+ +
1153
+ + groupManager.deleteUser(mockUser("alice"));
1154
+ + fireDatabasePathListener("alice");
1155
+ +
1156
+ + assertNotNull(someoneWhoCanRun(ownerRows(107), ALICE),
1157
+ + "The room is left without an owner that refers to an existing account: " + affiliationRows(107));
1158
+ + }
1159
+ +
1160
+ + @Test
1161
+ + public void group_owned_room_in_memory_keeps_an_owner() throws Exception {
1162
+ + final GroupManager groupManager = GroupManager.getInstance();
1163
+ + final Group group = groupManager.createGroup("roomowners2");
1164
+ + group.getMembers().add(new JID(ALICE));
1165
+ + final String groupJid = new GroupJID("roomowners2").toString();
1166
+ +
1167
+ + createPersistentRoom(207, "groupownedinmemory");
1168
+ + addAffiliation(207, groupJid, Affiliation.owner);
1169
+ + admins.add(new JID(ADMIN));
1170
+ +
1171
+ + final MUCRoom room = loadRoom("groupownedinmemory");
1172
+ + assertEquals(Affiliation.owner, room.getAffiliation(new JID(ALICE)),
1173
+ + "fixture: the account does not own the room through the group to begin with");
1174
+ +
1175
+ + groupManager.deleteUser(mockUser("alice"));
1176
+ + room.userDeleting(mockUser("alice"), Collections.emptyMap());
1177
+ +
1178
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1179
+ + "The room is left without an owner that refers to an existing account: " + asStrings(room.getOwners()));
1180
+ + }
1181
+ +
1182
+ + @Test
1183
+ + public void rooms_that_keep_another_owner_come_out_unchanged() throws Exception {
1184
+ + createPersistentRoom(301, "soleowner");
1185
+ + addAffiliation(301, ALICE, Affiliation.owner);
1186
+ +
1187
+ + createPersistentRoom(302, "onlyamember");
1188
+ + addAffiliation(302, BOB, Affiliation.owner);
1189
+ + addMember(302, ALICE, "ali");
1190
+ + addMember(302, CAROL, "caro");
1191
+ +
1192
+ + createPersistentRoom(303, "twoowners");
1193
+ + addAffiliation(303, ALICE, Affiliation.owner);
1194
+ + addAffiliation(303, BOB, Affiliation.owner);
1195
+ +
1196
+ + createPersistentRoom(304, "soleownerwithmembers");
1197
+ + addAffiliation(304, ALICE, Affiliation.owner);
1198
+ + addMember(304, CAROL, "caro");
1199
+ + addMember(304, DAVE, "dav");
1200
+ +
1201
+ + admins.add(new JID(ADMIN));
1202
+ +
1203
+ + fireDatabasePathListener("alice");
1204
+ +
1205
+ + assertNotNull(someoneWhoCanRun(ownerRows(301), ALICE),
1206
+ + "The room that lost its only owner is left without one: " + affiliationRows(301));
1207
+ + assertEquals(List.of(BOB + ":" + Affiliation.owner.getValue()), affiliationRows(302),
1208
+ + "A room that kept its owner did not come out unchanged.");
1209
+ + assertEquals(List.of(CAROL + ":caro"), memberRows(302),
1210
+ + "A room that kept its owner did not come out unchanged.");
1211
+ + assertEquals(List.of(BOB + ":" + Affiliation.owner.getValue()), affiliationRows(303),
1212
+ + "A room that kept one of its two owners did not come out unchanged.");
1213
+ + assertNotNull(someoneWhoCanRun(ownerRows(304), ALICE),
1214
+ + "The room that lost its only owner is left without one: " + affiliationRows(304));
1215
+ + assertMembershipSurvived(304, List.of(CAROL + ":caro", DAVE + ":dav"), ALICE);
1216
+ + }
1217
+ +
1218
+ + @Test
1219
+ + public void in_memory_room_with_no_admin_accounts_is_taken_over_by_a_member() throws Exception {
1220
+ + createPersistentRoom(103, "onlymembersleft");
1221
+ + addAffiliation(103, ALICE, Affiliation.owner);
1222
+ + addMember(103, CAROL, "caro");
1223
+ + admins.clear();
1224
+ + final MUCRoom room = startedService().getChatRoom("onlymembersleft");
1225
+ + assertNotNull(room, "fixture: the room did not load");
1226
+ +
1227
+ + deleteAccount("alice");
1228
+ +
1229
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1230
+ + "The deleted account still has an affiliation with the room.");
1231
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1232
+ + "The room is left without an owner: " + asStrings(room.getOwners()));
1233
+ + assertNotNull(someoneWhoCanRun(ownerRows(103), ALICE),
1234
+ + "After a restart the room has no owner: " + affiliationRows(103));
1235
+ + }
1236
+ +
1237
+ + @Test
1238
+ + public void db_path_room_is_taken_over_when_the_only_admin_is_the_one_leaving() throws Exception {
1239
+ + createPersistentRoom(113, "onlyadminleaves");
1240
+ + addAffiliation(113, ALICE, Affiliation.owner);
1241
+ + addMember(113, CAROL, "caro");
1242
+ + admins.clear();
1243
+ + admins.add(new JID(ALICE));
1244
+ +
1245
+ + deleteAccount("alice");
1246
+ +
1247
+ + assertNotNull(someoneWhoCanRun(ownerRows(113), ALICE),
1248
+ + "The room is left without an owner: " + affiliationRows(113));
1249
+ + assertFalse(affiliationRows(113).stream().anyMatch(r -> r.startsWith(ALICE + ":")),
1250
+ + "The deleted account is still affiliated with the room: " + affiliationRows(113));
1251
+ + }
1252
+ +
1253
+ + @Test
1254
+ + public void group_emptied_by_a_removal_keeps_its_room_owned_out_of_memory() throws Exception {
1255
+ + startedService();
1256
+ + final GroupManager groupManager = GroupManager.getInstance();
1257
+ + groupManager.createGroup("removedowners").getMembers().add(new JID(ALICE));
1258
+ + createPersistentRoom(108, "groupemptiedoutofmemory");
1259
+ + addAffiliation(108, new GroupJID("removedowners").toString(), Affiliation.owner);
1260
+ + addMember(108, CAROL, "caro");
1261
+ + admins.add(new JID(ADMIN));
1262
+ +
1263
+ + groupManager.getGroup("removedowners").getMembers().remove(new JID(ALICE));
1264
+ +
1265
+ + assertNotNull(someoneWhoCanRun(ownerRows(108), null),
1266
+ + "The room still names only a group that has nobody in it: " + affiliationRows(108));
1267
+ + }
1268
+ +
1269
+ + @Test
1270
+ + public void group_emptied_by_a_removal_keeps_its_room_owned_in_memory() throws Exception {
1271
+ + final MultiUserChatServiceImpl service = startedService();
1272
+ + final GroupManager groupManager = GroupManager.getInstance();
1273
+ + groupManager.createGroup("removedowners2").getMembers().add(new JID(ALICE));
1274
+ + createPersistentRoom(208, "groupemptiedinmemory");
1275
+ + addAffiliation(208, new GroupJID("removedowners2").toString(), Affiliation.owner);
1276
+ + addMember(208, CAROL, "caro");
1277
+ + admins.add(new JID(ADMIN));
1278
+ + final MUCRoom room = service.getChatRoom("groupemptiedinmemory");
1279
+ + assertNotNull(room, "fixture: the room did not load");
1280
+ +
1281
+ + groupManager.getGroup("removedowners2").getMembers().remove(new JID(ALICE));
1282
+ +
1283
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), null),
1284
+ + "The room still names only a group that has nobody in it: " + asStrings(room.getOwners()));
1285
+ + assertNotNull(someoneWhoCanRun(ownerRows(208), null),
1286
+ + "After a restart the room names only a group that has nobody in it: " + affiliationRows(208));
1287
+ + }
1288
+ +
1289
+ + @Test
1290
+ + public void in_memory_promotion_when_the_admin_is_banned_from_the_room() throws Exception {
1291
+ + createPersistentRoom(116, "adminisbanned");
1292
+ + addAffiliation(116, ALICE, Affiliation.owner);
1293
+ + addAffiliation(116, ADMIN, Affiliation.outcast);
1294
+ + admins.add(new JID(ALICE));
1295
+ + admins.add(new JID(ADMIN));
1296
+ + final MUCRoom room = startedService().getChatRoom("adminisbanned");
1297
+ + assertNotNull(room, "fixture: the room did not load");
1298
+ +
1299
+ + deleteAccount("alice");
1300
+ +
1301
+ + assertEquals(Affiliation.none, room.getAffiliation(new JID(ALICE)),
1302
+ + "The deleted account still has an affiliation with the room.");
1303
+ + assertNotNull(someoneWhoCanRun(asStrings(room.getOwners()), ALICE),
1304
+ + "The room is left without an owner: " + asStrings(room.getOwners()));
1305
+ + assertNotNull(someoneWhoCanRun(ownerRows(116), ALICE),
1306
+ + "After a restart the room has no owner: " + affiliationRows(116));
1307
+ + }
1308
+ +}
1309
+
1310
+ REFERENCE_PATCH
harbor/tasks/openfire_userdeleting_last_owner_contract/task.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+ artifacts = ["/workspace/submissions/submitted.patch"]
3
+ [metadata]
4
+ task = "openfire_userdeleting_last_owner_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/openfire_userdeleting_last_owner_contract/tests/Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-openfire:source-v9
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
+ RUN chmod -R a+rX /hud/m2
5
+ ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
6
+ RUN rm -f /hud/gold.diff
7
+ COPY verify.py evidence.py config.json test.sh /tests/
8
+ RUN chmod 755 /tests/test.sh
9
+ WORKDIR /app
10
+ CMD ["sleep", "infinity"]
harbor/tasks/openfire_userdeleting_last_owner_contract/tests/config.json ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "revision": "coding-rubric-v2",
3
+ "task_id": "openfire_userdeleting_last_owner_contract",
4
+ "arguments": {},
5
+ "grader_version": "0.6.15",
6
+ "source_image": "ec-swe-openfire:source-v9",
7
+ "source_image_id": "sha256:ebda27591100cc680c577a73428d3d69f0d2ec0753b0dfaaf40df5573b912beb",
8
+ "provenance": {
9
+ "repository": "igniterealtime/Openfire",
10
+ "environment_id": "832b2185-06cc-43ba-9c75-b0f58b3854ed",
11
+ "build": 9,
12
+ "build_id": "ab430f1d-8559-41f0-bea8-7224a7ce44e3",
13
+ "hosted_task": "openfire_userdeleting_last_owner_contract-0163de9c",
14
+ "task_version": 1,
15
+ "source_archive_sha256": "9c3e03f8f4d3ce0838f65f06a21b5e8e88a2e829c610ddc3192ea917c176bacc",
16
+ "hosted_revision_argument": "not recorded; the scenario does not read it"
17
+ },
18
+ "criteria": [
19
+ [
20
+ "db_path_persistent_room_keeps_an_owner",
21
+ 0.03,
22
+ true,
23
+ "bash",
24
+ 900
25
+ ],
26
+ [
27
+ "db_path_promotion_when_the_admin_already_has_a_row",
28
+ 0.03,
29
+ false,
30
+ "bash",
31
+ 900
32
+ ],
33
+ [
34
+ "in_memory_room_with_no_admin_accounts_is_taken_over_by_a_member",
35
+ 0.09,
36
+ false,
37
+ "bash",
38
+ 900
39
+ ],
40
+ [
41
+ "db_path_room_with_no_admin_accounts_is_taken_over_by_a_member",
42
+ 0.09,
43
+ false,
44
+ "bash",
45
+ 900
46
+ ],
47
+ [
48
+ "db_path_room_is_taken_over_when_the_only_admin_is_the_one_leaving",
49
+ 0.09,
50
+ false,
51
+ "bash",
52
+ 900
53
+ ],
54
+ [
55
+ "in_memory_room_is_taken_over_when_the_only_admin_is_the_one_leaving",
56
+ 0.09,
57
+ false,
58
+ "bash",
59
+ 900
60
+ ],
61
+ [
62
+ "db_path_room_whose_only_admin_is_a_shared_group_is_taken_over",
63
+ 0.03,
64
+ false,
65
+ "bash",
66
+ 900
67
+ ],
68
+ [
69
+ "service_level_lists_release_the_deleted_user",
70
+ 0.06,
71
+ false,
72
+ "bash",
73
+ 900
74
+ ],
75
+ [
76
+ "group_owned_room_out_of_memory_keeps_an_owner",
77
+ 0.03,
78
+ false,
79
+ "bash",
80
+ 900
81
+ ],
82
+ [
83
+ "group_owned_room_in_memory_keeps_an_owner",
84
+ 0.03,
85
+ false,
86
+ "bash",
87
+ 900
88
+ ],
89
+ [
90
+ "group_emptied_by_a_removal_keeps_its_room_owned_out_of_memory",
91
+ 0.09,
92
+ false,
93
+ "bash",
94
+ 900
95
+ ],
96
+ [
97
+ "group_emptied_by_a_removal_keeps_its_room_owned_in_memory",
98
+ 0.085,
99
+ false,
100
+ "bash",
101
+ 900
102
+ ],
103
+ [
104
+ "group_emptied_by_an_admin_removal_keeps_its_room_owned_out_of_memory",
105
+ 0.09,
106
+ false,
107
+ "bash",
108
+ 900
109
+ ],
110
+ [
111
+ "group_emptied_by_an_admin_removal_keeps_its_room_owned_in_memory",
112
+ 0.085,
113
+ false,
114
+ "bash",
115
+ 900
116
+ ],
117
+ [
118
+ "in_memory_promotion_when_the_admin_is_banned_from_the_room",
119
+ 0.03,
120
+ false,
121
+ "bash",
122
+ 900
123
+ ],
124
+ [
125
+ "rooms_that_keep_another_owner_come_out_unchanged",
126
+ 0.03,
127
+ false,
128
+ "bash",
129
+ 900
130
+ ],
131
+ [
132
+ "gate_repo_suite_green_and_tests_untouched",
133
+ 0.02,
134
+ true,
135
+ "bash",
136
+ 1800
137
+ ]
138
+ ],
139
+ "gates": [],
140
+ "reward_rule": "weighted_cap",
141
+ "local_hostname": false,
142
+ "fault_exit": 3,
143
+ "grader_readable": [
144
+ "/hud/m2"
145
+ ],
146
+ "grader_writable": [],
147
+ "blocker_cap": 0.6,
148
+ "empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
149
+ "verifier_files": {
150
+ "/app/env.py": "08a8fea48013da1bfbfdf4791922dd9e8d95dc2a17af0b7d17d7de7adbecc91a",
151
+ "/app/tasks.py": "317473bdc4396fde46516b3d0968ffd404182c167b678c11a7078c35984ae704",
152
+ "/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
153
+ "/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
154
+ "/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
155
+ "/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
156
+ "/app/task/prompt.md": "1220fccfd54e0cd15470a50e30d03e6699921a0ed26ddb248508379ccf44e8c5",
157
+ "/hud/grader/board_smoke.py": "c95453ba720db49ea6856a2f37ce7d25398344ddd7c9d978cb58175c8cef8b65",
158
+ "/hud/grader/run_grading.sh": "4a5b5b5e7fd69eff9ff060d46910830f47d91670af06f9dfe6833fb285ae94e9",
159
+ "/hud/grader/harness/HiddenOwnershipChecks.java": "2929de9902853a63560c940d189a02fe9efdf323957eb23b1aaba277c85ca934"
160
+ },
161
+ "preflight": [
162
+ [
163
+ "/bin/bash",
164
+ "--version"
165
+ ],
166
+ [
167
+ "setpriv",
168
+ "--version"
169
+ ],
170
+ [
171
+ "git",
172
+ "--version"
173
+ ],
174
+ [
175
+ "bash",
176
+ "-c",
177
+ "bash -lc 'java -version' || java -version"
178
+ ]
179
+ ]
180
+ }
harbor/tasks/openfire_userdeleting_last_owner_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/openfire_userdeleting_last_owner_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/openfire_userdeleting_last_owner_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/openfire_userdeleting_last_owner_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()