1// Copyright 2019 Google LLC
2//
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file or at
5// https://developers.google.com/open-source/licenses/bsd
6
7package main
8
9import (
10	"errors"
11	"io/ioutil"
12	"os"
13	"path/filepath"
14	"strings"
15	"testing"
16
17	"filippo.io/age"
18)
19
20func TestVectors(t *testing.T) {
21	var defaultIDs []age.Identity
22
23	password, err := ioutil.ReadFile("testdata/default_password.txt")
24	if err != nil {
25		t.Fatal(err)
26	}
27	p := strings.TrimSpace(string(password))
28	i, err := age.NewScryptIdentity(p)
29	if err != nil {
30		t.Fatal(err)
31	}
32	defaultIDs = append(defaultIDs, i)
33
34	ids, err := parseIdentitiesFile("testdata/default_key.txt")
35	if err != nil {
36		t.Fatal(err)
37	}
38	defaultIDs = append(defaultIDs, ids...)
39
40	files, _ := filepath.Glob("testdata/*.age")
41	for _, f := range files {
42		_, name := filepath.Split(f)
43		name = strings.TrimSuffix(name, ".age")
44		expectPass := strings.HasPrefix(name, "good_")
45		expectFailure := strings.HasPrefix(name, "fail_")
46		expectNoMatch := strings.HasPrefix(name, "nomatch_")
47		t.Run(name, func(t *testing.T) {
48			identities := defaultIDs
49			ids, err := parseIdentitiesFile("testdata/" + name + "_key.txt")
50			if err == nil {
51				identities = ids
52			}
53			password, err := ioutil.ReadFile("testdata/" + name + "_password.txt")
54			if err == nil {
55				p := strings.TrimSpace(string(password))
56				i, err := age.NewScryptIdentity(p)
57				if err != nil {
58					t.Fatal(err)
59				}
60				identities = []age.Identity{i}
61			}
62
63			in, err := os.Open("testdata/" + name + ".age")
64			if err != nil {
65				t.Fatal(err)
66			}
67			r, err := age.Decrypt(in, identities...)
68			if expectFailure {
69				if err == nil {
70					t.Fatal("expected Decrypt failure")
71				}
72				if e := new(age.NoIdentityMatchError); errors.As(err, &e) {
73					t.Errorf("got ErrIncorrectIdentity, expected more specific error")
74				}
75			} else if expectNoMatch {
76				if err == nil {
77					t.Fatal("expected Decrypt failure")
78				}
79				if e := new(age.NoIdentityMatchError); !errors.As(err, &e) {
80					t.Errorf("expected ErrIncorrectIdentity, got %v", err)
81				}
82			} else if expectPass {
83				if err != nil {
84					t.Fatal(err)
85				}
86				out, err := ioutil.ReadAll(r)
87				if err != nil {
88					t.Fatal(err)
89				}
90				t.Logf("%s", out)
91			} else {
92				t.Fatal("invalid test vector")
93			}
94		})
95	}
96}
97