A few quality of life improvements. Also a package for later Stormux releases.
This commit is contained in:
1 parent
2188921787
commit
bc6a403a0c
7 files changed
+1138
-89
No files matched your search
+11
@@ -0,0 +1,11 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# makepkg output in the Arch packaging directory
|
||||
/distro-packages/ArchLinux/src/
|
||||
/distro-packages/ArchLinux/pkg/
|
||||
/distro-packages/ArchLinux/sas/
|
||||
/distro-packages/ArchLinux/*.pkg.tar*
|
||||
/distro-packages/ArchLinux/*.src.tar*
|
||||
/distro-packages/ArchLinux/*.log
|
||||
@@ -0,0 +1,22 @@
|
||||
# SAS
|
||||
|
||||
SAS starts a temporary Stormux support session. It asks whether your screen reader is working, then lets you describe the problem. Press Enter on a blank line to finish the description; SAS then says "Contacting help, please wait." The description is sent privately to the assistant who accepts the request; the public `#stormux` channel only sees that someone is requesting assistance. Do not include passwords in it.
|
||||
|
||||
If your screen reader is not working, SAS speaks each character as you type. Use Left and Right Arrow to review characters, Backspace or Delete to correct them, and Control+R to hear the current line. SAS reminds you how to finish after each line.
|
||||
|
||||
Run `sas --version` to see which version is installed.
|
||||
|
||||
## Releasing
|
||||
|
||||
The version is a date, such as `2026.11.19`. Use a suffix such as `2026.11.19.1` for a second release on the same day.
|
||||
|
||||
1. Set `VERSION` near the top of `sas.py`, commit, and push to master.
|
||||
2. Build the package from `distro-packages/ArchLinux`. The PKGBUILD builds the latest master and takes its version from `VERSION`, so no tag or PKGBUILD edit is needed.
|
||||
|
||||
Always bump `VERSION` when releasing. pacman only upgrades systems when the version goes up, so a rebuild with the same `VERSION` will not reach anyone.
|
||||
|
||||
## AI-assisted contributions
|
||||
|
||||
AI-assisted contributions are welcome. The person submitting a contribution is responsible for reviewing and testing it before submission. Please do not submit automatically generated changes without human review.
|
||||
|
||||
Before making changes, read this README, confirm that you are working against the current maintained repository and branch, and check whether the issue still exists. Before submitting, review the diff, test the changed behavior and plausible regressions, and run the existing test suite where practical. Describe what changed and how it was tested. Leave submission to the contributor after they have reviewed and tested the result.
|
||||
@@ -0,0 +1,47 @@
|
||||
# Maintainer: Storm Dragon <storm_dragon@stormux.org>
|
||||
|
||||
pkgname=sas
|
||||
pkgver=2026.11.19
|
||||
pkgrel=1
|
||||
pkgdesc="Stormux Assistance Service: request remote help from a Stormux assistant"
|
||||
arch=('any')
|
||||
url="https://git.stormux.org/storm/sas"
|
||||
license=('unknown')
|
||||
depends=(
|
||||
'ii'
|
||||
'magic-wormhole'
|
||||
'openssh'
|
||||
'procps-ng'
|
||||
'python'
|
||||
'shadow'
|
||||
'speech-dispatcher'
|
||||
'sudo'
|
||||
'systemd'
|
||||
)
|
||||
makedepends=('git')
|
||||
install=sas.install
|
||||
source=("git+https://git.stormux.org/storm/sas.git#branch=master")
|
||||
sha256sums=('SKIP')
|
||||
|
||||
# The version comes from VERSION in sas.py; makepkg updates pkgver above.
|
||||
pkgver() {
|
||||
cd "${srcdir}/${pkgname}" || return 1
|
||||
local scriptVersion
|
||||
scriptVersion="$(sed -n 's/^VERSION = "\(.*\)"$/\1/p' sas.py)"
|
||||
if [[ -z "${scriptVersion}" ]]; then
|
||||
echo "Could not read VERSION from sas.py" >&2
|
||||
return 1
|
||||
fi
|
||||
echo "${scriptVersion}"
|
||||
}
|
||||
|
||||
check() {
|
||||
cd "${srcdir}/${pkgname}" || return 1
|
||||
PYTHONDONTWRITEBYTECODE=1 python -m unittest -q
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "${srcdir}/${pkgname}" || return 1
|
||||
install -Dm755 sas.py "${pkgdir}/usr/bin/sas"
|
||||
install -Dm644 README.md "${pkgdir}/usr/share/doc/${pkgname}/README.md"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
warn_about_old_copy() {
|
||||
if [ -e /usr/local/bin/sas ]; then
|
||||
echo "Warning: /usr/local/bin/sas exists. It runs instead of the packaged /usr/bin/sas,"
|
||||
echo "so package updates will not take effect. Remove it with: sudo rm /usr/local/bin/sas"
|
||||
fi
|
||||
}
|
||||
|
||||
post_install() {
|
||||
warn_about_old_copy
|
||||
}
|
||||
|
||||
post_upgrade() {
|
||||
warn_about_old_copy
|
||||
}
|
||||
@@ -1,28 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import collections
|
||||
import errno
|
||||
import fcntl
|
||||
import os
|
||||
import re
|
||||
import select
|
||||
import secrets
|
||||
import shutil
|
||||
import signal
|
||||
import string
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import threading
|
||||
import time
|
||||
import termios
|
||||
import tty
|
||||
import unicodedata
|
||||
import pwd
|
||||
|
||||
|
||||
VERSION = "2026.11.19"
|
||||
|
||||
stormuxAdmin = ("storm",)
|
||||
ircServer = "irc.stormux.org"
|
||||
ircPort = 6667
|
||||
ircChannel = "#stormux"
|
||||
remoteHost = "billysballoons.com"
|
||||
sasUser = "sas"
|
||||
sasHomeDir = f"/home/{sasUser}"
|
||||
sshdService = "sshd"
|
||||
pingIntervalSeconds = 180
|
||||
pingCount = 5
|
||||
maxWormholeFailures = 3
|
||||
wormholeCodeTimeoutSeconds = 600
|
||||
descriptionMessageDelaySeconds = 1
|
||||
tunnelPorts = range(2232, 2242)
|
||||
tunnelStartTimeoutSeconds = 60
|
||||
|
||||
sudoRefreshIntervalSeconds = 60
|
||||
sudoKeepaliveThread = None
|
||||
@@ -294,7 +310,9 @@ def find_wormhole_code(message):
|
||||
lowered = message.strip().lower()
|
||||
if lowered in ("yes", "accept"):
|
||||
return None
|
||||
match = re.search(r"\b\d+-[A-Za-z0-9-]+\b", message)
|
||||
# Wormhole codes are a channel number followed by two or more words,
|
||||
# e.g. 7-guitarist-revenge. Requiring words avoids matching "5-10".
|
||||
match = re.search(r"\b\d+(?:-[A-Za-z]+){2,}\b", message)
|
||||
if match:
|
||||
return match.group(0)
|
||||
return None
|
||||
@@ -314,7 +332,7 @@ class IrcSession:
|
||||
self.pmOffsets = {}
|
||||
|
||||
def start(self):
|
||||
if not shutil_which("ii"):
|
||||
if not shutil.which("ii"):
|
||||
raise RuntimeError("ii is not installed")
|
||||
supportsI = ii_supports_i()
|
||||
processEnv = os.environ.copy()
|
||||
@@ -333,15 +351,15 @@ class IrcSession:
|
||||
self.serverInPath = os.path.join(self.serverDir, "in")
|
||||
|
||||
def stop(self):
|
||||
if self.channelInPath and os.path.exists(self.channelInPath):
|
||||
if self.is_running() and self.channelInPath and os.path.exists(self.channelInPath):
|
||||
try:
|
||||
self.write_line(self.channelInPath, f"/part {self.channel}")
|
||||
except OSError:
|
||||
except (OSError, RuntimeError):
|
||||
pass
|
||||
if self.serverInPath and os.path.exists(self.serverInPath):
|
||||
if self.is_running() and self.serverInPath and os.path.exists(self.serverInPath):
|
||||
try:
|
||||
self.write_line(self.serverInPath, "/quit")
|
||||
except OSError:
|
||||
except (OSError, RuntimeError):
|
||||
pass
|
||||
if self.iiProcess and self.iiProcess.poll() is None:
|
||||
self.iiProcess.terminate()
|
||||
@@ -357,6 +375,7 @@ class IrcSession:
|
||||
startTime = time.monotonic()
|
||||
nextJoinTime = startTime
|
||||
while time.monotonic() - startTime < 60:
|
||||
self.ensure_running()
|
||||
if time.monotonic() >= nextJoinTime:
|
||||
self.write_line(self.serverInPath, joinMessage)
|
||||
nextJoinTime = time.monotonic() + 5
|
||||
@@ -385,6 +404,7 @@ class IrcSession:
|
||||
self.write_line(self.serverInPath, f"/msg {nick} {message}")
|
||||
|
||||
def get_private_messages(self, allowedUsers):
|
||||
self.ensure_running()
|
||||
messages = []
|
||||
for nick in allowedUsers:
|
||||
nickDir = os.path.join(self.serverDir, nick)
|
||||
@@ -417,6 +437,7 @@ class IrcSession:
|
||||
|
||||
def wait_for_server_dir(self):
|
||||
for _ in range(120):
|
||||
self.ensure_running()
|
||||
for rootDir in [self.baseDir] + list_subdirs(self.baseDir):
|
||||
if not os.path.isdir(rootDir):
|
||||
continue
|
||||
@@ -429,11 +450,33 @@ class IrcSession:
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("ii server directory not found")
|
||||
|
||||
def is_running(self):
|
||||
return self.iiProcess is not None and self.iiProcess.poll() is None
|
||||
|
||||
def ensure_running(self):
|
||||
if not self.is_running():
|
||||
raise RuntimeError("The connection to the Stormux chat server was lost")
|
||||
|
||||
@staticmethod
|
||||
def write_line(path, message):
|
||||
with open(path, "w", encoding="utf-8", errors="ignore") as fileHandle:
|
||||
fileHandle.write(message + "\n")
|
||||
fileHandle.flush()
|
||||
# Opening a FIFO for writing blocks until a reader exists. If ii has
|
||||
# exited, a blocking open would hang forever, so open non-blocking
|
||||
# (fails with ENXIO when nothing is reading) and then switch back to
|
||||
# blocking writes.
|
||||
try:
|
||||
fd = os.open(path, os.O_WRONLY | os.O_NONBLOCK)
|
||||
except OSError as exc:
|
||||
if exc.errno == errno.ENXIO:
|
||||
raise RuntimeError(
|
||||
"The connection to the Stormux chat server was lost"
|
||||
) from exc
|
||||
raise
|
||||
try:
|
||||
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
|
||||
fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
|
||||
os.write(fd, (message + "\n").encode("utf-8", errors="ignore"))
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def ii_supports_i():
|
||||
@@ -449,23 +492,332 @@ def list_subdirs(path):
|
||||
return []
|
||||
|
||||
|
||||
def shutil_which(command):
|
||||
for path in os.environ.get("PATH", "").split(os.pathsep):
|
||||
candidate = os.path.join(path, command)
|
||||
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def build_nick():
|
||||
baseUser = os.environ.get("SUDO_USER") or os.environ.get("USER") or "sas"
|
||||
return f"{baseUser}-{int(time.time())}"
|
||||
|
||||
|
||||
def describe_character(character):
|
||||
if character == " ":
|
||||
return "space"
|
||||
if character.isupper():
|
||||
return f"cap {character}"
|
||||
if character.isalnum():
|
||||
return character
|
||||
return unicodedata.name(character, character).lower()
|
||||
|
||||
|
||||
def read_terminal_key(fd):
|
||||
firstByte = os.read(fd, 1)
|
||||
if not firstByte:
|
||||
return "eof", None
|
||||
if firstByte == b"\x1b":
|
||||
sequence = b""
|
||||
while len(sequence) < 6 and select.select([fd], [], [], 0.05)[0]:
|
||||
sequence += os.read(fd, 1)
|
||||
if len(sequence) > 1 and 64 <= sequence[-1] <= 126:
|
||||
break
|
||||
return {
|
||||
b"[D": ("left", None),
|
||||
b"[C": ("right", None),
|
||||
b"OD": ("left", None),
|
||||
b"OC": ("right", None),
|
||||
b"[H": ("home", None),
|
||||
b"[F": ("end", None),
|
||||
b"[1~": ("home", None),
|
||||
b"[4~": ("end", None),
|
||||
b"OH": ("home", None),
|
||||
b"OF": ("end", None),
|
||||
b"[3~": ("delete", None),
|
||||
}.get(sequence, ("unknown", None))
|
||||
if firstByte in (b"\n", b"\r"):
|
||||
return "enter", None
|
||||
if firstByte in (b"\x7f", b"\x08"):
|
||||
return "backspace", None
|
||||
if firstByte == b"\x12":
|
||||
return "read_line", None
|
||||
if firstByte == b"\x01":
|
||||
return "home", None
|
||||
if firstByte == b"\x05":
|
||||
return "end", None
|
||||
if firstByte == b"\x04":
|
||||
return "delete", None
|
||||
if firstByte == b"\x03":
|
||||
raise KeyboardInterrupt
|
||||
if firstByte[0] < 32:
|
||||
return "unknown", None
|
||||
characterBytes = firstByte
|
||||
while len(characterBytes) < 4:
|
||||
try:
|
||||
return "character", characterBytes.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
if exc.reason != "unexpected end of data":
|
||||
break
|
||||
characterBytes += os.read(fd, 1)
|
||||
return "character", characterBytes.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def edit_spoken_line(readKey, announce, render):
|
||||
characters = []
|
||||
cursor = 0
|
||||
while True:
|
||||
key, value = readKey()
|
||||
if key == "enter":
|
||||
return "".join(characters)
|
||||
if key == "eof":
|
||||
raise EOFError
|
||||
if key == "character":
|
||||
characters.insert(cursor, value)
|
||||
cursor += 1
|
||||
announce(describe_character(value))
|
||||
elif key == "backspace":
|
||||
if cursor:
|
||||
cursor -= 1
|
||||
announce("Deleted " + describe_character(characters.pop(cursor)))
|
||||
else:
|
||||
announce("Start of line")
|
||||
elif key == "delete":
|
||||
if cursor < len(characters):
|
||||
announce("Deleted " + describe_character(characters.pop(cursor)))
|
||||
else:
|
||||
announce("End of line")
|
||||
elif key == "left":
|
||||
if cursor:
|
||||
cursor -= 1
|
||||
announce(describe_character(characters[cursor]))
|
||||
else:
|
||||
announce("Start of line")
|
||||
elif key == "right":
|
||||
cursor = min(len(characters), cursor + 1)
|
||||
announce(describe_character(characters[cursor]) if cursor < len(characters) else "End of line")
|
||||
elif key == "home":
|
||||
cursor = 0
|
||||
announce(describe_character(characters[0]) if characters else "Empty line")
|
||||
elif key == "end":
|
||||
cursor = len(characters)
|
||||
announce("End of line")
|
||||
elif key == "read_line":
|
||||
announce("".join(characters) or "Empty line")
|
||||
else:
|
||||
continue
|
||||
render(characters, cursor)
|
||||
|
||||
|
||||
def read_spoken_line():
|
||||
if not sys.stdin.isatty():
|
||||
return input()
|
||||
fd = sys.stdin.fileno()
|
||||
originalSettings = termios.tcgetattr(fd)
|
||||
|
||||
def render(characters, cursor):
|
||||
sys.stdout.write("\r\x1b[2K" + "".join(characters))
|
||||
if cursor < len(characters):
|
||||
sys.stdout.write(f"\x1b[{len(characters) - cursor}D")
|
||||
sys.stdout.flush()
|
||||
|
||||
try:
|
||||
tty.setcbreak(fd, when=termios.TCSANOW)
|
||||
return edit_spoken_line(
|
||||
lambda: read_terminal_key(fd), speak_message, render
|
||||
)
|
||||
finally:
|
||||
termios.tcsetattr(fd, termios.TCSADRAIN, originalSettings)
|
||||
sys.stdout.write("\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def announce_description(message, useSpeech):
|
||||
if useSpeech:
|
||||
speak_message(
|
||||
message,
|
||||
wait=True,
|
||||
applicationName="sas",
|
||||
connectionName="problem-description",
|
||||
)
|
||||
else:
|
||||
print(message, flush=True)
|
||||
|
||||
|
||||
def read_problem_description(useSpeech):
|
||||
prompt = (
|
||||
"Please describe your problem. Your description will be sent to the "
|
||||
"Stormux assistant who accepts your request."
|
||||
)
|
||||
if useSpeech:
|
||||
prompt += (
|
||||
" Left and Right Arrow review characters. Backspace deletes. "
|
||||
"Control R reads the current line."
|
||||
)
|
||||
prompt += " Press Enter on a blank line to end the description."
|
||||
announce_description(prompt, useSpeech)
|
||||
descriptionLines = []
|
||||
while True:
|
||||
line = (read_spoken_line() if useSpeech else input()).strip()
|
||||
if not line:
|
||||
announce_description("Contacting help, please wait.", useSpeech)
|
||||
return descriptionLines
|
||||
descriptionLines.append(line)
|
||||
announce_description(
|
||||
"Line added. Type another line, or press Enter on a blank line to finish.",
|
||||
useSpeech,
|
||||
)
|
||||
|
||||
|
||||
def wait_for_wormhole_code(ircSession, timeoutSeconds):
|
||||
deadline = time.monotonic() + timeoutSeconds
|
||||
while time.monotonic() < deadline:
|
||||
for _adminNick, messageText in ircSession.get_private_messages(stormuxAdmin):
|
||||
inviteCode = find_wormhole_code(messageText)
|
||||
if inviteCode:
|
||||
return inviteCode
|
||||
time.sleep(1)
|
||||
return None
|
||||
|
||||
|
||||
def wait_for_session_end(sshProcess, ircSession, adminNick):
|
||||
"""Wait until the tunnel exits or the admin sends "end" by private message.
|
||||
|
||||
Returns "admin" when the admin ended the session (the tunnel is stopped
|
||||
here), or "tunnel" when the ssh process exited on its own. Losing the IRC
|
||||
connection only stops listening for "end"; it never ends the session.
|
||||
"""
|
||||
listening = True
|
||||
while sshProcess.poll() is None:
|
||||
if listening:
|
||||
try:
|
||||
messages = ircSession.get_private_messages((adminNick,))
|
||||
except (OSError, RuntimeError):
|
||||
listening = False
|
||||
messages = []
|
||||
for _nick, messageText in messages:
|
||||
if messageText.strip().lower() == "end":
|
||||
stop_process(sshProcess)
|
||||
return "admin"
|
||||
time.sleep(1)
|
||||
return "tunnel"
|
||||
|
||||
|
||||
def stop_process(process):
|
||||
if process.poll() is not None:
|
||||
return
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
|
||||
|
||||
def build_tunnel_command(port, knownHostsPath, privateKeyPath):
|
||||
return [
|
||||
"ssh",
|
||||
"-v",
|
||||
"-N",
|
||||
"-R",
|
||||
f"localhost:{port}:localhost:22",
|
||||
"-o",
|
||||
"ExitOnForwardFailure=yes",
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"ServerAliveInterval=30",
|
||||
"-o",
|
||||
"ServerAliveCountMax=3",
|
||||
"-o",
|
||||
"StrictHostKeyChecking=accept-new",
|
||||
"-o",
|
||||
f"UserKnownHostsFile={knownHostsPath}",
|
||||
"-i",
|
||||
privateKeyPath,
|
||||
f"{sasUser}@{remoteHost}",
|
||||
]
|
||||
|
||||
|
||||
class TunnelMonitor:
|
||||
"""Reads ssh -v output to learn whether the remote forward was set up.
|
||||
|
||||
ssh's stderr must be drained for the life of the tunnel, so a daemon
|
||||
thread keeps reading it. Debug lines are only scanned for the forward
|
||||
result; a few recent non-debug lines are kept for error reports.
|
||||
"""
|
||||
|
||||
chatterPrefixes = ("OpenSSH_", "Authenticated to", "Transferred:", "Bytes per second")
|
||||
|
||||
def __init__(self, process):
|
||||
self.process = process
|
||||
self.forwardReady = threading.Event()
|
||||
self.forwardFailed = threading.Event()
|
||||
self.errorLines = collections.deque(maxlen=5)
|
||||
self.readerThread = threading.Thread(target=self.read_output, daemon=True)
|
||||
self.readerThread.start()
|
||||
|
||||
def read_output(self):
|
||||
for line in self.process.stderr:
|
||||
self.handle_line(line.rstrip("\n"))
|
||||
|
||||
def handle_line(self, line):
|
||||
if "remote forward success" in line:
|
||||
self.forwardReady.set()
|
||||
elif "remote forward failure" in line or "remote port forwarding failed" in line:
|
||||
self.forwardFailed.set()
|
||||
if line and not line.startswith("debug") and not line.startswith(self.chatterPrefixes):
|
||||
self.errorLines.append(line.strip())
|
||||
|
||||
def wait_for_forward(self, timeoutSeconds):
|
||||
deadline = time.monotonic() + timeoutSeconds
|
||||
while time.monotonic() < deadline:
|
||||
if self.forwardReady.is_set():
|
||||
return "ready"
|
||||
if self.forwardFailed.is_set():
|
||||
return "port_in_use"
|
||||
if self.process.poll() is not None:
|
||||
self.readerThread.join(timeout=2)
|
||||
if self.forwardFailed.is_set():
|
||||
return "port_in_use"
|
||||
return "exited"
|
||||
time.sleep(0.2)
|
||||
# No confirmation seen but ssh is still running; assume the forward
|
||||
# works rather than tearing down a possibly good tunnel.
|
||||
return "unconfirmed"
|
||||
|
||||
def error_text(self):
|
||||
return " ".join(self.errorLines)
|
||||
|
||||
|
||||
def start_tunnel(commandPrefix, knownHostsPath, privateKeyPath):
|
||||
"""Start the reverse tunnel, trying the next port if one is in use.
|
||||
|
||||
Returns (process, monitor, port). The process may already have exited
|
||||
for reasons other than a busy port; the caller reports that.
|
||||
"""
|
||||
for port in tunnelPorts:
|
||||
process = subprocess.Popen(
|
||||
commandPrefix + build_tunnel_command(port, knownHostsPath, privateKeyPath),
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
errors="replace",
|
||||
)
|
||||
monitor = TunnelMonitor(process)
|
||||
if monitor.wait_for_forward(tunnelStartTimeoutSeconds) == "port_in_use":
|
||||
stop_process(process)
|
||||
continue
|
||||
return process, monitor, port
|
||||
raise RuntimeError("Could not open a tunnel port on the support server")
|
||||
|
||||
|
||||
def send_problem_description(sendMessage, descriptionLines):
|
||||
# Pause after each message so a long description does not trip the IRC
|
||||
# server's flood protection.
|
||||
for line in descriptionLines:
|
||||
for part in textwrap.wrap(line, width=150, break_on_hyphens=False):
|
||||
sendMessage(part)
|
||||
time.sleep(descriptionMessageDelaySeconds)
|
||||
|
||||
|
||||
def main():
|
||||
say_or_print("Checking accessibility. Is your screen reader working? (y/n)", True)
|
||||
answer = input().strip().lower()
|
||||
useSpeech = answer in ("n", "no")
|
||||
descriptionLines = read_problem_description(useSpeech)
|
||||
|
||||
if useSpeech and not prepare_sudo_session(useSpeech=True):
|
||||
failureMessage = (
|
||||
@@ -481,11 +833,12 @@ def main():
|
||||
tempDir = tempfile.mkdtemp(prefix="sas-ii-")
|
||||
ircSession = None
|
||||
sshProcess = None
|
||||
confirmedAdmin = None
|
||||
sshdWasActiveAtStart = service_is_active(sshdService)
|
||||
shouldStopSshdOnCleanup = False
|
||||
|
||||
def cleanup(exitMessage=None):
|
||||
nonlocal cleanupDone, sshProcess
|
||||
nonlocal cleanupDone
|
||||
if cleanupDone:
|
||||
return
|
||||
cleanupDone = True
|
||||
@@ -521,7 +874,7 @@ def main():
|
||||
run_privileged(["pkill", "-u", sasUser], useSpeech, check=False)
|
||||
time.sleep(1)
|
||||
result = run_privileged(["userdel", "-r", sasUser], useSpeech, check=False)
|
||||
run_privileged(["rm", "-rf", f"/home/{sasUser}"], useSpeech, check=False)
|
||||
run_privileged(["rm", "-rf", sasHomeDir], useSpeech, check=False)
|
||||
if result.returncode != 0 and user_exists(sasUser):
|
||||
say_or_print(
|
||||
"Cleanup warning: failed to remove sas user. Please remove it manually.",
|
||||
@@ -537,12 +890,19 @@ def main():
|
||||
if sudoKeepaliveThread:
|
||||
sudoKeepaliveThread.join(timeout=2)
|
||||
|
||||
shutil.rmtree(tempDir, ignore_errors=True)
|
||||
|
||||
def notify_admin(message):
|
||||
# Best effort: never let a failed chat message stop cleanup.
|
||||
if not confirmedAdmin or not ircSession or not ircSession.is_running():
|
||||
return
|
||||
try:
|
||||
remove_tree(tempDir)
|
||||
except Exception:
|
||||
ircSession.send_private_message(confirmedAdmin, message)
|
||||
except (OSError, RuntimeError):
|
||||
pass
|
||||
|
||||
def handle_signal(signum, frame):
|
||||
notify_admin("The user interrupted the support session. Cleaning up.")
|
||||
cleanup("Interrupted. Cleaning up.")
|
||||
sys.exit(1)
|
||||
|
||||
@@ -566,13 +926,13 @@ def main():
|
||||
|
||||
if not user_exists(sasUser):
|
||||
run_privileged(
|
||||
["useradd", "-m", "-d", f"/home/{sasUser}", "-s", "/bin/bash", "-G", "wheel", sasUser],
|
||||
["useradd", "-m", "-d", sasHomeDir, "-s", "/bin/bash", "-G", "wheel", sasUser],
|
||||
useSpeech,
|
||||
)
|
||||
shouldRemoveUser = True
|
||||
else:
|
||||
say_or_print(
|
||||
"User 'sas' exists. Remove and recreate it? This will delete /home/sas. (y/n)",
|
||||
f"User '{sasUser}' exists. Remove and recreate it? This will delete {sasHomeDir}. (y/n)",
|
||||
useSpeech,
|
||||
)
|
||||
response = input().strip().lower()
|
||||
@@ -581,9 +941,9 @@ def main():
|
||||
return 1
|
||||
run_privileged(["pkill", "-u", sasUser], useSpeech, check=False)
|
||||
run_privileged(["userdel", "-r", sasUser], useSpeech, check=False)
|
||||
run_privileged(["rm", "-rf", f"/home/{sasUser}"], useSpeech, check=False)
|
||||
run_privileged(["rm", "-rf", sasHomeDir], useSpeech, check=False)
|
||||
run_privileged(
|
||||
["useradd", "-m", "-d", f"/home/{sasUser}", "-s", "/bin/bash", "-G", "wheel", sasUser],
|
||||
["useradd", "-m", "-d", sasHomeDir, "-s", "/bin/bash", "-G", "wheel", sasUser],
|
||||
useSpeech,
|
||||
)
|
||||
shouldRemoveUser = True
|
||||
@@ -609,7 +969,6 @@ def main():
|
||||
startTime = time.monotonic()
|
||||
nextPingTime = startTime
|
||||
pingsSent = 0
|
||||
confirmedAdmin = None
|
||||
|
||||
while time.monotonic() - startTime < pingIntervalSeconds * pingCount:
|
||||
now = time.monotonic()
|
||||
@@ -635,24 +994,29 @@ def main():
|
||||
useSpeech,
|
||||
)
|
||||
|
||||
send_problem_description(
|
||||
lambda message: ircSession.send_private_message(confirmedAdmin, message),
|
||||
descriptionLines,
|
||||
)
|
||||
ircSession.send_private_message(
|
||||
confirmedAdmin,
|
||||
f'password: "{password}" please send wormhole ssh invite code',
|
||||
"Please send wormhole ssh invite code.",
|
||||
)
|
||||
|
||||
say_or_print("Exchanging secure connection information. This may take a moment.", useSpeech)
|
||||
|
||||
failures = 0
|
||||
while failures < maxWormholeFailures:
|
||||
inviteCode = None
|
||||
while inviteCode is None:
|
||||
for adminNick, messageText in ircSession.get_private_messages(stormuxAdmin):
|
||||
inviteCode = find_wormhole_code(messageText)
|
||||
if inviteCode:
|
||||
break
|
||||
if inviteCode:
|
||||
break
|
||||
time.sleep(1)
|
||||
inviteCode = wait_for_wormhole_code(ircSession, wormholeCodeTimeoutSeconds)
|
||||
if inviteCode is None:
|
||||
notify_admin(
|
||||
"No wormhole invite code was received in time. The support session has ended."
|
||||
)
|
||||
cleanup(
|
||||
"No connection code was received from the assistant. "
|
||||
"The support session has ended. Please try again later."
|
||||
)
|
||||
return 1
|
||||
|
||||
if not path_exists_for_user(publicKeyPath, sasUser, useSpeech):
|
||||
raise RuntimeError(f"Public key missing: {publicKeyPath}")
|
||||
@@ -675,58 +1039,54 @@ def main():
|
||||
)
|
||||
|
||||
failures += 1
|
||||
errorTextFull = (result.stderr or result.stdout or "").strip()
|
||||
if errorTextFull and not useSpeech:
|
||||
errorTextFull = command_error_text(result)
|
||||
if errorTextFull:
|
||||
if not useSpeech:
|
||||
print("Wormhole ssh accept error:", flush=True)
|
||||
print(errorTextFull, flush=True)
|
||||
errorText = errorTextFull
|
||||
if errorText:
|
||||
errorText = " ".join(errorText.split())
|
||||
if len(errorText) > 400:
|
||||
errorText = errorText[:400] + "..."
|
||||
ircSession.send_private_message(
|
||||
confirmedAdmin,
|
||||
f"Wormhole ssh accept failed: {errorText}",
|
||||
f"Wormhole ssh accept failed: {concise_command_error(result)}",
|
||||
)
|
||||
if failures < maxWormholeFailures:
|
||||
ircSession.send_private_message(
|
||||
confirmedAdmin,
|
||||
"Wormhole ssh accept failed. Please send a new invite code.",
|
||||
)
|
||||
|
||||
if failures >= maxWormholeFailures:
|
||||
notify_admin("Wormhole failed too many times. The support session has ended.")
|
||||
cleanup("Wormhole failed too many times. Exiting.")
|
||||
return 1
|
||||
|
||||
ensure_sshd_active()
|
||||
|
||||
say_or_print("Starting reverse SSH tunnel. Press Ctrl+C to stop.", useSpeech)
|
||||
sshCommand = [
|
||||
"ssh",
|
||||
"-N",
|
||||
"-R",
|
||||
"localhost:2232:localhost:22",
|
||||
"-o",
|
||||
"ExitOnForwardFailure=yes",
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"ServerAliveInterval=30",
|
||||
"-o",
|
||||
"ServerAliveCountMax=3",
|
||||
"-o",
|
||||
"StrictHostKeyChecking=accept-new",
|
||||
"-o",
|
||||
f"UserKnownHostsFile={knownHostsPath}",
|
||||
"-i",
|
||||
privateKeyPath,
|
||||
f"{sasUser}@{remoteHost}",
|
||||
]
|
||||
sshCommand = sudo_command_prefix() + ["-u", sasUser, "-H"] + sshCommand
|
||||
sshProcess = subprocess.Popen(sshCommand)
|
||||
sshProcess.wait()
|
||||
commandPrefix = sudo_command_prefix() + ["-u", sasUser, "-H"]
|
||||
sshProcess, tunnelMonitor, tunnelPort = start_tunnel(
|
||||
commandPrefix, knownHostsPath, privateKeyPath
|
||||
)
|
||||
if sshProcess.poll() is None:
|
||||
notify_admin(
|
||||
f'Tunnel ready. password: "{password}" port {tunnelPort}. '
|
||||
"Send end to close the support session."
|
||||
)
|
||||
endReason = wait_for_session_end(sshProcess, ircSession, confirmedAdmin)
|
||||
if endReason == "admin":
|
||||
notify_admin("Ending the support session and cleaning up.")
|
||||
say_or_print("The assistant ended the support session. Cleaning up.", useSpeech)
|
||||
else:
|
||||
tunnelErrors = tunnelMonitor.error_text()
|
||||
if tunnelErrors and not useSpeech:
|
||||
print(f"SSH tunnel messages: {tunnelErrors}", flush=True)
|
||||
adminMessage = "The tunnel closed. The support session has ended."
|
||||
if tunnelErrors:
|
||||
adminMessage += f" SSH said: {tunnelErrors}"
|
||||
notify_admin(adminMessage)
|
||||
say_or_print("The support connection ended. Cleaning up.", useSpeech)
|
||||
|
||||
except Exception as exc:
|
||||
notify_admin(f"The support session failed: {exc}")
|
||||
cleanup(f"Error: {exc}")
|
||||
return 1
|
||||
finally:
|
||||
@@ -735,32 +1095,27 @@ def main():
|
||||
return 0
|
||||
|
||||
|
||||
def remove_tree(path):
|
||||
if not os.path.exists(path):
|
||||
return
|
||||
for rootDir, dirNames, fileNames in os.walk(path, topdown=False):
|
||||
for fileName in fileNames:
|
||||
try:
|
||||
os.unlink(os.path.join(rootDir, fileName))
|
||||
except OSError:
|
||||
pass
|
||||
for dirName in dirNames:
|
||||
try:
|
||||
os.rmdir(os.path.join(rootDir, dirName))
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.rmdir(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def command_line_main(arguments=None):
|
||||
arguments = sys.argv[1:] if arguments is None else arguments
|
||||
if arguments in (["-v"], ["--version"]):
|
||||
print(f"sas {VERSION}")
|
||||
return 0
|
||||
if arguments:
|
||||
print("Usage: sas", file=sys.stderr)
|
||||
print("Usage: sas [-v | --version]", file=sys.stderr)
|
||||
return 2
|
||||
# Signal handlers that clean up are installed only once setup begins.
|
||||
# Before that nothing needs undoing, so just announce the cancellation
|
||||
# instead of showing a traceback.
|
||||
try:
|
||||
return main()
|
||||
except KeyboardInterrupt:
|
||||
print(flush=True)
|
||||
speak_message("Cancelled. No support session was started.")
|
||||
return 130
|
||||
except EOFError:
|
||||
print(flush=True)
|
||||
speak_message("Input ended. No support session was started.")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import io
|
||||
import os
|
||||
import pty
|
||||
import termios
|
||||
import tty
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import sas
|
||||
|
||||
|
||||
class ProblemDescriptionTests(unittest.TestCase):
|
||||
@mock.patch("sas.announce_description")
|
||||
@mock.patch("sas.read_spoken_line", side_effect=["The keyboard stops responding", "after login", "", "unused"])
|
||||
def test_blank_line_ends_multiline_description(self, readLine, announce):
|
||||
descriptionLines = sas.read_problem_description(useSpeech=True)
|
||||
|
||||
self.assertEqual(descriptionLines, ["The keyboard stops responding", "after login"])
|
||||
self.assertEqual(readLine.call_count, 3)
|
||||
self.assertIn("Press Enter on a blank line", announce.call_args_list[0].args[0])
|
||||
self.assertEqual(announce.call_args.args, ("Contacting help, please wait.", True))
|
||||
self.assertEqual(announce.call_count, 4)
|
||||
|
||||
def test_working_screen_reader_uses_normal_line_input(self):
|
||||
with mock.patch("builtins.input", side_effect=["A problem", ""]), mock.patch(
|
||||
"sas.announce_description"
|
||||
) as announce:
|
||||
descriptionLines = sas.read_problem_description(useSpeech=False)
|
||||
|
||||
self.assertEqual(descriptionLines, ["A problem"])
|
||||
self.assertEqual(announce.call_args.args, ("Contacting help, please wait.", False))
|
||||
self.assertEqual(announce.call_count, 3)
|
||||
|
||||
@mock.patch("sas.speak_message")
|
||||
def test_spoken_instructions_wait_until_finished(self, speakMessage):
|
||||
sas.announce_description("Press Enter on a blank line to finish.", True)
|
||||
|
||||
speakMessage.assert_called_once_with(
|
||||
"Press Enter on a blank line to finish.",
|
||||
wait=True,
|
||||
applicationName="sas",
|
||||
connectionName="problem-description",
|
||||
)
|
||||
|
||||
def test_spoken_editor_can_review_correct_and_read_a_line(self):
|
||||
keys = iter([
|
||||
("character", "a"),
|
||||
("character", "b"),
|
||||
("left", None),
|
||||
("read_line", None),
|
||||
("backspace", None),
|
||||
("character", "x"),
|
||||
("right", None),
|
||||
("enter", None),
|
||||
])
|
||||
announce = mock.Mock()
|
||||
render = mock.Mock()
|
||||
|
||||
line = sas.edit_spoken_line(lambda: next(keys), announce, render)
|
||||
|
||||
self.assertEqual(line, "xb")
|
||||
self.assertEqual(
|
||||
[call.args[0] for call in announce.call_args_list],
|
||||
["a", "b", "b", "ab", "Deleted a", "x", "End of line"],
|
||||
)
|
||||
self.assertEqual(render.call_args.args, (["x", "b"], 2))
|
||||
|
||||
def test_terminal_keys_and_terminal_settings(self):
|
||||
masterFd, slaveFd = pty.openpty()
|
||||
originalSettings = termios.tcgetattr(slaveFd)
|
||||
try:
|
||||
tty.setcbreak(slaveFd)
|
||||
os.write(masterFd, b"\x1b[D\x1bOC\x7f\xc3\xa9\x12\r")
|
||||
self.assertEqual(sas.read_terminal_key(slaveFd), ("left", None))
|
||||
self.assertEqual(sas.read_terminal_key(slaveFd), ("right", None))
|
||||
self.assertEqual(sas.read_terminal_key(slaveFd), ("backspace", None))
|
||||
self.assertEqual(sas.read_terminal_key(slaveFd), ("character", "é"))
|
||||
self.assertEqual(sas.read_terminal_key(slaveFd), ("read_line", None))
|
||||
self.assertEqual(sas.read_terminal_key(slaveFd), ("enter", None))
|
||||
finally:
|
||||
termios.tcsetattr(slaveFd, termios.TCSADRAIN, originalSettings)
|
||||
os.close(masterFd)
|
||||
os.close(slaveFd)
|
||||
|
||||
def test_spoken_line_edits_keys_and_restores_terminal_settings(self):
|
||||
masterFd, slaveFd = pty.openpty()
|
||||
originalSettings = termios.tcgetattr(slaveFd)
|
||||
fakeStdin = mock.Mock()
|
||||
fakeStdin.isatty.return_value = True
|
||||
fakeStdin.fileno.return_value = slaveFd
|
||||
setCbreak = tty.setcbreak
|
||||
|
||||
def startInput(fd, when):
|
||||
setCbreak(fd, when=when)
|
||||
os.write(masterFd, b"ab\x1b[D\x7fx\r")
|
||||
|
||||
try:
|
||||
with mock.patch("sas.sys.stdin", fakeStdin), mock.patch(
|
||||
"sas.sys.stdout", io.StringIO()
|
||||
), mock.patch("sas.tty.setcbreak", side_effect=startInput), mock.patch(
|
||||
"sas.speak_message"
|
||||
) as speakMessage:
|
||||
line = sas.read_spoken_line()
|
||||
self.assertEqual(line, "xb")
|
||||
self.assertEqual(
|
||||
[call.args[0] for call in speakMessage.call_args_list],
|
||||
["a", "b", "b", "Deleted a", "x"],
|
||||
)
|
||||
self.assertEqual(termios.tcgetattr(slaveFd), originalSettings)
|
||||
finally:
|
||||
os.close(masterFd)
|
||||
os.close(slaveFd)
|
||||
|
||||
@mock.patch("sas.time.sleep")
|
||||
def test_description_splits_at_words_within_150_characters(self, sleep):
|
||||
sendMessage = mock.Mock()
|
||||
longLine = " ".join(["keyboard"] * 30)
|
||||
|
||||
sas.send_problem_description(sendMessage, [longLine])
|
||||
|
||||
messages = [call.args[0] for call in sendMessage.call_args_list]
|
||||
self.assertGreater(len(messages), 1)
|
||||
self.assertTrue(all(len(message) <= 150 for message in messages))
|
||||
self.assertEqual(" ".join(messages), longLine)
|
||||
self.assertEqual(sleep.call_count, len(messages))
|
||||
|
||||
@mock.patch("sas.time.sleep")
|
||||
def test_long_unbroken_word_is_split_to_fit(self, _sleep):
|
||||
sendMessage = mock.Mock()
|
||||
|
||||
sas.send_problem_description(sendMessage, ["x" * 300])
|
||||
|
||||
messages = [call.args[0] for call in sendMessage.call_args_list]
|
||||
self.assertTrue(all(len(message) <= 150 for message in messages))
|
||||
self.assertEqual("".join(messages), "x" * 300)
|
||||
|
||||
@mock.patch("sas.time.sleep")
|
||||
def test_description_lines_are_sent_without_prefix(self, _sleep):
|
||||
sendMessage = mock.Mock()
|
||||
|
||||
sas.send_problem_description(sendMessage, ["Sound stopped", "after update"])
|
||||
|
||||
self.assertEqual(
|
||||
[call.args[0] for call in sendMessage.call_args_list],
|
||||
["Sound stopped", "after update"],
|
||||
)
|
||||
|
||||
def test_empty_description_sends_no_messages(self):
|
||||
sendMessage = mock.Mock()
|
||||
|
||||
sas.send_problem_description(sendMessage, [])
|
||||
|
||||
sendMessage.assert_not_called()
|
||||
|
||||
def test_capital_letters_are_announced(self):
|
||||
self.assertEqual(sas.describe_character("A"), "cap A")
|
||||
self.assertEqual(sas.describe_character("a"), "a")
|
||||
self.assertEqual(sas.describe_character("7"), "7")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import sas
|
||||
|
||||
|
||||
class PrivilegeWorkflowTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
sas.sudoSessionPrepared = False
|
||||
sas.sudoAuthenticationError = ""
|
||||
|
||||
def tearDown(self):
|
||||
sas.sudoSessionPrepared = False
|
||||
sas.sudoAuthenticationError = ""
|
||||
|
||||
@mock.patch("sas.speak_message")
|
||||
@mock.patch("sas.start_sudo_keepalive")
|
||||
@mock.patch("sas.run_terminal_sudo_authentication")
|
||||
@mock.patch("sas.os.geteuid", return_value=1000)
|
||||
def test_cached_sudo_never_announces_a_password_prompt(
|
||||
self,
|
||||
_getEuid,
|
||||
runAuthentication,
|
||||
startKeepalive,
|
||||
speakMessage,
|
||||
):
|
||||
runAuthentication.return_value.returncode = 0
|
||||
|
||||
result = sas.ensure_sudo(useSpeech=True)
|
||||
|
||||
self.assertTrue(result)
|
||||
runAuthentication.assert_called_once_with()
|
||||
speakMessage.assert_not_called()
|
||||
startKeepalive.assert_called_once_with()
|
||||
|
||||
@mock.patch("sas.speak_message")
|
||||
@mock.patch("sas.ensure_sudo", return_value=True)
|
||||
@mock.patch("sas.run_command")
|
||||
@mock.patch("sas.os.geteuid", return_value=1000)
|
||||
def test_late_privileged_command_does_not_announce_directly(
|
||||
self, _getEuid, runCommand, _ensureSudo, speakMessage
|
||||
):
|
||||
sas.sudoSessionPrepared = True
|
||||
runCommand.return_value.returncode = 0
|
||||
|
||||
sas.run_privileged(["userdel", "sas"], useSpeech=True, check=False)
|
||||
|
||||
speakMessage.assert_not_called()
|
||||
runCommand.assert_called_once_with(
|
||||
["sudo", "-n", "userdel", "sas"], inputText=None, check=False
|
||||
)
|
||||
|
||||
@mock.patch("sas.authenticate_sudo", return_value=True)
|
||||
@mock.patch("sas.run_command")
|
||||
@mock.patch("sas.os.geteuid", return_value=1000)
|
||||
def test_speech_session_forces_one_upfront_authentication(
|
||||
self, _getEuid, runCommand, authenticateSudo
|
||||
):
|
||||
invalidateResult = mock.Mock(returncode=0, stdout="", stderr="")
|
||||
probeResult = mock.Mock(
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="sudo: a password is required\n",
|
||||
)
|
||||
runCommand.side_effect = [invalidateResult, probeResult]
|
||||
|
||||
result = sas.prepare_sudo_session(useSpeech=True)
|
||||
|
||||
self.assertTrue(result)
|
||||
self.assertEqual(runCommand.call_args_list[0], mock.call(["sudo", "-k"]))
|
||||
self.assertEqual(runCommand.call_args_list[1].args[0], ["sudo", "-n", "-v"])
|
||||
authenticateSudo.assert_called_once_with(useSpeech=True)
|
||||
self.assertTrue(sas.sudoSessionPrepared)
|
||||
|
||||
@mock.patch("sas.authenticate_sudo")
|
||||
@mock.patch("sas.start_sudo_keepalive")
|
||||
@mock.patch("sas.run_command")
|
||||
@mock.patch("sas.os.geteuid", return_value=1000)
|
||||
def test_password_warning_is_skipped_when_sudo_needs_no_password(
|
||||
self, _getEuid, runCommand, startKeepalive, authenticateSudo
|
||||
):
|
||||
runCommand.side_effect = [
|
||||
mock.Mock(returncode=0, stdout="", stderr=""),
|
||||
mock.Mock(returncode=0, stdout="", stderr=""),
|
||||
]
|
||||
|
||||
result = sas.prepare_sudo_session(useSpeech=True)
|
||||
|
||||
self.assertTrue(result)
|
||||
authenticateSudo.assert_not_called()
|
||||
startKeepalive.assert_called_once_with()
|
||||
self.assertTrue(sas.sudoSessionPrepared)
|
||||
|
||||
@mock.patch("sas.authenticate_sudo")
|
||||
@mock.patch("sas.run_command")
|
||||
@mock.patch("sas.os.geteuid", return_value=1000)
|
||||
def test_unexpected_sudo_error_never_requests_a_password(
|
||||
self, _getEuid, runCommand, authenticateSudo
|
||||
):
|
||||
runCommand.side_effect = [
|
||||
mock.Mock(returncode=0, stdout="", stderr=""),
|
||||
mock.Mock(returncode=1, stdout="", stderr="sudo: policy plugin failed\n"),
|
||||
]
|
||||
|
||||
result = sas.prepare_sudo_session(useSpeech=True)
|
||||
|
||||
self.assertFalse(result)
|
||||
authenticateSudo.assert_not_called()
|
||||
self.assertEqual(sas.sudoAuthenticationError, "sudo: policy plugin failed")
|
||||
|
||||
@mock.patch("sas.start_sudo_keepalive")
|
||||
@mock.patch("sas.run_command")
|
||||
@mock.patch("sas.os.geteuid", return_value=1000)
|
||||
def test_prepared_session_never_prompts_again(
|
||||
self, _getEuid, runCommand, startKeepalive
|
||||
):
|
||||
sas.sudoSessionPrepared = True
|
||||
runCommand.return_value.returncode = 0
|
||||
|
||||
result = sas.ensure_sudo(useSpeech=True)
|
||||
|
||||
self.assertTrue(result)
|
||||
runCommand.assert_called_once_with(["sudo", "-n", "-v"])
|
||||
startKeepalive.assert_not_called()
|
||||
|
||||
@mock.patch("sas.ensure_sudo", return_value=True)
|
||||
@mock.patch("sas.run_command")
|
||||
@mock.patch("sas.os.geteuid", return_value=1000)
|
||||
def test_run_as_user_is_noninteractive_after_upfront_authentication(
|
||||
self, _getEuid, runCommand, _ensureSudo
|
||||
):
|
||||
sas.sudoSessionPrepared = True
|
||||
|
||||
sas.run_as_user("sas", ["true"], useSpeech=True)
|
||||
|
||||
runCommand.assert_called_once_with(
|
||||
["sudo", "-n", "-u", "sas", "-H", "true"], check=True
|
||||
)
|
||||
|
||||
@mock.patch("sas.run_terminal_sudo_authentication")
|
||||
@mock.patch("sas.os.geteuid", return_value=1000)
|
||||
def test_authentication_failure_preserves_sudo_error(
|
||||
self, _getEuid, runAuthentication
|
||||
):
|
||||
runAuthentication.return_value.returncode = 1
|
||||
runAuthentication.return_value.stderr = "sudo: authentication failed\n"
|
||||
runAuthentication.return_value.stdout = ""
|
||||
|
||||
result = sas.authenticate_sudo(useSpeech=True)
|
||||
|
||||
self.assertFalse(result)
|
||||
self.assertEqual(sas.sudoAuthenticationError, "sudo: authentication failed")
|
||||
|
||||
|
||||
class TerminalSudoTests(unittest.TestCase):
|
||||
@mock.patch("sas.run_command")
|
||||
@mock.patch("builtins.input", return_value="")
|
||||
@mock.patch("sas.speak_message")
|
||||
def test_warning_and_enter_gate_precede_direct_sudo(
|
||||
self,
|
||||
speakMessage,
|
||||
readInput,
|
||||
runCommand,
|
||||
):
|
||||
events = []
|
||||
speakMessage.side_effect = lambda *_args, **_kwargs: events.append("speech")
|
||||
readInput.side_effect = lambda: events.append("enter") or ""
|
||||
runCommand.side_effect = lambda *_args, **_kwargs: events.append("sudo") or mock.Mock(
|
||||
returncode=0
|
||||
)
|
||||
|
||||
result = sas.run_terminal_sudo_authentication()
|
||||
|
||||
self.assertEqual(result.returncode, 0)
|
||||
self.assertEqual(events, ["speech", "enter", "sudo"])
|
||||
self.assertTrue(speakMessage.call_args.kwargs["wait"])
|
||||
self.assertIn("Do not type your password yet", speakMessage.call_args.args[0])
|
||||
self.assertIn("Press Enter to continue", speakMessage.call_args.args[0])
|
||||
self.assertIn(
|
||||
"stop immediately, do not finish it",
|
||||
speakMessage.call_args.args[0],
|
||||
)
|
||||
runCommand.assert_called_once_with(["sudo", "-v"])
|
||||
|
||||
@mock.patch("sas.__file__", "/usr/local/bin/sas")
|
||||
def test_normal_arguments_are_rejected(self):
|
||||
with mock.patch("sas.sys.stderr", io.StringIO()):
|
||||
result = sas.command_line_main(["Password:"])
|
||||
|
||||
self.assertEqual(result, 2)
|
||||
|
||||
|
||||
class VersionTests(unittest.TestCase):
|
||||
def test_version_flags_print_version(self):
|
||||
for flag in ("-v", "--version"):
|
||||
output = io.StringIO()
|
||||
with mock.patch("sas.sys.stdout", output), mock.patch("sas.main") as runMain:
|
||||
result = sas.command_line_main([flag])
|
||||
|
||||
self.assertEqual(result, 0)
|
||||
self.assertEqual(output.getvalue(), f"sas {sas.VERSION}\n")
|
||||
runMain.assert_not_called()
|
||||
|
||||
def test_version_is_calendar_style(self):
|
||||
self.assertRegex(sas.VERSION, r"^\d{4}\.\d{2}\.\d{2}(\.\d+)?$")
|
||||
|
||||
|
||||
class SpeechSynchronizationTests(unittest.TestCase):
|
||||
@mock.patch("sas.subprocess.run")
|
||||
def test_password_prompt_waits_for_speech_completion(self, runProcess):
|
||||
runProcess.return_value.returncode = 0
|
||||
|
||||
sas.speak_message(
|
||||
"Password prompt",
|
||||
wait=True,
|
||||
applicationName="sas",
|
||||
connectionName="sudo-password-test",
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
runProcess.call_args.args[0],
|
||||
[
|
||||
"spd-say",
|
||||
"-N",
|
||||
"sas",
|
||||
"-n",
|
||||
"sudo-password-test",
|
||||
"-w",
|
||||
"Password prompt",
|
||||
],
|
||||
)
|
||||
self.assertTrue(runProcess.call_args.kwargs["start_new_session"])
|
||||
|
||||
|
||||
class IrcFifoTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tempDir = tempfile.mkdtemp()
|
||||
self.fifoPath = os.path.join(self.tempDir, "in")
|
||||
os.mkfifo(self.fifoPath)
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.tempDir, ignore_errors=True)
|
||||
|
||||
def test_write_without_reader_fails_instead_of_hanging(self):
|
||||
with self.assertRaises(RuntimeError):
|
||||
sas.IrcSession.write_line(self.fifoPath, "/quit")
|
||||
|
||||
def test_write_with_reader_delivers_line(self):
|
||||
readFd = os.open(self.fifoPath, os.O_RDONLY | os.O_NONBLOCK)
|
||||
try:
|
||||
sas.IrcSession.write_line(self.fifoPath, "hello")
|
||||
self.assertEqual(os.read(readFd, 100), b"hello\n")
|
||||
finally:
|
||||
os.close(readFd)
|
||||
|
||||
def test_stop_with_dead_ii_does_not_hang(self):
|
||||
session = sas.IrcSession("server", 6667, "nick", "#chan", self.tempDir)
|
||||
session.serverInPath = self.fifoPath
|
||||
session.channelInPath = self.fifoPath
|
||||
session.iiProcess = mock.Mock()
|
||||
session.iiProcess.poll.return_value = 1
|
||||
|
||||
session.stop()
|
||||
|
||||
session.iiProcess.terminate.assert_not_called()
|
||||
|
||||
def test_reading_messages_after_ii_exits_raises(self):
|
||||
session = sas.IrcSession("server", 6667, "nick", "#chan", self.tempDir)
|
||||
session.serverDir = self.tempDir
|
||||
session.iiProcess = mock.Mock()
|
||||
session.iiProcess.poll.return_value = 1
|
||||
|
||||
with self.assertRaises(RuntimeError):
|
||||
session.get_private_messages(("storm",))
|
||||
|
||||
|
||||
class WormholeWaitTests(unittest.TestCase):
|
||||
@mock.patch("sas.time.sleep")
|
||||
def test_returns_code_when_received(self, _sleep):
|
||||
ircSession = mock.Mock()
|
||||
ircSession.get_private_messages.side_effect = [
|
||||
[],
|
||||
[("storm", "here you go 7-guitarist-revenge")],
|
||||
]
|
||||
|
||||
self.assertEqual(sas.wait_for_wormhole_code(ircSession, 60), "7-guitarist-revenge")
|
||||
|
||||
@mock.patch("sas.time.sleep")
|
||||
@mock.patch("sas.time.monotonic", side_effect=[0, 0, 30, 61])
|
||||
def test_returns_none_after_timeout(self, _monotonic, _sleep):
|
||||
ircSession = mock.Mock()
|
||||
ircSession.get_private_messages.return_value = []
|
||||
|
||||
self.assertIsNone(sas.wait_for_wormhole_code(ircSession, 60))
|
||||
|
||||
|
||||
class SessionEndTests(unittest.TestCase):
|
||||
@mock.patch("sas.time.sleep")
|
||||
def test_admin_end_message_stops_tunnel(self, _sleep):
|
||||
sshProcess = mock.Mock()
|
||||
sshProcess.poll.return_value = None
|
||||
ircSession = mock.Mock()
|
||||
ircSession.get_private_messages.side_effect = [
|
||||
[],
|
||||
[("storm", "ending now"), ("storm", " End ")],
|
||||
]
|
||||
|
||||
result = sas.wait_for_session_end(sshProcess, ircSession, "storm")
|
||||
|
||||
self.assertEqual(result, "admin")
|
||||
sshProcess.terminate.assert_called_once_with()
|
||||
ircSession.get_private_messages.assert_called_with(("storm",))
|
||||
|
||||
@mock.patch("sas.time.sleep")
|
||||
def test_tunnel_exit_ends_session(self, _sleep):
|
||||
sshProcess = mock.Mock()
|
||||
sshProcess.poll.side_effect = [None, 0]
|
||||
ircSession = mock.Mock()
|
||||
ircSession.get_private_messages.return_value = [("storm", "looks fine")]
|
||||
|
||||
result = sas.wait_for_session_end(sshProcess, ircSession, "storm")
|
||||
|
||||
self.assertEqual(result, "tunnel")
|
||||
sshProcess.terminate.assert_not_called()
|
||||
|
||||
@mock.patch("sas.time.sleep")
|
||||
def test_irc_loss_keeps_tunnel_running(self, _sleep):
|
||||
sshProcess = mock.Mock()
|
||||
sshProcess.poll.side_effect = [None, None, None, 0]
|
||||
ircSession = mock.Mock()
|
||||
ircSession.get_private_messages.side_effect = RuntimeError("lost")
|
||||
|
||||
result = sas.wait_for_session_end(sshProcess, ircSession, "storm")
|
||||
|
||||
self.assertEqual(result, "tunnel")
|
||||
self.assertEqual(ircSession.get_private_messages.call_count, 1)
|
||||
sshProcess.terminate.assert_not_called()
|
||||
|
||||
|
||||
class WormholeCodeTests(unittest.TestCase):
|
||||
def test_real_codes_are_found(self):
|
||||
self.assertEqual(sas.find_wormhole_code("7-guitarist-revenge"), "7-guitarist-revenge")
|
||||
self.assertEqual(
|
||||
sas.find_wormhole_code("code is 12-Apple-banana-cherry ok"),
|
||||
"12-Apple-banana-cherry",
|
||||
)
|
||||
|
||||
def test_casual_chat_is_not_a_code(self):
|
||||
for message in ("give me 5-10 minutes", "one moment", "yes", "3-way call", "2-3-4"):
|
||||
self.assertIsNone(sas.find_wormhole_code(message), message)
|
||||
|
||||
|
||||
class TunnelMonitorTests(unittest.TestCase):
|
||||
def make_monitor(self, lines, exitCode=None):
|
||||
process = mock.Mock()
|
||||
process.stderr = iter(line + "\n" for line in lines)
|
||||
process.poll.return_value = exitCode
|
||||
monitor = sas.TunnelMonitor(process)
|
||||
monitor.readerThread.join(timeout=2)
|
||||
return monitor
|
||||
|
||||
def test_forward_success_is_detected(self):
|
||||
monitor = self.make_monitor([
|
||||
"OpenSSH_10.6p1, OpenSSL 4.1.0",
|
||||
"debug1: remote forward success for: listen localhost:2232, connect localhost:22",
|
||||
])
|
||||
|
||||
self.assertEqual(monitor.wait_for_forward(5), "ready")
|
||||
self.assertEqual(monitor.error_text(), "")
|
||||
|
||||
def test_busy_port_is_detected(self):
|
||||
monitor = self.make_monitor(
|
||||
[
|
||||
"debug1: remote forward failure for: listen localhost:2232, connect localhost:22",
|
||||
"Error: remote port forwarding failed for listen port 2232",
|
||||
],
|
||||
exitCode=255,
|
||||
)
|
||||
|
||||
self.assertEqual(monitor.wait_for_forward(5), "port_in_use")
|
||||
|
||||
def test_other_exit_keeps_error_text(self):
|
||||
monitor = self.make_monitor(
|
||||
["debug1: Next authentication method: publickey", "sas@example: Permission denied (publickey)."],
|
||||
exitCode=255,
|
||||
)
|
||||
|
||||
self.assertEqual(monitor.wait_for_forward(5), "exited")
|
||||
self.assertEqual(monitor.error_text(), "sas@example: Permission denied (publickey).")
|
||||
|
||||
@mock.patch("sas.TunnelMonitor")
|
||||
@mock.patch("sas.subprocess.Popen")
|
||||
def test_start_tunnel_moves_to_next_port_when_busy(self, popen, tunnelMonitor):
|
||||
busyMonitor = mock.Mock()
|
||||
busyMonitor.wait_for_forward.return_value = "port_in_use"
|
||||
readyMonitor = mock.Mock()
|
||||
readyMonitor.wait_for_forward.return_value = "ready"
|
||||
tunnelMonitor.side_effect = [busyMonitor, readyMonitor]
|
||||
firstProcess = mock.Mock()
|
||||
firstProcess.poll.return_value = 255
|
||||
secondProcess = mock.Mock()
|
||||
popen.side_effect = [firstProcess, secondProcess]
|
||||
|
||||
process, monitor, port = sas.start_tunnel(["sudo"], "/known", "/key")
|
||||
|
||||
self.assertIs(process, secondProcess)
|
||||
self.assertIs(monitor, readyMonitor)
|
||||
self.assertEqual(port, 2233)
|
||||
self.assertIn("localhost:2232:localhost:22", popen.call_args_list[0].args[0])
|
||||
self.assertIn("localhost:2233:localhost:22", popen.call_args_list[1].args[0])
|
||||
|
||||
|
||||
class CancellationTests(unittest.TestCase):
|
||||
@mock.patch("sas.speak_message")
|
||||
@mock.patch("sas.main", side_effect=KeyboardInterrupt)
|
||||
def test_ctrl_c_before_setup_is_announced_without_traceback(self, _main, speakMessage):
|
||||
with mock.patch("sas.sys.stdout", io.StringIO()):
|
||||
result = sas.command_line_main([])
|
||||
|
||||
self.assertEqual(result, 130)
|
||||
self.assertIn("Cancelled", speakMessage.call_args.args[0])
|
||||
|
||||
@mock.patch("sas.speak_message")
|
||||
@mock.patch("sas.main", side_effect=EOFError)
|
||||
def test_end_of_input_is_announced_without_traceback(self, _main, speakMessage):
|
||||
with mock.patch("sas.sys.stdout", io.StringIO()):
|
||||
result = sas.command_line_main([])
|
||||
|
||||
self.assertEqual(result, 1)
|
||||
self.assertIn("No support session was started", speakMessage.call_args.args[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user