package docx_test import ( "archive/zip" "bytes" "encoding/json" "errors" "fmt" "io" "strings" "testing" "unicode" "github.com/carlosframework/docs/internal/docx" "github.com/carlosframework/docs/internal/export" ) // The fixtures in this file are SYNTHESIZED: OOXML written by hand in the // shapes Google Docs' DOCX export uses (its namespaces, its styles, a link // as w:hyperlink, a suggestion as w:ins/w:del, a table, a list paragraph). // None of them is a real Google export. A real export, with permission to // commit its contents, has not been supplied; until one is, this reader's // agreement with Google's actual output is unproven beyond these shapes, // and the gap is recorded in the branch discussion. const docNS = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ` + `xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ` + `xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ` + `xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ` + `xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" mc:Ignorable="w14"` // googleStyles is a styles part shaped like Google's: Arial 11pt as the // document default and on Normal, and the named heading, title and // subtitle styles. const googleStyles = `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` // The link targets are hostile on purpose. Import never reads the // relationships part, so none of them may appear anywhere in its output. const hostileRels = `` + `` + `` + `` + `` + `` func run(props, text string) string { if props != "" { props = "" + props + "" } return `` + props + `` + text + `` } func para(style, content string) string { ppr := "" if style != "" { ppr = `` } return `` + ppr + content + `` } // googleShaped is the synthesized fixture: every container whose text the // old reader lost, plus the omissions the report must name. func googleShaped(t *testing.T) []byte { t.Helper() body := para("Title", run("", "Quarterly plan")) + para("Heading1", run("", "Summary")) + // A link, inside a paragraph, with hostile targets in the rels. para("", run("", "Visit ")+`our site`+run("", ".")) + // Explicit bold off, the true spellings of on, and italic. para("", run(``, "not bold, ")+run(``, "bold, ")+run(``, "off again, ")+run(``, "both")) + // A list item. `` + run("", "First item") + `` + // A table, with a nested table in one cell. `` + para("", run("", "A1")) + `` + para("", run("", "B1")) + `` + `` + para("", run("", "A2")) + `` + para("", run("", "inner")) + `` + para("", run("", "B2")) + `` + // A suggestion: an insertion is kept, a deletion is not. para("", run("", "Kept ")+``+run("", "added")+``+ `removed`+run("", " text")) + // A block content control and a smart tag. `` + para("", run("", "in a control")) + `` + para("", ``+run("", "Smart")+``+` `+run("", " inline")+``) + // A tab, a line break and a page break. para("", `beforeafternext linenext page`) + // An image, a footnote, a comment, a size off the ladder, an // unknown face, a centred paragraph, a heading level. para("", ``+run("", "Caption")+``+ ``+run(``, "fifteen")+``+ run(``, " comic")+run(``, " fourteen")) + `` + run("", "Centred") + `` + para("Subtitle", run("", "A subtitle")) + para("Heading2", run(``, "Serif heading")) + para("", "") + `` return zipOf(t, map[string]string{ "[Content_Types].xml": ``, "word/document.xml": `` + body + ``, "word/styles.xml": googleStyles, "word/_rels/document.xml.rels": hostileRels, "word/comments.xml": ``, }) } func zipOf(t *testing.T, parts map[string]string) []byte { t.Helper() var buf bytes.Buffer z := zip.NewWriter(&buf) for name, body := range parts { w, err := z.Create(name) if err != nil { t.Fatal(err) } io.WriteString(w, body) } if err := z.Close(); err != nil { t.Fatal(err) } return buf.Bytes() } // shape renders a document as one line per block: its type, then each // run as text{marks}. func shape(d export.Document) []string { var out []string for _, b := range d.Root.Content { line := b.Type if b.Type == "heading" { line += fmt.Sprint(b.Attrs.Level) } line += ":" for _, r := range b.Content { var marks []string for _, m := range r.Marks { marks = append(marks, m.Type) } line += r.Text if len(marks) > 0 { line += "{" + strings.Join(marks, ",") + "}" } line += "|" } out = append(out, line) } return out } func TestImportReadsEveryContainerGoogleExportsTextIn(t *testing.T) { res, err := docx.Import(googleShaped(t)) if err != nil { t.Fatal(err) } // Arial is Liberation Sans (font_sans) and 11pt is size_11, Google's // default, so ordinary runs carry both; headings carry no inherited // size, because a heading's size is its level's here. const body = "font_sans,size_11" want := []string{ "heading1:Quarterly plan{font_sans}|", "heading1:Summary{font_sans}|", "paragraph:Visit {" + body + "}|our site{" + body + "}|.{" + body + "}|", "paragraph:not bold, {" + body + "}|bold, {" + body + ",strong}|off again, {" + body + "}|both{" + body + ",strong,em}|", "paragraph:First item{" + body + "}|", "paragraph:A1{" + body + "}|", "paragraph:B1{" + body + "}|", "paragraph:A2{" + body + "}|", "paragraph:inner{" + body + "}|", "paragraph:B2{" + body + "}|", "paragraph:Kept {" + body + "}|added{" + body + "}| text{" + body + "}|", "paragraph:in a control{" + body + "}|", "paragraph:Smart{" + body + "}| inline{" + body + "}|", "paragraph:before{" + body + "}| {" + body + "}|after{" + body + "}|", "paragraph:next line{" + body + "}|", "paragraph:next page{" + body + "}|", "paragraph:Caption{" + body + "}|fifteen{font_sans}| comic{size_11}| fourteen{font_sans,size_14}|", "paragraph:Centred{" + body + "}|", "paragraph:A subtitle{font_sans}|", "heading2:Serif heading{font_serif}|", "paragraph:", } got := shape(res.Document) if strings.Join(got, "\n") != strings.Join(want, "\n") { t.Errorf("document\n got:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) } type line struct { count int where string names string } wantReport := map[docx.Code]line{ docx.CodeTableFlattened: {2, "6,9", ""}, docx.CodeListFlattened: {1, "5", ""}, docx.CodeLinkTextKept: {1, "3", ""}, docx.CodeInsertionKept: {1, "11", ""}, docx.CodeDeletionOmitted: {1, "11", ""}, docx.CodeObjectOmitted: {1, "17", ""}, docx.CodeNotesOmitted: {1, "17", ""}, docx.CodeCommentsOmitted: {1, "17", ""}, docx.CodeHeadersOmitted: {1, "", ""}, docx.CodeTitleAsHeading: {1, "1", ""}, docx.CodeSubtitleAsParagraph: {1, "19", ""}, docx.CodeFontSubstituted: {1, "17", ""}, docx.CodeSizeDropped: {2, "17,19", ""}, docx.CodeFormattingLost: {2, "3,19", ""}, docx.CodeAlignmentLost: {1, "18", ""}, docx.CodeTabAsSpace: {1, "14", ""}, docx.CodeLineBreakSplit: {1, "15", ""}, docx.CodePageBreakSplit: {1, "16", ""}, } gotReport := map[docx.Code]line{} for _, it := range res.Report.Items { var where []string for _, p := range it.Paragraphs { where = append(where, fmt.Sprint(p)) } gotReport[it.Code] = line{it.Count, strings.Join(where, ","), ""} } for code, w := range wantReport { if g, ok := gotReport[code]; !ok { t.Errorf("report has no %s", code) } else if g != w { t.Errorf("report %s: got %+v, want %+v", code, g, w) } } for code := range gotReport { if _, ok := wantReport[code]; !ok { t.Errorf("report has an unexpected %s: %+v", code, gotReport[code]) } } // The report lists in Codes order. at := map[docx.Code]int{} for i, c := range docx.Codes { at[c] = i } for i := 1; i < len(res.Report.Items); i++ { if at[res.Report.Items[i-1].Code] > at[res.Report.Items[i].Code] { t.Errorf("report out of order at %d", i) } } } // The reader this replaced bound w:body>w:p>w:r>w:t alone and read w:b // by presence, with no error and no report. Run against it (its Read at // 056b94d), the first eleven cases below failed: link, table, insertion, // both content controls, smart tag and field text came back missing, // bold-off and italic-off came back on, and a tab or break joined its // neighbours. The last two passed there too; they are here because a // walk that descends into everything could get them wrong where an // unmarshal into fixed paths could not. func TestImportKeepsWhatTheOldReaderLost(t *testing.T) { for _, c := range []struct { name, body, want string }{ {"link", para("", ``+run("", "linked")+``), "paragraph:linked|"}, {"table", `` + para("", run("", "cell")) + ``, "paragraph:cell|"}, {"insertion", para("", ``+run("", "inserted")+``), "paragraph:inserted|"}, {"block content control", `` + para("", run("", "controlled")) + ``, "paragraph:controlled|"}, {"inline content control", para("", ``+run("", "inline")+``), "paragraph:inline|"}, {"smart tag", para("", ``+run("", "tagged")+``), "paragraph:tagged|"}, {"simple field", para("", ``+run("", "7")+``), "paragraph:7|"}, {"bold off", para("", run(``, "plain")), "paragraph:plain|"}, {"italic off", para("", run(``, "plain")), "paragraph:plain|"}, {"tab", para("", `ab`), "paragraph:a| |b|"}, {"break", para("", `ab`), "paragraph:a|\nparagraph:b|"}, {"deletion is not text", para("", run("", "kept")+`gone`), "paragraph:kept|"}, {"paragraph mark properties are not the run's", `` + run("", "plain") + ``, "paragraph:plain|"}, } { data := zipOf(t, map[string]string{ "word/document.xml": `` + c.body + ``, }) res, err := docx.Import(data) if err != nil { t.Errorf("%s: %v", c.name, err) continue } if got := strings.Join(shape(res.Document), "\n"); got != c.want { t.Errorf("%s: got %q, want %q", c.name, got, c.want) } } } // Bold and italic come through the whole cascade: document default, // paragraph style chain, character style, run, with an explicit off at // any nearer level winning. What a style carries that Docs cannot hold is // reported for the paragraphs it reaches, not dropped in silence. func TestImportFollowsTheStyleCascade(t *testing.T) { styles := `` + `` + `` + `` + `` + `` + `` + `` + `` + `` body := para("", run("", "default italic")) + para("Strong", run("", "style bold")+run(``, "run says not bold")) + para("StrongChild", run("", "inherited bold, italic off")) + para("", run(``, "character style, italic off")+run(``, "character style")) + para("Red", run("", "red")) + para("Centred", run("", "centred")) + `` + run("", "left after all") + `` + para("Heading1", run("", "heading")) res, err := docx.Import(zipOf(t, map[string]string{ "word/styles.xml": styles, "word/document.xml": `` + body + ``, })) if err != nil { t.Fatal(err) } want := []string{ "paragraph:default italic{em}|", "paragraph:style bold{strong,em}|run says not bold{em}|", "paragraph:inherited bold, italic off{strong}|", "paragraph:character style, italic off|character style{em}|", "paragraph:red{em}|", "paragraph:centred{em}|", "paragraph:left after all{em}|", "heading1:heading|", } if got := strings.Join(shape(res.Document), "\n"); got != strings.Join(want, "\n") { t.Errorf("document\n got:\n%s\nwant:\n%s", got, strings.Join(want, "\n")) } where := map[docx.Code]string{} for _, it := range res.Report.Items { var ps []string for _, p := range it.Paragraphs { ps = append(ps, fmt.Sprint(p)) } where[it.Code] = strings.Join(ps, ",") } if where[docx.CodeFormattingLost] != "4,5" { t.Errorf("formatting lost at %q, want the underlined character style (4) and the red paragraph style (5)", where[docx.CodeFormattingLost]) } if where[docx.CodeAlignmentLost] != "6" { t.Errorf("alignment lost at %q, want the centred style's paragraph only (6)", where[docx.CodeAlignmentLost]) } } func TestImportNeverReadsALinkTarget(t *testing.T) { res, err := docx.Import(googleShaped(t)) if err != nil { t.Fatal(err) } out, _ := json.Marshal(res) for _, s := range []string{"javascript", "alert", "/etc/passwd", "169.254", "rId9", "Someone"} { if strings.Contains(string(out), s) { t.Errorf("the result carries %q from the file's metadata", s) } } // The report is closed metadata: codes, counts and paragraph // numbers. No text from the file, and no face name either. rep, _ := json.Marshal(res.Report) for _, s := range []string{"Comic", "Arial", "Quarterly", "Summary", "our site", "removed"} { if strings.Contains(string(rep), s) { t.Errorf("the report quotes %q from the file", s) } } } func TestImportDropsControlCharacters(t *testing.T) { data := zipOf(t, map[string]string{ "word/document.xml": `` + para("", run("", "a\u0085b c\nd")) + ``, }) res, err := docx.Import(data) if err != nil { t.Fatal(err) } if got := strings.Join(shape(res.Document), ""); got != "paragraph:ab c d|" { t.Errorf("got %q", got) } } func TestImportRefusals(t *testing.T) { doc := func(body string) map[string]string { return map[string]string{"word/document.xml": `` + body + ``} } deep := strings.Repeat(``, 300) + para("", run("", "x")) + strings.Repeat(``, 300) many := map[string]string{"word/document.xml": doc(para("", run("", "x")))["word/document.xml"]} for i := 0; i < 1001; i++ { many[fmt.Sprintf("word/media/%d.bin", i)] = "" } cases := []struct { name string data []byte want error }{ {"not a zip", []byte("%PDF-1.7 not a word file"), docx.ErrNotWord}, {"no document part", zipOf(t, map[string]string{"word/styles.xml": googleStyles}), docx.ErrNotWord}, {"a spreadsheet", zipOf(t, map[string]string{"xl/workbook.xml": ""}), docx.ErrNotWord}, {"wrong root", zipOf(t, map[string]string{"word/document.xml": ``}), docx.ErrNotWord}, {"not well formed", zipOf(t, doc(``)), docx.ErrMalformed}, {"a DTD", zipOf(t, map[string]string{"word/document.xml": `]>`}), docx.ErrMalformed}, {"too deep", zipOf(t, doc(deep)), docx.ErrMalformed}, {"too many entries", zipOf(t, many), docx.ErrTooLarge}, {"nothing but empty paragraphs", zipOf(t, doc(para("", "")+para("", ``))), docx.ErrEmpty}, {"only deleted text", zipOf(t, doc(para("", `x`))), docx.ErrEmpty}, {"too many blocks", zipOf(t, doc(strings.Repeat(para("", run("", "x")), 5_001))), docx.ErrTooLarge}, {"too much text", zipOf(t, doc(para("", run("", strings.Repeat("x", 512<<10+1))))), docx.ErrTooLarge}, {"too many runs", zipOf(t, doc(para("", strings.Repeat(run("", "x"), 10_001)))), docx.ErrTooLarge}, } for _, c := range cases { if _, err := docx.Import(c.data); !errors.Is(err, c.want) { t.Errorf("%s: got %v, want %v", c.name, err, c.want) } } } // A part whose decompressed size is far past its compressed one is // refused from the bytes actually read, not from the header's claim. func TestImportCountsDecompressedBytes(t *testing.T) { var buf bytes.Buffer z := zip.NewWriter(&buf) w, _ := z.Create("word/document.xml") io.WriteString(w, ``) pad := bytes.Repeat([]byte(" "), 1<<20) for i := 0; i < 33; i++ { w.Write(pad) } io.WriteString(w, ``) z.Close() if buf.Len() > 1<<20 { t.Fatalf("the bomb is %d bytes compressed; the test means a small file", buf.Len()) } if _, err := docx.Import(buf.Bytes()); !errors.Is(err, docx.ErrTooLarge) { t.Errorf("got %v, want ErrTooLarge", err) } } func TestImportRefusesADuplicatedPart(t *testing.T) { var buf bytes.Buffer z := zip.NewWriter(&buf) for _, body := range []string{para("", run("", "one")), para("", run("", "two"))} { w, _ := z.Create("word/document.xml") io.WriteString(w, ``+body+``) } z.Close() if _, err := docx.Import(buf.Bytes()); !errors.Is(err, docx.ErrMalformed) { t.Errorf("got %v, want ErrMalformed", err) } } // Whatever the bytes, Import either refuses with one of its own errors // or returns runs the builder accepts: non-empty, no control character. func FuzzImport(f *testing.F) { var tb testing.T f.Add(googleShaped(&tb)) f.Add([]byte("PK\x03\x04")) f.Fuzz(func(t *testing.T, data []byte) { res, err := docx.Import(data) if err != nil { for _, known := range []error{docx.ErrNotWord, docx.ErrMalformed, docx.ErrTooLarge, docx.ErrEmpty} { if errors.Is(err, known) { return } } t.Fatalf("unexpected error %v", err) } for _, b := range res.Document.Root.Content { for _, r := range b.Content { if r.Text == "" || strings.IndexFunc(r.Text, unicode.IsControl) >= 0 { t.Fatalf("a run the builder would refuse: %q", r.Text) } } } }) }