Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / media / cdm / aes_decryptor_unittest.cc
blob6fd8cec7873e04d70fbcce08968f67b12b63eda5
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.
5 #include <string>
6 #include <vector>
8 #include "base/basictypes.h"
9 #include "base/bind.h"
10 #include "base/json/json_reader.h"
11 #include "base/values.h"
12 #include "media/base/cdm_callback_promise.h"
13 #include "media/base/cdm_key_information.h"
14 #include "media/base/decoder_buffer.h"
15 #include "media/base/decrypt_config.h"
16 #include "media/base/mock_filters.h"
17 #include "media/cdm/aes_decryptor.h"
18 #include "testing/gmock/include/gmock/gmock.h"
19 #include "testing/gtest/include/gtest/gtest.h"
20 #include "url/gurl.h"
22 using ::testing::_;
23 using ::testing::Gt;
24 using ::testing::IsNull;
25 using ::testing::NotNull;
26 using ::testing::SaveArg;
27 using ::testing::StrNe;
28 using ::testing::Unused;
30 MATCHER(IsEmpty, "") { return arg.empty(); }
31 MATCHER(IsNotEmpty, "") { return !arg.empty(); }
32 MATCHER(IsJSONDictionary, "") {
33 std::string result(arg.begin(), arg.end());
34 scoped_ptr<base::Value> root(base::JSONReader().ReadToValue(result));
35 return (root.get() && root->GetType() == base::Value::TYPE_DICTIONARY);
38 namespace media {
40 const uint8 kOriginalData[] = "Original subsample data.";
41 const int kOriginalDataSize = 24;
43 // In the examples below, 'k'(key) has to be 16 bytes, and will always require
44 // 2 bytes of padding. 'kid'(keyid) is variable length, and may require 0, 1,
45 // or 2 bytes of padding.
47 const uint8 kKeyId[] = {
48 // base64 equivalent is AAECAw
49 0x00, 0x01, 0x02, 0x03
52 // Key is 0x0405060708090a0b0c0d0e0f10111213,
53 // base64 equivalent is BAUGBwgJCgsMDQ4PEBESEw.
54 const char kKeyAsJWK[] =
55 "{"
56 " \"keys\": ["
57 " {"
58 " \"kty\": \"oct\","
59 " \"alg\": \"A128KW\","
60 " \"kid\": \"AAECAw\","
61 " \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
62 " }"
63 " ],"
64 " \"type\": \"temporary\""
65 "}";
67 // Same kid as kKeyAsJWK, key to decrypt kEncryptedData2
68 const char kKeyAlternateAsJWK[] =
69 "{"
70 " \"keys\": ["
71 " {"
72 " \"kty\": \"oct\","
73 " \"alg\": \"A128KW\","
74 " \"kid\": \"AAECAw\","
75 " \"k\": \"FBUWFxgZGhscHR4fICEiIw\""
76 " }"
77 " ]"
78 "}";
80 const char kWrongKeyAsJWK[] =
81 "{"
82 " \"keys\": ["
83 " {"
84 " \"kty\": \"oct\","
85 " \"alg\": \"A128KW\","
86 " \"kid\": \"AAECAw\","
87 " \"k\": \"7u7u7u7u7u7u7u7u7u7u7g\""
88 " }"
89 " ]"
90 "}";
92 const char kWrongSizedKeyAsJWK[] =
93 "{"
94 " \"keys\": ["
95 " {"
96 " \"kty\": \"oct\","
97 " \"alg\": \"A128KW\","
98 " \"kid\": \"AAECAw\","
99 " \"k\": \"AAECAw\""
100 " }"
101 " ]"
102 "}";
104 const uint8 kIv[] = {
105 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
106 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
109 // kOriginalData encrypted with kKey and kIv but without any subsamples (or
110 // equivalently using kSubsampleEntriesCypherOnly).
111 const uint8 kEncryptedData[] = {
112 0x2f, 0x03, 0x09, 0xef, 0x71, 0xaf, 0x31, 0x16,
113 0xfa, 0x9d, 0x18, 0x43, 0x1e, 0x96, 0x71, 0xb5,
114 0xbf, 0xf5, 0x30, 0x53, 0x9a, 0x20, 0xdf, 0x95
117 // kOriginalData encrypted with kSubsampleKey and kSubsampleIv using
118 // kSubsampleEntriesNormal.
119 const uint8 kSubsampleEncryptedData[] = {
120 0x4f, 0x72, 0x09, 0x16, 0x09, 0xe6, 0x79, 0xad,
121 0x70, 0x73, 0x75, 0x62, 0x09, 0xbb, 0x83, 0x1d,
122 0x4d, 0x08, 0xd7, 0x78, 0xa4, 0xa7, 0xf1, 0x2e
125 const uint8 kOriginalData2[] = "Changed Original data.";
127 const uint8 kIv2[] = {
128 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
129 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
132 const uint8 kKeyId2[] = {
133 // base64 equivalent is AAECAwQFBgcICQoLDA0ODxAREhM=
134 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
135 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
136 0x10, 0x11, 0x12, 0x13
139 const char kKey2AsJWK[] =
141 " \"keys\": ["
142 " {"
143 " \"kty\": \"oct\","
144 " \"alg\": \"A128KW\","
145 " \"kid\": \"AAECAwQFBgcICQoLDA0ODxAREhM\","
146 " \"k\": \"FBUWFxgZGhscHR4fICEiIw\""
147 " }"
148 " ]"
149 "}";
151 // 'k' in bytes is x14x15x16x17x18x19x1ax1bx1cx1dx1ex1fx20x21x22x23
153 const uint8 kEncryptedData2[] = {
154 0x57, 0x66, 0xf4, 0x12, 0x1a, 0xed, 0xb5, 0x79,
155 0x1c, 0x8e, 0x25, 0xd7, 0x17, 0xe7, 0x5e, 0x16,
156 0xe3, 0x40, 0x08, 0x27, 0x11, 0xe9
159 // Subsample entries for testing. The sum of |cypher_bytes| and |clear_bytes| of
160 // all entries must be equal to kOriginalDataSize to make the subsample entries
161 // valid.
163 const SubsampleEntry kSubsampleEntriesNormal[] = {
164 { 2, 7 },
165 { 3, 11 },
166 { 1, 0 }
169 const SubsampleEntry kSubsampleEntriesWrongSize[] = {
170 { 3, 6 }, // This entry doesn't match the correct entry.
171 { 3, 11 },
172 { 1, 0 }
175 const SubsampleEntry kSubsampleEntriesInvalidTotalSize[] = {
176 { 1, 1000 }, // This entry is too large.
177 { 3, 11 },
178 { 1, 0 }
181 const SubsampleEntry kSubsampleEntriesClearOnly[] = {
182 { 7, 0 },
183 { 8, 0 },
184 { 9, 0 }
187 const SubsampleEntry kSubsampleEntriesCypherOnly[] = {
188 { 0, 6 },
189 { 0, 8 },
190 { 0, 10 }
193 static scoped_refptr<DecoderBuffer> CreateEncryptedBuffer(
194 const std::vector<uint8>& data,
195 const std::vector<uint8>& key_id,
196 const std::vector<uint8>& iv,
197 const std::vector<SubsampleEntry>& subsample_entries) {
198 DCHECK(!data.empty());
199 scoped_refptr<DecoderBuffer> encrypted_buffer(new DecoderBuffer(data.size()));
200 memcpy(encrypted_buffer->writable_data(), &data[0], data.size());
201 CHECK(encrypted_buffer.get());
202 std::string key_id_string(
203 reinterpret_cast<const char*>(key_id.empty() ? NULL : &key_id[0]),
204 key_id.size());
205 std::string iv_string(
206 reinterpret_cast<const char*>(iv.empty() ? NULL : &iv[0]), iv.size());
207 encrypted_buffer->set_decrypt_config(scoped_ptr<DecryptConfig>(
208 new DecryptConfig(key_id_string, iv_string, subsample_entries)));
209 return encrypted_buffer;
212 enum PromiseResult { RESOLVED, REJECTED };
214 class AesDecryptorTest : public testing::Test {
215 public:
216 AesDecryptorTest()
217 : decryptor_(GURL::EmptyGURL(),
218 base::Bind(&AesDecryptorTest::OnSessionMessage,
219 base::Unretained(this)),
220 base::Bind(&AesDecryptorTest::OnSessionClosed,
221 base::Unretained(this)),
222 base::Bind(&AesDecryptorTest::OnSessionKeysChange,
223 base::Unretained(this))),
224 decrypt_cb_(base::Bind(&AesDecryptorTest::BufferDecrypted,
225 base::Unretained(this))),
226 original_data_(kOriginalData, kOriginalData + kOriginalDataSize),
227 encrypted_data_(kEncryptedData,
228 kEncryptedData + arraysize(kEncryptedData)),
229 subsample_encrypted_data_(
230 kSubsampleEncryptedData,
231 kSubsampleEncryptedData + arraysize(kSubsampleEncryptedData)),
232 key_id_(kKeyId, kKeyId + arraysize(kKeyId)),
233 iv_(kIv, kIv + arraysize(kIv)),
234 normal_subsample_entries_(
235 kSubsampleEntriesNormal,
236 kSubsampleEntriesNormal + arraysize(kSubsampleEntriesNormal)) {
239 protected:
240 void OnResolveWithSession(PromiseResult expected_result,
241 const std::string& session_id) {
242 EXPECT_EQ(expected_result, RESOLVED) << "Unexpectedly resolved.";
243 EXPECT_GT(session_id.length(), 0ul);
244 session_id_ = session_id;
247 void OnResolve(PromiseResult expected_result) {
248 EXPECT_EQ(expected_result, RESOLVED) << "Unexpectedly resolved.";
251 void OnReject(PromiseResult expected_result,
252 MediaKeys::Exception exception_code,
253 uint32 system_code,
254 const std::string& error_message) {
255 EXPECT_EQ(expected_result, REJECTED)
256 << "Unexpectedly rejected with message: " << error_message;
259 scoped_ptr<SimpleCdmPromise> CreatePromise(PromiseResult expected_result) {
260 scoped_ptr<SimpleCdmPromise> promise(
261 new CdmCallbackPromise<>(base::Bind(&AesDecryptorTest::OnResolve,
262 base::Unretained(this),
263 expected_result),
264 base::Bind(&AesDecryptorTest::OnReject,
265 base::Unretained(this),
266 expected_result)));
267 return promise.Pass();
270 scoped_ptr<NewSessionCdmPromise> CreateSessionPromise(
271 PromiseResult expected_result) {
272 scoped_ptr<NewSessionCdmPromise> promise(
273 new CdmCallbackPromise<std::string>(
274 base::Bind(&AesDecryptorTest::OnResolveWithSession,
275 base::Unretained(this),
276 expected_result),
277 base::Bind(&AesDecryptorTest::OnReject,
278 base::Unretained(this),
279 expected_result)));
280 return promise.Pass();
283 // Creates a new session using |key_id|. Returns the session ID.
284 std::string CreateSession(const std::vector<uint8>& key_id) {
285 DCHECK(!key_id.empty());
286 EXPECT_CALL(*this, OnSessionMessage(IsNotEmpty(), _, IsJSONDictionary(),
287 GURL::EmptyGURL()));
288 decryptor_.CreateSessionAndGenerateRequest(MediaKeys::TEMPORARY_SESSION,
289 EmeInitDataType::WEBM, key_id,
290 CreateSessionPromise(RESOLVED));
291 // This expects the promise to be called synchronously, which is the case
292 // for AesDecryptor.
293 return session_id_;
296 // Closes the session specified by |session_id|.
297 void CloseSession(const std::string& session_id) {
298 EXPECT_CALL(*this, OnSessionClosed(session_id));
299 decryptor_.CloseSession(session_id, CreatePromise(RESOLVED));
302 // Removes the session specified by |session_id|. This should simply do a
303 // CloseSession().
304 // TODO(jrummell): Clean this up when the prefixed API is removed.
305 // http://crbug.com/249976.
306 void RemoveSession(const std::string& session_id) {
307 EXPECT_CALL(*this, OnSessionClosed(session_id));
308 decryptor_.RemoveSession(session_id, CreatePromise(RESOLVED));
311 MOCK_METHOD2(OnSessionKeysChangeCalled,
312 void(const std::string& session_id,
313 bool has_additional_usable_key));
315 void OnSessionKeysChange(const std::string& session_id,
316 bool has_additional_usable_key,
317 CdmKeysInfo keys_info) {
318 keys_info_.swap(keys_info);
319 OnSessionKeysChangeCalled(session_id, has_additional_usable_key);
322 // Updates the session specified by |session_id| with |key|. |result|
323 // tests that the update succeeds or generates an error.
324 void UpdateSessionAndExpect(std::string session_id,
325 const std::string& key,
326 PromiseResult expected_result,
327 bool new_key_expected) {
328 DCHECK(!key.empty());
330 if (expected_result == RESOLVED) {
331 EXPECT_CALL(*this,
332 OnSessionKeysChangeCalled(session_id, new_key_expected));
333 } else {
334 EXPECT_CALL(*this, OnSessionKeysChangeCalled(_, _)).Times(0);
337 decryptor_.UpdateSession(session_id,
338 std::vector<uint8>(key.begin(), key.end()),
339 CreatePromise(expected_result));
342 bool KeysInfoContains(std::vector<uint8> expected) {
343 for (const auto& key_id : keys_info_) {
344 if (key_id->key_id == expected)
345 return true;
347 return false;
350 MOCK_METHOD2(BufferDecrypted, void(Decryptor::Status,
351 const scoped_refptr<DecoderBuffer>&));
353 enum DecryptExpectation {
354 SUCCESS,
355 DATA_MISMATCH,
356 DATA_AND_SIZE_MISMATCH,
357 DECRYPT_ERROR,
358 NO_KEY
361 void DecryptAndExpect(const scoped_refptr<DecoderBuffer>& encrypted,
362 const std::vector<uint8>& plain_text,
363 DecryptExpectation result) {
364 scoped_refptr<DecoderBuffer> decrypted;
366 switch (result) {
367 case SUCCESS:
368 case DATA_MISMATCH:
369 case DATA_AND_SIZE_MISMATCH:
370 EXPECT_CALL(*this, BufferDecrypted(Decryptor::kSuccess, NotNull()))
371 .WillOnce(SaveArg<1>(&decrypted));
372 break;
373 case DECRYPT_ERROR:
374 EXPECT_CALL(*this, BufferDecrypted(Decryptor::kError, IsNull()))
375 .WillOnce(SaveArg<1>(&decrypted));
376 break;
377 case NO_KEY:
378 EXPECT_CALL(*this, BufferDecrypted(Decryptor::kNoKey, IsNull()))
379 .WillOnce(SaveArg<1>(&decrypted));
380 break;
383 decryptor_.Decrypt(Decryptor::kVideo, encrypted, decrypt_cb_);
385 std::vector<uint8> decrypted_text;
386 if (decrypted.get() && decrypted->data_size()) {
387 decrypted_text.assign(
388 decrypted->data(), decrypted->data() + decrypted->data_size());
391 switch (result) {
392 case SUCCESS:
393 EXPECT_EQ(plain_text, decrypted_text);
394 break;
395 case DATA_MISMATCH:
396 EXPECT_EQ(plain_text.size(), decrypted_text.size());
397 EXPECT_NE(plain_text, decrypted_text);
398 break;
399 case DATA_AND_SIZE_MISMATCH:
400 EXPECT_NE(plain_text.size(), decrypted_text.size());
401 break;
402 case DECRYPT_ERROR:
403 case NO_KEY:
404 EXPECT_TRUE(decrypted_text.empty());
405 break;
409 MOCK_METHOD4(OnSessionMessage,
410 void(const std::string& session_id,
411 MediaKeys::MessageType message_type,
412 const std::vector<uint8>& message,
413 const GURL& legacy_destination_url));
414 MOCK_METHOD1(OnSessionClosed, void(const std::string& session_id));
416 AesDecryptor decryptor_;
417 AesDecryptor::DecryptCB decrypt_cb_;
418 std::string session_id_;
419 CdmKeysInfo keys_info_;
421 // Constants for testing.
422 const std::vector<uint8> original_data_;
423 const std::vector<uint8> encrypted_data_;
424 const std::vector<uint8> subsample_encrypted_data_;
425 const std::vector<uint8> key_id_;
426 const std::vector<uint8> iv_;
427 const std::vector<SubsampleEntry> normal_subsample_entries_;
428 const std::vector<SubsampleEntry> no_subsample_entries_;
431 TEST_F(AesDecryptorTest, CreateSessionWithNullInitData) {
432 EXPECT_CALL(*this,
433 OnSessionMessage(IsNotEmpty(), _, IsEmpty(), GURL::EmptyGURL()));
434 decryptor_.CreateSessionAndGenerateRequest(
435 MediaKeys::TEMPORARY_SESSION, EmeInitDataType::WEBM, std::vector<uint8>(),
436 CreateSessionPromise(RESOLVED));
439 TEST_F(AesDecryptorTest, MultipleCreateSession) {
440 EXPECT_CALL(*this,
441 OnSessionMessage(IsNotEmpty(), _, IsEmpty(), GURL::EmptyGURL()));
442 decryptor_.CreateSessionAndGenerateRequest(
443 MediaKeys::TEMPORARY_SESSION, EmeInitDataType::WEBM, std::vector<uint8>(),
444 CreateSessionPromise(RESOLVED));
446 EXPECT_CALL(*this,
447 OnSessionMessage(IsNotEmpty(), _, IsEmpty(), GURL::EmptyGURL()));
448 decryptor_.CreateSessionAndGenerateRequest(
449 MediaKeys::TEMPORARY_SESSION, EmeInitDataType::WEBM, std::vector<uint8>(),
450 CreateSessionPromise(RESOLVED));
452 EXPECT_CALL(*this,
453 OnSessionMessage(IsNotEmpty(), _, IsEmpty(), GURL::EmptyGURL()));
454 decryptor_.CreateSessionAndGenerateRequest(
455 MediaKeys::TEMPORARY_SESSION, EmeInitDataType::WEBM, std::vector<uint8>(),
456 CreateSessionPromise(RESOLVED));
459 TEST_F(AesDecryptorTest, CreateSessionWithCencInitData) {
460 const uint8 init_data[] = {
461 0x00, 0x00, 0x00, 0x44, // size = 68
462 0x70, 0x73, 0x73, 0x68, // 'pssh'
463 0x01, // version
464 0x00, 0x00, 0x00, // flags
465 0x10, 0x77, 0xEF, 0xEC, 0xC0, 0xB2, 0x4D, 0x02, // SystemID
466 0xAC, 0xE3, 0x3C, 0x1E, 0x52, 0xE2, 0xFB, 0x4B,
467 0x00, 0x00, 0x00, 0x02, // key count
468 0x7E, 0x57, 0x1D, 0x03, 0x7E, 0x57, 0x1D, 0x03, // key1
469 0x7E, 0x57, 0x1D, 0x03, 0x7E, 0x57, 0x1D, 0x03,
470 0x7E, 0x57, 0x1D, 0x04, 0x7E, 0x57, 0x1D, 0x04, // key2
471 0x7E, 0x57, 0x1D, 0x04, 0x7E, 0x57, 0x1D, 0x04,
472 0x00, 0x00, 0x00, 0x00 // datasize
474 EXPECT_CALL(*this, OnSessionMessage(IsNotEmpty(), _, IsJSONDictionary(),
475 GURL::EmptyGURL()));
476 decryptor_.CreateSessionAndGenerateRequest(
477 MediaKeys::TEMPORARY_SESSION, EmeInitDataType::CENC,
478 std::vector<uint8>(init_data, init_data + arraysize(init_data)),
479 CreateSessionPromise(RESOLVED));
482 TEST_F(AesDecryptorTest, CreateSessionWithKeyIdsInitData) {
483 const char init_data[] =
484 "{\"kids\":[\"AQI\",\"AQIDBA\",\"AQIDBAUGBwgJCgsMDQ4PEA\"]}";
486 EXPECT_CALL(*this, OnSessionMessage(IsNotEmpty(), _, IsJSONDictionary(),
487 GURL::EmptyGURL()));
488 decryptor_.CreateSessionAndGenerateRequest(
489 MediaKeys::TEMPORARY_SESSION, EmeInitDataType::KEYIDS,
490 std::vector<uint8>(init_data, init_data + arraysize(init_data) - 1),
491 CreateSessionPromise(RESOLVED));
494 TEST_F(AesDecryptorTest, NormalDecryption) {
495 std::string session_id = CreateSession(key_id_);
496 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
497 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
498 encrypted_data_, key_id_, iv_, no_subsample_entries_);
499 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
502 TEST_F(AesDecryptorTest, UnencryptedFrame) {
503 // An empty iv string signals that the frame is unencrypted.
504 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
505 original_data_, key_id_, std::vector<uint8>(), no_subsample_entries_);
506 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
509 TEST_F(AesDecryptorTest, WrongKey) {
510 std::string session_id = CreateSession(key_id_);
511 UpdateSessionAndExpect(session_id, kWrongKeyAsJWK, RESOLVED, true);
512 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
513 encrypted_data_, key_id_, iv_, no_subsample_entries_);
514 DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
517 TEST_F(AesDecryptorTest, NoKey) {
518 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
519 encrypted_data_, key_id_, iv_, no_subsample_entries_);
520 EXPECT_CALL(*this, BufferDecrypted(AesDecryptor::kNoKey, IsNull()));
521 decryptor_.Decrypt(Decryptor::kVideo, encrypted_buffer, decrypt_cb_);
524 TEST_F(AesDecryptorTest, KeyReplacement) {
525 std::string session_id = CreateSession(key_id_);
526 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
527 encrypted_data_, key_id_, iv_, no_subsample_entries_);
529 UpdateSessionAndExpect(session_id, kWrongKeyAsJWK, RESOLVED, true);
530 ASSERT_NO_FATAL_FAILURE(DecryptAndExpect(
531 encrypted_buffer, original_data_, DATA_MISMATCH));
533 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, false);
534 ASSERT_NO_FATAL_FAILURE(
535 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
538 TEST_F(AesDecryptorTest, WrongSizedKey) {
539 std::string session_id = CreateSession(key_id_);
540 UpdateSessionAndExpect(session_id, kWrongSizedKeyAsJWK, REJECTED, true);
543 TEST_F(AesDecryptorTest, MultipleKeysAndFrames) {
544 std::string session_id = CreateSession(key_id_);
545 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
546 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
547 encrypted_data_, key_id_, iv_, no_subsample_entries_);
548 ASSERT_NO_FATAL_FAILURE(
549 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
551 UpdateSessionAndExpect(session_id, kKey2AsJWK, RESOLVED, true);
553 // The first key is still available after we added a second key.
554 ASSERT_NO_FATAL_FAILURE(
555 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
557 // The second key is also available.
558 encrypted_buffer = CreateEncryptedBuffer(
559 std::vector<uint8>(kEncryptedData2,
560 kEncryptedData2 + arraysize(kEncryptedData2)),
561 std::vector<uint8>(kKeyId2, kKeyId2 + arraysize(kKeyId2)),
562 std::vector<uint8>(kIv2, kIv2 + arraysize(kIv2)),
563 no_subsample_entries_);
564 ASSERT_NO_FATAL_FAILURE(DecryptAndExpect(
565 encrypted_buffer,
566 std::vector<uint8>(kOriginalData2,
567 kOriginalData2 + arraysize(kOriginalData2) - 1),
568 SUCCESS));
571 TEST_F(AesDecryptorTest, CorruptedIv) {
572 std::string session_id = CreateSession(key_id_);
573 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
575 std::vector<uint8> bad_iv = iv_;
576 bad_iv[1]++;
578 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
579 encrypted_data_, key_id_, bad_iv, no_subsample_entries_);
581 DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
584 TEST_F(AesDecryptorTest, CorruptedData) {
585 std::string session_id = CreateSession(key_id_);
586 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
588 std::vector<uint8> bad_data = encrypted_data_;
589 bad_data[1]++;
591 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
592 bad_data, key_id_, iv_, no_subsample_entries_);
593 DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
596 TEST_F(AesDecryptorTest, EncryptedAsUnencryptedFailure) {
597 std::string session_id = CreateSession(key_id_);
598 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
599 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
600 encrypted_data_, key_id_, std::vector<uint8>(), no_subsample_entries_);
601 DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
604 TEST_F(AesDecryptorTest, SubsampleDecryption) {
605 std::string session_id = CreateSession(key_id_);
606 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
607 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
608 subsample_encrypted_data_, key_id_, iv_, normal_subsample_entries_);
609 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
612 // Ensures noninterference of data offset and subsample mechanisms. We never
613 // expect to encounter this in the wild, but since the DecryptConfig doesn't
614 // disallow such a configuration, it should be covered.
615 TEST_F(AesDecryptorTest, SubsampleDecryptionWithOffset) {
616 std::string session_id = CreateSession(key_id_);
617 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
618 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
619 subsample_encrypted_data_, key_id_, iv_, normal_subsample_entries_);
620 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
623 TEST_F(AesDecryptorTest, SubsampleWrongSize) {
624 std::string session_id = CreateSession(key_id_);
625 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
627 std::vector<SubsampleEntry> subsample_entries_wrong_size(
628 kSubsampleEntriesWrongSize,
629 kSubsampleEntriesWrongSize + arraysize(kSubsampleEntriesWrongSize));
631 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
632 subsample_encrypted_data_, key_id_, iv_, subsample_entries_wrong_size);
633 DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH);
636 TEST_F(AesDecryptorTest, SubsampleInvalidTotalSize) {
637 std::string session_id = CreateSession(key_id_);
638 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
640 std::vector<SubsampleEntry> subsample_entries_invalid_total_size(
641 kSubsampleEntriesInvalidTotalSize,
642 kSubsampleEntriesInvalidTotalSize +
643 arraysize(kSubsampleEntriesInvalidTotalSize));
645 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
646 subsample_encrypted_data_, key_id_, iv_,
647 subsample_entries_invalid_total_size);
648 DecryptAndExpect(encrypted_buffer, original_data_, DECRYPT_ERROR);
651 // No cypher bytes in any of the subsamples.
652 TEST_F(AesDecryptorTest, SubsampleClearBytesOnly) {
653 std::string session_id = CreateSession(key_id_);
654 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
656 std::vector<SubsampleEntry> clear_only_subsample_entries(
657 kSubsampleEntriesClearOnly,
658 kSubsampleEntriesClearOnly + arraysize(kSubsampleEntriesClearOnly));
660 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
661 original_data_, key_id_, iv_, clear_only_subsample_entries);
662 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
665 // No clear bytes in any of the subsamples.
666 TEST_F(AesDecryptorTest, SubsampleCypherBytesOnly) {
667 std::string session_id = CreateSession(key_id_);
668 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
670 std::vector<SubsampleEntry> cypher_only_subsample_entries(
671 kSubsampleEntriesCypherOnly,
672 kSubsampleEntriesCypherOnly + arraysize(kSubsampleEntriesCypherOnly));
674 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
675 encrypted_data_, key_id_, iv_, cypher_only_subsample_entries);
676 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS);
679 TEST_F(AesDecryptorTest, CloseSession) {
680 std::string session_id = CreateSession(key_id_);
681 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
682 encrypted_data_, key_id_, iv_, no_subsample_entries_);
684 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
685 ASSERT_NO_FATAL_FAILURE(
686 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
688 CloseSession(session_id);
691 TEST_F(AesDecryptorTest, RemoveSession) {
692 // TODO(jrummell): Clean this up when the prefixed API is removed.
693 // http://crbug.com/249976.
694 std::string session_id = CreateSession(key_id_);
695 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
696 encrypted_data_, key_id_, iv_, no_subsample_entries_);
698 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
699 ASSERT_NO_FATAL_FAILURE(
700 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
702 RemoveSession(session_id);
705 TEST_F(AesDecryptorTest, NoKeyAfterCloseSession) {
706 std::string session_id = CreateSession(key_id_);
707 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
708 encrypted_data_, key_id_, iv_, no_subsample_entries_);
710 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
711 ASSERT_NO_FATAL_FAILURE(
712 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
714 CloseSession(session_id);
715 ASSERT_NO_FATAL_FAILURE(
716 DecryptAndExpect(encrypted_buffer, original_data_, NO_KEY));
719 TEST_F(AesDecryptorTest, LatestKeyUsed) {
720 std::string session_id1 = CreateSession(key_id_);
721 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
722 encrypted_data_, key_id_, iv_, no_subsample_entries_);
724 // Add alternate key, buffer should not be decoded properly.
725 UpdateSessionAndExpect(session_id1, kKeyAlternateAsJWK, RESOLVED, true);
726 ASSERT_NO_FATAL_FAILURE(
727 DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH));
729 // Create a second session with a correct key value for key_id_.
730 std::string session_id2 = CreateSession(key_id_);
731 UpdateSessionAndExpect(session_id2, kKeyAsJWK, RESOLVED, true);
733 // Should be able to decode with latest key.
734 ASSERT_NO_FATAL_FAILURE(
735 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
738 TEST_F(AesDecryptorTest, LatestKeyUsedAfterCloseSession) {
739 std::string session_id1 = CreateSession(key_id_);
740 scoped_refptr<DecoderBuffer> encrypted_buffer = CreateEncryptedBuffer(
741 encrypted_data_, key_id_, iv_, no_subsample_entries_);
742 UpdateSessionAndExpect(session_id1, kKeyAsJWK, RESOLVED, true);
743 ASSERT_NO_FATAL_FAILURE(
744 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
746 // Create a second session with a different key value for key_id_.
747 std::string session_id2 = CreateSession(key_id_);
748 UpdateSessionAndExpect(session_id2, kKeyAlternateAsJWK, RESOLVED, true);
750 // Should not be able to decode with new key.
751 ASSERT_NO_FATAL_FAILURE(
752 DecryptAndExpect(encrypted_buffer, original_data_, DATA_MISMATCH));
754 // Close second session, should revert to original key.
755 CloseSession(session_id2);
756 ASSERT_NO_FATAL_FAILURE(
757 DecryptAndExpect(encrypted_buffer, original_data_, SUCCESS));
760 TEST_F(AesDecryptorTest, JWKKey) {
761 std::string session_id = CreateSession(key_id_);
763 // Try a simple JWK key (i.e. not in a set)
764 const std::string kJwkSimple =
766 " \"kty\": \"oct\","
767 " \"alg\": \"A128KW\","
768 " \"kid\": \"AAECAwQFBgcICQoLDA0ODxAREhM\","
769 " \"k\": \"FBUWFxgZGhscHR4fICEiIw\""
770 "}";
771 UpdateSessionAndExpect(session_id, kJwkSimple, REJECTED, true);
773 // Try a key list with multiple entries.
774 const std::string kJwksMultipleEntries =
776 " \"keys\": ["
777 " {"
778 " \"kty\": \"oct\","
779 " \"alg\": \"A128KW\","
780 " \"kid\": \"AAECAwQFBgcICQoLDA0ODxAREhM\","
781 " \"k\": \"FBUWFxgZGhscHR4fICEiIw\""
782 " },"
783 " {"
784 " \"kty\": \"oct\","
785 " \"alg\": \"A128KW\","
786 " \"kid\": \"JCUmJygpKissLS4vMA\","
787 " \"k\":\"MTIzNDU2Nzg5Ojs8PT4_QA\""
788 " }"
789 " ]"
790 "}";
791 UpdateSessionAndExpect(session_id, kJwksMultipleEntries, RESOLVED, true);
793 // Try a key with no spaces and some \n plus additional fields.
794 const std::string kJwksNoSpaces =
795 "\n\n{\"something\":1,\"keys\":[{\n\n\"kty\":\"oct\",\"alg\":\"A128KW\","
796 "\"kid\":\"AQIDBAUGBwgJCgsMCg4PAA\",\"k\":\"GawgguFyGrWKav7AX4VKUg"
797 "\",\"foo\":\"bar\"}]}\n\n";
798 UpdateSessionAndExpect(session_id, kJwksNoSpaces, RESOLVED, true);
800 // Try some non-ASCII characters.
801 UpdateSessionAndExpect(session_id,
802 "This is not ASCII due to \xff\xfe\xfd in it.",
803 REJECTED, true);
805 // Try a badly formatted key. Assume that the JSON parser is fully tested,
806 // so we won't try a lot of combinations. However, need a test to ensure
807 // that the code doesn't crash if invalid JSON received.
808 UpdateSessionAndExpect(session_id, "This is not a JSON key.", REJECTED, true);
810 // Try passing some valid JSON that is not a dictionary at the top level.
811 UpdateSessionAndExpect(session_id, "40", REJECTED, true);
813 // Try an empty dictionary.
814 UpdateSessionAndExpect(session_id, "{ }", REJECTED, true);
816 // Try an empty 'keys' dictionary.
817 UpdateSessionAndExpect(session_id, "{ \"keys\": [] }", REJECTED, true);
819 // Try with 'keys' not a dictionary.
820 UpdateSessionAndExpect(session_id, "{ \"keys\":\"1\" }", REJECTED, true);
822 // Try with 'keys' a list of integers.
823 UpdateSessionAndExpect(session_id, "{ \"keys\": [ 1, 2, 3 ] }", REJECTED,
824 true);
826 // Try padding(=) at end of 'k' base64 string.
827 const std::string kJwksWithPaddedKey =
829 " \"keys\": ["
830 " {"
831 " \"kty\": \"oct\","
832 " \"alg\": \"A128KW\","
833 " \"kid\": \"AAECAw\","
834 " \"k\": \"BAUGBwgJCgsMDQ4PEBESEw==\""
835 " }"
836 " ]"
837 "}";
838 UpdateSessionAndExpect(session_id, kJwksWithPaddedKey, REJECTED, true);
840 // Try padding(=) at end of 'kid' base64 string.
841 const std::string kJwksWithPaddedKeyId =
843 " \"keys\": ["
844 " {"
845 " \"kty\": \"oct\","
846 " \"alg\": \"A128KW\","
847 " \"kid\": \"AAECAw==\","
848 " \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
849 " }"
850 " ]"
851 "}";
852 UpdateSessionAndExpect(session_id, kJwksWithPaddedKeyId, REJECTED, true);
854 // Try a key with invalid base64 encoding.
855 const std::string kJwksWithInvalidBase64 =
857 " \"keys\": ["
858 " {"
859 " \"kty\": \"oct\","
860 " \"alg\": \"A128KW\","
861 " \"kid\": \"!@#$%^&*()\","
862 " \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
863 " }"
864 " ]"
865 "}";
866 UpdateSessionAndExpect(session_id, kJwksWithInvalidBase64, REJECTED, true);
868 // Try a 3-byte 'kid' where no base64 padding is required.
869 // |kJwksMultipleEntries| above has 2 'kid's that require 1 and 2 padding
870 // bytes. Note that 'k' has to be 16 bytes, so it will always require padding.
871 const std::string kJwksWithNoPadding =
873 " \"keys\": ["
874 " {"
875 " \"kty\": \"oct\","
876 " \"alg\": \"A128KW\","
877 " \"kid\": \"Kiss\","
878 " \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
879 " }"
880 " ]"
881 "}";
882 UpdateSessionAndExpect(session_id, kJwksWithNoPadding, RESOLVED, true);
884 // Empty key id.
885 const std::string kJwksWithEmptyKeyId =
887 " \"keys\": ["
888 " {"
889 " \"kty\": \"oct\","
890 " \"alg\": \"A128KW\","
891 " \"kid\": \"\","
892 " \"k\": \"BAUGBwgJCgsMDQ4PEBESEw\""
893 " }"
894 " ]"
895 "}";
896 UpdateSessionAndExpect(session_id, kJwksWithEmptyKeyId, REJECTED, true);
897 CloseSession(session_id);
900 TEST_F(AesDecryptorTest, GetKeyIds) {
901 std::vector<uint8> key_id1(kKeyId, kKeyId + arraysize(kKeyId));
902 std::vector<uint8> key_id2(kKeyId2, kKeyId2 + arraysize(kKeyId2));
904 std::string session_id = CreateSession(key_id_);
905 EXPECT_FALSE(KeysInfoContains(key_id1));
906 EXPECT_FALSE(KeysInfoContains(key_id2));
908 // Add 1 key, verify it is returned.
909 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
910 EXPECT_TRUE(KeysInfoContains(key_id1));
911 EXPECT_FALSE(KeysInfoContains(key_id2));
913 // Add second key, verify both IDs returned.
914 UpdateSessionAndExpect(session_id, kKey2AsJWK, RESOLVED, true);
915 EXPECT_TRUE(KeysInfoContains(key_id1));
916 EXPECT_TRUE(KeysInfoContains(key_id2));
919 TEST_F(AesDecryptorTest, NoKeysChangeForSameKey) {
920 std::vector<uint8> key_id(kKeyId, kKeyId + arraysize(kKeyId));
922 std::string session_id = CreateSession(key_id_);
923 EXPECT_FALSE(KeysInfoContains(key_id));
925 // Add key, verify it is returned.
926 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, true);
927 EXPECT_TRUE(KeysInfoContains(key_id));
929 // Add key a second time.
930 UpdateSessionAndExpect(session_id, kKeyAsJWK, RESOLVED, false);
931 EXPECT_TRUE(KeysInfoContains(key_id));
933 // Create a new session. Add key, should indicate key added for this session.
934 std::string session_id2 = CreateSession(key_id_);
935 UpdateSessionAndExpect(session_id2, kKeyAsJWK, RESOLVED, true);
938 } // namespace media