Skip to content

chore: add Vpn.Service app for Manager #9

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

Merged
merged 3 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
26 changes: 25 additions & 1 deletion Coder.Desktop.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Coder.Desktop.Vpn", "Vpn\Vp
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Coder.Desktop.Vpn.Proto", "Vpn.Proto\Vpn.Proto.csproj", "{318E78BB-E6AD-410F-8F3F-B680F6880293}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Coder.Desktop.Tests", "Tests\Tests.csproj", "{D247B2E7-38A0-4A69-A710-7E8FAA7B807E}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Coder.Desktop.Vpn.Service", "Vpn.Service\Vpn.Service.csproj", "{51B91794-0A2A-4F84-9935-8E17DD2AB260}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Coder.Desktop.Tests.Vpn", "Tests.Vpn\Tests.Vpn.csproj", "{D247B2E7-38A0-4A69-A710-7E8FAA7B807E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Coder.Desktop.Tests.Vpn.Proto", "Tests.Vpn.Proto\Tests.Vpn.Proto.csproj", "{AA3EEFF4-414B-4A83-8ACF-188C3C61CCE1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Coder.Desktop.Tests.Vpn.Service", "Tests.Vpn.Service\Tests.Vpn.Service.csproj", "{D32E5FE1-C251-4A08-8EBE-B8D4F18A36F1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Coder.Desktop.CoderSdk", "CoderSdk\CoderSdk.csproj", "{A3D2B2B3-A051-46BD-A190-5487A9F24C28}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -21,9 +29,25 @@ Global
{318E78BB-E6AD-410F-8F3F-B680F6880293}.Debug|Any CPU.Build.0 = Debug|Any CPU
{318E78BB-E6AD-410F-8F3F-B680F6880293}.Release|Any CPU.ActiveCfg = Release|Any CPU
{318E78BB-E6AD-410F-8F3F-B680F6880293}.Release|Any CPU.Build.0 = Release|Any CPU
{51B91794-0A2A-4F84-9935-8E17DD2AB260}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{51B91794-0A2A-4F84-9935-8E17DD2AB260}.Debug|Any CPU.Build.0 = Debug|Any CPU
{51B91794-0A2A-4F84-9935-8E17DD2AB260}.Release|Any CPU.ActiveCfg = Release|Any CPU
{51B91794-0A2A-4F84-9935-8E17DD2AB260}.Release|Any CPU.Build.0 = Release|Any CPU
{D247B2E7-38A0-4A69-A710-7E8FAA7B807E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D247B2E7-38A0-4A69-A710-7E8FAA7B807E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D247B2E7-38A0-4A69-A710-7E8FAA7B807E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D247B2E7-38A0-4A69-A710-7E8FAA7B807E}.Release|Any CPU.Build.0 = Release|Any CPU
{AA3EEFF4-414B-4A83-8ACF-188C3C61CCE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AA3EEFF4-414B-4A83-8ACF-188C3C61CCE1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AA3EEFF4-414B-4A83-8ACF-188C3C61CCE1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AA3EEFF4-414B-4A83-8ACF-188C3C61CCE1}.Release|Any CPU.Build.0 = Release|Any CPU
{D32E5FE1-C251-4A08-8EBE-B8D4F18A36F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D32E5FE1-C251-4A08-8EBE-B8D4F18A36F1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D32E5FE1-C251-4A08-8EBE-B8D4F18A36F1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D32E5FE1-C251-4A08-8EBE-B8D4F18A36F1}.Release|Any CPU.Build.0 = Release|Any CPU
{A3D2B2B3-A051-46BD-A190-5487A9F24C28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A3D2B2B3-A051-46BD-A190-5487A9F24C28}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A3D2B2B3-A051-46BD-A190-5487A9F24C28}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A3D2B2B3-A051-46BD-A190-5487A9F24C28}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
2 changes: 2 additions & 0 deletions Coder.Desktop.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -253,4 +253,6 @@
</Patterns>
</s:String>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002EMemberReordering_002EMigrations_002ECSharpFileLayoutPatternRemoveIsAttributeUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=codervpn/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=hkey/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=serdes/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
81 changes: 81 additions & 0 deletions CoderSdk/CoderApiClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace CoderSdk;

/// <summary>
/// Changes names from PascalCase to snake_case.
/// </summary>
internal class SnakeCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
return string.Concat(
name.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + char.ToLower(x) : char.ToLower(x).ToString())
);
}
}

