Skip to content
Closed
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
3 changes: 2 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@
**/Dockerfile.develop
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
**/values.dev.yaml
**/tests
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
bin
obj
.vs
*.user
*.user
.idea/
7 changes: 5 additions & 2 deletions ConplementAG.CopsController.csproj
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<RootNamespace>ConplementAG.CopsController</RootNamespace>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<UserSecretsId>dc526bff-7bba-4e39-adab-3033979b7f98</UserSecretsId>
<!-- tests/ contains the xunit project; without this exclude the Web SDK would glob its *.cs files into this assembly -->
<DefaultItemExcludes>$(DefaultItemExcludes);tests/**</DefaultItemExcludes>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="KubernetesClient" Version="21.0.41" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="10.0.12" />
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
</ItemGroup>
</Project>
</Project>
100 changes: 100 additions & 0 deletions Controllers/SiteShieldSyncController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using ConplementAG.CopsController.Services;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Serilog;

namespace ConplementAG.CopsController.Controllers
{
/// <summary>
/// Metacontroller sync hook of the CompositeController for CopsTraefikSiteShieldMiddleware resources.
/// </summary>
[Route("api/siteshield")]
[ApiController]
public class SiteShieldSyncController : ControllerBase
{
private readonly IAkamaiCredentialsProvider _credentialsProvider;
private readonly IAkamaiSiteShieldClient _siteShieldClient;
private readonly SiteShieldSyncResponseBuilder _responseBuilder;

public SiteShieldSyncController(IAkamaiCredentialsProvider credentialsProvider, IAkamaiSiteShieldClient siteShieldClient, SiteShieldSyncResponseBuilder responseBuilder)
{
_credentialsProvider = credentialsProvider;
_siteShieldClient = siteShieldClient;
_responseBuilder = responseBuilder;
}

[HttpGet]
public ActionResult<string> Get()
{
return "I am alive.";
}

[HttpPost("sync")]
public async Task<IActionResult> Sync([FromBody] JObject value, CancellationToken cancellationToken)
{
try
{
Log.Verbose("REQUEST===============================" + value?.ToString(Newtonsoft.Json.Formatting.Indented));

var request = SiteShieldSyncRequest.Parse(value);
var response = await SyncAsync(request, cancellationToken);
var json = response.ToJObject();

Log.Verbose("RESPONSE===============================" + json.ToString(Newtonsoft.Json.Formatting.Indented));
return Ok(json);
}
catch (Exception ex)
{
if (value?["parent"] is JObject parent)
{
Log.Error(ex, $"Error while handling Cops Resource {parent["kind"]}, {parent["metadata"]?["namespace"]}/{parent["metadata"]?["name"]}");
}
else
{
Log.Error(ex, "Error while handling unknown resource type. Here is the entire value object dump: " + value);
}
}

return StatusCode((int)HttpStatusCode.InternalServerError);
}

/// <summary>
/// Failures of the secret lookup or the Akamai call are reported in the resource status (HTTP 200), keeping
/// the existing Middleware untouched. Only malformed requests end up as HTTP 500.
/// </summary>
private async Task<SiteShieldSyncResponse> SyncAsync(SiteShieldSyncRequest request, CancellationToken cancellationToken)
{
var parent = request.Parent;
var resourceName = $"{parent.Metadata.Namespace}/{parent.Metadata.Name}";

try
{
var credentials = await _credentialsProvider.GetCredentialsAsync(parent.Metadata.Namespace, cancellationToken);
var map = await _siteShieldClient.GetMapAsync(credentials, parent.Spec.MapId, cancellationToken);

var response = _responseBuilder.BuildSuccess(parent, request.ObservedChild, map);
Log.Information($"Synced {parent.Kind} {resourceName}: {response.Status.Message}");
return response;
}
catch (SiteShieldException ex)
{
var detail = ex is AkamaiSiteShieldApiException apiException && !string.IsNullOrWhiteSpace(apiException.ResponseBody)
? $" Akamai response: {apiException.ResponseBody}"
: string.Empty;

Log.Error(ex, $"Sync of {parent.Kind} {resourceName} failed: {ex.Message}{detail}");
return _responseBuilder.BuildError(parent, request.ObservedChild, ex.Message);
}
catch (Exception ex)
{
// transport errors, timeouts, ...: the status message must stay stable, so only the exception type is reported
Log.Error(ex, $"Sync of {parent.Kind} {resourceName} failed unexpectedly");
return _responseBuilder.BuildError(parent, request.ObservedChild, $"Akamai SiteShield sync failed: {ex.GetType().Name}");
}
}
}
}
19 changes: 19 additions & 0 deletions CopsController.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ VisualStudioVersion = 17.0.32112.339
MinimumVisualStudioVersion = 15.0.26124.0
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConplementAG.CopsController", "ConplementAG.CopsController.csproj", "{42B54B22-D6D8-4016-A50E-C24291850B93}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConplementAG.CopsController.Tests", "tests\ConplementAG.CopsController.Tests\ConplementAG.CopsController.Tests.csproj", "{78B3977B-F410-4866-AC6A-D05501A94B61}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -27,10 +31,25 @@ Global
{42B54B22-D6D8-4016-A50E-C24291850B93}.Release|x64.Build.0 = Release|Any CPU
{42B54B22-D6D8-4016-A50E-C24291850B93}.Release|x86.ActiveCfg = Release|Any CPU
{42B54B22-D6D8-4016-A50E-C24291850B93}.Release|x86.Build.0 = Release|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Debug|Any CPU.Build.0 = Debug|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Debug|x64.ActiveCfg = Debug|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Debug|x64.Build.0 = Debug|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Debug|x86.ActiveCfg = Debug|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Debug|x86.Build.0 = Debug|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Release|Any CPU.ActiveCfg = Release|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Release|Any CPU.Build.0 = Release|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Release|x64.ActiveCfg = Release|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Release|x64.Build.0 = Release|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Release|x86.ActiveCfg = Release|Any CPU
{78B3977B-F410-4866-AC6A-D05501A94B61}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{78B3977B-F410-4866-AC6A-D05501A94B61} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {056F6C2C-B9B1-4BB2-B114-501D4B2E1A89}
EndGlobalSection
Expand Down
1 change: 1 addition & 0 deletions Dockerfile.develop
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble
ARG BUILD_CONFIGURATION=Debug
ENV ASPNETCORE_ENVIRONMENT=Development
ENV Serilog__MinimumLevel=Information
ENV DOTNET_USE_POLLING_FILE_WATCHER=true
ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080
Expand Down
166 changes: 166 additions & 0 deletions Models/AkamaiCredentials.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConplementAG.CopsController.Services;

namespace ConplementAG.CopsController.Models
{
/// <summary>
/// Akamai EdgeGrid API client credentials, read from a Kubernetes secret. Two layouts are supported and may be
/// mixed: the four separate keys host, client_token, client_secret and access_token, or one key "edgerc" holding
/// an .edgerc file whose [default] section provides the values. Separate keys win over the edgerc content.
/// </summary>
public sealed class AkamaiCredentials
{
public const string HostKey = "host";
public const string ClientTokenKey = "client_token";
public const string ClientSecretKey = "client_secret";
public const string AccessTokenKey = "access_token";

public const string EdgercKey = "edgerc";
public const string EdgercSection = "default";

public AkamaiCredentials(string host, string clientToken, string clientSecret, string accessToken)
{
Host = host ?? throw new ArgumentNullException(nameof(host));
ClientToken = clientToken ?? throw new ArgumentNullException(nameof(clientToken));
ClientSecret = clientSecret ?? throw new ArgumentNullException(nameof(clientSecret));
AccessToken = accessToken ?? throw new ArgumentNullException(nameof(accessToken));
}

/// <summary>Akamai API host without scheme, e.g. akab-xxxx.luna.akamaiapis.net</summary>
public string Host { get; }

public string ClientToken { get; }

public string ClientSecret { get; }

public string AccessToken { get; }

/// <summary>
/// Creates credentials from the data of a Kubernetes secret (values are already base64 decoded).
/// Values are trimmed (kubectl --from-file leaves a trailing newline) and the host is normalized.
/// </summary>
public static AkamaiCredentials FromSecretData(IDictionary<string, byte[]> data, string secretNamespace, string secretName)
{
data ??= new Dictionary<string, byte[]>();
var missing = new List<string>();

var edgerc = data.TryGetValue(EdgercKey, out var edgercBytes) && edgercBytes != null
? ParseEdgerc(Encoding.UTF8.GetString(edgercBytes), EdgercSection)
: new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

string Read(string key)
{
if (data.TryGetValue(key, out var bytes) && bytes != null)
{
var value = Encoding.UTF8.GetString(bytes).Trim();
if (value.Length > 0)
{
return value;
}
}

if (edgerc.TryGetValue(key, out var edgercValue) && !string.IsNullOrWhiteSpace(edgercValue))
{
return edgercValue.Trim();
}

missing.Add(key);
return null;
}

var host = Read(HostKey);
var clientToken = Read(ClientTokenKey);
var clientSecret = Read(ClientSecretKey);
var accessToken = Read(AccessTokenKey);

if (missing.Count > 0)
{
missing.Sort(StringComparer.Ordinal);
throw new AkamaiCredentialsException(
$"Credentials secret {secretNamespace}/{secretName} is missing key(s): {string.Join(", ", missing)} " +
$"(expected as separate keys or in the [{EdgercSection}] section of the key {EdgercKey})");
}

return new AkamaiCredentials(NormalizeHost(host), clientToken, clientSecret, accessToken);
}

/// <summary>
/// Minimal parser for the .edgerc INI format: "key = value" lines below "[section]" headers, comments start
/// with # or ;. Returns the values of the requested section; if that section does not exist but the file
/// contains exactly one section (or no header at all), that one is used.
/// </summary>
public static Dictionary<string, string> ParseEdgerc(string content, string section)
{
var sections = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
var current = string.Empty;

foreach (var rawLine in (content ?? string.Empty).Split('\n'))
{
var line = rawLine.Trim();

if (line.Length == 0 || line.StartsWith("#", StringComparison.Ordinal) || line.StartsWith(";", StringComparison.Ordinal))
{
continue;
}

if (line.StartsWith("[", StringComparison.Ordinal) && line.EndsWith("]", StringComparison.Ordinal))
{
current = line.Substring(1, line.Length - 2).Trim();
continue;
}

var separator = line.IndexOf('=');
if (separator <= 0)
{
continue;
}

var key = line.Substring(0, separator).Trim();
var value = line.Substring(separator + 1).Trim();

if (value.Length >= 2 && (value[0] == '"' && value[value.Length - 1] == '"' || value[0] == '\'' && value[value.Length - 1] == '\''))
{
value = value.Substring(1, value.Length - 2);
}

if (!sections.TryGetValue(current, out var values))
{
values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
sections[current] = values;
}

values[key] = value;
}

if (sections.TryGetValue(section ?? string.Empty, out var requested))
{
return requested;
}

return sections.Count == 1 ? sections.Values.First() : new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}

/// <summary>Strips an optional scheme and trailing slashes; EdgeGrid signs the bare host name.</summary>
public static string NormalizeHost(string host)
{
var value = host?.Trim() ?? string.Empty;

foreach (var scheme in new[] { "https://", "http://" })
{
if (value.StartsWith(scheme, StringComparison.OrdinalIgnoreCase))
{
value = value.Substring(scheme.Length);
break;
}
}

return value.TrimEnd('/');
}

// never expose the secret parts, e.g. through structured logging of this object
public override string ToString() => $"AkamaiCredentials(host={Host})";
}
}
37 changes: 37 additions & 0 deletions Models/AkamaiSiteShieldMap.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Newtonsoft.Json;

namespace ConplementAG.CopsController.Models
{
/// <summary>
/// Response of GET /siteshield/v1/maps/{id} of the Akamai Site Shield API (only the fields used here).
/// </summary>
public class AkamaiSiteShieldMap
{
[JsonProperty("id")]
public long? Id { get; set; }

[JsonProperty("mapAlias")]
public string MapAlias { get; set; }

[JsonProperty("ruleName")]
public string RuleName { get; set; }

/// <summary>CIDR blocks currently in use by the map.</summary>
[JsonProperty("currentCidrs")]
public string[] CurrentCidrs { get; set; }

/// <summary>CIDR blocks proposed by Akamai, which become current once acknowledged.</summary>
[JsonProperty("proposedCidrs")]
public string[] ProposedCidrs { get; set; }

[JsonProperty("acknowledged")]
public bool? Acknowledged { get; set; }

/// <summary>Epoch milliseconds until which the proposed CIDRs have to be acknowledged.</summary>
[JsonProperty("acknowledgeRequiredBy")]
public long? AcknowledgeRequiredBy { get; set; }

[JsonProperty("latestTicketId")]
public long? LatestTicketId { get; set; }
}
}
Loading
Loading