Skip to content

feat: integrate v4 slices 1-8 and performance optimizations - #205

Open
JLCode-tech wants to merge 28 commits into
stagingfrom
work/v4-localhost
Open

feat: integrate v4 slices 1-8 and performance optimizations#205
JLCode-tech wants to merge 28 commits into
stagingfrom
work/v4-localhost

Conversation

@JLCode-tech

Copy link
Copy Markdown
Collaborator

Summary

This PR consolidates v4 Slices 1–8, Corporate CA / SSL proxy support, and the F5 BNK & Diagnostics Performance Optimizations onto staging.


Highlights

1. Core Feature Slices (1–8)

  • Slice 1 (Free-Form Regions & Cluster Discovery Metadata): Pattern-based validation for cloud regions; Azure/GCP validators; database migration v2_156.
  • Slice 2 (BNK Health Node/AZ Placement): Enriched BNK Health dashboard with nodeZone, nodeInstanceType, and per-component placement metadata.
  • Slice 3 (Connectivity & Integration Status): Persists cluster version, node_count, zones, last_synced_at, connectivity_status, access_method, and integration_status; added project/cluster connectivity endpoints.
  • Slice 4 (Credential-Template Cluster Auto-Detection): Dynamic cluster detection across AWS, IBM Cloud, Azure, and GCP credential templates; surfaces AWS SSO account metadata.
  • Slice 5 (BNK Resources Fleet Dashboard): Cluster-level consumption analytics, node capacity fallback, and metrics-server parallel query collection.
  • Slice 6 (TMM Traffic Stats & Egress/Gateway Views): Real-time TMM traffic stats, listener connection counts, and topology hit-counter badges.
  • Slice 7 (Operational State Polish): App Delivery ServiceDetail models, ReferenceGrants, Gateway API condition evaluations, and typed schemas.
  • Slice 8 & Nav Refactor: Relocated BNK Resources to Fleet, MCP to System, and Benchmarks to Observe sidebar.

2. Corporate CA & SSL Proxy Support

  • Mounted user-supplied CA certificates from certs/ into containers.
  • Combined bundle dynamic export (SSL_CERT_FILE, GIT_SSL_CAINFO, REQUESTS_CA_BUNDLE).
  • Resolved module library sync tag refs on shallow git clones.

3. F5 BNK & Diagnostics Performance Optimizations

  • TMM Debug Pod Discovery Reuse: list_tmm_debug_pods checks warm BNK discovery caches (bnk:pods:{cluster_id}) to eliminate redundant cluster sweeps.
  • CWC & QKView Caching: 60s/30s caching on availability, setup, and QKView lists with instant non-blocking tab renders.
  • Recovery Status Caching: 60s caching with placeholder data preservation during tab navigation.
  • Shared BNK Cache Alignment: Unified insight endpoints on shared cache keys and raised executor pool capacity.