/// <summary>
/// Provides a limited selection of API methods for a Coder instance.
/// </summary>
public partial class CoderApiClient
{
// TODO: allow adding headers
private readonly HttpClient _httpClient = new();
private readonly JsonSerializerOptions _jsonOptions;

public CoderApiClient(string baseUrl)
{
var url = new Uri(baseUrl, UriKind.Absolute);
if (url.PathAndQuery != "/")
throw new ArgumentException($"Base URL '{baseUrl}' must not contain a path", nameof(baseUrl));
_httpClient.BaseAddress = url;
_jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = new SnakeCaseNamingPolicy(),
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
}

public CoderApiClient(string baseUrl, string token) : this(baseUrl)
{
SetSessionToken(token);
}

public void SetSessionToken(string token)
{
_httpClient.DefaultRequestHeaders.Remove("Coder-Session-Token");
_httpClient.DefaultRequestHeaders.Add("Coder-Session-Token", token);
}

private async Task<TResponse> SendRequestAsync<TResponse>(HttpMethod method, string path,
object? payload, CancellationToken ct = default)
{
try
{
var request = new HttpRequestMessage(method, path);

if (payload is not null)
{
var json = JsonSerializer.Serialize(payload, _jsonOptions);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
}

var res = await _httpClient.SendAsync(request, ct);
// TODO: this should be improved to try and parse a codersdk.Error response
res.EnsureSuccessStatusCode();

var content = await res.Content.ReadAsStringAsync(ct);
var data = JsonSerializer.Deserialize<TResponse>(content, _jsonOptions);
if (data is null) throw new JsonException("Deserialized response is null");
return data;
}
catch (Exception e)
{
throw new Exception($"API Request: {method} {path} (req body: {payload is not null})", e);
}
}
}
9 changes: 9 additions & 0 deletions CoderSdk/CoderSdk.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
22 changes: 22 additions & 0 deletions CoderSdk/Deployment.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace CoderSdk;

public class BuildInfo
{
public string ExternalUrl { get; set; } = "";
public string Version { get; set; } = "";
public string DashboardUrl { get; set; } = "";
public bool Telemetry { get; set; } = false;
public bool WorkspaceProxy { get; set; } = false;
public string AgentApiVersion { get; set; } = "";
public string ProvisionerApiVersion { get; set; } = "";
public string UpgradeMessage { get; set; } = "";
public string DeploymentId { get; set; } = "";
}

public partial class CoderApiClient
{
public Task<BuildInfo> GetBuildInfo(CancellationToken ct = default)
{
return SendRequestAsync<BuildInfo>(HttpMethod.Get, "/api/v2/buildinfo", null, ct);
}
}
17 changes: 17 additions & 0 deletions CoderSdk/Users.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace CoderSdk;

public class User
{
public const string Me = "me";

// TODO: fill out more fields
public string Username { get; set; } = "";
}

