aes_decryptor_unittest.cc revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <string>
6#include <vector>
7
8#include "base/basictypes.h"
9#include "base/bind.h"
10#include "media/base/decoder_buffer.h"
11#include "media/base/decrypt_config.h"
12#include "media/base/mock_filters.h"
13#include "media/cdm/aes_decryptor.h"
14#include "testing/gmock/include/gmock/gmock.h"
15#include "testing/gtest/include/gtest/gtest.h"
16
17using ::testing::_;
18using ::testing::Gt;
19using ::testing::IsNull;
20using ::testing::NotNull;
21using ::testing::SaveArg;
22using ::testing::StrNe;
23
24MATCHER(IsEmpty, "") { return arg.empty(); }
25
26namespace media {
27
28const uint8 kOriginalData[] = "Original subsample data.";
29const int kOriginalDataSize = 24;
30
31// In the examples below, 'k'(key) has to be 16 bytes, and will always require
32// 2 bytes of padding. 'kid'(keyid) is variable length, and may require 0, 1,
33// or 2 bytes of padding.
34
35const uint8 kKeyId[] = {
36    // base64 equivalent is AAECAw
37    0x00, 0x01, 0x02, 0x03
38};
39
40// Key is 0x0405060708090a0b0c0d0e0f10111213,
41// base64 equivalent is BAUGBwgJCgsMDQ4PEBESEw.
42const char kKeyAsJWK[] =
43    "{"
44    "  \"keys\": ["
45    "    {"
46    "      \"kty\": \"oct\","
47    "      \"kid\": \"AAECAw\","
48    "      \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
49    "    }"
50    "  ]"
51    "}";
52
53// Same kid as kKeyAsJWK, key to decrypt kEncryptedData2
54const char kKeyAlternateAsJWK[] =
55    "{"
56    "  \"keys\": ["
57    "    {"
58    "      \"kty\": \"oct\","
59    "      \"kid\": \"AAECAw\","
60    "      \"k\": \"FBUWFxgZGhscHR4fICEiIw\""
61    "    }"
62    "  ]"
63    "}";
64
65const char kWrongKeyAsJWK[] =
66    "{"
67    "  \"keys\": ["
68    "    {"
69    "      \"kty\": \"oct\","
70    "      \"kid\": \"AAECAw\","
71    "      \"k\": \"7u7u7u7u7u7u7u7u7u7u7g\""
72    "    }"
73    "  ]"
74    "}";
75
76const char kWrongSizedKeyAsJWK[] =
77    "{"
78    "  \"keys\": ["
79    "    {"
80    "      \"kty\": \"oct\","
81    "      \"kid\": \"AAECAw\","
82    "      \"k\": \"AAECAw\""
83    "    }"
84    "  ]"
85    "}";
86
87const uint8 kIv[] = {
88  0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
89  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
90};
91
92// kOriginalData encrypted with kKey and kIv but without any subsamples (or
93// equivalently using kSubsampleEntriesCypherOnly).
94const uint8 kEncryptedData[] = {
95  0x2f, 0x03, 0x09, 0xef, 0x71, 0xaf, 0x31, 0x16,
96  0xfa, 0x9d, 0x18, 0x43, 0x1e, 0x96, 0x71, 0xb5,
97  0xbf, 0xf5, 0x30, 0x53, 0x9a, 0x20, 0xdf, 0x95
98};
99
100// kOriginalData encrypted with kSubsampleKey and kSubsampleIv using
101// kSubsampleEntriesNormal.
102const uint8 kSubsampleEncryptedData[] = {
103  0x4f, 0x72, 0x09, 0x16, 0x09, 0xe6, 0x79, 0xad,
104  0x70, 0x73, 0x75, 0x62, 0x09, 0xbb, 0x83, 0x1d,
105  0x4d, 0x08, 0xd7, 0x78, 0xa4, 0xa7, 0xf1, 0x2e
106};
107
108const uint8 kOriginalData2[] = "Changed Original data.";
109
110const uint8 kIv2[] = {
111  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
112  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
113};
114
115const uint8 kKeyId2[] = {
116    // base64 equivalent is AAECAwQFBgcICQoLDA0ODxAREhM=
117    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
118    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
119    0x10, 0x11, 0x12, 0x13
120};
121
122const char kKey2AsJWK[] =
123    "{"
124    "  \"keys\": ["
125    "    {"
126    "      \"kty\": \"oct\","
127    "      \"kid\": \"AAECAwQFBgcICQoLDA0ODxAREhM\","
128    "      \"k\": \"FBUWFxgZGhscHR4fICEiIw\""
129    "    }"
130    "  ]"
131    "}";
132
133// 'k' in bytes is x14x15x16x17x18x19x1ax1bx1cx1dx1ex1fx20x21x22x23
134
135const uint8 kEncryptedData2[] = {
136  0x57, 0x66, 0xf4, 0x12, 0x1a, 0xed, 0xb5, 0x79,
137  0x1c, 0x8e, 0x25, 0xd7, 0x17, 0xe7, 0x5e, 0x16,
138  0xe3, 0x40, 0x08, 0x27, 0x11, 0xe9
139};
140
141// Subsample entries for testing. The sum of |cypher_bytes| and |clear_bytes| of
142// all entries must be equal to kOriginalDataSize to make the subsample entries
143// valid.
144
145const SubsampleEntry kSubsampleEntriesNormal[] = {
146  { 2, 7 },
147  { 3, 11 },
148  { 1, 0 }
149};
150
151const SubsampleEntry kSubsampleEntriesWrongSize[] = {
152  { 3, 6 }, // This entry doesn't match the correct entry.
153  { 3, 11 },
154  { 1, 0 }
155};
156
157const SubsampleEntry kSubsampleEntriesInvalidTotalSize[] = {
158  { 1, 1000 }, // This entry is too large.
159  { 3, 11 },
160  { 1, 0 }
161};
162
163const SubsampleEntry kSubsampleEntriesClearOnly[] = {
164  { 7, 0 },
165  { 8, 0 },
166  { 9, 0 }
167};
168
169const SubsampleEntry kSubsampleEntriesCypherOnly[] = {
170  { 0, 6 },
171  { 0, 8 },
172  { 0, 10 }
173};
174
175static scoped_refptr<DecoderBuffer> CreateEncryptedBuffer(
176    const std::vector<uint8>& data,
177    const std::vector<uint8>& key_id,
178    const std::vector<uint8>& iv,
179    const std::vector<SubsampleEntry>& subsample_entries) {
180  DCHECK(!data.empty());
181  scoped_refptr<DecoderBuffer> encrypted_buffer(new DecoderBuffer(data.size()));
182  memcpy(encrypted_buffer->writable_data(), &data[0], data.size());
183  CHECK(encrypted_buffer.get());
184  std::string key_id_string(
185      reinterpret_cast<const char*>(key_id.empty() ? NULL : &key_id[0]),
186      key_id.size());
187  std::string iv_string(
188      reinterpret_cast<const char*>(iv.empty() ? NULL : &iv[0]), iv.size());
189  encrypted_buffer->set_decrypt_config(scoped_ptr<DecryptConfig>(
190      new DecryptConfig(key_id_string, iv_string, subsample_entries)));
191  return encrypted_buffer;
192}
193
194class AesDecryptorTest : public testing::Test {
195 public:
196  AesDecryptorTest()
197      : decryptor_(base::Bind(&AesDecryptorTest::OnSessionCreated,
198                              base::Unretained(this)),
199                   base::Bind(&AesDecryptorTest::OnSessionMessage,
200                              base::Unretained(this)),
201                   base::Bind(&AesDecryptorTest::OnSessionReady,
202                              base::Unretained(this)),
203                   base::Bind(&AesDecryptorTest::OnSessionClosed,
204                              base::Unretained(this)),
205                   base::Bind(&AesDecryptorTest::OnSessionError,
206                              base::Unretained(this))),
207        decrypt_cb_(base::Bind(&AesDecryptorTest::BufferDecrypted,
208                               base::Unretained(this))),
209        original_data_(kOriginalData, kOriginalData + kOriginalDataSize),
210        encrypted_data_(kEncryptedData,
211                        kEncryptedData + arraysize(kEncryptedData)),
212        subsample_encrypted_data_(
213            kSubsampleEncryptedData,
214            kSubsampleEncryptedData + arraysize(kSubsampleEncryptedData)),
215        key_id_(kKeyId, kKeyId + arraysize(kKeyId)),
216        iv_(kIv, kIv + arraysize(kIv)),
217        normal_subsample_entries_(
218            kSubsampleEntriesNormal,
219            kSubsampleEntriesNormal + arraysize(kSubsampleEntriesNormal)),
220        next_session_id_(1) {
221  }
222
223 protected:
224  // Creates a new session using |key_id|. Returns the session ID.
225  uint32 CreateSession(const std::vector<uint8>& key_id) {
226    DCHECK(!key_id.empty());
227    uint32 session_id = next_session_id_++;
228    EXPECT_CALL(*this, OnSessionCreated(session_id, StrNe(std::string())));
229    EXPECT_CALL(*this, OnSessionMessage(session_id, key_id, ""));
230    EXPECT_TRUE(decryptor_.CreateSession(
231        session_id, std::string(), &key_id[0], key_id.size()));
232    return session_id;
233  }
234
235  // Releases the session specified by |session_id|.
236  void ReleaseSession(uint32 session_id) {
237    EXPECT_CALL(*this, OnSessionClosed(session_id));
238    decryptor_.ReleaseSession(session_id);
239  }
240
241  enum UpdateSessionExpectation {
242    SESSION_READY,
243    SESSION_ERROR
244  };
245
246  // Updates the session specified by |session_id| with |key|. |result|
247  // tests that the update succeeds or generates an error.
248  void UpdateSessionAndExpect(uint32 session_id,
249                              const std::string& key,
250                              UpdateSessionExpectation result) {
251    DCHECK(!key.empty());
252
253    switch (result) {
254      case SESSION_READY:
255        EXPECT_CALL(*this, OnSessionReady(session_id));
256        break;
257      case SESSION_ERROR:
258        EXPECT_CALL(*this,
259                    OnSessionError(session_id, MediaKeys::kUnknownError, 0));
260        break;
261    }
262
263    decryptor_.UpdateSession(
264        session_id, reinterpret_cast<const uint8*>(key.c_str()), key.length());
265  }
266
267  MOCK_METHOD2(BufferDecrypted, void(Decryptor::Status,
268                                     const scoped_refptr<DecoderBuffer>&));
269
270  enum DecryptExpectation {
271    SUCCESS,
272    DATA_MISMATCH,
273    DATA_AND_SIZE_MISMATCH,
274    DECRYPT_ERROR,
275    NO_KEY
276  };
277
278  void DecryptAndExpect(const scoped_refptr<DecoderBuffer>& encrypted,
279                        const std::vector<uint8>& plain_text,
280                        DecryptExpectation result) {
281    scoped_refptr<DecoderBuffer> decrypted;
282
283    switch (result) {
284      case SUCCESS:
285      case DATA_MISMATCH:
286      case DATA_AND_SIZE_MISMATCH:
287        EXPECT_CALL(*this, BufferDecrypted(Decryptor::kSuccess, NotNull()))
288            .WillOnce(SaveArg<1>(&decrypted));
289        break;
290      case DECRYPT_ERROR:
291        EXPECT_CALL(*this, BufferDecrypted(Decryptor::kError, IsNull()))
292            .WillOnce(SaveArg<1>(&decrypted));
293        break;
294      case NO_KEY:
295        EXPECT_CALL(*this, BufferDecrypted(Decryptor::kNoKey, IsNull()))
296            .WillOnce(SaveArg<1>(&decrypted));
297        break;
298    }
299
300    decryptor_.Decrypt(Decryptor::kVideo, encrypted, decrypt_cb_);
301
302    std::vector<uint8> decrypted_text;
303    if (decrypted && decrypted->data_size()) {
304      decrypted_text.assign(
305        decrypted->data(), decrypted->data() + decrypted->data_size());
306    }
307
308    switch (result) {
309      case SUCCESS:
310        EXPECT_EQ(plain_text, decrypted_text);
311        break;
312      case DATA_MISMATCH:
313        EXPECT_EQ(plain_text.size(), decrypted_text.size());
314        EXPECT_NE(plain_text, decrypted_text);
315        break;
316      case DATA_AND_SIZE_MISMATCH:
317        EXPECT_NE(plain_text.size(), decrypted_text.size());
318        break;
319      case DECRYPT_ERROR:
320      case NO_KEY:
321        EXPECT_TRUE(decrypted_text.empty());
322        break;
323    }
324  }
325
326  MOCK_METHOD2(OnSessionCreated,
327               void(uint32 session_id, const std::string& web_session_id));
328  MOCK_METHOD3(OnSessionMessage,
329               void(uint32 session_id,
330                    const std::vector<uint8>& message,
331                    const std::string& default_url));
332  MOCK_METHOD1(OnSessionReady, void(uint32 session_id));
333  MOCK_METHOD1(OnSessionClosed, void(uint32 session_id));
334  MOCK_METHOD3(OnSessionError,
335               void(uint32 session_id, MediaKeys::KeyError, int system_code));
336
337  AesDecryptor decryptor_;
338  AesDecryptor::DecryptCB decrypt_cb_;
339
340  // Constants for testing.
341  const std::vector<uint8> original_data_;
342  const std::vector<uint8> encrypted_data_;
343  const std::vector<uint8> subsample_encrypted_data_;
344  const std::vector<uint8> key_id_;
345  const std::vector<uint8> iv_;
346  const std::vector<SubsampleEntry> normal_subsample_entries_;
347  const std::vector<SubsampleEntry> no_subsample_entries_;
348
349  // Generate new session ID every time
350  uint32 next_session_id_;
351};
352
353TEST_F(AesDecryptorTest, CreateSessionWithNullInitData) {
354  uint32 session_id = 8;
355  EXPECT_CALL(*this, OnSessionMessage(session_id, IsEmpty(), ""));
356  EXPECT_CALL(*this, OnSessionCreated(session_id, StrNe(std::string())));
357  EXPECT_TRUE(decryptor_.CreateSession(session_id, std::string(), NULL, 0));
358}
359
360TEST_F(AesDecryptorTest, MultipleCreateSession) {
361  uint32 session_id1 = 10;
362  EXPECT_CALL(*this, OnSessionMessage(session_id1, IsEmpty(), ""));
363  EXPECT_CALL(*this, OnSessionCreated(session_id1, StrNe(std::string())));
364  EXPECT_TRUE(decryptor_.CreateSession(session_id1, std::string(), NULL, 0));
365
366  uint32 session_id2 = 11;
367  EXPECT_CALL(*this, OnSessionMessage(session_id2, IsEmpty(), ""));
368  EXPECT_CALL(*this, OnSessionCreated(session_id2, StrNe(std::string())));
369  EXPECT_TRUE(decryptor_.CreateSession(session_id2, std::string(), NULL, 0));
370
371  uint32 session_id3 = 23;
372  EXPECT_CALL(*this, OnSessionMessage(session_id3, IsEmpty(), ""));
373  EXPECT_CALL(*this, OnSessionCreated(session_id3, StrNe(std::string())));
374  EXPECT_TRUE(decryptor_.CreateSession(session_id3, std::string(), NULL, 0));
375}
376
377TEST_F(AesDecryptorTest, NormalDecryption) {
378  uint32 session_id = CreateSession(key_id_);
379  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
380  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
381      encrypted_data_, key_id_, iv_, no_subsample_entries_);
382  DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
383}
384
385TEST_F(AesDecryptorTest, UnencryptedFrame) {
386  // An empty iv string signals that the frame is unencrypted.
387  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
388      original_data_, key_id_, std::vector<uint8>(), no_subsample_entries_);
389  DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
390}
391
392TEST_F(AesDecryptorTest, WrongKey) {
393  uint32 session_id = CreateSession(key_id_);
394  UpdateSessionAndExpect(session_id, kWrongKeyAsJWK, SESSION_READY);
395  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
396      encrypted_data_, key_id_, iv_, no_subsample_entries_);
397  DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
398}
399
400TEST_F(AesDecryptorTest, NoKey) {
401  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
402      encrypted_data_, key_id_, iv_, no_subsample_entries_);
403  EXPECT_CALL(*this, BufferDecrypted(AesDecryptor::kNoKey, IsNull()));
404  decryptor_.Decrypt(Decryptor::kVideo, encrypted_buffer, decrypt_cb_);
405}
406
407TEST_F(AesDecryptorTest, KeyReplacement) {
408  uint32 session_id = CreateSession(key_id_);
409  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
410      encrypted_data_, key_id_, iv_, no_subsample_entries_);
411
412  UpdateSessionAndExpect(session_id, kWrongKeyAsJWK, SESSION_READY);
413  ASSERT_NO_FATAL_FAILURE(DecryptAndExpect(
414      encrypted_buffer, original_data_, DATA_MISMATCH));
415
416  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
417  ASSERT_NO_FATAL_FAILURE(
418      DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
419}
420
421TEST_F(AesDecryptorTest, WrongSizedKey) {
422  uint32 session_id = CreateSession(key_id_);
423  UpdateSessionAndExpect(session_id, kWrongSizedKeyAsJWK, SESSION_ERROR);
424}
425
426TEST_F(AesDecryptorTest, MultipleKeysAndFrames) {
427  uint32 session_id = CreateSession(key_id_);
428  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
429  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
430      encrypted_data_, key_id_, iv_, no_subsample_entries_);
431  ASSERT_NO_FATAL_FAILURE(
432      DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
433
434  UpdateSessionAndExpect(session_id, kKey2AsJWK, SESSION_READY);
435
436  // The first key is still available after we added a second key.
437  ASSERT_NO_FATAL_FAILURE(
438      DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
439
440  // The second key is also available.
441  encrypted_buffer = CreateEncryptedBuffer(
442      std::vector<uint8>(kEncryptedData2,
443                         kEncryptedData2 + arraysize(kEncryptedData2)),
444      std::vector<uint8>(kKeyId2, kKeyId2 + arraysize(kKeyId2)),
445      std::vector<uint8>(kIv2, kIv2 + arraysize(kIv2)),
446      no_subsample_entries_);
447  ASSERT_NO_FATAL_FAILURE(DecryptAndExpect(
448      encrypted_buffer,
449      std::vector<uint8>(kOriginalData2,
450                         kOriginalData2 + arraysize(kOriginalData2) - 1),
451      SUCCESS));
452}
453
454TEST_F(AesDecryptorTest, CorruptedIv) {
455  uint32 session_id = CreateSession(key_id_);
456  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
457
458  std::vector<uint8> bad_iv = iv_;
459  bad_iv[1]++;
460
461  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
462      encrypted_data_, key_id_, bad_iv, no_subsample_entries_);
463
464  DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
465}
466
467TEST_F(AesDecryptorTest, CorruptedData) {
468  uint32 session_id = CreateSession(key_id_);
469  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
470
471  std::vector<uint8> bad_data = encrypted_data_;
472  bad_data[1]++;
473
474  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
475      bad_data, key_id_, iv_, no_subsample_entries_);
476  DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
477}
478
479TEST_F(AesDecryptorTest, EncryptedAsUnencryptedFailure) {
480  uint32 session_id = CreateSession(key_id_);
481  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
482  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
483      encrypted_data_, key_id_, std::vector<uint8>(), no_subsample_entries_);
484  DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
485}
486
487TEST_F(AesDecryptorTest, SubsampleDecryption) {
488  uint32 session_id = CreateSession(key_id_);
489  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
490  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
491      subsample_encrypted_data_, key_id_, iv_, normal_subsample_entries_);
492  DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
493}
494
495// Ensures noninterference of data offset and subsample mechanisms. We never
496// expect to encounter this in the wild, but since the DecryptConfig doesn't
497// disallow such a configuration, it should be covered.
498TEST_F(AesDecryptorTest, SubsampleDecryptionWithOffset) {
499  uint32 session_id = CreateSession(key_id_);
500  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
501  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
502      subsample_encrypted_data_, key_id_, iv_, normal_subsample_entries_);
503  DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
504}
505
506TEST_F(AesDecryptorTest, SubsampleWrongSize) {
507  uint32 session_id = CreateSession(key_id_);
508  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
509
510  std::vector<SubsampleEntry> subsample_entries_wrong_size(
511      kSubsampleEntriesWrongSize,
512      kSubsampleEntriesWrongSize + arraysize(kSubsampleEntriesWrongSize));
513
514  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
515      subsample_encrypted_data_, key_id_, iv_, subsample_entries_wrong_size);
516  DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
517}
518
519TEST_F(AesDecryptorTest, SubsampleInvalidTotalSize) {
520  uint32 session_id = CreateSession(key_id_);
521  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
522
523  std::vector<SubsampleEntry> subsample_entries_invalid_total_size(
524      kSubsampleEntriesInvalidTotalSize,
525      kSubsampleEntriesInvalidTotalSize +
526          arraysize(kSubsampleEntriesInvalidTotalSize));
527
528  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
529      subsample_encrypted_data_, key_id_, iv_,
530      subsample_entries_invalid_total_size);
531  DecryptAndExpect(encrypted_buffer, original_data_, DECRYPT_ERROR);
532}
533
534// No cypher bytes in any of the subsamples.
535TEST_F(AesDecryptorTest, SubsampleClearBytesOnly) {
536  uint32 session_id = CreateSession(key_id_);
537  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
538
539  std::vector<SubsampleEntry> clear_only_subsample_entries(
540      kSubsampleEntriesClearOnly,
541      kSubsampleEntriesClearOnly + arraysize(kSubsampleEntriesClearOnly));
542
543  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
544      original_data_, key_id_, iv_, clear_only_subsample_entries);
545  DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
546}
547
548// No clear bytes in any of the subsamples.
549TEST_F(AesDecryptorTest, SubsampleCypherBytesOnly) {
550  uint32 session_id = CreateSession(key_id_);
551  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
552
553  std::vector<SubsampleEntry> cypher_only_subsample_entries(
554      kSubsampleEntriesCypherOnly,
555      kSubsampleEntriesCypherOnly + arraysize(kSubsampleEntriesCypherOnly));
556
557  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
558      encrypted_data_, key_id_, iv_, cypher_only_subsample_entries);
559  DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
560}
561
562TEST_F(AesDecryptorTest, ReleaseSession) {
563  uint32 session_id = CreateSession(key_id_);
564  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
565      encrypted_data_, key_id_, iv_, no_subsample_entries_);
566
567  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
568  ASSERT_NO_FATAL_FAILURE(
569      DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
570
571  ReleaseSession(session_id);
572}
573
574TEST_F(AesDecryptorTest, NoKeyAfterReleaseSession) {
575  uint32 session_id = CreateSession(key_id_);
576  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
577      encrypted_data_, key_id_, iv_, no_subsample_entries_);
578
579  UpdateSessionAndExpect(session_id, kKeyAsJWK, SESSION_READY);
580  ASSERT_NO_FATAL_FAILURE(
581      DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
582
583  ReleaseSession(session_id);
584  ASSERT_NO_FATAL_FAILURE(
585      DecryptAndExpect(encrypted_buffer, original_data_, NO_KEY));
586}
587
588TEST_F(AesDecryptorTest, LatestKeyUsed) {
589  uint32 session_id1 = CreateSession(key_id_);
590  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
591      encrypted_data_, key_id_, iv_, no_subsample_entries_);
592
593  // Add alternate key, buffer should not be decoded properly.
594  UpdateSessionAndExpect(session_id1, kKeyAlternateAsJWK, SESSION_READY);
595  ASSERT_NO_FATAL_FAILURE(
596      DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH));
597
598  // Create a second session with a correct key value for key_id_.
599  uint32 session_id2 = CreateSession(key_id_);
600  UpdateSessionAndExpect(session_id2, kKeyAsJWK, SESSION_READY);
601
602  // Should be able to decode with latest key.
603  ASSERT_NO_FATAL_FAILURE(
604      DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
605}
606
607TEST_F(AesDecryptorTest, LatestKeyUsedAfterReleaseSession) {
608  uint32 session_id1 = CreateSession(key_id_);
609  scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
610      encrypted_data_, key_id_, iv_, no_subsample_entries_);
611  UpdateSessionAndExpect(session_id1, kKeyAsJWK, SESSION_READY);
612  ASSERT_NO_FATAL_FAILURE(
613      DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
614
615  // Create a second session with a different key value for key_id_.
616  uint32 session_id2 = CreateSession(key_id_);
617  UpdateSessionAndExpect(session_id2, kKeyAlternateAsJWK, SESSION_READY);
618
619  // Should not be able to decode with new key.
620  ASSERT_NO_FATAL_FAILURE(
621      DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH));
622
623  // Close second session, should revert to original key.
624  ReleaseSession(session_id2);
625  ASSERT_NO_FATAL_FAILURE(
626      DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
627}
628
629TEST_F(AesDecryptorTest, JWKKey) {
630  uint32 session_id = CreateSession(key_id_);
631
632  // Try a simple JWK key (i.e. not in a set)
633  const std::string kJwkSimple =
634      "{"
635      "  \"kty\": \"oct\","
636      "  \"kid\": \"AAECAwQFBgcICQoLDA0ODxAREhM\","
637      "  \"k\": \"FBUWFxgZGhscHR4fICEiIw\""
638      "}";
639  UpdateSessionAndExpect(session_id, kJwkSimple, SESSION_ERROR);
640
641  // Try a key list with multiple entries.
642  const std::string kJwksMultipleEntries =
643      "{"
644      "  \"keys\": ["
645      "    {"
646      "      \"kty\": \"oct\","
647      "      \"kid\": \"AAECAwQFBgcICQoLDA0ODxAREhM\","
648      "      \"k\": \"FBUWFxgZGhscHR4fICEiIw\""
649      "    },"
650      "    {"
651      "      \"kty\": \"oct\","
652      "      \"kid\": \"JCUmJygpKissLS4vMA\","
653      "      \"k\":\"MTIzNDU2Nzg5Ojs8PT4/QA\""
654      "    }"
655      "  ]"
656      "}";
657  UpdateSessionAndExpect(session_id, kJwksMultipleEntries, SESSION_READY);
658
659  // Try a key with no spaces and some \n plus additional fields.
660  const std::string kJwksNoSpaces =
661      "\n\n{\"something\":1,\"keys\":[{\n\n\"kty\":\"oct\",\"alg\":\"A128KW\","
662      "\"kid\":\"AAECAwQFBgcICQoLDA0ODxAREhM\",\"k\":\"GawgguFyGrWKav7AX4VKUg"
663      "\",\"foo\":\"bar\"}]}\n\n";
664  UpdateSessionAndExpect(session_id, kJwksNoSpaces, SESSION_READY);
665
666  // Try some non-ASCII characters.
667  UpdateSessionAndExpect(session_id,
668                         "This is not ASCII due to \xff\xfe\xfd in it.",
669                         SESSION_ERROR);
670
671  // Try a badly formatted key. Assume that the JSON parser is fully tested,
672  // so we won't try a lot of combinations. However, need a test to ensure
673  // that the code doesn't crash if invalid JSON received.
674  UpdateSessionAndExpect(session_id, "This is not a JSON key.", SESSION_ERROR);
675
676  // Try passing some valid JSON that is not a dictionary at the top level.
677  UpdateSessionAndExpect(session_id, "40", SESSION_ERROR);
678
679  // Try an empty dictionary.
680  UpdateSessionAndExpect(session_id, "{ }", SESSION_ERROR);
681
682  // Try an empty 'keys' dictionary.
683  UpdateSessionAndExpect(session_id, "{ \"keys\": [] }", SESSION_ERROR);
684
685  // Try with 'keys' not a dictionary.
686  UpdateSessionAndExpect(session_id, "{ \"keys\":\"1\" }", SESSION_ERROR);
687
688  // Try with 'keys' a list of integers.
689  UpdateSessionAndExpect(
690      session_id, "{ \"keys\": [ 1, 2, 3 ] }", SESSION_ERROR);
691
692  // Try padding(=) at end of 'k' base64 string.
693  const std::string kJwksWithPaddedKey =
694      "{"
695      "  \"keys\": ["
696      "    {"
697      "      \"kty\": \"oct\","
698      "      \"kid\": \"AAECAw\","
699      "      \"k\": \"BAUGBwgJCgsMDQ4PEBESEw==\""
700      "    }"
701      "  ]"
702      "}";
703  UpdateSessionAndExpect(session_id, kJwksWithPaddedKey, SESSION_ERROR);
704
705  // Try padding(=) at end of 'kid' base64 string.
706  const std::string kJwksWithPaddedKeyId =
707      "{"
708      "  \"keys\": ["
709      "    {"
710      "      \"kty\": \"oct\","
711      "      \"kid\": \"AAECAw==\","
712      "      \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
713      "    }"
714      "  ]"
715      "}";
716  UpdateSessionAndExpect(session_id, kJwksWithPaddedKeyId, SESSION_ERROR);
717
718  // Try a key with invalid base64 encoding.
719  const std::string kJwksWithInvalidBase64 =
720      "{"
721      "  \"keys\": ["
722      "    {"
723      "      \"kty\": \"oct\","
724      "      \"kid\": \"!@#$%^&*()\","
725      "      \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
726      "    }"
727      "  ]"
728      "}";
729  UpdateSessionAndExpect(session_id, kJwksWithInvalidBase64, SESSION_ERROR);
730
731  // Try a 3-byte 'kid' where no base64 padding is required.
732  // |kJwksMultipleEntries| above has 2 'kid's that require 1 and 2 padding
733  // bytes. Note that 'k' has to be 16 bytes, so it will always require padding.
734  const std::string kJwksWithNoPadding =
735      "{"
736      "  \"keys\": ["
737      "    {"
738      "      \"kty\": \"oct\","
739      "      \"kid\": \"Kiss\","
740      "      \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
741      "    }"
742      "  ]"
743      "}";
744  UpdateSessionAndExpect(session_id, kJwksWithNoPadding, SESSION_READY);
745
746  // Empty key id.
747  const std::string kJwksWithEmptyKeyId =
748      "{"
749      "  \"keys\": ["
750      "    {"
751      "      \"kty\": \"oct\","
752      "      \"kid\": \"\","
753      "      \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
754      "    }"
755      "  ]"
756      "}";
757  UpdateSessionAndExpect(session_id, kJwksWithEmptyKeyId, SESSION_ERROR);
758  ReleaseSession(session_id);
759}
760
761}  // namespace media
762