keenlabs / keen-sdk-net

A .NET SDK for the Keen IO API
MIT License
37 stars 23 forks source link

Scoped Keys Are Malformed, resulting in "401 Unauthorized" #4

Closed wetzler closed 10 years ago

wetzler commented 10 years ago

Encrypted keys generated by the .NET library are invalid. When used for querying they produce a "401 Unauthorized". When tested using the Keen Decrypter, the keys return valid, and sometimes invalid results depending on IV.

A scoped key generated using 32 byte IV, when decrypted, looks something like:

��t=��pR�����D�ki�� �Z��T�˄�yN"T-�t َJɦ�5��փ���FG��gIQ�� }:�I�m��F׵W!VR��g�=O�f���f�xJ�,!�Ǎ���l{��E�� ��?:�vХB3f���\5���y�G?���z�����n�bQ,�@�t�Ip.�& �z骯W�o���"_EZw� ��

A scoped key generated using an empty string for IV, when decrypted:

{ 'filters': [{ 'property_name': 'v_id', 'operator': 'eq', 'property_value': 'a-valid-value' }], 'allowed_operations': [ 'read' ] }

Neither key works for querying; both return "401".

Groove ticket with customer example: https://keen-io.groovehq.com/groove_client/mailboxes/4308/filters/51671/tickets/2300068

davidknaack commented 10 years ago

If an IV is required (it usually should not be, the library will generate it), start with a 16 byte buffer and hex encode it to generate a 32 character string. This string is then passed to the encode function, and will appear as the first 32 characters of the scoped key:

var rnd = new System.Security.Cryptography.RNGCryptoServiceProvider(); byte[] bytes = new byte[16]; rnd.GetBytes(bytes);
var IV = String.Concat(bytes.Select(b => b.ToString("X2"))); var scopedKey = ScopedKey.EncryptString(keenMasterKey, str, IV );

The keys returning '401':

{ 'filters': [{ 'property_name': 'v_id', 'operator': 'eq', 'property_value': 'a-valid-value' }], 'allowed_operations': [ 'read' ] }

are malformed JSON. The Keen.IO API requires double quotes. See the syntax diagram at http://json.org for details. A key like the following should work:

{ "filters": [{ "property_name": "v_id", "operator": "eq", "property_value": "a-valid-value" }], "allowed_operations": [ "read" ] }

wetzler commented 10 years ago

Thanks so much, David! Good to know and I'll make sure to pass this onto the developer who encountered it.

wetzler commented 10 years ago

The developer confirmed that this resolved their issue. "I tested with (and without) IV, and it now works in both cases :)"