4
0

RemoteInstrumentEditsTests.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. #include "engine/RemoteInstrumentEdits.h"
  2. #include "engine/RemoteJsonLimits.h"
  3. #include "engine/RemoteAuthentication.h"
  4. #include <cstdio>
  5. #include <stdexcept>
  6. using namespace lynx;
  7. namespace
  8. {
  9. void check (bool condition, const char* message)
  10. {
  11. if (! condition) throw std::runtime_error (message);
  12. }
  13. template <typename Fn> void refuses (Fn&& fn)
  14. {
  15. bool rejected = false;
  16. try { fn(); } catch (const std::runtime_error&) { rejected = true; }
  17. check (rejected, "invalid instrument transaction was accepted");
  18. }
  19. Song fixture()
  20. {
  21. Song song;
  22. song.channels.resize (3);
  23. song.channels[0].instrument = InstrumentKind::layer;
  24. song.channels[0].layer.children = { 1, 2 };
  25. auto& channel = song.channels[1];
  26. channel.name = "Lead";
  27. channel.instrument = InstrumentKind::plugin;
  28. channel.plugin.id = "existing synth";
  29. channel.plugin.state = "existing state";
  30. channel.uid = 1234;
  31. channel.mixerTrack = 2;
  32. channel.volume = 0.23f;
  33. channel.pan = -0.4f;
  34. channel.muted = true;
  35. channel.group = 4;
  36. channel.swingMix = 0.13f;
  37. channel.colour = 0xff112233;
  38. channel.maxPolyphony = 4;
  39. channel.cutGroup = 2;
  40. channel.cutBy = 3;
  41. channel.keyLabels[60] = "C custom";
  42. channel.ghostHidden = true;
  43. channel.soloLock = true;
  44. channel.keyLow = 30;
  45. channel.keyHigh = 90;
  46. channel.receiveFrom = "Controller";
  47. channel.receiveMidiChannel = 3;
  48. channel.icon = 42;
  49. song.channels[2].instrument = InstrumentKind::audioClip;
  50. song.mixer.resize (4);
  51. song.patterns.resize (1);
  52. Note note;
  53. note.channel = 1;
  54. note.velocity = 0.44f;
  55. note.slide = true;
  56. note.modX = 0.21f;
  57. song.patterns[0].notes.push_back (note);
  58. song.patterns[0].channelLoops.push_back ({ 1, 8 });
  59. PatternEvents lane;
  60. lane.target = { AutomationTargetKind::channelParam, 1, 0, 3 };
  61. lane.events.push_back ({ 100, 0.8f });
  62. song.patterns[0].events.push_back (lane);
  63. Automation automation;
  64. automation.target = { AutomationTargetKind::channelVolume, 1 };
  65. automation.source.channel = 1;
  66. automation.points.push_back ({ 0, 0.25f });
  67. song.automations.push_back (automation);
  68. Clip clip;
  69. clip.kind = ClipKind::audio;
  70. clip.channel = 2;
  71. clip.length = 960;
  72. song.playlist.push_back (clip);
  73. song.arrangements.push_back ({ "Other", { clip } });
  74. return song;
  75. }
  76. void instrumentEdits()
  77. {
  78. const auto original = fixture();
  79. ChannelDef generator;
  80. generator.instrument = InstrumentKind::snare;
  81. generator.name = "New Snare";
  82. auto inserted = remote_instruments::create (original, generator, 1, 3);
  83. const auto& song = inserted.song;
  84. check (inserted.channelIndex == 1 && song.channels.size() == 4, "middle insertion failed");
  85. check (song.channels[1].mixerTrack == 3 && song.channels[1].instrument == InstrumentKind::snare, "selected generator or route lost");
  86. check (song.channels[2] == original.channels[1] && song.channels[2].instance.id == original.channels[1].instance.id,
  87. "middle insertion changed an existing hosted channel/instance");
  88. auto expectedNote = original.patterns[0].notes[0];
  89. expectedNote.channel = 2;
  90. check (song.patterns[0].notes[0] == expectedNote, "note insertion remap lost note expression");
  91. check (song.patterns[0].channelLoops[0].channel == 2 && song.patterns[0].channelLoops[0].setting == 8, "loop reference was not remapped");
  92. check (song.automations[0].target.index == 2 && song.automations[0].source.channel == 2, "automation references were not remapped");
  93. check (song.patterns[0].events[0].target.index == 2 && song.patterns[0].events[0].events == original.patterns[0].events[0].events,
  94. "pattern automation remap lost events");
  95. check (song.channels[0].layer.children == std::vector<int> ({ 2, 3 }), "Layer children were not remapped");
  96. check (song.playlist[0].channel == 3 && song.arrangements[1].clips[0].channel == 3, "audio sources were not remapped in every arrangement");
  97. check (original.channels.size() == 3 && original.patterns[0].notes[0].channel == 1, "staged insertion changed original");
  98. auto appended = remote_instruments::create (original, generator);
  99. check (appended.channelIndex == 3 && appended.song.channels.size() == 4, "default insertion did not append");
  100. check (appended.song.channels.back().mixerTrack != 2, "default insertion reused the occupied insert");
  101. check (appended.song.patterns == original.patterns && appended.song.automations == original.automations, "append remapped existing musical references");
  102. auto replaced = remote_instruments::replace (original, 1, generator);
  103. auto expected = original.channels[1];
  104. expected.instrument = generator.instrument;
  105. expected.name = generator.name;
  106. expected.plugin = generator.plugin;
  107. check (replaced.song.channels[1] == expected, "replacement lost channel identity/preferences or retained old plugin");
  108. check (replaced.song.channels[1].instance.id != original.channels[1].instance.id, "replacement reused the old runtime instrument instance");
  109. check (replaced.song.patterns == original.patterns && replaced.song.automations == original.automations
  110. && replaced.song.playlist == original.playlist, "replacement changed musical references");
  111. refuses ([&] { remote_instruments::create (original, generator, -1); });
  112. refuses ([&] { remote_instruments::create (original, generator, 4); });
  113. refuses ([&] { remote_instruments::create (original, generator, 1, 4); });
  114. refuses ([&] { remote_instruments::replace (original, 3, generator); });
  115. refuses ([&] { remote_instruments::replace (original, -1, generator); });
  116. check (original.channels[1].plugin.state == "existing state" && original.patterns[0].notes[0].channel == 1,
  117. "rejected transaction changed original model");
  118. }
  119. void authentication()
  120. {
  121. using namespace remote_auth;
  122. // RFC 4231 cases 1, 2, 3 and 6 include binary keys/data and a key
  123. // longer than SHA-256's block, independently checking the HMAC construction.
  124. check (hmacSha256 (std::string (20, '\x0b'), "Hi There") ==
  125. "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7", "RFC 4231 HMAC case 1 failed");
  126. check (hmacSha256 ("Jefe", "what do ya want for nothing?") ==
  127. "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843", "RFC 4231 HMAC case 2 failed");
  128. check (hmacSha256 (std::string (20, '\xaa'), std::string (50, '\xdd')) ==
  129. "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe", "RFC 4231 HMAC case 3 failed");
  130. check (hmacSha256 (std::string (131, '\xaa'), "Test Using Larger Than Block-Size Key - Hash Key First") ==
  131. "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54", "RFC 4231 HMAC long-key case failed");
  132. const auto key = std::string (64, 'a');
  133. const auto client = std::string ("0123456789abcdef0123456789abcdef");
  134. const auto server = std::string ("fedcba9876543210fedcba9876543210");
  135. const auto serverProof = proof (key, "server", client, server);
  136. const auto clientProof = proof (key, "client", client, server);
  137. // Independent Python hashlib/hmac vectors pin the ASCII token key and transcript.
  138. check (serverProof == "8dc31853f158358575e3b58b554d2bd73d555325a891b29c7bc5de90c3b4077a", "server proof transcript changed");
  139. check (clientProof == "2626f47afd5c951ff3c7147d1aed38a9443f7aedf728b2471db8acde57a2b12c", "client proof transcript changed");
  140. check (! constantTimeEqual (serverProof, clientProof), "server proof could be reflected as client authentication");
  141. check (! constantTimeEqual (clientProof, proof (key, "client", client, std::string (32, '0'))), "proof could be replayed for a fresh server nonce");
  142. check (! constantTimeEqual (clientProof, proof (std::string (64, 'b'), "client", client, server)), "wrong key proof authenticated");
  143. auto changed = clientProof;
  144. changed.back() = changed.back() == '0' ? '1' : '0';
  145. check (! constantTimeEqual (changed, clientProof), "changed proof authenticated");
  146. check (constantTimeEqual (clientProof, clientProof), "correct proof rejected");
  147. check (isLowerHex (client, 32) && ! isLowerHex (std::string (32, 'A'), 32)
  148. && ! isLowerHex (client + "0", 32), "nonce format validation failed");
  149. }
  150. void jsonNesting()
  151. {
  152. using remote_json::withinNestingLimit;
  153. check (withinNestingLimit (std::string (64, '[') + "0" + std::string (64, ']')), "nesting boundary was rejected");
  154. check (! withinNestingLimit (std::string (65, '[') + "0" + std::string (65, ']')), "over-nested unauthenticated array was accepted");
  155. check (! withinNestingLimit (std::string (100000, '['), 8), "pre-auth crash payload was accepted");
  156. check (! withinNestingLimit (std::string (100000, '[')), "authenticated crash payload was accepted");
  157. check (withinNestingLimit (std::string (8, '[') + "0" + std::string (8, ']'), 8), "handshake nesting boundary was rejected");
  158. check (! withinNestingLimit (std::string (9, '[') + "0" + std::string (9, ']'), 8), "over-nested handshake was accepted");
  159. std::string objects;
  160. for (int i = 0; i < 65; ++i) objects += "{\"x\":";
  161. check (! withinNestingLimit (objects + "0" + std::string (65, '}')), "over-nested objects were accepted");
  162. check (withinNestingLimit ("{\"name\":\"" + std::string (1000, '[') + "\"}"), "string data counted toward nesting");
  163. check (withinNestingLimit (R"json({"escaped":"\"[[[[\\","x":[0]})json", 2), "escaped quote or slash corrupted nesting count");
  164. check (! withinNestingLimit (R"json({"escaped":"\\","x":[[0]]})json", 2), "escaped slash hid actual nesting");
  165. check (withinNestingLimit (R"json({'name':'"[[[[',"x":[0]})json", 2), "single-quoted string data counted toward nesting");
  166. check (withinNestingLimit (R"json({'escaped':'\'[[[[',"x":[0]})json", 2), "escaped single quote corrupted nesting count");
  167. for (const auto limit : { 8u, 64u })
  168. {
  169. const auto deep = std::string (limit, '[') + "0" + std::string (limit, ']');
  170. check (! withinNestingLimit ("['\"'," + deep + "]", limit), "single-quoted double quote hid actual nesting");
  171. check (! withinNestingLimit ("{\"x\":'\"',\"deep\":" + deep + "}", limit), "mixed-quote object hid actual nesting");
  172. check (! withinNestingLimit ("['\\'\"'," + deep + "]", limit), "escaped single quote hid actual nesting");
  173. }
  174. }
  175. void jsonUtf8()
  176. {
  177. using remote_json::withinNestingLimit;
  178. for (const auto& valid : { std::string ("\xc2\x80"), std::string ("\xdf\xbf"), std::string ("\xe0\xa0\x80"),
  179. std::string ("\xed\x9f\xbf"), std::string ("\xee\x80\x80"), std::string ("\xef\xbf\xbf"),
  180. std::string ("\xf0\x90\x80\x80"), std::string ("\xf4\x8f\xbf\xbf"),
  181. std::string ("\xe9\x9f\xb3\xe6\xa8\x82\xf0\x9f\x8e\xb5") })
  182. check (withinNestingLimit ("{\"text\":\"" + valid + "\",\"array\":[0]}", 2), "canonical Unicode JSON was rejected");
  183. for (const auto& invalid : { std::string ("\x80"), std::string ("\xbf"), std::string ("\xc0\x80"), std::string ("\xc1\x9b"),
  184. std::string ("\xc2"), std::string ("\xc2\x7f"), std::string ("\xc3\x20"),
  185. std::string ("\xe0\x9f\xbf"), std::string ("\xe1\x80"), std::string ("\xe1\x80\x7f"),
  186. std::string ("\xed\xa0\x80"), std::string ("\xed\xbf\xbf"),
  187. std::string ("\xf0\x8f\xbf\xbf"), std::string ("\xf0\x90\x80"), std::string ("\xf1\x80\x80\x7f"),
  188. std::string ("\xf4\x90\x80\x80"), std::string ("\xf5\x80\x80\x80"),
  189. std::string ("\xfe"), std::string ("\xff"), std::string (1, '\0') })
  190. check (! withinNestingLimit ("{\"text\":\"" + invalid + "\"}"), "noncanonical UTF-8 or raw NUL reached the JSON parser");
  191. check (withinNestingLimit (R"({"nul":"\u0000","bracket":"\u005b"})", 1), "escaped Unicode syntax was rejected");
  192. for (const auto limit : { 8u, 64u })
  193. {
  194. // JUCE 8.0.4 decodes these malformed two-byte sequences to recursive
  195. // array delimiters; a raw ASCII-only depth scan used to miss all of them.
  196. std::string attack = "[";
  197. for (unsigned int i = 0; i < limit + 1; ++i) attack += "\xc1\x9b";
  198. attack += "0";
  199. for (unsigned int i = 0; i < limit + 1; ++i) attack += "\xc1\x9d";
  200. attack += "]";
  201. check (! withinNestingLimit (attack, limit), "overlong UTF-8 delimiters bypassed the nesting guard");
  202. }
  203. }
  204. }
  205. int main()
  206. {
  207. try
  208. {
  209. instrumentEdits();
  210. jsonNesting();
  211. jsonUtf8();
  212. authentication();
  213. std::puts ("Remote instrument edits, JSON nesting and authentication tests passed");
  214. return 0;
  215. }
  216. catch (const std::exception& error)
  217. {
  218. std::fprintf (stderr, "%s\n", error.what());
  219. return 1;
  220. }
  221. }