Setting uid/gid when mounting exfat and vfat filesystems.

This commit is contained in:
Roland 2026-02-08 09:50:18 -07:00
parent f779369bb8
commit 3a1d366c5c
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
4 changed files with 187 additions and 11 deletions

View file

@ -4,7 +4,9 @@ Disk utilities for WROLPi Controller.
Provides disk detection, mounting, and WROLPi drive identification.
"""
import grp
import json
import pwd
import subprocess
import tempfile
from dataclasses import dataclass
@ -16,6 +18,21 @@ from controller.lib.config import get_config, is_docker_mode
SUPPORTED_FILESYSTEMS = {"ext4", "btrfs", "vfat", "exfat"}
def get_wrolpi_uid_gid() -> tuple[int, int]:
"""
Get uid and gid for the wrolpi user.
Returns:
Tuple of (uid, gid). Falls back to (1001, 1001) if wrolpi user/group doesn't exist.
"""
try:
uid = pwd.getpwnam("wrolpi").pw_uid
gid = grp.getgrnam("wrolpi").gr_gid
return uid, gid
except KeyError:
return 1001, 1001 # wrolpi user is typically created after the first user
@dataclass
class BlockDevice:
"""Represents a block device/partition."""
@ -149,6 +166,12 @@ def mount_drive(
# Create mount point if needed
Path(mount_point).mkdir(parents=True, exist_ok=True)
# For exfat/vfat, add uid/gid options to set ownership to wrolpi user
# These filesystems don't support POSIX permissions natively
if fstype in ("exfat", "vfat"):
uid, gid = get_wrolpi_uid_gid()
options = f"{options},uid={uid},gid={gid}"
# Build mount command
cmd = ["mount"]
if fstype:

View file

@ -9,7 +9,7 @@ import subprocess
from datetime import datetime
from pathlib import Path
from controller.lib.disks import get_uuid, validate_mount_point
from controller.lib.disks import get_uuid, get_wrolpi_uid_gid, validate_mount_point
from controller.lib.wrol_mode import require_normal_mode
FSTAB_PATH = Path("/etc/fstab")
@ -160,6 +160,12 @@ def add_fstab_entry(
# This ensures we don't get duplicates when remounting the same device to a different location
entries = _filter_entry_with_comment(entries, mount_point=mount_point, device=device_spec)
# For exfat/vfat, add uid/gid options to set ownership to wrolpi user
# These filesystems don't support POSIX permissions natively
if fstype in ("exfat", "vfat"):
uid, gid = get_wrolpi_uid_gid()
options = f"{options},uid={uid},gid={gid}"
# Build new entry line
new_entry = f"{device_spec} {mount_point} {fstype} {options} 0 2\n"

View file

@ -11,6 +11,7 @@ from controller.lib.disks import (
BlockDevice,
get_block_devices,
get_uuid,
get_wrolpi_uid_gid,
validate_mount_point,
mount_drive,
unmount_drive,
@ -207,6 +208,80 @@ class TestMountDrive:
assert result["success"] is False
assert "mount failed" in result["error"]
def test_exfat_mount_includes_uid_gid(self):
"""Should add uid/gid options when mounting exfat."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("controller.lib.disks.get_wrolpi_uid_gid", return_value=(1001, 1001)):
with mock.patch("pathlib.Path.mkdir"):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="", stderr="")
result = mount_drive("/dev/sda1", "/media/test", fstype="exfat")
assert result["success"] is True
# Verify mount was called with uid/gid options
call_args = mock_run.call_args[0][0]
assert "-o" in call_args
options_idx = call_args.index("-o") + 1
options = call_args[options_idx]
assert "uid=1001" in options
assert "gid=1001" in options
def test_ext4_mount_does_not_include_uid_gid(self):
"""Should not add uid/gid options when mounting ext4."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("pathlib.Path.mkdir"):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="", stderr="")
result = mount_drive("/dev/sda1", "/media/test", fstype="ext4")
assert result["success"] is True
# Verify mount was called without uid/gid options
call_args = mock_run.call_args[0][0]
assert "-o" in call_args
options_idx = call_args.index("-o") + 1
options = call_args[options_idx]
assert "uid=" not in options
assert "gid=" not in options
def test_vfat_mount_includes_uid_gid(self):
"""Should add uid/gid options when mounting vfat (FAT32)."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("controller.lib.disks.get_wrolpi_uid_gid", return_value=(1001, 1001)):
with mock.patch("pathlib.Path.mkdir"):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="", stderr="")
result = mount_drive("/dev/sda1", "/media/test", fstype="vfat")
assert result["success"] is True
# Verify mount was called with uid/gid options
call_args = mock_run.call_args[0][0]
assert "-o" in call_args
options_idx = call_args.index("-o") + 1
options = call_args[options_idx]
assert "uid=1001" in options
assert "gid=1001" in options
class TestGetWrolpiUidGid:
"""Tests for get_wrolpi_uid_gid function."""
def test_returns_wrolpi_user_ids(self):
"""Should return uid/gid for wrolpi user when it exists."""
mock_pwd = mock.Mock()
mock_pwd.pw_uid = 1001
mock_grp = mock.Mock()
mock_grp.gr_gid = 1001
with mock.patch("controller.lib.disks.pwd.getpwnam", return_value=mock_pwd):
with mock.patch("controller.lib.disks.grp.getgrnam", return_value=mock_grp):
uid, gid = get_wrolpi_uid_gid()
assert uid == 1001
assert gid == 1001
def test_returns_fallback_when_user_not_found(self):
"""Should return 1001:1001 fallback when wrolpi user doesn't exist."""
with mock.patch("controller.lib.disks.pwd.getpwnam", side_effect=KeyError("wrolpi")):
uid, gid = get_wrolpi_uid_gid()
assert uid == 1001
assert gid == 1001
class TestUnmountDrive:
"""Tests for unmount_drive function."""

