Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Detect rootless Docker endpoint configurations #868

Merged
merged 3 commits into from
Apr 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ namespace DotNet.Testcontainers.Builders
using System;
using System.Linq;
using DotNet.Testcontainers.Configurations;
using JetBrains.Annotations;

/// <inheritdoc cref="IDockerRegistryAuthenticationProvider" />
[PublicAPI]
internal sealed class EnvironmentEndpointAuthenticationProvider : DockerEndpointAuthenticationProvider
{
private readonly Uri _dockerEngine;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ namespace DotNet.Testcontainers.Builders
using System.Security.Cryptography.X509Certificates;
using Docker.DotNet.X509;
using DotNet.Testcontainers.Configurations;
using JetBrains.Annotations;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

/// <inheritdoc cref="IDockerRegistryAuthenticationProvider" />
[PublicAPI]
internal sealed class MTlsEndpointAuthenticationProvider : TlsEndpointAuthenticationProvider
{
private static readonly X509CertificateParser CertificateParser = new X509CertificateParser();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
namespace DotNet.Testcontainers.Builders
namespace DotNet.Testcontainers.Builders
{
using System;
using System.Runtime.InteropServices;
using DotNet.Testcontainers.Configurations;
using JetBrains.Annotations;

/// <inheritdoc cref="IDockerRegistryAuthenticationProvider" />
[PublicAPI]
internal sealed class NpipeEndpointAuthenticationProvider : DockerEndpointAuthenticationProvider
{
#pragma warning disable S1075

/// <summary>
/// Gets the named pipe Docker Engine endpoint.
/// </summary>
[PublicAPI]
public static Uri DockerEngine { get; }
= new Uri("npipe://./pipe/docker_engine");

#pragma warning restore S1075

/// <inheritdoc />
public override bool IsApplicable()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
namespace DotNet.Testcontainers.Builders
{
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using DotNet.Testcontainers.Configurations;
using JetBrains.Annotations;

/// <inheritdoc cref="IDockerRegistryAuthenticationProvider" />
[PublicAPI]
internal sealed class RootlessUnixEndpointAuthenticationProvider : DockerEndpointAuthenticationProvider
{
private readonly Uri _dockerEngine;

/// <summary>
/// Initializes a new instance of the <see cref="RootlessUnixEndpointAuthenticationProvider" /> class.
/// </summary>
public RootlessUnixEndpointAuthenticationProvider()
: this(GetSocketPathFromEnv(), GetSocketPathFromHomeDir(), GetSocketPathFromRunDir())
{
}

/// <summary>
/// Initializes a new instance of the <see cref="RootlessUnixEndpointAuthenticationProvider" /> class.
/// </summary>
/// <param name="socketPaths">A list of socket paths.</param>
public RootlessUnixEndpointAuthenticationProvider(params string[] socketPaths)
{
_dockerEngine = socketPaths
.Where(File.Exists)
.Select(socketPath => new UriBuilder("unix", socketPath))
.Select(uriBuilder => uriBuilder.Uri)
.FirstOrDefault();
}

/// <inheritdoc />
public override bool IsApplicable()
{
return _dockerEngine != null;
}

/// <inheritdoc />
public override IDockerEndpointAuthenticationConfiguration GetAuthConfig()
{
return new DockerEndpointAuthenticationConfiguration(_dockerEngine);
}

private static string GetSocketPathFromEnv()
{
var xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
return string.Join("/", xdgRuntimeDir, "docker.sock");
}

private static string GetSocketPathFromHomeDir()
{
return string.Join("/", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".docker", "run", "docker.sock");
}

private static string GetSocketPathFromRunDir()
{
ushort uid = 0;

if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
uid = new Darwin().GetUid();
}

if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
uid = new Linux().GetUid();
}

return string.Join("/", string.Empty, "user", uid, "docker.sock");
}

/// <summary>
/// A user identity.
/// </summary>
[PublicAPI]
private interface IUserIdentity
{
/// <summary>
/// Gets the real user ID of the calling process.
/// </summary>
/// <returns>The real user ID of the calling process.</returns>
ushort GetUid();
}

/// <inheritdoc cref="IUserIdentity" />
[PublicAPI]
private sealed class Darwin : IUserIdentity
{
[DllImport("libSystem")]
private static extern ushort getuid();

/// <inheritdoc />
public ushort GetUid()
{
return getuid();
}
}

/// <inheritdoc cref="IUserIdentity" />
[PublicAPI]
private sealed class Linux : IUserIdentity
{
[DllImport("libc")]
private static extern ushort getuid();

/// <inheritdoc />
public ushort GetUid()
{
return getuid();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ namespace DotNet.Testcontainers.Builders
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using DotNet.Testcontainers.Configurations;
using JetBrains.Annotations;

/// <inheritdoc cref="IDockerRegistryAuthenticationProvider" />
[PublicAPI]
internal class TlsEndpointAuthenticationProvider : DockerEndpointAuthenticationProvider
{
protected const string CaCertificateFileName = "ca.pem";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
namespace DotNet.Testcontainers.Builders
namespace DotNet.Testcontainers.Builders
{
using System;
using System.Runtime.InteropServices;
using DotNet.Testcontainers.Configurations;
using JetBrains.Annotations;

/// <inheritdoc cref="IDockerRegistryAuthenticationProvider" />
[PublicAPI]
internal sealed class UnixEndpointAuthenticationProvider : DockerEndpointAuthenticationProvider
{
/// <summary>
/// Gets the Unix socket Docker Engine endpoint.
/// </summary>
[NotNull]
public static Uri DockerEngine { get; }
= new Uri("unix:/var/run/docker.sock");
= new Uri("unix:///var/run/docker.sock");

/// <inheritdoc />
public override bool IsApplicable()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public static class TestcontainersSettings
new EnvironmentEndpointAuthenticationProvider(),
new NpipeEndpointAuthenticationProvider(),
new UnixEndpointAuthenticationProvider(),
new RootlessUnixEndpointAuthenticationProvider(),
}
.Where(authProvider => authProvider.IsApplicable())
.Where(authProvider => authProvider.IsAvailable())
Expand Down
48 changes: 9 additions & 39 deletions src/Testcontainers/Containers/ResourceReaper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ namespace DotNet.Testcontainers.Containers
{
using System;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
Expand Down Expand Up @@ -238,6 +239,7 @@ await ryukInitializedTaskSource.Task
{
await resourceReaper.DisposeAsync()
.ConfigureAwait(false);

throw;
}

Expand Down Expand Up @@ -416,44 +418,6 @@ await Task.Delay(TimeSpan.FromSeconds(RetryTimeoutInSeconds), default)
}
}

private sealed class NamedPipeSocketMount : IMount
{
private const string DockerSocketFilePath = "\\\\.\\pipe\\docker_engine";

static NamedPipeSocketMount()
{
}

private NamedPipeSocketMount()
{
}

public static IMount Instance { get; }
= new NamedPipeSocketMount();

public MountType Type
=> MountType.NamedPipe;

public AccessMode AccessMode
=> AccessMode.ReadWrite;

public string Source
=> TestcontainersSettings.DockerSocketOverride ?? DockerSocketFilePath;

public string Target
=> DockerSocketFilePath;

public Task CreateAsync(CancellationToken ct = default)
{
return Task.CompletedTask;
}

public Task DeleteAsync(CancellationToken ct = default)
{
return Task.CompletedTask;
}
}

private sealed class UnixSocketMount : IMount
{
private const string DockerSocketFilePath = "/var/run/docker.sock";
Expand All @@ -476,7 +440,7 @@ public AccessMode AccessMode
=> AccessMode.ReadOnly;

public string Source
=> TestcontainersSettings.DockerSocketOverride ?? DockerSocketFilePath;
=> TestcontainersSettings.DockerSocketOverride ?? GetSocketPath();

public string Target
=> DockerSocketFilePath;
Expand All @@ -490,6 +454,12 @@ public Task DeleteAsync(CancellationToken ct = default)
{
return Task.CompletedTask;
}

private static string GetSocketPath()
{
var dockerEndpoints = new[] { TestcontainersSettings.OS.DockerEndpointAuthConfig.Endpoint, UnixEndpointAuthenticationProvider.DockerEngine };
return dockerEndpoints.First(dockerEndpoint => "unix".Equals(dockerEndpoint.Scheme, StringComparison.OrdinalIgnoreCase)).AbsolutePath;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public AuthConfigTestData()
Add(new object[] { new TlsEndpointAuthenticationProvider(DockerTlsHostConfiguration).GetAuthConfig(), new Uri(DockerTlsHost) });
Add(new object[] { new EnvironmentEndpointAuthenticationProvider(DockerHostConfiguration).GetAuthConfig(), new Uri(DockerHost) });
Add(new object[] { new NpipeEndpointAuthenticationProvider().GetAuthConfig(), new Uri("npipe://./pipe/docker_engine") });
Add(new object[] { new UnixEndpointAuthenticationProvider().GetAuthConfig(), new Uri("unix:/var/run/docker.sock") });
Add(new object[] { new UnixEndpointAuthenticationProvider().GetAuthConfig(), new Uri("unix:///var/run/docker.sock") });
}
}
}
Expand Down