diff --git a/scripts/fix_media_permissions.sh b/scripts/fix_media_permissions.sh index 43b50587..f7a5dcac 100755 --- a/scripts/fix_media_permissions.sh +++ b/scripts/fix_media_permissions.sh @@ -9,6 +9,40 @@ fi MEDIA_DIRECTORY="/media/wrolpi" +# Directories: WROLPi can list, enter, and write them; every service can list and enter them. Files: WROLPi can read and +# write them; every service can read them (Caddy serves media as its own user, so a 700 directory is a 403). Bits are +# only ever added. config/ holds private files (the VPN's key and login, and more): there, only WROLPi's own bits are +# fixed. +fix_modes() { + local media=$1 + # find prints paths as given, so "/media/wrolpi/" would never match the "/media/wrolpi//config" prune. + while [ "${media}" != "/" ] && [ "${media%/}" != "${media}" ]; do + media=${media%/} + done + local skip=( \( -path "${media}/config" -o -path "${media}/lost+found" \) -prune -o ) + dirs_fixed=$(find "${media}" "${skip[@]}" -type d ! -perm -755 -print 2>/dev/null | wc -l | tr -d ' ') + if [ "${dirs_fixed}" -gt 0 ]; then + find "${media}" "${skip[@]}" -type d ! -perm -755 -exec chmod u+rwx,go+rx {} + 2>/dev/null || errors=$((errors + 1)) + fi + files_fixed=$(find "${media}" "${skip[@]}" -type f ! -perm -644 -print 2>/dev/null | wc -l | tr -d ' ') + if [ "${files_fixed}" -gt 0 ]; then + find "${media}" "${skip[@]}" -type f ! -perm -644 -exec chmod u+rw,go+r {} + 2>/dev/null || errors=$((errors + 1)) + fi + local config="${media}/config" count + if [ -d "${config}" ]; then + count=$(find "${config}" -type d ! -perm -700 -print 2>/dev/null | wc -l | tr -d ' ') + if [ "${count}" -gt 0 ]; then + find "${config}" -type d ! -perm -700 -exec chmod u+rwx {} + 2>/dev/null || errors=$((errors + 1)) + dirs_fixed=$((dirs_fixed + count)) + fi + count=$(find "${config}" -type f ! -perm -600 -print 2>/dev/null | wc -l | tr -d ' ') + if [ "${count}" -gt 0 ]; then + find "${config}" -type f ! -perm -600 -exec chmod u+rw {} + 2>/dev/null || errors=$((errors + 1)) + files_fixed=$((files_fixed + count)) + fi + fi +} + # Source .env override if it exists. if [ -f /opt/wrolpi/.env ]; then # shellcheck disable=SC1091 @@ -44,27 +78,17 @@ dirs_fixed=0 files_fixed=0 # Fix ownership. +ownership_fixed=$(find "${MEDIA_DIRECTORY}" \( ! -user wrolpi -o ! -group wrolpi \) -print 2>/dev/null | wc -l | tr -d ' ') if ! chown -R wrolpi:wrolpi "${MEDIA_DIRECTORY}" 2>/dev/null; then echo "WARNING: Could not change ownership." errors=$((errors + 1)) fi -# Ensure directories have at least u+rwx so they can be listed, traversed, and written to. -count=$(find "${MEDIA_DIRECTORY}" -type d ! -perm -u+rwx -print 2>/dev/null | wc -l) -if [ "$count" -gt 0 ]; then - find "${MEDIA_DIRECTORY}" -type d ! -perm -u+rwx -exec chmod u+rwx {} + 2>/dev/null || errors=$((errors + 1)) - dirs_fixed=$count -fi - -# Ensure files have at least u+rw so they can be read and modified. -count=$(find "${MEDIA_DIRECTORY}" -type f ! -perm -u+rw -print 2>/dev/null | wc -l) -if [ "$count" -gt 0 ]; then - find "${MEDIA_DIRECTORY}" -type f ! -perm -u+rw -exec chmod u+rw {} + 2>/dev/null || errors=$((errors + 1)) - files_fixed=$count -fi +fix_modes "${MEDIA_DIRECTORY}" echo "" echo "=== Summary ===" +echo "Ownership fixed: ${ownership_fixed}" echo "Directories fixed: ${dirs_fixed}" echo "Files fixed: ${files_fixed}" echo "Errors: ${errors}" diff --git a/wrolpi/test/test_fix_media_permissions.py b/wrolpi/test/test_fix_media_permissions.py new file mode 100644 index 00000000..3ccb66d7 --- /dev/null +++ b/wrolpi/test/test_fix_media_permissions.py @@ -0,0 +1,140 @@ +""" +Tests that scripts/fix_media_permissions.sh leaves the library readable by every service (Caddy serves media as its +own user), and leaves WROLPi's config directory private. +""" +import os +import re +import stat +import subprocess + +import pytest + +from wrolpi.vars import PROJECT_DIR + +SCRIPT = PROJECT_DIR / 'scripts/fix_media_permissions.sh' + + +def _function(name: str) -> str: + match = re.search(rf'^{name}\(\) \{{\n.*?^\}}\n', SCRIPT.read_text(), re.MULTILINE | re.DOTALL) + assert match, f'{name} is not defined in {SCRIPT}' + return match.group(0) + + +@pytest.fixture(autouse=True) +def umask_022(): + """The counts include directories the test only makes, whose modes come from the umask.""" + previous = os.umask(0o022) + yield + os.umask(previous) + + +def _mode(path) -> int: + return stat.S_IMODE(path.lstat().st_mode) + + +def _fix_modes(media) -> list[str]: + """Run the script's fix_modes on `media` (as this user; it only adds permission bits), return the counts.""" + script = _function('fix_modes') + 'errors=0\nfix_modes "$1"\necho "$dirs_fixed $files_fixed $errors"\n' + result = subprocess.run(['bash', '-c', script, 'bash', media if isinstance(media, str) else str(media)], + capture_output=True, text=True, check=True) + return result.stdout.split() + + +def test_library_is_readable_by_every_service(tmp_path): + media = tmp_path / 'media' + channel = media / 'videos/Astronomy/Learn the Sky' + (channel / '2016').mkdir(parents=True) + video = channel / '2016/video.mp4' + video.write_bytes(b'video') + for path in (channel, channel / '2016'): + path.chmod(0o700) + video.chmod(0o700) + poster = channel / '2016/video.jpg' + poster.write_bytes(b'jpg') + poster.chmod(0o600) + # Already readable: left as it is (bits are only ever added; group-writable stays group-writable). + shared = media / 'docs' + shared.mkdir() + shared.chmod(0o775) + note = shared / 'note.txt' + note.write_text('note') + note.chmod(0o664) + + assert _fix_modes(media) == ['2', '2', '0'] + + assert _mode(channel) == 0o755 + assert _mode(channel / '2016') == 0o755 + assert _mode(video) == 0o744 + assert _mode(poster) == 0o644 + assert _mode(shared) == 0o775 + assert _mode(note) == 0o664 + + +def test_config_stays_private(tmp_path): + """config/ holds the VPN's key and login (and more); it is never opened to other users.""" + media = tmp_path / 'media' + vpn = media / 'config/vpn' + vpn.mkdir(parents=True) + vpn.chmod(0o700) + key = vpn / 'wireguard.conf' + key.write_text('PrivateKey = secret') + key.chmod(0o600) + lost_and_found = media / 'lost+found' + lost_and_found.mkdir() + lost_and_found.chmod(0o700) + + # WROLPi must still be able to write its own config. + tags = media / 'config/tags.yaml' + tags.write_text('tags: {}') + tags.chmod(0o400) + locked = media / 'config/backup' + locked.mkdir() + locked.chmod(0o500) + + assert _fix_modes(media) == ['1', '1', '0'] + + assert _mode(vpn) == 0o700 + assert _mode(key) == 0o600 + assert _mode(tags) == 0o600 + assert _mode(locked) == 0o700 + assert _mode(lost_and_found) == 0o700 + + +@pytest.mark.parametrize('slashes', ['/', '//']) +def test_config_stays_private_with_trailing_slash(tmp_path, slashes): + """MEDIA_DIRECTORY may come from .env with a trailing slash; config/ must still be skipped.""" + media = tmp_path / 'media' + vpn = media / 'config/vpn' + vpn.mkdir(parents=True) + vpn.chmod(0o700) + key = vpn / 'wireguard.conf' + key.write_text('PrivateKey = secret') + key.chmod(0o600) + ssl = media / 'config/ssl' + ssl.mkdir() + ca_key = ssl / 'ca.key' + ca_key.write_text('secret') + ca_key.chmod(0o600) + lost_and_found = media / 'lost+found' + lost_and_found.mkdir() + lost_and_found.chmod(0o700) + channel = media / 'videos/Learn the Sky' + channel.mkdir(parents=True) + channel.chmod(0o700) + + assert _fix_modes(f'{media}{slashes}') == ['1', '0', '0'] + + assert _mode(vpn) == 0o700 + assert _mode(key) == 0o600 + assert _mode(ca_key) == 0o600 + assert _mode(lost_and_found) == 0o700 + assert _mode(channel) == 0o755 + + +def test_runs_fix_modes(): + """The script runs it, after fixing ownership, and reports what it changed.""" + text = SCRIPT.read_text() + main = text[text.index(_function('fix_modes')) + len(_function('fix_modes')):] + assert 'fix_modes "${MEDIA_DIRECTORY}"' in main + assert main.index('chown -R wrolpi:wrolpi') < main.index('fix_modes "${MEDIA_DIRECTORY}"') + assert 'Ownership fixed:' in main