tftio-asana-cli 3.1.0

An interface to the Asana API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Asana rich text preparation and validation.
//!
//! The Asana API requires HTML rich text fields (`html_notes`, `html_text`) to
//! be valid XML wrapped in `<body>` tags, drawn from a fixed tag whitelist that
//! varies by object context, with attributes permitted only on a small set of
//! tags. This module rejects invalid documents locally so that we don't burn
//! API calls on payloads Asana would 400.
//!
//! Pipeline:
//! 1. Wrap content in `<body>` tags if missing.
//! 2. Escape bare ampersands that are not part of XML entity references.
//! 3. Walk the parsed XML asserting:
//!    - root element is `<body>`,
//!    - every element is in the context-specific tag whitelist,
//!    - every attribute is on a tag that allows attributes and is in that
//!      tag's attribute whitelist,
//!    - `data-asana-type` values are in the documented enum,
//!    - nesting rules are honoured (no headers/blockquote/pre inside list
//!      items, no lists inside headers/blockquote/pre).
//!
//! Reference: <https://developers.asana.com/docs/rich-text>

use regex::Regex;
use std::sync::LazyLock;
use thiserror::Error;

/// The object context the rich text is being prepared for.
///
/// Determines which tags are permitted (e.g. `<h1>` is allowed in
/// `TaskNotes` but not in `StoryText`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RichTextContext {
    /// `html_notes` on a task. Allows the universal tags plus
    /// `h1`, `h2`, `hr`, `img`.
    TaskNotes,
    /// `html_text` on a story (comment). Universal tags only.
    StoryText,
    /// Project brief body. Allows everything `TaskNotes` does plus
    /// `table`, `tr`, `td`, `object`.
    ProjectBrief,
}

/// Errors from rich text preparation.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum RichTextError {
    /// Content failed XML well-formedness parsing.
    #[error("invalid rich text XML: {0}")]
    InvalidXml(String),
    /// Root element was not `<body>`.
    #[error("root element must be <body>, found <{0}>")]
    RootMustBeBody(String),
    /// Tag is not on Asana's whitelist for this context.
    #[error("unsupported tag <{tag}> for {context:?}")]
    UnsupportedTag {
        /// Offending tag name.
        tag: String,
        /// Context being validated against.
        context: RichTextContext,
    },
    /// Attribute appeared on a tag that does not accept attributes.
    #[error("attribute `{attr}` is not allowed on <{tag}>")]
    DisallowedAttribute {
        /// Tag the attribute appeared on.
        tag: String,
        /// Attribute name.
        attr: String,
    },
    /// `data-asana-type` carried a value outside the documented enum.
    #[error("invalid data-asana-type value: {0}")]
    InvalidDataAsanaType(String),
    /// Nesting violates Asana's structural rules.
    #[error("invalid nesting: <{child}> cannot appear inside <{parent}>")]
    InvalidNesting {
        /// Containing tag.
        parent: String,
        /// Forbidden child tag.
        child: String,
    },
}

/// Prepare an HTML rich text string for the Asana API.
///
/// # Errors
///
/// Returns [`RichTextError`] if the prepared content is not well-formed XML
/// or violates any of Asana's structural / whitelist rules for `context`.
pub fn prepare_rich_text(input: &str, context: RichTextContext) -> Result<String, RichTextError> {
    let wrapped = ensure_body_wrap(input);
    let escaped = escape_bare_ampersands(&wrapped);
    validate(&escaped, context)?;
    Ok(escaped)
}

/// Regex matching XML entity references (the part after the `&`).
static XML_ENTITY: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?:amp|lt|gt|quot|apos|#\d+|#x[0-9a-fA-F]+);")
        .expect("the regex literal is valid at compile time")
});

/// Wrap content in `<body>` tags if not already wrapped.
fn ensure_body_wrap(input: &str) -> String {
    let trimmed = input.trim();
    if trimmed.starts_with("<body>") && trimmed.ends_with("</body>") {
        return trimmed.to_string();
    }
    format!("<body>{trimmed}</body>")
}

/// Escape bare ampersands in the input.
fn escape_bare_ampersands(input: &str) -> String {
    let mut escaped = String::with_capacity(input.len());
    let mut iter = input.char_indices();

    while let Some((index, ch)) = iter.next() {
        if ch != '&' {
            escaped.push(ch);
            continue;
        }

        let tail_start = index + ch.len_utf8();
        let tail = &input[tail_start..];

        if let Some(entity) = XML_ENTITY.find(tail).filter(|matched| matched.start() == 0) {
            escaped.push('&');
            escaped.push_str(entity.as_str());
            for _ in 0..entity.as_str().chars().count() {
                let _ = iter.next();
            }
        } else {
            escaped.push_str("&amp;");
        }
    }

    escaped
}

