Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions e2e/mock-console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,10 +316,13 @@ export async function mockConsole(page: Page, role: ConsoleRole = 'administrator
await json({ entries: [{ id: 2, created_at: '2026-01-01T00:00:02Z', action: 'tenant.created', category: 'platform', actor: { kind: 'platform', username: 'platform' }, detail: 'business unit Retail created', unit: { id: 'unit-retail', name: 'Retail', slug: 'retail' } }], next_before: null }); return
}
if (parts.length === 1 && parts[0] === 'notifications' && method === 'GET') { await json({ destinations: [{ ...destination, id: 'platform-1', name: 'Platform pager' }], status: { deployment: 0, managed: 1, active: 1, locked: 0, key_state: 'ready' }, update_routing: platformRouting }); return }
if (parts.length === 2 && parts[0] === 'notifications' && parts[1] === 'update-routing' && method === 'PUT') {
const value = body() as { destinations?: string[] }
if (parts.length === 2 && parts[0] === 'notifications' && parts[1] === 'update-routing' && method === 'PATCH') {
const value = body() as { destination_id: string; enabled: boolean; password: string }
record('platform-update-routing', value)
platformRouting = { configured: true, destinations: value.destinations ?? [] }
const selected = new Set(platformRouting.configured ? platformRouting.destinations : [])
if (value.enabled) selected.add(value.destination_id)
else selected.delete(value.destination_id)
platformRouting = { configured: true, destinations: [...selected].sort() }
await json(platformRouting); return
}
if (parts.length === 1 && parts[0] === 'status' && method === 'GET') {
Expand Down Expand Up @@ -382,11 +385,14 @@ export async function mockConsole(page: Page, role: ConsoleRole = 'administrator
if (failures.delete('incident-suppress')) { await json(jsonError('incident-suppress'), 422); return }
await route.fulfill({ status: 204 }); return
}
if (path === '/notifications/update-routing' && method === 'PUT') {
const value = body() as { destinations?: string[] }
if (path === '/notifications/update-routing' && method === 'PATCH') {
const value = body() as { destination_id: string; enabled: boolean; password: string }
record('update-routing', value)
if (failures.delete('update-routing')) { await json(jsonError('update-routing'), 422); return }
updateRouting = { configured: true, destinations: value.destinations ?? [] }
const selected = new Set(updateRouting.configured ? updateRouting.destinations : ['dest-1'])
if (value.enabled) selected.add(value.destination_id)
else selected.delete(value.destination_id)
updateRouting = { configured: true, destinations: [...selected].sort() }
await json(updateRouting); return
}
if (path === '/notifications/destinations' && method === 'POST') { await mutate('notification-create', destination, 201); return }
Expand Down
5 changes: 4 additions & 1 deletion e2e/mutation-outcomes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ test('inline update notification toggles expose failure and success outcomes', a
await retryDialog.getByLabel('Account password').fill('fixture-password')
await retryDialog.getByRole('button', { name: 'Disable update alerts' }).click()
await expect(page.locator('.destination-feedback[role="status"]')).toContainText('Application update alerts disabled for Operations')
expect(controls.payloads['update-routing']).toHaveLength(2)
expect(controls.payloads['update-routing']).toEqual([
{ destination_id: 'dest-1', enabled: false, password: 'fixture-password' },
{ destination_id: 'dest-1', enabled: false, password: 'fixture-password' },
])
})

test('scanner profile validation exposes failure and success outcomes', async ({ page }, testInfo) => {
Expand Down
2 changes: 1 addition & 1 deletion e2e/platform-console.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ test('a platform administrator creates a unit, invites its administrator, recove
await routing.getByLabel('Account password').fill('fixture-password')
await routing.getByRole('button', { name: 'Enable update alerts' }).click()
await expect(page.getByRole('checkbox', { name: 'Disable update alerts for Platform pager' })).toBeChecked()
expect(controls.payloads['platform-update-routing']).toEqual([{ destinations: ['platform-1'], password: 'fixture-password' }])
expect(controls.payloads['platform-update-routing']).toEqual([{ destination_id: 'platform-1', enabled: true, password: 'fixture-password' }])

await page.getByRole('link', { name: 'Audit' }).click()
await expect(page.getByText('business unit Retail created')).toBeVisible()
Expand Down
16 changes: 15 additions & 1 deletion internal/web/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ func hostStoreNotFound(err error) bool {
type hostSummary struct {
Address string `json:"address"`
AddressFamily string `json:"address_family,omitempty"`
Visibility string `json:"visibility"`
SourceTargets []string `json:"source_targets,omitempty"`
DNSNames []string `json:"dns_names,omitempty"`
Protocols []hostProtocolSummary `json:"protocols,omitempty"`
Expand Down Expand Up @@ -521,7 +522,7 @@ func summaryForHost(host model.HostObservation, legacy bool) hostSummary {
// retained one protocol record per port chunk. Normalize the copy before
// calculating counts so legacy rows cannot render duplicate TCP/UDP chips.
dedupeHost(&host)
result := hostSummary{Address: host.Address, AddressFamily: host.AddressFamily, SourceTargets: append([]string(nil), host.SourceTargets...), DNSNames: append([]string(nil), host.DNSNames...), Legacy: legacy}
result := hostSummary{Address: host.Address, AddressFamily: host.AddressFamily, Visibility: hostVisibility(host.Address), SourceTargets: append([]string(nil), host.SourceTargets...), DNSNames: append([]string(nil), host.DNSNames...), Legacy: legacy}
for _, protocol := range host.Protocols {
summary := hostProtocolSummary{Protocol: protocol.Protocol, ScanType: protocol.ScanType, ScannedPorts: protocol.ScannedPorts, ScannedPortCount: protocol.ScannedPortCount, ServiceDetection: protocol.ServiceDetection}
for _, port := range protocol.Ports {
Expand All @@ -540,6 +541,19 @@ func summaryForHost(host model.HostObservation, legacy bool) hostSummary {
return result
}

// hostVisibility shares the RDAP special-use classification rather than
// duplicating an incomplete list of private address prefixes in the UI.
func hostVisibility(address string) string {
ip := net.ParseIP(address)
if ip == nil {
return "unknown"
}
if rdap.IsPrivateAddress(ip) {
return "non_public"
}
return "public"
}

func (s *Server) latestScannedHosts(ctx context.Context, ts *store.TenantStore) ([]allHostSummary, error) {
latest := make(map[string]allHostSummary)
archivedJobs := make(map[string]bool)
Expand Down
23 changes: 23 additions & 0 deletions internal/web/hosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -494,3 +494,26 @@ func TestSummaryForHostCollapsesChunkedProtocolObservations(t *testing.T) {
}
}
}

func TestSummaryForHostUsesRDAPSpecialUseVisibilityPolicy(t *testing.T) {
tests := []struct {
address string
want string
}{
{address: "8.8.8.8", want: "public"},
{address: "2001:4860:4860::8888", want: "public"},
{address: "100.64.0.1", want: "non_public"},
{address: "192.0.2.1", want: "non_public"},
{address: "198.18.0.1", want: "non_public"},
{address: "::ffff:192.168.1.1", want: "non_public"},
{address: "2001:db8::1", want: "non_public"},
{address: "not-an-ip", want: "unknown"},
}
for _, test := range tests {
t.Run(test.address, func(t *testing.T) {
if got := summaryForHost(model.HostObservation{Address: test.address}, false).Visibility; got != test.want {
t.Fatalf("visibility = %q, want %q", got, test.want)
}
})
}
}
125 changes: 112 additions & 13 deletions internal/web/notification_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"net"
"net/http"
"sort"
"strings"
"time"

Expand All @@ -27,6 +28,24 @@ type notificationPayload struct {
func (s *Server) listNotificationDestinations(w http.ResponseWriter, r *http.Request, ts *store.TenantStore) {
w.Header().Set("Cache-Control", "no-store")
notifier := s.App.Notifier.Tenant(ts)
current, err := ts.ApplicationUpdateRouting(r.Context())
if err != nil {
if s.Log != nil {
s.Log.Warn("application update routing state unavailable", "error", err)
}
writeError(w, http.StatusInternalServerError, "notification_failed", "notification state could not be loaded", nil)
return
}
// Show legacy deployment digests as current selectors. The console
// drops selectors that are not in the destination list before saving.
destinations, _, err := notifier.CanonicalSelection(r.Context(), current.Destinations)
if err != nil {
if s.Log != nil {
s.Log.Warn("application update routing destinations unavailable", "error", err)
}
writeError(w, http.StatusInternalServerError, "notification_failed", "notification state could not be loaded", nil)
return
}
views, err := notifier.Destinations(r.Context())
var status map[string]any
if err == nil {
Expand All @@ -36,20 +55,10 @@ func (s *Server) listNotificationDestinations(w http.ResponseWriter, r *http.Req
writeError(w, http.StatusInternalServerError, "notification_failed", "notification state could not be loaded", nil)
return
}
routing := map[string]any{"configured": false, "destinations": []string{}}
if current, err := ts.ApplicationUpdateRouting(r.Context()); err == nil {
// Show legacy deployment digests as current selectors. The console
// drops selectors that are not in the destination list before saving.
destinations, _, _ := notifier.CanonicalSelection(r.Context(), current.Destinations)
if destinations == nil {
destinations = []string{}
}
routing = map[string]any{"configured": current.Configured, "destinations": destinations}
} else {
if s.Log != nil {
s.Log.Warn("application update routing state unavailable", "error", err)
}
if destinations == nil {
destinations = []string{}
}
routing := map[string]any{"configured": current.Configured, "destinations": destinations}
writeJSON(w, http.StatusOK, map[string]any{"destinations": views, "status": status, "update_routing": routing})
}

Expand Down Expand Up @@ -80,6 +89,8 @@ func (s *Server) updateNotificationRouting(w http.ResponseWriter, r *http.Reques
writeError(w, http.StatusBadRequest, "validation_failed", "destinations must be an array", map[string]string{"destinations": "select zero or more configured destinations"})
return
}
s.updateRoutingMu.Lock()
defer s.updateRoutingMu.Unlock()
// The routing may select only the tenant's own destinations; another
// tenant's destination is refused as an unknown one. The store checks
// the selection again when it writes it.
Expand Down Expand Up @@ -107,6 +118,94 @@ func (s *Server) updateNotificationRouting(w http.ResponseWriter, r *http.Reques
writeJSON(w, http.StatusOK, map[string]any{"configured": true, "destinations": destinations})
}

type toggleNotificationUpdateRoutingPayload struct {
DestinationID string `json:"destination_id"`
Enabled *bool `json:"enabled"`
Password string `json:"password"`
}

// toggleNotificationUpdateRouting changes one selector against the latest
// persisted routing, instead of replacing the full list a browser may have
// read before another administrator changed a different destination.
func (s *Server) toggleNotificationUpdateRouting(w http.ResponseWriter, r *http.Request, session store.Session, ts *store.TenantStore) {
w.Header().Set("Cache-Control", "no-store")
var input toggleNotificationUpdateRoutingPayload
if !decodeJSON(w, r, &input) {
return
}
input.DestinationID = strings.TrimSpace(input.DestinationID)
if input.DestinationID == "" || input.Enabled == nil {
writeError(w, http.StatusBadRequest, "validation_failed", "destination_id and enabled are required", map[string]string{"destination_id": "select one configured destination"})
return
}
if strings.TrimSpace(input.Password) == "" {
writeError(w, http.StatusBadRequest, "password_required", "account password confirmation is required", map[string]string{"password": "password confirmation is required"})
return
}
if err := s.Auth.ConfirmPasswordForUser(r.Context(), r, session.UserID, input.Password); err != nil {
s.writeNotificationAuthError(w, err)
return
}
s.updateRoutingMu.Lock()
defer s.updateRoutingMu.Unlock()
notifier := s.App.Notifier.Tenant(ts)
if err := notifier.ValidateDestinationSelection(r.Context(), []string{input.DestinationID}); err != nil {
if !writeDestinationSelectionError(w, err) {
writeError(w, http.StatusInternalServerError, "notification", "notification destinations could not be loaded", nil)
}
return
}
current, err := ts.ApplicationUpdateRouting(r.Context())
if err != nil {
if s.Log != nil {
s.Log.Warn("application update routing state unavailable", "error", err)
}
writeError(w, http.StatusInternalServerError, "notification_failed", "notification state could not be loaded", nil)
return
}
selection := current.Destinations
if !current.Configured {
selection, err = notifier.LegacySelection(r.Context())
if err != nil {
if s.Log != nil {
s.Log.Warn("legacy application update routing unavailable", "error", err)
}
writeError(w, http.StatusInternalServerError, "notification_failed", "notification state could not be loaded", nil)
return
}
}
selection = toggleUpdateDestination(selection, input.DestinationID, *input.Enabled)
if err := ts.SetApplicationUpdateDestinations(r.Context(), selection, store.AuditEntry{Action: "notifications.update_routing", Detail: "application update notification routing changed", ActorUserID: session.UserID, ActorUsername: session.Username}); err != nil {
if writeDestinationSelectionError(w, err) || s.writeAuditUnavailable(w, err, "notifications.update_routing") {
return
}
writeError(w, http.StatusInternalServerError, "notification", "application update notification routing could not be saved", nil)
return
}
s.broadcastTo(context.WithoutCancel(r.Context()), audienceTenant(ts), map[string]any{"type": "notification.changed"})
writeJSON(w, http.StatusOK, map[string]any{"configured": true, "destinations": selection})
}

func toggleUpdateDestination(selection []string, destinationID string, enabled bool) []string {
selected := make(map[string]struct{}, len(selection)+1)
for _, id := range selection {
if id = strings.TrimSpace(id); id != "" {
selected[id] = struct{}{}
}
}
if enabled {
selected[destinationID] = struct{}{}
} else {
delete(selected, destinationID)
}
result := make([]string, 0, len(selected))
for id := range selected {
result = append(result, id)
}
sort.Strings(result)
return result
}

// writeDestinationSelectionError answers a routing selection that names a
// destination outside the caller's own with a 400 that repeats the
// selector, and reports whether err was one. The notifier's check and the
Expand Down
Loading
Loading