From cf644a901d6bc7d4def037e3882e1b024addfe5f Mon Sep 17 00:00:00 2001 From: Luca Stancapiano Date: Wed, 11 Nov 2026 01:14:38 +0100 Subject: [PATCH] fix(web): save an app that has no cover image (#5987) Co-authored-by: Luca Stancapiano --- src/confighttp.cpp | 109 ++++++++++++++- src/confighttp.h | 5 + src_assets/common/assets/web/Apps.vue | 44 +++--- tests/unit/test_confighttp.cpp | 185 +++++++++++++++++++++++++ tests/web/Apps.optional-fields.test.js | 87 ++++++++++++ tests/web/Apps.test.js | 13 +- 6 files changed, 416 insertions(+), 27 deletions(-) create mode 100644 tests/web/Apps.optional-fields.test.js diff --git a/src/confighttp.cpp b/src/confighttp.cpp index edf1c5758..7a5f0c69a 100644 --- a/src/confighttp.cpp +++ b/src/confighttp.cpp @@ -1134,6 +1134,103 @@ namespace confighttp { } } + /** + * @brief Remove object members whose values are JSON null. + * + * @param object JSON object to mutate. + * @param members Member names to inspect. + */ + void erase_null_members(nlohmann::json &object, std::initializer_list members) { + for (const char *member : members) { + if (object.contains(member) && object[member].is_null()) { + object.erase(member); + } + } + } + + /** + * @brief Drop empty or invalid prep-cmd arrays and null prep-command members. + * + * @param input_tree Application JSON from the save request, mutated in place. + */ + void normalize_prep_cmd_field(nlohmann::json &input_tree) { + if (!input_tree.contains("prep-cmd")) { + return; + } + if (!input_tree["prep-cmd"].is_array() || input_tree["prep-cmd"].empty()) { + input_tree.erase("prep-cmd"); + return; + } + + for (auto &cmd : input_tree["prep-cmd"]) { + if (!cmd.is_object()) { + continue; + } + erase_null_members(cmd, {"do", "undo", "elevated"}); + } + } + + /** + * @brief Drop empty or invalid detached command arrays. + * + * @param input_tree Application JSON from the save request, mutated in place. + */ + void normalize_detached_field(nlohmann::json &input_tree) { + if (!input_tree.contains("detached")) { + return; + } + if (!input_tree["detached"].is_array() || input_tree["detached"].empty()) { + input_tree.erase("detached"); + } + } + + /** + * @brief Trim cover paths and omit missing, non-string, empty, or whitespace-only values. + * + * @param input_tree Application JSON from the save request, mutated in place. + */ + void normalize_image_path_field(nlohmann::json &input_tree) { + std::string image_path; + if (input_tree.contains("image-path") && input_tree["image-path"].is_string()) { + image_path = input_tree["image-path"].get(); + } + boost::trim(image_path); + if (image_path.empty()) { + input_tree.erase("image-path"); + return; + } + input_tree["image-path"] = image_path; + } + + /** + * @brief Omit null optional application fields and normalize empty collections and cover paths. + * + * Required `name`/`index` handling stays with the caller. Explicit `false` and `0` values are kept. + * Null `do`, `undo`, and `elevated` members are removed from preparation-command objects. + * Missing, non-string, empty, or whitespace-only image-path values are omitted from the saved + * application. Nonempty string values are trimmed before saving. + * + * @param input_tree Application JSON from the save request, mutated in place. + */ + void normalize_optional_app_fields(nlohmann::json &input_tree) { + erase_null_members(input_tree, { + "prep-cmd", + "detached", + "exclude-global-prep-cmd", + "elevated", + "auto-detach", + "wait-all", + "exit-timeout", + "cmd", + "output", + "working-dir", + "image-path", + }); + normalize_prep_cmd_field(input_tree); + normalize_detached_field(input_tree); + normalize_image_path_field(input_tree); + } + /** * @brief Save an application. To save a new application, the index must be `-1`. To update an existing application, you must provide the current index of the application. * @param response The HTTP response object. @@ -1164,6 +1261,10 @@ namespace confighttp { * } * @endcode * + * Missing, non-string, empty, or whitespace-only image-path values are omitted + * from the saved application. Nonempty string values are trimmed before saving. + * Null optional fields are omitted before persistence; explicit `false` and `0` are preserved. + * * @api_examples{/api/apps|:| POST|:| {"name":"Hello, World!","index":-1}} */ void saveApp(const resp_https_t &response, const req_https_t &request) { @@ -1191,13 +1292,7 @@ namespace confighttp { BOOST_LOG(info) << file; nlohmann::json file_tree = nlohmann::json::parse(file); - if (input_tree["prep-cmd"].empty()) { - input_tree.erase("prep-cmd"); - } - - if (input_tree["detached"].empty()) { - input_tree.erase("detached"); - } + normalize_optional_app_fields(input_tree); auto &apps_node = file_tree["apps"]; int index = input_tree["index"].get(); // this will intentionally cause an exception if the provided value is the wrong type diff --git a/src/confighttp.h b/src/confighttp.h index 1b8e9b2ff..fb3793124 100644 --- a/src/confighttp.h +++ b/src/confighttp.h @@ -196,6 +196,11 @@ namespace confighttp { void resetPortalToken(const resp_https_t &response, const req_https_t &request); + /** + * @brief Save an application with optional fields normalized before persistence. + */ + void saveApp(const resp_https_t &response, const req_https_t &request); + #ifdef SUNSHINE_TESTS /** * @brief Replace native permission statuses for deterministic HTTP tests. diff --git a/src_assets/common/assets/web/Apps.vue b/src_assets/common/assets/web/Apps.vue index bdf584fb7..8aaa73db2 100644 --- a/src_assets/common/assets/web/Apps.vue +++ b/src_assets/common/assets/web/Apps.vue @@ -804,31 +804,34 @@ "exit-timeout": 5, "prep-cmd": [], detached: [], + "working-dir": "", "image-path": "" }; this.editFormError = ""; this.openEditModal(); }, + /** + * @brief Open an application for editing with nullish optional fields defaulted. + * @param {number} id Index of the application to edit. + */ editApp(id) { this.editForm = structuredClone(toRaw(this.apps[id])); this.editForm.index = id; - if (this.editForm["prep-cmd"] === undefined) - this.editForm["prep-cmd"] = []; - if (this.editForm["detached"] === undefined) - this.editForm["detached"] = []; - if (this.editForm["exclude-global-prep-cmd"] === undefined) - this.editForm["exclude-global-prep-cmd"] = false; - if (this.editForm["elevated"] === undefined && this.platform === 'windows') { - this.editForm["elevated"] = false; - } - if (this.editForm["auto-detach"] === undefined) { - this.editForm["auto-detach"] = true; - } - if (this.editForm["wait-all"] === undefined) { - this.editForm["wait-all"] = true; - } - if (this.editForm["exit-timeout"] === undefined) { - this.editForm["exit-timeout"] = 5; + const defaults = { + "prep-cmd": [], + detached: [], + "exclude-global-prep-cmd": false, + elevated: false, + "auto-detach": true, + "wait-all": true, + "exit-timeout": 5, + cmd: "", + output: "", + "working-dir": "", + "image-path": "" + }; + for (const [key, value] of Object.entries(defaults)) { + this.editForm[key] ??= value; } this.editFormError = ""; this.openEditModal(); @@ -1024,10 +1027,13 @@ }, save() { this.editFormError = ""; - this.editForm["image-path"] = this.editForm["image-path"].toString().replaceAll('"', ''); + const currentImagePath = this.editForm["image-path"] == null ? "" : String(this.editForm["image-path"]).trim(); + this.editForm["image-path"] = currentImagePath.replaceAll('"', ''); const imagePath = this.editForm["image-path"]; - if (imagePath && !imagePath.toLowerCase().endsWith('.png')) { + if (!imagePath) { + delete this.editForm["image-path"]; + } else if (!imagePath.toLowerCase().endsWith('.png')) { this.editFormError = this.$t('file_browser.error_invalid_extension', { extensions: '.png' }); const modalBody = this.$refs.editModal.querySelector('.modal-body'); if (modalBody) modalBody.scrollTop = 0; diff --git a/tests/unit/test_confighttp.cpp b/tests/unit/test_confighttp.cpp index 6aaf9f11c..9fe7fb78f 100644 --- a/tests/unit/test_confighttp.cpp +++ b/tests/unit/test_confighttp.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -32,6 +33,7 @@ #include #include #include +#include #include #ifdef SUNSHINE_BUILD_PORTAL @@ -342,6 +344,7 @@ protected: server->resource["^/pairing-test$"]["GET"] = confighttp::getPendingPairings; server->resource["^/pairing-test$"]["POST"] = confighttp::savePin; server->resource["^/portal-token-reset-test$"]["POST"] = confighttp::resetPortalToken; + server->resource["^/api/apps$"]["POST"] = confighttp::saveApp; server->default_resource["GET"] = confighttp::getFallbackPage; // Start server @@ -401,6 +404,63 @@ protected: return "Basic " + SimpleWeb::Crypto::Base64::encode(username + ":" + password); } + /** + * @brief Build authenticated JSON POST headers with a fresh CSRF token. + * + * @return Headers suitable for POST /api/apps. + */ + SimpleWeb::CaseInsensitiveMultimap authenticated_json_headers() { + SimpleWeb::CaseInsensitiveMultimap auth_headers; + auth_headers.emplace("Authorization", create_auth_header("testuser", "testpass")); + const auto token_response = client->request("GET", "/csrf-token-test", "", auth_headers); + EXPECT_EQ(token_response->status_code, "200 OK"); + const auto csrf_token = nlohmann::json::parse(token_response->content.string()).at("csrf_token").get(); + + SimpleWeb::CaseInsensitiveMultimap headers; + headers.emplace("Authorization", create_auth_header("testuser", "testpass")); + headers.emplace("Content-Type", "application/json"); + headers.emplace("X-CSRF-Token", csrf_token); + return headers; + } + + /** + * @brief Redirect apps.json to a temporary directory and restore process state on destruction. + */ + class ScopedSaveAppAppsFile { + public: + /** + * @brief Create the temporary apps.json directory and take ownership of `proc::proc`. + * + * @param subdir Directory name under `SUNSHINE_TEST_BIN_DIR`. + */ + explicit ScopedSaveAppAppsFile(std::string_view subdir): + test_dir(std::filesystem::path(SUNSHINE_TEST_BIN_DIR) / subdir) { + std::filesystem::create_directories(test_dir); + config::stream.file_apps = (test_dir / "apps.json").string(); + } + + ScopedSaveAppAppsFile(const ScopedSaveAppAppsFile &) = delete; + ScopedSaveAppAppsFile &operator=(const ScopedSaveAppAppsFile &) = delete; + + /** + * @brief Restore `file_apps`/`proc::proc` and remove the temporary directory. + */ + ~ScopedSaveAppAppsFile() noexcept { + try { + config::stream.file_apps = previous_file_apps; + proc::proc = std::move(previous_proc); + std::error_code ec; + std::filesystem::remove_all(test_dir, ec); + } catch (...) { + ADD_FAILURE() << "Failed to restore apps.json path or process manager state"; + } + } + + std::filesystem::path test_dir; ///< Temporary directory for apps.json. + std::string previous_file_apps {config::stream.file_apps}; ///< Prior apps.json path. + proc::proc_t previous_proc {std::move(proc::proc)}; ///< Prior process manager state. + }; + /** * @brief Insert a test pairing request into the production pending-session registry. * @@ -2063,3 +2123,128 @@ TEST_F(BrowseDirectoryTest, GetWindowsDrives_EntriesHaveCorrectFormat) { } } #endif + +TEST_F(ConfigHttpTest, SaveAppNormalizesOptionalImagePath) { + using json = nlohmann::json; + ScopedSaveAppAppsFile apps_file("save_app_image_path"); + const auto headers = authenticated_json_headers(); + + const std::array, 7> cases {{ + {json::object(), ""}, + {json {{"image-path", nullptr}}, ""}, + {json {{"image-path", 42}}, ""}, + {json {{"image-path", ""}}, ""}, + {json {{"image-path", " \t "}}, ""}, + {json {{"image-path", " /covers/cover.png "}}, "/covers/cover.png"}, + {json {{"image-path", "/covers/cover.png"}}, "/covers/cover.png"}, + }}; + + for (const auto &[fields, expected_path] : cases) { + for (const int index : {-1, 0}) { + SCOPED_TRACE(fields.dump() + " index=" + std::to_string(index)); + json initial {{"env", json::object()}, {"apps", json::array()}}; + if (index == 0) { + initial["apps"].push_back({{"name", "Before"}, {"image-path", "old.png"}}); + } + { + std::ofstream file(config::stream.file_apps); + file << initial.dump(); + } + + json input = fields; + input["name"] = "Image test"; + input["index"] = index; + const auto response = client->request("POST", "/api/apps", input.dump(), headers); + ASSERT_EQ(response->status_code, "200 OK"); + EXPECT_TRUE(json::parse(response->content.string()).at("status").get()); + + std::ifstream file(config::stream.file_apps); + const auto saved = json::parse(file); + json expected {{"name", "Image test"}}; + if (!expected_path.empty()) { + expected["image-path"] = expected_path; + } + EXPECT_EQ(saved.at("apps"), json::array({expected})); + EXPECT_EQ(saved.at("env"), initial.at("env")); + } + } +} + +TEST_F(ConfigHttpTest, SaveAppOmitsNullOptionalFieldsAndPreservesConfiguredValues) { + using json = nlohmann::json; + ScopedSaveAppAppsFile apps_file("save_app_optional_fields"); + { + std::ofstream file(config::stream.file_apps); + file << json {{"env", json::object()}, {"apps", json::array()}}.dump(); + } + const auto headers = authenticated_json_headers(); + + json null_fields { + {"name", "Null optional"}, + {"index", -1}, + {"prep-cmd", nullptr}, + {"detached", nullptr}, + {"exclude-global-prep-cmd", nullptr}, + {"elevated", nullptr}, + {"auto-detach", nullptr}, + {"wait-all", nullptr}, + {"exit-timeout", nullptr}, + {"cmd", nullptr}, + {"output", nullptr}, + {"working-dir", nullptr}, + {"image-path", nullptr}, + }; + auto null_response = client->request("POST", "/api/apps", null_fields.dump(), headers); + ASSERT_EQ(null_response->status_code, "200 OK"); + { + std::ifstream file(config::stream.file_apps); + const auto saved = json::parse(file); + ASSERT_EQ(saved.at("apps").size(), 1U); + EXPECT_EQ(saved.at("apps").at(0), (json {{"name", "Null optional"}})); + } + + json configured { + {"name", "Configured"}, + {"index", -1}, + {"prep-cmd", json::array({json {{"do", "prepare"}, {"undo", "restore"}, {"elevated", false}}})}, + {"detached", json::array({"background"})}, + {"exclude-global-prep-cmd", false}, + {"elevated", false}, + {"auto-detach", false}, + {"wait-all", false}, + {"exit-timeout", 0}, + {"cmd", "launch --argument"}, + {"output", "/logs/app.log"}, + {"working-dir", "/apps"}, + {"image-path", "/covers/cover.png"}, + }; + auto configured_response = client->request("POST", "/api/apps", configured.dump(), headers); + ASSERT_EQ(configured_response->status_code, "200 OK"); + { + std::ifstream file(config::stream.file_apps); + const auto saved = json::parse(file); + ASSERT_EQ(saved.at("apps").size(), 2U); + json expected = configured; + expected.erase("index"); + EXPECT_EQ(saved.at("apps").at(0), expected); + } + + json nested_null_prep { + {"name", "Prep null members"}, + {"index", -1}, + {"prep-cmd", json::array({json {{"do", "prepare"}, {"undo", nullptr}, {"elevated", nullptr}}})}, + }; + auto nested_response = client->request("POST", "/api/apps", nested_null_prep.dump(), headers); + ASSERT_EQ(nested_response->status_code, "200 OK"); + { + std::ifstream file(config::stream.file_apps); + const auto saved = json::parse(file); + ASSERT_EQ(saved.at("apps").size(), 3U); + const auto &app = saved.at("apps").at(2); + ASSERT_TRUE(app.contains("prep-cmd")); + ASSERT_EQ(app.at("prep-cmd").size(), 1U); + EXPECT_EQ(app.at("prep-cmd").at(0), (json {{"do", "prepare"}})); + EXPECT_FALSE(app.at("prep-cmd").at(0).contains("undo")); + EXPECT_FALSE(app.at("prep-cmd").at(0).contains("elevated")); + } +} diff --git a/tests/web/Apps.optional-fields.test.js b/tests/web/Apps.optional-fields.test.js new file mode 100644 index 000000000..b7436bf6d --- /dev/null +++ b/tests/web/Apps.optional-fields.test.js @@ -0,0 +1,87 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../src_assets/common/assets/web/Navbar.vue', () => ({ + default: { template: '
' }, +})) +vi.mock('../../src_assets/common/assets/web/fetch_utils', () => ({ + apiFetch: vi.fn(() => Promise.resolve({ status: 204 })), +})) + +import { apiFetch } from '../../src_assets/common/assets/web/fetch_utils' +import Apps from '../../src_assets/common/assets/web/Apps.vue' + +beforeEach(() => vi.clearAllMocks()) + +/** + * @brief Construct editing state without invoking Bootstrap or the network. + * @param {object} app Application JSON to edit. + * @return {object} Context for editApp() and save(). + */ +function editContext(app) { + return { + apps: [app], + platform: 'windows', + openEditModal: vi.fn(), + $refs: { editModal: { querySelector: () => ({ scrollTop: 0 }) } }, + $t: key => key, + } +} + +describe('optional application fields', () => { + const defaults = { + 'prep-cmd': [], + detached: [], + 'exclude-global-prep-cmd': false, + elevated: false, + 'auto-detach': true, + 'wait-all': true, + 'exit-timeout': 5, + cmd: '', + output: '', + 'working-dir': '', + 'image-path': '', + } + + it.each([undefined, null])('defaults optional fields containing %s before editing and saving', value => { + const app = { name: 'No cover' } + if (value === null) { + for (const key of Object.keys(defaults)) { + app[key] = null + } + } + const ctx = editContext(app) + + Apps.methods.editApp.call(ctx, 0) + + expect(ctx.editForm).toEqual({ name: 'No cover', index: 0, ...defaults }) + expect(() => Apps.methods.addPrepCmd.call(ctx)).not.toThrow() + expect(() => Apps.methods.addDetached.call(ctx)).not.toThrow() + expect(() => Apps.methods.save.call(ctx)).not.toThrow() + expect(apiFetch).toHaveBeenCalledOnce() + expect(Object.values(JSON.parse(apiFetch.mock.calls[0][1].body))).not.toContain(null) + }) + + it('preserves false, zero, and configured optional values', () => { + const app = { + name: 'Configured', + ...defaults, + 'prep-cmd': [{ do: 'prepare', undo: 'restore', elevated: false }], + detached: ['background'], + 'auto-detach': false, + 'wait-all': false, + 'exit-timeout': 0, + cmd: 'launch --argument', + output: '/logs/app.log', + 'working-dir': '/apps', + 'image-path': '/covers/cover.png', + } + const ctx = editContext(app) + + Apps.methods.editApp.call(ctx, 0) + Apps.methods.save.call(ctx) + + expect(ctx.editForm).toEqual({ ...app, index: 0 }) + expect(JSON.parse(apiFetch.mock.calls[0][1].body)).toEqual({ ...app, index: 0 }) + expect(app).not.toHaveProperty('index') + }) +}) diff --git a/tests/web/Apps.test.js b/tests/web/Apps.test.js index cd9ed6c28..a5db635ab 100644 --- a/tests/web/Apps.test.js +++ b/tests/web/Apps.test.js @@ -154,12 +154,23 @@ describe('save – cover image validation', () => { ) }) - it('submits when the image path is empty', () => { + it('submits when the image path is empty and leaves the letter cover as the default', () => { const ctx = saveContext('') Apps.methods.save.call(ctx) expect(ctx.editFormError).toBe('') + expect(ctx.editForm['image-path']).toBeUndefined() + expect(apiFetch).toHaveBeenCalledOnce() + }) + + it('submits when the image path is missing', () => { + const ctx = saveContext(null) + + expect(() => Apps.methods.save.call(ctx)).not.toThrow() + + expect(ctx.editFormError).toBe('') + expect(ctx.editForm['image-path']).toBeUndefined() expect(apiFetch).toHaveBeenCalledOnce() })