diff --git a/CMakeLists.txt b/CMakeLists.txt index 23bc770f72..d7687a6c35 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3310,6 +3310,13 @@ add_test(NAME server_list COMMAND ${PYTHON3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/apps/serverlist_test.py $ ${CMAKE_BINARY_DIR}/server-list-test) set_tests_properties(server_list PROPERTIES TIMEOUT 60) +add_executable(json_configuration_profile_test + tests/util/json_configuration_profile_test.C) +target_link_libraries(json_configuration_profile_test PRIVATE ecceutil) +add_test(NAME json_configuration_profile + COMMAND json_configuration_profile_test + ${CMAKE_BINARY_DIR}/configuration-profile-test.json) +set_tests_properties(json_configuration_profile PROPERTIES TIMEOUT 60) # The central server over TLS (#236): the real data server and broker scripts # on loopback with a fresh certificate, then the clients with and without diff --git a/GETTING_STARTED.md b/GETTING_STARTED.md index 5f0e9a33ce..1892c3d630 100644 --- a/GETTING_STARTED.md +++ b/GETTING_STARTED.md @@ -499,10 +499,9 @@ Unix socket, no port, no password) and data server. The broker stops when that user's last session ends. Several users on one machine each get their own broker; mode 3 is only needed to share one. -A single-user install can keep its projects in a folder instead of a data -server; see the next section. Server mode remains the default on Linux; -on macOS, which has no mod_dav for a per-user data server, the data folder -is the default (#133). +A new or unconfigured user keeps projects in a folder by default on every +platform. An explicit server preference or an existing data-server setup +continues to use that server. See the next section for local data mode. #### Local data mode (a data folder instead of a data server) diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 16fad41290..57d3e7c4cb 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -704,6 +704,20 @@ The Organizer's menus and Preferences, item by item, are on the help pages `organizer-menubar` (menu bar, toolbar, Preferences) and `organizer-menus` (right-click menus). +### Data servers (Preferences > Data) + +Choose the PEM certificate in the **Add Server** or **Edit Server** dialog, +beside the HTTPS address. ECCE stores the pin for that server's origin in the +user's preferences; without a pin, the system certificate store and host-name +check apply. The same dialog has an optional **Username** field for the account +on that server. It is saved with the server entry and included when exporting +or importing a JSON configuration profile; connecting still prompts for that +account's password. Profiles do not include passwords. The Organizer hook +`prefs data cert PEM [PNG]` loads a certificate for the first listed HTTPS +server and reports `loaded:` or an error. +`tests/apps/prefs_data_test.py` (ctest `apps_prefs_data`) covers the data server +dialog, username persistence, and valid or invalid certificate files. + ### Which codes are offered (Preferences > Codes, #1049) Codes unticked in **Edit > Preferences > Codes** are hidden from making new diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index c10ea9b8bd..509588d936 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -68,7 +68,7 @@ those settings. | `ECCE_REMOTE_SERVER` | Central-server mode: read `siteconfig/RemoteServer/{DataServers,site_runtime}`, start no local broker or data server. `ecce -remote` sets it. | Set to enable. Default off. | | `ECCE_SITE_ADMIN_LOGIN` | The ssh login on the central server for `ecce -admin -remote` (`-l LOGIN` sets it). | Default: ssh's own (`~/.ssh/config`, else your user name). | | `ECCE_LOCAL` | Set by `ecce --local`: local data mode for this session in the preference's folder, whether or not the preference is ticked. `ECCE_LOCAL_DATA` wins over it. | Any value. Unset: the preference decides. | -| `ECCE_LOCAL_DATA` | Local data mode (#216): keep projects and calculations in this folder instead of a data server; no data server is started. Wins over Edit > Preferences > Data folder. The launchers export it for the whole session, set to the preference's folder or to empty (data server). | Path. Unset: the preference (off by default; folder `~/.ECCE-local`). Empty: a data server. | +| `ECCE_LOCAL_DATA` | Local data mode (#216): keep projects and calculations in this folder instead of a data server; no data server is started. Wins over Edit > Preferences > Data folder. The launchers export it for the whole session, set to the preference's folder or to empty (data server). | Path. Unset: the preference; if unset, new users default to `~/.ECCE-local` and detected existing data-server setups stay on the server. Empty: a data server. | | `ECCE_NO_MESSAGING` | Run without the message broker. Apps do not publish or subscribe. The launchers set it for `ecce -admin` and `-machine`. | Set to enable. Default off. | | `ECCE_NO_DATASERVER` | Launchers do not start the per-user data server. | Set to enable. Default off. | | `ECCE_DATASERVER_PORT` | Port of the per-user data server, as used by `ecce-dataserver-start` and `-status`. The test suite uses it for private servers. | Port. Default 8096. | diff --git a/docs/INSTALLING.md b/docs/INSTALLING.md index 61c3214893..a1973c769f 100644 --- a/docs/INSTALLING.md +++ b/docs/INSTALLING.md @@ -78,15 +78,16 @@ your `PATH`. ## 2. Choose where your data lives -**In a folder on your computer** — the default on macOS and Windows, -optional on Linux. There is nothing to set up: no account and no login. -On Linux, choose Edit → Preferences → Data folder (default -`~/.ECCE-local`; it takes effect at the next start), or start ECCE with -`ECCE_LOCAL_DATA=` set. See +**In a folder on your computer** — the default for new users on every +platform. There is nothing to set up: no account and no login. The folder +defaults to `~/.ECCE-local` on Linux and macOS, and `ecce-local` on Windows. +An existing data-server setup is kept. To choose another folder, use +Edit → Preferences → Data folder (it takes effect at the next start), or +start ECCE with `ECCE_LOCAL_DATA=` set. See [Deployment modes](../GETTING_STARTED.md#deployment-modes). -**In a data server on this computer** — the default on Linux. The data -server runs as your own user. Create a login on it once: +**In a data server on this computer** — an optional mode for one computer. +The data server runs as your own user. Create a login on it once: ``` ecce-dataserver-start @@ -179,9 +180,8 @@ shared is up to the site; the three modes are set up step by step in 1. **Everything local** (the default). Each user's session starts their own data server and broker; the broker listens on a Unix socket, not - on a network port. Nothing to configure. The data server can be - replaced by a folder (Edit → Preferences → Data folder), which is the - default on macOS and Windows. + on a network port. A new user keeps calculations in a folder by default; + an existing server setup stays on its data server. 2. **A central server** for a group or a class. One account on the server holds everyone's calculations and the shared libraries; users elsewhere connect to it. On the server, as that account: diff --git a/docs/OVERVIEW.md b/docs/OVERVIEW.md index a25766336f..56aad4e905 100644 --- a/docs/OVERVIEW.md +++ b/docs/OVERVIEW.md @@ -10,13 +10,14 @@ input, output and parsed properties, in projects in the Organizer. ## How ECCE is organised -![Two ways to run ECCE. With an ECCE server (on one computer, or a central server for a lab or class): the client saves to and loads from the server, which holds the data server and message broker. On its own (the default): the client keeps its data in a local folder with its own broker, and there is no ECCE server. In both, the client's job agent submits jobs over ssh to a compute machine and follows them.](images/ecce-architecture.svg) +![Two ways to run ECCE. With an ECCE server (on one computer, or a central server for a lab or class): the client saves to and loads from the server, which holds the data server and message broker. On its own (the default for new users): the client keeps its data in a local folder with its own broker, and there is no ECCE server. Existing server configurations remain in place. In both, the client's job agent submits jobs over ssh to a compute machine and follows them.](images/ecce-architecture.svg) The **client** (`ecce-client`) is the window you work in (the Organizer and the tools as tabs; `ECCE_ONE_PROCESS=0 ecce` opens one window per tool), plus a job agent that submits and follows jobs. Normally it works with an **ECCE server** (`ecce-server`: a data server and a message broker) that stores projects and results. The client can instead run **on its own**, keeping its data -in a folder on your disk (Edit → Preferences → Data folder; the default for a new installation); +in a folder on your disk (the default for new users; Edit → Preferences → +Data folder changes it; existing server configurations stay in server mode); it still starts a private message broker, ECCE's own (`eccebroker`, no Mosquitto needed), but no ECCE server. Neither server nor client runs calculations, except ECCE-QM on the client's own diff --git a/docs/claude/services/index.md b/docs/claude/services/index.md index 73d8b97ca1..252b519575 100644 --- a/docs/claude/services/index.md +++ b/docs/claude/services/index.md @@ -14,7 +14,7 @@ what the deployment mode needs (GETTING_STARTED, "Deployment modes"): - **Local (mode 1, the default on Linux):** a per-user `mosquitto` on a Unix socket and a per-user Apache data server, both non-root. - **Local data folder** (`ECCE_LOCAL_DATA` or the Data folder preference; - the default on macOS): the same per-user broker, no data server; the + the default for new users on all platforms): the same per-user broker, no data server; the data lives in a local folder (FileEDSI). - **Central server (mode 2, `-remote`):** one server account runs Apache and Mosquitto (TCP, authenticated) for everyone; clients start no data server diff --git a/docs/images/ecce-architecture.svg b/docs/images/ecce-architecture.svg index 729fbf4ff6..14e223b12f 100644 --- a/docs/images/ecce-architecture.svg +++ b/docs/images/ecce-architecture.svg @@ -60,5 +60,5 @@ ssh: submit, progress, results - One user, one computer; no data server. To become the default once native macOS and Windows clients build. + One user, one computer; local folder by default for new users. diff --git a/help/src/installation.md b/help/src/installation.md index 756b9fb0a1..dd81eb3585 100644 --- a/help/src/installation.md +++ b/help/src/installation.md @@ -173,8 +173,11 @@ added, with their name, type and address: another one. An **ECCE server (https)** needs a name and the address of the server, for example `https://ecce.example.edu`; a port other than 443 goes in the address, as in `https://ecce.example.edu:8443`. - The login is asked when you connect. **Test connection** checks that an ECCE - server answers and shows whether its certificate is trusted. For an SSH + The **TLS certificate** field lets you choose a PEM certificate for this + server; leave it blank to use the system certificate store. The certificate + is stored for this server's origin in your local preferences. The login is + asked when you connect. **Test connection** checks that an ECCE server + answers and shows whether its certificate is trusted. For an SSH folder it logs in, checks that the folder exists and can be written, and offers to create it if it is missing. The server needs only an SSH account and a folder; nothing is installed or run there. A login and a @@ -311,25 +314,13 @@ gives you the host name. In local data mode there is no data server and no login. Your projects and calculations are stored in an ordinary folder, by default `~/.ECCE-local`. -This suits one person on one computer. +This is the default for new users on every platform. If ECCE finds an +existing data-server configuration, it keeps using that server. -To use it from the first start: - -1. Start ECCE with the folder named in the environment: - - ``` - ECCE_LOCAL_DATA=$HOME/.ECCE-local ecce - ``` -2. The Organizer opens without a login window. - -To make it permanent: - -1. In the Organizer, choose **Edit > Preferences**. -2. Open the **Data** tab. -3. To use another folder, click **Change...** next to **Folder:** and - choose it. -4. Close the window and restart ECCE. The setting applies from the next - start. +To use another folder, open **Edit > Preferences > Data**, click +**Change...** next to **Folder:**, choose the folder, and restart ECCE. +To select a folder for one session, start ECCE with +`ECCE_LOCAL_DATA=$HOME/.ECCE-local ecce`. Changing mode copies nothing. The calculations of the other mode stay where they are, and the new mode starts empty. The variable `ECCE_LOCAL_DATA` diff --git a/include/dsm/CTLSSocket.H b/include/dsm/CTLSSocket.H index 6247bc3312..dc742614e1 100644 --- a/include/dsm/CTLSSocket.H +++ b/include/dsm/CTLSSocket.H @@ -1,10 +1,10 @@ // CTLSSocket.H -- TLS client socket (OpenSSL) for the https data server. // -// Trust: if $ECCE_HOME/siteconfig/RemoteServer/server.pem exists, that -// certificate is the only trust anchor and the presented certificate must be -// identical to it (host name is not checked, so IP addresses and aliases -// work). Otherwise the system store is used and the host name is verified. -// There is no mode in which verification is skipped. +// Trust: a per-user certificate pin for this server origin takes precedence. +// The legacy $ECCE_HOME/siteconfig/RemoteServer/server.pem pin is the fallback. +// A pin requires an exact certificate match; without a pin, the system store +// and host name are verified. There is no mode in which verification is +// skipped. #if !defined( __CTLSSOCKET_H ) #define __CTLSSOCKET_H @@ -53,6 +53,12 @@ public : // Path of the pinned certificate, or "" when the system store applies. static string_type pinnedCertPath(void); + // Origin-specific pin, falling back to the legacy shared pin. + static string_type pinnedCertPath(const string_type& host, port_type port); + // Save a PEM certificate pin for one TLS origin. An empty PEM removes it. + static bool storePinnedCertificate(const string_type& host, port_type port, + const string_type& pem, + string_type& error); private : SSL_CTX * ctx_; diff --git a/include/util/JsonConfigurationProfile.H b/include/util/JsonConfigurationProfile.H new file mode 100644 index 0000000000..7656819012 --- /dev/null +++ b/include/util/JsonConfigurationProfile.H @@ -0,0 +1,82 @@ +// Versioned profiles include data-server usernames but never passwords. +#ifndef JSONCONFIGURATIONPROFILE_HH +#define JSONCONFIGURATIONPROFILE_HH + +#include +#include + +namespace JsonConfigurationProfile { + +struct DataServer { + std::string name; + std::string url; + std::string username; + std::string tlsCertificatePem; +}; + +struct Code { + std::string name; + std::string program; + std::vector modules; +}; + +struct Queue { + std::string name; + unsigned int minProcessors; + unsigned int maxProcessors; + unsigned int maxCPU; + unsigned int maxMemory; + unsigned int minScratch; + unsigned int defProcessors; + unsigned int defRun; + unsigned int defMemory; + unsigned int defScratch; + std::string memUnits; + std::string requestLines; + + Queue() : minProcessors(0), maxProcessors(0), maxCPU(0), maxMemory(0), + minScratch(0), defProcessors(0), defRun(0), defMemory(0), + defScratch(0) {} +}; + +struct Setting { + std::string name; + std::string value; +}; + +struct ComputeResource { + std::string name; + std::string host; + std::string vendor; + std::string model; + std::string processor; + unsigned int processors; + unsigned int nodes; + bool allocationAccounts; + std::string queueManager; + std::vector codes; + std::vector queues; + std::vector settings; + + ComputeResource() : processors(0), nodes(0), allocationAccounts(false) {} +}; + +struct Profile { + unsigned int version; + std::vector dataServers; + std::vector computeResources; + std::vector jobCreationCodes; + + Profile() : version(3) {} +}; + +// Save atomically. Only data-server usernames are included; passwords and +// compute-resource machine credentials are excluded. +bool save(const std::string& path, const Profile& profile, std::string& error); + +// Parse and validate without applying anything to ECCE preferences. +bool load(const std::string& path, Profile& profile, std::string& error); + +} // namespace JsonConfigurationProfile + +#endif diff --git a/include/util/ServerList.H b/include/util/ServerList.H index 852d14ec58..88dd0656e0 100644 --- a/include/util/ServerList.H +++ b/include/util/ServerList.H @@ -4,7 +4,7 @@ * The servers a user has added (#767): SSH folders and ECCE servers, kept * per user in one plain file, ~/.ECCE/AddedServers, one line per server: * - *
+ *
[] * * type is "ssh" (address sftp://user@host/folder) or "ecce" (address * https://host[:port]). wx-free; Edit > Preferences > Data lists them. @@ -24,6 +24,7 @@ struct ServerEntry string name; string address; bool connectAtStart = false; + string username; // configured account for an ECCE data server; no password }; class ServerList diff --git a/include/wxgui/AddServerDialog.H b/include/wxgui/AddServerDialog.H index a8bf205a72..49129b9ddc 100644 --- a/include/wxgui/AddServerDialog.H +++ b/include/wxgui/AddServerDialog.H @@ -8,16 +8,16 @@ #include "util/ServerList.H" class ewxChoice; -class ewxTextCtrl; class ewxButton; class ewxStaticText; +class ewxTextCtrl; class wxProcessEvent; // Add Server... / Edit...: an SSH folder (name, host, user, folder) or an -// ECCE server (name, address). OK stores the entry in the user's -// ServerList (replacing oldName when editing), so Preferences and the -// Organizer share one dialog. Test connection reaches an ECCE server the -// way the start window does (certificate trusted, else pinned). +// ECCE server (name, HTTPS address, username, optional TLS certificate). OK stores the +// entry in the user's ServerList (replacing oldName when editing), so +// Preferences and the Organizer share one dialog. A selected certificate is +// pinned to that HTTPS origin for this user. class AddServerDialog : public wxDialog { public: @@ -30,7 +30,8 @@ public: // Test hooks: fill the fields as typing does; press OK. void fillForTest(bool ssh, const std::string& name, const std::string& a, - const std::string& b, const std::string& c); + const std::string& b, const std::string& c, + const std::string& username = ""); void acceptForTest(); void startupForTest(bool on) { p_startup->SetValue(on); } @@ -39,9 +40,11 @@ private: void OnTest(wxCommandEvent& event); void OnTestDone(wxProcessEvent& event); void OnOk(wxCommandEvent& event); + void OnChooseCertificate(wxCommandEvent& event); void testSsh(bool create); void showType(); bool collect(ServerEntry& e) const; + bool applyCertificate(const string& address, string& error) const; std::string p_old; ServerEntry p_entry; @@ -53,13 +56,19 @@ private: ewxTextCtrl* p_folder; ewxTextCtrl* p_port; ewxTextCtrl* p_address; + ewxTextCtrl* p_eccUser; + ewxTextCtrl* p_certificate; + ewxButton* p_chooseCertificate; + string p_certificatePath; + wxWindow* p_certificateLabel; + wxWindow* p_eccUserLabel; ewxButton* p_test; ewxStaticText* p_status; wxProcess* p_proc; std::shared_ptr > p_alive; // a login thread may outlive the dialog wxBoxSizer* p_top; wxWindow* p_sshRows[8]; - wxWindow* p_eccRows[2]; + wxWindow* p_eccRows[4]; }; #endif diff --git a/include/wxgui/GlobalPrefs.H b/include/wxgui/GlobalPrefs.H index e324490e52..df990210ff 100644 --- a/include/wxgui/GlobalPrefs.H +++ b/include/wxgui/GlobalPrefs.H @@ -93,6 +93,10 @@ private: void OnEditServer(wxCommandEvent& event); void OnRemoveServer(wxCommandEvent& event); void OnServerSelect(wxListEvent& event); + bool loadServerCertificate(const string& address, const string& path, + string& error); + void OnSaveConfiguration(wxCommandEvent& event); + void OnLoadConfiguration(wxCommandEvent& event); void updateServerButtons(); long selectedServer() const; ProgramRow makeProgramRow(wxWindow* page, wxSizer* sizer, @@ -166,13 +170,15 @@ private: struct ServerRow { enum { LISTED, ADMIN, EARLIER }; int kind; - string name, type, address; + string name, type, address, username; }; vector p_serverRows; wxListCtrl* p_serverList; ewxButton* p_addServer; ewxButton* p_editServer; ewxButton* p_removeServer; + ewxButton* p_saveConfiguration; + ewxButton* p_loadConfiguration; // Advanced page (#307): one row per EnvSwitches::all() entry. struct AdvancedRow { diff --git a/packaging/gateway/ecce-first-start b/packaging/gateway/ecce-first-start index f512d3a0b4..9c97f514ad 100755 --- a/packaging/gateway/ecce-first-start +++ b/packaging/gateway/ecce-first-start @@ -214,6 +214,17 @@ def choose_local(): return rc == 0 +def _get_server_certificate(host, port): + """Return the presented PEM certificate, with a bounded connect on py3.9.""" + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + with socket.create_connection((host, port), timeout=5) as raw: + with context.wrap_socket(raw, server_hostname=host) as conn: + der = conn.getpeercert(binary_form=True) + return ssl.DER_cert_to_PEM_cert(der) + + def _reachable(host, port, https, context): """The first HTTP(S) answer's peer certificate (DER) or b"", else None.""" try: @@ -246,7 +257,7 @@ def remote_setup(host, port): way, scheme, dport = "trusted", "https", tport else: try: - pem = ssl.get_server_certificate((host, tport), timeout=5) + pem = _get_server_certificate(host, tport) pinned = ssl.PEM_cert_to_DER_cert(pem) loose = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) loose.check_hostname = False @@ -313,7 +324,7 @@ def test_server(address): if _reachable(host, tport, True, ctx) is not None: return True, "The server answers and its certificate is trusted." try: - pem = ssl.get_server_certificate((host, tport), timeout=5) + pem = _get_server_certificate(host, tport) pinned = ssl.PEM_cert_to_DER_cert(pem) loose = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) loose.check_hostname = False diff --git a/src/apps/organizer/CalcMgr.C b/src/apps/organizer/CalcMgr.C index 672ed85bc8..7b6b707547 100644 --- a/src/apps/organizer/CalcMgr.C +++ b/src/apps/organizer/CalcMgr.C @@ -981,7 +981,7 @@ void CalcMgr::runTestCommand(const string& line) EcceURL(proj)); if (outcome.empty()) outcome = "done"; } else if (command == "server") { - // "server roots|sync|connect NAME|copycheck SRC DST|launchcheck URL" + // "server roots|sync|connect NAME|activate NAME|copycheck SRC DST|launchcheck URL" std::istringstream args(calcName); string sub, a, b, c; args >> sub >> a >> b >> c; @@ -1026,6 +1026,20 @@ void CalcMgr::runTestCommand(const string& line) ref = list[i].address; outcome = ref.empty() ? "no such server" : (connectServer(ref) ? "connected" : "not connected"); + } else if (sub == "activate") { + std::replace(a.begin(), a.end(), '_', ' '); + outcome = "no such server"; + wxTreeItemIdValue cookie; + for (wxTreeItemId id = p_treeCtrl->GetFirstChild(p_treeCtrl->GetRootItem(), cookie); + id.IsOk(); id = p_treeCtrl->GetNextChild(p_treeCtrl->GetRootItem(), cookie)) { + WxResourceTreeItemData *data = dynamic_cast( + p_treeCtrl->GetItemData(id)); + if (!data || data->serverName() != a) continue; + wxTreeEvent event(wxEVT_TREE_ITEM_ACTIVATED, p_treeCtrl, id); + p_treeCtrl->GetEventHandler()->ProcessEvent(event); + outcome = "activated"; + break; + } } else if (sub == "rootpos") { // Screen centre of the root's label, for a real right-click (#1221). outcome = "no such root"; @@ -4244,11 +4258,13 @@ bool CalcMgr::connectServer(const string& ref) if (ref.compare(0, 7, "sftp://") == 0) return connectSsh(ref); string name = ref; vector list = ServerList::load(); + string user = ServerList::loginFor(ref), pass; for (size_t i = 0; i < list.size(); i++) - if (list[i].type == "ecce" && ServerList::refOf(list[i].address) == ref) + if (list[i].type == "ecce" && ServerList::refOf(list[i].address) == ref) { name = list[i].name; + if (user.empty()) user = list[i].username; + } ServerList::markAdded(ref); - string user = ServerList::loginFor(ref), pass; if (!WxDavAuth::askAddedLogin(ref, user, pass)) { setMessage("Not connected to " + name + ": the login was cancelled.", WxFeedback::ERROR); @@ -10383,7 +10399,8 @@ void CalcMgr::OnTreectrlDeleteItem( wxTreeEvent& event ) void CalcMgr::OnTreectrlItemActivated( wxTreeEvent& event ) { auto *item = dynamic_cast(p_treeCtrl->GetItemData(event.GetItem())); - if (item && item->getResource()->getResourceType() == ResourceDescriptor::RT_DOCUMENT) + Resource *resource = item ? item->getResource() : NULL; + if (resource && resource->getResourceType() == ResourceDescriptor::RT_DOCUMENT) viewFile(item->getUrl()); else event.Skip(); } @@ -16451,8 +16468,10 @@ void CalcMgr::updateSelectionMenus() wxMenu *tools = menuBar->GetMenu(menuBar->FindMenu(_("Tools"))); clearMenu(*tools); addGlobalTools(*tools); - enableTopMenu(menuBar, _("Tools"), allCalcs && p_currentSelection.size() == 2, - p_menuTitlesChanged); + // Global tools do not depend on a calculation selection. Keep the menu + // available even when there is no selection (or a multi-selection other + // than the pair used by comparison tools). + enableTopMenu(menuBar, _("Tools"), true, p_menuTitlesChanged); enableMenuItem(menuBar, wxID_CHANGE_ACCESS, false); enableMenuItem(menuBar, wxID_RENAME, false); enableMenuItem(menuBar, wxID_VIEW_PROPERTY, false); diff --git a/src/dsm/cipc/CTLSSocket.C b/src/dsm/cipc/CTLSSocket.C index b7c59c2f55..584c55c0bf 100644 --- a/src/dsm/cipc/CTLSSocket.C +++ b/src/dsm/cipc/CTLSSocket.C @@ -1,7 +1,9 @@ // CTLSSocket.C -- TLS client socket (OpenSSL); see CTLSSocket.H. #include "dsm/CTLSSocket.H" +#include "util/Ecce.H" #include "util/RemoteServerDir.H" +#include "util/SDirectory.H" #include #include @@ -12,6 +14,7 @@ #ifdef _WIN32 #include #include +#include #else #include #include @@ -26,6 +29,12 @@ #include #include #include +#include +#include +#include +#include +#include +#include namespace ipc { @@ -76,6 +85,48 @@ private: }; #endif +static std::string normalizedOrigin(const std::string& host, + CTLSClientSocket::port_type port) +{ + std::string normalized = host; + if (normalized.size() > 1 && normalized[0] == '[' && + normalized[normalized.size() - 1] == ']') + normalized = normalized.substr(1, normalized.size() - 2); + for (size_t i = 0; i < normalized.size(); ++i) + normalized[i] = static_cast(std::tolower( + static_cast(normalized[i]))); + const unsigned int effectivePort = port > 0 ? (unsigned int)port : 443; + return "https://" + normalized + ":" + std::to_string(effectivePort); +} + +static std::string originPinPath(const std::string& host, + CTLSClientSocket::port_type port, + bool createDirectory) +{ + const std::string pref = Ecce::realUserPrefPath(); + if (pref.empty() || host.empty()) return ""; + const std::string dir = pref + "TlsCertificates"; + struct stat st; + if (stat(dir.c_str(), &st) != 0) { + if (!createDirectory || !SDirectory::create(dir, 0700)) { + if (stat(dir.c_str(), &st) != 0) return ""; + } + if (stat(dir.c_str(), &st) != 0) return ""; + } + if (!S_ISDIR(st.st_mode)) return ""; + + const std::string origin = normalizedOrigin(host, port); + static const char hex[] = "0123456789abcdef"; + std::string key; + key.reserve(origin.size() * 2); + for (size_t i = 0; i < origin.size(); ++i) { + const unsigned char c = static_cast(origin[i]); + key += hex[c >> 4]; + key += hex[c & 15]; + } + return dir + "/" + key + ".pem"; +} + CTLSClientSocket::string_type CTLSClientSocket::pinnedCertPath(void) { const char * home = getenv("ECCE_HOME"); @@ -85,6 +136,68 @@ CTLSClientSocket::string_type CTLSClientSocket::pinnedCertPath(void) return access(p.c_str(), F_OK) == 0 ? p : std::string(); } +CTLSClientSocket::string_type CTLSClientSocket::pinnedCertPath( + const string_type& host, port_type port) +{ + const std::string specific = originPinPath(host, port, false); + if (!specific.empty() && access(specific.c_str(), F_OK) == 0) + return specific; + return pinnedCertPath(); +} + +bool CTLSClientSocket::storePinnedCertificate(const string_type& host, + port_type port, const string_type& pem, string_type& error) +{ + if (host.empty()) { error = "A server host is required for a certificate pin."; return false; } + if (pem.empty()) { + const std::string path = originPinPath(host, port, false); + if (path.empty()) return true; + if (std::remove(path.c_str()) == 0 || errno == ENOENT) return true; + error = "Could not remove the origin-specific TLS certificate."; + return false; + } + const std::string path = originPinPath(host, port, true); + if (path.empty()) { error = "Could not access the per-user TLS certificate directory."; return false; } + + BIO* bio = BIO_new_mem_buf(pem.data(), (int)pem.size()); + X509* certificate = bio ? PEM_read_bio_X509(bio, 0, 0, 0) : 0; + if (bio) BIO_free(bio); + if (!certificate) { + ERR_clear_error(); + error = "The TLS certificate is not valid PEM."; + return false; + } + X509_free(certificate); + + const std::string temporary = path + ".tmp"; + { + std::ofstream file(temporary.c_str(), std::ios::binary | std::ios::trunc); + if (!file) { error = "Could not create the TLS certificate file."; return false; } + file.write(pem.data(), pem.size()); + file.close(); + if (!file) { + std::remove(temporary.c_str()); + error = "Could not write the TLS certificate file."; + return false; + } + } +#ifndef _WIN32 + chmod(temporary.c_str(), 0600); +#endif +#ifdef _WIN32 + const bool replaced = MoveFileExA(temporary.c_str(), path.c_str(), + MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH) != 0; +#else + const bool replaced = std::rename(temporary.c_str(), path.c_str()) == 0; +#endif + if (!replaced) { + std::remove(temporary.c_str()); + error = "Could not replace the TLS certificate file."; + return false; + } + return true; +} + CTLSClientSocket::CTLSClientSocket(const string_type& host, port_type port) : CClientSocket(host, port), ctx_(0), ssl_(0) { @@ -100,7 +213,7 @@ CTLSClientSocket::CTLSClientSocket(const string_type& host, port_type port) // A pin file that exists but cannot be used is an error, never a reason // to fall back to the system store. - const std::string pinPath = pinnedCertPath(); + const std::string pinPath = pinnedCertPath(host, port); const bool pin = !pinPath.empty(); if (pin) { FILE * f = fopen(pinPath.c_str(), "r"); diff --git a/src/util/genutil/JsonConfigurationProfile.C b/src/util/genutil/JsonConfigurationProfile.C new file mode 100644 index 0000000000..0935063f47 --- /dev/null +++ b/src/util/genutil/JsonConfigurationProfile.C @@ -0,0 +1,459 @@ +#include "util/JsonConfigurationProfile.H" + +#include "util/MiniJson.H" + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#endif + +using std::string; +using std::vector; + +namespace { + +string quote(const string& s) +{ + string out = "\""; + for (size_t i = 0; i < s.size(); ++i) { + const unsigned char c = static_cast(s[i]); + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (c < 0x20) { + char hex[7]; + snprintf(hex, sizeof(hex), "\\u%04x", c); + out += hex; + } else out += static_cast(c); + } + } + out += '"'; + return out; +} + +string lower(const string& s) +{ + string out = s; + for (size_t i = 0; i < out.size(); ++i) + if (out[i] >= 'A' && out[i] <= 'Z') out[i] += 'a' - 'A'; + return out; +} + +bool allowedMachineSetting(const string& key) +{ + const string k = lower(key); + return k == "shell" || k == "sourcefile" || k == "allocationcommand" || + k == "frontendmachine" || k == "frontendbypass" || k == "perlpath" || + k == "qmgrpath" || k == "libpath" || k == "xappspath" || + k == "noremoteaccess" || k == "usersubmit" || + k == "singleconnect" || k == "checkscratch" || k == "issamedomain"; +} + +void strings(std::ostringstream& out, const vector& values) +{ + out << '['; + for (size_t i = 0; i < values.size(); ++i) { + if (i) out << ','; + out << quote(values[i]); + } + out << ']'; +} + +bool credentialFreeUrl(const string& url) +{ + const size_t scheme = url.find("://"); + if (scheme == string::npos) return false; + const size_t authority = scheme + 3; + const size_t end = url.find_first_of("/?#", authority); + const size_t at = url.find('@', authority); + return at == string::npos || (end != string::npos && at > end); +} + +bool valid(const JsonConfigurationProfile::Profile& p, string& error) +{ + for (size_t i = 0; i < p.dataServers.size(); ++i) { + const JsonConfigurationProfile::DataServer& s = p.dataServers[i]; + if (s.name.empty() || s.url.empty() || !credentialFreeUrl(s.url)) { + error = "A data server needs a name and a URL without embedded credentials."; + return false; + } + if (s.username.find_first_of("\t\r\n") != string::npos) { + error = "A data-server username cannot contain tabs or line breaks."; + return false; + } + } + for (size_t i = 0; i < p.computeResources.size(); ++i) { + const JsonConfigurationProfile::ComputeResource& r = p.computeResources[i]; + if (r.name.empty() || r.name.find_first_of("/\\\t\r\n") != string::npos || + r.host.find('@') != string::npos || + r.host.find_first_of("\t\r\n") != string::npos) { + error = "A compute resource needs a name and a host without a login prefix."; + return false; + } + if (p.version >= 2 && + (r.host.empty() || r.vendor.empty() || r.model.empty() || + r.processor.empty() || r.processors == 0 || r.queueManager.empty() || + r.vendor.find_first_of("\t\r\n") != string::npos || + r.model.find_first_of("\t\r\n") != string::npos || + r.processor.find_first_of("\t\r\n") != string::npos || + r.queueManager.find_first_of("\t\r\n") != string::npos)) { + error = "A compute resource is missing required registration details."; + return false; + } + for (size_t prior = 0; prior < i; ++prior) { + if (p.computeResources[prior].name == r.name) { + error = "A compute resource name appears more than once."; + return false; + } + } + for (size_t j = 0; j < r.codes.size(); ++j) { + if (r.codes[j].name.empty() || + r.codes[j].name.find_first_of(":{}, \t\r\n") != string::npos || + r.codes[j].program.find_first_of("\t\r\n") != string::npos) { + error = "A compute resource contains a code with no name."; + return false; + } + for (size_t prior = 0; prior < j; ++prior) { + if (r.codes[prior].name == r.codes[j].name) { + error = "A code name appears more than once in a compute resource."; + return false; + } + } + for (size_t k = 0; k < r.codes[j].modules.size(); ++k) { + if (r.codes[j].modules[k].empty() || + r.codes[j].modules[k].find_first_of(" \t\r\n") != string::npos) { + error = "A code module name is empty or contains whitespace."; + return false; + } + } + } + for (size_t j = 0; j < r.queues.size(); ++j) { + const JsonConfigurationProfile::Queue& q = r.queues[j]; + if (q.name.empty() || q.name.find_first_not_of( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-") != string::npos) { + error = "A queue name contains unsupported characters."; + return false; + } + if (q.memUnits.find_first_of(",|\t\r\n") != string::npos) { + error = "Queue memory units contain an invalid character."; + return false; + } + for (size_t prior = 0; prior < j; ++prior) { + if (r.queues[prior].name == q.name) { + error = "A queue name appears more than once in a compute resource."; + return false; + } + } + } + for (size_t j = 0; j < r.settings.size(); ++j) { + const JsonConfigurationProfile::Setting& setting = r.settings[j]; + if (!allowedMachineSetting(setting.name) || setting.value.empty() || + setting.name.find_first_of(":{}\t\r\n") != string::npos || + setting.value.find_first_of("\r\n") != string::npos) { + error = "A machine setting is not allowed in a configuration profile."; + return false; + } + for (size_t prior = 0; prior < j; ++prior) { + if (lower(r.settings[prior].name) == lower(setting.name)) { + error = "A machine setting appears more than once."; + return false; + } + } + } + if (p.version >= 2 && + ((r.queueManager == "None" && !r.queues.empty()) || + (r.queueManager != "None" && r.queues.empty()))) { + error = "A resource must have queues when a queue manager is selected."; + return false; + } + } + return true; +} + +bool readString(const MiniJson& object, const string& key, string& value) +{ + const MiniJson& v = object.get(key); + if (!v.isString()) return false; + value = v.str(); + return true; +} + +bool readStringArray(const MiniJson& value, vector& out) +{ + if (value.type() != MiniJson::Array) return false; + out.clear(); + for (size_t i = 0; i < value.items().size(); ++i) { + if (!value.items()[i].isString()) return false; + out.push_back(value.items()[i].str()); + } + return true; +} + +bool readUnsigned(const MiniJson& object, const string& key, unsigned int& value) +{ + const MiniJson& v = object.get(key); + if (v.type() != MiniJson::Number || v.str().empty()) return false; + for (size_t i = 0; i < v.str().size(); ++i) + if (v.str()[i] < '0' || v.str()[i] > '9') return false; + char* end = 0; + const unsigned long parsed = strtoul(v.str().c_str(), &end, 10); + if (!end || *end || parsed > UINT_MAX) return false; + value = static_cast(parsed); + return true; +} + +} // namespace + +namespace JsonConfigurationProfile { + +bool save(const string& path, const Profile& profile, string& error) +{ + if (path.empty()) { error = "Choose a file name."; return false; } + if (!valid(profile, error)) return false; + + std::ostringstream out; + out << "{\n \"format\": \"ecce-configuration\",\n \"version\": 3,\n"; + out << " \"dataServers\": ["; + for (size_t i = 0; i < profile.dataServers.size(); ++i) { + const DataServer& s = profile.dataServers[i]; + out << (i ? "," : "") << "\n {\"name\":" << quote(s.name) + << ",\"url\":" << quote(s.url) + << ",\"username\":" << quote(s.username) + << ",\"tlsCertificatePem\":" << quote(s.tlsCertificatePem) << "}"; + } + if (!profile.dataServers.empty()) out << '\n' << " "; + out << "],\n \"computeResources\": ["; + for (size_t i = 0; i < profile.computeResources.size(); ++i) { + const ComputeResource& r = profile.computeResources[i]; + out << (i ? "," : "") << "\n {\"name\":" << quote(r.name) + << ",\"host\":" << quote(r.host) + << ",\"vendor\":" << quote(r.vendor) + << ",\"model\":" << quote(r.model) + << ",\"processor\":" << quote(r.processor) + << ",\"processors\":" << r.processors + << ",\"nodes\":" << r.nodes + << ",\"allocationAccounts\":" << (r.allocationAccounts ? 1 : 0) + << ",\"queueManager\":" << quote(r.queueManager) + << ",\"codes\":["; + for (size_t j = 0; j < r.codes.size(); ++j) { + const Code& c = r.codes[j]; + out << (j ? "," : "") << "{\"name\":" << quote(c.name) + << ",\"program\":" << quote(c.program) << ",\"modules\":"; + strings(out, c.modules); + out << '}'; + } + out << "],\"queues\":["; + for (size_t j = 0; j < r.queues.size(); ++j) { + const Queue& q = r.queues[j]; + out << (j ? "," : "") << "{\"name\":" << quote(q.name) + << ",\"minProcessors\":" << q.minProcessors + << ",\"maxProcessors\":" << q.maxProcessors + << ",\"maxCPU\":" << q.maxCPU + << ",\"maxMemory\":" << q.maxMemory + << ",\"minScratch\":" << q.minScratch + << ",\"defProcessors\":" << q.defProcessors + << ",\"defRun\":" << q.defRun + << ",\"defMemory\":" << q.defMemory + << ",\"defScratch\":" << q.defScratch + << ",\"memUnits\":" << quote(q.memUnits) + << ",\"requestLines\":" << quote(q.requestLines) << "}"; + } + out << "],\"settings\":["; + for (size_t j = 0; j < r.settings.size(); ++j) { + const Setting& setting = r.settings[j]; + out << (j ? "," : "") << "{\"name\":" << quote(setting.name) + << ",\"value\":" << quote(setting.value) << "}"; + } + out << "]}"; + } + if (!profile.computeResources.empty()) out << '\n' << " "; + out << "],\n \"jobCreationCodes\": "; + strings(out, profile.jobCreationCodes); + out << "\n}\n"; + + const string temporary = path + ".tmp"; + { + std::ofstream file(temporary.c_str(), std::ios::binary | std::ios::trunc); + if (!file) { error = "Could not open the temporary configuration file."; return false; } + file << out.str(); + file.close(); + if (!file) { + std::remove(temporary.c_str()); + error = "Could not write the configuration file."; + return false; + } + } +#ifdef _WIN32 + const bool replaced = MoveFileExA(temporary.c_str(), path.c_str(), + MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH) != 0; +#else + const bool replaced = std::rename(temporary.c_str(), path.c_str()) == 0; +#endif + if (!replaced) { + std::remove(temporary.c_str()); + error = "Could not replace the configuration file."; + return false; + } + return true; +} + +bool load(const string& path, Profile& profile, string& error) +{ + std::ifstream file(path.c_str(), std::ios::binary); + if (!file) { error = "Could not open the configuration file."; return false; } + std::ostringstream contents; + contents << file.rdbuf(); + if (contents.str().size() > 8 * 1024 * 1024) { + error = "The configuration file is larger than 8 MB."; + return false; + } + MiniJson root; + if (!MiniJson::parse(contents.str(), root, error) || + root.type() != MiniJson::Object) { + if (error.empty()) error = "The configuration must be a JSON object."; + return false; + } + string format; + if (!readString(root, "format", format) || format != "ecce-configuration" || + root.get("version").type() != MiniJson::Number || + (root.get("version").str() != "1" && root.get("version").str() != "2" && + root.get("version").str() != "3")) { + error = "This is not a supported ECCE configuration profile."; + return false; + } + const bool fullMachineDefinitions = root.get("version").str() == "2" || + root.get("version").str() == "3"; + + Profile parsed; + parsed.version = static_cast(atoi(root.get("version").str().c_str())); + const MiniJson& servers = root.get("dataServers"); + if (servers.type() != MiniJson::Array) { + error = "The configuration has no valid data server list."; + return false; + } + for (size_t i = 0; i < servers.items().size(); ++i) { + const MiniJson& item = servers.items()[i]; + DataServer s; + if (!readString(item, "name", s.name) || !readString(item, "url", s.url) || + !readString(item, "tlsCertificatePem", s.tlsCertificatePem)) { + error = "A data server entry is missing a required string field."; + return false; + } + if (parsed.version >= 3 && !readString(item, "username", s.username)) { + error = "A data server entry is missing its username field."; + return false; + } + parsed.dataServers.push_back(s); + } + + const MiniJson& resources = root.get("computeResources"); + if (resources.type() != MiniJson::Array) { + error = "The configuration has no valid compute resource list."; + return false; + } + for (size_t i = 0; i < resources.items().size(); ++i) { + const MiniJson& item = resources.items()[i]; + ComputeResource r; + if (!readString(item, "name", r.name) || !readString(item, "host", r.host) || + item.get("codes").type() != MiniJson::Array) { + error = "A compute resource entry is missing a required field."; + return false; + } + if (fullMachineDefinitions && + (!readString(item, "vendor", r.vendor) || + !readString(item, "model", r.model) || + !readString(item, "processor", r.processor) || + !readUnsigned(item, "processors", r.processors) || + !readUnsigned(item, "nodes", r.nodes) || + !readString(item, "queueManager", r.queueManager) || + item.get("queues").type() != MiniJson::Array || + item.get("settings").type() != MiniJson::Array)) { + error = "A compute resource is missing machine registration details."; + return false; + } + // Older administrator profiles can contain machine definitions whose + // vendor, model, or processor was left blank. MyMachines is tokenized + // on tabs, so empty columns would shift the remaining fields and make + // the resource unusable. Use the same generic label as the machine + // registration UI for those optional descriptors. + if (fullMachineDefinitions) { + if (r.vendor.empty()) r.vendor = "Unspecified"; + if (r.model.empty()) r.model = "Unspecified"; + if (r.processor.empty()) r.processor = "Unspecified"; + } + if (fullMachineDefinitions) { + unsigned int allocationAccounts = 0; + if (!readUnsigned(item, "allocationAccounts", allocationAccounts) || + allocationAccounts > 1) { + error = "A compute resource has an invalid allocation account setting."; + return false; + } + r.allocationAccounts = allocationAccounts != 0; + } + const MiniJson& codes = item.get("codes"); + for (size_t j = 0; j < codes.items().size(); ++j) { + const MiniJson& code = codes.items()[j]; + Code c; + if (!readString(code, "name", c.name) || !readString(code, "program", c.program) || + !readStringArray(code.get("modules"), c.modules)) { + error = "A code entry is missing a required field."; + return false; + } + r.codes.push_back(c); + } + if (fullMachineDefinitions) { + const MiniJson& queues = item.get("queues"); + for (size_t j = 0; j < queues.items().size(); ++j) { + const MiniJson& entry = queues.items()[j]; + Queue q; + if (!readString(entry, "name", q.name) || + !readUnsigned(entry, "minProcessors", q.minProcessors) || + !readUnsigned(entry, "maxProcessors", q.maxProcessors) || + !readUnsigned(entry, "maxCPU", q.maxCPU) || + !readUnsigned(entry, "maxMemory", q.maxMemory) || + !readUnsigned(entry, "minScratch", q.minScratch) || + !readUnsigned(entry, "defProcessors", q.defProcessors) || + !readUnsigned(entry, "defRun", q.defRun) || + !readUnsigned(entry, "defMemory", q.defMemory) || + !readUnsigned(entry, "defScratch", q.defScratch) || + !readString(entry, "memUnits", q.memUnits) || + !readString(entry, "requestLines", q.requestLines)) { + error = "A queue entry is missing a required field."; + return false; + } + r.queues.push_back(q); + } + const MiniJson& settings = item.get("settings"); + for (size_t j = 0; j < settings.items().size(); ++j) { + Setting setting; + if (!readString(settings.items()[j], "name", setting.name) || + !readString(settings.items()[j], "value", setting.value)) { + error = "A machine setting is missing a required field."; + return false; + } + r.settings.push_back(setting); + } + } + parsed.computeResources.push_back(r); + } + if (!readStringArray(root.get("jobCreationCodes"), parsed.jobCreationCodes)) { + error = "The configuration has no valid job creation code list."; + return false; + } + if (!valid(parsed, error)) return false; + profile = parsed; + return true; +} + +} // namespace JsonConfigurationProfile diff --git a/src/util/genutil/LocalData.C b/src/util/genutil/LocalData.C index af5510bc7a..89a1f6c2a5 100644 --- a/src/util/genutil/LocalData.C +++ b/src/util/genutil/LocalData.C @@ -13,6 +13,7 @@ #endif #include +#include #include #include @@ -21,6 +22,7 @@ #include "util/LocalData.H" #include "util/PreferenceLabels.H" #include "util/Preferences.H" +#include "util/RemoteServerDir.H" namespace { @@ -59,6 +61,24 @@ void mkdirs(const string& path, mode_t mode) } } +// Keep a pre-local-default Linux setup on its existing data server when no +// LocalData preference was ever written. These markers are only consulted +// for the default: an explicit preference or session environment wins. +bool hasExistingDataServerSetup() +{ + const string userPrefs = Ecce::realUserPrefPath(); + if (isDir(userPrefs + "dataserver")) return true; + if (access((userPrefs + "RemoteServer/DataServers").c_str(), R_OK) == 0 || + access((remoteServerDir() + "/DataServers").c_str(), R_OK) == 0) + return true; + + std::ifstream answer((userPrefs + "first-start-answer").c_str()); + string value; + if (std::getline(answer, value) && value.compare(0, 6, "server") == 0) + return true; + return false; +} + // Windows opens files as text unless told otherwise. #ifndef O_BINARY #define O_BINARY 0 @@ -226,12 +246,10 @@ bool LocalData::prefEnabled() Preferences pref(PrefLabels::GLOBALPREFFILE); bool on = false; if (pref.getBool(PrefLabels::LOCALDATA, on)) return on; -#ifdef __APPLE__ - // macOS has no mod_dav for a per-user data server: local by default. - return true; -#else - return false; -#endif + // New users keep jobs in a folder on every platform. Preserve an older + // server setup when its preference is still unset; an explicit off value + // above continues to select that server deliberately. + return !hasExistingDataServerSetup(); } string LocalData::prefFolder() diff --git a/src/util/genutil/ServerList.C b/src/util/genutil/ServerList.C index b80314e172..7a68b82c8e 100644 --- a/src/util/genutil/ServerList.C +++ b/src/util/genutil/ServerList.C @@ -48,8 +48,11 @@ vector ServerList::load() e.name = line.substr(a + 1, b - a - 1); size_t c = line.find('\t', b + 1); e.address = line.substr(b + 1, c == string::npos ? c : c - b - 1); + const size_t d = c == string::npos ? string::npos : line.find('\t', c + 1); // Three-column entries predate the option and retain their startup behavior. - e.connectAtStart = c == string::npos || line.substr(c + 1) != "0"; + e.connectAtStart = c == string::npos || + line.substr(c + 1, d == string::npos ? d : d - c - 1) != "0"; + if (d != string::npos) e.username = line.substr(d + 1); if (check(e).empty()) out.push_back(e); } return out; @@ -63,9 +66,12 @@ bool ServerList::save(const vector& list) { std::ofstream out(tmp.c_str(), std::ios::binary | std::ios::trunc); if (!out) return false; - for (size_t i = 0; i < list.size(); i++) + for (size_t i = 0; i < list.size(); i++) { out << list[i].type << '\t' << list[i].name << '\t' << list[i].address - << '\t' << (list[i].connectAtStart ? 1 : 0) << '\n'; + << '\t' << (list[i].connectAtStart ? 1 : 0); + if (!list[i].username.empty()) out << '\t' << list[i].username; + out << '\n'; + } if (!out) return false; } remove(path.c_str()); // rename() does not replace on Windows @@ -80,6 +86,10 @@ string ServerList::check(const ServerEntry& e) if (blank(e.address)) return "Type the address of the server."; if (!clean(e.name) || !clean(e.address)) return "The name and the address cannot contain tabs or line breaks."; + if (!clean(e.username)) + return "The username cannot contain tabs or line breaks."; + if (e.type == "ssh" && !e.username.empty()) + return "A username field is only used for an ECCE data server."; if (e.type == "ecce" && e.address.compare(0, 8, "https://") != 0 && !getenv("ECCE_TEST_ALLOW_HTTP_SERVER")) return "The address of an ECCE server starts with https://"; diff --git a/src/wxgui/wxdialogs/AddServerDialog.C b/src/wxgui/wxdialogs/AddServerDialog.C index 6e670d026a..0cf7bd20e7 100644 --- a/src/wxgui/wxdialogs/AddServerDialog.C +++ b/src/wxgui/wxdialogs/AddServerDialog.C @@ -3,10 +3,15 @@ #include "wx/process.h" #include "wx/sstream.h" #include "wx/gbsizer.h" +#include "wx/filedlg.h" +#include +#include #include #include "util/Ecce.H" +#include "util/EcceURL.H" #include "dsm/SftpEDSI.H" +#include "dsm/CTLSSocket.H" #include "wxgui/ewxButton.H" #include "wxgui/ewxChoice.H" #include "wxgui/ewxStaticText.H" @@ -41,9 +46,16 @@ AddServerDialog::AddServerDialog(wxWindow* parent, const ServerEntry* old) p_folder = new ewxTextCtrl(this, wxID_ANY); p_port = new ewxTextCtrl(this, wxID_ANY, "22"); p_address = new ewxTextCtrl(this, wxID_ANY); + p_eccUser = new ewxTextCtrl(this, wxID_ANY); + p_certificate = new ewxTextCtrl(this, wxID_ANY, wxEmptyString, + wxDefaultPosition, wxDefaultSize, wxTE_READONLY); + p_chooseCertificate = new ewxButton(this, wxID_ANY, _("Choose...")); p_host->SetHint(_("hpc.example.edu")); p_folder->SetHint(_("/home/me/ecce")); p_address->SetHint(_("https://ecce.example.edu:port")); + p_eccUser->SetHint(_("Account name on this data server")); + p_eccUser->SetToolTip(_("Saved with the server configuration; ECCE asks for the password when you connect.")); + p_certificate->SetHint(_("Optional; uses the system certificate store when blank")); p_address->SetToolTip(_("A port other than 443 goes in the address: https://host:8443")); p_port->SetToolTip(_("The port the SSH server listens on; 22 unless the site says otherwise.")); @@ -65,6 +77,19 @@ AddServerDialog::AddServerDialog(wxWindow* parent, const ServerEntry* old) grid->Add(p_address, 1, wxGROW); p_eccRows[m++] = al; p_eccRows[m++] = p_address; + p_eccUserLabel = new ewxStaticText(this, wxID_ANY, _("Username:")); + grid->Add(p_eccUserLabel, 0, wxALIGN_CENTER_VERTICAL); + grid->Add(p_eccUser, 1, wxGROW); + p_eccRows[m++] = p_eccUserLabel; + p_eccRows[m++] = p_eccUser; + p_certificateLabel = new ewxStaticText(this, wxID_ANY, _("TLS certificate:")); + wxBoxSizer* certRow = new wxBoxSizer(wxHORIZONTAL); + certRow->Add(p_certificate, 1, wxGROW|wxRIGHT, PAD); + certRow->Add(p_chooseCertificate, 0, wxALIGN_CENTER_VERTICAL); + grid->Add(p_certificateLabel, 0, wxALIGN_CENTER_VERTICAL); + grid->Add(certRow, 1, wxGROW); + p_certificate->SetToolTip(_("Optional PEM certificate used to verify this HTTPS server.")); + p_chooseCertificate->SetToolTip(_("Choose a PEM certificate for this server.")); top->Add(grid, 0, wxGROW|wxALL, PAD*2); p_startup = new wxCheckBox(this, wxID_ANY, _("Connect at start")); @@ -93,6 +118,15 @@ AddServerDialog::AddServerDialog(wxWindow* parent, const ServerEntry* old) p_name->SetValue(wxString::FromUTF8(old->name.c_str())); if (sel == 1) { p_address->SetValue(wxString::FromUTF8(old->address.c_str())); + p_eccUser->SetValue(wxString::FromUTF8(old->username.c_str())); + EcceURL url(old->address); + if (url.getProtocol() == "https") { + ipc::CTLSClientSocket::port_type port = url.getPort() > 0 + ? (ipc::CTLSClientSocket::port_type)url.getPort() + : (ipc::CTLSClientSocket::port_type)443; + p_certificatePath = ipc::CTLSClientSocket::pinnedCertPath(url.getHost(), port); + p_certificate->SetValue(wxString::FromUTF8(p_certificatePath.c_str())); + } } else { std::string u, h, f; if (ServerList::parseSsh(old->address, u, h, f)) { @@ -110,6 +144,8 @@ AddServerDialog::AddServerDialog(wxWindow* parent, const ServerEntry* old) showType(); p_type->Bind(wxEVT_CHOICE, &AddServerDialog::OnType, this); + p_chooseCertificate->Bind(wxEVT_BUTTON, + &AddServerDialog::OnChooseCertificate, this); p_test->Bind(wxEVT_BUTTON, &AddServerDialog::OnTest, this); Bind(wxEVT_END_PROCESS, &AddServerDialog::OnTestDone, this); ok->Bind(wxEVT_BUTTON, &AddServerDialog::OnOk, this); @@ -126,7 +162,10 @@ void AddServerDialog::showType() { bool ssh = p_type->GetSelection() == 0; for (int i = 0; i < 8; i++) p_sshRows[i]->Show(ssh); - for (int i = 0; i < 2; i++) p_eccRows[i]->Show(!ssh); + for (int i = 0; i < 4; i++) p_eccRows[i]->Show(!ssh); + p_certificateLabel->Show(!ssh); + p_certificate->Show(!ssh); + p_chooseCertificate->Show(!ssh); p_test->Enable(true); p_test->SetToolTip(ssh ? _("Log in and check that the folder exists and can be written.") : _("Check that the server answers and its certificate.")); @@ -162,6 +201,7 @@ bool AddServerDialog::collect(ServerEntry& e) const } else { e.type = "ecce"; e.address = p_address->GetValue().Trim().Trim(false).ToStdString(); + e.username = p_eccUser->GetValue().Trim().Trim(false).ToStdString(); } return true; } @@ -215,6 +255,11 @@ void AddServerDialog::OnTest(wxCommandEvent&) p_status->SetLabel(_("Type the address of the server first.")); return; } + std::string certError; + if (!applyCertificate(a, certError)) { + p_status->SetLabel(wxString::FromUTF8(certError.c_str())); + return; + } wxString home = wxString::FromUTF8(Ecce::ecceHome()); #ifdef __WXMSW__ wxString cmd = "\"" + home + "/python/python3w.exe\" \"" + home + @@ -259,7 +304,20 @@ void AddServerDialog::OnOk(wxCommandEvent&) { ServerEntry e; collect(e); - std::string err = ServerList::replace(p_old, e); + std::string err = ServerList::check(e); + if (!err.empty()) { + p_status->SetLabel(wxString::FromUTF8(err.c_str())); + Layout(); + Fit(); + return; + } + if (!applyCertificate(e.address, err)) { + p_status->SetLabel(wxString::FromUTF8(err.c_str())); + Layout(); + Fit(); + return; + } + err = ServerList::replace(p_old, e); if (!err.empty()) { p_status->SetLabel(wxString::FromUTF8(err.c_str())); Layout(); @@ -271,9 +329,46 @@ void AddServerDialog::OnOk(wxCommandEvent&) } +void AddServerDialog::OnChooseCertificate(wxCommandEvent&) +{ + wxFileDialog dlg(this, _("Select TLS certificate"), wxEmptyString, + wxEmptyString, _("PEM certificates (*.pem)|*.pem|All files (*.*)|*.*"), + wxFD_OPEN|wxFD_FILE_MUST_EXIST); + if (dlg.ShowModal() != wxID_OK) return; + p_certificatePath = dlg.GetPath().ToStdString(); + p_certificate->SetValue(dlg.GetPath()); + p_status->SetLabel(wxEmptyString); +} + + +bool AddServerDialog::applyCertificate(const string& address, + string& error) const +{ + if (p_certificatePath.empty()) return true; + EcceURL url(address); + if (url.getProtocol() != "https") { + error = "A TLS certificate can only be assigned to an HTTPS data server."; + return false; + } + std::ifstream file(p_certificatePath.c_str(), std::ios::binary); + std::ostringstream contents; + if (file) contents << file.rdbuf(); + if (!file || contents.str().empty()) { + error = "The certificate file could not be read or is empty."; + return false; + } + ipc::CTLSClientSocket::port_type port = url.getPort() > 0 + ? (ipc::CTLSClientSocket::port_type)url.getPort() + : (ipc::CTLSClientSocket::port_type)443; + return ipc::CTLSClientSocket::storePinnedCertificate( + url.getHost(), port, contents.str(), error); +} + + void AddServerDialog::fillForTest(bool ssh, const std::string& name, const std::string& a, const std::string& b, - const std::string& c) + const std::string& c, + const std::string& username) { p_type->SetSelection(ssh ? 0 : 1); showType(); @@ -284,6 +379,7 @@ void AddServerDialog::fillForTest(bool ssh, const std::string& name, p_folder->SetValue(wxString::FromUTF8(c.c_str())); } else { p_address->SetValue(wxString::FromUTF8(a.c_str())); + p_eccUser->SetValue(wxString::FromUTF8(username.c_str())); } } diff --git a/src/wxgui/wxdialogs/GlobalPrefs.C b/src/wxgui/wxdialogs/GlobalPrefs.C index 45b86c434f..e1fb04e8f6 100644 --- a/src/wxgui/wxdialogs/GlobalPrefs.C +++ b/src/wxgui/wxdialogs/GlobalPrefs.C @@ -16,13 +16,19 @@ #include "wx/scrolwin.h" #include +#include +#include #include #include +#include #include "util/JMSMessage.H" #include "util/JMSPublisher.H" #include "util/Preferences.H" #include "dsm/CodeChoice.H" +#include "dsm/CodeFactory.H" +#include "dsm/MachinePreferences.H" +#include "tdat/RefMachine.H" #include "util/PreferenceLabels.H" #include "util/TDateTime.H" #include "util/UnitFactory.H" @@ -32,9 +38,15 @@ #include "util/RemoteServerDir.H" #include "util/LocalData.H" #include "util/ServerList.H" +#include "util/ProcessMachine.H" +#include "tdat/ConfigFile.H" +#include "tdat/Queue.H" +#include "tdat/QueueMgr.H" #include "util/WindowLayout.H" #include "dsm/ResourceDescriptor.H" +#include "dsm/CTLSSocket.H" +#include "util/EcceURL.H" #include "tdat/TPerTab.H" #include "wxgui/ewxBitmap.H" @@ -52,6 +64,7 @@ #include "wxgui/AddServerDialog.H" #include "wxgui/GlobalPrefs.H" #include "wxgui/WindowShot.H" +#include "util/JsonConfigurationProfile.H" namespace { @@ -95,6 +108,65 @@ namespace { return s.substr(a, s.find_last_not_of(" \t") - a + 1); } + vector splitWords(const string& s) + { + std::istringstream in(s); + vector words; + string word; + while (in >> word) words.push_back(word); + return words; + } + + string lowerAscii(string s) + { + for (size_t i = 0; i < s.size(); ++i) + s[i] = static_cast(std::tolower(static_cast(s[i]))); + return s; + } + + bool safeProfileValue(const string& value, const string& localUser, + const string& remoteUser) + { + const string lower = lowerAscii(value); + const char* sensitive[] = { "password", "passwd", "credential", "token", + "secret", "username", "user=", "--account", + "account=" }; + for (size_t i = 0; i < sizeof(sensitive)/sizeof(sensitive[0]); ++i) + if (lower.find(sensitive[i]) != string::npos) return false; + if ((!localUser.empty() && value.find(localUser) != string::npos) || + (!remoteUser.empty() && value.find(remoteUser) != string::npos)) + return false; + return true; + } + + string profileRequestLines(const string& lines, const string& localUser, + const string& remoteUser) + { + std::istringstream input(lines); + string line, result; + while (std::getline(input, line)) { + if (!safeProfileValue(line, localUser, remoteUser)) continue; + if (!result.empty()) result += '\n'; + result += line; + } + return result; + } + + string readPinnedCertificate(const string& url) + { + EcceURL server(url); + const string path = ipc::CTLSClientSocket::pinnedCertPath( + server.getHost(), server.getPort() > 0 + ? (ipc::CTLSClientSocket::port_type)server.getPort() + : (ipc::CTLSClientSocket::port_type)443); + if (path.empty()) return ""; + std::ifstream in(path.c_str(), std::ios::binary); + if (!in) return ""; + std::ostringstream contents; + contents << in.rdbuf(); + return contents.str(); + } + const wxWindowID ID_PROGRAM_CHOICE = wxNewId(); const wxWindowID ID_PROGRAM_TEXT = wxNewId(); @@ -113,6 +185,7 @@ GlobalPrefs::GlobalPrefs(wxWindow* parent) p_localFolder(NULL), p_changeFolder(NULL), p_openFolder(NULL), p_localNote(NULL), p_serverList(NULL), p_addServer(NULL), p_editServer(NULL), p_removeServer(NULL), + p_saveConfiguration(NULL), p_loadConfiguration(NULL), p_resetAll(NULL), p_restoring(true) { p_editor.choice = p_terminal.choice = p_browser.choice = NULL; @@ -339,6 +412,25 @@ void GlobalPrefs::createGeneralPage(wxWindow* page) } outer->Add(box4, 0, wxGROW|wxALL, PAD); + wxStaticBoxSizer* profiles = new wxStaticBoxSizer(wxVERTICAL, page, + _("Configuration Profiles")); + wxWindow* profileBox = profiles->GetStaticBox(); + profiles->Add(new ewxStaticText(profileBox, wxID_ANY, + _("Save or load data server and compute resource settings as a JSON file.")), + 0, wxLEFT|wxRIGHT|wxTOP, PAD); + wxBoxSizer* profileButtons = new wxBoxSizer(wxHORIZONTAL); + p_saveConfiguration = new ewxButton(profileBox, wxID_ANY, + _("Save Configuration...")); + p_loadConfiguration = new ewxButton(profileBox, wxID_ANY, + _("Load Configuration...")); + profileButtons->Add(p_saveConfiguration, 0, wxRIGHT, PAD); + profileButtons->Add(p_loadConfiguration, 0); + profiles->Add(profileButtons, 0, wxALL, PAD); + outer->Add(profiles, 0, wxGROW|wxALL, PAD); + + p_saveConfiguration->Bind(wxEVT_BUTTON, &GlobalPrefs::OnSaveConfiguration, this); + p_loadConfiguration->Bind(wxEVT_BUTTON, &GlobalPrefs::OnLoadConfiguration, this); + page->SetSizer(outer); } @@ -958,12 +1050,14 @@ void GlobalPrefs::updateDataPage() r.name = _("This installation").ToStdString(); r.type = "ecce"; r.address = addr; + r.username.clear(); p_serverRows.push_back(r); } else if (chosenEarlier(addr)) { r.kind = ServerRow::EARLIER; r.name = _("Chosen at an earlier start").ToStdString(); r.type = "ecce"; r.address = addr; + r.username.clear(); p_serverRows.push_back(r); } vector mine = ServerList::load(); @@ -972,6 +1066,7 @@ void GlobalPrefs::updateDataPage() r.name = mine[i].name; r.type = mine[i].type; r.address = mine[i].address; + r.username = mine[i].username; p_serverRows.push_back(r); } for (size_t i = 0; i < p_serverRows.size(); i++) { @@ -1024,6 +1119,33 @@ void GlobalPrefs::OnServerSelect(wxListEvent& event) } +bool GlobalPrefs::loadServerCertificate(const string& address, + const string& path, + string& error) +{ + EcceURL url(address); + if (url.getProtocol() != "https") { + error = "A TLS certificate can only be assigned to an HTTPS data server."; + return false; + } + + std::ifstream file(path.c_str(), std::ios::binary); + std::ostringstream contents; + if (file) contents << file.rdbuf(); + if (!file || contents.str().empty()) { + error = "The certificate file could not be read or is empty."; + return false; + } + + const ipc::CTLSClientSocket::port_type port = url.getPort() > 0 + ? (ipc::CTLSClientSocket::port_type)url.getPort() + : (ipc::CTLSClientSocket::port_type)443; + if (!ipc::CTLSClientSocket::storePinnedCertificate( + url.getHost(), port, contents.str(), error)) return false; + return true; +} + + void GlobalPrefs::OnAddServer(wxCommandEvent& event) { AddServerDialog dlg(this); @@ -1041,6 +1163,7 @@ void GlobalPrefs::OnEditServer(wxCommandEvent& event) old.type = p_serverRows[at].type; old.name = p_serverRows[at].name; old.address = p_serverRows[at].address; + old.username = p_serverRows[at].username; AddServerDialog dlg(this, &old); dlg.ShowModal(); updateDataPage(); @@ -1075,6 +1198,440 @@ void GlobalPrefs::OnRemoveServer(wxCommandEvent& event) } +void GlobalPrefs::OnSaveConfiguration(wxCommandEvent& event) +{ + wxFileDialog dlg(this, _("Save ECCE configuration"), wxEmptyString, + "ecce-configuration.json", "JSON files (*.json)|*.json", + wxFD_SAVE|wxFD_OVERWRITE_PROMPT); + if (dlg.ShowModal() != wxID_OK) return; + + JsonConfigurationProfile::Profile profile; + for (size_t i = 0; i < p_serverRows.size(); ++i) { + const ServerRow& row = p_serverRows[i]; + if (row.kind == ServerRow::ADMIN || row.type != "ecce" || row.address.empty() || + row.address.find("@") != string::npos) + continue; + JsonConfigurationProfile::DataServer server; + server.name = row.name; + server.url = row.address; + server.username = row.username; + server.tlsCertificatePem = readPinnedCertificate(server.url); + profile.dataServers.push_back(server); + } + + profile.jobCreationCodes = CodeFactory::getMachineCodeNames(); + vector* names = RefMachine::referenceNames(RefMachine::allMachines); + for (size_t i = 0; names != NULL && i < names->size(); ++i) { + if ((*names)[i] == "localhost") continue; + RefMachine* machine = RefMachine::refLookup((*names)[i]); + if (machine == NULL) continue; + JsonConfigurationProfile::ComputeResource resource; + resource.name = machine->refname(); + resource.host = machine->fullname(); + resource.vendor = machine->vendor(); + resource.model = machine->model(); + resource.processor = machine->proctype(); + resource.processors = machine->proccount(); + resource.nodes = machine->nodes(); + resource.allocationAccounts = + machine->launchOptions().find("AA") != string::npos; + MachinePreferences* prefs = MachinePreferences::lookup(machine->refname()); + const string localUser = Ecce::realUser(); + const string remoteUser = prefs == NULL ? string() : prefs->getUsername(); + resource.queueManager = "None"; + const QueueManager* queueManager = QueueManager::lookup(resource.name); + if (queueManager != NULL) { + resource.queueManager = queueManager->queueMgrName(); + const ESQHDict* queueDict = queueManager->queues(); + if (queueDict != NULL) { + for (ESQHDict::const_iterator q = queueDict->begin(); + q != queueDict->end(); ++q) { + const Queue* source = q->second; + if (source == NULL) continue; + JsonConfigurationProfile::Queue queue; + queue.name = source->name(); + queue.minProcessors = source->minProcessors(); + queue.maxProcessors = source->maxProcessors(); + queue.maxCPU = source->runLimit(); + queue.maxMemory = source->memLimit(); + queue.minScratch = source->scratchLimit(); + queue.defProcessors = source->defProcessors(); + queue.defRun = source->defRun(); + queue.defMemory = source->defMemory(); + queue.defScratch = source->defScratch(); + queue.memUnits = source->memUnits(); + queue.requestLines = profileRequestLines(source->requestLines(), + localUser, remoteUser); + resource.queues.push_back(queue); + } + } + } + map config = RefMachine::config(machine->refname()); + const char* profileSettings[] = { + "shell", "sourceFile", "allocationCommand", "frontendMachine", + "frontendBypass", "perlPath", "qmgrPath", "libPath", "xappsPath", + "noRemoteAccess", "userSubmit", "singleConnect", "checkScratch", + "isSameDomain" + }; + for (size_t j = 0; j < sizeof(profileSettings)/sizeof(profileSettings[0]); ++j) { + const string key = lowerAscii(profileSettings[j]); + map::const_iterator setting = config.find(key); + if (setting == config.end() || setting->second.empty()) continue; + const string& value = setting->second; + if (!safeProfileValue(value, localUser, remoteUser) || + (!localUser.empty() && value.find("/" + localUser + "/") != string::npos) || + (!remoteUser.empty() && value.find("/" + remoteUser + "/") != string::npos)) + continue; + JsonConfigurationProfile::Setting exported; + exported.name = profileSettings[j]; + exported.value = value; + resource.settings.push_back(exported); + } + for (size_t j = 0; j < profile.jobCreationCodes.size(); ++j) { + const string& codeName = profile.jobCreationCodes[j]; + if (!machine->offersCode(codeName)) continue; + JsonConfigurationProfile::Code code; + code.name = codeName; + code.program = RefMachine::exePath(codeName, machine->refname(), + machine->vendor(), machine->model()); + const string modulesKey = lowerAscii(codeName) + "modules"; + map::const_iterator modules = config.find(modulesKey); + if (modules != config.end()) code.modules = splitWords(modules->second); + // Do not export a literal local or remote login embedded in a custom + // executable path. Module names are identifiers, not credentials. + if ((!localUser.empty() && + code.program.find("/" + localUser + "/") != string::npos) || + (!remoteUser.empty() && + code.program.find("/" + remoteUser + "/") != string::npos) || + !safeProfileValue(code.program, localUser, remoteUser)) + code.program.clear(); + resource.codes.push_back(code); + } + profile.computeResources.push_back(resource); + delete machine; + } + delete names; + + string error; + const string path = dlg.GetPath().ToStdString(); + if (!JsonConfigurationProfile::save(path, profile, error)) { + ewxMessageDialog message(this, wxString::FromUTF8(error.c_str()), + _("Save Configuration"), wxOK|wxICON_ERROR); + message.ShowModal(); + return; + } + ewxMessageDialog message(this, _("Configuration saved."), + _("Save Configuration"), wxOK|wxICON_INFORMATION); + message.ShowModal(); +} + + +void GlobalPrefs::OnLoadConfiguration(wxCommandEvent& event) +{ + wxFileDialog dlg(this, _("Load ECCE configuration"), wxEmptyString, + wxEmptyString, "JSON files (*.json)|*.json", + wxFD_OPEN|wxFD_FILE_MUST_EXIST); + if (dlg.ShowModal() != wxID_OK) return; + + JsonConfigurationProfile::Profile profile; + string error; + if (!JsonConfigurationProfile::load(dlg.GetPath().ToStdString(), profile, + error)) { + ewxMessageDialog message(this, wxString::FromUTF8(error.c_str()), + _("Load Configuration"), wxOK|wxICON_ERROR); + message.ShowModal(); + return; + } + + vector servers = ServerList::load(); + vector importedServers; + for (size_t i = 0; i < profile.dataServers.size(); ++i) { + ServerEntry server; + server.type = "ecce"; + server.name = profile.dataServers[i].name; + server.address = profile.dataServers[i].url; + server.username = profile.dataServers[i].username; + server.connectAtStart = false; + string invalid = ServerList::check(server); + if (!invalid.empty()) { + ewxMessageDialog message(this, wxString::FromUTF8(invalid.c_str()), + _("Load Configuration"), wxOK|wxICON_ERROR); + message.ShowModal(); + return; + } + for (size_t j = 0; j < importedServers.size(); ++j) { + if (importedServers[j].name == server.name) { + ewxMessageDialog message(this, _("The profile contains duplicate data server names."), + _("Load Configuration"), wxOK|wxICON_ERROR); + message.ShowModal(); + return; + } + } + importedServers.push_back(server); + } + + // Version 1 profiles contain code settings only and can be used with an + // existing registration. Version 2 adds machine definitions; version 3 + // also carries data-server usernames. + for (size_t i = 0; i < profile.computeResources.size(); ++i) { + if (profile.version == 1) { + RefMachine* machine = RefMachine::refLookup(profile.computeResources[i].name); + if (machine == NULL) { + string missing = profile.computeResources[i].name; + ewxMessageDialog message(this, + wxString::Format(_("This older profile does not contain enough details to create '%s'. Ask an administrator to export a new profile."), + wxString::FromUTF8(missing.c_str())), + _("Load Configuration"), wxOK|wxICON_ERROR); + message.ShowModal(); + return; + } + delete machine; + } + for (size_t j = 0; j < profile.computeResources[i].codes.size(); ++j) { + const JsonConfigurationProfile::Code& code = profile.computeResources[i].codes[j]; + if (code.program.find_first_of("\r\n") != string::npos) { + ewxMessageDialog message(this, _("A program path contains a line break."), + _("Load Configuration"), wxOK|wxICON_ERROR); + message.ShowModal(); + return; + } + for (size_t k = 0; k < code.modules.size(); ++k) { + if (code.modules[k].find_first_of(" \t\r\n") != string::npos) { + ewxMessageDialog message(this, _("A module name contains whitespace."), + _("Load Configuration"), wxOK|wxICON_ERROR); + message.ShowModal(); + return; + } + } + } + } + + std::ostringstream summary; + summary << "This profile contains " << profile.dataServers.size() + << " data servers, " << profile.computeResources.size() + << " compute resources, and " << profile.jobCreationCodes.size() + << " job creation codes.\n\n" + << "Merge adds or updates the listed resources and keeps other user resources.\n" + << "Replace removes ECCE servers absent from the profile and clears empty code paths and omitted shared settings on listed resources.\n" + << "SSH folders, unlisted user resources, and site machine definitions are kept.\n" + << "Data-server usernames are included; passwords and compute-resource login credentials are not."; + ewxMessageDialog message(this, wxString::FromUTF8(summary.str().c_str()), + _("Apply Configuration"), + wxYES_NO|wxCANCEL|wxICON_QUESTION); + message.SetButtonLabel(wxID_YES, _("Merge")); + message.SetButtonLabel(wxID_NO, _("Replace")); + const int choice = message.ShowModal(); + if (choice != wxID_YES && choice != wxID_NO) return; + const bool replace = choice == wxID_NO; + + // Build and validate the new server list before writing it. Merge by name; + // replace only the ECCE entries, preserving SSH folder configuration. + vector updatedServers; + for (size_t i = 0; i < servers.size(); ++i) { + if (servers[i].type == "ssh" || !replace) + updatedServers.push_back(servers[i]); + } + for (size_t i = 0; i < importedServers.size(); ++i) { + bool replaced = false; + for (size_t j = 0; j < updatedServers.size(); ++j) { + if (updatedServers[j].name == importedServers[i].name) { + if (updatedServers[j].type != "ecce") { + ewxMessageDialog errorDlg(this, + _("A server with the same name is already used by an SSH folder."), + _("Load Configuration"), wxOK|wxICON_ERROR); + errorDlg.ShowModal(); + return; + } + updatedServers[j] = importedServers[i]; + replaced = true; + break; + } + } + if (!replaced) updatedServers.push_back(importedServers[i]); + } + + if (profile.version >= 2) { + for (size_t i = 0; i < profile.computeResources.size(); ++i) { + const JsonConfigurationProfile::ComputeResource& resource = profile.computeResources[i]; + string form = "type=accept"; + form += ProcessMachine::field("siteconfig", "false"); + form += ProcessMachine::field("config", "external"); + form += ProcessMachine::field("machine", resource.host); + form += ProcessMachine::field("name", resource.name); + form += ProcessMachine::field("vendor", resource.vendor); + form += ProcessMachine::field("model", resource.model); + form += ProcessMachine::field("processor", resource.processor); + form += ProcessMachine::field("procs", std::to_string(resource.processors)); + form += ProcessMachine::field("nodes", std::to_string(resource.nodes)); + form += ProcessMachine::field("ssh", "true"); + string registeredCodes; + for (size_t j = 0; j < resource.codes.size(); ++j) { + if (j) registeredCodes += ","; + registeredCodes += resource.codes[j].name; + } + form += ProcessMachine::field("registeredcodes", registeredCodes); + for (size_t j = 0; j < resource.codes.size(); ++j) { + const JsonConfigurationProfile::Code& code = resource.codes[j]; + form += ProcessMachine::field(code.name, + code.program.empty() ? "EMSL" : code.program); + } + form += ProcessMachine::field("AA", + resource.allocationAccounts ? "true" : "false"); + form += ProcessMachine::field("qmgr", resource.queueManager); + form += ProcessMachine::field("numQueues", + std::to_string(resource.queues.size())); + for (size_t j = 0; j < resource.queues.size(); ++j) { + const JsonConfigurationProfile::Queue& queue = resource.queues[j]; + std::ostringstream details; + details << "name|" << queue.name + << ",minNodes|" << queue.minProcessors + << ",maxNodes|" << queue.maxProcessors + << ",maxCPU|" << queue.maxCPU + << ",maxMemory|" << queue.maxMemory + << ",minScratch|" << queue.minScratch + << ",defProcessors|" << queue.defProcessors + << ",defRun|" << queue.defRun + << ",defMemory|" << queue.defMemory + << ",defScratch|" << queue.defScratch + << ",memUnits|" << queue.memUnits; + string requestLines; + static const char hex[] = "0123456789ABCDEF"; + for (size_t k = 0; k < queue.requestLines.size(); ++k) { + const unsigned char c = static_cast(queue.requestLines[k]); + if (c == '%' || c == ',' || c == '|' || c == '\n' || c == '\r') { + requestLines += '%'; + requestLines += hex[c >> 4]; + requestLines += hex[c & 15]; + } else requestLines += static_cast(c); + } + details << ",requestLines|" << requestLines << ","; + form += ProcessMachine::field("q" + std::to_string(j), details.str()); + } + if (ProcessMachine::run(form) != 0) { + const string failed = resource.name; + ewxMessageDialog errorDlg(this, + wxString::Format(_("Could not register compute resource '%s' in your user configuration."), + wxString::FromUTF8(failed.c_str())), + _("Load Configuration"), wxOK|wxICON_ERROR); + errorDlg.ShowModal(); + return; + } + } + } + + // Write machine settings first. ConfigFile updates only the imported code + // keys in the user's layer, leaving site definitions and unrelated settings + // intact. Replace clears absent values for the codes in this profile. + string prefDir = Ecce::realUserPrefPath(); + vector stagedConfigs; + for (size_t i = 0; i < profile.computeResources.size(); ++i) { + const JsonConfigurationProfile::ComputeResource& resource = profile.computeResources[i]; + ConfigFile config; + const string configPath = prefDir + "CONFIG." + resource.name; + if (!config.load(configPath)) { + ewxMessageDialog errorDlg(this, _("Could not read a user machine configuration file."), + _("Load Configuration"), wxOK|wxICON_ERROR); + errorDlg.ShowModal(); + return; + } + bool configValid = true; + string configError; + for (size_t j = 0; j < resource.settings.size(); ++j) { + if (!config.set(resource.settings[j].name, resource.settings[j].value, + &configError)) { + configValid = false; + break; + } + } + for (size_t j = 0; j < resource.codes.size(); ++j) { + if (!configValid) break; + const JsonConfigurationProfile::Code& code = resource.codes[j]; + string modules; + for (size_t k = 0; k < code.modules.size(); ++k) { + if (k) modules += " "; + modules += code.modules[k]; + } + const string modulesKey = lowerAscii(code.name) + "modules"; + if (!code.program.empty() && code.program != "EMSL") { + if (!config.set(code.name, code.program, &configError)) { + configValid = false; + break; + } + } else if (replace) config.clear(code.name); + if (!modules.empty()) { + if (!config.set(modulesKey, modules, &configError)) { + configValid = false; + break; + } + } else if (replace) config.clear(modulesKey); + } + if (replace && profile.version >= 2) { + const char* replaceable[] = { + "shell", "sourceFile", "allocationCommand", "frontendMachine", + "frontendBypass", "perlPath", "qmgrPath", "libPath", "xappsPath", + "noRemoteAccess", "userSubmit", "singleConnect", "checkScratch", + "isSameDomain" + }; + for (size_t j = 0; j < sizeof(replaceable)/sizeof(replaceable[0]); ++j) { + bool included = false; + for (size_t k = 0; k < resource.settings.size(); ++k) + if (lowerAscii(resource.settings[k].name) == lowerAscii(replaceable[j])) + included = true; + if (!included) config.clear(replaceable[j]); + } + } + if (!configValid) { + ewxMessageDialog errorDlg(this, wxString::FromUTF8(configError.c_str()), + _("Load Configuration"), wxOK|wxICON_ERROR); + errorDlg.ShowModal(); + return; + } + stagedConfigs.push_back(config); + } + for (size_t i = 0; i < stagedConfigs.size(); ++i) { + string configError; + if (stagedConfigs[i].modified() && !stagedConfigs[i].save(&configError)) { + ewxMessageDialog errorDlg(this, wxString::FromUTF8(configError.c_str()), + _("Load Configuration"), wxOK|wxICON_ERROR); + errorDlg.ShowModal(); + return; + } + } + + // Save each pin against its URL origin; host-only/global certificate state + // is never changed by importing a profile. + for (size_t i = 0; i < profile.dataServers.size(); ++i) { + EcceURL url(profile.dataServers[i].url); + int port = url.getPort(); + if (port < 0) port = 443; + string certError; + if (!ipc::CTLSClientSocket::storePinnedCertificate( + url.getHost(), port, profile.dataServers[i].tlsCertificatePem, + certError)) { + ewxMessageDialog errorDlg(this, wxString::FromUTF8(certError.c_str()), + _("Load Configuration"), wxOK|wxICON_ERROR); + errorDlg.ShowModal(); + return; + } + } + if (!ServerList::save(updatedServers)) { + ewxMessageDialog errorDlg(this, _("The data server list could not be saved."), + _("Load Configuration"), wxOK|wxICON_ERROR); + errorDlg.ShowModal(); + return; + } + if (profile.version >= 2) { + RefMachine::markUpdateUserPrefs(); + QueueManager::finalize(); + } + updateDataPage(); + ewxMessageDialog done(this, + _("Configuration settings were applied. Compute resource login credentials were not imported; each user must configure their own login."), + _("Load Configuration"), wxOK|wxICON_INFORMATION); + done.ShowModal(); +} + + void GlobalPrefs::OnChangeDataFolder(wxCommandEvent& event) { string folder = LocalData::prefFolder(); @@ -1621,6 +2178,28 @@ string GlobalPrefs::dataTest(const string& line) vector w = words(); return !w.empty() && ecceClientShot(this, wxString::FromUTF8(w[0].c_str())) ? "saved" : "not saved"; } + if (op == "cert") { + vector w = words(); + if (w.empty()) return "bad arguments"; + for (size_t i = 0; i < p_serverRows.size(); ++i) { + if (p_serverRows[i].kind != ServerRow::LISTED) continue; + EcceURL url(p_serverRows[i].address); + if (url.getProtocol() != "https") continue; + p_serverList->SetItemState(i, wxLIST_STATE_SELECTED, + wxLIST_STATE_SELECTED); + updateServerButtons(); + string error; + if (!loadServerCertificate(p_serverRows[i].address, w[0], error)) + return "error=" + error; + if (w.size() > 1) + ecceClientShot(this, wxString::FromUTF8(w[1].c_str())); + const ipc::CTLSClientSocket::port_type port = url.getPort() > 0 + ? (ipc::CTLSClientSocket::port_type)url.getPort() + : (ipc::CTLSClientSocket::port_type)443; + return "loaded:" + ipc::CTLSClientSocket::pinnedCertPath(url.getHost(), port); + } + return "no HTTPS data server"; + } if (op == "discard") { // discard [on|off]: tick or clear as a click does, then the box and the file vector w = words(); @@ -1639,7 +2218,8 @@ string GlobalPrefs::dataTest(const string& line) string out; vector l = ServerList::load(); for (size_t i = 0; i < l.size(); i++) - out += l[i].type + "|" + l[i].name + "|" + l[i].address + ";"; + out += l[i].type + "|" + l[i].name + "|" + l[i].address + + (l[i].username.empty() ? string() : "|" + l[i].username) + ";"; return out.empty() ? "empty" : out; } if (op == "remove") { @@ -1664,7 +2244,8 @@ string GlobalPrefs::dataTest(const string& line) string result = "dialog did not close"; timer.Bind(wxEVT_TIMER, [&](wxTimerEvent&) { if (op == "add") dlg.fillForTest(ssh, name(w[1]), w.size() > 3 ? w[2] : "", - w.size() > 4 ? w[3] : "", w.size() > 5 ? w[4] : ""); + w.size() > 4 ? w[3] : "", w.size() > 5 ? w[4] : "", + !ssh && w.size() > 4 ? w[3] : ""); else dlg.fillForTest(ssh, "", "", "", ""); for (int i = 0; i < 5; i++) wxYield(); result = ecceClientShot(&dlg, wxString::FromUTF8(snap.c_str())) ? "saved" : "not saved"; diff --git a/src/wxgui/wxdialogs/WxDavAuth.C b/src/wxgui/wxdialogs/WxDavAuth.C index e4ccd70e2d..4e2e48a526 100644 --- a/src/wxgui/wxdialogs/WxDavAuth.C +++ b/src/wxgui/wxdialogs/WxDavAuth.C @@ -653,7 +653,10 @@ bool WxDavAuth::prompt(const string& strurl, where += ":" + std::to_string(url.getPort()); authDlg.setServer(where); if (secure) { - authDlg.setEncryption(ipc::CTLSClientSocket::pinnedCertPath().empty() + authDlg.setEncryption(ipc::CTLSClientSocket::pinnedCertPath( + url.getHost(), url.getPort() > 0 + ? (ipc::CTLSClientSocket::port_type)url.getPort() + : (ipc::CTLSClientSocket::port_type)443).empty() ? "Encrypted connection (TLS), certificate checked by the system" : "Encrypted connection (TLS), server certificate pinned"); } diff --git a/tests/apps/prefs_data_test.py b/tests/apps/prefs_data_test.py index d2d7304c74..888d29307f 100644 --- a/tests/apps/prefs_data_test.py +++ b/tests/apps/prefs_data_test.py @@ -13,6 +13,7 @@ """ import os import shutil +import subprocess import sys import tempfile @@ -31,7 +32,7 @@ def shot(name): return os.path.join(SHOTS, "767-" + name + ".png") -ECC = "ecce|Course server|https://ecce.example.edu" +ECC = "ecce|Course server|https://ecce.example.edu|courseuser" SSH = "ssh|Cluster storage|sftp://me@hpc.example.edu/home/me/ecce" PLAIN = [ @@ -44,7 +45,7 @@ def shot(name): ("prefs data discard off", lambda a: a == "box=off;file=off"), ("prefs data form ssh " + shot("add-ssh"), lambda a: a == "saved"), ("prefs data form ecce " + shot("add-ecce"), lambda a: a == "saved"), - ("prefs data add ecce Course_server https://ecce.example.edu " + shot("add-ecce-filled"), + ("prefs data add ecce Course_server https://ecce.example.edu courseuser " + shot("add-ecce-filled"), lambda a: a == "saved"), ("prefs data file", lambda a: a == ECC + ";"), ("prefs data add ssh Cluster_storage hpc.example.edu me /home/me/ecce " + shot("add-ssh-filled"), @@ -94,19 +95,48 @@ def run(display, steps, extra, label): def main(): + cert_dir = tempfile.mkdtemp(prefix="ecce-prefsdata-cert-") + cert = os.path.join(cert_dir, "data-server.pem") + invalid_cert = os.path.join(cert_dir, "invalid.pem") + with open(invalid_cert, "w") as handle: + handle.write("not a PEM certificate\n") + steps = list(PLAIN) + if shutil.which("openssl"): + subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", + "-nodes", "-keyout", os.path.join(cert_dir, "key.pem"), + "-out", cert, "-days", "3", "-subj", + "/CN=ecce.example.edu", "-addext", + "subjectAltName=DNS:ecce.example.edu"], + check=True, capture_output=True) + insert_at = next(i for i, (command, _) in enumerate(steps) + if command == "prefs data file") + 1 + steps[insert_at:insert_at] = [ + ("prefs data cert " + invalid_cert, + lambda a: a.startswith("error=")), + ("prefs data cert " + cert + " " + shot("server-cert"), + lambda a: a.startswith("loaded:") and "/TlsCertificates/" in a + and a.endswith(".pem")), + ] + def checkApp(display, name, results, verbose=False): # One organizer start: a second one in the same isolated state hit an # unrelated bookmark-file parse abort. - run(display, PLAIN, {"ECCE_TEST_PREFS_ADMIN_SERVER": "1"}, "prefs") - for png in ("data-empty", "data_empty", "add-ssh", "add-ecce", "data-two"): + run(display, steps, {"ECCE_TEST_PREFS_ADMIN_SERVER": "1"}, "prefs") + for png in ("data-empty", "data_empty", "add-ssh", "add-ecce", "data-two", + "server-cert"): if not os.path.exists(shot(png)): + if png == "server-cert" and not shutil.which("openssl"): + continue failures.append("no picture " + png) print("FAIL missing " + shot(png)) if failures: results.fail("prefs-data", "; ".join(failures)) - run_tests.checkApp = checkApp - sys.argv = [sys.argv[0], "--app", "organizer"] + sys.argv[1:] - return run_tests.main() + try: + run_tests.checkApp = checkApp + sys.argv = [sys.argv[0], "--app", "organizer"] + sys.argv[1:] + return run_tests.main() + finally: + shutil.rmtree(cert_dir, ignore_errors=True) if __name__ == "__main__": diff --git a/tests/apps/server_roots_test.py b/tests/apps/server_roots_test.py index 9f563db272..e6e58ad23c 100755 --- a/tests/apps/server_roots_test.py +++ b/tests/apps/server_roots_test.py @@ -78,6 +78,9 @@ def checkApp(display, name, results, verbose=False): notConn = lambda a: ROOT + " (not connected)" in a and "Local data" in a steps = [ ("server roots", notConn), + # Activating a disconnected placeholder must not dereference its + # absent Resource (the tree root has one only after connecting). + ("server activate " + NAME, lambda a: a == "activated"), ("server menu", lambda a: "[ ] " + NAME in a), ("server rootmenu " + NAME, lambda a: a == "Connect;Remove from list"), ("server connect " + NAME, lambda a: a == "connected"), diff --git a/tests/apps/serverlist_test.py b/tests/apps/serverlist_test.py index e9b1298df4..5633ae4331 100644 --- a/tests/apps/serverlist_test.py +++ b/tests/apps/serverlist_test.py @@ -67,4 +67,10 @@ def run(*a): "ssh\tLegacy\tsftp://me@hpc.example.edu/home/me/ecce\t1", "ecce\tNew\thttps://ecce.example.edu\t0"], "legacy entries connect at start; new entries wait to be chosen") +with open(fileName, "w") as f: + f.write("ecce\tCourse server\thttps://ecce.example.edu\t0\tcourseuser\n") +check(run("add", "ssh", "Cluster storage", "sftp://me@hpc.example.edu/home/me/ecce")[0] == 0 and + open(fileName).read().splitlines()[0] == + "ecce\tCourse server\thttps://ecce.example.edu\t0\tcourseuser", + "a saved data-server username survives later server-list updates") sys.exit(1 if failures else 0) diff --git a/tests/tls/first_connect_test.py b/tests/tls/first_connect_test.py index 17d6114858..f08e048338 100755 --- a/tests/tls/first_connect_test.py +++ b/tests/tls/first_connect_test.py @@ -134,6 +134,9 @@ def connect(name, port, **extra): p = free_port() first = serve(p, *cert("self1")) +r = sh(sys.executable, SETUP, "--test-server", f"https://localhost:{p}") +check(r.returncode == 0 and "not from a trusted authority" in r.stdout, + "dialog test accepts a self-signed TLS server: " + r.stdout + r.stderr) r, d = connect("pinned", p) check(r.returncode == 0 and r.stdout.strip() == "pinned", "self-signed: " + r.stdout + r.stderr) check(os.path.exists(d + "/server.pem") diff --git a/tests/util/json_configuration_profile_test.C b/tests/util/json_configuration_profile_test.C new file mode 100644 index 0000000000..372d68786b --- /dev/null +++ b/tests/util/json_configuration_profile_test.C @@ -0,0 +1,79 @@ +#include "util/JsonConfigurationProfile.H" + +#include +#include +#include +#include + +using JsonConfigurationProfile::DataServer; +using JsonConfigurationProfile::Profile; + +static bool check(bool ok, const char* what) +{ + std::cout << (ok ? "PASS " : "FAIL ") << what << '\n'; + return ok; +} + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + const std::string path = argv[1]; + std::string error; + Profile source; + DataServer server; + server.name = "Course server"; + server.url = "https://ecce.example.edu:8443"; + server.username = "courseuser"; + server.tlsCertificatePem = "-----BEGIN CERTIFICATE-----\ncertificate\n"; + source.dataServers.push_back(server); + + bool ok = true; + ok &= check(JsonConfigurationProfile::save(path, source, error), + "write version 3 profile"); + std::ifstream saved(path.c_str(), std::ios::binary); + std::ostringstream contents; + contents << saved.rdbuf(); + const std::string json = contents.str(); + ok &= check(json.find("\"version\": 3") != std::string::npos && + json.find("\"username\":\"courseuser\"") != std::string::npos, + "export contains server username"); + ok &= check(json.find("password") == std::string::npos, + "export contains no password field"); + + Profile loaded; + error.clear(); + ok &= check(JsonConfigurationProfile::load(path, loaded, error) && + loaded.version == 3 && loaded.dataServers.size() == 1 && + loaded.dataServers[0].username == "courseuser" && + loaded.dataServers[0].tlsCertificatePem == server.tlsCertificatePem, + "import restores username and TLS certificate"); + + const std::string oldPath = path + ".v2"; + { + std::ofstream old(oldPath.c_str(), std::ios::binary); + old << "{\"format\":\"ecce-configuration\",\"version\":2," + "\"dataServers\":[{\"name\":\"Old\"," + "\"url\":\"https://old.example.edu\"," + "\"tlsCertificatePem\":\"\"}]," + "\"computeResources\":[{\"name\":\"molecule\"," + "\"host\":\"cluster.example.edu\",\"vendor\":\"\"," + "\"model\":\"\",\"processor\":\"\"," + "\"processors\":64,\"nodes\":1,\"allocationAccounts\":0," + "\"queueManager\":\"None\",\"queues\":[],\"settings\":[]," + "\"codes\":[{\"name\":\"NWChem\",\"program\":\"EMSL\"," + "\"modules\":[]}]}],\"jobCreationCodes\":[\"NWChem\"]}\n"; + } + Profile old; + error.clear(); + ok &= check(JsonConfigurationProfile::load(oldPath, old, error) && + old.version == 2 && old.dataServers.size() == 1 && + old.dataServers[0].username.empty() && + old.computeResources.size() == 1 && + old.computeResources[0].vendor == "Unspecified" && + old.computeResources[0].model == "Unspecified" && + old.computeResources[0].processor == "Unspecified", + "version 2 profiles load with blank machine descriptors"); + std::remove(path.c_str()); + std::remove(oldPath.c_str()); + return ok ? 0 : 1; +}