oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 mrand "math/rand/v2"
11 "net/http"
12 "path"
13 "slices"
14 "strings"
15 "time"
16
17 "github.com/google/uuid"
18 "gorm.io/gorm"
19
20 "amadan.net/oficina/estilo.git/googleimport"
21 "amadan.net/rastrillo/rastrillo"
22
23 "github.com/carlosframework/docs/internal/core"
24 "github.com/carlosframework/docs/internal/docx"
25 "github.com/carlosframework/docs/internal/export"
26)
27
28// Importing a .docx (spec §11.2; implementation/google-drive-import.md
29// in estilo). One route serves both ways in: the ordinary file form, and
30// the Google Drive chooser, which exports the chosen file in the browser
31// and puts it in that same form's file input. The server never talks to
32// Google and never sees a Google token.
33//
34// The path is read (docx.Import) -> instructions (core.EncodeBuild) ->
35// a genuine Yjs update written by the core's yrs builder -> that update
36// replayed into a second document and its structure compared with what
37// the reader meant -> one transaction writing the document row, its
38// first update and its report (Store.CreateImported). A failure at any
39// step creates nothing.
40
41// maxImportFile is the largest file accepted: the shared chooser's
42// export bound, which is also Google's own export limit.
43const maxImportFile = googleimport.MaxExportBytes
44
45// maxImportBody is maxImportFile plus room for the multipart framing,
46// the creation token and the filename.
47const maxImportBody = maxImportFile + 64<<10
48
49// maxImportsAtOnce bounds the imports converting at one time. Each holds
50// its file and up to 64 MiB of decompressed parts; beyond this a request
51// is told to try again rather than queued.
52const maxImportsAtOnce = 2
53
54// errImportUnsealed: this instance's content sealing is not activated.
55// New content here is sealed or it is not written; an import is new
56// content, so until an operator runs `docs docs-seal` an import is
57// refused rather than stored in the clear. (The update log keeps its
58// legacy behaviour for existing documents; that is a different promise.)
59var errImportUnsealed = errors.New("docs: content sealing is not activated; run docs docs-seal before importing")
60
61// errImportMismatch: the built document did not replay to the structure
62// the reader produced. Never expected; refused rather than saved,
63// because a report is only true of the document it was made for.
64var errImportMismatch = errors.New("docs: imported document does not match what was read")
65
66// imported is a converted file, ready to store.
67type imported struct {
68 guid string
69 clientID uint64 // the row's, for the server's read handles
70 builder uint64 // the one the update is written under
71 update []byte
72 report []byte
73 blocks int
74}
75
76// convertImport turns a .docx into an update and a report, and proves the
77// update is the document the report describes.
78func convertImport(ctx context.Context, rt *core.Runtime, data []byte) (*imported, error) {
79 res, err := docx.Import(data)
80 if err != nil {
81 return nil, err
82 }
83 blocks := buildBlocks(res.Document)
84 ops, err := core.EncodeBuild(blocks)
85 if err != nil {
86 return nil, err
87 }
88 guid := uuid.NewString()
89 // The client id the import writes under. A uint32, as Yjs draws its
90 // own: unlike the row's client id, which the server only ever reads
91 // with, this one is in the update every browser decodes, and lib0
92 // refuses a client id past Number.MAX_SAFE_INTEGER. Drawn here, never
93 // by yrs (core/src/lib.rs), and never equal to the row's.
94 builder := uint64(mrand.Uint32())
95 stored := uint64(mrand.Int64())
96 for stored == builder || stored == builder+1 {
97 stored = uint64(mrand.Int64())
98 }
99 update, err := rt.Build(ctx, guid, builder, ops)
100 if err != nil {
101 return nil, err
102 }
103
104 h, err := rt.NewDoc(ctx, guid, builder+1)
105 if err != nil {
106 return nil, err
107 }
108 defer h.Close(ctx)
109 if err := h.Apply(ctx, update); err != nil {
110 return nil, err
111 }
112 structure, err := h.JSON(ctx)
113 if err != nil {
114 return nil, err
115 }
116 replayed, err := export.Parse("", structure)
117 if err != nil {
118 return nil, err
119 }
120 if !slices.Equal(canonicalBlocks(buildBlocks(replayed)), canonicalBlocks(blocks)) {
121 return nil, errImportMismatch
122 }
123
124 report, err := json.Marshal(res.Report)
125 if err != nil {
126 return nil, err
127 }
128 return &imported{guid: guid, clientID: stored, builder: builder, update: update, report: report, blocks: len(blocks)}, nil
129}
130
131// buildBlocks is a document's top-level paragraphs and headings as the
132// builder's blocks. The reader writes nothing else, and the replayed
133// document can hold nothing else, so anything else is left out here and
134// shows up as a mismatch.
135func buildBlocks(d export.Document) []core.BuildBlock {
136 var out []core.BuildBlock
137 for _, n := range d.Root.Content {
138 b := core.BuildBlock{}
139 switch n.Type {
140 case "paragraph":
141 case "heading":
142 b.Heading = n.Attrs.Level
143 default:
144 b.Heading = -1
145 }
146 for _, r := range n.Content {
147 run := core.BuildRun{Text: r.Text}
148 if !r.IsText() {
149 run.Text = "\x00" + r.Type
150 }
151 for _, m := range r.Marks {
152 run.Marks = append(run.Marks, m.Type)
153 }
154 b.Runs = append(b.Runs, run)
155 }
156 out = append(out, b)
157 }
158 return out
159}
160
161// canonicalBlocks renders blocks one string per block, with runs of the
162// same marks merged and each run's marks sorted, so two spellings of
163// one document compare equal: the builder merges adjacent runs, and the
164// core lists a run's marks in its own table's order.
165func canonicalBlocks(blocks []core.BuildBlock) []string {
166 out := make([]string, len(blocks))
167 for i, b := range blocks {
168 var s strings.Builder
169 fmt.Fprintf(&s, "%d", b.Heading)
170 last := "\x01"
171 for _, r := range b.Runs {
172 marks := slices.Clone(r.Marks)
173 slices.Sort(marks)
174 key := strings.Join(marks, ",")
175 if key != last {
176 fmt.Fprintf(&s, "\x02%s\x03", key)
177 last = key
178 }
179 s.WriteString(r.Text)
180 }
181 out[i] = s.String()
182 }
183 return out
184}
185
186// CreateImported makes an imported document: the row, its first update
187// and its report, in one transaction, with membership checked inside it
188// as CreateDraft does. A creation token already used by this owner
189// returns that document and writes nothing, so a retried submission
190// after a lost answer cannot import twice.
191func (s *Store) CreateImported(ctx context.Context, owner int64, title, token string, imp *imported) (*Document, error) {
192 // One line, as every title is (handlers.go's cleanTitle); a title that
193 // cleans to nothing is left as the caller gave it.
194 if c := cleanTitle(title); c != "" {
195 title = c
196 }
197 if s.content == nil {
198 return nil, errImportUnsealed
199 }
200 actor := s.ownerActor(ctx, owner)
201 if err := s.requireMember(ctx, actor); err != nil {
202 return nil, err
203 }
204 now := time.Now().UTC()
205 revision, err := newRevision(noRevisionTaken)
206 if err != nil {
207 return nil, err
208 }
209 var lastErr error
210 for attempt := 0; attempt < maxSqidAttempts; attempt++ {
211 sqid, err := newSqid()
212 if err != nil {
213 return nil, err
214 }
215 doc := &Document{Sqid: sqid, Title: title, OwnerID: owner, GUID: imp.guid, ClientID: imp.clientID,
216 Visibility: VisibilityTeam, Revision: revision, CreatedAt: now, UpdatedAt: now}
217 err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
218 if err := s.requireMember(ctx, actor); err != nil {
219 return err
220 }
221 if token != "" {
222 var existing Document
223 err := tx.Where("owner_id = ? AND creation_token = ?", owner, token).First(&existing).Error
224 if err == nil {
225 if existing.DeletedAt != nil {
226 return gorm.ErrRecordNotFound
227 }
228 *doc = existing
229 return s.requireMember(ctx, actor)
230 }
231 if !errors.Is(err, gorm.ErrRecordNotFound) {
232 return err
233 }
234 doc.CreationToken = &token
235 }
236 if err := tx.Create(doc).Error; err != nil {
237 return err
238 }
239 row := &DocUpdate{DocID: doc.ID, Seq: 1, UpdateBin: imp.update, CreatedAt: now}
240 if err := s.prepareContentUpdate(tx, doc.GUID, row); err != nil {
241 return err
242 }
243 if err := tx.Create(row).Error; err != nil {
244 return err
245 }
246 report := &DocImportReport{DocID: doc.ID, ReportBin: imp.report, CreatedAt: now}
247 if err := s.prepareContentReport(tx, doc.GUID, report); err != nil {
248 return err
249 }
250 if err := tx.Create(report).Error; err != nil {
251 return err
252 }
253 if err := announce(tx, doc.ID, doc.Revision, false); err != nil {
254 return err
255 }
256 return s.requireMember(ctx, actor)
257 })
258 if err == nil {
259 return doc, nil
260 }
261 lastErr = err
262 if !errors.Is(err, gorm.ErrDuplicatedKey) {
263 break
264 }
265 }
266 return nil, fmt.Errorf("docs: create imported document: %w", lastErr)
267}
268
269// ImportReport is doc's import report, or nil for a document that was
270// not imported. The caller has already established the reader may see
271// doc; the report says nothing the document does not.
272func (s *Store) ImportReport(ctx context.Context, doc *Document) (*docx.Report, error) {
273 var row DocImportReport
274 err := s.db.WithContext(ctx).Where("doc_id = ?", doc.ID).First(&row).Error
275 if errors.Is(err, gorm.ErrRecordNotFound) {
276 return nil, nil
277 }
278 if err != nil {
279 return nil, err
280 }
281 if err := s.openContentReport(doc.GUID, &row); err != nil {
282 return nil, err
283 }
284 var rep docx.Report
285 if err := json.Unmarshal(row.ReportBin, &rep); err != nil {
286 return nil, err
287 }
288 return &rep, nil
289}
290
291// hasImportReport is whether doc has a report, without opening it.
292func (s *Store) hasImportReport(ctx context.Context, docID int64) bool {
293 var n int64
294 return s.db.WithContext(ctx).Model(&DocImportReport{}).Where("doc_id = ?", docID).Count(&n).Error == nil && n > 0
295}
296
297// ---- pages
298
299type importPage struct {
300 Frame Frame
301 Title, Intro, Fidelity, FileLabel, Submit, Error string
302 Token string
303 Google googleimport.View
304 GoogleScript string
305}
306
307// importErrorKey is the catalog key for a refusal. Every one is a whole
308// answer that quotes nothing from the file.
309func importErrorKey(err error) string {
310 switch {
311 case errors.Is(err, docx.ErrNotWord):
312 return "docs.import.error.notword"
313 case errors.Is(err, docx.ErrMalformed):
314 return "docs.import.error.damaged"
315 case errors.Is(err, docx.ErrTooLarge), errors.Is(err, core.ErrBuildLimit):
316 return "docs.import.error.toolarge"
317 case errors.Is(err, docx.ErrEmpty):
318 return "docs.import.error.empty"
319 }
320 return "docs.import.error.failed"
321}
322
323func (h *handlers) importView(r *http.Request, token, errKey string) importPage {
324 title := rastrillo.T(r, "docs.import.title")
325 p := importPage{
326 Frame: h.frame(r, frameOptions{titleParts: []string{title}}),
327 Title: title,
328 Intro: rastrillo.T(r, "docs.import.intro"),
329 Fidelity: rastrillo.T(r, "docs.import.fidelity"),
330 FileLabel: rastrillo.T(r, "docs.import.file"),
331 Submit: rastrillo.T(r, "docs.import.submit"),
332 Token: token,
333 }
334 if errKey != "" {
335 p.Error = rastrillo.T(r, errKey)
336 }
337 if h.google.Enabled() {
338 p.Google = googleimport.View{Config: h.google, Kind: googleimport.Docs, FormID: "docs-import-form", InputID: "docs-import-file", Labels: googleimport.Text(rastrillo.LocaleFrom(r))}
339 p.GoogleScript = h.render.assets.Path("static/estilo/" + googleimport.JSName())
340 }
341 return p
342}
343
344// renderImport draws the import page, with the Google policy when the
345// chooser is on, at status (0 for 200).
346func (h *handlers) renderImport(w http.ResponseWriter, r *http.Request, p importPage, status int) {
347 // This page has no document to establish its emission guard. Keep
348 // membership live through rendering and each response chunk instead.
349 h.store.rememberResponse(r.Context(), permissionRead)
350 if access, ok := r.Context().Value(accessContextKey{}).(*requestAccess); ok && access != nil && h.store.team != nil && access.runtime == h.store.team {
351 prior := access.extraCheck
352 access.extraCheck = func(ctx context.Context) error {
353 if prior != nil {
354 if err := prior(ctx); err != nil {
355 return err
356 }
357 }
358 return h.store.requireMember(ctx, access.actor)
359 }
360 }
361 if h.google.Enabled() {
362 if err := googleimport.Headers(w, ContentSecurityPolicy); err != nil {
363 h.logger.Error("docs: import page policy", "err", err)
364 h.fail(w, r, http.StatusInternalServerError, failStatus)
365 return
366 }
367 } else {
368 w.Header().Set("Cache-Control", "no-store")
369 }
370 if err := h.render.pageStatus(w, r, "import", p, status); err != nil {
371 h.logger.Error("docs: render import page", "err", err)
372 h.fail(w, r, http.StatusInternalServerError, failStatus)
373 }
374}
375
376func (h *handlers) importGet(w http.ResponseWriter, r *http.Request) {
377 if !h.requireMemberRequest(w, r, false) {
378 return
379 }
380 if h.store.content == nil {
381 h.logger.Error("docs: import unavailable", "err", errImportUnsealed)
382 h.renderImport(w, r, h.importView(r, "", "docs.import.error.unsealed"), http.StatusServiceUnavailable)
383 return
384 }
385 h.renderImport(w, r, h.importView(r, uuid.NewString(), ""), 0)
386}
387
388// importPost reads the form without spilling to disk: MultipartReader,
389// one part at a time, the file read into memory up to maxImportFile.
390func (h *handlers) importPost(w http.ResponseWriter, r *http.Request) {
391 if !h.requireMemberRequest(w, r, false) {
392 return
393 }
394 owner, err := h.owner(r)
395 if err != nil {
396 h.logger.Error("docs: resolve signed-in person", "err", err)
397 h.fail(w, r, h.internalFailureStatus(), failStatus)
398 return
399 }
400 if h.store.content == nil {
401 h.logger.Error("docs: import unavailable", "err", errImportUnsealed)
402 h.renderImport(w, r, h.importView(r, "", "docs.import.error.unsealed"), http.StatusServiceUnavailable)
403 return
404 }
405 r.Body = http.MaxBytesReader(w, r.Body, maxImportBody)
406 token, name, data, status, errKey := readImportForm(r)
407 if token == "" {
408 token = uuid.NewString()
409 }
410 refuse := func(status int, key string) {
411 h.renderImport(w, r, h.importView(r, token, key), status)
412 }
413 if errKey != "" {
414 h.logger.Warn("docs: import refused", "reason", errKey)
415 refuse(status, errKey)
416 return
417 }
418
419 select {
420 case h.imports <- struct{}{}:
421 defer func() { <-h.imports }()
422 default:
423 refuse(http.StatusServiceUnavailable, "docs.import.error.busy")
424 return
425 }
426 started := time.Now()
427 imp, err := convertImport(r.Context(), h.store.core, data)
428 if err != nil {
429 key := importErrorKey(err)
430 // The reason only: never the file's name, title or content.
431 h.logger.Warn("docs: import refused", "reason", key, "bytes", len(data))
432 if key == "docs.import.error.failed" {
433 h.logger.Error("docs: import conversion failed", "err", err)
434 }
435 status := http.StatusUnprocessableEntity
436 if key == "docs.import.error.toolarge" {
437 status = http.StatusRequestEntityTooLarge
438 }
439 refuse(status, key)
440 return
441 }
442 title := importTitle(name)
443 if title == "" {
444 title = rastrillo.T(r, "docs.document.untitled")
445 }
446 doc, err := h.store.CreateImported(r.Context(), owner, title, token, imp)
447 if err != nil {
448 switch {
449 case errors.Is(err, errTeamNotMember):
450 h.fail(w, r, http.StatusForbidden, failStatus)
451 return
452 case errors.Is(err, errTeamUnavailable):
453 h.fail(w, r, http.StatusServiceUnavailable, failStatus)
454 return
455 }
456 h.logger.Error("docs: store imported document", "err", err)
457 refuse(h.internalFailureStatus(), "docs.import.error.failed")
458 return
459 }
460 h.logger.Info("docs: imported document", "doc_id", doc.ID, "bytes", len(data), "blocks", imp.blocks, "ms", time.Since(started).Milliseconds())
461 http.Redirect(w, r, "/d/"+doc.Sqid+"?imported=1", http.StatusSeeOther)
462}
463
464// readImportForm reads the creation token and the file. A refusal is a
465// status and a catalog key.
466func readImportForm(r *http.Request) (token, name string, data []byte, status int, errKey string) {
467 mr, err := r.MultipartReader()
468 if err != nil {
469 return "", "", nil, http.StatusBadRequest, "docs.import.error.nofile"
470 }
471 for parts := 0; ; parts++ {
472 if parts > 8 {
473 return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
474 }
475 part, err := mr.NextPart()
476 if err == io.EOF {
477 break
478 }
479 if err != nil {
480 var tooLarge *http.MaxBytesError
481 if errors.As(err, &tooLarge) {
482 return token, "", nil, http.StatusRequestEntityTooLarge, "docs.import.error.toolarge"
483 }
484 return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
485 }
486 switch part.FormName() {
487 case "creation_token":
488 b, err := io.ReadAll(io.LimitReader(part, 128))
489 if err == nil {
490 if id, err := uuid.Parse(strings.TrimSpace(string(b))); err == nil {
491 token = id.String()
492 }
493 }
494 case "file":
495 if data != nil {
496 return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
497 }
498 name = part.FileName()
499 var buf bytes.Buffer
500 n, err := io.Copy(&buf, io.LimitReader(part, maxImportFile+1))
501 if err != nil {
502 var tooLarge *http.MaxBytesError
503 if errors.As(err, &tooLarge) {
504 return token, "", nil, http.StatusRequestEntityTooLarge, "docs.import.error.toolarge"
505 }
506 return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
507 }
508 if n > maxImportFile {
509 return token, "", nil, http.StatusRequestEntityTooLarge, "docs.import.error.toolarge"
510 }
511 data = buf.Bytes()
512 }
513 part.Close()
514 }
515 if len(data) == 0 {
516 return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
517 }
518 if !strings.EqualFold(path.Ext(importBase(name)), ".docx") {
519 return token, "", nil, http.StatusUnsupportedMediaType, "docs.import.error.notword"
520 }
521 // The ZIP signature, before anything opens the archive.
522 if !bytes.HasPrefix(data, []byte("PK\x03\x04")) {
523 return token, "", nil, http.StatusUnsupportedMediaType, "docs.import.error.notword"
524 }
525 return token, name, data, 0, ""
526}
527
528// importBase is a filename with any directories taken off, whichever
529// separator a browser or the chooser used.
530func importBase(name string) string {
531 if i := strings.LastIndexAny(name, `/\`); i >= 0 {
532 name = name[i+1:]
533 }
534 return name
535}
536
537// importTitle is the document title a filename gives: its base, without
538// .docx, trimmed and bounded like a typed title.
539func importTitle(name string) string {
540 base := importBase(name)
541 base = base[:len(base)-len(path.Ext(base))]
542 base = strings.Map(func(c rune) rune {
543 if c < 0x20 || c == 0x7f {
544 return -1
545 }
546 return c
547 }, base)
548 base = strings.TrimSpace(base)
549 if len(base) > 1024 {
550 base = strings.ToValidUTF8(base[:1024], "")
551 }
552 return base
553}
554
555// reportView is a report as the page shows it: the statement of what an
556// import brings, always first, and one line per kind of loss.
557type reportView struct {
558 Heading, Statement, Incomplete, Empty string
559 Lines []reportLine
560 Href, OpenLabel string
561}
562
563type reportLine struct {
564 Text, Where string
565}
566
567func newReportView(r *http.Request, sqid string, rep *docx.Report) *reportView {
568 v := &reportView{
569 Heading: rastrillo.T(r, "docs.import.report.heading"),
570 Statement: rastrillo.T(r, "docs.import.fidelity"),
571 Incomplete: rastrillo.T(r, "docs.import.report.incomplete"),
572 Href: "/d/" + sqid + "/import-report",
573 OpenLabel: rastrillo.T(r, "docs.import.report.open"),
574 }
575 for _, it := range rep.Items {
576 key := "docs.import.report." + string(it.Code)
577 if !slices.Contains(docx.Codes, it.Code) {
578 continue
579 }
580 line := reportLine{Text: rastrillo.Tf(r, key, "count", it.Count)}
581 if len(it.Paragraphs) > 0 {
582 nums := make([]string, len(it.Paragraphs))
583 for i, p := range it.Paragraphs {
584 nums[i] = fmt.Sprint(p)
585 }
586 line.Where = rastrillo.Tf(r, "docs.import.report.where", "paragraphs", strings.Join(nums, ", "))
587 if it.Count > len(it.Paragraphs) {
588 line.Where = rastrillo.Tf(r, "docs.import.report.where.more", "paragraphs", strings.Join(nums, ", "))
589 }
590 }
591 v.Lines = append(v.Lines, line)
592 }
593 if len(v.Lines) == 0 {
594 v.Empty = rastrillo.T(r, "docs.import.report.none")
595 }
596 return v
597}
598
599type importReportPage struct {
600 Frame Frame
601 Report *reportView
602 Back string
603 BackHref string
604}
605
606// importReport is GET /d/{sqid}/import-report: the report, reopened.
607// Readable by anybody who can read the document; a document that was
608// not imported, or that the reader cannot see, is 404 alike.
609func (h *handlers) importReport(w http.ResponseWriter, r *http.Request) {
610 actor, err := h.actor(r)
611 if err != nil {
612 h.logger.Error("docs: resolve signed-in person", "err", err)
613 h.fail(w, r, h.internalFailureStatus(), failStatus)
614 return
615 }
616 doc, err := h.store.GetFor(r.Context(), actor, r.PathValue("sqid"))
617 if err != nil {
618 if errors.Is(err, gorm.ErrRecordNotFound) {
619 h.fail(w, r, http.StatusNotFound, failDocument)
620 return
621 }
622 h.logger.Error("docs: get document", "err", err)
623 h.fail(w, r, h.internalFailureStatus(), failStatus)
624 return
625 }
626 rep, err := h.store.ImportReport(r.Context(), doc)
627 if err != nil {
628 h.logger.Error("docs: open import report", "doc_id", doc.ID, "err", err)
629 h.fail(w, r, h.internalFailureStatus(), failStatus)
630 return
631 }
632 if rep == nil {
633 h.fail(w, r, http.StatusNotFound, failDocument)
634 return
635 }
636 heading := rastrillo.T(r, "docs.import.report.heading")
637 data := importReportPage{
638 Frame: h.frame(r, frameOptions{titleParts: []string{heading, doc.Title}, context: doc.Title}),
639 Report: newReportView(r, doc.Sqid, rep),
640 Back: rastrillo.T(r, "docs.import.report.back"),
641 BackHref: "/d/" + doc.Sqid,
642 }
643 w.Header().Set("Cache-Control", "no-store")
644 if err := h.render.page(w, r, "import-report", data); err != nil {
645 h.logger.Error("docs: render import report", "err", err)
646 h.fail(w, r, http.StatusInternalServerError, failStatus)
647 }
648}
649