mirror of
https://github.com/okieselbach/AutopilotMonitor.git
synced 2026-10-24 12:42:38 +00:00
feat(rules): community rule submissions — submit custom rules from the portal, review via GA page or MCP, publish by repo commit + reseed (D-236)
Tenant admins submit references to their own gather/analyze rules; the server freezes the rule, records pre-flight findings and fire stats, and stores it under a 12-character id (RuleSubmissions, SessionReports layout). Attribution is the submitter's frozen choice (anonymous by default) and becomes the published author. Review (approve with reserved id / decline with comment) through /admin/reports/rule-submissions or the MCP tools list_rule_submissions, get_rule_submission, review_rule_submission, reseed_rules_from_github; published is derived from the global catalog, never stored. Analyze rules now get the same server-side author stamp as gather rules; ANALYZE-ID-001 carries author Community. Privacy page names the credit; bumps internal and .claude/commands gitlinks. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
+1
-1
Submodule .claude/commands updated: 8dcfe1e23e...80ee4efaf6
+1
-1
Submodule internal updated: 33acedeb85...8efdea43fa
@@ -5,6 +5,7 @@
|
||||
"description": "Detects when a certificate with the configured subject is missing from the local machine personal store (LocalMachine\\My). Requires the gather rule GATHER-ID-002 (machine cert store inventory) to be enabled — the check runs against its gather_machine_cert_store output. A missing certificate may indicate that MDM enrollment certificate provisioning or SCEP certificate deployment failed.",
|
||||
"severity": "warning",
|
||||
"category": "identity",
|
||||
"author": "Community",
|
||||
"isCommunity": true,
|
||||
"enabled": false,
|
||||
"evaluateOn": [
|
||||
|
||||
+1
@@ -2806,6 +2806,7 @@
|
||||
"description": "Detects when a certificate with the configured subject is missing from the local machine personal store (LocalMachine\\My). Requires the gather rule GATHER-ID-002 (machine cert store inventory) to be enabled — the check runs against its gather_machine_cert_store output. A missing certificate may indicate that MDM enrollment certificate provisioning or SCEP certificate deployment failed.",
|
||||
"severity": "warning",
|
||||
"category": "identity",
|
||||
"author": "Community",
|
||||
"isCommunity": true,
|
||||
"enabled": false,
|
||||
"evaluateOn": [
|
||||
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using AutopilotMonitor.Functions.Functions.Rules;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Azure.Core.Serialization;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Analyze twin of <see cref="GatherRulesFunctionAuthorEndpointTests"/>: the rule Author is
|
||||
/// stamped from the caller's JWT on create, on a PUT-upsert of an unknown rule and on the
|
||||
/// template copy, and a true update keeps the original creator over editor and body.
|
||||
/// Before this pin, custom analyze rules were created as "Autopilot Monitor" and the edit
|
||||
/// path let the browser choose the author.
|
||||
/// </summary>
|
||||
public class AnalyzeRulesFunctionAuthorEndpointTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string RuleId = "ANALYZE-CUSTOM-777";
|
||||
private const string TemplateRuleId = "ANALYZE-SEC-004";
|
||||
|
||||
private sealed class FakeHttpResponseData : HttpResponseData
|
||||
{
|
||||
public FakeHttpResponseData(FunctionContext context) : base(context) { }
|
||||
public override HttpStatusCode StatusCode { get; set; } = HttpStatusCode.OK;
|
||||
public override HttpHeadersCollection Headers { get; set; } = new();
|
||||
public override Stream Body { get; set; } = new MemoryStream();
|
||||
public override HttpCookies Cookies { get; } = new Mock<HttpCookies>().Object;
|
||||
}
|
||||
|
||||
private static FunctionContext BuildContext(ClaimsPrincipal? principal)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddOptions();
|
||||
services.Configure<WorkerOptions>(o => o.Serializer =
|
||||
new JsonObjectSerializer(ApiJsonOptions.Create()));
|
||||
var provider = services.BuildServiceProvider();
|
||||
|
||||
var items = new Dictionary<object, object>();
|
||||
if (principal != null)
|
||||
{
|
||||
items["ClaimsPrincipal"] = principal;
|
||||
}
|
||||
|
||||
var context = new Mock<FunctionContext>();
|
||||
context.SetupGet(c => c.Items).Returns(items);
|
||||
context.SetupGet(c => c.InstanceServices).Returns(provider);
|
||||
return context.Object;
|
||||
}
|
||||
|
||||
private static HttpRequestData BuildRequest(ClaimsPrincipal? principal, object body)
|
||||
{
|
||||
var context = BuildContext(principal);
|
||||
var req = new Mock<HttpRequestData>(context);
|
||||
req.SetupGet(r => r.Headers).Returns(new HttpHeadersCollection());
|
||||
req.SetupGet(r => r.Body).Returns(
|
||||
new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(body))));
|
||||
req.Setup(r => r.CreateResponse()).Returns(() => new FakeHttpResponseData(context));
|
||||
return req.Object;
|
||||
}
|
||||
|
||||
private static ClaimsPrincipal Principal(params (string Type, string Value)[] claims)
|
||||
=> new(new ClaimsIdentity(claims.Select(c => new Claim(c.Type, c.Value)), "TestAuth"));
|
||||
|
||||
private static ClaimsPrincipal AlicePrincipal()
|
||||
=> Principal(("tid", TenantId), ("name", "Alice Admin"), ("upn", "alice@contoso.com"));
|
||||
|
||||
private static (AnalyzeRulesFunction function, List<AnalyzeRule> stored) BuildFunction(
|
||||
AnalyzeRule? existingTenantRule = null, AnalyzeRule? globalRule = null)
|
||||
{
|
||||
var repo = new Mock<IRuleRepository>(MockBehavior.Loose);
|
||||
var stored = new List<AnalyzeRule>();
|
||||
|
||||
repo.Setup(r => r.AnalyzeRuleExistsAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(false);
|
||||
repo.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(
|
||||
globalRule == null ? new List<AnalyzeRule>() : new List<AnalyzeRule> { globalRule });
|
||||
repo.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(
|
||||
existingTenantRule == null ? new List<AnalyzeRule>() : new List<AnalyzeRule> { existingTenantRule });
|
||||
repo.Setup(r => r.GetRuleStatesAsync(TenantId)).ReturnsAsync(new Dictionary<string, RuleState>());
|
||||
repo.Setup(r => r.StoreRuleStateAsync(TenantId, It.IsAny<string>(), It.IsAny<RuleState>())).ReturnsAsync(true);
|
||||
repo.Setup(r => r.StoreAnalyzeRuleAsync(It.IsAny<AnalyzeRule>(), TenantId))
|
||||
.Callback<AnalyzeRule, string>((rule, _) => stored.Add(rule))
|
||||
.ReturnsAsync(true);
|
||||
|
||||
var service = new AnalyzeRuleService(repo.Object, NullLogger<AnalyzeRuleService>.Instance);
|
||||
return (new AnalyzeRulesFunction(NullLogger<AnalyzeRulesFunction>.Instance, service), stored);
|
||||
}
|
||||
|
||||
private static AnalyzeRule SpoofedPayload() => new()
|
||||
{
|
||||
RuleId = RuleId,
|
||||
Title = "Proxy PAC unreachable",
|
||||
Description = "Custom",
|
||||
Severity = "warning",
|
||||
Category = "network",
|
||||
Explanation = "The PAC file could not be fetched.",
|
||||
IsBuiltIn = false,
|
||||
IsCommunity = false,
|
||||
Enabled = true,
|
||||
Author = "Spoofed Author",
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new() { Signal = "pac_failed", Source = "event_type", EventType = "network_pac_failed", Required = true }
|
||||
},
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task CreateRule_stamps_author_from_jwt_not_from_body()
|
||||
{
|
||||
var (function, stored) = BuildFunction();
|
||||
var req = BuildRequest(AlicePrincipal(), SpoofedPayload());
|
||||
|
||||
var response = await function.CreateRule(req);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Alice Admin", written.Author);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateRule_falls_back_to_product_name_without_identifying_claims()
|
||||
{
|
||||
var (function, stored) = BuildFunction();
|
||||
var req = BuildRequest(Principal(("tid", TenantId)), SpoofedPayload());
|
||||
|
||||
var response = await function.CreateRule(req);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Autopilot Monitor", written.Author);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRule_upsert_of_unknown_rule_stamps_author_from_jwt()
|
||||
{
|
||||
var (function, stored) = BuildFunction(existingTenantRule: null);
|
||||
var req = BuildRequest(AlicePrincipal(), SpoofedPayload());
|
||||
|
||||
var response = await function.UpdateRule(req, RuleId);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Alice Admin", written.Author);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRule_true_update_keeps_original_author_over_editor_and_body()
|
||||
{
|
||||
var existing = SpoofedPayload();
|
||||
existing.Author = "Original Creator";
|
||||
existing.CreatedAt = new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc);
|
||||
var (function, stored) = BuildFunction(existing);
|
||||
var req = BuildRequest(
|
||||
Principal(("tid", TenantId), ("name", "Bob Editor")), SpoofedPayload());
|
||||
|
||||
var response = await function.UpdateRule(req, RuleId);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Original Creator", written.Author);
|
||||
Assert.Equal(existing.CreatedAt, written.CreatedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateFromTemplate_stamps_the_copying_admin_not_the_template_author()
|
||||
{
|
||||
var template = new AnalyzeRule
|
||||
{
|
||||
RuleId = TemplateRuleId,
|
||||
Title = "AutoLogon enabled for an unexpected user",
|
||||
Description = "Template",
|
||||
Severity = "warning",
|
||||
Category = "security",
|
||||
Explanation = "Template",
|
||||
IsBuiltIn = true,
|
||||
Author = "Autopilot Monitor",
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new() { Signal = "autologon", Source = "event_type", EventType = "autologon_analysis", Operator = "equals", Value = "PLACEHOLDER", Required = true }
|
||||
},
|
||||
TemplateVariables = new List<TemplateVariable>
|
||||
{
|
||||
new() { Name = "allowed", Label = "Allowed", ConditionIndex = 0, Field = "value" }
|
||||
},
|
||||
};
|
||||
var (function, stored) = BuildFunction(globalRule: template);
|
||||
var req = BuildRequest(AlicePrincipal(), new { variables = new Dictionary<string, string> { ["allowed"] = "KIOSK-1" } });
|
||||
|
||||
var response = await function.CreateFromTemplate(req, TemplateRuleId);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Alice Admin", written.Author);
|
||||
Assert.Equal(TemplateRuleId, written.DerivedFromTemplateRuleId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The pure pieces of <see cref="RuleSubmissionService"/> (id suggestion, repo file, snapshot
|
||||
/// stripping, attribution shape) and the review state machine against mocked repositories.
|
||||
/// </summary>
|
||||
public class RuleSubmissionServiceTests
|
||||
{
|
||||
private const string TenantId = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
// ── id suggestion ───────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Suggest_is_max_plus_one_and_never_fills_a_gap()
|
||||
{
|
||||
// 001 and 003 exist, 002 is a retired id — the next is 004, not 002.
|
||||
var taken = new[] { "ANALYZE-NET-001", "ANALYZE-NET-003", "ANALYZE-APP-018", "GATHER-NET-009" };
|
||||
Assert.Equal("ANALYZE-NET-004", RuleSubmissionService.SuggestPublishedRuleId("analyze", "network", taken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Suggest_starts_at_001_for_an_empty_category_and_maps_the_kind_convention()
|
||||
{
|
||||
Assert.Equal("ANALYZE-NET-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "network", Array.Empty<string>()));
|
||||
Assert.Equal("GATHER-DEVICE-001", RuleSubmissionService.SuggestPublishedRuleId("gather", "device", Array.Empty<string>()));
|
||||
Assert.Equal("ANALYZE-DEV-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "device", Array.Empty<string>()));
|
||||
Assert.Equal("ANALYZE-ENRL-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "enrollment", Array.Empty<string>()));
|
||||
Assert.Equal("GATHER-ENROLL-001", RuleSubmissionService.SuggestPublishedRuleId("gather", "enrollment", Array.Empty<string>()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Suggest_is_case_insensitive_over_taken_ids()
|
||||
{
|
||||
Assert.Equal("ANALYZE-SEC-008", RuleSubmissionService.SuggestPublishedRuleId("analyze", "security", new[] { "analyze-sec-007" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Suggest_falls_back_to_the_upper_cased_category_when_unmapped()
|
||||
{
|
||||
Assert.Equal("ANALYZE-OFFICE-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "office", Array.Empty<string>()));
|
||||
}
|
||||
|
||||
// ── freeze + repo file ──────────────────────────────────────────────────
|
||||
|
||||
private static AnalyzeRule CustomAnalyzeRule() => new()
|
||||
{
|
||||
RuleId = "ANALYZE-CUSTOM-003",
|
||||
Title = "Proxy PAC unreachable",
|
||||
Description = "PAC download fails",
|
||||
Severity = "warning",
|
||||
Category = "network",
|
||||
Version = "1.2.0",
|
||||
Author = "Alice Admin",
|
||||
Enabled = false,
|
||||
IsBuiltIn = false,
|
||||
IsCommunity = false,
|
||||
Provenance = "embedded",
|
||||
MarkSessionAsFailed = true,
|
||||
Notify = true,
|
||||
NotifyChannelIds = new List<string> { "chan-1" },
|
||||
DerivedFromTemplateRuleId = "ANALYZE-SEC-004",
|
||||
Explanation = "The PAC file could not be fetched.",
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new() { Signal = "pac_failed", Source = "event_type", EventType = "network_pac_failed", Required = true },
|
||||
},
|
||||
CreatedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc),
|
||||
UpdatedAt = new DateTime(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc),
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Freeze_strips_server_and_tenant_fields_and_keeps_the_rule()
|
||||
{
|
||||
var json = RuleSubmissionService.FreezeRule(CustomAnalyzeRule());
|
||||
var node = JsonNode.Parse(json)!.AsObject();
|
||||
|
||||
foreach (var stripped in new[] { "isBuiltIn", "provenance", "createdAt", "updatedAt", "markSessionAsFailed", "notifyDefault", "notify", "notifyChannelIds" })
|
||||
Assert.False(node.ContainsKey(stripped), $"{stripped} must not be frozen");
|
||||
|
||||
Assert.Equal("ANALYZE-CUSTOM-003", node["ruleId"]!.GetValue<string>());
|
||||
Assert.Equal("Alice Admin", node["author"]!.GetValue<string>());
|
||||
Assert.Equal("ANALYZE-SEC-004", node["derivedFromTemplateRuleId"]!.GetValue<string>());
|
||||
Assert.Single(node["conditions"]!.AsArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RepoFile_carries_schema_pointer_assigned_id_credit_and_community_flag_in_repo_order()
|
||||
{
|
||||
var s = new RuleSubmission
|
||||
{
|
||||
RuleKind = RuleSubmissionKinds.Analyze,
|
||||
RuleJson = RuleSubmissionService.FreezeRule(CustomAnalyzeRule()),
|
||||
AttributionName = RuleAttributionModes.AnonymousAuthor,
|
||||
};
|
||||
|
||||
var file = RuleSubmissionService.BuildRepoFile(s, "ANALYZE-NET-002");
|
||||
|
||||
Assert.Equal("rules/analyze/ANALYZE-NET-002.json", file.Path);
|
||||
Assert.EndsWith("\n", file.Content);
|
||||
var node = JsonNode.Parse(file.Content)!.AsObject();
|
||||
var keys = node.Select(kv => kv.Key).ToList();
|
||||
Assert.Equal(new[] { "$schema", "ruleId", "title", "description", "severity", "category", "version", "author", "enabled", "isCommunity" }, keys.Take(10));
|
||||
Assert.Equal("../schema/analyze-rule.schema.json", node["$schema"]!.GetValue<string>());
|
||||
Assert.Equal("ANALYZE-NET-002", node["ruleId"]!.GetValue<string>());
|
||||
Assert.Equal("Community contribution", node["author"]!.GetValue<string>());
|
||||
Assert.True(node["isCommunity"]!.GetValue<bool>());
|
||||
// Analyze rules ship enabled — the tenant's own toggle state does not travel.
|
||||
Assert.True(node["enabled"]!.GetValue<bool>());
|
||||
Assert.False(node.ContainsKey("derivedFromTemplateRuleId"));
|
||||
Assert.False(node.ContainsKey("isBuiltIn"));
|
||||
Assert.Contains("\"explanation\": \"The PAC file could not be fetched.\"", file.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RepoFile_for_a_gather_rule_ships_disabled_and_without_severity()
|
||||
{
|
||||
var gather = new GatherRule
|
||||
{
|
||||
RuleId = "GATHER-CUSTOM-001",
|
||||
Title = "BIOS config",
|
||||
Description = "Reads the BIOS registry block",
|
||||
Category = "device",
|
||||
Enabled = true,
|
||||
IsBuiltIn = false,
|
||||
CollectorType = "registry",
|
||||
Target = "HKLM\\SOFTWARE\\Vendor\\BIOS",
|
||||
Trigger = "startup",
|
||||
OutputEventType = "gather_bios_config",
|
||||
};
|
||||
var s = new RuleSubmission
|
||||
{
|
||||
RuleKind = RuleSubmissionKinds.Gather,
|
||||
RuleJson = RuleSubmissionService.FreezeRule(gather),
|
||||
AttributionName = "Contoso IT",
|
||||
};
|
||||
|
||||
var file = RuleSubmissionService.BuildRepoFile(s, "GATHER-DEVICE-009");
|
||||
|
||||
Assert.Equal("rules/gather/GATHER-DEVICE-009.json", file.Path);
|
||||
var node = JsonNode.Parse(file.Content)!.AsObject();
|
||||
Assert.Equal("../schema/gather-rule.schema.json", node["$schema"]!.GetValue<string>());
|
||||
Assert.False(node["enabled"]!.GetValue<bool>());
|
||||
Assert.Equal("Contoso IT", node["author"]!.GetValue<string>());
|
||||
Assert.False(node.ContainsKey("severity"));
|
||||
// No \u escaping of the backslash-heavy registry path beyond JSON's own rules.
|
||||
Assert.Contains("HKLM\\\\SOFTWARE\\\\Vendor\\\\BIOS", file.Content);
|
||||
}
|
||||
|
||||
// ── attribution ─────────────────────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData("Alice A.")]
|
||||
[InlineData("Contoso IT & Ops (EMEA)")]
|
||||
[InlineData("Zoë Müller-Lüdenscheidt")]
|
||||
public void AttributionName_accepts_names(string name)
|
||||
=> Assert.Equal(name, RuleSubmissionService.ValidateAttributionName(name));
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("<script>")]
|
||||
[InlineData("https://example.com")]
|
||||
[InlineData("line\nbreak")]
|
||||
public void AttributionName_rejects_markup_urls_and_control_characters(string name)
|
||||
=> Assert.Throws<ArgumentException>(() => RuleSubmissionService.ValidateAttributionName(name));
|
||||
|
||||
// ── review state machine ────────────────────────────────────────────────
|
||||
|
||||
private static (RuleSubmissionService service, Mock<IRuleSubmissionRepository> repo) Build(
|
||||
RuleSubmission row, IEnumerable<string>? globalAnalyzeIds = null, IEnumerable<string>? reservedIds = null)
|
||||
{
|
||||
var repo = new Mock<IRuleSubmissionRepository>(MockBehavior.Loose);
|
||||
repo.Setup(r => r.GetAsync(row.SubmissionId)).ReturnsAsync(row);
|
||||
repo.Setup(r => r.UpdateAsync(It.IsAny<RuleSubmission>())).ReturnsAsync(true);
|
||||
repo.Setup(r => r.GetReservedPublishedRuleIdsAsync())
|
||||
.ReturnsAsync(new HashSet<string>(reservedIds ?? Array.Empty<string>(), StringComparer.OrdinalIgnoreCase));
|
||||
|
||||
var rules = new Mock<IRuleRepository>(MockBehavior.Loose);
|
||||
rules.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(
|
||||
(globalAnalyzeIds ?? Array.Empty<string>()).Select(id => new AnalyzeRule { RuleId = id, IsBuiltIn = true }).ToList());
|
||||
rules.Setup(r => r.GetGatherRulesAsync("global")).ReturnsAsync(new List<GatherRule>());
|
||||
|
||||
var metrics = new Mock<IMetricsRepository>(MockBehavior.Loose);
|
||||
var config = new Mock<TenantConfigurationService>(MockBehavior.Loose,
|
||||
Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
var service = new RuleSubmissionService(repo.Object, rules.Object, metrics.Object, config.Object,
|
||||
NullLogger<RuleSubmissionService>.Instance);
|
||||
return (service, repo);
|
||||
}
|
||||
|
||||
private static RuleSubmission PendingRow() => new()
|
||||
{
|
||||
SubmissionId = "a1b2c3d4e5f6",
|
||||
BatchId = "b",
|
||||
TenantId = TenantId,
|
||||
RuleKind = RuleSubmissionKinds.Analyze,
|
||||
SourceRuleId = "ANALYZE-CUSTOM-003",
|
||||
Title = "Proxy PAC unreachable",
|
||||
Category = "network",
|
||||
RuleJson = RuleSubmissionService.FreezeRule(CustomAnalyzeRule()),
|
||||
SubmittedBy = "alice@contoso.com",
|
||||
SubmittedByName = "Alice Admin",
|
||||
SubmittedAt = DateTime.UtcNow,
|
||||
Status = RuleSubmissionStatuses.Pending,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Approve_requires_a_reserved_id_of_the_same_kind()
|
||||
{
|
||||
var (service, _) = Build(PendingRow());
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve" }, "ga@example.com"));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-CUSTOM-009" }, "ga@example.com"));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "GATHER-NET-002" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Approve_refuses_an_id_taken_by_the_catalog_or_another_approval()
|
||||
{
|
||||
var (service, _) = Build(PendingRow(), globalAnalyzeIds: new[] { "ANALYZE-NET-001" }, reservedIds: new[] { "ANALYZE-NET-002" });
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-001" }, "ga@example.com"));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-002" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Approve_stores_id_comment_adaptation_flag_and_reviewer()
|
||||
{
|
||||
var (service, repo) = Build(PendingRow());
|
||||
RuleSubmission? written = null;
|
||||
repo.Setup(r => r.UpdateAsync(It.IsAny<RuleSubmission>())).Callback<RuleSubmission>(s => written = s).ReturnsAsync(true);
|
||||
|
||||
var result = await service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-003", ReviewComment = "Taken, will generalise the title.", WillBeAdapted = true },
|
||||
"ga@example.com");
|
||||
|
||||
Assert.Same(result, written);
|
||||
Assert.Equal(RuleSubmissionStatuses.Approved, result.Status);
|
||||
Assert.Equal("ANALYZE-NET-003", result.PublishedRuleId);
|
||||
Assert.True(result.WillBeAdapted);
|
||||
Assert.Equal("Taken, will generalise the title.", result.ReviewComment);
|
||||
Assert.Equal("ga@example.com", result.ReviewedBy);
|
||||
Assert.NotNull(result.ReviewedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Decline_requires_a_comment_and_clears_the_published_id()
|
||||
{
|
||||
var row = PendingRow();
|
||||
row.Status = RuleSubmissionStatuses.Approved;
|
||||
row.PublishedRuleId = "ANALYZE-NET-003";
|
||||
var (service, _) = Build(row);
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "decline" }, "ga@example.com"));
|
||||
|
||||
var result = await service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "decline", ReviewComment = "Too tenant-specific." }, "ga@example.com");
|
||||
|
||||
Assert.Equal(RuleSubmissionStatuses.Declined, result.Status);
|
||||
Assert.Null(result.PublishedRuleId);
|
||||
Assert.False(result.WillBeAdapted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Published_is_derived_and_final()
|
||||
{
|
||||
var row = PendingRow();
|
||||
row.Status = RuleSubmissionStatuses.Approved;
|
||||
row.PublishedRuleId = "ANALYZE-NET-003";
|
||||
var (service, _) = Build(row, globalAnalyzeIds: new[] { "ANALYZE-NET-003" });
|
||||
|
||||
var items = await service.ToItemsAsync(new[] { row });
|
||||
Assert.Equal(RuleSubmissionStatuses.Published, items[0].Status);
|
||||
Assert.Equal(RuleSubmissionStatuses.Approved, row.Status);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "decline", ReviewComment = "too late" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Approved_but_unpublished_stays_approved_on_the_wire()
|
||||
{
|
||||
var row = PendingRow();
|
||||
row.Status = RuleSubmissionStatuses.Approved;
|
||||
row.PublishedRuleId = "ANALYZE-NET-003";
|
||||
var (service, _) = Build(row, globalAnalyzeIds: new[] { "ANALYZE-NET-001" });
|
||||
|
||||
var items = await service.ToItemsAsync(new[] { row });
|
||||
Assert.Equal(RuleSubmissionStatuses.Approved, items[0].Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Withdraw_only_pending_and_only_own_tenant()
|
||||
{
|
||||
var row = PendingRow();
|
||||
var (service, _) = Build(row);
|
||||
|
||||
Assert.False(await service.WithdrawAsync("22222222-2222-2222-2222-222222222222", "a1b2c3d4e5f6", crossTenantAllowed: false));
|
||||
Assert.True(await service.WithdrawAsync(TenantId, "a1b2c3d4e5f6", crossTenantAllowed: false));
|
||||
Assert.Equal(RuleSubmissionStatuses.Withdrawn, row.Status);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.WithdrawAsync(TenantId, "a1b2c3d4e5f6", crossTenantAllowed: false));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-003" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unknown_decision_is_a_bad_request()
|
||||
{
|
||||
var (service, _) = Build(PendingRow());
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "maybe" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Detail_returns_the_typed_rule_suggested_id_and_repo_file()
|
||||
{
|
||||
var (service, _) = Build(PendingRow(), globalAnalyzeIds: new[] { "ANALYZE-NET-001" });
|
||||
|
||||
var detail = await service.GetDetailAsync("a1b2c3d4e5f6");
|
||||
|
||||
Assert.NotNull(detail);
|
||||
Assert.NotNull(detail!.AnalyzeRule);
|
||||
Assert.Null(detail.GatherRule);
|
||||
Assert.Equal("ANALYZE-CUSTOM-003", detail.AnalyzeRule!.RuleId);
|
||||
Assert.False(detail.AnalyzeRule.IsBuiltIn);
|
||||
Assert.Equal("ANALYZE-NET-002", detail.SuggestedPublishedRuleId);
|
||||
Assert.Equal("rules/analyze/ANALYZE-NET-002.json", detail.RepoFile!.Path);
|
||||
}
|
||||
|
||||
// ── submit ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static (RuleSubmissionService service, List<RuleSubmission> stored) BuildForSubmit(
|
||||
List<AnalyzeRule> tenantAnalyze, List<RuleSubmission>? existing = null, TenantConfiguration? config = null)
|
||||
{
|
||||
var stored = new List<RuleSubmission>();
|
||||
var repo = new Mock<IRuleSubmissionRepository>(MockBehavior.Loose);
|
||||
repo.Setup(r => r.GetForTenantAsync(TenantId)).ReturnsAsync(existing ?? new List<RuleSubmission>());
|
||||
repo.Setup(r => r.AddAsync(It.IsAny<RuleSubmission>())).Callback<RuleSubmission>(stored.Add).ReturnsAsync(true);
|
||||
repo.Setup(r => r.GetReservedPublishedRuleIdsAsync()).ReturnsAsync(new HashSet<string>());
|
||||
|
||||
var rules = new Mock<IRuleRepository>(MockBehavior.Loose);
|
||||
rules.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(tenantAnalyze);
|
||||
rules.Setup(r => r.GetGatherRulesAsync(TenantId)).ReturnsAsync(new List<GatherRule>());
|
||||
rules.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(new List<AnalyzeRule>());
|
||||
rules.Setup(r => r.GetGatherRulesAsync("global")).ReturnsAsync(new List<GatherRule>());
|
||||
|
||||
var metrics = new Mock<IMetricsRepository>(MockBehavior.Loose);
|
||||
metrics.Setup(m => m.GetRuleStatsAsync(TenantId, It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<int>()))
|
||||
.ReturnsAsync(new List<RuleStatsEntry>
|
||||
{
|
||||
new() { RuleId = "ANALYZE-CUSTOM-003", FireCount = 4, SessionsEvaluated = 40, EvaluationCount = 41 },
|
||||
new() { RuleId = "ANALYZE-CUSTOM-003", FireCount = 1, SessionsEvaluated = 10, EvaluationCount = 10 },
|
||||
new() { RuleId = "ANALYZE-CUSTOM-999", FireCount = 99, SessionsEvaluated = 99, EvaluationCount = 99 },
|
||||
});
|
||||
|
||||
var configRepo = new Mock<IConfigRepository>(MockBehavior.Loose);
|
||||
var configService = new Mock<TenantConfigurationService>(MockBehavior.Loose, configRepo.Object,
|
||||
NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
configService.Setup(c => c.GetConfigurationIfExistsAsync(TenantId)).ReturnsAsync(config);
|
||||
|
||||
var service = new RuleSubmissionService(repo.Object, rules.Object, metrics.Object, configService.Object,
|
||||
NullLogger<RuleSubmissionService>.Instance);
|
||||
return (service, stored);
|
||||
}
|
||||
|
||||
private static SubmitRuleSubmissionsRequest Request(params string[] ruleIds) => new()
|
||||
{
|
||||
TenantId = TenantId,
|
||||
Items = ruleIds.Select(id => new RuleSubmissionItemRef { Kind = "analyze", RuleId = id }).ToList(),
|
||||
Comment = "Fires when the PAC download fails during ESP.",
|
||||
AttributionMode = RuleAttributionModes.Anonymous,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_freezes_the_tenant_rule_records_findings_and_fire_stats()
|
||||
{
|
||||
var (service, stored) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() });
|
||||
|
||||
var created = await service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin");
|
||||
|
||||
var s = Assert.Single(created);
|
||||
Assert.Same(s, Assert.Single(stored));
|
||||
Assert.Equal(12, s.SubmissionId.Length);
|
||||
Assert.Equal(12, s.BatchId.Length);
|
||||
Assert.Equal(RuleSubmissionStatuses.Pending, s.Status);
|
||||
Assert.Equal("Community contribution", s.AttributionName);
|
||||
Assert.Equal("Proxy PAC unreachable", s.Title);
|
||||
Assert.Equal("network", s.Category);
|
||||
Assert.Equal("ANALYZE-SEC-004", s.DerivedFromTemplateRuleId);
|
||||
Assert.Contains(s.ValidationFindings, f => f.Level == "info" && f.Message.Contains("ANALYZE-SEC-004"));
|
||||
Assert.DoesNotContain(s.ValidationFindings, f => f.Level == "error");
|
||||
Assert.Equal(5, s.SourceFireStats!.FireCount);
|
||||
Assert.Equal(50, s.SourceFireStats.SessionsEvaluated);
|
||||
Assert.DoesNotContain("isBuiltIn", s.RuleJson);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_rejects_built_in_and_unknown_rules_without_storing_anything()
|
||||
{
|
||||
var builtIn = CustomAnalyzeRule();
|
||||
builtIn.RuleId = "ANALYZE-NET-001";
|
||||
builtIn.IsBuiltIn = true;
|
||||
var (service, stored) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule(), builtIn });
|
||||
|
||||
var ex = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003", "ANALYZE-NET-001", "ANALYZE-CUSTOM-404"), "alice@contoso.com", "Alice Admin"));
|
||||
|
||||
Assert.Contains("ANALYZE-NET-001", ex.Message);
|
||||
Assert.Contains("ANALYZE-CUSTOM-404", ex.Message);
|
||||
Assert.Empty(stored);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_rejects_a_rule_whose_draft_validation_fails()
|
||||
{
|
||||
var broken = CustomAnalyzeRule();
|
||||
broken.Conditions = new List<RuleCondition>();
|
||||
var (service, stored) = BuildForSubmit(new List<AnalyzeRule> { broken });
|
||||
|
||||
var ex = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin"));
|
||||
|
||||
Assert.Contains("at least one condition", ex.Message);
|
||||
Assert.Empty(stored);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_refuses_a_second_pending_submission_of_the_same_rule()
|
||||
{
|
||||
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, existing: new List<RuleSubmission> { PendingRow() });
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_enforces_the_daily_cap()
|
||||
{
|
||||
var existing = Enumerable.Range(0, RuleSubmissionService.MaxSubmissionsPerTenantPerDay)
|
||||
.Select(i => { var r = PendingRow(); r.SourceRuleId = $"OTHER-{i}"; r.Status = RuleSubmissionStatuses.Declined; return r; })
|
||||
.ToList();
|
||||
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, existing);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_organization_attribution_uses_the_company_name_and_fails_without_one()
|
||||
{
|
||||
var withName = new TenantConfiguration { TenantId = TenantId, DomainName = "contoso.example", CompanyName = "Contoso Ltd." };
|
||||
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, config: withName);
|
||||
var request = Request("ANALYZE-CUSTOM-003");
|
||||
request.AttributionMode = RuleAttributionModes.Organization;
|
||||
|
||||
var created = await service.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin");
|
||||
Assert.Equal("Contoso Ltd.", created[0].AttributionName);
|
||||
|
||||
var (noConfig, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, config: null);
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => noConfig.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_person_attribution_freezes_the_requested_name()
|
||||
{
|
||||
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() });
|
||||
var request = Request("ANALYZE-CUSTOM-003");
|
||||
request.AttributionMode = RuleAttributionModes.Person;
|
||||
request.AttributionName = " Alice A. ";
|
||||
|
||||
var created = await service.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin");
|
||||
Assert.Equal("Alice A.", created[0].AttributionName);
|
||||
Assert.Equal(RuleAttributionModes.Person, created[0].AttributionMode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Wire pins for the rule-submission responses (typed from the start — the anonymous side is
|
||||
/// the literal a client sees, so a reordered or renamed property fails here first).
|
||||
/// </summary>
|
||||
public class RuleSubmissionsWireParityTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 9, 9, 10, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
private static RuleSubmissionItem Item() => new()
|
||||
{
|
||||
SubmissionId = "a1b2c3d4e5f6",
|
||||
BatchId = "0f0e0d0c0b0a",
|
||||
TenantId = "11111111-1111-1111-1111-111111111111",
|
||||
RuleKind = "analyze",
|
||||
SourceRuleId = "ANALYZE-CUSTOM-003",
|
||||
Title = "Proxy PAC unreachable",
|
||||
Category = "network",
|
||||
Comment = "Fires when the PAC download fails.",
|
||||
SubmittedBy = "alice@contoso.com",
|
||||
SubmittedByName = "Alice Admin",
|
||||
AttributionMode = "anonymous",
|
||||
AttributionName = "Community contribution",
|
||||
SubmittedAt = T0,
|
||||
Status = "approved",
|
||||
ValidationFindings = new List<RuleSubmissionFinding> { new() { Level = "info", Message = "Derived from template ANALYZE-SEC-004" } },
|
||||
SourceFireStats = new RuleSubmissionFireStats { Days = 30, FireCount = 42, SessionsEvaluated = 310, EvaluationCount = 312 },
|
||||
ReviewedBy = "ga@example.com",
|
||||
ReviewedAt = T0.AddDays(1),
|
||||
ReviewComment = "Taken.",
|
||||
WillBeAdapted = true,
|
||||
PublishedRuleId = "ANALYZE-NET-002",
|
||||
DerivedFromTemplateRuleId = "ANALYZE-SEC-004",
|
||||
};
|
||||
|
||||
private static object ItemLiteral() => new
|
||||
{
|
||||
submissionId = "a1b2c3d4e5f6",
|
||||
batchId = "0f0e0d0c0b0a",
|
||||
tenantId = "11111111-1111-1111-1111-111111111111",
|
||||
ruleKind = "analyze",
|
||||
sourceRuleId = "ANALYZE-CUSTOM-003",
|
||||
title = "Proxy PAC unreachable",
|
||||
category = "network",
|
||||
comment = "Fires when the PAC download fails.",
|
||||
submittedBy = "alice@contoso.com",
|
||||
submittedByName = "Alice Admin",
|
||||
attributionMode = "anonymous",
|
||||
attributionName = "Community contribution",
|
||||
submittedAt = T0,
|
||||
status = "approved",
|
||||
validationFindings = new List<object> { new { level = "info", message = "Derived from template ANALYZE-SEC-004" } },
|
||||
sourceFireStats = new { days = 30, fireCount = 42, sessionsEvaluated = 310, evaluationCount = 312 },
|
||||
reviewedBy = "ga@example.com",
|
||||
reviewedAt = T0.AddDays(1),
|
||||
reviewComment = "Taken.",
|
||||
willBeAdapted = true,
|
||||
publishedRuleId = "ANALYZE-NET-002",
|
||||
derivedFromTemplateRuleId = "ANALYZE-SEC-004",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Submit_response_shape()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, message = "Rule submitted for review.", batchId = "0f0e0d0c0b0a", submissions = new List<object> { ItemLiteral() } },
|
||||
new SubmitRuleSubmissionsResponse { Success = true, Message = "Rule submitted for review.", BatchId = "0f0e0d0c0b0a", Submissions = new List<RuleSubmissionItem> { Item() } });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void List_nonPaged_has_no_nextLink_key()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, count = 1, submissions = new List<object> { ItemLiteral() } },
|
||||
new RuleSubmissionListResponse { Success = true, Count = 1, Submissions = new List<RuleSubmissionItem> { Item() } });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void List_paged_carries_nextLink()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, count = 1, submissions = new List<object> { ItemLiteral() }, nextLink = "/api/global/rule-submissions?pageSize=20&continuation=abc" },
|
||||
new RuleSubmissionListResponse { Success = true, Count = 1, Submissions = new List<RuleSubmissionItem> { Item() }, NextLink = "/api/global/rule-submissions?pageSize=20&continuation=abc" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void List_last_page_drops_the_nextLink_key()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, count = 0, submissions = new List<object>() },
|
||||
new RuleSubmissionListResponse { Success = true, Count = 0, Submissions = new List<RuleSubmissionItem>(), NextLink = null });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Detail_shape_with_analyze_rule_omits_the_gather_slot()
|
||||
{
|
||||
var rule = new AnalyzeRule
|
||||
{
|
||||
RuleId = "ANALYZE-CUSTOM-003", Title = "Proxy PAC unreachable", Description = "d", Severity = "warning", Category = "network",
|
||||
Explanation = "e", IsBuiltIn = false, Conditions = new List<RuleCondition>(),
|
||||
};
|
||||
var typed = new RuleSubmissionDetailResponse
|
||||
{
|
||||
Success = true,
|
||||
Submission = Item(),
|
||||
AnalyzeRule = rule,
|
||||
LiveFireStats = new RuleSubmissionFireStats { Days = 30, FireCount = 1, SessionsEvaluated = 2, EvaluationCount = 3 },
|
||||
SuggestedPublishedRuleId = "ANALYZE-NET-002",
|
||||
RepoFile = new RuleSubmissionRepoFile { Path = "rules/analyze/ANALYZE-NET-002.json", Content = "{}\n" },
|
||||
};
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new
|
||||
{
|
||||
success = true,
|
||||
submission = ItemLiteral(),
|
||||
analyzeRule = rule,
|
||||
liveFireStats = new { days = 30, fireCount = 1, sessionsEvaluated = 2, evaluationCount = 3 },
|
||||
suggestedPublishedRuleId = "ANALYZE-NET-002",
|
||||
repoFile = new { path = "rules/analyze/ANALYZE-NET-002.json", content = "{}\n" },
|
||||
},
|
||||
typed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Review_response_shape()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, message = "Submission approved.", submission = ItemLiteral() },
|
||||
new ReviewRuleSubmissionResponse { Success = true, Message = "Submission approved.", Submission = Item() });
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,12 @@ public sealed class SharedManifestParityTests
|
||||
["webhookProviderTypes"] = EnumMap<WebhookProviderType>(),
|
||||
["annotationLanes"] = AnnotationLanes.All,
|
||||
["annotationVerdicts"] = AnnotationVerdicts.All,
|
||||
// Community rule submissions: kinds, effective statuses (incl. the derived "published"),
|
||||
// attribution modes and reviewer decisions — the MCP tool schemas enumerate these.
|
||||
["ruleSubmissionKinds"] = RuleSubmissionKinds.All,
|
||||
["ruleSubmissionStatuses"] = RuleSubmissionStatuses.All,
|
||||
["ruleAttributionModes"] = RuleAttributionModes.All,
|
||||
["ruleSubmissionDecisions"] = RuleSubmissionDecisions.All,
|
||||
// Ops vocabularies. Declaration order kept for severities — it IS the ladder
|
||||
// (Info < Warning < Error < Critical), and the MCP renders it in that order.
|
||||
["opsEventCategories"] = ConstStrings(typeof(OpsEventCategory)),
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
using AutopilotMonitor.Functions.DataAccess.TableStorage;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Round-trip pins for the RuleSubmissions Store/Map pair (memory:
|
||||
/// feedback_table_storage_serialization — every new field in <see cref="RuleSubmission"/>
|
||||
/// MUST be exercised in Store+Map so silent drops surface here), plus the key and filter shapes.
|
||||
/// </summary>
|
||||
public class TableRuleSubmissionRepositoryTests
|
||||
{
|
||||
private const string TenantId = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
private static RuleSubmission Full() => new()
|
||||
{
|
||||
SubmissionId = "a1b2c3d4e5f6",
|
||||
BatchId = "0f0e0d0c0b0a",
|
||||
TenantId = TenantId,
|
||||
RuleKind = RuleSubmissionKinds.Analyze,
|
||||
SourceRuleId = "ANALYZE-CUSTOM-003",
|
||||
Title = "Proxy PAC unreachable",
|
||||
Category = "network",
|
||||
RuleJson = "{\"ruleId\":\"ANALYZE-CUSTOM-003\",\"title\":\"Proxy PAC unreachable\"}",
|
||||
Comment = "Fires when the PAC download fails during ESP.",
|
||||
SubmittedBy = "alice@contoso.com",
|
||||
SubmittedByName = "Alice Admin",
|
||||
AttributionMode = RuleAttributionModes.Person,
|
||||
AttributionName = "Alice A.",
|
||||
SubmittedAt = new DateTime(2026, 9, 9, 10, 30, 0, DateTimeKind.Utc),
|
||||
Status = RuleSubmissionStatuses.Approved,
|
||||
ValidationFindings = new List<RuleSubmissionFinding>
|
||||
{
|
||||
new() { Level = "info", Message = "Derived from template ANALYZE-SEC-004" },
|
||||
},
|
||||
SourceFireStats = new RuleSubmissionFireStats { Days = 30, FireCount = 42, SessionsEvaluated = 310, EvaluationCount = 312 },
|
||||
ReviewedBy = "ga@example.com",
|
||||
ReviewedAt = new DateTime(2026, 9, 10, 8, 0, 0, DateTimeKind.Utc),
|
||||
ReviewComment = "Taken, generalised for the community.",
|
||||
WillBeAdapted = true,
|
||||
PublishedRuleId = "ANALYZE-NET-002",
|
||||
DerivedFromTemplateRuleId = "ANALYZE-SEC-004",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Roundtrip_all_fields_survive_store_and_map()
|
||||
{
|
||||
var original = Full();
|
||||
|
||||
var mapped = TableRuleSubmissionRepository.MapSubmission(
|
||||
TableRuleSubmissionRepository.StoreSubmission(original));
|
||||
|
||||
Assert.Equal(original.SubmissionId, mapped.SubmissionId);
|
||||
Assert.Equal(original.BatchId, mapped.BatchId);
|
||||
Assert.Equal(original.TenantId, mapped.TenantId);
|
||||
Assert.Equal(original.RuleKind, mapped.RuleKind);
|
||||
Assert.Equal(original.SourceRuleId, mapped.SourceRuleId);
|
||||
Assert.Equal(original.Title, mapped.Title);
|
||||
Assert.Equal(original.Category, mapped.Category);
|
||||
Assert.Equal(original.RuleJson, mapped.RuleJson);
|
||||
Assert.Equal(original.Comment, mapped.Comment);
|
||||
Assert.Equal(original.SubmittedBy, mapped.SubmittedBy);
|
||||
Assert.Equal(original.SubmittedByName, mapped.SubmittedByName);
|
||||
Assert.Equal(original.AttributionMode, mapped.AttributionMode);
|
||||
Assert.Equal(original.AttributionName, mapped.AttributionName);
|
||||
Assert.Equal(original.SubmittedAt, mapped.SubmittedAt);
|
||||
Assert.Equal(original.Status, mapped.Status);
|
||||
Assert.Single(mapped.ValidationFindings);
|
||||
Assert.Equal("info", mapped.ValidationFindings[0].Level);
|
||||
Assert.Equal(original.ValidationFindings[0].Message, mapped.ValidationFindings[0].Message);
|
||||
Assert.NotNull(mapped.SourceFireStats);
|
||||
Assert.Equal(42, mapped.SourceFireStats!.FireCount);
|
||||
Assert.Equal(310, mapped.SourceFireStats.SessionsEvaluated);
|
||||
Assert.Equal(312, mapped.SourceFireStats.EvaluationCount);
|
||||
Assert.Equal(30, mapped.SourceFireStats.Days);
|
||||
Assert.Equal(original.ReviewedBy, mapped.ReviewedBy);
|
||||
Assert.Equal(original.ReviewedAt, mapped.ReviewedAt);
|
||||
Assert.Equal(original.ReviewComment, mapped.ReviewComment);
|
||||
Assert.True(mapped.WillBeAdapted);
|
||||
Assert.Equal(original.PublishedRuleId, mapped.PublishedRuleId);
|
||||
Assert.Equal(original.DerivedFromTemplateRuleId, mapped.DerivedFromTemplateRuleId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Roundtrip_pending_row_keeps_nulls_null()
|
||||
{
|
||||
var original = Full();
|
||||
original.Status = RuleSubmissionStatuses.Pending;
|
||||
original.Comment = null;
|
||||
original.SourceFireStats = null;
|
||||
original.ValidationFindings = new List<RuleSubmissionFinding>();
|
||||
original.ReviewedBy = null;
|
||||
original.ReviewedAt = null;
|
||||
original.ReviewComment = null;
|
||||
original.WillBeAdapted = false;
|
||||
original.PublishedRuleId = null;
|
||||
original.DerivedFromTemplateRuleId = null;
|
||||
|
||||
var mapped = TableRuleSubmissionRepository.MapSubmission(
|
||||
TableRuleSubmissionRepository.StoreSubmission(original));
|
||||
|
||||
Assert.Null(mapped.Comment);
|
||||
Assert.Null(mapped.SourceFireStats);
|
||||
Assert.Empty(mapped.ValidationFindings);
|
||||
Assert.Null(mapped.ReviewedBy);
|
||||
Assert.Null(mapped.ReviewedAt);
|
||||
Assert.Null(mapped.ReviewComment);
|
||||
Assert.False(mapped.WillBeAdapted);
|
||||
Assert.Null(mapped.PublishedRuleId);
|
||||
Assert.Null(mapped.DerivedFromTemplateRuleId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Store_uses_the_single_partition_and_an_inverted_tick_row_key()
|
||||
{
|
||||
var s = Full();
|
||||
var entity = TableRuleSubmissionRepository.StoreSubmission(s);
|
||||
|
||||
Assert.Equal("submissions", entity.PartitionKey);
|
||||
Assert.Equal($"{RowKeyCodec.InvertedTicks(s.SubmittedAt)}_{s.SubmissionId}", entity.RowKey);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Newer_submission_sorts_first()
|
||||
{
|
||||
var older = Full();
|
||||
var newer = Full();
|
||||
newer.SubmittedAt = older.SubmittedAt.AddMinutes(5);
|
||||
|
||||
var olderKey = TableRuleSubmissionRepository.StoreSubmission(older).RowKey;
|
||||
var newerKey = TableRuleSubmissionRepository.StoreSubmission(newer).RowKey;
|
||||
|
||||
Assert.True(string.CompareOrdinal(newerKey, olderKey) < 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_tolerates_a_corrupt_json_column()
|
||||
{
|
||||
var entity = TableRuleSubmissionRepository.StoreSubmission(Full());
|
||||
entity["ValidationFindingsJson"] = "{not json";
|
||||
entity["SourceFireStatsJson"] = "[]";
|
||||
|
||||
var mapped = TableRuleSubmissionRepository.MapSubmission(entity);
|
||||
|
||||
Assert.Empty(mapped.ValidationFindings);
|
||||
Assert.Null(mapped.SourceFireStats);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null, "PartitionKey eq 'submissions'")]
|
||||
[InlineData("t'1", null, "PartitionKey eq 'submissions' and TenantId eq 't''1'")]
|
||||
[InlineData(null, "pending", "PartitionKey eq 'submissions' and Status eq 'pending'")]
|
||||
[InlineData("t1", "approved", "PartitionKey eq 'submissions' and TenantId eq 't1' and Status eq 'approved'")]
|
||||
public void Filter_escapes_and_composes(string? tenantId, string? status, string expected)
|
||||
{
|
||||
Assert.Equal(expected, TableRuleSubmissionRepository.BuildFilter(tenantId, status));
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ namespace AutopilotMonitor.Functions.DataAccess
|
||||
services.AddSingleton<ISessionAnnotationRepository, TableSessionAnnotationRepository>();
|
||||
services.AddSingleton<IBootstrapRepository, TableBootstrapRepository>();
|
||||
services.AddSingleton<INotificationRepository, TableNotificationRepository>();
|
||||
services.AddSingleton<IRuleSubmissionRepository, TableRuleSubmissionRepository>();
|
||||
services.AddSingleton<ITenantNotificationRepository, TableTenantNotificationRepository>();
|
||||
services.AddSingleton<ISlaTenantStatusRepository, TableSlaTenantStatusRepository>();
|
||||
// What's new notifier watermark (single platform row in the AdminConfiguration table).
|
||||
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Pagination;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Azure;
|
||||
using Azure.Data.Tables;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
{
|
||||
/// <summary>
|
||||
/// Table-storage implementation of <see cref="IRuleSubmissionRepository"/>.
|
||||
/// PK = <see cref="PartitionKey"/> for every tenant, RK = inverted ticks + id (newest first).
|
||||
/// </summary>
|
||||
public class TableRuleSubmissionRepository : IRuleSubmissionRepository
|
||||
{
|
||||
internal const string PartitionKey = "submissions";
|
||||
|
||||
private readonly TableClient _tableClient;
|
||||
private readonly ILogger<TableRuleSubmissionRepository> _logger;
|
||||
|
||||
public TableRuleSubmissionRepository(TableStorageService storage, ILogger<TableRuleSubmissionRepository> logger)
|
||||
{
|
||||
_tableClient = storage.GetTableClient(Constants.TableNames.RuleSubmissions);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> AddAsync(RuleSubmission submission)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _tableClient.AddEntityAsync(StoreSubmission(submission));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to store rule submission {SubmissionId}", submission.SubmissionId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<RuleSubmission?> GetAsync(string submissionId)
|
||||
{
|
||||
var entity = await FindEntityAsync(submissionId);
|
||||
return entity == null ? null : MapSubmission(entity);
|
||||
}
|
||||
|
||||
public async Task<List<RuleSubmission>> GetForTenantAsync(string tenantId)
|
||||
{
|
||||
var results = new List<RuleSubmission>();
|
||||
try
|
||||
{
|
||||
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(filter: BuildFilter(tenantId, status: null)))
|
||||
{
|
||||
results.Add(MapSubmission(entity));
|
||||
}
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
_logger.LogDebug("RuleSubmissions table does not exist yet, returning empty list");
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task<RawPage<RuleSubmission>> GetPageAsync(string? tenantId, string? status, int pageSize, string? continuation)
|
||||
{
|
||||
if (pageSize < 1) throw new ArgumentOutOfRangeException(nameof(pageSize));
|
||||
try
|
||||
{
|
||||
var (entities, nextRawToken) = await AzureTablesPaginator.FetchPageAsync<TableEntity>(
|
||||
client: _tableClient,
|
||||
filter: BuildFilter(tenantId, status),
|
||||
pageSize: pageSize,
|
||||
continuation: continuation);
|
||||
|
||||
var page = new List<RuleSubmission>(entities.Count);
|
||||
foreach (var entity in entities) page.Add(MapSubmission(entity));
|
||||
// RowKey is the inverted tick of SubmittedAt — newest first by construction.
|
||||
return new RawPage<RuleSubmission>(page, nextRawToken);
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
_logger.LogDebug("RuleSubmissions table does not exist yet, returning empty page");
|
||||
return RawPage<RuleSubmission>.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(RuleSubmission submission)
|
||||
{
|
||||
var existing = await FindEntityAsync(submission.SubmissionId);
|
||||
if (existing == null)
|
||||
{
|
||||
_logger.LogWarning("UpdateAsync: rule submission {SubmissionId} not found", submission.SubmissionId);
|
||||
return false;
|
||||
}
|
||||
|
||||
var entity = StoreSubmission(submission);
|
||||
entity.RowKey = existing.RowKey;
|
||||
entity.ETag = existing.ETag;
|
||||
try
|
||||
{
|
||||
// If-Match on the ETag: two reviewers deciding the same submission cannot both win.
|
||||
await _tableClient.UpdateEntityAsync(entity, existing.ETag, TableUpdateMode.Replace);
|
||||
return true;
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 412)
|
||||
{
|
||||
_logger.LogWarning("UpdateAsync: rule submission {SubmissionId} changed underneath the reviewer", submission.SubmissionId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<HashSet<string>> GetReservedPublishedRuleIdsAsync()
|
||||
{
|
||||
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(
|
||||
filter: BuildFilter(tenantId: null, status: RuleSubmissionStatuses.Approved),
|
||||
select: new[] { "PublishedRuleId" }))
|
||||
{
|
||||
var id = entity.GetString("PublishedRuleId");
|
||||
if (!string.IsNullOrEmpty(id)) ids.Add(id!);
|
||||
}
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
_logger.LogDebug("RuleSubmissions table does not exist yet");
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private async Task<TableEntity?> FindEntityAsync(string submissionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(
|
||||
filter: $"PartitionKey eq '{PartitionKey}' and SubmissionId eq '{Escape(submissionId)}'"))
|
||||
{
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
_logger.LogDebug("RuleSubmissions table does not exist yet");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static string BuildFilter(string? tenantId, string? status)
|
||||
{
|
||||
var filter = $"PartitionKey eq '{PartitionKey}'";
|
||||
if (!string.IsNullOrEmpty(tenantId)) filter += $" and TenantId eq '{Escape(tenantId!)}'";
|
||||
if (!string.IsNullOrEmpty(status)) filter += $" and Status eq '{Escape(status!)}'";
|
||||
return filter;
|
||||
}
|
||||
|
||||
private static string Escape(string value) => value.Replace("'", "''");
|
||||
|
||||
// ── Store / Map ─────────────────────────────────────────────────────────
|
||||
// internal static: pinned by round-trip unit tests — every property must survive
|
||||
// Store→Map, so any new field lands in BOTH methods plus the test.
|
||||
|
||||
internal static TableEntity StoreSubmission(RuleSubmission s) =>
|
||||
new(PartitionKey, $"{RowKeyCodec.InvertedTicks(s.SubmittedAt)}_{s.SubmissionId}")
|
||||
{
|
||||
["SubmissionId"] = s.SubmissionId,
|
||||
["BatchId"] = s.BatchId,
|
||||
["TenantId"] = s.TenantId,
|
||||
["RuleKind"] = s.RuleKind,
|
||||
["SourceRuleId"] = s.SourceRuleId,
|
||||
["Title"] = s.Title,
|
||||
["Category"] = s.Category,
|
||||
["RuleJson"] = s.RuleJson,
|
||||
["Comment"] = s.Comment ?? string.Empty,
|
||||
["SubmittedBy"] = s.SubmittedBy,
|
||||
["SubmittedByName"] = s.SubmittedByName,
|
||||
["AttributionMode"] = s.AttributionMode,
|
||||
["AttributionName"] = s.AttributionName,
|
||||
["SubmittedAt"] = s.SubmittedAt,
|
||||
["Status"] = s.Status,
|
||||
["ValidationFindingsJson"] = JsonSerializer.Serialize(s.ValidationFindings),
|
||||
["SourceFireStatsJson"] = s.SourceFireStats == null ? string.Empty : JsonSerializer.Serialize(s.SourceFireStats),
|
||||
["ReviewedBy"] = s.ReviewedBy ?? string.Empty,
|
||||
["ReviewedAt"] = s.ReviewedAt,
|
||||
["ReviewComment"] = s.ReviewComment ?? string.Empty,
|
||||
["WillBeAdapted"] = s.WillBeAdapted,
|
||||
["PublishedRuleId"] = s.PublishedRuleId ?? string.Empty,
|
||||
["DerivedFromTemplateRuleId"] = s.DerivedFromTemplateRuleId ?? string.Empty,
|
||||
};
|
||||
|
||||
internal static RuleSubmission MapSubmission(TableEntity e) => new()
|
||||
{
|
||||
SubmissionId = e.GetString("SubmissionId") ?? string.Empty,
|
||||
BatchId = e.GetString("BatchId") ?? string.Empty,
|
||||
TenantId = e.GetString("TenantId") ?? string.Empty,
|
||||
RuleKind = e.GetString("RuleKind") ?? string.Empty,
|
||||
SourceRuleId = e.GetString("SourceRuleId") ?? string.Empty,
|
||||
Title = e.GetString("Title") ?? string.Empty,
|
||||
Category = e.GetString("Category") ?? string.Empty,
|
||||
RuleJson = e.GetString("RuleJson") ?? string.Empty,
|
||||
Comment = NullIfEmpty(e.GetString("Comment")),
|
||||
SubmittedBy = e.GetString("SubmittedBy") ?? string.Empty,
|
||||
SubmittedByName = e.GetString("SubmittedByName") ?? string.Empty,
|
||||
AttributionMode = e.GetString("AttributionMode") ?? RuleAttributionModes.Anonymous,
|
||||
AttributionName = e.GetString("AttributionName") ?? RuleAttributionModes.AnonymousAuthor,
|
||||
SubmittedAt = e.GetDateTimeOffset("SubmittedAt")?.UtcDateTime ?? DateTime.MinValue,
|
||||
Status = e.GetString("Status") ?? RuleSubmissionStatuses.Pending,
|
||||
ValidationFindings = DeserializeOrDefault<List<RuleSubmissionFinding>>(e.GetString("ValidationFindingsJson")) ?? new List<RuleSubmissionFinding>(),
|
||||
SourceFireStats = DeserializeOrDefault<RuleSubmissionFireStats>(e.GetString("SourceFireStatsJson")),
|
||||
ReviewedBy = NullIfEmpty(e.GetString("ReviewedBy")),
|
||||
ReviewedAt = e.GetDateTimeOffset("ReviewedAt")?.UtcDateTime,
|
||||
ReviewComment = NullIfEmpty(e.GetString("ReviewComment")),
|
||||
WillBeAdapted = e.GetBoolean("WillBeAdapted") ?? false,
|
||||
PublishedRuleId = NullIfEmpty(e.GetString("PublishedRuleId")),
|
||||
DerivedFromTemplateRuleId = NullIfEmpty(e.GetString("DerivedFromTemplateRuleId")),
|
||||
};
|
||||
|
||||
private static T? DeserializeOrDefault<T>(string? json) where T : class
|
||||
{
|
||||
if (string.IsNullOrEmpty(json)) return null;
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<T>(json!);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// A corrupt column must not hide the submission itself.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? NullIfEmpty(string? value) => string.IsNullOrEmpty(value) ? null : value;
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,10 @@ namespace AutopilotMonitor.Functions.Functions.Rules
|
||||
return await req.BadRequestAsync("Invalid rule data");
|
||||
}
|
||||
|
||||
// Author is stamped from the creator's token, never from the payload
|
||||
// (anti-spoof), and stays immutable through every later update.
|
||||
rule.Author = TenantHelper.GetUserDisplayName(req) ?? "Autopilot Monitor";
|
||||
|
||||
try
|
||||
{
|
||||
var success = await _ruleService.CreateRuleAsync(tenantId, rule);
|
||||
@@ -88,6 +92,11 @@ namespace AutopilotMonitor.Functions.Functions.Rules
|
||||
|
||||
rule.RuleId = ruleId;
|
||||
|
||||
// Same anti-spoof stamp as CreateRule: on a true update the service replaces
|
||||
// this with the original author (immutable attribution), but a full-payload PUT
|
||||
// that upserts a rule with no existing row must not store the payload's author.
|
||||
rule.Author = TenantHelper.GetUserDisplayName(req) ?? "Autopilot Monitor";
|
||||
|
||||
try
|
||||
{
|
||||
var success = await _ruleService.UpdateRuleAsync(tenantId, rule);
|
||||
@@ -124,7 +133,8 @@ namespace AutopilotMonitor.Functions.Functions.Rules
|
||||
|
||||
try
|
||||
{
|
||||
var newRule = await _ruleService.CreateFromTemplateAsync(tenantId, ruleId, variables);
|
||||
var author = TenantHelper.GetUserDisplayName(req) ?? "Autopilot Monitor";
|
||||
var newRule = await _ruleService.CreateFromTemplateAsync(tenantId, ruleId, variables, author);
|
||||
|
||||
var response = req.CreateResponse(HttpStatusCode.Created);
|
||||
await response.WriteAsJsonAsync(new CreateAnalyzeRuleFromTemplateResponse { Success = true, Rule = newRule, Message = "Custom rule created from template" });
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>One submission with the frozen rule, live fire stats, the suggested id and the repo file.</summary>
|
||||
public class GetGlobalRuleSubmissionFunction
|
||||
{
|
||||
private readonly ILogger<GetGlobalRuleSubmissionFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
|
||||
public GetGlobalRuleSubmissionFunction(ILogger<GetGlobalRuleSubmissionFunction> logger, RuleSubmissionService service)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
[Function("GetGlobalRuleSubmission")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "global/rule-submissions/{submissionId}")] HttpRequestData req,
|
||||
string submissionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + GlobalReadOrAdmin authorization enforced by PolicyEnforcementMiddleware
|
||||
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
|
||||
|
||||
var detail = await _service.GetDetailAsync(submissionId);
|
||||
if (detail == null) return await req.NotFoundAsync("Submission not found.");
|
||||
return await req.OkAsync(detail);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "GetGlobalRuleSubmission");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
using System.Web;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Pagination;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>Operator list across tenants: <c>?tenantId=</c> and <c>?status=</c> are server-side filters, paging as for session reports.</summary>
|
||||
public class GetGlobalRuleSubmissionsFunction
|
||||
{
|
||||
private readonly ILogger<GetGlobalRuleSubmissionsFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
|
||||
public GetGlobalRuleSubmissionsFunction(ILogger<GetGlobalRuleSubmissionsFunction> logger, RuleSubmissionService service)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
[Function("GetGlobalRuleSubmissions")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "global/rule-submissions")] HttpRequestData req)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + GlobalReadOrAdmin authorization enforced by PolicyEnforcementMiddleware
|
||||
var callerTenantId = TenantHelper.GetTenantId(req);
|
||||
|
||||
var query = HttpUtility.ParseQueryString(req.Url.Query ?? string.Empty);
|
||||
var parsed = RuleSubmissionsPagination.ParseQuery(query);
|
||||
if (parsed.Error != null) return await req.BadRequestAsync(parsed.Error);
|
||||
|
||||
var pageSize = parsed.PageSize ?? RuleSubmissionsPagination.DefaultPageSize;
|
||||
|
||||
string? azureToken = null;
|
||||
if (parsed.Continuation != null)
|
||||
{
|
||||
if (!RuleSubmissionsPagination.TryAcceptContinuation(
|
||||
parsed.Continuation, callerTenantId, parsed.FilterTenantId, parsed.FilterStatus,
|
||||
out azureToken, out var rejectReason))
|
||||
{
|
||||
_logger.LogWarning("GetGlobalRuleSubmissions: continuation rejected ({Reason})", rejectReason);
|
||||
return await req.BadRequestAsync($"Invalid continuation token ({rejectReason}). Restart pagination from the first page.");
|
||||
}
|
||||
}
|
||||
|
||||
var page = await _service.GetPageAsync(parsed.FilterTenantId, parsed.FilterStatus, pageSize, azureToken);
|
||||
var items = await _service.ToItemsAsync(page.Items);
|
||||
|
||||
string? nextLink = null;
|
||||
if (!string.IsNullOrEmpty(page.NextRawToken))
|
||||
{
|
||||
var fp = RuleSubmissionsPagination.Fingerprint(callerTenantId, parsed.FilterTenantId, parsed.FilterStatus);
|
||||
var wireToken = ContinuationToken.Encode(page.NextRawToken!, callerTenantId, fp);
|
||||
nextLink = RuleSubmissionsPagination.BuildNextLink(pageSize, wireToken, parsed.FilterTenantId, parsed.FilterStatus);
|
||||
}
|
||||
|
||||
return await req.OkAsync(new RuleSubmissionListResponse
|
||||
{
|
||||
Success = true,
|
||||
Count = items.Count,
|
||||
Submissions = items,
|
||||
NextLink = nextLink,
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "GetGlobalRuleSubmissions");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>The submitting tenant's own submissions, newest first, with the effective status.</summary>
|
||||
public class GetRuleSubmissionsFunction
|
||||
{
|
||||
private readonly ILogger<GetRuleSubmissionsFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
|
||||
public GetRuleSubmissionsFunction(ILogger<GetRuleSubmissionsFunction> logger, RuleSubmissionService service)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
[Function("GetRuleSubmissions")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "rules/submissions")] HttpRequestData req)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + TenantAdminOrGA authorization enforced by PolicyEnforcementMiddleware.
|
||||
// Always the JWT tenant — a GA reads foreign tenants through global/rule-submissions?tenantId=.
|
||||
var tenantId = req.GetRequestContext().TenantId;
|
||||
var rows = await _service.GetForTenantAsync(tenantId);
|
||||
var items = await _service.ToItemsAsync(rows);
|
||||
return await req.OkAsync(new RuleSubmissionListResponse { Success = true, Count = items.Count, Submissions = items });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "GetRuleSubmissions");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>The reviewer's decision (portal or MCP). The submitter is told through a tenant notification.</summary>
|
||||
public class ReviewRuleSubmissionFunction
|
||||
{
|
||||
private readonly ILogger<ReviewRuleSubmissionFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
private readonly TenantNotificationService _tenantNotifications;
|
||||
|
||||
public ReviewRuleSubmissionFunction(
|
||||
ILogger<ReviewRuleSubmissionFunction> logger,
|
||||
RuleSubmissionService service,
|
||||
TenantNotificationService tenantNotifications)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
_tenantNotifications = tenantNotifications;
|
||||
}
|
||||
|
||||
[Function("ReviewRuleSubmission")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "global/rule-submissions/{submissionId}")] HttpRequestData req,
|
||||
string submissionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + GlobalAdminOnly authorization enforced by PolicyEnforcementMiddleware
|
||||
var reviewer = TenantHelper.GetUserIdentifier(req);
|
||||
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
|
||||
|
||||
var read = await req.ReadAsync<ReviewRuleSubmissionRequest>();
|
||||
if (read.Error != null) return read.Error;
|
||||
|
||||
RuleSubmission updated;
|
||||
try
|
||||
{
|
||||
updated = await _service.ReviewAsync(submissionId, read.Value!, reviewer);
|
||||
}
|
||||
catch (KeyNotFoundException ex)
|
||||
{
|
||||
return await req.NotFoundAsync(ex.Message);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return await req.BadRequestAsync(ex.Message);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return await req.ConflictAsync(ex.Message);
|
||||
}
|
||||
|
||||
var approved = updated.Status == RuleSubmissionStatuses.Approved;
|
||||
var title = approved
|
||||
? $"Rule submission approved: {updated.SourceRuleId}"
|
||||
: $"Rule submission declined: {updated.SourceRuleId}";
|
||||
var message = approved
|
||||
? (updated.WillBeAdapted
|
||||
? $"\"{updated.Title}\" will be published as {updated.PublishedRuleId} after a small adaptation for the community."
|
||||
: $"\"{updated.Title}\" will be published as {updated.PublishedRuleId}.")
|
||||
: $"\"{updated.Title}\" was not accepted for the community pool.";
|
||||
if (!string.IsNullOrEmpty(updated.ReviewComment)) message += $" Reviewer: {updated.ReviewComment}";
|
||||
|
||||
// Best effort; the submissions list carries the same facts.
|
||||
_ = _tenantNotifications.CreateNotificationAsync(
|
||||
updated.TenantId, "rule_submission_decided", title, message,
|
||||
href: updated.RuleKind == RuleSubmissionKinds.Analyze ? "/analyze-rules" : "/gather-rules");
|
||||
|
||||
_logger.LogInformation("Rule submission {SubmissionId} {Status} by {Reviewer} (published id {PublishedRuleId})",
|
||||
submissionId, updated.Status, reviewer, updated.PublishedRuleId ?? "-");
|
||||
|
||||
var item = (await _service.ToItemsAsync(new[] { updated }))[0];
|
||||
return await req.OkAsync(new ReviewRuleSubmissionResponse
|
||||
{
|
||||
Success = true,
|
||||
Message = approved ? "Submission approved." : "Submission declined.",
|
||||
Submission = item,
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "ReviewRuleSubmission");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>
|
||||
/// A tenant admin submits one or more of the tenant's custom rules for the community pool.
|
||||
/// The body carries only rule references; the service freezes the rules server-side.
|
||||
/// </summary>
|
||||
public class SubmitRuleSubmissionsFunction
|
||||
{
|
||||
private readonly ILogger<SubmitRuleSubmissionsFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
private readonly IMaintenanceRepository _maintenanceRepo;
|
||||
private readonly TelegramNotificationService _telegram;
|
||||
private readonly GlobalNotificationService _globalNotifications;
|
||||
|
||||
public SubmitRuleSubmissionsFunction(
|
||||
ILogger<SubmitRuleSubmissionsFunction> logger,
|
||||
RuleSubmissionService service,
|
||||
IMaintenanceRepository maintenanceRepo,
|
||||
TelegramNotificationService telegram,
|
||||
GlobalNotificationService globalNotifications)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
_maintenanceRepo = maintenanceRepo;
|
||||
_telegram = telegram;
|
||||
_globalNotifications = globalNotifications;
|
||||
}
|
||||
|
||||
[Function("SubmitRuleSubmissions")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "rules/submissions")] HttpRequestData req)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + TenantAdminOrGA authorization enforced by PolicyEnforcementMiddleware
|
||||
var requestCtx = req.GetRequestContext();
|
||||
var tenantId = requestCtx.TenantId;
|
||||
var userIdentifier = requestCtx.UserPrincipalName;
|
||||
|
||||
var read = await req.ReadAsync<SubmitRuleSubmissionsRequest>(262_144);
|
||||
if (read.Error != null) return read.Error;
|
||||
var request = read.Value!;
|
||||
|
||||
// Same tenant-tamper gate as the session report: non-GAs submit for their JWT
|
||||
// tenant only; a GA may submit on behalf of a foreign tenant and must name it.
|
||||
if (!requestCtx.IsGlobalAdmin)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(request.TenantId)
|
||||
&& !string.Equals(request.TenantId, tenantId, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"SubmitRuleSubmissions: BLOCKED cross-tenant body for non-GA user={User} jwtTenant={JwtTenant} bodyTenant={BodyTenant}",
|
||||
userIdentifier, tenantId, request.TenantId);
|
||||
return await req.ForbiddenAsync("Body tenantId must match your authenticated tenant.");
|
||||
}
|
||||
request.TenantId = tenantId;
|
||||
}
|
||||
else if (string.IsNullOrEmpty(request.TenantId))
|
||||
{
|
||||
return await req.BadRequestAsync("tenantId is required in body for Global Admin submissions.");
|
||||
}
|
||||
|
||||
if (!SecurityValidator.IsValidGuid(request.TenantId))
|
||||
return await req.BadRequestAsync("Invalid tenantId.");
|
||||
|
||||
var displayName = TenantHelper.GetUserDisplayName(req) ?? userIdentifier;
|
||||
List<RuleSubmission> created;
|
||||
try
|
||||
{
|
||||
created = await _service.SubmitAsync(request.TenantId, request, userIdentifier, displayName);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return await req.BadRequestAsync(ex.Message);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return await req.ConflictAsync(ex.Message);
|
||||
}
|
||||
|
||||
if (!requestCtx.IsGlobalAdmin)
|
||||
{
|
||||
foreach (var s in created)
|
||||
{
|
||||
await _maintenanceRepo.LogAuditEntryAsync(
|
||||
request.TenantId, "CREATE", "RuleSubmission", s.SubmissionId, userIdentifier,
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
{ "Action", "SubmitRuleSubmission" },
|
||||
{ "RuleKind", s.RuleKind },
|
||||
{ "RuleId", s.SourceRuleId },
|
||||
{ "BatchId", s.BatchId },
|
||||
{ "AttributionMode", s.AttributionMode },
|
||||
{ "HasComment", (s.Comment != null).ToString() },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Operator notifications — best effort, one per rule so every id has its own deep link.
|
||||
foreach (var s in created)
|
||||
{
|
||||
_ = _telegram.SendRuleSubmissionAsync(s.SubmissionId, request.TenantId, userIdentifier, s.RuleKind, s.SourceRuleId, s.Title, s.Comment ?? string.Empty);
|
||||
_ = _globalNotifications.CreateNotificationAsync(
|
||||
"rule_submission",
|
||||
$"Rule submission {s.SubmissionId}",
|
||||
$"{s.SourceRuleId} \"{s.Title}\" ({s.RuleKind}) — {userIdentifier} (Tenant: {request.TenantId})",
|
||||
href: $"/admin/reports/rule-submissions?submissionId={Uri.EscapeDataString(s.SubmissionId)}");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Rule submissions stored: {Count} rule(s), batch {BatchId}, tenant {TenantId}, by {User}",
|
||||
created.Count, created[0].BatchId, request.TenantId, userIdentifier);
|
||||
|
||||
var items = await _service.ToItemsAsync(created);
|
||||
return await req.OkAsync(new SubmitRuleSubmissionsResponse
|
||||
{
|
||||
Success = true,
|
||||
Message = created.Count == 1 ? "Rule submitted for review." : $"{created.Count} rules submitted for review.",
|
||||
BatchId = created[0].BatchId,
|
||||
Submissions = items,
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "SubmitRuleSubmissions");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>The submitter takes a pending submission back. The row stays (status withdrawn) for the audit trail.</summary>
|
||||
public class WithdrawRuleSubmissionFunction
|
||||
{
|
||||
private readonly ILogger<WithdrawRuleSubmissionFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
|
||||
public WithdrawRuleSubmissionFunction(ILogger<WithdrawRuleSubmissionFunction> logger, RuleSubmissionService service)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
[Function("WithdrawRuleSubmission")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "rules/submissions/{submissionId}")] HttpRequestData req,
|
||||
string submissionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + TenantAdminOrGA authorization enforced by PolicyEnforcementMiddleware
|
||||
var requestCtx = req.GetRequestContext();
|
||||
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
|
||||
|
||||
bool withdrawn;
|
||||
try
|
||||
{
|
||||
// A foreign tenant's submission answers 404 for a non-GA — the row's existence is not theirs to learn.
|
||||
withdrawn = await _service.WithdrawAsync(requestCtx.TenantId, submissionId, crossTenantAllowed: requestCtx.IsGlobalAdmin);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return await req.ConflictAsync(ex.Message);
|
||||
}
|
||||
|
||||
if (!withdrawn) return await req.NotFoundAsync("Submission not found.");
|
||||
|
||||
_logger.LogInformation("Rule submission {SubmissionId} withdrawn by {User}", submissionId, requestCtx.UserPrincipalName);
|
||||
return await req.OkAsync(new SuccessMessageResponse { Success = true, Message = "Submission withdrawn." });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "WithdrawRuleSubmission");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Pagination
|
||||
{
|
||||
/// <summary>
|
||||
/// Pure helpers for the <c>GET /api/global/rule-submissions</c> pagination surface — the
|
||||
/// SessionReportsPagination contract with a second server-side filter (<c>status</c>). Both
|
||||
/// filters are bound into the continuation fingerprint so a token issued for one view cannot
|
||||
/// resume another.
|
||||
/// </summary>
|
||||
public static class RuleSubmissionsPagination
|
||||
{
|
||||
public const int DefaultPageSize = 200;
|
||||
|
||||
public static string Fingerprint(string callerTenantId, string? filterTenantId, string? filterStatus) =>
|
||||
ContinuationToken.ComputeFingerprint(new[]
|
||||
{
|
||||
new KeyValuePair<string, string?>("scope", "rule-submissions"),
|
||||
new KeyValuePair<string, string?>("tenantId", callerTenantId),
|
||||
new KeyValuePair<string, string?>("filterTenantId", filterTenantId),
|
||||
new KeyValuePair<string, string?>("filterStatus", filterStatus),
|
||||
});
|
||||
|
||||
public sealed class Parsed
|
||||
{
|
||||
public string? FilterTenantId { get; init; }
|
||||
public string? FilterStatus { get; init; }
|
||||
public int? PageSize { get; init; }
|
||||
public string? Continuation { get; init; }
|
||||
public string? Error { get; init; }
|
||||
}
|
||||
|
||||
public static Parsed ParseQuery(NameValueCollection? query)
|
||||
{
|
||||
var filterTenantIdRaw = query?["tenantId"];
|
||||
var filterStatusRaw = query?["status"];
|
||||
var pageSizeRaw = query?["pageSize"];
|
||||
var continuationRaw = query?["continuation"];
|
||||
|
||||
if (!QueryParams.TryPageSize(pageSizeRaw, out var pageSize, out var pageSizeError))
|
||||
return new Parsed { Error = pageSizeError };
|
||||
|
||||
if (!string.IsNullOrEmpty(filterStatusRaw)
|
||||
&& System.Array.IndexOf(Shared.Models.RuleSubmissionStatuses.Stored, filterStatusRaw) < 0)
|
||||
{
|
||||
return new Parsed { Error = $"status must be one of: {string.Join(", ", Shared.Models.RuleSubmissionStatuses.Stored)}" };
|
||||
}
|
||||
|
||||
var continuation = pageSize.HasValue && !string.IsNullOrEmpty(continuationRaw)
|
||||
? continuationRaw
|
||||
: null;
|
||||
|
||||
return new Parsed
|
||||
{
|
||||
FilterTenantId = string.IsNullOrEmpty(filterTenantIdRaw) ? null : filterTenantIdRaw,
|
||||
FilterStatus = string.IsNullOrEmpty(filterStatusRaw) ? null : filterStatusRaw,
|
||||
PageSize = pageSize,
|
||||
Continuation = continuation,
|
||||
};
|
||||
}
|
||||
|
||||
public static bool TryAcceptContinuation(
|
||||
string raw,
|
||||
string callerTenantId,
|
||||
string? filterTenantId,
|
||||
string? filterStatus,
|
||||
out string azureToken,
|
||||
out string? rejectReason)
|
||||
{
|
||||
var fp = Fingerprint(callerTenantId, filterTenantId, filterStatus);
|
||||
return ContinuationToken.TryDecode(raw, callerTenantId, fp, out azureToken, out rejectReason);
|
||||
}
|
||||
|
||||
public static string BuildNextLink(int pageSize, string wireContinuation, string? filterTenantId, string? filterStatus)
|
||||
{
|
||||
var sb = new StringBuilder("/api/global/rule-submissions");
|
||||
sb.Append('?');
|
||||
sb.Append("pageSize=").Append(pageSize.ToString(CultureInfo.InvariantCulture));
|
||||
sb.Append("&continuation=").Append(System.Uri.EscapeDataString(wireContinuation));
|
||||
if (!string.IsNullOrEmpty(filterTenantId))
|
||||
sb.Append("&tenantId=").Append(System.Uri.EscapeDataString(filterTenantId!));
|
||||
if (!string.IsNullOrEmpty(filterStatus))
|
||||
sb.Append("&status=").Append(System.Uri.EscapeDataString(filterStatus!));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,6 +318,7 @@ builder.Services.AddSingleton<AutopilotMonitor.Functions.Services.Diagnostics.Di
|
||||
builder.Services.AddSingleton<AutopilotMonitor.Functions.Services.Diagnostics.DiagnosticsBlobCascadeDeleter>();
|
||||
builder.Services.AddSingleton<AutopilotMonitor.Functions.Services.Diagnostics.SessionReportDiagnosticsArchiveCopier>();
|
||||
builder.Services.AddSingleton<SessionReportService>();
|
||||
builder.Services.AddSingleton<RuleSubmissionService>();
|
||||
builder.Services.AddSingleton<BootstrapSessionService>();
|
||||
|
||||
// Queue producers + handlers. Consumers are [QueueTrigger] functions under Functions/Queue/
|
||||
|
||||
@@ -354,6 +354,11 @@ public static class EndpointAccessPolicyCatalog
|
||||
// troubleshooting action, not a config change — a support-driven Operator may use it.
|
||||
// Viewer and the read-only Global Reader stay excluded (the tier admits no Viewer/Reader).
|
||||
new("POST", "diagnostics/files", EndpointPolicy.TenantAdminOrOperator),
|
||||
// Community rule submissions: the tenant admin submits references to own custom rules
|
||||
// (frozen server-side), lists and withdraws them for the JWT tenant only.
|
||||
new("POST", "rules/submissions", EndpointPolicy.TenantAdminOrGA),
|
||||
new("GET", "rules/submissions", EndpointPolicy.TenantAdminOrGA),
|
||||
new("DELETE", "rules/submissions/{submissionId}", EndpointPolicy.TenantAdminOrGA),
|
||||
new("DELETE", "sessions/{sessionId}", EndpointPolicy.TenantAdminOrGA, TenantScoping.QueryParam),
|
||||
new("GET", "tenants/{tenantId}/admins", EndpointPolicy.TenantAdminOrGA, TenantScoping.RouteParam),
|
||||
new("POST", "tenants/{tenantId}/admins", EndpointPolicy.TenantAdminOrGA, TenantScoping.RouteParam),
|
||||
@@ -513,6 +518,10 @@ public static class EndpointAccessPolicyCatalog
|
||||
new("POST", "global/session-reports/download-ticket", EndpointPolicy.GlobalReadOrAdmin),
|
||||
new("GET", "global/session-reports/download-url", EndpointPolicy.GlobalReadOrAdmin),
|
||||
new("PATCH", "global/session-reports/{reportId}/note", EndpointPolicy.GlobalAdminOnly),
|
||||
// Community rule submissions, operator side: cross-tenant read (Global Reader included), decision GA-only.
|
||||
new("GET", "global/rule-submissions", EndpointPolicy.GlobalReadOrAdmin, TenantScoping.QueryParam),
|
||||
new("GET", "global/rule-submissions/{submissionId}", EndpointPolicy.GlobalReadOrAdmin),
|
||||
new("PATCH", "global/rule-submissions/{submissionId}", EndpointPolicy.GlobalAdminOnly),
|
||||
// Flywheel evaluation stream: all annotation lanes across tenants (verdict/rule filters).
|
||||
new("GET", "global/session-annotations", EndpointPolicy.GlobalReadOrAdmin, TenantScoping.QueryParam),
|
||||
new("GET", "global/rules/gather", EndpointPolicy.GlobalReadOrAdmin, TenantScoping.QueryParam),
|
||||
|
||||
@@ -322,6 +322,16 @@ namespace AutopilotMonitor.Functions.Services
|
||||
rule.Notify = null;
|
||||
}
|
||||
|
||||
var existing = (await _ruleRepo.GetAnalyzeRulesAsync(tenantId))
|
||||
.FirstOrDefault(r => r.RuleId == rule.RuleId && !r.IsBuiltIn && !r.IsCommunity);
|
||||
if (existing != null)
|
||||
{
|
||||
rule.CreatedAt = existing.CreatedAt;
|
||||
// Author is stamped from the creator's token at create time and is
|
||||
// immutable afterwards — updates (incl. cross-tenant GA edits) keep it.
|
||||
rule.Author = existing.Author;
|
||||
}
|
||||
|
||||
rule.UpdatedAt = DateTime.UtcNow;
|
||||
return await _ruleRepo.StoreAnalyzeRuleAsync(rule, tenantId);
|
||||
}
|
||||
@@ -333,7 +343,8 @@ namespace AutopilotMonitor.Functions.Services
|
||||
public async Task<AnalyzeRule> CreateFromTemplateAsync(
|
||||
string tenantId,
|
||||
string templateRuleId,
|
||||
Dictionary<string, string> variableValues)
|
||||
Dictionary<string, string> variableValues,
|
||||
string? author = null)
|
||||
{
|
||||
var allRules = await GetAllRulesForTenantAsync(tenantId);
|
||||
var template = allRules.FirstOrDefault(r => r.RuleId == templateRuleId);
|
||||
@@ -370,6 +381,8 @@ namespace AutopilotMonitor.Functions.Services
|
||||
customRule.RuleId = $"{templateRuleId}-CUSTOM";
|
||||
customRule.IsBuiltIn = false;
|
||||
customRule.IsCommunity = false;
|
||||
// The copy is the tenant's rule, not the template author's.
|
||||
customRule.Author = string.IsNullOrWhiteSpace(author) ? "Autopilot Monitor" : author!;
|
||||
customRule.Enabled = true;
|
||||
customRule.DerivedFromTemplateRuleId = templateRuleId;
|
||||
customRule.TemplateVariables = new List<TemplateVariable>();
|
||||
|
||||
+1
@@ -141,6 +141,7 @@ namespace AutopilotMonitor.Functions.Services.Offboarding
|
||||
{
|
||||
(Constants.TableNames.BootstrapSessions, "CodeLookup"),
|
||||
(Constants.TableNames.SessionReports, "reports"),
|
||||
(Constants.TableNames.RuleSubmissions, "submissions"),
|
||||
};
|
||||
|
||||
// Plan §6.3.2 — Variant C (TenantId property only).
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Functions.Rules;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Community rule submissions: freezes a tenant's custom rule at submit time, records the
|
||||
/// pre-flight findings and fire telemetry, and carries the review through to the repo file.
|
||||
/// Publishing itself is a repository commit plus reseed — this service never writes the
|
||||
/// global rule partition; <c>published</c> is derived from the catalog on every read.
|
||||
/// </summary>
|
||||
public class RuleSubmissionService
|
||||
{
|
||||
public const int MaxRuleJsonLength = 32_000;
|
||||
public const int MaxSubmissionsPerTenantPerDay = 10;
|
||||
public const int FireStatsDays = 30;
|
||||
|
||||
/// <summary>The credit text is published in the repo, so it is a name and nothing else.</summary>
|
||||
private static readonly Regex AttributionNameShape = new(@"^[\p{L}\p{N} .,'&()\-]{1,64}$", RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>Rule fields that belong to the server or the tenant, never to a frozen or published rule.</summary>
|
||||
private static readonly string[] StrippedFields =
|
||||
{
|
||||
"isBuiltIn", "provenance", "createdAt", "updatedAt",
|
||||
"markSessionAsFailed", "notifyDefault", "notify", "notifyChannelIds",
|
||||
};
|
||||
|
||||
private static readonly JsonSerializerOptions RepoFileOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
|
||||
// The dominant convention per kind in rules/ (ANALYZE-APP vs GATHER-APPS …); an unmapped
|
||||
// category falls back to its upper-cased name, which the reviewer can overrule.
|
||||
private static readonly Dictionary<string, string> AnalyzeCategoryCodes = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["apps"] = "APP", ["device"] = "DEV", ["enrollment"] = "ENRL", ["esp"] = "ESP",
|
||||
["identity"] = "ID", ["network"] = "NET", ["security"] = "SEC",
|
||||
};
|
||||
private static readonly Dictionary<string, string> GatherCategoryCodes = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["apps"] = "APPS", ["device"] = "DEVICE", ["enrollment"] = "ENROLL", ["esp"] = "ESP",
|
||||
["identity"] = "ID", ["network"] = "NET",
|
||||
};
|
||||
|
||||
private readonly IRuleSubmissionRepository _submissions;
|
||||
private readonly IRuleRepository _ruleRepo;
|
||||
private readonly IMetricsRepository _metricsRepo;
|
||||
private readonly TenantConfigurationService _configService;
|
||||
private readonly ILogger<RuleSubmissionService> _logger;
|
||||
|
||||
public RuleSubmissionService(
|
||||
IRuleSubmissionRepository submissions,
|
||||
IRuleRepository ruleRepo,
|
||||
IMetricsRepository metricsRepo,
|
||||
TenantConfigurationService configService,
|
||||
ILogger<RuleSubmissionService> logger)
|
||||
{
|
||||
_submissions = submissions;
|
||||
_ruleRepo = ruleRepo;
|
||||
_metricsRepo = metricsRepo;
|
||||
_configService = configService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Freezes and stores every referenced rule. All-or-nothing: a pre-flight error on any
|
||||
/// item rejects the whole batch (<see cref="ArgumentException"/>), so a tenant never ends
|
||||
/// up with half a submission. <see cref="InvalidOperationException"/> = conflict (open
|
||||
/// duplicate, daily cap).
|
||||
/// </summary>
|
||||
public async Task<List<RuleSubmission>> SubmitAsync(
|
||||
string tenantId, SubmitRuleSubmissionsRequest request, string submittedBy, string submittedByName)
|
||||
{
|
||||
if (request.Items == null || request.Items.Count == 0)
|
||||
throw new ArgumentException("At least one rule is required.");
|
||||
if (request.Items.Count > SubmitRuleSubmissionsRequest.MaxItems)
|
||||
throw new ArgumentException($"At most {SubmitRuleSubmissionsRequest.MaxItems} rules per submission.");
|
||||
if (request.Comment != null && request.Comment.Length > SubmitRuleSubmissionsRequest.MaxCommentLength)
|
||||
throw new ArgumentException($"Comment exceeds {SubmitRuleSubmissionsRequest.MaxCommentLength} characters.");
|
||||
|
||||
var attributionName = await ResolveAttributionNameAsync(tenantId, request.AttributionMode, request.AttributionName);
|
||||
|
||||
var distinct = request.Items
|
||||
.Select(i => (Kind: i.Kind?.Trim().ToLowerInvariant() ?? string.Empty, RuleId: i.RuleId?.Trim() ?? string.Empty))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
foreach (var (kind, ruleId) in distinct)
|
||||
{
|
||||
if (!RuleSubmissionKinds.IsKnown(kind))
|
||||
throw new ArgumentException($"Unknown rule kind '{kind}'.");
|
||||
if (string.IsNullOrEmpty(ruleId))
|
||||
throw new ArgumentException("ruleId is required for every item.");
|
||||
}
|
||||
|
||||
var existing = await _submissions.GetForTenantAsync(tenantId);
|
||||
var since = DateTime.UtcNow.AddDays(-1);
|
||||
if (existing.Count(s => s.SubmittedAt >= since) + distinct.Count > MaxSubmissionsPerTenantPerDay)
|
||||
throw new InvalidOperationException($"At most {MaxSubmissionsPerTenantPerDay} rule submissions per tenant and day.");
|
||||
|
||||
var analyzeRules = distinct.Any(d => d.Kind == RuleSubmissionKinds.Analyze)
|
||||
? await _ruleRepo.GetAnalyzeRulesAsync(tenantId) : new List<AnalyzeRule>();
|
||||
var gatherRules = distinct.Any(d => d.Kind == RuleSubmissionKinds.Gather)
|
||||
? await _ruleRepo.GetGatherRulesAsync(tenantId) : new List<GatherRule>();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var batchId = NewId();
|
||||
var prepared = new List<RuleSubmission>(distinct.Count);
|
||||
var errors = new List<string>();
|
||||
|
||||
foreach (var (kind, ruleId) in distinct)
|
||||
{
|
||||
if (existing.Any(s => s.Status == RuleSubmissionStatuses.Pending
|
||||
&& s.RuleKind == kind
|
||||
&& string.Equals(s.SourceRuleId, ruleId, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException($"Rule '{ruleId}' already has a pending submission.");
|
||||
|
||||
var submission = new RuleSubmission
|
||||
{
|
||||
SubmissionId = NewId(),
|
||||
BatchId = batchId,
|
||||
TenantId = tenantId,
|
||||
RuleKind = kind,
|
||||
SourceRuleId = ruleId,
|
||||
Comment = string.IsNullOrWhiteSpace(request.Comment) ? null : request.Comment!.Trim(),
|
||||
SubmittedBy = submittedBy,
|
||||
SubmittedByName = submittedByName,
|
||||
AttributionMode = request.AttributionMode,
|
||||
AttributionName = attributionName,
|
||||
SubmittedAt = now,
|
||||
Status = RuleSubmissionStatuses.Pending,
|
||||
};
|
||||
|
||||
var findings = new List<RuleSubmissionFinding>();
|
||||
if (kind == RuleSubmissionKinds.Analyze)
|
||||
{
|
||||
var rule = analyzeRules.FirstOrDefault(r => string.Equals(r.RuleId, ruleId, StringComparison.OrdinalIgnoreCase)
|
||||
&& !r.IsBuiltIn && !r.IsCommunity);
|
||||
if (rule == null) { errors.Add($"{ruleId}: not a custom analyze rule of this tenant."); continue; }
|
||||
|
||||
submission.Title = rule.Title ?? string.Empty;
|
||||
submission.Category = rule.Category ?? string.Empty;
|
||||
submission.DerivedFromTemplateRuleId = rule.DerivedFromTemplateRuleId;
|
||||
submission.RuleJson = FreezeRule(rule);
|
||||
foreach (var e in DryRunAnalyzeRuleFunction.ValidateDraftRule(rule))
|
||||
findings.Add(new RuleSubmissionFinding { Level = "error", Message = e });
|
||||
if (!string.IsNullOrEmpty(rule.DerivedFromTemplateRuleId))
|
||||
findings.Add(new RuleSubmissionFinding { Level = "info", Message = $"Derived from template {rule.DerivedFromTemplateRuleId} — usually a filled-in copy rather than a new detection." });
|
||||
}
|
||||
else
|
||||
{
|
||||
var rule = gatherRules.FirstOrDefault(r => string.Equals(r.RuleId, ruleId, StringComparison.OrdinalIgnoreCase)
|
||||
&& !r.IsBuiltIn && !r.IsCommunity);
|
||||
if (rule == null) { errors.Add($"{ruleId}: not a custom gather rule of this tenant."); continue; }
|
||||
|
||||
submission.Title = rule.Title ?? string.Empty;
|
||||
submission.Category = rule.Category ?? string.Empty;
|
||||
submission.RuleJson = FreezeRule(rule);
|
||||
if (string.IsNullOrWhiteSpace(rule.CollectorType)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "collectorType is required" });
|
||||
if (string.IsNullOrWhiteSpace(rule.Target)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "target is required" });
|
||||
if (string.IsNullOrWhiteSpace(rule.Trigger)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "trigger is required" });
|
||||
if (string.IsNullOrWhiteSpace(rule.OutputEventType)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "outputEventType is required" });
|
||||
var scopeError = GatherRulesFunction.ValidateScopeAndEmitMode(rule);
|
||||
if (scopeError != null) findings.Add(new RuleSubmissionFinding { Level = "error", Message = scopeError });
|
||||
findings.Add(new RuleSubmissionFinding { Level = "info", Message = "Collector guardrails are enforced on the device; the full allowlist check runs in the MCP validate_rule tool." });
|
||||
}
|
||||
|
||||
if (submission.RuleJson.Length > MaxRuleJsonLength)
|
||||
findings.Add(new RuleSubmissionFinding { Level = "error", Message = $"rule document exceeds {MaxRuleJsonLength} characters" });
|
||||
|
||||
var itemErrors = findings.Where(f => f.Level == "error").Select(f => $"{ruleId}: {f.Message}").ToList();
|
||||
if (itemErrors.Count > 0) { errors.AddRange(itemErrors); continue; }
|
||||
|
||||
submission.ValidationFindings = findings;
|
||||
submission.SourceFireStats = await GetFireStatsAsync(tenantId, kind, ruleId);
|
||||
prepared.Add(submission);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
throw new ArgumentException("Submission rejected: " + string.Join(" | ", errors));
|
||||
|
||||
foreach (var submission in prepared)
|
||||
{
|
||||
if (!await _submissions.AddAsync(submission))
|
||||
throw new InvalidOperationException("Failed to store the submission.");
|
||||
}
|
||||
|
||||
return prepared;
|
||||
}
|
||||
|
||||
private async Task<string> ResolveAttributionNameAsync(string tenantId, string? mode, string? requestedName)
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case RuleAttributionModes.Anonymous:
|
||||
return RuleAttributionModes.AnonymousAuthor;
|
||||
case RuleAttributionModes.Organization:
|
||||
{
|
||||
var config = await _configService.GetConfigurationIfExistsAsync(tenantId);
|
||||
var name = config?.CompanyName;
|
||||
if (string.IsNullOrWhiteSpace(name)) name = config?.DomainName;
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
throw new ArgumentException("No organization name is known for this tenant — set the company name in the tenant settings or choose another attribution.");
|
||||
return ValidateAttributionName(name!.Trim());
|
||||
}
|
||||
case RuleAttributionModes.Person:
|
||||
if (string.IsNullOrWhiteSpace(requestedName))
|
||||
throw new ArgumentException("attributionName is required for the person attribution.");
|
||||
return ValidateAttributionName(requestedName!.Trim());
|
||||
default:
|
||||
throw new ArgumentException($"attributionMode must be one of: {string.Join(", ", RuleAttributionModes.All)}.");
|
||||
}
|
||||
}
|
||||
|
||||
internal static string ValidateAttributionName(string name)
|
||||
{
|
||||
if (!AttributionNameShape.IsMatch(name))
|
||||
throw new ArgumentException("attributionName may only contain letters, digits, spaces and . , ' & ( ) - (1–64 characters).");
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>Wire JSON of the rule minus server and tenant fields — what the reviewer sees and what ships.</summary>
|
||||
internal static string FreezeRule<T>(T rule)
|
||||
{
|
||||
var node = JsonSerializer.SerializeToNode(rule, ApiJsonOptions.Create()) as JsonObject
|
||||
?? throw new InvalidOperationException("Rule did not serialize to an object.");
|
||||
foreach (var field in StrippedFields) node.Remove(field);
|
||||
return node.ToJsonString();
|
||||
}
|
||||
|
||||
private async Task<RuleSubmissionFireStats?> GetFireStatsAsync(string tenantId, string kind, string ruleId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var end = DateTime.UtcNow;
|
||||
var start = end.AddDays(-FireStatsDays);
|
||||
var entries = await _metricsRepo.GetRuleStatsAsync(
|
||||
tenantId, start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
end.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), kind);
|
||||
var mine = entries.Where(e => string.Equals(e.RuleId, ruleId, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
return new RuleSubmissionFireStats
|
||||
{
|
||||
Days = FireStatsDays,
|
||||
FireCount = mine.Sum(e => e.FireCount),
|
||||
SessionsEvaluated = mine.Sum(e => e.SessionsEvaluated),
|
||||
EvaluationCount = mine.Sum(e => e.EvaluationCount),
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Fire stats unavailable for {RuleId} (tenant {TenantId})", ruleId, tenantId);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Read ────────────────────────────────────────────────────────────────
|
||||
|
||||
public Task<RuleSubmission?> GetAsync(string submissionId) => _submissions.GetAsync(submissionId);
|
||||
|
||||
public Task<List<RuleSubmission>> GetForTenantAsync(string tenantId) => _submissions.GetForTenantAsync(tenantId);
|
||||
|
||||
public Task<RawPage<RuleSubmission>> GetPageAsync(string? tenantId, string? status, int pageSize, string? continuation)
|
||||
=> _submissions.GetPageAsync(tenantId, status, pageSize, continuation);
|
||||
|
||||
/// <summary>Projects rows to the wire shape with the effective status (<c>published</c> derived from the catalog).</summary>
|
||||
public async Task<List<RuleSubmissionItem>> ToItemsAsync(IEnumerable<RuleSubmission> rows)
|
||||
{
|
||||
var list = rows.ToList();
|
||||
HashSet<string>? globalAnalyze = null, globalGather = null;
|
||||
if (list.Any(s => s.Status == RuleSubmissionStatuses.Approved && !string.IsNullOrEmpty(s.PublishedRuleId)))
|
||||
{
|
||||
globalAnalyze = (await _ruleRepo.GetAnalyzeRulesAsync("global")).Select(r => r.RuleId).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
globalGather = (await _ruleRepo.GetGatherRulesAsync("global")).Select(r => r.RuleId).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return list.Select(s => ToItem(s, IsPublished(s, globalAnalyze, globalGather))).ToList();
|
||||
}
|
||||
|
||||
private static bool IsPublished(RuleSubmission s, HashSet<string>? globalAnalyze, HashSet<string>? globalGather)
|
||||
{
|
||||
if (s.Status != RuleSubmissionStatuses.Approved || string.IsNullOrEmpty(s.PublishedRuleId)) return false;
|
||||
var set = s.RuleKind == RuleSubmissionKinds.Analyze ? globalAnalyze : globalGather;
|
||||
return set != null && set.Contains(s.PublishedRuleId!);
|
||||
}
|
||||
|
||||
internal static RuleSubmissionItem ToItem(RuleSubmission s, bool published) => new()
|
||||
{
|
||||
SubmissionId = s.SubmissionId,
|
||||
BatchId = s.BatchId,
|
||||
TenantId = s.TenantId,
|
||||
RuleKind = s.RuleKind,
|
||||
SourceRuleId = s.SourceRuleId,
|
||||
Title = s.Title,
|
||||
Category = s.Category,
|
||||
Comment = s.Comment,
|
||||
SubmittedBy = s.SubmittedBy,
|
||||
SubmittedByName = s.SubmittedByName,
|
||||
AttributionMode = s.AttributionMode,
|
||||
AttributionName = s.AttributionName,
|
||||
SubmittedAt = s.SubmittedAt,
|
||||
Status = published ? RuleSubmissionStatuses.Published : s.Status,
|
||||
ValidationFindings = s.ValidationFindings,
|
||||
SourceFireStats = s.SourceFireStats,
|
||||
ReviewedBy = s.ReviewedBy,
|
||||
ReviewedAt = s.ReviewedAt,
|
||||
ReviewComment = s.ReviewComment,
|
||||
WillBeAdapted = s.WillBeAdapted,
|
||||
PublishedRuleId = s.PublishedRuleId,
|
||||
DerivedFromTemplateRuleId = s.DerivedFromTemplateRuleId,
|
||||
};
|
||||
|
||||
/// <summary>Everything the reviewer (human or AI) needs for one submission.</summary>
|
||||
public async Task<RuleSubmissionDetailResponse?> GetDetailAsync(string submissionId)
|
||||
{
|
||||
var s = await _submissions.GetAsync(submissionId);
|
||||
if (s == null) return null;
|
||||
|
||||
var item = (await ToItemsAsync(new[] { s }))[0];
|
||||
var response = new RuleSubmissionDetailResponse { Success = true, Submission = item };
|
||||
|
||||
if (s.RuleKind == RuleSubmissionKinds.Analyze)
|
||||
{
|
||||
var rule = JsonSerializer.Deserialize<AnalyzeRule>(s.RuleJson, ApiJsonOptions.Read);
|
||||
if (rule != null) { rule.IsBuiltIn = false; rule.IsCommunity = false; }
|
||||
response.AnalyzeRule = rule;
|
||||
}
|
||||
else
|
||||
{
|
||||
var rule = JsonSerializer.Deserialize<GatherRule>(s.RuleJson, ApiJsonOptions.Read);
|
||||
if (rule != null) { rule.IsBuiltIn = false; rule.IsCommunity = false; }
|
||||
response.GatherRule = rule;
|
||||
}
|
||||
|
||||
response.LiveFireStats = await GetFireStatsAsync(s.TenantId, s.RuleKind, s.SourceRuleId);
|
||||
response.SuggestedPublishedRuleId = s.PublishedRuleId ?? await SuggestPublishedRuleIdAsync(s.RuleKind, s.Category);
|
||||
var fileId = s.PublishedRuleId ?? response.SuggestedPublishedRuleId;
|
||||
if (!string.IsNullOrEmpty(fileId))
|
||||
response.RepoFile = BuildRepoFile(s, fileId!);
|
||||
return response;
|
||||
}
|
||||
|
||||
// ── Review ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Applies a reviewer decision. Transitions: pending → approved | declined; approved → declined
|
||||
/// while not yet published. <see cref="KeyNotFoundException"/> = unknown id,
|
||||
/// <see cref="ArgumentException"/> = bad input, <see cref="InvalidOperationException"/> = conflict.
|
||||
/// </summary>
|
||||
public async Task<RuleSubmission> ReviewAsync(string submissionId, ReviewRuleSubmissionRequest request, string reviewedBy)
|
||||
{
|
||||
var s = await _submissions.GetAsync(submissionId) ?? throw new KeyNotFoundException("Submission not found.");
|
||||
var comment = string.IsNullOrWhiteSpace(request.ReviewComment) ? null : request.ReviewComment!.Trim();
|
||||
if (comment != null && comment.Length > ReviewRuleSubmissionRequest.MaxReviewCommentLength)
|
||||
throw new ArgumentException($"reviewComment exceeds {ReviewRuleSubmissionRequest.MaxReviewCommentLength} characters.");
|
||||
|
||||
var published = (await ToItemsAsync(new[] { s }))[0].Status == RuleSubmissionStatuses.Published;
|
||||
if (published)
|
||||
throw new InvalidOperationException("The rule is already published; the submission is final.");
|
||||
if (s.Status == RuleSubmissionStatuses.Withdrawn)
|
||||
throw new InvalidOperationException("The submitter withdrew this submission.");
|
||||
|
||||
switch (request.Decision)
|
||||
{
|
||||
case RuleSubmissionDecisions.Approve:
|
||||
{
|
||||
if (s.Status != RuleSubmissionStatuses.Pending)
|
||||
throw new InvalidOperationException($"Only a pending submission can be approved (status: {s.Status}).");
|
||||
var publishedRuleId = request.PublishedRuleId?.Trim();
|
||||
if (string.IsNullOrEmpty(publishedRuleId))
|
||||
throw new ArgumentException("publishedRuleId is required to approve.");
|
||||
await ValidatePublishedRuleIdAsync(s, publishedRuleId!);
|
||||
s.Status = RuleSubmissionStatuses.Approved;
|
||||
s.PublishedRuleId = publishedRuleId;
|
||||
s.WillBeAdapted = request.WillBeAdapted ?? false;
|
||||
break;
|
||||
}
|
||||
case RuleSubmissionDecisions.Decline:
|
||||
{
|
||||
if (s.Status != RuleSubmissionStatuses.Pending && s.Status != RuleSubmissionStatuses.Approved)
|
||||
throw new InvalidOperationException($"Cannot decline a submission in status {s.Status}.");
|
||||
if (comment == null)
|
||||
throw new ArgumentException("reviewComment is required to decline — the submitter sees it.");
|
||||
s.Status = RuleSubmissionStatuses.Declined;
|
||||
s.PublishedRuleId = null;
|
||||
s.WillBeAdapted = false;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new ArgumentException($"decision must be one of: {string.Join(", ", RuleSubmissionDecisions.All)}.");
|
||||
}
|
||||
|
||||
s.ReviewComment = comment;
|
||||
s.ReviewedBy = reviewedBy;
|
||||
s.ReviewedAt = DateTime.UtcNow;
|
||||
|
||||
if (!await _submissions.UpdateAsync(s))
|
||||
throw new InvalidOperationException("The submission changed underneath this review; reload and retry.");
|
||||
return s;
|
||||
}
|
||||
|
||||
private async Task ValidatePublishedRuleIdAsync(RuleSubmission s, string publishedRuleId)
|
||||
{
|
||||
var kindPrefix = s.RuleKind == RuleSubmissionKinds.Analyze ? "ANALYZE-" : "GATHER-";
|
||||
if (!RuleIdPolicy.IsReservedBuiltInId(publishedRuleId)
|
||||
|| !publishedRuleId.StartsWith(kindPrefix, StringComparison.OrdinalIgnoreCase)
|
||||
|| !Regex.IsMatch(publishedRuleId, @"^[A-Z]+-[A-Z]+-\d{3}$"))
|
||||
throw new ArgumentException($"publishedRuleId must be {kindPrefix}<CATEGORY>-<NNN> in the reserved built-in namespace (upper case, three digits).");
|
||||
|
||||
var taken = await GetTakenIdsAsync(s.RuleKind);
|
||||
if (taken.Contains(publishedRuleId))
|
||||
throw new InvalidOperationException($"Rule id '{publishedRuleId}' is already taken (catalog, global partition or another approved submission).");
|
||||
}
|
||||
|
||||
/// <summary>Tenant-side withdrawal; only while pending. False when there is nothing to withdraw.</summary>
|
||||
public async Task<bool> WithdrawAsync(string tenantId, string submissionId, bool crossTenantAllowed)
|
||||
{
|
||||
var s = await _submissions.GetAsync(submissionId);
|
||||
if (s == null) return false;
|
||||
if (!crossTenantAllowed && !string.Equals(s.TenantId, tenantId, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (s.Status != RuleSubmissionStatuses.Pending)
|
||||
throw new InvalidOperationException($"Only a pending submission can be withdrawn (status: {s.Status}).");
|
||||
s.Status = RuleSubmissionStatuses.Withdrawn;
|
||||
return await _submissions.UpdateAsync(s);
|
||||
}
|
||||
|
||||
// ── Id suggestion + repo file ───────────────────────────────────────────
|
||||
|
||||
private async Task<HashSet<string>> GetTakenIdsAsync(string kind)
|
||||
{
|
||||
var taken = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (kind == RuleSubmissionKinds.Analyze)
|
||||
{
|
||||
foreach (var r in BuiltInAnalyzeRules.GetAll()) taken.Add(r.RuleId);
|
||||
foreach (var r in await _ruleRepo.GetAnalyzeRulesAsync("global")) taken.Add(r.RuleId);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var r in BuiltInGatherRules.GetAll()) taken.Add(r.RuleId);
|
||||
foreach (var r in await _ruleRepo.GetGatherRulesAsync("global")) taken.Add(r.RuleId);
|
||||
}
|
||||
foreach (var id in await _submissions.GetReservedPublishedRuleIdsAsync()) taken.Add(id);
|
||||
return taken;
|
||||
}
|
||||
|
||||
public async Task<string> SuggestPublishedRuleIdAsync(string kind, string category)
|
||||
=> SuggestPublishedRuleId(kind, category, await GetTakenIdsAsync(kind));
|
||||
|
||||
/// <summary>
|
||||
/// Max + 1 within <c>{KIND}-{CODE}-</c> over every taken id. Gaps are retired ids that may
|
||||
/// return (RuleIdPolicy) and are never reused.
|
||||
/// </summary>
|
||||
internal static string SuggestPublishedRuleId(string kind, string category, IEnumerable<string> takenIds)
|
||||
{
|
||||
var codes = kind == RuleSubmissionKinds.Analyze ? AnalyzeCategoryCodes : GatherCategoryCodes;
|
||||
var code = codes.TryGetValue(category ?? string.Empty, out var mapped)
|
||||
? mapped
|
||||
: Regex.Replace((category ?? "MISC").ToUpperInvariant(), "[^A-Z]", "");
|
||||
if (code.Length == 0) code = "MISC";
|
||||
var prefix = (kind == RuleSubmissionKinds.Analyze ? "ANALYZE-" : "GATHER-") + code + "-";
|
||||
|
||||
var max = 0;
|
||||
foreach (var id in takenIds)
|
||||
{
|
||||
if (!id.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (int.TryParse(id.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n > max)
|
||||
max = n;
|
||||
}
|
||||
return prefix + (max + 1).ToString("D3", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The file that ships the rule: schema pointer first, the assigned id, the chosen credit,
|
||||
/// <c>isCommunity</c>, and <c>enabled</c> after the built-in convention (analyze rules ship
|
||||
/// on, gather rules opt-in because they cost device work). Lineage to the tenant's template
|
||||
/// copy is dropped.
|
||||
/// </summary>
|
||||
internal static RuleSubmissionRepoFile BuildRepoFile(RuleSubmission s, string publishedRuleId)
|
||||
{
|
||||
var frozen = JsonNode.Parse(s.RuleJson) as JsonObject
|
||||
?? throw new InvalidOperationException("Frozen rule is not an object.");
|
||||
var isAnalyze = s.RuleKind == RuleSubmissionKinds.Analyze;
|
||||
|
||||
var ordered = new JsonObject
|
||||
{
|
||||
["$schema"] = isAnalyze ? "../schema/analyze-rule.schema.json" : "../schema/gather-rule.schema.json",
|
||||
["ruleId"] = publishedRuleId,
|
||||
};
|
||||
foreach (var head in isAnalyze
|
||||
? new[] { "title", "description", "severity", "category", "version" }
|
||||
: new[] { "title", "description", "category", "version" })
|
||||
{
|
||||
if (frozen.TryGetPropertyValue(head, out var value)) ordered[head] = value?.DeepClone();
|
||||
}
|
||||
ordered["author"] = s.AttributionName;
|
||||
ordered["enabled"] = isAnalyze;
|
||||
ordered["isCommunity"] = true;
|
||||
|
||||
foreach (var kv in frozen)
|
||||
{
|
||||
if (ordered.ContainsKey(kv.Key)) continue;
|
||||
if (kv.Key == "derivedFromTemplateRuleId") continue;
|
||||
if (Array.IndexOf(StrippedFields, kv.Key) >= 0) continue;
|
||||
ordered[kv.Key] = kv.Value?.DeepClone();
|
||||
}
|
||||
|
||||
var folder = isAnalyze ? "analyze" : "gather";
|
||||
return new RuleSubmissionRepoFile
|
||||
{
|
||||
Path = $"rules/{folder}/{publishedRuleId}.json",
|
||||
Content = ordered.ToJsonString(RepoFileOptions) + "\n",
|
||||
};
|
||||
}
|
||||
|
||||
private static string NewId() => Guid.NewGuid().ToString("N").Substring(0, 12);
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,42 @@ namespace AutopilotMonitor.Functions.Services
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a Telegram notification when a tenant admin submits a custom rule for the
|
||||
/// community pool. The submission id comes first — it is the handle for the review.
|
||||
/// Best-effort — silently no-ops if the webhook URL is not configured.
|
||||
/// </summary>
|
||||
public async Task SendRuleSubmissionAsync(string submissionId, string tenantId, string submittedBy, string ruleKind, string ruleId, string title, string comment)
|
||||
{
|
||||
try
|
||||
{
|
||||
var webhookUrl = await GetWebhookUrlAsync();
|
||||
if (string.IsNullOrWhiteSpace(webhookUrl))
|
||||
{
|
||||
_logger.LogDebug("Telegram webhook URL not configured — skipping rule submission notification");
|
||||
return;
|
||||
}
|
||||
|
||||
var commentLine = string.IsNullOrWhiteSpace(comment) ? "" : $"\nComment: {comment}";
|
||||
var payload = new
|
||||
{
|
||||
chat_id = "-1003632442830",
|
||||
text = $"New Rule Submission {submissionId}\nRule: {ruleId} \"{title}\" ({ruleKind})\nTenantID: {tenantId}\nBy: {submittedBy}{commentLine}"
|
||||
};
|
||||
|
||||
var json = JsonConvert.SerializeObject(payload);
|
||||
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
var response = await _http.PostAsync(webhookUrl, content);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
_logger.LogInformation("Telegram rule submission notification sent for {SubmissionId}", submissionId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to send Telegram rule submission notification for {SubmissionId}", submissionId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a Telegram notification when a tenant admin submits a diag-files-only report
|
||||
/// (no session context). Best-effort — silently no-ops if the webhook URL is not configured.
|
||||
|
||||
@@ -35,6 +35,8 @@ public static class TenantNotificationAudienceCatalog
|
||||
["rule_frequency_regression"] = NotificationAudience.Admin,
|
||||
// App-version duration regression radar: packaging/rollout is an admin concern.
|
||||
["app_version_duration_regression"] = NotificationAudience.Admin,
|
||||
// Community rule submission decided (approved/declined): only admins submit, only admins act.
|
||||
["rule_submission_decided"] = NotificationAudience.Admin,
|
||||
};
|
||||
|
||||
public static NotificationAudience Resolve(string? type)
|
||||
|
||||
@@ -132,6 +132,8 @@ describe('role catalog snapshot — privilege-leak guard', () => {
|
||||
'get_platform_metrics',
|
||||
'get_resource',
|
||||
'get_rule_stats',
|
||||
// Platform scope (GA + Global Reader): one community rule submission with its frozen rule.
|
||||
'get_rule_submission',
|
||||
'get_session',
|
||||
'get_session_diagnostics',
|
||||
'get_session_events',
|
||||
@@ -151,6 +153,8 @@ describe('role catalog snapshot — privilege-leak guard', () => {
|
||||
'get_verdict_calibration',
|
||||
'get_vulnerability_summary',
|
||||
'list_blocked_devices',
|
||||
// Platform scope (GA + Global Reader): community rule submissions across tenants.
|
||||
'list_rule_submissions',
|
||||
'list_session_annotations',
|
||||
'list_session_reports',
|
||||
'list_tables',
|
||||
@@ -162,7 +166,10 @@ describe('role catalog snapshot — privilege-leak guard', () => {
|
||||
'query_raw_events',
|
||||
'query_raw_sessions',
|
||||
'query_table',
|
||||
// Community rule submission write surface (strictGa): the publish step and the decision.
|
||||
'reseed_rules_from_github',
|
||||
'revert_tenant_config',
|
||||
'review_rule_submission',
|
||||
'search_events',
|
||||
'search_knowledge',
|
||||
'search_sessions',
|
||||
@@ -200,6 +207,10 @@ describe('role catalog snapshot — privilege-leak guard', () => {
|
||||
// reads annotations (list_session_annotations) but never writes the GA lane.
|
||||
const ANNOTATION_WRITE_GA_STRICT = ['annotate_session'];
|
||||
|
||||
// Community rule submission write surface: strictGa only — a read-only Global Reader
|
||||
// lists and reads submissions but never decides one or triggers the reseed that publishes.
|
||||
const RULE_SUBMISSION_WRITE_GA_STRICT = ['reseed_rules_from_github', 'review_rule_submission'];
|
||||
|
||||
// Platform-only tools: a non-platform caller (tenant or delegated) gets no
|
||||
// cross-fleet aggregate surface at all. Superset of RAW_GA_STRICT and
|
||||
// CONFIG_WRITE_GA_STRICT (those are also platform-only) plus the curated
|
||||
@@ -213,11 +224,13 @@ describe('role catalog snapshot — privilege-leak guard', () => {
|
||||
'get_ime_pattern_health',
|
||||
'get_ops_events',
|
||||
'get_platform_metrics',
|
||||
'get_rule_submission',
|
||||
'get_session_report_download',
|
||||
'get_tenant_config',
|
||||
'get_tenant_config_schema',
|
||||
'get_verdict_calibration',
|
||||
'list_blocked_devices',
|
||||
'list_rule_submissions',
|
||||
'list_session_annotations',
|
||||
'list_session_reports',
|
||||
'list_tables',
|
||||
@@ -225,7 +238,9 @@ describe('role catalog snapshot — privilege-leak guard', () => {
|
||||
'list_tenants',
|
||||
'query_backend_logs',
|
||||
'query_table',
|
||||
'reseed_rules_from_github',
|
||||
'revert_tenant_config',
|
||||
'review_rule_submission',
|
||||
'update_tenant_config',
|
||||
];
|
||||
|
||||
@@ -246,7 +261,7 @@ describe('role catalog snapshot — privilege-leak guard', () => {
|
||||
|
||||
it('Global Reader = GA minus the secret-bearing raw tools, the config-write surface and the annotation write (strictGa split)', () => {
|
||||
expect(registeredToolNames(true, false)).toEqual(
|
||||
without(GA_FULL, [...RAW_GA_STRICT, ...CONFIG_WRITE_GA_STRICT, ...ANNOTATION_WRITE_GA_STRICT]));
|
||||
without(GA_FULL, [...RAW_GA_STRICT, ...CONFIG_WRITE_GA_STRICT, ...ANNOTATION_WRITE_GA_STRICT, ...RULE_SUBMISSION_WRITE_GA_STRICT]));
|
||||
});
|
||||
|
||||
it('tenant user = GA minus all platform-only tools', () => {
|
||||
@@ -265,6 +280,7 @@ describe('role catalog snapshot — privilege-leak guard', () => {
|
||||
['RAW_GA_STRICT', RAW_GA_STRICT],
|
||||
['CONFIG_WRITE_GA_STRICT', CONFIG_WRITE_GA_STRICT],
|
||||
['ANNOTATION_WRITE_GA_STRICT', ANNOTATION_WRITE_GA_STRICT],
|
||||
['RULE_SUBMISSION_WRITE_GA_STRICT', RULE_SUBMISSION_WRITE_GA_STRICT],
|
||||
['PLATFORM_ONLY', PLATFORM_ONLY],
|
||||
['DELEGATED_HIDDEN', DELEGATED_HIDDEN],
|
||||
['DELEGATED_ADDED', DELEGATED_ADDED],
|
||||
@@ -282,7 +298,7 @@ describe('role catalog snapshot — privilege-leak guard', () => {
|
||||
const registeredDiff = registeredToolNames(true, true).filter((n) => !readerNames.includes(n)).sort();
|
||||
expect([...GA_STRICT_TOOL_NAMES].sort()).toEqual(registeredDiff);
|
||||
expect([...GA_STRICT_TOOL_NAMES].sort()).toEqual(
|
||||
[...RAW_GA_STRICT, ...CONFIG_WRITE_GA_STRICT, ...ANNOTATION_WRITE_GA_STRICT].sort());
|
||||
[...RAW_GA_STRICT, ...CONFIG_WRITE_GA_STRICT, ...ANNOTATION_WRITE_GA_STRICT, ...RULE_SUBMISSION_WRITE_GA_STRICT].sort());
|
||||
});
|
||||
|
||||
it('the secret-bearing raw tools are a subset of the platform-only tools', () => {
|
||||
|
||||
@@ -3439,6 +3439,24 @@ export interface RevertTenantConfigurationRequest {
|
||||
reason?: string | null;
|
||||
}
|
||||
|
||||
/** Body of PATCH global/rule-submissions/{id}. */
|
||||
export interface ReviewRuleSubmissionRequest {
|
||||
/** One of All. */
|
||||
decision: string;
|
||||
/** Shown to the submitter. Required for decline. */
|
||||
reviewComment?: string | null;
|
||||
willBeAdapted?: boolean | null;
|
||||
/** Reserved-namespace id the rule ships under. Required for approve. */
|
||||
publishedRuleId?: string | null;
|
||||
}
|
||||
|
||||
/** Success body of PATCH global/rule-submissions/{id}. */
|
||||
export interface ReviewRuleSubmissionResponse {
|
||||
success: boolean;
|
||||
message: string;
|
||||
submission: RuleSubmissionItem;
|
||||
}
|
||||
|
||||
export interface RevokeTenantManagerRequest {
|
||||
homeTenantId: string;
|
||||
}
|
||||
@@ -3668,6 +3686,82 @@ export interface RuleStatsSummary {
|
||||
period: RuleStatsPeriod;
|
||||
}
|
||||
|
||||
/** Success body of GET global/rule-submissions/{id}: the submission, the frozen rule typed by kind (exactly one of the two rule properties is set), live fire stats, the suggested reserved id and the repo file built from the assigned (or suggested) id. */
|
||||
export interface RuleSubmissionDetailResponse {
|
||||
success: boolean;
|
||||
submission: RuleSubmissionItem;
|
||||
analyzeRule?: AnalyzeRule;
|
||||
gatherRule?: GatherRule;
|
||||
liveFireStats?: RuleSubmissionFireStats;
|
||||
suggestedPublishedRuleId?: string;
|
||||
repoFile?: RuleSubmissionRepoFile;
|
||||
}
|
||||
|
||||
/** A pre-flight finding recorded at submit time. Errors block the submission and are never stored. */
|
||||
export interface RuleSubmissionFinding {
|
||||
/** "error" | "warning" | "info". */
|
||||
level: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** Fire telemetry of the submitted rule in the submitting tenant over the trailing window. */
|
||||
export interface RuleSubmissionFireStats {
|
||||
days: number;
|
||||
fireCount: number;
|
||||
sessionsEvaluated: number;
|
||||
evaluationCount: number;
|
||||
}
|
||||
|
||||
/** Wire shape of one submission (list rows, submit response, detail head). The frozen rule document is not part of it — the detail response carries it typed. */
|
||||
export interface RuleSubmissionItem {
|
||||
submissionId: string;
|
||||
batchId: string;
|
||||
tenantId: string;
|
||||
ruleKind: string;
|
||||
sourceRuleId: string;
|
||||
title: string;
|
||||
category: string;
|
||||
comment?: string;
|
||||
submittedBy: string;
|
||||
submittedByName: string;
|
||||
attributionMode: string;
|
||||
attributionName: string;
|
||||
submittedAt: string;
|
||||
/** One of All — the effective status, published included. */
|
||||
status: string;
|
||||
validationFindings: RuleSubmissionFinding[];
|
||||
sourceFireStats?: RuleSubmissionFireStats;
|
||||
reviewedBy?: string;
|
||||
reviewedAt?: string;
|
||||
reviewComment?: string;
|
||||
willBeAdapted: boolean;
|
||||
publishedRuleId?: string;
|
||||
derivedFromTemplateRuleId?: string;
|
||||
}
|
||||
|
||||
/** One rule reference in a submit request; the server freezes the rule itself. */
|
||||
export interface RuleSubmissionItemRef {
|
||||
/** One of All. */
|
||||
kind: string;
|
||||
ruleId: string;
|
||||
}
|
||||
|
||||
/** Success body of GET rules/submissions and GET global/rule-submissions. */
|
||||
export interface RuleSubmissionListResponse {
|
||||
success: boolean;
|
||||
count: number;
|
||||
submissions: RuleSubmissionItem[];
|
||||
/** Absolute-path link to the next page; null/absent on the last page and in non-paged responses. */
|
||||
nextLink?: string;
|
||||
}
|
||||
|
||||
/** The repo-ready file for a submission: where it goes and what it contains. */
|
||||
export interface RuleSubmissionRepoFile {
|
||||
/** Repository-relative path, e.g. rules/analyze/ANALYZE-NET-002.json. */
|
||||
path: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
/** One day of a rule's trend ("yyyy-MM-dd"). */
|
||||
export interface RuleTrendPoint {
|
||||
date: string;
|
||||
@@ -4317,6 +4411,25 @@ export interface SubmitOffboardingFeedbackRequest {
|
||||
comment?: string | null;
|
||||
}
|
||||
|
||||
/** Body of POST rules/submissions: up to MaxItems of the caller's own custom rules. */
|
||||
export interface SubmitRuleSubmissionsRequest {
|
||||
tenantId: string;
|
||||
items: RuleSubmissionItemRef[];
|
||||
comment?: string | null;
|
||||
/** One of All. */
|
||||
attributionMode: string;
|
||||
/** Credit text for the person mode; ignored for the other modes. */
|
||||
attributionName?: string | null;
|
||||
}
|
||||
|
||||
/** Success body of POST rules/submissions. */
|
||||
export interface SubmitRuleSubmissionsResponse {
|
||||
success: boolean;
|
||||
message: string;
|
||||
batchId: string;
|
||||
submissions: RuleSubmissionItem[];
|
||||
}
|
||||
|
||||
/** Request to submit a session report for analysis by the Autopilot Monitor team. Sent as JSON from the frontend; the backend creates the ZIP and uploads to central storage. */
|
||||
export interface SubmitSessionReportRequest {
|
||||
tenantId: string;
|
||||
|
||||
@@ -155,6 +155,38 @@ export const ANNOTATION_VERDICTS = [
|
||||
] as const;
|
||||
export type AnnotationVerdict = (typeof ANNOTATION_VERDICTS)[number];
|
||||
|
||||
/** Community rule submission kinds (C# RuleSubmissionKinds). */
|
||||
export const RULE_SUBMISSION_KINDS = [
|
||||
"gather",
|
||||
"analyze",
|
||||
] as const;
|
||||
export type RuleSubmissionKind = (typeof RULE_SUBMISSION_KINDS)[number];
|
||||
|
||||
/** Effective rule submission statuses incl. the derived published (C# RuleSubmissionStatuses). */
|
||||
export const RULE_SUBMISSION_STATUSES = [
|
||||
"pending",
|
||||
"approved",
|
||||
"declined",
|
||||
"withdrawn",
|
||||
"published",
|
||||
] as const;
|
||||
export type RuleSubmissionStatus = (typeof RULE_SUBMISSION_STATUSES)[number];
|
||||
|
||||
/** How a contributed rule credits its author (C# RuleAttributionModes). */
|
||||
export const RULE_ATTRIBUTION_MODES = [
|
||||
"anonymous",
|
||||
"organization",
|
||||
"person",
|
||||
] as const;
|
||||
export type RuleAttributionMode = (typeof RULE_ATTRIBUTION_MODES)[number];
|
||||
|
||||
/** Reviewer decisions on a rule submission (C# RuleSubmissionDecisions). */
|
||||
export const RULE_SUBMISSION_DECISIONS = [
|
||||
"approve",
|
||||
"decline",
|
||||
] as const;
|
||||
export type RuleSubmissionDecision = (typeof RULE_SUBMISSION_DECISIONS)[number];
|
||||
|
||||
/** Telemetry stores behind the operator KQL proxy — query_backend_logs `source` (C# LogQuerySources). */
|
||||
export const LOG_SOURCES = [
|
||||
"backend",
|
||||
|
||||
@@ -25,6 +25,8 @@ export const GA_STRICT_TOOL_NAMES: ReadonlySet<string> = new Set([
|
||||
'update_tenant_config',
|
||||
'list_tenant_config_backups',
|
||||
'revert_tenant_config',
|
||||
'review_rule_submission',
|
||||
'reseed_rules_from_github',
|
||||
]);
|
||||
|
||||
/** Default first-page size of get_fleet_overview's session list (a fleet snapshot, not a sweep). */
|
||||
@@ -94,7 +96,12 @@ import type {
|
||||
QueryBackendLogsResponse,
|
||||
QueryRawSessionsResponse,
|
||||
QueryRawTableResponse,
|
||||
ReseedFromGitHubResponse,
|
||||
RevertTenantConfigurationRequest,
|
||||
ReviewRuleSubmissionRequest,
|
||||
ReviewRuleSubmissionResponse,
|
||||
RuleSubmissionDetailResponse,
|
||||
RuleSubmissionListResponse,
|
||||
RuleStatsResponse,
|
||||
RuleStatsRuleAggregate,
|
||||
SessionAnnotationListResponse,
|
||||
@@ -120,6 +127,9 @@ import {
|
||||
LOG_SOURCES,
|
||||
OPS_EVENT_CATEGORIES,
|
||||
OPS_EVENT_SEVERITIES,
|
||||
RULE_SUBMISSION_DECISIONS,
|
||||
RULE_SUBMISSION_KINDS,
|
||||
RULE_SUBMISSION_STATUSES,
|
||||
SESSION_STATUSES,
|
||||
} from '../generated/wire-vocabularies.generated.js';
|
||||
|
||||
@@ -1114,6 +1124,156 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
|
||||
})
|
||||
);
|
||||
|
||||
// ── Community rule submissions ────────────────────────────────────────
|
||||
// The submission id (12 hex chars, the session-report shape) is the handle for the whole
|
||||
// review: list → get → validate_rule / test_analyze_rule → review → repo commit → reseed.
|
||||
|
||||
// Tool 18d: list_rule_submissions — platform scope (GA + Global Reader).
|
||||
if (ga) server.registerTool(
|
||||
'list_rule_submissions',
|
||||
{
|
||||
title: 'List Rule Submissions',
|
||||
description:
|
||||
'List custom gather/analyze rules that tenant admins submitted for the community pool, newest first, with ' +
|
||||
'the effective status (pending | approved | declined | withdrawn | published — "published" is derived: the ' +
|
||||
'approved rule\'s published id exists in the global catalog). Platform scope; pass tenantId to filter to one ' +
|
||||
'tenant and status to one status. Each row carries the submission id — pass it to get_rule_submission for the ' +
|
||||
'frozen rule, findings, fire stats and the repo-ready file. Fully paginated; pass the whole nextLink as "continuation".',
|
||||
inputSchema: {
|
||||
tenantId: TenantGuidSchema.optional().describe('Optional — filter to a single tenant. Omit for the cross-tenant view.'),
|
||||
status: z.enum(RULE_SUBMISSION_STATUSES).optional()
|
||||
.describe('Optional — one effective status. "published" lists the approved submissions whose rule is live in the global catalog.'),
|
||||
pageSize: z.coerce.number().int().min(1).max(1000).optional()
|
||||
.describe('Page size (1-1000; default ' + DEFAULT_FIRST_PAGE_SIZE + ' on the first page). Follow nextLink for more.'),
|
||||
continuation: z.string().optional()
|
||||
.describe('The "continuation" value or the full nextLink path of a prior response; the latter is preferred.'),
|
||||
},
|
||||
annotations: READ_ONLY,
|
||||
},
|
||||
async (args) => withToolTelemetry('list_rule_submissions', args, async () => {
|
||||
try {
|
||||
const { tenantId, continuation } = args;
|
||||
const pageSize = pageSizeForCall(args.pageSize, continuation, DEFAULT_FIRST_PAGE_SIZE);
|
||||
// "published" is not a stored status: ask the backend for the approved rows and keep the live ones.
|
||||
const wantsPublished = args.status === 'published';
|
||||
const status = wantsPublished ? 'approved' : args.status;
|
||||
const path = followNextLink(
|
||||
'/api/global/rule-submissions',
|
||||
{ tenantId, status, pageSize },
|
||||
continuation,
|
||||
{ pageSize },
|
||||
);
|
||||
const data = await apiFetch<RuleSubmissionListResponse>(path);
|
||||
if (wantsPublished) {
|
||||
const submissions = data.submissions.filter((s) => s.status === 'published');
|
||||
return toolResultText({ ...data, count: submissions.length, submissions }, MAX_RESULT_SIZE_CHARS.adminStream);
|
||||
}
|
||||
return toolResultText(data, MAX_RESULT_SIZE_CHARS.adminStream);
|
||||
} catch (error: unknown) {
|
||||
return toolError('list_rule_submissions', args, error);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Tool 18e: get_rule_submission — platform scope (GA + Global Reader).
|
||||
if (ga) server.registerTool(
|
||||
'get_rule_submission',
|
||||
{
|
||||
title: 'Get Rule Submission',
|
||||
description:
|
||||
'Everything a review needs for one submitted rule: the submission (submitter, comment, attribution, ' +
|
||||
'effective status, review fields), the frozen rule typed by kind (analyzeRule or gatherRule — pass it to ' +
|
||||
'validate_rule, and for analyze rules to test_analyze_rule against sessions of the submitting tenant), the ' +
|
||||
'pre-flight findings recorded at submit time, the rule\'s fire stats in the submitting tenant (frozen and live), ' +
|
||||
'the suggested reserved rule id (max+1 in the category, gaps are retired ids) and repoFile: the ready-to-commit ' +
|
||||
'file content plus its path under rules/. After approval, publishing is a repo commit of that file followed by ' +
|
||||
'reseed_rules_from_github; the status turns "published" once the id is in the global catalog.',
|
||||
inputSchema: {
|
||||
submissionId: z.string().trim().regex(/^[0-9a-f]{12}$/i).describe('The 12-character submission id.'),
|
||||
},
|
||||
annotations: READ_ONLY,
|
||||
},
|
||||
async (args) => withToolTelemetry('get_rule_submission', args, async () => {
|
||||
try {
|
||||
const data = await apiFetch<RuleSubmissionDetailResponse>(`/api/global/rule-submissions/${encodeURIComponent(args.submissionId)}`);
|
||||
return toolResultText(data, MAX_RESULT_SIZE_CHARS.small);
|
||||
} catch (error: unknown) {
|
||||
return toolError('get_rule_submission', args, error);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Tool 18f: review_rule_submission — real Global Admin only (write).
|
||||
if (strictGa) server.registerTool(
|
||||
'review_rule_submission',
|
||||
{
|
||||
title: 'Review Rule Submission',
|
||||
description:
|
||||
'Record the decision on a submitted rule. Global Admin only. approve needs publishedRuleId — the reserved ' +
|
||||
'built-in id the rule will ship under (ANALYZE-<CAT>-NNN / GATHER-<CAT>-NNN, three digits; take ' +
|
||||
'suggestedPublishedRuleId from get_rule_submission unless you have a reason not to) — and may set ' +
|
||||
'willBeAdapted when the published rule will differ from the submitted one. decline needs reviewComment. ' +
|
||||
'The comment is shown to the submitter in both cases. Transitions: pending → approved | declined; ' +
|
||||
'approved → declined while not yet published; a published submission is final. Approving does NOT publish: ' +
|
||||
'commit the repo file (get_rule_submission → repoFile), push, then reseed_rules_from_github.',
|
||||
inputSchema: {
|
||||
submissionId: z.string().trim().regex(/^[0-9a-f]{12}$/i).describe('The 12-character submission id.'),
|
||||
decision: z.enum(RULE_SUBMISSION_DECISIONS).describe('approve or decline.'),
|
||||
reviewComment: z.string().max(4000).optional()
|
||||
.describe('Shown to the submitter. Required for decline; for approve it explains the adaptation, if any.'),
|
||||
willBeAdapted: z.boolean().optional()
|
||||
.describe('approve only — the published rule will be adapted (generalised) before it ships.'),
|
||||
publishedRuleId: z.string().trim().optional()
|
||||
.describe('approve only — the reserved id the rule ships under; must be free in catalog, global partition and other approvals.'),
|
||||
},
|
||||
annotations: MUTATING,
|
||||
},
|
||||
async (args) => withToolTelemetry('review_rule_submission', args, async () => {
|
||||
try {
|
||||
const { submissionId, decision, reviewComment, willBeAdapted, publishedRuleId } = args;
|
||||
const data = await apiFetch<ReviewRuleSubmissionResponse>(
|
||||
`/api/global/rule-submissions/${encodeURIComponent(submissionId)}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
body: jsonBody<ReviewRuleSubmissionRequest>({ decision, reviewComment, willBeAdapted, publishedRuleId }),
|
||||
},
|
||||
);
|
||||
return toolResultText(data, MAX_RESULT_SIZE_CHARS.small);
|
||||
} catch (error: unknown) {
|
||||
return toolError('review_rule_submission', args, error);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Tool 18g: reseed_rules_from_github — real Global Admin only (write): the publish step.
|
||||
if (strictGa) server.registerTool(
|
||||
'reseed_rules_from_github',
|
||||
{
|
||||
title: 'Reseed Rules From GitHub',
|
||||
description:
|
||||
'Pull the rule catalog of one kind from the public repository\'s main branch (rules/dist) into the global ' +
|
||||
'rule partition — the step that makes a committed and pushed community rule live for every tenant without a ' +
|
||||
'backend deploy. Global Admin only. Also sunsets GitHub-sourced rules the repository no longer ships, so run it ' +
|
||||
'only after the push landed. Returns deleted/written counts; the proof of a publish is get_rule_submission ' +
|
||||
'showing status "published", not this count.',
|
||||
inputSchema: {
|
||||
type: z.enum(RULE_SUBMISSION_KINDS).describe('Which catalog to reseed: analyze or gather.'),
|
||||
},
|
||||
annotations: MUTATING,
|
||||
},
|
||||
async (args) => withToolTelemetry('reseed_rules_from_github', args, async () => {
|
||||
try {
|
||||
const data = await apiFetch<ReseedFromGitHubResponse>(
|
||||
`/api/rules/reseed-from-github?type=${encodeURIComponent(args.type)}`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
return toolResultText(data, MAX_RESULT_SIZE_CHARS.small);
|
||||
} catch (error: unknown) {
|
||||
return toolError('reseed_rules_from_github', args, error);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Tool 18a: get_deployment_state — platform scope; every source is a public endpoint, the
|
||||
// tool only saves the operator six fetches and the drift arithmetic.
|
||||
if (ga) server.registerTool(
|
||||
|
||||
@@ -1276,6 +1276,12 @@ namespace AutopilotMonitor.Shared
|
||||
// Session reports (feedback from Tenant Admins)
|
||||
public const string SessionReports = "SessionReports";
|
||||
|
||||
// Custom rules submitted for the community pool. PK = "submissions" for every tenant,
|
||||
// RK = {invertedTicks}_{submissionId} (the SessionReports layout); tenant views and the
|
||||
// point lookup are property filters — a submission is a rare, deliberate act, so the
|
||||
// partition stays small enough that a second key layout would cost more than it saves.
|
||||
public const string RuleSubmissions = "RuleSubmissions";
|
||||
|
||||
// Bootstrap sessions (OOBE pre-enrollment agent deployment)
|
||||
public const string BootstrapSessions = "BootstrapSessions";
|
||||
|
||||
@@ -1454,6 +1460,7 @@ namespace AutopilotMonitor.Shared
|
||||
BlockedDevices,
|
||||
BlockedVersions,
|
||||
SessionReports,
|
||||
RuleSubmissions,
|
||||
BootstrapSessions,
|
||||
GlobalNotifications,
|
||||
TenantNotifications,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
|
||||
namespace AutopilotMonitor.Shared.DataAccess
|
||||
{
|
||||
/// <summary>
|
||||
/// Repository for the <c>RuleSubmissions</c> table (one partition, newest-first RowKeys).
|
||||
/// Expected volume is small — a submission is a rare, deliberate act — so the tenant view and
|
||||
/// the point lookup are property filters over the partition rather than a second key layout.
|
||||
/// </summary>
|
||||
public interface IRuleSubmissionRepository
|
||||
{
|
||||
Task<bool> AddAsync(RuleSubmission submission);
|
||||
|
||||
/// <summary>Point lookup by id across all tenants; null when unknown.</summary>
|
||||
Task<RuleSubmission?> GetAsync(string submissionId);
|
||||
|
||||
/// <summary>Every submission of one tenant, newest first.</summary>
|
||||
Task<List<RuleSubmission>> GetForTenantAsync(string tenantId);
|
||||
|
||||
/// <summary>One page newest-first, optionally filtered by tenant and stored status.</summary>
|
||||
Task<RawPage<RuleSubmission>> GetPageAsync(string? tenantId, string? status, int pageSize, string? continuation);
|
||||
|
||||
/// <summary>Replaces the row's mutable review columns; false when the row is gone.</summary>
|
||||
Task<bool> UpdateAsync(RuleSubmission submission);
|
||||
|
||||
/// <summary>The published ids reserved by approved submissions — the third set the id suggestion excludes.</summary>
|
||||
Task<HashSet<string>> GetReservedPublishedRuleIdsAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AutopilotMonitor.Shared.Models
|
||||
{
|
||||
/// <summary>One rule reference in a submit request; the server freezes the rule itself.</summary>
|
||||
[WireContract]
|
||||
public class RuleSubmissionItemRef
|
||||
{
|
||||
/// <summary>One of <see cref="RuleSubmissionKinds.All"/>.</summary>
|
||||
public string Kind { get; set; } = default!;
|
||||
public string RuleId { get; set; } = default!;
|
||||
}
|
||||
|
||||
/// <summary>Body of POST rules/submissions: up to <see cref="MaxItems"/> of the caller's own custom rules.</summary>
|
||||
public class SubmitRuleSubmissionsRequest : IApiRequest
|
||||
{
|
||||
public const int MaxItems = 10;
|
||||
public const int MaxCommentLength = 4000;
|
||||
public const int MaxAttributionNameLength = 64;
|
||||
|
||||
public string TenantId { get; set; } = default!;
|
||||
public List<RuleSubmissionItemRef> Items { get; set; } = new List<RuleSubmissionItemRef>();
|
||||
public string? Comment { get; set; }
|
||||
|
||||
/// <summary>One of <see cref="RuleAttributionModes.All"/>.</summary>
|
||||
public string AttributionMode { get; set; } = RuleAttributionModes.Anonymous;
|
||||
|
||||
/// <summary>Credit text for the <c>person</c> mode; ignored for the other modes.</summary>
|
||||
public string? AttributionName { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wire shape of one submission (list rows, submit response, detail head). The frozen rule
|
||||
/// document is not part of it — the detail response carries it typed.
|
||||
/// </summary>
|
||||
// Declaration order == wire order.
|
||||
[WireContract]
|
||||
public class RuleSubmissionItem
|
||||
{
|
||||
public string SubmissionId { get; set; } = default!;
|
||||
public string BatchId { get; set; } = default!;
|
||||
public string TenantId { get; set; } = default!;
|
||||
public string RuleKind { get; set; } = default!;
|
||||
public string SourceRuleId { get; set; } = default!;
|
||||
public string Title { get; set; } = default!;
|
||||
public string Category { get; set; } = default!;
|
||||
public string? Comment { get; set; }
|
||||
public string SubmittedBy { get; set; } = default!;
|
||||
public string SubmittedByName { get; set; } = default!;
|
||||
public string AttributionMode { get; set; } = default!;
|
||||
public string AttributionName { get; set; } = default!;
|
||||
public DateTime SubmittedAt { get; set; }
|
||||
|
||||
/// <summary>One of <see cref="RuleSubmissionStatuses.All"/> — the effective status, <c>published</c> included.</summary>
|
||||
public string Status { get; set; } = default!;
|
||||
public IReadOnlyList<RuleSubmissionFinding> ValidationFindings { get; set; } = default!;
|
||||
public RuleSubmissionFireStats? SourceFireStats { get; set; }
|
||||
public string? ReviewedBy { get; set; }
|
||||
public DateTime? ReviewedAt { get; set; }
|
||||
public string? ReviewComment { get; set; }
|
||||
public bool WillBeAdapted { get; set; }
|
||||
public string? PublishedRuleId { get; set; }
|
||||
public string? DerivedFromTemplateRuleId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Success body of POST rules/submissions.</summary>
|
||||
// Declaration order == wire order.
|
||||
public class SubmitRuleSubmissionsResponse : IApiResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string Message { get; set; } = default!;
|
||||
public string BatchId { get; set; } = default!;
|
||||
public IReadOnlyList<RuleSubmissionItem> Submissions { get; set; } = default!;
|
||||
}
|
||||
|
||||
/// <summary>Success body of GET rules/submissions and GET global/rule-submissions.</summary>
|
||||
// Declaration order == wire order.
|
||||
public class RuleSubmissionListResponse : IApiResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public int Count { get; set; }
|
||||
public IReadOnlyList<RuleSubmissionItem> Submissions { get; set; } = default!;
|
||||
|
||||
/// <summary>Absolute-path link to the next page; null/absent on the last page and in non-paged responses.</summary>
|
||||
public string? NextLink { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The repo-ready file for a submission: where it goes and what it contains.</summary>
|
||||
// Declaration order == wire order.
|
||||
[WireContract]
|
||||
public class RuleSubmissionRepoFile
|
||||
{
|
||||
/// <summary>Repository-relative path, e.g. <c>rules/analyze/ANALYZE-NET-002.json</c>.</summary>
|
||||
public string Path { get; set; } = default!;
|
||||
public string Content { get; set; } = default!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Success body of GET global/rule-submissions/{id}: the submission, the frozen rule typed by
|
||||
/// kind (exactly one of the two rule properties is set), live fire stats, the suggested
|
||||
/// reserved id and the repo file built from the assigned (or suggested) id.
|
||||
/// </summary>
|
||||
// Declaration order == wire order.
|
||||
public class RuleSubmissionDetailResponse : IApiResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public RuleSubmissionItem Submission { get; set; } = default!;
|
||||
public AnalyzeRule? AnalyzeRule { get; set; }
|
||||
public GatherRule? GatherRule { get; set; }
|
||||
public RuleSubmissionFireStats? LiveFireStats { get; set; }
|
||||
public string? SuggestedPublishedRuleId { get; set; }
|
||||
public RuleSubmissionRepoFile? RepoFile { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Body of PATCH global/rule-submissions/{id}.</summary>
|
||||
public class ReviewRuleSubmissionRequest : IApiRequest
|
||||
{
|
||||
public const int MaxReviewCommentLength = 4000;
|
||||
|
||||
/// <summary>One of <see cref="RuleSubmissionDecisions.All"/>.</summary>
|
||||
public string Decision { get; set; } = default!;
|
||||
|
||||
/// <summary>Shown to the submitter. Required for <c>decline</c>.</summary>
|
||||
public string? ReviewComment { get; set; }
|
||||
public bool? WillBeAdapted { get; set; }
|
||||
|
||||
/// <summary>Reserved-namespace id the rule ships under. Required for <c>approve</c>.</summary>
|
||||
public string? PublishedRuleId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Success body of PATCH global/rule-submissions/{id}.</summary>
|
||||
// Declaration order == wire order.
|
||||
public class ReviewRuleSubmissionResponse : IApiResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string Message { get; set; } = default!;
|
||||
public RuleSubmissionItem Submission { get; set; } = default!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AutopilotMonitor.Shared.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// One custom rule a tenant admin submitted for the community pool. Stored in the
|
||||
/// <c>RuleSubmissions</c> table: PK = <c>"submissions"</c> (one partition for every tenant,
|
||||
/// the SessionReports layout), RK = <c>{invertedTicks(SubmittedAt)}_{SubmissionId}</c>.
|
||||
/// <see cref="RuleJson"/> is the server-frozen snapshot of the rule at submit time — the
|
||||
/// tenant's later edits or deletes never reach it, and the payload never supplies it.
|
||||
/// The stored <see cref="Status"/> is never <see cref="RuleSubmissionStatuses.Published"/>:
|
||||
/// that value is derived at read time from the global rule catalog.
|
||||
/// </summary>
|
||||
public class RuleSubmission
|
||||
{
|
||||
/// <summary>Twelve hex characters, the same shape as a session report id.</summary>
|
||||
public string SubmissionId { get; set; } = default!;
|
||||
|
||||
/// <summary>Groups the rules of one submit action; each rule keeps its own id and status.</summary>
|
||||
public string BatchId { get; set; } = default!;
|
||||
public string TenantId { get; set; } = default!;
|
||||
|
||||
/// <summary>One of <see cref="RuleSubmissionKinds.All"/>.</summary>
|
||||
public string RuleKind { get; set; } = default!;
|
||||
|
||||
/// <summary>The rule id in the tenant's partition at submit time.</summary>
|
||||
public string SourceRuleId { get; set; } = default!;
|
||||
public string Title { get; set; } = default!;
|
||||
public string Category { get; set; } = default!;
|
||||
|
||||
/// <summary>Frozen rule document (wire JSON of the rule minus server and tenant fields).</summary>
|
||||
public string RuleJson { get; set; } = default!;
|
||||
public string? Comment { get; set; }
|
||||
public string SubmittedBy { get; set; } = default!;
|
||||
public string SubmittedByName { get; set; } = default!;
|
||||
|
||||
/// <summary>One of <see cref="RuleAttributionModes.All"/>.</summary>
|
||||
public string AttributionMode { get; set; } = RuleAttributionModes.Anonymous;
|
||||
|
||||
/// <summary>The exact text that becomes the published rule's <c>author</c>. Frozen at submit time.</summary>
|
||||
public string AttributionName { get; set; } = RuleAttributionModes.AnonymousAuthor;
|
||||
public DateTime SubmittedAt { get; set; }
|
||||
|
||||
/// <summary>One of <see cref="RuleSubmissionStatuses.Stored"/>.</summary>
|
||||
public string Status { get; set; } = RuleSubmissionStatuses.Pending;
|
||||
public List<RuleSubmissionFinding> ValidationFindings { get; set; } = new List<RuleSubmissionFinding>();
|
||||
public RuleSubmissionFireStats? SourceFireStats { get; set; }
|
||||
public string? ReviewedBy { get; set; }
|
||||
public DateTime? ReviewedAt { get; set; }
|
||||
public string? ReviewComment { get; set; }
|
||||
|
||||
/// <summary>The reviewer announced that the published rule will differ from the submitted one.</summary>
|
||||
public bool WillBeAdapted { get; set; }
|
||||
|
||||
/// <summary>The reserved-namespace id assigned on approval; the published rule's id.</summary>
|
||||
public string? PublishedRuleId { get; set; }
|
||||
public string? DerivedFromTemplateRuleId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A pre-flight finding recorded at submit time. Errors block the submission and are never stored.</summary>
|
||||
[WireContract]
|
||||
public class RuleSubmissionFinding
|
||||
{
|
||||
/// <summary>"error" | "warning" | "info".</summary>
|
||||
public string Level { get; set; } = default!;
|
||||
public string Message { get; set; } = default!;
|
||||
}
|
||||
|
||||
/// <summary>Fire telemetry of the submitted rule in the submitting tenant over the trailing window.</summary>
|
||||
[WireContract]
|
||||
public class RuleSubmissionFireStats
|
||||
{
|
||||
public int Days { get; set; }
|
||||
public int FireCount { get; set; }
|
||||
public int SessionsEvaluated { get; set; }
|
||||
public int EvaluationCount { get; set; }
|
||||
}
|
||||
|
||||
public static class RuleSubmissionKinds
|
||||
{
|
||||
public const string Gather = "gather";
|
||||
public const string Analyze = "analyze";
|
||||
public static readonly string[] All = { Gather, Analyze };
|
||||
|
||||
public static bool IsKnown(string? kind)
|
||||
=> kind == Gather || kind == Analyze;
|
||||
}
|
||||
|
||||
public static class RuleSubmissionStatuses
|
||||
{
|
||||
public const string Pending = "pending";
|
||||
public const string Approved = "approved";
|
||||
public const string Declined = "declined";
|
||||
public const string Withdrawn = "withdrawn";
|
||||
|
||||
/// <summary>Derived at read time (approved + the published id exists in the global catalog); never stored.</summary>
|
||||
public const string Published = "published";
|
||||
|
||||
/// <summary>Every wire value, including the derived one.</summary>
|
||||
public static readonly string[] All = { Pending, Approved, Declined, Withdrawn, Published };
|
||||
|
||||
/// <summary>The values a row may carry.</summary>
|
||||
public static readonly string[] Stored = { Pending, Approved, Declined, Withdrawn };
|
||||
}
|
||||
|
||||
public static class RuleAttributionModes
|
||||
{
|
||||
public const string Anonymous = "anonymous";
|
||||
public const string Organization = "organization";
|
||||
public const string Person = "person";
|
||||
public static readonly string[] All = { Anonymous, Organization, Person };
|
||||
|
||||
/// <summary>The <c>author</c> text of an anonymously contributed rule.</summary>
|
||||
public const string AnonymousAuthor = "Community contribution";
|
||||
|
||||
public static bool IsKnown(string? mode)
|
||||
=> mode == Anonymous || mode == Organization || mode == Person;
|
||||
}
|
||||
|
||||
public static class RuleSubmissionDecisions
|
||||
{
|
||||
public const string Approve = "approve";
|
||||
public const string Decline = "decline";
|
||||
public static readonly string[] All = { Approve, Decline };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
"use client";
|
||||
|
||||
import { Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { api } from "@/lib/api";
|
||||
import { apiErrorText, fetchJson, jsonBody, nullOn404 } from "@/lib/apiClient";
|
||||
import TruncatedLabel from "@/components/TruncatedLabel";
|
||||
import { extractContinuation } from "@/lib/paginationLink";
|
||||
import { isGuid } from "@/utils/inputValidation";
|
||||
import { trackEvent } from "@/lib/appInsights";
|
||||
import { useCanMutatePlatform } from "@/hooks/useCanMutatePlatform";
|
||||
import { TableSkeleton } from "@/components/skeletons/TableSkeleton";
|
||||
import { SectionCardHeader } from "@/components/SectionCardHeader";
|
||||
import { ModalPortal } from "@/components/ModalPortal";
|
||||
import { submissionStatusBadge } from "@/components/rules/MySubmissionsList";
|
||||
import type {
|
||||
ReseedFromGitHubResponse,
|
||||
ReviewRuleSubmissionRequest,
|
||||
ReviewRuleSubmissionResponse,
|
||||
RuleSubmissionDetailResponse,
|
||||
RuleSubmissionFireStats,
|
||||
RuleSubmissionItem,
|
||||
RuleSubmissionListResponse,
|
||||
} from "@/utils/wire-types.generated";
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
const STATUS_FILTERS = ["pending", "approved", "declined", "withdrawn"] as const;
|
||||
|
||||
interface RuleSubmissionsSectionProps {
|
||||
getAccessToken: () => Promise<string | null>;
|
||||
setError: (error: string | null) => void;
|
||||
}
|
||||
|
||||
function CopyButton({ value, title = "Copy to clipboard" }: { value: string; title?: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const handleCopy = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
navigator.clipboard.writeText(value).then(() => {
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
});
|
||||
};
|
||||
return (
|
||||
<button onClick={handleCopy} title={title} className="ml-1.5 p-0.5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
|
||||
{copied ? (
|
||||
<svg className="w-3.5 h-3.5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusBadge({ status }: { status: string }) {
|
||||
const b = submissionStatusBadge(status);
|
||||
return <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${b.cls}`}>{b.label}</span>;
|
||||
}
|
||||
|
||||
function KindBadge({ kind }: { kind: string }) {
|
||||
const cls = kind === "analyze"
|
||||
? "bg-indigo-100 text-indigo-800 dark:bg-indigo-900/40 dark:text-indigo-300"
|
||||
: "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300";
|
||||
return <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${cls}`}>{kind === "analyze" ? "Analyze" : "Gather"}</span>;
|
||||
}
|
||||
|
||||
function fireStatsText(s: RuleSubmissionFireStats | undefined | null): string {
|
||||
if (!s) return "not available";
|
||||
return `fired ${s.fireCount}× in ${s.sessionsEvaluated} evaluated sessions (${s.days} days, ${s.evaluationCount} evaluations)`;
|
||||
}
|
||||
|
||||
export function RuleSubmissionsSection(props: RuleSubmissionsSectionProps) {
|
||||
// useSearchParams() needs a Suspense boundary for the static prerender.
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<RuleSubmissionsSectionInner {...props} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function RuleSubmissionsSectionInner({ getAccessToken, setError }: RuleSubmissionsSectionProps) {
|
||||
// Decisions and the reseed are GA-only (GlobalAdminOnly routes); a Global Reader may look.
|
||||
const canMutate = useCanMutatePlatform();
|
||||
const [items, setItems] = useState<RuleSubmissionItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [detail, setDetail] = useState<RuleSubmissionDetailResponse | null>(null);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
|
||||
const [tenantFilterInput, setTenantFilterInput] = useState("");
|
||||
const [tenantFilterApplied, setTenantFilterApplied] = useState<string | undefined>(undefined);
|
||||
const [statusFilter, setStatusFilter] = useState<string>("");
|
||||
const [continuation, setContinuation] = useState<string | null>(null);
|
||||
const [nextLink, setNextLink] = useState<string | null>(null);
|
||||
const [continuationStack, setContinuationStack] = useState<Array<string | null>>([]);
|
||||
const [pageNumber, setPageNumber] = useState(1);
|
||||
|
||||
const openDetail = useCallback(async (submissionId: string) => {
|
||||
try {
|
||||
setDetailLoading(true);
|
||||
const data = await fetchJson<RuleSubmissionDetailResponse>(api.ruleSubmissions.detail(submissionId), getAccessToken);
|
||||
setDetail(data);
|
||||
} catch (err) {
|
||||
setError(apiErrorText(err, "Failed to load the submission"));
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [setError]);
|
||||
|
||||
// Deep link from the GA notification: ?submissionId=… opens the detail straight from the
|
||||
// detail endpoint — no dependency on the row being on the first page.
|
||||
const searchParams = useSearchParams();
|
||||
const submissionIdParam = searchParams?.get("submissionId") ?? null;
|
||||
const autoOpenConsumed = useRef(false);
|
||||
useEffect(() => {
|
||||
if (autoOpenConsumed.current || !submissionIdParam) return;
|
||||
autoOpenConsumed.current = true;
|
||||
const run = async () => { await openDetail(submissionIdParam); };
|
||||
void run();
|
||||
}, [submissionIdParam, openDetail]);
|
||||
|
||||
const fetchPage = useCallback(async (cursor: string | null, filterTenantId: string | undefined, status: string) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await fetchJson<RuleSubmissionListResponse>(
|
||||
api.ruleSubmissions.list({ tenantId: filterTenantId, status: status || undefined, pageSize: PAGE_SIZE, continuation: cursor ?? undefined }),
|
||||
getAccessToken,
|
||||
).catch(nullOn404);
|
||||
setItems(data?.submissions ?? []);
|
||||
setNextLink(data?.nextLink ?? null);
|
||||
} catch (err) {
|
||||
setError(apiErrorText(err, "Failed to load rule submissions"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
// getAccessToken churns on every MSAL refresh — see SessionReportsSection.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [setError]);
|
||||
|
||||
useEffect(() => {
|
||||
const run = async () => {
|
||||
setContinuation(null);
|
||||
setContinuationStack([]);
|
||||
setPageNumber(1);
|
||||
await fetchPage(null, tenantFilterApplied, statusFilter);
|
||||
};
|
||||
void run();
|
||||
}, [tenantFilterApplied, statusFilter, fetchPage]);
|
||||
|
||||
const handleApplyTenantFilter = () => {
|
||||
const trimmed = tenantFilterInput.trim();
|
||||
if (trimmed && !isGuid(trimmed)) {
|
||||
setError("Tenant ID must be a valid GUID");
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setTenantFilterApplied(trimmed || undefined);
|
||||
};
|
||||
|
||||
const handleNextPage = () => {
|
||||
const nextCont = extractContinuation(nextLink);
|
||||
if (!nextCont) return;
|
||||
setContinuationStack((stack) => [...stack, continuation]);
|
||||
setContinuation(nextCont);
|
||||
setPageNumber((n) => n + 1);
|
||||
void fetchPage(nextCont, tenantFilterApplied, statusFilter);
|
||||
};
|
||||
|
||||
const handlePrevPage = () => {
|
||||
if (continuationStack.length === 0) return;
|
||||
const prev = continuationStack[continuationStack.length - 1];
|
||||
setContinuationStack((stack) => stack.slice(0, -1));
|
||||
setContinuation(prev ?? null);
|
||||
setPageNumber((n) => Math.max(1, n - 1));
|
||||
void fetchPage(prev ?? null, tenantFilterApplied, statusFilter);
|
||||
};
|
||||
|
||||
const handleRefresh = () => fetchPage(continuation, tenantFilterApplied, statusFilter);
|
||||
|
||||
const handleReviewed = (updated: RuleSubmissionItem) => {
|
||||
setItems((prev) => prev.map((s) => (s.submissionId === updated.submissionId ? updated : s)));
|
||||
void openDetail(updated.submissionId);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-gradient-to-br from-indigo-50 to-purple-50 dark:from-gray-800 dark:to-gray-800 border-2 border-indigo-300 dark:border-indigo-700 rounded-lg shadow-lg">
|
||||
<SectionCardHeader
|
||||
tone="adminIndigoPurple"
|
||||
iconPath="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
title="Rule Submissions"
|
||||
subtitle="Custom rules submitted by Tenant Admins for the community pool"
|
||||
/>
|
||||
|
||||
{/* Filters + refresh */}
|
||||
<div className="px-6 pt-4 pb-2 flex items-center gap-2 flex-wrap">
|
||||
<span className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide">Filter:</span>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Tenant ID (GUID)"
|
||||
value={tenantFilterInput}
|
||||
onChange={(e) => setTenantFilterInput(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === "Enter") handleApplyTenantFilter(); }}
|
||||
className="w-72 px-2 py-1 text-xs font-mono border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-green-500 focus:border-green-500"
|
||||
/>
|
||||
<button onClick={handleApplyTenantFilter} disabled={loading} className="px-2.5 py-1 text-xs font-medium rounded-md border border-indigo-300 dark:border-indigo-700 text-indigo-700 dark:text-indigo-300 hover:bg-indigo-100 dark:hover:bg-indigo-900/40 disabled:opacity-40 transition-colors">
|
||||
Apply
|
||||
</button>
|
||||
{tenantFilterApplied && (
|
||||
<button onClick={() => { setTenantFilterInput(""); setTenantFilterApplied(undefined); }} disabled={loading} className="px-2.5 py-1 text-xs font-medium rounded-md border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-40 transition-colors">
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-green-500 focus:border-green-500"
|
||||
>
|
||||
<option value="">All statuses</option>
|
||||
{STATUS_FILTERS.map((s) => <option key={s} value={s}>{submissionStatusBadge(s).label}</option>)}
|
||||
</select>
|
||||
<button onClick={handleRefresh} disabled={loading} className="ml-auto px-2.5 py-1 text-xs font-medium rounded-md border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-40 transition-colors">
|
||||
{loading ? "Loading..." : "Refresh"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<div className="p-6 pt-2">
|
||||
{loading && items.length === 0 ? (
|
||||
<TableSkeleton columns={8} rows={6} />
|
||||
) : items.length === 0 ? (
|
||||
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
|
||||
<p className="text-sm">No rule submissions{statusFilter ? ` with status "${statusFilter}"` : " yet"}.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<thead className="bg-gray-50 dark:bg-gray-700/50">
|
||||
<tr>
|
||||
{["ID", "Date", "Kind", "Rule", "Tenant", "Submitted By", "Credit", "Status", "Comment"].map((h) => (
|
||||
<th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{h}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
|
||||
{items.map((s) => (
|
||||
<tr key={s.submissionId} onClick={() => openDetail(s.submissionId)} className="hover:bg-indigo-50 dark:hover:bg-indigo-900/20 cursor-pointer transition-colors">
|
||||
<td className="px-4 py-3 text-sm font-mono text-gray-900 dark:text-gray-100 whitespace-nowrap">
|
||||
<span className="inline-flex items-center">{s.submissionId}<CopyButton value={s.submissionId} /></span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-100 whitespace-nowrap">{new Date(s.submittedAt).toLocaleString()}</td>
|
||||
<td className="px-4 py-3 text-sm whitespace-nowrap"><KindBadge kind={s.ruleKind} /></td>
|
||||
<td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-100 max-w-xs">
|
||||
<span className="font-mono text-xs">{s.sourceRuleId}</span>
|
||||
<TruncatedLabel interactive={false} text={s.title} className="block text-xs text-gray-500 dark:text-gray-400" />
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm font-mono text-gray-700 dark:text-gray-300">{s.tenantId.slice(0, 8)}...</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{s.submittedBy}</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{s.attributionName}</td>
|
||||
<td className="px-4 py-3 text-sm whitespace-nowrap"><StatusBadge status={s.status} /></td>
|
||||
<td className="px-4 py-3 max-w-xs">
|
||||
{s.comment
|
||||
? <TruncatedLabel interactive={false} text={s.comment} className="block text-sm text-gray-700 dark:text-gray-300" />
|
||||
: <span className="text-sm text-gray-400 italic">no comment</span>}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<div className="flex items-center justify-between border-t border-gray-200 dark:border-gray-700 px-4 py-3 bg-gray-50 dark:bg-gray-700/50 rounded-b-md">
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">{items.length} on page {pageNumber}{nextLink ? "" : " (last)"}</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button onClick={handlePrevPage} disabled={continuationStack.length === 0 || loading} className="px-2.5 py-1 text-xs font-medium rounded-md border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-40 disabled:cursor-not-allowed transition-colors">Previous</button>
|
||||
<button onClick={handleNextPage} disabled={!nextLink || loading} className="px-2.5 py-1 text-xs font-medium rounded-md border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-40 disabled:cursor-not-allowed transition-colors">Next</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(detail || detailLoading) && (
|
||||
<SubmissionDetailModal
|
||||
detail={detail}
|
||||
loading={detailLoading}
|
||||
canMutate={canMutate}
|
||||
getAccessToken={getAccessToken}
|
||||
onClose={() => setDetail(null)}
|
||||
onReviewed={handleReviewed}
|
||||
onReload={(id) => openDetail(id)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Detail modal ──────────────────────────────────────────────────────────
|
||||
|
||||
function SubmissionDetailModal({
|
||||
detail, loading, canMutate, getAccessToken, onClose, onReviewed, onReload,
|
||||
}: {
|
||||
detail: RuleSubmissionDetailResponse | null;
|
||||
loading: boolean;
|
||||
canMutate: boolean;
|
||||
getAccessToken: () => Promise<string | null>;
|
||||
onClose: () => void;
|
||||
onReviewed: (updated: RuleSubmissionItem) => void;
|
||||
onReload: (submissionId: string) => void;
|
||||
}) {
|
||||
const s = detail?.submission ?? null;
|
||||
const [publishedRuleId, setPublishedRuleId] = useState("");
|
||||
const [reviewComment, setReviewComment] = useState("");
|
||||
const [willBeAdapted, setWillBeAdapted] = useState(false);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
|
||||
const [showRepoFile, setShowRepoFile] = useState(false);
|
||||
|
||||
// Seed the decision form from the loaded submission (adjust-during-render on identity change).
|
||||
const [seededFor, setSeededFor] = useState<string | null>(null);
|
||||
if (s && seededFor !== s.submissionId + s.status) {
|
||||
setSeededFor(s.submissionId + s.status);
|
||||
setPublishedRuleId(s.publishedRuleId ?? detail?.suggestedPublishedRuleId ?? "");
|
||||
setReviewComment(s.reviewComment ?? "");
|
||||
setWillBeAdapted(s.willBeAdapted);
|
||||
setMessage(null);
|
||||
}
|
||||
|
||||
const rule = detail?.analyzeRule ?? detail?.gatherRule ?? null;
|
||||
const ruleJson = rule ? JSON.stringify(rule, null, 2) : "";
|
||||
const decidable = !!s && (s.status === "pending" || s.status === "approved");
|
||||
|
||||
const review = async (decision: "approve" | "decline") => {
|
||||
if (!s) return;
|
||||
try {
|
||||
setBusy(decision);
|
||||
setMessage(null);
|
||||
const data = await fetchJson<ReviewRuleSubmissionResponse>(
|
||||
api.ruleSubmissions.review(s.submissionId),
|
||||
getAccessToken,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: jsonBody<ReviewRuleSubmissionRequest>({
|
||||
decision,
|
||||
reviewComment: reviewComment.trim() || undefined,
|
||||
willBeAdapted: decision === "approve" ? willBeAdapted : undefined,
|
||||
publishedRuleId: decision === "approve" ? publishedRuleId.trim() : undefined,
|
||||
}),
|
||||
},
|
||||
);
|
||||
trackEvent("rule_submission_reviewed", { decision, kind: s.ruleKind });
|
||||
setMessage({ kind: "ok", text: data.message });
|
||||
onReviewed(data.submission);
|
||||
} catch (err) {
|
||||
setMessage({ kind: "error", text: apiErrorText(err, "Review failed") });
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const reseed = async () => {
|
||||
if (!s) return;
|
||||
try {
|
||||
setBusy("reseed");
|
||||
setMessage(null);
|
||||
const type = s.ruleKind === "analyze" ? "analyze" : "gather";
|
||||
const data = await fetchJson<ReseedFromGitHubResponse>(api.rules.reseedFromGitHub(type), getAccessToken, { method: "POST" });
|
||||
const counts = type === "analyze" ? data.analyze : data.gather;
|
||||
setMessage({ kind: "ok", text: `Reseeded ${type} rules from GitHub: ${counts?.written ?? 0} written, ${counts?.deleted ?? 0} deleted.` });
|
||||
onReload(s.submissionId);
|
||||
} catch (err) {
|
||||
setMessage({ kind: "error", text: apiErrorText(err, "Reseed failed") });
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const downloadRepoFile = () => {
|
||||
if (!detail?.repoFile) return;
|
||||
const blob = new Blob([detail.repoFile.content], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = detail.repoFile.path.split("/").pop() ?? "rule.json";
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
return (
|
||||
<ModalPortal>
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" onClick={onClose}>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-3xl w-full max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="p-6">
|
||||
{!s ? (
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">{loading ? "Loading submission..." : "Submission not found."}</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center justify-between mb-4 gap-3">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Rule submission</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusBadge status={s.status} />
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-mono bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300">
|
||||
{s.submissionId}<CopyButton value={s.submissionId} />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className={`mb-4 p-3 rounded-lg text-sm ${message.kind === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-700 border border-red-200"}`}>
|
||||
{message.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3 text-sm">
|
||||
<div>
|
||||
<dt className="font-medium text-gray-500 dark:text-gray-400">Rule</dt>
|
||||
<dd className="mt-0.5 text-gray-900 dark:text-gray-100"><KindBadge kind={s.ruleKind} /> <span className="font-mono">{s.sourceRuleId}</span> — {s.title} <span className="text-gray-500">({s.category})</span></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium text-gray-500 dark:text-gray-400">Tenant</dt>
|
||||
<dd className="mt-0.5 font-mono text-gray-900 dark:text-gray-100 flex items-center">{s.tenantId}<CopyButton value={s.tenantId} /></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium text-gray-500 dark:text-gray-400">Submitted by</dt>
|
||||
<dd className="mt-0.5 text-gray-900 dark:text-gray-100">{s.submittedByName} <span className="text-gray-500">({s.submittedBy})</span> · {new Date(s.submittedAt).toLocaleString()}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium text-gray-500 dark:text-gray-400">Credit in the published rule</dt>
|
||||
<dd className="mt-0.5 text-gray-900 dark:text-gray-100">{s.attributionName} <span className="text-gray-500">({s.attributionMode})</span></dd>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<dt className="font-medium text-gray-500 dark:text-gray-400">Comment</dt>
|
||||
<dd className="mt-0.5 text-gray-900 dark:text-gray-100 whitespace-pre-wrap">{s.comment || <span className="text-gray-400 italic">no comment</span>}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium text-gray-500 dark:text-gray-400">Fire stats in the submitting tenant</dt>
|
||||
<dd className="mt-0.5 text-gray-900 dark:text-gray-100 text-xs">
|
||||
<div>At submit: {fireStatsText(s.sourceFireStats)}</div>
|
||||
<div>Now: {fireStatsText(detail?.liveFireStats)}</div>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium text-gray-500 dark:text-gray-400">Pre-flight findings</dt>
|
||||
<dd className="mt-0.5 text-xs">
|
||||
{s.validationFindings.length === 0
|
||||
? <span className="text-green-700">none</span>
|
||||
: <ul className="space-y-0.5">{s.validationFindings.map((f, i) => <li key={i} className={f.level === "warning" ? "text-amber-700" : "text-gray-600 dark:text-gray-300"}>{f.message}</li>)}</ul>}
|
||||
{s.derivedFromTemplateRuleId && <div className="text-gray-500 mt-0.5">Derived from template <span className="font-mono">{s.derivedFromTemplateRuleId}</span></div>}
|
||||
</dd>
|
||||
</div>
|
||||
{(s.reviewedBy || s.reviewComment) && (
|
||||
<div className="sm:col-span-2">
|
||||
<dt className="font-medium text-gray-500 dark:text-gray-400">Review</dt>
|
||||
<dd className="mt-0.5 text-gray-900 dark:text-gray-100 text-xs">
|
||||
{s.reviewedBy} · {s.reviewedAt ? new Date(s.reviewedAt).toLocaleString() : ""}
|
||||
{s.publishedRuleId && <> · publishes as <span className="font-mono">{s.publishedRuleId}</span></>}
|
||||
{s.willBeAdapted && <> · will be adapted</>}
|
||||
{s.reviewComment && <div className="whitespace-pre-wrap mt-0.5">{s.reviewComment}</div>}
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
|
||||
{/* Frozen rule */}
|
||||
<div className="mt-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-gray-500 dark:text-gray-400">Submitted rule (frozen at submit time)</span>
|
||||
<CopyButton value={ruleJson} title="Copy rule JSON" />
|
||||
</div>
|
||||
<pre className="mt-1 max-h-64 overflow-auto text-xs font-mono bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded p-3 text-gray-800 dark:text-gray-200">{ruleJson}</pre>
|
||||
</div>
|
||||
|
||||
{/* Repo file */}
|
||||
{detail?.repoFile && (
|
||||
<div className="mt-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-sm font-medium text-gray-500 dark:text-gray-400">
|
||||
Repo file · <span className="font-mono text-xs">{detail.repoFile.path}</span>
|
||||
{!s.publishedRuleId && detail.suggestedPublishedRuleId && <span className="text-xs text-gray-400"> (suggested id)</span>}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<button onClick={() => setShowRepoFile((v) => !v)} className="text-xs text-indigo-600 hover:text-indigo-800">{showRepoFile ? "Hide" : "Show"}</button>
|
||||
<CopyButton value={detail.repoFile.content} title="Copy file content" />
|
||||
<button onClick={downloadRepoFile} className="text-xs text-indigo-600 hover:text-indigo-800">Download</button>
|
||||
</span>
|
||||
</div>
|
||||
{showRepoFile && (
|
||||
<pre className="mt-1 max-h-64 overflow-auto text-xs font-mono bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded p-3 text-gray-800 dark:text-gray-200">{detail.repoFile.content}</pre>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Decision */}
|
||||
{canMutate && decidable && (
|
||||
<div className="mt-5 pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Decision</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">Published rule id (approve)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={publishedRuleId}
|
||||
onChange={(e) => setPublishedRuleId(e.target.value.toUpperCase())}
|
||||
disabled={s.status !== "pending"}
|
||||
className="w-full px-2 py-1.5 text-sm font-mono border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 disabled:opacity-60"
|
||||
/>
|
||||
<label className="mt-2 flex items-center gap-2 text-xs text-gray-700 dark:text-gray-300">
|
||||
<input type="checkbox" checked={willBeAdapted} onChange={(e) => setWillBeAdapted(e.target.checked)} disabled={s.status !== "pending"} className="h-4 w-4 text-green-600 border-gray-300 rounded" />
|
||||
I will adapt the rule before publishing
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">Note to the submitter (required to decline)</label>
|
||||
<textarea
|
||||
value={reviewComment}
|
||||
onChange={(e) => setReviewComment(e.target.value)}
|
||||
rows={3}
|
||||
maxLength={4000}
|
||||
className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
{s.status === "pending" && (
|
||||
<button onClick={() => review("approve")} disabled={!!busy || !publishedRuleId.trim()} className="px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white rounded-md text-sm font-medium transition-colors">
|
||||
{busy === "approve" ? "Approving..." : "Approve"}
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => review("decline")} disabled={!!busy || !reviewComment.trim()} className="px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-red-300 text-white rounded-md text-sm font-medium transition-colors">
|
||||
{busy === "decline" ? "Declining..." : "Decline"}
|
||||
</button>
|
||||
{s.status === "approved" && (
|
||||
<button onClick={reseed} disabled={!!busy} className="ml-auto px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400 text-white rounded-md text-sm font-medium transition-colors" title="After the repo file is committed and pushed: pull rules/dist from GitHub into the global catalog">
|
||||
{busy === "reseed" ? "Reseeding..." : `Reseed ${s.ruleKind} rules now`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-6 flex justify-end">
|
||||
<button onClick={onClose} className="px-4 py-2 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-md hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors text-sm">Close</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalPortal>
|
||||
);
|
||||
}
|
||||
@@ -3,12 +3,14 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { type ReportsSectionId } from "../reportsNavSections";
|
||||
import { SectionSessionReports } from "../sections/SectionSessionReports";
|
||||
import { SectionRuleSubmissions } from "../sections/SectionRuleSubmissions";
|
||||
import { SectionDistressReports } from "../sections/SectionDistressReports";
|
||||
import { SectionUserFeedback } from "../sections/SectionUserFeedback";
|
||||
import { SectionSessionExport } from "../sections/SectionSessionExport";
|
||||
|
||||
const SECTION_COMPONENTS: Record<ReportsSectionId, React.ComponentType> = {
|
||||
"session-reports": SectionSessionReports,
|
||||
"rule-submissions": SectionRuleSubmissions,
|
||||
"distress-reports": SectionDistressReports,
|
||||
"user-feedback": SectionUserFeedback,
|
||||
"session-export": SectionSessionExport,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export const REPORTS_NAV_SECTIONS = [
|
||||
{ id: "session-reports", label: "Session Reports", description: "Sessions reported by Tenant Admins for analysis" },
|
||||
{ id: "rule-submissions", label: "Rule Submissions", description: "Custom rules submitted by Tenant Admins for the community pool" },
|
||||
{ id: "distress-reports", label: "Distress Reports", description: "Pre-auth agent distress signals (cert/whitelist/registration failures)" },
|
||||
{ id: "user-feedback", label: "User Feedback", description: "Product feedback from users" },
|
||||
{ id: "session-export", label: "Session Export", description: "Export session event data" },
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useAdminConfig } from "../../AdminConfigContext";
|
||||
import { RuleSubmissionsSection } from "../../components/RuleSubmissionsSection";
|
||||
import { AdminNotifications } from "../../AdminNotifications";
|
||||
|
||||
export function SectionRuleSubmissions() {
|
||||
const { getAccessToken, setError } = useAdminConfig();
|
||||
return (
|
||||
<>
|
||||
<AdminNotifications />
|
||||
<RuleSubmissionsSection getAccessToken={getAccessToken} setError={setError} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -38,6 +38,9 @@ import { DOCS_PATHS } from "@/lib/docsPaths";
|
||||
import { DocsLink } from "@/components/DocsLink";
|
||||
import type { CreateAnalyzeRuleFromTemplateRequest, RuleStatsResponse, TenantConfiguration } from "@/utils/wire-types.generated";
|
||||
import { fetchJson, jsonBody } from "@/lib/apiClient";
|
||||
import { CommunityContributionBox } from "@/components/rules/CommunityContributionBox";
|
||||
import { MySubmissionsList } from "@/components/rules/MySubmissionsList";
|
||||
import { SubmitRulesModal } from "@/components/rules/SubmitRulesModal";
|
||||
|
||||
export default function AnalyzeRulesPage() {
|
||||
const { user, getAccessToken } = useAuth();
|
||||
@@ -98,6 +101,9 @@ export default function AnalyzeRulesPage() {
|
||||
|
||||
// Tenant notification channels (for the per-rule notify target selector)
|
||||
const [tenantChannels, setTenantChannels] = useState<{ id: string; name: string }[]>([]);
|
||||
// Community submissions: the picker modal and a counter that reloads the status list after a submit.
|
||||
const [showSubmitModal, setShowSubmitModal] = useState(false);
|
||||
const [submissionsRefreshKey, setSubmissionsRefreshKey] = useState(0);
|
||||
|
||||
// Global admin tenant scope (tenant list, selector state, override/effective tenant)
|
||||
const scope = useGlobalAdminScope();
|
||||
@@ -412,7 +418,6 @@ export default function AnalyzeRulesPage() {
|
||||
confidenceFactors: form.confidenceFactors.filter(f => f.signal.trim()),
|
||||
remediation: form.remediation.filter(r => r.title.trim()),
|
||||
relatedDocs: form.relatedDocs.filter(d => d.title.trim() && d.url.trim()),
|
||||
author: user?.displayName || user?.upn || rule.author,
|
||||
version: bumpVersion(rule.version),
|
||||
};
|
||||
|
||||
@@ -458,6 +463,10 @@ export default function AnalyzeRulesPage() {
|
||||
};
|
||||
|
||||
const rulesList = rules || [];
|
||||
// Only the tenant's own custom rules can be contributed.
|
||||
const submittableRules = rulesList
|
||||
.filter((r) => !r.isBuiltIn && !r.isCommunity)
|
||||
.map((r) => ({ ruleId: r.ruleId, title: r.title, category: r.category }));
|
||||
|
||||
// Map: templateRuleId -> custom copy ruleId (for template rules that already have a tenant copy)
|
||||
const templateCopyMap = new Map<string, string>();
|
||||
@@ -600,18 +609,16 @@ export default function AnalyzeRulesPage() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{/* Community Contribution Hint */}
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start space-x-3">
|
||||
<svg className="w-5 h-5 text-blue-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<p className="text-sm text-blue-800">
|
||||
Missing a rule, found a bug, or have an improvement idea? Help make Autopilot Monitor better —{" "}
|
||||
<a href="https://github.com/okieselbach/AutopilotMonitor/issues" target="_blank" rel="noopener noreferrer" className="font-medium underline hover:text-blue-900">
|
||||
open a GitHub issue
|
||||
</a>.
|
||||
</p>
|
||||
</div>
|
||||
{/* Community contribution: submit own custom rules for the shared pool; the list shows their status. */}
|
||||
<CommunityContributionBox onContribute={!isReadOnly && submittableRules.length > 0 ? () => setShowSubmitModal(true) : undefined} />
|
||||
<MySubmissionsList
|
||||
kind="analyze"
|
||||
getAccessToken={getAccessToken}
|
||||
refreshKey={submissionsRefreshKey}
|
||||
overrideTenantId={isGlobalOverride ? effectiveTenantId : undefined}
|
||||
readOnly={isReadOnly}
|
||||
onError={showError}
|
||||
/>
|
||||
|
||||
{/* Summary Stats */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-6 gap-4">
|
||||
@@ -928,6 +935,17 @@ export default function AnalyzeRulesPage() {
|
||||
)}
|
||||
</main>
|
||||
|
||||
{/* Community submission picker — custom rules only; the backend freezes the rule itself. */}
|
||||
<SubmitRulesModal
|
||||
show={showSubmitModal}
|
||||
kind="analyze"
|
||||
rules={submittableRules}
|
||||
tenantId={effectiveTenantId ?? ""}
|
||||
defaultCreditName={user?.displayName || ""}
|
||||
getAccessToken={getAccessToken}
|
||||
onClose={() => setShowSubmitModal(false)}
|
||||
onSubmitted={() => setSubmissionsRefreshKey((k) => k + 1)}
|
||||
/>
|
||||
{/* Template Configuration Modal */}
|
||||
{configureTemplateRule && (
|
||||
<TemplateConfigModal
|
||||
|
||||
@@ -24,6 +24,9 @@ import { DOCS_PATHS } from "@/lib/docsPaths";
|
||||
import { DocsLink } from "@/components/DocsLink";
|
||||
import type { TenantFeatureFlagsResponse } from "@/utils/wire-types.generated";
|
||||
import { fetchJson } from "@/lib/apiClient";
|
||||
import { CommunityContributionBox } from "@/components/rules/CommunityContributionBox";
|
||||
import { MySubmissionsList } from "@/components/rules/MySubmissionsList";
|
||||
import { SubmitRulesModal } from "@/components/rules/SubmitRulesModal";
|
||||
|
||||
export default function GatherRulesPage() {
|
||||
const { user, getAccessToken } = useAuth();
|
||||
@@ -56,6 +59,9 @@ export default function GatherRulesPage() {
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const [newRule, setNewRule] = useState<NewRuleForm>({ ...EMPTY_FORM });
|
||||
const [creating, setCreating] = useState(false);
|
||||
// Community submissions: the picker modal and a counter that reloads the status list after a submit.
|
||||
const [showSubmitModal, setShowSubmitModal] = useState(false);
|
||||
const [submissionsRefreshKey, setSubmissionsRefreshKey] = useState(0);
|
||||
|
||||
// JSON mode (create + edit)
|
||||
const [jsonModeCreate, setJsonModeCreate] = useState(false);
|
||||
@@ -339,6 +345,10 @@ export default function GatherRulesPage() {
|
||||
|
||||
// Computed values
|
||||
const rulesList = rules || [];
|
||||
// Only the tenant's own custom rules can be contributed.
|
||||
const submittableRules = rulesList
|
||||
.filter((r) => !r.isBuiltIn && !r.isCommunity)
|
||||
.map((r) => ({ ruleId: r.ruleId, title: r.title, category: r.category }));
|
||||
const filteredRules = rulesList.filter((rule) => {
|
||||
if (searchQuery) {
|
||||
const q = searchQuery.toLowerCase().trim();
|
||||
@@ -433,18 +443,16 @@ export default function GatherRulesPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Community Contribution Hint */}
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start space-x-3">
|
||||
<svg className="w-5 h-5 text-blue-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<p className="text-sm text-blue-800">
|
||||
Missing a rule, found a bug, or have an improvement idea? Help make Autopilot Monitor better —{" "}
|
||||
<a href="https://github.com/okieselbach/AutopilotMonitor/issues" target="_blank" rel="noopener noreferrer" className="font-medium underline hover:text-blue-900">
|
||||
open a GitHub issue
|
||||
</a>.
|
||||
</p>
|
||||
</div>
|
||||
{/* Community contribution: submit own custom rules for the shared pool; the list shows their status. */}
|
||||
<CommunityContributionBox onContribute={!isReadOnly && submittableRules.length > 0 ? () => setShowSubmitModal(true) : undefined} />
|
||||
<MySubmissionsList
|
||||
kind="gather"
|
||||
getAccessToken={getAccessToken}
|
||||
refreshKey={submissionsRefreshKey}
|
||||
overrideTenantId={isGlobalOverride ? effectiveTenantId : undefined}
|
||||
readOnly={isReadOnly}
|
||||
onError={showError}
|
||||
/>
|
||||
|
||||
{/* Summary Stats */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
|
||||
@@ -669,6 +677,17 @@ export default function GatherRulesPage() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* Community submission picker — custom rules only; the backend freezes the rule itself. */}
|
||||
<SubmitRulesModal
|
||||
show={showSubmitModal}
|
||||
kind="gather"
|
||||
rules={submittableRules}
|
||||
tenantId={effectiveTenantId ?? ""}
|
||||
defaultCreditName={user?.displayName || ""}
|
||||
getAccessToken={getAccessToken}
|
||||
onClose={() => setShowSubmitModal(false)}
|
||||
onSubmitted={() => setSubmissionsRefreshKey((k) => k + 1)}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { LandingNavbar } from "../../components/landing/LandingNavbar";
|
||||
import { SiteFooter } from "../../components/SiteFooter";
|
||||
import { DOCS_URL } from "@/utils/config";
|
||||
|
||||
const LAST_UPDATED = "2 September 2026";
|
||||
const LAST_UPDATED = "9 September 2026";
|
||||
const DOCS_SECURITY_FAQ = `${DOCS_URL}/trust/security-faq`;
|
||||
const DOCS_DATA_FLOWS = `${DOCS_URL}/trust/data-flows`;
|
||||
|
||||
@@ -192,7 +192,7 @@ export default function PrivacyPage() {
|
||||
</p>
|
||||
<ul className="list-disc list-inside space-y-2 text-gray-700 ml-4">
|
||||
<li><strong>Product feedback</strong> you submitted — it is not tied to enrollment data and is what improves the product.</li>
|
||||
<li><strong>Custom rules and IME log patterns</strong> you authored are archived rather than deleted. Detection knowledge is what makes this product useful, so contributed rules and patterns are subject to entering the community pool — the next organization hitting the same enrollment failure gets a diagnosis instead of a mystery. A rule is a detection definition, not device data.</li>
|
||||
<li><strong>Custom rules and IME log patterns</strong> you authored are archived rather than deleted. Detection knowledge is what makes this product useful, so contributed rules and patterns are subject to entering the community pool — the next organization hitting the same enrollment failure gets a diagnosis instead of a mystery. A rule is a detection definition, not device data. When you submit a rule from the portal, it is published anonymously unless you choose a credit — your organization name or a name you enter — which then appears as the rule's author for every tenant.</li>
|
||||
</ul>
|
||||
<p className="text-gray-700">
|
||||
Either can be removed on request.
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { DocsLink } from "@/components/DocsLink";
|
||||
import { DOCS_PATHS } from "@/lib/docsPaths";
|
||||
|
||||
interface CommunityContributionBoxProps {
|
||||
/** Undefined hides the button (read-only roles, no custom rules yet). */
|
||||
onContribute?: () => void;
|
||||
}
|
||||
|
||||
/** The community call-to-action on the rule pages: contribute a rule here, report bugs on GitHub. */
|
||||
export function CommunityContributionBox({ onContribute }: CommunityContributionBoxProps) {
|
||||
return (
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 flex flex-col sm:flex-row sm:items-center gap-3">
|
||||
<div className="flex items-start space-x-3 flex-1">
|
||||
<svg className="w-5 h-5 text-blue-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<p className="text-sm text-blue-800">
|
||||
Built a rule that would help others? Contribute it to the community rule pool — you keep your copy and choose
|
||||
how you are credited (<DocsLink path={DOCS_PATHS.contributeRule} label="how it works" />). Bugs and ideas:{" "}
|
||||
<a href="https://github.com/okieselbach/AutopilotMonitor/issues" target="_blank" rel="noopener noreferrer" className="font-medium underline hover:text-blue-900">
|
||||
open a GitHub issue
|
||||
</a>.
|
||||
</p>
|
||||
</div>
|
||||
{onContribute && (
|
||||
<button
|
||||
onClick={onContribute}
|
||||
className="px-3 py-1.5 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors text-sm font-medium whitespace-nowrap flex-shrink-0"
|
||||
>
|
||||
Contribute a rule
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import { apiErrorText, fetchJson, fetchOk, nullOn404 } from "@/lib/apiClient";
|
||||
import type { RuleSubmissionItem, RuleSubmissionListResponse } from "@/utils/wire-types.generated";
|
||||
import type { SubmittableRuleKind } from "./SubmitRulesModal";
|
||||
|
||||
interface MySubmissionsListProps {
|
||||
kind: SubmittableRuleKind;
|
||||
getAccessToken: () => Promise<string | null>;
|
||||
/** Bumped by the page after a submit so the list reloads. */
|
||||
refreshKey: number;
|
||||
/** Global Admin override: read the foreign tenant's submissions through the operator list. */
|
||||
overrideTenantId?: string;
|
||||
/** Read-only callers cannot withdraw. */
|
||||
readOnly: boolean;
|
||||
onError: (message: string) => void;
|
||||
}
|
||||
|
||||
/** Status → badge classes from the existing palette; "published" reuses the Community green. */
|
||||
export function submissionStatusBadge(status: string): { label: string; cls: string } {
|
||||
switch (status) {
|
||||
case "pending": return { label: "Pending review", cls: "bg-amber-100 text-amber-800" };
|
||||
case "approved": return { label: "Approved", cls: "bg-blue-100 text-blue-800" };
|
||||
case "published": return { label: "Published", cls: "bg-green-100 text-green-700" };
|
||||
case "declined": return { label: "Declined", cls: "bg-red-100 text-red-800" };
|
||||
case "withdrawn": return { label: "Withdrawn", cls: "bg-gray-100 text-gray-600" };
|
||||
default: return { label: status, cls: "bg-gray-100 text-gray-600" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The tenant's own community submissions of one rule kind — a compact, collapsible list that
|
||||
* renders nothing while there is nothing to show, so pages without submissions stay unchanged.
|
||||
*/
|
||||
export function MySubmissionsList({ kind, getAccessToken, refreshKey, overrideTenantId, readOnly, onError }: MySubmissionsListProps) {
|
||||
const [items, setItems] = useState<RuleSubmissionItem[]>([]);
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
const [withdrawing, setWithdrawing] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const url = overrideTenantId
|
||||
? api.ruleSubmissions.list({ tenantId: overrideTenantId, pageSize: 200 })
|
||||
: api.ruleSubmissions.mine();
|
||||
const data = await fetchJson<RuleSubmissionListResponse>(url, getAccessToken).catch(nullOn404);
|
||||
setItems((data?.submissions ?? []).filter((s) => s.ruleKind === kind));
|
||||
} catch (err) {
|
||||
onError(apiErrorText(err, "Failed to load your community submissions"));
|
||||
}
|
||||
// getAccessToken churns on every MSAL refresh; the identity of onError is the page's setter.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [kind, overrideTenantId, refreshKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const run = async () => { await load(); };
|
||||
void run();
|
||||
}, [load]);
|
||||
|
||||
const handleWithdraw = async (submissionId: string) => {
|
||||
try {
|
||||
setWithdrawing(submissionId);
|
||||
await fetchOk(api.ruleSubmissions.withdraw(submissionId), getAccessToken, { method: "DELETE" });
|
||||
await load();
|
||||
} catch (err) {
|
||||
onError(apiErrorText(err, "Failed to withdraw the submission"));
|
||||
} finally {
|
||||
setWithdrawing(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (items.length === 0) return null;
|
||||
|
||||
const pending = items.filter((s) => s.status === "pending").length;
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow">
|
||||
<button
|
||||
onClick={() => setCollapsed((c) => !c)}
|
||||
className="w-full flex items-center justify-between px-4 py-3 text-left"
|
||||
>
|
||||
<span className="flex items-center gap-2 text-sm font-medium text-gray-900">
|
||||
<svg className={`w-4 h-4 text-gray-400 transition-transform ${collapsed ? "" : "rotate-90"}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
Community submissions
|
||||
<span className="text-xs font-normal text-gray-500">({items.length}{pending > 0 ? `, ${pending} pending` : ""})</span>
|
||||
</span>
|
||||
</button>
|
||||
{!collapsed && (
|
||||
<ul className="border-t border-gray-100 divide-y divide-gray-100">
|
||||
{items.map((s) => {
|
||||
const badge = submissionStatusBadge(s.status);
|
||||
const open = expandedId === s.submissionId;
|
||||
const hasDetail = !!s.reviewComment || s.willBeAdapted || !!s.publishedRuleId;
|
||||
return (
|
||||
<li key={s.submissionId} className="px-4 py-2 text-sm">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium flex-shrink-0 ${badge.cls}`}>{badge.label}</span>
|
||||
<span className="font-medium text-gray-900 truncate">{s.sourceRuleId}</span>
|
||||
<span className="text-gray-500 truncate hidden sm:inline">{s.title}</span>
|
||||
<span className="ml-auto font-mono text-xs text-gray-500 flex-shrink-0" title="Submission id">{s.submissionId}</span>
|
||||
<span className="text-xs text-gray-400 flex-shrink-0 hidden md:inline">{new Date(s.submittedAt).toLocaleDateString()}</span>
|
||||
{hasDetail && (
|
||||
<button onClick={() => setExpandedId(open ? null : s.submissionId)} className="text-xs text-indigo-600 hover:text-indigo-800 flex-shrink-0">
|
||||
{open ? "Hide" : "Details"}
|
||||
</button>
|
||||
)}
|
||||
{!readOnly && s.status === "pending" && (
|
||||
<button
|
||||
onClick={() => handleWithdraw(s.submissionId)}
|
||||
disabled={withdrawing === s.submissionId}
|
||||
className="text-xs text-gray-500 hover:text-red-600 disabled:opacity-50 flex-shrink-0"
|
||||
>
|
||||
{withdrawing === s.submissionId ? "Withdrawing..." : "Withdraw"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{open && (
|
||||
<div className="mt-2 ml-1 pl-3 border-l-2 border-gray-200 text-xs text-gray-700 space-y-1">
|
||||
{s.publishedRuleId && (
|
||||
<p>
|
||||
{s.status === "published"
|
||||
? <>Published as <span className="font-mono">{s.publishedRuleId}</span> — the community rule is live for every tenant; you can delete your custom copy if you no longer need it.</>
|
||||
: <>Will be published as <span className="font-mono">{s.publishedRuleId}</span>.</>}
|
||||
</p>
|
||||
)}
|
||||
{s.willBeAdapted && <p>The published rule will be adapted for the community before it ships.</p>}
|
||||
{s.reviewComment && <p className="whitespace-pre-wrap"><span className="text-gray-500">Reviewer:</span> {s.reviewComment}</p>}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { api } from "@/lib/api";
|
||||
import { apiErrorText, fetchJson, jsonBody } from "@/lib/apiClient";
|
||||
import { trackEvent } from "@/lib/appInsights";
|
||||
import { ModalPortal } from "@/components/ModalPortal";
|
||||
import type {
|
||||
RuleSubmissionItem,
|
||||
SubmitRuleSubmissionsRequest,
|
||||
SubmitRuleSubmissionsResponse,
|
||||
} from "@/utils/wire-types.generated";
|
||||
|
||||
/** The rule kinds a submission can carry (mirrors C# RuleSubmissionKinds). */
|
||||
export type SubmittableRuleKind = "gather" | "analyze";
|
||||
|
||||
/** The subset of a rule the picker needs. */
|
||||
export interface SubmittableRule {
|
||||
ruleId: string;
|
||||
title: string;
|
||||
category: string;
|
||||
}
|
||||
|
||||
interface SubmitRulesModalProps {
|
||||
show: boolean;
|
||||
kind: SubmittableRuleKind;
|
||||
/** The tenant's own custom rules of this kind (never built-in or community). */
|
||||
rules: SubmittableRule[];
|
||||
/** Body tenant — the JWT tenant, or the foreign tenant in a Global Admin override. */
|
||||
tenantId: string;
|
||||
/** Prefill for the personal credit; the submitter may edit it. */
|
||||
defaultCreditName: string;
|
||||
getAccessToken: () => Promise<string | null>;
|
||||
onClose: () => void;
|
||||
/** Called after a successful submit so the page can refresh its submissions list. */
|
||||
onSubmitted: (created: RuleSubmissionItem[]) => void;
|
||||
}
|
||||
|
||||
type AttributionMode = "anonymous" | "organization" | "person";
|
||||
|
||||
const MAX_ITEMS = 10;
|
||||
|
||||
/**
|
||||
* Picks one or more of the tenant's custom rules and submits them for the community pool. The
|
||||
* body carries rule references only — the backend freezes the rules — plus the comment and the
|
||||
* attribution choice, which is anonymous unless the submitter says otherwise.
|
||||
*/
|
||||
export function SubmitRulesModal({
|
||||
show, kind, rules, tenantId, defaultCreditName, getAccessToken, onClose, onSubmitted,
|
||||
}: SubmitRulesModalProps) {
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const [comment, setComment] = useState("");
|
||||
const [attributionMode, setAttributionMode] = useState<AttributionMode>("anonymous");
|
||||
const [creditName, setCreditName] = useState(defaultCreditName);
|
||||
const [consent, setConsent] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<RuleSubmissionItem[] | null>(null);
|
||||
|
||||
// Reset the form each time the modal opens (adjust-during-render, no effect).
|
||||
const [prevShow, setPrevShow] = useState(show);
|
||||
if (prevShow !== show) {
|
||||
setPrevShow(show);
|
||||
if (show) {
|
||||
setSelected(new Set());
|
||||
setComment("");
|
||||
setAttributionMode("anonymous");
|
||||
setCreditName(defaultCreditName);
|
||||
setConsent(false);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (!show) return null;
|
||||
|
||||
const toggle = (ruleId: string) => {
|
||||
setError(null);
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(ruleId)) next.delete(ruleId);
|
||||
else if (next.size < MAX_ITEMS) next.add(ruleId);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const canSubmit = selected.size > 0 && consent && !submitting
|
||||
&& (attributionMode !== "person" || creditName.trim().length > 0);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
const data = await fetchJson<SubmitRuleSubmissionsResponse>(
|
||||
api.ruleSubmissions.submit(),
|
||||
getAccessToken,
|
||||
{
|
||||
method: "POST",
|
||||
body: jsonBody<SubmitRuleSubmissionsRequest>({
|
||||
tenantId,
|
||||
items: Array.from(selected).map((ruleId) => ({ kind, ruleId })),
|
||||
comment: comment.trim() || undefined,
|
||||
attributionMode,
|
||||
attributionName: attributionMode === "person" ? creditName.trim() : undefined,
|
||||
}),
|
||||
},
|
||||
);
|
||||
trackEvent("rule_submission_submitted", { kind, count: data.submissions.length, attributionMode });
|
||||
setResult(data.submissions);
|
||||
onSubmitted(data.submissions);
|
||||
} catch (err) {
|
||||
setError(apiErrorText(err, "Failed to submit"));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const kindLabel = kind === "analyze" ? "analyze" : "gather";
|
||||
|
||||
return (
|
||||
<ModalPortal>
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" onClick={onClose}>
|
||||
<div
|
||||
className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-lg w-full max-h-[90vh] overflow-y-auto"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="p-6">
|
||||
<div className="flex items-center mb-4">
|
||||
<div className="flex-shrink-0 w-12 h-12 bg-green-100 dark:bg-green-900/40 rounded-full flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-green-600 dark:text-green-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div className="ml-4">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Contribute to the community</h3>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">Custom {kindLabel} rules of this tenant</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{result ? (
|
||||
<div>
|
||||
<div className="mb-4 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
|
||||
<p className="text-sm font-semibold text-green-800 dark:text-green-300">
|
||||
{result.length === 1 ? "Rule submitted for review" : `${result.length} rules submitted for review`}
|
||||
</p>
|
||||
<p className="text-sm text-green-700 dark:text-green-400 mt-0.5">
|
||||
You will see the decision on this page. Keep the submission id if you want to ask about it.
|
||||
</p>
|
||||
</div>
|
||||
<ul className="space-y-2 text-sm">
|
||||
{result.map((s) => (
|
||||
<li key={s.submissionId} className="border border-gray-200 dark:border-gray-700 rounded-md px-3 py-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100 truncate">{s.sourceRuleId}</span>
|
||||
<span className="font-mono text-xs text-gray-600 dark:text-gray-300">{s.submissionId}</span>
|
||||
</div>
|
||||
{s.validationFindings.length > 0 && (
|
||||
<ul className="mt-1 space-y-0.5">
|
||||
{s.validationFindings.map((f, i) => (
|
||||
<li key={i} className={`text-xs ${f.level === "warning" ? "text-amber-700 dark:text-amber-400" : "text-gray-500 dark:text-gray-400"}`}>
|
||||
{f.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="mt-6 flex justify-end">
|
||||
<button onClick={onClose} className="px-4 py-2 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-md hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors text-sm">
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-gray-700 dark:text-gray-300 mb-4">
|
||||
Submitted rules are reviewed by the Autopilot Monitor team and, if accepted, published as community
|
||||
rules for every tenant. Your own copy stays untouched. A rule may be adapted before it ships.
|
||||
</p>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-700 dark:text-red-400 whitespace-pre-wrap">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rule picker */}
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Rules <span className="text-gray-400">({selected.size} of {rules.length} selected, max {MAX_ITEMS})</span>
|
||||
</label>
|
||||
{rules.length === 0 ? (
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 italic">This tenant has no custom {kindLabel} rules yet.</p>
|
||||
) : (
|
||||
<div className="max-h-48 overflow-y-auto border border-gray-200 dark:border-gray-700 rounded-md divide-y divide-gray-100 dark:divide-gray-700">
|
||||
{rules.map((r) => (
|
||||
<label key={r.ruleId} className="flex items-center gap-3 px-3 py-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.has(r.ruleId)}
|
||||
onChange={() => toggle(r.ruleId)}
|
||||
disabled={submitting}
|
||||
className="h-4 w-4 text-green-600 border-gray-300 rounded focus:ring-green-500"
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm text-gray-900 dark:text-gray-100 truncate">{r.title}</span>
|
||||
<span className="block text-xs font-mono text-gray-500 dark:text-gray-400">{r.ruleId} · {r.category}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Comment */}
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Comment <span className="text-gray-400">(optional)</span>
|
||||
</label>
|
||||
<textarea
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
placeholder="What does the rule detect, and why is it useful for other organizations?"
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500"
|
||||
rows={3}
|
||||
maxLength={4000}
|
||||
disabled={submitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Attribution */}
|
||||
<fieldset className="mb-4">
|
||||
<legend className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Credit in the published rule</legend>
|
||||
<div className="space-y-1.5 text-sm">
|
||||
<label className="flex items-start gap-2 cursor-pointer">
|
||||
<input type="radio" name="attribution" checked={attributionMode === "anonymous"} onChange={() => setAttributionMode("anonymous")} disabled={submitting} className="mt-0.5 h-4 w-4 text-green-600 border-gray-300 focus:ring-green-500" />
|
||||
<span className="text-gray-800 dark:text-gray-200">Community contribution <span className="text-gray-400">(anonymous, default)</span></span>
|
||||
</label>
|
||||
<label className="flex items-start gap-2 cursor-pointer">
|
||||
<input type="radio" name="attribution" checked={attributionMode === "organization"} onChange={() => setAttributionMode("organization")} disabled={submitting} className="mt-0.5 h-4 w-4 text-green-600 border-gray-300 focus:ring-green-500" />
|
||||
<span className="text-gray-800 dark:text-gray-200">My organization <span className="text-gray-400">(the company name from the tenant settings)</span></span>
|
||||
</label>
|
||||
<label className="flex items-start gap-2 cursor-pointer">
|
||||
<input type="radio" name="attribution" checked={attributionMode === "person"} onChange={() => setAttributionMode("person")} disabled={submitting} className="mt-0.5 h-4 w-4 text-green-600 border-gray-300 focus:ring-green-500" />
|
||||
<span className="text-gray-800 dark:text-gray-200">A name of my choice</span>
|
||||
</label>
|
||||
{attributionMode === "person" && (
|
||||
<input
|
||||
type="text"
|
||||
value={creditName}
|
||||
onChange={(e) => setCreditName(e.target.value)}
|
||||
maxLength={64}
|
||||
placeholder="Name shown as the rule's author"
|
||||
className="ml-6 w-[calc(100%-1.5rem)] px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500"
|
||||
disabled={submitting}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1.5">
|
||||
The credit becomes the public <code className="text-xs">author</code> field of the rule and is visible to every tenant.
|
||||
</p>
|
||||
</fieldset>
|
||||
|
||||
{/* Consent */}
|
||||
<label className="flex items-start gap-2 text-sm cursor-pointer mb-2">
|
||||
<input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)} disabled={submitting} className="mt-0.5 h-4 w-4 text-green-600 border-gray-300 rounded focus:ring-green-500" />
|
||||
<span className="text-gray-700 dark:text-gray-300">
|
||||
I grant the non-exclusive, royalty-free right to include these detection definitions in the shared
|
||||
community rule pool as described in the{" "}
|
||||
<Link href="/terms" target="_blank" className="underline hover:text-gray-900 dark:hover:text-gray-100">Terms</Link>.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<div className="mt-6 flex items-center justify-end gap-2">
|
||||
<button onClick={onClose} disabled={submitting} className="px-4 py-2 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-md hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors text-sm">
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!canSubmit}
|
||||
className="px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-green-400 disabled:cursor-not-allowed text-white rounded-md transition-colors text-sm font-medium"
|
||||
>
|
||||
{submitting ? "Submitting..." : selected.size > 1 ? `Submit ${selected.size} rules` : "Submit rule"}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalPortal>
|
||||
);
|
||||
}
|
||||
@@ -480,6 +480,27 @@ export const api = {
|
||||
`${API_BASE_URL}/api/global/session-reports/${encodeURIComponent(reportId)}/note`,
|
||||
},
|
||||
|
||||
// ── Community rule submissions ─────────────────────────────────────────────
|
||||
ruleSubmissions: {
|
||||
// Tenant side: submit references to own custom rules, list own submissions, withdraw a pending one.
|
||||
submit: () => `${API_BASE_URL}/api/rules/submissions`,
|
||||
mine: () => `${API_BASE_URL}/api/rules/submissions`,
|
||||
withdraw: (submissionId: string) =>
|
||||
`${API_BASE_URL}/api/rules/submissions/${encodeURIComponent(submissionId)}`,
|
||||
// Operator side (Global Admin / Global Reader): cross-tenant list, detail, decision.
|
||||
list: (opts?: { tenantId?: string; status?: string; pageSize?: number; continuation?: string }) =>
|
||||
`${API_BASE_URL}/api/global/rule-submissions${qs({
|
||||
tenantId: opts?.tenantId,
|
||||
status: opts?.status,
|
||||
pageSize: opts?.pageSize?.toString(),
|
||||
continuation: opts?.continuation,
|
||||
})}`,
|
||||
detail: (submissionId: string) =>
|
||||
`${API_BASE_URL}/api/global/rule-submissions/${encodeURIComponent(submissionId)}`,
|
||||
review: (submissionId: string) =>
|
||||
`${API_BASE_URL}/api/global/rule-submissions/${encodeURIComponent(submissionId)}`,
|
||||
},
|
||||
|
||||
// ── Diag Files Reports (no session context) ───────────────────────────────
|
||||
diagFilesReports: {
|
||||
submit: () => `${API_BASE_URL}/api/diagnostics/files`,
|
||||
|
||||
@@ -31,6 +31,7 @@ export const DOCS_PATHS = {
|
||||
// Rules
|
||||
analyzeRules: "/rules/analyze-rules",
|
||||
gatherRules: "/rules/gather-rules",
|
||||
contributeRule: "/rules/contribute-a-rule",
|
||||
imeLogPatterns: "/rules/ime-log-patterns",
|
||||
// Portal pages (page-header "Docs" link)
|
||||
sessionDetails: "/portal-guide/session-details-and-diagnosis",
|
||||
|
||||
@@ -270,6 +270,7 @@ export const EXPANDABLE_NAV_GROUPS: ExpandableNavGroup[] = [
|
||||
id: "ga-reports", label: "Reports", icon: <DocumentTextIcon />,
|
||||
items: [
|
||||
{ id: "ga-session-reports", label: "Session Reports", href: route("/admin/reports/session-reports") },
|
||||
{ id: "ga-rule-submissions", label: "Rule Submissions", href: route("/admin/reports/rule-submissions") },
|
||||
{ id: "ga-distress-reports", label: "Distress Reports", href: route("/admin/reports/distress-reports") },
|
||||
{ id: "ga-user-feedback", label: "User Feedback", href: route("/admin/reports/user-feedback") },
|
||||
{ id: "ga-session-export", label: "Session Export", href: route("/admin/reports/session-export") },
|
||||
|
||||
@@ -94,6 +94,14 @@ const MCP_VOCABULARIES = [
|
||||
doc: "Session-annotation lanes (C# AnnotationLanes)." },
|
||||
{ section: "annotationVerdicts", constName: "ANNOTATION_VERDICTS", typeName: "AnnotationVerdict",
|
||||
doc: "Session-annotation verdicts (C# AnnotationVerdicts)." },
|
||||
{ section: "ruleSubmissionKinds", constName: "RULE_SUBMISSION_KINDS", typeName: "RuleSubmissionKind",
|
||||
doc: "Community rule submission kinds (C# RuleSubmissionKinds)." },
|
||||
{ section: "ruleSubmissionStatuses", constName: "RULE_SUBMISSION_STATUSES", typeName: "RuleSubmissionStatus",
|
||||
doc: "Effective rule submission statuses incl. the derived published (C# RuleSubmissionStatuses)." },
|
||||
{ section: "ruleAttributionModes", constName: "RULE_ATTRIBUTION_MODES", typeName: "RuleAttributionMode",
|
||||
doc: "How a contributed rule credits its author (C# RuleAttributionModes)." },
|
||||
{ section: "ruleSubmissionDecisions", constName: "RULE_SUBMISSION_DECISIONS", typeName: "RuleSubmissionDecision",
|
||||
doc: "Reviewer decisions on a rule submission (C# RuleSubmissionDecisions)." },
|
||||
{ section: "logSources", constName: "LOG_SOURCES", typeName: "LogSourceName",
|
||||
doc: "Telemetry stores behind the operator KQL proxy — query_backend_logs `source` (C# LogQuerySources)." },
|
||||
{ section: "apiErrorCodes", constName: "API_ERROR_CODES", typeName: "ApiErrorCode",
|
||||
|
||||
@@ -483,6 +483,26 @@ export const SHARED_MANIFEST = {
|
||||
"different_problem",
|
||||
"inconclusive"
|
||||
],
|
||||
"ruleSubmissionKinds": [
|
||||
"gather",
|
||||
"analyze"
|
||||
],
|
||||
"ruleSubmissionStatuses": [
|
||||
"pending",
|
||||
"approved",
|
||||
"declined",
|
||||
"withdrawn",
|
||||
"published"
|
||||
],
|
||||
"ruleAttributionModes": [
|
||||
"anonymous",
|
||||
"organization",
|
||||
"person"
|
||||
],
|
||||
"ruleSubmissionDecisions": [
|
||||
"approve",
|
||||
"decline"
|
||||
],
|
||||
"opsEventCategories": [
|
||||
"Consent",
|
||||
"Maintenance",
|
||||
|
||||
@@ -479,6 +479,26 @@
|
||||
"different_problem",
|
||||
"inconclusive"
|
||||
],
|
||||
"ruleSubmissionKinds": [
|
||||
"gather",
|
||||
"analyze"
|
||||
],
|
||||
"ruleSubmissionStatuses": [
|
||||
"pending",
|
||||
"approved",
|
||||
"declined",
|
||||
"withdrawn",
|
||||
"published"
|
||||
],
|
||||
"ruleAttributionModes": [
|
||||
"anonymous",
|
||||
"organization",
|
||||
"person"
|
||||
],
|
||||
"ruleSubmissionDecisions": [
|
||||
"approve",
|
||||
"decline"
|
||||
],
|
||||
"opsEventCategories": [
|
||||
"Consent",
|
||||
"Maintenance",
|
||||
@@ -15924,6 +15944,76 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"ReviewRuleSubmissionRequest": {
|
||||
"kind": "object",
|
||||
"doc": "Body of PATCH global/rule-submissions/{id}.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "decision",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"doc": "One of All."
|
||||
},
|
||||
{
|
||||
"name": "reviewComment",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"optional": true,
|
||||
"doc": "Shown to the submitter. Required for decline."
|
||||
},
|
||||
{
|
||||
"name": "willBeAdapted",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "boolean",
|
||||
"nullable": true
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "publishedRuleId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"optional": true,
|
||||
"doc": "Reserved-namespace id the rule ships under. Required for approve."
|
||||
}
|
||||
]
|
||||
},
|
||||
"ReviewRuleSubmissionResponse": {
|
||||
"kind": "object",
|
||||
"doc": "Success body of PATCH global/rule-submissions/{id}.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "success",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "boolean"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "submission",
|
||||
"type": {
|
||||
"kind": "ref",
|
||||
"name": "RuleSubmissionItem"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"RevokeTenantManagerRequest": {
|
||||
"kind": "object",
|
||||
"fields": [
|
||||
@@ -16918,6 +17008,373 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"RuleSubmissionDetailResponse": {
|
||||
"kind": "object",
|
||||
"doc": "Success body of GET global/rule-submissions/{id}: the submission, the frozen rule typed by kind (exactly one of the two rule properties is set), live fire stats, the suggested reserved id and the repo file built from the assigned (or suggested) id.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "success",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "boolean"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "submission",
|
||||
"type": {
|
||||
"kind": "ref",
|
||||
"name": "RuleSubmissionItem"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "analyzeRule",
|
||||
"type": {
|
||||
"kind": "ref",
|
||||
"name": "AnalyzeRule"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "gatherRule",
|
||||
"type": {
|
||||
"kind": "ref",
|
||||
"name": "GatherRule"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "liveFireStats",
|
||||
"type": {
|
||||
"kind": "ref",
|
||||
"name": "RuleSubmissionFireStats"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "suggestedPublishedRuleId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "repoFile",
|
||||
"type": {
|
||||
"kind": "ref",
|
||||
"name": "RuleSubmissionRepoFile"
|
||||
},
|
||||
"optional": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"RuleSubmissionFinding": {
|
||||
"kind": "object",
|
||||
"doc": "A pre-flight finding recorded at submit time. Errors block the submission and are never stored.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "level",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"doc": "\"error\" | \"warning\" | \"info\"."
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"RuleSubmissionFireStats": {
|
||||
"kind": "object",
|
||||
"doc": "Fire telemetry of the submitted rule in the submitting tenant over the trailing window.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "days",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "number"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fireCount",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "number"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sessionsEvaluated",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "number"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "evaluationCount",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "number"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"RuleSubmissionItem": {
|
||||
"kind": "object",
|
||||
"doc": "Wire shape of one submission (list rows, submit response, detail head). The frozen rule document is not part of it — the detail response carries it typed.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "submissionId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "batchId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "tenantId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "ruleKind",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sourceRuleId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "title",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "category",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "comment",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "submittedBy",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "submittedByName",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "attributionMode",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "attributionName",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "submittedAt",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"doc": "One of All — the effective status, published included."
|
||||
},
|
||||
{
|
||||
"name": "validationFindings",
|
||||
"type": {
|
||||
"kind": "array",
|
||||
"element": {
|
||||
"kind": "ref",
|
||||
"name": "RuleSubmissionFinding"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sourceFireStats",
|
||||
"type": {
|
||||
"kind": "ref",
|
||||
"name": "RuleSubmissionFireStats"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "reviewedBy",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "reviewedAt",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "reviewComment",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "willBeAdapted",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "boolean"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "publishedRuleId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "derivedFromTemplateRuleId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"optional": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"RuleSubmissionItemRef": {
|
||||
"kind": "object",
|
||||
"doc": "One rule reference in a submit request; the server freezes the rule itself.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "kind",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"doc": "One of All."
|
||||
},
|
||||
{
|
||||
"name": "ruleId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"RuleSubmissionListResponse": {
|
||||
"kind": "object",
|
||||
"doc": "Success body of GET rules/submissions and GET global/rule-submissions.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "success",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "boolean"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "count",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "number"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "submissions",
|
||||
"type": {
|
||||
"kind": "array",
|
||||
"element": {
|
||||
"kind": "ref",
|
||||
"name": "RuleSubmissionItem"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "nextLink",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"optional": true,
|
||||
"doc": "Absolute-path link to the next page; null/absent on the last page and in non-paged responses."
|
||||
}
|
||||
]
|
||||
},
|
||||
"RuleSubmissionRepoFile": {
|
||||
"kind": "object",
|
||||
"doc": "The repo-ready file for a submission: where it goes and what it contains.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "path",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"doc": "Repository-relative path, e.g. rules/analyze/ANALYZE-NET-002.json."
|
||||
},
|
||||
{
|
||||
"name": "content",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"RuleTrendPoint": {
|
||||
"kind": "object",
|
||||
"doc": "One day of a rule's trend (\"yyyy-MM-dd\").",
|
||||
@@ -19897,6 +20354,93 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"SubmitRuleSubmissionsRequest": {
|
||||
"kind": "object",
|
||||
"doc": "Body of POST rules/submissions: up to MaxItems of the caller's own custom rules.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "tenantId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "items",
|
||||
"type": {
|
||||
"kind": "array",
|
||||
"element": {
|
||||
"kind": "ref",
|
||||
"name": "RuleSubmissionItemRef"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "comment",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"optional": true
|
||||
},
|
||||
{
|
||||
"name": "attributionMode",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
},
|
||||
"doc": "One of All."
|
||||
},
|
||||
{
|
||||
"name": "attributionName",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"optional": true,
|
||||
"doc": "Credit text for the person mode; ignored for the other modes."
|
||||
}
|
||||
]
|
||||
},
|
||||
"SubmitRuleSubmissionsResponse": {
|
||||
"kind": "object",
|
||||
"doc": "Success body of POST rules/submissions.",
|
||||
"fields": [
|
||||
{
|
||||
"name": "success",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "boolean"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "batchId",
|
||||
"type": {
|
||||
"kind": "primitive",
|
||||
"name": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "submissions",
|
||||
"type": {
|
||||
"kind": "array",
|
||||
"element": {
|
||||
"kind": "ref",
|
||||
"name": "RuleSubmissionItem"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"SubmitSessionReportRequest": {
|
||||
"kind": "object",
|
||||
"doc": "Request to submit a session report for analysis by the Autopilot Monitor team. Sent as JSON from the frontend; the backend creates the ZIP and uploads to central storage.",
|
||||
|
||||
@@ -3439,6 +3439,24 @@ export interface RevertTenantConfigurationRequest {
|
||||
reason?: string | null;
|
||||
}
|
||||
|
||||
/** Body of PATCH global/rule-submissions/{id}. */
|
||||
export interface ReviewRuleSubmissionRequest {
|
||||
/** One of All. */
|
||||
decision: string;
|
||||
/** Shown to the submitter. Required for decline. */
|
||||
reviewComment?: string | null;
|
||||
willBeAdapted?: boolean | null;
|
||||
/** Reserved-namespace id the rule ships under. Required for approve. */
|
||||
publishedRuleId?: string | null;
|
||||
}
|
||||
|
||||
/** Success body of PATCH global/rule-submissions/{id}. */
|
||||
export interface ReviewRuleSubmissionResponse {
|
||||
success: boolean;
|
||||
message: string;
|
||||
submission: RuleSubmissionItem;
|
||||
}
|
||||
|
||||
export interface RevokeTenantManagerRequest {
|
||||
homeTenantId: string;
|
||||
}
|
||||
@@ -3668,6 +3686,82 @@ export interface RuleStatsSummary {
|
||||
period: RuleStatsPeriod;
|
||||
}
|
||||
|
||||
/** Success body of GET global/rule-submissions/{id}: the submission, the frozen rule typed by kind (exactly one of the two rule properties is set), live fire stats, the suggested reserved id and the repo file built from the assigned (or suggested) id. */
|
||||
export interface RuleSubmissionDetailResponse {
|
||||
success: boolean;
|
||||
submission: RuleSubmissionItem;
|
||||
analyzeRule?: AnalyzeRule;
|
||||
gatherRule?: GatherRule;
|
||||
liveFireStats?: RuleSubmissionFireStats;
|
||||
suggestedPublishedRuleId?: string;
|
||||
repoFile?: RuleSubmissionRepoFile;
|
||||
}
|
||||
|
||||
/** A pre-flight finding recorded at submit time. Errors block the submission and are never stored. */
|
||||
export interface RuleSubmissionFinding {
|
||||
/** "error" | "warning" | "info". */
|
||||
level: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** Fire telemetry of the submitted rule in the submitting tenant over the trailing window. */
|
||||
export interface RuleSubmissionFireStats {
|
||||
days: number;
|
||||
fireCount: number;
|
||||
sessionsEvaluated: number;
|
||||
evaluationCount: number;
|
||||
}
|
||||
|
||||
/** Wire shape of one submission (list rows, submit response, detail head). The frozen rule document is not part of it — the detail response carries it typed. */
|
||||
export interface RuleSubmissionItem {
|
||||
submissionId: string;
|
||||
batchId: string;
|
||||
tenantId: string;
|
||||
ruleKind: string;
|
||||
sourceRuleId: string;
|
||||
title: string;
|
||||
category: string;
|
||||
comment?: string;
|
||||
submittedBy: string;
|
||||
submittedByName: string;
|
||||
attributionMode: string;
|
||||
attributionName: string;
|
||||
submittedAt: string;
|
||||
/** One of All — the effective status, published included. */
|
||||
status: string;
|
||||
validationFindings: RuleSubmissionFinding[];
|
||||
sourceFireStats?: RuleSubmissionFireStats;
|
||||
reviewedBy?: string;
|
||||
reviewedAt?: string;
|
||||
reviewComment?: string;
|
||||
willBeAdapted: boolean;
|
||||
publishedRuleId?: string;
|
||||
derivedFromTemplateRuleId?: string;
|
||||
}
|
||||
|
||||
/** One rule reference in a submit request; the server freezes the rule itself. */
|
||||
export interface RuleSubmissionItemRef {
|
||||
/** One of All. */
|
||||
kind: string;
|
||||
ruleId: string;
|
||||
}
|
||||
|
||||
/** Success body of GET rules/submissions and GET global/rule-submissions. */
|
||||
export interface RuleSubmissionListResponse {
|
||||
success: boolean;
|
||||
count: number;
|
||||
submissions: RuleSubmissionItem[];
|
||||
/** Absolute-path link to the next page; null/absent on the last page and in non-paged responses. */
|
||||
nextLink?: string;
|
||||
}
|
||||
|
||||
/** The repo-ready file for a submission: where it goes and what it contains. */
|
||||
export interface RuleSubmissionRepoFile {
|
||||
/** Repository-relative path, e.g. rules/analyze/ANALYZE-NET-002.json. */
|
||||
path: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
/** One day of a rule's trend ("yyyy-MM-dd"). */
|
||||
export interface RuleTrendPoint {
|
||||
date: string;
|
||||
@@ -4317,6 +4411,25 @@ export interface SubmitOffboardingFeedbackRequest {
|
||||
comment?: string | null;
|
||||
}
|
||||
|
||||
/** Body of POST rules/submissions: up to MaxItems of the caller's own custom rules. */
|
||||
export interface SubmitRuleSubmissionsRequest {
|
||||
tenantId: string;
|
||||
items: RuleSubmissionItemRef[];
|
||||
comment?: string | null;
|
||||
/** One of All. */
|
||||
attributionMode: string;
|
||||
/** Credit text for the person mode; ignored for the other modes. */
|
||||
attributionName?: string | null;
|
||||
}
|
||||
|
||||
/** Success body of POST rules/submissions. */
|
||||
export interface SubmitRuleSubmissionsResponse {
|
||||
success: boolean;
|
||||
message: string;
|
||||
batchId: string;
|
||||
submissions: RuleSubmissionItem[];
|
||||
}
|
||||
|
||||
/** Request to submit a session report for analysis by the Autopilot Monitor team. Sent as JSON from the frontend; the backend creates the ZIP and uploads to central storage. */
|
||||
export interface SubmitSessionReportRequest {
|
||||
tenantId: string;
|
||||
|
||||
Reference in New Issue
Block a user