| 1 | package sheets |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "os" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | |
| 14 | "amadan.net/oficina/sheets/internal/sheets/sealtest" |
| 15 | "amadan.net/oficina/sheets/internal/sheets/store" |
| 16 | "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| 17 | ) |
| 18 | |
| 19 | // googleWorkbook is a two-worksheet workbook in the shapes a Google |
| 20 | // Sheets export writes: typed text that looks like a number, a sealed |
| 21 | // canary cell, a Google-only function wrapped in __xludf.DUMMYFUNCTION |
| 22 | // with its saved value, and a kept formula over them. |
| 23 | func googleWorkbook(t *testing.T, firstSheetRows string) []byte { |
| 24 | t.Helper() |
| 25 | const rel = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" |
| 26 | sheet := func(rows string) string { |
| 27 | return `<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>` + rows + `</sheetData></worksheet>` |
| 28 | } |
| 29 | parts := map[string]string{ |
| 30 | "[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>`, |
| 31 | "_rels/.rels": `<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="` + rel + `/officeDocument" Target="xl/workbook.xml"/></Relationships>`, |
| 32 | "xl/workbook.xml": `<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="` + rel + `"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/><sheet name="Sheet2" sheetId="2" r:id="rId2"/></sheets></workbook>`, |
| 33 | "xl/_rels/workbook.xml.rels": `<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="` + rel + `/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="` + rel + `/worksheet" Target="worksheets/sheet2.xml"/><Relationship Id="rIdS" Type="` + rel + `/styles" Target="styles.xml"/></Relationships>`, |
| 34 | "xl/styles.xml": `<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><sz val="10"/><name val="Arial"/></font></fonts><fills count="1"><fill><patternFill patternType="none"/></fill></fills><borders count="1"><border/></borders><cellStyleXfs count="1"><xf/></cellStyleXfs><cellXfs count="1"><xf xfId="0"/></cellXfs></styleSheet>`, |
| 35 | "xl/worksheets/sheet1.xml": sheet(firstSheetRows), |
| 36 | "xl/worksheets/sheet2.xml": sheet(`<row r="1"><c r="A1"><v>1</v></c></row>`), |
| 37 | } |
| 38 | var buf bytes.Buffer |
| 39 | zw := zip.NewWriter(&buf) |
| 40 | for name, body := range parts { |
| 41 | w, err := zw.Create(name) |
| 42 | if err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | w.Write([]byte(body)) |
| 46 | } |
| 47 | if err := zw.Close(); err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | return buf.Bytes() |
| 51 | } |
| 52 | |
| 53 | const googleRows = `<row r="1">` + |
| 54 | `<c r="A1" t="inlineStr"><is><t>00123</t></is></c>` + |
| 55 | `<c r="B1" t="str"><f>IFERROR(__xludf.DUMMYFUNCTION("GOOGLEFINANCE(""X"")"),"7")</f><v>7</v></c>` + |
| 56 | `<c r="C1" t="inlineStr"><is><t>CANARY-CELL-VALUE-8f3a</t></is></c>` + |
| 57 | `</row><row r="2"><c r="A2"><v>4</v></c><c r="B2"><f>A2+3</f><v>7</v></c></row>` |
| 58 | |
| 59 | // importWorkbook posts body through the import form and waits for the |
| 60 | // job, returning where it landed. |
| 61 | func importWorkbook(t *testing.T, app *App, cookies []*http.Cookie, body []byte) string { |
| 62 | t.Helper() |
| 63 | rec := do(t, app, as(uploadRequest(t, "export.xlsx", body), cookies)) |
| 64 | if rec.Code != http.StatusSeeOther { |
| 65 | t.Fatalf("import answered %d", rec.Code) |
| 66 | } |
| 67 | location, page := awaitJob(t, app, cookies, rec.Header().Get("Location")) |
| 68 | if location == "" { |
| 69 | t.Fatalf("import did not finish; page said %q", page) |
| 70 | } |
| 71 | return location |
| 72 | } |
| 73 | |
| 74 | func TestImportLandsOnItsReportAndTheSheetOffersIt(t *testing.T) { |
| 75 | app, cookies := signIn(t) |
| 76 | location := importWorkbook(t, app, cookies, googleWorkbook(t, googleRows)) |
| 77 | sheetPath, ok := strings.CutSuffix(location, "/import-report") |
| 78 | if !ok { |
| 79 | t.Fatalf("job landed on %q, want an import report", location) |
| 80 | } |
| 81 | |
| 82 | rec := do(t, app, as(httptest.NewRequest(http.MethodGet, location, nil), cookies)) |
| 83 | page := rec.Body.String() |
| 84 | for _, want := range []string{"What import carries", "Google-only formulas kept as values", |
| 85 | "B1", "Text kept as text", "A1", "1 other worksheet(s) were left out", `href="` + sheetPath + `"`} { |
| 86 | if !strings.Contains(page, want) { |
| 87 | t.Errorf("report page lacks %q", want) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | rec = do(t, app, as(httptest.NewRequest(http.MethodGet, sheetPath, nil), cookies)) |
| 92 | if !strings.Contains(rec.Body.String(), `href="`+location+`"`) { |
| 93 | t.Error("the sheet's File menu does not offer its import report") |
| 94 | } |
| 95 | |
| 96 | rec = do(t, app, as(httptest.NewRequest(http.MethodGet, sheetPath+"/table", nil), cookies)) |
| 97 | table := rec.Body.String() |
| 98 | for _, want := range []string{"00123", ">7<", ""00123""} { |
| 99 | if !strings.Contains(table, want) { |
| 100 | t.Errorf("table view lacks %q", want) |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | func TestImportReportIsSealedAtRest(t *testing.T) { |
| 106 | app, cookies := signIn(t) |
| 107 | importWorkbook(t, app, cookies, googleWorkbook(t, googleRows)) |
| 108 | path := dbPath(t, app) |
| 109 | sealtest.AssertNoPlaintext(t, path) |
| 110 | for _, suffix := range []string{"", "-wal", "-shm"} { |
| 111 | b, err := os.ReadFile(path + suffix) |
| 112 | if err != nil { |
| 113 | continue |
| 114 | } |
| 115 | for _, plain := range []string{"formula-google-only", `"entries"`, "text-kept"} { |
| 116 | if bytes.Contains(b, []byte(plain)) { |
| 117 | t.Errorf("%s holds report plaintext %q", suffix, plain) |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // dbPath is the file behind app's database. |
| 124 | func dbPath(t *testing.T, app *App) string { |
| 125 | t.Helper() |
| 126 | var rows []struct { |
| 127 | Name, File string |
| 128 | } |
| 129 | if err := app.db.Raw("PRAGMA database_list").Scan(&rows).Error; err != nil || len(rows) == 0 { |
| 130 | t.Fatalf("database_list: %v", err) |
| 131 | } |
| 132 | return rows[0].File |
| 133 | } |
| 134 | |
| 135 | func TestImportReportFollowsSheetAccess(t *testing.T) { |
| 136 | app, cookies := signIn(t) |
| 137 | location := importWorkbook(t, app, cookies, googleWorkbook(t, googleRows)) |
| 138 | |
| 139 | // A guest admitted on another sheet does not see this one's report. |
| 140 | other, _ := newSheet(t, app, cookies, "Elsewhere") |
| 141 | guestOn(t, app, other.ID, "guest@example.com", SheetViewer) |
| 142 | guest := signInAs(t, app, "guest@example.com") |
| 143 | if rec := do(t, app, as(httptest.NewRequest(http.MethodGet, location, nil), guest)); rec.Code != http.StatusNotFound { |
| 144 | t.Errorf("stranger report = %d, want 404", rec.Code) |
| 145 | } |
| 146 | // A sheet that was never imported has none, and offers none. |
| 147 | other404 := importReportPath(other.ID) |
| 148 | if rec := do(t, app, as(httptest.NewRequest(http.MethodGet, other404, nil), cookies)); rec.Code != http.StatusNotFound { |
| 149 | t.Errorf("unimported sheet report = %d, want 404", rec.Code) |
| 150 | } |
| 151 | rec := do(t, app, as(httptest.NewRequest(http.MethodGet, strings.TrimSuffix(other404, "/import-report"), nil), cookies)) |
| 152 | if strings.Contains(rec.Body.String(), "/import-report") { |
| 153 | t.Error("an unimported sheet offers an import report") |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | func TestADiscardedImportLeavesNoReport(t *testing.T) { |
| 158 | app, cookies := signIn(t) |
| 159 | count := func() int64 { |
| 160 | var n int64 |
| 161 | app.db.Model(&store.ImportReport{}).Count(&n) |
| 162 | return n |
| 163 | } |
| 164 | |
| 165 | // Refused mid-import: the formula has no saved value to keep. |
| 166 | refused := `<row r="1"><c r="A1"><v>1</v></c><c r="B1"><f>GOOGLEFINANCE("CANARY-CELL-VALUE-8f3a")</f></c></row>` |
| 167 | rec := do(t, app, as(uploadRequest(t, "refused.xlsx", googleWorkbook(t, refused)), cookies)) |
| 168 | _, page := awaitJob(t, app, cookies, rec.Header().Get("Location")) |
| 169 | if !strings.Contains(page, "B1") || strings.Contains(page, "CANARY") { |
| 170 | t.Errorf("refusal should name B1 and nothing it held: %q", page) |
| 171 | } |
| 172 | if n := count(); n != 0 { |
| 173 | t.Errorf("refused import left %d reports", n) |
| 174 | } |
| 175 | |
| 176 | // Discarded before its reveal: the report rolls back with it. |
| 177 | s, err := app.createFillingSheet(nil, "late", signedInMember(t, app)) |
| 178 | if err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | app.discardSheet(s.ID) |
| 182 | if err := app.revealImport(s.ID, xlsxReportForTest()); err != errDiscardedBeforeReveal { |
| 183 | t.Errorf("reveal after discard = %v, want errDiscardedBeforeReveal", err) |
| 184 | } |
| 185 | if n := count(); n != 0 { |
| 186 | t.Errorf("discarded import left %d reports", n) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | func TestNativeImportJobKeepsTheSheetAsItsLocation(t *testing.T) { |
| 191 | app, cookies := signIn(t) |
| 192 | job, err := app.jobs.Start(signedInMember(t, app).Address, "Native test", importReportPath(42), |
| 193 | func(context.Context, func(string)) error { return nil }) |
| 194 | if err != nil { |
| 195 | t.Fatal(err) |
| 196 | } |
| 197 | var got struct{ Status, Location, Report string } |
| 198 | for i := 0; i < 100 && got.Status != "done"; i++ { |
| 199 | rec := do(t, app, as(nativeGet("/api/native/jobs/"+job.ID), cookies)) |
| 200 | if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { |
| 201 | t.Fatal(err) |
| 202 | } |
| 203 | } |
| 204 | if got.Location != "/sheets/42" || got.Report != "/sheets/42/import-report" { |
| 205 | t.Errorf("native job = %+v, want the sheet as location and the report beside it", got) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | func xlsxReportForTest() xlsx.Report { return xlsx.Report{Worksheets: 1} } |
| 210 | |