public partial class CoderApiClient
{
public Task<User> GetUser(string user, CancellationToken ct = default)
{
return SendRequestAsync<User>(HttpMethod.Get, $"/api/v2/users/{user}", null, ct);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ public void Valid()
{
var headerStr = "codervpn manager 1.3,2.1";
var header = RpcHeader.Parse(headerStr);
Assert.That(header.Role.ToString(), Is.EqualTo(RpcRole.Manager));
Assert.That(header.Role, Is.EqualTo("manager"));
Assert.That(header.VersionList, Is.EqualTo(new RpcVersionList(new RpcVersion(1, 3), new RpcVersion(2, 1))));
Assert.That(header.ToString(), Is.EqualTo(headerStr + "\n"));
Assert.That(header.ToBytes().ToArray(), Is.EqualTo(Encoding.UTF8.GetBytes(headerStr + "\n")));

headerStr = "codervpn tunnel 1.0";
header = RpcHeader.Parse(headerStr);
Assert.That(header.Role.ToString(), Is.EqualTo(RpcRole.Tunnel));
Assert.That(header.Role, Is.EqualTo("tunnel"));
Assert.That(header.VersionList, Is.EqualTo(new RpcVersionList(new RpcVersion(1, 0))));
Assert.That(header.ToString(), Is.EqualTo(headerStr + "\n"));
Assert.That(header.ToBytes().ToArray(), Is.EqualTo(Encoding.UTF8.GetBytes(headerStr + "\n")));
Expand All @@ -35,7 +35,8 @@ public void ParseInvalid()
Assert.That(ex.Message, Does.Contain("Wrong number of parts"));
ex = Assert.Throws<ArgumentException>(() => RpcHeader.Parse("cats manager 1.0"));
Assert.That(ex.Message, Does.Contain("Invalid preamble"));
ex = Assert.Throws<ArgumentException>(() => RpcHeader.Parse("codervpn cats 1.0"));
Assert.That(ex.Message, Does.Contain("Unknown role 'cats'"));
// RpcHeader doesn't care about the role string as long as it isn't empty.
ex = Assert.Throws<ArgumentException>(() => RpcHeader.Parse("codervpn 1.0"));
Assert.That(ex.Message, Does.Contain("Invalid role in header string"));
}
}
39 changes: 39 additions & 0 deletions Tests.Vpn.Proto/RpcMessageTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Coder.Desktop.Vpn.Proto;

namespace Coder.Desktop.Tests.Vpn.Proto;

[TestFixture]
public class RpcRoleAttributeTest
{
[Test]
public void Ok()
{
var role = new RpcRoleAttribute("manager");
Assert.That(role.Role, Is.EqualTo("manager"));
role = new RpcRoleAttribute("tunnel");
Assert.That(role.Role, Is.EqualTo("tunnel"));
role = new RpcRoleAttribute("service");
Assert.That(role.Role, Is.EqualTo("service"));
role = new RpcRoleAttribute("client");
Assert.That(role.Role, Is.EqualTo("client"));
}
}

[TestFixture]
public class RpcMessageTest
{
[Test]
public void GetRole()
{
// RpcMessage<RPC> is not a supported message type and doesn't have an
// RpcRoleAttribute
var ex = Assert.Throws<ArgumentException>(() => _ = RpcMessage<RPC>.GetRole());
Assert.That(ex.Message,
Does.Contain("Message type 'Coder.Desktop.Vpn.Proto.RPC' does not have a RpcRoleAttribute"));

Assert.That(ManagerMessage.GetRole(), Is.EqualTo("manager"));
Assert.That(TunnelMessage.GetRole(), Is.EqualTo("tunnel"));
Assert.That(ServiceMessage.GetRole(), Is.EqualTo("service"));
Assert.That(ClientMessage.GetRole(), Is.EqualTo("client"));
}
}
File renamed without changes.
35 changes: 35 additions & 0 deletions Tests.Vpn.Proto/Tests.Vpn.Proto.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<RootNamespace>Coder.Desktop.Tests.Vpn.Proto</RootNamespace>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0"/>
<PackageReference Include="NUnit" Version="4.2.2"/>
<PackageReference Include="NUnit.Analyzers" Version="4.4.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0"/>
</ItemGroup>

<ItemGroup>
<Using Include="NUnit.Framework"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Vpn.Proto\Vpn.Proto.csproj"/>
</ItemGroup>

</Project>
Loading