Skip to content
Open
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
24 changes: 21 additions & 3 deletions docs/real-data-readiness.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
1 change: 1 addition & 0 deletions src/client/src/app/core/models/resource.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ export interface PlatformStatus {
resourceCount: number;
relationshipCount: number;
lastDiscoveryAt?: string | null;
discoveryStatus?: 'NotStarted' | 'InProgress' | 'Succeeded' | 'Failed' | 'PartialFailure' | 'Demo';
serverTimeUtc: string;
}

Expand Down
23 changes: 20 additions & 3 deletions src/client/src/app/features/dashboard/dashboard.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,32 @@ import {
<div>
<strong>You are exploring a demo estate</strong>
<p>
54 synthetic resources across Azure and AWS are loaded so every feature is usable.
Configure cloud credentials (or <code>Platform:Mode=Live</code>) 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.
</p>
</div>
<a mat-stroked-button routerLink="/resources">Browse resources</a>
</div>
}

@if (
!meta.demoMode() &&
meta.status()?.configuredProviders?.length &&
meta.status()?.discoveryStatus !== 'Succeeded'
) {
<div class="demo-banner" role="status">
<mat-icon>cloud_off</mat-icon>
<div>
<strong>Live inventory is not confirmed</strong>
<p>
Discovery is pending or has failed. Counts may be empty or stale; they do not confirm
that the cloud subscription contains no resources.
</p>
</div>
</div>
}

@if (loading()) {
<app-loading-spinner message="Loading estate overview…" />
} @else if (loadError()) {
Expand Down
16 changes: 15 additions & 1 deletion src/client/src/app/layout/nav-shell.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<PlatformStatus | null>(null);
Expand Down Expand Up @@ -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();
Expand Down
27 changes: 17 additions & 10 deletions src/client/src/app/layout/nav-shell.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -73,19 +87,11 @@ interface NavItem {
<div class="runtime">
<span
class="runtime-dot"
[class.live]="!!meta.status()?.configuredProviders?.length && !meta.demoMode()"
[class.live]="meta.status()?.discoveryStatus === 'Succeeded' && !meta.demoMode()"
[class.demo]="meta.demoMode()"
></span>
<div class="runtime-text">
<strong>{{
!meta.status()
? 'Status unavailable'
: meta.demoMode()
? 'Demo estate'
: meta.status()?.configuredProviders?.length
? 'Connected estate'
: 'No providers configured'
}}</strong>
<strong>{{ runtimeLabel(meta.status()) }}</strong>
<span>
{{ meta.status()?.resourceCount ?? 0 }} resources ·
{{ meta.status()?.relationshipCount ?? 0 }} edges
Expand Down Expand Up @@ -515,6 +521,7 @@ interface NavItem {
]
})
export class NavShellComponent implements OnInit, OnDestroy {
readonly runtimeLabel = runtimeLabel;
readonly meta = inject(MetaService);
readonly realtime = inject(NotificationService);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ private async Task RunStartupSeedAsync(CancellationToken ct)
{
_logger.LogError(ex, "Startup seeding/discovery failed.");
_runtime.LastDiscoveryError = ex.Message;
_runtime.DiscoveryStatus = "Failed";
}
}
}
7 changes: 7 additions & 0 deletions src/server/CloudScope.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AzureOptions>() ?? new AzureOptions(),
builder.Configuration.GetSection(AwsOptions.SectionName).Get<AwsOptions>() ?? new AwsOptions(),
builder.Configuration.GetSection(AzureOpenAIOptions.SectionName).Get<AzureOpenAIOptions>() ?? new AzureOpenAIOptions());

if (useCosmos)
{
builder.Services.AddSingleton<CosmosDatabase>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,7 @@ public class PlatformStatus
public int ResourceCount { get; set; }
public int RelationshipCount { get; set; }
public DateTime? LastDiscoveryAt { get; set; }
/// <summary>NotStarted, InProgress, Succeeded, Failed, PartialFailure, or Demo.</summary>
public string DiscoveryStatus { get; set; } = "NotStarted";
public DateTime ServerTimeUtc { get; set; } = DateTime.UtcNow;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace CloudScope.Infrastructure.Configuration;

/// <summary>
/// Fail closed for live-data combinations whose isolation or privacy has not
/// yet been implemented. This does not authenticate users or secure a backend.
/// </summary>
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.");
}
}
8 changes: 8 additions & 0 deletions src/server/CloudScope.Infrastructure/Runtime/RuntimeState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public sealed class RuntimeState
private DateTime? _lastDiscoveryAt;
private string? _lastDiscoveryError;
private bool _discoveryInProgress;
private string _discoveryStatus = "NotStarted";

public bool DemoMode
{
Expand All @@ -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; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public async Task<IEnumerable<CloudResource>> DiscoverResourcesAsync(Cancellatio
return Array.Empty<CloudResource>();
}

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);
}

Expand Down Expand Up @@ -181,6 +181,7 @@ private async Task<List<CloudResource>> QueryResourceGraphAsync(string query, Ca
var client = _httpClientFactory.CreateClient("AzureManagement");
var resources = new List<CloudResource>();
string? skipToken = null;
var seenTokens = new HashSet<string>(StringComparer.Ordinal);

do
{
Expand Down Expand Up @@ -221,18 +222,16 @@ private async Task<List<CloudResource>> 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)
{
Expand All @@ -253,6 +252,40 @@ private async Task<List<CloudResource>> QueryResourceGraphAsync(string query, Ca
return resources;
}

/// <summary>
/// Validate that an HTTP 200 is a complete page, not an unusable or
/// truncated response that could be mistaken for an empty inventory.
/// </summary>
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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public async Task<DiscoveryResult> DiscoverAsync(CancellationToken ct = default)
try
{
_runtime.DiscoveryInProgress = true;
_runtime.DiscoveryStatus = "InProgress";
_runtime.LastDiscoveryError = null;

var configured = _providers.Where(p => p.IsConfigured).ToList();
Expand All @@ -62,6 +63,11 @@ public async Task<DiscoveryResult> 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)
Expand Down Expand Up @@ -135,24 +141,34 @@ public async Task<DiscoveryResult> 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.",
result.ResourcesDiscovered, result.RelationshipsDiscovered, result.Duration.TotalSeconds);

return result;
}
catch
{
_runtime.DiscoveryStatus = "Failed";
throw;
}
finally
{
_runtime.DiscoveryInProgress = false;
Expand Down Expand Up @@ -206,6 +222,7 @@ private async Task<DiscoveryResult> SeedDemoCoreAsync(CancellationToken ct)
};

_runtime.DemoMode = true;
_runtime.DiscoveryStatus = "Demo";
_runtime.LastDiscoveryAt = result.CompletedAt;

_logger.LogInformation(
Expand Down
Loading
Loading