Debian Codegraph @

cassandane/Cassandane/Cyrus/JMAPCalendars.pm

raw
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 2011-2017 FastMail Pty Ltd. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # 3. The name "Fastmail Pty Ltd" must not be used to
18 # endorse or promote products derived from this software without
19 # prior written permission. For permission or any legal
20 # details, please contact
21 # FastMail Pty Ltd
22 # PO Box 234
23 # Collins St West 8007
24 # Victoria
25 # Australia
26 #
27 # 4. Redistributions of any form whatsoever must retain the following
28 # acknowledgment:
29 # "This product includes software developed by Fastmail Pty. Ltd."
30 #
31 # FASTMAIL PTY LTD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
32 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
33 # EVENT SHALL OPERA SOFTWARE AUSTRALIA BE LIABLE FOR ANY SPECIAL, INDIRECT
34 # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
35 # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
36 # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
37 # OF THIS SOFTWARE.
38 #
39
40 package Cassandane::Cyrus::JMAPCalendars;
41 use strict;
42 use warnings;
43 use DateTime;
44 use JSON::XS;
45 use Net::CalDAVTalk 0.09;
46 use Net::CardDAVTalk 0.03;
47 use Mail::JMAPTalk 0.13;
48 use Data::ICal;
49 use Data::Dumper;
50 use Data::GUID qw(guid_string);
51 use Storable 'dclone';
52 use Cwd qw(abs_path);
53 use File::Basename;
54 use XML::Spice;
55 use MIME::Base64 qw(encode_base64url decode_base64url);
56
57 use lib '.';
58 use base qw(Cassandane::Cyrus::TestCase);
59 use Cassandane::Util::Log;
60 use Cassandane::Util::Slurp;
61
62 use charnames ':full';
63
64 sub new
65 {
66 my ($class, @args) = @_;
67 my $config = Cassandane::Config->default()->clone();
68
69 $config->set(caldav_realm => 'Cassandane',
70 caldav_historical_age => -1,
71 conversations => 'yes',
72 httpmodules => 'carddav caldav jmap',
73 httpallowcompress => 'no',
74 imipnotifier => 'imip',
75 sync_log => 'yes',
76 jmap_nonstandard_extensions => 'yes',
77 defaultdomain => 'example.com');
78
79 # Configure Sieve iMIP delivery
80 my ($maj, $min) = Cassandane::Instance->get_version();
81 if ($maj == 3 && $min == 0) {
82 # need to explicitly add 'body' to sieve_extensions for 3.0
83 $config->set(sieve_extensions =>
84 "fileinto reject vacation vacation-seconds imap4flags notify " .
85 "envelope relational regex subaddress copy date index " .
86 "imap4flags mailbox mboxmetadata servermetadata variables " .
87 "body");
88 }
89 elsif ($maj < 3) {
90 # also for 2.5 (the earliest Cyrus that Cassandane can test)
91 $config->set(sieve_extensions =>
92 "fileinto reject vacation vacation-seconds imap4flags notify " .
93 "envelope relational regex subaddress copy date index " .
94 "imap4flags body");
95 }
96 $config->set(sievenotifier => 'mailto');
97 $config->set(calendar_user_address_set => 'example.com');
98 $config->set(caldav_historical_age => -1);
99 $config->set(virtdomains => 'no');
100
101 my $self = $class->SUPER::new({
102 config => $config,
103 jmap => 1,
104 adminstore => 1,
105 deliver => 1,
106 services => [ 'imap', 'sieve', 'http' ],
107 }, @args);
108
109 $self->needs('component', 'jmap');
110 return $self;
111 }
112
113 sub set_up
114 {
115 my ($self) = @_;
116 $self->SUPER::set_up();
117 if ($self->{_want}->{start_instances}) {
118 $self->{jmap}->DefaultUsing([
119 'urn:ietf:params:jmap:core',
120 'urn:ietf:params:jmap:calendars',
121 'urn:ietf:params:jmap:principals',
122 'urn:ietf:params:jmap:calendars:preferences',
123 'https://cyrusimap.org/ns/jmap/calendars',
124 'https://cyrusimap.org/ns/jmap/debug',
125 ]);
126 }
127 }
128
129 sub encode_eventid
130 {
131 # This function hard-codes the event id format.
132 # It might break if we change the id scheme.
133 my ($uid, $recurid) = @_;
134 my $eid = 'E';
135 if ($recurid) {
136 $eid .= 'R'
137 }
138 if ($uid =~ /[^0-9A-Za-z\-_]/) {
139 $eid .= 'B';
140 }
141 $eid .= '-';
142 if ($recurid) {
143 $eid .= $recurid . '-';
144 }
145 if ($uid =~ /[^0-9A-Za-z\-_]/) {
146 $eid .= encode_base64url($uid);
147 }
148 else {
149 $eid .= $uid;
150 }
151 return $eid;
152 }
153
154 sub normalize_event
155 {
156 my ($event) = @_;
157
158 if (not exists $event->{q{@type}}) {
159 $event->{q{@type}} = 'Event';
160 }
161 if (not exists $event->{freeBusyStatus}) {
162 $event->{freeBusyStatus} = 'busy';
163 }
164 if (not exists $event->{priority}) {
165 $event->{priority} = 0;
166 }
167 if (not exists $event->{title}) {
168 $event->{title} = '';
169 }
170 if (not exists $event->{description}) {
171 $event->{description} = '';
172 }
173 if (not exists $event->{descriptionContentType}) {
174 $event->{descriptionContentType} = 'text/plain';
175 }
176 if (not exists $event->{showWithoutTime}) {
177 $event->{showWithoutTime} = JSON::false;
178 }
179 if (not exists $event->{locations}) {
180 $event->{locations} = undef;
181 } elsif (defined $event->{locations}) {
182 foreach my $loc (values %{$event->{locations}}) {
183 if (not exists $loc->{name}) {
184 $loc->{name} = '';
185 }
186 if (not exists $loc->{q{@type}}) {
187 $loc->{q{@type}} = 'Location';
188 }
189 foreach my $link (values %{$loc->{links}}) {
190 if (not exists $link->{q{@type}}) {
191 $link->{q{@type}} = 'Link';
192 }
193 }
194 }
195 }
196 if (not exists $event->{virtualLocations}) {
197 $event->{virtualLocations} = undef;
198 } elsif (defined $event->{virtualLocations}) {
199 foreach my $loc (values %{$event->{virtualLocations}}) {
200 if (not exists $loc->{name}) {
201 $loc->{name} = ''
202 }
203 if (not exists $loc->{description}) {
204 $loc->{description} = undef;
205 }
206 if (not exists $loc->{uri}) {
207 $loc->{uri} = undef;
208 }
209 if (not exists $loc->{q{@type}}) {
210 $loc->{q{@type}} = 'VirtualLocation';
211 }
212 }
213 }
214 if (not exists $event->{keywords}) {
215 $event->{keywords} = undef;
216 }
217 if (not exists $event->{locale}) {
218 $event->{locale} = undef;
219 }
220 if (not exists $event->{links}) {
221 $event->{links} = undef;
222 } elsif (defined $event->{links}) {
223 foreach my $link (values %{$event->{links}}) {
224 if (not exists $link->{q{@type}}) {
225 $link->{q{@type}} = 'Link';
226 }
227 }
228 }
229 if (not exists $event->{relatedTo}) {
230 $event->{relatedTo} = undef;
231 } elsif (defined $event->{relatedTo}) {
232 foreach my $rel (values %{$event->{relatedTo}}) {
233 if (not exists $rel->{q{@type}}) {
234 $rel->{q{@type}} = 'Relation';
235 }
236 }
237 }
238 if (not exists $event->{participants}) {
239 $event->{participants} = undef;
240 } elsif (defined $event->{participants}) {
241 foreach my $p (values %{$event->{participants}}) {
242 if (not exists $p->{linkIds}) {
243 $p->{linkIds} = undef;
244 }
245 if (not exists $p->{participationStatus}) {
246 $p->{participationStatus} = 'needs-action';
247 }
248 if (not exists $p->{expectReply}) {
249 $p->{expectReply} = JSON::false;
250 }
251 if (not exists $p->{scheduleSequence}) {
252 $p->{scheduleSequence} = 0;
253 }
254 if (not exists $p->{q{@type}}) {
255 $p->{q{@type}} = 'Participant';
256 }
257 foreach my $link (values %{$p->{links}}) {
258 if (not exists $link->{q{@type}}) {
259 $link->{q{@type}} = 'Link';
260 }
261 }
262 }
263 }
264 if (not exists $event->{replyTo}) {
265 $event->{replyTo} = undef;
266 }
267 if (not exists $event->{recurrenceRules}) {
268 $event->{recurrenceRules} = undef;
269 } elsif (defined $event->{recurrenceRules}) {
270 foreach my $rrule (@{$event->{recurrenceRules}}) {
271 if (not exists $rrule->{interval}) {
272 $rrule->{interval} = 1;
273 }
274 if (not exists $rrule->{firstDayOfWeek}) {
275 $rrule->{firstDayOfWeek} = 'mo';
276 }
277 if (not exists $rrule->{rscale}) {
278 $rrule->{rscale} = 'gregorian';
279 }
280 if (not exists $rrule->{skip}) {
281 $rrule->{skip} = 'omit';
282 }
283 if (not exists $rrule->{byDay}) {
284 $rrule->{byDay} = undef;
285 } elsif (defined $rrule->{byDay}) {
286 foreach my $nday (@{$rrule->{byDay}}) {
287 if (not exists $nday->{q{@type}}) {
288 $nday->{q{@type}} = 'NDay';
289 }
290 }
291 }
292 if (not exists $rrule->{q{@type}}) {
293 $rrule->{q{@type}} = 'RecurrenceRule';
294 }
295 }
296 }
297 if (not exists $event->{excludedRecurrenceRules}) {
298 $event->{excludedRecurrenceRules} = undef;
299 } elsif (defined $event->{excludedRecurrenceRules}) {
300 foreach my $exrule (@{$event->{excludedRecurrenceRules}}) {
301 if (not exists $exrule->{interval}) {
302 $exrule->{interval} = 1;
303 }
304 if (not exists $exrule->{firstDayOfWeek}) {
305 $exrule->{firstDayOfWeek} = 'mo';
306 }
307 if (not exists $exrule->{rscale}) {
308 $exrule->{rscale} = 'gregorian';
309 }
310 if (not exists $exrule->{skip}) {
311 $exrule->{skip} = 'omit';
312 }
313 if (not exists $exrule->{byDay}) {
314 $exrule->{byDay} = undef;
315 } elsif (defined $exrule->{byDay}) {
316 foreach my $nday (@{$exrule->{byDay}}) {
317 if (not exists $nday->{q{@type}}) {
318 $nday->{q{@type}} = 'NDay';
319 }
320 }
321 }
322 if (not exists $exrule->{q{@type}}) {
323 $exrule->{q{@type}} = 'RecurrenceRule';
324 }
325 }
326 }
327 if (not exists $event->{recurrenceOverrides}) {
328 $event->{recurrenceOverrides} = undef;
329 }
330 if (not exists $event->{alerts}) {
331 $event->{alerts} = undef;
332 }
333 elsif (defined $event->{alerts}) {
334 foreach my $alert (values %{$event->{alerts}}) {
335 if (not exists $alert->{action}) {
336 $alert->{action} = 'display';
337 }
338 if (not exists $alert->{q{@type}}) {
339 $alert->{q{@type}} = 'Alert';
340 }
341 if (not exists $alert->{relatedTo}) {
342 $alert->{relatedTo} = undef;
343 } elsif (defined $alert->{relatedTo}) {
344 foreach my $rel (values %{$alert->{relatedTo}}) {
345 if (not exists $rel->{q{@type}}) {
346 $rel->{q{@type}} = 'Relation';
347 }
348 }
349 }
350 if ($alert->{trigger} and $alert->{trigger}{q{@type}} eq 'OffsetTrigger') {
351 if (not exists $alert->{trigger}{relativeTo}) {
352 $alert->{trigger}{relativeTo} = 'start';
353 }
354 }
355 }
356 }
357 if (not exists $event->{useDefaultAlerts}) {
358 $event->{useDefaultAlerts} = JSON::false;
359 }
360 if (not exists $event->{prodId}) {
361 $event->{prodId} = undef;
362 }
363 if (not exists $event->{links}) {
364 $event->{links} = undef;
365 } elsif (defined $event->{links}) {
366 foreach my $link (values %{$event->{links}}) {
367 if (not exists $link->{cid}) {
368 $link->{cid} = undef;
369 }
370 if (not exists $link->{contentType}) {
371 $link->{contentType} = undef;
372 }
373 if (not exists $link->{size}) {
374 $link->{size} = undef;
375 }
376 if (not exists $link->{title}) {
377 $link->{title} = undef;
378 }
379 if (not exists $link->{q{@type}}) {
380 $link->{q{@type}} = 'Link';
381 }
382 }
383 }
384 if (not exists $event->{status}) {
385 $event->{status} = "confirmed";
386 }
387 if (not exists $event->{privacy}) {
388 $event->{privacy} = "public";
389 }
390 if (not exists $event->{isDraft}) {
391 $event->{isDraft} = JSON::false;
392 }
393 if (not exists $event->{excluded}) {
394 $event->{excluded} = JSON::false,
395 }
396
397 if (not exists $event->{calendarIds}) {
398 $event->{calendarIds} = undef;
399 }
400 if (not exists $event->{timeZone}) {
401 $event->{timeZone} = undef;
402 }
403
404 if (not exists $event->{mayInviteSelf}) {
405 $event->{mayInviteSelf} = JSON::false,
406 }
407
408 # undefine dynamically generated values
409 $event->{created} = undef;
410 $event->{updated} = undef;
411 $event->{uid} = undef;
412 $event->{id} = undef;
413 $event->{"x-href"} = undef;
414 $event->{sequence} = 0;
415 $event->{prodId} = undef;
416 $event->{isOrigin} = undef;
417 delete($event->{blobId});
418 delete($event->{debugBlobId});
419 }
420
421 sub assert_normalized_event_equals
422 {
423 my ($self, $a, $b) = @_;
424 my $copyA = dclone($a);
425 my $copyB = dclone($b);
426 normalize_event($copyA);
427 normalize_event($copyB);
428 return $self->assert_deep_equals($copyA, $copyB);
429 }
430
431 sub putandget_vevent
432 {
433 my ($self, $id, $ical, $props) = @_;
434
435 my $jmap = $self->{jmap};
436 my $caldav = $self->{caldav};
437
438 xlog $self, "get default calendar id";
439 my $res = $jmap->CallMethods([['Calendar/get', {ids => ["Default"]}, "R1"]]);
440 $self->assert_str_equals("Default", $res->[0][1]{list}[0]{id});
441 my $calid = $res->[0][1]{list}[0]{id};
442 my $xhref = $res->[0][1]{list}[0]{"x-href"};
443
444 # Create event via CalDAV to test CalDAV/JMAP interop.
445 xlog $self, "create event (via CalDAV)";
446 my $href = "$xhref/$id.ics";
447
448 $caldav->Request('PUT', $href, $ical, 'Content-Type' => 'text/calendar');
449
450 xlog $self, "get event $id";
451 $res = $jmap->CallMethods([['CalendarEvent/get', {ids => [$id], properties => $props}, "R1"]]);
452
453 my $event = $res->[0][1]{list}[0];
454 $self->assert_not_null($event);
455 return $event;
456 }
457
458 sub icalfile
459 {
460 my ($self, $name) = @_;
461
462 my $path = abs_path("data/icalendar/$name.ics");
463 $self->assert_file_test($path, '-f');
464 my $data = slurp_file($path);
465
466 my ($id) = ($data =~ m/^UID:(\S+)\r?$/m);
467 $self->assert($id);
468 return ($id, $data);
469 }
470
471 sub createandget_event
472 {
473 my ($self, $event, %params) = @_;
474
475 my $jmap = $self->{jmap};
476 my $accountId = $params{accountId} || 'cassandane';
477
478 xlog $self, "create event";
479 my $res = $jmap->CallMethods([['CalendarEvent/set', {
480 accountId => $accountId,
481 create => {"1" => $event}},
482 "R1"]]);
483 $self->assert_not_null($res->[0][1]{created});
484 my $id = $res->[0][1]{created}{"1"}{id};
485
486 xlog $self, "get calendar event $id";
487 $res = $jmap->CallMethods([['CalendarEvent/get', {ids => [$id]}, "R1"]]);
488 my $ret = $res->[0][1]{list}[0];
489 return $ret;
490 }
491
492 sub updateandget_event
493 {
494 my ($self, $event) = @_;
495
496 my $jmap = $self->{jmap};
497 my $id = $event->{id};
498
499 xlog $self, "update event $id";
500 my $res = $jmap->CallMethods([['CalendarEvent/set', {update => {$id => $event}}, "R1"]]);
501 $self->assert_not_null($res->[0][1]{updated});
502
503 xlog $self, "get calendar event $id";
504 $res = $jmap->CallMethods([['CalendarEvent/get', {ids => [$id]}, "R1"]]);
505 my $ret = $res->[0][1]{list}[0];
506 return $ret;
507 }
508
509 sub createcalendar
510 {
511 my ($self) = @_;
512
513 my $jmap = $self->{jmap};
514
515 xlog $self, "create calendar";
516 my $res = $jmap->CallMethods([
517 ['Calendar/set', { create => { "1" => {
518 name => "foo", color => "coral", sortOrder => 1, isVisible => \1
519 }}}, "R1"]
520 ]);
521 $self->assert_not_null($res->[0][1]{created});
522 return $res->[0][1]{created}{"1"}{id};
523 }
524
525 sub assert_rewrite_webdav_attachment_url_itip
526 :min_version_3_5 :needs_component_jmap
527 {
528 my ($self, $eventHref) = @_;
529 my $jmap = $self->{jmap};
530 my $caldav = $self->{caldav};
531
532 xlog "Assert ATTACH in iTIP message is a BINARY value";
533 my $data = $self->{instance}->getnotify();
534 my ($imip) = grep { $_->{METHOD} eq 'imip' } @$data;
535 $self->assert_not_null($imip);
536 my $payload = decode_json($imip->{MESSAGE});
537
538 my $ical = Data::ICal->new(data => $payload->{ical});
539 my %entries = map { $_->ical_entry_type() => $_ } @{$ical->entries()};
540 my $event = $entries{'VEVENT'};
541 $self->assert_not_null($event);
542
543 my $attach = $event->property('ATTACH');
544 $self->assert_num_equals(1, scalar @{$attach});
545 $self->assert_null($attach->[0]->parameters()->{'MANAGED-ID'});
546 $self->assert_str_equals('BINARY', $attach->[0]->parameters()->{VALUE});
547 $self->assert_str_equals('c29tZWJsb2I=', $attach->[0]->value()); # 'someblob' in base64
548
549 xlog "Assert ATTACH on server is a WebDAV attachment URI";
550 my $caldavResponse = $caldav->Request('GET', $eventHref);
551 $ical = Data::ICal->new(data => $caldavResponse->{content});
552 %entries = map { $_->ical_entry_type() => $_ } @{$ical->entries()};
553 $event = $entries{'VEVENT'};
554 $self->assert_not_null($event);
555
556 $attach = $event->property('ATTACH');
557 $self->assert_num_equals(1, scalar @{$attach});
558 $self->assert_not_null($attach->[0]->parameters()->{'MANAGED-ID'});
559 $self->assert_null($attach->[0]->parameters()->{VALUE});
560 my $webdavAttachURI =
561 $self->{instance}->{config}->get('webdav_attachments_baseurl') .
562 '/dav/calendars/user/cassandane/Attachments/';
563 $self->assert($attach->[0]->value() =~ /^$webdavAttachURI.+/);
564 }
565
566 sub create_user
567 {
568 my ($self, $username) = @_;
569
570 xlog $self, "create user $username";
571 my $admin = $self->{adminstore}->get_client();
572 $admin->create("user.$username");
573 $admin->setacl("user.$username", admin => 'lrswipkxtecdan') or die;
574 $admin->setacl("user.$username", $username => 'lrswipkxtecdn') or die;
575
576 my $http = $self->{instance}->get_service("http");
577 my $userJmap = Mail::JMAPTalk->new(
578 user => $username,
579 password => 'pass',
580 host => $http->host(),
581 port => $http->port(),
582 scheme => 'http',
583 url => '/jmap/',
584 );
585 $userJmap->DefaultUsing([
586 'urn:ietf:params:jmap:core',
587 'urn:ietf:params:jmap:calendars',
588 'https://cyrusimap.org/ns/jmap/calendars',
589 ]);
590
591 my $userCalDAV = Net::CalDAVTalk->new(
592 user => $username,
593 password => 'pass',
594 host => $http->host(),
595 port => $http->port(),
596 scheme => 'http',
597 url => '/',
598 expandurl => 1,
599 );
600
601 return ($userJmap, $userCalDAV);
602 }
603
604 sub deliver_imip {
605 my ($self) = @_;
606
607 my $uuid = guid_string();
608 my $imip = <<"EOF";
609 Date: Thu, 23 Sep 2021 09:06:18 -0400
610 From: Sally Sender <sender\@example.net>
611 To: Cassandane <cassandane\@example.com>
612 Message-ID: <$uuid\@example.net>
613 Content-Type: text/calendar; method=REQUEST; component=VEVENT
614 X-Cassandane-Unique: $uuid
615
616 BEGIN:VCALENDAR
617 VERSION:2.0
618 PRODID:-//Apple Inc.//Mac OS X 10.10.4//EN
619 METHOD:REQUEST
620 BEGIN:VEVENT
621 CREATED:20210923T034327Z
622 UID:$uuid
623 DTEND;TZID=America/New_York:20210923T183000
624 TRANSP:OPAQUE
625 SUMMARY:An Event
626 DTSTART;TZID=American/New_York:20210923T153000
627 DTSTAMP:20210923T034327Z
628 SEQUENCE:0
629 ORGANIZER;CN=Test User:MAILTO:foo\@example.net
630 ATTENDEE;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:cassandane\@example.com
631 END:VEVENT
632 END:VCALENDAR
633 EOF
634
635 xlog $self, "Deliver iMIP invite";
636 $self->{instance}->deliver(Cassandane::Message->new(raw => $imip));
637 };
638
639 use Cassandane::Tiny::Loader 'tiny-tests/JMAPCalendars';
640
641 1;