oficina / docs Public

Docs: imports only into sealed storage; route tests.

An import is new content, and new content here is sealed or not written:
until content sealing is activated (docs docs-seal), GET/POST /import
answer 503 with an operator-actionable message and CreateImported itself
refuses (errImportUnsealed). Existing legacy documents keep their
behaviour.

import_test.go (synthesized fixtures): a sealed, editable import with
its report (update 1 and report sealed, neither the text nor report
codes in the database or WAL, a report's ciphertext does not open as an
update, an edit applies on top, report on arrival only, link always,
404 for a stranger and for a document never imported), creation-token
idempotence, every refusal creating nothing and quoting nothing, the
unsealed refusal, guest 403, cross-site 403, the served policy with
Google on and off (one CSP, Google origins on the import page only,
form-action/frame-ancestors/base-uri kept, no COOP, no-store), partial
Google config refusing to boot, and titles from filenames. No log line
carries the file's name or content.

The parent session's browser harness, finalized: it activates sealing
through MaintainContent first and scans the DB and WAL after real
browser imports and edits.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 9adc9353245c89fa543a1f5351117c6197588f27 parent be64677
4 files changed, +516 −1
  • internal/docs/google_import_browser_test.go +31 −1
  • internal/docs/import.go +20 −0
  • internal/docs/import_test.go +464 −0
  • internal/docs/render.go +1 −0

CI failed — run details

diff --git a/internal/docs/google_import_browser_test.go b/internal/docs/google_import_browser_test.go
index bddf61b..1eb8e84 100644
--- a/internal/docs/google_import_browser_test.go
+++ b/internal/docs/google_import_browser_test.go
@@ -6,13 +6,17 @@ import (
"archive/zip"
"bytes"
"context"
+ "crypto/sha256"
+ "encoding/base64"
"encoding/json"
+ "fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"os/exec"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -29,7 +33,19 @@ import (
func TestGoogleImportBrowserCreatesAnEditableDocument(t *testing.T) {
server := httptest.NewUnstartedServer(nil)
origin := "http://" + server.Listener.Addr().String()
- app, err := docs.NewForTestWith(t, docs.Config{Origin: origin, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), GoogleImport: googleimport.Config{
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ key := bytes.Repeat([]byte{113}, 32) // synthetic fixture key, never deployment configuration
+ encoded := base64.StdEncoding.EncodeToString(key)
+ dbPath := filepath.Join(t.TempDir(), "docs.db")
+ if err := os.WriteFile(dbPath, nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := docs.MaintainContent(context.Background(), docs.ContentMaintenanceConfig{
+ DBPath: dbPath, ContentKey: encoded, ExpectedFingerprint: fmt.Sprintf("%x", sha256.Sum256(key)), Logger: logger,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ app, err := docs.NewForTestWith(t, docs.Config{DBPath: dbPath, ContentKey: encoded, Origin: origin, Logger: logger, GoogleImport: googleimport.Config{
ClientID: "123456789-client.apps.googleusercontent.com", APIKey: "AIzaPublicBrowserKey123456789", AppID: "123456789",
}})
if err != nil {
@@ -73,6 +89,20 @@ func TestGoogleImportBrowserCreatesAnEditableDocument(t *testing.T) {
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Google import browser flow: %v\n%s", err, out)
}
+ for _, suffix := range []string{"", "-wal"} {
+ data, err := os.ReadFile(dbPath + suffix)
+ if suffix == "-wal" && os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, content := range []string{"linked words", "Table cell", "Edited after import.", "table_flattened"} {
+ if bytes.Contains(data, []byte(content)) {
+ t.Errorf("imported content or report persisted unsealed in database%s", suffix)
+ }
+ }
+ }
}
func googleBrowserDOCX(t *testing.T) []byte {
diff --git a/internal/docs/import.go b/internal/docs/import.go
index 15cd244..4e35cb1 100644
--- a/internal/docs/import.go
+++ b/internal/docs/import.go
@@ -51,6 +51,13 @@ const maxImportBody = maxImportFile + 64<<10
// is told to try again rather than queued.
const maxImportsAtOnce = 2
+// errImportUnsealed: this instance's content sealing is not activated.
+// New content here is sealed or it is not written; an import is new
+// content, so until an operator runs `docs docs-seal` an import is
+// refused rather than stored in the clear. (The update log keeps its
+// legacy behaviour for existing documents; that is a different promise.)
+var errImportUnsealed = errors.New("docs: content sealing is not activated; run docs docs-seal before importing")
+
// errImportMismatch: the built document did not replay to the structure
// the reader produced. Never expected; refused rather than saved,
// because a report is only true of the document it was made for.
@@ -182,6 +189,9 @@ func canonicalBlocks(blocks []core.BuildBlock) []string {
// returns that document and writes nothing, so a retried submission
// after a lost answer cannot import twice.
func (s *Store) CreateImported(ctx context.Context, owner int64, title, token string, imp *imported) (*Document, error) {
+ if s.content == nil {
+ return nil, errImportUnsealed
+ }
actor := s.ownerActor(ctx, owner)
if err := s.requireMember(ctx, actor); err != nil {
return nil, err
@@ -340,6 +350,11 @@ func (h *handlers) importGet(w http.ResponseWriter, r *http.Request) {
if !h.requireMemberRequest(w, r, false) {
return
}
+ if h.store.content == nil {
+ h.logger.Error("docs: import unavailable", "err", errImportUnsealed)
+ h.renderImport(w, r, h.importView(r, "", "docs.import.error.unsealed"), http.StatusServiceUnavailable)
+ return
+ }
h.renderImport(w, r, h.importView(r, uuid.NewString(), ""), 0)
}
@@ -355,6 +370,11 @@ func (h *handlers) importPost(w http.ResponseWriter, r *http.Request) {
h.fail(w, r, h.internalFailureStatus(), failStatus)
return
}
+ if h.store.content == nil {
+ h.logger.Error("docs: import unavailable", "err", errImportUnsealed)
+ h.renderImport(w, r, h.importView(r, "", "docs.import.error.unsealed"), http.StatusServiceUnavailable)
+ return
+ }
r.Body = http.MaxBytesReader(w, r.Body, maxImportBody)
token, name, data, status, errKey := readImportForm(r)
if token == "" {
diff --git a/internal/docs/import_test.go b/internal/docs/import_test.go
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)
+ }
+ }
+}
diff --git a/internal/docs/render.go b/internal/docs/render.go
index 574f764..46a38b0 100644
--- a/internal/docs/render.go
+++ b/internal/docs/render.go
@@ -331,6 +331,7 @@ var Catalog = rastrillo.Catalog{
"docs.import.error.empty": "That document has no text Docs can import, so nothing was created.",
"docs.import.error.busy": "Docs is busy importing other documents. Try again in a moment.",
"docs.import.error.failed": "The import did not finish, and nothing was created. Try again.",
+ "docs.import.error.unsealed": "Importing is not available here yet: this instance has not turned on content sealing, and an import is only ever stored sealed. Ask whoever runs it to run docs docs-seal.",
"docs.import.report.heading": "Import report",
"docs.import.report.open": "Import report",