Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
998e3f7
fix(auth): map authenticator errors to access denied
janpenitent Sep 23, 2026
d2b8f01
test(auth): pin that only the base authenticator error is access denied
janpenitent Sep 23, 2026
eb15efd
fix(auth): honor prefix in 'prefix:attr' regex field syntax
aschumann-virtualcable Jul 20, 2026
cba968e
fix(auth): support attribute extraction with '**' prefix syntax
aschumann-virtualcable Jul 20, 2026
7fc9c2c
feat(snapshot): add snapshot creation and recovery for back to cache …
aschumann-virtualcable Jun 12, 2026
b00e5d5
feat(snapshot): implement snapshot reuse for back to cache operations
aschumann-virtualcable Jun 15, 2026
3cf223f
feat(snapshot): update logout process to support snapshot reuse on re…
aschumann-virtualcable Jun 15, 2026
00a3797
refactor(snapshot): remove unused snapshot reuse logic from service p…
aschumann-virtualcable Jun 16, 2026
259c529
fix(cache): do not mark a machine returning to cache as usable before…
aschumann-virtualcable Jul 13, 2026
70a0294
fix(auth): normalize username to dedupe rows polluted by invisible chars
aschumann-virtualcable Jul 13, 2026
d439584
fix(auth): migrate existing user rows and use NFC on username normali…
aschumann-virtualcable Jul 13, 2026
ec211c2
fix(auth): normalize username on every user lookup path
aschumann-virtualcable Jul 14, 2026
e33d275
Switches server import to parse CSV string input
aschumann-virtualcable Mar 13, 2026
42f8ad3
Add import CSV for federated authenticators and update admin GUI
aschumann-virtualcable Oct 1, 2026
8210877
Rebuild admin bundle: show Import CSV button and add template download
aschumann-virtualcable Oct 1, 2026
6c57033
Fix concurrent logout destroying valid cache elements in release_from…
janpenitent Jul 1, 2026
0196b5c
fix(tests): do not depend on DNS in physical machines migration test
janpenitent Aug 20, 2026
d4ee095
fix(auth): redirect to OAuth2 provider logout URL on logout
aschumann-virtualcable Sep 23, 2026
f24e863
Proxmox: do not treat lookup errors as a completed deletion
aschumann-virtualcable Sep 25, 2026
4a40282
fix(deferred-deletion): release the deleting marker when the worker s…
aschumann-virtualcable Oct 1, 2026
230e51d
fix(proxmox): do not delete a publication template while machines sti…
aschumann-virtualcable Oct 1, 2026
d0878c2
Use INFO_STATES to decide if a Proxmox publication still has machines
aschumann-virtualcable Oct 1, 2026
efdff51
fix(proxmox): wait for the VM disks to disappear before reporting the…
aschumann-virtualcable Oct 4, 2026
c93bc6e
fix(proxmox): do not let a recorded disk list outlive the vm it belon…
janpenitent Oct 5, 2026
77caf4c
fix(proxmox): check the disks of a deleted vm without filtering by it…
janpenitent Oct 6, 2026
d8f870b
fix(proxmox): encode volume slashes when deleting disks and protect p…
aschumann-virtualcable Oct 6, 2026
713f338
fix(proxmox): log warning when pre-delete disk inspection fails
aschumann-virtualcable Oct 6, 2026
98f2ab9
fix(SimpleLDAP): don't fail the connection test on sizeLimitExceeded
aschumann-virtualcable Jul 22, 2026
e474c9d
chore(mfa): trace TOTP validation to diagnose rejected codes
janpenitent Aug 19, 2026
42a983b
chore(mfa): log only rejected TOTP codes
janpenitent Aug 20, 2026
b39af2c
Ensures WOL uses current MAC for migrated user-services
aschumann-virtualcable May 14, 2026
65bf763
Fixes X2GO client path lookup for correct argument type
aschumann-virtualcable Apr 20, 2026
3a11bfb
test(userservice): seed the instance with the recorded unique_id befo…
aschumann-virtualcable Oct 9, 2026
91f7878
Revert the machine check in the Proxmox publication delete
aschumann-virtualcable Oct 4, 2026
b3ace3b
fix(auth): drop 0048 dedupe-user-names migration (breaking 5.0 chain)
aschumann-virtualcable Oct 19, 2026
31a1edb
test(physical_machines): fake DNS in the migration test
aschumann-virtualcable Oct 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion server/src/uds/REST/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from uds.core.util.config import GlobalConfig
from uds.core.auths.auth import root_user
from uds.core.util import net
from uds.core.util.auth import normalize_username
from uds.models import Authenticator, User
from uds.core.managers.crypto import CryptoManager

Expand Down Expand Up @@ -373,7 +374,9 @@ def get_user(self) -> 'User':
):
return root_user()

