| new file mode 100644 |
| index 0000000..798992b |
| --- /dev/null |
| +++ b/internal/docs/import_test.go |
| @@ -0,0 +1,464 @@ |
| +package docs |
| + |
| +import ( |
| + "archive/zip" |
| + "bytes" |
| + "context" |
| + "encoding/base64" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "mime/multipart" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/estilo.git/googleimport" |
| + "amadan.net/rastrillo/rastrillo" |
| +) |
| + |
| +// The fixtures here are SYNTHESIZED .docx files, not real Google exports. |
| + |
| +// importMarker is text that must never appear at rest: in the database, |
| +// its WAL, or the log. |
| +const importMarker = "Zanzibar-quokka" |
| + |
| +// importName is a filename that must never reach the log. |
| +const importName = "Secret board minutes.docx" |
| + |
| +const wordNS = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"` |
| + |
| +func wordDoc(t *testing.T, body string) []byte { |
| + t.Helper() |
| + var buf bytes.Buffer |
| + z := zip.NewWriter(&buf) |
| + w, err := z.Create("word/document.xml") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + io.WriteString(w, `<w:document `+wordNS+`><w:body>`+body+`</w:body></w:document>`) |
| + if err := z.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + return buf.Bytes() |
| +} |
| + |
| +// nestedDoc has text in a link and a table, a bold-off run, and a |
| +// suggestion, so a report has lines and the text has places to hide. |
| +func nestedDoc(t *testing.T) []byte { |
| + return wordDoc(t, `<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Minutes</w:t></w:r></w:p>`+ |
| + `<w:p><w:hyperlink r:id="rId1"><w:r><w:t>`+importMarker+` link</w:t></w:r></w:hyperlink></w:p>`+ |
| + `<w:tbl><w:tr><w:tc><w:p><w:r><w:t>cell text</w:t></w:r></w:p></w:tc></w:tr></w:tbl>`+ |
| + `<w:p><w:r><w:rPr><w:b w:val="0"/></w:rPr><w:t>not bold</w:t></w:r></w:p>`) |
| +} |
| + |
| +// sealedApp is an app on a database whose content sealing is activated, |
| +// as activatedContentApp makes one, with the caller's Config. |
| +func sealedApp(t *testing.T, cfg Config) (*App, string) { |
| + t.Helper() |
| + key := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{73}, 32)) |
| + cfg.DBPath = filepath.Join(t.TempDir(), "docs.db") |
| + cfg.Env = "development" |
| + cfg.ContentKey = key |
| + app, err := New(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := app.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + cipher, err := newContentCipher(key, "production") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := MaintainContent(context.Background(), ContentMaintenanceConfig{DBPath: cfg.DBPath, ContentKey: key, ExpectedFingerprint: cipher.fingerprint}); err != nil { |
| + t.Fatal(err) |
| + } |
| + app, err = New(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { app.Close() }) |
| + return app, cfg.DBPath |
| +} |
| + |
| +// signedIn caches one session per app and address: signing in afresh |
| +// for every request runs into the sign-in rate limit. |
| +var signedIn = map[*App]map[string][]*http.Cookie{} |
| + |
| +// asSignedIn is app.TestRequest without a fresh sign-in each time. |
| +func asSignedIn(t *testing.T, app *App, who, method, path string, body io.Reader) *http.Request { |
| + t.Helper() |
| + if signedIn[app] == nil { |
| + signedIn[app] = map[string][]*http.Cookie{} |
| + t.Cleanup(func() { delete(signedIn, app) }) |
| + } |
| + cookies, ok := signedIn[app][who] |
| + if !ok { |
| + cookies = app.TestRequest(t, who, method, path, nil).Cookies() |
| + signedIn[app][who] = cookies |
| + } |
| + req := httptest.NewRequest(method, path, body) |
| + for _, c := range cookies { |
| + req.AddCookie(c) |
| + } |
| + if method != http.MethodGet { |
| + req.Header.Set("Sec-Fetch-Site", "same-origin") |
| + } |
| + return req |
| +} |
| + |
| +func importRequest(t *testing.T, app *App, who, token, name string, file []byte) *http.Request { |
| + t.Helper() |
| + var body bytes.Buffer |
| + mw := multipart.NewWriter(&body) |
| + if token != "" { |
| + mw.WriteField("creation_token", token) |
| + } |
| + if file != nil { |
| + w, err := mw.CreateFormFile("file", name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w.Write(file) |
| + } |
| + mw.Close() |
| + req := asSignedIn(t, app, who, http.MethodPost, "/import", &body) |
| + req.Header.Set("Content-Type", mw.FormDataContentType()) |
| + return req |
| +} |
| + |
| +func countRows(t *testing.T, app *App, table string) int64 { |
| + t.Helper() |
| + var n int64 |
| + if err := app.store.db.Table(table).Count(&n).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +func TestImportCreatesASealedEditableDocumentWithItsReport(t *testing.T) { |
| + var logs bytes.Buffer |
| + app, dbPath := sealedApp(t, Config{Logger: slog.New(slog.NewTextHandler(&logs, nil))}) |
| + const who = "owner@example.com" |
| + const token = "1b0f8a52-6f0e-4a7e-9a0c-2f7f8d7f0a11" |
| + |
| + rec := serve(app, importRequest(t, app, who, token, importName, nestedDoc(t))) |
| + if rec.Code != http.StatusSeeOther { |
| + t.Fatalf("POST /import: %d %s", rec.Code, rec.Body.String()) |
| + } |
| + loc := rec.Header().Get("Location") |
| + sqid, ok := strings.CutSuffix(strings.TrimPrefix(loc, "/d/"), "?imported=1") |
| + if !ok || sqid == "" { |
| + t.Fatalf("Location %q", loc) |
| + } |
| + |
| + // The same submission again, after a lost answer, is the same document. |
| + again := serve(app, importRequest(t, app, who, token, importName, nestedDoc(t))) |
| + if again.Code != http.StatusSeeOther || again.Header().Get("Location") != loc { |
| + t.Fatalf("a retried import: %d %q, want the first document", again.Code, again.Header().Get("Location")) |
| + } |
| + if n := countRows(t, app, "documents"); n != 1 { |
| + t.Fatalf("%d documents after a retried import, want 1", n) |
| + } |
| + |
| + ctx := context.Background() |
| + owner := app.TestPerson(t, who) |
| + doc, err := app.store.Get(ctx, owner, sqid) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if doc.Title != "Secret board minutes" { |
| + t.Errorf("title %q", doc.Title) |
| + } |
| + text, err := app.store.Text(ctx, doc) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, want := range []string{"Minutes", importMarker + " link", "cell text", "not bold"} { |
| + if !strings.Contains(text, want) { |
| + t.Errorf("the document has no %q: %q", want, text) |
| + } |
| + } |
| + |
| + // Sealed at rest: the update, the report, and neither in the clear |
| + // in the database or its WAL. |
| + var upd DocUpdate |
| + if err := app.store.db.Where("doc_id = ?", doc.ID).First(&upd).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + var rep DocImportReport |
| + if err := app.store.db.Where("doc_id = ?", doc.ID).First(&rep).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if upd.Seq != 1 || upd.ContentEncoding != contentEncoding || rep.ContentEncoding != contentEncoding { |
| + t.Fatalf("update seq %d encoding %d, report encoding %d", upd.Seq, upd.ContentEncoding, rep.ContentEncoding) |
| + } |
| + for _, f := range []string{dbPath, dbPath + "-wal"} { |
| + b, err := os.ReadFile(f) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + for _, s := range []string{importMarker, "table_flattened", "link_text_kept"} { |
| + if bytes.Contains(b, []byte(s)) { |
| + t.Errorf("%s holds %q in the clear", filepath.Base(f), s) |
| + } |
| + } |
| + } |
| + // A report's ciphertext does not open as an update of the same |
| + // document: its own kind byte. |
| + probe := DocUpdate{Seq: 0, UpdateBin: append([]byte(nil), rep.ReportBin...), ContentEncoding: contentEncoding} |
| + if err := app.store.content.openUpdate(doc.GUID, &probe); err == nil { |
| + t.Error("a sealed report opened as an update") |
| + } |
| + |
| + // Editable: an ordinary update applies on top. |
| + if rec := serve(app, asSignedIn(t, app, who, http.MethodPost, "/d/"+sqid+"/updates", bytes.NewReader(validUpdate(t)))); rec.Code != http.StatusNoContent { |
| + t.Fatalf("POST update to the import: %d", rec.Code) |
| + } |
| + |
| + // The report shows once on arrival, and reopens from the bar. |
| + arrival := serve(app, asSignedIn(t, app, who, http.MethodGet, loc, nil)).Body.String() |
| + for _, want := range []string{"<dialog docs-dialog docs-import-arrival open>", "<section docs-import-report", "docs.import.report.table_flattened", "/d/" + sqid + "/import-report"} { |
| + if !strings.Contains(arrival, want) { |
| + t.Errorf("the arrival page has no %q", want) |
| + } |
| + } |
| + plain := serve(app, asSignedIn(t, app, who, http.MethodGet, "/d/"+sqid, nil)).Body.String() |
| + if strings.Contains(plain, "<dialog docs-dialog docs-import-arrival") || !strings.Contains(plain, "/d/"+sqid+"/import-report") { |
| + t.Error("the report should show only on arrival, and its link always") |
| + } |
| + page := serve(app, asSignedIn(t, app, who, http.MethodGet, "/d/"+sqid+"/import-report", nil)) |
| + if page.Code != http.StatusOK || !strings.Contains(page.Body.String(), "docs.import.report.link_text_kept") || !strings.Contains(page.Body.String(), "docs.import.report.incomplete") { |
| + t.Fatalf("the report page: %d", page.Code) |
| + } |
| + if rec := serve(app, asSignedIn(t, app, "stranger@example.com", http.MethodGet, "/d/"+sqid+"/import-report", nil)); rec.Code != http.StatusNotFound { |
| + t.Errorf("a stranger reading the report: %d, want 404", rec.Code) |
| + } |
| + created := createDocFor(t, app, who) |
| + if rec := serve(app, asSignedIn(t, app, who, http.MethodGet, "/d/"+created+"/import-report", nil)); rec.Code != http.StatusNotFound { |
| + t.Errorf("the report of a document never imported: %d, want 404", rec.Code) |
| + } |
| + |
| + if strings.Contains(logs.String(), importMarker) || strings.Contains(logs.String(), "Secret board") { |
| + t.Error("the log carries the file's content or name") |
| + } |
| +} |
| + |
| +func createDocFor(t *testing.T, app *App, who string) string { |
| + t.Helper() |
| + req := asSignedIn(t, app, who, http.MethodPost, "/documents", strings.NewReader("title=Typed")) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + rec := serve(app, req) |
| + if rec.Code != http.StatusSeeOther { |
| + t.Fatalf("POST /documents: %d", rec.Code) |
| + } |
| + return strings.TrimPrefix(rec.Header().Get("Location"), "/d/") |
| +} |
| + |
| +// Every refusal creates nothing, says why in words, and logs no name or |
| +// content. |
| +func TestImportRefusalsCreateNothing(t *testing.T) { |
| + var logs bytes.Buffer |
| + app, _ := sealedApp(t, Config{Logger: slog.New(slog.NewTextHandler(&logs, nil))}) |
| + const who = "owner@example.com" |
| + damaged := nestedDoc(t) |
| + damaged = append(damaged[:len(damaged)/2:len(damaged)/2], bytes.Repeat([]byte{0}, 64)...) |
| + for _, c := range []struct { |
| + name string |
| + file []byte |
| + fname string |
| + status int |
| + says string |
| + }{ |
| + {"no file", nil, "", http.StatusBadRequest, "docs.import.error.nofile"}, |
| + {"a PDF", []byte("%PDF-1.7 " + importMarker), "minutes.pdf", http.StatusUnsupportedMediaType, "docs.import.error.notword"}, |
| + {"a PDF named .docx", []byte("%PDF-1.7 " + importMarker), importName, http.StatusUnsupportedMediaType, "docs.import.error.notword"}, |
| + {"a damaged archive", damaged, importName, http.StatusUnprocessableEntity, "docs.import.error.notword"}, |
| + {"broken XML", wordDoc(t, `<w:p><w:r><w:t>`+importMarker), importName, http.StatusUnprocessableEntity, "docs.import.error.damaged"}, |
| + {"no text", wordDoc(t, `<w:p/><w:p><w:r><w:drawing/></w:r></w:p>`), importName, http.StatusUnprocessableEntity, "docs.import.error.empty"}, |
| + {"too large", append([]byte("PK\x03\x04"), bytes.Repeat([]byte("x"), googleimport.MaxExportBytes)...), importName, http.StatusRequestEntityTooLarge, "docs.import.error.toolarge"}, |
| + } { |
| + rec := serve(app, importRequest(t, app, who, "", c.fname, c.file)) |
| + body := rec.Body.String() |
| + if rec.Code != c.status || !strings.Contains(body, "docs-import-error") || !strings.Contains(body, c.says) { |
| + t.Errorf("%s: %d, want %d saying %q", c.name, rec.Code, c.status, c.says) |
| + } |
| + if strings.Contains(body, importMarker) { |
| + t.Errorf("%s: the page quotes the file", c.name) |
| + } |
| + } |
| + for _, table := range []string{"documents", "doc_updates", "doc_import_reports"} { |
| + if n := countRows(t, app, table); n != 0 { |
| + t.Errorf("%d rows in %s after refusals", n, table) |
| + } |
| + } |
| + if strings.Contains(logs.String(), importMarker) || strings.Contains(logs.String(), "Secret board") { |
| + t.Error("the log carries the file's content or name") |
| + } |
| +} |
| + |
| +// New content on this instance is sealed or it is not written: until |
| +// sealing is activated, the page says so and an import is refused. |
| +// Existing legacy documents are untouched by this. |
| +func TestImportIsRefusedUntilContentSealingIsActivated(t *testing.T) { |
| + app, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + const who = "owner@example.com" |
| + get := serve(app, asSignedIn(t, app, who, http.MethodGet, "/import", nil)) |
| + if get.Code != http.StatusServiceUnavailable || !strings.Contains(get.Body.String(), "docs.import.error.unsealed") { |
| + t.Errorf("GET /import unsealed: %d", get.Code) |
| + } |
| + post := serve(app, importRequest(t, app, who, "", importName, nestedDoc(t))) |
| + if post.Code != http.StatusServiceUnavailable || !strings.Contains(post.Body.String(), "docs.import.error.unsealed") { |
| + t.Errorf("POST /import unsealed: %d", post.Code) |
| + } |
| + if _, err := app.store.CreateImported(context.Background(), app.TestPerson(t, who), "x", "", &imported{}); !errors.Is(err, errImportUnsealed) { |
| + t.Errorf("CreateImported unsealed: %v", err) |
| + } |
| + for _, table := range []string{"documents", "doc_updates", "doc_import_reports"} { |
| + if n := countRows(t, app, table); n != 0 { |
| + t.Errorf("%d rows in %s", n, table) |
| + } |
| + } |
| + // The ordinary legacy path still writes. |
| + createDocFor(t, app, who) |
| +} |
| + |
| +// A guest, admitted by a grant to one document, does not import any more |
| +// than they create. |
| +func TestAGuestCannotImport(t *testing.T) { |
| + app, _ := sealedApp(t, Config{AllowedAddresses: "alice@example.com"}) |
| + sqid := createDocFor(t, app, "alice@example.com") |
| + share := asSignedIn(t, app, "alice@example.com", http.MethodPost, "/d/"+sqid+"/share", strings.NewReader("address=bob@example.com&role=writer")) |
| + share.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + if rec := serve(app, share); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("share: %d", rec.Code) |
| + } |
| + if rec := serve(app, asSignedIn(t, app, "bob@example.com", http.MethodGet, "/import", nil)); rec.Code != http.StatusForbidden { |
| + t.Errorf("guest GET /import: %d, want 403", rec.Code) |
| + } |
| + if rec := serve(app, importRequest(t, app, "bob@example.com", "", importName, nestedDoc(t))); rec.Code != http.StatusForbidden { |
| + t.Errorf("guest POST /import: %d, want 403", rec.Code) |
| + } |
| + if n := countRows(t, app, "documents"); n != 1 { |
| + t.Errorf("%d documents, want alice's one", n) |
| + } |
| +} |
| + |
| +// A cross-site POST is refused by the same origin check as every other |
| +// form, before anything is read. |
| +func TestImportRefusesACrossSitePost(t *testing.T) { |
| + app, _ := sealedApp(t, Config{}) |
| + req := importRequest(t, app, "owner@example.com", "", importName, nestedDoc(t)) |
| + req.Header.Set("Sec-Fetch-Site", "cross-site") |
| + if rec := serve(app, req); rec.Code != http.StatusForbidden { |
| + t.Errorf("cross-site import: %d, want 403", rec.Code) |
| + } |
| + if n := countRows(t, app, "documents"); n != 0 { |
| + t.Errorf("%d documents", n) |
| + } |
| +} |
| + |
| +var testGoogle = googleimport.Config{ |
| + ClientID: "1234567890-abcdefghijklmnop.apps.googleusercontent.com", |
| + APIKey: "AIzaSyTESTONLYabcdefghijklmnopqrstuvw", |
| + AppID: "1234567890", |
| +} |
| + |
| +// Served through rastrillo's production middleware, as the binary serves |
| +// it: the import page alone gains Google's origins, keeps every |
| +// directive that matters, sets no COOP, and with Google off is the app's |
| +// own policy with no Google anywhere. |
| +func TestImportPagePolicy(t *testing.T) { |
| + for _, on := range []bool{false, true} { |
| + cfg := Config{} |
| + if on { |
| + cfg.GoogleImport = testGoogle |
| + } |
| + app, _ := sealedApp(t, cfg) |
| + served, done, err := rastrillo.Handler(ServeOptions(rastrillo.Options{}, app)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if done != nil { |
| + defer done() |
| + } |
| + page := func(req *http.Request) *httptest.ResponseRecorder { |
| + req.Header.Set("Accept", "text/html") |
| + rec := httptest.NewRecorder() |
| + served.ServeHTTP(rec, req) |
| + return rec |
| + } |
| + for _, req := range []*http.Request{ |
| + asSignedIn(t, app, "owner@example.com", http.MethodGet, "/import", nil), |
| + importRequest(t, app, "owner@example.com", "", "notes.pdf", []byte("%PDF")), |
| + } { |
| + rec := page(req) |
| + policies := rec.Header().Values("Content-Security-Policy") |
| + body := rec.Body.String() |
| + if len(policies) != 1 { |
| + t.Fatalf("google %v %s: %d policies", on, req.Method, len(policies)) |
| + } |
| + if rec.Header().Get("Cross-Origin-Opener-Policy") != "" { |
| + t.Errorf("google %v %s: a COOP header", on, req.Method) |
| + } |
| + if rec.Header().Get("Cache-Control") != "no-store" { |
| + t.Errorf("google %v %s: Cache-Control %q", on, req.Method, rec.Header().Get("Cache-Control")) |
| + } |
| + policy := policies[0] |
| + for _, d := range []string{"form-action 'self'", "frame-ancestors 'none'", "base-uri 'self'"} { |
| + if !strings.Contains(policy, d) { |
| + t.Errorf("google %v %s: the policy lost %q", on, req.Method, d) |
| + } |
| + } |
| + if on { |
| + want, _ := googleimport.Policy(ContentSecurityPolicy) |
| + if policy != want || !strings.Contains(body, "estilo-google-import") || !strings.Contains(body, "/static/estilo/google-import.") { |
| + t.Errorf("google on %s: policy %q, chooser rendered %v", req.Method, policy, strings.Contains(body, "estilo-google-import")) |
| + } |
| + } else if policy != ContentSecurityPolicy || strings.Contains(body, "estilo-google-import") || strings.Contains(body, "google") { |
| + t.Errorf("google off %s: policy %q, or Google on the page", req.Method, policy) |
| + } |
| + } |
| + // Elsewhere the policy is the app's own either way. |
| + list := page(asSignedIn(t, app, "owner@example.com", http.MethodGet, "/", nil)) |
| + if got := list.Header().Get("Content-Security-Policy"); got != ContentSecurityPolicy { |
| + t.Errorf("google %v: the list's policy is %q", on, got) |
| + } |
| + } |
| +} |
| + |
| +func TestPartialGoogleConfigurationRefusesToStart(t *testing.T) { |
| + for _, cfg := range []googleimport.Config{ |
| + {ClientID: testGoogle.ClientID}, |
| + {ClientID: testGoogle.ClientID, APIKey: testGoogle.APIKey}, |
| + {ClientID: "not a client id", APIKey: testGoogle.APIKey, AppID: testGoogle.AppID}, |
| + {ClientID: testGoogle.ClientID, APIKey: testGoogle.APIKey, AppID: "my-project"}, |
| + } { |
| + if _, err := NewForTestWith(t, Config{GoogleImport: cfg}); err == nil { |
| + t.Errorf("%+v: started", cfg) |
| + } |
| + } |
| +} |
| + |
| +func TestImportTitleFromAFilename(t *testing.T) { |
| + for in, want := range map[string]string{ |
| + "Board minutes.docx": "Board minutes", |
| + `C:\Users\x\Q3 plan.DOCX`: "Q3 plan", |
| + "../../etc/passwd.docx": "passwd", |
| + " spaced .docx": "spaced", |
| + "tab\there.docx": "tabhere", |
| + ".docx": "", |
| + strings.Repeat("é", 600) + ".docx": strings.Repeat("é", 512), |
| + } { |
| + if got := importTitle(in); got != want { |
| + t.Errorf("importTitle(%q) = %q, want %q", in, got, want) |
| + } |
| + } |
| +} |