Skip to content

Commit

Permalink
#115 ignore files and add clients creation
Browse files Browse the repository at this point in the history
  • Loading branch information
joseantmazonsb committed Feb 23, 2022
1 parent dadadf0 commit bdac7a2
Show file tree
Hide file tree
Showing 2,400 changed files with 1,072 additions and 100,474 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@

namespace Cli.Test;

public class AddPeerCommandShould {
public class AddClientCommandShould {

private static readonly Mock<IWireguardService> WireguardServiceMock = new();

[Fact]
public async Task CreateRandomPeer() {
public async Task CreateRandomClient() {
var command = typeof(AddClientCommand);
var commandName = command.GetAttribute<CommandAttribute>().Name!;
var app = Utils.BuildTestApp(command);
Expand All @@ -34,7 +34,7 @@ public async Task CreateRandomPeer() {
}

[Fact]
public async Task CreatePeerWithName() {
public async Task CreateClientWithName() {
var command = typeof(AddClientCommand);
var commandName = command.GetAttribute<CommandAttribute>().Name!;
var app = Utils.BuildTestApp(command);
Expand All @@ -52,7 +52,7 @@ public async Task CreatePeerWithName() {
}

[Fact]
public async Task CreatePeerWithEndpoint() {
public async Task CreateClientWithEndpoint() {
var command = typeof(AddClientCommand);
var commandName = command.GetAttribute<CommandAttribute>().Name!;
var app = Utils.BuildTestApp(command);
Expand All @@ -70,7 +70,7 @@ public async Task CreatePeerWithEndpoint() {
}

[Fact]
public async Task CreatePeerWithIPs() {
public async Task CreateClientWithIPs() {
var command = typeof(AddClientCommand);
var commandName = command.GetAttribute<CommandAttribute>().Name!;
var app = Utils.BuildTestApp(command);
Expand All @@ -86,13 +86,13 @@ public async Task CreatePeerWithIPs() {
var errors = app.Error.GetString();
errors.Should().BeEmpty();
iface.Clients.Should().NotBeEmpty();
var peer = iface.Clients.First();
peer.IPv6Address!.ToString().Should().Be(ipv6);
peer.IPv4Address!.ToString().Should().Be(ipv4);
var client = iface.Clients.First();
client.IPv6Address!.ToString().Should().Be(ipv6);
client.IPv4Address!.ToString().Should().Be(ipv4);
}

[Fact]
public async Task CreatePeerWithDns() {
public async Task CreateClientWithDns() {
var command = typeof(AddClientCommand);
var commandName = command.GetAttribute<CommandAttribute>().Name!;
var app = Utils.BuildTestApp(command);
Expand All @@ -106,13 +106,13 @@ public async Task CreatePeerWithDns() {
var errors = app.Error.GetString();
errors.Should().BeEmpty();
iface.Clients.Should().NotBeEmpty();
var peer = iface.Clients.First();
peer.PrimaryDns.ToString().Should().Be(dns);
peer.SecondaryDns.Should().NotBeNull();
var client = iface.Clients.First();
client.PrimaryDns.ToString().Should().Be(dns);
client.SecondaryDns.Should().NotBeNull();
}

[Fact]
public async Task CreatePeerWithTwoDns() {
public async Task CreateClientWithTwoDns() {
var command = typeof(AddClientCommand);
var commandName = command.GetAttribute<CommandAttribute>().Name!;
var app = Utils.BuildTestApp(command);
Expand All @@ -127,13 +127,13 @@ public async Task CreatePeerWithTwoDns() {
var errors = app.Error.GetString();
errors.Should().BeEmpty();
iface.Clients.Should().NotBeEmpty();
var peer = iface.Clients.First();
peer.PrimaryDns.ToString().Should().Be(dns1);
peer.SecondaryDns!.ToString().Should().Be(dns2);
var client = iface.Clients.First();
client.PrimaryDns.ToString().Should().Be(dns1);
client.SecondaryDns!.ToString().Should().Be(dns2);
}

[Fact]
public async Task CreatePeerWithAllowedIPs() {
public async Task CreateClientWithAllowedIPs() {
var command = typeof(AddClientCommand);
var commandName = command.GetAttribute<CommandAttribute>().Name!;
var app = Utils.BuildTestApp(command);
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

namespace Cli.Test;

public class ListPeersCommandShould {
public class ListClientsCommandShould {

private static readonly Mock<IWireguardService> WireguardServiceMock = new();

Expand All @@ -23,7 +23,7 @@ public async Task ListOnePeer() {
var app = Utils.BuildTestApp(command);
var iface = GenerateInterface(app.ConfigurationManager);
app.ConfigurationManager.Configuration.Wireguard.Interfaces.Add(iface);
var peer = GeneratePeer(iface);
var peer = GeneratePeer(app.ConfigurationManager, iface);
iface.Clients.Add(peer);

var commandLine = $"{commandName}";
Expand All @@ -46,9 +46,9 @@ public async Task ListPeersForSpecificInterface() {
app.ConfigurationManager.Configuration.Wireguard.Interfaces.Add(iface1);
var iface2 = GenerateInterface(app.ConfigurationManager);
app.ConfigurationManager.Configuration.Wireguard.Interfaces.Add(iface2);
var peer = GeneratePeer(iface1);
var peer = GeneratePeer(app.ConfigurationManager, iface1);
iface1.Clients.Add(peer);
iface2.Clients.Add(GeneratePeer(iface2));
iface2.Clients.Add(GeneratePeer(app.ConfigurationManager, iface2));

var commandLine = $"{commandName} --interface {iface1.Name}";

Expand All @@ -64,7 +64,7 @@ private Interface GenerateInterface(IConfigurationManager configuration) {
return new DefaultInterfaceGenerator(configuration, WireguardServiceMock.Object).Generate();
}

private Client GeneratePeer(Interface iface) {
return new DefaultClientGenerator(WireguardServiceMock.Object).Generate(iface);
private Client GeneratePeer(IConfigurationManager configuration, Interface iface) {
return new DefaultClientGenerator(WireguardServiceMock.Object, configuration).Generate(iface);
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,15 @@ public ValueTask ExecuteAsync(IConsole console) {
console.Error.WriteLine(Validation.InterfaceNotFound);
return ValueTask.CompletedTask;
}
var peer = _generator.Generate(iface);
ApplyParametersSetByUser(peer);
if (!Validate(peer, console)) {
var client = _generator.Generate(iface);
ApplyParametersSetByUser(client);
if (!Validate(client, console)) {
return ValueTask.CompletedTask;
}

iface.Clients.Add(peer);
iface.Clients.Add(client);
_configurationManager.Save();
var msg = $"Added peer '{peer.Name}' to interface '{iface.Name}'.";
var msg = $"Added peer '{client.Name}' to interface '{iface.Name}'.";
_logger.Info(msg);
console.Output.WriteLine(msg);
return ValueTask.CompletedTask;
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class DefaultClientGeneratorShould {
private static IInterfaceGenerator InterfaceGenerator =>
new DefaultInterfaceGenerator(ConfigurationManagerMock.Object, WireguardServiceMock.Object);
private static IClientGenerator ClientGenerator =>
new DefaultClientGenerator(WireguardServiceMock.Object);
new DefaultClientGenerator(WireguardServiceMock.Object, ConfigurationManagerMock.Object);
private static AbstractValidator<Client> Validator => new ClientValidator(ConfigurationManagerMock.Object);

[Fact]
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Linguard.Core.Configuration;

public class LoggingConfiguration : ILoggingConfiguration{
public LogLevel Level { get; set; } = LogLevel.Info;
public LogLevel Level { get; set; }
public bool Overwrite { get; set; }

public object Clone() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
namespace Linguard.Core.Configuration;

public class TrafficConfiguration : ITrafficConfiguration {
public bool Enabled { get; set; } = true;
public ITrafficStorageDriver StorageDriver { get; set; } = new JsonTrafficStorageDriver();
public bool Enabled { get; set; }
public ITrafficStorageDriver StorageDriver { get; set; }
public object Clone() {
return MemberwiseClone();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
namespace Linguard.Core.Configuration;

public class WebConfiguration : IWebConfiguration {
public int LoginAttempts { get; set; } = 10;
public string SecretKey { get; set; } = string.Empty;
public int LoginAttempts { get; set; }
public string SecretKey { get; set; }
public Style Style { get; set; }

public object Clone() {
Expand Down
17 changes: 17 additions & 0 deletions Linguard/Core/Configuration/WireguardConfiguration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Linguard.Core.Models.Wireguard;

namespace Linguard.Core.Configuration;

public class WireguardConfiguration : IWireguardConfiguration {
public HashSet<Interface> Interfaces { get; set; }
public string IptablesBin { get; set; }
public string WireguardBin { get; set; }
public string WireguardQuickBin { get; set; }
public Uri? PrimaryDns { get; set; }
public Uri? SecondaryDns { get; set; }
public Uri? Endpoint { get; set; }

public object Clone() {
return MemberwiseClone();
}
}
File renamed without changes.
File renamed without changes.
71 changes: 71 additions & 0 deletions Linguard/Core/Managers/YamlConfigurationManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System.Net;
using Linguard.Core.Configuration;
using Linguard.Core.Configuration.Serialization;
using Linguard.Core.Drivers.TrafficStorage;
using Linguard.Core.Models;
using Linguard.Core.Models.Wireguard;
using Linguard.Core.OS;
using Linguard.Core.Utils;
using Linguard.Log;

namespace Linguard.Core.Managers;

public class YamlConfigurationManager : FileConfigurationManager {
private static readonly string[] SupportedExtensions = {"yaml", "yml"};

private FileInfo? _configurationFile;
protected sealed override FileInfo ConfigurationFile {
get {
if (_configurationFile != default) return _configurationFile;
var filename = Path.Combine(WorkingDirectory.BaseDirectory.FullName, AssemblyInfo.Product.ToLower());
var tries = 0;
while (tries < SupportedExtensions.Length && _configurationFile is not { Exists: true }) {
var filepath = Path.ChangeExtension(filename, SupportedExtensions[tries]);
_configurationFile = new FileInfo(filepath);
tries++;
}
return _configurationFile!;
}
}

public override async void LoadDefaults() {
LoadWebDefaults();
LoadLoggingDefaults();
LoadTrafficDefaults();
await LoadWireguardDefaults();
}

private void LoadWebDefaults() {
Configuration.Web.Style = Style.Default;
Configuration.Web.LoginAttempts = 10;
Configuration.Web.SecretKey = "";
}
private void LoadLoggingDefaults() {
Configuration.Logging.Level = LogLevel.Info;
Configuration.Logging.Overwrite = false;
}
private void LoadTrafficDefaults() {
Configuration.Traffic.Enabled = true;
Configuration.Traffic.StorageDriver = new JsonTrafficStorageDriver();
}
private async Task LoadWireguardDefaults() {
Configuration.Wireguard.Interfaces = new HashSet<Interface>();
Configuration.Wireguard.IptablesBin = new CommandRunner()
.Run("whereis iptables | tr ' ' '\n' | grep bin").Stdout;
Configuration.Wireguard.WireguardBin = new CommandRunner()
.Run("whereis wg | tr ' ' '\n' | grep bin").Stdout;
Configuration.Wireguard.WireguardQuickBin = new CommandRunner()
.Run("whereis wg-quick | tr ' ' '\n' | grep bin").Stdout;
Configuration.Wireguard.Interfaces = new();
Configuration.Wireguard.PrimaryDns = new("8.8.8.8", UriKind.RelativeOrAbsolute);
Configuration.Wireguard.SecondaryDns = new("8.8.4.4", UriKind.RelativeOrAbsolute);
var publicIp = Network.GetPublicIPAddress();
Configuration.Wireguard.Endpoint = publicIp == default
? default
: new(publicIp.ToString(), UriKind.RelativeOrAbsolute);
}

public YamlConfigurationManager(IConfiguration configuration, IWorkingDirectory workingDirectory)
: base(configuration, workingDirectory, new YamlConfigurationSerializer()) {
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
using System.Net;
using Bogus;
using Linguard.Core.Configuration;
using Linguard.Core.Managers;
using Linguard.Core.Models.Wireguard;
using Linguard.Core.Utils;

namespace Linguard.Core.Services;

public class DefaultClientGenerator : IClientGenerator {
private IWireguardConfiguration Configuration => _configurationManager.Configuration.Wireguard;
private readonly IConfigurationManager _configurationManager;
private readonly IWireguardService _wireguard;

public DefaultClientGenerator(IWireguardService wireguard) {
public DefaultClientGenerator(IWireguardService wireguard, IConfigurationManager configurationManager) {
_wireguard = wireguard;
_configurationManager = configurationManager;
}

public Client Generate(Interface iface) {
return new Faker<Client>()
.RuleFor(c => c.Nat, false)
.RuleFor(c => c.Description, f => f.Lorem.Sentence())
.RuleFor(c => c.PrimaryDns, new Uri("8.8.8.8", UriKind.RelativeOrAbsolute))
.RuleFor(c => c.SecondaryDns, new Uri("8.8.4.4", UriKind.RelativeOrAbsolute))
.RuleFor(c => c.Name, f => f.Person.FullName)
.RuleFor(c => c.Endpoint, new Uri("vpn.example.com", UriKind.RelativeOrAbsolute))
.RuleFor(c => c.PrivateKey, _wireguard.GenerateWireguardPrivateKey())
Expand All @@ -40,6 +44,16 @@ public Client Generate(Interface iface) {
if (p.IPv6Address != default) ips.Add(IPAddressCidr.Parse("::0/0"));
return ips;
})
.RuleFor(c => c.Endpoint, iface.Endpoint
?? Configuration.Endpoint
?? new(Network.GetPublicIPAddress()?.ToString() ?? string.Empty,
UriKind.RelativeOrAbsolute))
.RuleFor(c => c.PrimaryDns, iface.PrimaryDns
?? Configuration.PrimaryDns
?? new Uri("8.8.8.8", UriKind.RelativeOrAbsolute))
.RuleFor(c => c.SecondaryDns, iface.SecondaryDns
?? Configuration.SecondaryDns
?? new Uri("8.8.4.4", UriKind.RelativeOrAbsolute))
.Generate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ public Interface Generate() {
}
return default;
})
.RuleFor(i => i.Endpoint, Configuration.Endpoint)
.RuleFor(i => i.PrimaryDns, Configuration.PrimaryDns)
.RuleFor(i => i.SecondaryDns, Configuration.SecondaryDns)
.Generate();
}
}
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ public interface IWireguardService {
string GenerateWireguardConfiguration(IWireguardPeer peer);
DateTime GetLastHandshake(Client client);
IEnumerable<TrafficData> GetTrafficData();
IEnumerable<TrafficData> GetTrafficData(Client client);
IEnumerable<TrafficData> GetTrafficData(Interface iface);
TrafficData? GetTrafficData(Client client);
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,11 @@ public IEnumerable<TrafficData> GetTrafficData() {
return data;
}

public IEnumerable<TrafficData> GetTrafficData(Client client) {
public TrafficData? GetTrafficData(Client client) {
var data = GetTrafficData(GetInterface(client));
return data.Where(e => e.Peer is not Interface);
return data.SingleOrDefault(e => e.Peer.Equals(client));
}

public IEnumerable<TrafficData> GetTrafficData(Interface iface) {
var rawData = _commandRunner
.Run($"{Configuration.WireguardBin} show {iface.Name} dump")
Expand Down
File renamed without changes.
14 changes: 14 additions & 0 deletions Linguard/Core/Utils/Network.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Net;

namespace Linguard.Core.Utils;

public static class Network {
public static IPAddress? GetPublicIPAddress() {
const string url = "https://api.ipify.org/";
var response = new HttpClient()
.Send(new HttpRequestMessage(HttpMethod.Get, url))
.Content
.ReadAsStringAsync().Result;
return IPAddress.TryParse(response, out var ipAddress) ? ipAddress : default;
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit bdac7a2

Please sign in to comment.