4
0

RemoteProjectControlTests.cpp 46 KB

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