View file

@ -154,21 +154,93 @@ UUID=5678 /media/64GB exfat defaults,nofail,x-systemd.device-timeout=10s 0 2
with mock.patch("controller.lib.fstab.require_normal_mode"):
with mock.patch("controller.lib.fstab.get_uuid", return_value="5678"):
with mock.patch("controller.lib.fstab.backup_fstab"):
with mock.patch("controller.lib.fstab.get_wrolpi_uid_gid", return_value=(1001, 1001)):
with mock.patch("builtins.open", mock_file):
with mock.patch("subprocess.run"):
# Mount same device to different mount point
result = add_fstab_entry("/dev/sda1", "/media/64GB-2", "exfat")
assert result["success"] is True
written_str = "".join(written_content)
# Should only have ONE entry for UUID=5678 (the new one)
assert written_str.count("UUID=5678") == 1
# Should have the new mount point
assert "/media/64GB-2" in written_str
# Should NOT have the old mount point
assert "/media/64GB " not in written_str
# Should have exactly ONE WROLPi comment
assert written_str.count("WROLPi managed mount") == 1
def test_exfat_fstab_entry_includes_uid_gid(self):
"""Should add uid/gid options when adding exfat fstab entry."""
fstab_content = "# empty\n"
written_content = []
def mock_write(content):
written_content.append(content)
mock_file = mock.mock_open(read_data=fstab_content)
mock_file().write = mock_write
with mock.patch("controller.lib.fstab.require_normal_mode"):
with mock.patch("controller.lib.fstab.get_uuid", return_value="1234-5678"):
with mock.patch("controller.lib.fstab.backup_fstab"):
with mock.patch("controller.lib.fstab.get_wrolpi_uid_gid", return_value=(1001, 1001)):
with mock.patch("builtins.open", mock_file):
with mock.patch("subprocess.run"):
result = add_fstab_entry("/dev/sda1", "/media/usb", "exfat")
assert result["success"] is True
written_str = "".join(written_content)
# Should have uid/gid options
assert "uid=1001" in written_str
assert "gid=1001" in written_str
def test_ext4_fstab_entry_does_not_include_uid_gid(self):
"""Should not add uid/gid options when adding ext4 fstab entry."""
fstab_content = "# empty\n"
written_content = []
def mock_write(content):
written_content.append(content)
mock_file = mock.mock_open(read_data=fstab_content)
mock_file().write = mock_write
with mock.patch("controller.lib.fstab.require_normal_mode"):
with mock.patch("controller.lib.fstab.get_uuid", return_value="1234-5678"):
with mock.patch("controller.lib.fstab.backup_fstab"):
with mock.patch("builtins.open", mock_file):
with mock.patch("subprocess.run"):
# Mount same device to different mount point
result = add_fstab_entry("/dev/sda1", "/media/64GB-2", "exfat")
result = add_fstab_entry("/dev/sda1", "/media/data", "ext4")
assert result["success"] is True
written_str = "".join(written_content)
# Should only have ONE entry for UUID=5678 (the new one)
assert written_str.count("UUID=5678") == 1
# Should have the new mount point
assert "/media/64GB-2" in written_str
# Should NOT have the old mount point
assert "/media/64GB " not in written_str
# Should have exactly ONE WROLPi comment
assert written_str.count("WROLPi managed mount") == 1
# Should NOT have uid/gid options
assert "uid=" not in written_str
assert "gid=" not in written_str
def test_vfat_fstab_entry_includes_uid_gid(self):
"""Should add uid/gid options when adding vfat (FAT32) fstab entry."""
fstab_content = "# empty\n"
written_content = []
def mock_write(content):
written_content.append(content)
mock_file = mock.mock_open(read_data=fstab_content)
mock_file().write = mock_write
with mock.patch("controller.lib.fstab.require_normal_mode"):
with mock.patch("controller.lib.fstab.get_uuid", return_value="1234-5678"):
with mock.patch("controller.lib.fstab.backup_fstab"):
with mock.patch("controller.lib.fstab.get_wrolpi_uid_gid", return_value=(1001, 1001)):
with mock.patch("builtins.open", mock_file):
with mock.patch("subprocess.run"):
result = add_fstab_entry("/dev/sda1", "/media/usb", "vfat")
assert result["success"] is True
written_str = "".join(written_content)
# Should have uid/gid options
assert "uid=1001" in written_str
assert "gid=1001" in written_str
class TestRemoveFstabEntry: