diff --git a/src/Agent.Worker/ContainerOperationProvider.cs b/src/Agent.Worker/ContainerOperationProvider.cs index ebf8674763..3afde8c3a1 100644 --- a/src/Agent.Worker/ContainerOperationProvider.cs +++ b/src/Agent.Worker/ContainerOperationProvider.cs @@ -708,14 +708,43 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta Func addUserWithIdAndGroup; Func addUserToGroup; - bool userIdIsLarge = Int64.Parse(container.CurrentUserId) > 256000; + bool useShadowIfAlpine = false; - if (isAlpineBasedImage && userIdIsLarge) + if (isAlpineBasedImage) { - await DockerExec(executionContext, container.ContainerId, "apk add shadow"); + List shadowInfoOutput = await DockerExec(executionContext, container.ContainerId, "apk list --installed | grep shadow"); + bool shadowPreinstalled = false; + + foreach (string shadowInfoLine in shadowInfoOutput) + { + if (shadowInfoLine.Contains("{shadow}", StringComparison.Ordinal)) + { + Trace.Info("The 'shadow' package is preinstalled and therefore will be used."); + shadowPreinstalled = true; + break; + } + } + + bool userIdIsOutsideAdduserCommandRange = Int64.Parse(container.CurrentUserId) > 256000; + + if (userIdIsOutsideAdduserCommandRange && !shadowPreinstalled) + { + Trace.Info("User ID is outside the range of the 'adduser' command, therefore the 'shadow' package will be installed and used."); + + try + { + await DockerExec(executionContext, container.ContainerId, "apk add shadow"); + } + catch (InvalidOperationException) + { + throw new InvalidOperationException("The user ID is outside the range of the 'adduser' command. The alternative command 'useradd' cannot be used because the 'shadow' package is not preinstalled and it is not possible to install it."); + } + } + + useShadowIfAlpine = shadowPreinstalled || userIdIsOutsideAdduserCommandRange; } - if (isAlpineBasedImage && !userIdIsLarge) + if (isAlpineBasedImage && !useShadowIfAlpine) { addGroup = (groupName) => $"addgroup {groupName}"; addGroupWithId = (groupName, groupId) => $"addgroup -g {groupId} {groupName}";