using System.Net; using System.Net.Http.Json; using System.Text; using System.Text.Json; namespace OpenWaf.Tests.Integration; /// /// A second token that can look but not change (OPEN-62). /// /// One secret used to mean one thing: whatever could read the operator's /// surfaces could also clear the block list and rewrite the policy. The /// operator's actual question is not "does this thing know the secret" but /// "what is it allowed to do", and the shipped answer had to be all or nothing /// — so a Prometheus scrape held a key that can delete a ban, and OPEN-61's /// export document made that sharper by putting a whole edge's config behind the /// same single GET. /// /// What these tests hold is the shape of the answer, not the 200s: a known /// token without the right is answered 403 and told which key would grant it, /// while an unknown token is answered 401. Collapse those two and an operator /// debugging a script is sent looking at the wrong thing. The read/write line is /// drawn by the request method, so the tests also ask whether a write is refused /// without anyone having marked it as one. /// public sealed class ReadOnlyTokenTests { /// The header the operator is asked to use. Spelled out rather /// than read from the edge's type: the surface is the contract, and a test /// that imports the implementation's name stops noticing when it moves. private const string Header = "X-Admin-Token"; private const string Written = "203.0.113.161"; private const string Refused = "203.0.113.162"; private static async Task ReadAsync(EdgeFixture f, string path, string token) { using var request = new HttpRequestMessage(HttpMethod.Get, path); request.Headers.TryAddWithoutValidation(Header, token); using var response = await f.Client.SendAsync(request); return response.StatusCode; } private static async Task ReadBodyAsync(EdgeFixture f, string path, string token) { using var request = new HttpRequestMessage(HttpMethod.Get, path); request.Headers.TryAddWithoutValidation(Header, token); using var response = await f.Client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, response.StatusCode); return await response.Content.ReadAsStringAsync(); } private static async Task<(HttpStatusCode Status, string Body)> WriteAsync( EdgeFixture f, HttpMethod method, string path, string token, object? payload) { using var request = new HttpRequestMessage(method, path); request.Headers.TryAddWithoutValidation(Header, token); if (payload is not null) request.Content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json"); using var response = await f.Client.SendAsync(request); return (response.StatusCode, await response.Content.ReadAsStringAsync()); } /// The operator surfaces a read-only token is promised. Listed here /// rather than picked one by one so a surface added later is easy to add to /// the promise — and so a surface missing from it is visible. private static readonly string[] ReadSurfaces = { "/admin-api/state", "/admin-api/blocks", "/admin-api/allow", "/admin-api/rules", "/admin-api/policy", "/admin-api/rate", "/admin-api/observations", "/admin-api/streaks", "/admin-api/alerts", "/admin-api/countries", "/admin-api/countries/summary", "/admin-api/geo", "/admin-api/decide?ip=203.0.113.161" }; [Theory] [MemberData(nameof(ReadSurfaceData))] public async Task The_read_only_token_reads_every_operator_surface(string path) { await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); Assert.Equal(HttpStatusCode.OK, await ReadAsync(f, path, EdgeFixture.ReadOnlyToken)); } public static TheoryData ReadSurfaceData() { var data = new TheoryData(); foreach (var surface in ReadSurfaces) data.Add(surface); return data; } [Fact] public async Task The_read_only_token_sees_exactly_what_the_admin_token_sees() { // Read-only is about what a token may do, not about showing a weaker // view. A dashboard and an operator have to be able to compare answers, // and a filtered read would make "what does the edge think" depend on // who asked. await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); using (var write = await f.Client.PostAsJsonAsync( $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Written, reason = "written by the admin token" })) Assert.Equal(HttpStatusCode.NoContent, write.StatusCode); var asAdmin = await ReadBodyAsync(f, "/admin-api/blocks", EdgeFixture.AdminToken); var asReadOnly = await ReadBodyAsync(f, "/admin-api/blocks", EdgeFixture.ReadOnlyToken); Assert.Contains(Written, asAdmin); Assert.Equal(asAdmin, asReadOnly); } [Theory] [InlineData("POST", "/admin-api/blocks")] [InlineData("POST", "/admin-api/allow")] [InlineData("POST", "/admin-api/rules")] [InlineData("PUT", "/admin-api/policy")] [InlineData("PUT", "/admin-api/countries/de?allowed=false")] [InlineData("DELETE", "/admin-api/blocks?source=operator")] [InlineData("POST", "/admin-api/import")] public async Task A_write_is_refused_for_the_read_only_token_whatever_the_verb(string method, string path) { await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); var (status, body) = await WriteAsync(f, new HttpMethod(method), path, EdgeFixture.ReadOnlyToken, method == "POST" && path.EndsWith("import") ? new { version = 1, blocks = Array.Empty() } : new { ip = Refused, match = Refused, pattern = "/x*", mode = "Off" }); // 403, not 401: the token is known. The difference is the whole feature. Assert.Equal(HttpStatusCode.Forbidden, status); Assert.Contains("read-only", body); Assert.Contains("OpenWaf__Admin__Token", body); } [Fact] public async Task A_refused_write_leaves_nothing_behind() { await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); var (status, _) = await WriteAsync(f, HttpMethod.Post, "/admin-api/blocks", EdgeFixture.ReadOnlyToken, new { ip = Refused, reason = "must not land" }); Assert.Equal(HttpStatusCode.Forbidden, status); using var list = await f.Client.GetAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}"); using var all = await f.Client.GetAsync($"/admin-api/blocks?live=false&token={EdgeFixture.AdminToken}"); Assert.Equal("[]", await list.Content.ReadAsStringAsync()); Assert.Equal("[]", await all.Content.ReadAsStringAsync()); } [Fact] public async Task The_admin_token_still_writes_what_the_read_only_token_cannot() { // The regression this guards is the obvious wrong implementation: a // second token that quietly takes the first one's write power away. await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); var (refused, _) = await WriteAsync(f, HttpMethod.Post, "/admin-api/blocks", EdgeFixture.ReadOnlyToken, new { ip = Refused }); var (allowed, _) = await WriteAsync(f, HttpMethod.Post, "/admin-api/blocks", EdgeFixture.AdminToken, new { ip = Written, reason = "written by the admin token" }); Assert.Equal(HttpStatusCode.Forbidden, refused); Assert.Equal(HttpStatusCode.NoContent, allowed); using var list = await f.Client.GetAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}"); using var body = JsonDocument.Parse(await list.Content.ReadAsStringAsync()); Assert.Equal(1, body.RootElement.GetArrayLength()); Assert.Equal(Written, body.RootElement[0].GetProperty("sourceKey").GetString()); } [Theory] [InlineData("/admin-api/state")] [InlineData("/admin-api/blocks")] public async Task An_unknown_token_is_answered_401_on_a_read_and_on_a_write(string path) { await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); Assert.Equal(HttpStatusCode.Unauthorized, await ReadAsync(f, path, "guessed-token")); var (status, body) = await WriteAsync(f, HttpMethod.Post, "/admin-api/blocks", "guessed-token", new { ip = Refused }); Assert.Equal(HttpStatusCode.Unauthorized, status); // The body must not explain a level to a token that has none: that would // be a way to probe which of the two secrets is configured. Assert.DoesNotContain("read-only", body); } [Fact] public async Task The_export_document_needs_the_admin_token_because_it_is_a_capability() { await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); using (var write = await f.Client.PostAsJsonAsync( $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Written })) Assert.Equal(HttpStatusCode.NoContent, write.StatusCode); var (refused, refusedBody) = await WriteAsync(f, HttpMethod.Get, "/admin-api/export", EdgeFixture.ReadOnlyToken, null); Assert.Equal(HttpStatusCode.Forbidden, refused); Assert.Contains("capability", refusedBody); using var allowed = await f.Client.GetAsync($"/admin-api/export?token={EdgeFixture.AdminToken}"); Assert.Equal(HttpStatusCode.OK, allowed.StatusCode); using var document = JsonDocument.Parse(await allowed.Content.ReadAsStringAsync()); Assert.Equal(1, document.RootElement.GetProperty("counts").GetProperty("blocks").GetInt32()); } [Fact] public async Task The_state_says_whether_a_second_token_exists() { await using var with = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); await using var without = new EdgeFixture(); foreach (var (fixture, expected) in new[] { (with, true), (without, false) }) { using var response = await fixture.Client.GetAsync( $"/admin-api/state?token={EdgeFixture.AdminToken}"); using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); Assert.Equal(expected, body.RootElement.GetProperty("readOnlyTokenConfigured").GetBoolean()); } } [Fact] public async Task A_read_only_token_that_was_never_configured_authenticates_as_nothing() { // The feature is off by default, and off has to mean off rather than // "a level that exists but is empty". await using var f = new EdgeFixture(); Assert.Equal(HttpStatusCode.Unauthorized, await ReadAsync(f, "/admin-api/state", EdgeFixture.ReadOnlyToken)); Assert.Equal(HttpStatusCode.Unauthorized, await ReadAsync(f, "/metrics", EdgeFixture.ReadOnlyToken)); } [Fact] public async Task The_read_only_token_can_watch_the_numbers() { // A scrape is the clearest case of the whole feature: something that has // to be able to look and must not be able to change anything. await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); Assert.Equal(HttpStatusCode.OK, await ReadAsync(f, "/metrics", EdgeFixture.ReadOnlyToken)); Assert.Equal(HttpStatusCode.Unauthorized, await ReadAsync(f, "/metrics", "")); } }