diff --git a/CMakeLists.txt b/CMakeLists.txt index 06487e7498..fbc47a3241 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,13 +50,14 @@ endif() # job-side scripts the Launcher copies to compute hosts, the per-session # gateway scripts, ecce-remote-setup) and ecce-server (the per-user # or central WebDAV data server and its content, its mosquitto -# dependency). Every install() rule below carries a +# dependency), with the optional ecce-server-tui administration package. +# Every install() rule below carries a # COMPONENT tag either way -- that costs nothing when this is OFF, since # plain `cpack`/`cpack -G DEB` ignores COMPONENT entirely and produces # one monolithic package exactly as before (CPACK_DEB_COMPONENT_INSTALL # defaults OFF). Turning this ON is what makes CPack actually split them. -# ON from 9.0 (ecce-client and ecce-server); 8.x release branches are monolithic. -option(ECCE_SPLIT_PACKAGES "Package ecce-client and ecce-server as separate .deb/.rpm files instead of one monolithic package" ON) +# ON from 9.0 (ecce-client, ecce-server, and ecce-server-tui); 8.x release branches are monolithic. +option(ECCE_SPLIT_PACKAGES "Package ecce-client, ecce-server, and ecce-server-tui separately instead of one monolithic package" ON) add_compile_options( "$<$:-Wall>" @@ -1251,17 +1252,26 @@ endforeach() # below); nothing to vendor/extract here since both are ordinary Debian # packages. # ------------------------------------------------------------------------ -# The dataserver's own start/stop/status/adduser: only meaningful on a -# machine actually running the Apache instance, so these -- and the -# Apache config they resolve -- are server-only. +# The data-server service tools ship with ecce-server. The optional TUI is +# separate so headless/server-only installations do not need its Textual +# runtime dependency. It still runs as the account that owns the Apache +# instance and depends on ecce-server at package-install time. install(PROGRAMS ${CMAKE_SOURCE_DIR}/packaging/dataserver/ecce-dataserver-start ${CMAKE_SOURCE_DIR}/packaging/dataserver/ecce-dataserver-stop ${CMAKE_SOURCE_DIR}/packaging/dataserver/ecce-dataserver-status ${CMAKE_SOURCE_DIR}/packaging/dataserver/ecce-dataserver-adduser + ${CMAKE_SOURCE_DIR}/packaging/dataserver/ecce-dataserver-deluser + ${CMAKE_SOURCE_DIR}/packaging/dataserver/ecce-dataserver-cert-generate ${CMAKE_SOURCE_DIR}/packaging/dataserver/ecce-site-publish DESTINATION bin COMPONENT server) +install(PROGRAMS ${CMAKE_SOURCE_DIR}/packaging/dataserver/ecce-server-tui + DESTINATION bin + COMPONENT tui) +install(DIRECTORY ${CMAKE_SOURCE_DIR}/packaging/dataserver/tui/ecce_server_tui + DESTINATION lib + COMPONENT tui) install(FILES ${CMAKE_SOURCE_DIR}/packaging/dataserver/httpd.conf.ecce DESTINATION server/httpd-conf COMPONENT server) @@ -1310,7 +1320,7 @@ fi exec \"$ECCE_HOME/bin/ecce-launch\" \"$@\" ") install(PROGRAMS ${_launch_wrapper} DESTINATION ${ECCE_WRAPPER_DESTINATION} COMPONENT client) -foreach(_ds start stop status adduser) +foreach(_ds start stop status adduser deluser cert-generate) set(_ds_wrapper ${CMAKE_BINARY_DIR}/wrappers/ecce-dataserver-${_ds}) file(WRITE ${_ds_wrapper} "#!/bin/bash @@ -1322,6 +1332,15 @@ exec \"$ECCE_HOME/bin/ecce-dataserver-${_ds}\" \"$@\" install(PROGRAMS ${_ds_wrapper} DESTINATION ${ECCE_WRAPPER_DESTINATION} COMPONENT server) endforeach() +set(_server_tui_wrapper ${CMAKE_BINARY_DIR}/wrappers/ecce-server-tui) +file(WRITE ${_server_tui_wrapper} +"#!/bin/bash +${ECCE_HOME_SH} +export ECCE_REALUSERHOME=\${ECCE_REALUSERHOME:-$HOME} +exec \"$ECCE_HOME/bin/ecce-server-tui\" \"$@\" +") +install(PROGRAMS ${_server_tui_wrapper} DESTINATION ${ECCE_WRAPPER_DESTINATION} COMPONENT tui) + # The same wrapper for the central-server setup helper, so an # administrator can type "ecce-remote-setup " without knowing # where the installation lives. @@ -2055,7 +2074,7 @@ set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) # mod_ssl is in the apache2 package on Debian but its own package on RPM. # xterm: editing an input file with the default editor (vi) opens it in # an xterm (UserEditor.C). -set(CPACK_DEBIAN_PACKAGE_DEPENDS "apache2, apache2-utils, python3-wxgtk4.0, python3-numpy, python3-tqdm, python3-gemmi, mosquitto, libaprutil1, perl, xterm, openssl") +set(CPACK_DEBIAN_PACKAGE_DEPENDS "apache2, apache2-utils, python3-wxgtk4.0, python3-numpy, python3-tqdm, python3-gemmi, python3-textual, mosquitto, libaprutil1, perl, xterm, openssl") # NWChem is a real Debian package (confirmed working: /usr/bin/nwchem, # symlinked to nwchem.openmpi by the package itself) and the auto-register- # this-machine flow (RunMgmt::registerLocalMachine()) defaults new machine @@ -2110,7 +2129,7 @@ if(RPMBUILD_EXECUTABLE) set(CPACK_RPM_PACKAGE_LICENSE "ECL-2.0") set(CPACK_RPM_PACKAGE_GROUP "Applications/Engineering") set(CPACK_RPM_PACKAGE_URL "https://github.com/FriendsofECCE/ECCE") - set(CPACK_RPM_PACKAGE_REQUIRES "httpd, httpd-tools, mod_ssl, openssl, python3-wxpython4, python3-numpy, python3-tqdm, perl, xterm, mosquitto, apr-util${_coin_rpm}") + set(CPACK_RPM_PACKAGE_REQUIRES "httpd, httpd-tools, mod_ssl, openssl, python3-wxpython4, python3-numpy, python3-tqdm, python3-textual, perl, xterm, mosquitto, apr-util${_coin_rpm}") set(CPACK_RPM_PACKAGE_SUGGESTS "nwchem, openssh-clients, firefox") set(CPACK_RPM_FILE_NAME RPM-DEFAULT) # /opt/ecce is ours, but /opt itself is owned by filesystem(5). Without @@ -2188,7 +2207,7 @@ set(CPACK_RPM_CLIENT_USER_FILELIST "${_ecce_rpm_filelist}") # --------------------------------------------------------------------------- # Split packaging (ECCE_SPLIT_PACKAGES). Every install() rule above already -# carries COMPONENT client/server; this block only decides whether CPack +# carries COMPONENT client/server/tui; this block only decides whether CPack # acts on those tags at all, and what each resulting package's own # metadata is. No ecce-common component: auditing every install() rule # above by which side reads it, nothing was needed by both -- siteconfig/ @@ -2231,7 +2250,7 @@ if(ECCE_SPLIT_PACKAGES) unset(CPACK_DEBIAN_PACKAGE_SUGGESTS) set(CPACK_DEB_COMPONENT_INSTALL ON) - set(CPACK_COMPONENTS_ALL client server) + set(CPACK_COMPONENTS_ALL client server tui) # Each component becomes its own independently installable package # rather than CPack's default of one combined "unspecified"-grouped # archive; auto-shlibdeps and auto-provides/requires run separately per @@ -2279,8 +2298,13 @@ if(ECCE_SPLIT_PACKAGES) # The gateway scripts, ecce-remote-setup and the GUI-free job agent # (launchjob, eccejobmaster, eccejobstore) ship in ecce-client, and a server # needs them, so the server brings the client -- GUI libraries included, - # unused on a headless box. Accepted rather than a third package. + # unused on a headless box. A separate worker package is not warranted. set(CPACK_DEBIAN_SERVER_PACKAGE_DEPENDS "apache2, apache2-utils, mosquitto, libaprutil1, openssl, ecce-client (= ${_ecce_deb_version})") + set(CPACK_DEBIAN_TUI_PACKAGE_NAME "ecce-server-tui") + set(CPACK_DEBIAN_TUI_FILE_NAME DEB-DEFAULT) + set(CPACK_DEBIAN_TUI_PACKAGE_DESCRIPTION + "Extensible Computational Chemistry Environment - server administration terminal interface") + set(CPACK_DEBIAN_TUI_PACKAGE_DEPENDS "python3-textual, ecce-server (= ${_ecce_deb_version})") set(CPACK_DEBIAN_SERVER_PACKAGE_BREAKS "ecce (<< ${ECCE_MONOLITHIC_BREAK_VERSION})") set(CPACK_DEBIAN_SERVER_PACKAGE_REPLACES "ecce (<< ${ECCE_MONOLITHIC_BREAK_VERSION})") @@ -2309,6 +2333,9 @@ if(ECCE_SPLIT_PACKAGES) set(CPACK_RPM_SERVER_PACKAGE_NAME "ecce-server") set(CPACK_RPM_SERVER_FILE_NAME RPM-DEFAULT) set(CPACK_RPM_SERVER_PACKAGE_REQUIRES "httpd, httpd-tools, mod_ssl, openssl, mosquitto, apr-util, ecce-client = ${_ecce_deb_version}") + set(CPACK_RPM_TUI_PACKAGE_NAME "ecce-server-tui") + set(CPACK_RPM_TUI_FILE_NAME RPM-DEFAULT) + set(CPACK_RPM_TUI_PACKAGE_REQUIRES "python3-textual, ecce-server = ${_ecce_deb_version}") set(CPACK_RPM_SERVER_PACKAGE_OBSOLETES "ecce < ${ECCE_MONOLITHIC_BREAK_VERSION}") set(CPACK_RPM_SERVER_PACKAGE_CONFLICTS "ecce < ${ECCE_MONOLITHIC_BREAK_VERSION}") set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION "/opt") diff --git a/docs/INSTALLING.md b/docs/INSTALLING.md index 61c3214893..902bca41e9 100644 --- a/docs/INSTALLING.md +++ b/docs/INSTALLING.md @@ -11,20 +11,28 @@ tested. To build your own instead, see ## 1. Install the packages -9.x comes as two packages: `ecce-client` (the applications) and -`ecce-server` (the data server and broker; it needs the client of the same -version). Install both for a standalone machine. On Debian 13, from the -directory you downloaded them to: +9.x comes as `ecce-client` (the applications), `ecce-server` (the data +server and broker; it needs the client of the same version), and the optional +`ecce-server-tui` administration interface. Install the client and server +for a standalone machine. On Debian 13, from the directory you downloaded +them to: ``` sudo apt install ./ecce-client__amd64.deb ./ecce-server__amd64.deb ``` +To install the administration interface too, add its package: + +``` +sudo apt install ./ecce-client__amd64.deb ./ecce-server__amd64.deb ./ecce-server-tui__amd64.deb +``` + The `./` matters: it tells apt these are local files, and apt then pulls in the dependencies itself. `ecce-client` depends on `perl`, `xterm`, `curl`, `libmosquitto1`, wxPython (`python3-wxgtk4.0`) and Coin3D; `ecce-server` on Apache (`apache2`, `apache2-utils`), `mosquitto` and -`libaprutil1`. A machine that only connects to someone else's central +`libaprutil1`. `ecce-server-tui` depends on `ecce-server` and +`python3-textual`. A machine that only connects to someone else's central server needs only `ecce-client`, and so does a computer that keeps its data in a local folder (a local session runs ECCE's own message broker); apt recommends `ecce-server` with it, and `--no-install-recommends` leaves @@ -37,14 +45,21 @@ lines; your own lines there are kept) and reloads the profile; removing the package takes the block out again. If you install `mosquitto` after ECCE, run `sudo /opt/ecce/bin/ecce-apparmor-mosquitto install`. -On RHEL, Rocky or Fedora, `sudo dnf install ./ecce-client-.x86_64.rpm -./ecce-server-.x86_64.rpm`; on RHEL and Rocky run `sudo dnf install +On RHEL, Rocky or Fedora, install the client and server RPMs; add the TUI RPM +if you want the administration interface: + +``` +sudo dnf install ./ecce-client-.x86_64.rpm ./ecce-server-.x86_64.rpm ./ecce-server-tui-.x86_64.rpm +``` + +On RHEL and Rocky run `sudo dnf install epel-release` first, since Mosquitto and Coin3D (`Coin4`) come from EPEL. The RPMs of 9.0.0-alpha.3 were run on RHEL 9; see [Deployment modes](../GETTING_STARTED.md#deployment-modes). ECCE installs to `/opt/ecce` and puts `ecce` and its helper commands -(`ecce-dataserver-adduser`, `ecce-remote-setup`, `ecce-diagnose`, …) on +(`ecce-dataserver-adduser`, `ecce-dataserver-deluser`, `ecce-remote-setup`, +`ecce-diagnose`, …) on your `PATH`. **macOS and Windows** (experimental): native clients are in preview @@ -98,6 +113,34 @@ Use your Linux username — that's what the login dialog defaults to. **On a central server** for a group or a class: the server's administrator creates your account; see [Deployment modes](#deployment-modes). +The server administrator can run `ecce-server-tui` as the account that owns +the data server. Its Textual interface has separate screens for service +controls, users and groups, and profile setup. Within a profile, navigate among +data servers, compute resources, and job-creation codes; profiles can be +assigned to user groups and emailed to new or existing accounts. Profiles +include data-server URLs and public TLS pins, compute resource registrations, +queues, code paths and modules. They contain no passwords, SSH credentials or +private keys. Users enter their own data-server and compute-resource +credentials after loading the file in Preferences → Load Configuration. The +`ecce-server-tui` package installs Textual as a runtime dependency and +depends on the matching `ecce-server` version. When running from a source +checkout, install Textual for the Python interpreter used to launch the TUI. + +TLS certificate actions are in the shared data-server definition form: load a +public certificate pin, generate a certificate/key pair, or load a pair and +enable TLS for the local server and broker. Only the public certificate is +included in client profiles. + +Data servers and compute resources are defined in the shared resource catalog +and referenced by profiles. Editing a catalog definition updates every profile +that uses it; importing a client profile keeps its included resources local to +that profile until you add catalog resources. + +For automatic email, configure a local sendmail-compatible mailer, or set +`ECCE_SENDMAIL` to its executable path. `ECCE_TUI_FROM` can set the sender +address. Create separate profiles or groups when local clients need a +`localhost` server URL and remote clients need a network-reachable server URL. + ## 3. Start ECCE ``` 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..917338da3a --- /dev/null +++ b/include/util/JsonConfigurationProfile.H @@ -0,0 +1,85 @@ +// Versioned, credential-free configuration profiles saved from Preferences. +#ifndef JSONCONFIGURATIONPROFILE_HH +#define JSONCONFIGURATIONPROFILE_HH + +#include +#include + +namespace JsonConfigurationProfile { + +struct DataServer { + std::string name; + std::string url; + std::string tlsCertificatePem; + std::string username; +}; + +struct Code { + std::string name; + std::string program; + std::vector modules; + std::string setup; + std::string command; + std::string environment; +}; + +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(2) {} +}; + +// Save atomically. The schema has no username or password fields; URLs with +// user-info and hosts containing a login prefix are rejected. +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..5084dde3cf 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; // Optional login hint imported with a client profile. }; class ServerList @@ -61,6 +62,7 @@ class ServerList static bool isAdded(const string& ref); static void setLogin(const string& ref, const string& user); // "" forgets static string loginFor(const string& ref); + static string usernameFor(const string& ref); // The account whose home /Ecce/users/ is meant under url: an // added server's own login ("" before it), else Ecce::serverUser(). static string userFor(const string& url); diff --git a/include/wxgui/GlobalPrefs.H b/include/wxgui/GlobalPrefs.H index e324490e52..569ffa161b 100644 --- a/include/wxgui/GlobalPrefs.H +++ b/include/wxgui/GlobalPrefs.H @@ -93,6 +93,8 @@ private: void OnEditServer(wxCommandEvent& event); void OnRemoveServer(wxCommandEvent& event); void OnServerSelect(wxListEvent& event); + void OnSaveConfiguration(wxCommandEvent& event); + void OnLoadConfiguration(wxCommandEvent& event); void updateServerButtons(); long selectedServer() const; ProgramRow makeProgramRow(wxWindow* page, wxSizer* sizer, @@ -173,6 +175,8 @@ private: 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/dataserver/ecce-dataserver-cert-generate b/packaging/dataserver/ecce-dataserver-cert-generate new file mode 100755 index 0000000000..1d33667dd9 --- /dev/null +++ b/packaging/dataserver/ecce-dataserver-cert-generate @@ -0,0 +1,110 @@ +#!/bin/bash +# Generate a self-signed TLS certificate for this account's ECCE data server. +# This writes ~/.ECCE/tls/server.pem and server.key but does not enable TLS, +# configure the broker, or start or restart either service. + +set -u -o pipefail + +usage() { + cat <<'USAGE' +Usage: ecce-dataserver-cert-generate [--force] + +Generate a 10-year self-signed TLS certificate and private key in +$ECCE_REALUSERHOME/.ECCE/tls (default: $HOME/.ECCE/tls). +The certificate covers this host's fully qualified name, host name, +localhost, 127.0.0.1, and its reported IPv4 addresses. + +Existing server.pem or server.key files are preserved unless --force is used. +This command does not enable TLS or start/restart the data server or broker. +To activate TLS for the central server, run ecce-remote-setup --server --tls. +USAGE +} + +force=false +while [ "$#" -gt 0 ]; do + case "$1" in + --force) force=true ;; + -h|--help) usage; exit 0 ;; + *) echo "ecce-dataserver-cert-generate: unknown option $1" >&2; usage >&2; exit 2 ;; + esac + shift +done + +ECCE_REALUSERHOME="${ECCE_REALUSERHOME:-$HOME}" +TLSDIR="$ECCE_REALUSERHOME/.ECCE/tls" + +if ! command -v openssl >/dev/null 2>&1; then + echo "ecce-dataserver-cert-generate: requires the openssl command" >&2 + exit 1 +fi + +mkdir -p "$TLSDIR" || { + echo "ecce-dataserver-cert-generate: cannot create $TLSDIR" >&2 + exit 1 +} +chmod 700 "$TLSDIR" || { + echo "ecce-dataserver-cert-generate: cannot protect $TLSDIR" >&2 + exit 1 +} + +CERT="$TLSDIR/server.pem" +KEY="$TLSDIR/server.key" +if [ "$force" != true ] && { [ -e "$CERT" ] || [ -e "$KEY" ]; }; then + echo "ecce-dataserver-cert-generate: certificate or key already exists in $TLSDIR" >&2 + echo "Use --force to replace the existing files." >&2 + exit 1 +fi + +TMPDIR_CERT="$(mktemp -d "$TLSDIR/.ecce-cert.XXXXXX")" || { + echo "ecce-dataserver-cert-generate: cannot create temporary files in $TLSDIR" >&2 + exit 1 +} +trap 'rm -rf "$TMPDIR_CERT"' EXIT +trap 'exit 1' HUP INT TERM + +FQDN="$(hostname -f 2>/dev/null || hostname)" +HOSTNAME_SHORT="$(hostname 2>/dev/null || printf localhost)" +SAN="DNS:$FQDN,DNS:$HOSTNAME_SHORT,DNS:localhost,IP:127.0.0.1" +for ip in $(hostname -I 2>/dev/null); do + case "$ip" in + *:*) ;; + *) SAN="$SAN,IP:$ip" ;; + esac +done + +if ! (umask 077; openssl req -x509 -newkey rsa:3072 -nodes -days 3650 \ + -subj "/CN=$FQDN/O=ECCE central server" \ + -addext "subjectAltName=$SAN" \ + -keyout "$TMPDIR_CERT/server.key" -out "$TMPDIR_CERT/server.pem" \ + 2>"$TMPDIR_CERT/openssl.err"); then + echo "ecce-dataserver-cert-generate: openssl could not generate a certificate:" >&2 + cat "$TMPDIR_CERT/openssl.err" >&2 + exit 1 +fi + +PUB_CERT="$(openssl x509 -in "$TMPDIR_CERT/server.pem" -noout -pubkey 2>/dev/null | + openssl pkey -pubin -outform der 2>/dev/null | openssl dgst -sha256)" +PUB_KEY="$(openssl pkey -in "$TMPDIR_CERT/server.key" -pubout -outform der 2>/dev/null | + openssl dgst -sha256)" +if [ -z "$PUB_CERT" ] || [ "$PUB_CERT" != "$PUB_KEY" ] || + ! openssl x509 -in "$TMPDIR_CERT/server.pem" -noout -checkend 0 >/dev/null 2>&1; then + echo "ecce-dataserver-cert-generate: generated certificate/key validation failed" >&2 + exit 1 +fi + +chmod 600 "$TMPDIR_CERT/server.key" || exit 1 +chmod 644 "$TMPDIR_CERT/server.pem" || exit 1 +mv -f "$TMPDIR_CERT/server.key" "$KEY" || { + echo "ecce-dataserver-cert-generate: cannot install private key in $TLSDIR" >&2 + exit 1 +} +mv -f "$TMPDIR_CERT/server.pem" "$CERT" || { + echo "ecce-dataserver-cert-generate: cannot install certificate in $TLSDIR" >&2 + exit 1 +} + +echo "Generated a self-signed certificate for $FQDN, valid for 10 years." +echo "Certificate: $CERT" +echo "Private key: $KEY (permissions 600)" +echo "SHA-256 fingerprint: $(openssl x509 -in "$CERT" -noout -fingerprint -sha256 2>/dev/null)" +echo "TLS is not enabled. This command did not start or restart any service." diff --git a/packaging/dataserver/ecce-dataserver-deluser b/packaging/dataserver/ecce-dataserver-deluser new file mode 100755 index 0000000000..070c8c4b19 --- /dev/null +++ b/packaging/dataserver/ecce-dataserver-deluser @@ -0,0 +1,72 @@ +#!/bin/bash +# Revoke an ECCE data-server account; stored user data is kept by default. + +set -u + +usage() { + cat <<'USAGE' +Usage: ecce-dataserver-deluser USER --yes [--delete-data] + +Remove USER from this account's ECCE data-server password file. The user's +stored calculations are kept unless --delete-data is supplied. +USAGE +} + +userid="${1:-}" +if [ "$#" -gt 0 ]; then shift; fi +if ! [[ "$userid" =~ ^[A-Za-z0-9]+$ ]]; then + echo "ecce-dataserver-deluser: user name must contain letters and digits only" >&2 + usage >&2 + exit 2 +fi + +delete_data=false +confirmed=false +while [ "$#" -gt 0 ]; do + case "$1" in + --delete-data) delete_data=true ;; + --yes) confirmed=true ;; + -h|--help) usage; exit 0 ;; + *) echo "ecce-dataserver-deluser: unknown option $1" >&2; usage >&2; exit 2 ;; + esac + shift +done + +if [ "$confirmed" != true ]; then + echo "ecce-dataserver-deluser: pass --yes after confirming the account deletion" >&2 + exit 2 +fi + +ECCE_REALUSERHOME="${ECCE_REALUSERHOME:-$HOME}" +STATEDIR="$ECCE_REALUSERHOME/.ECCE/dataserver" +USERS="$STATEDIR/users" +if [ ! -f "$USERS" ]; then + echo "ecce-dataserver-deluser: data-server account file not found at $USERS" >&2 + exit 1 +fi +if ! grep -q "^${userid}:" "$USERS"; then + echo "ecce-dataserver-deluser: no account named '$userid'" >&2 + exit 1 +fi +if ! command -v htpasswd >/dev/null 2>&1; then + echo "ecce-dataserver-deluser: requires htpasswd (apache2-utils/httpd-tools)" >&2 + exit 1 +fi + +if ! htpasswd -D "$USERS" "$userid"; then + echo "ecce-dataserver-deluser: could not remove '$userid' from the account file" >&2 + exit 1 +fi + +if [ "$delete_data" = true ]; then + USERDIR="$STATEDIR/htdocs/Ecce/users/$userid" + if [ -e "$USERDIR" ] || [ -L "$USERDIR" ]; then + if ! rm -rf -- "$USERDIR"; then + echo "ecce-dataserver-deluser: account revoked, but could not remove $USERDIR" >&2 + exit 1 + fi + fi + echo "ecce-dataserver-deluser: removed account '$userid' and its stored user directory" +else + echo "ecce-dataserver-deluser: revoked account '$userid'; stored user data was kept" +fi diff --git a/packaging/dataserver/ecce-server-tui b/packaging/dataserver/ecce-server-tui new file mode 100755 index 0000000000..a21eb77419 --- /dev/null +++ b/packaging/dataserver/ecce-server-tui @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +"""Launch the ECCE server administration TUI.""" + +import os +import sys +from pathlib import Path + + +ecce_home = Path(os.environ.get("ECCE_HOME", Path(__file__).resolve().parent.parent)) +sys.path.insert(0, str(ecce_home / "lib")) + +from ecce_server_tui.app import main # noqa: E402 + + +raise SystemExit(main()) diff --git a/packaging/dataserver/tui/ecce_server_tui/__init__.py b/packaging/dataserver/tui/ecce_server_tui/__init__.py new file mode 100644 index 0000000000..79c3462099 --- /dev/null +++ b/packaging/dataserver/tui/ecce_server_tui/__init__.py @@ -0,0 +1,3 @@ +"""Administrative TUI for an ECCE data server.""" + +__version__ = "0.1.0" diff --git a/packaging/dataserver/tui/ecce_server_tui/app.py b/packaging/dataserver/tui/ecce_server_tui/app.py new file mode 100644 index 0000000000..6dd99ac0ae --- /dev/null +++ b/packaging/dataserver/tui/ecce_server_tui/app.py @@ -0,0 +1,958 @@ +"""Numbered terminal interface for ECCE server administration.""" + +from __future__ import annotations + +import getpass +import ipaddress +import csv +import json +import os +import re +import secrets +import shutil +import socket +import stat +import string +import subprocess +import tempfile +import sys +from email.message import EmailMessage +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit + +from .profiles import ( + ProfileError, + combine_profiles, + empty_profile, + load_profile, + normalize_profile, + save_profile, +) +from .store import Store, StoreError + + +_USER = re.compile(r"^[A-Za-z0-9]+$") +_EMAIL = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$") +_SETTINGS = ( + "shell", "sourceFile", "allocationCommand", "frontendMachine", + "frontendBypass", "perlPath", "qmgrPath", "libPath", "xappsPath", + "noRemoteAccess", "userSubmit", "singleConnect", "checkScratch", + "isSameDomain", +) + + +def _profile_template() -> dict[str, Any]: + return empty_profile() + + +class ServerTUI: + def __init__(self) -> None: + if os.geteuid() == 0: + raise RuntimeError("Run ecce-server-tui as the account that owns this data server, not as root.") + self.home = Path(os.environ.get("ECCE_REALUSERHOME", str(Path.home()))).expanduser().resolve() + try: + if self.home.stat().st_uid != os.geteuid(): + raise RuntimeError("ECCE_REALUSERHOME must be owned by the account running the TUI.") + except OSError as exc: + raise RuntimeError(f"Cannot access ECCE_REALUSERHOME: {exc}") from exc + self.ecce_home = Path(os.environ.get("ECCE_HOME", "/opt/ecce")).expanduser().resolve() + self.store = Store(self.home) + + def run(self) -> None: + while True: + print("\nECCE data server administration") + print("1. Control data server") + print("2. Manage users") + print("3. Manage groups and user types") + print("4. Manage client configuration profiles") + print("0. Exit") + choice = input("Choice: ").strip() + try: + if choice == "1": + self.server_menu() + elif choice == "2": + self.users_menu() + elif choice == "3": + self.groups_menu() + elif choice == "4": + self.profiles_menu() + elif choice == "0": + return + else: + print("Choose one of the listed numbers.") + except (ProfileError, StoreError, OSError, ValueError) as exc: + print(f"Error: {exc}") + input("Press Enter to continue...") + + def _command(self, script: str, *args: str, input_text: str | None = None) -> tuple[int, str]: + path = self.ecce_home / "bin" / script + if not path.is_file() or not os.access(path, os.X_OK): + return 127, f"Required ECCE command is missing or not executable: {path}" + try: + result = subprocess.run( + [str(path), *args], input=input_text, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + timeout=180, check=False, + ) + except subprocess.TimeoutExpired: + return 124, f"{script} did not finish within three minutes." + output = result.stdout[-12000:] + return result.returncode, output.strip() + + def server_menu(self) -> None: + rc, output = self._command("ecce-dataserver-status") + print("\nCurrent data-server status") + print(output or ("Status check completed." if rc == 0 else "Status check failed.")) + while True: + print("\nControl data server") + print("1. Show status") + print("2. Start data server") + print("3. Stop data server") + print("4. Generate TLS certificate") + print("5. Install certificate and enable TLS") + print("0. Back") + choice = input("Choice: ").strip() + if choice == "0": + return + if choice == "3" and input("Stop the data server? [y/N] ").strip().lower() != "y": + continue + if choice == "4": + force = input("Replace an existing certificate/key? [y/N] ").strip().lower() == "y" + rc, output = self._command( + "ecce-dataserver-cert-generate", *( ["--force"] if force else [] ) + ) + elif choice == "5": + cert = input("Path to certificate PEM: ").strip() + key = input("Path to matching private key: ").strip() + if not cert or not key: + print("Certificate and key paths are required.") + continue + if input("Install this pair and enable TLS for the data server and broker? [y/N] ").strip().lower() != "y": + continue + try: + validity = subprocess.run( + ["openssl", "x509", "-in", cert, "-noout", "-checkend", "0"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=15, check=False, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + print(f"Could not validate the certificate with openssl: {exc}") + continue + if validity.returncode != 0: + detail = validity.stderr.decode("utf-8", errors="replace").strip() + print(f"The certificate is invalid or expired. {detail}") + continue + rc, output = self._command( + "ecce-remote-setup", "--server", "--tls", "--cert", cert, "--key", key + ) + elif choice in {"1", "2", "3"}: + script = {"1": "ecce-dataserver-status", "2": "ecce-dataserver-start", + "3": "ecce-dataserver-stop"}[choice] + rc, output = self._command(script) + else: + print("Choose one of the listed numbers.") + continue + print(output or ("Completed." if rc == 0 else "Command failed without output.")) + + def _database(self) -> dict[str, Any]: + return self.store.load() + + def users_menu(self) -> None: + while True: + print("\nManage users") + print("1. List users") + print("2. Add user and send client configuration") + print("3. Bulk import users from CSV") + print("4. Change user password") + print("5. Update user email and resend configuration") + print("6. Delete user account") + print("0. Back") + choice = input("Choice: ").strip() + if choice == "0": + return + if choice == "1": + self.list_users() + elif choice == "2": + self.add_user() + elif choice == "3": + path = input("CSV file path: ").strip() + groups = input("Groups for these users (comma separated): ").strip() + profile = input("Profile override [optional]: ").strip() + location = input("Client location: [l]ocal to server, [r]emote: ").strip().lower() + try: + result = self.import_users_csv(path, groups, profile, location) + for line in result: + print(line) + except (OSError, ValueError, StoreError, ProfileError) as exc: + print(f"CSV import was not started: {exc}") + elif choice == "4": + self.change_password() + elif choice == "5": + self.update_email_and_resend() + elif choice == "6": + self.delete_user() + else: + print("Choose one of the listed numbers.") + + def list_users(self) -> None: + db = self._database() + users = self._server_accounts() + if not users: + print("No data-server accounts found.") + return + for username in sorted(users): + record = db["users"].get(username, {}) + profile = record.get("profile", "") + if not profile: + profile = ", ".join(sorted({ + db["groups"].get(group, {}).get("profile", "") + for group in record.get("groups", []) + } - {""})) or "(group profiles not assigned)" + print(f"{username}: {record.get('email') or '(no email)'}; " + f"groups: {', '.join(record.get('groups', [])) or '(none)'}; " + f"profile: {profile}") + + def _server_accounts(self) -> set[str]: + account_file = self.home / ".ECCE" / "dataserver" / "users" + accounts: set[str] = set() + try: + for line in account_file.read_text(encoding="utf-8").splitlines(): + username, separator, _hash = line.partition(":") + if separator and _USER.fullmatch(username): + accounts.add(username) + except FileNotFoundError: + pass + return accounts + + @staticmethod + def _email(value: str) -> str: + value = value.strip() + if value and not _EMAIL.fullmatch(value): + raise ValueError("Enter a valid email address, or leave it blank.") + return value + + @staticmethod + def _random_password() -> str: + alphabet = string.ascii_letters + string.digits + alphabet = "".join(char for char in alphabet if char not in "0O1lI") + return "".join(secrets.choice(alphabet) for _ in range(16)) + + def email_user_credentials(self, username: str, address: str, password: str) -> tuple[bool, str]: + mailer = os.environ.get("ECCE_SENDMAIL") or shutil.which("sendmail") + if not mailer: + return False, "No sendmail-compatible mailer is configured." + message = EmailMessage() + message["To"] = address + sender = os.environ.get("ECCE_TUI_FROM", f"ecce@{socket.getfqdn()}") + if "\r" in sender or "\n" in sender: + return False, "ECCE_TUI_FROM must be a single email address line." + message["From"] = sender + message["Subject"] = "Your ECCE data-server account" + message.set_content( + f"Hello {username},\n\n" + "Your ECCE data-server account has been created.\n\n" + f"Username: {username}\nPassword: {password}\n\n" + "A separate email will contain your ECCE client configuration.\n" + ) + try: + result = subprocess.run( + [mailer, "-t", "-oi"], input=message.as_bytes(), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=30, check=False, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + return False, str(exc) + if result.returncode: + detail = result.stderr.decode("utf-8", errors="replace")[-2000:] + return False, detail or "Mailer returned an error." + return True, "" + + def import_users_csv(self, path_text: str, groups_text: str, + profile_name: str, client_location: str) -> list[str]: + """Create users from a heading-based CSV and mail credentials/profile separately.""" + path = Path(path_text).expanduser() + if not path.is_file(): + raise ValueError(f"CSV file does not exist: {path}") + db = self._database() + groups = list(dict.fromkeys(part.strip() for part in groups_text.split(",") if part.strip())) + missing_groups = sorted(set(groups) - set(db["groups"])) + if missing_groups: + raise ValueError("Create these groups first: " + ", ".join(missing_groups)) + profile_name = profile_name.strip() + if profile_name: + self.store.load_profile(profile_name) + target = client_location.strip().lower() + if target not in {"l", "r", "local", "remote"}: + raise ValueError("Client location must be local or remote.") + target = "l" if target in {"l", "local"} else "r" + with path.open("r", encoding="utf-8-sig", newline="") as source: + reader = csv.DictReader(source) + if not reader.fieldnames: + raise ValueError("The CSV file must have a header row.") + normalized_headers = [" ".join((header or "").strip().casefold().split()) + for header in reader.fieldnames] + if len(normalized_headers) != len(set(normalized_headers)): + raise ValueError("The CSV file contains duplicate column headings.") + group_columns = [header for header in normalized_headers + if header in {"group", "groups", "group assignment"}] + if len(group_columns) > 1: + raise ValueError("Use only one 'group', 'groups', or 'group assignment' column.") + required = {"username", "email"} + if not required.issubset(normalized_headers): + raise ValueError("CSV headings must include 'username' and 'email'.") + rows: list[dict[str, str]] = [] + seen: set[str] = set() + existing = self._server_accounts() + for line_number, raw in enumerate(reader, start=2): + if None in raw: + raise ValueError(f"CSV line {line_number}: row has more values than the header.") + row: dict[str, str] = {} + for key, value in raw.items(): + normalized = " ".join((key or "").strip().casefold().split()) + row[normalized] = (value or "").strip() + if not any(row.values()): + continue + username = row.get("username", "") + if not _USER.fullmatch(username): + raise ValueError(f"CSV line {line_number}: username must contain letters and numbers only.") + if username in seen: + raise ValueError(f"CSV line {line_number}: username '{username}' appears more than once.") + seen.add(username) + email = self._email(row.get("email", "")) + if not email: + raise ValueError(f"CSV line {line_number}: email is required.") + if username in db["users"] or username in existing: + raise ValueError(f"CSV line {line_number}: account '{username}' already exists.") + row_groups_text = row.get(group_columns[0], "") if group_columns else "" + row_groups_text = row_groups_text or groups_text + row_groups = list(dict.fromkeys( + part.strip() for part in re.split(r"[,;]", row_groups_text) if part.strip())) + missing = sorted(set(row_groups) - set(db["groups"])) + if missing: + raise ValueError(f"CSV line {line_number}: unknown group(s): {', '.join(missing)}.") + row_profile = row.get("profile", "") or profile_name + if row_profile: + self.store.load_profile(row_profile) + if not row_groups and not row_profile: + raise ValueError(f"CSV line {line_number}: assign a group or profile in the CSV or import form.") + user_record = {"email": email, "groups": row_groups, "profile": row_profile} + resolved_profile = self._user_profile(user_record, db) + self._validate_client_location(resolved_profile, target) + password = row.get("password", "") or self._random_password() + if "\n" in password or "\r" in password or not password: + raise ValueError(f"CSV line {line_number}: password must be a non-empty single line.") + first = row.get("first name", "") or username + last = row.get("last name", "") or username + if any(char in first + last for char in "\r\n"): + raise ValueError(f"CSV line {line_number}: names cannot contain line breaks.") + rows.append({"username": username, "email": email, "password": password, + "first": first, "last": last, "groups": row_groups, + "profile": row_profile}) + if not rows: + raise ValueError("The CSV file contains no user rows.") + + outcomes: list[str] = [] + for row in rows: + username, password, email = row["username"], row["password"], row["email"] + code, output = self._command( + "ecce-dataserver-adduser", "--stdin", username, row["first"], row["last"], + input_text=password + "\n") + if code: + outcomes.append(f"{username}: account creation failed: {output or 'unknown error'}") + continue + record = {"email": email, "groups": row["groups"], "profile": row["profile"]} + db["users"][username] = record + self._sync_group_file_access(db) + self.store.save(db) + credentials_ok, detail = self.email_user_credentials(username, email, password) + outcomes.append(f"{username}: credentials email " + + ("sent" if credentials_ok else f"failed ({detail})")) + try: + self.deliver_user_profile(username, record, target) + outcomes.append(f"{username}: configuration email attempted separately") + except (OSError, ValueError, StoreError, ProfileError) as exc: + outcomes.append(f"{username}: configuration email failed ({exc})") + return outcomes + + def add_user(self) -> None: + db = self._database() + username = input("Username (letters and numbers): ").strip() + if not _USER.fullmatch(username): + raise ValueError("ECCE usernames must contain letters and numbers only.") + if username in db["users"]: + raise ValueError(f"User '{username}' is already managed by the TUI.") + existing_account = username in self._server_accounts() + if existing_account: + if input(f"Data-server account '{username}' already exists. Add profile/email details to it? [y/N] ").strip().lower() != "y": + return + first = input("First name [optional]: ").strip() or username + last = input("Last name [optional]: ").strip() or username + email = self._email(input("Email address [optional]: ")) + groups = sorted(db["groups"]) + selected_group = "" + if groups: + print("Available user types/groups: " + ", ".join(groups)) + selected_group = input("Assign group [blank for none]: ").strip() + if selected_group and selected_group not in db["groups"]: + raise ValueError(f"No group named '{selected_group}'.") + else: + print("Create a group and assign a configuration profile before sending a client profile.") + + profile = input("Client profile override [blank to use group profile]: ").strip() + if profile: + path = self.store.profile_path(profile) + if not path.is_file(): + raise ValueError(f"No profile named '{profile}'.") + self.store.load_profile(profile) + record = {"email": email, "groups": [selected_group] if selected_group else [], + "profile": profile} + client_location = "" + if email and (selected_group or profile): + self._user_profile(record, db) + client_location = input("Client location: [l]ocal to server, [r]emote: ").strip().lower() + self._validate_client_location(self._user_profile(record, db), client_location) + + if not existing_account: + password = getpass.getpass("Initial data-server password: ") + if not password: + raise ValueError("The password cannot be empty.") + if getpass.getpass("Repeat password: ") != password: + raise ValueError("The passwords do not match.") + rc, output = self._command( + "ecce-dataserver-adduser", "--stdin", username, first, last, + input_text=password + "\n", + ) + if output: + print(output) + if rc != 0: + print("The account was not added to TUI metadata because account creation failed.") + return + + db["users"][username] = record + self._sync_group_file_access(db) + self.store.save(db) + if email and (selected_group or profile): + self.deliver_user_profile(username, record, client_location) + elif email: + print("User created with an email address. Assign a group with a profile to send configuration.") + else: + print("User created. Add an email address and group later to send a client profile.") + + def change_password(self) -> None: + username = input("Username: ").strip() + if not _USER.fullmatch(username): + raise ValueError("ECCE usernames must contain letters and numbers only.") + password = getpass.getpass("New password: ") + if not password or getpass.getpass("Repeat new password: ") != password: + raise ValueError("The passwords are empty or do not match.") + rc, output = self._command("ecce-dataserver-adduser", "--passwd", username, + input_text=password + "\n") + print(output or ("Password changed." if rc == 0 else "Password change failed.")) + + def update_email_and_resend(self) -> None: + db = self._database() + username = input("Username: ").strip() + record = db["users"].get(username) + if record is None: + raise ValueError(f"No TUI-managed user named '{username}'.") + email = self._email(input("Email address: ")) + if not email: + raise ValueError("An email address is required for configuration delivery.") + record["email"] = email + self.store.save(db) + self.deliver_user_profile(username, record) + + def delete_user(self) -> None: + db = self._database() + username = input("Username to delete: ").strip() + if not _USER.fullmatch(username) or username not in self._server_accounts(): + raise ValueError(f"No data-server account named '{username}'.") + if input(f"Revoke data-server login for '{username}'? [y/N] ").strip().lower() != "y": + return + delete_data = input("Permanently delete this user's stored data too? [y/N] ").strip().lower() == "y" + if delete_data and input("This permanently removes the user's data directory. Confirm [y/N]: ").strip().lower() != "y": + return + args = [username, "--yes"] + if delete_data: + args.append("--delete-data") + rc, output = self._command("ecce-dataserver-deluser", *args) + print(output or ("User deleted." if rc == 0 else "User deletion failed.")) + if rc == 0: + if username in db["users"]: + db["users"][username]["groups"] = [] + self._sync_group_file_access(db) + db["users"].pop(username, None) + self.store.save(db) + generated_profile = self.store.root / "users" / f"{username}.json" + try: + generated_profile.unlink() + except FileNotFoundError: + pass + + def groups_menu(self) -> None: + while True: + print("\nManage groups and user types") + print("1. List groups") + print("2. Create group") + print("3. Assign a configuration profile to a group") + print("4. Add user to group") + print("5. Remove user from group") + print("6. Delete group") + print("7. Set group file access policy") + print("0. Back") + choice = input("Choice: ").strip() + if choice == "0": + return + if choice == "1": + db = self._database() + if not db["groups"]: + print("No groups defined.") + for name, value in sorted(db["groups"].items()): + policy = value.get("fileAccess", "none") + print(f"{name}: profile {value.get('profile') or '(unassigned)'}; " + f"member file access: {policy}") + elif choice == "2": + self.create_group() + elif choice == "3": + self.assign_profile_to_group() + elif choice == "4": + self.change_membership(add=True) + elif choice == "5": + self.change_membership(add=False) + elif choice == "6": + self.delete_group() + elif choice == "7": + self.set_group_file_access() + else: + print("Choose one of the listed numbers.") + + def create_group(self) -> None: + db = self._database() + name = self.store.safe_name(input("Group/user-type name: ").strip()) + if name in db["groups"]: + raise ValueError(f"Group '{name}' already exists.") + db["groups"][name] = {"profile": "", "fileAccess": "none"} + self.store.save(db) + print(f"Created group '{name}'. Assign a profile to it next.") + + def assign_profile_to_group(self) -> None: + db = self._database() + group = input("Group name: ").strip() + if group not in db["groups"]: + raise ValueError(f"No group named '{group}'.") + profiles = sorted(p.stem for p in self.store.profiles_dir.glob("*.json")) + if not profiles: + raise ValueError("Create or import a profile first.") + print("Profiles: " + ", ".join(profiles)) + profile = self.store.safe_name(input("Profile name: ").strip()) + if profile not in profiles: + raise ValueError(f"No profile named '{profile}'.") + db["groups"][group]["profile"] = profile + members = [u for u, r in db["users"].items() if group in r.get("groups", [])] + for username in members: + self._user_profile(db["users"][username], db) + self.store.save(db) + print(f"Assigned profile '{profile}' to group '{group}'.") + for username in members: + record = db["users"][username] + if record.get("email") and input( + f"Send updated configuration to {username} ({record['email']})? [y/N] ").strip().lower() == "y": + self.deliver_user_profile(username, record) + + def change_membership(self, *, add: bool) -> None: + db = self._database() + username = input("Username: ").strip() + if username not in db["users"]: + raise ValueError(f"No TUI-managed user named '{username}'.") + group = input("Group: ").strip() + if group not in db["groups"]: + raise ValueError(f"No group named '{group}'.") + memberships = db["users"][username].setdefault("groups", []) + if add: + if group in memberships: + raise ValueError(f"User '{username}' is already in group '{group}'.") + memberships.append(group) + else: + if group not in memberships: + raise ValueError(f"User '{username}' is not in group '{group}'.") + memberships.remove(group) + self._user_profile(db["users"][username], db) + self._sync_group_file_access(db) + self.store.save(db) + print(f"Updated groups for '{username}'.") + record = db["users"][username] + if record.get("email") and input( + f"Send updated configuration to {username} ({record['email']})? [y/N] ").strip().lower() == "y": + self.deliver_user_profile(username, record) + + def delete_group(self) -> None: + db = self._database() + group = input("Group name: ").strip() + if group not in db["groups"]: + raise ValueError(f"No group named '{group}'.") + members = [u for u, r in db["users"].items() if group in r.get("groups", [])] + if members: + print("Remove all group members first: " + ", ".join(sorted(members))) + return + if input(f"Delete group '{group}'? [y/N] ").strip().lower() != "y": + return + del db["groups"][group] + self._sync_group_file_access(db) + self.store.save(db) + print(f"Deleted group '{group}'.") + + def set_group_file_access(self) -> None: + db = self._database() + group = input("Group name: ").strip() + if group not in db["groups"]: + raise ValueError(f"No group named '{group}'.") + print("1. No group file access") + print("2. Group members can read one another's files") + print("3. Group members can read and write one another's files") + choice = input("File access policy: ").strip() + policies = {"1": "none", "2": "read", "3": "readwrite"} + if choice not in policies: + raise ValueError("Choose policy 1, 2, or 3.") + db["groups"][group]["fileAccess"] = policies[choice] + self._sync_group_file_access(db) + self.store.save(db) + print(f"Updated file access policy for '{group}'.") + + def _sync_group_file_access(self, db: dict[str, Any]) -> None: + """Apply group membership ACLs while retaining non-group shares.""" + members_by_group: dict[str, list[str]] = { + group: [username for username, record in db["users"].items() + if _USER.fullmatch(username) and group in record.get("groups", [])] + for group in db["groups"] + } + users_root = self.home / ".ECCE" / "dataserver" / "htdocs" / "Ecce" / "users" + for username, record in db["users"].items(): + if not _USER.fullmatch(username): + continue + directory = users_root / username + access_file = directory / ".htaccess" + if not directory.is_dir(): + continue + if directory.is_symlink() or access_file.is_symlink(): + raise ValueError(f"Cannot apply group file access for '{username}': account directory is a symbolic link.") + current = access_file.read_text(encoding="utf-8") if access_file.exists() else "" + read_line = re.search(r"(?m)^#R#(.*?)#R#\s*$", current) + write_line = re.search(r"(?m)^#RW#(.*?)#RW#\s*$", current) + readers = ({user for user in read_line.group(1).split() + if _USER.fullmatch(user)} if read_line else set()) + writers = ({user for user in write_line.group(1).split() + if _USER.fullmatch(user)} if write_line else {username}) + previous = record.get("groupFileAccess", {}) + if isinstance(previous, dict): + readers.difference_update(previous.get("read", [])) + writers.difference_update(previous.get("write", [])) + + group_readers: set[str] = set() + group_writers: set[str] = set() + for group in record.get("groups", []): + details = db["groups"].get(group, {}) + policy = details.get("fileAccess", "none") + peers = set(members_by_group.get(group, [])) - {username} + if policy in {"read", "readwrite"}: + group_readers.update(peers) + if policy == "readwrite": + group_writers.update(peers) + group_readers.difference_update(group_writers) + readers.update(group_readers) + writers.update(group_writers) + readers.discard(username) + writers.add(username) + readers.difference_update(writers) + + # The markers are also read by ECCE's Access Control dialog. Keep + # Apache's method-level authorization in sync with those lists. + read_users = sorted(readers | writers | {"ecceadm"}) + write_users = sorted(writers | {"ecceadm"}) + auth_name = re.search(r"(?m)^AuthName\s+.*$", current) + realm = auth_name.group(0) if auth_name else f"AuthName Ecce-{username}" + contents = ( + "# ECCE .htaccess File #\n#\n## DO NOT EDIT ## - file automatically generated\n#\n" + f"#R#{' '.join(sorted(readers))}#R#\n" + f"#RW#{' '.join(sorted(writers))}#RW#\n" + f"{realm}\n" + "\n" + "Allow from all\n" + f"require user {' '.join(read_users)}\n" + "\n" + "\n" + "Allow from all\n" + f"require user {' '.join(write_users)}\n" + "\n" + ) + mode = stat.S_IMODE(access_file.stat().st_mode) if access_file.exists() else 0o644 + fd, temporary = tempfile.mkstemp(prefix=".htaccess.", dir=directory) + try: + os.fchmod(fd, mode) + with os.fdopen(fd, "w", encoding="utf-8") as output: + output.write(contents) + output.flush() + os.fsync(output.fileno()) + os.replace(temporary, access_file) + except Exception: + try: + os.close(fd) + except OSError: + pass + try: + os.unlink(temporary) + except OSError: + pass + raise + record["groupFileAccess"] = { + "read": sorted(group_readers), + "write": sorted(group_writers), + } + + def profiles_menu(self) -> None: + while True: + print("\nClient configuration profiles") + print("1. List profiles") + print("2. Create profile") + print("3. Import client JSON profile") + print("4. Add data server") + print("5. Add compute resource") + print("6. Export profile") + print("0. Back") + choice = input("Choice: ").strip() + if choice == "0": + return + if choice == "1": + for path in sorted(self.store.profiles_dir.glob("*.json")): + try: + profile = self.store.load_profile(path.stem) + print(f"{path.stem}: {len(profile['dataServers'])} data servers, " + f"{len(profile['computeResources'])} compute resources") + except ProfileError as exc: + print(f"{path.stem}: invalid profile ({exc})") + elif choice == "2": + self.create_profile() + elif choice == "3": + self.import_profile() + elif choice == "4": + self.edit_profile(self._choose_profile(), self.add_data_server) + elif choice == "5": + self.edit_profile(self._choose_profile(), self.add_compute_resource) + elif choice == "6": + self.export_profile() + else: + print("Choose one of the listed numbers.") + + def _choose_profile(self) -> tuple[str, dict[str, Any]]: + names = sorted(p.stem for p in self.store.profiles_dir.glob("*.json")) + if not names: + raise ValueError("Create or import a profile first.") + print("Profiles: " + ", ".join(names)) + name = self.store.safe_name(input("Profile name: ").strip()) + if name not in names: + raise ValueError(f"No profile named '{name}'.") + return name, self.store.load_profile(name) + + def edit_profile(self, selected: tuple[str, dict[str, Any]], editor: Any) -> None: + name, _effective_profile = selected + profile = load_profile(self.store.profile_path(name)) + editor(profile) + save_profile(self.store.profile_path(name), profile) + print(f"Updated profile '{name}'.") + + def create_profile(self) -> None: + name = self.store.safe_name(input("Profile name: ").strip()) + path = self.store.profile_path(name) + if path.exists(): + raise ValueError(f"Profile '{name}' already exists.") + save_profile(path, _profile_template()) + print(f"Created empty profile '{name}'. Add servers and compute resources next.") + + def import_profile(self) -> None: + source = Path(input("Path to client JSON profile: ").strip()).expanduser() + profile = load_profile(source) + name = self.store.safe_name(input("Save as profile name: ").strip()) + path = self.store.profile_path(name) + if path.exists() and input(f"Replace profile '{name}'? [y/N] ").strip().lower() != "y": + return + save_profile(path, profile) + print(f"Imported '{source}' as profile '{name}'.") + + def add_data_server(self, profile: dict[str, Any]) -> None: + name = input("Data server display name: ").strip() + url = input("Server URL (https://host:port/Ecce; use localhost only for local clients): ").strip() + cert_path = input("Path to pinned public server.pem [blank for system CA]: ").strip() + pem = Path(cert_path).expanduser().read_text(encoding="utf-8") if cert_path else "" + profile["dataServers"].append({"name": name, "url": url, "tlsCertificatePem": pem}) + + def add_compute_resource(self, profile: dict[str, Any]) -> None: + resource: dict[str, Any] = { + "name": input("Registration name: ").strip(), + "host": input("Host or SSH alias: ").strip(), + "vendor": input("Vendor: ").strip(), + "model": input("Model: ").strip(), + "processor": input("Processor type: ").strip(), + "processors": self._number("Processors", 1), + "nodes": self._number("Nodes", 0), + "allocationAccounts": input("Uses allocation accounts? [y/N] ").strip().lower() == "y", + "queueManager": input("Queue manager name [None for unqueued]: ").strip() or "None", + "codes": [], + "queues": [], + "settings": [], + } + codes = input("Available code names (comma separated): ").strip() + for code_name in (part.strip() for part in codes.split(",")): + if not code_name: + continue + program = input(f" Program path for {code_name} [blank if site default]: ").strip() + modules = input(f" Modules for {code_name} (space separated): ").split() + resource["codes"].append({"name": code_name, "program": program, "modules": modules}) + if resource["queueManager"] != "None": + print("Enter queues; leave the name blank when finished.") + while True: + qname = input("Queue name [blank to finish]: ").strip() + if not qname: + break + resource["queues"].append({ + "name": qname, + "minProcessors": self._number("Minimum processors", 0), + "maxProcessors": self._number("Maximum processors", 0), + "maxCPU": self._number("Maximum CPU minutes", 0), + "maxMemory": self._number("Maximum memory", 0), + "minScratch": self._number("Minimum scratch", 0), + "defProcessors": self._number("Default processors", 0), + "defRun": self._number("Default run minutes", 0), + "defMemory": self._number("Default memory", 0), + "defScratch": self._number("Default scratch", 0), + "memUnits": input("Memory units [blank if none]: ").strip(), + "requestLines": input("Queue request lines [one line]: ").strip(), + }) + print("Optional shared machine settings (blank key to finish).") + print("Allowed: " + ", ".join(_SETTINGS)) + while True: + key = input("Setting name: ").strip() + if not key: + break + value = input("Setting value: ").strip() + resource["settings"].append({"name": key, "value": value}) + profile["computeResources"].append(resource) + profile["jobCreationCodes"] = sorted( + set(profile["jobCreationCodes"]) | {code["name"] for code in resource["codes"]} + ) + + @staticmethod + def _number(label: str, default: int) -> int: + raw = input(f"{label} [{default}]: ").strip() + value = default if not raw else int(raw) + if value < 0: + raise ValueError(f"{label} cannot be negative.") + return value + + def export_profile(self) -> None: + name, profile = self._choose_profile() + path = Path(input("Output JSON path: ").strip()).expanduser() + save_profile(path, profile) + print(f"Exported profile '{name}' to {path}.") + + def _user_profile(self, record: dict[str, Any], + db: dict[str, Any] | None = None) -> dict[str, Any]: + if db is None: + db = self._database() + direct_profile = record.get("profile", "") + if direct_profile and not isinstance(direct_profile, str): + raise ValueError("The user's assigned profile name is invalid.") + direct_profile = direct_profile.strip() + if direct_profile: + return self.store.load_profile(direct_profile) + selected = [] + for group in record.get("groups", []): + details = db["groups"].get(group) + if not details or not details.get("profile"): + raise ValueError(f"Group '{group}' has no assigned configuration profile.") + selected.append(self.store.load_profile(details["profile"])) + if not selected: + raise ValueError("Assign the user to a group with a profile before sending configuration.") + return combine_profiles(selected) + + @staticmethod + def _validate_client_location(profile: dict[str, Any], target: str) -> None: + if target not in {"l", "r"}: + raise ValueError("Choose local or remote for the client location.") + if target == "r": + for server in profile["dataServers"]: + host = (urlsplit(server["url"]).hostname or "").lower() + try: + loopback = ipaddress.ip_address(host).is_loopback + except ValueError: + loopback = host == "localhost" or host.endswith(".localhost") + if loopback: + raise ValueError(f"Server '{server['name']}' uses a loopback URL; set a client-reachable URL before remote delivery.") + + def deliver_user_profile(self, username: str, record: dict[str, Any], + client_location: str | None = None) -> None: + address = self._email(record.get("email", "")) + if not address: + print("No email address is stored; configuration was not sent.") + return + profile = self._user_profile(record) + # Each configured data-server entry in this mailed profile belongs to + # the selected user. The username is a login hint; no password is sent. + for server in profile["dataServers"]: + server["username"] = username + target = client_location or input("Client location: [l]ocal to server, [r]emote: ").strip().lower() + self._validate_client_location(profile, target) + output = self.store.root / "users" / f"{self.store.safe_name(username)}.json" + save_profile(output, profile) + mailer = os.environ.get("ECCE_SENDMAIL") or shutil.which("sendmail") + if not mailer: + print(f"Profile saved to {output}; no sendmail-compatible mailer is configured.") + return + message = EmailMessage() + message["To"] = address + sender = os.environ.get("ECCE_TUI_FROM", f"ecce@{socket.getfqdn()}") + if "\r" in sender or "\n" in sender: + raise ValueError("ECCE_TUI_FROM must be a single email address line.") + message["From"] = sender + message["Subject"] = "Your ECCE client configuration" + message.set_content( + f"Hello {username},\n\nYour ECCE client configuration is attached. In ECCE, open Preferences " + "and choose Load Configuration.\n\n" + "Your data-server and compute-resource passwords are not included. " + "ECCE will ask you to sign in when you connect.\n" + ) + message.add_attachment( + output.read_bytes(), maintype="application", subtype="json", + filename="ecce-configuration.json", + ) + try: + result = subprocess.run( + [mailer, "-t", "-oi"], input=message.as_bytes(), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=30, check=False, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + print(f"Profile saved to {output}; email delivery failed: {exc}") + return + if result.returncode: + detail = result.stderr.decode("utf-8", errors="replace")[-2000:] + print(f"Profile saved to {output}; email delivery failed: {detail or 'mailer returned an error'}") + else: + print(f"Configuration profile emailed to {address}.") + + +def main() -> int: + try: + try: + from .textual_app import run_textual + except (ImportError, AttributeError, TypeError) as exc: + print(f"ecce-server-tui: Textual is unavailable or too old ({exc}); using the basic terminal menu.", + file=sys.stderr) + ServerTUI().run() + return 0 + return run_textual() + except (KeyboardInterrupt, EOFError): + print("\nExiting ECCE server administration.") + except (RuntimeError, StoreError) as exc: + print(f"ecce-server-tui: {exc}", file=sys.stderr) + return 1 + return 0 diff --git a/packaging/dataserver/tui/ecce_server_tui/profiles.py b/packaging/dataserver/tui/ecce_server_tui/profiles.py new file mode 100644 index 0000000000..46a4994098 --- /dev/null +++ b/packaging/dataserver/tui/ecce_server_tui/profiles.py @@ -0,0 +1,337 @@ +"""Read, validate, merge, and write ECCE JSON client profiles.""" + +from __future__ import annotations + +import json +import os +import re +import tempfile +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit + + +FORMAT = "ecce-configuration" +VERSION = 2 +PROFILE_SETTINGS = { + "shell", "sourcefile", "allocationcommand", "frontendmachine", + "frontendbypass", "perlpath", "qmgrpath", "libpath", "xappspath", + "noremoteaccess", "usersubmit", "singleconnect", "checkscratch", + "issamedomain", +} +_QUEUE_NAME = re.compile(r"^[A-Za-z0-9_.-]+$") +_ENV_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +_SENSITIVE = re.compile( + r"password|passwd|credential|token|secret|username|user=|--account|account=|(?:^|[^a-z])account(?:$|[^a-z])", + re.IGNORECASE, +) + + +class ProfileError(ValueError): + pass + + +def _text(value: Any, label: str, *, nonempty: bool = False) -> str: + if not isinstance(value, str) or (nonempty and not value.strip()): + raise ProfileError(f"{label} must be {'a non-empty ' if nonempty else 'a '}string.") + if "\x00" in value: + raise ProfileError(f"{label} contains a NUL byte.") + return value + + +def _integer(value: Any, label: str, *, minimum: int = 0) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < minimum: + raise ProfileError(f"{label} must be an integer of at least {minimum}.") + return value + + +def _string_list(value: Any, label: str) -> list[str]: + if not isinstance(value, list): + raise ProfileError(f"{label} must be a list.") + result = [_text(item, label, nonempty=True) for item in value] + if len(result) != len(set(result)): + raise ProfileError(f"{label} contains duplicates.") + return result + + +def _no_userinfo_url(url: str) -> None: + try: + parsed = urlsplit(url) + port = parsed.port + except ValueError as exc: + raise ProfileError(f"The data server URL is invalid: {exc}") from exc + if parsed.scheme != "https" or not parsed.hostname: + raise ProfileError("A data server URL must be an https:// URL with a host name.") + if parsed.username is not None or parsed.password is not None: + raise ProfileError("A data server URL must not contain a username or password.") + if port is not None and not 1 <= port <= 65535: + raise ProfileError("A data server URL port must be from 1 to 65535.") + + +def normalize_profile(raw: Any) -> dict[str, Any]: + """Validate and return only the documented, credential-free profile fields.""" + if not isinstance(raw, dict) or raw.get("format") != FORMAT: + raise ProfileError("This is not an ECCE configuration profile.") + version = raw.get("version") + if version not in (1, 2): + raise ProfileError("This ECCE configuration profile version is unsupported.") + if version != VERSION: + raise ProfileError( + "The server TUI needs a version-2 profile with complete machine definitions. " + "Import it from a client with the current profile support." + ) + + servers = raw.get("dataServers") + resources = raw.get("computeResources") + if not isinstance(servers, list) or not isinstance(resources, list): + raise ProfileError("The profile must contain dataServers and computeResources lists.") + + result: dict[str, Any] = { + "format": FORMAT, + "version": VERSION, + "dataServers": [], + "computeResources": [], + "jobCreationCodes": _string_list(raw.get("jobCreationCodes"), "jobCreationCodes"), + } + server_names: set[str] = set() + for entry in servers: + if not isinstance(entry, dict): + raise ProfileError("A data server entry must be an object.") + name = _text(entry.get("name"), "Data server name", nonempty=True) + url = _text(entry.get("url"), "Data server URL", nonempty=True) + _no_userinfo_url(url) + if name in server_names: + raise ProfileError(f"The profile repeats data server '{name}'.") + server_names.add(name) + pem = _text(entry.get("tlsCertificatePem", ""), "TLS certificate") + if "PRIVATE KEY" in pem: + raise ProfileError("A client profile cannot contain a TLS private key.") + username = _text(entry.get("username", ""), "Data server username") + if username and not re.fullmatch(r"[A-Za-z0-9]+", username): + raise ProfileError("A data server username may contain only letters and numbers.") + result["dataServers"].append({ + "name": name, + "url": url, + "tlsCertificatePem": pem, + "username": username, + }) + + resource_names: set[str] = set() + for entry in resources: + if not isinstance(entry, dict): + raise ProfileError("A compute resource entry must be an object.") + name = _text(entry.get("name"), "Compute resource name", nonempty=True) + if any(c in name for c in "/\\\t\r\n"): + raise ProfileError(f"Compute resource name '{name}' contains an unsupported character.") + if name in resource_names: + raise ProfileError(f"The profile repeats compute resource '{name}'.") + resource_names.add(name) + host = _text(entry.get("host"), "Compute resource host", nonempty=True) + if "@" in host or any(c in host for c in "\t\r\n"): + raise ProfileError("Compute resource hosts must not contain a login name or line break.") + vendor = _text(entry.get("vendor", ""), "Vendor") + model = _text(entry.get("model", ""), "Model") + processor = _text(entry.get("processor", ""), "Processor") + queue_manager = _text(entry.get("queueManager"), "Queue manager", nonempty=True) + for label, value in (("Vendor", vendor), ("Model", model), + ("Processor", processor), ("Queue manager", queue_manager)): + if any(c in value for c in "\t\r\n"): + raise ProfileError(f"{label} contains a line break.") + + codes = entry.get("codes") + queues = entry.get("queues", []) + settings = entry.get("settings", []) + if not isinstance(codes, list) or not isinstance(queues, list) or not isinstance(settings, list): + raise ProfileError(f"Compute resource '{name}' has an invalid codes, queues, or settings list.") + clean_codes = [] + code_names: set[str] = set() + for code in codes: + if not isinstance(code, dict): + raise ProfileError(f"Compute resource '{name}' contains an invalid code.") + code_name = _text(code.get("name"), "Code name", nonempty=True) + if any(c in code_name for c in ":{}, \t\r\n"): + raise ProfileError(f"Code name '{code_name}' contains an unsupported character.") + if code_name in code_names: + raise ProfileError(f"Compute resource '{name}' repeats code '{code_name}'.") + code_names.add(code_name) + program = _text(code.get("program", ""), "Program path") + if any(c in program for c in "\t\r\n"): + raise ProfileError(f"Program path for '{code_name}' contains a line break.") + if _SENSITIVE.search(program): + raise ProfileError(f"Program path for '{code_name}' appears to contain account or credential data.") + modules = _string_list(code.get("modules", []), f"Modules for {code_name}") + if any(any(c.isspace() for c in item) for item in modules): + raise ProfileError(f"A module name for '{code_name}' contains whitespace.") + setup = _text(code.get("setup", ""), f"Setup commands for {code_name}").strip() + command = _text(code.get("command", ""), f"Command line for {code_name}").strip() + environment = _text(code.get("environment", ""), f"Environment variables for {code_name}").strip() + for label, value in (("Setup commands", setup), ("Command line", command), + ("Environment variables", environment)): + block_closes_early = ("\n" in value or "{" in value) and any( + line.startswith("}") for line in value.splitlines() + ) + if value == "-" or block_closes_early: + raise ProfileError(f"{label} for '{code_name}' cannot be represented in a machine configuration file.") + if _SENSITIVE.search(value): + raise ProfileError(f"{label} for '{code_name}' appears to contain account or credential data.") + for line in environment.splitlines(): + if not line.strip(): + continue + parts = line.strip().split(None, 1) + if len(parts) != 2 or not _ENV_NAME.fullmatch(parts[0]): + raise ProfileError( + f"Environment variable for '{code_name}' must use the format NAME value." + ) + clean_codes.append({ + "name": code_name, + "program": program, + "modules": modules, + "setup": setup, + "command": command, + "environment": environment, + }) + + clean_queues = [] + queue_names: set[str] = set() + for queue in queues: + if not isinstance(queue, dict): + raise ProfileError(f"Compute resource '{name}' contains an invalid queue.") + queue_name = _text(queue.get("name"), "Queue name", nonempty=True) + if not _QUEUE_NAME.fullmatch(queue_name): + raise ProfileError(f"Queue name '{queue_name}' contains an unsupported character.") + if queue_name in queue_names: + raise ProfileError(f"Compute resource '{name}' repeats queue '{queue_name}'.") + queue_names.add(queue_name) + units = _text(queue.get("memUnits", ""), "Queue memory units") + if any(c in units for c in ",|\t\r\n"): + raise ProfileError(f"Queue '{queue_name}' has invalid memory units.") + request_lines = _text(queue.get("requestLines", ""), "Queue request lines") + safe_lines = [line for line in request_lines.splitlines() if not _SENSITIVE.search(line)] + clean_queues.append({ + "name": queue_name, + "minProcessors": _integer(queue.get("minProcessors", 0), "Queue minimum processors"), + "maxProcessors": _integer(queue.get("maxProcessors", 0), "Queue maximum processors"), + "maxCPU": _integer(queue.get("maxCPU", 0), "Queue max CPU"), + "maxMemory": _integer(queue.get("maxMemory", 0), "Queue max memory"), + "minScratch": _integer(queue.get("minScratch", 0), "Queue minimum scratch"), + "defProcessors": _integer(queue.get("defProcessors", 0), "Queue default processors"), + "defRun": _integer(queue.get("defRun", 0), "Queue default run time"), + "defMemory": _integer(queue.get("defMemory", 0), "Queue default memory"), + "defScratch": _integer(queue.get("defScratch", 0), "Queue default scratch"), + "memUnits": units, + "requestLines": "\n".join(safe_lines), + }) + + clean_settings = [] + setting_names: set[str] = set() + for setting in settings: + if not isinstance(setting, dict): + raise ProfileError(f"Compute resource '{name}' contains an invalid setting.") + key = _text(setting.get("name"), "Machine setting name", nonempty=True) + value = _text(setting.get("value"), "Machine setting value", nonempty=True) + key_lower = key.lower() + if key_lower not in PROFILE_SETTINGS: + raise ProfileError(f"Machine setting '{key}' is not supported in client profiles.") + if key_lower in setting_names: + raise ProfileError(f"Compute resource '{name}' repeats setting '{key}'.") + if "\r" in value or "\n" in value: + raise ProfileError(f"Machine setting '{key}' contains a line break.") + if _SENSITIVE.search(value): + raise ProfileError(f"Machine setting '{key}' appears to contain account or credential data.") + setting_names.add(key_lower) + clean_settings.append({"name": key, "value": value}) + + if queue_manager == "None" and clean_queues: + raise ProfileError(f"Compute resource '{name}' has queues but no queue manager.") + if queue_manager != "None" and not clean_queues: + raise ProfileError(f"Compute resource '{name}' needs at least one queue for {queue_manager}.") + allocation_accounts = entry.get("allocationAccounts", False) + if isinstance(allocation_accounts, bool): + allocation_accounts = int(allocation_accounts) + if allocation_accounts not in (0, 1): + raise ProfileError("Allocation account setting must be true/false or 0/1.") + result["computeResources"].append({ + "name": name, + "host": host, + "vendor": vendor, + "model": model, + "processor": processor, + "processors": _integer(entry.get("processors"), "Processor count", minimum=1), + "nodes": _integer(entry.get("nodes", 0), "Node count"), + "allocationAccounts": int(allocation_accounts), + "queueManager": queue_manager, + "codes": clean_codes, + "queues": clean_queues, + "settings": clean_settings, + }) + return result + + +def load_profile(path: str | os.PathLike[str]) -> dict[str, Any]: + file_path = Path(path) + try: + if file_path.stat().st_size > 8 * 1024 * 1024: + raise ProfileError("The configuration profile is larger than 8 MB.") + raw = json.loads(file_path.read_text(encoding="utf-8")) + except ProfileError: + raise + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + raise ProfileError(f"Could not read the configuration profile: {exc}") from exc + return normalize_profile(raw) + + +def save_profile(path: str | os.PathLike[str], profile: dict[str, Any]) -> None: + normalized = normalize_profile(profile) + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + fd, temporary = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent) + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as stream: + json.dump(normalized, stream, indent=2, ensure_ascii=False) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, destination) + os.chmod(destination.parent, 0o700) + except Exception: + try: + os.unlink(temporary) + except OSError: + pass + raise + + +def empty_profile() -> dict[str, Any]: + return { + "format": FORMAT, + "version": VERSION, + "dataServers": [], + "computeResources": [], + "jobCreationCodes": [], + } + + +def combine_profiles(profiles: list[dict[str, Any]]) -> dict[str, Any]: + """Combine group profiles, rejecting ambiguous definitions by name.""" + combined = empty_profile() + servers: dict[str, dict[str, Any]] = {} + resources: dict[str, dict[str, Any]] = {} + codes: set[str] = set() + for raw in profiles: + profile = normalize_profile(raw) + for server in profile["dataServers"]: + name = server["name"] + if name in servers and servers[name] != server: + raise ProfileError(f"Group profiles define data server '{name}' differently.") + servers[name] = server + for resource in profile["computeResources"]: + name = resource["name"] + if name in resources and resources[name] != resource: + raise ProfileError(f"Group profiles define compute resource '{name}' differently.") + resources[name] = resource + codes.update(profile["jobCreationCodes"]) + combined["dataServers"] = list(servers.values()) + combined["computeResources"] = list(resources.values()) + combined["jobCreationCodes"] = sorted(codes) + return normalize_profile(combined) diff --git a/packaging/dataserver/tui/ecce_server_tui/store.py b/packaging/dataserver/tui/ecce_server_tui/store.py new file mode 100644 index 0000000000..34a8ce55d4 --- /dev/null +++ b/packaging/dataserver/tui/ecce_server_tui/store.py @@ -0,0 +1,132 @@ +"""Private account and group metadata for server-side client profiles.""" + +from __future__ import annotations + +import json +import os +import tempfile +import uuid +from pathlib import Path +from typing import Any + + +class StoreError(ValueError): + pass + + +class Store: + def __init__(self, real_home: Path): + self.root = real_home / ".ECCE" / "dataserver" / "admin" + self.profiles_dir = self.root / "profiles" + self.database = self.root / "accounts.json" + self.catalog_file = self.root / "resource-catalog.json" + self.root.mkdir(parents=True, exist_ok=True, mode=0o700) + self.profiles_dir.mkdir(parents=True, exist_ok=True, mode=0o700) + os.chmod(self.root, 0o700) + os.chmod(self.profiles_dir, 0o700) + + def load(self) -> dict[str, Any]: + if not self.database.exists(): + return {"version": 1, "groups": {}, "users": {}, "profileCatalogs": {}} + try: + value = json.loads(self.database.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + raise StoreError(f"Cannot read server TUI account metadata: {exc}") from exc + if (not isinstance(value, dict) or value.get("version") != 1 or + not isinstance(value.get("groups"), dict) or + not isinstance(value.get("users"), dict)): + raise StoreError("Server TUI account metadata has an unsupported format.") + if "profileCatalogs" not in value: + value["profileCatalogs"] = {} + if not isinstance(value["profileCatalogs"], dict): + raise StoreError("Server TUI profile catalog assignments have an unsupported format.") + return value + + def save(self, value: dict[str, Any]) -> None: + self.root.mkdir(parents=True, exist_ok=True, mode=0o700) + os.chmod(self.root, 0o700) + fd, temporary = tempfile.mkstemp(prefix=".accounts.", dir=self.root) + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as stream: + json.dump(value, stream, indent=2, ensure_ascii=False) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, self.database) + except Exception: + try: + os.unlink(temporary) + except OSError: + pass + raise + + def load_catalog(self) -> dict[str, Any]: + if not self.catalog_file.exists(): + return {"version": 1, "dataServers": {}, "computeResources": {}} + try: + value = json.loads(self.catalog_file.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + raise StoreError(f"Cannot read the shared resource catalog: {exc}") from exc + if (not isinstance(value, dict) or value.get("version") != 1 or + not isinstance(value.get("dataServers"), dict) or + not isinstance(value.get("computeResources"), dict)): + raise StoreError("The shared resource catalog has an unsupported format.") + return value + + def save_catalog(self, value: dict[str, Any]) -> None: + self.root.mkdir(parents=True, exist_ok=True, mode=0o700) + os.chmod(self.root, 0o700) + fd, temporary = tempfile.mkstemp(prefix=".resource-catalog.", dir=self.root) + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as stream: + json.dump(value, stream, indent=2, ensure_ascii=False) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, self.catalog_file) + except Exception: + try: + os.unlink(temporary) + except OSError: + pass + raise + + def load_profile(self, name: str) -> dict[str, Any]: + """Resolve catalog references and return a client-ready profile.""" + from .profiles import load_profile, normalize_profile + + profile = load_profile(self.profile_path(name)) + db = self.load() + catalog = self.load_catalog() + assigned = db["profileCatalogs"].get(name, {}) + if not isinstance(assigned, dict): + raise StoreError(f"Catalog assignments for profile '{name}' are invalid.") + for section in ("dataServers", "computeResources"): + refs = assigned.get(section, []) + if not isinstance(refs, list): + raise StoreError(f"Catalog assignments for profile '{name}' are invalid.") + for item_id in refs: + if not isinstance(item_id, str) or item_id not in catalog[section]: + raise StoreError(f"Profile '{name}' refers to a missing {section} catalog entry.") + entry = catalog[section][item_id] + profile[section].append(entry) + if section == "computeResources": + profile["jobCreationCodes"] = sorted( + set(profile["jobCreationCodes"]) | + {code["name"] for code in entry.get("codes", [])}) + return normalize_profile(profile) + + @staticmethod + def new_catalog_id() -> str: + return uuid.uuid4().hex + + @staticmethod + def safe_name(name: str) -> str: + if not name or name in {".", ".."} or any(c not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-" for c in name): + raise StoreError("Names may contain letters, numbers, period, underscore, and hyphen.") + return name + + def profile_path(self, name: str) -> Path: + return self.profiles_dir / (self.safe_name(name) + ".json") diff --git a/packaging/dataserver/tui/ecce_server_tui/textual_app.py b/packaging/dataserver/tui/ecce_server_tui/textual_app.py new file mode 100644 index 0000000000..8792c8bcc0 --- /dev/null +++ b/packaging/dataserver/tui/ecce_server_tui/textual_app.py @@ -0,0 +1,1671 @@ +"""Textual interface for ECCE data-server administration.""" + +from __future__ import annotations + +import json +import subprocess +import sys +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Any, Optional +from urllib.parse import urlsplit, urlunsplit + +from textual import on +from textual.app import App, ComposeResult +from textual.containers import Container, Horizontal, Vertical, VerticalScroll +from textual.screen import ModalScreen, Screen +from textual.widgets import Button, Checkbox, DataTable, Footer, Header, Input, Label, Select, Static, TextArea + +from . import app as backend +from .profiles import ProfileError, empty_profile, load_profile, normalize_profile, save_profile +from .store import Store, StoreError + + +def _server_url_fields(url: str) -> tuple[str, str]: + """Separate an existing URL port for the data-server editor.""" + try: + parsed = urlsplit(url) + port = parsed.port + except ValueError: + return url, "" + if not parsed.netloc or not parsed.hostname: + return url, str(port or "") + userinfo, separator, _authority = parsed.netloc.rpartition("@") + hostname = parsed.hostname + if ":" in hostname: + hostname = f"[{hostname}]" + netloc = (userinfo + separator if separator else "") + hostname + base_url = urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment)) + return base_url, str(port or "") + + +def _server_url_with_port(url: str, port_text: str) -> str: + """Ensure a data-server URL has the requested port or default 8443.""" + try: + parsed = urlsplit(url) + existing_port = parsed.port + except ValueError as exc: + raise ValueError(f"The data-server URL has an invalid port: {exc}") from exc + if not parsed.netloc or not parsed.hostname: + return url + port_text = port_text.strip() + if port_text: + if not port_text.isdecimal(): + raise ValueError("The data-server port must be a number from 1 to 65535.") + port = int(port_text) + else: + port = existing_port or 8443 + if not 1 <= port <= 65535: + raise ValueError("The data-server port must be from 1 to 65535.") + userinfo, separator, _authority = parsed.netloc.rpartition("@") + hostname = parsed.hostname + if ":" in hostname: + hostname = f"[{hostname}]" + netloc = (userinfo + separator if separator else "") + f"{hostname}:{port}" + return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment)) + + +def _available_codes(ecce_home: Path) -> list[str]: + """Read selectable job codes from the installed ECCE capability files.""" + cap_dir = ecce_home / "data" / "client" / "cap" + result = [] + if not cap_dir.is_dir(): + return result + for path in sorted(cap_dir.glob("*.edml"), key=lambda item: item.stem.casefold()): + try: + root = ET.parse(path).getroot() + except (ET.ParseError, OSError): + continue + elements = {element.tag.rsplit("}", 1)[-1].casefold(): element + for element in root.iter()} + if "template" not in elements or not ( + "inputgenerator" in elements or "taskinputgenerator" in elements + ): + continue + name = path.stem + if name != "ECCE-QM": + result.append(name) + return result + + +class EntryDialog(ModalScreen[Optional[dict[str, str]]]): + """A compact, keyboard-friendly form dialog.""" + + BINDINGS = [("escape", "cancel", "Close form")] + + def __init__(self, title: str, fields: list[tuple[str, ...]], + text_fields: list[tuple[str, ...]] | None = None): + super().__init__() + self.title = title + self.fields = fields + self.text_fields = text_fields or [] + + def compose(self) -> ComposeResult: + with Container(id="dialog"): + yield Label(self.title, classes="dialog-title") + with VerticalScroll(id="form-scroll"): + for field in self.fields: + field_id, label, placeholder = field[:3] + value = field[3] if len(field) > 3 else "" + yield Label(label, classes="field-label") + if len(field) > 4: + yield Select(field[4], value=value, prompt=placeholder, + allow_blank=False, id=field_id) + else: + yield Input(value=value, placeholder=placeholder, + password=field_id.startswith("password"), id=field_id) + for field in self.text_fields: + field_id, label, placeholder = field[:3] + value = field[3] if len(field) > 3 else "" + yield Label(label, classes="field-label") + yield TextArea(text=value, placeholder=placeholder, id=field_id) + with Horizontal(classes="actions"): + yield Button("Cancel", id="cancel") + yield Button("Save", variant="primary", id="save") + + @on(Button.Pressed) + def button_pressed(self, event: Button.Pressed) -> None: + if event.button.id == "cancel": + self.dismiss(None) + elif event.button.id == "save": + values: dict[str, str] = {} + for field in self.fields: + field_id = field[0] + if len(field) > 4: + selected = self.query_one(f"#{field_id}", Select).value + values[field_id] = "" if selected == "__group_profiles__" else str(selected) + else: + values[field_id] = self.query_one(f"#{field_id}", Input).value.strip() + values.update({field[0]: self.query_one(f"#{field[0]}", TextArea).text + for field in self.text_fields}) + self.dismiss(values) + + def action_cancel(self) -> None: + self.dismiss(None) + + +class ConfirmDialog(ModalScreen[bool]): + BINDINGS = [("escape", "cancel", "Cancel")] + + def __init__(self, message: str): + super().__init__() + self.message = message + + def compose(self) -> ComposeResult: + with Container(id="confirm-dialog"): + yield Static(self.message) + with Horizontal(classes="actions"): + yield Button("Cancel", id="cancel") + yield Button("Confirm", variant="error", id="confirm") + + @on(Button.Pressed) + def button_pressed(self, event: Button.Pressed) -> None: + self.dismiss(event.button.id == "confirm") + + def action_cancel(self) -> None: + self.dismiss(False) + + +class GroupPolicyDialog(ModalScreen[Optional[str]]): + BINDINGS = [("escape", "cancel", "Cancel")] + + def compose(self) -> ComposeResult: + with Container(id="dialog"): + yield Label("Group file access", classes="dialog-title") + yield Static("Choose what members can do in one another's data folders.") + yield Button("No group file access", id="none") + yield Button("Read files", id="read") + yield Button("Read and write files", id="readwrite") + yield Button("Cancel", id="cancel") + + @on(Button.Pressed) + def choose(self, event: Button.Pressed) -> None: + if event.button.id == "cancel": + self.dismiss(None) + elif event.button.id in {"none", "read", "readwrite"}: + self.dismiss(event.button.id) + + def action_cancel(self) -> None: + self.dismiss(None) + + +class CodeSelectionDialog(ModalScreen[Optional[list[dict[str, Any]]]]): + """Choose compute codes and open each code's settings on demand.""" + + BINDINGS = [("escape", "cancel", "Close selection")] + + def __init__(self, codes: list[str], old_codes: dict[str, dict[str, Any]]): + super().__init__() + self.codes = codes + self.code_values = {name: dict(value) for name, value in old_codes.items()} + self.configuring_code: str | None = None + + def compose(self) -> ComposeResult: + with Container(id="dialog"): + yield Label("Choose available codes", classes="dialog-title") + yield Static("Select codes for this resource. Configure opens the settings for that program.") + with VerticalScroll(id="form-scroll"): + if not self.codes: + yield Static("No code definitions were found under ECCE_HOME/data/client/cap.") + for index, code in enumerate(self.codes): + with Horizontal(classes="code-row"): + yield Checkbox(code, value=code in self.code_values, id=f"code-{index}") + yield Button("Configure", id=f"configure-{index}") + with Horizontal(classes="actions"): + yield Button("Cancel", id="cancel") + yield Button("Done", variant="primary", id="done") + + @on(Button.Pressed) + def button_pressed(self, event: Button.Pressed) -> None: + if event.button.id == "cancel": + self.dismiss(None) + elif event.button.id == "done": + self.dismiss([ + self.code_values.get(code, { + "name": code, "program": "", "modules": [], + "setup": "", "command": "", "environment": "", + }) + for index, code in enumerate(self.codes) + if self.query_one(f"#code-{index}", Checkbox).value + ]) + elif event.button.id and event.button.id.startswith("configure-"): + index = int(event.button.id.removeprefix("configure-")) + code = self.codes[index] + self.configuring_code = code + self.query_one(f"#code-{index}", Checkbox).value = True + self.app.push_screen(self._code_dialog(code), self.code_configured) + + def _code_dialog(self, code_name: str) -> EntryDialog: + old_code = self.code_values.get(code_name, {}) + fields = [ + ("modules", "Modules (space separated)", "module/version", " ".join(old_code.get("modules", []))), + ("program", "Executable location", "/path/to/program", old_code.get("program", "")), + ] + text_fields = [ + ("setup", "Commands to run before the program", "", old_code.get("setup", "")), + ("command", "Command line", "", old_code.get("command", "")), + ("environment", "Environment variables (one NAME value per line)", "", old_code.get("environment", "")), + ] + return EntryDialog(f"Configure {code_name}", fields, text_fields) + + def code_configured(self, values: dict[str, str] | None) -> None: + if values is None or self.configuring_code is None: + return + code_name = self.configuring_code + self.code_values[code_name] = { + "name": code_name, + "program": values["program"], + "modules": values["modules"].split(), + "setup": values["setup"].strip(), + "command": values["command"].strip(), + "environment": values["environment"].strip(), + } + self.configuring_code = None + + def action_cancel(self) -> None: + self.dismiss(None) + + +class JobCreationCodeSelectionDialog(ModalScreen[Optional[list[str]]]): + """Choose job creation codes for a client configuration profile.""" + + BINDINGS = [("escape", "cancel", "Close selection")] + + def __init__(self, codes: list[str], selected_codes: list[str]): + super().__init__() + self.codes = codes + self.selected_codes = set(selected_codes) + + def compose(self) -> ComposeResult: + with Container(id="dialog"): + yield Label("Choose job creation codes", classes="dialog-title") + yield Static("Select the codes users can choose when creating calculations.") + with VerticalScroll(id="form-scroll"): + if not self.codes: + yield Static("No code definitions were found under ECCE_HOME/data/client/cap.") + for index, code in enumerate(self.codes): + with Horizontal(classes="code-row"): + yield Checkbox(code, value=code in self.selected_codes, + id=f"job-code-{index}") + with Horizontal(classes="actions"): + yield Button("Cancel", id="cancel") + yield Button("Done", variant="primary", id="done") + + @on(Button.Pressed) + def button_pressed(self, event: Button.Pressed) -> None: + if event.button.id == "cancel": + self.dismiss(None) + elif event.button.id == "done": + self.dismiss([ + code for index, code in enumerate(self.codes) + if self.query_one(f"#job-code-{index}", Checkbox).value + ]) + + def action_cancel(self) -> None: + self.dismiss(None) + + +class DataServerDefinitionDialog(ModalScreen[Optional[dict[str, str]]]): + """Edit a data-server catalog item and its optional public TLS pin.""" + + BINDINGS = [("escape", "cancel", "Close form")] + + def __init__(self, old: dict[str, Any] | None = None): + super().__init__() + self.old = old or {} + self.url_value, self.port_value = _server_url_fields(self.old.get("url", "")) + self.certificate_pem = self.old.get("tlsCertificatePem", "") + self.dialog_title = "Edit data-server definition" if old else "New data-server definition" + + def compose(self) -> ComposeResult: + with Container(id="dialog"): + yield Label(self.dialog_title, classes="dialog-title") + yield Label("Display name", classes="field-label") + yield Input(value=self.old.get("name", ""), placeholder="Main data server", id="name") + yield Label("Client URL", classes="field-label") + yield Input(value=self.url_value, placeholder="https://server.example.org/Ecce", id="url") + yield Label("Port (defaults to 8443)", classes="field-label") + yield Input(value=self.port_value, placeholder="8443", id="port") + yield Label("Optional TLS certificate pin", classes="field-label") + yield Static("Only the public certificate is attached to client profiles. The private key stays on the server.") + yield Static(self._certificate_status(), id="certificate-status", classes="status-panel") + with Horizontal(classes="actions"): + yield Button("Load certificate", id="load-certificate") + yield Button("Generate certificate", id="generate-certificate") + yield Button("Clear pin", id="clear-certificate") + with Horizontal(classes="actions"): + yield Button("Load certificate/key and enable TLS here", id="enable-tls") + with Horizontal(classes="actions"): + yield Button("Cancel", id="cancel") + yield Button("Save", variant="primary", id="save") + + def _certificate_status(self) -> str: + return "Public certificate pin is attached." if self.certificate_pem else ( + "No certificate pin; clients will use the system certificate store.") + + @on(Button.Pressed) + def button_pressed(self, event: Button.Pressed) -> None: + action = event.button.id + if action == "cancel": + self.dismiss(None) + elif action == "save": + try: + url = _server_url_with_port( + self.query_one("#url", Input).value.strip(), + self.query_one("#port", Input).value, + ) + self.dismiss({ + "name": self.query_one("#name", Input).value.strip(), + "url": url, + "pem": self.certificate_pem, + }) + except ValueError as exc: + self.app.notify(str(exc), title="Invalid data-server port", severity="error") + elif action == "load-certificate": + self.app.push_screen(EntryDialog("Load a public TLS certificate", [ + ("path", "Certificate PEM file", "~/server.pem")]), self.load_certificate) + elif action == "generate-certificate": + self.app.push_screen(ConfirmDialog( + "Generate a TLS certificate and private key for this data server? Existing files are preserved. TLS will not be enabled."), + self.generate_certificate) + elif action == "enable-tls": + self.app.push_screen(EntryDialog("Load a certificate/key pair and enable local TLS", [ + ("cert", "Certificate PEM file", "~/server.pem"), + ("key", "Matching private key file", "~/server.key")]), self.confirm_tls) + elif action == "clear-certificate": + self.certificate_pem = "" + self.query_one("#certificate-status", Static).update(self._certificate_status()) + + def load_certificate(self, values: dict[str, str] | None) -> bool: + if not values: + return False + path = Path(values["path"]).expanduser() + try: + result = subprocess.run(["openssl", "x509", "-in", str(path), "-noout", "-checkend", "0"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=15, check=False) + if result.returncode: + detail = result.stderr.decode("utf-8", errors="replace").strip() + raise ValueError(f"The certificate is invalid or expired. {detail}") + pem = path.read_text(encoding="utf-8") + if "PRIVATE KEY" in pem: + raise ValueError("Load the public certificate only; private keys must not go in a client profile.") + self.certificate_pem = pem + self.query_one("#certificate-status", Static).update(f"Loaded public certificate from {path}.") + return True + except (OSError, UnicodeError, subprocess.TimeoutExpired, ValueError) as exc: + self.app.notify(str(exc), title="Could not load certificate", severity="error") + return False + + def confirm_tls(self, values: dict[str, str] | None) -> None: + if not values: + return + cert = str(Path(values["cert"]).expanduser()) + key = str(Path(values["key"]).expanduser()) + try: + check = subprocess.run(["openssl", "x509", "-in", cert, "-noout", "-checkend", "0"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=15, check=False) + except (OSError, subprocess.TimeoutExpired) as exc: + self.app.notify(f"Could not validate certificate with openssl: {exc}", severity="error") + return + if check.returncode: + detail = check.stderr.decode("utf-8", errors="replace").strip() + self.app.notify("Certificate is invalid or expired. " + detail, severity="error") + return + self.app.push_screen(ConfirmDialog( + "Install this certificate/key pair and enable TLS for the local data server and broker?"), + lambda confirmed: self.install_tls(cert, key, confirmed)) + + def install_tls(self, cert: str, key: str, confirmed: bool) -> None: + if not confirmed: + return + code, output = self.app.backend._command( + "ecce-remote-setup", "--server", "--tls", "--cert", cert, "--key", key) + if code: + self.app.notify(output or "TLS setup failed.", title="Could not enable TLS", severity="error") + return + if self.load_certificate({"path": cert}): + self.app.notify("TLS enabled for the local server and broker; the public certificate is attached here.") + else: + self.app.notify("TLS is enabled locally. Load the public certificate pin into this definition separately.", + severity="warning") + + def generate_certificate(self, confirmed: bool) -> None: + if not confirmed: + return + code, output = self.app.backend._command("ecce-dataserver-cert-generate") + if code: + if "--force to replace" in output: + self.app.push_screen(ConfirmDialog( + "A certificate or key already exists. Replace the existing certificate and private key?"), + lambda replace: self.replace_certificate(replace)) + return + self.app.notify(output or "Certificate generation failed.", title="Could not generate certificate", severity="error") + return + self.attach_generated_certificate() + + def replace_certificate(self, confirmed: bool) -> None: + if not confirmed: + return + code, output = self.app.backend._command("ecce-dataserver-cert-generate", "--force") + if code: + self.app.notify(output or "Certificate generation failed.", title="Could not generate certificate", severity="error") + return + self.attach_generated_certificate() + + def attach_generated_certificate(self) -> None: + cert = self.app.backend.home / ".ECCE" / "tls" / "server.pem" + try: + pem = cert.read_text(encoding="utf-8") + except OSError as exc: + self.app.notify(f"Generated certificate could not be read from {cert}: {exc}", severity="error") + return + self.certificate_pem = pem + self.query_one("#certificate-status", Static).update(f"Generated and attached public certificate from {cert}.") + self.app.notify("Certificate generated and attached to this data-server definition. TLS still needs to be enabled.") + + def action_cancel(self) -> None: + self.dismiss(None) + + +class HomeScreen(Screen): + def compose(self) -> ComposeResult: + yield Header() + with VerticalScroll(id="home"): + yield Static("ECCE / DATA SERVER", classes="eyebrow") + yield Label("Server administration", classes="hero") + yield Static("Configure the resources and client profiles people receive when they join.", + classes="subtitle") + with Vertical(classes="home-cards"): + with Vertical(classes="home-card"): + yield Static("01 CONFIGURATION", classes="eyebrow") + yield Label("Client profiles", classes="card-title") + yield Static("Build data-server and compute-resource configurations, then assign them by user type.") + yield Button("Open profiles", variant="primary", id="profiles") + with Vertical(classes="home-card"): + yield Static("02 SERVER", classes="eyebrow") + yield Label("Data server", classes="card-title") + yield Static("Check status, start or stop the service, and set up TLS.") + yield Button("Server controls", id="server") + with Vertical(classes="home-card"): + yield Static("03 ACCESS", classes="eyebrow") + yield Label("Users & groups", classes="card-title") + yield Static("Create accounts, set email addresses, and assign configuration groups.") + yield Button("User and group setup", id="access") + yield Button("Manage shared resource catalog", id="catalog") + yield Static("↑↓ move Enter select Esc back Ctrl+C quit", classes="hint") + yield Footer() + + @on(Button.Pressed) + def open_section(self, event: Button.Pressed) -> None: + if event.button.id == "profiles": + self.app.push_screen(ProfilesScreen()) + elif event.button.id == "server": + self.app.push_screen(ServerScreen()) + elif event.button.id == "access": + self.app.push_screen(AccessScreen()) + elif event.button.id == "catalog": + self.app.push_screen(CatalogScreen("dataServers")) + + +class ProfilesScreen(Screen): + BINDINGS = [("escape", "app.pop_screen", "Back")] + + def compose(self) -> ComposeResult: + yield Header() + with Vertical(id="workspace"): + yield Static("CONFIGURATION / PROFILES", classes="eyebrow") + yield Label("Client profiles", classes="page-title") + yield Static("Each profile can be assigned to a group and delivered to its members.", classes="subtitle") + yield DataTable(id="profiles-table", cursor_type="row") + with Horizontal(classes="toolbar"): + yield Button("New profile", variant="primary", id="new") + yield Button("Import JSON", id="import") + yield Button("Open selected", id="open") + yield Button("Export selected", id="export") + yield Button("Delete", variant="error", id="delete") + yield Button("Shared catalog", id="catalog") + yield Button("Back", id="back") + yield Static("A client profile contains no passwords or private keys.", classes="hint") + yield Footer() + + def on_mount(self) -> None: + table = self.query_one("#profiles-table", DataTable) + table.add_columns("Profile", "Data servers", "Compute resources", "Codes") + self.refresh_profiles() + + def refresh_profiles(self) -> None: + table = self.query_one("#profiles-table", DataTable) + table.clear() + for path in sorted(self.app.store.profiles_dir.glob("*.json")): + try: + profile = self.app.store.load_profile(path.stem) + table.add_row(path.stem, str(len(profile["dataServers"])), + str(len(profile["computeResources"])), + str(len(profile["jobCreationCodes"])), key=path.stem) + except (ProfileError, StoreError) as exc: + table.add_row(path.stem, "Invalid", "—", str(exc), key=path.stem) + + def selected_name(self) -> str | None: + table = self.query_one("#profiles-table", DataTable) + if table.row_count == 0: + return None + return str(table.get_row_at(table.cursor_row)[0]) + + @on(Button.Pressed) + def action(self, event: Button.Pressed) -> None: + action = event.button.id + if action == "back": + self.app.pop_screen() + elif action == "new": + self.app.push_screen(EntryDialog("Create a profile", [ + ("name", "Profile name", "e.g. research-team")]), self.create_profile) + elif action == "import": + self.app.push_screen(EntryDialog("Import a client profile", [ + ("path", "Path to JSON profile", "~/Downloads/ecce-configuration.json"), + ("name", "Save in the server as", "e.g. research-team")]), self.import_profile) + elif action == "open": + name = self.selected_name() + if name: + try: + self.app.push_screen(ProfileDetailScreen(name)) + except (OSError, ProfileError, StoreError) as exc: + self.app.notify(str(exc), title="Could not open profile", severity="error") + else: + self.app.notify("Create or import a profile first.", severity="warning") + elif action == "export": + name = self.selected_name() + if name: + self.app.push_screen(EntryDialog("Export profile", [ + ("path", "Output JSON path", f"{name}.json")]), + lambda values: self.export_profile(name, values)) + elif action == "delete": + name = self.selected_name() + if name: + self.app.push_screen(ConfirmDialog(f"Delete the profile '{name}'?"), + lambda confirmed: self.delete_profile(name, confirmed)) + elif action == "catalog": + self.app.push_screen(CatalogScreen("dataServers")) + + def create_profile(self, values: dict[str, str] | None) -> None: + if not values: + return + try: + name = self.app.store.safe_name(values["name"]) + destination = self.app.store.profile_path(name) + if destination.exists(): + raise ValueError(f"Profile '{name}' already exists.") + save_profile(destination, empty_profile()) + self.refresh_profiles() + self.app.push_screen(ProfileDetailScreen(name)) + except (ValueError, OSError, ProfileError, StoreError) as exc: + self.app.notify(str(exc), title="Could not create profile", severity="error") + + def import_profile(self, values: dict[str, str] | None) -> None: + if not values: + return + try: + name = self.app.store.safe_name(values["name"]) + destination = self.app.store.profile_path(name) + if destination.exists(): + self.app.notify(f"Profile '{name}' already exists. Delete it or choose another name.", severity="warning") + return + source = Path(values["path"]).expanduser() + save_profile(destination, load_profile(source)) + self.refresh_profiles() + self.app.notify(f"Imported {source} as '{name}'.") + except (ValueError, OSError, ProfileError, StoreError) as exc: + self.app.notify(str(exc), title="Could not import profile", severity="error") + + def export_profile(self, name: str, values: dict[str, str] | None) -> None: + if not values: + return + try: + save_profile(Path(values["path"]).expanduser(), self.app.store.load_profile(name)) + self.app.notify(f"Exported profile to {values['path']}.") + except (ValueError, OSError, ProfileError, StoreError) as exc: + self.app.notify(str(exc), title="Could not export profile", severity="error") + + def delete_profile(self, name: str, confirmed: bool) -> None: + if not confirmed: + return + db = self.app.store.load() + assigned = [group for group, record in db["groups"].items() if record.get("profile") == name] + if assigned: + self.app.notify("This profile is assigned to: " + ", ".join(assigned), severity="warning") + return + try: + self.app.store.profile_path(name).unlink() + db["profileCatalogs"].pop(name, None) + self.app.store.save(db) + self.refresh_profiles() + self.app.notify(f"Deleted profile '{name}'.") + except OSError as exc: + self.app.notify(str(exc), title="Could not delete profile", severity="error") + + +class ProfileDetailScreen(Screen): + BINDINGS = [("escape", "app.pop_screen", "Back")] + + def __init__(self, profile_name: str): + super().__init__() + self.profile_name = profile_name + self.section = "servers" + self.profile: dict[str, Any] = {} + self.visible_entries: list[tuple[str, int | str, dict[str, Any]]] = [] + + def compose(self) -> ComposeResult: + yield Header() + with Vertical(id="workspace"): + yield Static("CONFIGURATION / PROFILE EDITOR", classes="eyebrow") + yield Label(self.profile_name, classes="page-title") + yield Static("Choose a section, then add or remove entries. Changes are saved as you go.", classes="subtitle") + with Horizontal(classes="section-tabs"): + yield Button("Data servers", id="section-servers") + yield Button("Compute resources", id="section-resources") + yield Button("Job creation codes", id="section-codes") + yield DataTable(id="entries-table", cursor_type="row") + with Horizontal(classes="toolbar"): + yield Button("Add entry", variant="primary", id="add") + yield Button("Remove selected", variant="error", id="remove") + yield Button("Back to profiles", id="back") + yield Footer() + + def on_mount(self) -> None: + self.query_one("#entries-table", DataTable).add_columns("Name", "Details") + self.refresh_profile_entries() + + def refresh_profile_entries(self) -> None: + self.profile = load_profile(self.app.store.profile_path(self.profile_name)) + # Resolve once here for validation; retain the direct profile separately + # so catalog entries stay references instead of becoming copies. + self.app.store.load_profile(self.profile_name) + db = self.app.store.load() + catalog = self.app.store.load_catalog() + assignments = db["profileCatalogs"].get(self.profile_name, {}) + table = self.query_one("#entries-table", DataTable) + table.clear() + self.visible_entries = [] + if self.section == "servers": + section = "dataServers" + for index, entry in enumerate(self.profile[section]): + table.add_row(entry["name"], entry["url"], key=f"profile-{index}") + self.visible_entries.append(("profile", index, entry)) + elif self.section == "resources": + section = "computeResources" + for index, entry in enumerate(self.profile[section]): + detail = f"{entry['host']} · {len(entry['codes'])} codes · {len(entry['queues'])} queues" + table.add_row(entry["name"], detail, key=f"profile-{index}") + self.visible_entries.append(("profile", index, entry)) + else: + for index, name in enumerate(self.profile["jobCreationCodes"]): + table.add_row(name, "Available for calculation creation", key=str(index)) + self.visible_entries.append(("profile", index, {"name": name})) + if self.section in {"servers", "resources"}: + section = "dataServers" if self.section == "servers" else "computeResources" + for item_id in assignments.get(section, []): + entry = catalog[section][item_id] + detail = entry["url"] if section == "dataServers" else ( + f"{entry['host']} · {len(entry['codes'])} codes · {len(entry['queues'])} queues") + table.add_row(entry["name"], detail, key=f"catalog-{item_id}") + self.visible_entries.append(("catalog", item_id, entry)) + for button_id in ("section-servers", "section-resources", "section-codes"): + self.query_one(f"#{button_id}", Button).variant = "primary" if button_id.endswith(self.section) else "default" + self.query_one("#add", Button).label = "Select codes" if self.section == "codes" else "Add entry" + + @on(Button.Pressed) + def action(self, event: Button.Pressed) -> None: + action = event.button.id or "" + if action.startswith("section-"): + self.section = action.removeprefix("section-") + try: + self.refresh_profile_entries() + except (OSError, ProfileError, StoreError) as exc: + self.app.notify(str(exc), severity="error") + elif action == "back": + self.app.pop_screen() + elif action == "add": + self.add_entry() + elif action == "remove": + self.remove_entry() + + def add_entry(self) -> None: + if self.section == "servers": + section = "dataServers" + elif self.section == "resources": + section = "computeResources" + else: + codes = _available_codes(self.app.backend.ecce_home) + codes.extend(sorted(set(self.profile["jobCreationCodes"]) - set(codes), + key=str.casefold)) + self.app.push_screen( + JobCreationCodeSelectionDialog(codes, self.profile["jobCreationCodes"]), + self.save_job_creation_codes) + return + self.app.push_screen(CatalogScreen(section, select_mode=True), self.attach_catalog_item) + + def attach_catalog_item(self, item_id: str | None) -> None: + if not item_id: + return + section = "dataServers" if self.section == "servers" else "computeResources" + try: + item = self.app.store.load_catalog()[section][item_id] + effective = self.app.store.load_profile(self.profile_name) + if any(existing["name"].casefold() == item["name"].casefold() + for existing in effective[section]): + self.app.notify("This profile already contains a resource with that name.", severity="warning") + return + db = self.app.store.load() + assignments = db["profileCatalogs"].setdefault( + self.profile_name, {"dataServers": [], "computeResources": []}) + refs = assignments.setdefault(section, []) + if item_id in refs: + self.app.notify("That catalog item is already assigned to this profile.", severity="warning") + return + refs.append(item_id) + self.app.store.save(db) + self.refresh_profile_entries() + self.app.notify("Shared catalog item assigned to this profile.") + except (OSError, ValueError, ProfileError, StoreError) as exc: + self.app.notify(str(exc), title="Could not assign catalog item", severity="error") + + def save_job_creation_codes(self, selected: list[str] | None) -> None: + if selected is None: + return + self.profile["jobCreationCodes"] = sorted(set(selected), key=str.casefold) + try: + self.save() + except (ValueError, ProfileError, StoreError) as exc: + self.app.notify(str(exc), title="Could not add code", severity="error") + + def save(self) -> None: + normalized = normalize_profile(self.profile) + save_profile(self.app.store.profile_path(self.profile_name), normalized) + self.refresh_profile_entries() + self.app.notify("Profile saved.") + + def remove_entry(self) -> None: + table = self.query_one("#entries-table", DataTable) + if table.row_count == 0: + self.app.notify("There are no entries to remove.", severity="warning") + return + row_index = table.cursor_row + entry_name = str(table.get_row_at(row_index)[0]) + self.app.push_screen(ConfirmDialog(f"Remove '{entry_name}' from this profile?"), + lambda confirmed: self.confirm_remove(row_index, confirmed)) + + def confirm_remove(self, row_index: int, confirmed: bool) -> None: + if not confirmed: + return + try: + source, item_id, _entry = self.visible_entries[row_index] + if source == "catalog": + db = self.app.store.load() + section = "dataServers" if self.section == "servers" else "computeResources" + refs = db["profileCatalogs"].get(self.profile_name, {}).get(section, []) + refs.remove(item_id) + self.app.store.save(db) + self.refresh_profile_entries() + self.app.notify("Removed shared catalog item from this profile.") + else: + collection = {"servers": "dataServers", "resources": "computeResources", "codes": "jobCreationCodes"}[self.section] + del self.profile[collection][int(item_id)] + self.save() + except (ValueError, ProfileError) as exc: + self.app.notify(str(exc), title="Could not remove entry", severity="error") + + +class CatalogScreen(Screen): + """Reusable data-server and compute-resource definitions.""" + + BINDINGS = [("escape", "back", "Back")] + + def __init__(self, section: str = "dataServers", *, select_mode: bool = False): + super().__init__() + self.section = section + self.select_mode = select_mode + self.item_ids: list[str] = [] + + def compose(self) -> ComposeResult: + yield Header() + with Vertical(id="workspace"): + yield Static("SHARED CONFIGURATION / RESOURCE CATALOG", classes="eyebrow") + yield Label("Reusable resources", classes="page-title") + yield Static("Define each server or compute resource once, then attach it to any number of profiles.", classes="subtitle") + with Horizontal(classes="section-tabs"): + yield Button("Data servers", id="catalog-servers") + yield Button("Compute resources", id="catalog-resources") + yield DataTable(id="catalog-table", cursor_type="row") + with Horizontal(classes="toolbar"): + yield Button("New definition", variant="primary", id="new") + yield Button("Edit selected", id="edit") + yield Button("Delete selected", variant="error", id="delete") + yield Button("Use selected", variant="primary", id="use") + yield Button("Back", id="back") + yield Footer() + + def on_mount(self) -> None: + self.query_one("#catalog-table", DataTable).add_columns("Name", "Address / host", "Details") + self.query_one("#use", Button).display = self.select_mode + self.refresh_catalog() + + def refresh_catalog(self) -> None: + catalog = self.app.store.load_catalog() + section = self.section + table = self.query_one("#catalog-table", DataTable) + table.clear() + self.item_ids = [] + for item_id, entry in sorted(catalog[section].items(), key=lambda pair: pair[1]["name"].casefold()): + if section == "dataServers": + address = entry["url"] + detail = "TLS certificate pinned" if entry.get("tlsCertificatePem") else "System certificate store" + else: + address = entry["host"] + detail = f"{len(entry['codes'])} codes · {len(entry['queues'])} queues" + table.add_row(entry["name"], address, detail, key=item_id) + self.item_ids.append(item_id) + for button_id in ("catalog-servers", "catalog-resources"): + self.query_one(f"#{button_id}", Button).variant = ( + "primary" if button_id.endswith("servers") == (section == "dataServers") else "default") + + def selected_id(self) -> str | None: + table = self.query_one("#catalog-table", DataTable) + return self.item_ids[table.cursor_row] if table.row_count else None + + @on(Button.Pressed) + def action(self, event: Button.Pressed) -> None: + action = event.button.id + if action == "back": + self.action_back() + elif action == "catalog-servers": + self.section = "dataServers" + self.refresh_catalog() + elif action == "catalog-resources": + self.section = "computeResources" + self.refresh_catalog() + elif action == "new": + self.edit_item(None) + elif action == "edit": + item_id = self.selected_id() + if item_id: + self.edit_item(item_id) + else: + self.app.notify("Select a catalog entry first.", severity="warning") + elif action == "delete": + item_id = self.selected_id() + if item_id: + entry = self.app.store.load_catalog()[self.section][item_id] + self.app.push_screen(ConfirmDialog(f"Delete '{entry['name']}' from the shared catalog?"), + lambda confirmed: self.delete_item(item_id, confirmed)) + else: + self.app.notify("Select a catalog entry first.", severity="warning") + elif action == "use": + item_id = self.selected_id() + if item_id: + self.dismiss(item_id) + else: + self.app.notify("Select a catalog entry first.", severity="warning") + + def action_back(self) -> None: + if self.select_mode: + self.dismiss(None) + else: + self.app.pop_screen() + + def edit_item(self, item_id: str | None) -> None: + catalog = self.app.store.load_catalog() + old = catalog[self.section].get(item_id, {}) if item_id else {} + if self.section == "dataServers": + self.app.push_screen(DataServerDefinitionDialog(old), + lambda values: self.save_item(item_id, values, old)) + else: + old_codes = {code["name"]: code for code in old.get("codes", [])} + available_codes = self.available_codes() + available_codes.extend(sorted(set(old_codes) - set(available_codes))) + self.app.push_screen( + CodeSelectionDialog(available_codes, old_codes), + lambda selected: self.edit_compute_details(item_id, old, selected) + ) + + def available_codes(self) -> list[str]: + return _available_codes(self.app.backend.ecce_home) + + def edit_compute_details(self, item_id: str | None, old: dict[str, Any], + selected: list[dict[str, Any]] | None) -> None: + if selected is None: + return + self.compute_codes = selected + fields = [ + ("name", "Registration name", "Cluster", old.get("name", "")), + ("host", "Host or SSH alias", "cluster.example.org", old.get("host", "")), + ("vendor", "Vendor (optional)", "Linux", old.get("vendor", "")), + ("model", "Model (optional)", "HPC cluster", old.get("model", "")), + ("processor", "Processor type (optional)", "AMD EPYC", old.get("processor", "")), + ("processors", "Processors per node", "64", str(old.get("processors", 1))), + ("nodes", "Nodes", "1", str(old.get("nodes", 0))), + ("allocation", "Allocation accounts: true or false", "false", str(old.get("allocationAccounts", False)).lower()), + ("queue_manager", "Queue manager (None for unqueued)", "slurm", old.get("queueManager", "None")), + ] + details = [ + ("queues", "Queues JSON list", "[]", json.dumps(old.get("queues", []), indent=2)), + ("settings", "Machine settings JSON list", "[]", json.dumps(old.get("settings", []), indent=2)), + ] + self.app.push_screen( + EntryDialog("Edit compute definition" if item_id else "New compute definition", fields, details), + lambda values: self.compute_details_saved(item_id, old, values) + ) + + def compute_details_saved(self, item_id: str | None, old: dict[str, Any], + values: dict[str, str] | None) -> None: + if values is None: + return + values = dict(values) + values["codes"] = json.dumps(self.compute_codes) + self.save_item(item_id, values, old) + + def save_item(self, item_id: str | None, values: dict[str, str] | None, + old: dict[str, Any]) -> None: + if not values: + return + try: + if self.section == "dataServers": + pem = values.get("pem", old.get("tlsCertificatePem", "")) + entry = {"name": values["name"], "url": values["url"], "tlsCertificatePem": pem} + candidate = {"format": "ecce-configuration", "version": 2, + "dataServers": [entry], "computeResources": [], "jobCreationCodes": []} + else: + entry = { + "name": values["name"], "host": values["host"], "vendor": values["vendor"], + "model": values["model"], "processor": values["processor"], + "processors": int(values["processors"]), "nodes": int(values["nodes"] or "0"), + "allocationAccounts": values["allocation"].lower() in {"true", "1", "yes"}, + "queueManager": values["queue_manager"] or "None", + "codes": json.loads(values["codes"] or "[]"), + "queues": json.loads(values["queues"] or "[]"), + "settings": json.loads(values["settings"] or "[]"), + } + candidate = {"format": "ecce-configuration", "version": 2, + "dataServers": [], "computeResources": [entry], "jobCreationCodes": []} + entry = normalize_profile(candidate)[self.section][0] + catalog = self.app.store.load_catalog() + for other_id, other in catalog[self.section].items(): + if other_id != item_id and other["name"].casefold() == entry["name"].casefold(): + raise ValueError(f"A {self.section} catalog entry named '{entry['name']}' already exists.") + if item_id: + db = self.app.store.load() + for profile_name, refs in db["profileCatalogs"].items(): + if item_id not in refs.get(self.section, []): + continue + embedded = load_profile(self.app.store.profile_path(profile_name))[self.section] + other_names = {value["name"].casefold() for value in embedded} + other_names.update( + catalog[self.section][other_ref]["name"].casefold() + for other_ref in refs.get(self.section, []) if other_ref != item_id) + if entry["name"].casefold() in other_names: + raise ValueError( + f"'{entry['name']}' would duplicate a resource in profile '{profile_name}'.") + item_id = item_id or self.app.store.new_catalog_id() + catalog[self.section][item_id] = entry + self.app.store.save_catalog(catalog) + self.refresh_catalog() + self.app.notify("Shared catalog definition saved. Profiles using it will see this update.") + except (OSError, ValueError, KeyError, TypeError, ProfileError, StoreError) as exc: + self.app.notify(str(exc), title="Could not save catalog definition", severity="error") + + def delete_item(self, item_id: str, confirmed: bool) -> None: + if not confirmed: + return + db = self.app.store.load() + assigned = [profile for profile, refs in db["profileCatalogs"].items() + if item_id in refs.get(self.section, [])] + if assigned: + self.app.notify("Remove this item from profiles first: " + ", ".join(sorted(assigned)), severity="warning") + return + catalog = self.app.store.load_catalog() + del catalog[self.section][item_id] + self.app.store.save_catalog(catalog) + self.refresh_catalog() + self.app.notify("Deleted shared catalog definition.") + + +class ServerScreen(Screen): + BINDINGS = [("escape", "app.pop_screen", "Back")] + + def compose(self) -> ComposeResult: + yield Header() + with Vertical(id="workspace"): + yield Static("SERVER / SERVICE CONTROL", classes="eyebrow") + yield Label("Data server", classes="page-title") + yield Static("Commands run as the account that owns this data server.", classes="subtitle") + yield Static("Generate, load, or install TLS certificates from a data-server definition in the shared catalog.", classes="hint") + yield Static("Loading status…", id="status", classes="status-panel") + with Horizontal(classes="toolbar"): + yield Button("Refresh status", id="status-button") + yield Button("Start", variant="primary", id="start") + yield Button("Stop", variant="error", id="stop") + yield Button("Back", id="back") + yield Footer() + + def on_mount(self) -> None: + self.refresh_status() + + def run_command(self, name: str, *args: str) -> tuple[int, str]: + return self.app.backend._command(name, *args) + + def refresh_status(self) -> None: + code, output = self.run_command("ecce-dataserver-status") + self.query_one("#status", Static).update(output or ("Status check completed." if code == 0 else "Status check failed.")) + + @on(Button.Pressed) + def action(self, event: Button.Pressed) -> None: + action = event.button.id + if action == "back": + self.app.pop_screen() + elif action == "status-button": + self.refresh_status() + elif action in {"start", "stop"}: + if action == "stop": + self.app.push_screen(ConfirmDialog("Stop the ECCE data server?"), + lambda confirmed: self.execute("ecce-dataserver-stop", (), confirmed)) + else: + self.execute("ecce-dataserver-start", (), True) + + def execute(self, command: str, args: tuple[str, ...], confirmed: bool) -> None: + if not confirmed: + return + code, output = self.run_command(command, *args) + self.app.notify(output or ("Command completed." if code == 0 else "Command failed."), + severity="information" if code == 0 else "error", timeout=8) + self.refresh_status() + + +class AccessScreen(Screen): + BINDINGS = [("escape", "app.pop_screen", "Back")] + + def compose(self) -> ComposeResult: + yield Header() + with Vertical(id="workspace"): + yield Static("ACCESS / USERS AND GROUPS", classes="eyebrow") + yield Label("User and group setup", classes="page-title") + yield Static("Create accounts, set contact details, assign groups, and map each group to a client profile.", classes="subtitle") + with Horizontal(classes="section-tabs"): + yield Button("Open user management", variant="primary", id="users-tab") + yield Button("Open group management", id="groups-tab") + with Horizontal(classes="home-cards"): + with Vertical(classes="home-card"): + yield Label("Users", classes="card-title") + yield Static("Manage data-server logins, email addresses, and group membership.") + yield Button("Manage users", variant="primary", id="users") + with Vertical(classes="home-card"): + yield Label("Groups / user types", classes="card-title") + yield Static("Create user types and choose the client profile each one receives.") + yield Button("Manage groups", id="groups") + yield Button("Back", id="back") + yield Footer() + + @on(Button.Pressed) + def action(self, event: Button.Pressed) -> None: + if event.button.id == "back": + self.app.pop_screen() + elif event.button.id in {"users", "users-tab"}: + self.app.push_screen(UsersScreen()) + elif event.button.id in {"groups", "groups-tab"}: + self.app.push_screen(GroupsScreen()) + + +class UsersScreen(Screen): + BINDINGS = [("escape", "app.pop_screen", "Back")] + + def compose(self) -> ComposeResult: + yield Header() + with Vertical(id="workspace"): + yield Static("ACCESS / USERS", classes="eyebrow") + with Horizontal(classes="section-tabs"): + yield Button("Users", variant="primary", id="manage-users-tab") + yield Button("Groups / user types", id="manage-groups-tab") + yield Label("Data-server users", classes="page-title") + yield Static("A user can use a profile assigned directly or combine the profiles assigned to their groups.", classes="subtitle") + yield DataTable(id="users-table", cursor_type="row") + with Horizontal(classes="toolbar"): + yield Button("Add user", variant="primary", id="add") + yield Button("Bulk import CSV", id="import-csv") + yield Button("Edit user / profile", id="edit") + yield Button("Email configuration", id="send-profile") + with Horizontal(classes="toolbar"): + yield Button("Change selected user's password", variant="primary", id="password") + yield Button("Delete account", variant="error", id="delete") + yield Button("Back", id="back") + yield Footer() + + def on_mount(self) -> None: + self.query_one("#users-table", DataTable).add_columns("Username", "Email", "Groups", "Client profile") + self.refresh_users() + + def refresh_users(self) -> None: + db = self.app.store.load() + table = self.query_one("#users-table", DataTable) + table.clear() + for username in sorted(self.app.backend._server_accounts()): + record = db["users"].get(username, {}) + profile = record.get("profile", "") + if not profile: + profiles = sorted({db["groups"].get(group, {}).get("profile", "") + for group in record.get("groups", [])} - {""}) + profile = ", ".join(profiles) if profiles else "—" + table.add_row(username, record.get("email") or "—", + ", ".join(record.get("groups", [])) or "—", profile, + key=username) + + def selected_user(self) -> str | None: + table = self.query_one("#users-table", DataTable) + return str(table.get_row_at(table.cursor_row)[0]) if table.row_count else None + + @on(Button.Pressed) + def action(self, event: Button.Pressed) -> None: + action = event.button.id + if action == "back": + self.app.pop_screen() + elif action == "manage-groups-tab": + self.app.pop_screen() + self.app.push_screen(GroupsScreen()) + elif action == "add": + profile_options = [("Use assigned group profile(s)", "__group_profiles__")] + profile_options.extend((profile, profile) for profile in sorted( + p.stem for p in self.app.store.profiles_dir.glob("*.json"))) + self.app.push_screen(EntryDialog("Create data-server user", [ + ("username", "Username (letters and numbers)", "jsmith"), + ("first", "First name", "Jordan"), ("last", "Last name", "Smith"), + ("email", "Email address", "jsmith@example.org"), + ("groups", "Groups (comma separated)", "research"), + ("profile", "Client configuration profile", "Choose a profile", "__group_profiles__", + profile_options), + ("client", "Client location: local or remote", "remote", "remote"), + ("password", "Initial password", "Enter password"), + ("password_again", "Repeat password", "Repeat password")]), self.create_user) + elif action == "import-csv": + groups = ", ".join(sorted(self.app.store.load()["groups"])) + profiles = ", ".join(sorted(p.stem for p in self.app.store.profiles_dir.glob("*.json"))) + self.app.push_screen(EntryDialog("Bulk import CSV (username/email required; group(s)/profile optional)", [ + ("path", "CSV file path", "/path/to/users.csv"), + ("groups", "Default groups (CSV group/groups column overrides)", groups), + ("profile", f"Default profile (CSV profile column overrides; available: {profiles or 'none'})", "Optional; blank uses group profiles"), + ("client", "Client location: local or remote", "remote", "remote")]), + self.import_csv_users) + elif action == "edit": + username = self.selected_user() + if username: + record = self.app.store.load()["users"].get(username, {}) + profiles = ", ".join(sorted(p.stem for p in self.app.store.profiles_dir.glob("*.json"))) + profile_options = [("Use assigned group profile(s)", "__group_profiles__")] + profile_options.extend((profile, profile) for profile in sorted( + p.stem for p in self.app.store.profiles_dir.glob("*.json"))) + current_profile = record.get("profile", "") or "__group_profiles__" + if current_profile != "__group_profiles__" and current_profile not in { + option[1] for option in profile_options}: + profile_options.append((f"{current_profile} (unavailable)", current_profile)) + self.app.push_screen(EntryDialog("Update user details", [ + ("email", "Email address", "jsmith@example.org", record.get("email", "")), + ("groups", "Groups (comma separated)", "research, teaching", + ",".join(record.get("groups", []))), + ("profile", f"Client configuration profile (available: {profiles or 'none'})", + "Choose a profile", current_profile, profile_options), + ("client", "Client location: local or remote", "remote", "remote")]), + lambda values: self.update_user(username, values)) + elif action == "password": + username = self.selected_user() + if username: + self.app.push_screen(EntryDialog(f"Change password for {username}", [ + ("password", "New password", "Enter password"), + ("password_again", "Repeat password", "Repeat password")]), + lambda values: self.change_password(username, values)) + elif action == "send-profile": + username = self.selected_user() + if username: + self.email_user_profile(username) + elif action == "delete": + username = self.selected_user() + if username: + self.app.push_screen(ConfirmDialog( + f"Revoke the data-server login for '{username}'? Their stored data will be kept."), + lambda confirmed: self.delete_user(username, confirmed)) + + def _group_names(self, value: str) -> list[str]: + names = list(dict.fromkeys(part.strip() for part in value.split(",") if part.strip())) + db = self.app.store.load() + missing = sorted(set(names) - set(db["groups"])) + if missing: + raise ValueError("Create these groups first: " + ", ".join(missing)) + return names + + def import_csv_users(self, values: dict[str, str] | None) -> None: + if not values: + return + try: + results = self.app.backend.import_users_csv( + values["path"], values["groups"], values["profile"], values["client"]) + self.refresh_users() + for result in results: + print(result) + created = sum(1 for result in results if result.endswith("configuration email attempted separately")) + self.app.notify(f"CSV import finished: {created} users created. Check terminal output for separate email delivery results.") + except (OSError, ValueError, StoreError, ProfileError) as exc: + self.app.notify(str(exc), title="Could not import users", severity="error") + + def _profile_name(self, value: str) -> str: + name = value.strip() + if not name: + return "" + path = self.app.store.profile_path(name) + if not path.is_file(): + raise ValueError(f"No profile named '{name}'.") + self.app.store.load_profile(name) + return name + + def create_user(self, values: dict[str, str] | None) -> None: + if not values: + return + try: + username = self.app.store.safe_name(values["username"]) + if not username.isalnum(): + raise ValueError("ECCE usernames must contain letters and numbers only.") + if username in self.app.backend._server_accounts(): + raise ValueError(f"Data-server account '{username}' already exists.") + email = self.app.backend._email(values["email"]) + groups = self._group_names(values["groups"]) + profile_name = self._profile_name(values.get("profile", "")) + client = values["client"].strip().lower() + if client not in {"local", "remote"}: + raise ValueError("Client location must be local or remote.") + if values["password"] != values["password_again"] or not values["password"]: + raise ValueError("Enter the same non-empty password twice.") + if email and (groups or profile_name): + record = {"email": email, "groups": groups, "profile": profile_name} + client_profile = self.app.backend._user_profile(record) + self.app.backend._validate_client_location(client_profile, client[0]) + code, output = self.app.backend._command( + "ecce-dataserver-adduser", "--stdin", username, + values["first"].strip() or username, values["last"].strip() or username, + input_text=values["password"] + "\n") + if code: + raise ValueError(output or "Account creation failed.") + record = {"email": email, "groups": groups, "profile": profile_name} + db = self.app.store.load() + db["users"][username] = record + self.app.backend._sync_group_file_access(db) + self.app.store.save(db) + self.refresh_users() + if email and (groups or profile_name): + self.app.backend.deliver_user_profile(username, record, client[0]) + self.app.notify(f"Created user '{username}'.") + except (OSError, ValueError, StoreError, ProfileError) as exc: + self.app.notify(str(exc), title="Could not create user", severity="error") + + def update_user(self, username: str, values: dict[str, str] | None) -> None: + if not values: + return + try: + record = self.app.store.load()["users"].get(username) + if record is None: + raise ValueError(f"No managed details for '{username}'.") + record["email"] = self.app.backend._email(values["email"]) + record["groups"] = self._group_names(values["groups"]) + record["profile"] = self._profile_name(values.get("profile", "")) + db = self.app.store.load() + db["users"][username] = record + if record["email"] and (record["groups"] or record["profile"]): + location = values["client"].strip().lower() + if location not in {"local", "remote"}: + raise ValueError("Client location must be local or remote.") + profile = self.app.backend._user_profile(record, db) + self.app.backend._validate_client_location(profile, location[0]) + self.app.backend._sync_group_file_access(db) + self.app.store.save(db) + self.refresh_users() + if record["email"] and (record["groups"] or record["profile"]): + self.app.push_screen(ConfirmDialog(f"Email the updated configuration to {record['email']}?"), + lambda confirmed: self.deliver_update(username, record, location[0], confirmed)) + return + self.app.notify(f"Updated '{username}'.") + except (OSError, ValueError, StoreError, ProfileError) as exc: + self.app.notify(str(exc), title="Could not update user", severity="error") + + def deliver_update(self, username: str, record: dict[str, Any], location: str, + confirmed: bool) -> None: + if confirmed: + self.app.backend.deliver_user_profile(username, record, location) + self.app.notify(f"Configuration delivery attempted for '{username}'.") + + def email_user_profile(self, username: str) -> None: + try: + db = self.app.store.load() + record = db["users"].get(username) + if record is None: + raise ValueError(f"No managed details for '{username}'.") + if not record.get("email"): + raise ValueError(f"Add an email address for '{username}' first.") + profile = self.app.backend._user_profile(record, db) + self.app.push_screen(EntryDialog(f"Email configuration to {username}", [ + ("client", "Client location: local or remote", "remote", "remote")]), + lambda values: self.confirm_profile_email(username, record, profile, values)) + except (OSError, ValueError, StoreError, ProfileError) as exc: + self.app.notify(str(exc), title="Could not prepare configuration email", severity="error") + + def confirm_profile_email(self, username: str, record: dict[str, Any], + profile: dict[str, Any], + values: dict[str, str] | None) -> None: + if not values: + return + location = values["client"].strip().lower() + if location not in {"local", "remote"}: + self.app.notify("Client location must be local or remote.", severity="error") + return + try: + self.app.backend._validate_client_location(profile, location[0]) + except ValueError as exc: + self.app.notify(str(exc), severity="error") + return + self.app.push_screen( + ConfirmDialog(f"Email the configuration and username '{username}' to {record['email']}?"), + lambda confirmed: self.deliver_update(username, record, location[0], confirmed) + ) + + def change_password(self, username: str, values: dict[str, str] | None) -> None: + if not values: + return + if not values["password"] or values["password"] != values["password_again"]: + self.app.notify("Enter the same non-empty password twice.", severity="error") + return + code, output = self.app.backend._command("ecce-dataserver-adduser", "--passwd", username, + input_text=values["password"] + "\n") + self.app.notify(output or ("Password changed." if code == 0 else "Password change failed."), + severity="information" if code == 0 else "error") + + def delete_user(self, username: str, confirmed: bool) -> None: + if not confirmed: + return + code, output = self.app.backend._command("ecce-dataserver-deluser", username, "--yes") + if code: + self.app.notify(output or "Account removal failed.", severity="error") + return + db = self.app.store.load() + if username in db["users"]: + db["users"][username]["groups"] = [] + self.app.backend._sync_group_file_access(db) + db["users"].pop(username, None) + self.app.store.save(db) + try: + (self.app.store.root / "users" / f"{username}.json").unlink() + except FileNotFoundError: + pass + self.refresh_users() + self.app.notify(f"Revoked '{username}'. Stored data was kept.") + + +class GroupsScreen(Screen): + BINDINGS = [("escape", "app.pop_screen", "Back")] + + def compose(self) -> ComposeResult: + yield Header() + with Vertical(id="workspace"): + yield Static("ACCESS / GROUPS", classes="eyebrow") + with Horizontal(classes="section-tabs"): + yield Button("User management", id="manage-users-tab") + yield Button("Groups / user types", variant="primary", id="manage-groups-tab") + yield Label("Groups and user types", classes="page-title") + yield Static("Manage memberships, client profiles, and file-access privileges for each group.", classes="subtitle") + yield DataTable(id="groups-table", cursor_type="row") + with Horizontal(classes="toolbar"): + yield Button("Create group", variant="primary", id="create") + yield Button("View / edit members", id="members") + with Horizontal(classes="toolbar"): + yield Button("Assign profile", id="assign") + yield Button("Edit privileges", id="policy") + yield Button("Delete group", variant="error", id="delete") + yield Button("Back", id="back") + yield Footer() + + def on_mount(self) -> None: + self.query_one("#groups-table", DataTable).add_columns("Group", "Client profile", "Members", "Member file access") + self.refresh_groups() + + def refresh_groups(self) -> None: + db = self.app.store.load() + table = self.query_one("#groups-table", DataTable) + table.clear() + for name, details in sorted(db["groups"].items()): + members = [user for user, record in db["users"].items() if name in record.get("groups", [])] + policy = {"none": "None", "read": "Read", "readwrite": "Read/write"}.get( + details.get("fileAccess", "none"), "None") + table.add_row(name, details.get("profile") or "Unassigned", str(len(members)), policy, key=name) + + def selected_group(self) -> str | None: + table = self.query_one("#groups-table", DataTable) + return str(table.get_row_at(table.cursor_row)[0]) if table.row_count else None + + @on(Button.Pressed) + def action(self, event: Button.Pressed) -> None: + action = event.button.id + if action == "back": + self.app.pop_screen() + elif action == "manage-users-tab": + self.app.pop_screen() + self.app.push_screen(UsersScreen()) + elif action == "create": + self.app.push_screen(EntryDialog("Create group / user type", [ + ("name", "Group name", "research")]), self.create_group) + elif action == "assign": + name = self.selected_group() + if name: + profiles = ", ".join(sorted(p.stem for p in self.app.store.profiles_dir.glob("*.json"))) + self.app.push_screen(EntryDialog("Assign a client profile", [ + ("profile", f"Profile name (available: {profiles or 'none'})", "research-team")]), + lambda values: self.assign_profile(name, values)) + elif action == "policy": + name = self.selected_group() + if name: + self.app.push_screen(GroupPolicyDialog(), + lambda policy: self.set_file_access(name, policy)) + elif action == "members": + name = self.selected_group() + if name: + self.app.push_screen(GroupMembersScreen(name)) + elif action == "delete": + name = self.selected_group() + if name: + self.app.push_screen(ConfirmDialog(f"Delete group '{name}'? It must have no members."), + lambda confirmed: self.delete_group(name, confirmed)) + + def create_group(self, values: dict[str, str] | None) -> None: + if not values: + return + try: + name = self.app.store.safe_name(values["name"]) + db = self.app.store.load() + if name in db["groups"]: + raise ValueError(f"Group '{name}' already exists.") + db["groups"][name] = {"profile": "", "fileAccess": "none"} + self.app.store.save(db) + self.refresh_groups() + self.app.notify(f"Created group '{name}'.") + except (ValueError, StoreError) as exc: + self.app.notify(str(exc), title="Could not create group", severity="error") + + def set_file_access(self, name: str, policy: str | None) -> None: + if not policy: + return + try: + db = self.app.store.load() + if name not in db["groups"]: + raise ValueError(f"No group named '{name}'.") + db["groups"][name]["fileAccess"] = policy + self.app.backend._sync_group_file_access(db) + self.app.store.save(db) + self.refresh_groups() + label = {"none": "no group file access", "read": "read access", + "readwrite": "read and write access"}[policy] + self.app.notify(f"Set '{name}' to {label} for members' data folders.") + except (OSError, ValueError, StoreError) as exc: + self.app.notify(str(exc), title="Could not update group file access", severity="error") + + def assign_profile(self, name: str, values: dict[str, str] | None) -> None: + if not values: + return + profile = values["profile"].strip() + try: + db = self.app.store.load() + path = self.app.store.profile_path(profile) + if not path.is_file(): + raise ValueError(f"No profile named '{profile}'.") + self.app.store.load_profile(profile) + db["groups"][name]["profile"] = profile + self.app.store.save(db) + self.refresh_groups() + self.app.notify(f"Group '{name}' now uses profile '{profile}'. Resend profiles from the user screen when ready.") + except (ValueError, OSError, StoreError, ProfileError) as exc: + self.app.notify(str(exc), title="Could not assign profile", severity="error") + + def delete_group(self, name: str, confirmed: bool) -> None: + if not confirmed: + return + db = self.app.store.load() + members = [user for user, record in db["users"].items() if name in record.get("groups", [])] + if members: + self.app.notify("Remove the group from these users first: " + ", ".join(sorted(members)), severity="warning") + return + del db["groups"][name] + self.app.store.save(db) + self.refresh_groups() + self.app.notify(f"Deleted group '{name}'.") + + +class GroupMembersScreen(Screen): + BINDINGS = [("escape", "app.pop_screen", "Back")] + + def __init__(self, group_name: str): + super().__init__() + self.group_name = group_name + + def compose(self) -> ComposeResult: + yield Header() + with Vertical(id="workspace"): + yield Static("ACCESS / GROUPS / MEMBERS", classes="eyebrow") + yield Label(f"Members of {self.group_name}", classes="page-title") + yield Static("Select an account to add it to or remove it from this group.", classes="subtitle") + yield DataTable(id="members-table", cursor_type="row") + with Horizontal(classes="toolbar"): + yield Button("Add selected user", variant="primary", id="add-member") + yield Button("Remove selected user", variant="error", id="remove-member") + yield Button("Back to groups", id="back") + yield Footer() + + def on_mount(self) -> None: + self.query_one("#members-table", DataTable).add_columns("Username", "Email", "Membership") + self.refresh_members() + + def refresh_members(self) -> None: + db = self.app.store.load() + table = self.query_one("#members-table", DataTable) + table.clear() + for username in sorted(self.app.backend._server_accounts()): + record = db["users"].get(username, {}) + assigned = self.group_name in record.get("groups", []) + table.add_row(username, record.get("email") or "—", + "Member" if assigned else "Not a member", key=username) + + def selected_user(self) -> str | None: + table = self.query_one("#members-table", DataTable) + return str(table.get_row_at(table.cursor_row)[0]) if table.row_count else None + + @on(Button.Pressed) + def action(self, event: Button.Pressed) -> None: + if event.button.id == "back": + self.app.pop_screen() + elif event.button.id == "add-member": + self.update_membership(add=True) + elif event.button.id == "remove-member": + self.update_membership(add=False) + + def update_membership(self, *, add: bool) -> None: + username = self.selected_user() + if not username: + self.app.notify("Select a user first.", severity="warning") + return + try: + db = self.app.store.load() + if self.group_name not in db["groups"]: + raise ValueError(f"No group named '{self.group_name}'.") + record = db["users"].setdefault( + username, {"email": "", "groups": [], "profile": ""}) + memberships = record.setdefault("groups", []) + if add: + if self.group_name in memberships: + self.app.notify(f"'{username}' is already a member of '{self.group_name}'.", severity="warning") + return + memberships.append(self.group_name) + else: + if self.group_name not in memberships: + self.app.notify(f"'{username}' is not a member of '{self.group_name}'.", severity="warning") + return + memberships.remove(self.group_name) + self.app.backend._sync_group_file_access(db) + self.app.store.save(db) + self.refresh_members() + self.app.notify(f"Updated '{username}' in group '{self.group_name}'.") + except (OSError, ValueError, StoreError) as exc: + self.app.notify(str(exc), title="Could not update group members", severity="error") + + +class ServerAdminApp(App): + TITLE = "ECCE Server Admin" + SUB_TITLE = "Data server and client configuration" + CSS = """ + Screen { background: #101a2a; color: #e7edf7; } + Header { background: #13243a; color: #e7edf7; } + Footer { background: #13243a; } + #home, #workspace { width: 100%; height: 1fr; padding: 2 4; } + #home { align-horizontal: center; } + .eyebrow { color: #63d4c6; text-style: bold; margin-bottom: 1; } + .hero { color: #f1f5fb; text-style: bold; text-align: center; width: 100%; height: auto; margin: 0 0 1 0; } + .page-title { color: #f1f5fb; text-style: bold; height: auto; margin-bottom: 1; } + .subtitle { color: #a9b7ca; margin-bottom: 2; } + .home-cards { width: 100%; max-width: 76; height: auto; } + .home-card { width: 100%; height: auto; min-height: 8; border: round #2d4563; background: #17263b; padding: 1 2; margin: 0 0 1 0; } + .home-card Button { width: 100%; } + .card-title { color: #f1f5fb; text-style: bold; margin-bottom: 1; } + .hint { color: #8293aa; margin-top: 1; } + .toolbar, .section-tabs { height: auto; margin-top: 1; } + .toolbar Button, .section-tabs Button { margin-right: 1; } + .code-row { height: auto; align-vertical: middle; } + .code-row Checkbox { width: 1fr; } + #profiles-table, #entries-table { height: 1fr; min-height: 8; border: round #2d4563; } + .status-panel { border: round #2d4563; background: #17263b; padding: 2; height: auto; min-height: 7; margin: 1 0 2 0; } + #dialog, #confirm-dialog { width: 76; max-width: 92%; max-height: 90%; border: round #63d4c6; background: #17263b; padding: 1 2; } + #dialog { height: auto; } + #form-scroll { height: 1fr; max-height: 34; } + .dialog-title { color: #f1f5fb; text-style: bold; margin-bottom: 1; } + .field-label { color: #a9b7ca; margin-top: 1; } + Input, TextArea { margin-bottom: 1; } + TextArea { height: 8; } + .actions { height: auto; align-horizontal: right; margin-top: 1; } + .actions Button { margin-left: 1; } + """ + + BINDINGS = [("q", "quit", "Quit")] + + def __init__(self) -> None: + super().__init__() + self.backend = backend.ServerTUI() + self.store: Store = self.backend.store + + def on_mount(self) -> None: + self.push_screen(HomeScreen()) + + +def run_textual() -> int: + try: + ServerAdminApp().run() + except (RuntimeError, StoreError) as exc: + print(f"ecce-server-tui: {exc}", file=sys.stderr) + return 1 + return 0 diff --git a/src/apps/organizer/CalcMgr.C b/src/apps/organizer/CalcMgr.C index 958415c4b6..d5dcbbc95d 100644 --- a/src/apps/organizer/CalcMgr.C +++ b/src/apps/organizer/CalcMgr.C @@ -4061,6 +4061,7 @@ bool CalcMgr::connectServer(const string& ref) name = list[i].name; ServerList::markAdded(ref); string user = ServerList::loginFor(ref), pass; + if (user.empty()) user = ServerList::usernameFor(ref); if (!WxDavAuth::askAddedLogin(ref, user, pass)) { setMessage("Not connected to " + name + ": the login was cancelled.", WxFeedback::ERROR); 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..b2d6356b3a --- /dev/null +++ b/src/util/genutil/JsonConfigurationProfile.C @@ -0,0 +1,525 @@ +#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 safeCodeText(const string& value) +{ + const string text = lower(value); + const char* const sensitive[] = { + "password", "passwd", "credential", "token", "secret", "username", + "user=", "--account", "account=" + }; + for (size_t i = 0; i < sizeof(sensitive)/sizeof(sensitive[0]); ++i) + if (text.find(sensitive[i]) != string::npos) return false; + size_t account = text.find("account"); + while (account != string::npos) { + const size_t end = account + 7; + const bool leftBoundary = account == 0 || + !((text[account - 1] >= 'a' && text[account - 1] <= 'z')); + const bool rightBoundary = end == text.size() || + !(text[end] >= 'a' && text[end] <= 'z'); + if (leftBoundary && rightBoundary) return false; + account = text.find("account", end); + } + return value.find('\0') == string::npos; +} + +bool validEnvironment(const string& value) +{ + std::istringstream lines(value); + string line; + while (std::getline(lines, line)) { + const size_t first = line.find_first_not_of(" \t\r"); + if (first == string::npos) continue; + const size_t last = line.find_last_not_of(" \t\r"); + line = line.substr(first, last - first + 1); + const size_t split = line.find_first_of(" \t"); + if (split == string::npos || split == 0) return false; + const string name = line.substr(0, split); + if (!((name[0] >= 'A' && name[0] <= 'Z') || + (name[0] >= 'a' && name[0] <= 'z') || name[0] == '_')) return false; + for (size_t i = 1; i < name.size(); ++i) + if (!((name[i] >= 'A' && name[i] <= 'Z') || + (name[i] >= 'a' && name[i] <= 'z') || + (name[i] >= '0' && name[i] <= '9') || name[i] == '_')) return false; + } + return true; +} + +bool validCodeBlock(const string& value) +{ + if (value == "-") return false; + if (value.find('\n') == string::npos && value.find('{') == string::npos) + return true; + std::istringstream lines(value); + string line; + while (std::getline(lines, line)) + if (!line.empty() && line[0] == '}') return false; + return true; +} + +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 username or password information."; + return false; + } + if (s.username.find_first_not_of( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") != string::npos) { + error = "A data server username may contain only letters and numbers."; + 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.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 || + !safeCodeText(r.codes[j].program) || !safeCodeText(r.codes[j].setup) || + !safeCodeText(r.codes[j].command) || + !safeCodeText(r.codes[j].environment) || + !validCodeBlock(r.codes[j].program) || + !validCodeBlock(r.codes[j].setup) || + !validCodeBlock(r.codes[j].command) || + !validCodeBlock(r.codes[j].environment) || + !validEnvironment(r.codes[j].environment)) { + 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\": 2,\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) + << ",\"tlsCertificatePem\":" << quote(s.tlsCertificatePem) + << ",\"username\":" << quote(s.username) << "}"; + } + 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 << ",\"setup\":" << quote(c.setup) + << ",\"command\":" << quote(c.command) + << ",\"environment\":" << quote(c.environment); + 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")) { + error = "This is not a supported ECCE configuration profile."; + return false; + } + const bool fullMachineDefinitions = root.get("version").str() == "2"; + + 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; + } + // Older client profiles do not carry a data-server username. + if (item.get("username").type() != MiniJson::Null && + !readString(item, "username", s.username)) { + error = "A data server username must be a string."; + 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; + } + 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; + } + const MiniJson& setup = code.get("setup"); + const MiniJson& command = code.get("command"); + const MiniJson& environment = code.get("environment"); + if ((!setup.isNull() && !readString(code, "setup", c.setup)) || + (!command.isNull() && !readString(code, "command", c.command)) || + (!environment.isNull() && !readString(code, "environment", c.environment))) { + error = "A code entry has an invalid optional setting."; + 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/ServerList.C b/src/util/genutil/ServerList.C index b80314e172..fc8c9c659a 100644 --- a/src/util/genutil/ServerList.C +++ b/src/util/genutil/ServerList.C @@ -48,8 +48,12 @@ 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); - // Three-column entries predate the option and retain their startup behavior. - e.connectAtStart = c == string::npos || line.substr(c + 1) != "0"; + size_t d = c == string::npos ? c : line.find('\t', c + 1); + // Three-column entries predate the startup option; four-column entries + // predate the optional login hint. + 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; @@ -65,7 +69,8 @@ bool ServerList::save(const vector& list) if (!out) return false; 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) << '\t' + << list[i].username << '\n'; if (!out) return false; } remove(path.c_str()); // rename() does not replace on Windows @@ -78,8 +83,12 @@ string ServerList::check(const ServerEntry& e) if (e.type != "ssh" && e.type != "ecce") return "Choose the type of the server."; if (blank(e.name)) return "Give the server a name."; 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.name) || !clean(e.address) || !clean(e.username)) + return "The name, address, and username cannot contain tabs or line breaks."; + if (e.type == "ecce" && + e.username.find_first_not_of( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") != string::npos) + return "A data server username may contain only letters and numbers."; 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://"; @@ -118,7 +127,11 @@ string ServerList::replace(const string& oldName, const ServerEntry& e) } if (!oldName.empty() && at == list.size()) return "No such server."; if (at == list.size()) list.push_back(e); - else list[at] = e; + else { + ServerEntry replacement = e; + if (replacement.username.empty()) replacement.username = list[at].username; + list[at] = replacement; + } return save(list) ? "" : "The list of servers could not be saved."; } @@ -247,6 +260,15 @@ string ServerList::loginFor(const string& ref) return it == logins().end() ? sessionLogin(ref) : it->second; } +string ServerList::usernameFor(const string& ref) +{ + vector list = load(); + for (size_t i = 0; i < list.size(); i++) + if (list[i].type == "ecce" && refOf(list[i].address) == ref) + return list[i].username; + return ""; +} + string ServerList::sshRootOf(const string& url) { vector list = load(); diff --git a/src/wxgui/wxdialogs/GlobalPrefs.C b/src/wxgui/wxdialogs/GlobalPrefs.C index 45b86c434f..17ad8e15d9 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); } @@ -1075,6 +1167,473 @@ 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.tlsCertificatePem = readPinnedCertificate(server.url); + server.username = ServerList::usernameFor(ServerList::refOf(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); + map::const_iterator setup = + config.find(lowerAscii(codeName) + "_setup"); + if (setup != config.end() && + safeProfileValue(setup->second, localUser, remoteUser)) + code.setup = setup->second; + map::const_iterator command = + config.find(lowerAscii(codeName) + "command"); + if (command != config.end() && + safeProfileValue(command->second, localUser, remoteUser)) + code.command = command->second; + map::const_iterator environment = + config.find(lowerAscii(codeName) + "environment"); + if (environment != config.end() && + safeProfileValue(environment->second, localUser, remoteUser)) + code.environment = environment->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.connectAtStart = false; + server.username = profile.dataServers[i].username; + 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 profiles include a machine definition. + 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" + << "Compute resource login credentials are not included."; + 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; + } + if (importedServers[i].username.empty()) + importedServers[i].username = updatedServers[j].username; + 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.empty() ? "Unspecified" : resource.vendor); + form += ProcessMachine::field( + "model", resource.model.empty() ? "Unspecified" : resource.model); + form += ProcessMachine::field( + "processor", resource.processor.empty() ? "Unspecified" : 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); + const string codeKeys[] = { + lowerAscii(code.name) + "_setup", + lowerAscii(code.name) + "command", + lowerAscii(code.name) + "environment" + }; + const string codeValues[] = {code.setup, code.command, code.environment}; + for (size_t k = 0; k < 3; ++k) { + if (!codeValues[k].empty()) { + if (!config.set(codeKeys[k], codeValues[k], &configError)) { + configValid = false; + break; + } + } else if (replace) config.clear(codeKeys[k]); + } + } + 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();