/// Universal tags allowed in every context.
const UNIVERSAL_TAGS: &[&str] = &[
    "body",
    "strong",
    "em",
    "u",
    "s",
    "code",
    "a",
    "ol",
    "ul",
    "li",
    "blockquote",
    "pre",
];

/// Tags allowed in `TaskNotes` (and `ProjectBrief`) beyond universal.
const TASK_EXTRA_TAGS: &[&str] = &["h1", "h2", "hr", "img"];

/// Tags allowed only in `ProjectBrief` beyond `TaskNotes`.
const PROJECT_BRIEF_EXTRA_TAGS: &[&str] = &["table", "tr", "td", "object"];

/// Tags whose contents may not contain a list element.
const NO_LIST_INSIDE: &[&str] = &["h1", "h2", "blockquote", "pre"];

/// Tags forbidden inside a list item.
const FORBIDDEN_INSIDE_LI: &[&str] = &["h1", "h2", "blockquote", "pre"];

/// Allowed `<a>` attributes.
const A_ATTRS: &[&str] = &[
    "href",
    "data-asana-gid",
    "data-asana-type",
    "data-asana-project",
    "data-asana-tag",
    "data-asana-dynamic",
];

/// Allowed `<img>` attributes.
const IMG_ATTRS: &[&str] = &[
    "data-asana-gid",
    "src",
    "data-src-width",
    "data-src-height",
    "data-thumbnail-url",
    "data-thumbnail-width",
    "data-thumbnail-height",
    "style",
];

/// Allowed `<object>` attributes.
const OBJECT_ATTRS: &[&str] = &["type", "data-asana-gid", "data", "data-asana-type"];

/// Allowed values for the `data-asana-type` attribute.
const DATA_ASANA_TYPE_VALUES: &[&str] = &[
    "user",
    "task",
    "project",
    "tag",
    "conversation",
    "project_status",
    "team",
    "search",
    "attachment",
];

fn tag_allowed(tag: &str, context: RichTextContext) -> bool {
    if UNIVERSAL_TAGS.contains(&tag) {
        return true;
    }
    match context {
        RichTextContext::StoryText => false,
        RichTextContext::TaskNotes => TASK_EXTRA_TAGS.contains(&tag),
        RichTextContext::ProjectBrief => {
            TASK_EXTRA_TAGS.contains(&tag) || PROJECT_BRIEF_EXTRA_TAGS.contains(&tag)
        }
    }
}

fn allowed_attrs(tag: &str) -> Option<&'static [&'static str]> {
    match tag {
        "a" => Some(A_ATTRS),
        "img" => Some(IMG_ATTRS),
        "object" => Some(OBJECT_ATTRS),
        _ => None,
    }
}

/// Validate XML structure, tag/attribute whitelists, and nesting.
fn validate(input: &str, context: RichTextContext) -> Result<(), RichTextError> {
    use quick_xml::events::Event;
    use quick_xml::reader::Reader;

    let mut reader = Reader::from_str(input);
    let mut stack: Vec<String> = Vec::new();
    let mut saw_root = false;

    loop {
        match reader.read_event() {
            Ok(Event::Eof) => return Ok(()),
            Ok(Event::Start(e)) => {
                let tag = std::str::from_utf8(e.name().as_ref())
                    .map_err(|err| RichTextError::InvalidXml(err.to_string()))?
                    .to_string();
                check_element(&tag, &e, &stack, context, saw_root)?;
                saw_root = true;
                stack.push(tag);
            }
            Ok(Event::Empty(e)) => {
                let tag = std::str::from_utf8(e.name().as_ref())
                    .map_err(|err| RichTextError::InvalidXml(err.to_string()))?
                    .to_string();
                check_element(&tag, &e, &stack, context, saw_root)?;
                saw_root = true;
            }
            Ok(Event::End(_)) => {
                stack.pop();
            }
            Ok(_) => {}
            Err(error) => return Err(RichTextError::InvalidXml(error.to_string())),
        }
    }
}

fn check_element(
    tag: &str,
    bytes: &quick_xml::events::BytesStart,
    stack: &[String],
    context: RichTextContext,
    saw_root: bool,
) -> Result<(), RichTextError> {
    if !saw_root && tag != "body" {
        return Err(RichTextError::RootMustBeBody(tag.to_string()));
    }

    if !tag_allowed(tag, context) {
        return Err(RichTextError::UnsupportedTag {
            tag: tag.to_string(),
            context,
        });
    }

    check_nesting(tag, stack)?;
    check_attributes(tag, bytes)?;
    Ok(())
}

