diff --git a/.dockerignore b/.dockerignore
index 98eef99..8438acf 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -11,4 +11,5 @@
**/Dockerfile.develop
**/obj
**/secrets.dev.yaml
-**/values.dev.yaml
\ No newline at end of file
+**/values.dev.yaml
+**/tests
diff --git a/.gitignore b/.gitignore
index 366b97f..26f5c93 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
bin
obj
.vs
-*.user
\ No newline at end of file
+*.user
+.idea/
diff --git a/ConplementAG.CopsController.csproj b/ConplementAG.CopsController.csproj
index 0e6472b..2e50b65 100644
--- a/ConplementAG.CopsController.csproj
+++ b/ConplementAG.CopsController.csproj
@@ -1,15 +1,18 @@
-
+
net10.0
InProcess
ConplementAG.CopsController
true
dc526bff-7bba-4e39-adab-3033979b7f98
+
+ $(DefaultItemExcludes);tests/**
+
-
\ No newline at end of file
+
diff --git a/Controllers/SiteShieldSyncController.cs b/Controllers/SiteShieldSyncController.cs
new file mode 100644
index 0000000..d8ad4ce
--- /dev/null
+++ b/Controllers/SiteShieldSyncController.cs
@@ -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
+{
+ ///
+ /// Metacontroller sync hook of the CompositeController for CopsTraefikSiteShieldMiddleware resources.
+ ///
+ [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 Get()
+ {
+ return "I am alive.";
+ }
+
+ [HttpPost("sync")]
+ public async Task 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ private async Task 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}");
+ }
+ }
+ }
+}
diff --git a/CopsController.sln b/CopsController.sln
index 6d18f8e..1ea9d19 100644
--- a/CopsController.sln
+++ b/CopsController.sln
@@ -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
@@ -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
diff --git a/Dockerfile.develop b/Dockerfile.develop
index 1352568..ca0ab01 100644
--- a/Dockerfile.develop
+++ b/Dockerfile.develop
@@ -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
diff --git a/Models/AkamaiCredentials.cs b/Models/AkamaiCredentials.cs
new file mode 100644
index 0000000..0540c50
--- /dev/null
+++ b/Models/AkamaiCredentials.cs
@@ -0,0 +1,166 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ConplementAG.CopsController.Services;
+
+namespace ConplementAG.CopsController.Models
+{
+ ///
+ /// 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.
+ ///
+ 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));
+ }
+
+ /// Akamai API host without scheme, e.g. akab-xxxx.luna.akamaiapis.net
+ public string Host { get; }
+
+ public string ClientToken { get; }
+
+ public string ClientSecret { get; }
+
+ public string AccessToken { get; }
+
+ ///
+ /// 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.
+ ///
+ public static AkamaiCredentials FromSecretData(IDictionary data, string secretNamespace, string secretName)
+ {
+ data ??= new Dictionary();
+ var missing = new List();
+
+ var edgerc = data.TryGetValue(EdgercKey, out var edgercBytes) && edgercBytes != null
+ ? ParseEdgerc(Encoding.UTF8.GetString(edgercBytes), EdgercSection)
+ : new Dictionary(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);
+ }
+
+ ///
+ /// 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.
+ ///
+ public static Dictionary ParseEdgerc(string content, string section)
+ {
+ var sections = new Dictionary>(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(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(StringComparer.OrdinalIgnoreCase);
+ }
+
+ /// Strips an optional scheme and trailing slashes; EdgeGrid signs the bare host name.
+ 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})";
+ }
+}
diff --git a/Models/AkamaiSiteShieldMap.cs b/Models/AkamaiSiteShieldMap.cs
new file mode 100644
index 0000000..4a851f6
--- /dev/null
+++ b/Models/AkamaiSiteShieldMap.cs
@@ -0,0 +1,37 @@
+using Newtonsoft.Json;
+
+namespace ConplementAG.CopsController.Models
+{
+ ///
+ /// Response of GET /siteshield/v1/maps/{id} of the Akamai Site Shield API (only the fields used here).
+ ///
+ public class AkamaiSiteShieldMap
+ {
+ [JsonProperty("id")]
+ public long? Id { get; set; }
+
+ [JsonProperty("mapAlias")]
+ public string MapAlias { get; set; }
+
+ [JsonProperty("ruleName")]
+ public string RuleName { get; set; }
+
+ /// CIDR blocks currently in use by the map.
+ [JsonProperty("currentCidrs")]
+ public string[] CurrentCidrs { get; set; }
+
+ /// CIDR blocks proposed by Akamai, which become current once acknowledged.
+ [JsonProperty("proposedCidrs")]
+ public string[] ProposedCidrs { get; set; }
+
+ [JsonProperty("acknowledged")]
+ public bool? Acknowledged { get; set; }
+
+ /// Epoch milliseconds until which the proposed CIDRs have to be acknowledged.
+ [JsonProperty("acknowledgeRequiredBy")]
+ public long? AcknowledgeRequiredBy { get; set; }
+
+ [JsonProperty("latestTicketId")]
+ public long? LatestTicketId { get; set; }
+ }
+}
diff --git a/Models/CopsTraefikSiteShieldMiddleware.cs b/Models/CopsTraefikSiteShieldMiddleware.cs
new file mode 100644
index 0000000..14a4865
--- /dev/null
+++ b/Models/CopsTraefikSiteShieldMiddleware.cs
@@ -0,0 +1,93 @@
+using Newtonsoft.Json;
+
+namespace ConplementAG.CopsController.Models
+{
+ ///
+ /// Parent resource of the siteshield CompositeController. Namespaced: the generated Traefik Middleware and the
+ /// Akamai credentials secret live in the same namespace as this resource.
+ ///
+ public class CopsTraefikSiteShieldMiddleware
+ {
+ public const string KindName = "CopsTraefikSiteShieldMiddleware";
+
+ [JsonProperty("apiVersion")]
+ public string ApiVersion { get; set; }
+
+ [JsonProperty("kind")]
+ public string Kind { get; set; }
+
+ [JsonProperty("metadata")]
+ public CopsTraefikSiteShieldMiddlewareMetadata Metadata { get; set; }
+
+ [JsonProperty("spec")]
+ public CopsTraefikSiteShieldMiddlewareSpec Spec { get; set; }
+
+ [JsonProperty("status")]
+ public CopsTraefikSiteShieldMiddlewareStatus Status { get; set; }
+
+ public static CopsTraefikSiteShieldMiddleware FromJson(string json) => JsonConvert.DeserializeObject(json, Converter.Settings);
+ }
+
+ public class CopsTraefikSiteShieldMiddlewareMetadata
+ {
+ [JsonProperty("name")]
+ public string Name { get; set; }
+
+ [JsonProperty("namespace")]
+ public string Namespace { get; set; }
+
+ [JsonProperty("generation")]
+ public long? Generation { get; set; }
+ }
+
+ public class CopsTraefikSiteShieldMiddlewareSpec
+ {
+ [JsonProperty("mapId")]
+ public long MapId { get; set; }
+
+ [JsonProperty("additionalSourceRanges")]
+ public string[] AdditionalSourceRanges { get; set; }
+
+ [JsonProperty("ipStrategy")]
+ public TraefikIpStrategy IpStrategy { get; set; }
+ }
+
+ ///
+ /// Status written by metacontroller from the sync hook response. Every property here must also exist in the
+ /// status schema of the CRD (deployment/crds/copstraefiksiteshieldmiddleware.crd.yaml), otherwise the api server
+ /// prunes it and the stored status never equals the returned one.
+ ///
+ public class CopsTraefikSiteShieldMiddlewareStatus
+ {
+ public const string StateReady = "Ready";
+ public const string StateError = "Error";
+
+ [JsonProperty("state")]
+ public string State { get; set; }
+
+ [JsonProperty("message")]
+ public string Message { get; set; }
+
+ [JsonProperty("mapId")]
+ public long? MapId { get; set; }
+
+ [JsonProperty("mapAlias")]
+ public string MapAlias { get; set; }
+
+ [JsonProperty("cidrCount")]
+ public int? CidrCount { get; set; }
+
+ [JsonProperty("acknowledged")]
+ public bool? Acknowledged { get; set; }
+
+ ///
+ /// RFC3339 timestamp (seconds precision) of the last change of the generated sourceRange. Kept as a string on
+ /// purpose, so that it is carried over between syncs byte for byte.
+ ///
+ [JsonProperty("lastCidrChange")]
+ public string LastCidrChange { get; set; }
+
+ [JsonProperty("observedGeneration")]
+ public long? ObservedGeneration { get; set; }
+ }
+}
diff --git a/Models/TraefikMiddleware.cs b/Models/TraefikMiddleware.cs
new file mode 100644
index 0000000..505a126
--- /dev/null
+++ b/Models/TraefikMiddleware.cs
@@ -0,0 +1,80 @@
+using Newtonsoft.Json;
+
+namespace ConplementAG.CopsController.Models
+{
+ ///
+ /// Child resource generated for a CopsTraefikSiteShieldMiddleware: a Traefik Middleware of type ipAllowList.
+ /// Metadata intentionally only contains name and namespace, so that an observed child re-emitted from a sync
+ /// request never carries uid, resourceVersion or managedFields.
+ ///
+ public class TraefikMiddleware
+ {
+ public const string ApiVersionValue = "traefik.io/v1alpha1";
+ public const string KindValue = "Middleware";
+
+ /// Key of this child type in the "children" map of the metacontroller sync request.
+ public const string MetacontrollerChildKey = "Middleware.traefik.io/v1alpha1";
+
+ [JsonProperty("apiVersion")]
+ public string ApiVersion { get; set; }
+
+ [JsonProperty("kind")]
+ public string Kind { get; set; }
+
+ [JsonProperty("metadata")]
+ public K8sMetadata Metadata { get; set; }
+
+ [JsonProperty("spec")]
+ public TraefikMiddlewareSpec Spec { get; set; }
+
+ public static TraefikMiddleware IpAllowList(string name, string @namespace, string[] sourceRange, TraefikIpStrategy ipStrategy = null)
+ {
+ return new TraefikMiddleware
+ {
+ ApiVersion = ApiVersionValue,
+ Kind = KindValue,
+ Metadata = new K8sMetadata { Name = name, Namespace = @namespace },
+ Spec = new TraefikMiddlewareSpec
+ {
+ IpAllowList = new TraefikIpAllowList
+ {
+ SourceRange = sourceRange,
+ IpStrategy = ipStrategy
+ }
+ }
+ };
+ }
+
+ public static TraefikMiddleware FromJson(string json) => JsonConvert.DeserializeObject(json, Converter.Settings);
+ }
+
+ public class TraefikMiddlewareSpec
+ {
+ [JsonProperty("ipAllowList")]
+ public TraefikIpAllowList IpAllowList { get; set; }
+ }
+
+ public class TraefikIpAllowList
+ {
+ [JsonProperty("sourceRange")]
+ public string[] SourceRange { get; set; }
+
+ [JsonProperty("ipStrategy", NullValueHandling = NullValueHandling.Ignore)]
+ public TraefikIpStrategy IpStrategy { get; set; }
+ }
+
+ ///
+ /// Traefik ipStrategy. Shared between the CR spec and the generated Middleware, the shape is identical.
+ ///
+ public class TraefikIpStrategy
+ {
+ [JsonProperty("depth", NullValueHandling = NullValueHandling.Ignore)]
+ public int? Depth { get; set; }
+
+ [JsonProperty("excludedIPs", NullValueHandling = NullValueHandling.Ignore)]
+ public string[] ExcludedIPs { get; set; }
+
+ [JsonProperty("ipv6Subnet", NullValueHandling = NullValueHandling.Ignore)]
+ public int? Ipv6Subnet { get; set; }
+ }
+}
diff --git a/Program.cs b/Program.cs
index 16d1a9c..8c621c2 100644
--- a/Program.cs
+++ b/Program.cs
@@ -18,7 +18,9 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
.ConfigureAppConfiguration((hostingContext, config) => { config.AddEnvironmentVariables(); })
.UseSerilog((ctx, config) =>
{
- config.ReadFrom.Configuration(new ConfigurationBuilder().AddEnvironmentVariables().Build());
+ // appsettings.json sets the default (MinimumLevel Error), environment variables such as
+ // Serilog__MinimumLevel override it
+ config.ReadFrom.Configuration(ctx.Configuration);
config.Enrich.FromLogContext();
config.WriteTo.Console(new JsonFormatter());
})
diff --git a/README.md b/README.md
index d917858..3edbe7f 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,81 @@ This project is "based" on [metacontroller](https://github.com/GoogleCloudPlatfo
Check the instructions on the [release page](https://github.com/conplementAG/cops-controller/releases).
+The custom resource definitions are not part of the Helm chart, install them with `kubectl apply -f deployment/crds`.
+
+The controller logs at level `Error` by default; `copsController.logLevel` in the Helm chart (environment variable `Serilog__MinimumLevel`) raises it, e.g. to `Information` to see every sync or `Verbose` to dump the metacontroller requests and responses.
+
+## Custom resources
+
+### CopsNamespace
+
+Creates a namespace including the RBAC for its administrators and a default limit range. See `deployment/crds/copsnamespace.crd.yaml` for the schema.
+
+### CopsTraefikSiteShieldMiddleware
+
+Generates a [Traefik Middleware](https://doc.traefik.io/traefik/reference/routing-configuration/http/middlewares/ipallowlist/) of type `ipAllowList` whose `sourceRange` contains the current and the proposed CIDRs of an [Akamai SiteShield](https://techdocs.akamai.com/site-shield/docs) map, so that only traffic coming through Akamai reaches the service. The Middleware gets the same name and namespace as the resource and is refreshed from the Akamai Site Shield API once a day (`siteShield.resyncPeriodSeconds`); a failed sync is retried every 5 minutes until it succeeds.
+
+#### Prerequisites
+
+- The Traefik CRDs (`middlewares.traefik.io`) are installed in the cluster, as on every cops cluster. Without them Metacontroller reports a `CreateError` event for the `cops-controller-siteshield` CompositeController and only that controller stays inactive.
+- Metacontroller is allowed to manage `middlewares.traefik.io` (the default Metacontroller chart grants all permissions).
+- See `deployment/cops-controller/values.yaml` for the `siteShield` values (resync period, secret name).
+
+#### Credentials
+
+Every resource uses its own Akamai credentials: an [EdgeGrid API client](https://techdocs.akamai.com/developer/docs/authenticate-with-edgegrid) with access to the Site Shield API, stored in a secret named `akamai-siteshield-credentials` in the namespace of the resource. The secret either has the four keys of the `.edgerc` file:
+
+```sh
+kubectl create secret generic akamai-siteshield-credentials -n myapp \
+ --from-literal=host=akab-xxxxxxxx.luna.akamaiapis.net \
+ --from-literal=client_token=akab-... \
+ --from-literal=client_secret=... \
+ --from-literal=access_token=akab-...
+```
+
+or one key `edgerc` with the content of an `.edgerc` file, whose `[default]` section is used (`kubectl create secret generic akamai-siteshield-credentials -n myapp --from-file=edgerc=~/.edgerc`):
+
+```yaml
+apiVersion: v1
+kind: Secret
+metadata:
+ name: akamai-siteshield-credentials
+ namespace: myapp
+stringData:
+ edgerc: |
+ [default]
+ client_secret = ...
+ host = akab-xxxxxxxx.luna.akamaiapis.net
+ access_token = akab-...
+ client_token = akab-...
+```
+
+cops-controller is only allowed to read secrets with exactly this name (ClusterRole restricted by `resourceNames`). The name can be changed with `siteShield.credentialsSecretName`.
+
+#### Example
+
+```yaml
+apiVersion: coreops.conplement.cloud/v1
+kind: CopsTraefikSiteShieldMiddleware
+metadata:
+ name: siteshield
+ namespace: myapp
+spec:
+ mapId: 12345 # id of the Akamai SiteShield map
+ additionalSourceRanges: # optional, allowed in addition to the Akamai ranges
+ - 10.0.0.0/8
+ ipStrategy: # optional, passed through to the Middleware
+ depth: 1
+```
+
+The generated Middleware `myapp/siteshield` is referenced from an `IngressRoute` like any other middleware. A Middleware with the name of the resource must not exist before the resource is created.
+
+#### Status
+
+`kubectl get ctsm -n myapp` shows the map id, the state and the number of CIDRs. `status.message` explains an `Error` state (secret missing, unknown map id, API not reachable, ...). In state `Error` an existing Middleware is kept unchanged and the sync is retried after 5 minutes. `status.lastCidrChange` is the time of the last change of the generated `sourceRange`, `status.acknowledged` tells whether the proposed CIDRs of the map have already been acknowledged in Akamai.
+
+Troubleshooting: `kubectl describe ctsm -n `, the cops-controller logs, `kubectl describe compositecontroller cops-controller-siteshield` (e.g. an event `CreateError` when the Traefik CRDs are missing) and the Metacontroller logs.
+
## Development
For developing, we use Visual Studio Code and Telepresence (intercepting cluster workload and redirect traffic to local service).
@@ -36,7 +111,9 @@ Make sure you are running a version of cops-controller locally listing to port 5
Also, you might have issues with C# and .NET Core unless you install the dotnet core build tools as well: https://github.com/OmniSharp/omnisharp-roslyn/issues/1311#issuecomment-428361674
-5. Run `donet restore` / `dotnet build` and you are ready to go.
+5. Run `dotnet restore` / `dotnet build` and you are ready to go. `dotnet test` runs the unit tests in `tests/ConplementAG.CopsController.Tests`.
Hints on development:
- - When running inside Kubernetes, follow both metacontroller and this container logs. Metacontroller logs can be reached via `kubectl logs metacontroller-0 -n metacontroller -f` or a similar command.
\ No newline at end of file
+ - When running inside Kubernetes, follow both metacontroller and this container logs. Metacontroller logs can be reached via `kubectl logs metacontroller-0 -n metacontroller -f` or a similar command.
+ - The CopsTraefikSiteShieldMiddleware sync reads the credentials secret through the Kubernetes API: inside the cluster with the service account of the pod, locally with the current kubeconfig context.
+ - The component tests (`run_tests.sh`) only validate the CRD schema of CopsTraefikSiteShieldMiddleware, because they must not depend on the Traefik CRDs. The sync itself is covered by the unit tests and has to be checked manually on a cluster with Traefik.
diff --git a/Services/AkamaiSiteShieldClient.cs b/Services/AkamaiSiteShieldClient.cs
new file mode 100644
index 0000000..0a389e9
--- /dev/null
+++ b/Services/AkamaiSiteShieldClient.cs
@@ -0,0 +1,111 @@
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Threading;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Models;
+using Newtonsoft.Json;
+
+namespace ConplementAG.CopsController.Services
+{
+ ///
+ /// Minimal Akamai Site Shield API client. Requests are signed with EdgeGrid (EG1-HMAC-SHA256, see
+ /// ) using the credentials of the resource being synced, so no credentials
+ /// are bound to the HttpClient itself.
+ ///
+ public class AkamaiSiteShieldClient : IAkamaiSiteShieldClient
+ {
+ public const string HttpClientName = "akamai-siteshield";
+
+ private const string UnexpectedBodyMessage = "Akamai SiteShield API returned an unexpected response body";
+
+ private readonly IHttpClientFactory _httpClientFactory;
+
+ public AkamaiSiteShieldClient(IHttpClientFactory httpClientFactory)
+ {
+ _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
+ }
+
+ public async Task GetMapAsync(AkamaiCredentials credentials, long mapId, CancellationToken cancellationToken)
+ {
+ if (credentials == null)
+ {
+ throw new ArgumentNullException(nameof(credentials));
+ }
+
+ using var request = new HttpRequestMessage(HttpMethod.Get, $"https://{credentials.Host}/siteshield/v1/maps/{mapId}");
+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ try
+ {
+ // sign last: the signature covers the final request
+ await EdgeGridRequestSigner.SignAsync(request, credentials, cancellationToken: cancellationToken);
+ }
+ catch (ArgumentException ex)
+ {
+ // the message names the offending credential key, never its value
+ throw new AkamaiCredentialsException($"Akamai credentials are invalid: {ex.Message}", ex);
+ }
+
+ using var response = await _httpClientFactory.CreateClient(HttpClientName).SendAsync(request, cancellationToken);
+
+ if (!response.IsSuccessStatusCode)
+ {
+ // the Akamai error body (type, title, detail) explains the failure, it is logged but never put into the status
+ var errorBody = await ReadBodyForLogAsync(response, cancellationToken);
+ throw new AkamaiSiteShieldApiException(ErrorMessage(response.StatusCode, mapId), response.StatusCode, responseBody: errorBody);
+ }
+
+ var json = await response.Content.ReadAsStringAsync(cancellationToken);
+ AkamaiSiteShieldMap map;
+
+ try
+ {
+ map = JsonConvert.DeserializeObject(json);
+ }
+ catch (JsonException ex)
+ {
+ throw new AkamaiSiteShieldApiException(UnexpectedBodyMessage, response.StatusCode, ex);
+ }
+
+ if (map?.Id == null)
+ {
+ throw new AkamaiSiteShieldApiException(UnexpectedBodyMessage, response.StatusCode);
+ }
+
+ return map;
+ }
+
+ private static string ErrorMessage(HttpStatusCode statusCode, long mapId)
+ {
+ switch (statusCode)
+ {
+ case HttpStatusCode.NotFound:
+ return $"Akamai SiteShield map {mapId} not found (HTTP 404)";
+ case HttpStatusCode.Forbidden:
+ return $"Access to Akamai SiteShield map {mapId} denied (HTTP 403); check the permissions of the API client";
+ case HttpStatusCode.Unauthorized:
+ return "Akamai SiteShield authentication failed (HTTP 401); check the credentials secret";
+ default:
+ return $"Akamai SiteShield API returned HTTP {(int)statusCode}";
+ }
+ }
+
+ private static async Task ReadBodyForLogAsync(HttpResponseMessage response, CancellationToken cancellationToken)
+ {
+ const int maxLength = 2000;
+
+ try
+ {
+ var body = await response.Content.ReadAsStringAsync(cancellationToken);
+ return body.Length > maxLength ? body.Substring(0, maxLength) + "..." : body;
+ }
+ catch (Exception ex) when (!(ex is OperationCanceledException))
+ {
+ return null;
+ }
+ }
+
+ }
+}
diff --git a/Services/EdgeGridRequestSigner.cs b/Services/EdgeGridRequestSigner.cs
new file mode 100644
index 0000000..c1f3939
--- /dev/null
+++ b/Services/EdgeGridRequestSigner.cs
@@ -0,0 +1,101 @@
+using System;
+using System.Globalization;
+using System.Net.Http;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Models;
+
+namespace ConplementAG.CopsController.Services
+{
+ ///
+ /// Signs requests for Akamai APIs with the EdgeGrid EG1-HMAC-SHA256 scheme, see
+ /// https://techdocs.akamai.com/developer/docs/authenticate-with-edgegrid and Akamai's reference clients:
+ ///
+ /// signingKey = base64(HMAC-SHA256(key = clientSecret, msg = timestamp))
+ /// dataToSign = method \t scheme \t host \t path?query \t canonicalizedHeaders \t contentHash \t authHeaderWithoutSignature
+ /// signature = base64(HMAC-SHA256(key = signingKey, msg = dataToSign))
+ ///
+ /// No request headers are part of the signature (canonicalizedHeaders is empty) and, as in the reference clients,
+ /// only POST bodies are hashed (the first maxBody bytes).
+ ///
+ public static class EdgeGridRequestSigner
+ {
+ public const string Scheme = "EG1-HMAC-SHA256";
+ public const string TimestampFormat = "yyyyMMdd'T'HH:mm:ss'+0000'";
+ public const int DefaultMaxBody = 131072;
+
+ ///
+ /// Adds the Authorization header to the request. Timestamp and nonce are generated unless given (tests).
+ ///
+ public static async Task SignAsync(HttpRequestMessage request, AkamaiCredentials credentials, DateTimeOffset? timestamp = null, string nonce = null, int maxBody = DefaultMaxBody, CancellationToken cancellationToken = default)
+ {
+ if (request == null)
+ {
+ throw new ArgumentNullException(nameof(request));
+ }
+
+ if (credentials == null)
+ {
+ throw new ArgumentNullException(nameof(credentials));
+ }
+
+ if (request.RequestUri == null || !request.RequestUri.IsAbsoluteUri)
+ {
+ throw new ArgumentException("The request needs an absolute URI", nameof(request));
+ }
+
+ foreach (var (name, value) in new[] { ("host", credentials.Host), ("client_token", credentials.ClientToken), ("client_secret", credentials.ClientSecret), ("access_token", credentials.AccessToken) })
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ throw new ArgumentException($"The credential value {name} is empty", nameof(credentials));
+ }
+ }
+
+ var timestampText = (timestamp ?? DateTimeOffset.UtcNow).ToUniversalTime().ToString(TimestampFormat, CultureInfo.InvariantCulture);
+ var nonceText = string.IsNullOrEmpty(nonce) ? Guid.NewGuid().ToString() : nonce;
+
+ var authHeaderWithoutSignature = $"{Scheme} client_token={credentials.ClientToken};access_token={credentials.AccessToken};timestamp={timestampText};nonce={nonceText};";
+
+ var uri = request.RequestUri;
+ var dataToSign = string.Join("\t",
+ request.Method.Method.ToUpperInvariant(),
+ uri.Scheme.ToLowerInvariant(),
+ uri.Authority.ToLowerInvariant(),
+ uri.PathAndQuery,
+ string.Empty,
+ await ContentHashAsync(request, maxBody, cancellationToken),
+ authHeaderWithoutSignature);
+
+ var signingKey = Base64Hmac(Encoding.UTF8.GetBytes(credentials.ClientSecret), timestampText);
+ var signature = Base64Hmac(Encoding.UTF8.GetBytes(signingKey), dataToSign);
+
+ request.Headers.Remove("Authorization");
+ request.Headers.TryAddWithoutValidation("Authorization", authHeaderWithoutSignature + "signature=" + signature);
+ }
+
+ private static async Task ContentHashAsync(HttpRequestMessage request, int maxBody, CancellationToken cancellationToken)
+ {
+ if (request.Method != HttpMethod.Post || request.Content == null)
+ {
+ return string.Empty;
+ }
+
+ var body = await request.Content.ReadAsByteArrayAsync(cancellationToken);
+ if (body.Length == 0)
+ {
+ return string.Empty;
+ }
+
+ var length = Math.Min(body.Length, maxBody);
+ return Convert.ToBase64String(SHA256.HashData(new ReadOnlySpan(body, 0, length)));
+ }
+
+ private static string Base64Hmac(byte[] key, string message)
+ {
+ return Convert.ToBase64String(HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(message)));
+ }
+ }
+}
diff --git a/Services/IAkamaiCredentialsProvider.cs b/Services/IAkamaiCredentialsProvider.cs
new file mode 100644
index 0000000..12e0957
--- /dev/null
+++ b/Services/IAkamaiCredentialsProvider.cs
@@ -0,0 +1,13 @@
+using System.Threading;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Models;
+
+namespace ConplementAG.CopsController.Services
+{
+ public interface IAkamaiCredentialsProvider
+ {
+ /// Loads the Akamai credentials to use for resources in the given namespace.
+ /// The secret is missing, not readable or incomplete.
+ Task GetCredentialsAsync(string @namespace, CancellationToken cancellationToken);
+ }
+}
diff --git a/Services/IAkamaiSiteShieldClient.cs b/Services/IAkamaiSiteShieldClient.cs
new file mode 100644
index 0000000..6849196
--- /dev/null
+++ b/Services/IAkamaiSiteShieldClient.cs
@@ -0,0 +1,13 @@
+using System.Threading;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Models;
+
+namespace ConplementAG.CopsController.Services
+{
+ public interface IAkamaiSiteShieldClient
+ {
+ /// Fetches a Site Shield map (GET /siteshield/v1/maps/{mapId}).
+ /// The API answered with an error or an unexpected body.
+ Task GetMapAsync(AkamaiCredentials credentials, long mapId, CancellationToken cancellationToken);
+ }
+}
diff --git a/Services/IKubernetesSecretReader.cs b/Services/IKubernetesSecretReader.cs
new file mode 100644
index 0000000..1c1ae76
--- /dev/null
+++ b/Services/IKubernetesSecretReader.cs
@@ -0,0 +1,13 @@
+using System.Threading;
+using System.Threading.Tasks;
+using k8s.Models;
+
+namespace ConplementAG.CopsController.Services
+{
+ /// Thin seam over the Kubernetes client, so that the credentials provider can be tested without a cluster.
+ public interface IKubernetesSecretReader
+ {
+ /// Reads a secret; throws k8s.Autorest.HttpOperationException on api errors (404, 403, ...).
+ Task ReadAsync(string name, string @namespace, CancellationToken cancellationToken);
+ }
+}
diff --git a/Services/KubernetesSecretAkamaiCredentialsProvider.cs b/Services/KubernetesSecretAkamaiCredentialsProvider.cs
new file mode 100644
index 0000000..301ca83
--- /dev/null
+++ b/Services/KubernetesSecretAkamaiCredentialsProvider.cs
@@ -0,0 +1,67 @@
+using System;
+using System.Net;
+using System.Threading;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Models;
+using k8s.Autorest;
+using k8s.Models;
+using Microsoft.Extensions.Options;
+
+namespace ConplementAG.CopsController.Services
+{
+ ///
+ /// Reads the Akamai credentials from the secret with the configured fixed name in the namespace of the
+ /// CopsTraefikSiteShieldMiddleware. No caching: one GET per sync keeps credential rotation instant.
+ ///
+ public class KubernetesSecretAkamaiCredentialsProvider : IAkamaiCredentialsProvider
+ {
+ private readonly IKubernetesSecretReader _secretReader;
+ private readonly SiteShieldOptions _options;
+
+ public KubernetesSecretAkamaiCredentialsProvider(IKubernetesSecretReader secretReader, IOptions options)
+ {
+ _secretReader = secretReader ?? throw new ArgumentNullException(nameof(secretReader));
+ _options = options?.Value ?? new SiteShieldOptions();
+ }
+
+ public async Task GetCredentialsAsync(string @namespace, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrEmpty(@namespace))
+ {
+ throw new ArgumentException("Namespace is required", nameof(@namespace));
+ }
+
+ var name = _options.CredentialsSecretName;
+ V1Secret secret;
+
+ // The KubernetesClient default timeout (100s) exceeds the webhook timeout of the CompositeController, so the
+ // read is bounded like the Akamai request (see Startup). A cancellation of the hook itself is passed on as is.
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeout.CancelAfter(TimeSpan.FromSeconds(_options.RequestTimeoutSeconds));
+
+ try
+ {
+ secret = await _secretReader.ReadAsync(name, @namespace, timeout.Token);
+ }
+ catch (OperationCanceledException ex) when (timeout.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
+ {
+ throw new AkamaiCredentialsException($"Reading credentials secret {@namespace}/{name} timed out after {_options.RequestTimeoutSeconds}s", ex);
+ }
+ catch (HttpOperationException ex) when (ex.Response?.StatusCode == HttpStatusCode.NotFound)
+ {
+ throw new AkamaiCredentialsException($"Credentials secret {@namespace}/{name} not found; create it in the namespace of the {CopsTraefikSiteShieldMiddleware.KindName}", ex);
+ }
+ catch (HttpOperationException ex) when (ex.Response?.StatusCode == HttpStatusCode.Forbidden || ex.Response?.StatusCode == HttpStatusCode.Unauthorized)
+ {
+ throw new AkamaiCredentialsException($"Access to credentials secret {@namespace}/{name} denied (HTTP {(int)ex.Response.StatusCode}); check the cops-controller ClusterRole and ClusterRoleBinding", ex);
+ }
+ catch (HttpOperationException ex)
+ {
+ var statusCode = ex.Response != null ? (int)ex.Response.StatusCode : 0;
+ throw new AkamaiCredentialsException($"Reading credentials secret {@namespace}/{name} failed (HTTP {statusCode})", ex);
+ }
+
+ return AkamaiCredentials.FromSecretData(secret?.Data, @namespace, name);
+ }
+ }
+}
diff --git a/Services/KubernetesSecretReader.cs b/Services/KubernetesSecretReader.cs
new file mode 100644
index 0000000..3b41ca7
--- /dev/null
+++ b/Services/KubernetesSecretReader.cs
@@ -0,0 +1,23 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using k8s;
+using k8s.Models;
+
+namespace ConplementAG.CopsController.Services
+{
+ public class KubernetesSecretReader : IKubernetesSecretReader
+ {
+ private readonly IKubernetes _kubernetes;
+
+ public KubernetesSecretReader(IKubernetes kubernetes)
+ {
+ _kubernetes = kubernetes ?? throw new ArgumentNullException(nameof(kubernetes));
+ }
+
+ public Task ReadAsync(string name, string @namespace, CancellationToken cancellationToken)
+ {
+ return _kubernetes.CoreV1.ReadNamespacedSecretAsync(name, @namespace, cancellationToken: cancellationToken);
+ }
+ }
+}
diff --git a/Services/SiteShieldException.cs b/Services/SiteShieldException.cs
new file mode 100644
index 0000000..865d177
--- /dev/null
+++ b/Services/SiteShieldException.cs
@@ -0,0 +1,48 @@
+using System;
+using System.Net;
+
+namespace ConplementAG.CopsController.Services
+{
+ ///
+ /// Expected failure of a CopsTraefikSiteShieldMiddleware sync. The message is reported in the resource status,
+ /// so it must be stable: no timestamps, request ids or raw transport error texts.
+ ///
+ public class SiteShieldException : Exception
+ {
+ public SiteShieldException(string message) : base(message)
+ {
+ }
+
+ public SiteShieldException(string message, Exception innerException) : base(message, innerException)
+ {
+ }
+ }
+
+ public class AkamaiCredentialsException : SiteShieldException
+ {
+ public AkamaiCredentialsException(string message) : base(message)
+ {
+ }
+
+ public AkamaiCredentialsException(string message, Exception innerException) : base(message, innerException)
+ {
+ }
+ }
+
+ public class AkamaiSiteShieldApiException : SiteShieldException
+ {
+ public AkamaiSiteShieldApiException(string message, HttpStatusCode? statusCode = null, Exception innerException = null, string responseBody = null) : base(message, innerException)
+ {
+ StatusCode = statusCode;
+ ResponseBody = responseBody;
+ }
+
+ public HttpStatusCode? StatusCode { get; }
+
+ ///
+ /// Body of the Akamai error response (truncated), for the logs only: it explains e.g. why a 401 happened,
+ /// but may differ per request and therefore never becomes part of the resource status.
+ ///
+ public string ResponseBody { get; }
+ }
+}
diff --git a/Services/SiteShieldOptions.cs b/Services/SiteShieldOptions.cs
new file mode 100644
index 0000000..9688415
--- /dev/null
+++ b/Services/SiteShieldOptions.cs
@@ -0,0 +1,26 @@
+namespace ConplementAG.CopsController.Services
+{
+ ///
+ /// Configuration of the CopsTraefikSiteShieldMiddleware sync, bound to the "CopsController:SiteShield" section
+ /// (environment variables CopsController__SiteShield__*).
+ ///
+ public class SiteShieldOptions
+ {
+ public const string SectionName = "CopsController:SiteShield";
+
+ ///
+ /// Fixed name of the secret holding the Akamai EdgeGrid credentials. It is read from the namespace of the
+ /// CopsTraefikSiteShieldMiddleware; the ClusterRole of the controller only allows reading secrets with this name.
+ ///
+ public string CredentialsSecretName { get; set; } = "akamai-siteshield-credentials";
+
+ /// Delay until metacontroller re-syncs a resource whose last sync failed.
+ public int ErrorResyncAfterSeconds { get; set; } = 300;
+
+ ///
+ /// Timeout of each request of a sync (credentials secret read, Akamai API call). Must stay below the webhook
+ /// timeout of the CompositeController.
+ ///
+ public int RequestTimeoutSeconds { get; set; } = 20;
+ }
+}
diff --git a/Services/SiteShieldSyncRequest.cs b/Services/SiteShieldSyncRequest.cs
new file mode 100644
index 0000000..2c3c05a
--- /dev/null
+++ b/Services/SiteShieldSyncRequest.cs
@@ -0,0 +1,69 @@
+using System;
+using ConplementAG.CopsController.Models;
+using Newtonsoft.Json.Linq;
+
+namespace ConplementAG.CopsController.Services
+{
+ ///
+ /// The parts of a metacontroller CompositeController sync request which are relevant for the siteshield sync.
+ ///
+ public sealed class SiteShieldSyncRequest
+ {
+ private SiteShieldSyncRequest(CopsTraefikSiteShieldMiddleware parent, TraefikMiddleware observedChild)
+ {
+ Parent = parent;
+ ObservedChild = observedChild;
+ }
+
+ public CopsTraefikSiteShieldMiddleware Parent { get; }
+
+ /// The Middleware currently existing for the parent, or null if none exists yet.
+ public TraefikMiddleware ObservedChild { get; }
+
+ public static SiteShieldSyncRequest Parse(JObject request)
+ {
+ if (request == null)
+ {
+ throw new ArgumentException("Sync request body is empty");
+ }
+
+ if (!(request["parent"] is JObject parentObject))
+ {
+ throw new ArgumentException("Sync request contains no parent object");
+ }
+
+ var kind = parentObject["kind"]?.ToString();
+ if (!string.Equals(kind, CopsTraefikSiteShieldMiddleware.KindName, StringComparison.OrdinalIgnoreCase))
+ {
+ throw new ArgumentException($"Unknown resource of kind {kind}, expected {CopsTraefikSiteShieldMiddleware.KindName}");
+ }
+
+ var parent = CopsTraefikSiteShieldMiddleware.FromJson(parentObject.ToString());
+
+ if (string.IsNullOrEmpty(parent.Metadata?.Name) || string.IsNullOrEmpty(parent.Metadata?.Namespace))
+ {
+ throw new ArgumentException($"{CopsTraefikSiteShieldMiddleware.KindName} has no metadata.name or metadata.namespace");
+ }
+
+ if (parent.Spec == null)
+ {
+ throw new ArgumentException($"{CopsTraefikSiteShieldMiddleware.KindName} {parent.Metadata.Namespace}/{parent.Metadata.Name} has no spec");
+ }
+
+ TraefikMiddleware observedChild = null;
+
+ if (request["children"]?[TraefikMiddleware.MetacontrollerChildKey] is JObject middlewares)
+ {
+ // hook version v1 keys children of the same scope by name, v2 by namespace/name
+ var childToken = middlewares[parent.Metadata.Name] ?? middlewares[$"{parent.Metadata.Namespace}/{parent.Metadata.Name}"];
+
+ if (childToken is JObject childObject)
+ {
+ observedChild = TraefikMiddleware.FromJson(childObject.ToString());
+ }
+ }
+
+ return new SiteShieldSyncRequest(parent, observedChild);
+ }
+ }
+}
diff --git a/Services/SiteShieldSyncResponse.cs b/Services/SiteShieldSyncResponse.cs
new file mode 100644
index 0000000..ceec5b1
--- /dev/null
+++ b/Services/SiteShieldSyncResponse.cs
@@ -0,0 +1,29 @@
+using System.Collections.Generic;
+using ConplementAG.CopsController.Models;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+
+namespace ConplementAG.CopsController.Services
+{
+ ///
+ /// Response of the metacontroller sync hook for a CopsTraefikSiteShieldMiddleware.
+ ///
+ public sealed class SiteShieldSyncResponse
+ {
+ // Null members are dropped: the api server prunes them from the stored status anyway, so a status containing
+ // nulls would never be equal to the stored one and metacontroller would write it (and re-sync) on every sync.
+ private static readonly JsonSerializer Serializer = JsonSerializer.Create(new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
+
+ [JsonProperty("status")]
+ public CopsTraefikSiteShieldMiddlewareStatus Status { get; set; }
+
+ [JsonProperty("children")]
+ public List Children { get; set; } = new List();
+
+ /// One-time delay after which metacontroller re-syncs this parent (used for faster retries after failures).
+ [JsonProperty("resyncAfterSeconds")]
+ public int? ResyncAfterSeconds { get; set; }
+
+ public JObject ToJObject() => JObject.FromObject(this, Serializer);
+ }
+}
diff --git a/Services/SiteShieldSyncResponseBuilder.cs b/Services/SiteShieldSyncResponseBuilder.cs
new file mode 100644
index 0000000..d65872e
--- /dev/null
+++ b/Services/SiteShieldSyncResponseBuilder.cs
@@ -0,0 +1,122 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using ConplementAG.CopsController.Models;
+using Microsoft.Extensions.Options;
+
+namespace ConplementAG.CopsController.Services
+{
+ ///
+ /// Builds the sync response for a CopsTraefikSiteShieldMiddleware. Pure, no I/O.
+ ///
+ /// The status has to be deterministic for unchanged inputs: metacontroller re-syncs the parent after writing its
+ /// status, so a status which differs on every sync (e.g. a sync timestamp) would cause an endless sync loop
+ /// against the Akamai API.
+ ///
+ public class SiteShieldSyncResponseBuilder
+ {
+ private const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
+
+ private readonly TimeProvider _timeProvider;
+ private readonly SiteShieldOptions _options;
+
+ public SiteShieldSyncResponseBuilder(TimeProvider timeProvider, IOptions options)
+ {
+ _timeProvider = timeProvider ?? TimeProvider.System;
+ _options = options?.Value ?? new SiteShieldOptions();
+ }
+
+ public SiteShieldSyncResponse BuildSuccess(CopsTraefikSiteShieldMiddleware parent, TraefikMiddleware observedChild, AkamaiSiteShieldMap map)
+ {
+ if (parent == null)
+ {
+ throw new ArgumentNullException(nameof(parent));
+ }
+
+ if (map == null)
+ {
+ throw new ArgumentNullException(nameof(map));
+ }
+
+ var additionalSourceRanges = parent.Spec?.AdditionalSourceRanges;
+
+ var invalid = SourceRanges.FindInvalid(additionalSourceRanges);
+ if (invalid.Length > 0)
+ {
+ // only a spec change can fix this, and a spec change triggers a sync anyway: no timed retry
+ return BuildError(parent, observedChild, $"spec.additionalSourceRanges contains invalid entries: {string.Join(", ", invalid)}", retry: false);
+ }
+
+ var sourceRange = SourceRanges.Union(map.CurrentCidrs, map.ProposedCidrs, additionalSourceRanges);
+ if (sourceRange.Length == 0)
+ {
+ // an empty sourceRange is rejected by Traefik and would break the routers using the middleware
+ return BuildError(parent, observedChild, $"Akamai SiteShield map {map.Id} returned no CIDRs");
+ }
+
+ var child = TraefikMiddleware.IpAllowList(parent.Metadata.Name, parent.Metadata.Namespace, sourceRange, parent.Spec?.IpStrategy);
+
+ var previousChange = parent.Status?.LastCidrChange;
+ var unchanged = observedChild != null && SourceRanges.SequenceEqual(observedChild.Spec?.IpAllowList?.SourceRange, sourceRange);
+ var lastCidrChange = unchanged && !string.IsNullOrEmpty(previousChange) ? previousChange : Now();
+
+ var message = string.IsNullOrEmpty(map.MapAlias)
+ ? $"Middleware synced from Akamai SiteShield map {map.Id}"
+ : $"Middleware synced from Akamai SiteShield map {map.Id} ({map.MapAlias})";
+
+ return new SiteShieldSyncResponse
+ {
+ Children = new List { child },
+ Status = new CopsTraefikSiteShieldMiddlewareStatus
+ {
+ State = CopsTraefikSiteShieldMiddlewareStatus.StateReady,
+ Message = message,
+ MapId = map.Id,
+ MapAlias = map.MapAlias,
+ CidrCount = sourceRange.Length,
+ Acknowledged = map.Acknowledged,
+ LastCidrChange = lastCidrChange,
+ ObservedGeneration = parent.Metadata?.Generation
+ }
+ };
+ }
+
+ ///
+ /// Error response: the observed Middleware is returned unchanged (metacontroller deletes every observed child
+ /// missing from the response, and a transient Akamai outage must never drop the allow list), the previous
+ /// status values are carried over and the state is set to Error with the given stable message.
+ ///
+ public SiteShieldSyncResponse BuildError(CopsTraefikSiteShieldMiddleware parent, TraefikMiddleware observedChild, string stableMessage, bool retry = true)
+ {
+ if (parent == null)
+ {
+ throw new ArgumentNullException(nameof(parent));
+ }
+
+ var response = new SiteShieldSyncResponse
+ {
+ Status = new CopsTraefikSiteShieldMiddlewareStatus
+ {
+ State = CopsTraefikSiteShieldMiddlewareStatus.StateError,
+ Message = stableMessage,
+ MapId = parent.Spec?.MapId,
+ MapAlias = parent.Status?.MapAlias,
+ CidrCount = observedChild?.Spec?.IpAllowList?.SourceRange?.Length ?? parent.Status?.CidrCount,
+ Acknowledged = parent.Status?.Acknowledged,
+ LastCidrChange = parent.Status?.LastCidrChange,
+ ObservedGeneration = parent.Metadata?.Generation
+ },
+ ResyncAfterSeconds = retry ? _options.ErrorResyncAfterSeconds : (int?)null
+ };
+
+ if (observedChild != null)
+ {
+ response.Children.Add(observedChild);
+ }
+
+ return response;
+ }
+
+ private string Now() => _timeProvider.GetUtcNow().ToString(TimestampFormat, CultureInfo.InvariantCulture);
+ }
+}
diff --git a/Services/SourceRanges.cs b/Services/SourceRanges.cs
new file mode 100644
index 0000000..77ceead
--- /dev/null
+++ b/Services/SourceRanges.cs
@@ -0,0 +1,157 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+
+namespace ConplementAG.CopsController.Services
+{
+ ///
+ /// Helpers for the sourceRange list of a Traefik ipAllowList middleware.
+ ///
+ public static class SourceRanges
+ {
+ private static readonly string[] Empty = Array.Empty();
+
+ ///
+ /// Merges all given ranges into one deterministic list: trimmed, without empty entries, deduplicated
+ /// (case-insensitive, IPv6 may be written in either case) and sorted ordinally.
+ ///
+ public static string[] Union(params IEnumerable[] ranges)
+ {
+ var set = new HashSet(StringComparer.OrdinalIgnoreCase);
+
+ foreach (var range in ranges ?? Array.Empty>())
+ {
+ if (range == null)
+ {
+ continue;
+ }
+
+ foreach (var entry in range)
+ {
+ var trimmed = entry?.Trim();
+ if (!string.IsNullOrEmpty(trimmed))
+ {
+ set.Add(trimmed);
+ }
+ }
+ }
+
+ var result = set.ToArray();
+ Array.Sort(result, StringComparer.Ordinal);
+ return result;
+ }
+
+ public static bool SequenceEqual(string[] first, string[] second)
+ {
+ return (first ?? Empty).SequenceEqual(second ?? Empty, StringComparer.Ordinal);
+ }
+
+ /// Returns the entries which are neither an IP address nor a CIDR range, sorted ordinally.
+ public static string[] FindInvalid(IEnumerable ranges)
+ {
+ if (ranges == null)
+ {
+ return Empty;
+ }
+
+ var invalid = ranges
+ .Where(entry => !IsValidSourceRange(entry))
+ .Select(entry => entry?.Trim() ?? "")
+ .Distinct(StringComparer.Ordinal)
+ .ToArray();
+
+ Array.Sort(invalid, StringComparer.Ordinal);
+ return invalid;
+ }
+
+ ///
+ /// Accepts what Traefik accepts (Go net.ParseIP / net.ParseCIDR): a bare IPv4/IPv6 address or a CIDR range. The
+ /// address of a range may have host bits set (Akamai publishes e.g. 192.0.2.114/24), so System.Net.IPNetwork is
+ /// deliberately not used. System.Net.IPAddress alone is too lenient: it also parses shortened (10/8), hex and
+ /// octal (0x7f.0.0.1, 010.0.0.1) IPv4 octets, bracketed IPv6 ([::1]) and zone ids (fe80::1%eth0), all of which
+ /// Traefik rejects, and an unparsable sourceRange disables every router using the middleware.
+ ///
+ public static bool IsValidSourceRange(string value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ return false;
+ }
+
+ var trimmed = value.Trim();
+ var slash = trimmed.IndexOf('/');
+ var addressPart = slash < 0 ? trimmed : trimmed.Substring(0, slash);
+ var isIPv6 = addressPart.IndexOf(':') >= 0;
+
+ if (isIPv6 ? !IsStrictIPv6(addressPart) : !IsStrictIPv4(addressPart))
+ {
+ return false;
+ }
+
+ if (slash < 0)
+ {
+ return true;
+ }
+
+ var prefixPart = trimmed.Substring(slash + 1);
+ if (!IsDecimalWithoutLeadingZeros(prefixPart) || !int.TryParse(prefixPart, NumberStyles.None, CultureInfo.InvariantCulture, out var prefixLength))
+ {
+ return false;
+ }
+
+ return prefixLength <= (isIPv6 ? 128 : 32);
+ }
+
+ /// Exactly four decimal octets of up to three digits without leading zeros, each at most 255.
+ private static bool IsStrictIPv4(string address)
+ {
+ var octets = address.Split('.');
+ if (octets.Length != 4)
+ {
+ return false;
+ }
+
+ foreach (var octet in octets)
+ {
+ if (!IsDecimalWithoutLeadingZeros(octet) || octet.Length > 3 || int.Parse(octet, CultureInfo.InvariantCulture) > 255)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// Hex groups and colons only (optionally with an embedded strict IPv4 address), no brackets, no zone id.
+ private static bool IsStrictIPv6(string address)
+ {
+ foreach (var c in address)
+ {
+ if (!(c == ':' || c == '.' || Uri.IsHexDigit(c)))
+ {
+ return false;
+ }
+ }
+
+ if (address.IndexOf('.') >= 0 && !IsStrictIPv4(address.Substring(address.LastIndexOf(':') + 1)))
+ {
+ return false;
+ }
+
+ return IPAddress.TryParse(address, out var parsed) && parsed.AddressFamily == AddressFamily.InterNetworkV6;
+ }
+
+ private static bool IsDecimalWithoutLeadingZeros(string digits)
+ {
+ if (digits.Length == 0 || digits.Any(c => c < '0' || c > '9'))
+ {
+ return false;
+ }
+
+ return digits.Length == 1 || digits[0] != '0';
+ }
+ }
+}
diff --git a/Startup.cs b/Startup.cs
index f445c4c..7ea896b 100644
--- a/Startup.cs
+++ b/Startup.cs
@@ -1,8 +1,13 @@
-using Microsoft.AspNetCore.Builder;
+using System;
+using System.Net.Http;
+using ConplementAG.CopsController.Services;
+using k8s;
+using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Options;
namespace ConplementAG.CopsController
{
@@ -19,6 +24,26 @@ public Startup(IConfiguration configuration)
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson();
+
+ // CopsTraefikSiteShieldMiddleware sync
+ services.Configure(Configuration.GetSection(SiteShieldOptions.SectionName));
+
+ services.AddHttpClient(AkamaiSiteShieldClient.HttpClientName)
+ .ConfigureHttpClient((serviceProvider, client) =>
+ {
+ client.Timeout = TimeSpan.FromSeconds(serviceProvider.GetRequiredService>().Value.RequestTimeoutSeconds);
+ })
+ // EdgeGrid signatures are valid for one hop only, a redirect would have to be signed again
+ .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false });
+
+ // Resolved lazily with the first siteshield request: in-cluster configuration inside the pod, kubeconfig
+ // fallback when running locally (telepresence). The CopsNamespace sync never touches it.
+ services.AddSingleton(_ => new Kubernetes(KubernetesClientConfiguration.BuildDefaultConfig()));
+ services.AddSingleton();
+ services.AddSingleton(TimeProvider.System);
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
diff --git a/appsettings.json b/appsettings.json
index 74e66c3..a720986 100644
--- a/appsettings.json
+++ b/appsettings.json
@@ -1,11 +1,19 @@
-{
- "Logging": {
- "LogLevel": {
- "Default": "Information"
- }
- },
- "AllowedHosts": "*",
- "CopsController": {
- "NamespaceAdminRole": "cluster-admin"
- }
-}
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Error"
+ }
+ },
+ "Serilog": {
+ "MinimumLevel": "Error"
+ },
+ "AllowedHosts": "*",
+ "CopsController": {
+ "NamespaceAdminRole": "cluster-admin",
+ "SiteShield": {
+ "CredentialsSecretName": "akamai-siteshield-credentials",
+ "ErrorResyncAfterSeconds": 300,
+ "RequestTimeoutSeconds": 20
+ }
+ }
+}
diff --git a/deployment/cops-controller/templates/03-deployment.yaml b/deployment/cops-controller/templates/03-deployment.yaml
index 2e50820..22784fc 100644
--- a/deployment/cops-controller/templates/03-deployment.yaml
+++ b/deployment/cops-controller/templates/03-deployment.yaml
@@ -20,6 +20,7 @@ spec:
app: {{ template "cops-controller.name" . }}
release: {{ .Release.Name }}
spec:
+ serviceAccountName: {{ template "cops-controller.name" . }}
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:v{{ .Values.image.tag }}"
@@ -30,7 +31,8 @@ spec:
protocol: TCP
env:
- name: Serilog__MinimumLevel
- value: Error
+ value: {{ .Values.copsController.logLevel | quote }}
- name: CopsController__NamespaceAdminRole
value: {{ .Values.copsController.namespaceAdminRole }}
-
\ No newline at end of file
+ - name: CopsController__SiteShield__CredentialsSecretName
+ value: {{ .Values.siteShield.credentialsSecretName | quote }}
diff --git a/deployment/cops-controller/templates/05-siteshield-controller.yaml b/deployment/cops-controller/templates/05-siteshield-controller.yaml
new file mode 100644
index 0000000..a96b961
--- /dev/null
+++ b/deployment/cops-controller/templates/05-siteshield-controller.yaml
@@ -0,0 +1,23 @@
+apiVersion: metacontroller.k8s.io/v1alpha1
+kind: CompositeController
+metadata:
+ name: {{ template "cops-controller.name" . }}-siteshield
+spec:
+ generateSelector: true
+ # periodic re-sync against the Akamai SiteShield API, even if nothing changed in the cluster
+ resyncPeriodSeconds: {{ .Values.siteShield.resyncPeriodSeconds }}
+ parentResource:
+ apiVersion: coreops.conplement.cloud/v1
+ resource: copstraefiksiteshieldmiddlewares
+ childResources:
+ - apiVersion: traefik.io/v1alpha1
+ resource: middlewares
+ updateStrategy:
+ method: InPlace
+ hooks:
+ sync:
+ webhook:
+ url: http://{{ template "cops-controller.name" . }}.{{ .Release.Namespace }}/api/siteshield/sync
+ # the hook reads a secret and calls the Akamai API (request timeout 20s each, see
+ # CopsController__SiteShield__RequestTimeoutSeconds); the metacontroller default is 10s
+ timeout: 45s
diff --git a/deployment/cops-controller/templates/06-serviceaccount.yaml b/deployment/cops-controller/templates/06-serviceaccount.yaml
new file mode 100644
index 0000000..97d6743
--- /dev/null
+++ b/deployment/cops-controller/templates/06-serviceaccount.yaml
@@ -0,0 +1,9 @@
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: {{ template "cops-controller.name" . }}
+ labels:
+ app: {{ template "cops-controller.name" . }}
+ chart: {{ template "cops-controller.chart" . }}
+ release: {{ .Release.Name }}
+ heritage: {{ .Release.Service }}
diff --git a/deployment/cops-controller/templates/07-siteshield-credentials-rbac.yaml b/deployment/cops-controller/templates/07-siteshield-credentials-rbac.yaml
new file mode 100644
index 0000000..dac1f73
--- /dev/null
+++ b/deployment/cops-controller/templates/07-siteshield-credentials-rbac.yaml
@@ -0,0 +1,35 @@
+# Allows the controller to read the Akamai credentials secret in any namespace, but only the secret with the fixed
+# name used by CopsTraefikSiteShieldMiddleware resources. Only "get" is granted: list and watch cannot be
+# restricted to resource names.
+apiVersion: rbac.authorization.k8s.io/v1
+kind: ClusterRole
+metadata:
+ name: {{ template "cops-controller.name" . }}-siteshield-credentials-reader
+ labels:
+ app: {{ template "cops-controller.name" . }}
+ chart: {{ template "cops-controller.chart" . }}
+ release: {{ .Release.Name }}
+ heritage: {{ .Release.Service }}
+rules:
+- apiGroups: [""]
+ resources: ["secrets"]
+ resourceNames: [{{ .Values.siteShield.credentialsSecretName | quote }}]
+ verbs: ["get"]
+---
+apiVersion: rbac.authorization.k8s.io/v1
+kind: ClusterRoleBinding
+metadata:
+ name: {{ template "cops-controller.name" . }}-siteshield-credentials-reader
+ labels:
+ app: {{ template "cops-controller.name" . }}
+ chart: {{ template "cops-controller.chart" . }}
+ release: {{ .Release.Name }}
+ heritage: {{ .Release.Service }}
+roleRef:
+ apiGroup: rbac.authorization.k8s.io
+ kind: ClusterRole
+ name: {{ template "cops-controller.name" . }}-siteshield-credentials-reader
+subjects:
+- kind: ServiceAccount
+ name: {{ template "cops-controller.name" . }}
+ namespace: {{ .Release.Namespace }}
diff --git a/deployment/cops-controller/values.yaml b/deployment/cops-controller/values.yaml
index cfb78c6..9bbdbdc 100644
--- a/deployment/cops-controller/values.yaml
+++ b/deployment/cops-controller/values.yaml
@@ -2,4 +2,16 @@ image:
repository: conplementag/cops-controller
tag: 1.12.0 # x-release-please-version
copsController:
- namespaceAdminRole: cluster-admin
\ No newline at end of file
+ namespaceAdminRole: cluster-admin
+ # Serilog minimum level of the controller logs (Verbose, Debug, Information, Warning, Error, Fatal)
+ logLevel: Error
+siteShield:
+ # CopsTraefikSiteShieldMiddleware controller. Requires the traefik CRDs (middlewares.traefik.io), which are part of
+ # every cops cluster.
+ # How often (in seconds) every CopsTraefikSiteShieldMiddleware is re-synced with the Akamai SiteShield API when
+ # nothing changed in the cluster: once a day. Failed syncs are retried every 5 minutes until they succeed.
+ resyncPeriodSeconds: 86400
+ # Fixed name of the secret holding the Akamai EdgeGrid credentials (keys host, client_token, client_secret,
+ # access_token, or one key edgerc with an .edgerc file). It is read from the namespace of each
+ # CopsTraefikSiteShieldMiddleware; the controller is only allowed to read secrets with exactly this name.
+ credentialsSecretName: akamai-siteshield-credentials
diff --git a/deployment/crds/copstraefiksiteshieldmiddleware.crd.yaml b/deployment/crds/copstraefiksiteshieldmiddleware.crd.yaml
new file mode 100644
index 0000000..b3b6c5c
--- /dev/null
+++ b/deployment/crds/copstraefiksiteshieldmiddleware.crd.yaml
@@ -0,0 +1,121 @@
+apiVersion: apiextensions.k8s.io/v1
+kind: CustomResourceDefinition
+metadata:
+ name: copstraefiksiteshieldmiddlewares.coreops.conplement.cloud
+spec:
+ group: coreops.conplement.cloud
+ scope: Namespaced
+ names:
+ kind: CopsTraefikSiteShieldMiddleware
+ listKind: CopsTraefikSiteShieldMiddlewareList
+ plural: copstraefiksiteshieldmiddlewares
+ singular: copstraefiksiteshieldmiddleware
+ shortNames:
+ - ctsm
+ versions:
+ - name: v1
+ served: true
+ storage: true
+ subresources:
+ # status enables the status subresource. It is written by metacontroller from the sync hook response.
+ status: {}
+ additionalPrinterColumns:
+ - name: MapId
+ type: integer
+ jsonPath: .spec.mapId
+ - name: State
+ type: string
+ jsonPath: .status.state
+ - name: CIDRs
+ type: integer
+ jsonPath: .status.cidrCount
+ - name: Age
+ type: date
+ jsonPath: .metadata.creationTimestamp
+ schema:
+ openAPIV3Schema:
+ description: |-
+ Generates a Traefik Middleware (traefik.io/v1alpha1) of type ipAllowList with the same name in the same
+ namespace. Its sourceRange contains the current and the proposed CIDRs of an Akamai SiteShield map.
+ The Akamai API credentials are read from the secret "akamai-siteshield-credentials" in the same namespace
+ (keys host, client_token, client_secret, access_token, or one key edgerc with an .edgerc file).
+ type: object
+ required:
+ - spec
+ properties:
+ spec:
+ type: object
+ required:
+ - mapId
+ properties:
+ mapId:
+ description: |-
+ Numeric id of the Akamai SiteShield map (see Akamai Control Center or GET /siteshield/v1/maps).
+ The currentCidrs and proposedCidrs of this map are merged into the sourceRange of the Middleware.
+ type: integer
+ format: int64
+ minimum: 1
+ additionalSourceRanges:
+ description: |-
+ Optional additional IP addresses or CIDR ranges which are allowed in addition to the Akamai
+ SiteShield ranges.
+ type: array
+ items:
+ type: string
+ minLength: 1
+ ipStrategy:
+ description: |-
+ Optional Traefik ipStrategy, passed through unchanged to spec.ipAllowList.ipStrategy of the Middleware.
+ type: object
+ properties:
+ depth:
+ description: |-
+ Position of the client IP in the X-Forwarded-For header, counted from the right (0 = disabled).
+ type: integer
+ minimum: 0
+ excludedIPs:
+ description: |-
+ IP addresses or CIDR ranges to skip when scanning the X-Forwarded-For header (ignored when
+ depth is set).
+ type: array
+ items:
+ type: string
+ ipv6Subnet:
+ description: |-
+ Reduces IPv6 client addresses to the first address of a subnet of this size (1-128).
+ Requires Traefik 3.2 or newer.
+ type: integer
+ minimum: 1
+ maximum: 128
+ status:
+ type: object
+ properties:
+ state:
+ description: |-
+ Ready when the Middleware is in sync with the Akamai SiteShield map, Error otherwise (see message).
+ type: string
+ enum:
+ - Ready
+ - Error
+ message:
+ type: string
+ mapId:
+ type: integer
+ format: int64
+ mapAlias:
+ type: string
+ cidrCount:
+ description: |-
+ Number of entries in the generated sourceRange.
+ type: integer
+ acknowledged:
+ description: |-
+ Whether the proposed CIDRs of the map have been acknowledged in Akamai.
+ type: boolean
+ lastCidrChange:
+ description: |-
+ Timestamp (RFC3339) of the last change of the generated sourceRange.
+ type: string
+ observedGeneration:
+ type: integer
+ format: int64
diff --git a/packages.lock.json b/packages.lock.json
index 5ee7654..403ffaa 100644
--- a/packages.lock.json
+++ b/packages.lock.json
@@ -2,6 +2,16 @@
"version": 1,
"dependencies": {
"net10.0": {
+ "KubernetesClient": {
+ "type": "Direct",
+ "requested": "[21.0.41, )",
+ "resolved": "21.0.41",
+ "contentHash": "PMf2gothjvOhnby/ihpZXkex/OiKtOJobTTd2VVYENvzexwoi9fHy65Wjxg4hYSEO+W/GSYU7MmtxZEV+CQN+Q==",
+ "dependencies": {
+ "Fractions": "8.3.2",
+ "YamlDotNet": "18.1.0"
+ }
+ },
"Microsoft.AspNetCore.Mvc.NewtonsoftJson": {
"type": "Direct",
"requested": "[10.0.12, )",
@@ -47,6 +57,11 @@
"Serilog": "4.0.0"
}
},
+ "Fractions": {
+ "type": "Transitive",
+ "resolved": "8.3.2",
+ "contentHash": "q0Xzg9nmBd1Y0fTn/EEG84dWqd02EogojtdBh/MUmtHhwIJBMJk3jo+4MRDCdLfi6lVDXD8UZBA0QkBH3FUh8A=="
+ },
"Microsoft.AspNetCore.JsonPatch": {
"type": "Transitive",
"resolved": "10.0.12",
@@ -118,6 +133,11 @@
"dependencies": {
"Serilog": "4.2.0"
}
+ },
+ "YamlDotNet": {
+ "type": "Transitive",
+ "resolved": "18.1.0",
+ "contentHash": "5K+9KFg2TdTl7VXv88Qzi/0lqK6JFoNP3lRuImPYGRV7K/QYklDyTrj4+A+KAki1JsQi6qKY+hDyY7d6WRqjrw=="
}
}
}
diff --git a/run_tests.sh b/run_tests.sh
index 0c74d6a..6e17fcf 100755
--- a/run_tests.sh
+++ b/run_tests.sh
@@ -59,6 +59,11 @@ function cleanup {
kubectl delete $namespaces --ignore-not-found
fi
+ if kubectl get crd copstraefiksiteshieldmiddlewares.coreops.conplement.cloud > /dev/null 2>&1; then
+ echo "Deleting all cops traefik siteshield middlewares for cleanup..."
+ kubectl delete ctsm --all-namespaces -l tests=$UNIVERSAL_TEST_IDENTIFIED --ignore-not-found
+ fi
+
echo "Deleting all remaining RBAC rules..."
clusterRoles=$(kubectl get clusterroles -o name -l tests=$UNIVERSAL_TEST_IDENTIFIED)
clusterRoleBindings=$(kubectl get clusterrolebindings -o name -l tests=$UNIVERSAL_TEST_IDENTIFIED)
diff --git a/tests/ConplementAG.CopsController.Tests/AkamaiCredentialsTests.cs b/tests/ConplementAG.CopsController.Tests/AkamaiCredentialsTests.cs
new file mode 100644
index 0000000..fa953b4
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/AkamaiCredentialsTests.cs
@@ -0,0 +1,139 @@
+using System.Collections.Generic;
+using System.Text;
+using ConplementAG.CopsController.Models;
+using ConplementAG.CopsController.Services;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ public class AkamaiCredentialsTests
+ {
+ private static Dictionary Data(string host = "akab-x.luna.akamaiapis.net", string clientToken = "ct", string clientSecret = "cs", string accessToken = "at")
+ {
+ var data = new Dictionary();
+
+ void Add(string key, string value)
+ {
+ if (value != null)
+ {
+ data[key] = Encoding.UTF8.GetBytes(value);
+ }
+ }
+
+ Add("host", host);
+ Add("client_token", clientToken);
+ Add("client_secret", clientSecret);
+ Add("access_token", accessToken);
+ return data;
+ }
+
+ [Fact]
+ public void FromSecretData_TrimsValuesAndNormalizesHost()
+ {
+ var credentials = AkamaiCredentials.FromSecretData(Data(host: "https://akab-x.luna.akamaiapis.net/\n", clientToken: "ct\n"), "myapp", "akamai-siteshield-credentials");
+
+ Assert.Equal("akab-x.luna.akamaiapis.net", credentials.Host);
+ Assert.Equal("ct", credentials.ClientToken);
+ Assert.Equal("cs", credentials.ClientSecret);
+ Assert.Equal("at", credentials.AccessToken);
+ }
+
+ [Fact]
+ public void FromSecretData_ReportsMissingAndEmptyKeysSorted()
+ {
+ var ex = Assert.Throws(() => AkamaiCredentials.FromSecretData(Data(host: " ", accessToken: null), "myapp", "akamai-siteshield-credentials"));
+
+ Assert.StartsWith("Credentials secret myapp/akamai-siteshield-credentials is missing key(s): access_token, host", ex.Message);
+ }
+
+ [Fact]
+ public void FromSecretData_WithoutData_ReportsAllKeys()
+ {
+ var ex = Assert.Throws(() => AkamaiCredentials.FromSecretData(null, "myapp", "akamai-siteshield-credentials"));
+
+ Assert.StartsWith("Credentials secret myapp/akamai-siteshield-credentials is missing key(s): access_token, client_secret, client_token, host", ex.Message);
+ Assert.Contains("[default] section of the key edgerc", ex.Message);
+ }
+
+ private const string Edgerc = "[default]\r\nclient_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN=\r\nhost = akab-x.luna.akamaiapis.net\r\naccess_token = akab-access\r\nclient_token = akab-client\r\nmax-body = 131072\r\n";
+
+ private static Dictionary EdgercData(string content) => new Dictionary { ["edgerc"] = Encoding.UTF8.GetBytes(content) };
+
+ [Fact]
+ public void FromSecretData_ReadsEdgercFormat()
+ {
+ var credentials = AkamaiCredentials.FromSecretData(EdgercData(Edgerc), "myapp", "akamai-siteshield-credentials");
+
+ Assert.Equal("akab-x.luna.akamaiapis.net", credentials.Host);
+ Assert.Equal("akab-client", credentials.ClientToken);
+ Assert.Equal("C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN=", credentials.ClientSecret);
+ Assert.Equal("akab-access", credentials.AccessToken);
+ }
+
+ [Fact]
+ public void FromSecretData_SeparateKeysWinOverEdgerc()
+ {
+ var data = EdgercData(Edgerc);
+ data["host"] = Encoding.UTF8.GetBytes("https://other.luna.akamaiapis.net");
+
+ var credentials = AkamaiCredentials.FromSecretData(data, "myapp", "akamai-siteshield-credentials");
+
+ Assert.Equal("other.luna.akamaiapis.net", credentials.Host);
+ Assert.Equal("akab-client", credentials.ClientToken);
+ }
+
+ [Fact]
+ public void FromSecretData_EdgercWithoutDefaultSectionAmongSeveral_ReportsMissingKeys()
+ {
+ var content = "[papi]\nhost = a\nclient_token = b\nclient_secret = c\naccess_token = d\n[siteshield]\nhost = e\nclient_token = f\nclient_secret = g\naccess_token = h\n";
+
+ var ex = Assert.Throws(() => AkamaiCredentials.FromSecretData(EdgercData(content), "myapp", "akamai-siteshield-credentials"));
+
+ Assert.Contains("missing key(s): access_token, client_secret, client_token, host", ex.Message);
+ }
+
+ [Fact]
+ public void ParseEdgerc_UsesRequestedSectionAndIgnoresCommentsAndQuotes()
+ {
+ var content = "# comment\n; another comment\n\n[other]\nhost = other\n[default]\n host = \"akab-x.luna.akamaiapis.net\" \nclient_token='akab-client'\nbroken line without separator\nclient_secret = a=b==\n";
+
+ var values = AkamaiCredentials.ParseEdgerc(content, "default");
+
+ Assert.Equal("akab-x.luna.akamaiapis.net", values["host"]);
+ Assert.Equal("akab-client", values["client_token"]);
+ Assert.Equal("a=b==", values["client_secret"]);
+ Assert.False(values.ContainsKey("access_token"));
+ }
+
+ [Fact]
+ public void ParseEdgerc_FallsBackToTheOnlySectionOrToHeaderlessContent()
+ {
+ Assert.Equal("a", AkamaiCredentials.ParseEdgerc("[siteshield]\nhost = a\n", "default")["host"]);
+ Assert.Equal("b", AkamaiCredentials.ParseEdgerc("host = b\n", "default")["host"]);
+ Assert.Empty(AkamaiCredentials.ParseEdgerc("", "default"));
+ Assert.Empty(AkamaiCredentials.ParseEdgerc(null, "default"));
+ }
+
+ [Theory]
+ [InlineData("akab-x.luna.akamaiapis.net", "akab-x.luna.akamaiapis.net")]
+ [InlineData("HTTPS://akab-x.luna.akamaiapis.net", "akab-x.luna.akamaiapis.net")]
+ [InlineData("http://akab-x.luna.akamaiapis.net//", "akab-x.luna.akamaiapis.net")]
+ [InlineData(" akab-x.luna.akamaiapis.net/ ", "akab-x.luna.akamaiapis.net")]
+ [InlineData(null, "")]
+ public void NormalizeHost_StripsSchemeAndSlashes(string input, string expected)
+ {
+ Assert.Equal(expected, AkamaiCredentials.NormalizeHost(input));
+ }
+
+ [Fact]
+ public void ToString_DoesNotExposeSecrets()
+ {
+ var text = new AkamaiCredentials("host", "token-value", "secret-value", "access-value").ToString();
+
+ Assert.Contains("host", text);
+ Assert.DoesNotContain("secret-value", text);
+ Assert.DoesNotContain("token-value", text);
+ Assert.DoesNotContain("access-value", text);
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/AkamaiSiteShieldClientTests.cs b/tests/ConplementAG.CopsController.Tests/AkamaiSiteShieldClientTests.cs
new file mode 100644
index 0000000..1306b60
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/AkamaiSiteShieldClientTests.cs
@@ -0,0 +1,157 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Models;
+using ConplementAG.CopsController.Services;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ public class AkamaiSiteShieldClientTests
+ {
+ private const string MapJson = @"{
+ ""id"": 12345, ""mapAlias"": ""prod-map"", ""ruleName"": ""s12345.akamaiedge.net"", ""service"": ""S"", ""type"": ""Production"",
+ ""currentCidrs"": [ ""23.0.0.0/12"", ""2.16.0.0/13"" ], ""proposedCidrs"": [ ""104.64.0.0/10"" ],
+ ""acknowledged"": false, ""acknowledgeRequiredBy"": 1767225600000, ""latestTicketId"": 42,
+ ""contacts"": [ ""someone@example.com"" ], ""shared"": false
+ }";
+
+ /// Captures the outgoing request (the client disposes it after sending) and answers with a canned response.
+ private sealed class FakeHttpMessageHandler : HttpMessageHandler
+ {
+ private readonly HttpStatusCode _statusCode;
+ private readonly string _body;
+
+ public FakeHttpMessageHandler(HttpStatusCode statusCode, string body)
+ {
+ _statusCode = statusCode;
+ _body = body;
+ }
+
+ public HttpMethod Method { get; private set; }
+ public Uri Uri { get; private set; }
+ public Dictionary Headers { get; } = new Dictionary();
+
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ Method = request.Method;
+ Uri = request.RequestUri;
+ foreach (var header in request.Headers)
+ {
+ Headers[header.Key] = string.Join(", ", header.Value);
+ }
+
+ return Task.FromResult(new HttpResponseMessage(_statusCode) { Content = new StringContent(_body ?? "") });
+ }
+ }
+
+ private sealed class FakeHttpClientFactory : IHttpClientFactory
+ {
+ private readonly HttpMessageHandler _handler;
+
+ public FakeHttpClientFactory(HttpMessageHandler handler)
+ {
+ _handler = handler;
+ }
+
+ public List RequestedNames { get; } = new List();
+
+ public HttpClient CreateClient(string name)
+ {
+ RequestedNames.Add(name);
+ return new HttpClient(_handler, disposeHandler: false);
+ }
+ }
+
+ private static readonly AkamaiCredentials Credentials = new AkamaiCredentials("akab-x.luna.akamaiapis.net", "akab-client-token", "c2VjcmV0", "akab-access-token");
+
+ private static (AkamaiSiteShieldClient client, FakeHttpMessageHandler handler, FakeHttpClientFactory factory) Setup(HttpStatusCode statusCode, string body)
+ {
+ var handler = new FakeHttpMessageHandler(statusCode, body);
+ var factory = new FakeHttpClientFactory(handler);
+ return (new AkamaiSiteShieldClient(factory), handler, factory);
+ }
+
+ [Fact]
+ public async Task GetMapAsync_SendsSignedGetRequestToSiteShieldApi()
+ {
+ var (client, handler, factory) = Setup(HttpStatusCode.OK, MapJson);
+
+ await client.GetMapAsync(Credentials, 12345, CancellationToken.None);
+
+ Assert.Equal(new[] { AkamaiSiteShieldClient.HttpClientName }, factory.RequestedNames);
+ Assert.Equal(HttpMethod.Get, handler.Method);
+ Assert.Equal("https://akab-x.luna.akamaiapis.net/siteshield/v1/maps/12345", handler.Uri.ToString());
+ Assert.Equal("application/json", handler.Headers["Accept"]);
+
+ var authorization = handler.Headers["Authorization"];
+ Assert.StartsWith("EG1-HMAC-SHA256 ", authorization);
+ Assert.Contains("client_token=akab-client-token;", authorization);
+ Assert.Contains("access_token=akab-access-token;", authorization);
+ Assert.Contains("timestamp=", authorization);
+ Assert.Contains("nonce=", authorization);
+ Assert.Contains("signature=", authorization);
+ Assert.DoesNotContain("c2VjcmV0", authorization);
+ }
+
+ [Fact]
+ public async Task GetMapAsync_MapsResponseAndIgnoresUnknownFields()
+ {
+ var (client, _, _) = Setup(HttpStatusCode.OK, MapJson);
+
+ var map = await client.GetMapAsync(Credentials, 12345, CancellationToken.None);
+
+ Assert.Equal(12345, map.Id);
+ Assert.Equal("prod-map", map.MapAlias);
+ Assert.Equal("s12345.akamaiedge.net", map.RuleName);
+ Assert.Equal(new[] { "23.0.0.0/12", "2.16.0.0/13" }, map.CurrentCidrs);
+ Assert.Equal(new[] { "104.64.0.0/10" }, map.ProposedCidrs);
+ Assert.False(map.Acknowledged);
+ Assert.Equal(1767225600000, map.AcknowledgeRequiredBy);
+ Assert.Equal(42, map.LatestTicketId);
+ }
+
+ [Theory]
+ [InlineData(HttpStatusCode.NotFound, "Akamai SiteShield map 12345 not found (HTTP 404)")]
+ [InlineData(HttpStatusCode.Forbidden, "Access to Akamai SiteShield map 12345 denied (HTTP 403); check the permissions of the API client")]
+ [InlineData(HttpStatusCode.Unauthorized, "Akamai SiteShield authentication failed (HTTP 401); check the credentials secret")]
+ [InlineData(HttpStatusCode.InternalServerError, "Akamai SiteShield API returned HTTP 500")]
+ [InlineData(HttpStatusCode.TooManyRequests, "Akamai SiteShield API returned HTTP 429")]
+ public async Task GetMapAsync_ErrorStatus_ReportsStableMessage(HttpStatusCode statusCode, string expectedMessage)
+ {
+ var (client, _, _) = Setup(statusCode, @"{ ""type"": ""error"", ""detail"": ""some volatile detail with request id 0xdeadbeef"" }");
+
+ var ex = await Assert.ThrowsAsync(() => client.GetMapAsync(Credentials, 12345, CancellationToken.None));
+
+ Assert.Equal(expectedMessage, ex.Message);
+ Assert.Equal(statusCode, ex.StatusCode);
+ Assert.Contains("0xdeadbeef", ex.ResponseBody);
+ }
+
+ [Theory]
+ [InlineData("this is not json")]
+ [InlineData("{}")]
+ [InlineData("[]")]
+ [InlineData("")]
+ public async Task GetMapAsync_UnexpectedBody_ReportsStableMessage(string body)
+ {
+ var (client, _, _) = Setup(HttpStatusCode.OK, body);
+
+ var ex = await Assert.ThrowsAsync(() => client.GetMapAsync(Credentials, 12345, CancellationToken.None));
+
+ Assert.Equal("Akamai SiteShield API returned an unexpected response body", ex.Message);
+ }
+
+ [Fact]
+ public async Task GetMapAsync_RequiresCredentials()
+ {
+ var (client, _, _) = Setup(HttpStatusCode.OK, MapJson);
+
+ await Assert.ThrowsAsync(() => client.GetMapAsync(null, 12345, CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/ConplementAG.CopsController.Tests.csproj b/tests/ConplementAG.CopsController.Tests/ConplementAG.CopsController.Tests.csproj
new file mode 100644
index 0000000..ecadbc3
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/ConplementAG.CopsController.Tests.csproj
@@ -0,0 +1,17 @@
+
+
+ net10.0
+ false
+ true
+ ConplementAG.CopsController.Tests
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/ConplementAG.CopsController.Tests/EdgeGridOfficialVectorTests.cs b/tests/ConplementAG.CopsController.Tests/EdgeGridOfficialVectorTests.cs
new file mode 100644
index 0000000..29e4cd0
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/EdgeGridOfficialVectorTests.cs
@@ -0,0 +1,67 @@
+using System;
+using System.Net.Http;
+using System.Text;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Models;
+using ConplementAG.CopsController.Services;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ ///
+ /// Pins to the official EdgeGrid test vectors shipped with Akamai's reference
+ /// client (AkamaiOPEN-edgegrid-python, akamai/edgegrid/test/testdata.json and testcases.json). Only the cases
+ /// without signed custom headers are used, because this signer never includes headers in the signature.
+ ///
+ public class EdgeGridOfficialVectorTests
+ {
+ private const string Host = "akaa-baseurl-xxxxxxxxxxx-xxxxxxxxxxxxx.luna.akamaiapis.net";
+ private const int MaxBody = 2048;
+
+ private static readonly AkamaiCredentials Credentials = new AkamaiCredentials(
+ Host,
+ "akab-client-token-xxx-xxxxxxxxxxxxxxxx",
+ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=",
+ "akab-access-token-xxx-xxxxxxxxxxxxxxxx");
+
+ private static readonly DateTimeOffset Timestamp = new DateTimeOffset(2014, 3, 21, 19, 34, 21, TimeSpan.Zero);
+ private const string Nonce = "nonce-xx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
+
+ private const string ExpectedPrefix = "EG1-HMAC-SHA256 client_token=akab-client-token-xxx-xxxxxxxxxxxxxxxx;access_token=akab-access-token-xxx-xxxxxxxxxxxxxxxx;timestamp=20140321T19:34:21+0000;nonce=nonce-xx-xxxx-xxxx-xxxx-xxxxxxxxxxxx;signature=";
+
+ private static async Task SignAsync(string method, string path, string body)
+ {
+ var request = new HttpRequestMessage(new HttpMethod(method), "https://" + Host + path);
+ if (body != null)
+ {
+ request.Content = new ByteArrayContent(Encoding.ASCII.GetBytes(body));
+ }
+
+ await EdgeGridRequestSigner.SignAsync(request, Credentials, Timestamp, Nonce, MaxBody);
+ return string.Join(" ", request.Headers.GetValues("Authorization"));
+ }
+
+ [Theory]
+ [InlineData("simple GET", "GET", "/", null, "tL+y4hxyHxgWVD30X3pWnGKHcPzmrIF+LThiAOhMxYU=")]
+ [InlineData("GET with querystring", "GET", "/testapi/v1/t1?p1=1&p2=2", null, "hKDH1UlnQySSHjvIcZpDMbQHihTQ0XyVAKZaApabdeA=")]
+ [InlineData("POST inside limit", "POST", "/testapi/v1/t3", "datadatadatadatadatadatadatadata", "hXm4iCxtpN22m4cbZb4lVLW5rhX8Ca82vCFqXzSTPe4=")]
+ [InlineData("POST empty body", "POST", "/testapi/v1/t6", "", "1gEDxeQGD5GovIkJJGcBaKnZ+VaPtrc4qBUHixjsPCQ=")]
+ [InlineData("PUT test", "PUT", "/testapi/v1/t6", "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP", "GNBWEYSEWOLtu+7dD52da2C39aX/Jchpon3K/AmBqBU=")]
+ [InlineData("PATCH test", "PATCH", "/testapi/v1/t6", "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP", "JIl05ImY1AOnMtmw+9LKgaFA8mnzsEKabbnHmI8LsQ4=")]
+ [InlineData("GET with query params", "GET", "/testapi/v1/configs/111?from=12345&limit=200000", null, "XM+hsuSs6nuy/5eDRty1IjtVCAdr8xPFRAZ/b8RXDm8=")]
+ [InlineData("GET with query params and separator in path", "GET", "/testapi/v1/configs/111;222;333?from=12345&limit=200000", null, "pmQF7Is2+O4r/mMojPR4yeF58BrempNNoBX5/DT0Fxs=")]
+ public async Task SignAsync_MatchesOfficialVector(string testName, string method, string path, string body, string expectedSignature)
+ {
+ Assert.Equal(ExpectedPrefix + expectedSignature, await SignAsync(method, path, body));
+ }
+
+ [Theory]
+ [InlineData("POST length equals max_body", 2048)]
+ [InlineData("POST too large", 4096)]
+ public async Task SignAsync_HashesOnlyTheFirstMaxBodyBytesOfAPost(string testName, int bodyLength)
+ {
+ // both official cases expect the same signature: the body is truncated to max_body before hashing
+ Assert.Equal(ExpectedPrefix + "6Q6PiTipLae6n4GsSIDTCJ54bEbHUBp+4MUXrbQCBoY=", await SignAsync("POST", "/testapi/v1/t3", new string('d', bodyLength)));
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/EdgeGridRequestSignerTests.cs b/tests/ConplementAG.CopsController.Tests/EdgeGridRequestSignerTests.cs
new file mode 100644
index 0000000..009c42b
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/EdgeGridRequestSignerTests.cs
@@ -0,0 +1,135 @@
+using System;
+using System.Globalization;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Models;
+using ConplementAG.CopsController.Services;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ public class EdgeGridRequestSignerTests
+ {
+ private const string Host = "akab-h05tnam3wl42son7nktnlnnx-kbob3i3v.luna.akamaiapis.net";
+ private const string ClientToken = "akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj";
+ private const string ClientSecret = "C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN=";
+ private const string AccessToken = "akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij";
+
+ private static readonly AkamaiCredentials Credentials = new AkamaiCredentials(Host, ClientToken, ClientSecret, AccessToken);
+
+ private static readonly Regex AuthorizationPattern = new Regex(
+ @"^EG1-HMAC-SHA256 client_token=(?[^;]+);access_token=(?[^;]+);timestamp=(?[^;]+);nonce=(?[^;]+);signature=(?[^;]+)$");
+
+ ///
+ /// Independent re-implementation of the algorithm as documented by Akamai and implemented by the reference
+ /// clients (edgegrid-python / edgegrid-golang). Kept separate from the production code on purpose.
+ ///
+ private static string ReferenceSignature(string method, string host, string relativeUrl, string contentHash, string timestamp, string nonce)
+ {
+ var authHeaderWithoutSignature = $"EG1-HMAC-SHA256 client_token={ClientToken};access_token={AccessToken};timestamp={timestamp};nonce={nonce};";
+ var dataToSign = string.Join("\t", method, "https", host, relativeUrl, "", contentHash, authHeaderWithoutSignature);
+
+ var signingKey = Base64Hmac(Encoding.UTF8.GetBytes(ClientSecret), timestamp);
+ return Base64Hmac(Encoding.UTF8.GetBytes(signingKey), dataToSign);
+ }
+
+ private static string Base64Hmac(byte[] key, string message)
+ {
+ using var hmac = new HMACSHA256(key);
+ return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(message)));
+ }
+
+ private static Match Authorization(HttpRequestMessage request)
+ {
+ var authorization = string.Join(" ", request.Headers.GetValues("Authorization"));
+ var match = AuthorizationPattern.Match(authorization);
+ Assert.True(match.Success, "unexpected Authorization header format: " + authorization);
+ return match;
+ }
+
+ [Theory]
+ [InlineData("/siteshield/v1/maps/3974")]
+ [InlineData("/siteshield/v1/maps/3974?accountSwitchKey=1-ABC%3A1-DEF")]
+ public async Task SignAsync_Get_MatchesReferenceAlgorithmWithCurrentTimestamp(string relativeUrl)
+ {
+ var request = new HttpRequestMessage(HttpMethod.Get, $"https://{Host}{relativeUrl}");
+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ await EdgeGridRequestSigner.SignAsync(request, Credentials);
+
+ var match = Authorization(request);
+ Assert.Equal(ClientToken, match.Groups["ct"].Value);
+ Assert.Equal(AccessToken, match.Groups["at"].Value);
+
+ var timestamp = match.Groups["ts"].Value;
+ Assert.Matches(@"^\d{8}T\d{2}:\d{2}:\d{2}\+0000$", timestamp);
+ var parsedTimestamp = DateTimeOffset.ParseExact(timestamp, "yyyyMMdd'T'HH:mm:ss'+0000'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
+ Assert.True(Math.Abs((DateTimeOffset.UtcNow - parsedTimestamp).TotalSeconds) < 30, "timestamp is not the current UTC time: " + timestamp);
+
+ var nonce = match.Groups["nonce"].Value;
+ Assert.True(Guid.TryParse(nonce, out _), "nonce is not a guid: " + nonce);
+
+ Assert.Equal(ReferenceSignature("GET", Host, relativeUrl, "", timestamp, nonce), match.Groups["sig"].Value);
+ }
+
+ [Fact]
+ public async Task SignAsync_UsesGivenTimestampAndNonce()
+ {
+ var request = new HttpRequestMessage(HttpMethod.Get, $"https://{Host}/siteshield/v1/maps/3974");
+
+ await EdgeGridRequestSigner.SignAsync(request, Credentials, new DateTimeOffset(2026, 11, 30, 12, 34, 56, TimeSpan.FromHours(2)), "nonce-xx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
+
+ var match = Authorization(request);
+ Assert.Equal("20261130T10:34:56+0000", match.Groups["ts"].Value);
+ Assert.Equal("nonce-xx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", match.Groups["nonce"].Value);
+ Assert.Equal(ReferenceSignature("GET", Host, "/siteshield/v1/maps/3974", "", "20261130T10:34:56+0000", "nonce-xx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"), match.Groups["sig"].Value);
+ }
+
+ [Fact]
+ public async Task SignAsync_Post_HashesTheBodyUpToMaxBody()
+ {
+ const string body = "{\"key\":\"value\",\"padding\":\"0123456789\"}";
+ var request = new HttpRequestMessage(HttpMethod.Post, $"https://{Host}/siteshield/v1/maps/3974/acknowledge") { Content = new StringContent(body, Encoding.UTF8, "application/json") };
+
+ await EdgeGridRequestSigner.SignAsync(request, Credentials, new DateTimeOffset(2026, 11, 30, 10, 0, 0, TimeSpan.Zero), "n", maxBody: 16);
+
+ var expectedHash = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(body.Substring(0, 16))));
+ Assert.Equal(ReferenceSignature("POST", Host, "/siteshield/v1/maps/3974/acknowledge", expectedHash, "20261130T10:00:00+0000", "n"), Authorization(request).Groups["sig"].Value);
+ }
+
+ [Fact]
+ public async Task SignAsync_ReplacesAnExistingAuthorizationHeader()
+ {
+ var request = new HttpRequestMessage(HttpMethod.Get, $"https://{Host}/siteshield/v1/maps/3974");
+ request.Headers.TryAddWithoutValidation("Authorization", "Bearer stale");
+
+ await EdgeGridRequestSigner.SignAsync(request, Credentials);
+
+ Assert.Single(request.Headers.GetValues("Authorization"));
+ Authorization(request);
+ }
+
+ [Fact]
+ public async Task SignAsync_RejectsEmptyCredentialValues()
+ {
+ var request = new HttpRequestMessage(HttpMethod.Get, $"https://{Host}/siteshield/v1/maps/3974");
+
+ var ex = await Assert.ThrowsAsync(() => EdgeGridRequestSigner.SignAsync(request, new AkamaiCredentials(Host, "", ClientSecret, AccessToken)));
+
+ Assert.Contains("client_token", ex.Message);
+ Assert.DoesNotContain(ClientSecret, ex.Message);
+ }
+
+ [Fact]
+ public async Task SignAsync_RejectsRelativeUris()
+ {
+ var request = new HttpRequestMessage(HttpMethod.Get, new Uri("/siteshield/v1/maps/3974", UriKind.Relative));
+
+ await Assert.ThrowsAsync(() => EdgeGridRequestSigner.SignAsync(request, Credentials));
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/KubernetesSecretAkamaiCredentialsProviderTests.cs b/tests/ConplementAG.CopsController.Tests/KubernetesSecretAkamaiCredentialsProviderTests.cs
new file mode 100644
index 0000000..56724a3
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/KubernetesSecretAkamaiCredentialsProviderTests.cs
@@ -0,0 +1,144 @@
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Net.Http;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Services;
+using k8s.Autorest;
+using k8s.Models;
+using Microsoft.Extensions.Options;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ public class KubernetesSecretAkamaiCredentialsProviderTests
+ {
+ private sealed class FakeSecretReader : IKubernetesSecretReader
+ {
+ public string RequestedName { get; private set; }
+ public string RequestedNamespace { get; private set; }
+ public Func> Result { get; set; }
+
+ public Task ReadAsync(string name, string @namespace, CancellationToken cancellationToken)
+ {
+ RequestedName = name;
+ RequestedNamespace = @namespace;
+ return Result(cancellationToken);
+ }
+ }
+
+ private static HttpOperationException ApiError(HttpStatusCode statusCode)
+ {
+ return new HttpOperationException("api error") { Response = new HttpResponseMessageWrapper(new HttpResponseMessage(statusCode), "") };
+ }
+
+ /// A read which never completes on its own, like a hanging API server.
+ private static async Task HangingRead(CancellationToken cancellationToken)
+ {
+ await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
+ return null;
+ }
+
+ private static KubernetesSecretAkamaiCredentialsProvider Provider(FakeSecretReader reader, int requestTimeoutSeconds = 20)
+ {
+ return new KubernetesSecretAkamaiCredentialsProvider(reader, Options.Create(new SiteShieldOptions { CredentialsSecretName = "akamai-siteshield-credentials", RequestTimeoutSeconds = requestTimeoutSeconds }));
+ }
+
+ [Fact]
+ public async Task GetCredentialsAsync_ReadsConfiguredSecretFromGivenNamespace()
+ {
+ var reader = new FakeSecretReader
+ {
+ Result = _ => Task.FromResult(new V1Secret
+ {
+ Data = new Dictionary
+ {
+ ["host"] = Encoding.UTF8.GetBytes("akab-x.luna.akamaiapis.net"),
+ ["client_token"] = Encoding.UTF8.GetBytes("ct"),
+ ["client_secret"] = Encoding.UTF8.GetBytes("cs"),
+ ["access_token"] = Encoding.UTF8.GetBytes("at")
+ }
+ })
+ };
+
+ var credentials = await Provider(reader).GetCredentialsAsync("myapp", CancellationToken.None);
+
+ Assert.Equal("akamai-siteshield-credentials", reader.RequestedName);
+ Assert.Equal("myapp", reader.RequestedNamespace);
+ Assert.Equal("akab-x.luna.akamaiapis.net", credentials.Host);
+ Assert.Equal("ct", credentials.ClientToken);
+ }
+
+ [Fact]
+ public async Task GetCredentialsAsync_SecretNotFound_ReportsStableMessage()
+ {
+ var reader = new FakeSecretReader { Result = _ => throw ApiError(HttpStatusCode.NotFound) };
+
+ var ex = await Assert.ThrowsAsync(() => Provider(reader).GetCredentialsAsync("myapp", CancellationToken.None));
+
+ Assert.StartsWith("Credentials secret myapp/akamai-siteshield-credentials not found", ex.Message);
+ }
+
+ [Theory]
+ [InlineData(HttpStatusCode.Forbidden, 403)]
+ [InlineData(HttpStatusCode.Unauthorized, 401)]
+ public async Task GetCredentialsAsync_AccessDenied_ReportsRbacHint(HttpStatusCode statusCode, int code)
+ {
+ var reader = new FakeSecretReader { Result = _ => throw ApiError(statusCode) };
+
+ var ex = await Assert.ThrowsAsync(() => Provider(reader).GetCredentialsAsync("myapp", CancellationToken.None));
+
+ Assert.Contains($"denied (HTTP {code})", ex.Message);
+ Assert.Contains("ClusterRole", ex.Message);
+ }
+
+ [Fact]
+ public async Task GetCredentialsAsync_OtherApiError_ReportsStatusCode()
+ {
+ var reader = new FakeSecretReader { Result = _ => throw ApiError(HttpStatusCode.InternalServerError) };
+
+ var ex = await Assert.ThrowsAsync(() => Provider(reader).GetCredentialsAsync("myapp", CancellationToken.None));
+
+ Assert.Equal("Reading credentials secret myapp/akamai-siteshield-credentials failed (HTTP 500)", ex.Message);
+ }
+
+ [Fact]
+ public async Task GetCredentialsAsync_SecretReadTimesOut_ReportsTimeout()
+ {
+ var reader = new FakeSecretReader { Result = HangingRead };
+
+ var ex = await Assert.ThrowsAsync(() => Provider(reader, requestTimeoutSeconds: 1).GetCredentialsAsync("myapp", CancellationToken.None));
+
+ Assert.Equal("Reading credentials secret myapp/akamai-siteshield-credentials timed out after 1s", ex.Message);
+ Assert.IsAssignableFrom(ex.InnerException);
+ }
+
+ [Fact]
+ public async Task GetCredentialsAsync_HookCancelled_PropagatesCancellation()
+ {
+ var reader = new FakeSecretReader { Result = HangingRead };
+ using var hook = new CancellationTokenSource();
+ hook.Cancel();
+
+ await Assert.ThrowsAnyAsync(() => Provider(reader).GetCredentialsAsync("myapp", hook.Token));
+ }
+
+ [Fact]
+ public async Task GetCredentialsAsync_SecretWithoutData_ReportsMissingKeys()
+ {
+ var reader = new FakeSecretReader { Result = _ => Task.FromResult(new V1Secret()) };
+
+ var ex = await Assert.ThrowsAsync(() => Provider(reader).GetCredentialsAsync("myapp", CancellationToken.None));
+
+ Assert.Contains("is missing key(s)", ex.Message);
+ }
+
+ [Fact]
+ public async Task GetCredentialsAsync_RequiresNamespace()
+ {
+ await Assert.ThrowsAsync(() => Provider(new FakeSecretReader()).GetCredentialsAsync("", CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/SiteShieldSyncControllerTests.cs b/tests/ConplementAG.CopsController.Tests/SiteShieldSyncControllerTests.cs
new file mode 100644
index 0000000..0613c80
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/SiteShieldSyncControllerTests.cs
@@ -0,0 +1,135 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using ConplementAG.CopsController.Controllers;
+using ConplementAG.CopsController.Models;
+using ConplementAG.CopsController.Services;
+using Microsoft.AspNetCore.Mvc;
+using Newtonsoft.Json.Linq;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ public class SiteShieldSyncControllerTests
+ {
+ private sealed class FakeCredentialsProvider : IAkamaiCredentialsProvider
+ {
+ public Func Result { get; set; } = _ => new AkamaiCredentials("akab-x.luna.akamaiapis.net", "ct", "cs", "at");
+
+ public Task GetCredentialsAsync(string @namespace, CancellationToken cancellationToken) => Task.FromResult(Result(@namespace));
+ }
+
+ private sealed class FakeSiteShieldClient : IAkamaiSiteShieldClient
+ {
+ public Func Result { get; set; } = _ => TestData.Map();
+
+ public Task GetMapAsync(AkamaiCredentials credentials, long mapId, CancellationToken cancellationToken) => Task.FromResult(Result(mapId));
+ }
+
+ private static JObject Request(bool withObservedChild)
+ {
+ var request = new JObject
+ {
+ ["parent"] = JObject.FromObject(TestData.Parent()),
+ ["children"] = new JObject { ["Middleware.traefik.io/v1alpha1"] = new JObject() }
+ };
+
+ if (withObservedChild)
+ {
+ request["children"]["Middleware.traefik.io/v1alpha1"]["siteshield"] = JObject.FromObject(TestData.ObservedChild());
+ }
+
+ return request;
+ }
+
+ private static SiteShieldSyncController Controller(FakeCredentialsProvider credentialsProvider = null, FakeSiteShieldClient siteShieldClient = null)
+ {
+ return new SiteShieldSyncController(credentialsProvider ?? new FakeCredentialsProvider(), siteShieldClient ?? new FakeSiteShieldClient(), TestData.Builder());
+ }
+
+ private static JObject Body(IActionResult result)
+ {
+ var ok = Assert.IsType(result);
+ return Assert.IsType(ok.Value);
+ }
+
+ [Fact]
+ public async Task Sync_Success_ReturnsMiddlewareAndReadyStatus()
+ {
+ var result = await Controller().Sync(Request(withObservedChild: false), CancellationToken.None);
+
+ var body = Body(result);
+ Assert.Equal("Ready", (string)body["status"]["state"]);
+ Assert.Equal("siteshield", (string)body["children"][0]["metadata"]["name"]);
+ Assert.Equal("myapp", (string)body["children"][0]["metadata"]["namespace"]);
+ Assert.Equal(TestData.DefaultSourceRange, body["children"][0]["spec"]["ipAllowList"]["sourceRange"].ToObject());
+ }
+
+ [Fact]
+ public async Task Sync_SiteShieldFailure_ReportsErrorStatusAndKeepsObservedChild()
+ {
+ var client = new FakeSiteShieldClient { Result = mapId => throw new AkamaiSiteShieldApiException($"Akamai SiteShield map {mapId} not found (HTTP 404)") };
+
+ var result = await Controller(siteShieldClient: client).Sync(Request(withObservedChild: true), CancellationToken.None);
+
+ var body = Body(result);
+ Assert.Equal("Error", (string)body["status"]["state"]);
+ Assert.Equal("Akamai SiteShield map 12345 not found (HTTP 404)", (string)body["status"]["message"]);
+ Assert.Equal(300, (int)body["resyncAfterSeconds"]);
+ Assert.Equal(new[] { "1.2.3.4/32", "5.6.7.8/32" }, body["children"][0]["spec"]["ipAllowList"]["sourceRange"].ToObject());
+ }
+
+ [Fact]
+ public async Task Sync_CredentialsFailure_ReportsErrorStatus()
+ {
+ var provider = new FakeCredentialsProvider { Result = ns => throw new AkamaiCredentialsException($"Credentials secret {ns}/akamai-siteshield-credentials not found") };
+
+ var result = await Controller(credentialsProvider: provider).Sync(Request(withObservedChild: false), CancellationToken.None);
+
+ var body = Body(result);
+ Assert.Equal("Error", (string)body["status"]["state"]);
+ Assert.Equal("Credentials secret myapp/akamai-siteshield-credentials not found", (string)body["status"]["message"]);
+ Assert.Empty((JArray)body["children"]);
+ }
+
+ [Fact]
+ public async Task Sync_UnexpectedFailure_ReportsOnlyTheExceptionType()
+ {
+ var client = new FakeSiteShieldClient { Result = _ => throw new InvalidOperationException("volatile details 0xdeadbeef") };
+
+ var result = await Controller(siteShieldClient: client).Sync(Request(withObservedChild: true), CancellationToken.None);
+
+ var body = Body(result);
+ Assert.Equal("Error", (string)body["status"]["state"]);
+ Assert.Equal("Akamai SiteShield sync failed: InvalidOperationException", (string)body["status"]["message"]);
+ Assert.Single((JArray)body["children"]);
+ }
+
+ [Fact]
+ public async Task Sync_MalformedRequest_ReturnsInternalServerError()
+ {
+ var emptyBody = await Controller().Sync(new JObject(), CancellationToken.None);
+ Assert.Equal(500, Assert.IsType(emptyBody).StatusCode);
+
+ var noBody = await Controller().Sync(null, CancellationToken.None);
+ Assert.Equal(500, Assert.IsType(noBody).StatusCode);
+
+ var nullParent = await Controller().Sync(new JObject { ["parent"] = JValue.CreateNull() }, CancellationToken.None);
+ Assert.Equal(500, Assert.IsType(nullParent).StatusCode);
+
+ var scalarParent = await Controller().Sync(new JObject { ["parent"] = "not an object" }, CancellationToken.None);
+ Assert.Equal(500, Assert.IsType(scalarParent).StatusCode);
+
+ var otherKind = Request(withObservedChild: false);
+ otherKind["parent"]["kind"] = "CopsNamespace";
+ var wrongKind = await Controller().Sync(otherKind, CancellationToken.None);
+ Assert.Equal(500, Assert.IsType(wrongKind).StatusCode);
+ }
+
+ [Fact]
+ public void Get_ReportsAlive()
+ {
+ Assert.Equal("I am alive.", Controller().Get().Value);
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/SiteShieldSyncRequestTests.cs b/tests/ConplementAG.CopsController.Tests/SiteShieldSyncRequestTests.cs
new file mode 100644
index 0000000..d5002d3
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/SiteShieldSyncRequestTests.cs
@@ -0,0 +1,143 @@
+using System;
+using System.Linq;
+using ConplementAG.CopsController.Services;
+using Newtonsoft.Json.Linq;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ public class SiteShieldSyncRequestTests
+ {
+ private const string ParentJson = @"{
+ ""apiVersion"": ""coreops.conplement.cloud/v1"",
+ ""kind"": ""CopsTraefikSiteShieldMiddleware"",
+ ""metadata"": { ""name"": ""siteshield"", ""namespace"": ""myapp"", ""generation"": 2, ""uid"": ""0a1b"" },
+ ""spec"": {
+ ""mapId"": 12345,
+ ""additionalSourceRanges"": [ ""10.0.0.0/8"" ],
+ ""ipStrategy"": { ""depth"": 1, ""excludedIPs"": [ ""10.0.0.1"" ] }
+ },
+ ""status"": { ""state"": ""Ready"", ""lastCidrChange"": ""2026-01-01T00:00:00Z"", ""cidrCount"": 2, ""mapAlias"": ""prod-map"", ""acknowledged"": true }
+ }";
+
+ private const string ChildJson = @"{
+ ""apiVersion"": ""traefik.io/v1alpha1"",
+ ""kind"": ""Middleware"",
+ ""metadata"": {
+ ""name"": ""siteshield"", ""namespace"": ""myapp"", ""uid"": ""ffff"", ""resourceVersion"": ""17"",
+ ""labels"": { ""controller-uid"": ""0a1b"" },
+ ""ownerReferences"": [ { ""kind"": ""CopsTraefikSiteShieldMiddleware"", ""name"": ""siteshield"" } ]
+ },
+ ""spec"": { ""ipAllowList"": { ""sourceRange"": [ ""1.2.3.4/32"", ""5.6.7.8/32"" ], ""ipStrategy"": { ""depth"": 1 } } }
+ }";
+
+ private static JObject Request(string childKey = "siteshield", bool withChildrenMap = true)
+ {
+ var request = new JObject
+ {
+ ["controller"] = new JObject { ["kind"] = "CompositeController" },
+ ["parent"] = JObject.Parse(ParentJson),
+ ["related"] = new JObject(),
+ ["finalizing"] = false
+ };
+
+ if (withChildrenMap)
+ {
+ var middlewares = new JObject();
+ if (childKey != null)
+ {
+ middlewares[childKey] = JObject.Parse(ChildJson);
+ }
+
+ request["children"] = new JObject { ["Middleware.traefik.io/v1alpha1"] = middlewares };
+ }
+
+ return request;
+ }
+
+ [Fact]
+ public void Parse_ReadsParent()
+ {
+ var parsed = SiteShieldSyncRequest.Parse(Request());
+
+ var parent = parsed.Parent;
+ Assert.Equal("CopsTraefikSiteShieldMiddleware", parent.Kind);
+ Assert.Equal("siteshield", parent.Metadata.Name);
+ Assert.Equal("myapp", parent.Metadata.Namespace);
+ Assert.Equal(2, parent.Metadata.Generation);
+ Assert.Equal(12345, parent.Spec.MapId);
+ Assert.Equal(new[] { "10.0.0.0/8" }, parent.Spec.AdditionalSourceRanges);
+ Assert.Equal(1, parent.Spec.IpStrategy.Depth);
+ Assert.Equal(new[] { "10.0.0.1" }, parent.Spec.IpStrategy.ExcludedIPs);
+ Assert.Null(parent.Spec.IpStrategy.Ipv6Subnet);
+ Assert.Equal("Ready", parent.Status.State);
+ Assert.Equal("2026-01-01T00:00:00Z", parent.Status.LastCidrChange);
+ Assert.Equal(2, parent.Status.CidrCount);
+ Assert.Equal("prod-map", parent.Status.MapAlias);
+ Assert.True(parent.Status.Acknowledged);
+ }
+
+ [Fact]
+ public void Parse_ReadsObservedChildWithoutServerSideMetadata()
+ {
+ var parsed = SiteShieldSyncRequest.Parse(Request());
+
+ var child = parsed.ObservedChild;
+ Assert.NotNull(child);
+ Assert.Equal("traefik.io/v1alpha1", child.ApiVersion);
+ Assert.Equal("Middleware", child.Kind);
+ Assert.Equal("siteshield", child.Metadata.Name);
+ Assert.Equal("myapp", child.Metadata.Namespace);
+ Assert.Equal(new[] { "1.2.3.4/32", "5.6.7.8/32" }, child.Spec.IpAllowList.SourceRange);
+ Assert.Equal(1, child.Spec.IpAllowList.IpStrategy.Depth);
+
+ // re-emitting the observed child must not carry uid, resourceVersion, labels or owner references
+ var reEmitted = JObject.FromObject(child);
+ Assert.Equal(new[] { "name", "namespace" }, ((JObject)reEmitted["metadata"]).Properties().Select(p => p.Name).ToArray());
+ }
+
+ [Fact]
+ public void Parse_SupportsHookVersion2ChildKey()
+ {
+ var parsed = SiteShieldSyncRequest.Parse(Request(childKey: "myapp/siteshield"));
+
+ Assert.NotNull(parsed.ObservedChild);
+ }
+
+ [Fact]
+ public void Parse_WithoutObservedChild_ReturnsNull()
+ {
+ Assert.Null(SiteShieldSyncRequest.Parse(Request(childKey: null)).ObservedChild);
+ Assert.Null(SiteShieldSyncRequest.Parse(Request(withChildrenMap: false)).ObservedChild);
+ }
+
+ [Fact]
+ public void Parse_RejectsMissingBody()
+ {
+ Assert.Throws(() => SiteShieldSyncRequest.Parse(null));
+ Assert.Throws(() => SiteShieldSyncRequest.Parse(new JObject()));
+ }
+
+ [Fact]
+ public void Parse_RejectsOtherKinds()
+ {
+ var request = Request();
+ request["parent"]["kind"] = "CopsNamespace";
+
+ var ex = Assert.Throws(() => SiteShieldSyncRequest.Parse(request));
+ Assert.Contains("CopsNamespace", ex.Message);
+ }
+
+ [Fact]
+ public void Parse_RejectsParentWithoutNamespaceOrSpec()
+ {
+ var withoutNamespace = Request();
+ ((JObject)withoutNamespace["parent"]["metadata"]).Remove("namespace");
+ Assert.Throws(() => SiteShieldSyncRequest.Parse(withoutNamespace));
+
+ var withoutSpec = Request();
+ ((JObject)withoutSpec["parent"]).Remove("spec");
+ Assert.Throws(() => SiteShieldSyncRequest.Parse(withoutSpec));
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/SiteShieldSyncResponseBuilderTests.cs b/tests/ConplementAG.CopsController.Tests/SiteShieldSyncResponseBuilderTests.cs
new file mode 100644
index 0000000..7e99019
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/SiteShieldSyncResponseBuilderTests.cs
@@ -0,0 +1,174 @@
+using ConplementAG.CopsController.Models;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ public class SiteShieldSyncResponseBuilderTests
+ {
+ [Fact]
+ public void BuildSuccess_CreatesMiddlewareNextToParentWithMergedSourceRange()
+ {
+ var response = TestData.Builder().BuildSuccess(TestData.Parent(), null, TestData.Map());
+
+ var child = Assert.Single(response.Children);
+ Assert.Equal("traefik.io/v1alpha1", child.ApiVersion);
+ Assert.Equal("Middleware", child.Kind);
+ Assert.Equal("siteshield", child.Metadata.Name);
+ Assert.Equal("myapp", child.Metadata.Namespace);
+ Assert.Equal(TestData.DefaultSourceRange, child.Spec.IpAllowList.SourceRange);
+ Assert.Null(child.Spec.IpAllowList.IpStrategy);
+
+ Assert.Equal(CopsTraefikSiteShieldMiddlewareStatus.StateReady, response.Status.State);
+ Assert.Equal("Middleware synced from Akamai SiteShield map 12345 (prod-map)", response.Status.Message);
+ Assert.Equal(12345, response.Status.MapId);
+ Assert.Equal("prod-map", response.Status.MapAlias);
+ Assert.Equal(3, response.Status.CidrCount);
+ Assert.True(response.Status.Acknowledged);
+ Assert.Equal(TestData.NowAsStatusTimestamp, response.Status.LastCidrChange);
+ Assert.Equal(3, response.Status.ObservedGeneration);
+ Assert.Null(response.ResyncAfterSeconds);
+ }
+
+ [Fact]
+ public void BuildSuccess_WithoutMapAlias_UsesShortMessage()
+ {
+ var response = TestData.Builder().BuildSuccess(TestData.Parent(), null, TestData.Map(mapAlias: null));
+
+ Assert.Equal("Middleware synced from Akamai SiteShield map 12345", response.Status.Message);
+ }
+
+ [Fact]
+ public void BuildSuccess_IncludesAdditionalSourceRangesAndPassesIpStrategyThrough()
+ {
+ var ipStrategy = new TraefikIpStrategy { Depth = 2, ExcludedIPs = new[] { "10.0.0.1" } };
+ var parent = TestData.Parent(additionalSourceRanges: new[] { "10.0.0.0/8", " 2.16.0.0/13 " }, ipStrategy: ipStrategy);
+
+ var response = TestData.Builder().BuildSuccess(parent, null, TestData.Map());
+
+ var child = Assert.Single(response.Children);
+ Assert.Equal(new[] { "10.0.0.0/8", "104.64.0.0/10", "2.16.0.0/13", "23.0.0.0/12" }, child.Spec.IpAllowList.SourceRange);
+ Assert.Same(ipStrategy, child.Spec.IpAllowList.IpStrategy);
+ Assert.Equal(4, response.Status.CidrCount);
+ }
+
+ [Fact]
+ public void BuildSuccess_CarriesLastCidrChangeOverWhenSourceRangeIsUnchanged()
+ {
+ var parent = TestData.Parent(status: new CopsTraefikSiteShieldMiddlewareStatus { LastCidrChange = "2026-01-01T00:00:00Z" });
+ var observedChild = TestData.ObservedChild(TestData.DefaultSourceRange);
+
+ var response = TestData.Builder().BuildSuccess(parent, observedChild, TestData.Map());
+
+ Assert.Equal("2026-01-01T00:00:00Z", response.Status.LastCidrChange);
+ }
+
+ [Fact]
+ public void BuildSuccess_SetsNewLastCidrChangeWhenSourceRangeChanged()
+ {
+ var parent = TestData.Parent(status: new CopsTraefikSiteShieldMiddlewareStatus { LastCidrChange = "2026-01-01T00:00:00Z" });
+ var observedChild = TestData.ObservedChild(new[] { "1.2.3.4/32" });
+
+ var response = TestData.Builder().BuildSuccess(parent, observedChild, TestData.Map());
+
+ Assert.Equal(TestData.NowAsStatusTimestamp, response.Status.LastCidrChange);
+ }
+
+ [Fact]
+ public void BuildSuccess_SetsNewLastCidrChangeWhenNoPreviousValueExists()
+ {
+ var observedChild = TestData.ObservedChild(TestData.DefaultSourceRange);
+
+ var response = TestData.Builder().BuildSuccess(TestData.Parent(), observedChild, TestData.Map());
+
+ Assert.Equal(TestData.NowAsStatusTimestamp, response.Status.LastCidrChange);
+ }
+
+ [Fact]
+ public void BuildSuccess_WithInvalidAdditionalSourceRanges_ReportsErrorWithoutRetry()
+ {
+ var parent = TestData.Parent(additionalSourceRanges: new[] { "zzz", "10.0.0.0/8", "abc" });
+ var observedChild = TestData.ObservedChild();
+
+ var response = TestData.Builder().BuildSuccess(parent, observedChild, TestData.Map());
+
+ Assert.Equal(CopsTraefikSiteShieldMiddlewareStatus.StateError, response.Status.State);
+ Assert.Equal("spec.additionalSourceRanges contains invalid entries: abc, zzz", response.Status.Message);
+ Assert.Null(response.ResyncAfterSeconds);
+ Assert.Same(observedChild, Assert.Single(response.Children));
+ }
+
+ [Fact]
+ public void BuildSuccess_WithoutAnyCidrs_ReportsErrorWithRetry()
+ {
+ var map = new AkamaiSiteShieldMap { Id = 12345, MapAlias = "prod-map", CurrentCidrs = new string[0], ProposedCidrs = null };
+ var observedChild = TestData.ObservedChild();
+
+ var response = TestData.Builder(errorResyncAfterSeconds: 42).BuildSuccess(TestData.Parent(), observedChild, map);
+
+ Assert.Equal(CopsTraefikSiteShieldMiddlewareStatus.StateError, response.Status.State);
+ Assert.Equal("Akamai SiteShield map 12345 returned no CIDRs", response.Status.Message);
+ Assert.Equal(42, response.ResyncAfterSeconds);
+ Assert.Same(observedChild, Assert.Single(response.Children));
+ }
+
+ [Fact]
+ public void BuildError_KeepsObservedChildAndPreviousStatusValues()
+ {
+ var previousStatus = new CopsTraefikSiteShieldMiddlewareStatus
+ {
+ State = CopsTraefikSiteShieldMiddlewareStatus.StateReady,
+ MapAlias = "prod-map",
+ Acknowledged = false,
+ LastCidrChange = "2026-01-01T00:00:00Z",
+ CidrCount = 99
+ };
+ var parent = TestData.Parent(status: previousStatus);
+ var observedChild = TestData.ObservedChild();
+
+ var response = TestData.Builder(errorResyncAfterSeconds: 123).BuildError(parent, observedChild, "something failed");
+
+ Assert.Same(observedChild, Assert.Single(response.Children));
+ Assert.Equal(CopsTraefikSiteShieldMiddlewareStatus.StateError, response.Status.State);
+ Assert.Equal("something failed", response.Status.Message);
+ Assert.Equal(12345, response.Status.MapId);
+ Assert.Equal("prod-map", response.Status.MapAlias);
+ Assert.False(response.Status.Acknowledged);
+ Assert.Equal("2026-01-01T00:00:00Z", response.Status.LastCidrChange);
+ Assert.Equal(2, response.Status.CidrCount);
+ Assert.Equal(3, response.Status.ObservedGeneration);
+ Assert.Equal(123, response.ResyncAfterSeconds);
+ }
+
+ [Fact]
+ public void BuildError_WithoutObservedChild_ReturnsNoChildren()
+ {
+ var response = TestData.Builder().BuildError(TestData.Parent(), null, "something failed");
+
+ Assert.Empty(response.Children);
+ Assert.Null(response.Status.CidrCount);
+ Assert.Null(response.Status.MapAlias);
+ Assert.Null(response.Status.LastCidrChange);
+ Assert.Equal(300, response.ResyncAfterSeconds);
+ }
+
+ [Fact]
+ public void BuildError_WithoutRetry_HasNoResync()
+ {
+ var response = TestData.Builder().BuildError(TestData.Parent(), null, "something failed", retry: false);
+
+ Assert.Null(response.ResyncAfterSeconds);
+ }
+
+ [Fact]
+ public void BuildSuccess_IsDeterministicForUnchangedInputs()
+ {
+ var previous = TestData.Builder().BuildSuccess(TestData.Parent(), null, TestData.Map());
+ var parent = TestData.Parent(status: previous.Status);
+ var observedChild = previous.Children[0];
+
+ var next = TestData.Builder().BuildSuccess(parent, observedChild, TestData.Map());
+
+ Assert.Equal(previous.ToJObject().ToString(), next.ToJObject().ToString());
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/SiteShieldSyncResponseSerializationTests.cs b/tests/ConplementAG.CopsController.Tests/SiteShieldSyncResponseSerializationTests.cs
new file mode 100644
index 0000000..3e4ffb6
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/SiteShieldSyncResponseSerializationTests.cs
@@ -0,0 +1,70 @@
+using ConplementAG.CopsController.Models;
+using Newtonsoft.Json.Linq;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ public class SiteShieldSyncResponseSerializationTests
+ {
+ [Fact]
+ public void ToJObject_SuccessResponse_HasMetacontrollerShapeWithoutNulls()
+ {
+ var parent = TestData.Parent(ipStrategy: new TraefikIpStrategy { Depth = 1 });
+ var json = TestData.Builder().BuildSuccess(parent, null, TestData.Map()).ToJObject();
+
+ Assert.Null(json["resyncAfterSeconds"]);
+
+ var status = (JObject)json["status"];
+ Assert.Equal("Ready", (string)status["state"]);
+ Assert.Equal(TestData.NowAsStatusTimestamp, (string)status["lastCidrChange"]);
+ Assert.Equal(JTokenType.String, status["lastCidrChange"].Type);
+ Assert.Equal(12345, (long)status["mapId"]);
+ Assert.Equal(3, (long)status["observedGeneration"]);
+
+ var child = (JObject)Assert.Single((JArray)json["children"]);
+ Assert.Equal("traefik.io/v1alpha1", (string)child["apiVersion"]);
+ Assert.Equal("Middleware", (string)child["kind"]);
+ Assert.Equal("siteshield", (string)child["metadata"]["name"]);
+ Assert.Equal("myapp", (string)child["metadata"]["namespace"]);
+ Assert.Equal(TestData.DefaultSourceRange, child["spec"]["ipAllowList"]["sourceRange"].ToObject());
+ Assert.Equal(1, (int)child["spec"]["ipAllowList"]["ipStrategy"]["depth"]);
+ Assert.Null(child["spec"]["ipAllowList"]["ipStrategy"]["excludedIPs"]);
+ Assert.Null(child["spec"]["ipAllowList"]["ipStrategy"]["ipv6Subnet"]);
+ }
+
+ [Fact]
+ public void ToJObject_WithoutIpStrategy_OmitsIt()
+ {
+ var json = TestData.Builder().BuildSuccess(TestData.Parent(), null, TestData.Map()).ToJObject();
+
+ Assert.Null(json["children"][0]["spec"]["ipAllowList"]["ipStrategy"]);
+ }
+
+ [Fact]
+ public void ToJObject_ErrorResponse_OmitsNullStatusMembersAndKeepsEmptyChildrenArray()
+ {
+ var json = TestData.Builder().BuildError(TestData.Parent(), null, "something failed", retry: false).ToJObject();
+
+ var status = (JObject)json["status"];
+ Assert.Equal("Error", (string)status["state"]);
+ Assert.Equal("something failed", (string)status["message"]);
+ Assert.Null(status["mapAlias"]);
+ Assert.Null(status["cidrCount"]);
+ Assert.Null(status["acknowledged"]);
+ Assert.Null(status["lastCidrChange"]);
+ Assert.Null(json["resyncAfterSeconds"]);
+
+ Assert.Equal(JTokenType.Array, json["children"].Type);
+ Assert.Empty((JArray)json["children"]);
+ }
+
+ [Fact]
+ public void ToJObject_ErrorResponseWithRetry_ContainsResyncAfterSeconds()
+ {
+ var json = TestData.Builder(errorResyncAfterSeconds: 300).BuildError(TestData.Parent(), TestData.ObservedChild(), "something failed").ToJObject();
+
+ Assert.Equal(300, (int)json["resyncAfterSeconds"]);
+ Assert.Single((JArray)json["children"]);
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/SourceRangesTests.cs b/tests/ConplementAG.CopsController.Tests/SourceRangesTests.cs
new file mode 100644
index 0000000..28842f3
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/SourceRangesTests.cs
@@ -0,0 +1,118 @@
+using ConplementAG.CopsController.Services;
+using Xunit;
+
+namespace ConplementAG.CopsController.Tests
+{
+ public class SourceRangesTests
+ {
+ [Fact]
+ public void Union_MergesTrimsDeduplicatesAndSorts()
+ {
+ var result = SourceRanges.Union(
+ new[] { " 23.0.0.0/12", "2001:DB8::/32" },
+ new[] { "23.0.0.0/12", "10.0.0.0/8", "", null },
+ null,
+ new[] { "2001:db8::/32" });
+
+ Assert.Equal(new[] { "10.0.0.0/8", "2001:DB8::/32", "23.0.0.0/12" }, result);
+ }
+
+ [Fact]
+ public void Union_IsDeterministicRegardlessOfInputOrder()
+ {
+ var first = SourceRanges.Union(new[] { "b/32", "a/32" }, new[] { "c/32" });
+ var second = SourceRanges.Union(new[] { "c/32" }, new[] { "a/32", "b/32" });
+
+ Assert.Equal(first, second);
+ }
+
+ [Fact]
+ public void Union_WithoutInput_IsEmpty()
+ {
+ Assert.Empty(SourceRanges.Union());
+ Assert.Empty(SourceRanges.Union(null, new string[0]));
+ }
+
+ [Fact]
+ public void SequenceEqual_IsNullSafeAndOrdinal()
+ {
+ Assert.True(SourceRanges.SequenceEqual(null, null));
+ Assert.True(SourceRanges.SequenceEqual(null, new string[0]));
+ Assert.True(SourceRanges.SequenceEqual(new[] { "a", "b" }, new[] { "a", "b" }));
+ Assert.False(SourceRanges.SequenceEqual(new[] { "a", "b" }, new[] { "b", "a" }));
+ Assert.False(SourceRanges.SequenceEqual(new[] { "a" }, new[] { "A" }));
+ Assert.False(SourceRanges.SequenceEqual(new[] { "a" }, null));
+ }
+
+ [Theory]
+ [InlineData("10.0.0.0/8")]
+ [InlineData("192.0.2.114/24")]
+ [InlineData("192.0.2.10")]
+ [InlineData("0.0.0.0/0")]
+ [InlineData("255.255.255.255/32")]
+ [InlineData("2001:db8::/32")]
+ [InlineData("2001:DB8::/32")]
+ [InlineData("2001:db8::1")]
+ [InlineData("::/0")]
+ [InlineData("::ffff:192.0.2.10")]
+ [InlineData(" 10.0.0.0/8 ")]
+ public void IsValidSourceRange_AcceptsAddressesAndRanges(string value)
+ {
+ Assert.True(SourceRanges.IsValidSourceRange(value));
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("abc")]
+ [InlineData("10.0.0.0/33")]
+ [InlineData("10.0.0.0/-1")]
+ [InlineData("10.0.0.0/")]
+ [InlineData("10.0.0.0/8/8")]
+ [InlineData("10/8")]
+ [InlineData("192.168.1/24")]
+ [InlineData("2001:db8::/129")]
+ public void IsValidSourceRange_RejectsInvalidEntries(string value)
+ {
+ Assert.False(SourceRanges.IsValidSourceRange(value));
+ }
+
+ ///
+ /// System.Net.IPAddress parses these, Traefik (Go net.ParseIP / net.ParseCIDR) does not; an entry Traefik cannot
+ /// parse disables every router using the middleware, so they must be reported as invalid spec instead.
+ ///
+ [Theory]
+ [InlineData("0x7f.0.0.1")]
+ [InlineData("010.0.0.1/8")]
+ [InlineData("1.2.3.04")]
+ [InlineData("256.0.0.1")]
+ [InlineData("1.2.3.4.5")]
+ [InlineData("10.0.0.0/08")]
+ [InlineData("10.0.0.0/+8")]
+ [InlineData("[::1]")]
+ [InlineData("[2001:db8::]/32")]
+ [InlineData("fe80::1%eth0")]
+ [InlineData("::ffff:010.0.0.1")]
+ [InlineData("2001:db8::zzzz")]
+ public void IsValidSourceRange_RejectsWhatTraefikRejects(string value)
+ {
+ Assert.False(SourceRanges.IsValidSourceRange(value));
+ }
+
+ [Fact]
+ public void FindInvalid_ReturnsSortedDistinctInvalidEntries()
+ {
+ var invalid = SourceRanges.FindInvalid(new[] { "10.0.0.0/8", "zzz", "abc", "zzz", null, "2001:db8::/32" });
+
+ Assert.Equal(new[] { "", "abc", "zzz" }, invalid);
+ }
+
+ [Fact]
+ public void FindInvalid_WithoutInput_IsEmpty()
+ {
+ Assert.Empty(SourceRanges.FindInvalid(null));
+ Assert.Empty(SourceRanges.FindInvalid(new string[0]));
+ }
+ }
+}
diff --git a/tests/ConplementAG.CopsController.Tests/TestData.cs b/tests/ConplementAG.CopsController.Tests/TestData.cs
new file mode 100644
index 0000000..f8ec499
--- /dev/null
+++ b/tests/ConplementAG.CopsController.Tests/TestData.cs
@@ -0,0 +1,72 @@
+using System;
+using ConplementAG.CopsController.Models;
+using ConplementAG.CopsController.Services;
+using Microsoft.Extensions.Options;
+
+namespace ConplementAG.CopsController.Tests
+{
+ internal static class TestData
+ {
+ public static readonly DateTimeOffset Now = new DateTimeOffset(2026, 11, 30, 12, 0, 0, TimeSpan.Zero);
+ public const string NowAsStatusTimestamp = "2026-11-30T12:00:00Z";
+
+ public static CopsTraefikSiteShieldMiddleware Parent(
+ string[] additionalSourceRanges = null,
+ TraefikIpStrategy ipStrategy = null,
+ CopsTraefikSiteShieldMiddlewareStatus status = null,
+ long mapId = 12345)
+ {
+ return new CopsTraefikSiteShieldMiddleware
+ {
+ ApiVersion = "coreops.conplement.cloud/v1",
+ Kind = CopsTraefikSiteShieldMiddleware.KindName,
+ Metadata = new CopsTraefikSiteShieldMiddlewareMetadata { Name = "siteshield", Namespace = "myapp", Generation = 3 },
+ Spec = new CopsTraefikSiteShieldMiddlewareSpec
+ {
+ MapId = mapId,
+ AdditionalSourceRanges = additionalSourceRanges,
+ IpStrategy = ipStrategy
+ },
+ Status = status
+ };
+ }
+
+ public static AkamaiSiteShieldMap Map(string[] currentCidrs = null, string[] proposedCidrs = null, string mapAlias = "prod-map")
+ {
+ return new AkamaiSiteShieldMap
+ {
+ Id = 12345,
+ MapAlias = mapAlias,
+ RuleName = "s12345.akamaiedge.net",
+ CurrentCidrs = currentCidrs ?? new[] { "23.0.0.0/12", "2.16.0.0/13" },
+ ProposedCidrs = proposedCidrs ?? new[] { "23.0.0.0/12", "104.64.0.0/10" },
+ Acknowledged = true
+ };
+ }
+
+ /// The sorted union of the default Map() CIDRs.
+ public static readonly string[] DefaultSourceRange = { "104.64.0.0/10", "2.16.0.0/13", "23.0.0.0/12" };
+
+ public static TraefikMiddleware ObservedChild(string[] sourceRange = null)
+ {
+ return TraefikMiddleware.IpAllowList("siteshield", "myapp", sourceRange ?? new[] { "1.2.3.4/32", "5.6.7.8/32" });
+ }
+
+ public static SiteShieldSyncResponseBuilder Builder(int errorResyncAfterSeconds = 300)
+ {
+ return new SiteShieldSyncResponseBuilder(new FixedTimeProvider(Now), Options.Create(new SiteShieldOptions { ErrorResyncAfterSeconds = errorResyncAfterSeconds }));
+ }
+
+ private sealed class FixedTimeProvider : TimeProvider
+ {
+ private readonly DateTimeOffset _now;
+
+ public FixedTimeProvider(DateTimeOffset now)
+ {
+ _now = now;
+ }
+
+ public override DateTimeOffset GetUtcNow() => _now;
+ }
+ }
+}
diff --git a/tests/invalid-definitions/10.yaml b/tests/invalid-definitions/10.yaml
new file mode 100644
index 0000000..5a19b79
--- /dev/null
+++ b/tests/invalid-definitions/10.yaml
@@ -0,0 +1,9 @@
+apiVersion: coreops.conplement.cloud/v1
+kind: CopsTraefikSiteShieldMiddleware
+metadata:
+ name: test-invalid-ctsm-10-map-id-zero
+ namespace: default
+ labels:
+ tests: cops-controller-component-tests
+spec:
+ mapId: 0
diff --git a/tests/invalid-definitions/11.yaml b/tests/invalid-definitions/11.yaml
new file mode 100644
index 0000000..3fe374e
--- /dev/null
+++ b/tests/invalid-definitions/11.yaml
@@ -0,0 +1,11 @@
+apiVersion: coreops.conplement.cloud/v1
+kind: CopsTraefikSiteShieldMiddleware
+metadata:
+ name: test-invalid-ctsm-11-depth-not-a-number
+ namespace: default
+ labels:
+ tests: cops-controller-component-tests
+spec:
+ mapId: 12345
+ ipStrategy:
+ depth: "two"
diff --git a/tests/invalid-definitions/12.yaml b/tests/invalid-definitions/12.yaml
new file mode 100644
index 0000000..99ca6ee
--- /dev/null
+++ b/tests/invalid-definitions/12.yaml
@@ -0,0 +1,10 @@
+apiVersion: coreops.conplement.cloud/v1
+kind: CopsTraefikSiteShieldMiddleware
+metadata:
+ name: test-invalid-ctsm-12-source-ranges-not-a-list
+ namespace: default
+ labels:
+ tests: cops-controller-component-tests
+spec:
+ mapId: 12345
+ additionalSourceRanges: 10.0.0.0/8
diff --git a/tests/invalid-definitions/8.yaml b/tests/invalid-definitions/8.yaml
new file mode 100644
index 0000000..a229d15
--- /dev/null
+++ b/tests/invalid-definitions/8.yaml
@@ -0,0 +1,10 @@
+apiVersion: coreops.conplement.cloud/v1
+kind: CopsTraefikSiteShieldMiddleware
+metadata:
+ name: test-invalid-ctsm-8-missing-map-id
+ namespace: default
+ labels:
+ tests: cops-controller-component-tests
+spec:
+ additionalSourceRanges:
+ - 10.0.0.0/8
diff --git a/tests/invalid-definitions/9.yaml b/tests/invalid-definitions/9.yaml
new file mode 100644
index 0000000..9095603
--- /dev/null
+++ b/tests/invalid-definitions/9.yaml
@@ -0,0 +1,9 @@
+apiVersion: coreops.conplement.cloud/v1
+kind: CopsTraefikSiteShieldMiddleware
+metadata:
+ name: test-invalid-ctsm-9-map-id-not-a-number
+ namespace: default
+ labels:
+ tests: cops-controller-component-tests
+spec:
+ mapId: "abc"
diff --git a/tests/tests.sh b/tests/tests.sh
index 7ebc1c6..7092c08 100644
--- a/tests/tests.sh
+++ b/tests/tests.sh
@@ -170,6 +170,11 @@ function test_validDefinitions {
ensureAccessToNamespace "test-valid-ns-2-only-users"
ensureAccessToNamespace "test-valid-ns-3-lot-of-users-and-sa"
ensureAccessToNamespace "test-valid-ns-4-version2"
+
+ # CopsTraefikSiteShieldMiddleware definitions are only validated against the CRD schema here: syncing them needs
+ # the traefik CRDs and Akamai credentials, which must not become a test dependency (see ensureAllResourcesAreSupported)
+ kubectl get ctsm test-valid-ctsm-1-full -n default || fail "Expected the valid CopsTraefikSiteShieldMiddleware definition 5.yaml to be accepted."
+ kubectl get ctsm test-valid-ctsm-2-minimal -n default || fail "Expected the valid CopsTraefikSiteShieldMiddleware definition 6.yaml to be accepted."
}
function test_invalidDefinitions {
@@ -184,6 +189,13 @@ function test_invalidDefinitions {
expectApplyToFail "tests/invalid-definitions/5.yaml"
expectApplyToFail "tests/invalid-definitions/6.yaml"
expectApplyToFail "tests/invalid-definitions/7.yaml"
+
+ # CopsTraefikSiteShieldMiddleware
+ expectApplyToFail "tests/invalid-definitions/8.yaml"
+ expectApplyToFail "tests/invalid-definitions/9.yaml"
+ expectApplyToFail "tests/invalid-definitions/10.yaml"
+ expectApplyToFail "tests/invalid-definitions/11.yaml"
+ expectApplyToFail "tests/invalid-definitions/12.yaml"
}
# Tests following business cases:
diff --git a/tests/valid-definitions/5.yaml b/tests/valid-definitions/5.yaml
new file mode 100644
index 0000000..0dbe2d5
--- /dev/null
+++ b/tests/valid-definitions/5.yaml
@@ -0,0 +1,17 @@
+apiVersion: coreops.conplement.cloud/v1
+kind: CopsTraefikSiteShieldMiddleware
+metadata:
+ name: test-valid-ctsm-1-full
+ namespace: default
+ labels:
+ tests: cops-controller-component-tests
+spec:
+ mapId: 12345
+ additionalSourceRanges:
+ - 10.0.0.0/8
+ - 192.0.2.10
+ - 2001:db8::/32
+ ipStrategy:
+ depth: 1
+ excludedIPs:
+ - 10.0.0.1
diff --git a/tests/valid-definitions/6.yaml b/tests/valid-definitions/6.yaml
new file mode 100644
index 0000000..15ec502
--- /dev/null
+++ b/tests/valid-definitions/6.yaml
@@ -0,0 +1,9 @@
+apiVersion: coreops.conplement.cloud/v1
+kind: CopsTraefikSiteShieldMiddleware
+metadata:
+ name: test-valid-ctsm-2-minimal
+ namespace: default
+ labels:
+ tests: cops-controller-component-tests
+spec:
+ mapId: 1