Skip to content

Commit

Permalink
#115 refactor: use type mappings instead of tag mappings by default
Browse files Browse the repository at this point in the history
+ Added configuration empty tests for serialization
  • Loading branch information
joseantmazonsb committed Mar 5, 2022
1 parent 47a857d commit 2c57052
Show file tree
Hide file tree
Showing 15 changed files with 116 additions and 52 deletions.
4 changes: 2 additions & 2 deletions Linguard/Cli/Commands/AddInterfaceCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ public AddInterfaceCommand(IConfigurationManager configurationManager, ILogger l
public bool? Auto { get; set; } = default;

[CommandOption("onUp", Description = "Commands to execute right after the interface is brought up.")]
public ICollection<Rule>? OnUp { get; set; } = default;
public ISet<Rule>? OnUp { get; set; } = default;

[CommandOption("onDown", Description = "Commands to execute right after the interface is brought down.")]
public ICollection<Rule>? OnDown { get; set; } = default;
public ISet<Rule>? OnDown { get; set; } = default;

[CommandOption("pubkey", Description = "The peer's public key.")]
public string? PublicKey { get; set; } = default;
Expand Down
10 changes: 5 additions & 5 deletions Linguard/Core.Test/InterfaceShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,19 @@ public void CreateValidWireguardConfiguration() {
IPv6Address = IPAddressCidr.Parse("47cc:ec62:b8b4:d4c0:9c90:4c5c:1df5:a13f/64"),
PublicKey = "c892a52a-1fad-4564-af83-641744cd4dc3",
PrivateKey = "16116afc-3068-4ff5-88e0-0662ef57641a",
OnUp = new Rule[] {
OnUp = new HashSet<Rule> {
"/usr/sbin/iptables -I FORWARD -i wg0 -j ACCEPT",
"/usr/sbin/iptables -I FORWARD -o wg0 -j ACCEPT",
"/usr/sbin/iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE"
},
OnDown = new Rule[] {
OnDown = new HashSet<Rule> {
"/usr/sbin/iptables -D FORWARD -i wg0 -j ACCEPT",
"/usr/sbin/iptables -D FORWARD -o wg0 -j ACCEPT",
"/usr/sbin/iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE"
},
Gateway = _system.NetworkInterfaces.First(),
Clients = new[] {
new Client {
Clients = new HashSet<Client> {
new() {
Endpoint = new Uri("vpn.example.com", UriKind.RelativeOrAbsolute),
Name = "peer1",
Nat = true,
Expand All @@ -69,7 +69,7 @@ public void CreateValidWireguardConfiguration() {
AllowedIPs = new HashSet<IPAddressCidr> { IPAddressCidr.Parse("1.1.2.0/24") },
PrimaryDns = new Uri("8.8.8.8", UriKind.RelativeOrAbsolute)
},
new Client {
new() {
Endpoint = new Uri("vpn2.example.com", UriKind.RelativeOrAbsolute),
Name = "peer2",
IPv4Address = IPAddressCidr.Parse("1.1.1.2/30"),
Expand Down
21 changes: 14 additions & 7 deletions Linguard/Core.Test/Mocks/YamlConfigurationSerializerMock.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using Linguard.Core.Configuration;
using System.Collections.Generic;
using Linguard.Core;
using Linguard.Core.Configuration;
using Linguard.Core.Configuration.Serialization;
using Linguard.Core.Drivers.TrafficStorage;
using Linguard.Core.Models.Wireguard;
using YamlDotNet.Serialization.NamingConventions;

namespace Core.Test.Mocks;
Expand All @@ -13,11 +16,15 @@ public static class YamlConfigurationSerializerMock {
.WithTypeConverter<NetworkInterfaceTypeConverterMock>()
.WithTypeConverter<UriTypeConverter>()
.WithTypeConverter<StyleTypeConverter>()
.WithTagMapping<Configuration>("!Configuration")
.WithTagMapping<WireguardConfiguration>("!Wireguard")
.WithTagMapping<LoggingConfiguration>("!Logging")
.WithTagMapping<WebConfiguration>("!Web")
.WithTagMapping<TrafficConfiguration>("!Traffic")
.WithTagMapping<JsonTrafficStorageDriver>("!Json")
.WithTypeMapping<IConfiguration, Configuration>()
.WithTypeMapping<IWireguardConfiguration, WireguardConfiguration>()
.WithTypeMapping<ILoggingConfiguration, LoggingConfiguration>()
.WithTypeMapping<IWebConfiguration, WebConfiguration>()
.WithTypeMapping<ITrafficConfiguration, TrafficConfiguration>()
.WithTypeMapping<ITrafficStorageDriver, JsonTrafficStorageDriver>()
.WithTypeMapping<ISet<Interface>, HashSet<Interface>>()
.WithTypeMapping<ISet<Client>, HashSet<Client>>()
.WithTypeMapping<ISet<IPAddressCidr>, HashSet<IPAddressCidr>>()
.WithTypeMapping<ISet<Rule>, HashSet<Rule>>()
.Build();
}
2 changes: 1 addition & 1 deletion Linguard/Core.Test/WireguardDumpParserShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class WireguardDumpParserShould {
public WireguardDumpParserShould() {
var iface = new Interface {
Name = "wg1",
Clients = new List<Client> {
Clients = new HashSet<Client> {
new() {
PublicKey = "fE/wdxzl0klVp/IR8UcaoGUMjqaWi3jAd7KzHKFS6Ds="
},
Expand Down
65 changes: 48 additions & 17 deletions Linguard/Core.Test/YamlConfigurationSerializerShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ public class YamlConfigurationSerializerShould {

#region Yaml string

const string yaml = @"!Configuration
Wireguard: !Wireguard
const string yaml = @"Wireguard:
Interfaces:
- Gateway: eth0
Port: 0
Expand All @@ -44,27 +43,27 @@ public class YamlConfigurationSerializerShould {
PrimaryDns: ''
SecondaryDns: ''
Endpoint: 192.168.0.1
Id: 00000000-0000-0000-0000-000000000000
Id: 00000000-0000-0000-0000-000000000001
PublicKey:
PrivateKey:
IPv4Address: 1.1.1.3/30
IPv6Address: ''
Name: peer2
Description:
- AllowedIPs: []
- AllowedIPs:
Nat: false
PrimaryDns: ''
SecondaryDns: ''
Endpoint: ''
Id: 00000000-0000-0000-0000-000000000000
Id: 00000000-0000-0000-0000-000000000002
PublicKey:
PrivateKey:
IPv4Address: 1.1.1.4/30
IPv6Address: ''
Name: peer3
Description:
OnUp: []
OnDown: []
OnUp:
OnDown:
PrimaryDns: ''
SecondaryDns: ''
Endpoint: ''
Expand All @@ -81,16 +80,16 @@ public class YamlConfigurationSerializerShould {
PrimaryDns: ''
SecondaryDns: ''
Endpoint: ''
Logging: !Logging
Logging:
Level: Debug
Overwrite: false
Web: !Web
Web:
LoginAttempts: 10
SecretKey: ''
Style: Default
Traffic: !Traffic
Traffic:
Enabled: false
StorageDriver: !Json
StorageDriver:
TimestampFormat: aaa
";
#endregion
Expand Down Expand Up @@ -128,22 +127,29 @@ public void Serialize() {
Name = "wg1",
IPv4Address = IPAddressCidr.Parse("1.1.1.1/24"),
Gateway = new NetworkInterfaceMock("eth0").Object,
Clients = new []{
new Client {
Clients = new HashSet<Client> {
new() {
Endpoint = new Uri("vpn.example.com", UriKind.RelativeOrAbsolute),
Name = "peer1",
IPv4Address = IPAddressCidr.Parse("1.1.1.2/30"),
AllowedIPs = new HashSet<IPAddressCidr> {IPAddressCidr.Parse("1.1.1.0/24"), IPAddressCidr.Parse("1.1.2.0/24")},
AllowedIPs = new HashSet<IPAddressCidr> {
IPAddressCidr.Parse("1.1.1.0/24"), IPAddressCidr.Parse("1.1.2.0/24")
},
Id = Guid.Parse("00000000-0000-0000-0000-000000000000")
},
new Client {
new() {
Endpoint = new Uri("192.168.0.1", UriKind.RelativeOrAbsolute),
Name = "peer2",
IPv4Address = IPAddressCidr.Parse("1.1.1.3/30"),
AllowedIPs = new HashSet<IPAddressCidr> {IPAddressCidr.Parse("1.1.1.0/24"), IPAddressCidr.Parse("1.1.2.0/24")}
AllowedIPs = new HashSet<IPAddressCidr> {
IPAddressCidr.Parse("1.1.1.0/24"), IPAddressCidr.Parse("1.1.2.0/24")
},
Id = Guid.Parse("00000000-0000-0000-0000-000000000001")
},
new Client {
new() {
Name = "peer3",
IPv4Address = IPAddressCidr.Parse("1.1.1.4/30"),
Id = Guid.Parse("00000000-0000-0000-0000-000000000002")
}
}
}},
Expand All @@ -156,4 +162,29 @@ public void Serialize() {
var output = serializer.Serialize(config);
output.Trim().Should().Be(yaml.Trim());
}

[Fact]
public void SerializeEmpty() {
const string yaml = @"Wireguard:
Logging:
Web:
Traffic:
";
var serializer = YamlConfigurationSerializerMock.Instance;
var output = serializer.Serialize(new Configuration());
output.Should().Be(yaml);
}

[Fact]
public void DeserializeEmpty() {
const string yaml = @"Wireguard:
Logging:
Web:
Traffic:
";
var serializer = YamlConfigurationSerializerMock.Instance;
var output = serializer.Deserialize(yaml);
var config = new Configuration();
output.Should().Be(config);
}
}
26 changes: 22 additions & 4 deletions Linguard/Core/Configuration/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,30 @@
namespace Linguard.Core.Configuration;

public class Configuration : IConfiguration {
public IWireguardConfiguration Wireguard { get; set; } = new WireguardConfiguration();
public ILoggingConfiguration Logging { get; set; } = new LoggingConfiguration();
public IWebConfiguration Web { get; set; } = new WebConfiguration();
public ITrafficConfiguration Traffic { get; set; } = new TrafficConfiguration();
public IWireguardConfiguration? Wireguard { get; set; }
public ILoggingConfiguration? Logging { get; set; }
public IWebConfiguration? Web { get; set; }
public ITrafficConfiguration? Traffic { get; set; }

public object Clone() {
return Cloning.Clone(this);
}

protected bool Equals(Configuration other) {
return Equals(Wireguard, other.Wireguard)
&& Equals(Logging, other.Logging)
&& Equals(Web, other.Web)
&& Equals(Traffic, other.Traffic);
}

public override bool Equals(object? obj) {
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Configuration)obj);
}

public override int GetHashCode() {
return HashCode.Combine(Wireguard, Logging, Web, Traffic);
}
}
2 changes: 1 addition & 1 deletion Linguard/Core/Configuration/IWireguardConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Linguard.Core.Configuration;

public interface IWireguardConfiguration : ICloneable {
public HashSet<Interface> Interfaces { get; set; }
public ISet<Interface> Interfaces { get; set; }
/// <summary>
/// Path to the <c>iptables</c> binary file.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Linguard.Core.Drivers.TrafficStorage;
using Linguard.Core.Models.Wireguard;
using YamlDotNet.Serialization.NamingConventions;

namespace Linguard.Core.Configuration.Serialization;
Expand All @@ -11,11 +12,15 @@ public static class DefaultYamlConfigurationSerializer {
.WithTypeConverter<NetworkInterfaceTypeConverter>()
.WithTypeConverter<UriTypeConverter>()
.WithTypeConverter<StyleTypeConverter>()
.WithTagMapping<Configuration>("!Configuration")
.WithTagMapping<WireguardConfiguration>("!Wireguard")
.WithTagMapping<LoggingConfiguration>("!Logging")
.WithTagMapping<WebConfiguration>("!Web")
.WithTagMapping<TrafficConfiguration>("!Traffic")
.WithTagMapping<JsonTrafficStorageDriver>("!Json")
.WithTypeMapping<IConfiguration, Configuration>()
.WithTypeMapping<IWireguardConfiguration, WireguardConfiguration>()
.WithTypeMapping<ILoggingConfiguration, LoggingConfiguration>()
.WithTypeMapping<IWebConfiguration, WebConfiguration>()
.WithTypeMapping<ITrafficConfiguration, TrafficConfiguration>()
.WithTypeMapping<ITrafficStorageDriver, JsonTrafficStorageDriver>()
.WithTypeMapping<ISet<Interface>, HashSet<Interface>>()
.WithTypeMapping<ISet<Client>, HashSet<Client>>()
.WithTypeMapping<ISet<IPAddressCidr>, HashSet<IPAddressCidr>>()
.WithTypeMapping<ISet<Rule>, HashSet<Rule>>()
.Build();
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ public YamlConfigurationSerializerBuilder WithTypeConverter<T>() where T : IYaml
return WithTypeConverter(Activator.CreateInstance<T>());
}

public YamlConfigurationSerializerBuilder WithTypeMapping<TFrom, TTo>() where TTo : TFrom {
_deserializerBuilder.WithTypeMapping<TFrom, TTo>();
return this;
}

public YamlConfigurationSerializer Build() {
return new YamlConfigurationSerializer(_serializerBuilder.Build(), _deserializerBuilder.Build());
}
Expand Down
2 changes: 1 addition & 1 deletion Linguard/Core/Configuration/WireguardConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Linguard.Core.Configuration;

public class WireguardConfiguration : IWireguardConfiguration {
public HashSet<Interface> Interfaces { get; set; }
public ISet<Interface> Interfaces { get; set; }
public string IptablesBin { get; set; }
public string WireguardBin { get; set; }
public string WireguardQuickBin { get; set; }
Expand Down
3 changes: 1 addition & 2 deletions Linguard/Core/Managers/ConfigurationManagerBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,13 @@ private void LoadTrafficDefaults() {
Configuration.Traffic.StorageDriver = new JsonTrafficStorageDriver();
}
private void LoadWireguardDefaults() {
Configuration.Wireguard.Interfaces = new HashSet<Interface>();
Configuration.Wireguard.IptablesBin = _systemWrapper
.RunCommand("whereis iptables | tr ' ' '\n' | grep bin").Stdout;
Configuration.Wireguard.WireguardBin = _systemWrapper
.RunCommand("whereis wg | tr ' ' '\n' | grep bin").Stdout;
Configuration.Wireguard.WireguardQuickBin = _systemWrapper
.RunCommand("whereis wg-quick | tr ' ' '\n' | grep bin").Stdout;
Configuration.Wireguard.Interfaces = new();
Configuration.Wireguard.Interfaces = new HashSet<Interface>();
Configuration.Wireguard.PrimaryDns = new("8.8.8.8", UriKind.RelativeOrAbsolute);
Configuration.Wireguard.SecondaryDns = new("8.8.4.4", UriKind.RelativeOrAbsolute);
var publicIp = Network.GetPublicIPAddress();
Expand Down
1 change: 0 additions & 1 deletion Linguard/Core/Managers/FileConfigurationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ public override void Load() {
$"Configuration file '{ConfigurationFile.FullName}' does not exist."
);
}

try {
Configuration = Serializer.Deserialize(File.ReadAllText(ConfigurationFile.FullName));
}
Expand Down
2 changes: 1 addition & 1 deletion Linguard/Core/Models/Wireguard/Client.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
namespace Linguard.Core.Models.Wireguard;

public class Client : WireguardPeerBase, ICloneable {
public HashSet<IPAddressCidr> AllowedIPs { get; set; } = new();
public ISet<IPAddressCidr> AllowedIPs { get; set; }
public bool Nat { get; set; }
public Uri PrimaryDns { get; set; }
public Uri? SecondaryDns { get; set; }
Expand Down
6 changes: 3 additions & 3 deletions Linguard/Core/Models/Wireguard/Interface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ public class Interface : WireguardPeerBase, ICloneable {
public NetworkInterface Gateway { get; set; }
public int Port { get; set; }
public bool Auto { get; set; }
public ICollection<Client> Clients { get; set; } = new List<Client>();
public ICollection<Rule> OnUp { get; set; } = new List<Rule>();
public ICollection<Rule> OnDown { get; set; } = new List<Rule>();
public ISet<Client> Clients { get; set; }
public ISet<Rule> OnUp { get; set; }
public ISet<Rule> OnDown { get; set; }
/// <summary>
/// Default primary DNS for all peers if none specified.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion Linguard/Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
builder.Services.AddTransient<IWorkingDirectory, WorkingDirectory>();
builder.Services.AddSingleton<IConfigurationSerializer>(DefaultYamlConfigurationSerializer.Instance);
builder.Services.AddTransient<ILogger, NLogLogger>();
builder.Services.AddTransient<ISystemWrapper, Linguard.Core.OS.SystemWrapper>();
builder.Services.AddTransient<ISystemWrapper, SystemWrapper>();
builder.Services.AddTransient<IWireguardService, WireguardService>();
builder.Services.AddTransient<IInterfaceGenerator, DefaultInterfaceGenerator>();
builder.Services.AddTransient<IClientGenerator, DefaultClientGenerator>();
Expand Down

0 comments on commit 2c57052

Please sign in to comment.