From 97d99c63a2d4c66716681ca7f228b6117d7be808 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 11 Nov 2026 18:49:55 +0100 Subject: [PATCH] fix(credentials): run sudo without a password when the account has none A passwordless sudo setup (NOPASSWD, or an account without a password) was still asked for a password: leaving the field empty never satisfied the gate, so the dialog reopened and the operation could not run at all. The gate now asks sudo itself (`sudo -n true`) and lets the request through when it needs nothing, privileged commands fall back to `sudo -n` when no password is held, and an empty field cancels instead of looping. Releasing the lock records its own pending request so an answered prompt is replayed rather than lost. --- app/main-window.cpp | 17 ++++++++++---- app/main-window.h | 3 ++- core/app-core.cpp | 30 +++++++++++++++++++++++- core/app-core.h | 4 ++++ doc/operations.md | 6 +++++ providers/pacman-manager.cpp | 44 +++++++++++++++++++++++------------ providers/pacman-manager.h | 18 ++++++++++++-- tests/app-core.test.cpp | 11 +++++++++ tests/pacman-manager.test.cpp | 22 ++++++++++++++++++ 9 files changed, 131 insertions(+), 24 deletions(-) diff --git a/app/main-window.cpp b/app/main-window.cpp index b643ca9..e0df6ba 100644 --- a/app/main-window.cpp +++ b/app/main-window.cpp @@ -465,8 +465,10 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { updateStatusBar(); // With per-session credentials, ask for the sudo password once, right - // after the window is shown (so the dialog has a visible parent). - if (m_core->credentialMode() == AppCore::CredentialMode::AtLaunch) { + // after the window is shown (so the dialog has a visible parent) — unless + // sudo needs none on this machine. + if (m_core->credentialMode() == AppCore::CredentialMode::AtLaunch + && m_core->sudoRequiresPassword()) { QTimer::singleShot(0, this, [this] { promptForSudoPassword(); }); } @@ -1350,7 +1352,9 @@ void MainWindow::changeEvent(QEvent* event) { // The core knows *when* a password is needed (it owns the credential state and // the sudo pipeline); the frame only owns the dialog. bool MainWindow::promptForSudoPassword() { - if (m_core->hasSudoPassword()) return true; + // Nothing to ask when the session already holds a password or when sudo + // works without one (passwordless rule, account with no password). + if (m_core->hasSudoPassword() || !m_core->sudoRequiresPassword()) return true; LogManager::instance().logEvent( QStringLiteral("ui"), @@ -1361,11 +1365,14 @@ bool MainWindow::promptForSudoPassword() { this, "Authentification", tr("Mot de passe administrateur (sudo) :"), QLineEdit::Password, QString(), &ok); - if (!ok) { + if (!ok || password.isEmpty()) { + // An empty field is not a password: replaying the request would land on + // this very dialog again, so it is cancelled instead of looping. LogManager::instance().logEvent( QStringLiteral("ui"), tr("mot de passe refusé par l'utilisateur")); - statusBar()->showMessage(tr("Opération annulée : identifiants requis.")); + statusBar()->showMessage(ok ? tr("Mot de passe administrateur (sudo) requis.") + : tr("Opération annulée : identifiants requis.")); return false; } diff --git a/app/main-window.h b/app/main-window.h index 1d29ca2..b98efcb 100644 --- a/app/main-window.h +++ b/app/main-window.h @@ -145,7 +145,8 @@ private: // it needs before replaying it. void handleStartResult(const AppCore::StartResult& result, const QString& title); // Asks for the sudo password and hands it to the core. Returns false when - // the user cancelled. + // the user cancelled — or left the field empty while sudo requires one, + // which would only reopen the same dialog. bool promptForSudoPassword(); // Names the process holding pacman's database and offers to close it — or to // drop a stale lock — so the pending action can resume. diff --git a/core/app-core.cpp b/core/app-core.cpp index 5c34808..5d3f47e 100644 --- a/core/app-core.cpp +++ b/core/app-core.cpp @@ -290,6 +290,11 @@ bool AppCore::hasSudoPassword() const { return m_pacman && m_pacman->hasPassword(); } +bool AppCore::sudoRequiresPassword() const { + return m_pacman && !m_pacman->hasPassword() + && !PacmanManager::sudoWorksWithoutPassword(); +} + AppCore::StartResult AppCore::credentialGate( const std::vector& providers) const { bool privileged = false; @@ -309,6 +314,11 @@ AppCore::StartResult AppCore::credentialGate( } if (m_pacman->hasPassword()) return accepted(); + // Nothing to ask when sudo accepts the session as it is — a NOPASSWD rule, + // or an account with no password. Prompting there left the user with a + // dialog whose empty field could never satisfy the gate. + if (PacmanManager::sudoWorksWithoutPassword()) return accepted(); + // The view prompts for the password and calls retryPendingRequest(). return refused(tr("Mot de passe administrateur (sudo) requis."), /*needsPassword=*/true); @@ -595,7 +605,18 @@ AppCore::StartResult AppCore::releaseDatabaseLock() { const PacmanManager::LockHolder holder = PacmanManager::detectLockHolder(); const StartResult gate = credentialGate({m_pacman}); - if (!gate.started) return gate; + if (!gate.started) { + // The release itself now waits for the password, and the view replays + // it through retryPendingRequest() once the user answered. A request + // that was already pending wins: freeing the lock is meant to resume + // that one, not to replace it. + if (!m_pending) { + Request request; + request.action = QStringLiteral("release-lock"); + m_pending = request; + } + return gate; + } setBusy(true); emit statusMessage(tr("Libération de la base de données pacman...")); @@ -632,6 +653,10 @@ AppCore::StartResult AppCore::releaseDatabaseLock() { } LogManager::instance().endCommand(true); emit statusMessage(tr("Base libérée, reprise de l'opération...")); + // A release waiting for its own password has nothing left to resume. + if (m_pending && m_pending->action == QLatin1String("release-lock")) { + m_pending.reset(); + } // Deferred so the status message paints before the replayed action // starts streaming its own progress. QTimer::singleShot(0, this, [this] { retryPendingRequest(); }); @@ -1092,6 +1117,9 @@ AppCore::StartResult AppCore::retryPendingRequest() { const Request request = *m_pending; m_pending.reset(); + // Releasing the lock is not a startRequest action: it has its own entry + // point, which re-checks the credentials before running. + if (request.action == QLatin1String("release-lock")) return releaseDatabaseLock(); // A bulk removal is replayed with the groups it still has queued. const StartResult result = startRequest(request); if (!result.started && !result.needsPassword && !result.locked) { diff --git a/core/app-core.h b/core/app-core.h index cc623d8..d22af28 100644 --- a/core/app-core.h +++ b/core/app-core.h @@ -157,6 +157,10 @@ public: void setSudoPassword(const QString& password); void clearSudoPassword(); bool hasSudoPassword() const; + // Whether the view has to ask for a password at all: a passwordless sudo + // (NOPASSWD, or an account without one) has nothing to answer, so the + // prompt is skipped and privileged operations run straight away. + bool sudoRequiresPassword() const; // ---- History, logs, package details ---- void clearHistory(); diff --git a/doc/operations.md b/doc/operations.md index ef73495..9cf1fb4 100644 --- a/doc/operations.md +++ b/doc/operations.md @@ -74,6 +74,12 @@ refusé (« incorrect password », « authentication failure ») est **oublié immédiatement** : la prochaine tentative repose la question au lieu de réutiliser un secret faux. +Sans mot de passe (`sudo` en `NOPASSWD`, compte sans mot de passe), rien n'est +demandé : l'application vérifie avec `sudo -n true` que sudo accepte la session, +puis lance les commandes avec `sudo -n`. Sur une machine qui exige un mot de +passe, `sudo -n` échoue aussitôt — l'échec est remonté comme une erreur +d'authentification au lieu d'attendre une réponse que personne ne peut donner. + ## Verrou de la base pacman (`/var/lib/pacman/db.lck`) Si pacman refuse de démarrer, le core cherche **qui** tient le verrou, dans cet diff --git a/providers/pacman-manager.cpp b/providers/pacman-manager.cpp index b6c8c06..34eb90b 100644 --- a/providers/pacman-manager.cpp +++ b/providers/pacman-manager.cpp @@ -72,10 +72,11 @@ static std::string lastOutputLines(const std::string& output, int keep = 5) { } // Run a privileged pacman command as root, piping the password to `sudo -S` -// on stdin and capturing combined stdout+stderr. Output is delivered to the -// progress callback as pacman produces it — including its in-place download -// meters, which is what makes the bar move during a long download — and the -// full output is still returned for the auth/error checks. +// on stdin — or using `sudo -n` when there is none — and capturing combined +// stdout+stderr. Output is delivered to the progress callback as pacman +// produces it — including its in-place download meters, which is what makes +// the bar move during a long download — and the full output is still returned +// for the auth/error checks. // // The percentage comes from ProgressTracker, not from the raw counters: pacman // restarts "(1/24)" at every phase of the transaction, so forwarding those @@ -86,9 +87,9 @@ static std::string execPrivileged(const std::string& pacmanCmd, // The journal gets the command as the user would type it. The password is // piped to sudo on stdin and must never reach the trace. trace("$ sudo " + pacmanCmd); - const std::string full = "printf '%s\\n' " + shellQuote(password) - + " | sudo -S " + pacmanCmd + " 2>&1"; - return runWithProgress(full, progressCallback); + return runWithProgress(PacmanManager::privilegedCommand(pacmanCmd, password) + + " 2>&1", + progressCallback); } // pacman's database lock file. Every manager that goes through libalpm (pacman, @@ -766,10 +767,8 @@ bool PacmanManager::waitForDatabase(int timeoutMs) { } int PacmanManager::runCommand(const std::string& command, bool withSudo) const { - std::string full = command; - if (withSudo) { - full = "printf '%s\\n' " + shellQuote(m_password) + " | sudo -S " + command; - } + const std::string full = withSudo ? privilegedCommand(command, m_password) + : command; return system((full + " > /dev/null 2>&1").c_str()); } @@ -778,15 +777,15 @@ bool PacmanManager::terminateProcess(int pid, const char* signal) const { "kill -" + std::string(signal) + " " + std::to_string(pid); if (runCommand(command, /*withSudo=*/false) == 0) return true; // The holder belongs to another user (a manager started with sudo in a - // terminal): only the session password can reach it. - return hasPassword() && runCommand(command, /*withSudo=*/true) == 0; + // terminal): only root can reach it. Called unconditionally: without a + // password this is `sudo -n`, which fails at once when one is required. + return runCommand(command, /*withSudo=*/true) == 0; } bool PacmanManager::removeLockFile() const { const std::string command = std::string("rm -f ") + kLockFilePath; if (runCommand(command, /*withSudo=*/false) == 0 && databaseIsFree()) return true; - return hasPassword() && runCommand(command, /*withSudo=*/true) == 0 - && databaseIsFree(); + return runCommand(command, /*withSudo=*/true) == 0 && databaseIsFree(); } bool PacmanManager::releaseDatabaseLock(const LockHolder& holder, @@ -866,6 +865,21 @@ void PacmanManager::clearPassword() { m_password.clear(); } +bool PacmanManager::sudoWorksWithoutPassword() { + return system("sudo -n true > /dev/null 2>&1") == 0; +} + +std::string PacmanManager::privilegedCommand(const std::string& command, + const std::string& password) { + // No password is not a missing one: it means the account may use a + // passwordless sudo, which `-n` runs without asking. On a setup that does + // require a password, `-n` fails at once ("a password is required"), which + // authFailed() reports as an authentication error instead of hanging on a + // prompt the command cannot answer. + if (password.empty()) return "sudo -n " + command; + return "printf '%s\\n' " + shellQuote(password) + " | sudo -S " + command; +} + bool PacmanManager::hasPassword() const { return !m_password.empty(); } diff --git a/providers/pacman-manager.h b/providers/pacman-manager.h index 30ec59b..40b79a5 100644 --- a/providers/pacman-manager.h +++ b/providers/pacman-manager.h @@ -132,6 +132,20 @@ public: void clearPassword(); bool hasPassword() const; + // Whether sudo accepts this session without asking for anything (a + // passwordless sudo such as NOPASSWD, or an account with no password at + // all). Asked of sudo itself with `sudo -n true`, so it reflects what the + // next command will really get rather than the account's passwd entry. + static bool sudoWorksWithoutPassword(); + + // The shell command that runs `command` as root: the password is piped to + // `sudo -S`, or `sudo -n` is used when there is none. Without a password, + // a passwordless setup therefore still works, and a password-requiring one + // fails fast instead of waiting on a prompt nobody can answer. Exposed as + // static so both branches can be unit-tested without invoking sudo. + static std::string privilegedCommand(const std::string& command, + const std::string& password); + std::vector search(const std::string& query) override; bool install(const std::string& packageName, ProgressCallback progressCallback) override; @@ -157,8 +171,8 @@ private: bool isPackageInstalled(const std::string& name); // Run a one-off command (kill, rm) and return its exit status, through sudo - // with the session password when asked. Used by the lock recovery, which - // needs the status rather than the output. + // when asked (with the session password, or passwordless). Used by the lock + // recovery, which needs the status rather than the output. int runCommand(const std::string& command, bool withSudo) const; bool terminateProcess(int pid, const char* signal) const; bool removeLockFile() const; diff --git a/tests/app-core.test.cpp b/tests/app-core.test.cpp index b642170..857f8ad 100644 --- a/tests/app-core.test.cpp +++ b/tests/app-core.test.cpp @@ -83,6 +83,9 @@ void testBulkRemovalRefusesAnEmptySelection() { void testPrivilegedActionAsksForThePasswordFirst() { AppCore core; if (!core.hasAvailableProvider()) return; // nothing to update on this box + // A passwordless sudo setup has nothing to ask (and the request would + // really update the machine): there is no dialog to check here. + if (!core.sudoRequiresPassword()) return; // No password captured yet: the request is refused but kept pending, so the // view can prompt and replay. @@ -107,6 +110,9 @@ void testPrivilegedActionAsksForThePasswordFirst() { void testEveryPrivilegedPathAsksForThePassword() { AppCore core; if (!core.hasAvailableProvider()) return; // nothing privileged on this box + // Without a password to ask for, the gate accepts every path: nothing is + // left waiting for the view, and nothing is run to check it here. + if (!core.sudoRequiresPassword()) return; PackageInfo pkg; pkg.name = "firefox"; @@ -163,6 +169,11 @@ void testCredentialsStayInTheCore() { assert(core.hasSudoPassword()); core.clearSudoPassword(); assert(!core.hasSudoPassword()); + + // An empty password is not a secret: it means "none", which the + // passwordless-sudo path handles instead of storing an empty string. + core.setSudoPassword(QString()); + assert(!core.hasSudoPassword()); } void testCredentialModeIsPersistedAndReported() { diff --git a/tests/pacman-manager.test.cpp b/tests/pacman-manager.test.cpp index 5b1762e..f76145e 100644 --- a/tests/pacman-manager.test.cpp +++ b/tests/pacman-manager.test.cpp @@ -190,6 +190,25 @@ static void testAuthFailed_ignoresPacmanErrors() { assert(!PacmanManager::authFailed("warning: firefox is up to date")); } +// A captured password goes to `sudo -S` on stdin, quoted so it stays data. +static void testPrivilegedCommand_pipesThePassword() { + assert(PacmanManager::privilegedCommand("pacman -S firefox", "secret") + == "printf '%s\\n' 'secret' | sudo -S pacman -S firefox"); + assert(PacmanManager::privilegedCommand("true", "a'b") + == "printf '%s\\n' 'a'\\''b' | sudo -S true"); +} + +// No password is not a missing one: the command runs through `sudo -n`, which +// keeps a passwordless setup working and fails fast on a password-requiring +// one instead of waiting on a prompt nobody can answer. +static void testPrivilegedCommand_withoutPasswordUsesSudoN() { + const std::string command = + PacmanManager::privilegedCommand("pacman -S firefox", std::string()); + assert(command == "sudo -n pacman -S firefox"); + assert(command.find("sudo -S") == std::string::npos); + assert(command.find("printf") == std::string::npos); +} + // The lock dialog names the process that holds pacman's database, so the // description has to cover the three states the detection can report. static void testDescribeLockHolder() { @@ -300,6 +319,9 @@ int main() { testAuthFailed_detectsMissingPassword(); testAuthFailed_ignoresPacmanErrors(); + testPrivilegedCommand_pipesThePassword(); + testPrivilegedCommand_withoutPasswordUsesSudoN(); + testDescribeLockHolder(); testLockHolderPid_findsTheHolder();