4
0

RemoteProjectControlTests.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. #include "engine/RemoteProjectControl.h"
  2. #include "engine/RemoteJsonPatch.h"
  3. #include "engine/RemoteFileSecurity.h"
  4. #include "engine/ProjectFile.h"
  5. #include "engine/RemoteNotes.h"
  6. #include "core/SessionIds.h"
  7. #include "core/ClipLauncher.h"
  8. #include "core/PluginSubstitutes.h"
  9. #include "core/FlExtraFx.h"
  10. #include "core/VideoPlayer.h"
  11. #include "core/VisualFx.h"
  12. #include "core/Vfx.h"
  13. #include <cstdio>
  14. #include <stdexcept>
  15. #include <limits>
  16. using namespace lynx;
  17. namespace
  18. {
  19. void check (bool condition, const char* message)
  20. {
  21. if (! condition) throw std::runtime_error (message);
  22. }
  23. juce::var json (const char* text)
  24. {
  25. juce::var result;
  26. check (juce::JSON::parse (text, result).wasOk(), "Bad test JSON");
  27. return result;
  28. }
  29. template <class Fn> void refuses (Fn&& operation)
  30. {
  31. bool rejected = false;
  32. try { operation(); } catch (const std::runtime_error&) { rejected = true; }
  33. check (rejected, "Invalid transaction was accepted");
  34. }
  35. template <class Fn> void refusesWith (Fn&& operation, const char* reason)
  36. {
  37. std::string actual = "operation was accepted";
  38. try { operation(); }
  39. catch (const std::runtime_error& error)
  40. {
  41. actual = error.what();
  42. if (actual.find (reason) != std::string::npos) return;
  43. }
  44. throw std::runtime_error (std::string ("Expected rejection containing '") + reason + "', got: " + actual);
  45. }
  46. juce::var addValue (const char* path, const juce::var& value)
  47. {
  48. auto* operation = new juce::DynamicObject();
  49. operation->setProperty ("op", "add");
  50. operation->setProperty ("path", path);
  51. operation->setProperty ("value", value);
  52. return juce::Array<juce::var> { juce::var (operation) };
  53. }
  54. juce::String encoded (const std::vector<std::uint8_t>& bytes)
  55. {
  56. return juce::Base64::toBase64 (bytes.data(), bytes.size());
  57. }
  58. Song fixture()
  59. {
  60. Song song;
  61. ChannelDef channel;
  62. channel.name = "Lead";
  63. channel.synth.cutoff = 2432.12353515625f;
  64. channel.synth.resonance = 0.123456791f;
  65. channel.modelParams = { 0.123456791f, 1.23456788e-12f, 1.23456789e20f };
  66. channel.synth.spectrum[0] = 0.123456791f;
  67. channel.synth.spectrum[1] = 1.23456788e-12f;
  68. channel.synth.spectrumPhase[0] = 0.234567896f;
  69. channel.synth.spectrumDecay[0] = 2.12345672f;
  70. channel.synth.spectrumTarget[0] = 0.345678925f;
  71. channel.volume = 0.73123455f;
  72. song.channels.push_back (channel);
  73. song.mixer = Song::defaultMixer (2);
  74. song.mixer[1].volume = 0.812345683f;
  75. song.mixer[1].pan = -0.123456791f;
  76. song.mixer[1].stereo = 0.234567896f;
  77. song.mixer[1].sends.push_back ({ 2, 0.345678925f });
  78. song.mixer[1].lostSends.push_back ({ "Deleted insert", 0.456789017f });
  79. song.swing = 0.123456791f;
  80. song.chanceSeed = 0x89abcdefu;
  81. song.bpm = 130.12345678901235;
  82. Pattern pattern;
  83. pattern.name = "Lead";
  84. pattern.lengthTicks = 3840;
  85. Note note;
  86. note.channel = 0;
  87. note.start = 13;
  88. note.length = 1001;
  89. note.velocity = 0.73123455f;
  90. note.pan = 0.123456791f;
  91. note.finePitch = 4.56789112f;
  92. note.release = 0.456789017f;
  93. note.modX = 0.89123404f;
  94. note.modY = 0.345678925f;
  95. note.chance = 0.73123455f;
  96. note.velocityRange = 0.123456791f;
  97. note.chanceGroup = 7;
  98. note.chanceOne = true;
  99. pattern.notes.push_back (note);
  100. note.start = 1920;
  101. note.chance = 1.0f;
  102. note.velocityRange = 0.0f;
  103. note.chanceGroup = 0;
  104. pattern.notes.push_back (note); // Exact documents also preserve the inactive play-one flag.
  105. PatternEvents lane;
  106. lane.target = { AutomationTargetKind::channelVolume, 0 };
  107. lane.events.push_back ({ 17, 0.765432119f });
  108. pattern.events.push_back (lane);
  109. song.patterns.push_back (pattern);
  110. Automation automation;
  111. automation.name = "Level";
  112. automation.target = { AutomationTargetKind::channelVolume, 0 };
  113. automation.points.push_back ({ 0, 0.765432119f, 0.456789017f });
  114. song.automations.push_back (automation);
  115. Clip clip;
  116. clip.pattern = 0;
  117. clip.length = 3840;
  118. clip.gain = 0.123456791f;
  119. clip.offsetFraction = 0.234567896f;
  120. clip.pan = -0.345678925f;
  121. clip.pitch = 0.456789017f;
  122. clip.stretch = 1.123456789012345;
  123. song.playlist.push_back (clip);
  124. uids::normalize (song);
  125. return song;
  126. }
  127. #include "RemoteNotesTests.inc"
  128. void patchSemantics()
  129. {
  130. const auto source = json (R"({"a/b":{"~name":[1,2]},"x":1})");
  131. const auto result = remote_json::apply (source, json (R"([
  132. {"op":"test","path":"/x","value":1.0},
  133. {"op":"add","path":"/a~1b/~0name/1","value":3},
  134. {"op":"replace","path":"/x","value":4},
  135. {"op":"remove","path":"/a~1b/~0name/0"},
  136. {"op":"add","path":"/a~1b/~0name/-","value":5}
  137. ])"));
  138. check (remote_json::equal (result, json (R"({"a/b":{"~name":[3,2,5]},"x":4})")), "JSON Patch ordering/escaping differs");
  139. check (remote_json::equal (source, json (R"({"a/b":{"~name":[1,2]},"x":1})")), "Patching mutated its source");
  140. refuses ([&] { remote_json::apply (source, json (R"([{"op":"replace","path":"/x","value":3},{"op":"test","path":"/x","value":2}])")); });
  141. check (source["x"] == juce::var (1), "A failed later operation leaked an earlier change");
  142. refuses ([&] { remote_json::apply (source, json (R"([{"op":"test","path":"/x","value":1.00000001}])")); });
  143. refuses ([&] { remote_json::apply (source, json (R"([{"op":"add","path":"/a~1b/~0name/01","value":0}])")); });
  144. refuses ([&] { remote_json::apply (source, json (R"([{"op":"add","path":"/a~1b/~0name/4","value":0}])")); });
  145. refuses ([&] { remote_json::apply (source, json (R"([{"op":"replace","path":"/bad~2path","value":0}])")); });
  146. refuses ([&] { remote_json::apply (source, json (R"([{"op":"replace","path":"/missing","value":0}])")); });
  147. refuses ([&] { remote_json::apply (source, json (R"([{"op":"move","path":"/x","value":0}])")); });
  148. refuses ([&] { remote_json::apply (source, json (R"([{"op":"remove","path":"/x","value":0}])")); });
  149. refuses ([&] { remote_json::apply (source, json (R"([{"op":"replace","path":"/x","value":0,"extra":1}])")); });
  150. }
  151. void exactDocuments()
  152. {
  153. const auto source = fixture();
  154. const auto ordinary = ProjectFile::toJson (source);
  155. const auto exact = ProjectFile::toJsonExact (source);
  156. check (exact != ordinary, "Exact snapshots still use rounded save numbers");
  157. check (ProjectFile::toJson (source) == ordinary, "Exact serialization changed later ordinary saves");
  158. juce::String error;
  159. const auto loaded = ProjectFile::fromJson (exact, error);
  160. check (loaded.has_value(), "Exact project did not load");
  161. check (loaded->patterns == source.patterns && loaded->automations == source.automations
  162. && loaded->channels == source.channels && loaded->mixer == source.mixer
  163. && loaded->playlist == source.playlist && loaded->swing == source.swing
  164. && loaded->chanceSeed == source.chanceSeed,
  165. "Exact snapshots lost native float bits or unrequested data");
  166. const auto staged = remote_document::stage (source, json (R"([
  167. {"op":"test","path":"/bpm","value":130.12345678901235},
  168. {"op":"replace","path":"/bpm","value":142},
  169. {"op":"replace","path":"/patterns/0/name","value":"Verse"}
  170. ])"));
  171. auto expected = source;
  172. expected.bpm = 142;
  173. expected.patterns[0].name = "Verse";
  174. check (staged.bpm == 142 && staged.patterns == expected.patterns && staged.channels == source.channels
  175. && staged.mixer == source.mixer && staged.automations == source.automations && staged.playlist == source.playlist
  176. && staged.swing == source.swing && staged.chanceSeed == source.chanceSeed
  177. && staged.projectId == source.projectId && staged.nextUid == source.nextUid,
  178. "Metadata transaction changed unrelated native state");
  179. check (source.bpm == 130.12345678901235 && source.patterns[0].name == "Lead", "Staging mutated the live input");
  180. const auto onlyName = remote_document::stage (source, json (R"([{"op":"replace","path":"/patterns/0/name","value":"Only name"}])"));
  181. check (onlyName.bpm == source.bpm && onlyName.playlist[0].stretch == source.playlist[0].stretch,
  182. "Metadata-only edit changed unrelated double precision");
  183. check (remote_document::hash (remote_document::bytes (source)).size() == 64, "Document hash malformed");
  184. }
  185. void transactionValidation()
  186. {
  187. const auto source = fixture();
  188. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/bpm","value":1200}])")); });
  189. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/bpm","value":"fast"}])")); });
  190. refuses ([&] { remote_document::stage (source, json (R"([{"op":"add","path":"/unknown","value":1}])")); });
  191. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/projectId","value":"different"}])")); });
  192. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/patterns/0/notes/0/0","value":1.5}])")); });
  193. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/patterns/0/notes/0/2","value":4}])")); });
  194. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/patterns/0/uid","value":"ffffffffffffffff"}])")); });
  195. refuses ([&] { remote_document::stage (source, json (R"([{"op":"remove","path":"/patterns/0"}])")); });
  196. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/bpm","value":140},{"op":"test","path":"/bpm","value":130}])")); });
  197. auto locked = source;
  198. locked.playlistTracks.resize (1);
  199. locked.playlistTracks[0].lockedToContent = true;
  200. refuses ([&] { remote_document::stage (locked, json (R"([{"op":"replace","path":"/playlist/0/2","value":960}])")); });
  201. const auto changed = remote_document::stage (locked, json (R"([
  202. {"op":"remove","path":"/playlistTrackLocks"},
  203. {"op":"replace","path":"/playlist/0/2","value":960}
  204. ])"));
  205. check ((changed.playlistTracks.empty() || ! changed.playlistTracks[0].lockedToContent)
  206. && changed.playlist[0].start == 960, "Explicit unlock/edit transaction failed");
  207. check (source.bpm == 130.12345678901235 && source.patterns[0].notes[0].channel == 0, "Rejected transactions changed their input");
  208. }
  209. void currentModelDocuments()
  210. {
  211. auto source = fixture();
  212. source.playlist[0].fadeInTension = 0.123456791f;
  213. source.playlist[0].fadeOutTension = -0.234567896f;
  214. source.playlist[0].linearFades = 1;
  215. source.playlist[0].flFadeFlags = 0x12345678;
  216. source.playlist[0].fadeCurve = 2;
  217. source.automations[0].lfo.on = true;
  218. source.automations[0].lfo.range = 0.345678925f;
  219. source.automations[0].lfo.amp = { { 0, 0.456789017f, -0.123456791f }, { 960, 0.765432119f, 0.234567896f } };
  220. Modulator mod;
  221. mod.name = "Preserve LFO";
  222. mod.routes.push_back ({ { AutomationTargetKind::mixerPan, 1, 0, 0 }, 0.234567896f });
  223. source.modulators.push_back (mod);
  224. source.playlistTracks.resize (1);
  225. source.playlistTracks[0].lanes.push_back ({ 0, 72 });
  226. source.playlistTracks[0].lanesFolded = true;
  227. source.clipGrid.emplace();
  228. source.clipGrid->scenes.emplace_back();
  229. source.clipGrid->slots.emplace_back();
  230. auto gridClip = source.playlist[0];
  231. gridClip.uid = 0;
  232. gridClip.start = 0;
  233. gridClip.gridSlot = 0;
  234. source.clipGrid->clips.push_back (gridClip);
  235. VideoTrack videoTrack;
  236. videoTrack.name = "Picture";
  237. videoTrack.clips.push_back ({ "/videos/existing.mp4", 0.123456789012345, 0.234567890123456, 3.345678901234567, 10.0, 99 });
  238. source.videoTracks.push_back (videoTrack);
  239. uids::normalize (source);
  240. const auto changed = remote_document::stage (source, addValue ("/patterns/0/name", "Preserved"));
  241. check (changed.playlist == source.playlist && changed.automations == source.automations
  242. && changed.modulators == source.modulators && changed.playlistTracks == source.playlistTracks
  243. && changed.clipGrid == source.clipGrid && changed.videoTracks == source.videoTracks,
  244. "A metadata edit changed clip fades, LFOs, lanes, grid clips or video tracks");
  245. refusesWith ([&] {
  246. remote_document::stage (source, addValue ("/video/tracks/0/clips/0/path", "\\\\server\\share\\new.mp4"));
  247. }, "native media, page or resource locations");
  248. refusesWith ([&] {
  249. remote_document::stage (source, json (R"([{"op":"replace","path":"/clipGrid/clips/0/clip/0/16","value":"ffffffffffffffff"}])"));
  250. }, "existing identities");
  251. auto locked = source;
  252. locked.playlistTracks[0].lockedToContent = true;
  253. refusesWith ([&] {
  254. remote_document::stage (locked, json (R"([{"op":"replace","path":"/clipGrid/clips/0/clip/0/3","value":1920}])"));
  255. }, "Unlock the Playlist row");
  256. check (locked.clipGrid == source.clipGrid && source.videoTracks[0].clips[0].path == "/videos/existing.mp4",
  257. "A refused grid or video edit changed the input");
  258. auto stopMarker = fixture();
  259. launcher::setStopButton (stopMarker, 0, 0, false);
  260. const auto unchanged = remote_document::bytes (stopMarker);
  261. refuses ([&] { remote_document::stage (stopMarker, addValue ("/patterns/0/name", "No data loss")); });
  262. check (remote_document::bytes (stopMarker) == unchanged,
  263. "A grid stop marker lost by the native loader was committed or changed its input");
  264. }
  265. void documentIoPolicy()
  266. {
  267. const auto source = fixture();
  268. refusesWith ([&] { remote_document::stage (source, addValue ("/mixer/1/recordTo", "/tmp/remote-output.wav")); },
  269. "recording output paths");
  270. refusesWith ([&] { remote_document::stage (source, addValue ("/dataFolder", "\\\\server\\share\\output")); },
  271. "output/data folders");
  272. refusesWith ([&] { remote_document::stage (source, addValue ("/channels/0/sample", "\\\\server\\share\\sample.wav")); },
  273. "introduce asset paths");
  274. auto nested = source;
  275. nested.channels[0].instrument = InstrumentKind::patcher;
  276. PatchNode node;
  277. node.generator = true;
  278. node.channel.name = "Nested";
  279. node.channel.instrument = InstrumentKind::sampler;
  280. nested.channels[0].patcher.nodes.push_back (node);
  281. refusesWith ([&] {
  282. remote_document::stage (nested, addValue ("/channels/0/patcher/nodes/0/channel/sample", "\\\\server\\share\\nested.wav"));
  283. }, "introduce asset paths");
  284. auto hosted = source;
  285. hosted.channels[0].instrument = InstrumentKind::plugin;
  286. hosted.channels[0].plugin.id = "existing-catalog-id";
  287. hosted.channels[0].plugin.name = "Existing";
  288. refusesWith ([&] { remote_document::stage (hosted, addValue ("/channels/0/plugin/id", "VST3-\\\\server\\share\\new.dll")); },
  289. "introduce plugin loader IDs");
  290. ForeignPlugin foreign;
  291. foreign.format = ForeignPlugin::Format::vst2;
  292. foreign.name = "External";
  293. foreign.path = "\\\\server\\share\\external.dll";
  294. refusesWith ([&] {
  295. remote_document::stage (hosted, addValue ("/channels/0/plugin/foreign", juce::String (foreignToText (foreign))));
  296. }, "introduce foreign plugin locations");
  297. auto assets = source;
  298. assets.channels[0].samplePath = "/samples/existing.wav";
  299. const auto document = json (ProjectFile::toJsonExact (assets).toRawUTF8());
  300. auto copy = document["channels"][0].clone();
  301. copy.getDynamicObject()->removeProperty ("uid");
  302. const auto cloned = remote_document::stage (assets, addValue ("/channels/-", copy));
  303. check (cloned.channels.size() == 2 && cloned.channels[1].samplePath == assets.channels[0].samplePath
  304. && cloned.channels[1].uid != assets.channels[0].uid, "Existing assets could not be reused by a fresh entity");
  305. copy.getDynamicObject()->setProperty ("sample", "\\\\server\\share\\new.wav");
  306. refusesWith ([&] { remote_document::stage (assets, addValue ("/channels/-", copy)); }, "introduce asset paths");
  307. check (source.mixer[1].recordTo.empty() && source.channels[0].samplePath.empty(), "I/O rejection changed its source");
  308. }
  309. void knownNativeStatePolicy()
  310. {
  311. auto notebook = fixture();
  312. EffectSlot html;
  313. html.kind = EffectKind::htmlNotebook;
  314. html.state = flextra::htmlnotebook::stateFor ("/pages/existing.html");
  315. notebook.mixer[1].effects.push_back (html);
  316. for (const auto* address : { "\\\\server\\share\\page.html", "/tmp/program.exe", "https://example.invalid/page" })
  317. refusesWith ([&] {
  318. remote_document::stage (notebook, addValue ("/mixer/1/effects/0/state", encoded (flextra::htmlnotebook::stateFor (address))));
  319. }, "native media, page or resource locations");
  320. const auto renamed = remote_document::stage (notebook, json (R"([{"op":"replace","path":"/patterns/0/name","value":"Same page"}])"));
  321. check (renamed.mixer[1].effects[0].state == html.state, "Metadata edit did not preserve an existing notebook page");
  322. auto player = fixture();
  323. player.channels[0].instrument = InstrumentKind::videoplayer;
  324. video::Settings videoSettings;
  325. videoSettings.path = "/videos/existing.mp4";
  326. player.channels[0].pluginState = video::write (videoSettings);
  327. auto incoming = videoSettings;
  328. incoming.path = "\\\\server\\share\\video.mp4";
  329. refusesWith ([&] {
  330. remote_document::stage (player, addValue ("/channels/0/pluginState", encoded (video::write (incoming))));
  331. }, "native media, page or resource locations");
  332. auto volumeOnly = videoSettings;
  333. volumeOnly.volume = 64;
  334. const auto adjustedVideo = remote_document::stage (player, addValue ("/channels/0/pluginState", encoded (video::write (volumeOnly))));
  335. check (video::readOrDefault (adjustedVideo.channels[0].pluginState).volume == 64
  336. && video::readOrDefault (adjustedVideo.channels[0].pluginState).path == videoSettings.path,
  337. "Allowlisted native state edit changed or refused an existing media resource");
  338. const auto playerDocument = json (ProjectFile::toJsonExact (player).toRawUTF8());
  339. auto newPlayer = playerDocument["channels"][0].clone();
  340. newPlayer.getDynamicObject()->removeProperty ("uid");
  341. newPlayer.getDynamicObject()->setProperty ("pluginState", encoded (video::write (incoming)));
  342. refusesWith ([&] { remote_document::stage (player, addValue ("/channels/-", newPlayer)); }, "native media, page or resource locations");
  343. auto visualizer = fixture();
  344. EffectSlot visual;
  345. visual.kind = EffectKind::visualizer;
  346. auto scene = visualfx::scene::defaultScene();
  347. visualfx::scene::Layer image;
  348. image.type = visualfx::scene::LayerType::image;
  349. image.path = "/images/existing.png";
  350. scene.layers = { image };
  351. visual.state = visualfx::scene::toState (scene);
  352. visualizer.mixer[1].effects.push_back (visual);
  353. scene.layers[0].path = "\\\\server\\share\\image.png";
  354. refusesWith ([&] {
  355. remote_document::stage (visualizer, addValue ("/mixer/1/effects/0/state", encoded (visualfx::scene::toState (scene))));
  356. }, "native media, page or resource locations");
  357. auto script = vfx::defaultScript();
  358. script.setSource ("while True:\n pass\n");
  359. vfx::State state;
  360. state.kind = vfx::Kind::script;
  361. state.fl = vfx::writeScript (script);
  362. const auto payload = vfx::writeState (state);
  363. auto noteProcessor = fixture();
  364. vfx::makeChannel (noteProcessor.channels[0], vfx::Kind::keyMapper);
  365. uids::normalize (noteProcessor);
  366. refusesWith ([&] {
  367. remote_document::stage (noteProcessor, addValue ("/channels/0/pluginState", encoded (payload)));
  368. }, "VFX Script payloads");
  369. auto processorCopy = json (ProjectFile::toJsonExact (noteProcessor).toRawUTF8())["channels"][0].clone();
  370. processorCopy.getDynamicObject()->removeProperty ("uid");
  371. processorCopy.getDynamicObject()->setProperty ("pluginState", encoded (payload));
  372. refusesWith ([&] { remote_document::stage (noteProcessor, addValue ("/channels/-", processorCopy)); }, "VFX Script payloads");
  373. auto nested = fixture();
  374. nested.channels[0].instrument = InstrumentKind::patcher;
  375. PatchNode node;
  376. node.generator = true;
  377. vfx::makeChannel (node.channel, vfx::Kind::keyMapper);
  378. nested.channels[0].patcher.nodes.push_back (node);
  379. refusesWith ([&] {
  380. remote_document::stage (nested, addValue ("/channels/0/patcher/nodes/0/channel/pluginState", encoded (payload)));
  381. }, "VFX Script payloads");
  382. }
  383. void hostedStateClearIsRejectedBeforeCommit()
  384. {
  385. auto source = fixture();
  386. const auto saved = juce::MemoryBlock ("saved state", 11).toBase64Encoding().toStdString();
  387. source.channels[0].instrument = InstrumentKind::plugin;
  388. source.channels[0].plugin.id = "Known hosted instrument";
  389. source.channels[0].plugin.state = saved;
  390. EffectSlot hosted;
  391. hosted.kind = EffectKind::plugin;
  392. hosted.plugin.id = "Known hosted effect";
  393. hosted.plugin.state = saved;
  394. source.mixer[1].effects.push_back (hosted);
  395. EffectSlot parallel;
  396. parallel.kind = EffectKind::parallel;
  397. parallel.branches.resize (1);
  398. parallel.branches[0].chain.push_back (hosted);
  399. source.mixer[1].effects.push_back (parallel);
  400. ChannelDef patcher;
  401. patcher.instrument = InstrumentKind::patcher;
  402. PatchNode node;
  403. node.generator = false;
  404. node.effect = hosted;
  405. node.busHeads.push_back ({ 1, hosted, 1.0f });
  406. patcher.patcher.nodes.push_back (node);
  407. source.channels.push_back (std::move (patcher));
  408. uids::normalize (source);
  409. const auto replacement = [&] (const Song& changed, const char* field) {
  410. juce::var document;
  411. check (juce::JSON::parse (ProjectFile::toJsonExact (changed), document).wasOk(), "Cannot build clear-state fixture");
  412. auto* operation = new juce::DynamicObject();
  413. operation->setProperty ("op", "replace");
  414. operation->setProperty ("path", juce::String ("/") + field);
  415. operation->setProperty ("value", document[field]);
  416. return juce::var (juce::Array<juce::var> { juce::var (operation) });
  417. };
  418. auto changed = source;
  419. changed.channels[0].plugin.state.clear();
  420. refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
  421. refusesWith ([&] { remote_document::stage (source, json (R"([{"op":"remove","path":"/channels/0/plugin/state"}])")); },
  422. "Hosted plugin state is read-only");
  423. changed = source;
  424. changed.mixer[1].effects[0].plugin.state.clear();
  425. refusesWith ([&] { remote_document::stage (source, replacement (changed, "mixer")); }, "Hosted plugin state is read-only");
  426. changed = source;
  427. changed.mixer[1].effects[1].branches[0].chain[0].plugin.state.clear();
  428. refusesWith ([&] { remote_document::stage (source, replacement (changed, "mixer")); }, "Hosted plugin state is read-only");
  429. changed = source;
  430. changed.channels[1].patcher.nodes[0].effect.plugin.state.clear();
  431. refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
  432. changed = source;
  433. changed.channels[1].patcher.nodes[0].busHeads[0].head->plugin.state.clear();
  434. refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
  435. check (source.channels[0].plugin.state == saved && source.mixer[1].effects[0].plugin.state == saved,
  436. "Clear-state rejection changed its input");
  437. // Metadata and typed wrapper routing remain editable without passing a vendor blob to a device.
  438. const auto renamed = remote_document::stage (source, json (R"([{"op":"replace","path":"/channels/0/name","value":"Renamed"}])"));
  439. check (renamed.channels[0].name == "Renamed" && renamed.channels[0].plugin.state == saved, "Metadata edit lost hosted state");
  440. changed = source;
  441. const auto other = juce::MemoryBlock ("new saved state", 15).toBase64Encoding().toStdString();
  442. changed.channels[0].plugin.state = other;
  443. refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
  444. for (const auto* path : { "/channels/0/plugin/state", "/mixer/1/effects/0/plugin/state",
  445. "/mixer/1/effects/1/branches/0/chain/0/plugin/state",
  446. "/channels/1/patcher/nodes/0/effect/plugin/state",
  447. "/channels/1/patcher/nodes/0/busHeads/0/head/plugin/state" })
  448. refusesWith ([&] { remote_document::stage (source, addValue (path, juce::String (other))); }, "Hosted plugin state is read-only");
  449. auto document = json (ProjectFile::toJsonExact (source).toRawUTF8());
  450. auto copy = document["channels"][0].clone();
  451. copy.getDynamicObject()->removeProperty ("uid");
  452. refusesWith ([&] { remote_document::stage (source, addValue ("/channels/-", copy)); }, "Hosted plugin state is read-only");
  453. copy = document["mixer"][1]["effects"][0].clone();
  454. refusesWith ([&] { remote_document::stage (source, addValue ("/mixer/2/effects", juce::Array<juce::var> { copy })); },
  455. "Hosted plugin state is read-only");
  456. changed = source;
  457. changed.channels[0].plugin.state = other;
  458. refusesWith ([&] { remote_document::stage (source, addValue ("", json (ProjectFile::toJsonExact (changed).toRawUTF8()))); },
  459. "Hosted plugin state is read-only");
  460. auto substitute = source;
  461. substitute.mixer[1].effects[0].kind = EffectKind::utility;
  462. substitute.mixer[1].effects[0].substituteFor = hosted.plugin;
  463. refusesWith ([&] { remote_document::stage (substitute, addValue ("/mixer/1/effects/0/substituteFor/state", juce::String (other))); },
  464. "Hosted plugin state is read-only");
  465. auto empty = source;
  466. empty.channels[0].plugin.state.clear();
  467. refusesWith ([&] { remote_document::stage (empty, addValue ("/channels/0/plugin/state", juce::String (saved))); }, "Hosted plugin state is read-only");
  468. const auto routed = remote_document::stage (source, addValue ("/channels/0/plugin/outputs", json ("[[1,1]]")));
  469. check (routed.channels[0].plugin.outputs.size() == 1 && routed.channels[0].plugin.outputs[0].offset == 1
  470. && routed.channels[0].plugin.state == saved, "Allowlisted wrapper output routing changed or refused hosted state");
  471. // Stable channel identities permit reordering without treating their saved states as new data.
  472. auto reordered = source;
  473. std::swap (reordered.channels[0], reordered.channels[1]);
  474. const auto moved = remote_document::stage (source, replacement (reordered, "channels"));
  475. check (moved.channels[1].plugin.state == saved, "Reordering stable channel identities lost hosted state");
  476. auto sameId = source;
  477. auto second = sameId.channels[0];
  478. second.uid = 0;
  479. second.plugin.state.clear();
  480. sameId.channels.push_back (second);
  481. uids::normalize (sameId);
  482. auto swapped = sameId;
  483. std::swap (swapped.channels[0], swapped.channels[2]);
  484. const auto sameIdMoved = remote_document::stage (sameId, replacement (swapped, "channels"));
  485. check (sameIdMoved.channels[0].plugin.state.empty() && sameIdMoved.channels[2].plugin.state == saved,
  486. "Reordering same-ID channels confused their stable device states");
  487. swapped = sameId;
  488. std::swap (swapped.channels[0].plugin.state, swapped.channels[2].plugin.state);
  489. refusesWith ([&] { remote_document::stage (sameId, replacement (swapped, "channels")); }, "Hosted plugin state is read-only");
  490. check (source.channels[0].plugin.state == saved && source.mixer[1].effects[0].plugin.state == saved,
  491. "Hosted-state rejection changed its input");
  492. }
  493. void documentFieldAllowlist()
  494. {
  495. auto source = fixture();
  496. source.info.title = "Original";
  497. source.info.url = "https://existing.example/project";
  498. source.info.showOnOpen = true;
  499. source.info.created = 1234.0;
  500. source.info.workSeconds = 42.0;
  501. const auto original = remote_document::bytes (source);
  502. const auto named = remote_document::stage (source, json (R"([
  503. {"op":"replace","path":"/info/title","value":"New title"},
  504. {"op":"add","path":"/info/author","value":"Producer"},
  505. {"op":"add","path":"/info/genre","value":"Electronic"},
  506. {"op":"add","path":"/info/comments","value":"Session notes"},
  507. {"op":"add","path":"/channels/0/synthSettings/chorus","value":1},
  508. {"op":"replace","path":"/patterns/0/events/0/events/0/1","value":0.5},
  509. {"op":"replace","path":"/automations/0/points/0/1","value":0.5}
  510. ])"));
  511. check (named.info.title == "New title" && named.info.author == "Producer" && named.info.genre == "Electronic"
  512. && named.info.comments == "Session notes" && named.info.url == source.info.url
  513. && named.info.showOnOpen && named.info.created == source.info.created && named.info.workSeconds == source.info.workSeconds
  514. && named.channels[0].synth.chorus == 1 && named.patterns[0].events[0].events[0].value == 0.5f
  515. && named.automations[0].points[0].value == 0.5f, "Allowlisted musical or project metadata edit failed");
  516. for (const auto* path : { "/info/url", "/info/showOnOpen", "/info/created", "/info/workSeconds" })
  517. refusesWith ([&] { remote_document::stage (source, addValue (path, juce::String (path) == "/info/url" ? juce::var ("file:///tmp/program") : juce::var (false))); },
  518. "read-only");
  519. refusesWith ([&] { remote_document::stage (source, json (R"([{"op":"remove","path":"/info"}])")); }, "read-only");
  520. auto changed = source;
  521. changed.info.url = "https://new.example/launch";
  522. refusesWith ([&] { remote_document::stage (source, addValue ("/info", json (ProjectFile::toJsonExact (changed).toRawUTF8())["info"])); },
  523. "read-only");
  524. refusesWith ([&] { remote_document::stage (source, addValue ("", json (ProjectFile::toJsonExact (changed).toRawUTF8()))); }, "read-only");
  525. refusesWith ([&] { remote_document::stage (fixture(), addValue ("/info", json (R"({"title":"Injected","url":"file:///tmp/program","showOnOpen":true})"))); },
  526. "read-only");
  527. for (const auto* path : { "/futureLoader", "/channels/0/futureLoader", "/channels/0/synthSettings/futureLoader",
  528. "/patterns/0/events/0/futureLoader", "/automations/0/futureLoader", "/mixer/1/futureLoader" })
  529. refusesWith ([&] { remote_document::stage (source, addValue (path, "file:///tmp/program")); }, "editable document allowlist");
  530. auto document = json (ProjectFile::toJsonExact (source).toRawUTF8());
  531. auto channel = document["channels"][0].clone();
  532. channel.getDynamicObject()->removeProperty ("uid");
  533. channel["synthSettings"].getDynamicObject()->setProperty ("futureLoader", "/tmp/program");
  534. refusesWith ([&] { remote_document::stage (source, addValue ("/channels/-", channel)); }, "editable document allowlist");
  535. refusesWith ([&] { remote_document::stage (source, addValue ("/patterns/0/notes/0/0", json (R"({"futureLoader":"/tmp/program"})"))); },
  536. "does not allow editable object members");
  537. const auto labeled = remote_document::stage (source, addValue ("/channels/0/keyLabels", json (R"({"60":"Middle C","127":"Top"})")));
  538. check (labeled.channels[0].keyLabels.at (60) == "Middle C", "MIDI key-label allowlist rejected a valid dictionary");
  539. refusesWith ([&] { remote_document::stage (source, addValue ("/channels/0/keyLabels", json (R"({"futureLoader":"/tmp/program"})"))); }, "MIDI keys");
  540. check (remote_document::bytes (source) == original, "Allowlist rejection changed its input");
  541. }
  542. void richDocumentAllowlist()
  543. {
  544. auto source = fixture();
  545. VideoTrack existingVideo;
  546. existingVideo.name = "Existing picture";
  547. existingVideo.clips.push_back ({ "/videos/existing.mp4", 0.0, 0.0, 2.0, 2.0, 99 });
  548. source.videoTracks.push_back (existingVideo);
  549. auto rich = source;
  550. rich.channelGroups = { "Instruments" };
  551. rich.channels[0].group = 0;
  552. rich.channels[0].keyLabels[60] = "Middle C";
  553. rich.channels[0].arp.direction = 1;
  554. rich.channels[0].misc.gateBeats = 0.5f;
  555. rich.channels[0].sampler.pitch = 3.0f;
  556. rich.channels[0].sampler.warp = { { 0.0, 0.0 }, { 1.0, 2.0 } };
  557. rich.channels[0].sampler.precompute.normalize = true;
  558. ChannelDef layered;
  559. layered.instrument = InstrumentKind::layer;
  560. layered.layer.children = { 0 };
  561. rich.channels.push_back (layered);
  562. EffectSlot parallel;
  563. parallel.kind = EffectKind::parallel;
  564. parallel.branches.resize (1);
  565. parallel.branches[0].chain.emplace_back();
  566. rich.mixer[1].effects.push_back (parallel);
  567. ChannelDef patcher;
  568. patcher.instrument = InstrumentKind::patcher;
  569. PatchNode node;
  570. node.effect.kind = EffectKind::utility;
  571. node.label = "Bus processor";
  572. node.paramIns = { 0 };
  573. node.busHeads.push_back ({ 1, node.effect, 0.5f });
  574. patcher.patcher.nodes.push_back (node);
  575. rich.channels.push_back (patcher);
  576. Modulator modulator;
  577. modulator.name = "LFO";
  578. modulator.routes.push_back ({ { AutomationTargetKind::mixerPan, 1, 0, 0 }, 0.25f });
  579. rich.modulators.push_back (modulator);
  580. Vca vca;
  581. vca.name = "Band";
  582. vca.members = { 1, 2 };
  583. rich.vcas.push_back (vca);
  584. rich.clipGrid.emplace();
  585. rich.clipGrid->scenes.emplace_back();
  586. rich.clipGrid->scenes[0].name = "Scene";
  587. rich.clipGrid->slots.emplace_back();
  588. auto gridClip = source.playlist[0];
  589. gridClip.uid = 0;
  590. gridClip.start = 0;
  591. gridClip.gridSlot = 0;
  592. rich.clipGrid->clips.push_back (gridClip);
  593. VideoTrack video;
  594. video.name = "Picture";
  595. video.clips.push_back ({ "/videos/existing.mp4", 0.0, 0.0, 2.0, 2.0, 0 });
  596. rich.videoTracks.push_back (video);
  597. AdrCue cue;
  598. cue.id = "101";
  599. cue.out = 2.0;
  600. cue.line = "Dialogue";
  601. cue.takes.emplace_back();
  602. cue.takes[0].clip = source.playlist[0].uid;
  603. cue.takes[0].note = "First take";
  604. rich.adr.cues.push_back (cue);
  605. auto document = json (ProjectFile::toJsonExact (rich).toRawUTF8());
  606. const auto accepted = remote_document::stage (source, addValue ("", document));
  607. check (accepted.channels.size() == 3 && accepted.channels[0].keyLabels.at (60) == "Middle C"
  608. && accepted.channels[0].sampler.warp.size() == 2 && accepted.channels[1].layer.children == layered.layer.children
  609. && accepted.channels[2].patcher.nodes[0].busHeads.size() == 1
  610. && accepted.mixer[1].effects[0].branches[0].chain.size() == 1 && accepted.modulators.size() == 1
  611. && accepted.vcas.size() == 1 && accepted.clipGrid->slots.size() == 1 && accepted.videoTracks.size() == 2
  612. && accepted.adr.cues[0].takes[0].note == "First take", "Allowlist discarded a supported rich native object/tuple workflow");
  613. for (const auto* path : { "/channels/2/patcher/nodes/0/futureLoader",
  614. "/channels/2/patcher/nodes/0/busHeads/0/head/futureLoader",
  615. "/mixer/1/effects/0/branches/0/chain/0/futureLoader",
  616. "/clipGrid/clips/0/futureLoader", "/video/tracks/0/clips/0/futureLoader",
  617. "/adr/cues/0/takes/0/futureLoader" })
  618. refusesWith ([&] { remote_document::stage (accepted, addValue (path, "file:///tmp/program")); }, "editable document allowlist");
  619. }
  620. void discoveryCleanup()
  621. {
  622. const auto directory = juce::File::getCurrentWorkingDirectory()
  623. .getChildFile ("lynx-control-test-" + remote_files::randomToken());
  624. struct Cleanup
  625. {
  626. juce::File directory;
  627. ~Cleanup() { directory.deleteRecursively(); }
  628. } cleanup { directory };
  629. const auto file = directory.getChildFile ("connection.json");
  630. const juce::String record = R"({"token":"owned"})";
  631. remote_files::writeDiscovery (file, record);
  632. remote_files::removeDiscoveryIfOwned (file, "another process");
  633. check (file.existsAsFile(), "Cleanup removed another process's discovery record");
  634. remote_files::removeDiscoveryIfOwned (file, "owned");
  635. check (! file.exists(), "Cleanup kept its own discovery record");
  636. // The original crash payload must also be harmless during disable/shutdown.
  637. for (const auto size : { 16384, 100000 })
  638. {
  639. remote_files::writeDiscovery (file, juce::String (std::string ((std::size_t) size, '[')));
  640. remote_files::removeDiscoveryIfOwned (file, "owned");
  641. check (file.existsAsFile(), "Cleanup removed a malformed discovery record");
  642. }
  643. // JUCE's release parser accepts overlong UTF-8 as recursive array brackets.
  644. // The raw-byte gate must reject it before parsing even with a matching token.
  645. std::string invalidUtf8 = R"({"token":"owned","deep":)";
  646. for (int i = 0; i < 32; ++i) invalidUtf8 += "\xc1\x9b";
  647. invalidUtf8 += "0";
  648. for (int i = 0; i < 32; ++i) invalidUtf8 += "\xc1\x9d";
  649. invalidUtf8 += "}";
  650. // Keep malformed bytes outside JUCE strings: release-build conversion itself
  651. // can corrupt memory before JSON parsing, so the raw gate must run first.
  652. check (! remote_json::withinNestingLimit (invalidUtf8, 8), "Noncanonical UTF-8 passed the pre-conversion gate");
  653. {
  654. auto output = file.createOutputStream();
  655. check (output != nullptr && output->setPosition (0) && output->truncate().wasOk()
  656. && output->write (invalidUtf8.data(), invalidUtf8.size()), "Could not write malformed UTF-8 discovery fixture");
  657. output->flush();
  658. }
  659. remote_files::removeDiscoveryIfOwned (file, "owned");
  660. check (file.existsAsFile(), "Cleanup parsed a noncanonical UTF-8 discovery record");
  661. const juce::String unicodeRecord = juce::String::fromUTF8 ("{\"token\":\"owned\",\"name\":\""
  662. "\xe9\x9f\xb3\xe6\xa8\x82\xf0\x9f\x8e\xb5\"}");
  663. remote_files::writeDiscovery (file, unicodeRecord);
  664. remote_files::removeDiscoveryIfOwned (file, "owned");
  665. check (! file.exists(), "Cleanup rejected a canonical Unicode discovery record");
  666. // An oversized record with a valid prefix must be rejected rather than parsed
  667. // from a truncated buffer. A record at the byte limit remains valid.
  668. remote_files::writeDiscovery (file, record + juce::String::repeatedString (" ", 16385 - record.length()));
  669. remote_files::removeDiscoveryIfOwned (file, "owned");
  670. check (file.existsAsFile(), "Cleanup accepted an oversized discovery record");
  671. remote_files::writeDiscovery (file, record + juce::String::repeatedString (" ", 16384 - record.length()));
  672. remote_files::removeDiscoveryIfOwned (file, "owned");
  673. check (! file.exists(), "Cleanup rejected a discovery record at the byte limit");
  674. }
  675. }
  676. int main()
  677. {
  678. const char* activeTest = "initialization";
  679. const auto run = [&] (const char* name, auto test) { activeTest = name; test(); };
  680. try
  681. {
  682. run ("patchSemantics", patchSemantics);
  683. run ("exactDocuments", exactDocuments);
  684. run ("remoteNotesRoundtrip", remoteNotesRoundtrip);
  685. run ("transactionValidation", transactionValidation);
  686. run ("currentModelDocuments", currentModelDocuments);
  687. run ("documentIoPolicy", documentIoPolicy);
  688. run ("hostedStateClearIsRejectedBeforeCommit", hostedStateClearIsRejectedBeforeCommit);
  689. run ("documentFieldAllowlist", documentFieldAllowlist);
  690. run ("richDocumentAllowlist", richDocumentAllowlist);
  691. run ("knownNativeStatePolicy", knownNativeStatePolicy);
  692. run ("discoveryCleanup", discoveryCleanup);
  693. std::puts ("Remote JSON Patch, exact project documents, atomic staging and discovery cleanup tests passed");
  694. return 0;
  695. }
  696. catch (const std::exception& error)
  697. {
  698. std::fprintf (stderr, "%s: %s\n", activeTest, error.what());
  699. return 1;
  700. }
  701. }