1 // Copyright 2015 The BoringSSL Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef OPENSSL_HEADER_CRYPTO_TEST_FILE_TEST_H
16 #define OPENSSL_HEADER_CRYPTO_TEST_FILE_TEST_H
17 
18 #include <openssl/base.h>
19 
20 #include <stdint.h>
21 
22 #include <functional>
23 #include <map>
24 #include <memory>
25 #include <set>
26 #include <string>
27 #include <vector>
28 
29 // File-based test framework.
30 //
31 // This module provides a file-based test framework. The file format is based on
32 // that of OpenSSL upstream's evp_test and BoringSSL's aead_test. NIST CAVP test
33 // vector files are also supported. Each input file is a sequence of attributes,
34 // instructions and blank lines.
35 //
36 // Each attribute has the form:
37 //
38 //   Name = Value
39 //
40 // Instructions are enclosed in square brackets and may appear without a value:
41 //
42 //   [Name = Value]
43 //
44 // or
45 //
46 //   [Name]
47 //
48 // Commas in instruction lines are treated as separate instructions. Thus this:
49 //
50 //   [Name1,Name2]
51 //
52 // is the same as:
53 //
54 //   [Name1]
55 //   [Name2]
56 //
57 // Either '=' or ':' may be used to delimit the name from the value. Both the
58 // name and value have leading and trailing spaces stripped.
59 //
60 // Each file contains a number of instruction blocks and test cases.
61 //
62 // An instruction block is a sequence of instructions followed by a blank line.
63 // Instructions apply to all test cases following its appearance, until the next
64 // instruction block. Instructions are unordered.
65 //
66 // A test is a sequence of one or more attributes followed by a blank line.  For
67 // tests that process multiple kinds of test cases, the first attribute is
68 // parsed out as the test's type and parameter. Otherwise, attributes are
69 // unordered. The first attribute is also included in the set of attributes, so
70 // tests which do not dispatch may ignore this mechanism.
71 //
72 // Additional blank lines and lines beginning with # are ignored.
73 //
74 // Functions in this module freely output to |stderr| on failure. Tests should
75 // also do so, and it is recommended they include the corresponding test's line
76 // number in any output. |PrintLine| does this automatically.
77 //
78 // Each attribute in a test and all instructions applying to it must be
79 // consumed. When a test completes, if any attributes or insturctions haven't
80 // been processed, the framework reports an error.
81 
82 class FileTest;
83 typedef bool (*FileTestFunc)(FileTest *t, void *arg);
84 
85 class FileTest {
86  public:
87   enum ReadResult {
88     kReadSuccess,
89     kReadEOF,
90     kReadError,
91   };
92 
93   class LineReader {
94    public:
~LineReader()95     virtual ~LineReader() {}
96     virtual ReadResult ReadLine(char *out, size_t len) = 0;
97   };
98 
99   struct Options {
100     // path is the path to the input file.
101     const char *path = nullptr;
102     // callback is called for each test. It should get the parameters from this
103     // object and signal any errors by returning false.
104     FileTestFunc callback = nullptr;
105     // arg is an opaque pointer that is passed to |callback|.
106     void *arg = nullptr;
107     // silent suppressed the "PASS" string that is otherwise printed after
108     // successful runs.
109     bool silent = false;
110     // comment_callback is called after each comment in the input is parsed.
111     std::function<void(const std::string&)> comment_callback;
112     // is_kas_test is true if a NIST “KAS” test is being parsed. These tests
113     // are inconsistent with the other NIST files to such a degree that they
114     // need their own boolean.
115     bool is_kas_test = false;
116   };
117 
118   explicit FileTest(std::unique_ptr<LineReader> reader,
119                     std::function<void(const std::string &)> comment_callback,
120                     bool is_kas_test);
121   ~FileTest();
122 
123   // ReadNext reads the next test from the file. It returns |kReadSuccess| if
124   // successfully reading a test and |kReadEOF| at the end of the file. On
125   // error or if the previous test had unconsumed attributes, it returns
126   // |kReadError|.
127   ReadResult ReadNext();
128 
129   // PrintLine is a variant of printf which prepends the line number and appends
130   // a trailing newline.
131   void PrintLine(const char *format, ...) OPENSSL_PRINTF_FORMAT_FUNC(2, 3);
132 
start_line()133   unsigned start_line() const { return start_line_; }
134 
135   // GetType returns the name of the first attribute of the current test.
136   const std::string &GetType();
137   // GetParameter returns the value of the first attribute of the current test.
138   const std::string &GetParameter();
139 
140   // HasAttribute returns true if the current test has an attribute named |key|.
141   bool HasAttribute(const std::string &key);
142 
143   // GetAttribute looks up the attribute with key |key|. It sets |*out_value| to
144   // the value and returns true if it exists and returns false with an error to
145   // |stderr| otherwise.
146   bool GetAttribute(std::string *out_value, const std::string &key);
147 
148   // GetAttributeOrDie looks up the attribute with key |key| and aborts if it is
149   // missing. It should only be used after a |HasAttribute| call.
150   const std::string &GetAttributeOrDie(const std::string &key);
151 
152   // IgnoreAttribute marks the attribute with key |key| as used.
IgnoreAttribute(const std::string & key)153   void IgnoreAttribute(const std::string &key) { HasAttribute(key); }
154 
155   // GetBytes looks up the attribute with key |key| and decodes it as a byte
156   // string. On success, it writes the result to |*out| and returns
157   // true. Otherwise it returns false with an error to |stderr|. The value may
158   // be either a hexadecimal string or a quoted ASCII string. It returns true on
159   // success and returns false with an error to |stderr| on failure.
160   bool GetBytes(std::vector<uint8_t> *out, const std::string &key);
161 
162   // AtNewInstructionBlock returns true if the current test was immediately
163   // preceded by an instruction block.
164   bool IsAtNewInstructionBlock() const;
165 
166   // HasInstruction returns true if the current test has an instruction.
167   bool HasInstruction(const std::string &key);
168 
169   // IgnoreInstruction marks the instruction with key |key| as used.
IgnoreInstruction(const std::string & key)170   void IgnoreInstruction(const std::string &key) { HasInstruction(key); }
171 
172   // IgnoreAllUnusedInstructions disables checking for unused instructions.
173   void IgnoreAllUnusedInstructions();
174 
175   // GetInstruction looks up the instruction with key |key|. It sets
176   // |*out_value| to the value (empty string if the instruction has no value)
177   // and returns true if it exists and returns false with an error to |stderr|
178   // otherwise.
179   bool GetInstruction(std::string *out_value, const std::string &key);
180 
181   // GetInstructionOrDie looks up the instruction with key |key| and aborts if
182   // it is missing. It should only be used after a |HasInstruction| call.
183   const std::string &GetInstructionOrDie(const std::string &key);
184 
185   // GetInstructionBytes behaves like GetBytes, but looks up the corresponding
186   // instruction.
187   bool GetInstructionBytes(std::vector<uint8_t> *out, const std::string &key);
188 
189   // CurrentTestToString returns the file content parsed for the current test.
190   // If the current test was preceded by an instruction block, the return test
191   // case is preceded by the instruction block and a single blank line. All
192   // other blank or comment lines are omitted.
193   const std::string &CurrentTestToString() const;
194 
195   // InjectInstruction adds a key value pair to the most recently parsed set of
196   // instructions.
197   void InjectInstruction(const std::string &key, const std::string &value);
198 
199   // SkipCurrent passes the current test case. Unused attributes are ignored.
200   void SkipCurrent();
201 
202  private:
203   void ClearTest();
204   void ClearInstructions();
205   void OnKeyUsed(const std::string &key);
206   void OnInstructionUsed(const std::string &key);
207   bool ConvertToBytes(std::vector<uint8_t> *out, const std::string &value);
208 
209   std::unique_ptr<LineReader> reader_;
210   // line_ is the number of lines read.
211   unsigned line_ = 0;
212 
213   // start_line_ is the line number of the first attribute of the test.
214   unsigned start_line_ = 0;
215   // type_ is the name of the first attribute of the test.
216   std::string type_;
217   // parameter_ is the value of the first attribute.
218   std::string parameter_;
219   // attribute_count_ maps unsuffixed attribute names to the number of times
220   // they have occurred so far.
221   std::map<std::string, size_t> attribute_count_;
222   // attributes_ contains all attributes in the test, including the first.
223   std::map<std::string, std::string> attributes_;
224   // instructions_ contains all instructions in scope for the test.
225   std::map<std::string, std::string> instructions_;
226 
227   // unused_attributes_ is the set of attributes that have not been queried.
228   std::set<std::string> unused_attributes_;
229 
230   // unused_instructions_ is the set of instructions that have not been queried.
231   std::set<std::string> unused_instructions_;
232 
233   std::string current_test_;
234 
235   bool is_at_new_instruction_block_ = false;
236   bool seen_non_comment_ = false;
237   bool is_kas_test_ = false;
238 
239   // comment_callback_, if set, is a callback function that is called with the
240   // contents of each comment as they are parsed.
241   std::function<void(const std::string&)> comment_callback_;
242 
243   FileTest(const FileTest &) = delete;
244   FileTest &operator=(const FileTest &) = delete;
245 };
246 
247 // FileTestMain runs a file-based test out of |path| and returns an exit code
248 // suitable to return out of |main|. |run_test| should return true on pass and
249 // false on failure. FileTestMain also implements common handling of the 'Error'
250 // attribute. A test with that attribute is expected to fail. The value of the
251 // attribute is the reason string of the expected OpenSSL error code.
252 //
253 // Tests are guaranteed to run serially and may affect global state if need be.
254 // It is legal to use "tests" which, for example, import a private key into a
255 // list of keys. This may be used to initialize a shared set of keys for many
256 // tests. However, if one test fails, the framework will continue to run
257 // subsequent tests.
258 int FileTestMain(FileTestFunc run_test, void *arg, const char *path);
259 
260 // FileTestMain accepts a larger number of options via a struct.
261 int FileTestMain(const FileTest::Options &opts);
262 
263 // FileTestGTest behaves like FileTestMain, but for GTest. |path| must be the
264 // name of a test file embedded in the test binary.
265 void FileTestGTest(const char *path, std::function<void(FileTest *)> run_test);
266 
267 #endif  // OPENSSL_HEADER_CRYPTO_TEST_FILE_TEST_H
268