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