One admin secret meant one thing: whatever could read /admin-api/state could also delete every block and rewrite the policy. A Prometheus scrape therefore held a key that can lift a ban, a second operator checking why a visitor was refused held a key that can change what the edge enforces, and OPEN-61's export put a whole edge's config behind the same single GET. The operator's question was never "does this thing know the secret" but "what is it allowed to do", and the shipped answer could only be all or nothing. OpenWaf:Admin:ReadOnlyToken (env OPENWAF_READ_ONLY_TOKEN) is the second level. Unset is the default and the whole of the previous behaviour. The rulings: * A known token without the right is answered 403, not 401, and the body names the key that would grant the write. Collapsing the two sentences sends someone debugging a failing script to check the secret when what is wrong is the endpoint it was sent to. * The line is drawn by the request method, not by a flag per endpoint: GET/HEAD/OPTIONS read, everything else writes. A write endpoint added tomorrow is behind the rule the moment it is written; a per-endpoint flag would fail the other way, and one forgotten flag would open the write. * GET /admin-api/export is the one read held to the admin token. It is a read and it is still the whole config, so it is the surface where "can read" and "can take" are the same act - and the dashboard token is exactly the one that must not be able to lift a fleet's config. * A read-only token sees byte-identical answers to the admin token. Read-only is about what a token may do, not about a weaker view: two people comparing answers must not get different answers because of who asked. * A read-only token equal to the admin token (compared after trimming, because env files add newlines) aborts startup naming both keys and never the secret. /admin-api/state answers readOnlyTokenConfigured, so the operator can check the key took effect instead of guessing from a 401. What the run caught, in order: (1) A real defect, and the interesting one. On the shipped image the startup refusal printed its reason and then the process sat at 100% CPU inside the runtime's crash path - the container stayed "Up (unhealthy)" forever, no exit code, nothing for a supervisor to react to. Refusing to start is only useful if the process leaves, so the refusal now writes the reason to stderr and returns 1; measured again on the image, it exits in 2 s with code 1 and the same sentence. (2) The gate's own assertion for that case had the same blind spot as the bug: waiting on a foreground docker compose run cannot tell "refused" from "hung", so the container is now started detached and polled for an exit within 30 s, and the assertion is that it left. (3) Two smoke asserts were wrong rather than the product: the blocks listing field is sourceKey, not ip, so the first version read an empty answer, and a two-code assertion compared a newline-separated pair against a space-separated literal. (4) An integration assert compared JsonElement.ToString() against "true" - a bool element prints True, so it now reads GetBoolean(). Gates on this tree: build 0 warnings / 0 errors, unit 307/307, integration 286/286 in 26s, smoke 105 passed / 0 failed (23 new), image 262 MB, compose-smoke 261 passed / 0 failed with 0 containers left behind (18 new, against the shipped image), console 90 assertions / 0 failed. Refs OPEN-62.
234 lines
12 KiB
C#
234 lines
12 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public sealed class ReadOnlyTokenTests
|
|
{
|
|
/// <summary>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.</summary>
|
|
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<HttpStatusCode> 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<string> 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());
|
|
}
|
|
|
|
/// <summary>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.</summary>
|
|
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<string> ReadSurfaceData()
|
|
{
|
|
var data = new TheoryData<string>();
|
|
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<object>() }
|
|
: 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", ""));
|
|
}
|
|
}
|