File: tree_signer_test.cc

package info (click to toggle)
golang-github-google-certificate-transparency 0.0~git20160709.0.0f6e3d1~ds1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 5,676 kB
  • sloc: cpp: 35,278; python: 11,838; java: 1,911; sh: 1,885; makefile: 950; xml: 520; ansic: 225
file content (337 lines) | stat: -rw-r--r-- 11,101 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/* -*- indent-tabs-mode: nil -*- */
#include <gtest/gtest.h>
#include <stdint.h>
#include <memory>
#include <string>

#include "log/etcd_consistent_store.h"
#include "log/file_db.h"
#include "log/log_signer.h"
#include "log/log_verifier.h"
#include "log/sqlite_db.h"
#include "log/test_db.h"
#include "log/test_signer.h"
#include "log/tree_signer.h"
#include "merkletree/merkle_verifier.h"
#include "proto/cert_serializer.h"
#include "proto/ct.pb.h"
#include "util/fake_etcd.h"
#include "util/mock_masterelection.h"
#include "util/status_test_util.h"
#include "util/sync_task.h"
#include "util/testing.h"
#include "util/thread_pool.h"
#include "util/util.h"

namespace cert_trans {

using cert_trans::EntryHandle;
using cert_trans::LoggedEntry;
using cert_trans::MockMasterElection;
using ct::ClusterNodeState;
using ct::SequenceMapping;
using ct::SignedTreeHead;
using std::make_shared;
using std::move;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::unordered_map;
using std::vector;
using testing::NiceMock;
using util::Status;


// TODO(alcutter): figure out if/how we can keep abstract rather than
// hardcoding LoggedEntry in here.
template <class T>
class TreeSignerTest : public ::testing::Test {
 protected:
  TreeSignerTest()
      : test_db_(),
        base_(make_shared<libevent::Base>()),
        event_pump_(base_),
        etcd_client_(base_.get()),
        pool_(2),
        test_signer_(),
        verifier_(),
        tree_signer_() {
  }

  void SetUp() {
    test_db_.reset(new TestDB<T>);
    verifier_.reset(new LogVerifier(
        TestSigner::DefaultLogSigVerifier(),
        new MerkleVerifier(unique_ptr<Sha256Hasher>(new Sha256Hasher))));
    store_.reset(new EtcdConsistentStore(base_.get(), &pool_, &etcd_client_,
                                         &election_, "/root", "id"));
    log_signer_.reset(TestSigner::DefaultLogSigner());
    tree_signer_.reset(
        new TreeSigner(std::chrono::duration<double>(0), db(),
                       unique_ptr<CompactMerkleTree>(new CompactMerkleTree(
                           unique_ptr<Sha256Hasher>(new Sha256Hasher))),
                       store_.get(), log_signer_.get()));
    // Set a default empty STH so that we can call UpdateTree() on the signer.
    store_->SetServingSTH(SignedTreeHead());
    // Force an empty sequence mapping file:
    {
      util::SyncTask task(&pool_);
      EtcdClient::Response r;
      etcd_client_.ForceSet("/root/sequence_mapping", "", &r, task.task());
      task.Wait();
    }
  }

  void AddPendingEntry(LoggedEntry* logged_cert) const {
    logged_cert->clear_sequence_number();
    CHECK(this->store_->AddPendingEntry(logged_cert).ok());
  }

  void DeletePendingEntry(const LoggedEntry& logged_cert) const {
    EntryHandle<LoggedEntry> e;
    CHECK_EQ(Status::OK,
             this->store_->GetPendingEntryForHash(logged_cert.Hash(), &e));
    CHECK_EQ(Status::OK, this->store_->DeleteEntry(e));
  }

  void AddSequencedEntry(LoggedEntry* logged_cert, int64_t seq) const {
    logged_cert->clear_sequence_number();
    CHECK(this->store_->AddPendingEntry(logged_cert).ok());

    // This below would normally be done by TreeSigner::SequenceNewEntries()
    EntryHandle<LoggedEntry> entry;
    EntryHandle<SequenceMapping> mapping;
    CHECK(this->store_->GetSequenceMapping(&mapping).ok());
    SequenceMapping::Mapping* m(mapping.MutableEntry()->add_mapping());
    m->set_sequence_number(seq);
    m->set_entry_hash(logged_cert->Hash());
    CHECK(this->store_->UpdateSequenceMapping(&mapping).ok());
    logged_cert->set_sequence_number(seq);
    CHECK_EQ(Database::OK, this->db()->CreateSequencedEntry(*logged_cert));
  }


  TreeSigner* GetSimilar() {
    return new TreeSigner(std::chrono::duration<double>(0), db(),
                          unique_ptr<CompactMerkleTree>(new CompactMerkleTree(
                              *tree_signer_->cert_tree_,
                              unique_ptr<Sha256Hasher>(new Sha256Hasher))),
                          store_.get(), log_signer_.get());
  }

