mirror of
https://github.com/gotenberg/gotenberg.git
synced 2026-12-06 16:22:15 +00:00
feat(pdf): add dropSignatures to the stages that rewrite a signed PDF
This commit is contained in:
2
go.mod
2
go.mod
@@ -11,7 +11,7 @@ require (
|
||||
github.com/dlclark/regexp2/v2 v2.13.0
|
||||
github.com/gomarkdown/markdown v0.0.0-20261109103609-13f93121d67a
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gotenberg/litho v0.0.12
|
||||
github.com/gotenberg/litho v0.0.13
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8
|
||||
github.com/labstack/echo/v5 v5.4.5
|
||||
github.com/labstack/gommon v0.5.0
|
||||
|
||||
4
go.sum
4
go.sum
@@ -118,8 +118,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
|
||||
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
|
||||
github.com/gotenberg/litho v0.0.12 h1:karLO4Mwo/ZDF6B7iX6idOWaS8EGpuCsd/MSqoklIEo=
|
||||
github.com/gotenberg/litho v0.0.12/go.mod h1:BYtOYpLnI02JzPt4FbeozPgTz1OrCPyyao5kAoEpn4Y=
|
||||
github.com/gotenberg/litho v0.0.13 h1:nhThqw2v0E1gJY0IXdJZ5/lH5o6A2q8ts6V0iJHmVgQ=
|
||||
github.com/gotenberg/litho v0.0.13/go.mod h1:BYtOYpLnI02JzPt4FbeozPgTz1OrCPyyao5kAoEpn4Y=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 h1:5T5Ns3kMpWr+z3s5ZA0e7ljVyWNVNxK76sHPAxi5D1k=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0/go.mod h1:oWNYw09cH8wl8fFgC5hKlBLxR4XfKy2KQpP8MJjeCcc=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
|
||||
|
||||
@@ -487,17 +487,6 @@ func (s *optimizeStage) compaction(packObjectStreams bool) []litho.WriteOption {
|
||||
// carries. encryptionHandled tells that the stages remove the encryption on
|
||||
// purpose, with decrypt, or apply one of their own, with encrypt.
|
||||
func (s *optimizeStage) guardedWriteOptions(ctx context.Context, r *litho.Reader, encryptionHandled bool) ([]litho.WriteOption, error) {
|
||||
// A signature's digest covers the bytes of the file it was made in (ISO
|
||||
// 32000-1, 12.8.1): no rewrite keeps it.
|
||||
signatures, err := r.ExtractSignatures(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read the signatures: %w", err)
|
||||
}
|
||||
|
||||
if len(signatures) > 0 {
|
||||
return nil, &stageInputError{message: "the PDF is signed, and optimizing would remove its signatures"}
|
||||
}
|
||||
|
||||
// A rewrite writes the document decrypted.
|
||||
if r.IsEncrypted() && !encryptionHandled {
|
||||
return nil, &stageInputError{message: `the PDF is encrypted, and optimizing would write it decrypted: on /forms/pdf/pipe, add a "decrypt" stage before "optimize" to remove the encryption, or an "encrypt" stage to keep one`}
|
||||
|
||||
@@ -122,6 +122,12 @@ var lithoFixes = []struct {
|
||||
return message + "; draw at a lower 'dpi', or raise --pdf-max-render-pixels (env PDF_MAX_RENDER_PIXELS)"
|
||||
},
|
||||
},
|
||||
{
|
||||
err: litho.ErrSignaturesDropped,
|
||||
fix: func(string) string {
|
||||
return `the PDF is signed, and this stage rewrites it, which would remove its signatures; set "dropSignatures" to true to remove them`
|
||||
},
|
||||
},
|
||||
{
|
||||
err: litho.ErrIncompatibleProfiles,
|
||||
fix: func(message string) string {
|
||||
|
||||
@@ -123,7 +123,7 @@ func (p *Processor) run(ctx *api.Context, stages Stages, inputPaths []string, fi
|
||||
for i := 0; i < len(stages); {
|
||||
switch s := stages[i].(type) {
|
||||
case *mergeStage:
|
||||
docs, err = p.merge(ctx, docs, password)
|
||||
docs, err = p.merge(ctx, s, docs, password)
|
||||
i++
|
||||
case *splitStage:
|
||||
docs, err = p.split(ctx, s, docs, password)
|
||||
@@ -272,7 +272,8 @@ func (p *Processor) write(ctx *api.Context, pipeline *litho.Pipeline, ops []stri
|
||||
}
|
||||
|
||||
writeCtx := litho.ContextWithHTTPClient(spanCtx, client)
|
||||
_, err = pipeline.WriteTo(writeCtx, out, append(opts, litho.WithPipelineTempDir(ctx.DirPath()))...)
|
||||
var dropped []litho.DroppedSignature
|
||||
_, err = pipeline.WriteTo(writeCtx, out, append(opts, litho.WithPipelineTempDir(ctx.DirPath()), litho.WithDroppedSignatures(&dropped))...)
|
||||
|
||||
closeErr := out.Close()
|
||||
if err != nil {
|
||||
@@ -283,13 +284,17 @@ func (p *Processor) write(ctx *api.Context, pipeline *litho.Pipeline, ops []stri
|
||||
return document{}, fmt.Errorf("close output file: %w", closeErr)
|
||||
}
|
||||
|
||||
if len(dropped) > 0 {
|
||||
ctx.Log().InfoContext(ctx, fmt.Sprintf("%s removed %d signature(s) to write '%s'", strings.Join(ops, ", "), len(dropped), filename))
|
||||
}
|
||||
|
||||
ctx.RegisterDiskPath(path, filename)
|
||||
|
||||
return document{path: path, filename: filename}, nil
|
||||
}
|
||||
|
||||
// merge appends every document, in order, into one named after the first.
|
||||
func (p *Processor) merge(ctx *api.Context, docs []document, password string) ([]document, error) {
|
||||
func (p *Processor) merge(ctx *api.Context, s *mergeStage, docs []document, password string) ([]document, error) {
|
||||
// A single document is not rewritten, but it is read all the same: merge
|
||||
// must not hand back a file the other routes refuse.
|
||||
if len(docs) == 1 {
|
||||
@@ -319,16 +324,11 @@ func (p *Processor) merge(ctx *api.Context, docs []document, password string) ([
|
||||
}
|
||||
|
||||
readers = append(readers, r)
|
||||
|
||||
err = refuseSigned(ctx, r)
|
||||
if err != nil {
|
||||
return nil, &stageError{op: "merge", filename: d.filename, err: err}
|
||||
}
|
||||
}
|
||||
|
||||
pipeline := litho.NewPipeline().Open(readers[0]).Merge(readers[1:])
|
||||
|
||||
merged, err := p.write(ctx, pipeline, []string{"merge"}, docs[0].filename)
|
||||
merged, err := p.write(ctx, pipeline, []string{"merge"}, docs[0].filename, signatureRemoval(s)...)
|
||||
if err != nil {
|
||||
return nil, &stageError{op: "merge", filename: docs[0].filename, err: err}
|
||||
}
|
||||
@@ -381,12 +381,6 @@ func (p *Processor) compose(ctx *api.Context, s *composeStage, docs []document,
|
||||
}
|
||||
|
||||
readers = append(readers, r)
|
||||
|
||||
// The composed document is a new file: no signature survives.
|
||||
err = refuseSigned(ctx, r)
|
||||
if err != nil {
|
||||
return nil, &stageError{op: "compose", filename: d.filename, err: err}
|
||||
}
|
||||
}
|
||||
|
||||
placements := make([]litho.Placement, len(s.Placements))
|
||||
@@ -404,7 +398,7 @@ func (p *Processor) compose(ctx *api.Context, s *composeStage, docs []document,
|
||||
|
||||
pipeline := litho.NewPipeline().Compose(s.width*pointsPerInch, s.height*pointsPerInch, placements)
|
||||
|
||||
composed, err := p.write(ctx, pipeline, []string{"compose"}, docs[0].filename)
|
||||
composed, err := p.write(ctx, pipeline, []string{"compose"}, docs[0].filename, signatureRemoval(s)...)
|
||||
if err != nil {
|
||||
return nil, failed(err)
|
||||
}
|
||||
@@ -478,11 +472,6 @@ func (p *Processor) splitOne(ctx *api.Context, s *splitStage, d document, passwo
|
||||
}
|
||||
defer func() { _ = r.Close() }()
|
||||
|
||||
err = refuseSigned(ctx, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pageCount, err := r.PageCount(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("count pages: %w", err)
|
||||
@@ -497,7 +486,7 @@ func (p *Processor) splitOne(ctx *api.Context, s *splitStage, d document, passwo
|
||||
parts := make([]document, 0, len(groups))
|
||||
|
||||
for i, pages := range groups {
|
||||
part, err := p.write(ctx, litho.NewPipeline().Open(r).Split(pages), []string{"split"}, fmt.Sprintf("%s_%d.pdf", base, i))
|
||||
part, err := p.write(ctx, litho.NewPipeline().Open(r).Split(pages), []string{"split"}, fmt.Sprintf("%s_%d.pdf", base, i), signatureRemoval(s)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -570,19 +559,14 @@ func (p *Processor) runOne(ctx *api.Context, run Stages, d document, password st
|
||||
return document{}, &stageError{op: run[0].op(), filename: d.filename, err: fmt.Errorf("count pages: %w", err)}
|
||||
}
|
||||
|
||||
// A rewrite drops the signatures of the PDF: refuse it before running.
|
||||
// optimize has a guard of its own.
|
||||
// The first rewrite drops the signatures of the PDF, which the edits
|
||||
// before it keep: it decides whether litho may.
|
||||
var firstRewrite rewriter
|
||||
for _, s := range run {
|
||||
if !rewrites(s) {
|
||||
continue
|
||||
if rw, ok := s.(rewriter); ok {
|
||||
firstRewrite = rw
|
||||
break
|
||||
}
|
||||
|
||||
err = refuseSigned(ctx, r)
|
||||
if err != nil {
|
||||
return document{}, &stageError{op: s.op(), filename: d.filename, err: err}
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
env := &runEnv{processor: p, pageCount: pageCount, files: files, source: r}
|
||||
@@ -590,8 +574,7 @@ func (p *Processor) runOne(ctx *api.Context, run Stages, d document, password st
|
||||
|
||||
pipeline := litho.NewPipeline().Open(r)
|
||||
var (
|
||||
dropped []litho.DroppedSignature
|
||||
writeOpts = []litho.WriteOption{litho.WithDroppedSignatures(&dropped)}
|
||||
writeOpts []litho.WriteOption
|
||||
optimizing bool
|
||||
compactionSkipped bool
|
||||
// litho applies most edits when a later stage or the write runs: a
|
||||
@@ -657,8 +640,23 @@ func (p *Processor) runOne(ctx *api.Context, run Stages, d document, password st
|
||||
ops[i] = s.op()
|
||||
}
|
||||
|
||||
if firstRewrite != nil {
|
||||
writeOpts = append(writeOpts, signatureRemoval(firstRewrite)...)
|
||||
}
|
||||
|
||||
out, err := p.write(ctx, pipeline, ops, d.filename, writeOpts...)
|
||||
if err != nil {
|
||||
// litho refuses the rewrite that would drop the signatures: the first
|
||||
// rewriting stage decides. Without one, any edit rewrites a PDF litho
|
||||
// repaired on reading, and no stage can allow it.
|
||||
if errors.Is(err, litho.ErrSignaturesDropped) {
|
||||
if firstRewrite != nil {
|
||||
return document{}, &stageError{op: firstRewrite.op(), filename: d.filename, err: err}
|
||||
}
|
||||
|
||||
return document{}, &stageError{op: run[len(run)-1].op(), filename: d.filename, err: &stageInputError{message: "the PDF is signed and damaged, and any edit rewrites it while repairing it, which would remove its signatures"}}
|
||||
}
|
||||
|
||||
// The stage that applied a failed edit, whose error wraps it, is not
|
||||
// the one that queued it.
|
||||
if e := editError(err); e != nil {
|
||||
@@ -685,12 +683,6 @@ func (p *Processor) runOne(ctx *api.Context, run Stages, d document, password st
|
||||
return document{}, &stageError{op: run[len(run)-1].op(), filename: d.filename, err: err}
|
||||
}
|
||||
|
||||
// Any edit rewrites a PDF litho repaired on reading: the stages above
|
||||
// cannot tell it before running.
|
||||
if len(dropped) > 0 {
|
||||
return document{}, &stageError{op: run[len(run)-1].op(), filename: d.filename, err: errSignedRewrite()}
|
||||
}
|
||||
|
||||
if optimizing && compactionSkipped {
|
||||
ctx.Log().WarnContext(ctx, fmt.Sprintf("optimize wrote '%s' without compacting it: litho appended an update to the document rather than rewriting it", d.filename))
|
||||
}
|
||||
@@ -702,42 +694,15 @@ func (p *Processor) runOne(ctx *api.Context, run Stages, d document, password st
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// errSignedRewrite is the refusal of a stage that would rewrite a signed PDF.
|
||||
func errSignedRewrite() error {
|
||||
return &stageInputError{message: "the PDF is signed, and this stage rewrites it, which would remove its signatures"}
|
||||
}
|
||||
|
||||
// refuseSigned returns [errSignedRewrite] when the PDF r reads is signed: a
|
||||
// signature's digest covers the bytes of the file it was made in (ISO
|
||||
// 32000-1, 12.8.1), so no rewrite keeps it.
|
||||
func refuseSigned(ctx context.Context, r *litho.Reader) error {
|
||||
signatures, err := r.ExtractSignatures(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read the signatures: %w", err)
|
||||
// signatureRemoval returns the write options that let litho drop the
|
||||
// signatures of the PDF the rewrite s writes, when s allows it: litho refuses
|
||||
// it otherwise (see [litho.ErrSignaturesDropped]).
|
||||
func signatureRemoval(s rewriter) []litho.WriteOption {
|
||||
if !s.dropsSignatures() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(signatures) > 0 {
|
||||
return errSignedRewrite()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// rewrites reports whether stage s rewrites the document whole, which drops
|
||||
// its signatures (litho's Writer.DroppedSignatures lists those edits): select,
|
||||
// delete and compose build a new file, as merge and split do, and insert,
|
||||
// encryption, decryption, form flattening, redaction, remediation, color
|
||||
// conversion and transparency flattening rewrite it. The other edits append
|
||||
// an incremental update, which keeps them. optimize, which forces a rewrite,
|
||||
// has a guard of its own.
|
||||
func rewrites(s stage) bool {
|
||||
switch s.(type) {
|
||||
case *selectStage, *deleteStage, *insertStage, *encryptStage, *decryptStage, *flattenFormStage,
|
||||
*redactStage, *remediateStage, *convertColorsStage, *flattenTransparencyStage, *composeStage:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return []litho.WriteOption{litho.WithSignatureRemoval()}
|
||||
}
|
||||
|
||||
// maxFormFieldsInMessage bounds the field names an unknown field's message
|
||||
|
||||
@@ -1080,7 +1080,7 @@ func TestRunOptimize(t *testing.T) {
|
||||
prepare: `[{"op":"sign","certificate":"cert.pem","key":"key.pem"}]`,
|
||||
fixtures: []string{"pem/cert.pem", "pem/key.pem"},
|
||||
stages: `[{"op":"optimize"}]`,
|
||||
wantErr: "Stage 'optimize' failed on 'page_1.pdf': the PDF is signed, and optimizing would remove its signatures",
|
||||
wantErr: `Stage 'optimize' failed on 'page_1.pdf': the PDF is signed, and this stage rewrites it, which would remove its signatures; set "dropSignatures" to true to remove them`,
|
||||
},
|
||||
{
|
||||
name: "encrypted",
|
||||
@@ -1241,9 +1241,9 @@ func TestRefusalLogging(t *testing.T) {
|
||||
}
|
||||
|
||||
// A stage that rewrites a signed PDF would drop its signatures: it answers
|
||||
// 400, while an incremental edit keeps them.
|
||||
// 400 unless it sets dropSignatures, while an incremental edit keeps them.
|
||||
func TestRunSignedInput(t *testing.T) {
|
||||
const signedMessage = "the PDF is signed, and this stage rewrites it, which would remove its signatures"
|
||||
const signedMessage = `the PDF is signed, and this stage rewrites it, which would remove its signatures; set "dropSignatures" to true to remove them`
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
@@ -1256,12 +1256,14 @@ func TestRunSignedInput(t *testing.T) {
|
||||
{name: "insert", stages: `[{"op":"insert","source":"page_2.pdf"}]`, fixtures: []string{"page_2.pdf"}, wantOp: "insert"},
|
||||
{name: "encrypt", stages: `[{"op":"encrypt","userPassword":"u"}]`, wantOp: "encrypt"},
|
||||
{name: "flatten-form", stages: `[{"op":"flatten-form"}]`, wantOp: "flatten-form"},
|
||||
{name: "redact", stages: `[{"op":"redact","regions":[{"page":1,"x":0,"y":0,"width":10,"height":10}]}]`, wantOp: "redact"},
|
||||
{name: "redact", stages: `[{"op":"redact","regions":[{"page":1,"x":0,"y":0,"width":612,"height":792}]}]`, wantOp: "redact"},
|
||||
{name: "remediate", stages: `[{"op":"remediate","profile":"PDF/A-2b"}]`, wantOp: "remediate"},
|
||||
{name: "convert-colors", stages: `[{"op":"convert-colors","target":"gray"}]`, wantOp: "convert-colors"},
|
||||
{name: "flatten-transparency", stages: `[{"op":"flatten-transparency"}]`, wantOp: "flatten-transparency"},
|
||||
{name: "split", stages: `[{"op":"split","every":1}]`, wantOp: "split"},
|
||||
{name: "merge", stages: `[{"op":"merge"}]`, fixtures: []string{"page_2.pdf"}, wantOp: "merge"},
|
||||
{name: "compose", stages: `[{"op":"compose","paperSize":"A4","placements":[{"page":1,"x":0,"y":0}]}]`, wantOp: "compose"},
|
||||
{name: "optimize", stages: `[{"op":"optimize"}]`, wantOp: "optimize"},
|
||||
{name: "an incremental edit, then a rewrite", stages: `[{"op":"stamp-text","text":"DRAFT"},{"op":"select","pages":"1"}]`, wantOp: "select"},
|
||||
{name: "stamp-text", stages: `[{"op":"stamp-text","text":"DRAFT"}]`},
|
||||
{name: "set-metadata", stages: `[{"op":"set-metadata","title":"Signed"}]`},
|
||||
@@ -1272,11 +1274,11 @@ func TestRunSignedInput(t *testing.T) {
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
processor := testProcessor()
|
||||
ctx, paths := testContext(t, append([]string{"page_1.pdf", "pem/cert.pem", "pem/key.pem"}, tc.fixtures...)...)
|
||||
ctx, paths := testContext(t, append([]string{"pages_3.pdf", "pem/cert.pem", "pem/key.pem"}, tc.fixtures...)...)
|
||||
files := make(map[string]string, len(paths))
|
||||
maps.Copy(files, paths)
|
||||
|
||||
signed, err := processor.Run(ctx, mustStages(t, `[{"op":"sign","certificate":"cert.pem","key":"key.pem"}]`), []string{paths["page_1.pdf"]}, files)
|
||||
signed, err := processor.Run(ctx, mustStages(t, `[{"op":"sign","certificate":"cert.pem","key":"key.pem"}]`), []string{paths["pages_3.pdf"]}, files)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -1289,10 +1291,27 @@ func TestRunSignedInput(t *testing.T) {
|
||||
outputs, err := processor.Run(ctx, mustStages(t, tc.stages), inputs, files)
|
||||
if tc.wantOp != "" {
|
||||
status, message := api.ParseError(err)
|
||||
want := fmt.Sprintf("Stage '%s' failed on 'page_1.pdf': %s", tc.wantOp, signedMessage)
|
||||
want := fmt.Sprintf("Stage '%s' failed on 'pages_3.pdf': %s", tc.wantOp, signedMessage)
|
||||
if status != http.StatusBadRequest || message != want {
|
||||
t.Fatalf("got %d %q, want 400 %q", status, message, want)
|
||||
t.Fatalf("got %d %q (%v), want 400 %q", status, message, err, want)
|
||||
}
|
||||
|
||||
// The same stage, allowed to drop the signatures, writes the
|
||||
// PDF without them.
|
||||
allowed := strings.Replace(tc.stages, `{"op":"`+tc.wantOp+`"`, `{"op":"`+tc.wantOp+`","dropSignatures":true`, 1)
|
||||
outputs, err = processor.Run(ctx, mustStages(t, allowed), inputs, files)
|
||||
if err != nil {
|
||||
t.Fatalf("with dropSignatures: %v", err)
|
||||
}
|
||||
|
||||
for _, output := range outputs {
|
||||
// encrypt writes the PDF for its user password.
|
||||
signatures, err := openOutput(t, output, litho.WithPassword("u")).ExtractSignatures(context.Background())
|
||||
if err != nil || len(signatures) != 0 {
|
||||
t.Fatalf("with dropSignatures: signatures = %v, %v, want none", signatures, err)
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ func stageFromForm(op string, form *api.FormData) (Stages, map[string]string, er
|
||||
object := map[string]any{"op": op}
|
||||
t := reflect.TypeOf(newStage()).Elem()
|
||||
|
||||
for field := range t.Fields() {
|
||||
for _, field := range reflect.VisibleFields(t) {
|
||||
name, _, _ := strings.Cut(field.Tag.Get("json"), ",")
|
||||
if name == "" {
|
||||
continue
|
||||
|
||||
@@ -12,8 +12,33 @@ import (
|
||||
"github.com/gotenberg/gotenberg/v9/pkg/modules/api"
|
||||
)
|
||||
|
||||
// signatureDrop is the option of the stages that rewrite a PDF whole, or
|
||||
// build a new one from it. A signature's digest covers the bytes of the file
|
||||
// it was made in (ISO 32000-1, 12.8.1), so no such output keeps it: litho
|
||||
// leaves each signature out and draws its visible appearance into the page.
|
||||
// litho refuses such an output unless DropSignatures allows it (see
|
||||
// [litho.ErrSignaturesDropped]); a stage that ends up appending an update to
|
||||
// the PDF keeps its signatures and needs none.
|
||||
type signatureDrop struct {
|
||||
DropSignatures bool `json:"dropSignatures"`
|
||||
}
|
||||
|
||||
func (s signatureDrop) dropsSignatures() bool { return s.DropSignatures }
|
||||
|
||||
// rewriter is a stage that rewrites a PDF whole, or builds a new one from it:
|
||||
// merge, split, select, delete, insert, compose, flatten-form,
|
||||
// flatten-transparency, convert-colors, redact, optimize, encrypt, decrypt and
|
||||
// remediate. The other edits append an incremental update, which keeps the
|
||||
// signatures.
|
||||
type rewriter interface {
|
||||
stage
|
||||
dropsSignatures() bool
|
||||
}
|
||||
|
||||
// mergeStage appends every current document, in order, into one.
|
||||
type mergeStage struct{}
|
||||
type mergeStage struct {
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*mergeStage) op() string { return "merge" }
|
||||
func (*mergeStage) validate() error { return nil }
|
||||
@@ -25,6 +50,8 @@ func (*mergeStage) files() []string { return nil }
|
||||
type splitStage struct {
|
||||
Every *int `json:"every"`
|
||||
Ranges []string `json:"ranges"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*splitStage) op() string { return "split" }
|
||||
@@ -53,6 +80,8 @@ func (*splitStage) files() []string { return nil }
|
||||
// selectStage keeps the given pages, in the given order.
|
||||
type selectStage struct {
|
||||
Pages string `json:"pages"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*selectStage) op() string { return "select" }
|
||||
@@ -62,6 +91,8 @@ func (*selectStage) files() []string { return nil }
|
||||
// deleteStage removes the given pages.
|
||||
type deleteStage struct {
|
||||
Pages string `json:"pages"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*deleteStage) op() string { return "delete" }
|
||||
@@ -75,6 +106,8 @@ type insertStage struct {
|
||||
Source string `json:"source"`
|
||||
At int `json:"at"`
|
||||
SourcePages string `json:"sourcePages"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*insertStage) op() string { return "insert" }
|
||||
@@ -254,6 +287,8 @@ type composeStage struct {
|
||||
// it.
|
||||
width float64
|
||||
height float64
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
// placement draws a page of one of the current documents on a composed page.
|
||||
@@ -462,14 +497,18 @@ func (s *setFormStage) validate() error {
|
||||
func (*setFormStage) files() []string { return nil }
|
||||
|
||||
// flattenFormStage burns the form fields into the page content.
|
||||
type flattenFormStage struct{}
|
||||
type flattenFormStage struct {
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*flattenFormStage) op() string { return "flatten-form" }
|
||||
func (*flattenFormStage) validate() error { return nil }
|
||||
func (*flattenFormStage) files() []string { return nil }
|
||||
|
||||
// flattenTransparencyStage replaces transparent content with opaque content.
|
||||
type flattenTransparencyStage struct{}
|
||||
type flattenTransparencyStage struct {
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*flattenTransparencyStage) op() string { return "flatten-transparency" }
|
||||
func (*flattenTransparencyStage) validate() error { return nil }
|
||||
@@ -479,6 +518,8 @@ func (*flattenTransparencyStage) files() []string { return nil }
|
||||
// "gray", or "output-intent" for the document's own output intent.
|
||||
type convertColorsStage struct {
|
||||
Target string `json:"target"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*convertColorsStage) op() string { return "convert-colors" }
|
||||
@@ -507,6 +548,8 @@ type redactRegion struct {
|
||||
// redactStage removes the content under the given regions.
|
||||
type redactStage struct {
|
||||
Regions []redactRegion `json:"regions"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*redactStage) op() string { return "redact" }
|
||||
@@ -616,6 +659,8 @@ type optimizeStage struct {
|
||||
Dedup *bool `json:"dedup"`
|
||||
RecompressImages *bool `json:"recompressImages"`
|
||||
SubsetFonts *bool `json:"subsetFonts"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*optimizeStage) op() string { return "optimize" }
|
||||
@@ -663,6 +708,8 @@ type encryptStage struct {
|
||||
OwnerPassword string `json:"ownerPassword"`
|
||||
Algorithm string `json:"algorithm"`
|
||||
Permissions *permissions `json:"permissions"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*encryptStage) op() string { return "encrypt" }
|
||||
@@ -686,6 +733,8 @@ func (*encryptStage) files() []string { return nil }
|
||||
// encryption.
|
||||
type decryptStage struct {
|
||||
Password string `json:"password"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*decryptStage) op() string { return "decrypt" }
|
||||
@@ -708,6 +757,8 @@ type remediateStage struct {
|
||||
Xml string `json:"xml"`
|
||||
Level string `json:"level"`
|
||||
DocumentType string `json:"documentType"`
|
||||
|
||||
signatureDrop
|
||||
}
|
||||
|
||||
func (*remediateStage) op() string { return "remediate" }
|
||||
|
||||
@@ -471,7 +471,7 @@ func optionNames(s stage) map[string]bool {
|
||||
t := reflect.TypeOf(s).Elem()
|
||||
names := make(map[string]bool, t.NumField())
|
||||
|
||||
for field := range t.Fields() {
|
||||
for _, field := range reflect.VisibleFields(t) {
|
||||
name, _, _ := strings.Cut(field.Tag.Get("json"), ",")
|
||||
if name != "" {
|
||||
names[name] = true
|
||||
|
||||
@@ -31,6 +31,8 @@ func TestParseStages(t *testing.T) {
|
||||
{name: "missing op", raw: `[{"angle":90}]`, wantErr: `"op" must name an operation`},
|
||||
{name: "unknown op", raw: `[{"op":"shred"}]`, wantErr: `unknown operation "shred"`},
|
||||
{name: "unknown option", raw: `[{"op":"rotate","angle":90,"degrees":90}]`, wantErr: `rotate: unknown option "degrees"`},
|
||||
{name: "dropSignatures on a rewrite", raw: `[{"op":"split","every":1,"dropSignatures":true}]`, wantOps: []string{"split"}},
|
||||
{name: "dropSignatures on an incremental edit", raw: `[{"op":"rotate","angle":90,"dropSignatures":true}]`, wantErr: `rotate: unknown option "dropSignatures"`},
|
||||
{name: "option names are exact", raw: `[{"op":"set-metadata","Title":"T"}]`, wantErr: `set-metadata: unknown option "Title"`},
|
||||
{name: "wrong option type", raw: `[{"op":"rotate","angle":"ninety"}]`, wantErr: `stage 0: rotate: "angle" is invalid (got "ninety", want an integer)`},
|
||||
{name: "fraction for an integer", raw: `[{"op":"rotate","angle":90.5}]`, wantErr: `rotate: "angle" is invalid (got 90.5, want an integer)`},
|
||||
@@ -378,3 +380,23 @@ func TestComposeStageFromForm(t *testing.T) {
|
||||
t.Fatalf("placements = %+v", s.Placements)
|
||||
}
|
||||
}
|
||||
|
||||
// A rewriting stage reads dropSignatures from its flat form field, as its own
|
||||
// options.
|
||||
func TestSplitStageFromFormDropSignatures(t *testing.T) {
|
||||
ctx, _ := testContext(t, "pages_3.pdf")
|
||||
mock := &api.ContextMock{Context: ctx}
|
||||
mock.SetValues(map[string][]string{
|
||||
"every": {"1"},
|
||||
"dropSignatures": {"true"},
|
||||
})
|
||||
|
||||
stages, _, err := stageFromForm("split", ctx.FormData())
|
||||
if err != nil {
|
||||
t.Fatalf("stageFromForm: %v", err)
|
||||
}
|
||||
|
||||
if s := stages[0].(*splitStage); !s.DropSignatures || s.Every == nil || *s.Every != 1 {
|
||||
t.Fatalf("stage = %+v, want every 1 and dropSignatures", s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ Feature: /forms/pdf/optimize
|
||||
Then the response status code should be 400
|
||||
Then the response body should match string:
|
||||
"""
|
||||
Stage 'optimize' failed on 'foo.pdf': the PDF is signed, and optimizing would remove its signatures
|
||||
Stage 'optimize' failed on 'foo.pdf': the PDF is signed, and this stage rewrites it, which would remove its signatures; set "dropSignatures" to true to remove them
|
||||
"""
|
||||
When I make a "POST" request to Gotenberg at the "/forms/pdf/encrypt" endpoint with the following form data and header(s):
|
||||
| files | testdata/page_1.pdf | file |
|
||||
|
||||
@@ -38,7 +38,8 @@ Feature: /forms/pdf/sign
|
||||
Then the response PDF(s) should NOT be signed
|
||||
|
||||
# A stage that rewrites a signed PDF would drop its signatures, even after an
|
||||
# incremental edit; an incremental edit alone keeps them.
|
||||
# incremental edit, unless it sets dropSignatures; an incremental edit alone
|
||||
# keeps them.
|
||||
Scenario: POST /forms/pdf/pipe (Signed PDF)
|
||||
Given I have a default Gotenberg container
|
||||
When I make a "POST" request to Gotenberg at the "/forms/pdf/sign" endpoint with the following form data and header(s):
|
||||
@@ -55,16 +56,14 @@ Feature: /forms/pdf/sign
|
||||
Then the response status code should be 400
|
||||
Then the response body should match string:
|
||||
"""
|
||||
Stage 'select' failed on 'foo.pdf': the PDF is signed, and this stage rewrites it, which would remove its signatures
|
||||
"""
|
||||
When I make a "POST" request to Gotenberg at the "/forms/pdf/remediate" endpoint with the following form data and header(s):
|
||||
| files | teststore/foo.pdf | file |
|
||||
| profile | PDF/A-2b | field |
|
||||
Then the response status code should be 400
|
||||
Then the response body should match string:
|
||||
"""
|
||||
Stage 'remediate' failed on 'foo.pdf': the PDF is signed, and this stage rewrites it, which would remove its signatures
|
||||
Stage 'select' failed on 'foo.pdf': the PDF is signed, and this stage rewrites it, which would remove its signatures; set "dropSignatures" to true to remove them
|
||||
"""
|
||||
When I make a "POST" request to Gotenberg at the "/forms/pdf/split" endpoint with the following form data and header(s):
|
||||
| files | teststore/foo.pdf | file |
|
||||
| every | 1 | field |
|
||||
| dropSignatures | true | field |
|
||||
Then the response status code should be 200
|
||||
Then the response PDF(s) should NOT be signed
|
||||
When I make a "POST" request to Gotenberg at the "/forms/pdf/pipe" endpoint with the following form data and header(s):
|
||||
| files | teststore/foo.pdf | file |
|
||||
| stages | [{"op":"stamp-text","text":"DRAFT"}] | field |
|
||||
|
||||
Reference in New Issue
Block a user