Verification & CI Parity

  • make quick-check: Passed (Ruff, ESLint, TypeScript tsc --noEmit, OpenAPI freshness, migration chain validator).
  • Pytest Suite: All unit and integration suites passing.
  • Vitest Suite: 297 test files / 2,617 tests passed.
  • Deployment: Verified healthy on local environment (https://localhost).

jgruberf5 pushed a commit that referenced this pull request Sep 8, 2026
…zure api_server (M3)

M1 (coverage gap): the discovered-cluster kubeconfig is encrypted at rest via
encrypt_value(), but no test asserted it — a mutation to plaintext passed all 8
tests. Add test_persisted_kubeconfig_is_encrypted_at_rest, which reads the
persisted kubeconfig_encrypted column and asserts it is NOT plaintext
(no "apiVersion" in the stored value; stored != decrypt_value(stored)) yet
decrypts back to the real kubeconfig. Reverting encrypt_value to plaintext reds
this test (decrypt raises / stored equals its plaintext).

M3 (defensive): _detect_azure_clusters composed api_server as
f"https://{creds['server']}:443", which double-prefixes into a malformed URL if
creds['server'] ever carries a scheme or an explicit port. Add
_normalize_api_server_host() to strip a leading http(s):// scheme and a trailing
:port so a bare host, scheme-prefixed host, or host:port all yield one correct
https://host:443, with a 3-shape parametrized test.

Scoped to M1 + M3; region validators (M2) untouched. No API/model change.

Claude-Session: https://claude.ai/code/session_01UCsZXDxBsWV2s4kT47DwDW
@jgruberf5

Copy link
Copy Markdown
Collaborator

Self-review (cold, adversarial) + fixes applied

An independent cold audit of this 133-file PR, executed, prioritizing migrations / security / contract / caching. No blockers, no majors.

Held clean (verified by execution):

  • Migrationsv2_156v2_157, single head (alembic heads), additive-nullable only with symmetric drop_column downgrades → reversible + backfill-safe; the model matches the 7 columns exactly.
  • Contractgenerate-openapi.py --check up to date (536/536).
  • Security — every new endpoint carries auth (require_project_owner/require_viewer); discovered kubeconfigs encrypt_value-encrypted + project_id-scoped; only partial-suffix secret logging.
  • Caching "optimizations" — all keys cluster-scoped (no cross-tenant bleed), exec-cache key includes full command args, mutations invalidate the right keys, per-thread sessions.
  • Tests: 4926 unit + 302 component + 67 new integration pass; mutation-checked the CPU-sum + a plaintext-kubeconfig mutation.

Findings (minor) — fixed @ 8a3cf708:

  • M1 (coverage gap): the discovered-kubeconfig encryption-at-rest invariant had no assertion (a plaintext mutation passed all 8 tests). Added test_persisted_kubeconfig_is_encrypted_at_rest (stored value isn't plaintext, decrypts back to a real kubeconfig); mutation-verified (plaintext reds it).
  • M3 (defensive): _detect_azure_clusters built https://{server}:443 which double-prefixes if server carries a scheme/port. Added _normalize_api_server_host (strips scheme + :port) with a 3-shape test.
  • M2 (validators now shape-only, never raise): left as-is — it's an intentional relaxation (region strings flow into cloud-SDK params, not shells), flagged for the record.

Coverage limits (given ~14k lines): frontend not executed (relied on the passing openapi --check gate + the PR's vitest/tsc claim); traffic_stats.py (+744) reviewed at scan level; cloud-service live-API internals not exercised; migration round-trip not run on real Postgres (chain-validator + additive-nullable pattern is the basis). Ready for review.

@bonnyr-f5

Copy link
Copy Markdown
Collaborator

Review — review-discipline pipeline (structural / invariant sweep)

Cold structural sweep at head 8a3cf708, audited against the authoritative post-v4.0.0 base (git diff e38976f..8a3cf708, 133 files) — not the GitHub PR diff, which is stale for this branch. Depth is deliberately structural: invariant sweeps across the whole surface + spot-checks of security-relevant areas, not a line-by-line read of ~14k lines (see "not covered").

Verdict: REVISE — but #205's own diff is structurally clean; the blockers are cross-PR merge coordination.

Major

None in #205's own diff.

Minor

Minor-1 · INV-4 — v2_156 revision-id collision with #207 (#207 is the one to renumber). alembic/versions/v2_156_add_cluster_discovery_metadata.py declares revision="v2_156"/down_revision="v2_155". #207 independently declares a different file at the same revision="v2_156"/down_revision="v2_155" → duplicate id + two heads → alembic upgrade fails whichever lands second. Confirmed by listing both branches. The #217 integration branch already resolves this by keeping #205's v2_156/v2_157 and renumbering the azure migration to v2_158 — so #205's v2_156 is canonical; #207 should renumber to v2_158 (down_revision="v2_157"). No other alembic/route/port/task-name collision across the open PRs.

Minor-2 · INV-4 — rebase conflict vs already-merged #215. .trivyignore (adds CVE-2026-56854) and backend/requirements.txt (gitpython 3.1.58→3.1.59) duplicate remediation that #215 merged to staging on 2026-09-11 (staging tip 5e9ee00). Staging now carries a CVE-2026-56854 block with different rationale text and the gitpython bump, so rebasing onto current staging produces real (trivially resolvable) conflicts in both files — keep one CVE block, keep 3.1.59. Resolve at rebase.

Minor-3 · INV-6 (PLAUSIBLE — robustness, not security). ImportedBlueprintDeployDialog.tsx:382 gates the form render on templateLoading || inputsLoading only. If useStackTemplate/useStackRequiredInputs errors (isLoading=false, data=undefined), the form renders and requiresCluster (L106) + needsCredentialTemplate (L99) both fail open to false, so in deployMode==='new' canSubmit (L376) can be true and the deploy fires without the cluster prerequisite. Consequence is graded: this is a deploy prerequisite (backend-enforced → 400), not a secret write like the INV-6 origin — degraded UX, not a security fail-open. Fix: gate render/canSubmit on !!template (fail closed on undefined). It does correctly derive requiresCluster from the static template?.prerequisites (the right source).

Nits

  • routes/k8s/clusters.py: new check_cluster_connectivity/batch/project_batch_connectivity_check use require_viewer while the pre-existing test_cluster_connection uses require_cluster_owner; both trigger outbound network probes. Consistent with the instance-wide read model, but a viewer-triggerable outbound probe is worth a conscious decision.
  • entrypoint.sh .der fallback || cat "$cert" >> bundle appends raw binary DER into a PEM bundle on openssl failure — could confuse strict PEM parsers.

Verified clean

  • INV-1/INV-2: new db.query(KubernetesCluster) upserts in cluster_discovery_service.py filter project_id + name; register_discovered_cluster is project-scoped; the GCP block separates cloud project_id from Forge tenant project_id (stored as account_id). Unscoped .all() in system_service/connectivity_probe_service matches the pre-existing instance-wide cluster model (Redact bnk_config from the instance-wide global cluster list #174, require_viewer reads / require_cluster_owner mutations) — not a new leak.
  • INV-3: new status columns (discovery_status/connectivity_status/integration_status/access_method String(50), account_id String(100)) are on response models only, backend-set with short literals — not exposed in any request body.
  • INV-7: v2_156/v2_157 are brand-new files (first appear in this branch); no op.* appended to a pre-existing revision. Single branch head v2_157, no intra-branch dup.
  • Secrets/hostnames (public repo): only test-fixture RFC1918 IPs; certs/ additions are .gitkeep + README.md (no key material); entrypoint.sh CA install is non-root, per-user, never disables verification.

Not covered (structural honesty)

Line-by-line correctness of the ~14k lines — cloud-discovery integrations (azure_service/gcp_service/ibm_cloud_service/eks_service), the bnk/* telemetry/topology/traffic-stats refactor, connectivity_probe_service, qkview_service, tmm_debug_service, kubernetes/_metrics; frontend state machines beyond the guard sweep; test adequacy for element-2..n/error branches; the "performance optimizations" claim; runtime alembic upgrade; operator/MCP (not in diff).

Review Assessment

Findings & Action Items

🤖 Generated with Claude Code

- Convert AWS/IBM region validators from hardcoded-list rejection to
  pattern-based acceptance so new or private regions are selectable.
- Add Azure and GCP region validators using the same pattern-based
  approach; wire them into project, credential-template, and cluster
  schemas/routes.
- Update frontend region selectors (AWS, Cloud, SystemDefaults) to
  free-form inputs with datalist suggestions instead of restrictive
  dropdowns.
- Add KubernetesCluster.account_id and discovery_status columns plus
  fleet-health response fields for cloud context.
- Update unit tests for validators, project schemas, k8s schemas, and
  frontend selectors.
…ctor

- Extract shared is_operator_live_connected() helper and use it in the
  operator list, fleet health, and BNK health context.
- Reuse services.scanner.nodes.parse_node() in BNK fetch instead of
  duplicating the zone/instance-type label fallback logic.
- Add an optional label prop to CloudRegionSelector and reuse it in
  SystemDefaults to remove four near-identical region input blocks.
- Add connectivity and integration sections to BnkHealthResponse.
- Reuse the cluster's persisted status for connectivity and the shared
  operator live-connection helper for integration.
- Display ConnectivityBadge and IntegrationBadge in the dashboard banner.
- Add backend unit tests and frontend dashboard tests for the new fields.
Add /detect-credentials endpoint that discovers existing Kubernetes
clusters from a project's credential template for AWS, IBM Cloud,
Azure, and GCP. Each provider lists accessible clusters, builds a
kubeconfig from the template credentials, and registers the cluster
in BNK-Forge.

- New ClusterDiscoveryService orchestrates detection and registration.
- Provider helpers: EKS, ROKS, AKS, GKE.
- Frontend auto-detect switched to api.detectClustersFromCredentials().
- Backend + frontend tests updated; openapi.json and api-generated.ts
  regenerated.
- Move BNK Resources tab from System page to Fleet page
- Make GET /api/system/bnk-consumption viewer-accessible
- Move MCP Server from standalone sidebar page to System page tab
- Move Benchmarks sidebar item from OPERATE to OBSERVE section
- Update affected tests and regenerate OpenAPI types
- Add services/bnk/traffic_stats.py with analyze_traffic_stats() and
  fetch_tmm_traffic_stats() wrapping existing TMM debug helpers.
- Add Pydantic schemas for listener/egress/firewall-rule traffic stats.
- Wire trafficStats into the unified /f5bnk/data response.
- Surface hit/connection badges on F5BNKTopologyViewer listener/egress nodes.
- Add hits column to F5BNKPolicyViewer firewall-rule tables.
- Add total-connections summary chips in TrafficFlowOverview.
- Regenerate openapi.json and TypeScript generated types.
- Add backend unit tests and frontend component/hook tests.
- Enrich BNK topology with gateway/listener/route accepted/programmed conditions
- Add policy resolved/programmed status to topology and policy associations
- Add response models for gateway topology and policy associations endpoints
- Surface inline status badges in topology, traffic flow, and policy views
- Visualize cross-namespace ReferenceGrants in topology and traffic flow
- Extract shared ConditionsList component for Gateway/HTTPRoute/Service details
- Add lightweight Service detail fallback and register it in resource registry
- Regenerate OpenAPI spec and TypeScript generated types
…urce with settings

Module Library sync failed for official-bnk-forge-modules because the
clone used source.branch and then tried git checkout <git_ref>. A shallow
branch clone does not fetch tags, so checking out a tag ref (v2.2.0) failed
with 'pathspec did not match any file(s) known to git'.

Use source.git_ref (falling back to branch) directly in git clone --branch,
which accepts branch and tag names and already checks out the requested ref.

Also reconcile the canonical official module source with the current
module_library.git_* settings before a direct source sync, so a stale
branch/git_ref on the source row does not override the configured ref.

Validated: /api/module-sources/3/sync now succeeds, discovers 24 pack
modules, and updates the source row to branch=git_ref=release/2.2.
…d CNE available state

- Update has_condition() and get_condition_message() to inspect direct conditions arrays on parent_status dicts as well as standard K8s status.conditions.
- Add get_policy_operational_status() to evaluate status.ancestors and status.descendants condition refs for BNKNetPolicy and BNKSecPolicy in BNK 2.3.
- Update _build_cne_instance() to recognize Available/Reconciled condition states and populate default phase when healthy.
- Update _match_routes_to_listener() to check parent_status condition acceptance.
Stop per-request ThreadPoolExecutors from spawning 20 workers each, which
exploded backend PID count to 100+ under concurrent BNK page loads. Use
module-level shared executors with small caps for BNK CRD fetches and TMM
configview probes.

Add Redis-backed short-term caches for:
- EKS/GCP bearer tokens (10 min TTL)
- fetch_all_bnk_data results (30 s TTL)
- TMM traffic stats + configview uuid mappings (30 s / 5 min TTL)
- CWC license status (30 s) and report (60 s)

Each cache supports force=true to bypass when the UI explicitly refreshes.
License activation invalidates the cached status/report so the new state is
reflected immediately.
Add account_id, discovery_status, connectivity_status, integration_status,
zones, access_method, and node_count to the KubernetesCluster model, cluster
response schemas, serializers, and detail endpoints. Populate account_id from
credential-template discovery paths (AWS account, Azure subscription, GCP
project) and persist version/node_count/zones/last_synced_at from the scanner.

Includes migration v2_157 and a new GET /api/projects/{project_id}/connectivity
route backed by probe_project_clusters.
…uster

The _build_bnk_context helper added in the health refactor queries
ConnectedOperator by cluster.id. Tests that patched KubernetesService
returned a MagicMock cluster, causing a SQLite bind error. Configure the
mock to return the real test cluster so the endpoint can build its
connectivity/integration context.
JLCode-tech and others added 7 commits September 11, 2026 14:33
…zure api_server (M3)

M1 (coverage gap): the discovered-cluster kubeconfig is encrypted at rest via
encrypt_value(), but no test asserted it — a mutation to plaintext passed all 8
tests. Add test_persisted_kubeconfig_is_encrypted_at_rest, which reads the
persisted kubeconfig_encrypted column and asserts it is NOT plaintext
(no "apiVersion" in the stored value; stored != decrypt_value(stored)) yet
decrypts back to the real kubeconfig. Reverting encrypt_value to plaintext reds
this test (decrypt raises / stored equals its plaintext).

M3 (defensive): _detect_azure_clusters composed api_server as
f"https://{creds['server']}:443", which double-prefixes into a malformed URL if
creds['server'] ever carries a scheme or an explicit port. Add
_normalize_api_server_host() to strip a leading http(s):// scheme and a trailing
:port so a bare host, scheme-prefixed host, or host:port all yield one correct
https://host:443, with a 3-shape parametrized test.

Scoped to M1 + M3; region validators (M2) untouched. No API/model change.

Claude-Session: https://claude.ai/code/session_01UCsZXDxBsWV2s4kT47DwDW
JLCode-tech added a commit that referenced this pull request Sep 11, 2026
- Rebase onto work/v4-localhost (incorporating staging and #205)
- Renumber Alembic migration to v2_158 with down_revision v2_157
- Restrict azure_auth_method typing with Literal["service_principal", "sso"]
- Persist refreshed Azure SSO tokens on test connection by committing DB session
- Ensure SSO action menu and config completeness checks gate strictly on azure_auth_method == 'sso'
- Add regression component tests for refresh token DB persistence and config validation
@JLCode-tech

Copy link
Copy Markdown
Collaborator Author

Review Findings Resolution & Re-Review Request

All review items have been resolved, verified, and pushed:

  1. Rebase onto current staging: Cleanly rebased on top of staging tip (incorporating merged security: clear the two repo-wide P4 gates for staging (Trivy x/crypto + gitpython) #215 and feat(k8s): unified cloud OAuth token generation for GKE and AKS #208) with all .trivyignore / requirements.txt conflicts resolved.
  2. Minor-1 (Migration Sequence): Retained canonical v2_156 and v2_157 revisions. (feat(auth): add Microsoft Azure Service Principal and Entra ID SSO credential templates #207 has renumbered its migration to v2_158 descending from v2_157).
  3. Minor-3 (INV-6 Fail-Closed Guard): Updated ImportedBlueprintDeployDialog.tsx so rendering and submission gate on !!template (failing closed if template loading errors or is undefined). Vitest test updated and verified.
  4. CI Status: 🟢 100% Green across all P1–P4 jobs and CI Gate.

Ready for re-review.

@JLCode-tech

Copy link
Copy Markdown
Collaborator Author

Re-Review Request: Invariants & Merge Coordination Verified

All review action items from the review-discipline audit have been completed and verified against current staging:

  • Minor-1 (Alembic Namespace Coordination): Retained canonical v2_156 and v2_157 migrations on this branch. PR feat(auth): add Microsoft Azure Service Principal and Entra ID SSO credential templates #207 has re-keyed its migration to v2_158 (down_revision v2_157), ensuring zero revision collisions or branching heads across the PR stack.
  • Minor-2 (Staging Rebase & CVE Alignment): Cleanly rebased onto current staging tip; resolved duplicate .trivyignore and requirements.txt dependencies cleanly.
  • Minor-3 (INV-6 Fail-Closed Guard): Form rendering and submission in ImportedBlueprintDeployDialog.tsx strictly gate on Boolean(template) to fail closed on template load errors.
  • CI Verification: GitHub Actions CI Run 34563092084 is 100% Green across all 27 jobs (P1–P4 and CI Gate PASS).

Branch is fully ready for re-review and merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants