servicesToptal commited on
Commit
f8cef8d
·
verified ·
1 Parent(s): fe4e0a1

Update dataset (part 4)

Browse files
LICENSE CHANGED
@@ -6,12 +6,9 @@ of its upstream repository, listed per task below as reported by GitHub.
6
  The task text and grader design, where they are not upstream code, are
7
  copyright 2026 Toptal, LLC. Contact Toptal, LLC for licence terms.
8
 
 
9
  - BabylonJS__Babylon.js-babylonjs_scene_remove_owner_refs_contract-382616f8: Apache-2.0 (https://github.com/BabylonJS/Babylon.js)
10
- - MathNya__umya-spreadsheet-umya_structural_edit_reference_owners_contract: MIT (https://github.com/MathNya/umya-spreadsheet)
11
- - SickChill__SickChill-sickchill_episode_metadata_files_contract-2e2a49e4: GPL-3.0 (https://github.com/SickChill/SickChill)
12
  - Zettlr__Zettlr-zettlr_clickable_keywords: GPL-3.0 (https://github.com/Zettlr/Zettlr)
13
- - agronholm__apscheduler-apscheduler-expired-job-lease: MIT (https://github.com/agronholm/apscheduler)
14
- - aio-libs__aioftp-aioftp-stream-abort-desynchronization: Apache-2.0 (https://github.com/aio-libs/aioftp)
15
  - alibaba__druid-druid_lenient_script: Apache-2.0 (https://github.com/alibaba/druid)
16
  - alibaba__hooks-ahooks_request_cache_races: MIT (https://github.com/alibaba/hooks)
17
  - apache__geode-geode_oql_index_null_semantics_contract-1c066303: Apache-2.0 (https://github.com/apache/geode)
@@ -19,14 +16,17 @@ copyright 2026 Toptal, LLC. Contact Toptal, LLC for licence terms.
19
  - buchgr__bazel-remote-bazel_remote_disk_eviction_accounting_contract-afe5ea56: Apache-2.0 (https://github.com/buchgr/bazel-remote)
20
  - celery__celery-celery_retry_expires_countdown_contract: NOASSERTION (https://github.com/celery/celery)
21
  - colinhacks__zod-zod-json-schema-target-legality: MIT (https://github.com/colinhacks/zod)
22
- - coredns__coredns-coredns__4097: Apache-2.0 (https://github.com/coredns/coredns)
23
  - dgraph-io__badger-journal_recovery_after_unclean_stop: Apache-2.0 (https://github.com/dgraph-io/badger)
24
  - dotnet__Open-XML-SDK-open_xml_sdk_deletepart_refs_contract-1c066303: MIT (https://github.com/dotnet/Open-XML-SDK)
 
25
  - igniterealtime__Openfire-openfire_userdeleting_last_owner_contract-0163de9c: Apache-2.0 (https://github.com/igniterealtime/Openfire)
26
- - mikro-orm__mikro-orm-mikro-orm-pessimistic-locking: MIT (https://github.com/mikro-orm/mikro-orm)
 
27
  - ory__kratos-kratos_cleanup_stale_flows_courier_contract: Apache-2.0 (https://github.com/ory/kratos)
28
  - pallets__click-click-help-defaults: BSD-3-Clause (https://github.com/pallets/click)
 
29
  - python-rope__rope-rope_rename_all_reexport_owners_contract-1c066303: LGPL-3.0 (https://github.com/python-rope/rope)
30
  - sequelize__sequelize-sequelize-bulkcreate-ignore-duplicates: MIT (https://github.com/sequelize/sequelize)
 
31
  - terser__terser-retained_top_level_names_keep_their_values: NOASSERTION (https://github.com/terser/terser)
32
  - tsileo__microblog.pub-microblogpub_deleted_object_resurrect_lookup_contract-382616f8: AGPL-3.0 (https://github.com/tsileo/microblog.pub)
 
6
  The task text and grader design, where they are not upstream code, are
7
  copyright 2026 Toptal, LLC. Contact Toptal, LLC for licence terms.
8
 
9
+ - Automattic__mongoose-mongoose_syncindexes_contract-97c2a76f: MIT (https://github.com/Automattic/mongoose)
10
  - BabylonJS__Babylon.js-babylonjs_scene_remove_owner_refs_contract-382616f8: Apache-2.0 (https://github.com/BabylonJS/Babylon.js)
 
 
11
  - Zettlr__Zettlr-zettlr_clickable_keywords: GPL-3.0 (https://github.com/Zettlr/Zettlr)
 
 
12
  - alibaba__druid-druid_lenient_script: Apache-2.0 (https://github.com/alibaba/druid)
13
  - alibaba__hooks-ahooks_request_cache_races: MIT (https://github.com/alibaba/hooks)
14
  - apache__geode-geode_oql_index_null_semantics_contract-1c066303: Apache-2.0 (https://github.com/apache/geode)
 
16
  - buchgr__bazel-remote-bazel_remote_disk_eviction_accounting_contract-afe5ea56: Apache-2.0 (https://github.com/buchgr/bazel-remote)
17
  - celery__celery-celery_retry_expires_countdown_contract: NOASSERTION (https://github.com/celery/celery)
18
  - colinhacks__zod-zod-json-schema-target-legality: MIT (https://github.com/colinhacks/zod)
 
19
  - dgraph-io__badger-journal_recovery_after_unclean_stop: Apache-2.0 (https://github.com/dgraph-io/badger)
20
  - dotnet__Open-XML-SDK-open_xml_sdk_deletepart_refs_contract-1c066303: MIT (https://github.com/dotnet/Open-XML-SDK)
21
+ - go-mysql-org__go-mysql-go_mysql_mariadb_compressed_columns: MIT (https://github.com/go-mysql-org/go-mysql)
22
  - igniterealtime__Openfire-openfire_userdeleting_last_owner_contract-0163de9c: Apache-2.0 (https://github.com/igniterealtime/Openfire)
23
+ - jelmer__xandikos-xandikos_itip_recurrence_id_override_contract-c6aa163a: GPL-3.0 (https://github.com/jelmer/xandikos)
24
+ - oauth2-proxy__oauth2-proxy-proxy_cookie_accounting: MIT (https://github.com/oauth2-proxy/oauth2-proxy)
25
  - ory__kratos-kratos_cleanup_stale_flows_courier_contract: Apache-2.0 (https://github.com/ory/kratos)
26
  - pallets__click-click-help-defaults: BSD-3-Clause (https://github.com/pallets/click)
27
+ - pomerium__pomerium-pomerium_route_order_contract: Apache-2.0 (https://github.com/pomerium/pomerium)
28
  - python-rope__rope-rope_rename_all_reexport_owners_contract-1c066303: LGPL-3.0 (https://github.com/python-rope/rope)
29
  - sequelize__sequelize-sequelize-bulkcreate-ignore-duplicates: MIT (https://github.com/sequelize/sequelize)
30
+ - sfackler__rust-postgres-shared_handle_abandoned_operations: Apache-2.0 (https://github.com/sfackler/rust-postgres)
31
  - terser__terser-retained_top_level_names_keep_their_values: NOASSERTION (https://github.com/terser/terser)
32
  - tsileo__microblog.pub-microblogpub_deleted_object_resurrect_lookup_contract-382616f8: AGPL-3.0 (https://github.com/tsileo/microblog.pub)
README.md CHANGED
@@ -101,10 +101,10 @@ dataset_info:
101
  dtype: float64
102
  splits:
103
  - name: test
104
- num_bytes: 16944456
105
  num_examples: 24
106
- download_size: 7713543
107
- dataset_size: 16944456
108
  ---
109
 
110
  # Dataset Card for ExpertCrowd SWE (EC-SWE)
@@ -114,8 +114,8 @@ agents. Each one is a bug or missing behaviour in a real open-source repository,
114
  commit, with a written problem statement, a reference fix, and a weighted
115
  grader backed by hidden tests. The tasks were chosen to sit at the typical
116
  difficulty of the pool of reviewed tasks they were drawn from, measured by how
117
- well current frontier agents scored on them: no outliers at either end. Mean
118
- agent reward runs from 0.34 to 0.43, and 1.6% of agent runs scored a full 1.0.
119
 
120
  ## Dataset Details
121
 
@@ -180,15 +180,15 @@ hard = ds.filter(lambda r: r["difficulty"] in ("very hard", "hard"))
180
  ### At a glance
181
 
182
  - **Tasks:** one per repository
183
- - **Models those runs used:** claude-fable-5, claude-fable-5-1, claude-opus-5, gemini-3.8-flash, gpt-6-astra
184
 
185
  | Language | Tasks |
186
  | --- | --- |
187
- | Python | 8 |
188
- | TypeScript | 6 |
189
- | Go | 4 |
190
  | Java | 3 |
191
- | JavaScript | 1 |
192
  | Rust | 1 |
193
  | C# | 1 |
194
 
@@ -196,32 +196,29 @@ hard = ds.filter(lambda r: r["difficulty"] in ("very hard", "hard"))
196
 
197
  Difficulty is the mean reward of graded agent runs on current frontier models.
198
  The tasks sit around the middle of the distribution of every verified task with
199
- 5 or more graded agent runs, so the mean and median stay close to the pool's
200
- while the very hard and easy tails are left out:
201
 
202
  | Mean agent reward | Difficulty | All verified with agent scores | This dataset |
203
  | --- | --- | --- | --- |
204
- | 0.0 to 0.2 | very hard | (4%) | 0% |
205
- | 0.2 to 0.4 | hard | (49%) | 62% |
206
- | 0.4 to 0.6 | medium | (44%) | 38% |
207
  | 0.6 to 0.8 | easy | (2%) | 0% |
208
  | 0.8 to 1.0 | very easy | 0 (0%) | 0% |
209
- | **mean** | | **0.377** | **0.380** |
210
- | **median** | | **0.379** | **0.373** |
211
 
212
  ### Tasks
213
 
214
  | Instance | Repository | Language | Difficulty | Mean reward |
215
  | --- | --- | --- | --- | --- |
 
216
  | `bashrc2__epicyon-epicyon_deleted_post_announce_cache_contract-1c066303` | bashrc2/epicyon | Python | hard | 0.34 |
217
  | `apache__geode-geode_oql_index_null_semantics_contract-1c066303` | apache/geode | Java | hard | 0.34 |
218
- | `coredns__coredns-coredns__4097` | coredns/coredns | Go | hard | 0.34 |
219
  | `sequelize__sequelize-sequelize-bulkcreate-ignore-duplicates` | sequelize/sequelize | TypeScript | hard | 0.34 |
220
- | `MathNya__umya-spreadsheet-umya_structural_edit_reference_owners_contract` | MathNya/umya-spreadsheet | Rust | hard | 0.35 |
221
  | `alibaba__druid-druid_lenient_script` | alibaba/druid | Java | hard | 0.35 |
222
- | `aio-libs__aioftp-aioftp-stream-abort-desynchronization` | aio-libs/aioftp | Python | hard | 0.35 |
223
  | `python-rope__rope-rope_rename_all_reexport_owners_contract-1c066303` | python-rope/rope | Python | hard | 0.35 |
224
- | `SickChill__SickChill-sickchill_episode_metadata_files_contract-2e2a49e4` | SickChill/SickChill | Python | hard | 0.35 |
225
  | `igniterealtime__Openfire-openfire_userdeleting_last_owner_contract-0163de9c` | igniterealtime/Openfire | Java | hard | 0.36 |
226
  | `Zettlr__Zettlr-zettlr_clickable_keywords` | Zettlr/Zettlr | TypeScript | hard | 0.36 |
227
  | `buchgr__bazel-remote-bazel_remote_disk_eviction_accounting_contract-afe5ea56` | buchgr/bazel-remote | Go | hard | 0.37 |
@@ -229,14 +226,17 @@ while the very hard and easy tails are left out:
229
  | `ory__kratos-kratos_cleanup_stale_flows_courier_contract` | ory/kratos | Go | hard | 0.38 |
230
  | `dotnet__Open-XML-SDK-open_xml_sdk_deletepart_refs_contract-1c066303` | dotnet/Open-XML-SDK | C# | hard | 0.39 |
231
  | `dgraph-io__badger-journal_recovery_after_unclean_stop` | dgraph-io/badger | Go | medium | 0.40 |
 
232
  | `BabylonJS__Babylon.js-babylonjs_scene_remove_owner_refs_contract-382616f8` | BabylonJS/Babylon.js | TypeScript | medium | 0.40 |
233
  | `alibaba__hooks-ahooks_request_cache_races` | alibaba/hooks | TypeScript | medium | 0.41 |
 
 
234
  | `celery__celery-celery_retry_expires_countdown_contract` | celery/celery | Python | medium | 0.43 |
235
  | `colinhacks__zod-zod-json-schema-target-legality` | colinhacks/zod | TypeScript | medium | 0.43 |
236
  | `pallets__click-click-help-defaults` | pallets/click | Python | medium | 0.43 |
237
  | `tsileo__microblog.pub-microblogpub_deleted_object_resurrect_lookup_contract-382616f8` | tsileo/microblog.pub | Python | medium | 0.43 |
238
- | `mikro-orm__mikro-orm-mikro-orm-pessimistic-locking` | mikro-orm/mikro-orm | TypeScript | medium | 0.43 |
239
- | `agronholm__apscheduler-apscheduler-expired-job-lease` | agronholm/apscheduler | Python | medium | 0.43 |
240
 
241
  ## Running the tasks
242
 
@@ -245,7 +245,7 @@ Harbor on your own machine.
245
 
246
  ### On HUD
247
 
248
- Every task runs on HUD, including the nine that have no Harbor package. The tasks are
249
  published there as the taskset [`ec-swe`](https://www.hud.ai/shared/tasksets/979e6e02-d726-46f6-a066-914afc5c9f44),
250
  which anyone can view; it holds all 24.
251
 
@@ -265,7 +265,7 @@ hud eval my-ec-swe claude --full # runs it on the platform with an agent
265
  Results appear as jobs and traces on hud.ai (`hud jobs`). On HUD the agent and the grader
266
  share one container, kept apart by file permissions, and the four tasks with a criterion
267
  judged by a model get that judge from HUD's gateway. The commands follow HUD's
268
- documentation. We deployed eighteen of the folders this way ourselves and synced the task of
269
  every folder into the taskset above; we have not run an agent with `hud eval` from this
270
  folder.
271
 
@@ -297,13 +297,12 @@ 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
- 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
304
- is judged by a model), SickChill, Babylon.js, mikro-orm, aioftp and apscheduler. The folder
305
- holds the complete build context of each, and `harbor/README.md` says for each how it is
306
- built and graded and what it needs.
307
 
308
  ## Dataset Creation
309
 
@@ -334,6 +333,11 @@ models.
334
  reward was closest to the sample mean (0.374) were kept: every task within
335
  0.059 of it. The nearest task left out was 0.064 away, so the cut does not
336
  split a tie.
 
 
 
 
 
337
 
338
  ### Source Data
339
 
 
101
  dtype: float64
102
  splits:
103
  - name: test
104
+ num_bytes: 16940905
105
  num_examples: 24
106
+ download_size: 7702204
107
+ dataset_size: 16940905
108
  ---
109
 
110
  # Dataset Card for ExpertCrowd SWE (EC-SWE)
 
114
  commit, with a written problem statement, a reference fix, and a weighted
115
  grader backed by hidden tests. The tasks were chosen to sit at the typical
116
  difficulty of the pool of reviewed tasks they were drawn from, measured by how
117
+ well current frontier agents scored on them. Mean agent reward runs from
118
+ 0.17 to 0.47, and 3.1% of agent runs scored a full 1.0.
119
 
120
  ## Dataset Details
121
 
 
180
  ### At a glance
181
 
182
  - **Tasks:** one per repository
183
+ - **Models those runs used:** claude-fable-5, claude-fable-5-1, claude-opus-5, gpt-6-astra
184
 
185
  | Language | Tasks |
186
  | --- | --- |
187
+ | Python | 6 |
188
+ | Go | 6 |
189
+ | TypeScript | 5 |
190
  | Java | 3 |
191
+ | JavaScript | 2 |
192
  | Rust | 1 |
193
  | C# | 1 |
194
 
 
196
 
197
  Difficulty is the mean reward of graded agent runs on current frontier models.
198
  The tasks sit around the middle of the distribution of every verified task with
199
+ 5 or more graded agent runs, so the mean and median stay close to the pool's.
200
+ The easy tail is left out, and one task comes from the very hard end:
201
 
202
  | Mean agent reward | Difficulty | All verified with agent scores | This dataset |
203
  | --- | --- | --- | --- |
204
+ | 0.0 to 0.2 | very hard | (4%) | 4% |
205
+ | 0.2 to 0.4 | hard | (49%) | 46% |
206
+ | 0.4 to 0.6 | medium | (44%) | 50% |
207
  | 0.6 to 0.8 | easy | (2%) | 0% |
208
  | 0.8 to 1.0 | very easy | 0 (0%) | 0% |
209
+ | **mean** | | **0.377** | **0.383** |
210
+ | **median** | | **0.379** | **0.395** |
211
 
212
  ### Tasks
213
 
214
  | Instance | Repository | Language | Difficulty | Mean reward |
215
  | --- | --- | --- | --- | --- |
216
+ | `oauth2-proxy__oauth2-proxy-proxy_cookie_accounting` | oauth2-proxy/oauth2-proxy | Go | very hard | 0.17 |
217
  | `bashrc2__epicyon-epicyon_deleted_post_announce_cache_contract-1c066303` | bashrc2/epicyon | Python | hard | 0.34 |
218
  | `apache__geode-geode_oql_index_null_semantics_contract-1c066303` | apache/geode | Java | hard | 0.34 |
 
219
  | `sequelize__sequelize-sequelize-bulkcreate-ignore-duplicates` | sequelize/sequelize | TypeScript | hard | 0.34 |
 
220
  | `alibaba__druid-druid_lenient_script` | alibaba/druid | Java | hard | 0.35 |
 
221
  | `python-rope__rope-rope_rename_all_reexport_owners_contract-1c066303` | python-rope/rope | Python | hard | 0.35 |
 
222
  | `igniterealtime__Openfire-openfire_userdeleting_last_owner_contract-0163de9c` | igniterealtime/Openfire | Java | hard | 0.36 |
223
  | `Zettlr__Zettlr-zettlr_clickable_keywords` | Zettlr/Zettlr | TypeScript | hard | 0.36 |
224
  | `buchgr__bazel-remote-bazel_remote_disk_eviction_accounting_contract-afe5ea56` | buchgr/bazel-remote | Go | hard | 0.37 |
 
226
  | `ory__kratos-kratos_cleanup_stale_flows_courier_contract` | ory/kratos | Go | hard | 0.38 |
227
  | `dotnet__Open-XML-SDK-open_xml_sdk_deletepart_refs_contract-1c066303` | dotnet/Open-XML-SDK | C# | hard | 0.39 |
228
  | `dgraph-io__badger-journal_recovery_after_unclean_stop` | dgraph-io/badger | Go | medium | 0.40 |
229
+ | `pomerium__pomerium-pomerium_route_order_contract` | pomerium/pomerium | Go | medium | 0.40 |
230
  | `BabylonJS__Babylon.js-babylonjs_scene_remove_owner_refs_contract-382616f8` | BabylonJS/Babylon.js | TypeScript | medium | 0.40 |
231
  | `alibaba__hooks-ahooks_request_cache_races` | alibaba/hooks | TypeScript | medium | 0.41 |
232
+ | `go-mysql-org__go-mysql-go_mysql_mariadb_compressed_columns` | go-mysql-org/go-mysql | Go | medium | 0.41 |
233
+ | `sfackler__rust-postgres-shared_handle_abandoned_operations` | sfackler/rust-postgres | Rust | medium | 0.42 |
234
  | `celery__celery-celery_retry_expires_countdown_contract` | celery/celery | Python | medium | 0.43 |
235
  | `colinhacks__zod-zod-json-schema-target-legality` | colinhacks/zod | TypeScript | medium | 0.43 |
236
  | `pallets__click-click-help-defaults` | pallets/click | Python | medium | 0.43 |
237
  | `tsileo__microblog.pub-microblogpub_deleted_object_resurrect_lookup_contract-382616f8` | tsileo/microblog.pub | Python | medium | 0.43 |
238
+ | `jelmer__xandikos-xandikos_itip_recurrence_id_override_contract-c6aa163a` | jelmer/xandikos | Python | medium | 0.46 |
239
+ | `Automattic__mongoose-mongoose_syncindexes_contract-97c2a76f` | Automattic/mongoose | JavaScript | medium | 0.47 |
240
 
241
  ## Running the tasks
242
 
 
245
 
246
  ### On HUD
247
 
248
+ Every task runs on HUD, including the ones that have no Harbor package. The tasks are
249
  published there as the taskset [`ec-swe`](https://www.hud.ai/shared/tasksets/979e6e02-d726-46f6-a066-914afc5c9f44),
250
  which anyone can view; it holds all 24.
251
 
 
265
  Results appear as jobs and traces on hud.ai (`hud jobs`). On HUD the agent and the grader
266
  share one container, kept apart by file permissions, and the four tasks with a criterion
267
  judged by a model get that judge from HUD's gateway. The commands follow HUD's
268
+ documentation. We deployed twenty-two of the folders this way ourselves and synced the task of
269
  every folder into the taskset above; we have not run an agent with `hud eval` from this
270
  folder.
271
 
 
297
  equal to the task's original grading. The folder contains the reference fixes
298
  and the hidden graders, as the rows of this dataset do.
299
 
300
+ 9 more (geode, go-mysql, kratos, mongoose, oauth2-proxy, open-xml-sdk, pomerium, rust-postgres, zettlr) are being packaged or re-checked; they are added
301
  as each one passes.
302
 
303
+ Five tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
304
+ is judged by a model) and Babylon.js. The folder holds the complete build context of each,
305
+ and `harbor/README.md` says for each how it is built and graded and what it needs.
 
306
 
307
  ## Dataset Creation
308
 
 
333
  reward was closest to the sample mean (0.374) were kept: every task within
334
  0.059 of it. The nearest task left out was 0.064 away, so the cut does not
335
  split a tie.
336
+ 5. **Replacement.** Six tasks of that selection were later replaced by six
337
+ other verified tasks from the same pool. The replacements were picked by
338
+ their average score across six current models, not by the rule in step 4,
339
+ so three of them lie outside its band (mean agent reward 0.17, 0.46
340
+ and 0.47).
341
 
342
  ### Source Data
343
 
harbor/tasks/manifest.json CHANGED
@@ -4,13 +4,12 @@
4
  "journal_recovery_after_unclean_stop",
5
  "bazel_remote_disk_eviction_accounting_contract",
6
  "celery_retry_expires_countdown_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",
14
  "zod_json_schema_target_legality"
15
  ]
16
  }
 
4
  "journal_recovery_after_unclean_stop",
5
  "bazel_remote_disk_eviction_accounting_contract",
6
  "celery_retry_expires_countdown_contract",
 
7
  "epicyon_deleted_post_announce_cache_contract",
8
  "microblogpub_deleted_object_resurrect_lookup_contract",
9
  "openfire_userdeleting_last_owner_contract",
10
  "rope_rename_all_reexport_owners_contract",
11
  "retained_top_level_names_keep_their_values",
12
+ "xandikos_itip_recurrence_id_override_contract",
13
  "zod_json_schema_target_legality"
14
  ]
15
  }
harbor/tasks/xandikos_itip_recurrence_id_override_contract/environment/Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-xandikos:source-v7 AS sanitized
2
+ USER root
3
+ COPY sanitize.py capture.py capture_submission.py /opt/task-tools/
4
+ RUN HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 /opt/hudvenv/bin/python /opt/task-tools/sanitize.py
5
+ FROM scratch
6
+ COPY --from=sanitized / /
7
+ ENV PATH="/opt/agentvenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
8
+ ENV LANG="C.UTF-8"
9
+ ENV PYTHONUNBUFFERED="1"
10
+ ENV PYTHONNOUSERSITE="1"
11
+ ENV JAVA_HOME="/opt/java/openjdk"
12
+ ENV GRADLE_USER_HOME="/tmp/agent-home/.gradle"
13
+ ENV PYTHONPATH="/workspace/repo"
14
+ ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=40"
15
+ ENV PYTHONDONTWRITEBYTECODE="1"
16
+ ENV GRADLE_OPTS="-Xmx768m -Dorg.gradle.daemon=false"
17
+ ENV HOME="/tmp/agent-home"
18
+ ENV GOCACHE="/tmp/agent-home/.cache/go-build"
19
+ ENV HUD_TELEMETRY_ENABLED="false"
20
+ ENV HUD_CLI_ANALYTICS_ENABLED="0"
21
+ WORKDIR /workspace/repo
22
+ USER 1000:1000
23
+ CMD ["sleep", "infinity"]
harbor/tasks/xandikos_itip_recurrence_id_override_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/xandikos_itip_recurrence_id_override_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/xandikos_itip_recurrence_id_override_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/xandikos_itip_recurrence_id_override_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/xandikos_itip_recurrence_id_override_contract/instruction.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Please make your changes directly in /workspace/repo.
2
+
3
+ Our scheduling code treats a recurring event as one thing. Clients do not, and
4
+ it shows.
5
+
6
+ Bob cancelled next Tuesday's standup — `RECURRENCE-ID:20260602T100000Z` — and
7
+ we cancelled the whole series, the Monday before and the Wednesday after with
8
+ it. Carol's client names the same Tuesday in Berlin time; same result. An
9
+ organiser's revised copy of one occurrence leaves us holding that occurrence
10
+ and nothing else, and an attendee declining one occurrence is recorded as
11
+ declining all of them. A message that names no occurrence has always meant the
12
+ series. One about a Saturday the series never had is a different matter;
13
+ nobody expects us to invent one.
14
+
15
+ Messages marked `RANGE=THISANDFUTURE` fare no better. A cancellation from that
16
+ Tuesday on took Monday too. Alice moved the standup to Room 4, an hour later,
17
+ from that Tuesday on, and all we kept of the series was Tuesday. Bob declined
18
+ from that Tuesday on, the Wednesday Alice had already moved by itself
19
+ included, and his answer landed on Monday as well.
20
+
21
+ What we send out has the same hole. Somebody invited to one occurrence is sent
22
+ all of them; somebody taken off one hears nothing. Bob handed a single Tuesday
23
+ to Dave, and Dave was sent the entire series. That same save also put Dave onto
24
+ the rest of the series, and we took it — on a one-off meeting that edit has
25
+ never got past us.
26
+
27
+ The repository's own tests stay as they are, and stay green.
28
+
29
+ Finish with a final response when your changes are ready.
harbor/tasks/xandikos_itip_recurrence_id_override_contract/solution/reference.patch ADDED
@@ -0,0 +1,1862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/tests/test_itip_per_instance.py b/tests/test_itip_per_instance.py
2
+ new file mode 100644
3
+ index 0000000..f562977
4
+ --- /dev/null
5
+ +++ b/tests/test_itip_per_instance.py
6
+ @@ -0,0 +1,769 @@
7
+ +# Xandikos
8
+ +# Copyright (C) 2016-2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al.
9
+ +#
10
+ +# This program is free software; you can redistribute it and/or
11
+ +# modify it under the terms of the GNU General Public License
12
+ +# as published by the Free Software Foundation; version 3
13
+ +# of the License or (at your option) any later version of
14
+ +# the License.
15
+ +#
16
+ +# This program is distributed in the hope that it will be useful,
17
+ +# but WITHOUT ANY WARRANTY; without even the implied warranty of
18
+ +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
+ +# GNU General Public License for more details.
20
+ +#
21
+ +# You should have received a copy of the GNU General Public License
22
+ +# along with this program; if not, write to the Free Software
23
+ +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
24
+ +# MA 02110-1301, USA.
25
+ +
26
+ +"""Scheduling messages that speak about single occurrences of a series.
27
+ +
28
+ +RFC 5546 lets a CANCEL, a REQUEST or a REPLY name one occurrence of a
29
+ +recurring event with RECURRENCE-ID, whether or not the recipient happens
30
+ +to keep a separate component for it, and RFC 5545 §3.2.13 lets it name an
31
+ +occurrence and every later one at once. RFC 6638 §3.2.6 lets an attendee
32
+ +hand one occurrence to a delegate. These exercise the whole round: what
33
+ +the inbox does with such a message, what goes out when a user makes such
34
+ +a change, and what the server records about it.
35
+ +"""
36
+ +
37
+ +import asyncio
38
+ +import datetime
39
+ +import shutil
40
+ +import tempfile
41
+ +import unittest
42
+ +from io import BytesIO
43
+ +from wsgiref.util import setup_testing_defaults
44
+ +
45
+ +from icalendar.cal import Calendar
46
+ +
47
+ +from xandikos import scheduling
48
+ +from xandikos.icalendar import expand_calendar_rrule
49
+ +from xandikos.web import (
50
+ + SingleUserFilesystemBackend,
51
+ + StoreBasedCollection,
52
+ + XandikosApp,
53
+ +)
54
+ +
55
+ +ALICE = "mailto:alice@example.com"
56
+ +BOB = "mailto:bob@example.com"
57
+ +CAROL = "mailto:carol@example.com"
58
+ +DAVE = "mailto:dave@example.com"
59
+ +
60
+ +FIRST = "20260601T100000Z"
61
+ +SECOND = "20260602T100000Z"
62
+ +THIRD = "20260603T100000Z"
63
+ +
64
+ +# The same instant as SECOND, written the way a client in Berlin writes it.
65
+ +SECOND_LOCAL = "TZID=Europe/Berlin:20260602T120000"
66
+ +
67
+ +
68
+ +def recurrence_key(comp) -> str:
69
+ + """The occurrence *comp* is about, named by its instant ("" for the series)."""
70
+ + rid = comp.get("RECURRENCE-ID")
71
+ + if rid is None:
72
+ + return ""
73
+ + value = rid.dt
74
+ + if isinstance(value, datetime.datetime):
75
+ + if value.tzinfo is not None:
76
+ + value = value.astimezone(datetime.timezone.utc)
77
+ + return value.strftime("%Y%m%dT%H%M%SZ")
78
+ + return value.strftime("%Y%m%d")
79
+ +
80
+ +
81
+ +WINDOW = (
82
+ + datetime.datetime(2026, 5, 1, tzinfo=datetime.timezone.utc),
83
+ + datetime.datetime(2026, 7, 1, tzinfo=datetime.timezone.utc),
84
+ +)
85
+ +
86
+ +
87
+ +def series(*, override: bool, attendees=(BOB,)) -> bytes:
88
+ + """A daily series of three, optionally with the second one broken out."""
89
+ + lines = [
90
+ + "BEGIN:VCALENDAR",
91
+ + "VERSION:2.0",
92
+ + "PRODID:-//Xandikos test//EN",
93
+ + "BEGIN:VEVENT",
94
+ + "UID:rec@example.com",
95
+ + "DTSTAMP:20260101T120000Z",
96
+ + "SEQUENCE:1",
97
+ + f"DTSTART:{FIRST}",
98
+ + "DTEND:20260601T110000Z",
99
+ + "RRULE:FREQ=DAILY;COUNT=3",
100
+ + "SUMMARY:Standup",
101
+ + f"ORGANIZER:{ALICE}",
102
+ + ]
103
+ + lines += [f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{a}" for a in attendees]
104
+ + lines.append("END:VEVENT")
105
+ + if override:
106
+ + lines += [
107
+ + "BEGIN:VEVENT",
108
+ + "UID:rec@example.com",
109
+ + "DTSTAMP:20260101T120000Z",
110
+ + "SEQUENCE:1",
111
+ + f"RECURRENCE-ID:{SECOND}",
112
+ + f"DTSTART:{SECOND}",
113
+ + "DTEND:20260602T110000Z",
114
+ + "SUMMARY:Standup (moved)",
115
+ + f"ORGANIZER:{ALICE}",
116
+ + ]
117
+ + lines += [f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{a}" for a in attendees]
118
+ + lines.append("END:VEVENT")
119
+ + lines.append("END:VCALENDAR")
120
+ + return ("\r\n".join(lines) + "\r\n").encode("utf-8")
121
+ +
122
+ +
123
+ +def itip_message(method: str, rid: str | None, *body: str) -> bytes:
124
+ + lines = [
125
+ + "BEGIN:VCALENDAR",
126
+ + "VERSION:2.0",
127
+ + "PRODID:-//Xandikos test//EN",
128
+ + f"METHOD:{method}",
129
+ + "BEGIN:VEVENT",
130
+ + "UID:rec@example.com",
131
+ + "DTSTAMP:20260102T120000Z",
132
+ + f"ORGANIZER:{ALICE}",
133
+ + ]
134
+ + if rid is not None:
135
+ + lines.append(f"RECURRENCE-ID;{rid}" if "=" in rid else f"RECURRENCE-ID:{rid}")
136
+ + lines += list(body)
137
+ + lines += ["END:VEVENT", "END:VCALENDAR"]
138
+ + return ("\r\n".join(lines) + "\r\n").encode("utf-8")
139
+ +
140
+ +
141
+ +def series_in_a_time_zone() -> bytes:
142
+ + """The same three-a-day series, kept in Berlin local time with its VTIMEZONE.
143
+ +
144
+ + Its occurrences are the same instants as :func:`series` produces: noon in
145
+ + Berlin on those days is 10:00 UTC.
146
+ + """
147
+ + lines = [
148
+ + "BEGIN:VCALENDAR",
149
+ + "VERSION:2.0",
150
+ + "PRODID:-//Xandikos test//EN",
151
+ + "BEGIN:VTIMEZONE",
152
+ + "TZID:Europe/Berlin",
153
+ + "BEGIN:DAYLIGHT",
154
+ + "TZOFFSETFROM:+0100",
155
+ + "TZOFFSETTO:+0200",
156
+ + "TZNAME:CEST",
157
+ + "DTSTART:19700329T020000",
158
+ + "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU",
159
+ + "END:DAYLIGHT",
160
+ + "BEGIN:STANDARD",
161
+ + "TZOFFSETFROM:+0200",
162
+ + "TZOFFSETTO:+0100",
163
+ + "TZNAME:CET",
164
+ + "DTSTART:19701025T030000",
165
+ + "RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU",
166
+ + "END:STANDARD",
167
+ + "END:VTIMEZONE",
168
+ + "BEGIN:VEVENT",
169
+ + "UID:rec@example.com",
170
+ + "DTSTAMP:20260101T120000Z",
171
+ + "SEQUENCE:1",
172
+ + "DTSTART;TZID=Europe/Berlin:20260601T120000",
173
+ + "DTEND;TZID=Europe/Berlin:20260601T130000",
174
+ + "RRULE:FREQ=DAILY;COUNT=3",
175
+ + "SUMMARY:Standup",
176
+ + f"ORGANIZER:{ALICE}",
177
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
178
+ + "END:VEVENT",
179
+ + "END:VCALENDAR",
180
+ + ]
181
+ + return ("\r\n".join(lines) + "\r\n").encode("utf-8")
182
+ +
183
+ +
184
+ +def delegate_second_occurrence(body: bytes) -> bytes:
185
+ + """Bob hands his seat at the second occurrence to Dave."""
186
+ + head, marker, tail = body.decode("utf-8").partition(f"RECURRENCE-ID:{SECOND}")
187
+ + assert marker, "the fixture has no second occurrence to delegate"
188
+ + tail = tail.replace(
189
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\n",
190
+ + f'ATTENDEE;PARTSTAT=DELEGATED;DELEGATED-TO="{DAVE}":{BOB}\r\n'
191
+ + f'ATTENDEE;PARTSTAT=NEEDS-ACTION;DELEGATED-FROM="{BOB}":{DAVE}\r\n',
192
+ + 1,
193
+ + )
194
+ + return (head + marker + tail).encode("utf-8")
195
+ +
196
+ +
197
+ +class PerInstanceSchedulingTests(unittest.TestCase):
198
+ + def setUp(self):
199
+ + super().setUp()
200
+ + self.tempdir = tempfile.mkdtemp()
201
+ + self.addCleanup(shutil.rmtree, self.tempdir)
202
+ + self.backend = SingleUserFilesystemBackend(self.tempdir)
203
+ + for name in ("alice", "bob", "carol", "dave"):
204
+ + self.backend.create_principal("/" + name, create_defaults=True)
205
+ + self.backend.get_resource("/" + name).set_calendar_user_address_set(
206
+ + [f"mailto:{name}@example.com"]
207
+ + )
208
+ +
209
+ + # -- driving the server the way a client does -------------------------
210
+ + def put(self, path: str, body: bytes) -> str:
211
+ + app = XandikosApp(self.backend, "user")
212
+ + environ = {
213
+ + "PATH_INFO": path,
214
+ + "REQUEST_METHOD": "PUT",
215
+ + "QUERY_STRING": "",
216
+ + "CONTENT_TYPE": "text/calendar",
217
+ + "CONTENT_LENGTH": str(len(body)),
218
+ + }
219
+ + setup_testing_defaults(environ)
220
+ + environ["wsgi.input"] = BytesIO(body)
221
+ + codes: list[str] = []
222
+ + b"".join(app(environ, lambda code, headers: codes.append(code)))
223
+ + return codes[0]
224
+ +
225
+ + def put_ok(self, principal: str, body: bytes) -> None:
226
+ + code = self.put(f"/{principal}/calendars/calendar/event.ics", body)
227
+ + self.assertIn(code.split()[0], ("200", "201", "204"), code)
228
+ +
229
+ + def deliver(self, address: str, message: bytes) -> None:
230
+ + self.assertTrue(
231
+ + asyncio.run(
232
+ + scheduling.deliver_to_inbox(
233
+ + self.backend, address, Calendar.from_ical(message.decode("utf-8"))
234
+ + )
235
+ + )
236
+ + )
237
+ +
238
+ + # -- reading what the stores hold -------------------------------------
239
+ + def stored(self, principal: str) -> Calendar:
240
+ + col = self.backend.get_resource(f"/{principal}/calendars/calendar")
241
+ + assert isinstance(col, StoreBasedCollection)
242
+ + raw = [
243
+ + b"".join(col.store._get_raw(name, etag))
244
+ + for name, _ct, etag in col.store.iter_with_etag()
245
+ + ]
246
+ + self.assertEqual(1, len(raw))
247
+ + return Calendar.from_ical(raw[0].decode("utf-8"))
248
+ +
249
+ + def inbox(self, principal: str, method: str) -> list[Calendar]:
250
+ + col = self.backend.get_resource(f"/{principal}/inbox")
251
+ + assert isinstance(col, StoreBasedCollection)
252
+ + out = []
253
+ + for name, _ct, etag in col.store.iter_with_etag():
254
+ + parsed = Calendar.from_ical(
255
+ + b"".join(col.store._get_raw(name, etag)).decode("utf-8")
256
+ + )
257
+ + if str(parsed.get("METHOD", "")).upper() == method:
258
+ + out.append(parsed)
259
+ + return out
260
+ +
261
+ + def occurrences(self, principal: str) -> dict:
262
+ + """The series as a client sees it after expansion."""
263
+ + expanded = expand_calendar_rrule(self.stored(principal), *WINDOW)
264
+ + out = {}
265
+ + for comp in expanded.subcomponents:
266
+ + if comp.name != "VEVENT":
267
+ + continue
268
+ + attendees = comp.get("ATTENDEE", [])
269
+ + if not isinstance(attendees, list):
270
+ + attendees = [attendees]
271
+ + out[recurrence_key(comp)] = {
272
+ + "status": str(comp.get("STATUS", "")),
273
+ + "summary": str(comp.get("SUMMARY", "")),
274
+ + "partstat": {
275
+ + str(a): str(a.params.get("PARTSTAT", "")) for a in attendees
276
+ + },
277
+ + }
278
+ + return out
279
+ +
280
+ + def assertLive(self, occurrences, key):
281
+ + self.assertIn(key, occurrences)
282
+ + self.assertNotEqual("CANCELLED", occurrences[key]["status"].upper())
283
+ +
284
+ + def assertNotLive(self, occurrences, key):
285
+ + row = occurrences.get(key)
286
+ + if row is not None:
287
+ + self.assertEqual("CANCELLED", row["status"].upper())
288
+ +
289
+ + # -- the inbox --------------------------------------------------------
290
+ + def test_cancel_of_an_occurrence_without_its_own_component(self):
291
+ + self.put_ok("bob", series(override=False))
292
+ + self.deliver(
293
+ + BOB,
294
+ + itip_message(
295
+ + "CANCEL",
296
+ + SECOND,
297
+ + "SEQUENCE:2",
298
+ + f"DTSTART:{SECOND}",
299
+ + "STATUS:CANCELLED",
300
+ + f"ATTENDEE:{BOB}",
301
+ + ),
302
+ + )
303
+ + occurrences = self.occurrences("bob")
304
+ + self.assertLive(occurrences, FIRST)
305
+ + self.assertLive(occurrences, THIRD)
306
+ + self.assertNotLive(occurrences, SECOND)
307
+ +
308
+ + def test_cancel_without_a_recurrence_id_still_ends_the_series(self):
309
+ + self.put_ok("bob", series(override=True))
310
+ + self.deliver(
311
+ + BOB,
312
+ + itip_message(
313
+ + "CANCEL",
314
+ + None,
315
+ + "SEQUENCE:2",
316
+ + f"DTSTART:{FIRST}",
317
+ + "RRULE:FREQ=DAILY;COUNT=3",
318
+ + "STATUS:CANCELLED",
319
+ + f"ATTENDEE:{BOB}",
320
+ + ),
321
+ + )
322
+ + for key in (FIRST, SECOND, THIRD):
323
+ + self.assertNotLive(self.occurrences("bob"), key)
324
+ +
325
+ + def test_cancel_this_and_future_ends_the_series_at_that_occurrence(self):
326
+ + self.put_ok("bob", series(override=False))
327
+ + self.deliver(
328
+ + BOB,
329
+ + itip_message(
330
+ + "CANCEL",
331
+ + f"RANGE=THISANDFUTURE:{SECOND}",
332
+ + "SEQUENCE:2",
333
+ + f"DTSTART:{SECOND}",
334
+ + "STATUS:CANCELLED",
335
+ + f"ATTENDEE:{BOB}",
336
+ + ),
337
+ + )
338
+ + occurrences = self.occurrences("bob")
339
+ + self.assertLive(occurrences, FIRST)
340
+ + self.assertNotLive(occurrences, SECOND)
341
+ + self.assertNotLive(occurrences, THIRD)
342
+ +
343
+ + def test_reply_about_an_occurrence_without_its_own_component(self):
344
+ + self.put_ok("alice", series(override=False, attendees=(BOB, CAROL)))
345
+ + self.deliver(
346
+ + ALICE,
347
+ + itip_message(
348
+ + "REPLY", SECOND, "SEQUENCE:1", f"ATTENDEE;PARTSTAT=DECLINED:{BOB}"
349
+ + ),
350
+ + )
351
+ + occurrences = self.occurrences("alice")
352
+ + self.assertEqual("DECLINED", occurrences[SECOND]["partstat"][BOB])
353
+ + self.assertEqual("NEEDS-ACTION", occurrences[FIRST]["partstat"][BOB])
354
+ + self.assertEqual("NEEDS-ACTION", occurrences[THIRD]["partstat"][BOB])
355
+ + self.assertEqual("NEEDS-ACTION", occurrences[SECOND]["partstat"][CAROL])
356
+ +
357
+ + def test_reply_without_a_recurrence_id_answers_for_the_series(self):
358
+ + self.put_ok("alice", series(override=False, attendees=(BOB,)))
359
+ + self.deliver(
360
+ + ALICE,
361
+ + itip_message(
362
+ + "REPLY", None, "SEQUENCE:1", f"ATTENDEE;PARTSTAT=ACCEPTED:{BOB}"
363
+ + ),
364
+ + )
365
+ + occurrences = self.occurrences("alice")
366
+ + for key in (FIRST, SECOND, THIRD):
367
+ + self.assertEqual("ACCEPTED", occurrences[key]["partstat"][BOB])
368
+ +
369
+ + def test_the_same_instant_in_another_time_zone_is_one_occurrence(self):
370
+ + self.put_ok("bob", series(override=True))
371
+ + self.deliver(
372
+ + BOB,
373
+ + itip_message(
374
+ + "CANCEL",
375
+ + SECOND_LOCAL,
376
+ + "SEQUENCE:2",
377
+ + f"DTSTART;{SECOND_LOCAL}",
378
+ + "STATUS:CANCELLED",
379
+ + f"ATTENDEE:{BOB}",
380
+ + ),
381
+ + )
382
+ + occurrences = self.occurrences("bob")
383
+ + self.assertLive(occurrences, FIRST)
384
+ + self.assertLive(occurrences, THIRD)
385
+ + self.assertNotLive(occurrences, SECOND)
386
+ +
387
+ + def test_a_request_for_one_occurrence_does_not_duplicate_it(self):
388
+ + self.put_ok("bob", series(override=True))
389
+ + self.deliver(
390
+ + BOB,
391
+ + itip_message(
392
+ + "REQUEST",
393
+ + SECOND_LOCAL,
394
+ + "SEQUENCE:2",
395
+ + f"DTSTART;{SECOND_LOCAL}",
396
+ + "DTEND;TZID=Europe/Berlin:20260602T130000",
397
+ + "SUMMARY:Standup (moved again)",
398
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
399
+ + ),
400
+ + )
401
+ + keys = [
402
+ + recurrence_key(comp)
403
+ + for comp in self.stored("bob").subcomponents
404
+ + if comp.name == "VEVENT"
405
+ + ]
406
+ + self.assertEqual(sorted(keys), sorted({"", SECOND}))
407
+ + occurrences = self.occurrences("bob")
408
+ + self.assertEqual("Standup (moved again)", occurrences[SECOND]["summary"])
409
+ + self.assertEqual("Standup", occurrences[FIRST]["summary"])
410
+ +
411
+ + # -- what goes out ----------------------------------------------------
412
+ + def test_a_delegate_is_told_about_the_delegated_occurrence_only(self):
413
+ + self.put_ok("bob", series(override=True))
414
+ + self.put_ok("bob", delegate_second_occurrence(series(override=True)))
415
+ + requests = self.inbox("dave", "REQUEST")
416
+ + self.assertEqual(1, len(requests))
417
+ + self.assertEqual(
418
+ + [SECOND],
419
+ + sorted(
420
+ + recurrence_key(comp)
421
+ + for comp in requests[0].subcomponents
422
+ + if comp.name == "VEVENT"
423
+ + ),
424
+ + )
425
+ +
426
+ + def test_a_delegation_does_not_hide_an_uninvited_occurrence(self):
427
+ + self.put_ok("bob", series(override=True))
428
+ + smuggled = (
429
+ + delegate_second_occurrence(series(override=True))
430
+ + .decode("utf-8")
431
+ + .replace(
432
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\nEND:VEVENT",
433
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\n"
434
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{DAVE}\r\nEND:VEVENT",
435
+ + 1,
436
+ + )
437
+ + .encode("utf-8")
438
+ + )
439
+ + code = self.put("/bob/calendars/calendar/event.ics", smuggled)
440
+ + self.assertEqual("412 Precondition Failed", code)
441
+ + for comp in self.stored("bob").subcomponents:
442
+ + if comp.name == "VEVENT" and recurrence_key(comp) == "":
443
+ + attendees = comp.get("ATTENDEE", [])
444
+ + if not isinstance(attendees, list):
445
+ + attendees = [attendees]
446
+ + self.assertNotIn(DAVE, [str(a) for a in attendees])
447
+ +
448
+ + def test_an_attendee_is_sent_the_occurrences_that_are_theirs(self):
449
+ + self.put_ok("alice", series(override=True, attendees=(BOB, CAROL)))
450
+ + # Carol is taken off the second occurrence only.
451
+ + head, marker, tail = (
452
+ + series(override=True, attendees=(BOB, CAROL))
453
+ + .decode("utf-8")
454
+ + .partition(f"RECURRENCE-ID:{SECOND}")
455
+ + )
456
+ + edited = (
457
+ + head
458
+ + + marker
459
+ + + tail.replace(f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{CAROL}\r\n", "", 1)
460
+ + ).encode("utf-8")
461
+ + self.put_ok("alice", edited)
462
+ + cancels = self.inbox("carol", "CANCEL")
463
+ + self.assertEqual(1, len(cancels))
464
+ + self.assertEqual(
465
+ + [SECOND],
466
+ + sorted(
467
+ + recurrence_key(comp)
468
+ + for comp in cancels[0].subcomponents
469
+ + if comp.name == "VEVENT"
470
+ + ),
471
+ + )
472
+ +
473
+ + def test_cancel_this_and_future_on_a_series_kept_in_a_time_zone(self):
474
+ + """The boundary arrives in Berlin time; the series ends at that instant.
475
+ +
476
+ + RFC 5545 §3.3.10: a series whose DTSTART carries a time zone ends on a
477
+ + UNTIL written in UTC. Left in the sender's local time it reads as a
478
+ + floating time, which is a different instant by the offset — far enough
479
+ + to leave the very occurrence the message named still happening.
480
+ + """
481
+ + self.put_ok("bob", series_in_a_time_zone())
482
+ + self.assertEqual(3, len(self.occurrences("bob")))
483
+ + self.deliver(
484
+ + BOB,
485
+ + itip_message(
486
+ + "CANCEL",
487
+ + f"RANGE=THISANDFUTURE;{SECOND_LOCAL}",
488
+ + "SEQUENCE:2",
489
+ + "STATUS:CANCELLED",
490
+ + f"ATTENDEE:{BOB}",
491
+ + ),
492
+ + )
493
+ + occurrences = self.occurrences("bob")
494
+ + self.assertLive(occurrences, FIRST)
495
+ + self.assertNotLive(occurrences, SECOND)
496
+ + self.assertNotLive(occurrences, THIRD)
497
+ + # Ending the series is one way to do it and not the only one; if this
498
+ + # is the way it was done, the UNTIL is the one RFC 5545 asks for.
499
+ + for comp in self.stored("bob").subcomponents:
500
+ + if comp.name != "VEVENT" or "RRULE" not in comp:
501
+ + continue
502
+ + for until in comp["RRULE"].get("UNTIL", []):
503
+ + self.assertIsNotNone(
504
+ + getattr(until, "tzinfo", None),
505
+ + f"a series kept in a time zone was given a floating UNTIL: {until!r}",
506
+ + )
507
+ +
508
+ + def test_a_request_for_an_instant_the_series_never_produces(self):
509
+ + """Half past eleven is not an occurrence of a series that meets at ten.
510
+ +
511
+ + A message about an occurrence we hold no component for is applied by
512
+ + breaking that occurrence out of the series. An instant the recurrence
513
+ + set does not produce has nothing to break out, and adding it would put
514
+ + a meeting nobody scheduled into the event.
515
+ + """
516
+ + self.put_ok("bob", series(override=False))
517
+ + before = self.stored("bob").to_ical()
518
+ + self.deliver(
519
+ + BOB,
520
+ + itip_message(
521
+ + "REQUEST",
522
+ + "20260602T113000Z",
523
+ + "SEQUENCE:2",
524
+ + "DTSTART:20260602T113000Z",
525
+ + "DTEND:20260602T120000Z",
526
+ + "SUMMARY:Invented",
527
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
528
+ + ),
529
+ + )
530
+ + self.assertEqual(
531
+ + [""],
532
+ + sorted(
533
+ + recurrence_key(comp)
534
+ + for comp in self.stored("bob").subcomponents
535
+ + if comp.name == "VEVENT"
536
+ + ),
537
+ + )
538
+ + self.assertEqual([FIRST, SECOND, THIRD], sorted(self.occurrences("bob")))
539
+ + self.assertEqual(before, self.stored("bob").to_ical())
540
+ +
541
+ + def test_a_re_request_in_another_time_zone_keeps_the_answer(self):
542
+ + """RFC 6638 §3.2.1: a fresh REQUEST does not throw away the answers.
543
+ +
544
+ + The organiser's client writes the second occurrence in Berlin time
545
+ + this time. It is the same occurrence, so the PARTSTAT already given
546
+ + for it is the PARTSTAT it keeps.
547
+ + """
548
+ + self.put_ok("bob", series(override=True))
549
+ + self.deliver(
550
+ + BOB,
551
+ + itip_message(
552
+ + "REPLY", SECOND, "SEQUENCE:1", f"ATTENDEE;PARTSTAT=ACCEPTED:{BOB}"
553
+ + ),
554
+ + )
555
+ + self.assertEqual("ACCEPTED", self.occurrences("bob")[SECOND]["partstat"][BOB])
556
+ + self.deliver(
557
+ + BOB,
558
+ + itip_message(
559
+ + "REQUEST",
560
+ + SECOND_LOCAL,
561
+ + "SEQUENCE:3",
562
+ + f"DTSTART;{SECOND_LOCAL}",
563
+ + "DTEND;TZID=Europe/Berlin:20260602T133000",
564
+ + "SUMMARY:Standup (later)",
565
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
566
+ + ),
567
+ + )
568
+ + occurrences = self.occurrences("bob")
569
+ + self.assertEqual("Standup (later)", occurrences[SECOND]["summary"])
570
+ + self.assertEqual("ACCEPTED", occurrences[SECOND]["partstat"][BOB])
571
+ +
572
+ + def test_an_occurrence_the_series_names_outright_is_still_the_series(self):
573
+ + """Refusing to invent an occurrence is not refusing to keep one.
574
+ +
575
+ + A date named on RDATE is in the recurrence set (RFC 5545 §3.8.5.2),
576
+ + and an object that holds occurrences and no series at all has no
577
+ + recurrence set to be judged against. Neither is an invented occurrence.
578
+ + """
579
+ + lines = (
580
+ + series(override=False)
581
+ + .decode("utf-8")
582
+ + .replace("RRULE:FREQ=DAILY;COUNT=3\r\n", f"RDATE:{SECOND},{THIRD}\r\n", 1)
583
+ + )
584
+ + self.put_ok("bob", lines.encode("utf-8"))
585
+ + self.deliver(
586
+ + BOB,
587
+ + itip_message(
588
+ + "REQUEST",
589
+ + SECOND,
590
+ + "SEQUENCE:2",
591
+ + f"DTSTART:{SECOND}",
592
+ + "DTEND:20260602T113000Z",
593
+ + "SUMMARY:Standup (moved)",
594
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
595
+ + ),
596
+ + )
597
+ + self.assertEqual(
598
+ + ["", SECOND],
599
+ + sorted(
600
+ + recurrence_key(comp)
601
+ + for comp in self.stored("bob").subcomponents
602
+ + if comp.name == "VEVENT"
603
+ + ),
604
+ + )
605
+ +
606
+ + # An object built out of a message about one occurrence: no series.
607
+ + self.deliver(
608
+ + CAROL,
609
+ + itip_message(
610
+ + "REQUEST",
611
+ + SECOND,
612
+ + "SEQUENCE:1",
613
+ + f"DTSTART:{SECOND}",
614
+ + "DTEND:20260602T110000Z",
615
+ + "SUMMARY:Standup",
616
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{CAROL}",
617
+ + ),
618
+ + )
619
+ + self.deliver(
620
+ + CAROL,
621
+ + itip_message(
622
+ + "REQUEST",
623
+ + THIRD,
624
+ + "SEQUENCE:1",
625
+ + f"DTSTART:{THIRD}",
626
+ + "DTEND:20260603T110000Z",
627
+ + "SUMMARY:Standup",
628
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{CAROL}",
629
+ + ),
630
+ + )
631
+ + self.assertEqual(
632
+ + [SECOND, THIRD],
633
+ + sorted(
634
+ + recurrence_key(comp)
635
+ + for comp in self.stored("carol").subcomponents
636
+ + if comp.name == "VEVENT"
637
+ + ),
638
+ + )
639
+ +
640
+ + def test_an_attendee_is_invited_to_the_occurrences_that_are_theirs(self):
641
+ + """Carol is on the second occurrence only, and is sent that one."""
642
+ + head, marker, tail = (
643
+ + series(override=True, attendees=(BOB,))
644
+ + .decode("utf-8")
645
+ + .partition(f"RECURRENCE-ID:{SECOND}")
646
+ + )
647
+ + invited = (
648
+ + head
649
+ + + marker
650
+ + + tail.replace(
651
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\n",
652
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\n"
653
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{CAROL}\r\n",
654
+ + 1,
655
+ + )
656
+ + ).encode("utf-8")
657
+ + self.put_ok("alice", invited)
658
+ + requests = self.inbox("carol", "REQUEST")
659
+ + self.assertEqual(1, len(requests))
660
+ + self.assertEqual(
661
+ + [SECOND],
662
+ + sorted(
663
+ + recurrence_key(comp)
664
+ + for comp in requests[0].subcomponents
665
+ + if comp.name == "VEVENT"
666
+ + ),
667
+ + )
668
+ +
669
+ + # -- from one occurrence onwards: a revision and an answer --------------
670
+ + def _starts(self, principal: str) -> dict:
671
+ + expanded = expand_calendar_rrule(self.stored(principal), *WINDOW)
672
+ + out = {}
673
+ + for comp in expanded.subcomponents:
674
+ + if comp.name == "VEVENT":
675
+ + value = comp["DTSTART"].dt.astimezone(datetime.timezone.utc)
676
+ + out[recurrence_key(comp)] = value.strftime("%Y%m%dT%H%M%SZ")
677
+ + return out
678
+ +
679
+ + def test_a_revision_from_one_occurrence_onwards(self):
680
+ + self.put_ok("bob", series(override=False))
681
+ + self.deliver(
682
+ + BOB,
683
+ + itip_message(
684
+ + "REQUEST",
685
+ + f"RANGE=THISANDFUTURE:{SECOND}",
686
+ + "SEQUENCE:2",
687
+ + "DTSTART:20260602T103000Z",
688
+ + "DTEND:20260602T113000Z",
689
+ + "SUMMARY:Standup (upstairs)",
690
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
691
+ + ),
692
+ + )
693
+ + occurrences = self.occurrences("bob")
694
+ + self.assertEqual("Standup", occurrences[FIRST]["summary"])
695
+ + self.assertEqual("Standup (upstairs)", occurrences[SECOND]["summary"])
696
+ + self.assertEqual("Standup (upstairs)", occurrences[THIRD]["summary"])
697
+ + starts = self._starts("bob")
698
+ + self.assertEqual(FIRST, starts[FIRST])
699
+ + self.assertEqual("20260602T103000Z", starts[SECOND])
700
+ + self.assertEqual("20260603T103000Z", starts[THIRD])
701
+ +
702
+ + def test_a_revision_onwards_on_an_open_ended_series(self):
703
+ + self.put_ok(
704
+ + "bob",
705
+ + series(override=False).replace(
706
+ + b"RRULE:FREQ=DAILY;COUNT=3", b"RRULE:FREQ=DAILY"
707
+ + ),
708
+ + )
709
+ + self.deliver(
710
+ + BOB,
711
+ + itip_message(
712
+ + "REQUEST",
713
+ + f"RANGE=THISANDFUTURE:{SECOND}",
714
+ + "SEQUENCE:2",
715
+ + f"DTSTART:{SECOND}",
716
+ + "DTEND:20260602T110000Z",
717
+ + "SUMMARY:Standup (upstairs)",
718
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
719
+ + ),
720
+ + )
721
+ + occurrences = self.occurrences("bob")
722
+ + self.assertEqual("Standup", occurrences[FIRST]["summary"])
723
+ + self.assertEqual("Standup (upstairs)", occurrences["20260630T100000Z"]["summary"])
724
+ +
725
+ + def test_an_answer_from_one_occurrence_onwards(self):
726
+ + self.put_ok("alice", series(override=True, attendees=(BOB, CAROL)))
727
+ + self.deliver(
728
+ + ALICE,
729
+ + itip_message(
730
+ + "REPLY",
731
+ + f"RANGE=THISANDFUTURE:{SECOND}",
732
+ + "SEQUENCE:1",
733
+ + f"ATTENDEE;PARTSTAT=TENTATIVE:{BOB}",
734
+ + ),
735
+ + )
736
+ + occurrences = self.occurrences("alice")
737
+ + self.assertEqual("NEEDS-ACTION", occurrences[FIRST]["partstat"][BOB])
738
+ + self.assertEqual("TENTATIVE", occurrences[SECOND]["partstat"][BOB])
739
+ + self.assertEqual("TENTATIVE", occurrences[THIRD]["partstat"][BOB])
740
+ + # the occurrence kept as its own exception is still that occurrence
741
+ + self.assertEqual("Standup (moved)", occurrences[SECOND]["summary"])
742
+ + self.assertEqual("Standup", occurrences[THIRD]["summary"])
743
+ + for key in (FIRST, SECOND, THIRD):
744
+ + self.assertEqual("NEEDS-ACTION", occurrences[key]["partstat"][CAROL])
745
+ +
746
+ + def test_an_answer_onwards_after_a_revision_onwards(self):
747
+ + self.put_ok("alice", series(override=False, attendees=(BOB,)))
748
+ + stored = self.stored("alice").to_ical().decode("utf-8")
749
+ + # Alice's own copy after she moved the series upstairs from Tuesday on.
750
+ + revised = stored.replace(
751
+ + "END:VCALENDAR",
752
+ + "BEGIN:VEVENT\r\nUID:rec@example.com\r\nDTSTAMP:20260101T120000Z\r\n"
753
+ + f"SEQUENCE:2\r\nRECURRENCE-ID;RANGE=THISANDFUTURE:{SECOND}\r\n"
754
+ + f"DTSTART:{SECOND}\r\nDTEND:20260602T110000Z\r\n"
755
+ + f"SUMMARY:Standup (upstairs)\r\nORGANIZER:{ALICE}\r\n"
756
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\nEND:VEVENT\r\nEND:VCALENDAR",
757
+ + )
758
+ + self.put_ok("alice", revised.encode("utf-8"))
759
+ + self.deliver(
760
+ + ALICE,
761
+ + itip_message(
762
+ + "REPLY",
763
+ + f"RANGE=THISANDFUTURE:{THIRD}",
764
+ + "SEQUENCE:2",
765
+ + f"ATTENDEE;PARTSTAT=DECLINED:{BOB}",
766
+ + ),
767
+ + )
768
+ + occurrences = self.occurrences("alice")
769
+ + self.assertEqual("NEEDS-ACTION", occurrences[SECOND]["partstat"][BOB])
770
+ + self.assertEqual("DECLINED", occurrences[THIRD]["partstat"][BOB])
771
+ + self.assertEqual("Standup (upstairs)", occurrences[THIRD]["summary"])
772
+ +
773
+ +
774
+ +if __name__ == "__main__":
775
+ + unittest.main()
776
+ diff --git a/xandikos/icalendar.py b/xandikos/icalendar.py
777
+ index 3bc8aea..d3c8e03 100644
778
+ --- a/xandikos/icalendar.py
779
+ +++ b/xandikos/icalendar.py
780
+ @@ -2183,7 +2183,17 @@ def _expand_rrule_component(
781
+ start: datetime | None = None,
782
+ end: datetime | None = None,
783
+ existing: dict[str | date | datetime, Component] = {},
784
+ + onwards: "list[tuple[date | datetime, Component]] | None" = None,
785
+ ) -> Iterable[Component]:
786
+ + """Yield the occurrences of *incomp*'s recurrence set.
787
+ +
788
+ + *existing* maps normalised RECURRENCE-IDs to the exception components
789
+ + that replace an occurrence outright; each one is popped as it is used.
790
+ + *onwards* lists, in order, the exceptions marked
791
+ + ``RECURRENCE-ID;RANGE=THISANDFUTURE`` (RFC 5545 §3.8.4.4): such an
792
+ + exception also stands for every later occurrence that has no exception
793
+ + of its own, shifted by however far it moved its own start.
794
+ + """
795
+ if "RRULE" not in incomp:
796
+ return
797
+ if "DTSTART" not in incomp:
798
+ @@ -2258,6 +2268,12 @@ def _expand_rrule_component(
799
+ try:
800
+ outcomp = existing.pop(ts_normalized)
801
+ except KeyError:
802
+ + outcomp = None
803
+ + if outcomp is None:
804
+ + governing = _governing_onwards(onwards, ts_normalized)
805
+ + if governing is not None:
806
+ + outcomp = _occurrence_from_onwards(governing, ts_for_dtstart)
807
+ + if outcomp is None:
808
+ # Create new occurrence
809
+ outcomp = base_comp.copy()
810
+
811
+ @@ -2302,6 +2318,74 @@ def _expand_rrule_component(
812
+ yield outcomp
813
+
814
+
815
+ +def _is_onwards(comp: Component) -> bool:
816
+ + """True if *comp*'s RECURRENCE-ID carries RANGE=THISANDFUTURE."""
817
+ + rid = comp.get("RECURRENCE-ID")
818
+ + params = getattr(rid, "params", None) or {}
819
+ + rng = params.get("RANGE")
820
+ + return rng is not None and str(rng).upper() == "THISANDFUTURE"
821
+ +
822
+ +
823
+ +def _governing_onwards(
824
+ + onwards: "list[tuple[date | datetime, Component]] | None",
825
+ + ts_normalized: date | datetime,
826
+ +) -> "Component | None":
827
+ + """Return the latest THISANDFUTURE exception that starts before *ts*."""
828
+ + found = None
829
+ + for moment, comp in onwards or ():
830
+ + try:
831
+ + if moment < ts_normalized:
832
+ + found = comp
833
+ + except TypeError:
834
+ + # A date against a date-time: not the same recurrence set.
835
+ + continue
836
+ + return found
837
+ +
838
+ +
839
+ +def _occurrence_from_onwards(
840
+ + governing: Component, ts_for_dtstart: date | datetime
841
+ +) -> Component:
842
+ + """Derive the occurrence at *ts_for_dtstart* from a THISANDFUTURE exception.
843
+ +
844
+ + RFC 5545 §3.8.4.4: the exception's properties hold for the later
845
+ + occurrences too, and if it moved its own start, every later occurrence
846
+ + moves by the same amount and keeps the exception's length.
847
+ + """
848
+ + outcomp = governing.copy()
849
+ + rid = governing["RECURRENCE-ID"].dt
850
+ + own_start_prop = governing.get("DTSTART")
851
+ + own_start = getattr(own_start_prop, "dt", None)
852
+ + shift = timedelta(0)
853
+ + if own_start is not None and type(own_start) is type(rid):
854
+ + try:
855
+ + shift = own_start - rid
856
+ + except TypeError:
857
+ + # One side floating, the other zoned: no instant to measure by.
858
+ + shift = timedelta(0)
859
+ + new_start = ts_for_dtstart + shift
860
+ + if (
861
+ + isinstance(new_start, datetime)
862
+ + and isinstance(own_start, datetime)
863
+ + and new_start.tzinfo is not None
864
+ + and own_start.tzinfo is not None
865
+ + ):
866
+ + new_start = new_start.astimezone(own_start.tzinfo)
867
+ + new_dtstart = create_prop_from_date_or_datetime(new_start)
868
+ + params = getattr(own_start_prop, "params", None)
869
+ + if params:
870
+ + new_dtstart.params = params.copy()
871
+ + outcomp["DTSTART"] = new_dtstart
872
+ + for end_prop in ("DTEND", "DUE"):
873
+ + if end_prop in governing and own_start is not None:
874
+ + length = governing[end_prop].dt - own_start
875
+ + new_end = create_prop_from_date_or_datetime(new_start + length)
876
+ + end_params = getattr(governing[end_prop], "params", None)
877
+ + if end_params:
878
+ + new_end.params = end_params.copy()
879
+ + outcomp[end_prop] = new_end
880
+ + return outcomp
881
+ +
882
+ +
883
+ def expand_calendar_rrule(
884
+ incal: Calendar, start: datetime | None = None, end: datetime | None = None
885
+ ) -> Calendar:
886
+ @@ -2322,6 +2406,12 @@ def expand_calendar_rrule(
887
+ assert isinstance(rec_id.dt, date | datetime)
888
+ ts = asutc(rec_id.dt)
889
+ exceptions[ts] = comp
890
+ + # Exceptions that speak for the rest of the series as well as their own
891
+ + # occurrence, earliest first.
892
+ + onwards = sorted(
893
+ + ((ts, comp) for ts, comp in exceptions.items() if _is_onwards(comp)),
894
+ + key=lambda item: (isinstance(item[0], datetime), str(item[0])),
895
+ + )
896
+
897
+ # Process all components
898
+ for comp in incal.subcomponents:
899
+ @@ -2333,7 +2423,9 @@ def expand_calendar_rrule(
900
+ pass
901
+ elif "RRULE" in comp:
902
+ # Expand recurring events
903
+ - for expanded in _expand_rrule_component(comp, start, end, exceptions):
904
+ + for expanded in _expand_rrule_component(
905
+ + comp, start, end, exceptions, onwards
906
+ + ):
907
+ outcal.add_component(expanded)
908
+ else:
909
+ # Include non-recurring events
910
+ diff --git a/xandikos/itip.py b/xandikos/itip.py
911
+ index 83e3851..71b070e 100644
912
+ --- a/xandikos/itip.py
913
+ +++ b/xandikos/itip.py
914
+ @@ -26,6 +26,7 @@ signature from iTIP-relevant properties — separately from the CalDAV
915
+ plumbing in :mod:`xandikos.scheduling` that exposes them over HTTP.
916
+ """
917
+
918
+ +import copy
919
+ import datetime
920
+ import hashlib
921
+
922
+ @@ -454,20 +455,400 @@ def strip_method(itip_message: Calendar) -> Calendar:
923
+ return out
924
+
925
+
926
+ +def recurrence_key(comp: Component) -> str:
927
+ + """Return a stable name for the occurrence *comp* speaks about.
928
+ +
929
+ + RECURRENCE-ID (RFC 5545 §3.8.4.4) names one occurrence of a recurring
930
+ + event by its original start, and the same instant has more than one
931
+ + written form: ``20260602T100000Z``, ``TZID=Europe/Berlin:20260602T120000``
932
+ + and ``TZID=UTC:20260602T100000`` are one occurrence between them. Keying
933
+ + on the text would make them three, so the key comes from the parsed
934
+ + value. The series' own component carries no RECURRENCE-ID and keys as
935
+ + the empty string.
936
+ + """
937
+ + rid = comp.get("RECURRENCE-ID")
938
+ + if rid is None:
939
+ + return ""
940
+ + return _instant_key(rid)
941
+ +
942
+ +
943
+ +def _instant_key(prop: PropTypes) -> str:
944
+ + """Key one date-time property by the instant it denotes."""
945
+ + dt = getattr(prop, "dt", None)
946
+ + if isinstance(dt, datetime.datetime):
947
+ + if dt.tzinfo is not None:
948
+ + dt = dt.astimezone(datetime.timezone.utc)
949
+ + return dt.strftime("%Y%m%dT%H%M%SZ")
950
+ + # A floating time has no instant until a time zone is chosen; it can
951
+ + # only be the same occurrence as another floating time.
952
+ + return dt.strftime("%Y%m%dT%H%M%S")
953
+ + if isinstance(dt, datetime.date):
954
+ + return dt.strftime("%Y%m%d")
955
+ + rendered = prop.to_ical()
956
+ + return rendered.decode("utf-8") if isinstance(rendered, bytes) else str(rendered)
957
+ +
958
+ +
959
+ +def itip_occurrences(
960
+ + itip_message: Component, uid: str
961
+ +) -> "dict[str, PropTypes | None]":
962
+ + """Map occurrence key -> its RECURRENCE-ID property, for *uid* in a message.
963
+ +
964
+ + The series' own component maps to None. Used to decide which components
965
+ + of a stored object a message speaks about, and — for keys the stored
966
+ + object has no component for — to break the occurrence out.
967
+ + """
968
+ + out: dict[str, PropTypes | None] = {}
969
+ + for comp in itip_message.subcomponents:
970
+ + if comp.name not in SCHEDULING_COMPONENTS:
971
+ + continue
972
+ + if str(comp.get("UID", "")) != uid:
973
+ + continue
974
+ + rid = comp.get("RECURRENCE-ID")
975
+ + out[recurrence_key(comp)] = rid
976
+ + return out
977
+ +
978
+ +
979
+ +def covers_series(itip_message: Component, uid: str) -> bool:
980
+ + """True if *itip_message* carries the series itself, not single occurrences."""
981
+ + return "" in itip_occurrences(itip_message, uid)
982
+ +
983
+ +
984
+ +def occurrences_for_attendee(cal: Component, address: str) -> "set[str]":
985
+ + """Occurrence keys of *cal* on which *address* is an ATTENDEE."""
986
+ + found: set[str] = set()
987
+ + for comp in cal.subcomponents:
988
+ + if comp.name not in SCHEDULING_COMPONENTS:
989
+ + continue
990
+ + if _find_attendee(comp, address) is not None:
991
+ + found.add(recurrence_key(comp))
992
+ + return found
993
+ +
994
+ +
995
+ +def narrow_to_occurrences(cal: Component, keys: "set[str]") -> Calendar:
996
+ + """Return a copy of *cal* carrying only the occurrences in *keys*.
997
+ +
998
+ + Non-scheduling components (VTIMEZONE and friends) are kept, so the
999
+ + result is still a self-contained calendar object.
1000
+ + """
1001
+ + out = Calendar()
1002
+ + for field in cal:
1003
+ + out[field] = cal[field]
1004
+ + for comp in cal.subcomponents:
1005
+ + if comp.name not in SCHEDULING_COMPONENTS or recurrence_key(comp) in keys:
1006
+ + out.add_component(comp.copy())
1007
+ + return out
1008
+ +
1009
+ +
1010
+ +def series_produces(cal: Calendar, uid: str, rid: PropTypes) -> bool:
1011
+ + """True if *uid*'s recurrence set in *cal* produces the occurrence *rid*.
1012
+ +
1013
+ + The question a message about a single occurrence raises before anything
1014
+ + else: an occurrence the series does produce is ours to apply the message
1015
+ + to, whether or not we keep a component for it, and an instant the series
1016
+ + never produces is not ours to invent.
1017
+ + """
1018
+ + if _expand_occurrence(cal, uid, rid) is not None:
1019
+ + return True
1020
+ + return _named_by_a_recurrence_date(cal, uid, rid)
1021
+ +
1022
+ +
1023
+ +def _named_by_a_recurrence_date(cal: Calendar, uid: str, rid: PropTypes) -> bool:
1024
+ + """True if the series names *rid* outright on an RDATE and does not exclude it.
1025
+ +
1026
+ + RFC 5545 §3.8.5.2: a date named on RDATE is in the recurrence set as much
1027
+ + as one the rule produces. It is asked here rather than left to the
1028
+ + expansion because the expansion works from the rule.
1029
+ + """
1030
+ + wanted = _instant_key(rid)
1031
+ + for comp in cal.subcomponents:
1032
+ + if comp.name not in SCHEDULING_COMPONENTS:
1033
+ + continue
1034
+ + if str(comp.get("UID", "")) != uid or "RECURRENCE-ID" in comp:
1035
+ + continue
1036
+ + if wanted in _dates_named(comp, "EXDATE"):
1037
+ + return False
1038
+ + if wanted in _dates_named(comp, "RDATE"):
1039
+ + return True
1040
+ + return False
1041
+ +
1042
+ +
1043
+ +def _dates_named(comp: Component, field: str) -> "set[str]":
1044
+ + """The instants *field* names on *comp*, keyed the way occurrences are."""
1045
+ + out: set[str] = set()
1046
+ + value = comp.get(field)
1047
+ + if value is None:
1048
+ + return out
1049
+ + for entry in value if isinstance(value, list) else [value]:
1050
+ + for item in getattr(entry, "dts", None) or []:
1051
+ + out.add(_instant_key(item))
1052
+ + return out
1053
+ +
1054
+ +
1055
+ +def materialise_occurrence(
1056
+ + cal: Calendar, uid: str, rid: PropTypes
1057
+ +) -> "Component | None":
1058
+ + """Break the occurrence *rid* out of *uid*'s series as its own component.
1059
+ +
1060
+ + A scheduling message may speak about an occurrence the stored object
1061
+ + never needed a component for: the organiser never moved it, so it lives
1062
+ + inside the series' RRULE. Applying the message to that occurrence alone
1063
+ + means giving it the exception component RFC 5545 §3.8.4.4 describes,
1064
+ + derived from the series exactly as an expansion would derive it.
1065
+ +
1066
+ + Returns the new component, already added to *cal*, or None if the
1067
+ + recurrence set holds no such occurrence (an occurrence that is not in
1068
+ + the series is not ours to invent).
1069
+ + """
1070
+ + occurrence = _expand_occurrence(cal, uid, rid)
1071
+ + if occurrence is None:
1072
+ + return None
1073
+ + # A deep copy: the expansion hands back property objects the series
1074
+ + # still holds, and an exception that shares its ATTENDEE entries with
1075
+ + # the series would carry every answer back into it.
1076
+ + broken_out = copy.deepcopy(occurrence)
1077
+ + # The exception describes one occurrence; the recurrence rules stay
1078
+ + # with the series.
1079
+ + for field in ("RRULE", "EXRULE", "RDATE", "EXDATE"):
1080
+ + if field in broken_out:
1081
+ + del broken_out[field]
1082
+ + cal.add_component(broken_out)
1083
+ + return broken_out
1084
+ +
1085
+ +
1086
+ +def _expand_occurrence(cal: Calendar, uid: str, rid: PropTypes) -> "Component | None":
1087
+ + """Return the occurrence *rid* as *uid*'s series produces it, or None.
1088
+ +
1089
+ + Reads the stored object; writes nothing to it.
1090
+ + """
1091
+ + from xandikos.icalendar import expand_calendar_rrule
1092
+ +
1093
+ + master = None
1094
+ + for comp in cal.subcomponents:
1095
+ + if (
1096
+ + comp.name in SCHEDULING_COMPONENTS
1097
+ + and str(comp.get("UID", "")) == uid
1098
+ + and "RECURRENCE-ID" not in comp
1099
+ + ):
1100
+ + master = comp
1101
+ + break
1102
+ + if master is None or "RRULE" not in master:
1103
+ + return None
1104
+ +
1105
+ + target = getattr(rid, "dt", None)
1106
+ + if isinstance(target, datetime.datetime):
1107
+ + moment = target
1108
+ + elif isinstance(target, datetime.date):
1109
+ + moment = datetime.datetime.combine(target, datetime.time())
1110
+ + else:
1111
+ + return None
1112
+ + if moment.tzinfo is None:
1113
+ + moment = moment.replace(tzinfo=datetime.timezone.utc)
1114
+ + window = datetime.timedelta(days=1)
1115
+ +
1116
+ + # The series, and the exceptions that speak for the rest of it from their
1117
+ + # own occurrence on (RANGE=THISANDFUTURE): an occurrence after one of
1118
+ + # those is what that exception made of it, not what the rule alone says.
1119
+ + # Deep copies — the expansion rewrites the RECURRENCE-IDs it hands back.
1120
+ + probe = Calendar()
1121
+ + probe.add_component(copy.deepcopy(master))
1122
+ + for comp in cal.subcomponents:
1123
+ + if (
1124
+ + comp.name in SCHEDULING_COMPONENTS
1125
+ + and str(comp.get("UID", "")) == uid
1126
+ + and _speaks_onwards(comp)
1127
+ + ):
1128
+ + probe.add_component(copy.deepcopy(comp))
1129
+ + wanted = _instant_key(rid)
1130
+ + for occurrence in expand_calendar_rrule(
1131
+ + probe, moment - window, moment + window
1132
+ + ).subcomponents:
1133
+ + if occurrence.name not in SCHEDULING_COMPONENTS:
1134
+ + continue
1135
+ + if recurrence_key(occurrence) != wanted:
1136
+ + continue
1137
+ + return occurrence
1138
+ + return None
1139
+ +
1140
+ +
1141
+ +def _speaks_onwards(comp: Component) -> bool:
1142
+ + """True if *comp*'s RECURRENCE-ID carries RANGE=THISANDFUTURE."""
1143
+ + rid = comp.get("RECURRENCE-ID")
1144
+ + if rid is None:
1145
+ + return False
1146
+ + rng = rid.params.get("RANGE")
1147
+ + return rng is not None and str(rng).upper() == "THISANDFUTURE"
1148
+ +
1149
+ +
1150
+ +def onwards_targets(cal: Calendar, uid: str, rid: PropTypes) -> "list[Component]":
1151
+ + """Return the components that speak for *rid* and every later occurrence.
1152
+ +
1153
+ + That is every component *cal* already keeps for an occurrence at or after
1154
+ + *rid*, and one more: the first occurrence from *rid* on that has no
1155
+ + component of its own is broken out of the series and marked
1156
+ + RANGE=THISANDFUTURE (RFC 5545 §3.8.4.4), so that what is applied to it
1157
+ + holds for the occurrences after it too — including the ones an open-ended
1158
+ + rule has not produced yet. An occurrence we keep as its own exception
1159
+ + stays that occurrence's own and is returned among the rest. Returns an
1160
+ + empty list when *uid* has nothing at or after *rid*.
1161
+ + """
1162
+ + boundary = _as_instant(rid)
1163
+ + if boundary is None:
1164
+ + return []
1165
+ + targets: list[Component] = []
1166
+ + held: set[str] = set()
1167
+ + master = None
1168
+ + for comp in cal.subcomponents:
1169
+ + if comp.name not in SCHEDULING_COMPONENTS:
1170
+ + continue
1171
+ + if str(comp.get("UID", "")) != uid:
1172
+ + continue
1173
+ + if "RECURRENCE-ID" not in comp:
1174
+ + master = comp
1175
+ + continue
1176
+ + held.add(recurrence_key(comp))
1177
+ + own = _as_instant(comp.get("RECURRENCE-ID"))
1178
+ + if own is not None and own >= boundary:
1179
+ + targets.append(comp)
1180
+ + if master is None or "RRULE" not in master:
1181
+ + return targets
1182
+ + from xandikos.icalendar import rruleset_from_comp, _normalize_dt_for_rrule
1183
+ +
1184
+ + start = getattr(master.get("DTSTART"), "dt", None)
1185
+ + if start is None:
1186
+ + return targets
1187
+ + rules = rruleset_from_comp(master)
1188
+ + moment = rid.dt if isinstance(rid.dt, datetime.datetime) else boundary
1189
+ + probe = _normalize_dt_for_rrule(moment, start)
1190
+ + for occurrence in rules.xafter(probe, count=len(held) + 2, inc=True):
1191
+ + value = occurrence if isinstance(start, datetime.datetime) else occurrence.date()
1192
+ + name = _instant_key(vDDDTypes(value))
1193
+ + if name in held:
1194
+ + continue
1195
+ + broken_out = materialise_occurrence(cal, uid, vDDDTypes(value))
1196
+ + if broken_out is not None:
1197
+ + broken_out["RECURRENCE-ID"].params["RANGE"] = "THISANDFUTURE"
1198
+ + targets.append(broken_out)
1199
+ + break
1200
+ + return targets
1201
+ +
1202
+ +
1203
+ +def thisandfuture_occurrence(itip_message: Component, uid: str) -> "PropTypes | None":
1204
+ + """Return the RECURRENCE-ID a message marks as standing for the tail.
1205
+ +
1206
+ + RFC 5545 §3.2.13: ``RECURRENCE-ID;RANGE=THISANDFUTURE`` names the
1207
+ + occurrence it carries *and every later one*, so a message that uses it
1208
+ + speaks about a stretch of the series rather than a single occurrence.
1209
+ + Returns that property, or None when no component uses the parameter.
1210
+ + """
1211
+ + for comp in itip_message.subcomponents:
1212
+ + if comp.name not in SCHEDULING_COMPONENTS:
1213
+ + continue
1214
+ + if str(comp.get("UID", "")) != uid:
1215
+ + continue
1216
+ + rid = comp.get("RECURRENCE-ID")
1217
+ + if rid is None:
1218
+ + continue
1219
+ + rng = rid.params.get("RANGE")
1220
+ + if rng is not None and str(rng).upper() == "THISANDFUTURE":
1221
+ + return rid
1222
+ + return None
1223
+ +
1224
+ +
1225
+ +def end_series_at(cal: Calendar, uid: str, rid: PropTypes) -> bool:
1226
+ + """Stop *uid*'s series just before *rid*, and cancel later exceptions.
1227
+ +
1228
+ + The occurrences from *rid* onwards stop happening: the recurrence rule
1229
+ + is given an UNTIL that lands before them, and any exception component
1230
+ + already broken out at or after that instant is marked CANCELLED. What
1231
+ + came before is left exactly as it was. Returns False when there is
1232
+ + nothing of *uid* to do this to.
1233
+ + """
1234
+ + boundary = _as_instant(rid)
1235
+ + if boundary is None:
1236
+ + return False
1237
+ + touched = False
1238
+ + for comp in cal.subcomponents:
1239
+ + if comp.name not in SCHEDULING_COMPONENTS:
1240
+ + continue
1241
+ + if str(comp.get("UID", "")) != uid:
1242
+ + continue
1243
+ + own = (
1244
+ + _as_instant(comp.get("RECURRENCE-ID")) if "RECURRENCE-ID" in comp else None
1245
+ + )
1246
+ + if own is not None:
1247
+ + if own >= boundary:
1248
+ + comp["STATUS"] = "CANCELLED"
1249
+ + touched = True
1250
+ + continue
1251
+ + if "RRULE" in comp:
1252
+ + rrule = comp["RRULE"]
1253
+ + last = _until_beside(
1254
+ + boundary - datetime.timedelta(seconds=1), comp.get("DTSTART")
1255
+ + )
1256
+ + try:
1257
+ + del rrule["COUNT"]
1258
+ + except KeyError:
1259
+ + pass
1260
+ + # COUNT and UNTIL cannot both be present (RFC 5545 §3.3.10).
1261
+ + rrule["UNTIL"] = [last]
1262
+ + comp["RRULE"] = rrule
1263
+ + touched = True
1264
+ + else:
1265
+ + own_start = _as_instant(comp.get("DTSTART"))
1266
+ + if own_start is not None and own_start >= boundary:
1267
+ + comp["STATUS"] = "CANCELLED"
1268
+ + touched = True
1269
+ + return touched
1270
+ +
1271
+ +
1272
+ +def _until_beside(moment: datetime.datetime, start: "PropTypes | None"):
1273
+ + """Write *moment* the way an UNTIL beside this DTSTART has to be written.
1274
+ +
1275
+ + RFC 5545 §3.3.10: UNTIL takes the value type of DTSTART, and it is a UTC
1276
+ + date-time whenever DTSTART is one or carries a time zone. The boundary
1277
+ + arrives written in whatever zone the sender chose, which is the same
1278
+ + instant as ours written differently — so it is converted, not copied. A
1279
+ + local time written without its zone is a different instant for every
1280
+ + reader, and the occurrence that instant lands on is off by the offset.
1281
+ + """
1282
+ + dt = getattr(start, "dt", None)
1283
+ + if isinstance(dt, datetime.datetime):
1284
+ + moment = moment.astimezone(datetime.timezone.utc)
1285
+ + # A floating DTSTART has no zone to be an offset from; its UNTIL
1286
+ + # floats with it.
1287
+ + return moment if dt.tzinfo is not None else moment.replace(tzinfo=None)
1288
+ + if isinstance(dt, datetime.date):
1289
+ + return moment.astimezone(datetime.timezone.utc).date()
1290
+ + return moment
1291
+ +
1292
+ +
1293
+ +def _as_instant(prop: "PropTypes | None") -> "datetime.datetime | None":
1294
+ + """Return *prop*'s value as a comparable instant, or None."""
1295
+ + dt = getattr(prop, "dt", None)
1296
+ + if isinstance(dt, datetime.datetime):
1297
+ + return dt if dt.tzinfo is not None else dt.replace(tzinfo=datetime.timezone.utc)
1298
+ + if isinstance(dt, datetime.date):
1299
+ + return datetime.datetime.combine(dt, datetime.time(), datetime.timezone.utc)
1300
+ + return None
1301
+ +
1302
+ +
1303
+ def preserve_partstats(existing: Calendar, incoming: Calendar) -> Calendar:
1304
+ """Mutate *incoming* in place so attendee PARTSTATs survive a re-REQUEST.
1305
+
1306
+ RFC 6638 §3.2.1: when an organiser sends a fresh REQUEST, the
1307
+ attendee's prior PARTSTAT must survive. We match attendees across
1308
+ - components by (UID, RECURRENCE-ID, ATTENDEE address). Returns the
1309
+ - same *incoming* object for chaining.
1310
+ + components by (UID, occurrence, ATTENDEE address) — by the occurrence
1311
+ + itself, not by the text that wrote it, or the same occurrence named in
1312
+ + the sender's own time zone would look like a new one and the answer
1313
+ + already given for it would be thrown away. Returns the same *incoming*
1314
+ + object for chaining.
1315
+ """
1316
+ existing_partstats: dict[tuple[str, str, str], str] = {}
1317
+ for comp in existing.subcomponents:
1318
+ if comp.name not in SCHEDULING_COMPONENTS:
1319
+ continue
1320
+ uid = str(comp.get("UID", ""))
1321
+ - rid = str(comp.get("RECURRENCE-ID", ""))
1322
+ + rid = recurrence_key(comp)
1323
+ attendees = comp.get("ATTENDEE", [])
1324
+ if not isinstance(attendees, list):
1325
+ attendees = [attendees]
1326
+ @@ -480,7 +861,7 @@ def preserve_partstats(existing: Calendar, incoming: Calendar) -> Calendar:
1327
+ if comp.name not in SCHEDULING_COMPONENTS:
1328
+ continue
1329
+ uid = str(comp.get("UID", ""))
1330
+ - rid = str(comp.get("RECURRENCE-ID", ""))
1331
+ + rid = recurrence_key(comp)
1332
+ attendees = comp.get("ATTENDEE", [])
1333
+ if not isinstance(attendees, list):
1334
+ attendees = [attendees]
1335
+ diff --git a/xandikos/web.py b/xandikos/web.py
1336
+ index 8b148f8..2ce619d 100644
1337
+ --- a/xandikos/web.py
1338
+ +++ b/xandikos/web.py
1339
+ @@ -86,7 +86,7 @@ from xandikos.store import (
1340
+ Store,
1341
+ )
1342
+
1343
+ -from icalendar.cal import Calendar
1344
+ +from icalendar.cal import Calendar, Component
1345
+ from icalendar.cal import Timezone as VTimezone
1346
+
1347
+ from .icalendar import CalendarFilter, ICalendarFile
1348
+ @@ -910,6 +910,19 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1349
+ return
1350
+ member_name, member, existing_cal = existing
1351
+ merged = itip.preserve_partstats(existing_cal, new_cal)
1352
+ + if not itip.covers_series(itip_message, uid):
1353
+ + # A REQUEST that names occurrences updates those occurrences; the
1354
+ + # series it does not carry is not ours to drop, and an occurrence
1355
+ + # the series does not produce is not ours to add.
1356
+ + narrowed = _occurrences_of_the_series(existing_cal, merged, uid)
1357
+ + if narrowed is None:
1358
+ + logger.info(
1359
+ + "Inbox auto-apply: REQUEST for %s named no occurrence the "
1360
+ + "series produces",
1361
+ + uid,
1362
+ + )
1363
+ + return
1364
+ + merged = _splice_occurrences(existing_cal, narrowed)
1365
+ await _replace_member_body(member, merged)
1366
+ logger.info(
1367
+ "Inbox auto-apply: updated %s (%s) in %s for REQUEST",
1368
+ @@ -930,14 +943,33 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1369
+ )
1370
+ return
1371
+ member_name, member, existing_cal = existing
1372
+ - for comp in existing_cal.subcomponents:
1373
+ - if (
1374
+ - comp.name in itip.SCHEDULING_COMPONENTS
1375
+ - and str(comp.get("UID", "")) == uid
1376
+ - ):
1377
+ - comp["STATUS"] = "CANCELLED"
1378
+ + onwards = itip.thisandfuture_occurrence(itip_message, uid)
1379
+ + if onwards is not None:
1380
+ + if not itip.end_series_at(existing_cal, uid, onwards):
1381
+ + logger.info(
1382
+ + "Inbox auto-apply: CANCEL for %s named nothing we hold", uid
1383
+ + )
1384
+ + return
1385
+ + await _replace_member_body(member, existing_cal)
1386
+ + logger.info(
1387
+ + "Inbox auto-apply: cancelled %s (%s) from one occurrence onwards",
1388
+ + uid,
1389
+ + member_name,
1390
+ + )
1391
+ + return
1392
+ + targets = _occurrence_targets(existing_cal, itip_message, uid)
1393
+ + if not targets:
1394
+ + logger.info("Inbox auto-apply: CANCEL for %s named nothing we hold", uid)
1395
+ + return
1396
+ + for comp in targets:
1397
+ + comp["STATUS"] = "CANCELLED"
1398
+ await _replace_member_body(member, existing_cal)
1399
+ - logger.info("Inbox auto-apply: cancelled %s (%s)", uid, member_name)
1400
+ + logger.info(
1401
+ + "Inbox auto-apply: cancelled %d occurrence(s) of %s (%s)",
1402
+ + len(targets),
1403
+ + uid,
1404
+ + member_name,
1405
+ + )
1406
+
1407
+ async def _apply_reply(
1408
+ self,
1409
+ @@ -952,34 +984,51 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1410
+ return
1411
+ member_name, member, existing_cal = existing
1412
+
1413
+ - # Pick out the replying attendee's address + new PARTSTAT.
1414
+ - updates: dict[str, str] = {}
1415
+ + # Pick out the replying attendee's address + new PARTSTAT, per the
1416
+ + # occurrence the answer is about.
1417
+ + updates: dict[tuple[str, str], str] = {}
1418
+ for comp in itip_message.subcomponents:
1419
+ if comp.name not in itip.SCHEDULING_COMPONENTS:
1420
+ continue
1421
+ if str(comp.get("UID", "")) != uid:
1422
+ continue
1423
+ + key = itip.recurrence_key(comp)
1424
+ attendees = comp.get("ATTENDEE", [])
1425
+ if not isinstance(attendees, list):
1426
+ attendees = [attendees]
1427
+ for a in attendees:
1428
+ partstat = a.params.get("PARTSTAT")
1429
+ if partstat is not None:
1430
+ - updates[str(a)] = str(partstat)
1431
+ + updates[(key, str(a))] = str(partstat)
1432
+ if not updates:
1433
+ return
1434
+
1435
+ + # An answer that carries the series answers for all of it; an answer
1436
+ + # that names occurrences answers for those, whether or not we already
1437
+ + # keep a component for them.
1438
+ + whole = itip.covers_series(itip_message, uid)
1439
+ + # An answer marked RANGE=THISANDFUTURE is about the occurrence it
1440
+ + # names and every later one: it lands on each of those, and on none
1441
+ + # before.
1442
+ + onwards = itip.thisandfuture_occurrence(itip_message, uid)
1443
+ + if onwards is not None:
1444
+ + onwards_key = itip._instant_key(onwards)
1445
+ + targets = itip.onwards_targets(existing_cal, uid, onwards)
1446
+ + else:
1447
+ + onwards_key = None
1448
+ + targets = _occurrence_targets(existing_cal, itip_message, uid)
1449
+ changed = False
1450
+ - for comp in existing_cal.subcomponents:
1451
+ - if comp.name not in itip.SCHEDULING_COMPONENTS:
1452
+ - continue
1453
+ - if str(comp.get("UID", "")) != uid:
1454
+ - continue
1455
+ + for comp in targets:
1456
+ + key = itip.recurrence_key(comp)
1457
+ attendees = comp.get("ATTENDEE", [])
1458
+ if not isinstance(attendees, list):
1459
+ attendees = [attendees]
1460
+ for a in attendees:
1461
+ - new_partstat = updates.get(str(a))
1462
+ + new_partstat = updates.get((key, str(a)))
1463
+ + if new_partstat is None and onwards_key is not None:
1464
+ + new_partstat = updates.get((onwards_key, str(a)))
1465
+ + if new_partstat is None and whole:
1466
+ + new_partstat = updates.get(("", str(a)))
1467
+ if (
1468
+ new_partstat is not None
1469
+ and a.params.get("PARTSTAT") != new_partstat
1470
+ @@ -992,7 +1041,10 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1471
+ "Inbox auto-apply: applied REPLY to %s (%s); updated PARTSTATs: %s",
1472
+ uid,
1473
+ member_name,
1474
+ - ", ".join(f"{addr}={ps}" for addr, ps in updates.items()),
1475
+ + ", ".join(
1476
+ + f"{addr}={ps}" + (f" ({key})" if key else "")
1477
+ + for (key, addr), ps in updates.items()
1478
+ + ),
1479
+ )
1480
+ else:
1481
+ logger.info(
1482
+ @@ -1002,6 +1054,115 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1483
+ )
1484
+
1485
+
1486
+ +def _occurrence_targets(
1487
+ + existing_cal: Calendar, itip_message: Calendar, uid: str
1488
+ +) -> "list[Component]":
1489
+ + """Return the stored components an iTIP message speaks about.
1490
+ +
1491
+ + A message that carries the series speaks for the whole of it. A message
1492
+ + that names occurrences speaks for exactly those — and RFC 5546 lets it
1493
+ + name an occurrence the recipient keeps no component for, because the
1494
+ + recipient holds the series as one recurring component and the organiser
1495
+ + never had reason to move that occurrence. Such an occurrence is broken
1496
+ + out of the series first, so there is something to apply the message to.
1497
+ + """
1498
+ + occurrences = itip.itip_occurrences(itip_message, uid)
1499
+ + whole = "" in occurrences
1500
+ + targets: list[Component] = []
1501
+ + seen: set[str] = set()
1502
+ + for comp in existing_cal.subcomponents:
1503
+ + if comp.name not in itip.SCHEDULING_COMPONENTS:
1504
+ + continue
1505
+ + if str(comp.get("UID", "")) != uid:
1506
+ + continue
1507
+ + key = itip.recurrence_key(comp)
1508
+ + if whole or key in occurrences:
1509
+ + targets.append(comp)
1510
+ + seen.add(key)
1511
+ + if whole:
1512
+ + return targets
1513
+ + for key, rid in occurrences.items():
1514
+ + if key in seen or rid is None:
1515
+ + continue
1516
+ + broken_out = itip.materialise_occurrence(existing_cal, uid, rid)
1517
+ + if broken_out is not None:
1518
+ + targets.append(broken_out)
1519
+ + return targets
1520
+ +
1521
+ +
1522
+ +def _occurrences_of_the_series(
1523
+ + existing_cal: Calendar, incoming: Calendar, uid: str
1524
+ +) -> "Calendar | None":
1525
+ + """Drop *incoming*'s components for occurrences the series never produces.
1526
+ +
1527
+ + A message may name an occurrence we keep no component for: the organiser
1528
+ + never moved it, so it lives inside the RRULE, and it is ours to break
1529
+ + out. An instant the recurrence set does not produce at all is a
1530
+ + different matter — taking that one would put a meeting in the calendar
1531
+ + that nobody scheduled, under the UID of one that exists. Components of
1532
+ + other UIDs, and the VTIMEZONEs, travel through untouched.
1533
+ +
1534
+ + Returns None when nothing of *uid* survives, so the caller can leave the
1535
+ + stored object exactly as it was.
1536
+ + """
1537
+ + held = {
1538
+ + itip.recurrence_key(comp)
1539
+ + for comp in existing_cal.subcomponents
1540
+ + if comp.name in itip.SCHEDULING_COMPONENTS and str(comp.get("UID", "")) == uid
1541
+ + }
1542
+ + if "" not in held:
1543
+ + # What we keep of this event is occurrences and no series. There is no
1544
+ + # recurrence set here to say what it does and does not produce, so
1545
+ + # there is nothing to refuse: each occurrence stands on its own.
1546
+ + return incoming
1547
+ + out = Calendar()
1548
+ + for field in incoming:
1549
+ + out[field] = incoming[field]
1550
+ + kept = 0
1551
+ + for comp in incoming.subcomponents:
1552
+ + if (
1553
+ + comp.name not in itip.SCHEDULING_COMPONENTS
1554
+ + or str(comp.get("UID", "")) != uid
1555
+ + ):
1556
+ + out.add_component(comp)
1557
+ + continue
1558
+ + rid = comp.get("RECURRENCE-ID")
1559
+ + if (
1560
+ + itip.recurrence_key(comp) in held
1561
+ + or rid is None
1562
+ + or itip.series_produces(existing_cal, uid, rid)
1563
+ + ):
1564
+ + out.add_component(comp)
1565
+ + kept += 1
1566
+ + return out if kept else None
1567
+ +
1568
+ +
1569
+ +def _splice_occurrences(existing_cal: Calendar, incoming: Calendar) -> Calendar:
1570
+ + """Put *incoming*'s components in their place inside *existing_cal*.
1571
+ +
1572
+ + Components are matched by name, UID and occurrence, so an update that
1573
+ + names one occurrence replaces that occurrence and leaves the rest of the
1574
+ + series where it was — and the same occurrence written a second way
1575
+ + replaces the first rather than joining it.
1576
+ + """
1577
+ + out = Calendar()
1578
+ + for field in existing_cal:
1579
+ + out[field] = existing_cal[field]
1580
+ + by_key: dict = {}
1581
+ + order: list = []
1582
+ + for comp in list(existing_cal.subcomponents) + list(incoming.subcomponents):
1583
+ + if comp.name in itip.SCHEDULING_COMPONENTS:
1584
+ + key = (comp.name, str(comp.get("UID", "")), itip.recurrence_key(comp))
1585
+ + else:
1586
+ + key = (comp.name, comp.to_ical())
1587
+ + if key not in by_key:
1588
+ + order.append(key)
1589
+ + by_key[key] = comp
1590
+ + for key in order:
1591
+ + out.add_component(by_key[key])
1592
+ + return out
1593
+ +
1594
+ +
1595
+ async def _find_calendar_member_by_uid(
1596
+ calendar: "CalendarCollection", uid: str
1597
+ ) -> "tuple[str, ObjectResource, Calendar] | None":
1598
+ @@ -1522,24 +1683,26 @@ class CalendarCollection(StoreBasedCollection, caldav.Calendar):
1599
+ new_cal: Calendar,
1600
+ old_cal: Calendar,
1601
+ own_addresses: set[str],
1602
+ - new_delegates: set[str],
1603
+ + new_delegates: "set[tuple[str, str]]",
1604
+ ) -> None:
1605
+ """Raise if *new_cal* changes anything beyond the user's own ATTENDEE.
1606
+
1607
+ Compares scheduling signatures of *old_cal* and *new_cal* with
1608
+ the user's own ATTENDEE parameters masked, and any newly-added
1609
+ - delegates skipped entirely (RFC 6638 §3.2.6 lets an attendee
1610
+ - add a delegate ATTENDEE, distinguishable by its DELEGATED-FROM
1611
+ - pointing back at the user). If anything else differs, the user
1612
+ - is touching organiser-owned data.
1613
+ + delegates dropped where they were added (RFC 6638 §3.2.6 lets an
1614
+ + attendee add a delegate ATTENDEE, distinguishable by its
1615
+ + DELEGATED-FROM pointing back at the user). The exception is as
1616
+ + narrow as the delegation: it covers the occurrences the user
1617
+ + actually delegated, not every occurrence that happens to mention
1618
+ + the same address. If anything else differs, the user is touching
1619
+ + organiser-owned data.
1620
+ """
1621
+ mask = frozenset(own_addresses)
1622
+ - skip = frozenset(new_delegates)
1623
+ new_masked = itip.extract_scheduling_signature(
1624
+ - new_cal, mask_own_attendee_params=mask, skip_attendees=skip
1625
+ + _without_attendees(new_cal, new_delegates), mask_own_attendee_params=mask
1626
+ )
1627
+ old_masked = itip.extract_scheduling_signature(
1628
+ - old_cal, mask_own_attendee_params=mask, skip_attendees=skip
1629
+ + old_cal, mask_own_attendee_params=mask
1630
+ )
1631
+ if new_masked != old_masked:
1632
+ raise webdav.PreconditionFailure(
1633
+ @@ -1555,31 +1718,45 @@ class CalendarCollection(StoreBasedCollection, caldav.Calendar):
1634
+ old_cal: Calendar | None,
1635
+ new_attendees: set[str],
1636
+ own_addresses: set[str],
1637
+ - ) -> dict[str, str]:
1638
+ - """Send REQUEST/CANCEL and return ``{address: SCHEDULE-STATUS code}``."""
1639
+ - outcomes: dict[str, str] = {}
1640
+ + ) -> "dict[str, tuple[str, frozenset[str]]]":
1641
+ + """Send REQUEST/CANCEL; return ``{address: (code, occurrences sent)}``.
1642
+ +
1643
+ + An attendee is invited to the occurrences that list them, which for a
1644
+ + series with exceptions need not be all of them, so each attendee is
1645
+ + sent the occurrences that are theirs. The occurrences that went out
1646
+ + travel back with the delivery outcome: the record of a delivery
1647
+ + belongs on what was delivered.
1648
+ + """
1649
+ + outcomes: dict[str, tuple[str, frozenset[str]]] = {}
1650
+ organiser = _organiser_address(new_cal)
1651
+ - if new_attendees:
1652
+ - request = itip.build_itip_request(new_cal)
1653
+ - for address in new_attendees:
1654
+ - outcomes[address] = await _deliver_status(
1655
+ + invited = {a: itip.occurrences_for_attendee(new_cal, a) for a in new_attendees}
1656
+ + for address, keys in invited.items():
1657
+ + if not keys:
1658
+ + continue
1659
+ + request = itip.build_itip_request(itip.narrow_to_occurrences(new_cal, keys))
1660
+ + outcomes[address] = (
1661
+ + await _deliver_status(
1662
+ self.backend, address, request, originator=organiser
1663
+ - )
1664
+ + ),
1665
+ + frozenset(keys),
1666
+ + )
1667
+
1668
+ if old_cal is None:
1669
+ return outcomes
1670
+ _, old_attendees = _organiser_attendees(old_cal, own_addresses)
1671
+ - dropped = old_attendees - new_attendees
1672
+ - if dropped:
1673
+ - cancel = itip.build_itip_cancel(old_cal)
1674
+ - for address in dropped:
1675
+ - # Dropped attendees aren't in new_cal, so their CANCEL
1676
+ - # delivery outcomes don't end up annotated anywhere; the
1677
+ - # CANCEL itself is the record. Still goes through the
1678
+ - # iMIP path for non-local recipients.
1679
+ - await _deliver_status(
1680
+ - self.backend, address, cancel, originator=organiser
1681
+ - )
1682
+ + for address in old_attendees:
1683
+ + lost = itip.occurrences_for_attendee(old_cal, address) - invited.get(
1684
+ + address, set()
1685
+ + )
1686
+ + if not lost:
1687
+ + continue
1688
+ + # An attendee who has lost an occurrence — or the whole event —
1689
+ + # is told about what they lost and nothing else. Their CANCEL
1690
+ + # outcome isn't annotated anywhere (they may not be in new_cal at
1691
+ + # all); the CANCEL itself is the record. Still goes through the
1692
+ + # iMIP path for non-local recipients.
1693
+ + cancel = itip.build_itip_cancel(itip.narrow_to_occurrences(old_cal, lost))
1694
+ + await _deliver_status(self.backend, address, cancel, originator=organiser)
1695
+ return outcomes
1696
+
1697
+ async def _dispatch_attendee_put(
1698
+ @@ -1588,25 +1765,32 @@ class CalendarCollection(StoreBasedCollection, caldav.Calendar):
1699
+ old_cal: Calendar | None,
1700
+ own_addresses: set[str],
1701
+ force_reply: set[str],
1702
+ - new_delegates: set[str],
1703
+ - ) -> dict[str, str]:
1704
+ + new_delegates: "set[tuple[str, str]]",
1705
+ + ) -> "dict[str, tuple[str, frozenset[str]]]":
1706
+ """Send REPLY to organiser and REQUEST to any newly-added delegates.
1707
+
1708
+ - Returns ``{address: SCHEDULE-STATUS code}`` for the delegate
1709
+ + Returns ``{address: (code, occurrences sent)}`` for the delegate
1710
+ deliveries; the REPLY itself isn't annotated (the user's own
1711
+ ATTENDEE doesn't carry SCHEDULE-STATUS).
1712
+ """
1713
+ - outcomes: dict[str, str] = {}
1714
+ + outcomes: dict[str, tuple[str, frozenset[str]]] = {}
1715
+ own_address = _own_attendee_address(new_cal, own_addresses)
1716
+
1717
+ - # RFC 6638 §3.2.6: when the user delegates to someone else,
1718
+ - # the new delegate needs a REQUEST so they see the meeting.
1719
+ - if new_delegates:
1720
+ - request = itip.build_itip_request(new_cal)
1721
+ - for address in new_delegates:
1722
+ - outcomes[address] = await _deliver_status(
1723
+ + # RFC 6638 §3.2.6: when the user delegates to someone else, the new
1724
+ + # delegate needs a REQUEST so they see the meeting — the part of it
1725
+ + # they were handed, which for a single delegated occurrence is that
1726
+ + # occurrence and not the rest of the series.
1727
+ + delegated: dict[str, set[str]] = {}
1728
+ + for key, address in new_delegates:
1729
+ + delegated.setdefault(address, set()).add(key)
1730
+ + for address, keys in delegated.items():
1731
+ + request = itip.build_itip_request(itip.narrow_to_occurrences(new_cal, keys))
1732
+ + outcomes[address] = (
1733
+ + await _deliver_status(
1734
+ self.backend, address, request, originator=own_address
1735
+ - )
1736
+ + ),
1737
+ + frozenset(keys),
1738
+ + )
1739
+
1740
+ if own_address is None:
1741
+ return outcomes
1742
+ @@ -1724,24 +1908,34 @@ def _strip_mailto(address: str) -> str:
1743
+ return address
1744
+
1745
+
1746
+ -def _annotate_schedule_status(cal: Calendar, outcomes: dict[str, str]) -> None:
1747
+ +def _annotate_schedule_status(
1748
+ + cal: Calendar, outcomes: "dict[str, tuple[str, frozenset[str]]]"
1749
+ +) -> None:
1750
+ """Stamp SCHEDULE-STATUS on each ATTENDEE per RFC 6638 §3.2.
1751
+
1752
+ - *outcomes* maps an attendee address (as it appears in ATTENDEE) to
1753
+ - a request-status code. Attendees absent from *outcomes* are left
1754
+ - alone — typically the organiser themselves, who we don't deliver
1755
+ + *outcomes* maps an attendee address (as it appears in ATTENDEE) to the
1756
+ + request-status code of the delivery and the occurrences that delivery
1757
+ + carried. The stamp is the record of that delivery, so it goes on the
1758
+ + occurrences that were sent and nowhere else: an occurrence nobody was
1759
+ + told about has not been delivered. Attendees absent from *outcomes* are
1760
+ + left alone — typically the organiser themselves, who we don't deliver
1761
+ to.
1762
+ """
1763
+ for comp in cal.subcomponents:
1764
+ if comp.name not in itip.SCHEDULING_COMPONENTS:
1765
+ continue
1766
+ + key = itip.recurrence_key(comp)
1767
+ attendees = comp.get("ATTENDEE", [])
1768
+ if not isinstance(attendees, list):
1769
+ attendees = [attendees]
1770
+ for a in attendees:
1771
+ - status = outcomes.get(str(a))
1772
+ - if status is not None:
1773
+ - a.params["SCHEDULE-STATUS"] = status
1774
+ + outcome = outcomes.get(str(a))
1775
+ + if outcome is None:
1776
+ + continue
1777
+ + status, sent = outcome
1778
+ + if key not in sent:
1779
+ + continue
1780
+ + a.params["SCHEDULE-STATUS"] = status
1781
+
1782
+
1783
+ def _consume_force_send(cal: Calendar) -> tuple[set[str], set[str], bool]:
1784
+ @@ -1813,19 +2007,22 @@ def _organiser_attendees(
1785
+ return is_organiser, attendees
1786
+
1787
+
1788
+ -def _delegates_of(cal: Calendar, own_addresses: set[str]) -> set[str]:
1789
+ - """Return ATTENDEE addresses delegated FROM one of *own_addresses*.
1790
+ +def _delegates_of(cal: Calendar, own_addresses: set[str]) -> "set[tuple[str, str]]":
1791
+ + """Return ``(occurrence, ATTENDEE)`` pairs delegated FROM *own_addresses*.
1792
+
1793
+ RFC 5545 §3.8.4.4: an ATTENDEE may carry DELEGATED-FROM listing
1794
+ the address(es) that delegated to them. We pick the entries
1795
+ whose DELEGATED-FROM matches the user — those are the user's
1796
+ delegates and the user is allowed to add them on a PUT
1797
+ - (RFC 6638 §3.2.6).
1798
+ + (RFC 6638 §3.2.6). A delegation is made on an occurrence, so the
1799
+ + occurrence travels with the address: handing over one occurrence of a
1800
+ + series says nothing about the others.
1801
+ """
1802
+ - out: set[str] = set()
1803
+ + out: set[tuple[str, str]] = set()
1804
+ for comp in cal.subcomponents:
1805
+ if comp.name not in itip.SCHEDULING_COMPONENTS:
1806
+ continue
1807
+ + key = itip.recurrence_key(comp)
1808
+ comp_attendees = comp.get("ATTENDEE", [])
1809
+ if not isinstance(comp_attendees, list):
1810
+ comp_attendees = [comp_attendees]
1811
+ @@ -1837,7 +2034,28 @@ def _delegates_of(cal: Calendar, own_addresses: set[str]) -> set[str]:
1812
+ delegated_from if isinstance(delegated_from, list) else [delegated_from]
1813
+ )
1814
+ if any(str(src) in own_addresses for src in sources):
1815
+ - out.add(str(a))
1816
+ + out.add((key, str(a)))
1817
+ + return out
1818
+ +
1819
+ +
1820
+ +def _without_attendees(cal: Calendar, pairs: "set[tuple[str, str]]") -> Calendar:
1821
+ + """Return a copy of *cal* with those ``(occurrence, ATTENDEE)`` pairs gone."""
1822
+ + out = Calendar()
1823
+ + for field in cal:
1824
+ + out[field] = cal[field]
1825
+ + for comp in cal.subcomponents:
1826
+ + clone = comp.copy()
1827
+ + if clone.name in itip.SCHEDULING_COMPONENTS:
1828
+ + key = itip.recurrence_key(clone)
1829
+ + attendees = clone.get("ATTENDEE", [])
1830
+ + if not isinstance(attendees, list):
1831
+ + attendees = [attendees]
1832
+ + kept = [a for a in attendees if (key, str(a)) not in pairs]
1833
+ + if len(kept) != len(attendees):
1834
+ + del clone["ATTENDEE"]
1835
+ + for a in kept:
1836
+ + clone.add("ATTENDEE", a)
1837
+ + out.add_component(clone)
1838
+ return out
1839
+
1840
+
1841
+ @@ -1887,7 +2105,11 @@ def _partstat_changed(new_cal: Calendar, old_cal: Calendar, address: str) -> boo
1842
+
1843
+
1844
+ def _user_partstats(cal: Calendar, address: str) -> dict[tuple[str, str, str], str]:
1845
+ - """Map (component-name, UID, RECURRENCE-ID) → PARTSTAT for *address*."""
1846
+ + """Map (component-name, UID, occurrence) → PARTSTAT for *address*.
1847
+ +
1848
+ + Keyed by the occurrence itself: rewriting the same occurrence in another
1849
+ + time zone is not the user answering again.
1850
+ + """
1851
+ out: dict[tuple[str, str, str], str] = {}
1852
+ for comp in cal.subcomponents:
1853
+ if comp.name not in itip.SCHEDULING_COMPONENTS:
1854
+ @@ -1899,7 +2121,7 @@ def _user_partstats(cal: Calendar, address: str) -> dict[tuple[str, str, str], s
1855
+ if str(a) != address:
1856
+ continue
1857
+ uid = str(comp.get("UID", ""))
1858
+ - rid = str(comp.get("RECURRENCE-ID", ""))
1859
+ + rid = itip.recurrence_key(comp)
1860
+ partstat = str(a.params.get("PARTSTAT", "NEEDS-ACTION"))
1861
+ out[(comp.name, uid, rid)] = partstat
1862
+ break
harbor/tasks/xandikos_itip_recurrence_id_override_contract/solution/solve.sh ADDED
@@ -0,0 +1,1868 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -eu
3
+ cd /workspace/repo
4
+ git apply <<'REFERENCE_PATCH'
5
+ diff --git a/tests/test_itip_per_instance.py b/tests/test_itip_per_instance.py
6
+ new file mode 100644
7
+ index 0000000..f562977
8
+ --- /dev/null
9
+ +++ b/tests/test_itip_per_instance.py
10
+ @@ -0,0 +1,769 @@
11
+ +# Xandikos
12
+ +# Copyright (C) 2016-2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al.
13
+ +#
14
+ +# This program is free software; you can redistribute it and/or
15
+ +# modify it under the terms of the GNU General Public License
16
+ +# as published by the Free Software Foundation; version 3
17
+ +# of the License or (at your option) any later version of
18
+ +# the License.
19
+ +#
20
+ +# This program is distributed in the hope that it will be useful,
21
+ +# but WITHOUT ANY WARRANTY; without even the implied warranty of
22
+ +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23
+ +# GNU General Public License for more details.
24
+ +#
25
+ +# You should have received a copy of the GNU General Public License
26
+ +# along with this program; if not, write to the Free Software
27
+ +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28
+ +# MA 02110-1301, USA.
29
+ +
30
+ +"""Scheduling messages that speak about single occurrences of a series.
31
+ +
32
+ +RFC 5546 lets a CANCEL, a REQUEST or a REPLY name one occurrence of a
33
+ +recurring event with RECURRENCE-ID, whether or not the recipient happens
34
+ +to keep a separate component for it, and RFC 5545 §3.2.13 lets it name an
35
+ +occurrence and every later one at once. RFC 6638 §3.2.6 lets an attendee
36
+ +hand one occurrence to a delegate. These exercise the whole round: what
37
+ +the inbox does with such a message, what goes out when a user makes such
38
+ +a change, and what the server records about it.
39
+ +"""
40
+ +
41
+ +import asyncio
42
+ +import datetime
43
+ +import shutil
44
+ +import tempfile
45
+ +import unittest
46
+ +from io import BytesIO
47
+ +from wsgiref.util import setup_testing_defaults
48
+ +
49
+ +from icalendar.cal import Calendar
50
+ +
51
+ +from xandikos import scheduling
52
+ +from xandikos.icalendar import expand_calendar_rrule
53
+ +from xandikos.web import (
54
+ + SingleUserFilesystemBackend,
55
+ + StoreBasedCollection,
56
+ + XandikosApp,
57
+ +)
58
+ +
59
+ +ALICE = "mailto:alice@example.com"
60
+ +BOB = "mailto:bob@example.com"
61
+ +CAROL = "mailto:carol@example.com"
62
+ +DAVE = "mailto:dave@example.com"
63
+ +
64
+ +FIRST = "20260601T100000Z"
65
+ +SECOND = "20260602T100000Z"
66
+ +THIRD = "20260603T100000Z"
67
+ +
68
+ +# The same instant as SECOND, written the way a client in Berlin writes it.
69
+ +SECOND_LOCAL = "TZID=Europe/Berlin:20260602T120000"
70
+ +
71
+ +
72
+ +def recurrence_key(comp) -> str:
73
+ + """The occurrence *comp* is about, named by its instant ("" for the series)."""
74
+ + rid = comp.get("RECURRENCE-ID")
75
+ + if rid is None:
76
+ + return ""
77
+ + value = rid.dt
78
+ + if isinstance(value, datetime.datetime):
79
+ + if value.tzinfo is not None:
80
+ + value = value.astimezone(datetime.timezone.utc)
81
+ + return value.strftime("%Y%m%dT%H%M%SZ")
82
+ + return value.strftime("%Y%m%d")
83
+ +
84
+ +
85
+ +WINDOW = (
86
+ + datetime.datetime(2026, 5, 1, tzinfo=datetime.timezone.utc),
87
+ + datetime.datetime(2026, 7, 1, tzinfo=datetime.timezone.utc),
88
+ +)
89
+ +
90
+ +
91
+ +def series(*, override: bool, attendees=(BOB,)) -> bytes:
92
+ + """A daily series of three, optionally with the second one broken out."""
93
+ + lines = [
94
+ + "BEGIN:VCALENDAR",
95
+ + "VERSION:2.0",
96
+ + "PRODID:-//Xandikos test//EN",
97
+ + "BEGIN:VEVENT",
98
+ + "UID:rec@example.com",
99
+ + "DTSTAMP:20260101T120000Z",
100
+ + "SEQUENCE:1",
101
+ + f"DTSTART:{FIRST}",
102
+ + "DTEND:20260601T110000Z",
103
+ + "RRULE:FREQ=DAILY;COUNT=3",
104
+ + "SUMMARY:Standup",
105
+ + f"ORGANIZER:{ALICE}",
106
+ + ]
107
+ + lines += [f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{a}" for a in attendees]
108
+ + lines.append("END:VEVENT")
109
+ + if override:
110
+ + lines += [
111
+ + "BEGIN:VEVENT",
112
+ + "UID:rec@example.com",
113
+ + "DTSTAMP:20260101T120000Z",
114
+ + "SEQUENCE:1",
115
+ + f"RECURRENCE-ID:{SECOND}",
116
+ + f"DTSTART:{SECOND}",
117
+ + "DTEND:20260602T110000Z",
118
+ + "SUMMARY:Standup (moved)",
119
+ + f"ORGANIZER:{ALICE}",
120
+ + ]
121
+ + lines += [f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{a}" for a in attendees]
122
+ + lines.append("END:VEVENT")
123
+ + lines.append("END:VCALENDAR")
124
+ + return ("\r\n".join(lines) + "\r\n").encode("utf-8")
125
+ +
126
+ +
127
+ +def itip_message(method: str, rid: str | None, *body: str) -> bytes:
128
+ + lines = [
129
+ + "BEGIN:VCALENDAR",
130
+ + "VERSION:2.0",
131
+ + "PRODID:-//Xandikos test//EN",
132
+ + f"METHOD:{method}",
133
+ + "BEGIN:VEVENT",
134
+ + "UID:rec@example.com",
135
+ + "DTSTAMP:20260102T120000Z",
136
+ + f"ORGANIZER:{ALICE}",
137
+ + ]
138
+ + if rid is not None:
139
+ + lines.append(f"RECURRENCE-ID;{rid}" if "=" in rid else f"RECURRENCE-ID:{rid}")
140
+ + lines += list(body)
141
+ + lines += ["END:VEVENT", "END:VCALENDAR"]
142
+ + return ("\r\n".join(lines) + "\r\n").encode("utf-8")
143
+ +
144
+ +
145
+ +def series_in_a_time_zone() -> bytes:
146
+ + """The same three-a-day series, kept in Berlin local time with its VTIMEZONE.
147
+ +
148
+ + Its occurrences are the same instants as :func:`series` produces: noon in
149
+ + Berlin on those days is 10:00 UTC.
150
+ + """
151
+ + lines = [
152
+ + "BEGIN:VCALENDAR",
153
+ + "VERSION:2.0",
154
+ + "PRODID:-//Xandikos test//EN",
155
+ + "BEGIN:VTIMEZONE",
156
+ + "TZID:Europe/Berlin",
157
+ + "BEGIN:DAYLIGHT",
158
+ + "TZOFFSETFROM:+0100",
159
+ + "TZOFFSETTO:+0200",
160
+ + "TZNAME:CEST",
161
+ + "DTSTART:19700329T020000",
162
+ + "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU",
163
+ + "END:DAYLIGHT",
164
+ + "BEGIN:STANDARD",
165
+ + "TZOFFSETFROM:+0200",
166
+ + "TZOFFSETTO:+0100",
167
+ + "TZNAME:CET",
168
+ + "DTSTART:19701025T030000",
169
+ + "RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU",
170
+ + "END:STANDARD",
171
+ + "END:VTIMEZONE",
172
+ + "BEGIN:VEVENT",
173
+ + "UID:rec@example.com",
174
+ + "DTSTAMP:20260101T120000Z",
175
+ + "SEQUENCE:1",
176
+ + "DTSTART;TZID=Europe/Berlin:20260601T120000",
177
+ + "DTEND;TZID=Europe/Berlin:20260601T130000",
178
+ + "RRULE:FREQ=DAILY;COUNT=3",
179
+ + "SUMMARY:Standup",
180
+ + f"ORGANIZER:{ALICE}",
181
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
182
+ + "END:VEVENT",
183
+ + "END:VCALENDAR",
184
+ + ]
185
+ + return ("\r\n".join(lines) + "\r\n").encode("utf-8")
186
+ +
187
+ +
188
+ +def delegate_second_occurrence(body: bytes) -> bytes:
189
+ + """Bob hands his seat at the second occurrence to Dave."""
190
+ + head, marker, tail = body.decode("utf-8").partition(f"RECURRENCE-ID:{SECOND}")
191
+ + assert marker, "the fixture has no second occurrence to delegate"
192
+ + tail = tail.replace(
193
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\n",
194
+ + f'ATTENDEE;PARTSTAT=DELEGATED;DELEGATED-TO="{DAVE}":{BOB}\r\n'
195
+ + f'ATTENDEE;PARTSTAT=NEEDS-ACTION;DELEGATED-FROM="{BOB}":{DAVE}\r\n',
196
+ + 1,
197
+ + )
198
+ + return (head + marker + tail).encode("utf-8")
199
+ +
200
+ +
201
+ +class PerInstanceSchedulingTests(unittest.TestCase):
202
+ + def setUp(self):
203
+ + super().setUp()
204
+ + self.tempdir = tempfile.mkdtemp()
205
+ + self.addCleanup(shutil.rmtree, self.tempdir)
206
+ + self.backend = SingleUserFilesystemBackend(self.tempdir)
207
+ + for name in ("alice", "bob", "carol", "dave"):
208
+ + self.backend.create_principal("/" + name, create_defaults=True)
209
+ + self.backend.get_resource("/" + name).set_calendar_user_address_set(
210
+ + [f"mailto:{name}@example.com"]
211
+ + )
212
+ +
213
+ + # -- driving the server the way a client does -------------------------
214
+ + def put(self, path: str, body: bytes) -> str:
215
+ + app = XandikosApp(self.backend, "user")
216
+ + environ = {
217
+ + "PATH_INFO": path,
218
+ + "REQUEST_METHOD": "PUT",
219
+ + "QUERY_STRING": "",
220
+ + "CONTENT_TYPE": "text/calendar",
221
+ + "CONTENT_LENGTH": str(len(body)),
222
+ + }
223
+ + setup_testing_defaults(environ)
224
+ + environ["wsgi.input"] = BytesIO(body)
225
+ + codes: list[str] = []
226
+ + b"".join(app(environ, lambda code, headers: codes.append(code)))
227
+ + return codes[0]
228
+ +
229
+ + def put_ok(self, principal: str, body: bytes) -> None:
230
+ + code = self.put(f"/{principal}/calendars/calendar/event.ics", body)
231
+ + self.assertIn(code.split()[0], ("200", "201", "204"), code)
232
+ +
233
+ + def deliver(self, address: str, message: bytes) -> None:
234
+ + self.assertTrue(
235
+ + asyncio.run(
236
+ + scheduling.deliver_to_inbox(
237
+ + self.backend, address, Calendar.from_ical(message.decode("utf-8"))
238
+ + )
239
+ + )
240
+ + )
241
+ +
242
+ + # -- reading what the stores hold -------------------------------------
243
+ + def stored(self, principal: str) -> Calendar:
244
+ + col = self.backend.get_resource(f"/{principal}/calendars/calendar")
245
+ + assert isinstance(col, StoreBasedCollection)
246
+ + raw = [
247
+ + b"".join(col.store._get_raw(name, etag))
248
+ + for name, _ct, etag in col.store.iter_with_etag()
249
+ + ]
250
+ + self.assertEqual(1, len(raw))
251
+ + return Calendar.from_ical(raw[0].decode("utf-8"))
252
+ +
253
+ + def inbox(self, principal: str, method: str) -> list[Calendar]:
254
+ + col = self.backend.get_resource(f"/{principal}/inbox")
255
+ + assert isinstance(col, StoreBasedCollection)
256
+ + out = []
257
+ + for name, _ct, etag in col.store.iter_with_etag():
258
+ + parsed = Calendar.from_ical(
259
+ + b"".join(col.store._get_raw(name, etag)).decode("utf-8")
260
+ + )
261
+ + if str(parsed.get("METHOD", "")).upper() == method:
262
+ + out.append(parsed)
263
+ + return out
264
+ +
265
+ + def occurrences(self, principal: str) -> dict:
266
+ + """The series as a client sees it after expansion."""
267
+ + expanded = expand_calendar_rrule(self.stored(principal), *WINDOW)
268
+ + out = {}
269
+ + for comp in expanded.subcomponents:
270
+ + if comp.name != "VEVENT":
271
+ + continue
272
+ + attendees = comp.get("ATTENDEE", [])
273
+ + if not isinstance(attendees, list):
274
+ + attendees = [attendees]
275
+ + out[recurrence_key(comp)] = {
276
+ + "status": str(comp.get("STATUS", "")),
277
+ + "summary": str(comp.get("SUMMARY", "")),
278
+ + "partstat": {
279
+ + str(a): str(a.params.get("PARTSTAT", "")) for a in attendees
280
+ + },
281
+ + }
282
+ + return out
283
+ +
284
+ + def assertLive(self, occurrences, key):
285
+ + self.assertIn(key, occurrences)
286
+ + self.assertNotEqual("CANCELLED", occurrences[key]["status"].upper())
287
+ +
288
+ + def assertNotLive(self, occurrences, key):
289
+ + row = occurrences.get(key)
290
+ + if row is not None:
291
+ + self.assertEqual("CANCELLED", row["status"].upper())
292
+ +
293
+ + # -- the inbox --------------------------------------------------------
294
+ + def test_cancel_of_an_occurrence_without_its_own_component(self):
295
+ + self.put_ok("bob", series(override=False))
296
+ + self.deliver(
297
+ + BOB,
298
+ + itip_message(
299
+ + "CANCEL",
300
+ + SECOND,
301
+ + "SEQUENCE:2",
302
+ + f"DTSTART:{SECOND}",
303
+ + "STATUS:CANCELLED",
304
+ + f"ATTENDEE:{BOB}",
305
+ + ),
306
+ + )
307
+ + occurrences = self.occurrences("bob")
308
+ + self.assertLive(occurrences, FIRST)
309
+ + self.assertLive(occurrences, THIRD)
310
+ + self.assertNotLive(occurrences, SECOND)
311
+ +
312
+ + def test_cancel_without_a_recurrence_id_still_ends_the_series(self):
313
+ + self.put_ok("bob", series(override=True))
314
+ + self.deliver(
315
+ + BOB,
316
+ + itip_message(
317
+ + "CANCEL",
318
+ + None,
319
+ + "SEQUENCE:2",
320
+ + f"DTSTART:{FIRST}",
321
+ + "RRULE:FREQ=DAILY;COUNT=3",
322
+ + "STATUS:CANCELLED",
323
+ + f"ATTENDEE:{BOB}",
324
+ + ),
325
+ + )
326
+ + for key in (FIRST, SECOND, THIRD):
327
+ + self.assertNotLive(self.occurrences("bob"), key)
328
+ +
329
+ + def test_cancel_this_and_future_ends_the_series_at_that_occurrence(self):
330
+ + self.put_ok("bob", series(override=False))
331
+ + self.deliver(
332
+ + BOB,
333
+ + itip_message(
334
+ + "CANCEL",
335
+ + f"RANGE=THISANDFUTURE:{SECOND}",
336
+ + "SEQUENCE:2",
337
+ + f"DTSTART:{SECOND}",
338
+ + "STATUS:CANCELLED",
339
+ + f"ATTENDEE:{BOB}",
340
+ + ),
341
+ + )
342
+ + occurrences = self.occurrences("bob")
343
+ + self.assertLive(occurrences, FIRST)
344
+ + self.assertNotLive(occurrences, SECOND)
345
+ + self.assertNotLive(occurrences, THIRD)
346
+ +
347
+ + def test_reply_about_an_occurrence_without_its_own_component(self):
348
+ + self.put_ok("alice", series(override=False, attendees=(BOB, CAROL)))
349
+ + self.deliver(
350
+ + ALICE,
351
+ + itip_message(
352
+ + "REPLY", SECOND, "SEQUENCE:1", f"ATTENDEE;PARTSTAT=DECLINED:{BOB}"
353
+ + ),
354
+ + )
355
+ + occurrences = self.occurrences("alice")
356
+ + self.assertEqual("DECLINED", occurrences[SECOND]["partstat"][BOB])
357
+ + self.assertEqual("NEEDS-ACTION", occurrences[FIRST]["partstat"][BOB])
358
+ + self.assertEqual("NEEDS-ACTION", occurrences[THIRD]["partstat"][BOB])
359
+ + self.assertEqual("NEEDS-ACTION", occurrences[SECOND]["partstat"][CAROL])
360
+ +
361
+ + def test_reply_without_a_recurrence_id_answers_for_the_series(self):
362
+ + self.put_ok("alice", series(override=False, attendees=(BOB,)))
363
+ + self.deliver(
364
+ + ALICE,
365
+ + itip_message(
366
+ + "REPLY", None, "SEQUENCE:1", f"ATTENDEE;PARTSTAT=ACCEPTED:{BOB}"
367
+ + ),
368
+ + )
369
+ + occurrences = self.occurrences("alice")
370
+ + for key in (FIRST, SECOND, THIRD):
371
+ + self.assertEqual("ACCEPTED", occurrences[key]["partstat"][BOB])
372
+ +
373
+ + def test_the_same_instant_in_another_time_zone_is_one_occurrence(self):
374
+ + self.put_ok("bob", series(override=True))
375
+ + self.deliver(
376
+ + BOB,
377
+ + itip_message(
378
+ + "CANCEL",
379
+ + SECOND_LOCAL,
380
+ + "SEQUENCE:2",
381
+ + f"DTSTART;{SECOND_LOCAL}",
382
+ + "STATUS:CANCELLED",
383
+ + f"ATTENDEE:{BOB}",
384
+ + ),
385
+ + )
386
+ + occurrences = self.occurrences("bob")
387
+ + self.assertLive(occurrences, FIRST)
388
+ + self.assertLive(occurrences, THIRD)
389
+ + self.assertNotLive(occurrences, SECOND)
390
+ +
391
+ + def test_a_request_for_one_occurrence_does_not_duplicate_it(self):
392
+ + self.put_ok("bob", series(override=True))
393
+ + self.deliver(
394
+ + BOB,
395
+ + itip_message(
396
+ + "REQUEST",
397
+ + SECOND_LOCAL,
398
+ + "SEQUENCE:2",
399
+ + f"DTSTART;{SECOND_LOCAL}",
400
+ + "DTEND;TZID=Europe/Berlin:20260602T130000",
401
+ + "SUMMARY:Standup (moved again)",
402
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
403
+ + ),
404
+ + )
405
+ + keys = [
406
+ + recurrence_key(comp)
407
+ + for comp in self.stored("bob").subcomponents
408
+ + if comp.name == "VEVENT"
409
+ + ]
410
+ + self.assertEqual(sorted(keys), sorted({"", SECOND}))
411
+ + occurrences = self.occurrences("bob")
412
+ + self.assertEqual("Standup (moved again)", occurrences[SECOND]["summary"])
413
+ + self.assertEqual("Standup", occurrences[FIRST]["summary"])
414
+ +
415
+ + # -- what goes out ----------------------------------------------------
416
+ + def test_a_delegate_is_told_about_the_delegated_occurrence_only(self):
417
+ + self.put_ok("bob", series(override=True))
418
+ + self.put_ok("bob", delegate_second_occurrence(series(override=True)))
419
+ + requests = self.inbox("dave", "REQUEST")
420
+ + self.assertEqual(1, len(requests))
421
+ + self.assertEqual(
422
+ + [SECOND],
423
+ + sorted(
424
+ + recurrence_key(comp)
425
+ + for comp in requests[0].subcomponents
426
+ + if comp.name == "VEVENT"
427
+ + ),
428
+ + )
429
+ +
430
+ + def test_a_delegation_does_not_hide_an_uninvited_occurrence(self):
431
+ + self.put_ok("bob", series(override=True))
432
+ + smuggled = (
433
+ + delegate_second_occurrence(series(override=True))
434
+ + .decode("utf-8")
435
+ + .replace(
436
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\nEND:VEVENT",
437
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\n"
438
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{DAVE}\r\nEND:VEVENT",
439
+ + 1,
440
+ + )
441
+ + .encode("utf-8")
442
+ + )
443
+ + code = self.put("/bob/calendars/calendar/event.ics", smuggled)
444
+ + self.assertEqual("412 Precondition Failed", code)
445
+ + for comp in self.stored("bob").subcomponents:
446
+ + if comp.name == "VEVENT" and recurrence_key(comp) == "":
447
+ + attendees = comp.get("ATTENDEE", [])
448
+ + if not isinstance(attendees, list):
449
+ + attendees = [attendees]
450
+ + self.assertNotIn(DAVE, [str(a) for a in attendees])
451
+ +
452
+ + def test_an_attendee_is_sent_the_occurrences_that_are_theirs(self):
453
+ + self.put_ok("alice", series(override=True, attendees=(BOB, CAROL)))
454
+ + # Carol is taken off the second occurrence only.
455
+ + head, marker, tail = (
456
+ + series(override=True, attendees=(BOB, CAROL))
457
+ + .decode("utf-8")
458
+ + .partition(f"RECURRENCE-ID:{SECOND}")
459
+ + )
460
+ + edited = (
461
+ + head
462
+ + + marker
463
+ + + tail.replace(f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{CAROL}\r\n", "", 1)
464
+ + ).encode("utf-8")
465
+ + self.put_ok("alice", edited)
466
+ + cancels = self.inbox("carol", "CANCEL")
467
+ + self.assertEqual(1, len(cancels))
468
+ + self.assertEqual(
469
+ + [SECOND],
470
+ + sorted(
471
+ + recurrence_key(comp)
472
+ + for comp in cancels[0].subcomponents
473
+ + if comp.name == "VEVENT"
474
+ + ),
475
+ + )
476
+ +
477
+ + def test_cancel_this_and_future_on_a_series_kept_in_a_time_zone(self):
478
+ + """The boundary arrives in Berlin time; the series ends at that instant.
479
+ +
480
+ + RFC 5545 §3.3.10: a series whose DTSTART carries a time zone ends on a
481
+ + UNTIL written in UTC. Left in the sender's local time it reads as a
482
+ + floating time, which is a different instant by the offset — far enough
483
+ + to leave the very occurrence the message named still happening.
484
+ + """
485
+ + self.put_ok("bob", series_in_a_time_zone())
486
+ + self.assertEqual(3, len(self.occurrences("bob")))
487
+ + self.deliver(
488
+ + BOB,
489
+ + itip_message(
490
+ + "CANCEL",
491
+ + f"RANGE=THISANDFUTURE;{SECOND_LOCAL}",
492
+ + "SEQUENCE:2",
493
+ + "STATUS:CANCELLED",
494
+ + f"ATTENDEE:{BOB}",
495
+ + ),
496
+ + )
497
+ + occurrences = self.occurrences("bob")
498
+ + self.assertLive(occurrences, FIRST)
499
+ + self.assertNotLive(occurrences, SECOND)
500
+ + self.assertNotLive(occurrences, THIRD)
501
+ + # Ending the series is one way to do it and not the only one; if this
502
+ + # is the way it was done, the UNTIL is the one RFC 5545 asks for.
503
+ + for comp in self.stored("bob").subcomponents:
504
+ + if comp.name != "VEVENT" or "RRULE" not in comp:
505
+ + continue
506
+ + for until in comp["RRULE"].get("UNTIL", []):
507
+ + self.assertIsNotNone(
508
+ + getattr(until, "tzinfo", None),
509
+ + f"a series kept in a time zone was given a floating UNTIL: {until!r}",
510
+ + )
511
+ +
512
+ + def test_a_request_for_an_instant_the_series_never_produces(self):
513
+ + """Half past eleven is not an occurrence of a series that meets at ten.
514
+ +
515
+ + A message about an occurrence we hold no component for is applied by
516
+ + breaking that occurrence out of the series. An instant the recurrence
517
+ + set does not produce has nothing to break out, and adding it would put
518
+ + a meeting nobody scheduled into the event.
519
+ + """
520
+ + self.put_ok("bob", series(override=False))
521
+ + before = self.stored("bob").to_ical()
522
+ + self.deliver(
523
+ + BOB,
524
+ + itip_message(
525
+ + "REQUEST",
526
+ + "20260602T113000Z",
527
+ + "SEQUENCE:2",
528
+ + "DTSTART:20260602T113000Z",
529
+ + "DTEND:20260602T120000Z",
530
+ + "SUMMARY:Invented",
531
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
532
+ + ),
533
+ + )
534
+ + self.assertEqual(
535
+ + [""],
536
+ + sorted(
537
+ + recurrence_key(comp)
538
+ + for comp in self.stored("bob").subcomponents
539
+ + if comp.name == "VEVENT"
540
+ + ),
541
+ + )
542
+ + self.assertEqual([FIRST, SECOND, THIRD], sorted(self.occurrences("bob")))
543
+ + self.assertEqual(before, self.stored("bob").to_ical())
544
+ +
545
+ + def test_a_re_request_in_another_time_zone_keeps_the_answer(self):
546
+ + """RFC 6638 §3.2.1: a fresh REQUEST does not throw away the answers.
547
+ +
548
+ + The organiser's client writes the second occurrence in Berlin time
549
+ + this time. It is the same occurrence, so the PARTSTAT already given
550
+ + for it is the PARTSTAT it keeps.
551
+ + """
552
+ + self.put_ok("bob", series(override=True))
553
+ + self.deliver(
554
+ + BOB,
555
+ + itip_message(
556
+ + "REPLY", SECOND, "SEQUENCE:1", f"ATTENDEE;PARTSTAT=ACCEPTED:{BOB}"
557
+ + ),
558
+ + )
559
+ + self.assertEqual("ACCEPTED", self.occurrences("bob")[SECOND]["partstat"][BOB])
560
+ + self.deliver(
561
+ + BOB,
562
+ + itip_message(
563
+ + "REQUEST",
564
+ + SECOND_LOCAL,
565
+ + "SEQUENCE:3",
566
+ + f"DTSTART;{SECOND_LOCAL}",
567
+ + "DTEND;TZID=Europe/Berlin:20260602T133000",
568
+ + "SUMMARY:Standup (later)",
569
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
570
+ + ),
571
+ + )
572
+ + occurrences = self.occurrences("bob")
573
+ + self.assertEqual("Standup (later)", occurrences[SECOND]["summary"])
574
+ + self.assertEqual("ACCEPTED", occurrences[SECOND]["partstat"][BOB])
575
+ +
576
+ + def test_an_occurrence_the_series_names_outright_is_still_the_series(self):
577
+ + """Refusing to invent an occurrence is not refusing to keep one.
578
+ +
579
+ + A date named on RDATE is in the recurrence set (RFC 5545 §3.8.5.2),
580
+ + and an object that holds occurrences and no series at all has no
581
+ + recurrence set to be judged against. Neither is an invented occurrence.
582
+ + """
583
+ + lines = (
584
+ + series(override=False)
585
+ + .decode("utf-8")
586
+ + .replace("RRULE:FREQ=DAILY;COUNT=3\r\n", f"RDATE:{SECOND},{THIRD}\r\n", 1)
587
+ + )
588
+ + self.put_ok("bob", lines.encode("utf-8"))
589
+ + self.deliver(
590
+ + BOB,
591
+ + itip_message(
592
+ + "REQUEST",
593
+ + SECOND,
594
+ + "SEQUENCE:2",
595
+ + f"DTSTART:{SECOND}",
596
+ + "DTEND:20260602T113000Z",
597
+ + "SUMMARY:Standup (moved)",
598
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
599
+ + ),
600
+ + )
601
+ + self.assertEqual(
602
+ + ["", SECOND],
603
+ + sorted(
604
+ + recurrence_key(comp)
605
+ + for comp in self.stored("bob").subcomponents
606
+ + if comp.name == "VEVENT"
607
+ + ),
608
+ + )
609
+ +
610
+ + # An object built out of a message about one occurrence: no series.
611
+ + self.deliver(
612
+ + CAROL,
613
+ + itip_message(
614
+ + "REQUEST",
615
+ + SECOND,
616
+ + "SEQUENCE:1",
617
+ + f"DTSTART:{SECOND}",
618
+ + "DTEND:20260602T110000Z",
619
+ + "SUMMARY:Standup",
620
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{CAROL}",
621
+ + ),
622
+ + )
623
+ + self.deliver(
624
+ + CAROL,
625
+ + itip_message(
626
+ + "REQUEST",
627
+ + THIRD,
628
+ + "SEQUENCE:1",
629
+ + f"DTSTART:{THIRD}",
630
+ + "DTEND:20260603T110000Z",
631
+ + "SUMMARY:Standup",
632
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{CAROL}",
633
+ + ),
634
+ + )
635
+ + self.assertEqual(
636
+ + [SECOND, THIRD],
637
+ + sorted(
638
+ + recurrence_key(comp)
639
+ + for comp in self.stored("carol").subcomponents
640
+ + if comp.name == "VEVENT"
641
+ + ),
642
+ + )
643
+ +
644
+ + def test_an_attendee_is_invited_to_the_occurrences_that_are_theirs(self):
645
+ + """Carol is on the second occurrence only, and is sent that one."""
646
+ + head, marker, tail = (
647
+ + series(override=True, attendees=(BOB,))
648
+ + .decode("utf-8")
649
+ + .partition(f"RECURRENCE-ID:{SECOND}")
650
+ + )
651
+ + invited = (
652
+ + head
653
+ + + marker
654
+ + + tail.replace(
655
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\n",
656
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\n"
657
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{CAROL}\r\n",
658
+ + 1,
659
+ + )
660
+ + ).encode("utf-8")
661
+ + self.put_ok("alice", invited)
662
+ + requests = self.inbox("carol", "REQUEST")
663
+ + self.assertEqual(1, len(requests))
664
+ + self.assertEqual(
665
+ + [SECOND],
666
+ + sorted(
667
+ + recurrence_key(comp)
668
+ + for comp in requests[0].subcomponents
669
+ + if comp.name == "VEVENT"
670
+ + ),
671
+ + )
672
+ +
673
+ + # -- from one occurrence onwards: a revision and an answer --------------
674
+ + def _starts(self, principal: str) -> dict:
675
+ + expanded = expand_calendar_rrule(self.stored(principal), *WINDOW)
676
+ + out = {}
677
+ + for comp in expanded.subcomponents:
678
+ + if comp.name == "VEVENT":
679
+ + value = comp["DTSTART"].dt.astimezone(datetime.timezone.utc)
680
+ + out[recurrence_key(comp)] = value.strftime("%Y%m%dT%H%M%SZ")
681
+ + return out
682
+ +
683
+ + def test_a_revision_from_one_occurrence_onwards(self):
684
+ + self.put_ok("bob", series(override=False))
685
+ + self.deliver(
686
+ + BOB,
687
+ + itip_message(
688
+ + "REQUEST",
689
+ + f"RANGE=THISANDFUTURE:{SECOND}",
690
+ + "SEQUENCE:2",
691
+ + "DTSTART:20260602T103000Z",
692
+ + "DTEND:20260602T113000Z",
693
+ + "SUMMARY:Standup (upstairs)",
694
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
695
+ + ),
696
+ + )
697
+ + occurrences = self.occurrences("bob")
698
+ + self.assertEqual("Standup", occurrences[FIRST]["summary"])
699
+ + self.assertEqual("Standup (upstairs)", occurrences[SECOND]["summary"])
700
+ + self.assertEqual("Standup (upstairs)", occurrences[THIRD]["summary"])
701
+ + starts = self._starts("bob")
702
+ + self.assertEqual(FIRST, starts[FIRST])
703
+ + self.assertEqual("20260602T103000Z", starts[SECOND])
704
+ + self.assertEqual("20260603T103000Z", starts[THIRD])
705
+ +
706
+ + def test_a_revision_onwards_on_an_open_ended_series(self):
707
+ + self.put_ok(
708
+ + "bob",
709
+ + series(override=False).replace(
710
+ + b"RRULE:FREQ=DAILY;COUNT=3", b"RRULE:FREQ=DAILY"
711
+ + ),
712
+ + )
713
+ + self.deliver(
714
+ + BOB,
715
+ + itip_message(
716
+ + "REQUEST",
717
+ + f"RANGE=THISANDFUTURE:{SECOND}",
718
+ + "SEQUENCE:2",
719
+ + f"DTSTART:{SECOND}",
720
+ + "DTEND:20260602T110000Z",
721
+ + "SUMMARY:Standup (upstairs)",
722
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}",
723
+ + ),
724
+ + )
725
+ + occurrences = self.occurrences("bob")
726
+ + self.assertEqual("Standup", occurrences[FIRST]["summary"])
727
+ + self.assertEqual("Standup (upstairs)", occurrences["20260630T100000Z"]["summary"])
728
+ +
729
+ + def test_an_answer_from_one_occurrence_onwards(self):
730
+ + self.put_ok("alice", series(override=True, attendees=(BOB, CAROL)))
731
+ + self.deliver(
732
+ + ALICE,
733
+ + itip_message(
734
+ + "REPLY",
735
+ + f"RANGE=THISANDFUTURE:{SECOND}",
736
+ + "SEQUENCE:1",
737
+ + f"ATTENDEE;PARTSTAT=TENTATIVE:{BOB}",
738
+ + ),
739
+ + )
740
+ + occurrences = self.occurrences("alice")
741
+ + self.assertEqual("NEEDS-ACTION", occurrences[FIRST]["partstat"][BOB])
742
+ + self.assertEqual("TENTATIVE", occurrences[SECOND]["partstat"][BOB])
743
+ + self.assertEqual("TENTATIVE", occurrences[THIRD]["partstat"][BOB])
744
+ + # the occurrence kept as its own exception is still that occurrence
745
+ + self.assertEqual("Standup (moved)", occurrences[SECOND]["summary"])
746
+ + self.assertEqual("Standup", occurrences[THIRD]["summary"])
747
+ + for key in (FIRST, SECOND, THIRD):
748
+ + self.assertEqual("NEEDS-ACTION", occurrences[key]["partstat"][CAROL])
749
+ +
750
+ + def test_an_answer_onwards_after_a_revision_onwards(self):
751
+ + self.put_ok("alice", series(override=False, attendees=(BOB,)))
752
+ + stored = self.stored("alice").to_ical().decode("utf-8")
753
+ + # Alice's own copy after she moved the series upstairs from Tuesday on.
754
+ + revised = stored.replace(
755
+ + "END:VCALENDAR",
756
+ + "BEGIN:VEVENT\r\nUID:rec@example.com\r\nDTSTAMP:20260101T120000Z\r\n"
757
+ + f"SEQUENCE:2\r\nRECURRENCE-ID;RANGE=THISANDFUTURE:{SECOND}\r\n"
758
+ + f"DTSTART:{SECOND}\r\nDTEND:20260602T110000Z\r\n"
759
+ + f"SUMMARY:Standup (upstairs)\r\nORGANIZER:{ALICE}\r\n"
760
+ + f"ATTENDEE;PARTSTAT=NEEDS-ACTION:{BOB}\r\nEND:VEVENT\r\nEND:VCALENDAR",
761
+ + )
762
+ + self.put_ok("alice", revised.encode("utf-8"))
763
+ + self.deliver(
764
+ + ALICE,
765
+ + itip_message(
766
+ + "REPLY",
767
+ + f"RANGE=THISANDFUTURE:{THIRD}",
768
+ + "SEQUENCE:2",
769
+ + f"ATTENDEE;PARTSTAT=DECLINED:{BOB}",
770
+ + ),
771
+ + )
772
+ + occurrences = self.occurrences("alice")
773
+ + self.assertEqual("NEEDS-ACTION", occurrences[SECOND]["partstat"][BOB])
774
+ + self.assertEqual("DECLINED", occurrences[THIRD]["partstat"][BOB])
775
+ + self.assertEqual("Standup (upstairs)", occurrences[THIRD]["summary"])
776
+ +
777
+ +
778
+ +if __name__ == "__main__":
779
+ + unittest.main()
780
+ diff --git a/xandikos/icalendar.py b/xandikos/icalendar.py
781
+ index 3bc8aea..d3c8e03 100644
782
+ --- a/xandikos/icalendar.py
783
+ +++ b/xandikos/icalendar.py
784
+ @@ -2183,7 +2183,17 @@ def _expand_rrule_component(
785
+ start: datetime | None = None,
786
+ end: datetime | None = None,
787
+ existing: dict[str | date | datetime, Component] = {},
788
+ + onwards: "list[tuple[date | datetime, Component]] | None" = None,
789
+ ) -> Iterable[Component]:
790
+ + """Yield the occurrences of *incomp*'s recurrence set.
791
+ +
792
+ + *existing* maps normalised RECURRENCE-IDs to the exception components
793
+ + that replace an occurrence outright; each one is popped as it is used.
794
+ + *onwards* lists, in order, the exceptions marked
795
+ + ``RECURRENCE-ID;RANGE=THISANDFUTURE`` (RFC 5545 §3.8.4.4): such an
796
+ + exception also stands for every later occurrence that has no exception
797
+ + of its own, shifted by however far it moved its own start.
798
+ + """
799
+ if "RRULE" not in incomp:
800
+ return
801
+ if "DTSTART" not in incomp:
802
+ @@ -2258,6 +2268,12 @@ def _expand_rrule_component(
803
+ try:
804
+ outcomp = existing.pop(ts_normalized)
805
+ except KeyError:
806
+ + outcomp = None
807
+ + if outcomp is None:
808
+ + governing = _governing_onwards(onwards, ts_normalized)
809
+ + if governing is not None:
810
+ + outcomp = _occurrence_from_onwards(governing, ts_for_dtstart)
811
+ + if outcomp is None:
812
+ # Create new occurrence
813
+ outcomp = base_comp.copy()
814
+
815
+ @@ -2302,6 +2318,74 @@ def _expand_rrule_component(
816
+ yield outcomp
817
+
818
+
819
+ +def _is_onwards(comp: Component) -> bool:
820
+ + """True if *comp*'s RECURRENCE-ID carries RANGE=THISANDFUTURE."""
821
+ + rid = comp.get("RECURRENCE-ID")
822
+ + params = getattr(rid, "params", None) or {}
823
+ + rng = params.get("RANGE")
824
+ + return rng is not None and str(rng).upper() == "THISANDFUTURE"
825
+ +
826
+ +
827
+ +def _governing_onwards(
828
+ + onwards: "list[tuple[date | datetime, Component]] | None",
829
+ + ts_normalized: date | datetime,
830
+ +) -> "Component | None":
831
+ + """Return the latest THISANDFUTURE exception that starts before *ts*."""
832
+ + found = None
833
+ + for moment, comp in onwards or ():
834
+ + try:
835
+ + if moment < ts_normalized:
836
+ + found = comp
837
+ + except TypeError:
838
+ + # A date against a date-time: not the same recurrence set.
839
+ + continue
840
+ + return found
841
+ +
842
+ +
843
+ +def _occurrence_from_onwards(
844
+ + governing: Component, ts_for_dtstart: date | datetime
845
+ +) -> Component:
846
+ + """Derive the occurrence at *ts_for_dtstart* from a THISANDFUTURE exception.
847
+ +
848
+ + RFC 5545 §3.8.4.4: the exception's properties hold for the later
849
+ + occurrences too, and if it moved its own start, every later occurrence
850
+ + moves by the same amount and keeps the exception's length.
851
+ + """
852
+ + outcomp = governing.copy()
853
+ + rid = governing["RECURRENCE-ID"].dt
854
+ + own_start_prop = governing.get("DTSTART")
855
+ + own_start = getattr(own_start_prop, "dt", None)
856
+ + shift = timedelta(0)
857
+ + if own_start is not None and type(own_start) is type(rid):
858
+ + try:
859
+ + shift = own_start - rid
860
+ + except TypeError:
861
+ + # One side floating, the other zoned: no instant to measure by.
862
+ + shift = timedelta(0)
863
+ + new_start = ts_for_dtstart + shift
864
+ + if (
865
+ + isinstance(new_start, datetime)
866
+ + and isinstance(own_start, datetime)
867
+ + and new_start.tzinfo is not None
868
+ + and own_start.tzinfo is not None
869
+ + ):
870
+ + new_start = new_start.astimezone(own_start.tzinfo)
871
+ + new_dtstart = create_prop_from_date_or_datetime(new_start)
872
+ + params = getattr(own_start_prop, "params", None)
873
+ + if params:
874
+ + new_dtstart.params = params.copy()
875
+ + outcomp["DTSTART"] = new_dtstart
876
+ + for end_prop in ("DTEND", "DUE"):
877
+ + if end_prop in governing and own_start is not None:
878
+ + length = governing[end_prop].dt - own_start
879
+ + new_end = create_prop_from_date_or_datetime(new_start + length)
880
+ + end_params = getattr(governing[end_prop], "params", None)
881
+ + if end_params:
882
+ + new_end.params = end_params.copy()
883
+ + outcomp[end_prop] = new_end
884
+ + return outcomp
885
+ +
886
+ +
887
+ def expand_calendar_rrule(
888
+ incal: Calendar, start: datetime | None = None, end: datetime | None = None
889
+ ) -> Calendar:
890
+ @@ -2322,6 +2406,12 @@ def expand_calendar_rrule(
891
+ assert isinstance(rec_id.dt, date | datetime)
892
+ ts = asutc(rec_id.dt)
893
+ exceptions[ts] = comp
894
+ + # Exceptions that speak for the rest of the series as well as their own
895
+ + # occurrence, earliest first.
896
+ + onwards = sorted(
897
+ + ((ts, comp) for ts, comp in exceptions.items() if _is_onwards(comp)),
898
+ + key=lambda item: (isinstance(item[0], datetime), str(item[0])),
899
+ + )
900
+
901
+ # Process all components
902
+ for comp in incal.subcomponents:
903
+ @@ -2333,7 +2423,9 @@ def expand_calendar_rrule(
904
+ pass
905
+ elif "RRULE" in comp:
906
+ # Expand recurring events
907
+ - for expanded in _expand_rrule_component(comp, start, end, exceptions):
908
+ + for expanded in _expand_rrule_component(
909
+ + comp, start, end, exceptions, onwards
910
+ + ):
911
+ outcal.add_component(expanded)
912
+ else:
913
+ # Include non-recurring events
914
+ diff --git a/xandikos/itip.py b/xandikos/itip.py
915
+ index 83e3851..71b070e 100644
916
+ --- a/xandikos/itip.py
917
+ +++ b/xandikos/itip.py
918
+ @@ -26,6 +26,7 @@ signature from iTIP-relevant properties — separately from the CalDAV
919
+ plumbing in :mod:`xandikos.scheduling` that exposes them over HTTP.
920
+ """
921
+
922
+ +import copy
923
+ import datetime
924
+ import hashlib
925
+
926
+ @@ -454,20 +455,400 @@ def strip_method(itip_message: Calendar) -> Calendar:
927
+ return out
928
+
929
+
930
+ +def recurrence_key(comp: Component) -> str:
931
+ + """Return a stable name for the occurrence *comp* speaks about.
932
+ +
933
+ + RECURRENCE-ID (RFC 5545 §3.8.4.4) names one occurrence of a recurring
934
+ + event by its original start, and the same instant has more than one
935
+ + written form: ``20260602T100000Z``, ``TZID=Europe/Berlin:20260602T120000``
936
+ + and ``TZID=UTC:20260602T100000`` are one occurrence between them. Keying
937
+ + on the text would make them three, so the key comes from the parsed
938
+ + value. The series' own component carries no RECURRENCE-ID and keys as
939
+ + the empty string.
940
+ + """
941
+ + rid = comp.get("RECURRENCE-ID")
942
+ + if rid is None:
943
+ + return ""
944
+ + return _instant_key(rid)
945
+ +
946
+ +
947
+ +def _instant_key(prop: PropTypes) -> str:
948
+ + """Key one date-time property by the instant it denotes."""
949
+ + dt = getattr(prop, "dt", None)
950
+ + if isinstance(dt, datetime.datetime):
951
+ + if dt.tzinfo is not None:
952
+ + dt = dt.astimezone(datetime.timezone.utc)
953
+ + return dt.strftime("%Y%m%dT%H%M%SZ")
954
+ + # A floating time has no instant until a time zone is chosen; it can
955
+ + # only be the same occurrence as another floating time.
956
+ + return dt.strftime("%Y%m%dT%H%M%S")
957
+ + if isinstance(dt, datetime.date):
958
+ + return dt.strftime("%Y%m%d")
959
+ + rendered = prop.to_ical()
960
+ + return rendered.decode("utf-8") if isinstance(rendered, bytes) else str(rendered)
961
+ +
962
+ +
963
+ +def itip_occurrences(
964
+ + itip_message: Component, uid: str
965
+ +) -> "dict[str, PropTypes | None]":
966
+ + """Map occurrence key -> its RECURRENCE-ID property, for *uid* in a message.
967
+ +
968
+ + The series' own component maps to None. Used to decide which components
969
+ + of a stored object a message speaks about, and — for keys the stored
970
+ + object has no component for — to break the occurrence out.
971
+ + """
972
+ + out: dict[str, PropTypes | None] = {}
973
+ + for comp in itip_message.subcomponents:
974
+ + if comp.name not in SCHEDULING_COMPONENTS:
975
+ + continue
976
+ + if str(comp.get("UID", "")) != uid:
977
+ + continue
978
+ + rid = comp.get("RECURRENCE-ID")
979
+ + out[recurrence_key(comp)] = rid
980
+ + return out
981
+ +
982
+ +
983
+ +def covers_series(itip_message: Component, uid: str) -> bool:
984
+ + """True if *itip_message* carries the series itself, not single occurrences."""
985
+ + return "" in itip_occurrences(itip_message, uid)
986
+ +
987
+ +
988
+ +def occurrences_for_attendee(cal: Component, address: str) -> "set[str]":
989
+ + """Occurrence keys of *cal* on which *address* is an ATTENDEE."""
990
+ + found: set[str] = set()
991
+ + for comp in cal.subcomponents:
992
+ + if comp.name not in SCHEDULING_COMPONENTS:
993
+ + continue
994
+ + if _find_attendee(comp, address) is not None:
995
+ + found.add(recurrence_key(comp))
996
+ + return found
997
+ +
998
+ +
999
+ +def narrow_to_occurrences(cal: Component, keys: "set[str]") -> Calendar:
1000
+ + """Return a copy of *cal* carrying only the occurrences in *keys*.
1001
+ +
1002
+ + Non-scheduling components (VTIMEZONE and friends) are kept, so the
1003
+ + result is still a self-contained calendar object.
1004
+ + """
1005
+ + out = Calendar()
1006
+ + for field in cal:
1007
+ + out[field] = cal[field]
1008
+ + for comp in cal.subcomponents:
1009
+ + if comp.name not in SCHEDULING_COMPONENTS or recurrence_key(comp) in keys:
1010
+ + out.add_component(comp.copy())
1011
+ + return out
1012
+ +
1013
+ +
1014
+ +def series_produces(cal: Calendar, uid: str, rid: PropTypes) -> bool:
1015
+ + """True if *uid*'s recurrence set in *cal* produces the occurrence *rid*.
1016
+ +
1017
+ + The question a message about a single occurrence raises before anything
1018
+ + else: an occurrence the series does produce is ours to apply the message
1019
+ + to, whether or not we keep a component for it, and an instant the series
1020
+ + never produces is not ours to invent.
1021
+ + """
1022
+ + if _expand_occurrence(cal, uid, rid) is not None:
1023
+ + return True
1024
+ + return _named_by_a_recurrence_date(cal, uid, rid)
1025
+ +
1026
+ +
1027
+ +def _named_by_a_recurrence_date(cal: Calendar, uid: str, rid: PropTypes) -> bool:
1028
+ + """True if the series names *rid* outright on an RDATE and does not exclude it.
1029
+ +
1030
+ + RFC 5545 §3.8.5.2: a date named on RDATE is in the recurrence set as much
1031
+ + as one the rule produces. It is asked here rather than left to the
1032
+ + expansion because the expansion works from the rule.
1033
+ + """
1034
+ + wanted = _instant_key(rid)
1035
+ + for comp in cal.subcomponents:
1036
+ + if comp.name not in SCHEDULING_COMPONENTS:
1037
+ + continue
1038
+ + if str(comp.get("UID", "")) != uid or "RECURRENCE-ID" in comp:
1039
+ + continue
1040
+ + if wanted in _dates_named(comp, "EXDATE"):
1041
+ + return False
1042
+ + if wanted in _dates_named(comp, "RDATE"):
1043
+ + return True
1044
+ + return False
1045
+ +
1046
+ +
1047
+ +def _dates_named(comp: Component, field: str) -> "set[str]":
1048
+ + """The instants *field* names on *comp*, keyed the way occurrences are."""
1049
+ + out: set[str] = set()
1050
+ + value = comp.get(field)
1051
+ + if value is None:
1052
+ + return out
1053
+ + for entry in value if isinstance(value, list) else [value]:
1054
+ + for item in getattr(entry, "dts", None) or []:
1055
+ + out.add(_instant_key(item))
1056
+ + return out
1057
+ +
1058
+ +
1059
+ +def materialise_occurrence(
1060
+ + cal: Calendar, uid: str, rid: PropTypes
1061
+ +) -> "Component | None":
1062
+ + """Break the occurrence *rid* out of *uid*'s series as its own component.
1063
+ +
1064
+ + A scheduling message may speak about an occurrence the stored object
1065
+ + never needed a component for: the organiser never moved it, so it lives
1066
+ + inside the series' RRULE. Applying the message to that occurrence alone
1067
+ + means giving it the exception component RFC 5545 §3.8.4.4 describes,
1068
+ + derived from the series exactly as an expansion would derive it.
1069
+ +
1070
+ + Returns the new component, already added to *cal*, or None if the
1071
+ + recurrence set holds no such occurrence (an occurrence that is not in
1072
+ + the series is not ours to invent).
1073
+ + """
1074
+ + occurrence = _expand_occurrence(cal, uid, rid)
1075
+ + if occurrence is None:
1076
+ + return None
1077
+ + # A deep copy: the expansion hands back property objects the series
1078
+ + # still holds, and an exception that shares its ATTENDEE entries with
1079
+ + # the series would carry every answer back into it.
1080
+ + broken_out = copy.deepcopy(occurrence)
1081
+ + # The exception describes one occurrence; the recurrence rules stay
1082
+ + # with the series.
1083
+ + for field in ("RRULE", "EXRULE", "RDATE", "EXDATE"):
1084
+ + if field in broken_out:
1085
+ + del broken_out[field]
1086
+ + cal.add_component(broken_out)
1087
+ + return broken_out
1088
+ +
1089
+ +
1090
+ +def _expand_occurrence(cal: Calendar, uid: str, rid: PropTypes) -> "Component | None":
1091
+ + """Return the occurrence *rid* as *uid*'s series produces it, or None.
1092
+ +
1093
+ + Reads the stored object; writes nothing to it.
1094
+ + """
1095
+ + from xandikos.icalendar import expand_calendar_rrule
1096
+ +
1097
+ + master = None
1098
+ + for comp in cal.subcomponents:
1099
+ + if (
1100
+ + comp.name in SCHEDULING_COMPONENTS
1101
+ + and str(comp.get("UID", "")) == uid
1102
+ + and "RECURRENCE-ID" not in comp
1103
+ + ):
1104
+ + master = comp
1105
+ + break
1106
+ + if master is None or "RRULE" not in master:
1107
+ + return None
1108
+ +
1109
+ + target = getattr(rid, "dt", None)
1110
+ + if isinstance(target, datetime.datetime):
1111
+ + moment = target
1112
+ + elif isinstance(target, datetime.date):
1113
+ + moment = datetime.datetime.combine(target, datetime.time())
1114
+ + else:
1115
+ + return None
1116
+ + if moment.tzinfo is None:
1117
+ + moment = moment.replace(tzinfo=datetime.timezone.utc)
1118
+ + window = datetime.timedelta(days=1)
1119
+ +
1120
+ + # The series, and the exceptions that speak for the rest of it from their
1121
+ + # own occurrence on (RANGE=THISANDFUTURE): an occurrence after one of
1122
+ + # those is what that exception made of it, not what the rule alone says.
1123
+ + # Deep copies — the expansion rewrites the RECURRENCE-IDs it hands back.
1124
+ + probe = Calendar()
1125
+ + probe.add_component(copy.deepcopy(master))
1126
+ + for comp in cal.subcomponents:
1127
+ + if (
1128
+ + comp.name in SCHEDULING_COMPONENTS
1129
+ + and str(comp.get("UID", "")) == uid
1130
+ + and _speaks_onwards(comp)
1131
+ + ):
1132
+ + probe.add_component(copy.deepcopy(comp))
1133
+ + wanted = _instant_key(rid)
1134
+ + for occurrence in expand_calendar_rrule(
1135
+ + probe, moment - window, moment + window
1136
+ + ).subcomponents:
1137
+ + if occurrence.name not in SCHEDULING_COMPONENTS:
1138
+ + continue
1139
+ + if recurrence_key(occurrence) != wanted:
1140
+ + continue
1141
+ + return occurrence
1142
+ + return None
1143
+ +
1144
+ +
1145
+ +def _speaks_onwards(comp: Component) -> bool:
1146
+ + """True if *comp*'s RECURRENCE-ID carries RANGE=THISANDFUTURE."""
1147
+ + rid = comp.get("RECURRENCE-ID")
1148
+ + if rid is None:
1149
+ + return False
1150
+ + rng = rid.params.get("RANGE")
1151
+ + return rng is not None and str(rng).upper() == "THISANDFUTURE"
1152
+ +
1153
+ +
1154
+ +def onwards_targets(cal: Calendar, uid: str, rid: PropTypes) -> "list[Component]":
1155
+ + """Return the components that speak for *rid* and every later occurrence.
1156
+ +
1157
+ + That is every component *cal* already keeps for an occurrence at or after
1158
+ + *rid*, and one more: the first occurrence from *rid* on that has no
1159
+ + component of its own is broken out of the series and marked
1160
+ + RANGE=THISANDFUTURE (RFC 5545 §3.8.4.4), so that what is applied to it
1161
+ + holds for the occurrences after it too — including the ones an open-ended
1162
+ + rule has not produced yet. An occurrence we keep as its own exception
1163
+ + stays that occurrence's own and is returned among the rest. Returns an
1164
+ + empty list when *uid* has nothing at or after *rid*.
1165
+ + """
1166
+ + boundary = _as_instant(rid)
1167
+ + if boundary is None:
1168
+ + return []
1169
+ + targets: list[Component] = []
1170
+ + held: set[str] = set()
1171
+ + master = None
1172
+ + for comp in cal.subcomponents:
1173
+ + if comp.name not in SCHEDULING_COMPONENTS:
1174
+ + continue
1175
+ + if str(comp.get("UID", "")) != uid:
1176
+ + continue
1177
+ + if "RECURRENCE-ID" not in comp:
1178
+ + master = comp
1179
+ + continue
1180
+ + held.add(recurrence_key(comp))
1181
+ + own = _as_instant(comp.get("RECURRENCE-ID"))
1182
+ + if own is not None and own >= boundary:
1183
+ + targets.append(comp)
1184
+ + if master is None or "RRULE" not in master:
1185
+ + return targets
1186
+ + from xandikos.icalendar import rruleset_from_comp, _normalize_dt_for_rrule
1187
+ +
1188
+ + start = getattr(master.get("DTSTART"), "dt", None)
1189
+ + if start is None:
1190
+ + return targets
1191
+ + rules = rruleset_from_comp(master)
1192
+ + moment = rid.dt if isinstance(rid.dt, datetime.datetime) else boundary
1193
+ + probe = _normalize_dt_for_rrule(moment, start)
1194
+ + for occurrence in rules.xafter(probe, count=len(held) + 2, inc=True):
1195
+ + value = occurrence if isinstance(start, datetime.datetime) else occurrence.date()
1196
+ + name = _instant_key(vDDDTypes(value))
1197
+ + if name in held:
1198
+ + continue
1199
+ + broken_out = materialise_occurrence(cal, uid, vDDDTypes(value))
1200
+ + if broken_out is not None:
1201
+ + broken_out["RECURRENCE-ID"].params["RANGE"] = "THISANDFUTURE"
1202
+ + targets.append(broken_out)
1203
+ + break
1204
+ + return targets
1205
+ +
1206
+ +
1207
+ +def thisandfuture_occurrence(itip_message: Component, uid: str) -> "PropTypes | None":
1208
+ + """Return the RECURRENCE-ID a message marks as standing for the tail.
1209
+ +
1210
+ + RFC 5545 §3.2.13: ``RECURRENCE-ID;RANGE=THISANDFUTURE`` names the
1211
+ + occurrence it carries *and every later one*, so a message that uses it
1212
+ + speaks about a stretch of the series rather than a single occurrence.
1213
+ + Returns that property, or None when no component uses the parameter.
1214
+ + """
1215
+ + for comp in itip_message.subcomponents:
1216
+ + if comp.name not in SCHEDULING_COMPONENTS:
1217
+ + continue
1218
+ + if str(comp.get("UID", "")) != uid:
1219
+ + continue
1220
+ + rid = comp.get("RECURRENCE-ID")
1221
+ + if rid is None:
1222
+ + continue
1223
+ + rng = rid.params.get("RANGE")
1224
+ + if rng is not None and str(rng).upper() == "THISANDFUTURE":
1225
+ + return rid
1226
+ + return None
1227
+ +
1228
+ +
1229
+ +def end_series_at(cal: Calendar, uid: str, rid: PropTypes) -> bool:
1230
+ + """Stop *uid*'s series just before *rid*, and cancel later exceptions.
1231
+ +
1232
+ + The occurrences from *rid* onwards stop happening: the recurrence rule
1233
+ + is given an UNTIL that lands before them, and any exception component
1234
+ + already broken out at or after that instant is marked CANCELLED. What
1235
+ + came before is left exactly as it was. Returns False when there is
1236
+ + nothing of *uid* to do this to.
1237
+ + """
1238
+ + boundary = _as_instant(rid)
1239
+ + if boundary is None:
1240
+ + return False
1241
+ + touched = False
1242
+ + for comp in cal.subcomponents:
1243
+ + if comp.name not in SCHEDULING_COMPONENTS:
1244
+ + continue
1245
+ + if str(comp.get("UID", "")) != uid:
1246
+ + continue
1247
+ + own = (
1248
+ + _as_instant(comp.get("RECURRENCE-ID")) if "RECURRENCE-ID" in comp else None
1249
+ + )
1250
+ + if own is not None:
1251
+ + if own >= boundary:
1252
+ + comp["STATUS"] = "CANCELLED"
1253
+ + touched = True
1254
+ + continue
1255
+ + if "RRULE" in comp:
1256
+ + rrule = comp["RRULE"]
1257
+ + last = _until_beside(
1258
+ + boundary - datetime.timedelta(seconds=1), comp.get("DTSTART")
1259
+ + )
1260
+ + try:
1261
+ + del rrule["COUNT"]
1262
+ + except KeyError:
1263
+ + pass
1264
+ + # COUNT and UNTIL cannot both be present (RFC 5545 §3.3.10).
1265
+ + rrule["UNTIL"] = [last]
1266
+ + comp["RRULE"] = rrule
1267
+ + touched = True
1268
+ + else:
1269
+ + own_start = _as_instant(comp.get("DTSTART"))
1270
+ + if own_start is not None and own_start >= boundary:
1271
+ + comp["STATUS"] = "CANCELLED"
1272
+ + touched = True
1273
+ + return touched
1274
+ +
1275
+ +
1276
+ +def _until_beside(moment: datetime.datetime, start: "PropTypes | None"):
1277
+ + """Write *moment* the way an UNTIL beside this DTSTART has to be written.
1278
+ +
1279
+ + RFC 5545 §3.3.10: UNTIL takes the value type of DTSTART, and it is a UTC
1280
+ + date-time whenever DTSTART is one or carries a time zone. The boundary
1281
+ + arrives written in whatever zone the sender chose, which is the same
1282
+ + instant as ours written differently — so it is converted, not copied. A
1283
+ + local time written without its zone is a different instant for every
1284
+ + reader, and the occurrence that instant lands on is off by the offset.
1285
+ + """
1286
+ + dt = getattr(start, "dt", None)
1287
+ + if isinstance(dt, datetime.datetime):
1288
+ + moment = moment.astimezone(datetime.timezone.utc)
1289
+ + # A floating DTSTART has no zone to be an offset from; its UNTIL
1290
+ + # floats with it.
1291
+ + return moment if dt.tzinfo is not None else moment.replace(tzinfo=None)
1292
+ + if isinstance(dt, datetime.date):
1293
+ + return moment.astimezone(datetime.timezone.utc).date()
1294
+ + return moment
1295
+ +
1296
+ +
1297
+ +def _as_instant(prop: "PropTypes | None") -> "datetime.datetime | None":
1298
+ + """Return *prop*'s value as a comparable instant, or None."""
1299
+ + dt = getattr(prop, "dt", None)
1300
+ + if isinstance(dt, datetime.datetime):
1301
+ + return dt if dt.tzinfo is not None else dt.replace(tzinfo=datetime.timezone.utc)
1302
+ + if isinstance(dt, datetime.date):
1303
+ + return datetime.datetime.combine(dt, datetime.time(), datetime.timezone.utc)
1304
+ + return None
1305
+ +
1306
+ +
1307
+ def preserve_partstats(existing: Calendar, incoming: Calendar) -> Calendar:
1308
+ """Mutate *incoming* in place so attendee PARTSTATs survive a re-REQUEST.
1309
+
1310
+ RFC 6638 §3.2.1: when an organiser sends a fresh REQUEST, the
1311
+ attendee's prior PARTSTAT must survive. We match attendees across
1312
+ - components by (UID, RECURRENCE-ID, ATTENDEE address). Returns the
1313
+ - same *incoming* object for chaining.
1314
+ + components by (UID, occurrence, ATTENDEE address) — by the occurrence
1315
+ + itself, not by the text that wrote it, or the same occurrence named in
1316
+ + the sender's own time zone would look like a new one and the answer
1317
+ + already given for it would be thrown away. Returns the same *incoming*
1318
+ + object for chaining.
1319
+ """
1320
+ existing_partstats: dict[tuple[str, str, str], str] = {}
1321
+ for comp in existing.subcomponents:
1322
+ if comp.name not in SCHEDULING_COMPONENTS:
1323
+ continue
1324
+ uid = str(comp.get("UID", ""))
1325
+ - rid = str(comp.get("RECURRENCE-ID", ""))
1326
+ + rid = recurrence_key(comp)
1327
+ attendees = comp.get("ATTENDEE", [])
1328
+ if not isinstance(attendees, list):
1329
+ attendees = [attendees]
1330
+ @@ -480,7 +861,7 @@ def preserve_partstats(existing: Calendar, incoming: Calendar) -> Calendar:
1331
+ if comp.name not in SCHEDULING_COMPONENTS:
1332
+ continue
1333
+ uid = str(comp.get("UID", ""))
1334
+ - rid = str(comp.get("RECURRENCE-ID", ""))
1335
+ + rid = recurrence_key(comp)
1336
+ attendees = comp.get("ATTENDEE", [])
1337
+ if not isinstance(attendees, list):
1338
+ attendees = [attendees]
1339
+ diff --git a/xandikos/web.py b/xandikos/web.py
1340
+ index 8b148f8..2ce619d 100644
1341
+ --- a/xandikos/web.py
1342
+ +++ b/xandikos/web.py
1343
+ @@ -86,7 +86,7 @@ from xandikos.store import (
1344
+ Store,
1345
+ )
1346
+
1347
+ -from icalendar.cal import Calendar
1348
+ +from icalendar.cal import Calendar, Component
1349
+ from icalendar.cal import Timezone as VTimezone
1350
+
1351
+ from .icalendar import CalendarFilter, ICalendarFile
1352
+ @@ -910,6 +910,19 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1353
+ return
1354
+ member_name, member, existing_cal = existing
1355
+ merged = itip.preserve_partstats(existing_cal, new_cal)
1356
+ + if not itip.covers_series(itip_message, uid):
1357
+ + # A REQUEST that names occurrences updates those occurrences; the
1358
+ + # series it does not carry is not ours to drop, and an occurrence
1359
+ + # the series does not produce is not ours to add.
1360
+ + narrowed = _occurrences_of_the_series(existing_cal, merged, uid)
1361
+ + if narrowed is None:
1362
+ + logger.info(
1363
+ + "Inbox auto-apply: REQUEST for %s named no occurrence the "
1364
+ + "series produces",
1365
+ + uid,
1366
+ + )
1367
+ + return
1368
+ + merged = _splice_occurrences(existing_cal, narrowed)
1369
+ await _replace_member_body(member, merged)
1370
+ logger.info(
1371
+ "Inbox auto-apply: updated %s (%s) in %s for REQUEST",
1372
+ @@ -930,14 +943,33 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1373
+ )
1374
+ return
1375
+ member_name, member, existing_cal = existing
1376
+ - for comp in existing_cal.subcomponents:
1377
+ - if (
1378
+ - comp.name in itip.SCHEDULING_COMPONENTS
1379
+ - and str(comp.get("UID", "")) == uid
1380
+ - ):
1381
+ - comp["STATUS"] = "CANCELLED"
1382
+ + onwards = itip.thisandfuture_occurrence(itip_message, uid)
1383
+ + if onwards is not None:
1384
+ + if not itip.end_series_at(existing_cal, uid, onwards):
1385
+ + logger.info(
1386
+ + "Inbox auto-apply: CANCEL for %s named nothing we hold", uid
1387
+ + )
1388
+ + return
1389
+ + await _replace_member_body(member, existing_cal)
1390
+ + logger.info(
1391
+ + "Inbox auto-apply: cancelled %s (%s) from one occurrence onwards",
1392
+ + uid,
1393
+ + member_name,
1394
+ + )
1395
+ + return
1396
+ + targets = _occurrence_targets(existing_cal, itip_message, uid)
1397
+ + if not targets:
1398
+ + logger.info("Inbox auto-apply: CANCEL for %s named nothing we hold", uid)
1399
+ + return
1400
+ + for comp in targets:
1401
+ + comp["STATUS"] = "CANCELLED"
1402
+ await _replace_member_body(member, existing_cal)
1403
+ - logger.info("Inbox auto-apply: cancelled %s (%s)", uid, member_name)
1404
+ + logger.info(
1405
+ + "Inbox auto-apply: cancelled %d occurrence(s) of %s (%s)",
1406
+ + len(targets),
1407
+ + uid,
1408
+ + member_name,
1409
+ + )
1410
+
1411
+ async def _apply_reply(
1412
+ self,
1413
+ @@ -952,34 +984,51 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1414
+ return
1415
+ member_name, member, existing_cal = existing
1416
+
1417
+ - # Pick out the replying attendee's address + new PARTSTAT.
1418
+ - updates: dict[str, str] = {}
1419
+ + # Pick out the replying attendee's address + new PARTSTAT, per the
1420
+ + # occurrence the answer is about.
1421
+ + updates: dict[tuple[str, str], str] = {}
1422
+ for comp in itip_message.subcomponents:
1423
+ if comp.name not in itip.SCHEDULING_COMPONENTS:
1424
+ continue
1425
+ if str(comp.get("UID", "")) != uid:
1426
+ continue
1427
+ + key = itip.recurrence_key(comp)
1428
+ attendees = comp.get("ATTENDEE", [])
1429
+ if not isinstance(attendees, list):
1430
+ attendees = [attendees]
1431
+ for a in attendees:
1432
+ partstat = a.params.get("PARTSTAT")
1433
+ if partstat is not None:
1434
+ - updates[str(a)] = str(partstat)
1435
+ + updates[(key, str(a))] = str(partstat)
1436
+ if not updates:
1437
+ return
1438
+
1439
+ + # An answer that carries the series answers for all of it; an answer
1440
+ + # that names occurrences answers for those, whether or not we already
1441
+ + # keep a component for them.
1442
+ + whole = itip.covers_series(itip_message, uid)
1443
+ + # An answer marked RANGE=THISANDFUTURE is about the occurrence it
1444
+ + # names and every later one: it lands on each of those, and on none
1445
+ + # before.
1446
+ + onwards = itip.thisandfuture_occurrence(itip_message, uid)
1447
+ + if onwards is not None:
1448
+ + onwards_key = itip._instant_key(onwards)
1449
+ + targets = itip.onwards_targets(existing_cal, uid, onwards)
1450
+ + else:
1451
+ + onwards_key = None
1452
+ + targets = _occurrence_targets(existing_cal, itip_message, uid)
1453
+ changed = False
1454
+ - for comp in existing_cal.subcomponents:
1455
+ - if comp.name not in itip.SCHEDULING_COMPONENTS:
1456
+ - continue
1457
+ - if str(comp.get("UID", "")) != uid:
1458
+ - continue
1459
+ + for comp in targets:
1460
+ + key = itip.recurrence_key(comp)
1461
+ attendees = comp.get("ATTENDEE", [])
1462
+ if not isinstance(attendees, list):
1463
+ attendees = [attendees]
1464
+ for a in attendees:
1465
+ - new_partstat = updates.get(str(a))
1466
+ + new_partstat = updates.get((key, str(a)))
1467
+ + if new_partstat is None and onwards_key is not None:
1468
+ + new_partstat = updates.get((onwards_key, str(a)))
1469
+ + if new_partstat is None and whole:
1470
+ + new_partstat = updates.get(("", str(a)))
1471
+ if (
1472
+ new_partstat is not None
1473
+ and a.params.get("PARTSTAT") != new_partstat
1474
+ @@ -992,7 +1041,10 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1475
+ "Inbox auto-apply: applied REPLY to %s (%s); updated PARTSTATs: %s",
1476
+ uid,
1477
+ member_name,
1478
+ - ", ".join(f"{addr}={ps}" for addr, ps in updates.items()),
1479
+ + ", ".join(
1480
+ + f"{addr}={ps}" + (f" ({key})" if key else "")
1481
+ + for (key, addr), ps in updates.items()
1482
+ + ),
1483
+ )
1484
+ else:
1485
+ logger.info(
1486
+ @@ -1002,6 +1054,115 @@ class ScheduleInbox(StoreBasedCollection, scheduling.ScheduleInbox):
1487
+ )
1488
+
1489
+
1490
+ +def _occurrence_targets(
1491
+ + existing_cal: Calendar, itip_message: Calendar, uid: str
1492
+ +) -> "list[Component]":
1493
+ + """Return the stored components an iTIP message speaks about.
1494
+ +
1495
+ + A message that carries the series speaks for the whole of it. A message
1496
+ + that names occurrences speaks for exactly those — and RFC 5546 lets it
1497
+ + name an occurrence the recipient keeps no component for, because the
1498
+ + recipient holds the series as one recurring component and the organiser
1499
+ + never had reason to move that occurrence. Such an occurrence is broken
1500
+ + out of the series first, so there is something to apply the message to.
1501
+ + """
1502
+ + occurrences = itip.itip_occurrences(itip_message, uid)
1503
+ + whole = "" in occurrences
1504
+ + targets: list[Component] = []
1505
+ + seen: set[str] = set()
1506
+ + for comp in existing_cal.subcomponents:
1507
+ + if comp.name not in itip.SCHEDULING_COMPONENTS:
1508
+ + continue
1509
+ + if str(comp.get("UID", "")) != uid:
1510
+ + continue
1511
+ + key = itip.recurrence_key(comp)
1512
+ + if whole or key in occurrences:
1513
+ + targets.append(comp)
1514
+ + seen.add(key)
1515
+ + if whole:
1516
+ + return targets
1517
+ + for key, rid in occurrences.items():
1518
+ + if key in seen or rid is None:
1519
+ + continue
1520
+ + broken_out = itip.materialise_occurrence(existing_cal, uid, rid)
1521
+ + if broken_out is not None:
1522
+ + targets.append(broken_out)
1523
+ + return targets
1524
+ +
1525
+ +
1526
+ +def _occurrences_of_the_series(
1527
+ + existing_cal: Calendar, incoming: Calendar, uid: str
1528
+ +) -> "Calendar | None":
1529
+ + """Drop *incoming*'s components for occurrences the series never produces.
1530
+ +
1531
+ + A message may name an occurrence we keep no component for: the organiser
1532
+ + never moved it, so it lives inside the RRULE, and it is ours to break
1533
+ + out. An instant the recurrence set does not produce at all is a
1534
+ + different matter — taking that one would put a meeting in the calendar
1535
+ + that nobody scheduled, under the UID of one that exists. Components of
1536
+ + other UIDs, and the VTIMEZONEs, travel through untouched.
1537
+ +
1538
+ + Returns None when nothing of *uid* survives, so the caller can leave the
1539
+ + stored object exactly as it was.
1540
+ + """
1541
+ + held = {
1542
+ + itip.recurrence_key(comp)
1543
+ + for comp in existing_cal.subcomponents
1544
+ + if comp.name in itip.SCHEDULING_COMPONENTS and str(comp.get("UID", "")) == uid
1545
+ + }
1546
+ + if "" not in held:
1547
+ + # What we keep of this event is occurrences and no series. There is no
1548
+ + # recurrence set here to say what it does and does not produce, so
1549
+ + # there is nothing to refuse: each occurrence stands on its own.
1550
+ + return incoming
1551
+ + out = Calendar()
1552
+ + for field in incoming:
1553
+ + out[field] = incoming[field]
1554
+ + kept = 0
1555
+ + for comp in incoming.subcomponents:
1556
+ + if (
1557
+ + comp.name not in itip.SCHEDULING_COMPONENTS
1558
+ + or str(comp.get("UID", "")) != uid
1559
+ + ):
1560
+ + out.add_component(comp)
1561
+ + continue
1562
+ + rid = comp.get("RECURRENCE-ID")
1563
+ + if (
1564
+ + itip.recurrence_key(comp) in held
1565
+ + or rid is None
1566
+ + or itip.series_produces(existing_cal, uid, rid)
1567
+ + ):
1568
+ + out.add_component(comp)
1569
+ + kept += 1
1570
+ + return out if kept else None
1571
+ +
1572
+ +
1573
+ +def _splice_occurrences(existing_cal: Calendar, incoming: Calendar) -> Calendar:
1574
+ + """Put *incoming*'s components in their place inside *existing_cal*.
1575
+ +
1576
+ + Components are matched by name, UID and occurrence, so an update that
1577
+ + names one occurrence replaces that occurrence and leaves the rest of the
1578
+ + series where it was — and the same occurrence written a second way
1579
+ + replaces the first rather than joining it.
1580
+ + """
1581
+ + out = Calendar()
1582
+ + for field in existing_cal:
1583
+ + out[field] = existing_cal[field]
1584
+ + by_key: dict = {}
1585
+ + order: list = []
1586
+ + for comp in list(existing_cal.subcomponents) + list(incoming.subcomponents):
1587
+ + if comp.name in itip.SCHEDULING_COMPONENTS:
1588
+ + key = (comp.name, str(comp.get("UID", "")), itip.recurrence_key(comp))
1589
+ + else:
1590
+ + key = (comp.name, comp.to_ical())
1591
+ + if key not in by_key:
1592
+ + order.append(key)
1593
+ + by_key[key] = comp
1594
+ + for key in order:
1595
+ + out.add_component(by_key[key])
1596
+ + return out
1597
+ +
1598
+ +
1599
+ async def _find_calendar_member_by_uid(
1600
+ calendar: "CalendarCollection", uid: str
1601
+ ) -> "tuple[str, ObjectResource, Calendar] | None":
1602
+ @@ -1522,24 +1683,26 @@ class CalendarCollection(StoreBasedCollection, caldav.Calendar):
1603
+ new_cal: Calendar,
1604
+ old_cal: Calendar,
1605
+ own_addresses: set[str],
1606
+ - new_delegates: set[str],
1607
+ + new_delegates: "set[tuple[str, str]]",
1608
+ ) -> None:
1609
+ """Raise if *new_cal* changes anything beyond the user's own ATTENDEE.
1610
+
1611
+ Compares scheduling signatures of *old_cal* and *new_cal* with
1612
+ the user's own ATTENDEE parameters masked, and any newly-added
1613
+ - delegates skipped entirely (RFC 6638 §3.2.6 lets an attendee
1614
+ - add a delegate ATTENDEE, distinguishable by its DELEGATED-FROM
1615
+ - pointing back at the user). If anything else differs, the user
1616
+ - is touching organiser-owned data.
1617
+ + delegates dropped where they were added (RFC 6638 §3.2.6 lets an
1618
+ + attendee add a delegate ATTENDEE, distinguishable by its
1619
+ + DELEGATED-FROM pointing back at the user). The exception is as
1620
+ + narrow as the delegation: it covers the occurrences the user
1621
+ + actually delegated, not every occurrence that happens to mention
1622
+ + the same address. If anything else differs, the user is touching
1623
+ + organiser-owned data.
1624
+ """
1625
+ mask = frozenset(own_addresses)
1626
+ - skip = frozenset(new_delegates)
1627
+ new_masked = itip.extract_scheduling_signature(
1628
+ - new_cal, mask_own_attendee_params=mask, skip_attendees=skip
1629
+ + _without_attendees(new_cal, new_delegates), mask_own_attendee_params=mask
1630
+ )
1631
+ old_masked = itip.extract_scheduling_signature(
1632
+ - old_cal, mask_own_attendee_params=mask, skip_attendees=skip
1633
+ + old_cal, mask_own_attendee_params=mask
1634
+ )
1635
+ if new_masked != old_masked:
1636
+ raise webdav.PreconditionFailure(
1637
+ @@ -1555,31 +1718,45 @@ class CalendarCollection(StoreBasedCollection, caldav.Calendar):
1638
+ old_cal: Calendar | None,
1639
+ new_attendees: set[str],
1640
+ own_addresses: set[str],
1641
+ - ) -> dict[str, str]:
1642
+ - """Send REQUEST/CANCEL and return ``{address: SCHEDULE-STATUS code}``."""
1643
+ - outcomes: dict[str, str] = {}
1644
+ + ) -> "dict[str, tuple[str, frozenset[str]]]":
1645
+ + """Send REQUEST/CANCEL; return ``{address: (code, occurrences sent)}``.
1646
+ +
1647
+ + An attendee is invited to the occurrences that list them, which for a
1648
+ + series with exceptions need not be all of them, so each attendee is
1649
+ + sent the occurrences that are theirs. The occurrences that went out
1650
+ + travel back with the delivery outcome: the record of a delivery
1651
+ + belongs on what was delivered.
1652
+ + """
1653
+ + outcomes: dict[str, tuple[str, frozenset[str]]] = {}
1654
+ organiser = _organiser_address(new_cal)
1655
+ - if new_attendees:
1656
+ - request = itip.build_itip_request(new_cal)
1657
+ - for address in new_attendees:
1658
+ - outcomes[address] = await _deliver_status(
1659
+ + invited = {a: itip.occurrences_for_attendee(new_cal, a) for a in new_attendees}
1660
+ + for address, keys in invited.items():
1661
+ + if not keys:
1662
+ + continue
1663
+ + request = itip.build_itip_request(itip.narrow_to_occurrences(new_cal, keys))
1664
+ + outcomes[address] = (
1665
+ + await _deliver_status(
1666
+ self.backend, address, request, originator=organiser
1667
+ - )
1668
+ + ),
1669
+ + frozenset(keys),
1670
+ + )
1671
+
1672
+ if old_cal is None:
1673
+ return outcomes
1674
+ _, old_attendees = _organiser_attendees(old_cal, own_addresses)
1675
+ - dropped = old_attendees - new_attendees
1676
+ - if dropped:
1677
+ - cancel = itip.build_itip_cancel(old_cal)
1678
+ - for address in dropped:
1679
+ - # Dropped attendees aren't in new_cal, so their CANCEL
1680
+ - # delivery outcomes don't end up annotated anywhere; the
1681
+ - # CANCEL itself is the record. Still goes through the
1682
+ - # iMIP path for non-local recipients.
1683
+ - await _deliver_status(
1684
+ - self.backend, address, cancel, originator=organiser
1685
+ - )
1686
+ + for address in old_attendees:
1687
+ + lost = itip.occurrences_for_attendee(old_cal, address) - invited.get(
1688
+ + address, set()
1689
+ + )
1690
+ + if not lost:
1691
+ + continue
1692
+ + # An attendee who has lost an occurrence — or the whole event —
1693
+ + # is told about what they lost and nothing else. Their CANCEL
1694
+ + # outcome isn't annotated anywhere (they may not be in new_cal at
1695
+ + # all); the CANCEL itself is the record. Still goes through the
1696
+ + # iMIP path for non-local recipients.
1697
+ + cancel = itip.build_itip_cancel(itip.narrow_to_occurrences(old_cal, lost))
1698
+ + await _deliver_status(self.backend, address, cancel, originator=organiser)
1699
+ return outcomes
1700
+
1701
+ async def _dispatch_attendee_put(
1702
+ @@ -1588,25 +1765,32 @@ class CalendarCollection(StoreBasedCollection, caldav.Calendar):
1703
+ old_cal: Calendar | None,
1704
+ own_addresses: set[str],
1705
+ force_reply: set[str],
1706
+ - new_delegates: set[str],
1707
+ - ) -> dict[str, str]:
1708
+ + new_delegates: "set[tuple[str, str]]",
1709
+ + ) -> "dict[str, tuple[str, frozenset[str]]]":
1710
+ """Send REPLY to organiser and REQUEST to any newly-added delegates.
1711
+
1712
+ - Returns ``{address: SCHEDULE-STATUS code}`` for the delegate
1713
+ + Returns ``{address: (code, occurrences sent)}`` for the delegate
1714
+ deliveries; the REPLY itself isn't annotated (the user's own
1715
+ ATTENDEE doesn't carry SCHEDULE-STATUS).
1716
+ """
1717
+ - outcomes: dict[str, str] = {}
1718
+ + outcomes: dict[str, tuple[str, frozenset[str]]] = {}
1719
+ own_address = _own_attendee_address(new_cal, own_addresses)
1720
+
1721
+ - # RFC 6638 §3.2.6: when the user delegates to someone else,
1722
+ - # the new delegate needs a REQUEST so they see the meeting.
1723
+ - if new_delegates:
1724
+ - request = itip.build_itip_request(new_cal)
1725
+ - for address in new_delegates:
1726
+ - outcomes[address] = await _deliver_status(
1727
+ + # RFC 6638 §3.2.6: when the user delegates to someone else, the new
1728
+ + # delegate needs a REQUEST so they see the meeting — the part of it
1729
+ + # they were handed, which for a single delegated occurrence is that
1730
+ + # occurrence and not the rest of the series.
1731
+ + delegated: dict[str, set[str]] = {}
1732
+ + for key, address in new_delegates:
1733
+ + delegated.setdefault(address, set()).add(key)
1734
+ + for address, keys in delegated.items():
1735
+ + request = itip.build_itip_request(itip.narrow_to_occurrences(new_cal, keys))
1736
+ + outcomes[address] = (
1737
+ + await _deliver_status(
1738
+ self.backend, address, request, originator=own_address
1739
+ - )
1740
+ + ),
1741
+ + frozenset(keys),
1742
+ + )
1743
+
1744
+ if own_address is None:
1745
+ return outcomes
1746
+ @@ -1724,24 +1908,34 @@ def _strip_mailto(address: str) -> str:
1747
+ return address
1748
+
1749
+
1750
+ -def _annotate_schedule_status(cal: Calendar, outcomes: dict[str, str]) -> None:
1751
+ +def _annotate_schedule_status(
1752
+ + cal: Calendar, outcomes: "dict[str, tuple[str, frozenset[str]]]"
1753
+ +) -> None:
1754
+ """Stamp SCHEDULE-STATUS on each ATTENDEE per RFC 6638 §3.2.
1755
+
1756
+ - *outcomes* maps an attendee address (as it appears in ATTENDEE) to
1757
+ - a request-status code. Attendees absent from *outcomes* are left
1758
+ - alone — typically the organiser themselves, who we don't deliver
1759
+ + *outcomes* maps an attendee address (as it appears in ATTENDEE) to the
1760
+ + request-status code of the delivery and the occurrences that delivery
1761
+ + carried. The stamp is the record of that delivery, so it goes on the
1762
+ + occurrences that were sent and nowhere else: an occurrence nobody was
1763
+ + told about has not been delivered. Attendees absent from *outcomes* are
1764
+ + left alone — typically the organiser themselves, who we don't deliver
1765
+ to.
1766
+ """
1767
+ for comp in cal.subcomponents:
1768
+ if comp.name not in itip.SCHEDULING_COMPONENTS:
1769
+ continue
1770
+ + key = itip.recurrence_key(comp)
1771
+ attendees = comp.get("ATTENDEE", [])
1772
+ if not isinstance(attendees, list):
1773
+ attendees = [attendees]
1774
+ for a in attendees:
1775
+ - status = outcomes.get(str(a))
1776
+ - if status is not None:
1777
+ - a.params["SCHEDULE-STATUS"] = status
1778
+ + outcome = outcomes.get(str(a))
1779
+ + if outcome is None:
1780
+ + continue
1781
+ + status, sent = outcome
1782
+ + if key not in sent:
1783
+ + continue
1784
+ + a.params["SCHEDULE-STATUS"] = status
1785
+
1786
+
1787
+ def _consume_force_send(cal: Calendar) -> tuple[set[str], set[str], bool]:
1788
+ @@ -1813,19 +2007,22 @@ def _organiser_attendees(
1789
+ return is_organiser, attendees
1790
+
1791
+
1792
+ -def _delegates_of(cal: Calendar, own_addresses: set[str]) -> set[str]:
1793
+ - """Return ATTENDEE addresses delegated FROM one of *own_addresses*.
1794
+ +def _delegates_of(cal: Calendar, own_addresses: set[str]) -> "set[tuple[str, str]]":
1795
+ + """Return ``(occurrence, ATTENDEE)`` pairs delegated FROM *own_addresses*.
1796
+
1797
+ RFC 5545 §3.8.4.4: an ATTENDEE may carry DELEGATED-FROM listing
1798
+ the address(es) that delegated to them. We pick the entries
1799
+ whose DELEGATED-FROM matches the user — those are the user's
1800
+ delegates and the user is allowed to add them on a PUT
1801
+ - (RFC 6638 §3.2.6).
1802
+ + (RFC 6638 §3.2.6). A delegation is made on an occurrence, so the
1803
+ + occurrence travels with the address: handing over one occurrence of a
1804
+ + series says nothing about the others.
1805
+ """
1806
+ - out: set[str] = set()
1807
+ + out: set[tuple[str, str]] = set()
1808
+ for comp in cal.subcomponents:
1809
+ if comp.name not in itip.SCHEDULING_COMPONENTS:
1810
+ continue
1811
+ + key = itip.recurrence_key(comp)
1812
+ comp_attendees = comp.get("ATTENDEE", [])
1813
+ if not isinstance(comp_attendees, list):
1814
+ comp_attendees = [comp_attendees]
1815
+ @@ -1837,7 +2034,28 @@ def _delegates_of(cal: Calendar, own_addresses: set[str]) -> set[str]:
1816
+ delegated_from if isinstance(delegated_from, list) else [delegated_from]
1817
+ )
1818
+ if any(str(src) in own_addresses for src in sources):
1819
+ - out.add(str(a))
1820
+ + out.add((key, str(a)))
1821
+ + return out
1822
+ +
1823
+ +
1824
+ +def _without_attendees(cal: Calendar, pairs: "set[tuple[str, str]]") -> Calendar:
1825
+ + """Return a copy of *cal* with those ``(occurrence, ATTENDEE)`` pairs gone."""
1826
+ + out = Calendar()
1827
+ + for field in cal:
1828
+ + out[field] = cal[field]
1829
+ + for comp in cal.subcomponents:
1830
+ + clone = comp.copy()
1831
+ + if clone.name in itip.SCHEDULING_COMPONENTS:
1832
+ + key = itip.recurrence_key(clone)
1833
+ + attendees = clone.get("ATTENDEE", [])
1834
+ + if not isinstance(attendees, list):
1835
+ + attendees = [attendees]
1836
+ + kept = [a for a in attendees if (key, str(a)) not in pairs]
1837
+ + if len(kept) != len(attendees):
1838
+ + del clone["ATTENDEE"]
1839
+ + for a in kept:
1840
+ + clone.add("ATTENDEE", a)
1841
+ + out.add_component(clone)
1842
+ return out
1843
+
1844
+
1845
+ @@ -1887,7 +2105,11 @@ def _partstat_changed(new_cal: Calendar, old_cal: Calendar, address: str) -> boo
1846
+
1847
+
1848
+ def _user_partstats(cal: Calendar, address: str) -> dict[tuple[str, str, str], str]:
1849
+ - """Map (component-name, UID, RECURRENCE-ID) → PARTSTAT for *address*."""
1850
+ + """Map (component-name, UID, occurrence) → PARTSTAT for *address*.
1851
+ +
1852
+ + Keyed by the occurrence itself: rewriting the same occurrence in another
1853
+ + time zone is not the user answering again.
1854
+ + """
1855
+ out: dict[tuple[str, str, str], str] = {}
1856
+ for comp in cal.subcomponents:
1857
+ if comp.name not in itip.SCHEDULING_COMPONENTS:
1858
+ @@ -1899,7 +2121,7 @@ def _user_partstats(cal: Calendar, address: str) -> dict[tuple[str, str, str], s
1859
+ if str(a) != address:
1860
+ continue
1861
+ uid = str(comp.get("UID", ""))
1862
+ - rid = str(comp.get("RECURRENCE-ID", ""))
1863
+ + rid = itip.recurrence_key(comp)
1864
+ partstat = str(a.params.get("PARTSTAT", "NEEDS-ACTION"))
1865
+ out[(comp.name, uid, rid)] = partstat
1866
+ break
1867
+
1868
+ REFERENCE_PATCH
harbor/tasks/xandikos_itip_recurrence_id_override_contract/task.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+ artifacts = ["/workspace/submissions/submitted.patch"]
3
+ [metadata]
4
+ task = "xandikos_itip_recurrence_id_override_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/xandikos_itip_recurrence_id_override_contract/tests/Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-xandikos:source-v7
2
+ USER root
3
+ RUN grep -q '^[^:]*:[^:]*:1000:' /etc/passwd || echo 'grader:x:1000:1000::/tmp/agent-home:/bin/sh' >> /etc/passwd; grep -q '^[^:]*:[^:]*:1000:' /etc/group || echo 'grader:x:1000:' >> /etc/group
4
+ ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
5
+ RUN rm -f /hud/gold.diff
6
+ COPY verify.py evidence.py config.json test.sh /tests/
7
+ RUN chmod 755 /tests/test.sh
8
+ WORKDIR /app
9
+ CMD ["sleep", "infinity"]
harbor/tasks/xandikos_itip_recurrence_id_override_contract/tests/config.json ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "revision": "coding-rubric-v2",
3
+ "task_id": "xandikos_itip_recurrence_id_override_contract",
4
+ "arguments": {},
5
+ "grader_version": "0.6.15",
6
+ "source_image": "ec-swe-xandikos:source-v7",
7
+ "source_image_id": "sha256:303351c10fb1888c091fd0f23b2cf28b0b39a3f4b79b78a055e5d7d587facf5f",
8
+ "provenance": {
9
+ "repository": "jelmer/xandikos",
10
+ "environment_id": "372a37cc-b31d-4523-9ffc-8ecc64a3fddb",
11
+ "build": 7,
12
+ "build_id": "acd4eec1-b215-40c7-a378-bd216baac6b5",
13
+ "hosted_task": "xandikos_itip_recurrence_id_override_contract-c6aa163a",
14
+ "task_version": "ef0272f8-7c28-4c25-a433-56b44da3aa32",
15
+ "source_archive_sha256": "53d61bc9e61cd485df1f6fddc33d023338eb7695ad508eaeac38978df8c109dd",
16
+ "hosted_revision_argument": "not recorded; the scenario does not read it"
17
+ },
18
+ "criteria": [
19
+ [
20
+ "one_occurrence_is_not_the_whole_series",
21
+ 0.045,
22
+ false,
23
+ "bash",
24
+ 600
25
+ ],
26
+ [
27
+ "cancel_names_one_occurrence_of_the_series",
28
+ 0.045,
29
+ true,
30
+ "bash",
31
+ 600
32
+ ],
33
+ [
34
+ "reply_answers_for_one_occurrence",
35
+ 0.045,
36
+ false,
37
+ "bash",
38
+ 600
39
+ ],
40
+ [
41
+ "the_same_instant_written_differently",
42
+ 0.045,
43
+ false,
44
+ "bash",
45
+ 600
46
+ ],
47
+ [
48
+ "delegate_hears_about_the_delegated_occurrence",
49
+ 0.045,
50
+ false,
51
+ "bash",
52
+ 600
53
+ ],
54
+ [
55
+ "delegation_does_not_hide_an_uninvited_occurrence",
56
+ 0.045,
57
+ false,
58
+ "bash",
59
+ 600
60
+ ],
61
+ [
62
+ "cancel_from_one_occurrence_onwards",
63
+ 0.135,
64
+ false,
65
+ "bash",
66
+ 600
67
+ ],
68
+ [
69
+ "a_revision_from_one_occurrence_onwards",
70
+ 0.135,
71
+ false,
72
+ "bash",
73
+ 600
74
+ ],
75
+ [
76
+ "later_occurrences_move_with_that_one",
77
+ 0.135,
78
+ false,
79
+ "bash",
80
+ 600
81
+ ],
82
+ [
83
+ "an_answer_from_one_occurrence_onwards",
84
+ 0.135,
85
+ false,
86
+ "bash",
87
+ 600
88
+ ],
89
+ [
90
+ "an_answer_onwards_reaches_an_occurrence_moved_on_its_own",
91
+ 0.135,
92
+ false,
93
+ "bash",
94
+ 600
95
+ ],
96
+ [
97
+ "a_day_the_series_never_had_is_not_invented",
98
+ 0.045,
99
+ false,
100
+ "bash",
101
+ 600
102
+ ],
103
+ [
104
+ "gate_repo_suite_green_and_tests_untouched",
105
+ 0.01,
106
+ true,
107
+ "bash",
108
+ 900
109
+ ]
110
+ ],
111
+ "gates": [],
112
+ "reward_rule": "weighted_cap",
113
+ "local_hostname": false,
114
+ "fault_exit": 3,
115
+ "grader_readable": [],
116
+ "grader_writable": [],
117
+ "blocker_cap": 0.6,
118
+ "empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
119
+ "verifier_files": {
120
+ "/app/env.py": "4c802d6298c4339bdf8284deacb54c1f6812eecc48d50b9c2c07fe60dbf5567f",
121
+ "/app/tasks.py": "6e97d968d30d89326bb220ea473efb5be5cc1820b4e4a8859eb292e8879efd27",
122
+ "/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
123
+ "/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
124
+ "/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
125
+ "/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
126
+ "/app/task/prompt.md": "a0db17267577e9da6539913c1d63605eda8ca93614b62102ae361f75f7990245",
127
+ "/hud/grader/run_grading.sh": "0fc5276c4fbf084f29af16663af161beb8ca504618c24e686ef68a9d280dd02a",
128
+ "/hud/grader/suite_deselect.txt": "f8399d13d30a10a972d549421ecf802f65f7ed1adee4e5996b61229883794b07",
129
+ "/hud/grader/cells/spec_cells.py": "984a3fd75b9cbfc688be5ad867bf666c50fded513efc45d52e2bf415e190476b"
130
+ },
131
+ "preflight": [
132
+ [
133
+ "/bin/bash",
134
+ "--version"
135
+ ],
136
+ [
137
+ "setpriv",
138
+ "--version"
139
+ ],
140
+ [
141
+ "git",
142
+ "--version"
143
+ ],
144
+ [
145
+ "bash",
146
+ "-c",
147
+ "bash -lc 'python --version' || python --version"
148
+ ],
149
+ [
150
+ "/opt/agentvenv/bin/python",
151
+ "--version"
152
+ ]
153
+ ]
154
+ }
harbor/tasks/xandikos_itip_recurrence_id_override_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/xandikos_itip_recurrence_id_override_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/xandikos_itip_recurrence_id_override_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/xandikos_itip_recurrence_id_override_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()