Debian Codegraph @

internal/format/format_test.go

raw symbols SCIP
1 // Copyright 2021 The age Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build go1.18
6
7 package format_test
8
9 import (
10 "bufio"
11 "bytes"
12 "errors"
13 "io"
14 "io/fs"
15 "strings"
16 "testing"
17
18 agetest "c2sp.org/CCTV/age"
19 "filippo.io/age/internal/format"
20 )
21
22 func TestStanzaMarshal(t *testing.T) {
23 s := &format.Stanza{
24 Type: "test",
25 Args: []string{"1", "2", "3"},
26 Body: nil, // empty
27 }
28 buf := &bytes.Buffer{}
29 s.Marshal(buf)
30 if exp := "-> test 1 2 3\n\n"; buf.String() != exp {
31 t.Errorf("wrong empty stanza encoding: expected %q, got %q", exp, buf.String())
32 }
33
34 buf.Reset()
35 s.Body = []byte("AAA")
36 s.Marshal(buf)
37 if exp := "-> test 1 2 3\nQUFB\n"; buf.String() != exp {
38 t.Errorf("wrong normal stanza encoding: expected %q, got %q", exp, buf.String())
39 }
40
41 buf.Reset()
42 s.Body = bytes.Repeat([]byte("A"), format.BytesPerLine)
43 s.Marshal(buf)
44 if exp := "-> test 1 2 3\nQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\n\n"; buf.String() != exp {
45 t.Errorf("wrong 64 columns stanza encoding: expected %q, got %q", exp, buf.String())
46 }
47
48 for _, s := range []*format.Stanza{
49 {Type: ""},
50 {Type: "test", Args: []string{""}},
51 {Type: "test", Args: []string{"a b"}},
52 {Type: "test", Args: []string{"a\nb"}},
53 {Type: "test", Args: []string{"café"}},
54 } {
55 buf.Reset()
56 if err := s.Marshal(buf); err == nil {
57 t.Errorf("Marshal accepted type %q, args %q", s.Type, s.Args)
58 }
59 if buf.Len() != 0 {
60 t.Errorf("Marshal wrote %d bytes", buf.Len())
61 }
62 }
63 }
64
65 func TestHeaderMarshalNoStanzas(t *testing.T) {
66 buf := &bytes.Buffer{}
67 if err := (&format.Header{}).Marshal(buf); err == nil {
68 t.Fatal("Marshal accepted a header with no stanzas")
69 }
70 if buf.Len() != 0 {
71 t.Errorf("Marshal wrote %d bytes", buf.Len())
72 }
73 }
74
75 func TestParseLimits(t *testing.T) {
76 const (
77 intro = "age-encryption.org/v1\n"
78 maxHeaderBytes = 2 << 20
79 )
80 footer := "--- " + format.EncodeToString(make([]byte, 32)) + "\n"
81
82 t.Run("header size", func(t *testing.T) {
83 makeHeader := func(size int) []byte {
84 const opening = "-> test "
85 fixed := len(intro) + len(opening) + len("\n\n") + len(footer)
86 return []byte(intro + opening + strings.Repeat("a", size-fixed) + "\n\n" + footer)
87 }
88
89 if _, _, err := format.Parse(bytes.NewReader(makeHeader(maxHeaderBytes))); err != nil {
90 t.Fatalf("maximum-size header was rejected: %v", err)
91 }
92 _, _, err := format.Parse(bytes.NewReader(makeHeader(maxHeaderBytes + 1)))
93 if err == nil || !strings.Contains(err.Error(), "header exceeds 2 MiB") {
94 t.Fatalf("unexpected oversized-header error: %v", err)
95 }
96 var parseError *format.ParseError
97 if !errors.As(err, &parseError) {
98 t.Errorf("oversized-header error is not a ParseError: %T", err)
99 }
100 if strings.Count(err.Error(), "parsing age header") != 1 {
101 t.Errorf("oversized-header error nests ParseError prefixes: %v", err)
102 }
103
104 // An intro line that exceeds the limit before any newline.
105 _, _, err = format.Parse(bytes.NewReader(bytes.Repeat([]byte{'a'}, maxHeaderBytes+1)))
106 if err == nil || !strings.Contains(err.Error(), "header exceeds 2 MiB") {
107 t.Fatalf("unexpected oversized-intro error: %v", err)
108 }
109 if !errors.As(err, &parseError) {
110 t.Errorf("oversized-intro error is not a ParseError: %T", err)
111 }
112 if strings.Count(err.Error(), "parsing age header") != 1 {
113 t.Errorf("oversized-intro error nests ParseError prefixes: %v", err)
114 }
115 })
116
117 t.Run("recipient stanzas", func(t *testing.T) {
118 makeHeader := func(stanzas int) []byte {
119 return []byte(intro + strings.Repeat("-> test\n\n", stanzas) + footer)
120 }
121
122 if _, _, err := format.Parse(bytes.NewReader(makeHeader(0))); err == nil || !strings.Contains(err.Error(), "no recipient stanzas") {
123 t.Fatalf("unexpected zero-stanza error: %v", err)
124 }
125 if _, _, err := format.Parse(bytes.NewReader(makeHeader(1024))); err != nil {
126 t.Fatalf("header with 1024 stanzas was rejected: %v", err)
127 }
128 _, _, err := format.Parse(bytes.NewReader(makeHeader(1025)))
129 if err == nil || !strings.Contains(err.Error(), "more than 1024 recipient stanzas") {
130 t.Fatalf("unexpected stanza-limit error: %v", err)
131 }
132 })
133
134 t.Run("recipient stanza arguments", func(t *testing.T) {
135 makeHeader := func(args int) []byte {
136 return []byte(intro + "-> test" + strings.Repeat(" a", args) + "\n\n" + footer)
137 }
138
139 if _, _, err := format.Parse(bytes.NewReader(makeHeader(128))); err != nil {
140 t.Fatalf("stanza with 128 arguments was rejected: %v", err)
141 }
142 _, _, err := format.Parse(bytes.NewReader(makeHeader(129)))
143 if err == nil {
144 t.Fatal("stanza with 129 arguments was accepted")
145 }
146 })
147
148 t.Run("payload is not limited", func(t *testing.T) {
149 header := []byte(intro + "-> test\n\n" + footer)
150 want := bytes.Repeat([]byte("p"), maxHeaderBytes+1)
151 _, payload, err := format.Parse(io.MultiReader(bytes.NewReader(header), bytes.NewReader(want)))
152 if err != nil {
153 t.Fatal(err)
154 }
155 got, err := io.ReadAll(payload)
156 if err != nil {
157 t.Fatal(err)
158 }
159 if !bytes.Equal(got, want) {
160 t.Error("payload was truncated or modified")
161 }
162 })
163
164 t.Run("bufio reader is preserved", func(t *testing.T) {
165 header := []byte(intro + "-> test\n\n" + footer)
166 input := bufio.NewReader(bytes.NewReader(append(header, "payload"...)))
167 _, payload, err := format.Parse(input)
168 if err != nil {
169 t.Fatal(err)
170 }
171 if payload != input {
172 t.Error("Parse did not return the input bufio.Reader")
173 }
174 })
175 }
176
177 func FuzzMalleability(f *testing.F) {
178 tests, err := fs.ReadDir(agetest.Vectors, ".")
179 if err != nil {
180 f.Fatal(err)
181 }
182 for _, test := range tests {
183 contents, err := fs.ReadFile(agetest.Vectors, test.Name())
184 if err != nil {
185 f.Fatal(err)
186 }
187 _, contents, ok := bytes.Cut(contents, []byte("\n\n"))
188 if !ok {
189 f.Fatal("testkit file without header")
190 }
191 f.Add(contents)
192 }
193 if len(tests) == 0 {
194 f.Fatal("no test vectors")
195 }
196 f.Fuzz(func(t *testing.T, data []byte) {
197 h, payload, err := format.Parse(bytes.NewReader(data))
198 if err != nil {
199 if h != nil {
200 t.Error("h != nil on error")
201 }
202 if payload != nil {
203 t.Error("payload != nil on error")
204 }
205 t.Skip()
206 }
207 w := &bytes.Buffer{}
208 if err := h.Marshal(w); err != nil {
209 t.Fatal(err)
210 }
211 if _, err := io.Copy(w, payload); err != nil {
212 t.Fatal(err)
213 }
214 if !bytes.Equal(w.Bytes(), data) {
215 t.Error("Marshal output different from input")
216 }
217 })
218 }
219
220 const secret = "AGE-SECRET-KEY-1NOTAREALKEYNOTAREALKEYNOTAREALKEYNOTAREALKEYNOTAREALKEYNOTA"
221
222 const pluginSecret = "AGE-PLUGIN-PQ-1NOTAREALKEYNOTAREALKEYNOTAREALKEYNOTAREALKEYNOTAREALKEYNOTA"
223
224 func TestParseIntroErrorIsNotSecret(t *testing.T) {
225 for _, test := range []struct {
226 name string
227 input string
228 secret bool
229 }{
230 {"identity", secret + "\n", true},
231 {"identity, no newline", secret, true},
232 {"plugin identity", pluginSecret + "\n", true},
233 {"plugin identity, no newline", pluginSecret, true},
234 {"truncated intro", "age-encryption.org/v1", false},
235 {"binary", "\x00\x01\x02", false},
236 } {
237 t.Run(test.name, func(t *testing.T) {
238 _, _, err := format.Parse(strings.NewReader(test.input))
239 if err == nil {
240 t.Fatal("expected an error")
241 }
242 if strings.Contains(err.Error(), "file is empty") {
243 t.Errorf("error says the file is empty, but it is %d bytes: %v",
244 len(test.input), err)
245 }
246 // Check substrings, not just the key prefix.
247 if test.secret {
248 key := strings.TrimSuffix(test.input, "\n")
249 for i := 0; i+17 <= len(key); i++ {
250 if strings.Contains(err.Error(), key[i:i+17]) {
251 t.Errorf("error includes %q, a run of the first line, "+
252 "which is a private key: %v", key[i:i+17], err)
253 break
254 }
255 }
256 }
257 })
258 }
259
260 // Preserve the error for empty files (#416).
261 t.Run("empty", func(t *testing.T) {
262 _, _, err := format.Parse(strings.NewReader(""))
263 if err == nil {
264 t.Fatal("expected an error")
265 }
266 if !strings.Contains(err.Error(), "file is empty") {
267 t.Errorf("expected an empty file error, got: %v", err)
268 }
269 })
270 }
271
272 func TestParseIntroErrorShowsMangling(t *testing.T) {
273 for _, test := range []struct {
274 name string
275 input string
276 want string
277 }{
278 {"crlf", "age-encryption.org/v1\r\n", `\r`},
279 {"utf8 bom", "\xef\xbb\xbfage-encryption.org/v1\n", `\ufeff`},
280 {"utf16be", "\x00a\x00g\x00e\x00-\x00e\x00n\x00c\x00r\x00y\x00p\x00", `\x00a\x00g\x00e`},
281 {"trailing space", "age-encryption.org/v1 \n", `v1 `},
282 {"wrong version", "age-encryption.org/v2\n", "v2"},
283 {"leading blank line", "\nage-encryption.org/v1\n", `"\n"`},
284 } {
285 t.Run(test.name, func(t *testing.T) {
286 _, _, err := format.Parse(strings.NewReader(test.input))
287 if err == nil {
288 t.Fatal("expected an error")
289 }
290 if !strings.Contains(err.Error(), test.want) {
291 t.Errorf("error does not show the mangling: got %v, want it to contain %q",
292 err, test.want)
293 }
294 })
295 }
296 }