fn check_nesting(tag: &str, stack: &[String]) -> Result<(), RichTextError> {
    for ancestor in stack.iter().rev() {
        let a = ancestor.as_str();
        if a == "li" && FORBIDDEN_INSIDE_LI.contains(&tag) {
            return Err(RichTextError::InvalidNesting {
                parent: a.to_string(),
                child: tag.to_string(),
            });
        }
        if NO_LIST_INSIDE.contains(&a) && (tag == "ol" || tag == "ul" || tag == "li") {
            return Err(RichTextError::InvalidNesting {
                parent: a.to_string(),
                child: tag.to_string(),
            });
        }
    }
    Ok(())
}

fn check_attributes(tag: &str, bytes: &quick_xml::events::BytesStart) -> Result<(), RichTextError> {
    let allowed = allowed_attrs(tag);
    for attr in bytes.attributes() {
        let attr = attr.map_err(|err| RichTextError::InvalidXml(err.to_string()))?;
        let name = std::str::from_utf8(attr.key.as_ref())
            .map_err(|err| RichTextError::InvalidXml(err.to_string()))?
            .to_string();

        let Some(allow_list) = allowed else {
            return Err(RichTextError::DisallowedAttribute {
                tag: tag.to_string(),
                attr: name,
            });
        };

        if !allow_list.contains(&name.as_str()) {
            return Err(RichTextError::DisallowedAttribute {
                tag: tag.to_string(),
                attr: name,
            });
        }

        if name == "data-asana-type" {
            let value = attr
                .normalized_value(quick_xml::XmlVersion::Implicit1_0)
                .map_err(|err| RichTextError::InvalidXml(err.to_string()))?;
            if !DATA_ASANA_TYPE_VALUES.contains(&value.as_ref()) {
                return Err(RichTextError::InvalidDataAsanaType(value.into_owned()));
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn task(s: &str) -> Result<String, RichTextError> {
        prepare_rich_text(s, RichTextContext::TaskNotes)
    }
    fn story(s: &str) -> Result<String, RichTextError> {
        prepare_rich_text(s, RichTextContext::StoryText)
    }

    #[test]
    fn body_wrap_adds_tags_when_missing() {
        assert_eq!(
            ensure_body_wrap("<em>hello</em>"),
            "<body><em>hello</em></body>"
        );
    }

    #[test]
    fn body_wrap_preserves_existing_tags() {
        assert_eq!(
            ensure_body_wrap("<body><em>hello</em></body>"),
            "<body><em>hello</em></body>"
        );
    }

    #[test]
    fn body_wrap_handles_plain_text() {
        assert_eq!(ensure_body_wrap("hello world"), "<body>hello world</body>");
    }

    #[test]
    fn escape_bare_ampersand() {
        assert_eq!(escape_bare_ampersands("Tom & Jerry"), "Tom &amp; Jerry");
    }

    #[test]
    fn escape_preserves_existing_entities() {
        assert_eq!(escape_bare_ampersands("Tom &amp; Jerry"), "Tom &amp; Jerry");
    }

    #[test]
    fn escape_preserves_numeric_entities() {
        assert_eq!(escape_bare_ampersands("&#169; 2026"), "&#169; 2026");
    }

    #[test]
    fn escape_idempotent() {
        let once = escape_bare_ampersands("Tom & Jerry");
        let twice = escape_bare_ampersands(&once);
        assert_eq!(once, twice);
    }

    #[test]
    fn task_accepts_universal_tags() {
        assert!(task("<body><strong>bold</strong> <em>i</em> <code>x</code></body>").is_ok());
    }

    #[test]
    fn task_accepts_h1_and_hr() {
        assert!(task("<body><h1>Title</h1><hr/></body>").is_ok());
    }

    #[test]
    fn story_rejects_h1() {
        let err = story("<body><h1>Nope</h1></body>").unwrap_err();
        assert!(matches!(
            err,
            RichTextError::UnsupportedTag { ref tag, .. } if tag == "h1"
        ));
    }

    #[test]
    fn story_accepts_universal_tags() {
        assert!(story("<body><strong>x</strong> &amp; <em>y</em></body>").is_ok());
    }

    #[test]
    fn rejects_unknown_tag() {
        let err = task("<body><div>hi</div></body>").unwrap_err();
        assert!(matches!(
            err,
            RichTextError::UnsupportedTag { ref tag, .. } if tag == "div"
        ));
    }

    #[test]
    fn rejects_p_tag() {
        let err = task("<body><p>paragraph</p></body>").unwrap_err();
        assert!(matches!(err, RichTextError::UnsupportedTag { .. }));
    }

    #[test]
    fn rejects_attribute_on_strong() {
        let err = task(r#"<body><strong class="x">hi</strong></body>"#).unwrap_err();
        assert!(matches!(
            err,
            RichTextError::DisallowedAttribute { ref tag, ref attr }
                if tag == "strong" && attr == "class"
        ));
    }

    #[test]
    fn accepts_a_with_href_and_gid() {
        assert!(task(
            r#"<body><a href="https://x" data-asana-gid="123" data-asana-type="task">t</a></body>"#
        )
        .is_ok());
    }

    #[test]
    fn rejects_unknown_a_attribute() {
        let err = task(r#"<body><a target="_blank">x</a></body>"#).unwrap_err();
        assert!(matches!(
            err,
            RichTextError::DisallowedAttribute { ref attr, .. } if attr == "target"
        ));
    }

    #[test]
    fn rejects_invalid_data_asana_type() {
        let err = task(r#"<body><a data-asana-type="bogus">x</a></body>"#).unwrap_err();
        assert!(matches!(err, RichTextError::InvalidDataAsanaType(ref v) if v == "bogus"));
    }

    #[test]
    fn rejects_h1_inside_li() {
        let err = task("<body><ul><li><h1>nope</h1></li></ul></body>").unwrap_err();
        assert!(matches!(
            err,
            RichTextError::InvalidNesting { ref parent, ref child }
                if parent == "li" && child == "h1"
        ));
    }

    #[test]
    fn rejects_blockquote_inside_li() {
        let err = task("<body><ul><li><blockquote>x</blockquote></li></ul></body>").unwrap_err();
        assert!(matches!(err, RichTextError::InvalidNesting { .. }));
    }

    #[test]
    fn rejects_list_inside_blockquote() {
        let err = task("<body><blockquote><ul><li>x</li></ul></blockquote></body>").unwrap_err();
        assert!(matches!(
            err,
            RichTextError::InvalidNesting { ref parent, ref child }
                if parent == "blockquote" && child == "ul"
        ));
    }

    #[test]
    fn rejects_list_inside_pre() {
        let err = task("<body><pre><ol><li>x</li></ol></pre></body>").unwrap_err();
        assert!(matches!(err, RichTextError::InvalidNesting { .. }));
    }

    #[test]
    fn rejects_uppercase_tag() {
        let err = task("<BODY>x</BODY>").unwrap_err();
        // After ensure_body_wrap, the upper-case BODY remains; root check fails.
        assert!(
            matches!(
                err,
                RichTextError::UnsupportedTag { ref tag, .. } if tag == "BODY"
                    || tag.eq_ignore_ascii_case("body")
            ) || matches!(err, RichTextError::RootMustBeBody(_))
        );
    }

    #[test]
    fn accepts_self_closing_hr_in_task() {
        assert!(task("<body>line<hr/>end</body>").is_ok());
    }

    #[test]
    fn rejects_mismatched_tags() {
        let err = task("<body><em>x</strong></body>").unwrap_err();
        assert!(matches!(err, RichTextError::InvalidXml(_)));
    }

    #[test]
    fn prepare_wraps_and_validates() {
        let result = task("<em>hello</em>").unwrap();
        assert_eq!(result, "<body><em>hello</em></body>");
    }

    #[test]
    fn prepare_escapes_and_validates() {
        let result = task("<body>Tom & Jerry</body>").unwrap();
        assert_eq!(result, "<body>Tom &amp; Jerry</body>");
    }

    #[test]
    fn prepare_passes_valid_through() {
        let input = "<body><strong>bold</strong> &amp; done</body>";
        assert_eq!(task(input).unwrap(), input);
    }

    #[test]
    fn prepare_handles_nested_lists() {
        let input = "<body><ul><li>one</li><li>two</li></ul></body>";
        assert_eq!(task(input).unwrap(), input);
    }

    #[test]
    fn prepare_handles_link_attributes() {
        let input = r#"<body><a data-asana-gid="123" data-asana-type="task">t</a></body>"#;
        assert_eq!(task(input).unwrap(), input);
    }

    #[test]
    fn project_brief_allows_table() {
        let input = "<body><table><tr><td>cell</td></tr></table></body>";
        assert!(prepare_rich_text(input, RichTextContext::ProjectBrief).is_ok());
    }

    #[test]
    fn task_rejects_table() {
        let err = task("<body><table><tr><td>c</td></tr></table></body>").unwrap_err();
        assert!(matches!(err, RichTextError::UnsupportedTag { .. }));
    }
}