return Authenticator.objects.get(pk=auth_id).users.get(name=username)
# Normalized as in Authenticator.get_or_create_user: the stored row is clean, so
# a session username carrying invisible chars would not match it
return Authenticator.objects.get(pk=auth_id).users.get(name=normalize_username(username))

def get_param(self, *names: str) -> str:
"""
Expand Down
18 changes: 12 additions & 6 deletions server/src/uds/REST/methods/servers_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
"""
import logging
import typing
import io
import csv

from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
Expand Down Expand Up @@ -345,11 +347,11 @@ def maintenance(self, parent: 'Model', id: str) -> typing.Any:

def importcsv(self, parent: 'Model') -> typing.Any:
"""
We receive a json with string[][] format with the data.
We receive a csv string with the data.
Has no header, only the data.
"""
parent = ensure.is_instance(parent, models.ServerGroup)
data: list[list[str]] = self._params.get('data', [])
data: typing.Any = self._params.get('data', '')
logger.debug('Data received: %s', data)
# String lines can have 1, 2 or 3 fields.
# if 1, it's a IP
Expand All @@ -358,16 +360,20 @@ def importcsv(self, parent: 'Model') -> typing.Any:
# if ip is empty and has a hostname, it will be kept, but if it has no hostname, it will be skipped
# If the IP is invalid and has no hostname, it will be skipped
import_errors: list[str] = []
for line_number, row in enumerate(data, 1):

f = io.StringIO('\n'.join(','.join(row) for row in data))
reader: typing.Iterable[list[str]] = csv.reader(f)

for line_number, row in enumerate(reader, 1):
if len(row) == 0:
continue
hostname = row[0].strip()
hostname = row[0]
ip = ''
mac = consts.MAC_UNKNOWN
if len(row) > 1:
ip = row[1].strip()
ip = row[1]
if len(row) > 2:
mac = row[2].strip().upper().strip() or consts.MAC_UNKNOWN
mac = row[2].upper() or consts.MAC_UNKNOWN
if mac and not net.is_valid_mac(mac):
import_errors.append(f'Line {line_number}: MAC {mac} is invalid, skipping')
continue # skip invalid macs
Expand Down
78 changes: 78 additions & 0 deletions server/src/uds/REST/methods/users_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,13 @@

"""
Author: Adolfo Gómez, dkmaster at dkmon dot com
Author: Andres Schumann, aschumann at virtualcable dot es
"""
import logging
import typing
import collections.abc
import io
import csv

from django.utils.translation import gettext as _
from django.forms.models import model_to_dict
Expand All @@ -42,6 +45,7 @@

from uds.core.auths.user import User as AUser
from uds.core.util import log, ensure
from uds.core.util.auth import normalize_username
from uds.core.util.model import process_uuid, sql_stamp_seconds
from uds.models import Authenticator, User, Group, ServicePool
from uds.core.managers.crypto import CryptoManager
Expand Down Expand Up @@ -84,6 +88,8 @@ class Users(DetailHandler):
'clean_related',
'add_to_group',
'enable_client_logging',
'importcsv',
'import',
]

def get_items(self, parent: 'Model', item: typing.Optional[str]) -> typing.Any:
Expand Down Expand Up @@ -210,6 +216,12 @@ def save_item(self, parent: 'Model', item: typing.Optional[str]) -> typing.Any:
'staff_member',
'is_admin',
]
# Normalized as on login, or a name pasted with invisible chars (BOM, zero-width, ...)
# would create a row that no authenticated user could ever match.
# Note this also turns an all-invisible name into an empty one, rejected right below.
if 'name' in self._params:
self._params['name'] = normalize_username(self._params['name'])

if self._params.get('name', '').strip() == '':
raise exceptions.rest.RequestError(_('Username cannot be empty'))

Expand Down Expand Up @@ -360,6 +372,72 @@ def enable_client_logging(self, parent: 'Model', item: str) -> dict[str, str]:

return {'status': 'ok'}

def importcsv(self, parent: 'Model') -> typing.Any:
auth = ensure.is_instance(parent, Authenticator)
if not auth.get_instance().external_source:
raise exceptions.rest.RequestError(
_('User import is only supported for external/federated authenticators')
)

data: typing.Any = self._params.get('data', '')
has_header: bool = bool(self._params.get('has_header', False))
separator: str = str(self._params.get('separator', ','))

if isinstance(data, list):
rows: list[list[str]] = [
[str(cell).strip() for cell in row]
for row in data
if isinstance(row, (list, tuple))
]
else:
if separator == 'tab':
separator = '\t'
f = io.StringIO(str(data))
reader = csv.reader(f, delimiter=separator)
rows = [[cell.strip() for cell in row] for row in reader]

