diff --git a/docs/real-data-readiness.md b/docs/real-data-readiness.md index 7adb687..1c46b7f 100644 --- a/docs/real-data-readiness.md +++ b/docs/real-data-readiness.md @@ -42,8 +42,12 @@ credentials to the Vercel demo function. 4. **Separate storage:** disable demo seeding and use a new, empty storage namespace for real data. Existing discovery upserts resources and does not automatically remove a previously seeded demo estate; never reuse a demo store - for live data. Do not delete existing data automatically. A migration and - provenance strategy must be designed before reusing a persistent store. + for live data. The backend now refuses to start with both a configured live + provider and Cosmos storage, because stored data has no provenance marker. A + process that has loaded the demo cannot switch to live discovery. Use a new + in-memory store for initial testing; it is lost on restart. Do not delete + existing data automatically. A migration and provenance strategy must be + designed before enabling persistent live storage. 5. **Integration and proof:** route browser API calls through the protected gateway, not directly to a private backend or a browser-visible secret. Verify provider identity and authorization, actual discovery and provenance, error @@ -60,7 +64,21 @@ credentials to the Vercel demo function. authoritative for billing. 7. **AI consent:** independently approve whether any real inventory can be sent to an AI provider, review that provider's data use and billing terms, and - enforce per-user access and data minimization. Keep the preview demo isolated. + enforce per-user access and data minimization. Backend startup now rejects + configured Azure OpenAI alongside live providers until this is implemented. + Keep the preview demo isolated. None of these gates creates a cloud account, authorizes spending or proves a live deployment. The Vercel production demo function remains disabled by design. + +## Hosting constraint + +The Vercel demo is not a .NET backend or identity-aware gateway. A separately +protected, reachable backend is still required to connect its UI to real data; +no such deployment has been provisioned or validated. Any self-hosted option +requires a running device and network connection. Do not use a public quick +tunnel as an authentication gateway. Cloudflare's documentation states that +[Zero Trust onboarding requires payment details even on its Free plan](https://developers.cloudflare.com/cloudflare-one/setup/), +so that option does not satisfy a strict no-card requirement as documented. +A different no-card identity-aware solution and end-to-end Vercel routing remain +unverified; free quotas or trials are not a guarantee of permanent no-cost service. diff --git a/src/client/src/app/core/models/resource.model.ts b/src/client/src/app/core/models/resource.model.ts index 01d92b3..dbd6aba 100644 --- a/src/client/src/app/core/models/resource.model.ts +++ b/src/client/src/app/core/models/resource.model.ts @@ -331,6 +331,7 @@ export interface PlatformStatus { resourceCount: number; relationshipCount: number; lastDiscoveryAt?: string | null; + discoveryStatus?: 'NotStarted' | 'InProgress' | 'Succeeded' | 'Failed' | 'PartialFailure' | 'Demo'; serverTimeUtc: string; } diff --git a/src/client/src/app/features/dashboard/dashboard.component.ts b/src/client/src/app/features/dashboard/dashboard.component.ts index a073739..31ab385 100644 --- a/src/client/src/app/features/dashboard/dashboard.component.ts +++ b/src/client/src/app/features/dashboard/dashboard.component.ts @@ -85,15 +85,32 @@ import {
You are exploring a demo estate

- 54 synthetic resources across Azure and AWS are loaded so every feature is usable. - Configure cloud credentials (or Platform:Mode=Live) to discover your own - estate. + 54 synthetic resources across Azure and AWS are loaded so every feature is usable. A + separately protected backend and read-only access are required to discover a real + estate. Never add cloud credentials to this demo preview.

Browse resources } + @if ( + !meta.demoMode() && + meta.status()?.configuredProviders?.length && + meta.status()?.discoveryStatus !== 'Succeeded' + ) { +
+ cloud_off +
+ Live inventory is not confirmed +

+ Discovery is pending or has failed. Counts may be empty or stale; they do not confirm + that the cloud subscription contains no resources. +

+
+
+ } + @if (loading()) { } @else if (loadError()) { diff --git a/src/client/src/app/layout/nav-shell.component.spec.ts b/src/client/src/app/layout/nav-shell.component.spec.ts index f7d5886..89042a8 100644 --- a/src/client/src/app/layout/nav-shell.component.spec.ts +++ b/src/client/src/app/layout/nav-shell.component.spec.ts @@ -7,7 +7,7 @@ import { MetaService } from '../core/services/meta.service'; import { NotificationService } from '../core/services/notification.service'; import { ResourceService } from '../core/services/resource.service'; import { ToastService } from '../core/services/toast.service'; -import { NavShellComponent } from './nav-shell.component'; +import { NavShellComponent, runtimeLabel } from './nav-shell.component'; describe('NavShellComponent realtime availability', () => { const metadata = signal(null); @@ -45,6 +45,20 @@ describe('NavShellComponent realtime availability', () => { .compileComponents(); }); + it('never labels a configured provider as connected before successful discovery', () => { + const live = { ...status, configuredProviders: ['Azure'] }; + expect(runtimeLabel(null)).toBe('Status unavailable'); + expect(runtimeLabel(live)).toBe('Connection unverified'); + expect(runtimeLabel({ ...live, discoveryStatus: 'NotStarted' })).toBe('Connection unverified'); + expect(runtimeLabel({ ...live, discoveryStatus: 'InProgress' })).toBe('Discovering resources'); + expect(runtimeLabel({ ...live, discoveryStatus: 'Failed' })).toBe('Discovery needs attention'); + expect(runtimeLabel({ ...live, discoveryStatus: 'PartialFailure' })).toBe( + 'Discovery needs attention' + ); + expect(runtimeLabel({ ...live, discoveryStatus: 'Succeeded' })).toBe('Connected estate'); + expect(runtimeLabel({ ...live, demoMode: true })).toBe('Demo estate'); + }); + it('connects only when a backend supports realtime, and resumes after recovery', () => { const fixture = TestBed.createComponent(NavShellComponent); fixture.detectChanges(); diff --git a/src/client/src/app/layout/nav-shell.component.ts b/src/client/src/app/layout/nav-shell.component.ts index 414b485..b634e79 100644 --- a/src/client/src/app/layout/nav-shell.component.ts +++ b/src/client/src/app/layout/nav-shell.component.ts @@ -15,12 +15,26 @@ import { MatButtonModule } from '@angular/material/button'; import { MatTooltipModule } from '@angular/material/tooltip'; import { filter, interval } from 'rxjs'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { PlatformStatus } from '../core/models'; import { MetaService } from '../core/services/meta.service'; import { NotificationService } from '../core/services/notification.service'; import { RefreshService } from '../core/services/refresh.service'; import { ResourceService } from '../core/services/resource.service'; import { ToastService } from '../core/services/toast.service'; +// A configured provider is not proof of a successful discovery. +export function runtimeLabel(status: PlatformStatus | null): string { + if (!status) return 'Status unavailable'; + if (status.demoMode) return 'Demo estate'; + if (!status.configuredProviders.length) return 'No providers configured'; + if (status.discoveryStatus === 'Succeeded') return 'Connected estate'; + if (status.discoveryStatus === 'InProgress') return 'Discovering resources'; + if (status.discoveryStatus === 'Failed' || status.discoveryStatus === 'PartialFailure') { + return 'Discovery needs attention'; + } + return 'Connection unverified'; +} + interface NavItem { label: string; icon: string; @@ -73,19 +87,11 @@ interface NavItem {
- {{ - !meta.status() - ? 'Status unavailable' - : meta.demoMode() - ? 'Demo estate' - : meta.status()?.configuredProviders?.length - ? 'Connected estate' - : 'No providers configured' - }} + {{ runtimeLabel(meta.status()) }} {{ meta.status()?.resourceCount ?? 0 }} resources · {{ meta.status()?.relationshipCount ?? 0 }} edges @@ -515,6 +521,7 @@ interface NavItem { ] }) export class NavShellComponent implements OnInit, OnDestroy { + readonly runtimeLabel = runtimeLabel; readonly meta = inject(MetaService); readonly realtime = inject(NotificationService); diff --git a/src/server/CloudScope.Api/HostedServices/DiscoveryBackgroundService.cs b/src/server/CloudScope.Api/HostedServices/DiscoveryBackgroundService.cs index 2e5fbb4..772e960 100644 --- a/src/server/CloudScope.Api/HostedServices/DiscoveryBackgroundService.cs +++ b/src/server/CloudScope.Api/HostedServices/DiscoveryBackgroundService.cs @@ -116,6 +116,7 @@ private async Task RunStartupSeedAsync(CancellationToken ct) { _logger.LogError(ex, "Startup seeding/discovery failed."); _runtime.LastDiscoveryError = ex.Message; + _runtime.DiscoveryStatus = "Failed"; } } } diff --git a/src/server/CloudScope.Api/Program.cs b/src/server/CloudScope.Api/Program.cs index d131ffe..a52e66e 100644 --- a/src/server/CloudScope.Api/Program.cs +++ b/src/server/CloudScope.Api/Program.cs @@ -75,6 +75,13 @@ var useCosmos = platformOptions.StorageProvider.Equals("Cosmos", StringComparison.OrdinalIgnoreCase) && cosmosOptions.IsConfigured; +// Persistent storage lacks data provenance, and sharing real inventory with +// external AI requires explicit consent and access controls. Fail closed. +LiveDataSafety.Validate(useCosmos, + builder.Configuration.GetSection(AzureOptions.SectionName).Get() ?? new AzureOptions(), + builder.Configuration.GetSection(AwsOptions.SectionName).Get() ?? new AwsOptions(), + builder.Configuration.GetSection(AzureOpenAIOptions.SectionName).Get() ?? new AzureOpenAIOptions()); + if (useCosmos) { builder.Services.AddSingleton(); diff --git a/src/server/CloudScope.Core/Domain/Models/CostRecommendation.cs b/src/server/CloudScope.Core/Domain/Models/CostRecommendation.cs index 21ca4d1..ac4b87d 100644 --- a/src/server/CloudScope.Core/Domain/Models/CostRecommendation.cs +++ b/src/server/CloudScope.Core/Domain/Models/CostRecommendation.cs @@ -81,5 +81,7 @@ public class PlatformStatus public int ResourceCount { get; set; } public int RelationshipCount { get; set; } public DateTime? LastDiscoveryAt { get; set; } + /// NotStarted, InProgress, Succeeded, Failed, PartialFailure, or Demo. + public string DiscoveryStatus { get; set; } = "NotStarted"; public DateTime ServerTimeUtc { get; set; } = DateTime.UtcNow; } diff --git a/src/server/CloudScope.Infrastructure/Configuration/LiveDataSafety.cs b/src/server/CloudScope.Infrastructure/Configuration/LiveDataSafety.cs new file mode 100644 index 0000000..be6b473 --- /dev/null +++ b/src/server/CloudScope.Infrastructure/Configuration/LiveDataSafety.cs @@ -0,0 +1,21 @@ +namespace CloudScope.Infrastructure.Configuration; + +/// +/// Fail closed for live-data combinations whose isolation or privacy has not +/// yet been implemented. This does not authenticate users or secure a backend. +/// +public static class LiveDataSafety +{ + public static void Validate(bool useCosmos, AzureOptions azure, AwsOptions aws, AzureOpenAIOptions ai) + { + var providerConfigured = !string.IsNullOrWhiteSpace(azure.SubscriptionId) || + (!string.IsNullOrWhiteSpace(aws.AccessKeyId) && !string.IsNullOrWhiteSpace(aws.SecretAccessKey)); + if (!providerConfigured) return; + + if (useCosmos) + throw new InvalidOperationException("Live discovery with persistent Cosmos storage is disabled until data provenance and isolation are implemented. Use a fresh in-memory store."); + + if (!string.IsNullOrWhiteSpace(ai.Endpoint) || !string.IsNullOrWhiteSpace(ai.ApiKey)) + throw new InvalidOperationException("External AI is disabled with live providers until real-data sharing and access controls are implemented."); + } +} diff --git a/src/server/CloudScope.Infrastructure/Runtime/RuntimeState.cs b/src/server/CloudScope.Infrastructure/Runtime/RuntimeState.cs index 0bc27e6..07c09e2 100644 --- a/src/server/CloudScope.Infrastructure/Runtime/RuntimeState.cs +++ b/src/server/CloudScope.Infrastructure/Runtime/RuntimeState.cs @@ -15,6 +15,7 @@ public sealed class RuntimeState private DateTime? _lastDiscoveryAt; private string? _lastDiscoveryError; private bool _discoveryInProgress; + private string _discoveryStatus = "NotStarted"; public bool DemoMode { @@ -40,6 +41,13 @@ public string? LastDiscoveryError set { lock (_sync) _lastDiscoveryError = value; } } + // Reports outcome, not just whether a provider has been configured. + public string DiscoveryStatus + { + get { lock (_sync) return _discoveryStatus; } + set { lock (_sync) _discoveryStatus = value; } + } + public bool DiscoveryInProgress { get { lock (_sync) return _discoveryInProgress; } diff --git a/src/server/CloudScope.Infrastructure/Services/Azure/AzureResourceGraphService.cs b/src/server/CloudScope.Infrastructure/Services/Azure/AzureResourceGraphService.cs index f1cd3d7..5abf45e 100644 --- a/src/server/CloudScope.Infrastructure/Services/Azure/AzureResourceGraphService.cs +++ b/src/server/CloudScope.Infrastructure/Services/Azure/AzureResourceGraphService.cs @@ -60,7 +60,7 @@ public async Task> DiscoverResourcesAsync(Cancellatio return Array.Empty(); } - var query = $"Resources | project {string.Join(", ", DefaultQueryFields)} | order by name asc"; + var query = $"Resources | project {string.Join(", ", DefaultQueryFields)} | order by id asc"; return await QueryResourceGraphAsync(query, ct); } @@ -181,6 +181,7 @@ private async Task> QueryResourceGraphAsync(string query, Ca var client = _httpClientFactory.CreateClient("AzureManagement"); var resources = new List(); string? skipToken = null; + var seenTokens = new HashSet(StringComparer.Ordinal); do { @@ -221,18 +222,16 @@ private async Task> QueryResourceGraphAsync(string query, Ca using var document = JsonDocument.Parse(body); var root = document.RootElement; - if (root.TryGetProperty("data", out var data) && data.ValueKind == JsonValueKind.Array) + var page = ValidatePage(root); + foreach (var row in page.Data.EnumerateArray()) { - foreach (var row in data.EnumerateArray()) - { - var resource = MapResource(row); - if (resource is not null) resources.Add(resource); - } + var resource = MapResource(row) ?? throw new CloudProviderException( + "Azure", "Resource Graph returned a resource without an ID."); + resources.Add(resource); } - - skipToken = root.TryGetProperty("$skipToken", out var next) && next.ValueKind == JsonValueKind.String - ? next.GetString() - : null; + skipToken = page.SkipToken; + if (skipToken is not null && !seenTokens.Add(skipToken)) + throw new CloudProviderException("Azure", "Resource Graph repeated a continuation token."); } catch (CloudProviderException) { @@ -253,6 +252,40 @@ private async Task> QueryResourceGraphAsync(string query, Ca return resources; } + /// + /// Validate that an HTTP 200 is a complete page, not an unusable or + /// truncated response that could be mistaken for an empty inventory. + /// + public static (JsonElement Data, string? SkipToken) ValidatePage(JsonElement root) + { + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("data", out var data) || data.ValueKind != JsonValueKind.Array) + throw new CloudProviderException("Azure", "Resource Graph returned an invalid data page."); + + string? skipToken = null; + if (root.TryGetProperty("$skipToken", out var next) && next.ValueKind != JsonValueKind.Null) + { + if (next.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(next.GetString())) + throw new CloudProviderException("Azure", "Resource Graph returned an invalid continuation token."); + skipToken = next.GetString(); + } + + if (root.TryGetProperty("resultTruncated", out var truncated)) + { + bool isTruncated; + if (truncated.ValueKind == JsonValueKind.True || truncated.ValueKind == JsonValueKind.False) + isTruncated = truncated.GetBoolean(); + else if (truncated.ValueKind == JsonValueKind.String && bool.TryParse(truncated.GetString(), out var parsed)) + isTruncated = parsed; + else + throw new CloudProviderException("Azure", "Resource Graph returned an invalid truncation indicator."); + if (isTruncated && skipToken is null) + throw new CloudProviderException("Azure", "Resource Graph returned a truncated page without a continuation token."); + } + + return (data, skipToken); + } + private CloudResource? MapResource(JsonElement row) { var id = GetString(row, "id"); diff --git a/src/server/CloudScope.Infrastructure/Services/Discovery/CloudDiscoveryService.cs b/src/server/CloudScope.Infrastructure/Services/Discovery/CloudDiscoveryService.cs index 46a6560..8d6e85e 100644 --- a/src/server/CloudScope.Infrastructure/Services/Discovery/CloudDiscoveryService.cs +++ b/src/server/CloudScope.Infrastructure/Services/Discovery/CloudDiscoveryService.cs @@ -50,6 +50,7 @@ public async Task DiscoverAsync(CancellationToken ct = default) try { _runtime.DiscoveryInProgress = true; + _runtime.DiscoveryStatus = "InProgress"; _runtime.LastDiscoveryError = null; var configured = _providers.Where(p => p.IsConfigured).ToList(); @@ -62,6 +63,11 @@ public async Task DiscoverAsync(CancellationToken ct = default) return await SeedDemoCoreAsync(ct); } + // A process that seeded demo data must never reinterpret the same + // store as live. Do not delete data; require a fresh process/store. + if (_runtime.DemoMode) + throw new InvalidOperationException("Live discovery requires a fresh store that has never contained demo data."); + var result = new DiscoveryResult { StartedAt = DateTime.UtcNow, DemoMode = false }; foreach (var provider in configured) @@ -135,17 +141,22 @@ public async Task DiscoverAsync(CancellationToken ct = default) result.ResourcesDiscovered = result.Providers.Sum(p => p.ResourcesDiscovered); result.CompletedAt = DateTime.UtcNow; - _runtime.LastDiscoveryAt = result.CompletedAt; - _runtime.DemoMode = false; - - try + var failures = result.Providers.Count(p => p.Error is not null); + _runtime.DiscoveryStatus = failures == 0 ? "Succeeded" + : failures == result.Providers.Count ? "Failed" : "PartialFailure"; + if (failures == 0) { - await _notifications.NotifyDiscoveryCompleted(result.ResourcesDiscovered, result.Duration); - } - catch (Exception ex) when (ex is not OperationCanceledException) - { - _logger.LogWarning(ex, "Could not send discovery completion notification."); + _runtime.LastDiscoveryAt = result.CompletedAt; + try + { + await _notifications.NotifyDiscoveryCompleted(result.ResourcesDiscovered, result.Duration); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Could not send discovery completion notification."); + } } + _runtime.DemoMode = false; _logger.LogInformation( "Discovery finished: {Resources} resources, {Edges} relationships, {Duration:0.0}s.", @@ -153,6 +164,11 @@ public async Task DiscoverAsync(CancellationToken ct = default) return result; } + catch + { + _runtime.DiscoveryStatus = "Failed"; + throw; + } finally { _runtime.DiscoveryInProgress = false; @@ -206,6 +222,7 @@ private async Task SeedDemoCoreAsync(CancellationToken ct) }; _runtime.DemoMode = true; + _runtime.DiscoveryStatus = "Demo"; _runtime.LastDiscoveryAt = result.CompletedAt; _logger.LogInformation( diff --git a/src/server/CloudScope.Infrastructure/Services/Discovery/PlatformStatusService.cs b/src/server/CloudScope.Infrastructure/Services/Discovery/PlatformStatusService.cs index 97fd0a1..d2eeb23 100644 --- a/src/server/CloudScope.Infrastructure/Services/Discovery/PlatformStatusService.cs +++ b/src/server/CloudScope.Infrastructure/Services/Discovery/PlatformStatusService.cs @@ -50,7 +50,8 @@ public async Task GetStatusAsync(CancellationToken ct = default) .ToList(), ResourceCount = await _resourceRepository.GetCountAsync(ct: ct), RelationshipCount = await _graphRepository.GetEdgeCountAsync(ct), - LastDiscoveryAt = _runtime.LastDiscoveryAt + LastDiscoveryAt = _runtime.LastDiscoveryAt, + DiscoveryStatus = _runtime.DiscoveryStatus }; } } diff --git a/src/server/CloudScope.Tests/Unit/AzureResourceGraphResponseTests.cs b/src/server/CloudScope.Tests/Unit/AzureResourceGraphResponseTests.cs new file mode 100644 index 0000000..b41b463 --- /dev/null +++ b/src/server/CloudScope.Tests/Unit/AzureResourceGraphResponseTests.cs @@ -0,0 +1,37 @@ +using System.Text.Json; +using CloudScope.Infrastructure.Services.Azure; + +namespace CloudScope.Tests.Unit; + +public class AzureResourceGraphResponseTests +{ + [Fact] + public void EmptyDataIsAValidEmptyPage() + { + using var document = JsonDocument.Parse("{\"data\":[],\"resultTruncated\":\"false\"}"); + var page = AzureResourceGraphService.ValidatePage(document.RootElement); + Assert.Equal(0, page.Data.GetArrayLength()); + Assert.Null(page.SkipToken); + } + + [Theory] + [InlineData("{}")] + [InlineData("{\"data\":null}")] + [InlineData("{\"data\":[],\"resultTruncated\":true}")] + [InlineData("{\"data\":[],\"resultTruncated\":\"true\"}")] + [InlineData("{\"data\":[],\"$skipToken\":\"\"}")] + [InlineData("{\"data\":[],\"resultTruncated\":\"unknown\"}")] + public void MalformedOrUnpageableResponsesFailInsteadOfLookingEmpty(string json) + { + using var document = JsonDocument.Parse(json); + Assert.Throws( + () => AzureResourceGraphService.ValidatePage(document.RootElement)); + } + + [Fact] + public void TruncatedPageWithContinuationIsAccepted() + { + using var document = JsonDocument.Parse("{\"data\":[],\"resultTruncated\":true,\"$skipToken\":\"next\"}"); + Assert.Equal("next", AzureResourceGraphService.ValidatePage(document.RootElement).SkipToken); + } +} diff --git a/src/server/CloudScope.Tests/Unit/DiscoveryCoordinationTests.cs b/src/server/CloudScope.Tests/Unit/DiscoveryCoordinationTests.cs index 831cf93..21ef653 100644 --- a/src/server/CloudScope.Tests/Unit/DiscoveryCoordinationTests.cs +++ b/src/server/CloudScope.Tests/Unit/DiscoveryCoordinationTests.cs @@ -70,4 +70,121 @@ public async Task DemoSeedingIsRejectedWhenDisabledOrAProviderIsConfigured() await Assert.ThrowsAsync(() => disabled.DiscoverAsync()); Assert.Equal(0, await store.GetCountAsync()); } + [Fact] + public async Task EmptySuccessfulDiscoveryIsNotReportedAsFailure() + { + var provider = new Mock(); + provider.SetupGet(p => p.IsConfigured).Returns(true); + provider.SetupGet(p => p.Provider).Returns(CloudProvider.Azure); + provider.Setup(p => p.DiscoverResourcesAsync(It.IsAny())) + .ReturnsAsync(Array.Empty()); + var store = new InMemoryCloudStore(); + var runtime = new RuntimeState(); + var notifications = new Mock(); + var service = new CloudDiscoveryService(new[] { provider.Object }, store, store, + notifications.Object, runtime, Options.Create(new PlatformOptions()), + NullLogger.Instance); + + var result = await service.DiscoverAsync(); + Assert.Equal(0, result.ResourcesDiscovered); + Assert.Null(result.Providers.Single().Error); + Assert.Equal("Succeeded", runtime.DiscoveryStatus); + Assert.NotNull(runtime.LastDiscoveryAt); + Assert.False(runtime.DemoMode); + } + + [Fact] + public async Task ProviderFailureIsNotReportedAsAnEmptySuccessfulDiscovery() + { + var provider = new Mock(); + provider.SetupGet(p => p.IsConfigured).Returns(true); + provider.SetupGet(p => p.Provider).Returns(CloudProvider.Azure); + provider.Setup(p => p.DiscoverResourcesAsync(It.IsAny())) + .ThrowsAsync(new InvalidOperationException("private diagnostic")); + var store = new InMemoryCloudStore(); + var runtime = new RuntimeState(); + var notifications = new Mock(); + var service = new CloudDiscoveryService(new[] { provider.Object }, store, store, + notifications.Object, runtime, Options.Create(new PlatformOptions()), + NullLogger.Instance); + + var result = await service.DiscoverAsync(); + Assert.Equal("Failed", runtime.DiscoveryStatus); + Assert.Null(runtime.LastDiscoveryAt); + Assert.Equal("Discovery failed. See server logs for details.", result.Providers.Single().Error); + notifications.Verify(n => n.NotifyDiscoveryCompleted(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task PlatformStatusExposesDiscoveryOutcomeWithoutPrivateErrors() + { + var store = new InMemoryCloudStore(); + var runtime = new RuntimeState { DiscoveryStatus = "Failed", LastDiscoveryError = "private diagnostic" }; + var status = new PlatformStatusService(store, store, Array.Empty(), runtime, + Options.Create(new AzureOpenAIOptions())); + var result = await status.GetStatusAsync(); + Assert.Equal("Failed", result.DiscoveryStatus); + Assert.Null(result.LastDiscoveryAt); + Assert.Equal(0, result.ResourceCount); + } + + [Fact] + public async Task PartialProviderFailureDoesNotMarkTheEstateConnected() + { + var azure = new Mock(); + azure.SetupGet(p => p.IsConfigured).Returns(true); + azure.SetupGet(p => p.Provider).Returns(CloudProvider.Azure); + azure.Setup(p => p.DiscoverResourcesAsync(It.IsAny())) + .ReturnsAsync(Array.Empty()); + var aws = new Mock(); + aws.SetupGet(p => p.IsConfigured).Returns(true); + aws.SetupGet(p => p.Provider).Returns(CloudProvider.AWS); + aws.Setup(p => p.DiscoverResourcesAsync(It.IsAny())) + .ThrowsAsync(new InvalidOperationException()); + var store = new InMemoryCloudStore(); + var runtime = new RuntimeState(); + var service = new CloudDiscoveryService(new[] { azure.Object, aws.Object }, store, store, + new Mock().Object, runtime, Options.Create(new PlatformOptions()), + NullLogger.Instance); + + await service.DiscoverAsync(); + Assert.Equal("PartialFailure", runtime.DiscoveryStatus); + Assert.Null(runtime.LastDiscoveryAt); + } + + [Fact] + public async Task AStoreSeededWithDemoDataCannotBeSwitchedToLive() + { + var configured = false; + var provider = new Mock(); + provider.SetupGet(p => p.IsConfigured).Returns(() => configured); + provider.SetupGet(p => p.Provider).Returns(CloudProvider.Azure); + var store = new InMemoryCloudStore(); + var runtime = new RuntimeState(); + var service = new CloudDiscoveryService(new[] { provider.Object }, store, store, + new Mock().Object, runtime, Options.Create(new PlatformOptions()), + NullLogger.Instance); + + await service.SeedDemoAsync(); + var originalCount = await store.GetCountAsync(); + configured = true; + await Assert.ThrowsAsync(() => service.DiscoverAsync()); + Assert.Equal("Failed", runtime.DiscoveryStatus); + Assert.True(runtime.DemoMode); + Assert.Equal(originalCount, await store.GetCountAsync()); + provider.Verify(p => p.DiscoverResourcesAsync(It.IsAny()), Times.Never); + } + + [Fact] + public void LiveStorageAndExternalAiAreRejectedUntilTheyHaveSafeProvenanceAndConsent() + { + var azure = new AzureOptions { SubscriptionId = "test-subscription" }; + var aws = new AwsOptions(); + var ai = new AzureOpenAIOptions(); + LiveDataSafety.Validate(false, azure, aws, ai); + Assert.Throws(() => LiveDataSafety.Validate(true, azure, aws, ai)); + ai.Endpoint = "https://example.invalid"; + Assert.Throws(() => LiveDataSafety.Validate(false, azure, aws, ai)); + LiveDataSafety.Validate(true, new AzureOptions(), aws, ai); // demo behavior unchanged + } }