From e2bdcf5fe581cc68b9b75f356ae341fbbe2b8f38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Klemen=20Tu=C5=A1ar?= Date: Fri, 5 Apr 2024 09:51:08 +0200 Subject: [PATCH] :safety_vest: prevent Utils.encode from calling toString on complex types --- lib/src/utils.dart | 10 ++++++++++ test/unit/utils_test.dart | 35 ++++++++++++++++------------------- 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/lib/src/utils.dart b/lib/src/utils.dart index 958ee67..28f3295 100644 --- a/lib/src/utils.dart +++ b/lib/src/utils.dart @@ -225,6 +225,16 @@ final class Utils { Encoding charset = utf8, Format? format = Format.rfc3986, }) { + // these can not be encoded + if (value is Iterable || + value is Map || + value is Symbol || + value is Record || + value is Future || + value is Undefined) { + return ''; + } + final String? str = value is ByteBuffer ? charset.decode(value.asUint8List()) : value?.toString(); diff --git a/test/unit/utils_test.dart b/test/unit/utils_test.dart index 552ff6f..d5cb9c8 100644 --- a/test/unit/utils_test.dart +++ b/test/unit/utils_test.dart @@ -27,28 +27,25 @@ void main() { ); expect(DummyEnum.lorem, isA()); expect(Utils.encode(DummyEnum.lorem), equals('lorem')); + + // does not encode + // Iterable + expect(Utils.encode([1, 2]), equals('')); + // Map + expect(Utils.encode({'a': 'b'}), equals('')); + // Symbol + expect(Utils.encode(#a), equals('')); + // Record + expect(Utils.encode(('a', 'b')), equals('')); + // Future expect( - Utils.encode({ - 'foo': 'bar', - 'baz': [ - {'a': 'b'}, - {'c': DummyEnum.dolor}, - ], - }), - equals( - '%7Bfoo%3A%20bar%2C%20baz%3A%20%5B%7Ba%3A%20b%7D%2C%20%7Bc%3A%20dolor%7D%5D%7D', - ), + Utils.encode(Future.value('b')), + equals(''), ); + // Undefined expect( - Utils.encode({ - 'filters': { - 'name': 'foo', - 'example': DummyEnum.lorem, - } - }), - equals( - '%7Bfilters%3A%20%7Bname%3A%20foo%2C%20example%3A%20lorem%7D%7D', - ), + Utils.encode(const Undefined()), + equals(''), ); });