if has_header and rows:
rows = rows[1:]

existing_usernames: set[str] = set(auth.users.values_list('name', flat=True))
errors: list[str] = []

for line_num, row in enumerate(rows, 1):
if not row or not any(row):
continue
username = row[0].strip()
if not username:
errors.append(_('Line {}: username is required').format(line_num))
continue
if username in existing_usernames:
errors.append(_('Line {}: user {} already exists').format(line_num, username))
continue

comments = ''
if len(row) > 1 and row[1].strip():
comments = f'{row[1].strip()} (import)'

try:
auth.users.create(
name=username,
real_name=username,
comments=comments,
state=State.ACTIVE,
staff_member=False,
is_admin=False,
mfa_data='',
password='',
)
existing_usernames.add(username)
except Exception as e:
logger.error('Error importing user %s: %s', username, e)
errors.append(_('Line {}: error creating user {}: {}').format(line_num, username, e))

return errors


setattr(Users, 'import', Users.importcsv)


class Groups(DetailHandler):
custom_methods = ['services_pools', 'users']
Expand Down
2 changes: 1 addition & 1 deletion server/src/uds/auths/OAuth2/authenticator.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def logout(
return types.auth.SUCCESS_AUTH

return types.auth.AuthenticationResult(
types.auth.AuthenticationState.SUCCESS,
types.auth.AuthenticationState.REDIRECT,
url=self.logout_url.value.replace('{token}', urllib.parse.quote(token)),
)

Expand Down
5 changes: 5 additions & 0 deletions server/src/uds/auths/SimpleLDAP/authenticator.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,7 @@ def ensure_at_least_one(filter: str, error_msg: str) -> None:
scope=ldaputil.SCOPE_SUBTREE, # pyright: ignore reportGeneralTypeIssues
filterstr=f'(&(objectClass={self.group_class.as_str()})({self.group_id_attr.as_str()}=*))',
attrlist=[self.member_attr.as_str()],
sizelimit=LDAP_RESULT_LIMIT,
)
)
if not res:
Expand All @@ -548,6 +549,10 @@ def ensure_at_least_one(filter: str, error_msg: str) -> None:
break
if ok is False:
raise Exception(_('Can\'t locate any group with the membership attribute specified'))
except ldap.SIZELIMIT_EXCEEDED: # type: ignore
# Server reports the limit as an error and drops the partial results,
# but reaching it already proves that matching groups exist
return types.core.TestResult(True)
except Exception as e:
return types.core.TestResult(False, str(e))

Expand Down
5 changes: 4 additions & 1 deletion server/src/uds/core/managers/servers_api/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

from uds import models
from uds.core import consts, osmanagers, types
from uds.core.managers.userservice import UserServiceManager
from uds.core.util import log
from uds.core.util.model import sql_now
from uds.REST.utils import rest_result
Expand Down Expand Up @@ -146,7 +147,9 @@ def process_logout(server: 'models.Server', data: dict[str, typing.Any]) -> typi
osmanager: typing.Optional[osmanagers.OSManager] = userservice.get_osmanager_instance()
if not osmanager or osmanager.is_removable_on_logout(userservice):
logger.debug('Removable on logout: %s', osmanager)
userservice.release()
# Use release_from_logout (same as actor logout) so pools that allow putting
# back to cache (e.g. snapshot reuse) return the machine instead of destroying it
UserServiceManager.manager().release_from_logout(userservice)

return rest_result(consts.OK)

Expand Down
84 changes: 49 additions & 35 deletions server/src/uds/core/managers/userservice.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,8 @@ def move_to_level(self, cache: UserService, cache_level: types.services.CacheLev
)
if state.is_runing() and cache.is_usable():
cache.set_state(State.PREPARING)
else:
cache.set_state(State.USABLE)

# Data will be serialized on makeUnique process
UserServiceOpChecker.make_unique(cache, state)
Expand All @@ -332,20 +334,26 @@ def forced_move_assigned_to_cache_l1(self, user_service: UserService) -> None:
user_service_copy.in_use = False
user_service_copy.state = State.REMOVED
user_service_copy.os_state = State.USABLE
log.log(user_service_copy, types.log.LogLevel.INFO, 'Service moved to cache')

# Save the new element.
# Save BEFORE logging: an unsaved copy has owner_id=None, and that failed uds_log
# insert poisons an enclosing atomic() (release_from_logout) -> next save() dies
user_service_copy.save()

log.log(user_service_copy, types.log.LogLevel.INFO, 'Service moved to cache')

# Now, move the original to cache, but do it "hard" way, so we do not need to check for state
user_service.state = State.USABLE
user_service.state = State.PREPARING # move_to_level will set real final state depending on the result of the operation
user_service.os_state = State.USABLE
user_service.user = None
user_service.cache_level = types.services.CacheLevel.L1
user_service.in_use = False
user_service.src_hostname = user_service.src_ip = ''
user_service.save()

