Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / media / cdm / json_web_key.cc
blobf60c6f5b10267e2d775f8a9c65e1bf3a8b942476
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 "media/cdm/json_web_key.h"
7 #include "base/base64.h"
8 #include "base/json/json_reader.h"
9 #include "base/json/json_string_value_serializer.h"
10 #include "base/json/string_escape.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "base/values.h"
17 namespace media {
19 const char kKeysTag[] = "keys";
20 const char kKeyTypeTag[] = "kty";
21 const char kKeyTypeOct[] = "oct"; // Octet sequence.
22 const char kKeyTag[] = "k";
23 const char kKeyIdTag[] = "kid";
24 const char kKeyIdsTag[] = "kids";
25 const char kBase64Padding = '=';
26 const char kBase64Plus[] = "+";
27 const char kBase64UrlPlusReplacement[] = "-";
28 const char kBase64Slash[] = "/";
29 const char kBase64UrlSlashReplacement[] = "_";
30 const char kBase64UrlInvalid[] = "+/=";
31 const char kTypeTag[] = "type";
32 const char kTemporarySession[] = "temporary";
33 const char kPersistentLicenseSession[] = "persistent-license";
34 const char kPersistentReleaseMessageSession[] = "persistent-release-message";
36 // Encodes |input| into a base64url string without padding.
37 static std::string EncodeBase64Url(const uint8* input, int input_length) {
38 std::string encoded_text;
39 base::Base64Encode(
40 std::string(reinterpret_cast<const char*>(input), input_length),
41 &encoded_text);
43 // Remove any padding characters added by Base64Encode().
44 size_t found = encoded_text.find_last_not_of(kBase64Padding);
45 if (found != std::string::npos)
46 encoded_text.erase(found + 1);
48 // base64url encoding means the characters '-' and '_' must be used
49 // instead of '+' and '/', respectively.
50 base::ReplaceChars(encoded_text, kBase64Plus, kBase64UrlPlusReplacement,
51 &encoded_text);
52 base::ReplaceChars(encoded_text, kBase64Slash, kBase64UrlSlashReplacement,
53 &encoded_text);
55 return encoded_text;
58 // Decodes a base64url string. Returns empty string on error.
59 static std::string DecodeBase64Url(const std::string& encoded_text) {
60 // EME spec doesn't allow '+', '/', or padding characters.
61 if (encoded_text.find_first_of(kBase64UrlInvalid) != std::string::npos) {
62 DVLOG(1) << "Invalid base64url format: " << encoded_text;
63 return std::string();
66 // Since base::Base64Decode() requires padding characters, add them so length
67 // of |encoded_text| is exactly a multiple of 4.
68 size_t num_last_grouping_chars = encoded_text.length() % 4;
69 std::string modified_text = encoded_text;
70 if (num_last_grouping_chars > 0)
71 modified_text.append(4 - num_last_grouping_chars, kBase64Padding);
73 // base64url encoding means the characters '-' and '_' must be used
74 // instead of '+' and '/', respectively, so replace them before calling
75 // base::Base64Decode().
76 base::ReplaceChars(modified_text, kBase64UrlPlusReplacement, kBase64Plus,
77 &modified_text);
78 base::ReplaceChars(modified_text, kBase64UrlSlashReplacement, kBase64Slash,
79 &modified_text);
81 std::string decoded_text;
82 if (!base::Base64Decode(modified_text, &decoded_text)) {
83 DVLOG(1) << "Base64 decoding failed on: " << modified_text;
84 return std::string();
87 return decoded_text;
90 static std::string ShortenTo64Characters(const std::string& input) {
91 // Convert |input| into a string with escaped characters replacing any
92 // non-ASCII characters. Limiting |input| to the first 65 characters so
93 // we don't waste time converting a potentially long string and then
94 // throwing away the excess.
95 std::string escaped_str =
96 base::EscapeBytesAsInvalidJSONString(input.substr(0, 65), false);
97 if (escaped_str.length() <= 64u)
98 return escaped_str;
100 // This may end up truncating an escaped character, but the first part of
101 // the string should provide enough information.
102 return escaped_str.substr(0, 61).append("...");
105 std::string GenerateJWKSet(const uint8* key, int key_length,
106 const uint8* key_id, int key_id_length) {
107 // Both |key| and |key_id| need to be base64 encoded strings in the JWK.
108 std::string key_base64 = EncodeBase64Url(key, key_length);
109 std::string key_id_base64 = EncodeBase64Url(key_id, key_id_length);
111 // Create the JWK, and wrap it into a JWK Set.
112 scoped_ptr<base::DictionaryValue> jwk(new base::DictionaryValue());
113 jwk->SetString(kKeyTypeTag, kKeyTypeOct);
114 jwk->SetString(kKeyTag, key_base64);
115 jwk->SetString(kKeyIdTag, key_id_base64);
116 scoped_ptr<base::ListValue> list(new base::ListValue());
117 list->Append(jwk.release());
118 base::DictionaryValue jwk_set;
119 jwk_set.Set(kKeysTag, list.release());
121 // Finally serialize |jwk_set| into a string and return it.
122 std::string serialized_jwk;
123 JSONStringValueSerializer serializer(&serialized_jwk);
124 serializer.Serialize(jwk_set);
125 return serialized_jwk;
128 // Processes a JSON Web Key to extract the key id and key value. Sets |jwk_key|
129 // to the id/value pair and returns true on success.
130 static bool ConvertJwkToKeyPair(const base::DictionaryValue& jwk,
131 KeyIdAndKeyPair* jwk_key) {
132 std::string type;
133 if (!jwk.GetString(kKeyTypeTag, &type) || type != kKeyTypeOct) {
134 DVLOG(1) << "Missing or invalid '" << kKeyTypeTag << "': " << type;
135 return false;
138 // Get the key id and actual key parameters.
139 std::string encoded_key_id;
140 std::string encoded_key;
141 if (!jwk.GetString(kKeyIdTag, &encoded_key_id)) {
142 DVLOG(1) << "Missing '" << kKeyIdTag << "' parameter";
143 return false;
145 if (!jwk.GetString(kKeyTag, &encoded_key)) {
146 DVLOG(1) << "Missing '" << kKeyTag << "' parameter";
147 return false;
150 // Key ID and key are base64-encoded strings, so decode them.
151 std::string raw_key_id = DecodeBase64Url(encoded_key_id);
152 if (raw_key_id.empty()) {
153 DVLOG(1) << "Invalid '" << kKeyIdTag << "' value: " << encoded_key_id;
154 return false;
157 std::string raw_key = DecodeBase64Url(encoded_key);
158 if (raw_key.empty()) {
159 DVLOG(1) << "Invalid '" << kKeyTag << "' value: " << encoded_key;
160 return false;
163 // Add the decoded key ID and the decoded key to the list.
164 *jwk_key = std::make_pair(raw_key_id, raw_key);
165 return true;
168 bool ExtractKeysFromJWKSet(const std::string& jwk_set,
169 KeyIdAndKeyPairs* keys,
170 MediaKeys::SessionType* session_type) {
171 if (!base::IsStringASCII(jwk_set)) {
172 DVLOG(1) << "Non ASCII JWK Set: " << jwk_set;
173 return false;
176 scoped_ptr<base::Value> root(base::JSONReader().ReadToValue(jwk_set));
177 if (!root.get() || root->GetType() != base::Value::TYPE_DICTIONARY) {
178 DVLOG(1) << "Not valid JSON: " << jwk_set << ", root: " << root.get();
179 return false;
182 // Locate the set from the dictionary.
183 base::DictionaryValue* dictionary =
184 static_cast<base::DictionaryValue*>(root.get());
185 base::ListValue* list_val = NULL;
186 if (!dictionary->GetList(kKeysTag, &list_val)) {
187 DVLOG(1) << "Missing '" << kKeysTag
188 << "' parameter or not a list in JWK Set";
189 return false;
192 // Create a local list of keys, so that |jwk_keys| only gets updated on
193 // success.
194 KeyIdAndKeyPairs local_keys;
195 for (size_t i = 0; i < list_val->GetSize(); ++i) {
196 base::DictionaryValue* jwk = NULL;
197 if (!list_val->GetDictionary(i, &jwk)) {
198 DVLOG(1) << "Unable to access '" << kKeysTag << "'[" << i
199 << "] in JWK Set";
200 return false;
202 KeyIdAndKeyPair key_pair;
203 if (!ConvertJwkToKeyPair(*jwk, &key_pair)) {
204 DVLOG(1) << "Error from '" << kKeysTag << "'[" << i << "]";
205 return false;
207 local_keys.push_back(key_pair);
210 // Successfully processed all JWKs in the set. Now check if "type" is
211 // specified.
212 base::Value* value = NULL;
213 std::string session_type_id;
214 if (!dictionary->Get(kTypeTag, &value)) {
215 // Not specified, so use the default type.
216 *session_type = MediaKeys::TEMPORARY_SESSION;
217 } else if (!value->GetAsString(&session_type_id)) {
218 DVLOG(1) << "Invalid '" << kTypeTag << "' value";
219 return false;
220 } else if (session_type_id == kTemporarySession) {
221 *session_type = MediaKeys::TEMPORARY_SESSION;
222 } else if (session_type_id == kPersistentLicenseSession) {
223 *session_type = MediaKeys::PERSISTENT_LICENSE_SESSION;
224 } else if (session_type_id == kPersistentReleaseMessageSession) {
225 *session_type = MediaKeys::PERSISTENT_RELEASE_MESSAGE_SESSION;
226 } else {
227 DVLOG(1) << "Invalid '" << kTypeTag << "' value: " << session_type_id;
228 return false;
231 // All done.
232 keys->swap(local_keys);
233 return true;
236 bool ExtractKeyIdsFromKeyIdsInitData(const std::string& input,
237 KeyIdList* key_ids,
238 std::string* error_message) {
239 if (!base::IsStringASCII(input)) {
240 error_message->assign("Non ASCII: ");
241 error_message->append(ShortenTo64Characters(input));
242 return false;
245 scoped_ptr<base::Value> root(base::JSONReader().ReadToValue(input));
246 if (!root.get() || root->GetType() != base::Value::TYPE_DICTIONARY) {
247 error_message->assign("Not valid JSON: ");
248 error_message->append(ShortenTo64Characters(input));
249 return false;
252 // Locate the set from the dictionary.
253 base::DictionaryValue* dictionary =
254 static_cast<base::DictionaryValue*>(root.get());
255 base::ListValue* list_val = NULL;
256 if (!dictionary->GetList(kKeyIdsTag, &list_val)) {
257 error_message->assign("Missing '");
258 error_message->append(kKeyIdsTag);
259 error_message->append("' parameter or not a list");
260 return false;
263 // Create a local list of key ids, so that |key_ids| only gets updated on
264 // success.
265 KeyIdList local_key_ids;
266 for (size_t i = 0; i < list_val->GetSize(); ++i) {
267 std::string encoded_key_id;
268 if (!list_val->GetString(i, &encoded_key_id)) {
269 error_message->assign("'");
270 error_message->append(kKeyIdsTag);
271 error_message->append("'[");
272 error_message->append(base::UintToString(i));
273 error_message->append("] is not string.");
274 return false;
277 // Key ID is a base64-encoded string, so decode it.
278 std::string raw_key_id = DecodeBase64Url(encoded_key_id);
279 if (raw_key_id.empty()) {
280 error_message->assign("'");
281 error_message->append(kKeyIdsTag);
282 error_message->append("'[");
283 error_message->append(base::UintToString(i));
284 error_message->append("] is not valid base64url encoded. Value: ");
285 error_message->append(ShortenTo64Characters(encoded_key_id));
286 return false;
289 // Add the decoded key ID to the list.
290 local_key_ids.push_back(std::vector<uint8>(
291 raw_key_id.data(), raw_key_id.data() + raw_key_id.length()));
294 // All done.
295 key_ids->swap(local_key_ids);
296 error_message->clear();
297 return true;
300 void CreateLicenseRequest(const KeyIdList& key_ids,
301 MediaKeys::SessionType session_type,
302 std::vector<uint8>* license) {
303 // Create the license request.
304 scoped_ptr<base::DictionaryValue> request(new base::DictionaryValue());
305 scoped_ptr<base::ListValue> list(new base::ListValue());
306 for (const auto& key_id : key_ids)
307 list->AppendString(EncodeBase64Url(&key_id[0], key_id.size()));
308 request->Set(kKeyIdsTag, list.release());
310 switch (session_type) {
311 case MediaKeys::TEMPORARY_SESSION:
312 request->SetString(kTypeTag, kTemporarySession);
313 break;
314 case MediaKeys::PERSISTENT_LICENSE_SESSION:
315 request->SetString(kTypeTag, kPersistentLicenseSession);
316 break;
317 case MediaKeys::PERSISTENT_RELEASE_MESSAGE_SESSION:
318 request->SetString(kTypeTag, kPersistentReleaseMessageSession);
319 break;
322 // Serialize the license request as a string.
323 std::string json;
324 JSONStringValueSerializer serializer(&json);
325 serializer.Serialize(*request);
327 // Convert the serialized license request into std::vector and return it.
328 std::vector<uint8> result(json.begin(), json.end());
329 license->swap(result);
332 void CreateKeyIdsInitData(const KeyIdList& key_ids,
333 std::vector<uint8>* init_data) {
334 // Create the init_data.
335 scoped_ptr<base::DictionaryValue> dictionary(new base::DictionaryValue());
336 scoped_ptr<base::ListValue> list(new base::ListValue());
337 for (const auto& key_id : key_ids)
338 list->AppendString(EncodeBase64Url(&key_id[0], key_id.size()));
339 dictionary->Set(kKeyIdsTag, list.release());
341 // Serialize the dictionary as a string.
342 std::string json;
343 JSONStringValueSerializer serializer(&json);
344 serializer.Serialize(*dictionary);
346 // Convert the serialized data into std::vector and return it.
347 std::vector<uint8> result(json.begin(), json.end());
348 init_data->swap(result);
351 bool ExtractFirstKeyIdFromLicenseRequest(const std::vector<uint8>& license,
352 std::vector<uint8>* first_key) {
353 const std::string license_as_str(
354 reinterpret_cast<const char*>(!license.empty() ? &license[0] : NULL),
355 license.size());
356 if (!base::IsStringASCII(license_as_str)) {
357 DVLOG(1) << "Non ASCII license: " << license_as_str;
358 return false;
361 scoped_ptr<base::Value> root(base::JSONReader().ReadToValue(license_as_str));
362 if (!root.get() || root->GetType() != base::Value::TYPE_DICTIONARY) {
363 DVLOG(1) << "Not valid JSON: " << license_as_str;
364 return false;
367 // Locate the set from the dictionary.
368 base::DictionaryValue* dictionary =
369 static_cast<base::DictionaryValue*>(root.get());
370 base::ListValue* list_val = NULL;
371 if (!dictionary->GetList(kKeyIdsTag, &list_val)) {
372 DVLOG(1) << "Missing '" << kKeyIdsTag << "' parameter or not a list";
373 return false;
376 // Get the first key.
377 if (list_val->GetSize() < 1) {
378 DVLOG(1) << "Empty '" << kKeyIdsTag << "' list";
379 return false;
382 std::string encoded_key;
383 if (!list_val->GetString(0, &encoded_key)) {
384 DVLOG(1) << "First entry in '" << kKeyIdsTag << "' not a string";
385 return false;
388 std::string decoded_string = DecodeBase64Url(encoded_key);
389 if (decoded_string.empty()) {
390 DVLOG(1) << "Invalid '" << kKeyIdsTag << "' value: " << encoded_key;
391 return false;
394 std::vector<uint8> result(decoded_string.begin(), decoded_string.end());
395 first_key->swap(result);
396 return true;
399 } // namespace media