  T* db() const {
    return test_db_->db();
  }
  unique_ptr<TestDB<T>> test_db_;
  shared_ptr<libevent::Base> base_;
  libevent::EventPumpThread event_pump_;
  FakeEtcdClient etcd_client_;
  ThreadPool pool_;
  NiceMock<MockMasterElection> election_;
  std::unique_ptr<EtcdConsistentStore> store_;
  TestSigner test_signer_;
  unique_ptr<LogVerifier> verifier_;
  unique_ptr<LogSigner> log_signer_;
  unique_ptr<TreeSigner> tree_signer_;
};

typedef testing::Types<FileDB, SQLiteDB> Databases;


EntryHandle<LoggedEntry> H(const LoggedEntry& l) {
  EntryHandle<LoggedEntry> handle;
  handle.MutableEntry()->CopyFrom(l);
  return handle;
}


TYPED_TEST_CASE(TreeSignerTest, Databases);

TYPED_TEST(TreeSignerTest, PendingEntriesOrder) {
  PendingEntriesOrder ordering;
  LoggedEntry lowest;
  this->test_signer_.CreateUnique(&lowest);

  // Can't be lower than itself!
  EXPECT_FALSE(ordering(H(lowest), H(lowest)));

  // check timestamp:
  LoggedEntry higher_timestamp(lowest);
  higher_timestamp.mutable_sct()->set_timestamp(lowest.timestamp() + 1);
  EXPECT_TRUE(ordering(H(lowest), H(higher_timestamp)));
  EXPECT_FALSE(ordering(H(higher_timestamp), H(lowest)));

  // check hash fallback:
  LoggedEntry higher_hash(lowest);
  while (higher_hash.Hash() <= lowest.Hash()) {
    this->test_signer_.CreateUnique(&higher_hash);
    higher_hash.mutable_sct()->set_timestamp(lowest.timestamp());
  }
  EXPECT_TRUE(ordering(H(lowest), H(higher_hash)));
  EXPECT_FALSE(ordering(H(higher_hash), H(lowest)));
}


// TODO(ekasper): KAT tests.
TYPED_TEST(TreeSignerTest, Sign) {
  LoggedEntry logged_cert;
  this->test_signer_.CreateUnique(&logged_cert);
  this->AddPendingEntry(&logged_cert);
  // this->AddSequencedEntry(&logged_cert, 0);
  EXPECT_OK(this->tree_signer_->SequenceNewEntries());
  EXPECT_EQ(TreeSigner::OK, this->tree_signer_->UpdateTree());

  const SignedTreeHead sth(this->tree_signer_->LatestSTH());
  EXPECT_EQ(1U, sth.tree_size());
  EXPECT_EQ(sth.timestamp(), this->tree_signer_->LastUpdateTime());
}


TYPED_TEST(TreeSignerTest, Timestamp) {
  LoggedEntry logged_cert;
  this->test_signer_.CreateUnique(&logged_cert);
  this->AddSequencedEntry(&logged_cert, 0);

  EXPECT_EQ(TreeSigner::OK, this->tree_signer_->UpdateTree());
  uint64_t last_update = this->tree_signer_->LastUpdateTime();
  EXPECT_GE(last_update, logged_cert.sct().timestamp());

  // Now create a second entry with a timestamp some time in the future
  // and verify that the signer's timestamp is greater than that.
  uint64_t future = last_update + 10000;
  LoggedEntry logged_cert2;
  this->test_signer_.CreateUnique(&logged_cert2);
  logged_cert2.mutable_sct()->set_timestamp(future);
  this->AddSequencedEntry(&logged_cert2, 1);

  EXPECT_EQ(TreeSigner::OK, this->tree_signer_->UpdateTree());
  EXPECT_GE(this->tree_signer_->LastUpdateTime(), future);
}


TYPED_TEST(TreeSignerTest, Verify) {
  LoggedEntry logged_cert;
  this->test_signer_.CreateUnique(&logged_cert);
  this->AddSequencedEntry(&logged_cert, 0);

  EXPECT_EQ(TreeSigner::OK, this->tree_signer_->UpdateTree());

  const SignedTreeHead sth(this->tree_signer_->LatestSTH());
  EXPECT_EQ(LogVerifier::VERIFY_OK,
            this->verifier_->VerifySignedTreeHead(sth));
}


TYPED_TEST(TreeSignerTest, ResumeClean) {
  LoggedEntry logged_cert;
  this->test_signer_.CreateUnique(&logged_cert);
  this->AddSequencedEntry(&logged_cert, 0);

  EXPECT_EQ(TreeSigner::OK, this->tree_signer_->UpdateTree());
  const SignedTreeHead sth(this->tree_signer_->LatestSTH());
  {
    // Simulate the caller of UpdateTree() pushing this new tree out to the
    // cluster.
    ClusterNodeState node_state;
    *node_state.mutable_newest_sth() = sth;
    CHECK_EQ(util::Status::OK, this->store_->SetClusterNodeState(node_state));
  }

  unique_ptr<TreeSigner> signer2(this->GetSimilar());

  // Update
  EXPECT_EQ(TreeSigner::OK, signer2->UpdateTree());

  const SignedTreeHead sth2(signer2->LatestSTH());
  EXPECT_LT(sth.timestamp(), sth2.timestamp());
  EXPECT_EQ(sth.sha256_root_hash(), sth2.sha256_root_hash());
  EXPECT_EQ(sth.tree_size(), sth2.tree_size());
}


// Test resuming when the tree head signature is lagging behind the
// sequence number commits.
TYPED_TEST(TreeSignerTest, ResumePartialSign) {
  EXPECT_EQ(TreeSigner::OK, this->tree_signer_->UpdateTree());
  const SignedTreeHead sth(this->tree_signer_->LatestSTH());
  {
    // Simulate the caller of UpdateTree() pushing this new tree out to the
    // cluster.
    ClusterNodeState node_state;
    *node_state.mutable_newest_sth() = sth;
    CHECK_EQ(util::Status::OK, this->store_->SetClusterNodeState(node_state));
  }

  LoggedEntry logged_cert;
  this->test_signer_.CreateUnique(&logged_cert);
  this->AddSequencedEntry(&logged_cert, 0);

  unique_ptr<TreeSigner> signer2(this->GetSimilar());
  EXPECT_EQ(TreeSigner::OK, signer2->UpdateTree());
  const SignedTreeHead sth2(signer2->LatestSTH());
  // The signer should have picked up the sequence number commit.
  EXPECT_EQ(1U, sth2.tree_size());
  EXPECT_LT(sth.timestamp(), sth2.timestamp());
  EXPECT_NE(sth.sha256_root_hash(), sth2.sha256_root_hash());
}


TYPED_TEST(TreeSignerTest, SignEmpty) {
  EXPECT_EQ(TreeSigner::OK, this->tree_signer_->UpdateTree());

  const SignedTreeHead sth(this->tree_signer_->LatestSTH());
  EXPECT_GT(sth.timestamp(), 0U);
  EXPECT_EQ(sth.tree_size(), 0U);
}


TYPED_TEST(TreeSignerTest, SequenceNewEntriesCleansUpOldSequenceMappings) {
  LoggedEntry logged_cert;
  this->test_signer_.CreateUnique(&logged_cert);
  this->AddPendingEntry(&logged_cert);
  EXPECT_OK(this->tree_signer_->SequenceNewEntries());
  EXPECT_EQ(TreeSigner::OK, this->tree_signer_->UpdateTree());
  EXPECT_EQ(Status::OK,
            this->store_->SetServingSTH(this->tree_signer_->LatestSTH()));
  sleep(1);

  {
    EntryHandle<SequenceMapping> mapping;
    CHECK_EQ(Status::OK, this->store_->GetSequenceMapping(&mapping));
    EXPECT_EQ(1, mapping.Entry().mapping_size());
    EXPECT_EQ(logged_cert.Hash(), mapping.Entry().mapping(0).entry_hash());
  }

  unordered_map<string, LoggedEntry> new_logged_certs;
  for (int i(0); i < 2; ++i) {
    LoggedEntry c;
    this->test_signer_.CreateUnique(&c);
    this->AddPendingEntry(&c);
    new_logged_certs.insert(make_pair(c.Hash(), c));
  }
  this->DeletePendingEntry(logged_cert);
  LOG(INFO) << "2";
  EXPECT_OK(this->tree_signer_->SequenceNewEntries());

  {
    EntryHandle<SequenceMapping> mapping;
    CHECK_EQ(Status::OK, this->store_->GetSequenceMapping(&mapping));
    CHECK_GE(mapping.Entry().mapping_size(), 0);
    EXPECT_EQ(new_logged_certs.size(),
              static_cast<size_t>(mapping.Entry().mapping_size()));
    for (int i(0); i < mapping.Entry().mapping_size(); ++i) {
      const auto& m(mapping.Entry().mapping(i));
      EXPECT_NE(new_logged_certs.end(), new_logged_certs.find(m.entry_hash()));
    }
  }
}


}  // namespace cert_trans


int main(int argc, char** argv) {
  cert_trans::test::InitTesting(argv[0], &argc, &argv, true);
  ConfigureSerializerForV1CT();
  return RUN_ALL_TESTS();
}