# Execute back operations to move to level 1 (runs the move-to-cache queue,
# which for "snapshot" put_back_to_cache triggers the snapshot recovery op)
user_service.move_to_level(types.services.CacheLevel.L1)

def get_cache_servicepool_stats(
self,
servicepool: ServicePool,
Expand All @@ -369,8 +377,6 @@ def get_cache_servicepool_stats(
):
return types.services.ServicePoolStats.null() # No cache needed for this servicepool

service_instance = servicepool.service.get_instance()

servicepool.userservices.update() # Cleans cached queries

# If this deployedService don't have a publication active and needs it, ignore it
Expand Down Expand Up @@ -413,12 +419,9 @@ def get_cache_servicepool_stats(
assigned_filter = self.get_cache_state_filter(servicepool, types.services.CacheLevel.NONE)

counts: dict[str, int] = servicepool.userservices.aggregate(
l1_cache_count=Count(Case(When(l1_cache_filter, then=1), output_field=IntegerField()))
+ l1_cache_increased_by,
l2_cache_count=Count(Case(When(l2_cache_filter, then=1), output_field=IntegerField()))
+ l2_cache_increased_by,
assigned_count=Count(Case(When(assigned_filter, then=1), output_field=IntegerField()))
+ assigned_increased_by,
l1_cache_count=Count(Case(When(l1_cache_filter, then=1), output_field=IntegerField())),
l2_cache_count=Count(Case(When(l2_cache_filter, then=1), output_field=IntegerField())),
assigned_count=Count(Case(When(assigned_filter, then=1), output_field=IntegerField())),
)

pool_stat = types.services.ServicePoolStats(
Expand Down Expand Up @@ -525,31 +528,42 @@ def release_from_logout(self, userservice: UserService) -> None:

This method will take care of removing the service if no cache is desired of cache already full (on servicepool)
"""
if userservice.allow_putting_back_to_cache() is False:
userservice.release() # Normal release
return

# Some sanity checks, should never happen
if userservice.cache_level != types.services.CacheLevel.NONE:
logger.error('Cache level is not NONE for userservice %s on release_on_logout', userservice)
userservice.release()
return

if userservice.is_usable() is False:
logger.error('State is not USABLE for userservice %s on release_on_logout', userservice)
userservice.release()
return

# Fix assigned value, because "userservice" will not count as assigned anymore
stats = self.get_cache_servicepool_stats(userservice.deployed_service, assigned_increased_by=-1)
# Concurrent logout events may hit the same userservice (duplicate actor logouts,
# or the unused-services worker racing an interactive logout). Lock and re-read so
# only the first event acts on a consistent state.
with transaction.atomic():
try:
userservice = UserService.objects.select_for_update().get(id=userservice.id)
except UserService.DoesNotExist:
# Row already released & cleaned by a prior logout, nothing to do
return

# Note that only moves to cache L1
# Also, we can get values for L2 cache, thats why we check L1 for overflow and needed
if stats.is_null() or stats.has_l1_cache_overflow():
userservice.release() # Mark as removable
elif stats.is_l1_cache_growth_required():
# Move the clone of the user service to cache, and set our as REMOVED
self.forced_move_assigned_to_cache_l1(userservice)
if userservice.allow_putting_back_to_cache() is False:
userservice.release()
return

# Already handled by a prior logout (back in cache or no longer usable). Skip:
# releasing here would destroy the cache element that logout just returned.
if userservice.cache_level != types.services.CacheLevel.NONE or not userservice.is_usable():
logger.debug('Userservice %s already handled on logout, skipping', userservice)
return

servicepool = userservice.deployed_service

# Fix assigned value, because "userservice" will not count as assigned anymore.
# The same cache overflow/growth logic decides whether to return the machine to
# cache or destroy it. For snapshot pools, the move-to-cache queue additionally
# reverts the machine to its snapshot (BACK_TO_CACHE_SNAPSHOT_RECOVER).
stats = self.get_cache_servicepool_stats(servicepool, assigned_increased_by=-1)

# Note that only moves to cache L1
# Also, we can get values for L2 cache, thats why we check L1 for overflow and needed
if stats.is_null() or stats.has_l1_cache_overflow():
userservice.release() # Mark as removable
elif stats.is_l1_cache_growth_required():
# Move the clone of the user service to cache, and set our as REMOVED
# (for snapshot pools, this also reverts the machine to its snapshot)
self.forced_move_assigned_to_cache_l1(userservice)

def get_existing_assignation_for_user(
self, service_pool: ServicePool, user: User
Expand Down
Loading
Loading