Add type validation to non-template .arb file parsing logic (#139035)

Resolves https://github.com/flutter/flutter/issues/138297. 

When reading from a .arb file (which contains localizations of strings in the form of a user-defined JSON string-string map), validate the type of values that we read.

See [this comment of mine on #138297](https://github.com/flutter/flutter/issues/138297#issuecomment-1827043260) to see how I arrived at this fix.
This commit is contained in:
Andrew Kolos 2023-11-27 12:50:24 -08:00 committed by GitHub
parent e8282edf4d
commit 1952a6c8a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 1 deletions

View File

@ -4,6 +4,7 @@
import 'package:intl/locale.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../convert.dart';
@ -646,7 +647,14 @@ class AppResourceBundle {
final Map<String, Object?> resources;
final Iterable<String> resourceIds;
String? translationFor(String resourceId) => resources[resourceId] as String?;
String? translationFor(String resourceId) {
final Object? result = resources[resourceId];
if (result is! String?) {
throwToolExit('Localized message for key "$resourceId" in "${file.path}" '
'is not a string.');
}
return result;
}
@override
String toString() {

View File

@ -1241,6 +1241,34 @@ class AppLocalizationsEn extends AppLocalizations {
)),
);
});
testWithoutContext('AppResourceBundle throws if file contains non-string value', () {
const String inputPathString = 'lib/l10n';
const String templateArbFileName = 'app_en.arb';
const String outputFileString = 'app_localizations.dart';
const String classNameString = 'AppLocalizations';
fs.file(fs.path.join(inputPathString, templateArbFileName))
..createSync(recursive: true)
..writeAsStringSync('{ "helloWorld": "Hello World!" }');
fs.file(fs.path.join(inputPathString, 'app_es.arb'))
..createSync(recursive: true)
..writeAsStringSync('{ "helloWorld": {} }');
final LocalizationsGenerator generator = LocalizationsGenerator(
fileSystem: fs,
inputPathString: inputPathString,
templateArbFileName: templateArbFileName,
outputFileString: outputFileString,
classNameString: classNameString,
logger: logger,
);
expect(
() => generator.loadResources(),
throwsToolExit(message: 'Localized message for key "helloWorld" in '
'"lib/l10n/app_es.arb" is not a string.'),
);
});
});
group('writeOutputFiles', () {