Debian Codegraph @

src/validator/validate_rrule.rs

raw symbols SCIP
1 use std::ops::RangeInclusive;
2
3 use crate::{Frequency, NWeekday, RRule, Tz, Unvalidated};
4
5 use super::ValidationError;
6
7 /// Range of values that a month can be.
8 /// Range: `1..=12`
9 pub(crate) static MONTH_RANGE: RangeInclusive<u8> = 1..=12;
10
11 /// Range of values that a year can be.
12 /// Range: `-10_000..=10_000`
13 pub(crate) static YEAR_RANGE: RangeInclusive<i32> = -10_000..=10_000;
14
15 type Validator =
16 &'static dyn Fn(&RRule<Unvalidated>, &chrono::DateTime<Tz>) -> Result<(), ValidationError>;
17
18 const VALIDATION_PIPELINE: [Validator; 11] = [
19 &validate_until,
20 &validate_by_set_pos,
21 &validate_by_month,
22 &validate_by_month_day,
23 &validate_by_year_day,
24 &validate_by_week_number,
25 &validate_by_weekday,
26 &validate_by_hour,
27 &validate_by_minute,
28 &validate_by_second,
29 &validate_by_easter,
30 ];
31
32 /// Check if rules are valid as defined by the RFC and crate limitations.
33 /// It checks all values in the [`RRule`] and makes sure that they are in
34 /// the accepted ranges. If the function returns `Ok`, no errors where found.
35 ///
36 /// This check should always be done and just enforces limits set by the standard.
37 /// Validation will always be enforced and can not be disabled using feature flags.
38 pub(crate) fn validate_rrule_forced(
39 rrule: &RRule<Unvalidated>,
40 dt_start: &chrono::DateTime<Tz>,
41 ) -> Result<(), ValidationError> {
42 VALIDATION_PIPELINE
43 .into_iter()
44 .try_for_each(|validator| validator(rrule, dt_start))
45 }
46
47 // Until:
48 // - Timezones are correctly synced as specified in the RFC
49 // - Value should be later than `dt_start`.
50 fn validate_until(
51 rrule: &RRule<Unvalidated>,
52 dt_start: &chrono::DateTime<Tz>,
53 ) -> Result<(), ValidationError> {
54 match rrule.until {
55 Some(until) => {
56 match dt_start.timezone() {
57 Tz::Local(_) => {
58 let allowed_timezones = vec![Tz::LOCAL, Tz::UTC];
59 if !allowed_timezones.contains(&until.timezone()) {
60 return Err(ValidationError::DtStartUntilMismatchTimezone {
61 dt_start_tz: dt_start.timezone().name().into(),
62 until_tz: until.timezone().name().into(),
63 expected: allowed_timezones
64 .into_iter()
65 .map(|tz| tz.name().into())
66 .collect(),
67 });
68 }
69 }
70 Tz::Tz(_) => {
71 if until.timezone() != Tz::UTC {
72 return Err(ValidationError::DtStartUntilMismatchTimezone {
73 dt_start_tz: dt_start.timezone().name().into(),
74 until_tz: until.timezone().name().into(),
75 expected: vec!["UTC".into()],
76 });
77 }
78 }
79 }
80
81 if until < *dt_start {
82 return Err(ValidationError::UntilBeforeStart {
83 until: until.to_rfc3339(),
84 dt_start: dt_start.to_rfc3339(),
85 });
86 }
87 Ok(())
88 }
89 _ => Ok(()),
90 }
91 }
92
93 // By_set_pos:
94 // - Can be a value from -366 to -1 and 1 to 366 depending on `freq`
95 fn validate_by_set_pos(
96 rrule: &RRule<Unvalidated>,
97 _dt_start: &chrono::DateTime<Tz>,
98 ) -> Result<(), ValidationError> {
99 validate_not_equal_for_vec(&0, &rrule.by_set_pos, "BYSETPOS")?;
100 let range = match rrule.freq {
101 Frequency::Yearly | Frequency::Daily => -366..=366, // TODO is the daily range correct?
102 Frequency::Monthly => -31..=31,
103 Frequency::Weekly => -53..=53,
104 Frequency::Hourly => -24..=24,
105 Frequency::Minutely | Frequency::Secondly => -60..=60,
106 };
107 if let Err(value) = validate_range_for_vec_error(&range, &rrule.by_set_pos) {
108 return Err(ValidationError::InvalidFieldValueRangeWithFreq {
109 field: "BYSETPOS".into(),
110 value: value.to_string(),
111 freq: rrule.freq,
112 start_idx: range.start().to_string(),
113 end_idx: range.end().to_string(),
114 });
115 }
116 // - It MUST only be used in conjunction with another BYxxx rule part.
117 if !rrule.by_set_pos.is_empty()
118 && rrule.by_easter.is_none()
119 && rrule.by_hour.is_empty()
120 && rrule.by_minute.is_empty()
121 && rrule.by_second.is_empty()
122 && rrule.by_month_day.is_empty()
123 && rrule.by_month.is_empty()
124 && rrule.by_year_day.is_empty()
125 && rrule.by_week_no.is_empty()
126 && rrule.by_weekday.is_empty()
127 {
128 return Err(ValidationError::BySetPosWithoutByRule);
129 }
130 Ok(())
131 }
132
133 // By_month:
134 // - Can be a value from 1 to 12.
135 fn validate_by_month(
136 rrule: &RRule<Unvalidated>,
137 _dt_start: &chrono::DateTime<Tz>,
138 ) -> Result<(), ValidationError> {
139 validate_range_for_vec(&MONTH_RANGE, &rrule.by_month, "BYMONTH")
140 }
141
142 // By_month_day:
143 // - Can be a value from -31 to -1 and 1 to 31.
144 fn validate_by_month_day(
145 rrule: &RRule<Unvalidated>,
146 _dt_start: &chrono::DateTime<Tz>,
147 ) -> Result<(), ValidationError> {
148 validate_not_equal_for_vec(&0, &rrule.by_month_day, "BYMONTHDAY")?;
149 validate_range_for_vec(&(-31..=31), &rrule.by_month_day, "BYMONTHDAY")?;
150 // - MUST NOT be specified when the FREQ rule part is set to WEEKLY.
151 // Validated below
152 if !rrule.by_month_day.is_empty() {
153 let valid = rrule.freq != Frequency::Weekly;
154 if !valid {
155 return Err(ValidationError::InvalidByRuleAndFrequency {
156 by_rule: "BYMONTHDAY".into(),
157 freq: rrule.freq,
158 });
159 }
160 }
161 Ok(())
162 }
163
164 // By_year_day:
165 // - Can be a value from -366 to -1 and 1 to 366.
166 fn validate_by_year_day(
167 rrule: &RRule<Unvalidated>,
168 _dt_start: &chrono::DateTime<Tz>,
169 ) -> Result<(), ValidationError> {
170 validate_not_equal_for_vec(&0, &rrule.by_year_day, "BYYEARDAY")?;
171 validate_range_for_vec(&(-366..=366), &rrule.by_year_day, "BYYEARDAY")?;
172 // - MUST NOT be specified when the FREQ rule part is set to DAILY, WEEKLY, or MONTHLY.
173 // Validated below
174 if !rrule.by_year_day.is_empty() {
175 let valid = !matches!(
176 rrule.freq,
177 Frequency::Monthly | Frequency::Weekly | Frequency::Daily
178 );
179 if !valid {
180 return Err(ValidationError::InvalidByRuleAndFrequency {
181 by_rule: "BYYEARDAY".into(),
182 freq: rrule.freq,
183 });
184 }
185 }
186 Ok(())
187 }
188 // By_week_no:
189 // - Can be a value from -53 to -1 and 1 to 53.
190 fn validate_by_week_number(
191 rrule: &RRule<Unvalidated>,
192 _dt_start: &chrono::DateTime<Tz>,
193 ) -> Result<(), ValidationError> {
194 validate_not_equal_for_vec(&0, &rrule.by_week_no, "BYWEEKNO")?;
195 validate_range_for_vec(&(-53..=53), &rrule.by_week_no, "BYWEEKNO")?;
196 // - MUST NOT be used when the FREQ rule part is set to anything other than YEARLY.
197 // Validated below
198 if !rrule.by_week_no.is_empty() {
199 let valid = rrule.freq == Frequency::Yearly;
200 if !valid {
201 return Err(ValidationError::InvalidByRuleAndFrequency {
202 by_rule: "BYWEEKNO".into(),
203 freq: rrule.freq,
204 });
205 }
206 }
207 Ok(())
208 }
209
210 // By_weekday:
211 // - Check if value for `Nth` is within range.
212 // The Range depends on frequency and can only happen weekly, so `/7` from normal count.
213 fn validate_by_weekday(
214 rrule: &RRule<Unvalidated>,
215 _dt_start: &chrono::DateTime<Tz>,
216 ) -> Result<(), ValidationError> {
217 let range = match rrule.freq {
218 Frequency::Yearly | Frequency::Daily => (-366 / 7)..=(366 / 7 + 1), // TODO is the daily range correct?
219 Frequency::Monthly => (-31 / 7)..=(31 / 7 + 1),
220 Frequency::Weekly => (-53 / 7)..=(53 / 7 + 1),
221 Frequency::Hourly => (-24 / 7)..=(24 / 7 + 1),
222 Frequency::Minutely | Frequency::Secondly => (-60 / 7)..=(60 / 7 + 1),
223 };
224 for item in &rrule.by_weekday {
225 if let NWeekday::Nth(number, _weekday) = item {
226 // If value not in range = error
227 if !range.contains(number) {
228 return Err(ValidationError::InvalidFieldValueRangeWithFreq {
229 field: "BYDAY".into(),
230 value: number.to_string(),
231 freq: rrule.freq,
232 start_idx: range.start().to_string(),
233 end_idx: range.end().to_string(),
234 });
235 }
236 }
237 }
238 Ok(())
239 }
240
241 // By_hour:
242 // - Can be a value from 0 to 23.
243 fn validate_by_hour(
244 rrule: &RRule<Unvalidated>,
245 _dt_start: &chrono::DateTime<Tz>,
246 ) -> Result<(), ValidationError> {
247 validate_range_for_vec(&(0..=23), &rrule.by_hour, "BYHOUR")
248 }
249
250 // By_minute:
251 // - Can be a value from 0 to 59.
252 fn validate_by_minute(
253 rrule: &RRule<Unvalidated>,
254 _dt_start: &chrono::DateTime<Tz>,
255 ) -> Result<(), ValidationError> {
256 validate_range_for_vec(&(0..=59), &rrule.by_minute, "BYMINUTE")
257 }
258
259 // By_second:
260 // - Can be a value from 0 to 59.
261 fn validate_by_second(
262 rrule: &RRule<Unvalidated>,
263 _dt_start: &chrono::DateTime<Tz>,
264 ) -> Result<(), ValidationError> {
265 validate_range_for_vec(&(0..=59), &rrule.by_second, "BYSECOND")
266 }
267
268 fn validate_by_easter(
269 rrule: &RRule<Unvalidated>,
270 _dt_start: &chrono::DateTime<Tz>,
271 ) -> Result<(), ValidationError> {
272 #[cfg(feature = "by-easter")]
273 {
274 // By_easter:
275 // - Can be a value from -366 to 366.
276 // Validated below
277 if let Some(by_easter) = &rrule.by_easter {
278 validate_range_for_vec(&(-366..=366), &[*by_easter], "BYEASTER")?;
279 }
280 // - Can only be used on frequency: Yearly, Monthly, Daily
281 // Validated below
282 if rrule.by_easter.is_some() {
283 let valid = matches!(
284 rrule.freq,
285 Frequency::Yearly | Frequency::Monthly | Frequency::Daily
286 );
287 if !valid {
288 return Err(ValidationError::InvalidByRuleAndFrequency {
289 by_rule: "BYEASTER".into(),
290 freq: rrule.freq,
291 });
292 }
293 }
294 // - Can only be used when `by_hour`, `by_minute` and `by_second` are used.
295 // TODO don't know why this is true, but seems to loop forever otherwise.
296 if rrule.by_easter.is_some()
297 && (rrule.by_hour.is_empty()
298 || rrule.by_minute.is_empty()
299 || rrule.by_second.is_empty())
300 {
301 return Err(ValidationError::InvalidByRuleWithByEaster);
302 }
303 }
304 #[cfg(not(feature = "by-easter"))]
305 {
306 if rrule.by_easter.is_some() {
307 log::warn!(
308 "The `by-easter` feature flag is not set, but `by_easter` is used.\
309 The `by_easter` will be ignored, as if it was set to `None`."
310 );
311 }
312 }
313 Ok(())
314 }
315
316 fn validate_range_for_vec_error<'a, T: PartialOrd>(
317 range: &RangeInclusive<T>,
318 list: &'a [T],
319 ) -> Result<(), &'a T> {
320 for item in list {
321 // If value not in range = error
322 if !range.contains(item) {
323 return Err(item);
324 }
325 }
326 Ok(())
327 }
328
329 fn validate_range_for_vec<T: PartialOrd + ToString>(
330 range: &RangeInclusive<T>,
331 list: &[T],
332 field: &str,
333 ) -> Result<(), ValidationError> {
334 for item in list {
335 // If value not in range = error
336 if !range.contains(item) {
337 return Err(ValidationError::InvalidFieldValueRange {
338 field: field.to_string(),
339 value: item.to_string(),
340 start_idx: range.start().to_string(),
341 end_idx: range.end().to_string(),
342 });
343 }
344 }
345 Ok(())
346 }
347
348 fn validate_not_equal_for_vec<T: PartialEq<T> + ToString>(
349 value: &T,
350 list: &[T],
351 field: &str,
352 ) -> Result<(), ValidationError> {
353 if list.iter().any(|item| item == value) {
354 return Err(ValidationError::InvalidFieldValue {
355 field: field.to_string(),
356 value: value.to_string(),
357 });
358 }
359 Ok(())
360 }
361
362 #[cfg(test)]
363 mod tests {
364 use chrono::TimeZone;
365
366 use crate::core::Tz;
367
368 use super::*;
369
370 const UTC: Tz = Tz::UTC;
371
372 #[test]
373 fn rejects_by_set_pos_without_byxxx_rule() {
374 let rrule = RRule {
375 by_set_pos: vec![-1],
376 ..Default::default()
377 };
378 let dt_start = UTC.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap();
379 let res = validate_rrule_forced(&rrule, &dt_start);
380 assert!(res.is_err());
381 let err = res.unwrap_err();
382 assert_eq!(err, ValidationError::BySetPosWithoutByRule);
383
384 // When creating RRule directly,
385 // if `rrule.by_set_hour` is empty, then it is going to default to
386 // `dt_start.hour()`, therefore, there is always a BYXXX
387 // rule, and the rrule is accepted.
388 let res = rrule.build(dt_start);
389 assert!(res.is_ok());
390 }
391
392 #[test]
393 fn rejects_by_rule_field_with_invalid_value() {
394 let tests = [
395 (
396 "BYSETPOS",
397 RRule {
398 by_set_pos: vec![0],
399 ..Default::default()
400 },
401 ),
402 (
403 "BYSETPOS",
404 RRule {
405 by_set_pos: vec![1, -2, 0],
406 ..Default::default()
407 },
408 ),
409 (
410 "BYMONTHDAY",
411 RRule {
412 by_month_day: vec![0],
413 ..Default::default()
414 },
415 ),
416 (
417 "BYYEARDAY",
418 RRule {
419 by_year_day: vec![0],
420 ..Default::default()
421 },
422 ),
423 ];
424 for (field, rrule) in tests {
425 let res =
426 validate_rrule_forced(&rrule, &UTC.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap());
427 assert!(res.is_err());
428 let err = res.unwrap_err();
429 assert_eq!(
430 err,
431 ValidationError::InvalidFieldValue {
432 field: field.into(),
433 value: "0".into()
434 }
435 );
436 }
437 }
438
439 #[test]
440 fn rejects_by_rule_field_with_value_outside_allowed_range() {
441 let tests = [
442 (
443 "BYMONTHDAY",
444 RRule {
445 by_month_day: vec![34],
446 ..Default::default()
447 },
448 "34",
449 "-31",
450 "31",
451 ),
452 (
453 "BYYEARDAY",
454 RRule {
455 by_year_day: vec![17, 400],
456 ..Default::default()
457 },
458 "400",
459 "-366",
460 "366",
461 ),
462 ];
463 for (field, rrule, value, start_idx, end_idx) in tests {
464 let res =
465 validate_rrule_forced(&rrule, &UTC.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap());
466 assert!(res.is_err());
467 let err = res.unwrap_err();
468 assert_eq!(
469 err,
470 ValidationError::InvalidFieldValueRange {
471 field: field.into(),
472 value: value.into(),
473 start_idx: start_idx.into(),
474 end_idx: end_idx.into()
475 }
476 );
477 }
478 }
479
480 #[test]
481 fn rejects_by_rule_value_outside_allowed_freq_range() {
482 let tests = [
483 (
484 "BYSETPOS",
485 RRule {
486 freq: Frequency::Hourly,
487 by_set_pos: vec![30],
488 ..Default::default()
489 },
490 "30",
491 "-24",
492 "24",
493 ),
494 (
495 "BYSETPOS",
496 RRule {
497 freq: Frequency::Yearly,
498 by_set_pos: vec![400],
499 ..Default::default()
500 },
501 "400",
502 "-366",
503 "366",
504 ),
505 ];
506 for (field, rrule, value, start_idx, end_idx) in tests {
507 let res =
508 validate_rrule_forced(&rrule, &UTC.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap());
509 assert!(res.is_err());
510 let err = res.unwrap_err();
511 assert_eq!(
512 err,
513 ValidationError::InvalidFieldValueRangeWithFreq {
514 field: field.into(),
515 freq: rrule.freq,
516 value: value.into(),
517 start_idx: start_idx.into(),
518 end_idx: end_idx.into(),
519 }
520 );
521 }
522 }
523
524 #[test]
525 fn rejects_invalid_by_rule_and_freq_combos() {
526 let tests = [
527 (
528 "BYMONTHDAY",
529 RRule {
530 freq: Frequency::Weekly,
531 by_month_day: vec![-1],
532 ..Default::default()
533 },
534 ),
535 (
536 "BYYEARDAY",
537 RRule {
538 freq: Frequency::Monthly,
539 by_year_day: vec![120],
540 ..Default::default()
541 },
542 ),
543 (
544 "BYYEARDAY",
545 RRule {
546 freq: Frequency::Weekly,
547 by_year_day: vec![120],
548 ..Default::default()
549 },
550 ),
551 (
552 "BYYEARDAY",
553 RRule {
554 freq: Frequency::Daily,
555 by_year_day: vec![120],
556 ..Default::default()
557 },
558 ),
559 ];
560 for (field, rrule) in tests {
561 let res =
562 validate_rrule_forced(&rrule, &UTC.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap());
563 assert!(res.is_err());
564 let err = res.unwrap_err();
565 assert_eq!(
566 err,
567 ValidationError::InvalidByRuleAndFrequency {
568 by_rule: field.into(),
569 freq: rrule.freq
570 }
571 );
572 }
573 }
574
575 #[test]
576 fn rejects_start_date_after_until() {
577 let rrule = RRule {
578 until: Some(UTC.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap()),
579 ..Default::default()
580 };
581 let dt_start = UTC.with_ymd_and_hms(2020, 1, 2, 0, 0, 0).unwrap();
582 let res = validate_rrule_forced(&rrule, &dt_start);
583 assert!(res.is_err());
584 let err = res.unwrap_err();
585 assert_eq!(
586 err,
587 ValidationError::UntilBeforeStart {
588 until: rrule.until.unwrap().to_rfc3339(),
589 dt_start: dt_start.to_rfc3339()
590 }
591 );
592 }
593
594 #[test]
595 fn allows_until_with_compatible_timezone() {
596 fn t(start_tz: Tz, until_tz: Tz) -> (chrono::DateTime<Tz>, chrono::DateTime<Tz>) {
597 (
598 start_tz.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap(),
599 until_tz.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap(),
600 )
601 }
602
603 let tests = [t(Tz::LOCAL, Tz::LOCAL), t(Tz::LOCAL, UTC), t(UTC, UTC)];
604
605 for (start_date, until) in tests {
606 let rrule = RRule {
607 until: Some(until),
608 ..Default::default()
609 };
610 let res = validate_rrule_forced(&rrule, &start_date);
611 assert!(res.is_ok());
612 }
613 }
614
615 #[test]
616 fn rejects_until_with_incompatible_timezone() {
617 fn t(start_tz: Tz, until_tz: Tz) -> (chrono::DateTime<Tz>, chrono::DateTime<Tz>) {
618 (
619 start_tz.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap(),
620 until_tz.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap(),
621 )
622 }
623
624 let tests = [
625 t(Tz::UTC, Tz::LOCAL),
626 t(Tz::Europe__Berlin, Tz::LOCAL),
627 t(Tz::LOCAL, Tz::Europe__Berlin),
628 ];
629
630 for (start_date, until) in tests {
631 let rrule = RRule {
632 until: Some(until),
633 ..Default::default()
634 };
635 let res = validate_rrule_forced(&rrule, &start_date);
636 assert!(res.is_err());
637 let err = res.unwrap_err();
638 assert!(matches!(
639 err,
640 ValidationError::DtStartUntilMismatchTimezone { .. }
641 ));
642 }
643 }
644 }