From 504e40dec0faa6ec26a03b97c964e71cc096e3e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Durmu=C5=9F?= Date: Sun, 8 Nov 2026 21:05:10 +0300 Subject: [PATCH 1/9] A leaf dials one connection per application account and can chain through other leaves, while every server stays in one cluster. Parent leaves carry downstream application accounts, hub routes update when the mesh changes, and an operator key change reloads without rolling the hub. --- .../managers/fog-platform-spec-manager.js | 3 + src/helpers/error-messages.js | 6 +- src/schemas/fog-platform-spec.js | 16 +- src/services/application-service.js | 15 +- src/services/fog-platform-service.js | 8 +- src/services/iofog-service.js | 32 + src/services/microservices-service.js | 22 + src/services/nats-auth-service.js | 9 +- src/services/nats-service.js | 817 ++++++++-- src/templates/nats/leaf.conf | 10 + test/src/data/fog-platform-managers.test.js | 23 + test/src/services/application-service.test.js | 19 +- .../src/services/fog-platform-service.test.js | 27 + test/src/services/iofog-service.test.js | 127 ++ .../services/microservices-service.test.js | 38 + .../src/services/nats-resolver-bundle.test.js | 6 + test/src/services/nats-service.test.js | 1335 +++++++++++++++++ 17 files changed, 2369 insertions(+), 144 deletions(-) diff --git a/src/data/managers/fog-platform-spec-manager.js b/src/data/managers/fog-platform-spec-manager.js index 28d231b6..e02433bc 100644 --- a/src/data/managers/fog-platform-spec-manager.js +++ b/src/data/managers/fog-platform-spec-manager.js @@ -26,6 +26,9 @@ class FogPlatformSpecManager extends BaseManager { async upsertSpec (fogUuid, specObject, transaction) { const sanitized = pickPlatformSpecFields(specObject) + if (sanitized.natsMode === 'server') { + delete sanitized.upstreamNatsServers + } await validateFogPlatformSpec(sanitized) const specJson = serializeSpecJson(sanitized) diff --git a/src/helpers/error-messages.js b/src/helpers/error-messages.js index 38cff9ea..14581a96 100644 --- a/src/helpers/error-messages.js +++ b/src/helpers/error-messages.js @@ -91,6 +91,10 @@ module.exports = { INVALID_SYSTEM_FOG_KUBERNETES: 'System fog can\'t be created when ControlPlane is Kubernetes', INVALID_UPSTREAM_ROUTER: 'Upstream router must be interior \'{}\'', INVALID_UPSTREAM_NATS: 'Upstream nats must be server \'{}\'', + NATS_UPSTREAM_MIXED: 'Upstream NATS list cannot mix servers and leaves', + NATS_UPSTREAM_SELF: 'Upstream NATS cannot include this agent', + NATS_UPSTREAM_CYCLE: 'Upstream NATS list contains a cycle', + NATS_UPSTREAM_UNEQUAL: 'Leaf upstreams must share the same upstream set', EDGE_ROUTER_HAS_DOWNSTREAM: 'Edge router {} has, or will have, downstream routers', HOST_IS_REQUIRED: '"host" is required', PORT_RESERVED: 'Port \'{}\' is reserved for internal use', @@ -122,7 +126,7 @@ module.exports = { NOT_KUBERNETES_ENV: 'Controller is not running in Kubernetes environment', K8S_SECRET_NOT_ALLOWED: 'Kubernetes secret type is not allowed in non-Kubernetes environment', INVALID_DEFAULT_BRIDGE: 'Invalid default bridge, If service type is not microservice, defaultBridge must be default-router\'{}\'', - INVALID_ROUTER_CONNECTION: 'Invalid router connection, router {} is not connected to {}', + DEFAULT_BRIDGE_UNREACHABLE: '{} is not reachable from agent \'{}\'', NO_AVAILABLE_BRIDGE_PORT: 'No bridge port available in range for {}', SERVICE_REQUIRES_ROUTER: 'TCP bridge service requires a router on agent \'{}\'', CONFIGMAP_ALREADY_EXISTS: 'ConfigMap with name {} already exists', diff --git a/src/schemas/fog-platform-spec.js b/src/schemas/fog-platform-spec.js index 30b038f3..b28ced79 100644 --- a/src/schemas/fog-platform-spec.js +++ b/src/schemas/fog-platform-spec.js @@ -200,6 +200,13 @@ function pickPlatformSpecFields (source) { return spec } +function dropServerUpstreamList (spec) { + if (spec && spec.natsMode === 'server') { + delete spec.upstreamNatsServers + } + return spec +} + function buildPlatformSpecFromFogData (fogData, options = {}) { const spec = pickPlatformSpecFields(fogData) if (options.applyCreateDefaults) { @@ -210,11 +217,13 @@ function buildPlatformSpecFromFogData (fogData, options = {}) { spec.natsMode = 'leaf' } } - return spec + return dropServerUpstreamList(spec) } function mergePlatformSpecPatch (existingSpec, patchFogData) { const merged = pickPlatformSpecFields(existingSpec) + const carriedUnusedServerList = merged.natsMode === 'server' && + patchFogData.upstreamNatsServers === undefined for (const field of FOG_PLATFORM_SPEC_SCALAR_FIELDS) { if (patchFogData[field] !== undefined) { merged[field] = patchFogData[field] @@ -225,7 +234,10 @@ function mergePlatformSpecPatch (existingSpec, patchFogData) { merged[field] = field === 'tags' ? normalizeSpecTags(patchFogData[field]) : patchFogData[field] } } - return merged + if (carriedUnusedServerList) { + delete merged.upstreamNatsServers + } + return dropServerUpstreamList(merged) } module.exports = { diff --git a/src/services/application-service.js b/src/services/application-service.js index 72a195b7..731ac13d 100644 --- a/src/services/application-service.js +++ b/src/services/application-service.js @@ -121,9 +121,9 @@ const deleteApplicationEndPoint = async function (conditions, isCLI, transaction throw new Errors.ValidationError('Cannot delete system application.') } - await _updateChangeTrackingsAndDeleteMicroservicesByApplicationId(conditions, true, transaction) + const fogUuids = await _updateChangeTrackingsAndDeleteMicroservicesByApplicationId(conditions, true, transaction) - await NatsAuthService.deleteAccountForApplication(application.id, transaction) + await NatsAuthService.deleteAccountForApplication(application.id, transaction, { fogUuids }) await ApplicationManager.delete(where, transaction) } @@ -136,10 +136,10 @@ const deleteSystemApplicationEndPoint = async function (conditions, isCLI, trans const application = await ApplicationManager.findOne({ ...conditions }, transaction) - await _updateChangeTrackingsAndDeleteMicroservicesByApplicationId(conditions, true, transaction) + const fogUuids = await _updateChangeTrackingsAndDeleteMicroservicesByApplicationId(conditions, true, transaction) if (application) { - await NatsAuthService.deleteAccountForApplication(application.id, transaction) + await NatsAuthService.deleteAccountForApplication(application.id, transaction, { fogUuids }) } await ApplicationManager.delete(where, transaction) @@ -465,12 +465,11 @@ async function _updateChangeTrackingsAndDeleteMicroservicesByApplicationId (cond } iofogUuids.push(ms.iofogUuid) } - iofogUuids - .filter(onlyUnique) - .filter((val) => val !== null) - for (const iofogUuid of iofogUuids) { + const fogUuids = iofogUuids.filter(onlyUnique).filter((val) => val != null && val !== '') + for (const iofogUuid of fogUuids) { await ChangeTrackingService.update(iofogUuid, ChangeTrackingService.events.microserviceFull, transaction) } + return fogUuids } module.exports = { diff --git a/src/services/fog-platform-service.js b/src/services/fog-platform-service.js index 558fbe71..30f8d8a3 100644 --- a/src/services/fog-platform-service.js +++ b/src/services/fog-platform-service.js @@ -199,11 +199,9 @@ async function resolveNatsConfigFromSpec (fogUuid, spec, transaction) { } const connections = await NatsConnectionManager.findAllWithNats({ sourceNats: nats.id }, transaction) - if (connections && connections.length > 0) { - natsConfig.upstreamNatsServers = connections.map( - (connection) => _getNatsUuid(connection.dest, defaultHub) - ) - } + natsConfig.upstreamNatsServers = (connections || []).map( + (connection) => _getNatsUuid(connection.dest, defaultHub) + ) return natsConfig } diff --git a/src/services/iofog-service.js b/src/services/iofog-service.js index 2ce141fe..3f374e11 100644 --- a/src/services/iofog-service.js +++ b/src/services/iofog-service.js @@ -339,6 +339,23 @@ async function _handleRouterCertificates (fogData, uuid, routerModeCrossedNone, } } +async function _validateSubmittedLeafUpstreams (natsMode, isSystem, upstreamNatsServers, transaction, fogUuid) { + if (natsMode !== 'leaf' || upstreamNatsServers === undefined) { + return + } + const defaultHub = await NatsInstanceManager.findOne({ isHub: true }, transaction) + const sourceInstance = fogUuid + ? await NatsInstanceManager.findByFog(fogUuid, transaction) + : null + await NatsService._validateAndReturnUpstreamNats( + upstreamNatsServers, + isSystem === true, + defaultHub, + transaction, + sourceInstance + ) +} + async function createFogEndPoint (fogData, isCLI, transaction) { await Validator.validate(fogData, Validator.schemas.iofogCreate) const isKubernetes = await checkKubernetesEnvironment() @@ -447,6 +464,13 @@ async function createFogEndPoint (fogData, isCLI, transaction) { ) } + await _validateSubmittedLeafUpstreams( + natsMode, + fogData.isSystem, + fogData.upstreamNatsServers, + transaction + ) + const fog = await FogManager.create(createFogData, transaction) // Set tags (synchronously, as this is a simple DB op) @@ -557,6 +581,14 @@ async function updateFogEndPoint (fogData, isCLI, transaction) { throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_SYSTEM_CHANGE)) } + await _validateSubmittedLeafUpstreams( + effectiveNatsMode, + isSystem, + fogData.upstreamNatsServers, + transaction, + fogData.uuid + ) + // Prevent overwriting detected arch (1 or 2) with "auto" (0) // If arch is being set to "auto" (0) but the agent has already detected its type (1 or 2), // preserve the detected type to ensure getAgentMicroservices can find matching images diff --git a/src/services/microservices-service.js b/src/services/microservices-service.js index 00b4f71c..1015a498 100644 --- a/src/services/microservices-service.js +++ b/src/services/microservices-service.js @@ -1034,6 +1034,15 @@ async function createMicroserviceEndPoint (microserviceData, isCLI, transaction) throw new Errors.ValidationError('Microservice natsAccess requires application natsAccess=true') } await _ensureNatsCredsForMicroservice(microservice, transaction) + } else if (microservice.iofogUuid) { + const app = await ApplicationManager.findOne({ id: microservice.applicationId }, transaction) + if (app && app.natsAccess && !app.isSystem) { + await NatsAuthService.enqueueNatsReconcileOutbox({ + reason: 'account-created', + applicationId: app.id, + fogUuids: [microservice.iofogUuid] + }, transaction) + } } const res = { @@ -1859,6 +1868,19 @@ async function updateMicroserviceEndPoint (microserviceUuid, microserviceData, i await _ensureNatsCredsForMicroservice(updatedMicroservice, transaction) } + const previousFogUuid = microservice.iofogUuid + const nextFogUuid = updatedMicroservice && updatedMicroservice.iofogUuid + if (previousFogUuid !== nextFogUuid && (previousFogUuid || nextFogUuid)) { + const application = await ApplicationManager.findOne({ id: microservice.applicationId }, transaction) + if (application && application.natsAccess && !application.isSystem) { + await NatsAuthService.enqueueNatsReconcileOutbox({ + reason: 'account-created', + applicationId: application.id, + fogUuids: [previousFogUuid, nextFogUuid].filter(Boolean) + }, transaction) + } + } + if (changeTrackingEnabled) { await _updateChangeTracking(true, microservice.iofogUuid, transaction) await _updateChangeTracking(true, updatedMicroservice.iofogUuid, transaction) diff --git a/src/services/nats-auth-service.js b/src/services/nats-auth-service.js index 4b4e5543..015aa3cf 100644 --- a/src/services/nats-auth-service.js +++ b/src/services/nats-auth-service.js @@ -701,7 +701,12 @@ async function ensureUserForMicroservice (microservice, transaction) { natsUserRuleId: userRule ? userRule.id : null }, transaction) - await _enqueueNatsReconcileOutbox({ fogUuids: [microservice.iofogUuid] }, transaction) + await _enqueueNatsReconcileOutbox({ + reason: 'account-created', + applicationId: microservice.applicationId, + fogUuids: microservice.iofogUuid ? [microservice.iofogUuid] : undefined, + mutationKind: 'access-enable' + }, transaction) return { account, user: natsUser } } @@ -1231,9 +1236,11 @@ async function revokeMicroserviceUser (microserviceUuid, transaction, ...rest) { } await NatsUserManager.delete({ id: user.id }, transaction) if (options.triggerReconcile !== false) { + const microservice = await MicroserviceManager.findOne({ uuid: microserviceUuid }, transaction) await _enqueueNatsReconcileOutbox({ reason: 'account-created', applicationId: account.applicationId, + fogUuids: microservice && microservice.iofogUuid ? [microservice.iofogUuid] : undefined, microserviceUuid, mutationKind: 'access-disable' }, transaction) diff --git a/src/services/nats-service.js b/src/services/nats-service.js index b27091e5..76c55d96 100644 --- a/src/services/nats-service.js +++ b/src/services/nats-service.js @@ -22,6 +22,7 @@ const SecretService = require('./secret-service') const NatsInstanceManager = require('../data/managers/nats-instance-manager') const NatsConnectionManager = require('../data/managers/nats-connection-manager') const NatsAccountManager = require('../data/managers/nats-account-manager') +const NatsOperatorManager = require('../data/managers/nats-operator-manager') const NatsReconcileTaskManager = require('../data/managers/nats-reconcile-task-manager') const ReconcileOutboxManager = require('../data/managers/reconcile-outbox-manager') const NatsUserManager = require('../data/managers/nats-user-manager') @@ -155,9 +156,10 @@ async function _updateConfigMapIfChanged (name, data, existing, transaction) { const existingHash = _configMapDataHash(existing.data) const newHash = _configMapDataHash(data) if (existingHash === newHash) { - return + return false } - return ConfigMapService.updateConfigMapEndpoint(name, { data, immutable: false }, transaction) + await ConfigMapService.updateConfigMapEndpoint(name, { data, immutable: false }, transaction) + return true } async function _ensureConfigMap (name, data, transaction) { @@ -166,7 +168,8 @@ async function _ensureConfigMap (name, data, transaction) { return _updateConfigMapIfChanged(name, data, existing, transaction) } try { - return await ConfigMapService.createConfigMapEndpoint({ name, data, immutable: false, useVault: true }, transaction) + await ConfigMapService.createConfigMapEndpoint({ name, data, immutable: false, useVault: true }, transaction) + return true } catch (error) { if (error.name !== 'ConflictError') { throw error @@ -179,6 +182,13 @@ async function _ensureConfigMap (name, data, transaction) { } } +async function _noteLeafConfigMapChange (fog, changed, transaction) { + if (!changed || !fog || !fog.uuid) { + return + } + await ChangeTrackingService.update(fog.uuid, ChangeTrackingService.events.microserviceList, transaction) +} + async function _ensureVolumeMount (name, opts, transaction) { try { await VolumeMountService.getVolumeMountEndpoint(name, transaction) @@ -361,7 +371,7 @@ async function _buildHubJwtBundle (transaction) { return jwtBundle } -async function _getLeafAppIds (fog, transaction) { +async function _localLeafAppIds (fog, transaction) { const microservices = await MicroserviceManager.findAll({ iofogUuid: fog.uuid }, transaction) const appIds = [...new Set(microservices.map(ms => ms.applicationId).filter(Boolean))] const nonSystemAppIds = [] @@ -375,7 +385,50 @@ async function _getLeafAppIds (fog, transaction) { } /** - * Build JWT bundle for a fog using preloaded maps (used inside reconcile to avoid per-fog DB). + * Applications this leaf bridges: non-system applications with NATS access and a + * microservice on this agent, plus those same applications on every leaf that + * dials this one, walked to the bottom of the chain. A repeated agent stops the + * walk. Leaf system accounts are not application accounts and are not included. + */ +async function _getLeafAppIds (fog, transaction) { + const seenFogs = new Set() + const seenApps = new Set() + const out = [] + + async function walk (currentFog) { + if (!currentFog || !currentFog.uuid || seenFogs.has(currentFog.uuid)) { + return + } + seenFogs.add(currentFog.uuid) + const localAppIds = await _localLeafAppIds(currentFog, transaction) + for (const appId of localAppIds) { + if (seenApps.has(appId)) { + continue + } + seenApps.add(appId) + out.push(appId) + } + const instance = await NatsInstanceManager.findByFog(currentFog.uuid, transaction) + if (!instance || !instance.isLeaf || instance.id == null) { + return + } + const inbound = await NatsConnectionManager.findAllWithNats({ destNats: instance.id }, transaction) || [] + for (const connection of inbound) { + const source = connection && connection.source + if (!source || !source.isLeaf || !source.iofogUuid) { + continue + } + await walk({ uuid: source.iofogUuid }) + } + } + + await walk(fog) + return out +} + +/** + * Build resolver files for one agent. A leaf includes downstream applications. + * Account tokens prefer the accounts already loaded for this pass. * @param {object} fog * @param {boolean} forLeaf * @param {{ applicationsWithNatsById: Map, accountByAppId: Map, systemAccount: object|null, microservicesByFog: Map }} maps @@ -390,13 +443,16 @@ async function _buildJwtBundleFromMaps (fog, forLeaf, maps, transaction) { if (forLeaf) { const leafSystemAccount = await NatsAuthService.ensureLeafSystemAccount(fog, transaction) jwtBundle[`${leafSystemAccount.publicKey}.jwt`] = leafSystemAccount.jwt - for (const appId of appIds) { - const app = applicationsWithNatsById.get(appId) - if (!app || app.isSystem || !app.natsAccess) continue + const bridgedAppIds = await _getLeafAppIds(fog, transaction) + for (const appId of bridgedAppIds) { let account = accountByAppId.get(appId) if (!account) { account = await NatsAuthService.ensureAccountForApplication(appId, transaction) + if (account) { + accountByAppId.set(appId, account) + } } + if (!account) continue jwtBundle[`${account.publicKey}.jwt`] = account.jwt } } else { @@ -479,6 +535,7 @@ async function _buildLeafCredsConfigMap (fog, natsInstance, transaction) { } else { await ConfigMapService.createConfigMapEndpoint({ name: leafCredsMapName, data: credsData, immutable: false, useVault: true }, transaction) } + await _noteLeafConfigMapChange(fog, true, transaction) } await _ensureVolumeMount(leafCredsMapName, { configMapName: leafCredsMapName }, transaction) @@ -514,8 +571,21 @@ async function ensureLeafCredsForFog (fogUuid, transaction) { if (natsInstance.isLeaf) { await _buildLeafRemotes(fog, natsInstance, transaction) const jwtBundle = await _buildJwtBundle(fog, natsInstance.isLeaf, transaction) - await _ensureConfigMap(natsJwtBundleConfigMap(fog), jwtBundle, transaction) + const bundleChanged = await _ensureConfigMap(natsJwtBundleConfigMap(fog), jwtBundle, transaction) + await _noteLeafConfigMapChange(fog, bundleChanged, transaction) + } +} + +function _leafRemoteUrl (dest) { + if (!dest || dest.host == null) { + return null } + const host = String(dest.host).trim() + if (!host) { + return null + } + const port = dest.leafPort || DEFAULT_LEAF_PORT + return `tls://${host}:${port}` } async function _computeLeafRemotesForInstance (fog, natsInstance, transaction, certName) { @@ -527,6 +597,19 @@ async function _computeLeafRemotesForInstance (fog, natsInstance, transaction, c if (!upstreamConnections || upstreamConnections.length === 0) { return remotes } + const urls = [] + const seenUrls = new Set() + for (const upstream of upstreamConnections) { + const url = _leafRemoteUrl(upstream && upstream.dest) + if (!url || seenUrls.has(url)) { + continue + } + seenUrls.add(url) + urls.push(url) + } + if (urls.length === 0) { + return remotes + } const tlsConfig = certName ? { ca_file: `${NATS_CERTS_DIR}/${certName}/ca.crt`, @@ -537,25 +620,19 @@ async function _computeLeafRemotesForInstance (fog, natsInstance, transaction, c timeout: '3s' } : undefined + const leafUserName = `leaf-${slugifyName(fog.name)}` const appIds = await _getLeafAppIds(fog, transaction) for (const appId of appIds) { const account = await NatsAuthService.ensureAccountForApplication(appId, transaction) - for (const upstream of upstreamConnections) { - if (!upstream.dest || !upstream.dest.host) { - continue - } - const port = upstream.dest.leafPort || DEFAULT_LEAF_PORT - const leafUserName = `leaf-${slugifyName(fog.name)}` - const remote = { - urls: [`tls://${upstream.dest.host}:${port}`], - account: account.publicKey, - credentials: `${NATS_CREDS_DIR}/${slugifyName(account.name)}/${slugifyName(leafUserName)}.creds` - } - if (tlsConfig) { - remote.tls = tlsConfig - } - remotes.push(remote) + const remote = { + urls: urls.slice(), + account: account.publicKey, + credentials: `${NATS_CREDS_DIR}/${slugifyName(account.name)}/${slugifyName(leafUserName)}.creds` + } + if (tlsConfig) { + remote.tls = tlsConfig } + remotes.push(remote) } return remotes } @@ -585,12 +662,50 @@ async function _getControllerManagedClusterRoutes (transaction) { return routes } +function _peerClusterRoute (peer) { + if (!peer || peer.host == null) { + return null + } + const host = String(peer.host).trim() + if (!host) { + return null + } + return `nats://${host}:${peer.clusterPort || DEFAULT_CLUSTER_PORT}` +} + +function _serverConfigTemplate (clusterRoutes) { + if (!clusterRoutes || clusterRoutes.length === 0) { + return readTemplate('server-no-cluster.conf') + } + return readTemplate('server.conf') +} + async function _computeClusterRoutesForInstance (natsInstance, transaction) { - const allServerInstances = await NatsInstanceManager.findAll({ isLeaf: false }, transaction) + if (!natsInstance || natsInstance.isLeaf || natsInstance.id == null) { + return [] + } + const connections = await NatsConnectionManager.findAllWithNats( + { sourceNats: natsInstance.id }, + transaction + ) + const ownHost = natsInstance.host == null ? '' : String(natsInstance.host).trim() const routes = [] - for (const inst of allServerInstances || []) { - if (!inst.host) continue - routes.push(`nats://${inst.host}:${inst.clusterPort || DEFAULT_CLUSTER_PORT}`) + const seen = new Set() + for (const connection of connections || []) { + const dest = connection.dest + if (!dest || dest.id === natsInstance.id || dest.isLeaf) { + continue + } + const host = dest.host == null ? '' : String(dest.host).trim() + if (ownHost && host === ownHost) { + continue + } + const route = _peerClusterRoute(dest) + if (!route || seen.has(route)) { + continue + } + seen.add(route) + routes.push(route) } return routes } @@ -635,6 +750,57 @@ async function _patchK8sJwtBundleExternal (fullServerJwtBundle) { } } +function _replaceOperatorJwtLine (content, operatorJwt) { + const match = content.match(/^operator\s*=\s*(\S+)\s*$/m) + if (!match) { + return { status: 'missing-line' } + } + if (match[1] === operatorJwt) { + return { status: 'unchanged' } + } + return { + status: 'changed', + content: content.replace(/^operator\s*=\s*\S+\s*$/m, `operator = ${operatorJwt}`) + } +} + +async function _patchK8sHubOperatorJwtOnce (operatorJwt) { + const configMap = await K8sClient.getConfigMap(K8S_NATS_SERVER_CONFIG_MAP, { ignoreNotFound: true }) + if (!configMap || !configMap.data) { + logger.debug(`Hub ConfigMap ${K8S_NATS_SERVER_CONFIG_MAP} not found or empty (expected before operator creates it)`) + return + } + const content = configMap.data[NATS_CONFIG_KEY] + if (!content) { + logger.warn(`Key ${NATS_CONFIG_KEY} not found in ConfigMap ${K8S_NATS_SERVER_CONFIG_MAP}`) + return + } + const replaced = _replaceOperatorJwtLine(content, operatorJwt) + if (replaced.status === 'missing-line') { + logger.warn(`Could not find operator line in ${K8S_NATS_SERVER_CONFIG_MAP}`) + return + } + if (replaced.status === 'unchanged') { + return + } + await K8sClient.patchConfigMap( + K8S_NATS_SERVER_CONFIG_MAP, + { data: { [NATS_CONFIG_KEY]: replaced.content } }, + { ignoreNotFound: true } + ) +} + +async function _patchK8sHubOperatorJwtExternal (operatorJwt) { + try { + await _patchK8sHubOperatorJwtOnce(operatorJwt) + } catch (error) { + if (!K8sClient.isK8sConflict(error)) { + throw error + } + await _patchK8sHubOperatorJwtOnce(operatorJwt) + } +} + async function _rolloutNatsStatefulSetExternal () { await K8sClient.rolloutStatefulSet('nats') } @@ -668,7 +834,7 @@ function _scheduleK8sAfterCommit (transaction, fn) { } } -async function _applyEnsureNatsK8sExternal (k8sHubPatch) { +async function _applyEnsureNatsK8sExternal (k8sHubPatch, k8sRollout) { if (!k8sHubPatch) { return } @@ -676,6 +842,15 @@ async function _applyEnsureNatsK8sExternal (k8sHubPatch) { await _patchK8sHubConfigMapClusterRoutesExternal(k8sHubPatch) } catch (err) { logger.warn(`Failed to patch Kubernetes NATS hub ConfigMap cluster routes: ${err.message}`) + return + } + if (!k8sRollout) { + return + } + try { + await _rolloutNatsStatefulSetExternal() + } catch (rolloutErr) { + logger.warn(`Failed to rollout NATS StatefulSet after hub ConfigMap patch: ${rolloutErr.message}`) } } @@ -697,29 +872,58 @@ async function _applyCleanupNatsK8sExternal (k8sCleanup) { } } -async function _applyK8sJwtBundleExternal (fullServerJwtBundle) { - if (!fullServerJwtBundle) { +async function _applyK8sHubAuthExternal ({ fullServerJwtBundle, hubOperatorJwt } = {}) { + if (fullServerJwtBundle) { + try { + await _patchK8sJwtBundleExternal(fullServerJwtBundle) + } catch (err) { + logger.warn(`Failed to patch Kubernetes NATS hub JWT bundle ConfigMap: ${err.message}`) + } + } + if (!hubOperatorJwt) { return } try { - await _patchK8sJwtBundleExternal(fullServerJwtBundle) + await _patchK8sHubOperatorJwtExternal(hubOperatorJwt) } catch (err) { - logger.warn(`Failed to patch Kubernetes NATS hub JWT bundle ConfigMap: ${err.message}`) + logger.warn(`Failed to patch Kubernetes NATS hub operator JWT: ${err.message}`) } } function _clusterConfigRequiresRebuild (oldRoutes, newRoutes) { - const oldLen = (oldRoutes && oldRoutes.length) || 0 - const newLen = (newRoutes && newRoutes.length) || 0 - if (oldLen === 0 && newLen > 0) { + const oldList = oldRoutes || [] + const newList = newRoutes || [] + const oldClustered = oldList.length > 0 + const newClustered = newList.length > 0 + if (oldClustered !== newClustered) { return true } - if (oldLen > 0 && newLen < oldLen) { - const oldSet = new Set(oldRoutes || []) - const everyNewInOld = (newRoutes || []).every(r => oldSet.has(r)) - return everyNewInOld + if (!oldClustered || newList.length >= oldList.length) { + return false + } + const oldSet = new Set(oldList) + return newList.every((route) => oldSet.has(route)) +} + +function _sameRouteSet (left, right) { + const leftList = left || [] + const rightList = right || [] + if (leftList.length !== rightList.length) { + return false + } + const leftSet = new Set(leftList) + return rightList.every((route) => leftSet.has(route)) +} + +function _controllerClusterRouteUpdate (oldRoutes, newRoutes) { + const nextRoutes = newRoutes || [] + if (_sameRouteSet(oldRoutes, nextRoutes)) { + return { k8sHubPatch: null, k8sRollout: false } + } + return { + k8sHubPatch: nextRoutes, + k8sRollout: _clusterConfigRequiresRebuild(oldRoutes, nextRoutes) } - return false } async function _renderAndPersistNatsConfig (fog, natsInstance, certName, mqttCertName, configMapName, configKey, template, isHub, isServerMode, transaction) { @@ -728,8 +932,8 @@ async function _renderAndPersistNatsConfig (fog, natsInstance, certName, mqttCer : await NatsAuthService.ensureLeafSystemAccount(fog, transaction) const operator = await NatsAuthService.ensureOperator(transaction) const clusterRoutes = (isHub || isServerMode) ? await _computeClusterRoutesForInstance(natsInstance, transaction) : [] - if ((isHub || isServerMode) && clusterRoutes.length === 1) { - template = readTemplate('server-no-cluster.conf') + if (isHub || isServerMode) { + template = _serverConfigTemplate(clusterRoutes) } const leafRemotes = isServerMode ? [] : await _computeLeafRemotesForInstance(fog, natsInstance, transaction, certName) const jetstreamKey = await _ensureJetstreamKey(fog, transaction) @@ -790,37 +994,141 @@ async function _ensureJetstreamKey (fog, transaction) { return { secretName, jsk: key } } -async function _validateAndReturnUpstreamNats (upstreamNatsIds, isSystemFog, defaultHub, transaction) { - if (!upstreamNatsIds) { - if (!defaultHub) { - if (isSystemFog) { - return [] - } - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_NATS, Constants.DEFAULT_NATS_HUB_NAME)) +function _sameIdSet (left, right) { + if (left.size !== right.size) { + return false + } + for (const id of left) { + if (!right.has(id)) { + return false + } + } + return true +} + +async function _directDestinationIds (sourceId, transaction) { + const connections = await NatsConnectionManager.findAllWithNats({ sourceNats: sourceId }, transaction) + const ids = new Set() + for (const connection of connections || []) { + if (connection.dest && connection.dest.id != null) { + ids.add(connection.dest.id) } + } + return ids +} - const allSystemFogs = await FogManager.findAll({ isSystem: true }, transaction) - const systemFogNats = [] - for (const systemFog of allSystemFogs) { - const systemFogNatsInstance = await NatsInstanceManager.findOne({ - iofogUuid: systemFog.uuid - }, transaction) - if (systemFogNatsInstance) { - systemFogNats.push(systemFogNatsInstance) +async function _leafUpstreamReaches (startId, forbiddenIds, transaction) { + const seen = new Set([startId]) + const queue = [startId] + while (queue.length > 0) { + const id = queue.shift() + const connections = await NatsConnectionManager.findAllWithNats({ sourceNats: id }, transaction) + for (const connection of connections || []) { + const dest = connection.dest + if (!dest || dest.id == null) { + continue + } + if (forbiddenIds.has(dest.id)) { + return true + } + if (!dest.isLeaf || seen.has(dest.id)) { + continue } + seen.add(dest.id) + queue.push(dest.id) } + } + return false +} - const combinedNats = [defaultHub] - for (const systemFogNatsInstance of systemFogNats) { - if (systemFogNatsInstance.id !== defaultHub.id) { - combinedNats.push(systemFogNatsInstance) +async function _repairServerClusterMesh (transaction) { + const servers = await NatsInstanceManager.findAll({ isLeaf: false }, transaction) || [] + const serverIds = new Set(servers.map((server) => server.id)) + // Only server-sourced rows belong to the mesh. A leaf upstream that names a server stays. + + for (const server of servers) { + const existing = await NatsConnectionManager.findAllWithNats({ sourceNats: server.id }, transaction) || [] + const keptDestIds = new Set() + for (const connection of existing) { + const destId = connection.dest && connection.dest.id + const destIsServer = destId != null && destId !== server.id && serverIds.has(destId) + if (!destIsServer || keptDestIds.has(destId)) { + if (connection.id != null) { + await NatsConnectionManager.delete({ id: connection.id }, transaction) + } + continue + } + keptDestIds.add(destId) + } + for (const other of servers) { + if (other.id === server.id || keptDestIds.has(other.id)) { + continue } + await NatsConnectionManager.create({ + sourceNats: server.id, + destNats: other.id + }, transaction) } + } +} - return combinedNats +async function _replaceLeafUpstreamConnections (sourceId, upstreamNats, transaction) { + const existingConnections = await NatsConnectionManager.findAllWithNats( + { sourceNats: sourceId }, + transaction + ) || [] + const desiredDestIds = new Set((upstreamNats || []).map((node) => node.id)) + const existingDestIds = new Set() + for (const connection of existingConnections) { + const destId = connection.dest && connection.dest.id + if (!destId || !desiredDestIds.has(destId) || existingDestIds.has(destId)) { + await NatsConnectionManager.delete({ id: connection.id }, transaction) + continue + } + existingDestIds.add(destId) } + for (const upstream of upstreamNats || []) { + if (!existingDestIds.has(upstream.id)) { + await NatsConnectionManager.create({ + sourceNats: sourceId, + destNats: upstream.id + }, transaction) + } + } +} - const upstreamNats = [] +async function _flagClusterRouteRebuilds (oldRoutesByInstanceId, transaction) { + const servers = await NatsInstanceManager.findAll({ isLeaf: false }, transaction) || [] + for (const server of servers) { + const oldRoutes = (oldRoutesByInstanceId && oldRoutesByInstanceId.get(server.id)) || [] + const newRoutes = await _computeClusterRoutesForInstance(server, transaction) + if (!_clusterConfigRequiresRebuild(oldRoutes, newRoutes) || !server.iofogUuid) { + continue + } + const natsMicroservice = await MicroserviceManager.findOne({ + iofogUuid: server.iofogUuid, + name: getSystemMicroserviceName('nats') + }, transaction) + if (!natsMicroservice) { + continue + } + await MicroserviceManager.update({ uuid: natsMicroservice.uuid }, { rebuild: true }, transaction) + await ChangeTrackingService.update(server.iofogUuid, ChangeTrackingService.events.microserviceList, transaction) + } +} + +async function _validateAndReturnUpstreamNats (upstreamNatsIds, isSystemFog, defaultHub, transaction, sourceInstance) { + if (upstreamNatsIds == null) { + if (!defaultHub) { + if (isSystemFog) { + return [] + } + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_NATS, Constants.DEFAULT_NATS_HUB_NAME)) + } + return [defaultHub] + } + + const resolved = [] for (const upstreamId of upstreamNatsIds) { let upstreamNatsInstance = upstreamId === Constants.DEFAULT_NATS_HUB_NAME ? defaultHub @@ -835,14 +1143,150 @@ async function _validateAndReturnUpstreamNats (upstreamNatsIds, isSystemFog, def if (!upstreamNatsInstance) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_NATS, upstreamId)) } - if (upstreamNatsInstance.isLeaf) { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_UPSTREAM_NATS, upstreamId)) + resolved.push(upstreamNatsInstance) + } + + const upstreamNats = [] + const seenIds = new Set() + for (const instance of resolved) { + if (seenIds.has(instance.id)) { + continue + } + seenIds.add(instance.id) + upstreamNats.push(instance) + } + if (upstreamNats.length === 0) { + return [] + } + + const allServers = upstreamNats.every((instance) => !instance.isLeaf) + const allLeaves = upstreamNats.every((instance) => instance.isLeaf) + if (!allServers && !allLeaves) { + throw new Errors.ValidationError(ErrorMessages.NATS_UPSTREAM_MIXED) + } + if (sourceInstance && upstreamNats.some((instance) => instance.id === sourceInstance.id)) { + throw new Errors.ValidationError(ErrorMessages.NATS_UPSTREAM_SELF) + } + if (!allLeaves) { + return upstreamNats + } + + const namedIds = new Set(upstreamNats.map((instance) => instance.id)) + const sourceId = sourceInstance && sourceInstance.id + for (const parent of upstreamNats) { + const forbiddenIds = new Set(namedIds) + if (sourceId != null) { + forbiddenIds.add(sourceId) + } + forbiddenIds.delete(parent.id) + const reaches = await _leafUpstreamReaches(parent.id, forbiddenIds, transaction) + if (reaches) { + throw new Errors.ValidationError(ErrorMessages.NATS_UPSTREAM_CYCLE) } - upstreamNats.push(upstreamNatsInstance) } + + if (upstreamNats.length >= 2) { + const destinationSets = [] + for (const parent of upstreamNats) { + destinationSets.push(await _directDestinationIds(parent.id, transaction)) + } + const first = destinationSets[0] + for (const other of destinationSets.slice(1)) { + if (!_sameIdSet(first, other)) { + throw new Errors.ValidationError(ErrorMessages.NATS_UPSTREAM_UNEQUAL) + } + } + } + return upstreamNats } +async function _storeNatsUpstreams (savedInstance, fog, natsConfig, defaultHub, transaction) { + if (!savedInstance.isLeaf) { + // A server does not store the submitted upstream list. + await _repairServerClusterMesh(transaction) + return + } + + let upstreamIds = natsConfig && natsConfig.upstreamNatsServers + if (typeof upstreamIds === 'string') { + try { + upstreamIds = JSON.parse(upstreamIds) + } catch (error) { + upstreamIds = [] + } + } + const upstreamNats = await _validateAndReturnUpstreamNats( + upstreamIds, + fog.isSystem === true, + defaultHub, + transaction, + savedInstance + ) + const previousConnections = await NatsConnectionManager.findAllWithNats( + { sourceNats: savedInstance.id }, + transaction + ) || [] + await _replaceLeafUpstreamConnections(savedInstance.id, upstreamNats, transaction) + await _enqueueLeafUpstreamRefresh(savedInstance, previousConnections, upstreamNats, transaction) +} + +async function _enqueueLeafUpstreamRefresh (savedInstance, previousConnections, upstreamNats, transaction) { + const previousIds = new Set() + const previousLeafById = new Map() + for (const connection of previousConnections || []) { + const dest = connection && connection.dest + if (!dest || dest.id == null) { + continue + } + previousIds.add(dest.id) + if (dest.isLeaf && dest.iofogUuid) { + previousLeafById.set(dest.id, dest) + } + } + const nextIds = new Set() + const nextLeafById = new Map() + for (const upstream of upstreamNats || []) { + if (!upstream || upstream.id == null) { + continue + } + nextIds.add(upstream.id) + if (upstream.isLeaf && upstream.iofogUuid) { + nextLeafById.set(upstream.id, upstream) + } + } + if (_sameIdSet(previousIds, nextIds)) { + return + } + const fogUuids = new Set() + if (savedInstance && savedInstance.isLeaf && savedInstance.iofogUuid) { + fogUuids.add(savedInstance.iofogUuid) + } + const changedParents = [] + for (const [id, dest] of previousLeafById) { + if (!nextIds.has(id)) { + fogUuids.add(dest.iofogUuid) + changedParents.push(dest) + } + } + for (const [id, dest] of nextLeafById) { + if (!previousIds.has(id)) { + fogUuids.add(dest.iofogUuid) + changedParents.push(dest) + } + } + for (const parent of changedParents) { + await _addAncestorLeafFogs(parent, fogUuids, transaction) + } + if (fogUuids.size === 0) { + return + } + await ReconcileOutboxManager.enqueueNats({ + reason: 'leaf-upstream-changed', + fogUuids: [...fogUuids] + }, transaction) +} + async function _ensureNatsMicroservice (fog, mode, transaction) { const application = await ensureSystemApplication(fog, transaction) const name = getSystemMicroserviceName('nats') @@ -1045,7 +1489,8 @@ async function ensureNatsForFogAuthPrepDb (fog, natsConfig, prep, transaction) { if (isLeaf) { const jwtBundle = await _buildJwtBundle(fog, true, transaction) - await _ensureConfigMap(natsJwtBundleConfigMap(fog), jwtBundle, transaction) + const bundleChanged = await _ensureConfigMap(natsJwtBundleConfigMap(fog), jwtBundle, transaction) + await _noteLeafConfigMapChange(fog, bundleChanged, transaction) } else { const fullJwtBundle = await _buildHubJwtBundle(transaction) await _ensureConfigMap(K8S_NATS_JWT_BUNDLE_CONFIG_MAP, fullJwtBundle, transaction) @@ -1115,14 +1560,18 @@ async function ensureNatsForFogTopologyDb (fog, natsConfig, prep, authCtx, trans const instance = await NatsInstanceManager.findByFog(fog.uuid, transaction) let oldRoutesByInstanceId = null - let oldRoutesForCurrent = [] - if (!isLeaf) { + const repairsServerMesh = !isLeaf || !!(instance && !instance.isLeaf) + const trackControllerRoutes = repairsServerMesh && _isKubernetesControlPlane() + let oldControllerRoutes = null + if (trackControllerRoutes) { + oldControllerRoutes = await _getControllerManagedClusterRoutes(transaction) + } + if (repairsServerMesh) { const allServerInstances = await NatsInstanceManager.findAll({ isLeaf: false }, transaction) oldRoutesByInstanceId = new Map() for (const inst of allServerInstances || []) { oldRoutesByInstanceId.set(inst.id, await _computeClusterRoutesForInstance(inst, transaction)) } - oldRoutesForCurrent = instance ? (oldRoutesByInstanceId.get(instance.id) || []) : [] } const jsStorageSizeRaw = (natsConfig && natsConfig.jsStorageSize) != null ? String(natsConfig.jsStorageSize).trim() : null const jsMemoryStoreSizeRaw = (natsConfig && natsConfig.jsMemoryStoreSize) != null ? String(natsConfig.jsMemoryStoreSize).trim() : null @@ -1166,32 +1615,10 @@ async function ensureNatsForFogTopologyDb (fog, natsConfig, prep, authCtx, trans await _removeLeafOnlyArtifactsForFog(fog, microservice, transaction) } - let upstreamIds = natsConfig && natsConfig.upstreamNatsServers - if (typeof upstreamIds === 'string') { - try { - upstreamIds = JSON.parse(upstreamIds) - } catch (error) { - upstreamIds = [] - } - } const defaultHub = await NatsInstanceManager.findOne({ isHub: true }, transaction) - const upstreamNats = await _validateAndReturnUpstreamNats(upstreamIds, fog.isSystem === true, defaultHub, transaction) - - const existingConnections = await NatsConnectionManager.findAllWithNats( - { sourceNats: savedInstance.id }, - transaction - ) - const existingDestIds = new Set(existingConnections.map(conn => conn.dest && conn.dest.id).filter(Boolean)) - const desiredDestIds = new Set(upstreamNats.map(node => node.id)) - for (const connection of existingConnections) { - if (connection.dest && !desiredDestIds.has(connection.dest.id)) { - await NatsConnectionManager.delete({ id: connection.id }, transaction) - } - } - for (const upstream of upstreamNats) { - if (!existingDestIds.has(upstream.id)) { - await NatsConnectionManager.create({ sourceNats: savedInstance.id, destNats: upstream.id }, transaction) - } + await _storeNatsUpstreams(savedInstance, fog, natsConfig, defaultHub, transaction) + if (savedInstance.isLeaf && instance && !instance.isLeaf) { + await _repairServerClusterMesh(transaction) } await _renderAndPersistNatsConfig( @@ -1208,19 +1635,16 @@ async function ensureNatsForFogTopologyDb (fog, natsConfig, prep, authCtx, trans ) let k8sHubPatch = null - if (_isKubernetesControlPlane() && !savedInstance.isLeaf && savedInstance.host) { - k8sHubPatch = await _getControllerManagedClusterRoutes(transaction) + let k8sRollout = false + if (trackControllerRoutes) { + const newControllerRoutes = await _getControllerManagedClusterRoutes(transaction) + const controllerRouteUpdate = _controllerClusterRouteUpdate(oldControllerRoutes, newControllerRoutes) + k8sHubPatch = controllerRouteUpdate.k8sHubPatch + k8sRollout = controllerRouteUpdate.k8sRollout } - if (!savedInstance.isLeaf) { - const newRoutesForCurrent = await _computeClusterRoutesForInstance(savedInstance, transaction) - if (_clusterConfigRequiresRebuild(oldRoutesForCurrent, newRoutesForCurrent)) { - const natsMicroservice = await MicroserviceManager.findOne({ iofogUuid: fog.uuid, name: getSystemMicroserviceName('nats') }, transaction) - if (natsMicroservice) { - await MicroserviceManager.update({ uuid: natsMicroservice.uuid }, { rebuild: true }, transaction) - await ChangeTrackingService.update(fog.uuid, ChangeTrackingService.events.microserviceList, transaction) - } - } + if (repairsServerMesh) { + await _flagClusterRouteRebuilds(oldRoutesByInstanceId, transaction) const allServerInstancesNow = await NatsInstanceManager.findAll({ isLeaf: false }, transaction) const otherInstances = (allServerInstancesNow || []).filter(i => i.id !== savedInstance.id) if (otherInstances.length > 0) { @@ -1275,7 +1699,7 @@ async function ensureNatsForFogTopologyDb (fog, natsConfig, prep, authCtx, trans } await ChangeTrackingService.update(fog.uuid, ChangeTrackingService.events.microserviceList, transaction) - return { microservice, k8sHubPatch } + return { microservice, k8sHubPatch, k8sRollout } } /** @deprecated Use phased ensure; kept for grep gates and direct unit tests */ @@ -1322,7 +1746,7 @@ async function _ensureNatsForFogPhased (fog, natsConfig, { priority = PRIORITY_I (transaction) => ensureNatsForFogTopologyDb(fog, natsConfig, prep, authCtx, transaction), { priority, label: 'nats.ensure.topology' } ) - await _applyEnsureNatsK8sExternal(result && result.k8sHubPatch) + await _applyEnsureNatsK8sExternal(result && result.k8sHubPatch, result && result.k8sRollout) return result && result.microservice } @@ -1385,11 +1809,25 @@ async function cleanupNatsForFogDb (fog, transaction) { const wasLeaf = !!(natsInstance && natsInstance.isLeaf) const wasServer = !!(natsInstance && !natsInstance.isLeaf) const wasHub = !!(natsInstance && natsInstance.isHub) + let oldServerRoutesById = null + if (wasServer) { + oldServerRoutesById = new Map() + const servers = await NatsInstanceManager.findAll({ isLeaf: false }, transaction) || [] + for (const server of servers) { + if (server.id === natsInstance.id) { + continue + } + oldServerRoutesById.set(server.id, await _computeClusterRoutesForInstance(server, transaction)) + } + } let k8sCleanup = null if (natsInstance) { await NatsConnectionManager.delete({ sourceNats: natsInstance.id }, transaction) await NatsConnectionManager.delete({ destNats: natsInstance.id }, transaction) await NatsInstanceManager.delete({ id: natsInstance.id }, transaction) + if (oldServerRoutesById) { + await _flagClusterRouteRebuilds(oldServerRoutesById, transaction) + } if (_isKubernetesControlPlane() && !natsInstance.isLeaf) { k8sCleanup = { desiredControllerRoutes: await _getControllerManagedClusterRoutes(transaction), @@ -1491,13 +1929,61 @@ async function cleanupNatsForFog (...args) { return _cleanupNatsForFogPhased(fog, { priority: PRIORITY_INTERACTIVE }) } -function _getAffectedFogUuidsForApplication (applicationId, natsInstanceByFog, microservicesByFog) { +async function _addAncestorLeafFogs (startInstance, out, transaction) { + const seen = new Set() + const queue = [] + if (startInstance && startInstance.id != null) { + seen.add(startInstance.id) + queue.push(startInstance) + } + while (queue.length > 0) { + const current = queue.shift() + const upstreams = await NatsConnectionManager.findAllWithNats({ sourceNats: current.id }, transaction) || [] + for (const connection of upstreams) { + const dest = connection && connection.dest + if (!dest || dest.id == null || !dest.isLeaf || !dest.iofogUuid) { + continue + } + out.add(dest.iofogUuid) + if (!seen.has(dest.id)) { + seen.add(dest.id) + queue.push(dest) + } + } + } +} + +async function _getAffectedFogUuidsForApplication (applicationId, natsInstanceByFog, microservicesByFog, transaction, seedFogUuids) { const out = new Set() for (const [fogUuid, ni] of natsInstanceByFog) { - if (!ni.isLeaf) out.add(fogUuid) + if (ni && !ni.isLeaf) out.add(fogUuid) } - for (const [fogUuid, msList] of microservicesByFog) { - if (msList.some(ms => ms.applicationId === applicationId)) out.add(fogUuid) + const fogUuidsWithApp = new Set() + for (const uuid of seedFogUuids || []) { + if (uuid) fogUuidsWithApp.add(uuid) + } + for (const [fogUuid, msList] of microservicesByFog || []) { + if (!fogUuid || !msList.some(ms => ms.applicationId === applicationId)) continue + fogUuidsWithApp.add(fogUuid) + } + if (applicationId != null) { + const rows = await MicroserviceManager.findAll({ applicationId }, transaction) || [] + for (const ms of rows) { + if (ms && ms.iofogUuid) fogUuidsWithApp.add(ms.iofogUuid) + } + } + const leavesRunningApp = [] + const seenLeafIds = new Set() + for (const fogUuid of fogUuidsWithApp) { + out.add(fogUuid) + const ni = natsInstanceByFog.get(fogUuid) + if (ni && ni.isLeaf && ni.id != null && !seenLeafIds.has(ni.id)) { + seenLeafIds.add(ni.id) + leavesRunningApp.push(ni) + } + } + for (const ni of leavesRunningApp) { + await _addAncestorLeafFogs(ni, out, transaction) } return out } @@ -1594,7 +2080,13 @@ async function _reconcileResolverArtifactsOnceDb (options = {}, transaction) { if (fogFilter) { candidateFogs = fogs.filter((fog) => fogFilter.has(fog.uuid)) } else if ((reason === 'account-created' || reason === 'account-deleted') && options.applicationId != null) { - const affected = _getAffectedFogUuidsForApplication(options.applicationId, natsInstanceByFog, microservicesByFog) + const affected = await _getAffectedFogUuidsForApplication( + options.applicationId, + natsInstanceByFog, + microservicesByFog, + transaction, + options.fogUuids + ) candidateFogs = fogs.filter((f) => affected.has(f.uuid)) } else if (reason === 'account-rule-updated' && options.accountRuleId != null) { const affected = _getAffectedFogUuidsForAccountRule( @@ -1689,7 +2181,8 @@ async function _reconcileResolverArtifactsOnceDb (options = {}, transaction) { const isServerMode = !natsInstance.isLeaf if (natsInstance.isLeaf) { const leafJwtBundle = await _buildJwtBundleFromMaps(fog, true, maps, transaction) - await _ensureConfigMap(natsJwtBundleConfigMap(fog), leafJwtBundle, transaction) + const bundleChanged = await _ensureConfigMap(natsJwtBundleConfigMap(fog), leafJwtBundle, transaction) + await _noteLeafConfigMapChange(fog, bundleChanged, transaction) } else { await _ensureVolumeMount(natsJwtDirMount(fog), { configMapName: K8S_NATS_JWT_BUNDLE_CONFIG_MAP }, transaction) await VolumeMountService.linkVolumeMountEndpoint(natsJwtDirMount(fog), [fog.uuid], transaction) @@ -1734,12 +2227,14 @@ async function _reconcileResolverArtifactsOnceDb (options = {}, transaction) { } } + const operator = await NatsOperatorManager.findOne({}, transaction) return { - fullServerJwtBundle: _isKubernetesControlPlane() ? fullServerJwtBundle : null + fullServerJwtBundle: _isKubernetesControlPlane() ? fullServerJwtBundle : null, + hubOperatorJwt: _isKubernetesControlPlane() && operator ? operator.jwt : null } } -const REASON_VALUES = ['auth-mutation', 'account-created', 'account-deleted', 'account-rule-updated', 'user-rule-updated', 'server-deleted', 'cluster-routes-changed', 'system-account-created'] +const REASON_VALUES = ['auth-mutation', 'account-created', 'account-deleted', 'account-rule-updated', 'user-rule-updated', 'server-deleted', 'cluster-routes-changed', 'system-account-created', 'leaf-upstream-changed'] async function _computeAffectedFogUuidsForEnqueue (options, transaction) { const reason = options.reason || 'auth-mutation' @@ -1781,7 +2276,13 @@ async function _computeAffectedFogUuidsForEnqueue (options, transaction) { return serverFogUuids } if ((reason === 'account-created' || reason === 'account-deleted') && options.applicationId != null) { - const affected = _getAffectedFogUuidsForApplication(options.applicationId, natsInstanceByFog, microservicesByFog) + const affected = await _getAffectedFogUuidsForApplication( + options.applicationId, + natsInstanceByFog, + microservicesByFog, + transaction, + options.fogUuids + ) return fogUuids.filter((u) => affected.has(u)) } if (reason === 'account-rule-updated' && options.accountRuleId != null) { @@ -1801,6 +2302,43 @@ async function _computeAffectedFogUuidsForEnqueue (options, transaction) { return fogUuids } +async function _collectPendingAccountFogUuids (scope, transaction) { + const rows = await NatsReconcileTaskManager.findAll({ + reason: scope.reason, + applicationId: scope.applicationId, + accountRuleId: scope.accountRuleId, + userRuleId: scope.userRuleId, + status: 'pending' + }, transaction) || [] + const seeds = [] + for (const row of rows) { + const listed = row && row.fogUuids ? String(row.fogUuids).split(',') : [] + for (const uuid of listed) { + const trimmed = uuid.trim() + if (trimmed) seeds.push(trimmed) + } + } + return seeds +} + +async function _expandAccountFogUuids (applicationId, seedFogUuids, transaction) { + const fogs = await FogManager.findAll({}, transaction) || [] + const natsInstances = await NatsInstanceManager.findAll({}, transaction) || [] + const natsInstanceByFog = new Map() + for (const ni of natsInstances) { + if (ni.iofogUuid) natsInstanceByFog.set(ni.iofogUuid, ni) + } + const affected = await _getAffectedFogUuidsForApplication( + applicationId, + natsInstanceByFog, + new Map(), + transaction, + seedFogUuids + ) + const known = new Set(fogs.map((fog) => fog.uuid)) + return [...affected].filter((uuid) => known.has(uuid)) +} + function _chunkFogUuids (fogUuids, chunkSize) { const chunks = [] for (let i = 0; i < fogUuids.length; i += chunkSize) { @@ -1817,7 +2355,16 @@ async function enqueueReconcileTask (options = {}, transaction) { const scope = { reason, applicationId, accountRuleId, userRuleId } let affectedFogUuids - if (Array.isArray(options.fogUuids) && options.fogUuids.length > 0) { + if ((reason === 'account-created' || reason === 'account-deleted') && applicationId != null) { + const seeds = [] + if (Array.isArray(options.fogUuids)) { + for (const uuid of options.fogUuids) { + if (uuid) seeds.push(uuid) + } + } + const pendingSeeds = await _collectPendingAccountFogUuids(scope, transaction) + affectedFogUuids = await _expandAccountFogUuids(applicationId, seeds.concat(pendingSeeds), transaction) + } else if (Array.isArray(options.fogUuids) && options.fogUuids.length > 0) { affectedFogUuids = options.fogUuids } else { affectedFogUuids = await _computeAffectedFogUuidsForEnqueue({ ...options, reason }, transaction) @@ -1855,14 +2402,18 @@ async function claimNextTask (controllerUuid, stalenessSeconds) { async function _reconcileResolverArtifactsDbLoop (options, transaction) { let fullServerJwtBundle = null + let hubOperatorJwt = null do { natsReconcilePending = false const result = await _reconcileResolverArtifactsOnceDb(options, transaction) if (result && result.fullServerJwtBundle) { fullServerJwtBundle = result.fullServerJwtBundle } + if (result && result.hubOperatorJwt) { + hubOperatorJwt = result.hubOperatorJwt + } } while (natsReconcilePending) - return { fullServerJwtBundle } + return { fullServerJwtBundle, hubOperatorJwt } } async function reconcileResolverArtifacts (...args) { @@ -1879,8 +2430,8 @@ async function reconcileResolverArtifacts (...args) { try { if (parentTx) { const result = await _reconcileResolverArtifactsDbLoop(options, parentTx) - if (result.fullServerJwtBundle) { - _scheduleK8sAfterCommit(parentTx, () => _applyK8sJwtBundleExternal(result.fullServerJwtBundle)) + if (result.fullServerJwtBundle || result.hubOperatorJwt) { + _scheduleK8sAfterCommit(parentTx, () => _applyK8sHubAuthExternal(result)) } return { scheduled: false } } @@ -1889,7 +2440,7 @@ async function reconcileResolverArtifacts (...args) { (transaction) => _reconcileResolverArtifactsDbLoop(options, transaction), { priority: PRIORITY_BACKGROUND, label: 'nats.reconcileResolverArtifacts' } ) - await _applyK8sJwtBundleExternal(result.fullServerJwtBundle) + await _applyK8sHubAuthExternal(result) return { scheduled: false } } finally { natsReconcileRunning = false @@ -1925,8 +2476,8 @@ function scheduleResolverArtifactsReconcile (options = {}) { return { scheduled: true } } -function scheduleEnsureNatsK8sAfterCommit (transaction, k8sHubPatch) { - _scheduleK8sAfterCommit(transaction, () => _applyEnsureNatsK8sExternal(k8sHubPatch)) +function scheduleEnsureNatsK8sAfterCommit (transaction, k8sHubPatch, k8sRollout) { + _scheduleK8sAfterCommit(transaction, () => _applyEnsureNatsK8sExternal(k8sHubPatch, k8sRollout)) } function normalizeJetstreamSize (value, defaultValue) { @@ -1954,5 +2505,19 @@ module.exports = { setReconcilePending, normalizeJetstreamSize, mergeK8sHubClusterRoutes, - _ensureConfigMap + _ensureConfigMap, + _repairServerClusterMesh, + _computeClusterRoutesForInstance, + _serverConfigTemplate, + _clusterConfigRequiresRebuild, + _controllerClusterRouteUpdate, + _replaceOperatorJwtLine, + _validateAndReturnUpstreamNats, + _replaceLeafUpstreamConnections, + _storeNatsUpstreams, + _computeLeafRemotesForInstance, + _renderAndPersistNatsConfig, + _buildJwtBundle, + _buildLeafCredsConfigMap, + _getAffectedFogUuidsForApplication } diff --git a/src/templates/nats/leaf.conf b/src/templates/nats/leaf.conf index 2b0f861b..67b049b6 100644 --- a/src/templates/nats/leaf.conf +++ b/src/templates/nats/leaf.conf @@ -20,6 +20,16 @@ jetstream: { } leafnodes: { + port: $NATS_LEAF_PORT + advertise: $NATS_LEAF_ADVERTISE + tls: { + ca_file: "$NATS_TLS_DIR/$NATS_CERT_NAME/ca.crt" + cert_file: "$NATS_TLS_DIR/$NATS_CERT_NAME/tls.crt" + key_file: "$NATS_TLS_DIR/$NATS_CERT_NAME/tls.key" + handshake_first: true + verify: true + timeout: "3s" + } reconnect: "10s" remotes: $NATS_LEAF_REMOTES } diff --git a/test/src/data/fog-platform-managers.test.js b/test/src/data/fog-platform-managers.test.js index a159e19d..1d81ad70 100644 --- a/test/src/data/fog-platform-managers.test.js +++ b/test/src/data/fog-platform-managers.test.js @@ -52,6 +52,29 @@ describe('Fog platform spec schema', () => { await validateFogPlatformSpec(merged) }) + it('drops a server upstream list instead of storing it', () => { + const merged = mergePlatformSpecPatch({ + natsMode: 'server', + upstreamNatsServers: ['default-nats-hub', 'edge-1'] + }, { + upstreamNatsServers: ['default-nats-hub', 'edge-1'] + }) + + expect(merged.natsMode).to.equal('server') + expect(merged).to.not.have.property('upstreamNatsServers') + }) + + it('does not carry a server upstream list into a leaf update that omits the field', () => { + const merged = mergePlatformSpecPatch({ + natsMode: 'server', + upstreamNatsServers: ['default-nats-hub', 'edge-1'] + }, { + natsMode: 'leaf' + }) + + expect(merged).to.eql({ natsMode: 'leaf' }) + }) + it('round-trips spec JSON through parse and serialize', () => { const spec = { routerMode: 'interior', diff --git a/test/src/services/application-service.test.js b/test/src/services/application-service.test.js index f3572220..e918936f 100644 --- a/test/src/services/application-service.test.js +++ b/test/src/services/application-service.test.js @@ -139,10 +139,27 @@ describe('Application Service', () => { it('deletes microservices, NATS account, and the application', async () => { await $subject expect(MicroserviceService.deleteMicroserviceWithRoutesAndPortMappings).to.have.been.calledWith(microservices[0], transaction) - expect(NatsAuthService.deleteAccountForApplication).to.have.been.calledWith(application.id, transaction) + expect(NatsAuthService.deleteAccountForApplication).to.have.been.calledWith(application.id, transaction, { + fogUuids: ['fog-uuid'] + }) expect(ApplicationManager.delete).to.have.been.calledWith({ name }, transaction) }) + it('seeds each agent once when microservices share an agent', async () => { + ApplicationManager.findApplicationMicroservices.resolves([ + { uuid: 'msvc-1', iofogUuid: 'fog-uuid' }, + { uuid: 'msvc-2', iofogUuid: 'fog-uuid' }, + { uuid: 'msvc-3', iofogUuid: null } + ]) + + await $subject + + expect(NatsAuthService.deleteAccountForApplication).to.have.been.calledWith(application.id, transaction, { + fogUuids: ['fog-uuid'] + }) + expect(ChangeTrackingService.update).to.have.been.calledOnce + }) + context('when application is system', () => { beforeEach(() => { ApplicationManager.findOne.resolves({ ...application, isSystem: true }) diff --git a/test/src/services/fog-platform-service.test.js b/test/src/services/fog-platform-service.test.js index 37e873c7..6c0fd469 100644 --- a/test/src/services/fog-platform-service.test.js +++ b/test/src/services/fog-platform-service.test.js @@ -608,6 +608,33 @@ describe('Fog platform service', () => { expect(result.upstreamNatsServers).to.eql(['default-nats-hub']) }) + + it('keeps an empty upstream list when the spec omits upstreamNatsServers', async () => { + $sandbox.stub(NatsInstanceManager, 'findOne').resolves({ id: 1, isHub: true, iofogUuid: 'hub' }) + $sandbox.stub(NatsInstanceManager, 'findByFog').resolves({ id: 5, iofogUuid: fogUuid, isLeaf: true }) + $sandbox.stub(NatsConnectionManager, 'findAllWithNats').resolves([]) + + const result = await FogPlatformService.resolveNatsConfigFromSpec( + fogUuid, + { natsMode: 'leaf' }, + transaction + ) + + expect(result.upstreamNatsServers).to.eql([]) + }) + + it('leaves the upstream list unset when the agent has no NATS instance', async () => { + $sandbox.stub(NatsInstanceManager, 'findOne').resolves({ id: 1, isHub: true, iofogUuid: 'hub' }) + $sandbox.stub(NatsInstanceManager, 'findByFog').resolves(null) + + const result = await FogPlatformService.resolveNatsConfigFromSpec( + fogUuid, + { natsMode: 'leaf' }, + transaction + ) + + expect(result.upstreamNatsServers).to.equal(undefined) + }) }) describe('.markReconcileFailed()', () => { diff --git a/test/src/services/iofog-service.test.js b/test/src/services/iofog-service.test.js index d7b6b54e..159926bb 100644 --- a/test/src/services/iofog-service.test.js +++ b/test/src/services/iofog-service.test.js @@ -234,6 +234,54 @@ describe('ioFog Service', () => { expect(RouterService.validateAndReturnUpstreamRouters).to.have.been.called }) }) + + context('when a leaf names its upstreams', () => { + beforeEach(() => { + $sandbox.stub(NatsInstanceManager, 'findOne').resolves({ id: 1, isHub: true }) + $sandbox.stub(NatsService, '_validateAndReturnUpstreamNats').resolves([]) + }) + + afterEach(() => { + delete fogData.natsMode + delete fogData.upstreamNatsServers + }) + + it('does not store the list when the new agent is a server', async () => { + fogData.natsMode = 'server' + fogData.upstreamNatsServers = ['default-nats-hub', 'edge-1'] + + await ioFogService.createFogEndPoint(fogData, isCLI, transaction) + + expect(NatsService._validateAndReturnUpstreamNats).to.not.have.been.called + const stored = FogPlatformSpecManager.upsertSpec.firstCall.args[1] + expect(stored.natsMode).to.equal('server') + expect(stored).to.not.have.property('upstreamNatsServers') + }) + + it('checks the list before the agent is created', async () => { + fogData.natsMode = 'leaf' + fogData.upstreamNatsServers = ['default-nats-hub', 'edge-b'] + + await ioFogService.createFogEndPoint(fogData, isCLI, transaction) + + expect(NatsService._validateAndReturnUpstreamNats).to.have.been.calledOnce + expect(NatsService._validateAndReturnUpstreamNats.firstCall.args[0]).to.eql(['default-nats-hub', 'edge-b']) + expect(ioFogManager.create).to.have.been.calledOnce + }) + + it('rejects a mixed list before reconcile is enqueued', async () => { + NatsService._validateAndReturnUpstreamNats.rejects( + new Errors.ValidationError('Upstream NATS list cannot mix servers and leaves') + ) + fogData.natsMode = 'leaf' + fogData.upstreamNatsServers = ['default-nats-hub', 'factory'] + + await expect(ioFogService.createFogEndPoint(fogData, isCLI, transaction)) + .to.be.rejectedWith(Errors.ValidationError, /mix servers and leaves/) + expect(ioFogManager.create).to.not.have.been.called + expect(ReconcileOutboxManager.enqueueFogPlatform).to.not.have.been.called + }) + }) }) describe('.updateFogEndPoint()', () => { @@ -304,6 +352,85 @@ describe('ioFog Service', () => { .to.be.rejectedWith('Agent Resource Name is immutable') }) + context('when a leaf submits upstream NATS servers', () => { + const leaf = { id: 20, isLeaf: true, iofogUuid: uuid } + + beforeEach(() => { + NatsInstanceManager.findByFog.resolves(leaf) + $sandbox.stub(NatsInstanceManager, 'findOne').resolves({ id: 1, isHub: true, isLeaf: false }) + $sandbox.stub(NatsService, '_validateAndReturnUpstreamNats').resolves([leaf]) + }) + + it('checks the list before the spec is stored', async () => { + const data = { ...fogData, natsMode: 'leaf', upstreamNatsServers: ['default-nats-hub', 'edge-b'] } + + await ioFogService.updateFogEndPoint(data, isCLI, transaction) + + expect(NatsService._validateAndReturnUpstreamNats).to.have.been.calledOnce + const args = NatsService._validateAndReturnUpstreamNats.firstCall.args + expect(args[0]).to.eql(['default-nats-hub', 'edge-b']) + expect(args[1]).to.equal(false) + expect(args[4]).to.equal(leaf) + expect(FogPlatformSpecManager.upsertSpec).to.have.been.calledOnce + }) + + it('rejects a mixed list before reconcile is enqueued', async () => { + NatsService._validateAndReturnUpstreamNats.rejects( + new Errors.ValidationError('Upstream NATS list cannot mix servers and leaves') + ) + const data = { ...fogData, natsMode: 'leaf', upstreamNatsServers: ['default-nats-hub', 'factory'] } + + await expect(ioFogService.updateFogEndPoint(data, isCLI, transaction)) + .to.be.rejectedWith(Errors.ValidationError, /mix servers and leaves/) + expect(ioFogManager.update).to.not.have.been.called + expect(FogPlatformSpecManager.upsertSpec).to.not.have.been.called + expect(ReconcileOutboxManager.enqueueFogPlatform).to.not.have.been.called + }) + + it('keeps an omitted list without checking it', async () => { + const data = { ...fogData, natsMode: 'leaf' } + + await ioFogService.updateFogEndPoint(data, isCLI, transaction) + + expect(NatsService._validateAndReturnUpstreamNats).to.not.have.been.called + expect(FogPlatformSpecManager.upsertSpec).to.have.been.calledOnce + }) + }) + + context('when a server submits a leaf name', () => { + beforeEach(() => { + $sandbox.stub(NatsService, '_validateAndReturnUpstreamNats').resolves([]) + }) + + it('stores the spec without checking the list', async () => { + const data = { ...fogData, natsMode: 'server', upstreamNatsServers: ['default-nats-hub', 'edge-1'] } + + await ioFogService.updateFogEndPoint(data, isCLI, transaction) + + expect(NatsService._validateAndReturnUpstreamNats).to.not.have.been.called + const stored = FogPlatformSpecManager.upsertSpec.firstCall.args[1] + expect(stored.natsMode).to.equal('server') + expect(stored).to.not.have.property('upstreamNatsServers') + expect(ReconcileOutboxManager.enqueueFogPlatform).to.have.been.calledOnce + }) + + it('removes a previously stored server list when the update omits the field', async () => { + FogPlatformSpecManager.getParsedSpec.resolves({ + fogUuid: uuid, + generation: 1, + spec: { + natsMode: 'server', + upstreamNatsServers: ['default-nats-hub', 'edge-1'] + } + }) + + await ioFogService.updateFogEndPoint({ ...fogData, natsMode: 'server' }, isCLI, transaction) + + const stored = FogPlatformSpecManager.upsertSpec.firstCall.args[1] + expect(stored).to.not.have.property('upstreamNatsServers') + }) + }) + context('when upstream endpoint changes', () => { beforeEach(() => { RouterManager.findOne.callsFake((query) => { diff --git a/test/src/services/microservices-service.test.js b/test/src/services/microservices-service.test.js index 819907bc..fc32a3f8 100644 --- a/test/src/services/microservices-service.test.js +++ b/test/src/services/microservices-service.test.js @@ -366,6 +366,23 @@ describe('Microservices Service', () => { expect(result).to.eql({ uuid: msvcUuid, name: 'new-msvc' }) }) + context('when the application has NATS access and the microservice does not', () => { + beforeEach(() => { + ApplicationManager.findOne.resolves({ id: 42, name: 'my-app', isSystem: false, natsAccess: true }) + $sandbox.stub(NatsAuthService, 'enqueueNatsReconcileOutbox').resolves() + }) + + it('reconciles the agent the microservice is placed on', async () => { + await $subject + + expect(NatsAuthService.enqueueNatsReconcileOutbox).to.have.been.calledOnceWith({ + reason: 'account-created', + applicationId: 42, + fogUuids: ['fog-uuid'] + }, transaction) + }) + }) + it('rejects top-level natsAccess (use natsConfig)', () => { const badPayload = { ...microserviceData, natsAccess: true } return expect( @@ -810,6 +827,27 @@ describe('Microservices Service', () => { }) }) + context('when the microservice moves to another agent', () => { + def('updateData', () => ({ iofogUuid: 'other-fog' })) + + beforeEach(() => { + ApplicationManager.findOne.resolves({ id: existing.applicationId, natsAccess: true, isSystem: false }) + MicroserviceManager.updateAndFind.resolves({ ...existing, iofogUuid: 'other-fog' }) + $sandbox.stub(MicroserviceStatusManager, 'update').resolves() + $sandbox.stub(NatsAuthService, 'enqueueNatsReconcileOutbox').resolves() + }) + + it('reconciles the old and new agents', async () => { + await $subject + + expect(NatsAuthService.enqueueNatsReconcileOutbox).to.have.been.calledOnceWith({ + reason: 'account-created', + applicationId: existing.applicationId, + fogUuids: [existing.iofogUuid, 'other-fog'] + }, transaction) + }) + }) + context('when volumeMappings include a system serviceAccount volume', () => { const userVolume = { hostDestination: 'nats-creds-data', diff --git a/test/src/services/nats-resolver-bundle.test.js b/test/src/services/nats-resolver-bundle.test.js index 0c7a1a53..9f04055e 100644 --- a/test/src/services/nats-resolver-bundle.test.js +++ b/test/src/services/nats-resolver-bundle.test.js @@ -3,6 +3,7 @@ const sinon = require('sinon') const { Op } = require('sequelize') const NatsAccountManager = require('../../../src/data/managers/nats-account-manager') +const NatsOperatorManager = require('../../../src/data/managers/nats-operator-manager') const NatsInstanceManager = require('../../../src/data/managers/nats-instance-manager') const NatsAccountRuleManager = require('../../../src/data/managers/nats-account-rule-manager') const NatsConnectionManager = require('../../../src/data/managers/nats-connection-manager') @@ -12,6 +13,7 @@ const ApplicationManager = require('../../../src/data/managers/application-manag const MicroserviceManager = require('../../../src/data/managers/microservice-manager') const ConfigMapService = require('../../../src/services/config-map-service') const NatsAuthService = require('../../../src/services/nats-auth-service') +const ChangeTrackingService = require('../../../src/services/change-tracking-service') const config = require('../../../src/config') const transactionRunner = require('../../../src/helpers/transaction-runner') @@ -53,6 +55,9 @@ describe('NATS resolver bundle freshness', () => { $sandbox.stub(ApplicationManager, 'findAll').resolves([app]) $sandbox.stub(NatsInstanceManager, 'findAll').resolves([{ iofogUuid: fog.uuid, isLeaf: true, isHub: false }]) $sandbox.stub(NatsConnectionManager, 'findAllWithNats').resolves([]) + $sandbox.stub(NatsInstanceManager, 'findByFog').resolves({ id: 5, isLeaf: true, iofogUuid: fog.uuid }) + $sandbox.stub(ApplicationManager, 'findOne').resolves(app) + $sandbox.stub(ChangeTrackingService, 'update').resolves() $sandbox.stub(MicroserviceManager, 'findAll').callsFake((query) => { if (query.name) { return Promise.resolve([{ uuid: 'nats-ms', iofogUuid: fog.uuid, name: 'nats' }]) @@ -70,6 +75,7 @@ describe('NATS resolver bundle freshness', () => { return Promise.resolve([staleAccount]) }) $sandbox.stub(NatsAccountManager, 'findOne').resolves(null) + $sandbox.stub(NatsOperatorManager, 'findOne').resolves(null) $sandbox.stub(NatsAuthService, 'ensureSystemAccount').resolves() $sandbox.stub(NatsAuthService, 'ensureLeafSystemAccount').resolves({ publicKey: 'LEAFSYS', diff --git a/test/src/services/nats-service.test.js b/test/src/services/nats-service.test.js index 4dcb11ae..112f319b 100644 --- a/test/src/services/nats-service.test.js +++ b/test/src/services/nats-service.test.js @@ -5,6 +5,7 @@ const NatsService = require('../../../src/services/nats-service') const NatsInstanceManager = require('../../../src/data/managers/nats-instance-manager') const NatsConnectionManager = require('../../../src/data/managers/nats-connection-manager') const NatsAccountManager = require('../../../src/data/managers/nats-account-manager') +const NatsOperatorManager = require('../../../src/data/managers/nats-operator-manager') const NatsAccountRuleManager = require('../../../src/data/managers/nats-account-rule-manager') const NatsUserManager = require('../../../src/data/managers/nats-user-manager') const MicroserviceManager = require('../../../src/data/managers/microservice-manager') @@ -15,6 +16,11 @@ const ConfigMapManager = require('../../../src/data/managers/config-map-manager' const NatsAuthService = require('../../../src/services/nats-auth-service') const SecretService = require('../../../src/services/secret-service') const Errors = require('../../../src/helpers/errors') +const FogManager = require('../../../src/data/managers/iofog-manager') +const ApplicationManager = require('../../../src/data/managers/application-manager') +const ChangeTrackingService = require('../../../src/services/change-tracking-service') +const ReconcileOutboxManager = require('../../../src/data/managers/reconcile-outbox-manager') +const NatsReconcileTaskManager = require('../../../src/data/managers/nats-reconcile-task-manager') describe('NATS Service', () => { def('sandbox', () => sinon.createSandbox()) @@ -57,6 +63,33 @@ describe('NATS Service', () => { expect(ConfigMapService.deleteConfigMapEndpoint).to.have.been.called expect(SecretService.deleteSecretEndpoint).to.have.been.called }) + + it('reloads a remaining server when its only peer is removed', async () => { + const removed = { id: 77, isLeaf: false, isHub: false, iofogUuid: 'gone', host: '10.0.0.9', clusterPort: 6222 } + const peer = { id: 3, isLeaf: false, isHub: false, iofogUuid: 'peer', host: '10.0.0.3', clusterPort: 6222 } + NatsInstanceManager.findByFog.resolves(removed) + NatsInstanceManager.findAll.resetBehavior() + NatsInstanceManager.findAll + .onCall(0).resolves([removed, peer]) + .onCall(1).resolves([peer]) + .onCall(2).resolves([peer]) + $sandbox.stub(NatsConnectionManager, 'findAllWithNats') + .onCall(0).resolves([{ dest: { id: removed.id, isLeaf: false, host: removed.host, clusterPort: 6222 } }]) + .onCall(1).resolves([]) + $sandbox.stub(MicroserviceManager, 'findOne').resolves({ uuid: 'ms-peer' }) + $sandbox.stub(MicroserviceManager, 'update').resolves() + $sandbox.stub(ChangeTrackingService, 'update').resolves() + $sandbox.stub(NatsAuthService, 'deleteServerSysUserForFog').resolves() + $sandbox.stub(ReconcileOutboxManager, 'enqueueNats').resolves() + + await NatsService.cleanupNatsForFogDb(fog, transaction) + + expect(MicroserviceManager.update).to.have.been.calledWith( + { uuid: 'ms-peer' }, + { rebuild: true }, + transaction + ) + }) }) describe('single hub server config (no cluster block)', () => { @@ -205,6 +238,1105 @@ describe('NATS Service', () => { const result = NatsService.mergeK8sHubClusterRoutes(currentRoutes, []) expect(result).to.eql(['nats://nats-0.nats-headless:6222']) }) + + it('keeps a nats-headless route when mesh routes replace the controller list', () => { + const currentRoutes = [ + 'nats://nats-0.nats-headless:6222', + 'nats://10.0.0.1:6222' + ] + const meshRoutes = ['nats://10.0.0.2:6222', 'nats://10.0.0.3:6222'] + expect(NatsService.mergeK8sHubClusterRoutes(currentRoutes, meshRoutes)).to.eql([ + 'nats://nats-0.nats-headless:6222', + 'nats://10.0.0.2:6222', + 'nats://10.0.0.3:6222' + ]) + }) + }) + + describe('server mesh', () => { + const transaction = {} + + beforeEach(() => { + $sandbox.stub(NatsInstanceManager, 'findAll') + $sandbox.stub(NatsConnectionManager, 'findAllWithNats') + $sandbox.stub(NatsConnectionManager, 'create').resolves() + $sandbox.stub(NatsConnectionManager, 'delete').resolves() + }) + + it('connects every server to every other server in both directions', async () => { + const hub = { id: 1, isLeaf: false, isHub: true, host: '10.0.0.1', iofogUuid: 'hub' } + const edge = { id: 2, isLeaf: false, isHub: false, host: '10.0.0.2', iofogUuid: 'edge' } + NatsInstanceManager.findAll.resolves([hub, edge]) + NatsConnectionManager.findAllWithNats.callsFake(({ sourceNats }) => { + if (sourceNats === hub.id) { + return Promise.resolve([{ id: 8, dest: hub }]) + } + return Promise.resolve([]) + }) + + await NatsService._repairServerClusterMesh(transaction) + + const created = NatsConnectionManager.create.getCalls().map((call) => call.args[0]) + expect(created).to.deep.include({ sourceNats: hub.id, destNats: edge.id }) + expect(created).to.deep.include({ sourceNats: edge.id, destNats: hub.id }) + expect(created.some((row) => row.sourceNats === row.destNats)).to.equal(false) + expect(NatsConnectionManager.delete).to.have.been.calledWith({ id: 8 }, transaction) + }) + + it('removes a server link that points at a leaf', async () => { + const server = { id: 1, isLeaf: false, host: '10.0.0.1', iofogUuid: 'srv' } + NatsInstanceManager.findAll.resolves([server]) + NatsConnectionManager.findAllWithNats.resolves([ + { id: 9, dest: { id: 3, isLeaf: true, host: '10.0.0.3' } } + ]) + + await NatsService._repairServerClusterMesh(transaction) + + expect(NatsConnectionManager.findAllWithNats).to.have.been.calledOnceWith({ sourceNats: server.id }, transaction) + expect(NatsConnectionManager.delete).to.have.been.calledOnceWith({ id: 9 }, transaction) + expect(NatsConnectionManager.create).to.not.have.been.called + }) + + it('does not reject a server whose upstream list names a leaf', async () => { + const server = { id: 1, isLeaf: false, host: '10.0.0.1', iofogUuid: 'srv' } + const other = { id: 2, isLeaf: false, host: '10.0.0.2', iofogUuid: 'other' } + const hub = { id: 9, isHub: true, isLeaf: false, iofogUuid: 'hub' } + NatsInstanceManager.findAll.resolves([server, other]) + NatsConnectionManager.findAllWithNats.resolves([]) + $sandbox.stub(FogManager, 'findOne').rejects(new Error('server list must not be resolved')) + + await NatsService._storeNatsUpstreams( + server, + { uuid: 'srv', isSystem: true }, + { upstreamNatsServers: ['some-leaf'] }, + hub, + transaction + ) + + expect(FogManager.findOne).to.not.have.been.called + expect(NatsConnectionManager.create).to.have.been.calledWith( + { sourceNats: server.id, destNats: other.id }, + transaction + ) + expect(NatsConnectionManager.create).to.have.been.calledWith( + { sourceNats: other.id, destNats: server.id }, + transaction + ) + }) + }) + + describe('cluster routes', () => { + const transaction = {} + const self = { id: 1, isLeaf: false, host: '10.0.0.1', clusterPort: 6222, iofogUuid: 'self' } + + it('lists only the other server when two servers are connected', async () => { + $sandbox.stub(NatsConnectionManager, 'findAllWithNats').resolves([ + { dest: { id: 2, isLeaf: false, host: '10.0.0.2', clusterPort: 6222 } } + ]) + + const routes = await NatsService._computeClusterRoutesForInstance(self, transaction) + + expect(routes).to.eql(['nats://10.0.0.2:6222']) + }) + + it('builds routes from the other servers and skips an empty host', async () => { + $sandbox.stub(NatsConnectionManager, 'findAllWithNats').resolves([ + { dest: { id: 1, isLeaf: false, host: '10.0.0.1', clusterPort: 6222 } }, + { dest: { id: 2, isLeaf: false, host: ' ', clusterPort: 6222 } }, + { dest: { id: 3, isLeaf: false, host: '10.0.0.3', clusterPort: 6223 } }, + { dest: { id: 4, isLeaf: true, host: '10.0.0.4', clusterPort: 6222 } } + ]) + + const routes = await NatsService._computeClusterRoutesForInstance(self, transaction) + + expect(routes).to.eql(['nats://10.0.0.3:6223']) + }) + + it('uses the no-cluster server config when a server has no peers', () => { + const content = NatsService._serverConfigTemplate([]) + expect(content).to.not.include('cluster {') + expect(content).to.include('jetstream') + }) + + it('uses the clustered server config when a peer route exists', () => { + const content = NatsService._serverConfigTemplate(['nats://10.0.0.2:6222']) + expect(content).to.include('cluster:') + expect(content).to.include('routes:') + }) + + it('reloads when a server gains or loses its only peer', () => { + expect(NatsService._clusterConfigRequiresRebuild([], ['nats://10.0.0.2:6222'])).to.equal(true) + expect(NatsService._clusterConfigRequiresRebuild(['nats://10.0.0.2:6222'], [])).to.equal(true) + expect(NatsService._clusterConfigRequiresRebuild([], [])).to.equal(false) + expect(NatsService._clusterConfigRequiresRebuild( + ['nats://10.0.0.2:6222'], + ['nats://10.0.0.2:6222'] + )).to.equal(false) + expect(NatsService._clusterConfigRequiresRebuild( + ['nats://10.0.0.2:6222', 'nats://10.0.0.3:6222'], + ['nats://10.0.0.2:6222'] + )).to.equal(true) + }) + + it('patches the hub routes and rolls when a server becomes a leaf', () => { + const update = NatsService._controllerClusterRouteUpdate( + ['nats://10.0.0.1:6222', 'nats://10.0.0.2:6222'], + ['nats://10.0.0.1:6222'] + ) + expect(update.k8sHubPatch).to.eql(['nats://10.0.0.1:6222']) + expect(update.k8sRollout).to.equal(true) + }) + + it('patches the hub routes without a rollout when a peer joins an existing cluster', () => { + const update = NatsService._controllerClusterRouteUpdate( + ['nats://10.0.0.1:6222'], + ['nats://10.0.0.1:6222', 'nats://10.0.0.2:6222'] + ) + expect(update.k8sHubPatch).to.eql(['nats://10.0.0.1:6222', 'nats://10.0.0.2:6222']) + expect(update.k8sRollout).to.equal(false) + }) + + it('patches the hub routes and rolls when the first cluster route appears', () => { + const update = NatsService._controllerClusterRouteUpdate([], ['nats://10.0.0.2:6222']) + expect(update.k8sHubPatch).to.eql(['nats://10.0.0.2:6222']) + expect(update.k8sRollout).to.equal(true) + }) + + it('leaves the hub routes alone when the controller route list is unchanged', () => { + const update = NatsService._controllerClusterRouteUpdate( + ['nats://10.0.0.2:6222', 'nats://10.0.0.1:6222'], + ['nats://10.0.0.1:6222', 'nats://10.0.0.2:6222'] + ) + expect(update.k8sHubPatch).to.equal(null) + expect(update.k8sRollout).to.equal(false) + }) + }) + + describe('leaf upstream list', () => { + const transaction = {} + const hub = { id: 1, isHub: true, isLeaf: false, iofogUuid: 'hub-agent', host: '10.0.0.1', clusterPort: 6222 } + const serverB = { id: 2, isHub: false, isLeaf: false, iofogUuid: 'server-b', host: '10.0.0.2', clusterPort: 6222 } + const leaf = { id: 10, isLeaf: true, iofogUuid: 'leaf-agent', host: '10.0.0.10' } + const parentA = { id: 11, isLeaf: true, iofogUuid: 'parent-a', host: '10.0.0.11' } + const parentB = { id: 12, isLeaf: true, iofogUuid: 'parent-b', host: '10.0.0.12' } + const middle = { id: 13, isLeaf: true, iofogUuid: 'middle', host: '10.0.0.13' } + let instances + let fogsByName + let destsBySource + + beforeEach(() => { + instances = { + [hub.iofogUuid]: hub, + [serverB.iofogUuid]: serverB, + [leaf.iofogUuid]: leaf, + [parentA.iofogUuid]: parentA, + [parentB.iofogUuid]: parentB, + [middle.iofogUuid]: middle + } + fogsByName = {} + destsBySource = {} + $sandbox.stub(NatsInstanceManager, 'findOne').callsFake((query) => { + return Promise.resolve((query && instances[query.iofogUuid]) || null) + }) + $sandbox.stub(FogManager, 'findOne').callsFake((query) => { + return Promise.resolve((query && fogsByName[query.name]) || null) + }) + $sandbox.stub(NatsConnectionManager, 'findAllWithNats').callsFake((query) => { + const dests = destsBySource[query.sourceNats] || [] + return Promise.resolve(dests.map((dest) => ({ dest }))) + }) + $sandbox.stub(NatsConnectionManager, 'create').resolves() + $sandbox.stub(NatsConnectionManager, 'delete').resolves() + $sandbox.stub(ReconcileOutboxManager, 'enqueueNats').resolves() + }) + + function validate (ids, source = leaf) { + return NatsService._validateAndReturnUpstreamNats(ids, false, hub, transaction, source) + } + + it('attaches a new leaf to the hub only', async () => { + const result = await NatsService._validateAndReturnUpstreamNats(undefined, true, hub, transaction, leaf) + expect(result).to.eql([hub]) + expect(FogManager.findOne).to.not.have.been.called + }) + + it('treats a null list as omitted and an empty list as no upstream', async () => { + const omitted = await NatsService._validateAndReturnUpstreamNats(null, false, hub, transaction, leaf) + const cleared = await NatsService._validateAndReturnUpstreamNats([], false, hub, transaction, leaf) + expect(omitted).to.eql([hub]) + expect(cleared).to.eql([]) + }) + + it('starts a system agent with no upstreams when the hub does not exist yet', async () => { + const result = await NatsService._validateAndReturnUpstreamNats(undefined, true, null, transaction, leaf) + expect(result).to.eql([]) + }) + + it('rejects a leaf when the hub does not exist yet', () => { + return expect(NatsService._validateAndReturnUpstreamNats(undefined, false, null, transaction, leaf)) + .to.be.rejectedWith(Errors.NotFoundError) + }) + + it('stores nothing when a leaf upstream list is empty', async () => { + NatsConnectionManager.findAllWithNats.callsFake(() => Promise.resolve([{ id: 4, dest: hub }])) + await NatsService._storeNatsUpstreams( + leaf, + { isSystem: false }, + { upstreamNatsServers: [] }, + hub, + transaction + ) + expect(NatsConnectionManager.delete).to.have.been.calledOnceWith({ id: 4 }, transaction) + expect(NatsConnectionManager.create).to.not.have.been.called + }) + + it('stores only the hub when a leaf omits its upstream list', async () => { + await NatsService._storeNatsUpstreams(leaf, { isSystem: false }, {}, hub, transaction) + expect(NatsConnectionManager.create).to.have.been.calledOnceWith( + { sourceNats: leaf.id, destNats: hub.id }, + transaction + ) + }) + + it('rejects a list that mixes a server and a leaf', () => { + return expect(validate([hub.iofogUuid, parentA.iofogUuid])) + .to.be.rejectedWith(Errors.ValidationError, /mix servers and leaves/) + }) + + it('rejects a leaf that names itself', () => { + return expect(validate([leaf.iofogUuid])) + .to.be.rejectedWith(Errors.ValidationError, /this agent/) + }) + + it('rejects a cycle back to this leaf', () => { + destsBySource[parentA.id] = [leaf] + return expect(validate([parentA.iofogUuid])) + .to.be.rejectedWith(Errors.ValidationError, /cycle/) + }) + + it('rejects a cycle through another leaf', () => { + destsBySource[parentA.id] = [middle] + destsBySource[middle.id] = [leaf] + return expect(validate([parentA.iofogUuid])) + .to.be.rejectedWith(Errors.ValidationError, /cycle/) + }) + + it('rejects a parent that already dials another parent in the list', () => { + destsBySource[parentA.id] = [parentB] + return expect(validate([parentA.iofogUuid, parentB.iofogUuid])) + .to.be.rejectedWith(Errors.ValidationError, /cycle/) + }) + + it('rejects leaf parents that dial different upstreams', () => { + destsBySource[parentA.id] = [hub] + destsBySource[parentB.id] = [] + return expect(validate([parentA.iofogUuid, parentB.iofogUuid])) + .to.be.rejectedWith(Errors.ValidationError, /same upstream set/) + }) + + it('accepts a parent leaf that has no upstreams', async () => { + const result = await validate([parentA.iofogUuid]) + expect(result).to.eql([parentA]) + }) + + it('accepts leaf parents that both have no upstreams', async () => { + const result = await validate([parentB.iofogUuid, parentA.iofogUuid]) + expect(result.map((instance) => instance.id)).to.eql([parentB.id, parentA.id]) + }) + + it('accepts leaf parents that dial the same servers', async () => { + destsBySource[parentA.id] = [serverB, hub] + destsBySource[parentB.id] = [hub, serverB] + const result = await validate([parentA.iofogUuid, parentB.iofogUuid]) + expect(result.map((instance) => instance.id)).to.eql([parentA.id, parentB.id]) + }) + + it('keeps the first occurrence of a repeated upstream', async () => { + const result = await validate(['default-nats-hub', hub.iofogUuid, 'default-nats-hub']) + expect(result).to.eql([hub]) + }) + + it('accepts a list of servers', async () => { + const result = await validate(['default-nats-hub', serverB.iofogUuid]) + expect(result.map((instance) => instance.id)).to.eql([hub.id, serverB.id]) + }) + + it('rejects an unknown upstream name', () => { + return expect(validate(['missing'])).to.be.rejectedWith(Errors.NotFoundError) + }) + + it('rejects an agent that has no NATS instance', () => { + fogsByName['edge-x'] = { uuid: 'edge-x', name: 'edge-x' } + return expect(validate(['edge-x'])).to.be.rejectedWith(Errors.NotFoundError) + }) + + it('refreshes the leaf and leaf parents when the upstream list changes', async () => { + NatsConnectionManager.findAllWithNats.callsFake((query) => { + if (query.sourceNats === leaf.id) { + return Promise.resolve([{ id: 4, dest: parentA }]) + } + const dests = destsBySource[query.sourceNats] || [] + return Promise.resolve(dests.map((dest) => ({ dest }))) + }) + + await NatsService._storeNatsUpstreams( + leaf, + { isSystem: false }, + { upstreamNatsServers: [parentB.iofogUuid] }, + hub, + transaction + ) + + expect(ReconcileOutboxManager.enqueueNats).to.have.been.calledOnce + const payload = ReconcileOutboxManager.enqueueNats.firstCall.args[0] + expect(payload.reason).to.equal('leaf-upstream-changed') + expect(payload.fogUuids).to.have.members([leaf.iofogUuid, parentA.iofogUuid, parentB.iofogUuid]) + expect(payload.fogUuids).to.not.include(hub.iofogUuid) + }) + + it('refreshes ancestor leaves when a parent leaf is added or removed', async () => { + const grandparent = { id: 14, isLeaf: true, iofogUuid: 'grandparent', host: '10.0.0.14' } + instances[grandparent.iofogUuid] = grandparent + destsBySource[parentB.id] = [grandparent] + destsBySource[grandparent.id] = [hub] + NatsConnectionManager.findAllWithNats.callsFake((query) => { + if (query.sourceNats === leaf.id) { + return Promise.resolve([{ id: 4, dest: parentA }]) + } + const dests = destsBySource[query.sourceNats] || [] + return Promise.resolve(dests.map((dest) => ({ dest }))) + }) + + await NatsService._storeNatsUpstreams( + leaf, + { isSystem: false }, + { upstreamNatsServers: [parentB.iofogUuid] }, + hub, + transaction + ) + + const payload = ReconcileOutboxManager.enqueueNats.firstCall.args[0] + expect(payload.fogUuids).to.have.members([ + leaf.iofogUuid, + parentA.iofogUuid, + parentB.iofogUuid, + grandparent.iofogUuid + ]) + expect(payload.fogUuids).to.not.include(hub.iofogUuid) + }) + + it('refreshes ancestor leaves when a parent leaf is removed', async () => { + const grandparent = { id: 14, isLeaf: true, iofogUuid: 'grandparent', host: '10.0.0.14' } + destsBySource[parentB.id] = [grandparent] + destsBySource[grandparent.id] = [hub] + NatsConnectionManager.findAllWithNats.callsFake((query) => { + if (query.sourceNats === leaf.id) { + return Promise.resolve([{ id: 4, dest: parentB }]) + } + const dests = destsBySource[query.sourceNats] || [] + return Promise.resolve(dests.map((dest) => ({ dest }))) + }) + + await NatsService._storeNatsUpstreams( + leaf, + { isSystem: false }, + { upstreamNatsServers: [hub.iofogUuid] }, + hub, + transaction + ) + + const payload = ReconcileOutboxManager.enqueueNats.firstCall.args[0] + expect(payload.fogUuids).to.have.members([ + leaf.iofogUuid, + parentB.iofogUuid, + grandparent.iofogUuid + ]) + expect(payload.fogUuids).to.not.include(hub.iofogUuid) + }) + + it('does not refresh a server when a leaf starts or stops dialing it', async () => { + NatsConnectionManager.findAllWithNats.callsFake((query) => { + if (query.sourceNats === leaf.id) { + return Promise.resolve([{ id: 4, dest: hub }]) + } + const dests = destsBySource[query.sourceNats] || [] + return Promise.resolve(dests.map((dest) => ({ dest }))) + }) + + await NatsService._storeNatsUpstreams( + leaf, + { isSystem: false }, + { upstreamNatsServers: [parentA.iofogUuid] }, + hub, + transaction + ) + + const payload = ReconcileOutboxManager.enqueueNats.firstCall.args[0] + expect(payload.fogUuids).to.have.members([leaf.iofogUuid, parentA.iofogUuid]) + expect(payload.fogUuids).to.not.include(hub.iofogUuid) + }) + + it('leaves parents alone when the upstream list is unchanged', async () => { + NatsConnectionManager.findAllWithNats.callsFake((query) => { + if (query.sourceNats === leaf.id) { + return Promise.resolve([{ id: 4, dest: parentA }]) + } + const dests = destsBySource[query.sourceNats] || [] + return Promise.resolve(dests.map((dest) => ({ dest }))) + }) + + await NatsService._storeNatsUpstreams( + leaf, + { isSystem: false }, + { upstreamNatsServers: [parentA.iofogUuid] }, + hub, + transaction + ) + + expect(ReconcileOutboxManager.enqueueNats).to.not.have.been.called + }) + }) + + describe('leaf remotes', () => { + const transaction = {} + const fog = { uuid: 'leaf-agent', name: 'edge-1', host: '10.0.0.10' } + const natsInstance = { id: 10, isLeaf: true, leafPort: 7422 } + const certName = 'nats-server-edge-1' + + function upstream (host, leafPort, id) { + return { dest: { id, host, leafPort, isLeaf: false } } + } + + beforeEach(() => { + $sandbox.stub(NatsConnectionManager, 'findAllWithNats').resolves([]) + $sandbox.stub(NatsInstanceManager, 'findByFog').resolves(null) + $sandbox.stub(MicroserviceManager, 'findAll').resolves([]) + $sandbox.stub(ApplicationManager, 'findOne').resolves(null) + $sandbox.stub(NatsAuthService, 'ensureAccountForApplication').resolves(null) + }) + + function useAccount (id, name, publicKey) { + MicroserviceManager.findAll.resolves([{ applicationId: id }]) + ApplicationManager.findOne.resolves({ id, name, isSystem: false, natsAccess: true }) + NatsAuthService.ensureAccountForApplication.resolves({ name, publicKey }) + } + + it('builds one remote with a url for each parent leaf', async () => { + NatsConnectionManager.findAllWithNats.resolves([ + { dest: { id: 11, host: '10.0.0.11', leafPort: 7422, isLeaf: true } }, + { dest: { id: 12, host: '10.0.0.12', leafPort: 7422, isLeaf: true } } + ]) + useAccount(7, 'billing', 'PUB_BILLING') + + const remotes = await NatsService._computeLeafRemotesForInstance(fog, natsInstance, transaction, certName) + + expect(remotes).to.have.length(1) + expect(remotes[0].urls).to.eql([ + 'tls://10.0.0.11:7422', + 'tls://10.0.0.12:7422' + ]) + }) + + it('builds one remote with a url for each upstream in stored order', async () => { + NatsConnectionManager.findAllWithNats.resolves([ + upstream('10.0.0.1', 7422, 1), + upstream('10.0.0.3', 7424, 3), + upstream('10.0.0.2', 7423, 2) + ]) + useAccount(7, 'billing', 'PUB_BILLING') + + const remotes = await NatsService._computeLeafRemotesForInstance(fog, natsInstance, transaction, certName) + + expect(remotes).to.have.length(1) + expect(remotes[0].urls).to.eql([ + 'tls://10.0.0.1:7422', + 'tls://10.0.0.3:7424', + 'tls://10.0.0.2:7423' + ]) + expect(remotes[0].account).to.equal('PUB_BILLING') + expect(remotes[0].credentials).to.equal('/etc/nats/creds/billing/leaf-edge-1.creds') + expect(remotes[0].tls).to.include({ verify: true, handshake_first: true }) + }) + + it('keeps the first url when a destination is repeated', async () => { + NatsConnectionManager.findAllWithNats.resolves([ + upstream('10.0.0.1', 7422, 1), + upstream('10.0.0.1', 7422, 1) + ]) + useAccount(7, 'billing', 'PUB_BILLING') + + const remotes = await NatsService._computeLeafRemotesForInstance(fog, natsInstance, transaction, certName) + + expect(remotes).to.have.length(1) + expect(remotes[0].urls).to.eql(['tls://10.0.0.1:7422']) + }) + + it('builds one remote per application with the same urls', async () => { + NatsConnectionManager.findAllWithNats.resolves([ + upstream('10.0.0.1', 7422, 1), + upstream('10.0.0.2', 7422, 2) + ]) + MicroserviceManager.findAll.resolves([{ applicationId: 7 }, { applicationId: 8 }]) + ApplicationManager.findOne.callsFake((query) => { + if (query.id === 7) { + return Promise.resolve({ id: 7, name: 'billing', isSystem: false, natsAccess: true }) + } + return Promise.resolve({ id: 8, name: 'telemetry', isSystem: false, natsAccess: true }) + }) + NatsAuthService.ensureAccountForApplication.callsFake((appId) => { + if (appId === 7) { + return Promise.resolve({ name: 'billing', publicKey: 'PUB_BILLING' }) + } + return Promise.resolve({ name: 'telemetry', publicKey: 'PUB_TELEMETRY' }) + }) + + const remotes = await NatsService._computeLeafRemotesForInstance(fog, natsInstance, transaction, certName) + + expect(remotes.map((remote) => remote.account)).to.eql(['PUB_BILLING', 'PUB_TELEMETRY']) + expect(remotes[0].urls).to.eql(remotes[1].urls) + expect(remotes[0].urls).to.eql(['tls://10.0.0.1:7422', 'tls://10.0.0.2:7422']) + expect(remotes[1].credentials).to.equal('/etc/nats/creds/telemetry/leaf-edge-1.creds') + }) + + it('builds no remotes when a leaf has no upstreams', async () => { + useAccount(7, 'billing', 'PUB_BILLING') + + const remotes = await NatsService._computeLeafRemotesForInstance(fog, natsInstance, transaction, certName) + + expect(remotes).to.eql([]) + expect(NatsAuthService.ensureAccountForApplication).to.not.have.been.called + }) + + it('skips an upstream that has no host', async () => { + NatsConnectionManager.findAllWithNats.resolves([ + upstream(' ', 7422, 1), + upstream(null, 7422, 2), + upstream('10.0.0.2', 7422, 3) + ]) + useAccount(7, 'billing', 'PUB_BILLING') + + const remotes = await NatsService._computeLeafRemotesForInstance(fog, natsInstance, transaction, certName) + + expect(remotes).to.have.length(1) + expect(remotes[0].urls).to.eql(['tls://10.0.0.2:7422']) + }) + }) + + describe('downstream application accounts', () => { + const transaction = {} + const regional = { uuid: 'regional-agent', name: 'regional', host: '10.0.0.20', natsMicroserviceUuid: 'ms-regional' } + const factory = { uuid: 'factory-agent', name: 'factory' } + const plant = { uuid: 'plant-agent', name: 'plant' } + const regionalNats = { id: 20, isLeaf: true, iofogUuid: regional.uuid, host: '10.0.0.20', leafPort: 7422 } + const factoryNats = { id: 21, isLeaf: true, iofogUuid: factory.uuid, host: '10.0.0.21', leafPort: 7422 } + const plantNats = { id: 22, isLeaf: true, iofogUuid: plant.uuid, host: '10.0.0.22', leafPort: 7422 } + const hubNats = { id: 1, isLeaf: false, isHub: true, iofogUuid: 'hub-agent', host: '10.0.0.1', leafPort: 7422 } + const appA = { id: 7, name: 'billing', isSystem: false, natsAccess: true } + const appB = { id: 8, name: 'telemetry', isSystem: false, natsAccess: true } + const systemApp = { id: 9, name: 'system-factory', isSystem: true, natsAccess: true } + let factoryMicroservices + let plantMicroservices + let includePlant + + beforeEach(() => { + factoryMicroservices = [{ applicationId: appA.id }, { applicationId: systemApp.id }] + plantMicroservices = [{ applicationId: appB.id }] + includePlant = false + $sandbox.stub(NatsInstanceManager, 'findByFog').callsFake((uuid) => { + if (uuid === regional.uuid) return Promise.resolve(regionalNats) + if (uuid === factory.uuid) return Promise.resolve(factoryNats) + if (uuid === plant.uuid) return Promise.resolve(plantNats) + return Promise.resolve(null) + }) + $sandbox.stub(NatsConnectionManager, 'findAllWithNats').callsFake((query) => { + if (query.sourceNats === regionalNats.id) { + return Promise.resolve([{ dest: hubNats }]) + } + if (query.destNats === regionalNats.id) { + return Promise.resolve([{ source: factoryNats }]) + } + if (query.destNats === factoryNats.id) { + return Promise.resolve(includePlant ? [{ source: plantNats }] : []) + } + return Promise.resolve([]) + }) + $sandbox.stub(NatsConnectionManager, 'create').resolves() + $sandbox.stub(MicroserviceManager, 'findAll').callsFake((query) => { + if (query.iofogUuid === factory.uuid) return Promise.resolve(factoryMicroservices) + if (query.iofogUuid === plant.uuid) return Promise.resolve(plantMicroservices) + return Promise.resolve([]) + }) + $sandbox.stub(ApplicationManager, 'findOne').callsFake((query) => { + if (query.id === appA.id) return Promise.resolve(appA) + if (query.id === appB.id) return Promise.resolve(appB) + if (query.id === systemApp.id) return Promise.resolve(systemApp) + return Promise.resolve(null) + }) + $sandbox.stub(NatsAuthService, 'ensureAccountForApplication').callsFake((appId) => { + if (appId === appA.id) { + return Promise.resolve({ id: 70, name: 'billing', publicKey: 'PUB_BILLING', jwt: 'billing.jwt' }) + } + if (appId === appB.id) { + return Promise.resolve({ id: 80, name: 'telemetry', publicKey: 'PUB_TELEMETRY', jwt: 'telemetry.jwt' }) + } + return Promise.resolve({ id: 90, name: 'system-factory', publicKey: 'PUB_SYSTEM', jwt: 'system.jwt' }) + }) + $sandbox.stub(NatsAuthService, 'ensureLeafSystemAccount').callsFake((fog) => { + if (fog && fog.uuid === factory.uuid) { + return Promise.resolve({ publicKey: 'FACTORY_SYS', jwt: 'factory-sys.jwt' }) + } + return Promise.resolve({ publicKey: 'REGIONAL_SYS', jwt: 'regional-sys.jwt' }) + }) + $sandbox.stub(NatsAuthService, 'ensureLeafUserForAccount').resolves({ + user: { name: 'leaf-regional', credsSecretName: 'creds-regional' } + }) + $sandbox.stub(NatsAuthService, 'ensureLeafSystemAccountUser').resolves({ + account: { name: 'SYS-leaf-regional' }, + user: { name: 'leaf-regional', credsSecretName: 'creds-sys' } + }) + $sandbox.stub(SecretService, 'getSecretEndpoint').resolves({ + data: { 'billing/leaf-regional.creds': 'regional-cred-body' } + }) + $sandbox.stub(ConfigMapManager, 'getConfigMap').resolves(null) + $sandbox.stub(ConfigMapService, 'createConfigMapEndpoint').resolves() + $sandbox.stub(ConfigMapService, 'updateConfigMapEndpoint').resolves() + $sandbox.stub(VolumeMountService, 'getVolumeMountEndpoint').resolves({ name: 'mount' }) + $sandbox.stub(VolumeMountService, 'linkVolumeMountEndpoint').resolves() + $sandbox.stub(VolumeMappingManager, 'findOne').resolves({ id: 1 }) + $sandbox.stub(ChangeTrackingService, 'update').resolves() + }) + + it('bridges a child application toward the hub with the parent leaf user', async () => { + const bundle = await NatsService._buildJwtBundle(regional, true, transaction) + const remotes = await NatsService._computeLeafRemotesForInstance(regional, regionalNats, transaction, 'nats-server-regional') + + expect(bundle['PUB_BILLING.jwt']).to.equal('billing.jwt') + expect(bundle['REGIONAL_SYS.jwt']).to.equal('regional-sys.jwt') + expect(remotes).to.have.length(1) + expect(remotes[0].account).to.equal('PUB_BILLING') + expect(remotes[0].urls).to.eql(['tls://10.0.0.1:7422']) + expect(remotes[0].credentials).to.equal('/etc/nats/creds/billing/leaf-regional.creds') + expect(remotes[0].credentials).to.not.include('factory') + expect(NatsAuthService.ensureAccountForApplication).to.not.have.been.calledWith(systemApp.id) + }) + + it('writes the parent leaf user into the parent creds for a child-only account', async () => { + await NatsService._buildLeafCredsConfigMap(regional, regionalNats, transaction) + + expect(NatsAuthService.ensureLeafUserForAccount).to.have.been.calledWith( + 70, + 'regional', + transaction, + regional.natsMicroserviceUuid + ) + const created = ConfigMapService.createConfigMapEndpoint.firstCall.args[0] + expect(created.data['billing/leaf-regional.creds']).to.equal('regional-cred-body') + expect(Object.keys(created.data).some((key) => key.includes('factory'))).to.equal(false) + expect(ChangeTrackingService.update).to.have.been.calledWith( + regional.uuid, + ChangeTrackingService.events.microserviceList, + transaction + ) + }) + + it('bridges a grandchild application and omits the child leaf system account', async () => { + includePlant = true + + const bundle = await NatsService._buildJwtBundle(regional, true, transaction) + + expect(bundle['PUB_BILLING.jwt']).to.equal('billing.jwt') + expect(bundle['PUB_TELEMETRY.jwt']).to.equal('telemetry.jwt') + expect(bundle['FACTORY_SYS.jwt']).to.equal(undefined) + expect(bundle['REGIONAL_SYS.jwt']).to.equal('regional-sys.jwt') + expect(NatsAuthService.ensureLeafSystemAccount).to.have.been.calledOnce + expect(NatsAuthService.ensureLeafSystemAccount).to.have.been.calledWith(regional, transaction) + }) + + it('keeps a downstream account in the bundle when the parent has no upstream', async () => { + NatsConnectionManager.findAllWithNats.callsFake((query) => { + if (query.destNats === regionalNats.id) { + return Promise.resolve([{ source: factoryNats }]) + } + return Promise.resolve([]) + }) + + const bundle = await NatsService._buildJwtBundle(regional, true, transaction) + const remotes = await NatsService._computeLeafRemotesForInstance(regional, regionalNats, transaction, 'nats-server-regional') + + expect(bundle['PUB_BILLING.jwt']).to.equal('billing.jwt') + expect(remotes).to.eql([]) + expect(NatsConnectionManager.create).to.not.have.been.called + }) + + it('drops a downstream application from the parent bundle and remote after the child microservice is removed', async () => { + const beforeBundle = await NatsService._buildJwtBundle(regional, true, transaction) + const beforeRemotes = await NatsService._computeLeafRemotesForInstance(regional, regionalNats, transaction, 'nats-server-regional') + expect(beforeBundle['PUB_BILLING.jwt']).to.equal('billing.jwt') + expect(beforeRemotes.map((remote) => remote.account)).to.eql(['PUB_BILLING']) + + factoryMicroservices = [] + const afterBundle = await NatsService._buildJwtBundle(regional, true, transaction) + const afterRemotes = await NatsService._computeLeafRemotesForInstance(regional, regionalNats, transaction, 'nats-server-regional') + + expect(afterBundle['PUB_BILLING.jwt']).to.equal(undefined) + expect(afterRemotes).to.eql([]) + }) + + it('does not repeat an application when leaf dials loop', async () => { + NatsConnectionManager.findAllWithNats.callsFake((query) => { + if (query.sourceNats === regionalNats.id) { + return Promise.resolve([{ dest: hubNats }]) + } + if (query.destNats === regionalNats.id) { + return Promise.resolve([{ source: factoryNats }]) + } + if (query.destNats === factoryNats.id) { + return Promise.resolve([{ source: regionalNats }]) + } + return Promise.resolve([]) + }) + + const bundle = await NatsService._buildJwtBundle(regional, true, transaction) + + expect(Object.keys(bundle).filter((key) => key === 'PUB_BILLING.jwt')).to.eql(['PUB_BILLING.jwt']) + }) + + it('includes ancestor leaves when an application runs on a downstream leaf', async () => { + const national = { id: 23, isLeaf: true, iofogUuid: 'national-agent' } + const otherServer = { id: 2, isLeaf: false, iofogUuid: 'server-b' } + const bystander = { id: 30, isLeaf: true, iofogUuid: 'bystander' } + const natsInstanceByFog = new Map([ + [hubNats.iofogUuid, hubNats], + [otherServer.iofogUuid, otherServer], + [national.iofogUuid, national], + [regional.uuid, regionalNats], + [factory.uuid, factoryNats], + [bystander.iofogUuid, bystander] + ]) + const microservicesByFog = new Map([ + [factory.uuid, [{ applicationId: appA.id }]] + ]) + NatsConnectionManager.findAllWithNats.callsFake((query) => { + if (query.sourceNats === factoryNats.id) { + return Promise.resolve([{ dest: regionalNats }]) + } + if (query.sourceNats === regionalNats.id) { + return Promise.resolve([{ dest: national }]) + } + if (query.sourceNats === national.id) { + return Promise.resolve([{ dest: hubNats }]) + } + return Promise.resolve([]) + }) + + const affected = await NatsService._getAffectedFogUuidsForApplication( + appA.id, + natsInstanceByFog, + microservicesByFog, + transaction + ) + + expect(affected.has(factory.uuid)).to.equal(true) + expect(affected.has(regional.uuid)).to.equal(true) + expect(affected.has(national.iofogUuid)).to.equal(true) + expect(affected.has(hubNats.iofogUuid)).to.equal(true) + expect(affected.has(otherServer.iofogUuid)).to.equal(true) + expect(affected.has(bystander.iofogUuid)).to.equal(false) + }) + }) + + describe('application account reconcile tasks', () => { + const transaction = {} + const factory = 'factory-agent' + const regional = 'regional-agent' + const national = 'national-agent' + const hub = 'hub-agent' + const otherServer = 'server-b' + const bystander = 'bystander' + const otherFactory = 'other-factory' + const otherRegional = 'other-regional' + const fogs = [factory, regional, national, hub, otherServer, bystander, otherFactory, otherRegional] + .map((uuid) => ({ uuid })) + const instances = [ + { id: 21, isLeaf: true, iofogUuid: factory }, + { id: 20, isLeaf: true, iofogUuid: regional }, + { id: 23, isLeaf: true, iofogUuid: national }, + { id: 1, isLeaf: false, iofogUuid: hub }, + { id: 2, isLeaf: false, iofogUuid: otherServer }, + { id: 30, isLeaf: true, iofogUuid: bystander }, + { id: 40, isLeaf: true, iofogUuid: otherFactory }, + { id: 41, isLeaf: true, iofogUuid: otherRegional } + ] + const upstream = { + 21: [{ dest: { id: 20, isLeaf: true, iofogUuid: regional } }], + 20: [{ dest: { id: 23, isLeaf: true, iofogUuid: national } }], + 23: [{ dest: { id: 1, isLeaf: false, iofogUuid: hub } }], + 40: [{ dest: { id: 41, isLeaf: true, iofogUuid: otherRegional } }], + 41: [{ dest: { id: 1, isLeaf: false, iofogUuid: hub } }] + } + const chain = [factory, regional, national, hub, otherServer] + + function taskFogUuids () { + return NatsReconcileTaskManager.create.getCalls() + .flatMap((call) => String(call.args[0].fogUuids || '').split(',')) + .map((uuid) => uuid.trim()) + .filter(Boolean) + } + + beforeEach(() => { + $sandbox.stub(FogManager, 'findAll').resolves(fogs) + $sandbox.stub(NatsInstanceManager, 'findAll').resolves(instances) + $sandbox.stub(MicroserviceManager, 'findAll').resolves([]) + $sandbox.stub(NatsConnectionManager, 'findAllWithNats').callsFake((query) => { + return Promise.resolve(upstream[query.sourceNats] || []) + }) + $sandbox.stub(NatsReconcileTaskManager, 'findAll').resolves([]) + $sandbox.stub(NatsReconcileTaskManager, 'getEntity').returns({ destroy: () => Promise.resolve() }) + $sandbox.stub(NatsReconcileTaskManager, 'create').resolves() + }) + + it('refreshes the leaf chain when application NATS access is turned off', async () => { + MicroserviceManager.findAll.resolves([{ applicationId: 7, iofogUuid: factory }]) + + await NatsService.enqueueReconcileTask({ + reason: 'account-deleted', + applicationId: 7 + }, transaction) + + expect(taskFogUuids()).to.have.members(chain) + expect(taskFogUuids()).to.not.include(bystander) + }) + + it('refreshes ancestor leaves when a microservice is created on a downstream leaf', async () => { + await NatsService.enqueueReconcileTask({ + reason: 'account-created', + applicationId: 7, + fogUuids: [factory] + }, transaction) + + expect(taskFogUuids()).to.have.members(chain) + expect(taskFogUuids()).to.not.include(bystander) + }) + + it('refreshes ancestor leaves after the microservice row is gone', async () => { + await NatsService.enqueueReconcileTask({ + reason: 'account-created', + applicationId: 7, + fogUuids: [factory] + }, transaction) + + expect(taskFogUuids()).to.have.members(chain) + expect(MicroserviceManager.findAll).to.have.been.called + }) + + it('refreshes both leaf chains when a microservice moves', async () => { + await NatsService.enqueueReconcileTask({ + reason: 'account-created', + applicationId: 7, + fogUuids: [factory, otherFactory] + }, transaction) + + expect(taskFogUuids()).to.have.members(chain.concat([otherFactory, otherRegional])) + expect(taskFogUuids()).to.not.include(bystander) + }) + + it('keeps a removed agent when a later change for the same application is still pending', async () => { + NatsReconcileTaskManager.findAll.resolves([{ fogUuids: otherFactory }]) + + await NatsService.enqueueReconcileTask({ + reason: 'account-created', + applicationId: 7, + fogUuids: [factory] + }, transaction) + + expect(taskFogUuids()).to.have.members(chain.concat([otherFactory, otherRegional])) + }) + + it('does not expand an explicit fog list for a cluster route change', async () => { + await NatsService.enqueueReconcileTask({ + reason: 'cluster-routes-changed', + fogUuids: [otherServer] + }, transaction) + + expect(NatsReconcileTaskManager.create).to.have.been.calledOnce + expect(NatsReconcileTaskManager.create.firstCall.args[0].fogUuids).to.equal(otherServer) + expect(MicroserviceManager.findAll).to.not.have.been.called + expect(NatsReconcileTaskManager.findAll).to.not.have.been.called + }) + }) + + describe('leaf broker config', () => { + const fs = require('fs') + const path = require('path') + const transaction = {} + const fog = { + uuid: 'leaf-agent', + name: 'edge-1', + host: '10.0.0.10', + natsMicroserviceUuid: 'ms-nats' + } + const natsInstance = { + id: 10, + isLeaf: true, + serverPort: 4222, + leafPort: 7422, + clusterPort: 6222, + mqttPort: 8883, + httpPort: 8222 + } + + function leafTemplate () { + return fs.readFileSync(path.join(__dirname, '../../../src/templates/nats/leaf.conf'), 'utf8') + } + + function renderLeaf () { + return NatsService._renderAndPersistNatsConfig( + fog, + natsInstance, + 'nats-server-edge-1', + 'nats-mqtt-edge-1', + 'nats-server-conf-edge-1', + 'server.conf', + leafTemplate(), + false, + false, + transaction + ) + } + + beforeEach(() => { + $sandbox.stub(NatsAuthService, 'ensureLeafSystemAccount').resolves({ publicKey: 'SYSLEAF' }) + $sandbox.stub(NatsAuthService, 'ensureSystemAccount').resolves({ publicKey: 'SYS' }) + $sandbox.stub(NatsAuthService, 'ensureOperator').resolves({ jwt: 'op-jwt' }) + $sandbox.stub(SecretService, 'getSecretEndpoint').resolves({ data: { jsk: 'jet-key' } }) + $sandbox.stub(NatsConnectionManager, 'findAllWithNats').resolves([]) + $sandbox.stub(ConfigMapManager, 'getConfigMap').resolves(null) + $sandbox.stub(ConfigMapService, 'createConfigMapEndpoint').resolves() + $sandbox.stub(ConfigMapService, 'updateConfigMapEndpoint').resolves() + $sandbox.stub(MicroserviceManager, 'update').resolves() + $sandbox.stub(ChangeTrackingService, 'update').resolves() + }) + + it('keeps the leaf domain as the agent name and the server domain as the controller namespace', async () => { + const previousNamespace = process.env.CONTROLLER_NAMESPACE + process.env.CONTROLLER_NAMESPACE = 'plant-ns' + try { + const leafRendered = await renderLeaf() + expect(leafRendered).to.include('domain: "edge-1"') + expect(leafRendered).to.not.include('plant-ns') + + NatsConnectionManager.findAllWithNats.resolves([]) + const serverRendered = await NatsService._renderAndPersistNatsConfig( + { uuid: 'hub-agent', name: 'hub', host: '10.0.0.1', natsMicroserviceUuid: 'ms-hub' }, + { + id: 1, + isLeaf: false, + host: '10.0.0.1', + serverPort: 4222, + leafPort: 7422, + clusterPort: 6222, + mqttPort: 8883, + httpPort: 8222 + }, + 'nats-server-hub', + 'nats-mqtt-hub', + 'nats-server-conf-hub', + 'server.conf', + leafTemplate(), + true, + true, + transaction + ) + + expect(serverRendered).to.include('domain: "plant-ns"') + expect(serverRendered).to.not.include('domain: "hub"') + } finally { + if (previousNamespace == null) { + delete process.env.CONTROLLER_NAMESPACE + } else { + process.env.CONTROLLER_NAMESPACE = previousNamespace + } + } + }) + + it('renders a leaf listener with port, advertise, and tls verify', async () => { + const rendered = await renderLeaf() + + expect(rendered).to.include('leafnodes:') + expect(rendered).to.match(/port:\s*7422/) + expect(rendered).to.include('advertise: 10.0.0.10') + expect(rendered).to.include('verify: true') + expect(rendered).to.include('handshake_first: true') + expect(rendered).to.include('reconnect: "10s"') + expect(rendered).to.include('remotes: []') + }) + + it('renders a server with an empty leaf remote list', async () => { + NatsConnectionManager.findAllWithNats.resolves([ + { dest: { id: 2, isLeaf: false, host: '10.0.0.2', clusterPort: 6222, leafPort: 7422 } } + ]) + $sandbox.stub(NatsAuthService, 'ensureAccountForApplication').rejects(new Error('servers do not dial leaf remotes')) + const server = { + id: 1, + isLeaf: false, + host: '10.0.0.1', + serverPort: 4222, + leafPort: 7422, + clusterPort: 6222, + mqttPort: 8883, + httpPort: 8222 + } + + const rendered = await NatsService._renderAndPersistNatsConfig( + { uuid: 'hub-agent', name: 'hub', host: '10.0.0.1', natsMicroserviceUuid: 'ms-hub' }, + server, + 'nats-server-hub', + 'nats-mqtt-hub', + 'nats-server-conf-hub', + 'server.conf', + leafTemplate(), + false, + true, + transaction + ) + + expect(rendered).to.include('cluster:') + expect(rendered).to.include('nats://10.0.0.2:6222') + expect(rendered).to.not.include('remotes:') + expect(rendered).to.not.include('tls://') + expect(NatsAuthService.ensureAccountForApplication).to.not.have.been.called + }) + + it('writes a changed leaf config without rebuilding the container', async () => { + ConfigMapManager.getConfigMap.resolves({ data: { 'server.conf': 'port: 1\n' } }) + + await renderLeaf() + + expect(ConfigMapService.updateConfigMapEndpoint).to.have.been.calledOnce + expect(MicroserviceManager.update).to.not.have.been.called + expect(ChangeTrackingService.update).to.not.have.been.called + }) + + it('does not restart the leaf broker the first time its config is written', async () => { + await renderLeaf() + + expect(ConfigMapService.createConfigMapEndpoint).to.have.been.calledOnce + expect(MicroserviceManager.update).to.not.have.been.called + expect(ChangeTrackingService.update).to.not.have.been.called + }) + + it('does not restart the leaf broker when the rendered config is unchanged', async () => { + const rendered = await renderLeaf() + ConfigMapManager.getConfigMap.resolves({ data: { 'server.conf': rendered } }) + MicroserviceManager.update.resetHistory() + ChangeTrackingService.update.resetHistory() + + await renderLeaf() + + expect(ConfigMapService.updateConfigMapEndpoint).to.not.have.been.called + expect(MicroserviceManager.update).to.not.have.been.called + expect(ChangeTrackingService.update).to.not.have.been.called + }) }) describe('operator JWT fields', () => { @@ -366,6 +1498,72 @@ describe('NATS Service', () => { expect(txLabels).to.deep.equal(['nats.ensure.certPrep', 'nats.ensure.authPrep', 'nats.ensure.topology']) }) + it('rolls the NATS StatefulSet after a hub route patch that removes a peer', async () => { + stubKubernetesControlPlane() + const callOrder = [] + const NatsServiceFresh = loadNatsServiceWithTxStub(async (fn, runOptions = {}) => { + if (runOptions.label === 'nats.ensure.certPrep') { + return { serverCertName: 'cert', mqttCertName: 'mqtt', jetstreamKey: { secretName: 'jsk', jsk: 'key' } } + } + if (runOptions.label === 'nats.ensure.authPrep') { + return { mode: 'leaf', isHub: false, isLeaf: true } + } + if (runOptions.label === 'nats.ensure.topology') { + return { + microservice: { uuid: 'ms-1' }, + k8sHubPatch: ['nats://10.0.0.1:6222'], + k8sRollout: true + } + } + return fn({}) + }) + $sandbox.stub(k8sClient, 'getConfigMap').callsFake(async () => { + callOrder.push('k8s-get') + return { data: { 'server.conf': 'routes: ["nats://10.0.0.1:6222","nats://10.0.0.2:6222"]' } } + }) + $sandbox.stub(k8sClient, 'patchConfigMap').callsFake(async () => { + callOrder.push('k8s-patch') + }) + $sandbox.stub(k8sClient, 'rolloutStatefulSet').callsFake(async () => { + callOrder.push('k8s-rollout') + }) + + await NatsServiceFresh.ensureNatsForFog({ uuid: 'fog-1', name: 'local-agent' }, { mode: 'leaf' }) + + expect(callOrder).to.deep.equal(['k8s-get', 'k8s-patch', 'k8s-rollout']) + expect(k8sClient.rolloutStatefulSet).to.have.been.calledOnceWith('nats') + }) + + it('patches hub routes without rolling when a peer joins an existing cluster', async () => { + stubKubernetesControlPlane() + const NatsServiceFresh = loadNatsServiceWithTxStub(async (fn, runOptions = {}) => { + if (runOptions.label === 'nats.ensure.certPrep') { + return { serverCertName: 'cert', mqttCertName: 'mqtt', jetstreamKey: { secretName: 'jsk', jsk: 'key' } } + } + if (runOptions.label === 'nats.ensure.authPrep') { + return { mode: 'server', isHub: false, isLeaf: false } + } + if (runOptions.label === 'nats.ensure.topology') { + return { + microservice: { uuid: 'ms-1' }, + k8sHubPatch: ['nats://10.0.0.1:6222', 'nats://10.0.0.2:6222'], + k8sRollout: false + } + } + return fn({}) + }) + $sandbox.stub(k8sClient, 'getConfigMap').resolves({ + data: { 'server.conf': 'routes: ["nats://10.0.0.1:6222"]' } + }) + $sandbox.stub(k8sClient, 'patchConfigMap').resolves() + $sandbox.stub(k8sClient, 'rolloutStatefulSet').resolves() + + await NatsServiceFresh.ensureNatsForFog({ uuid: 'fog-1', name: 'local-agent' }, { mode: 'server' }) + + expect(k8sClient.patchConfigMap).to.have.been.calledOnce + expect(k8sClient.rolloutStatefulSet).to.not.have.been.called + }) + it('reconcileResolverArtifacts applies JWT bundle K8s patch after runInTransaction', async () => { stubKubernetesControlPlane() const callOrder = [] @@ -383,6 +1581,7 @@ describe('NATS Service', () => { $sandbox.stub(NatsAccountRuleManager, 'findOne').resolves({ id: 1, name: 'default-account' }) $sandbox.stub(NatsAccountManager, 'findOne').resolves({ id: 1, isSystem: true }) $sandbox.stub(require('../../../src/services/nats-auth-service'), 'ensureSystemAccount').resolves() + $sandbox.stub(NatsOperatorManager, 'findOne').resolves(null) $sandbox.stub(ConfigMapManager, 'getConfigMap').resolves(null) $sandbox.stub(ConfigMapService, 'createConfigMapEndpoint').resolves({ name: 'iofog-nats-jwt-bundle' }) $sandbox.stub(k8sClient, 'getConfigMap').callsFake(async () => { @@ -398,4 +1597,140 @@ describe('NATS Service', () => { expect(callOrder).to.deep.equal(['tx-start', 'tx-end', 'k8s-get', 'k8s-patch']) }) }) + + describe('Kubernetes hub operator JWT', () => { + const k8sClient = require('../../../src/utils/k8s-client') + const config = require('../../../src/config') + const hubConf = [ + '# Operator', + 'operator = OLDJWT', + 'system_account = SYS', + 'routes: ["nats://10.0.0.1:6222"]' + ].join('\n') + + function loadNatsServiceWithTxStub (runInTransactionImpl) { + const txRunnerPath = require.resolve('../../../src/helpers/transaction-runner') + const natsPath = require.resolve('../../../src/services/nats-service') + delete require.cache[natsPath] + delete require.cache[txRunnerPath] + const transactionRunner = require('../../../src/helpers/transaction-runner') + $sandbox.stub(transactionRunner, 'runInTransaction').callsFake(runInTransactionImpl) + return require('../../../src/services/nats-service') + } + + function stubReconcileDb () { + $sandbox.stub(config, 'get').callsFake((key, defaultValue) => { + if (key === 'app.ControlPlane') return 'kubernetes' + if (key === 'nats.enabled') return false + return defaultValue + }) + $sandbox.stub(FogManager, 'findAll').resolves([]) + $sandbox.stub(ApplicationManager, 'findAll').resolves([]) + $sandbox.stub(NatsInstanceManager, 'findAll').resolves([]) + $sandbox.stub(NatsAccountRuleManager, 'findOne').resolves({ id: 1, name: 'default-account' }) + $sandbox.stub(NatsAccountManager, 'findOne').resolves({ id: 1, publicKey: 'SYS', jwt: 'SYSJWT', isSystem: true }) + $sandbox.stub(NatsAuthService, 'ensureSystemAccount').resolves() + $sandbox.stub(ConfigMapManager, 'getConfigMap').resolves(null) + $sandbox.stub(ConfigMapService, 'createConfigMapEndpoint').resolves({ name: 'iofog-nats-jwt-bundle' }) + } + + it('replaces only the operator line and leaves routes intact', () => { + const replaced = NatsService._replaceOperatorJwtLine(hubConf, 'NEWJWT') + expect(replaced.status).to.equal('changed') + expect(replaced.content).to.include('operator = NEWJWT') + expect(replaced.content).to.include('routes: ["nats://10.0.0.1:6222"]') + expect(replaced.content).to.not.include('OLDJWT') + }) + + it('reports an unchanged operator line', () => { + const replaced = NatsService._replaceOperatorJwtLine(hubConf, 'OLDJWT') + expect(replaced.status).to.equal('unchanged') + expect(replaced.content).to.equal(undefined) + }) + + it('patches the hub operator line without rolling the StatefulSet', async () => { + stubReconcileDb() + $sandbox.stub(NatsOperatorManager, 'findOne').resolves({ jwt: 'NEWJWT' }) + const NatsServiceFresh = loadNatsServiceWithTxStub(async (fn) => fn({})) + $sandbox.stub(k8sClient, 'getConfigMap').callsFake(async (name) => { + if (name === 'iofog-nats-config') { + return { data: { 'server.conf': hubConf } } + } + return { data: { 'SYS.jwt': 'SYSJWT' } } + }) + $sandbox.stub(k8sClient, 'patchConfigMap').resolves() + $sandbox.stub(k8sClient, 'rolloutStatefulSet').resolves() + + await NatsServiceFresh.reconcileResolverArtifacts({}) + + const operatorPatch = k8sClient.patchConfigMap.getCalls().find((call) => call.args[0] === 'iofog-nats-config') + expect(operatorPatch).to.not.equal(undefined) + expect(operatorPatch.args[1].data['server.conf']).to.include('operator = NEWJWT') + expect(operatorPatch.args[1].data['server.conf']).to.include('routes: ["nats://10.0.0.1:6222"]') + expect(k8sClient.rolloutStatefulSet).to.not.have.been.called + }) + + it('does not patch the hub config when the operator line already matches', async () => { + stubReconcileDb() + $sandbox.stub(NatsOperatorManager, 'findOne').resolves({ jwt: 'OLDJWT' }) + const NatsServiceFresh = loadNatsServiceWithTxStub(async (fn) => fn({})) + $sandbox.stub(k8sClient, 'getConfigMap').callsFake(async (name) => { + if (name === 'iofog-nats-config') { + return { data: { 'server.conf': hubConf } } + } + return { data: { 'SYS.jwt': 'SYSJWT' } } + }) + $sandbox.stub(k8sClient, 'patchConfigMap').resolves() + $sandbox.stub(k8sClient, 'rolloutStatefulSet').resolves() + + await NatsServiceFresh.reconcileResolverArtifacts({}) + + const operatorPatch = k8sClient.patchConfigMap.getCalls().find((call) => call.args[0] === 'iofog-nats-config') + expect(operatorPatch).to.equal(undefined) + expect(k8sClient.rolloutStatefulSet).to.not.have.been.called + }) + + it('returns when the hub ConfigMap does not exist yet', async () => { + stubReconcileDb() + $sandbox.stub(NatsOperatorManager, 'findOne').resolves({ jwt: 'NEWJWT' }) + const NatsServiceFresh = loadNatsServiceWithTxStub(async (fn) => fn({})) + $sandbox.stub(k8sClient, 'getConfigMap').resolves(null) + $sandbox.stub(k8sClient, 'patchConfigMap').resolves() + $sandbox.stub(k8sClient, 'rolloutStatefulSet').resolves() + + await NatsServiceFresh.reconcileResolverArtifacts({}) + + const operatorPatch = k8sClient.patchConfigMap.getCalls().find((call) => call.args[0] === 'iofog-nats-config') + expect(operatorPatch).to.equal(undefined) + expect(k8sClient.rolloutStatefulSet).to.not.have.been.called + }) + + it('retries the operator line patch once after a conflict', async () => { + stubReconcileDb() + $sandbox.stub(NatsOperatorManager, 'findOne').resolves({ jwt: 'NEWJWT' }) + const NatsServiceFresh = loadNatsServiceWithTxStub(async (fn) => fn({})) + $sandbox.stub(k8sClient, 'getConfigMap').callsFake(async (name) => { + if (name === 'iofog-nats-config') { + return { data: { 'server.conf': hubConf } } + } + return { data: { 'SYS.jwt': 'SYSJWT' } } + }) + const conflict = Object.assign(new Error('conflict'), { code: 409 }) + let operatorAttempts = 0 + $sandbox.stub(k8sClient, 'patchConfigMap').callsFake(async (name) => { + if (name !== 'iofog-nats-config') return + operatorAttempts += 1 + if (operatorAttempts === 1) { + throw conflict + } + }) + $sandbox.stub(k8sClient, 'rolloutStatefulSet').resolves() + + await NatsServiceFresh.reconcileResolverArtifacts({}) + + const operatorPatches = k8sClient.patchConfigMap.getCalls().filter((call) => call.args[0] === 'iofog-nats-config') + expect(operatorPatches).to.have.length(2) + expect(k8sClient.rolloutStatefulSet).to.not.have.been.called + }) + }) }) From 4aa1760ff8f93f3f1c626320a55dfb1a14545126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Durmu=C5=9F?= Date: Sun, 8 Nov 2026 21:05:16 +0300 Subject: [PATCH 2/9] Accept an agent name or uuid as the service bridge when that interior is reachable, and skip the Kubernetes Service when the listener is not on the hub router. --- docs/service-interconnection.md | 19 +- src/services/service-platform-service.js | 28 +- src/services/services-service.js | 289 +++++++++++++----- .../services/service-platform-service.test.js | 83 +++++ test/src/services/services-service.test.js | 280 +++++++++++++++++ 5 files changed, 603 insertions(+), 96 deletions(-) diff --git a/docs/service-interconnection.md b/docs/service-interconnection.md index deed4598..2d60fe69 100644 --- a/docs/service-interconnection.md +++ b/docs/service-interconnection.md @@ -79,7 +79,7 @@ spec: | `spec.type` | YAML | yes | `microservice`, `agent`, `k8s`, or `external`. Immutable. | | `spec.resource` | YAML | yes | Who or what the connector dials. Meaning depends on `type`. | | `spec.targetPort` | YAML | yes | TCP port on that backend. Becomes `tcpConnector.port`. | -| `spec.defaultBridge` | YAML | no | Which hub router owns the listener. Default `default-router`. Immutable. | +| `spec.defaultBridge` | YAML | no | Which router owns the listener. Default `default-router`. For `microservice` and `agent`, an agent name or agent uuid of an interior this agent can reach. A name is stored as that agent's uuid. `default-router` is stored as that literal. Immutable. | | `spec.servicePort` | YAML | on Kubernetes, for non-`k8s` types | Port clients use on the Kubernetes Service. On a remote control plane Controller overwrites this with `bridgePort`. | | `spec.k8sType` | YAML | on Kubernetes, for non-`k8s` types | `LoadBalancer`, `ClusterIP`, or `NodePort`. | | `bridgePort` | assigned | — | Port the router listener binds. Taken from `BRIDGE_PORTS_RANGE` (default `10024-65535`), first free port. Not accepted from YAML. | @@ -98,7 +98,7 @@ spec: `microservice` and `agent` require a router on that agent. Router mode `none` is rejected: a TCP bridge service requires a router on the agent. -`k8s` and `external` require `defaultBridge: default-router`. For `microservice` and `agent`, `defaultBridge` may instead be the uuid of an upstream router that this agent's router is already connected to. +`k8s` and `external` require `defaultBridge: default-router`. For `microservice` and `agent`, `defaultBridge` may instead name an interior this agent's router can reach. Use the agent name or the agent uuid, the same forms as `upstreamRouters`. Uuid is tried first, then the agent name. The stored value is that agent's uuid. The literal `default-router` is not rewritten to the system agent's uuid. Reachability is the interior mesh. An edge reaches a bridge when an interior it dials is in that bridge's mesh, so `edge → interior1 → interior2` allows `interior2` and, once `interior2` links to the hub, `default-router`. Interior links count in both directions. A bridge in another island is rejected. ### Connector host @@ -136,10 +136,11 @@ The connector is written onto the router that can open that host: `CONTROL_PLANE=kubernetes` (or `app.ControlPlane: kubernetes`). -| `spec.type` | `k8sType` and `servicePort` | Controller creates a Kubernetes Service | -|---|---|---| -| `microservice`, `agent`, `external` | required | yes | -| `k8s` | not required | no. `type: k8s` is itself rejected unless the control plane is Kubernetes | +| `spec.type` | `defaultBridge` | `k8sType` and `servicePort` | Controller creates a Kubernetes Service | +|---|---|---|---| +| `microservice`, `agent`, `external` | `default-router` | required | yes. The listener is written to ConfigMap `iofog-router` | +| `microservice`, `agent` | an agent name or uuid | not required | no. The listener is written to that router's microservice `config`. `serviceEndpoint` is that router's host and `servicePort` is `bridgePort` | +| `k8s` | `default-router` only | not required | no. `type: k8s` is itself rejected unless the control plane is Kubernetes | The Service is created in `CONTROLLER_NAMESPACE` (`app.namespace`). Name is `metadata.name`. @@ -329,8 +330,8 @@ The connector and the listener share `address`, which is the service name. The l | Control plane | Hub listener and hub connector | Agent router | |---|---|---| -| Kubernetes | ConfigMap `iofog-router`, key `skrouterd.json`, in `CONTROLLER_NAMESPACE`. The file is a JSON array of pairs. A hub lock serializes writers. | The agent that owns the backend gets the connector in its router microservice `config`. Tagged agents get listeners in that same `config`. | -| Remote | The default router's microservice `config`, or the router for `defaultBridge` when that is an agent uuid. Object form, under `bridges`. | Same as Kubernetes for the backend connector and for tagged listeners. | +| Kubernetes | ConfigMap `iofog-router` when `defaultBridge` is `default-router`. A named bridge stores the listener in that router's microservice `config`, same as a remote control plane. The file is a JSON array of pairs. A hub lock serializes writers of the ConfigMap. | The agent that owns the backend gets the connector in its router microservice `config`. Tagged agents get listeners in that same `config`. | +| Remote | The default router's microservice `config`, or the router for `defaultBridge` when that is an agent uuid (a name given at create is stored as that uuid). Object form, under `bridges`. | Same as Kubernetes for the backend connector and for tagged listeners. | Kubernetes hub file (`skrouterd.json`): @@ -351,7 +352,7 @@ Kubernetes hub file (`skrouterd.json`): ] ``` -On Kubernetes the **listener is always** written to that ConfigMap. The **connector** is written there only for `k8s` and `external` (their site is the default router). A `microservice` or `agent` connector is written to that agent's router config instead, including on Kubernetes. +On Kubernetes the listener is written to that ConfigMap when `defaultBridge` is `default-router`. A named bridge writes it to that router's microservice `config` instead, and Controller does not create a Kubernetes Service. The connector is written to the ConfigMap only for `k8s` and `external` (their site is the default router). A `microservice` or `agent` connector is written to that agent's router config instead, including on Kubernetes. Remote hub router microservice `config`: diff --git a/src/services/service-platform-service.js b/src/services/service-platform-service.js index 9cda3cf9..7b316bc0 100644 --- a/src/services/service-platform-service.js +++ b/src/services/service-platform-service.js @@ -296,7 +296,15 @@ async function planHubTcpConnectorDelete (serviceConfig, transaction) { return emptyK8sHubRouterPlan() } -async function planHubTcpListenerUpsert (serviceConfig) { +function _listenerOnKubernetesHub (serviceConfig) { + return !serviceConfig.defaultBridge || serviceConfig.defaultBridge === 'default-router' +} + +async function planHubTcpListenerUpsert (serviceConfig, transaction) { + if (!_listenerOnKubernetesHub(serviceConfig)) { + await upsertHubTcpListenerDb(serviceConfig, transaction) + return emptyK8sHubRouterPlan() + } const listener = ServicesService._buildTcpListener(serviceConfig) return { ...emptyK8sHubRouterPlan(), @@ -304,7 +312,11 @@ async function planHubTcpListenerUpsert (serviceConfig) { } } -async function planHubTcpListenerDelete (serviceConfig) { +async function planHubTcpListenerDelete (serviceConfig, transaction) { + if (!_listenerOnKubernetesHub(serviceConfig)) { + await deleteHubTcpListenerDb(serviceConfig, transaction) + return emptyK8sHubRouterPlan() + } return { ...emptyK8sHubRouterPlan(), deleteListenerNames: [`${serviceConfig.name}-listener`] @@ -315,7 +327,7 @@ async function upsertHubTcpListener (serviceConfig, transaction) { const isK8s = await ServicesService.checkKubernetesEnvironment() if (isK8s) { - const plan = await planHubTcpListenerUpsert(serviceConfig) + const plan = await planHubTcpListenerUpsert(serviceConfig, transaction) await applyK8sHubRouterPlan(plan) return } @@ -351,7 +363,7 @@ async function deleteHubTcpListener (serviceConfig, transaction) { const isK8s = await ServicesService.checkKubernetesEnvironment() if (isK8s) { - const plan = await planHubTcpListenerDelete(serviceConfig) + const plan = await planHubTcpListenerDelete(serviceConfig, transaction) await applyK8sHubRouterPlan(plan) return } @@ -402,7 +414,7 @@ async function watchLoadBalancerWithTimeout (serviceName) { } function needsK8sService (serviceConfig, isK8s) { - if (!isK8s) { + if (!isK8s || !_listenerOnKubernetesHub(serviceConfig)) { return false } const serviceType = (serviceConfig.type || '').toLowerCase() @@ -459,7 +471,7 @@ async function reconcileServiceHub (serviceConfig, snapshot, transaction) { } plans.push(await planHubTcpConnectorUpsert(serviceConfig, transaction)) - plans.push(await planHubTcpListenerUpsert(serviceConfig)) + plans.push(await planHubTcpListenerUpsert(serviceConfig, transaction)) return mergeK8sHubRouterPlans(...plans) } @@ -467,7 +479,7 @@ async function reconcileServiceHub (serviceConfig, snapshot, transaction) { async function reconcileServiceDeleteHub (serviceConfig, transaction) { const plans = [ await planHubTcpConnectorDelete(serviceConfig, transaction), - await planHubTcpListenerDelete(serviceConfig) + await planHubTcpListenerDelete(serviceConfig, transaction) ] return mergeK8sHubRouterPlans(...plans) } @@ -539,7 +551,7 @@ async function reconcileService (serviceName, task) { await applyK8sHubRouterPlan(hubPlan) if (isDelete) { - if ((prep.serviceConfig.type || '').toLowerCase() !== 'k8s') { + if (needsK8sService(prep.serviceConfig, isK8s)) { await ServicesService._deleteK8sService(prep.serviceConfig.name) } } else { diff --git a/src/services/services-service.js b/src/services/services-service.js index a278a9ac..d4f9a882 100644 --- a/src/services/services-service.js +++ b/src/services/services-service.js @@ -6,6 +6,7 @@ const RouterConnectionManager = require('../data/managers/router-connection-mana const K8sClient = require('../utils/k8s-client') const AppHelper = require('../helpers/app-helper') const config = require('../config') +const Constants = require('../helpers/constants') const Errors = require('../helpers/errors') const ErrorMessages = require('../helpers/error-messages') const Validator = require('../schemas') @@ -165,13 +166,43 @@ async function checkKubernetesEnvironment () { return controlPlane && controlPlane.toLowerCase() === 'kubernetes' } +function _usesKubernetesHubService (serviceConfig) { + const bridge = serviceConfig.defaultBridge || Constants.DEFAULT_ROUTER_NAME + return bridge === Constants.DEFAULT_ROUTER_NAME +} + async function validateNonK8sType (serviceConfig) { const isK8s = await checkKubernetesEnvironment() - if (serviceConfig.type.toLowerCase() !== 'k8s' && isK8s) { - if (!serviceConfig.k8sType || !serviceConfig.servicePort) { - throw new Errors.ValidationError('Kubernetes environment is required for k8s service type(LoadBalancer or ClusterIP or NodePort) and service port') + const serviceType = (serviceConfig.type || '').toLowerCase() + if (!isK8s || serviceType === 'k8s' || serviceType === '') { + return + } + // A named bridge is reached on that router. It does not need a Kubernetes Service. + if (!_usesKubernetesHubService(serviceConfig)) { + return + } + if (!serviceConfig.k8sType || !serviceConfig.servicePort) { + throw new Errors.ValidationError('Kubernetes environment is required for k8s service type(LoadBalancer or ClusterIP or NodePort) and service port') + } +} + +async function _assignBridgeEndpoint (serviceData, transaction) { + if (serviceData.defaultBridge === Constants.DEFAULT_ROUTER_NAME) { + const defaultRouter = await RouterManager.findOne({ isDefault: true }, transaction) + if (!defaultRouter) { + throw new Errors.NotFoundError('Default router not found') } + serviceData.serviceEndpoint = defaultRouter.host + serviceData.servicePort = serviceData.bridgePort + return + } + + const router = await RouterManager.findOne({ iofogUuid: serviceData.defaultBridge }, transaction) + if (!router) { + throw new Errors.NotFoundError('Router not found') } + serviceData.serviceEndpoint = router.host + serviceData.servicePort = serviceData.bridgePort } async function _validateServiceName (serviceConfig) { @@ -238,59 +269,157 @@ async function validateFogServiceType (serviceConfig, transaction) { serviceConfig.resource = fogNode.uuid } -async function validateDefaultBridge (serviceConfig, transaction) { - // If defaultBridge is empty, set it to 'default-router' - if (!serviceConfig.defaultBridge) { - logger.debug('Setting default bridge to default-router') - serviceConfig.defaultBridge = 'default-router' - return +async function _findRouterByBridgeId (bridgeId, transaction) { + const routerByUuid = await RouterManager.findOne({ iofogUuid: bridgeId }, transaction) + if (routerByUuid) { + return routerByUuid } - // If service type is not microservice or agent, defaultBridge must be 'default-router' - if (serviceConfig.type.toLowerCase() !== 'microservice' && serviceConfig.type.toLowerCase() !== 'agent') { - if (serviceConfig.defaultBridge !== 'default-router') { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_DEFAULT_BRIDGE, serviceConfig.defaultBridge)) + const fog = await FogManager.findOne({ name: bridgeId }, transaction) + if (!fog) { + return null + } + return RouterManager.findOne({ iofogUuid: fog.uuid }, transaction) +} + +function _isInteriorLinkEnd (router, bridgeRouter) { + if (!router) { + return false + } + if (bridgeRouter && router.id === bridgeRouter.id) { + return true + } + return router.isEdge === false +} + +// Inter-router links are full duplex once up, so the interior mesh is undirected. +// An edge reaches the bridge when an interior it dials is in that mesh. +function _bridgeRouterReachable (agentRouter, bridgeRouter, connections) { + if (agentRouter.id === bridgeRouter.id) { + return true + } + + const neighbors = new Map() + const link = (left, right) => { + if (!neighbors.has(left)) { + neighbors.set(left, new Set()) } - return + neighbors.get(left).add(right) } - // For microservice or agent type, if user provided a UUID instead of 'default-router' - if (serviceConfig.defaultBridge !== 'default-router') { - let iofogUuid + const edgeUpstreams = [] + for (const connection of connections || []) { + const source = connection.source + const dest = connection.dest + if (!source || !dest) { + continue + } + const sourceInterior = _isInteriorLinkEnd(source, bridgeRouter) + const destInterior = _isInteriorLinkEnd(dest, bridgeRouter) + if (sourceInterior && destInterior) { + link(source.id, dest.id) + link(dest.id, source.id) + } + if (source.id === agentRouter.id && destInterior) { + edgeUpstreams.push(dest.id) + } + } - if (serviceConfig.type.toLowerCase() === 'microservice') { - // Get the microservice to find its iofog node - const microservice = await MicroserviceManager.findOne({ uuid: serviceConfig.resource }, transaction) - if (!microservice) { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, serviceConfig.resource)) + const reachable = new Set([bridgeRouter.id]) + const queue = [bridgeRouter.id] + while (queue.length > 0) { + const current = queue.shift() + const nextIds = neighbors.get(current) + if (!nextIds) { + continue + } + for (const nextId of nextIds) { + if (!reachable.has(nextId)) { + reachable.add(nextId) + queue.push(nextId) } - iofogUuid = microservice.iofogUuid - } else if (serviceConfig.type.toLowerCase() === 'agent') { - // For agent type, the resource is the agent UUID - iofogUuid = serviceConfig.resource } + } - // Get the router for the iofog node - const router = await RouterManager.findOne({ iofogUuid }, transaction) - if (!router) { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_ROUTER, iofogUuid)) - } + if (agentRouter.isEdge === false) { + return reachable.has(agentRouter.id) + } + return edgeUpstreams.some((id) => reachable.has(id)) +} + +async function _serviceBackendRouter (serviceConfig, transaction) { + let iofogUuid - // Check if the router has a connection to the specified upstream router - const upstreamRouter = await RouterManager.findOne({ iofogUuid: serviceConfig.defaultBridge }, transaction) - if (!upstreamRouter) { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_ROUTER, serviceConfig.defaultBridge)) + if (serviceConfig.type.toLowerCase() === 'microservice') { + const microservice = await MicroserviceManager.findOne({ uuid: serviceConfig.resource }, transaction) + if (!microservice) { + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, serviceConfig.resource)) } + iofogUuid = microservice.iofogUuid + } else { + iofogUuid = serviceConfig.resource + } - const routerConnection = await RouterConnectionManager.findOne({ - sourceRouter: router.id, - destRouter: upstreamRouter.id - }, transaction) + const router = await RouterManager.findOne({ iofogUuid }, transaction) + if (!router) { + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_ROUTER, iofogUuid)) + } + return router +} + +async function _assertBridgeReachable (agentRouter, bridgeRouter, bridgeId, transaction) { + const connections = await RouterConnectionManager.findAllWithRouters({}, transaction) + if (_bridgeRouterReachable(agentRouter, bridgeRouter, connections)) { + return + } + throw new Errors.ValidationError(AppHelper.formatMessage( + ErrorMessages.DEFAULT_BRIDGE_UNREACHABLE, + bridgeId, + agentRouter.iofogUuid + )) +} + +async function _assertDefaultRouterReachable (agentRouter, transaction) { + const defaultRouter = await RouterManager.findOne({ isDefault: true }, transaction) + if (!defaultRouter) { + throw new Errors.NotFoundError('Default router not found') + } + await _assertBridgeReachable(agentRouter, defaultRouter, Constants.DEFAULT_ROUTER_NAME, transaction) +} - if (!routerConnection) { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_ROUTER_CONNECTION, serviceConfig.defaultBridge, router.id)) +async function validateDefaultBridge (serviceConfig, transaction) { + // If defaultBridge is empty, set it to 'default-router' + if (!serviceConfig.defaultBridge) { + logger.debug('Setting default bridge to default-router') + serviceConfig.defaultBridge = Constants.DEFAULT_ROUTER_NAME + } + + // If service type is not microservice or agent, defaultBridge must be 'default-router'. + // Those types place the connector on the hub, so there is no agent path to check. + if (serviceConfig.type.toLowerCase() !== 'microservice' && serviceConfig.type.toLowerCase() !== 'agent') { + if (serviceConfig.defaultBridge !== Constants.DEFAULT_ROUTER_NAME) { + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_DEFAULT_BRIDGE, serviceConfig.defaultBridge)) } + return + } + + const router = await _serviceBackendRouter(serviceConfig, transaction) + + // The hub sentinel is stored as-is. It is not an agent name or uuid. + if (serviceConfig.defaultBridge === Constants.DEFAULT_ROUTER_NAME) { + await _assertDefaultRouterReachable(router, transaction) + return + } + + // Agent uuid first, then agent name. Same order as upstreamRouters. + const bridgeId = serviceConfig.defaultBridge + const bridgeRouter = await _findRouterByBridgeId(bridgeId, transaction) + if (!bridgeRouter || !bridgeRouter.iofogUuid) { + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_ROUTER, bridgeId)) } + + await _assertBridgeReachable(router, bridgeRouter, bridgeId, transaction) + serviceConfig.defaultBridge = bridgeRouter.iofogUuid } async function defineBridgePort (serviceConfig, transaction) { @@ -649,22 +778,8 @@ async function createServiceEndpoint (serviceData, transaction) { // Set provisioning fields serviceData.provisioningStatus = 'pending' serviceData.provisioningError = null - if (!isK8s) { - if (serviceData.defaultBridge === 'default-router') { - const defaultRouter = await RouterManager.findOne({ isDefault: true }, transaction) - if (!defaultRouter) { - throw new Errors.NotFoundError('Default router not found') - } - serviceData.serviceEndpoint = defaultRouter.host - serviceData.servicePort = serviceData.bridgePort - } else { - const router = await RouterManager.findOne({ iofogUuid: serviceData.defaultBridge }, transaction) - if (!router) { - throw new Errors.NotFoundError('Router not found') - } - serviceData.serviceEndpoint = router.host - serviceData.servicePort = serviceData.bridgePort - } + if (!isK8s || !_usesKubernetesHubService(serviceData)) { + await _assignBridgeEndpoint(serviceData, transaction) } // 7. Create service in database first @@ -707,19 +822,31 @@ async function updateServiceEndpoint (serviceName, serviceData, transaction) { throw new Errors.ValidationError('Changing service type is not allowed. Please delete the service and create a new one with the desired type.') } - if (serviceData.defaultBridge && serviceData.defaultBridge !== existingService.defaultBridge) { - throw new Errors.ValidationError('Changing default bridge is not allowed. Please delete the service and create a new one with the desired default bridge.') - } - // 4. Check K8s environment if type is k8s const isK8s = await checkKubernetesEnvironment() if (existingService.type === 'k8s' && !isK8s) { throw new Errors.ValidationError('Kubernetes environment is required for k8s service type') } - if (serviceData.type !== 'k8s' && isK8s) { + if (isK8s && (serviceData.type || existingService.type) !== 'k8s') { logger.debug('Validating non k8s service type') - await validateNonK8sType(serviceData) + await validateNonK8sType({ + type: serviceData.type || existingService.type, + defaultBridge: existingService.defaultBridge, + k8sType: serviceData.k8sType, + servicePort: serviceData.servicePort + }) + } + + // Bridge validation needs the service type and backend. Fill them from the + // stored row when the patch omits them, then drop them so they are not rewritten. + const omittedType = serviceData.defaultBridge !== undefined && serviceData.type === undefined + const omittedResource = serviceData.defaultBridge !== undefined && serviceData.resource === undefined + if (omittedType) { + serviceData.type = existingService.type + } + if (omittedResource) { + serviceData.resource = existingService.resource } // 5. Validate microservice type if needed @@ -732,10 +859,21 @@ async function updateServiceEndpoint (serviceName, serviceData, transaction) { await validateFogServiceType(serviceData, transaction) } - // 7. Validate default bridge if needed + // 7. Validate default bridge if needed. Resolve an agent name to its uuid + // before the immutability check, so resending the same router by name is not a change. if (serviceData.defaultBridge) { await validateDefaultBridge(serviceData, transaction) } + if (omittedType) { + delete serviceData.type + } + if (omittedResource) { + delete serviceData.resource + } + + if (serviceData.defaultBridge && serviceData.defaultBridge !== existingService.defaultBridge) { + throw new Errors.ValidationError('Changing default bridge is not allowed. Please delete the service and create a new one with the desired default bridge.') + } serviceData.bridgePort = existingService.bridgePort @@ -743,22 +881,15 @@ async function updateServiceEndpoint (serviceName, serviceData, transaction) { serviceData.provisioningStatus = 'pending' serviceData.provisioningError = null - if (!isK8s) { - if (serviceData.defaultBridge === 'default-router') { - const defaultRouter = await RouterManager.findOne({ isDefault: true }, transaction) - if (!defaultRouter) { - throw new Errors.NotFoundError('Default router not found') - } - serviceData.serviceEndpoint = defaultRouter.host - serviceData.servicePort = serviceData.bridgePort - } else { - const router = await RouterManager.findOne({ iofogUuid: serviceData.defaultBridge }, transaction) - if (!router) { - throw new Errors.NotFoundError('Router not found') - } - serviceData.serviceEndpoint = router.host - serviceData.servicePort = serviceData.bridgePort + const effectiveBridge = serviceData.defaultBridge || existingService.defaultBridge + if (!isK8s || effectiveBridge !== Constants.DEFAULT_ROUTER_NAME) { + const endpointFields = { + defaultBridge: effectiveBridge, + bridgePort: serviceData.bridgePort } + await _assignBridgeEndpoint(endpointFields, transaction) + serviceData.serviceEndpoint = endpointFields.serviceEndpoint + serviceData.servicePort = endpointFields.servicePort } // 8. Update service in database diff --git a/test/src/services/service-platform-service.test.js b/test/src/services/service-platform-service.test.js index fd4c3561..b5465c8c 100644 --- a/test/src/services/service-platform-service.test.js +++ b/test/src/services/service-platform-service.test.js @@ -160,6 +160,53 @@ describe('Service platform service', () => { expect(K8sClient.patchConfigMap.callCount).to.equal(2) }) + it('writes a named bridge listener on that router and skips the Kubernetes Service', async () => { + const FogManager = require('../../../src/data/managers/iofog-manager') + const MicroserviceManager = require('../../../src/data/managers/microservice-manager') + const ApplicationManager = require('../../../src/data/managers/application-manager') + const ChangeTrackingService = require('../../../src/services/change-tracking-service') + + ServiceManager.findOneWithTags.resolves({ + ...service, + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'interior-uuid', + k8sType: null, + tags: [] + }) + ServicesService._determineConnectorSiteId.resolves('edge-uuid') + $sandbox.stub(FogManager, 'findOne').callsFake((query) => Promise.resolve({ + uuid: query.uuid, + name: query.uuid === 'interior-uuid' ? 'interior1' : 'edge1' + })) + $sandbox.stub(ApplicationManager, 'findOne').resolves({ id: 10, name: 'system-interior1', isSystem: true }) + $sandbox.stub(MicroserviceManager, 'findOne').callsFake((query) => { + if (query.name === 'router') { + return Promise.resolve({ uuid: 'router-ms', config: '{}' }) + } + return Promise.resolve(null) + }) + $sandbox.stub(MicroserviceManager, 'update').resolves() + $sandbox.stub(ChangeTrackingService, 'update').resolves() + + const namedTask = { + ...task, + specSnapshot: JSON.stringify({ + ...JSON.parse(task.specSnapshot), + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'interior-uuid', + k8sType: null + }) + } + + await ServicePlatformService.reconcileService(serviceName, namedTask) + + expect(K8sClient.patchConfigMap).to.not.have.been.called + expect(ServicesService._syncK8sServiceResource).to.not.have.been.called + expect(MicroserviceManager.update).to.have.been.called + }) + it('throws when LoadBalancer IP watch times out', async () => { ServicesService._syncK8sServiceResource.resolves(null) @@ -245,6 +292,42 @@ describe('Service platform service', () => { expect(ServiceManager.update).to.not.have.been.called expect(result.isDelete).to.equal(true) }) + + it('skips Kubernetes Service deletion when the bridge is not the hub', async () => { + const FogManager = require('../../../src/data/managers/iofog-manager') + const MicroserviceManager = require('../../../src/data/managers/microservice-manager') + const ApplicationManager = require('../../../src/data/managers/application-manager') + const ChangeTrackingService = require('../../../src/services/change-tracking-service') + + ServicesService._determineConnectorSiteId.resolves('edge-uuid') + $sandbox.stub(FogManager, 'findOne').callsFake((query) => Promise.resolve({ + uuid: query.uuid, + name: 'interior1' + })) + $sandbox.stub(ApplicationManager, 'findOne').resolves({ id: 10, name: 'system-interior1', isSystem: true }) + $sandbox.stub(MicroserviceManager, 'findOne').callsFake((query) => { + if (query.name === 'router') { + return Promise.resolve({ uuid: 'router-ms', config: '{}' }) + } + return Promise.resolve(null) + }) + $sandbox.stub(MicroserviceManager, 'update').resolves() + $sandbox.stub(ChangeTrackingService, 'update').resolves() + + const namedDelete = { + ...deleteTask, + specSnapshot: JSON.stringify({ + ...snapshot, + type: 'microservice', + defaultBridge: 'interior-uuid' + }) + } + + await ServicePlatformService.reconcileService(serviceName, namedDelete) + + expect(ServicesService._deleteK8sService).to.not.have.been.called + expect(K8sClient.patchConfigMap).to.not.have.been.called + }) }) describe('.acquireHubLockWithTimeout()', () => { diff --git a/test/src/services/services-service.test.js b/test/src/services/services-service.test.js index f7823228..3eb36498 100644 --- a/test/src/services/services-service.test.js +++ b/test/src/services/services-service.test.js @@ -5,8 +5,11 @@ const ServiceController = require('../../../src/controllers/service-controller') const YamlParserService = require('../../../src/services/yaml-parser-service') const ServicesService = require('../../../src/services/services-service') const ServiceManager = require('../../../src/data/managers/service-manager') +const MicroserviceManager = require('../../../src/data/managers/microservice-manager') +const FogManager = require('../../../src/data/managers/iofog-manager') const ReconcileOutboxManager = require('../../../src/data/managers/reconcile-outbox-manager') const RouterManager = require('../../../src/data/managers/router-manager') +const RouterConnectionManager = require('../../../src/data/managers/router-connection-manager') const TagsManager = require('../../../src/data/managers/tags-manager') const Validator = require('../../../src/schemas') const Errors = require('../../../src/helpers/errors') @@ -490,4 +493,281 @@ spec: expect(K8sClient.createService).to.have.been.calledOnce }) }) + + describe('defaultBridge agent name', () => { + const edgeRouter = { id: 11, isEdge: true, iofogUuid: 'edge-uuid', host: 'edge.example.com' } + const interiorRouter = { id: 22, isEdge: false, iofogUuid: 'interior-uuid', host: 'interior.example.com' } + + function stubBridgeRouters () { + delete process.env.CONTROL_PLANE + $sandbox.stub(Validator, 'validate').resolves(true) + $sandbox.stub(ServiceManager, 'findAll').resolves([]) + $sandbox.stub(ServiceManager, 'create').callsFake((data) => Promise.resolve(buildServiceModel(data))) + $sandbox.stub(ReconcileOutboxManager, 'enqueueServicePlatform').resolves() + $sandbox.stub(TagsManager, 'findOne').resolves(null) + $sandbox.stub(TagsManager, 'create').callsFake(({ value }) => Promise.resolve({ value })) + $sandbox.stub(MicroserviceManager, 'findOne').resolves({ + uuid: 'ms-uuid', + iofogUuid: 'edge-uuid' + }) + $sandbox.stub(FogManager, 'findOne').callsFake((query) => { + if (query.name === 'interior1') { + return Promise.resolve({ uuid: 'interior-uuid', name: 'interior1' }) + } + return Promise.resolve(null) + }) + $sandbox.stub(RouterManager, 'findOne').callsFake((query) => { + if (query.iofogUuid === 'edge-uuid') { + return Promise.resolve(edgeRouter) + } + if (query.iofogUuid === 'interior-uuid') { + return Promise.resolve(interiorRouter) + } + return Promise.resolve(null) + }) + $sandbox.stub(RouterConnectionManager, 'findAllWithRouters').resolves([ + { source: edgeRouter, dest: interiorRouter } + ]) + } + + beforeEach(() => { + stubBridgeRouters() + }) + + it('stores the agent uuid when defaultBridge is the upstream agent name', async () => { + await ServicesService.createServiceEndpoint({ + name: 'checkout', + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'interior1', + targetPort: 8080 + }, $transaction) + + const createPayload = ServiceManager.create.firstCall.args[0] + expect(createPayload.defaultBridge).to.equal('interior-uuid') + expect(createPayload.serviceEndpoint).to.equal('interior.example.com') + expect(FogManager.findOne).to.have.been.calledWith({ name: 'interior1' }, $transaction) + }) + + it('stores an agent uuid without a name lookup', async () => { + await ServicesService.createServiceEndpoint({ + name: 'checkout', + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'interior-uuid', + targetPort: 8080 + }, $transaction) + + expect(ServiceManager.create.firstCall.args[0].defaultBridge).to.equal('interior-uuid') + expect(FogManager.findOne).to.not.have.been.called + }) + + it('rejects an unknown agent name', async () => { + try { + await ServicesService.createServiceEndpoint({ + name: 'checkout', + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'missing-node', + targetPort: 8080 + }, $transaction) + expect.fail('expected validation error') + } catch (error) { + expect(error).to.be.instanceOf(Errors.ValidationError) + expect(error.message).to.include('missing-node') + } + expect(ServiceManager.create).to.not.have.been.called + }) + + it('accepts default-router when the edge reaches the hub through an interior', async () => { + const defaultRouter = { id: 1, isDefault: true, isEdge: false, host: 'hub.example.com', iofogUuid: null } + const edge = { id: 11, isEdge: true, iofogUuid: 'edge-uuid', host: 'edge.example.com' } + const interior = { id: 22, isEdge: false, iofogUuid: 'interior-uuid', host: 'interior.example.com' } + RouterManager.findOne.callsFake((query) => { + if (query.isDefault) { + return Promise.resolve(defaultRouter) + } + if (query.iofogUuid === 'edge-uuid') { + return Promise.resolve(edge) + } + return Promise.resolve(null) + }) + RouterConnectionManager.findAllWithRouters.resolves([ + { source: edge, dest: interior }, + { source: interior, dest: defaultRouter } + ]) + + await ServicesService.createServiceEndpoint({ + name: 'checkout', + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'default-router', + targetPort: 8080 + }, $transaction) + + const createPayload = ServiceManager.create.firstCall.args[0] + expect(createPayload.defaultBridge).to.equal('default-router') + expect(createPayload.serviceEndpoint).to.equal('hub.example.com') + }) + + it('accepts default-router when another interior joins the edge upstream to the hub', async () => { + const defaultRouter = { id: 1, isDefault: true, isEdge: false, host: 'hub.example.com' } + const edge = { id: 11, isEdge: true, iofogUuid: 'edge-uuid' } + const interior = { id: 22, isEdge: false, iofogUuid: 'interior-uuid' } + const interior2 = { id: 33, isEdge: false, iofogUuid: 'interior-2-uuid' } + RouterManager.findOne.callsFake((query) => { + if (query.isDefault) { + return Promise.resolve(defaultRouter) + } + if (query.iofogUuid === 'edge-uuid') { + return Promise.resolve(edge) + } + return Promise.resolve(null) + }) + RouterConnectionManager.findAllWithRouters.resolves([ + { source: edge, dest: interior }, + { source: interior2, dest: interior }, + { source: interior2, dest: defaultRouter } + ]) + + await ServicesService.createServiceEndpoint({ + name: 'checkout', + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'default-router', + targetPort: 8080 + }, $transaction) + + expect(ServiceManager.create.firstCall.args[0].defaultBridge).to.equal('default-router') + }) + + it('rejects default-router when the upstream interior has no path to the hub', async () => { + const defaultRouter = { id: 1, isDefault: true, isEdge: false, host: 'hub.example.com' } + const edge = { id: 11, isEdge: true, iofogUuid: 'edge-uuid' } + const interior = { id: 22, isEdge: false, iofogUuid: 'interior-uuid' } + RouterManager.findOne.callsFake((query) => { + if (query.isDefault) { + return Promise.resolve(defaultRouter) + } + if (query.iofogUuid === 'edge-uuid') { + return Promise.resolve(edge) + } + return Promise.resolve(null) + }) + RouterConnectionManager.findAllWithRouters.resolves([ + { source: edge, dest: interior } + ]) + + try { + await ServicesService.createServiceEndpoint({ + name: 'checkout', + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'default-router', + targetPort: 8080 + }, $transaction) + expect.fail('expected validation error') + } catch (error) { + expect(error).to.be.instanceOf(Errors.ValidationError) + expect(error.message).to.include('edge-uuid') + } + expect(ServiceManager.create).to.not.have.been.called + }) + + it('accepts an interior reached through another interior', async () => { + const interior2 = { id: 33, isEdge: false, iofogUuid: 'interior-2-uuid', host: 'interior2.example.com' } + FogManager.findOne.callsFake((query) => { + if (query.name === 'interior2') { + return Promise.resolve({ uuid: 'interior-2-uuid', name: 'interior2' }) + } + return Promise.resolve(null) + }) + RouterManager.findOne.callsFake((query) => { + if (query.iofogUuid === 'edge-uuid') { + return Promise.resolve(edgeRouter) + } + if (query.iofogUuid === 'interior-2-uuid') { + return Promise.resolve(interior2) + } + return Promise.resolve(null) + }) + RouterConnectionManager.findAllWithRouters.resolves([ + { source: edgeRouter, dest: interiorRouter }, + { source: interiorRouter, dest: interior2 } + ]) + + await ServicesService.createServiceEndpoint({ + name: 'checkout', + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'interior2', + targetPort: 8080 + }, $transaction) + + const createPayload = ServiceManager.create.firstCall.args[0] + expect(createPayload.defaultBridge).to.equal('interior-2-uuid') + expect(createPayload.serviceEndpoint).to.equal('interior2.example.com') + }) + + it('rejects an interior that shares no mesh with the edge', async () => { + const interior2 = { id: 33, isEdge: false, iofogUuid: 'interior-2-uuid', host: 'interior2.example.com' } + FogManager.findOne.callsFake((query) => { + if (query.name === 'interior2') { + return Promise.resolve({ uuid: 'interior-2-uuid', name: 'interior2' }) + } + return Promise.resolve(null) + }) + RouterManager.findOne.callsFake((query) => { + if (query.iofogUuid === 'edge-uuid') { + return Promise.resolve(edgeRouter) + } + if (query.iofogUuid === 'interior-2-uuid') { + return Promise.resolve(interior2) + } + return Promise.resolve(null) + }) + RouterConnectionManager.findAllWithRouters.resolves([ + { source: edgeRouter, dest: interiorRouter } + ]) + + try { + await ServicesService.createServiceEndpoint({ + name: 'checkout', + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'interior2', + targetPort: 8080 + }, $transaction) + expect.fail('expected validation error') + } catch (error) { + expect(error).to.be.instanceOf(Errors.ValidationError) + expect(error.message).to.include('interior2') + expect(error.message).to.include('edge-uuid') + } + expect(ServiceManager.create).to.not.have.been.called + }) + + it('accepts the same upstream sent by name on update', async () => { + const existingService = buildServiceModel({ + type: 'microservice', + resource: 'ms-uuid', + defaultBridge: 'interior-uuid', + tags: [] + }) + $sandbox.stub(ServiceManager, 'findOneWithTags').resolves(existingService) + $sandbox.stub(ServiceManager, 'update').callsFake((where, data) => + Promise.resolve(buildServiceModel({ ...existingService, ...data })) + ) + + await ServicesService.updateServiceEndpoint('checkout', { + name: 'checkout', + defaultBridge: 'interior1', + targetPort: 8080 + }, $transaction) + + expect(ServiceManager.update.firstCall.args[1].defaultBridge).to.equal('interior-uuid') + expect(ServiceManager.update.firstCall.args[1].type).to.equal(undefined) + expect(ServiceManager.update.firstCall.args[1].resource).to.equal(undefined) + }) + }) }) From 2610155e461a4b7feb182398c7feb11766e93267 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Durmu=C5=9F?= Date: Sun, 8 Nov 2026 21:05:23 +0300 Subject: [PATCH 3/9] Expose each NATS broker's JetStream domain on the topology nodes so a hub or server reports the Controller namespace and a leaf reports the agent name. --- src/services/network-topology-service.js | 16 ++++- .../services/network-topology-service.test.js | 67 +++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/src/services/network-topology-service.js b/src/services/network-topology-service.js index 7a4d8968..2d4031f5 100644 --- a/src/services/network-topology-service.js +++ b/src/services/network-topology-service.js @@ -154,6 +154,19 @@ function _natsDisplayName (nats, defaultHub, fog) { return fog ? fog.name : nats.iofogUuid } +function _controllerNamespace () { + const namespace = process.env.CONTROLLER_NAMESPACE || config.get('app.namespace') + return namespace || null +} + +function _natsJsDomain (nats, defaultHub, fog) { + const isHub = !!(defaultHub && nats.id === defaultHub.id) + if (isHub || !nats.isLeaf) { + return _controllerNamespace() + } + return (fog && fog.name) || null +} + async function _loadFogMap (iofogUuids, transaction) { const uuids = [...new Set((iofogUuids || []).filter(Boolean))] if (!uuids.length) { @@ -199,7 +212,8 @@ function _formatNatsListNode (nats, defaultHub, fogMap) { deploymentTarget: _natsDeploymentTarget(nats, defaultHub), displayName: _natsDisplayName(nats, defaultHub, fog), role: _natsRole(nats, defaultHub), - mode: _natsMode(nats) + mode: _natsMode(nats), + jsDomain: _natsJsDomain(nats, defaultHub, fog) } } diff --git a/test/src/services/network-topology-service.test.js b/test/src/services/network-topology-service.test.js index e23d3b18..a2d27ce6 100644 --- a/test/src/services/network-topology-service.test.js +++ b/test/src/services/network-topology-service.test.js @@ -290,4 +290,71 @@ describe('Network Topology Service', () => { expect(result.nodes[0].deploymentTarget).to.equal('remote') }) }) + + describe('NATS jsDomain', () => { + const originalNamespace = process.env.CONTROLLER_NAMESPACE + + afterEach(() => { + if (originalNamespace === undefined) { + delete process.env.CONTROLLER_NAMESPACE + } else { + process.env.CONTROLLER_NAMESPACE = originalNamespace + } + }) + + function stubNatsList (defaultHub, rows, fogs) { + $sandbox.stub(NatsInstanceManager, 'findOne').resolves(defaultHub) + stubFogFindAll(fogs) + $sandbox.stub(NatsInstanceManager, 'getEntity').returns({ + findAndCountAll: $sandbox.stub().resolves({ + count: rows.length, + rows + }) + }) + } + + it('uses the controller namespace on a hub and a server, and the agent name on a leaf', async () => { + process.env.CONTROLLER_NAMESPACE = 'datasance' + const hub = makeNats({ id: 50, isLeaf: false, isHub: true, iofogUuid: null, host: '185.11.248.72' }) + const server = makeNats({ id: 3, isLeaf: false, isHub: false, iofogUuid: 'server-uuid', host: '10.204.0.2' }) + const leaf = makeNats({ id: 4, isLeaf: true, isHub: false, iofogUuid: 'leaf-uuid', host: '10.132.0.4' }) + const orphanLeaf = makeNats({ id: 5, isLeaf: true, isHub: false, iofogUuid: 'missing-uuid', host: '10.0.0.9' }) + stubNatsList(hub, [hub, server, leaf, orphanLeaf], [ + { uuid: 'server-uuid', name: 'edge-2', host: '10.204.0.2' }, + { uuid: 'leaf-uuid', name: 'edge-1', host: '10.132.0.4' } + ]) + + const result = await NetworkTopologyService.listNatsNodes({ query: {} }, transaction) + const domainById = Object.fromEntries(result.nodes.map((node) => [node.id, node.jsDomain])) + + expect(domainById[constants.DEFAULT_NATS_HUB_NAME]).to.equal('datasance') + expect(domainById['server-uuid']).to.equal('datasance') + expect(domainById['leaf-uuid']).to.equal('edge-1') + expect(domainById['missing-uuid']).to.equal(null) + }) + + it('uses app.namespace when CONTROLLER_NAMESPACE is unset', async () => { + delete process.env.CONTROLLER_NAMESPACE + const config = require('../../../src/config') + const hub = makeNats({ id: 50, isLeaf: false, isHub: true, iofogUuid: null, host: 'nats.local' }) + stubNatsList(hub, [hub], []) + + const result = await NetworkTopologyService.listNatsNodes({ query: {} }, transaction) + expect(result.nodes[0].jsDomain).to.equal(config.get('app.namespace') || null) + }) + + it('includes jsDomain on node detail', async () => { + process.env.CONTROLLER_NAMESPACE = 'datasance' + const hub = makeNats({ id: 50, isLeaf: false, isHub: true, iofogUuid: null, host: 'nats.local' }) + $sandbox.stub(NatsInstanceManager, 'findOne').resolves(hub) + stubFogFindAll([]) + + const result = await NetworkTopologyService.getNatsNode({ + params: { id: constants.DEFAULT_NATS_HUB_NAME } + }, transaction) + + expect(result.jsDomain).to.equal('datasance') + expect(result.isHub).to.equal(true) + }) + }) }) From ee40bffd3b5f5f25fc3c802e708dd3ac9ce59b06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Durmu=C5=9F?= Date: Sun, 8 Nov 2026 21:05:51 +0300 Subject: [PATCH 4/9] Describe how an operator key rotation updates the hub server config and reloads it without rolling the StatefulSet. --- docs/networking-topology-controlplane.md | 2 ++ docs/pki.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/networking-topology-controlplane.md b/docs/networking-topology-controlplane.md index 77bf42eb..37a94b7c 100644 --- a/docs/networking-topology-controlplane.md +++ b/docs/networking-topology-controlplane.md @@ -350,6 +350,8 @@ The operator owns the hub processes and the listener, TLS, and replica-route sec **`iofog-nats-config` / `server.conf`.** When an agent NATS server is ensured or removed, Controller rewrites the `routes` array. Every route that contains `nats-headless` is kept. Routes for agent servers (`nats://{agentHost}:{clusterPort}`) are appended. The operator’s next rewrite replaces its own `nats-.nats-headless` ordinals and keeps those non-ordinal routes. Removing an agent server also rolls the `nats` StatefulSet so the pods drop the deleted route. Adding a server patches the ConfigMap and does not roll the StatefulSet by itself. +The same reconcile replaces the `operator` line when it differs from the current operator JWT. That write does not roll the StatefulSet. The NATS image reloads `server.conf`. The installer’s rewrite of this file must take `operator` from `GET /api/v3/nats/operator`, not from the JWT stored at bootstrap, and must not restart the StatefulSet for that line. When the operator public key changes, refresh secret `nats-operator-seed` from `GET /api/v3/nats/bootstrap`. + **`iofog-nats-jwt-bundle`.** When application accounts change, Controller patches this ConfigMap with the full resolver bundle: the system account, every application with `natsAccess`, and the controller relay account when NATS relay is enabled. The patch runs only when the bundle contents change. Because the operator does not replace an existing ConfigMap, those extra account JWTs survive the operator’s next reconcile. User credential files are not in this bundle. How those accounts are signed is in [nats-access.md](nats-access.md). No agent on this control plane is `isSystem`, and none of them is the hub. A leaf still dials the hub host stored by `PUT /api/v3/nats/hub`. An edge router still dials the host stored by `PUT /api/v3/router`. diff --git a/docs/pki.md b/docs/pki.md index a6f0df5a..40b766d4 100644 --- a/docs/pki.md +++ b/docs/pki.md @@ -106,7 +106,7 @@ POST /api/v3/nats/operator/rotate Authorization: Bearer ``` -Controller accepts the request, rotates operator material, re-signs accounts, and schedules resolver reconciliation in the background. Plan maintenance when NATS leaf nodes may reload operator trust. +Controller accepts the request, rotates operator material, re-signs accounts, and schedules resolver reconciliation in the background. On Kubernetes that reconcile writes the new operator JWT into `iofog-nats-config`. The NATS image reloads the file. The StatefulSet is not restarted for this change. Agent NATS configs are rendered with the same JWT and reload the same way. This is **NATS credential rotation**, not the skipped per-agent CA migration. From 8f01b3a984e5dbffdf4c8f0b3b1bb971979cd50c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Durmu=C5=9F?= Date: Sun, 8 Nov 2026 21:05:55 +0300 Subject: [PATCH 5/9] Describe the single NATS cluster, leaf solicit lists, and downstream accounts so the operator guide matches the brokers that are rendered. --- docs/networking-topology-messaging-fabric.md | 47 ++++++++++++++------ 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/docs/networking-topology-messaging-fabric.md b/docs/networking-topology-messaging-fabric.md index 20e3c8aa..4400e073 100644 --- a/docs/networking-topology-messaging-fabric.md +++ b/docs/networking-topology-messaging-fabric.md @@ -21,15 +21,21 @@ natsMode: leaf | Role | What it is | What the process listens on | |---|---|---| -| `leaf` | Local NATS that dials upstream servers over TLS | Client `4222`, MQTT `8883`, monitor `8222` | -| `server` | Full server. Forms the cluster and accepts leaf connections. | Those, plus cluster `6222` and leafnode `7422` | +| `leaf` | Local NATS. One upstream connection per application account. | Client `4222`, MQTT `8883`, monitor `8222`, and leafnode `7422` | +| `server` | Full server. One cluster with every other server, and it accepts leaf connections. | Those, plus cluster `6222` | | `none` | No NATS process on this agent | None | -Both `leaf` and `server` publish the full port set on the microservice (`4222`, `6222`, `7422`, `8883`, `8222`). A leaf does not open the cluster or leafnode listeners. It dials each upstream on `7422`. +Both `leaf` and `server` publish the full port set on the microservice (`4222`, `6222`, `7422`, `8883`, `8222`). A leaf does not open the cluster listener. It listens on the leafnode port and dials each named upstream on `7422`. `host` is required unless both the router role and the NATS role are `none`. -Omit `upstreamNatsServers` and Controller attaches this node to the hub (`default-nats-hub`) plus every NATS server that runs on a system agent. A leaf cannot be an upstream. Name an upstream by agent uuid, agent name, or `default-nats-hub`. +`upstreamNatsServers` names an agent uuid, an agent name, or `default-nats-hub`. + +On a server that list is not used and is not stored. Every server is connected to every other server, in both directions, and a server is not connected to itself. Cluster routes are those other servers. Naming a leaf in the list is not an error. A later read shows the other servers, not the list that was submitted. + +On a leaf the list is the solicit list for one connection per application account. Omit it on create and the leaf attaches to `default-nats-hub` only. After that dial succeeds, leafnode advertise tells the leaf about the other servers. If the hub is down on the first dial, the leaf does not try those other servers unless you named them. Send `[]` and the leaf stores no upstream. Workloads on that node use the local broker only. A later update that omits the field keeps the stored list, including an empty one. Sending the key replaces the list. + +A leaf list is all servers or all leaves. Controller rejects a mix of a server and a leaf, a name that is this same node, a cycle, a named leaf that is already upstream of another named leaf, and two leaf parents whose next hops differ. Two leaf parents are accepted when neither is upstream of the other and both have the same upstream destinations, including when both have none. A leaf may name a parent leaf that itself has no upstream. That tree does not gain a connection to the hub. A system agent must be `natsMode: server`. On a control plane that is not Kubernetes, the first agent in an empty cluster is the system agent. Controller sets `routerMode: interior` and `natsMode: server` on that create, including when the request asked for another role. That node becomes the hub when no hub exists yet. @@ -80,8 +86,8 @@ What is protected: |---|---| | Client port `4222` | Operator mode. Clients authenticate with a user JWT. The generated config does not put a TLS stanza on this port. Workload creds are issued automatically. See [nats-access.md](nats-access.md). | | Cluster (servers) | TLS, `verify: true`, `handshake_first: true` | -| Leafnode listener (servers) | TLS, `verify: true`, `handshake_first: true` | -| Leaf remotes (leaves) | TLS, `verify: true`, `handshake_first: true`. Each URL is `tls://{upstreamHost}:{leafPort}`. | +| Leafnode listener | TLS, `verify: true`, `handshake_first: true`. Servers and leaves both listen. Advertise is the agent host. | +| Leaf remotes | TLS, `verify: true`, `handshake_first: true`. Each address is `tls://{upstreamHost}:{leafPort}`, and every address for one account sits on one remote. | | MQTT `8883` | TLS, `handshake_first: true` | | JetStream disk | ChaChaPoly with a per-node key Controller generates | @@ -106,7 +112,7 @@ jetstream: { cluster: { port: 6222 - routes: ["nats://:6222"] + routes: ["nats://:6222"] tls: { verify: true, handshake_first: true, ca/cert/key from nats-server- } } @@ -132,17 +138,30 @@ The resolver directory is the account-JWT bundle: the system account, every appl A server also gets a system user (`admin-hub` on the hub, `admin-server-{agent}` on other servers) and mounts that creds file at `/etc/nats/creds`. -When another server is added or removed, Controller recomputes cluster routes for every server and reconciles the others. Growing the cluster from one member to many rebuilds the local NATS container so it switches to the clustered config. On Kubernetes, routes that contain `nats-headless` are left in place and the agent servers are appended. +`upstreamNatsServers` on a server does not choose peers. Controller stores one connection each way between every pair of servers and none from a server to itself. Cluster `routes` are the other servers' `nats://host:6222` values, taken from that mesh. A peer with no host is skipped. A server with no peers renders the no-cluster template, which has no `cluster` block and no route to itself. + +When a server is added or removed, Controller repairs that mesh and reconciles the other servers. Growing the cluster from one member to many rebuilds the local NATS container so it switches to the clustered config. On Kubernetes, routes that contain `nats-headless` are left in place and the agent servers are appended. --- ## Leaf config and connections -`natsMode: leaf` renders `leaf.conf`. It still runs JetStream, MQTT, the operator, and a resolver. It does not open cluster routes. It dials upstreams: +`natsMode: leaf` renders `leaf.conf`. It still runs JetStream, MQTT, the operator, and a resolver. It does not open cluster routes. It listens for child leaves on the leafnode port, with TLS and advertise set to the agent host: + +``` +leafnodes: { + port: 7422 + advertise: + tls: { verify: true, handshake_first: true, certificate nats-server- } + remotes: [ ... ] +} +``` + +Each application account is one remote. `urls` is the solicit list: one `tls://{host}:{leafPort}` address per accepted upstream, in the order given, with a repeated name kept once. The leaf dials one address. If that host is down before the first successful dial, it tries the next. It does not hold a connection per address. ```json { - "urls": ["tls://203.0.113.1:7422"], + "urls": ["tls://203.0.113.1:7422", "tls://203.0.113.2:7422"], "account": "", "credentials": "/etc/nats/creds/orders/leaf-plant-a.creds", "tls": { @@ -156,13 +175,13 @@ When another server is added or removed, Controller recomputes cluster routes fo } ``` -Controller creates that remote for each application that has `natsAccess` and a microservice on this agent, and for each upstream server. The leaf user is `leaf-{agentName}` inside that application account, with the `default-leaf-user` rule (`LEAFNODE` and `WEBSOCKET`). The creds files are collected into ConfigMap `nats-leaf-creds-{agent}` and mounted at `/etc/nats/creds`. +Controller creates that remote for each non-system application that has `natsAccess` and a microservice on this agent, and for the same kind of application on every leaf below this one. The leaf user is `leaf-{agentName}` inside that application account, with the `default-leaf-user` rule (`LEAFNODE` and `WEBSOCKET`), including when the application has no workload on this agent. A child's `SYS-leaf-*` account stays on the child. The creds files are collected into ConfigMap `nats-leaf-creds-{agent}` and mounted at `/etc/nats/creds`. -The leaf resolver bundle is smaller than the hub bundle. It holds this fog's leaf system account (`SYS-leaf-{agentName}`) and the application accounts that have workloads here. It is ConfigMap `nats-jwt-bundle-{agent}`. +The leaf resolver bundle holds this fog's leaf system account (`SYS-leaf-{agentName}`) and those application accounts. It is ConfigMap `nats-jwt-bundle-{agent}`. A parent whose own upstream list is empty still stores the downstream account tokens and does not gain a hub remote. -A leaf also has its own system user `admin-leaf-{agent}` on that leaf system account, used for the leaf's system traffic. +The JetStream domain stays the agent name on a leaf and the Controller namespace on a server. A stream on the hub is not automatically present on a factory leaf. `GET /api/v3/network-topology/nats/nodes` returns that domain as `jsDomain` on every NATS node. The NATS overview, subgraph, and node detail use the same field. A hub or server reports the Controller namespace. A leaf reports the agent name, or `null` when the agent row is missing. -If you leave `upstreamNatsServers` empty, the upstream set is the hub plus each system agent's NATS server. A system agent created before a hub exists starts with no upstreams. Later leaves attach to the hub. +Omit `upstreamNatsServers` on create and the leaf solicits `default-nats-hub` only. Other servers are learned from advertise after that dial. A hub that is down on the first dial is not replaced by servers you did not name. `[]` is a local broker. A later update that omits the field keeps the stored list. A system agent created before a hub exists starts with no upstreams. Later leaves attach to the hub. Switching a leaf to a server removes the leaf JWT ConfigMap, the leaf creds ConfigMap, and the leaf system account. Switching a server to a leaf builds those artifacts and stops using cluster routes. From 9f5ada46684ea3ef9fd713f39e8cfe78d700c6bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Durmu=C5=9F?= Date: Sun, 8 Nov 2026 21:06:04 +0300 Subject: [PATCH 6/9] Describe leaf upstream lists, service bridges, JetStream domains, and operator rotation on the API. --- docs/swagger.yaml | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 3476f2ce..7595dbc6 100755 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1,6 +1,6 @@ openapi : "3.0.0" info: - version: 3.9.4 + version: 3.9.5 title: Cloud Native Controller for Edge Native Workloads paths: /live: @@ -8087,7 +8087,9 @@ paths: tags: - NATS summary: Rotates NATS operator keys and JWT - description: Schedules account/user re-sign and resolver reconciliation in background after operator rotation is accepted. + description: > + Replaces the fleet NATS operator key and re-signs every account JWT. User credential files stay valid because account keys do not change. Servers reload the new operator JWT and then accept only account JWTs signed by the new key. Until that reload finishes, clients can fail to connect. + The response is the operator that existed when the request was accepted. Read GET /nats/operator after reconciliation for the new public key and JWT. On Kubernetes, reconciliation writes the new operator JWT into the hub server config and the NATS image reloads that file. The StatefulSet is not rolled. A control-plane reconcile must not write the previous operator JWT back into that file. operationId: rotateNatsOperator security: - authToken: [] @@ -9465,6 +9467,12 @@ components: description: JetStream max memory store (e.g. 1g). Units m, mb, g, gb, t, tb. upstreamNatsServers: type: array + description: >- + Agent uuid, agent name, or default-nats-hub. On a server the list + is not used, is not stored, and a later read returns the other + servers in the cluster. On a leaf, omit on create to attach to default-nats-hub + only. An empty array attaches to nothing. Omit on a later update + to keep the stored list. A leaf list is all servers or all leaves. items: type: string runtimeClasses: @@ -9652,6 +9660,12 @@ components: description: JetStream max memory store (e.g. 1g). Units m, mb, g, gb, t, tb. upstreamNatsServers: type: array + description: >- + Agent uuid, agent name, or default-nats-hub. On a server the list + is not used, is not stored, and a later read returns the other + servers in the cluster. On a leaf, omit on create to attach to default-nats-hub + only. An empty array attaches to nothing. Omit on a later update + to keep the stored list. A leaf list is all servers or all leaves. items: type: string host: @@ -12315,6 +12329,16 @@ components: type: string defaultBridge: type: string + description: >- + Router that owns the service listener. `default-router` when omitted. + `k8s` and `external` accept only `default-router`. `microservice` and + `agent` also accept the agent name or agent uuid of an interior the + agent's router can reach (uuid is matched first, then name). A name is + stored as that agent's uuid. `default-router` is stored as that literal. + Reachability walks the interior mesh in both directions, including a + bridge behind another interior. On Kubernetes, `k8sType` and + `servicePort` are required only when this is `default-router`. A named + bridge does not create a Kubernetes Service. Immutable. bridgePort: type: number targetPort: @@ -13244,6 +13268,16 @@ components: NatsTopologyNode: allOf: - $ref: "#/components/schemas/NetworkTopologyNodeBase" + - type: object + properties: + jsDomain: + type: string + nullable: true + description: >- + JetStream domain for this broker. The Controller namespace on a + hub or server, the agent name on a leaf, or null when a leaf + has no agent row. + required: [jsDomain] RouterTopologyNodeDetail: allOf: - $ref: "#/components/schemas/RouterTopologyNode" From 9748aed1e900edaec3d2c08be5319d5fc1c81ac2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Durmu=C5=9F?= Date: Sun, 8 Nov 2026 21:06:07 +0300 Subject: [PATCH 7/9] Bump Secret Manager and Azure Identity so the production tree drops the vulnerable glob and minimatch releases and the pinned MSAL override. --- package-lock.json | 242 +++++++++++++++------------------------------- package.json | 7 +- 2 files changed, 81 insertions(+), 168 deletions(-) diff --git a/package-lock.json b/package-lock.json index c7b960e0..972dc344 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,19 +1,19 @@ { "name": "controller", - "version": "3.9.4", + "version": "3.9.5-dev", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "controller", - "version": "3.9.4", + "version": "3.9.5-dev", "hasInstallScript": true, "license": "EPL-2.0", "dependencies": { "@aws-sdk/client-secrets-manager": "^3.1156.0", - "@azure/identity": "^4.14.0", + "@azure/identity": "^4.14.1", "@azure/keyvault-secrets": "^4.11.2", - "@google-cloud/secret-manager": "^6.1.1", + "@google-cloud/secret-manager": "^7.2.0", "@kubernetes/client-node": "^1.4.0", "@msgpack/msgpack": "^3.1.2", "@nats-io/jwt": "^0.0.10-5", @@ -506,9 +506,9 @@ } }, "node_modules/@azure/identity": { - "version": "4.14.0", - "resolved": "https://registry.npmjs.org/@azure/identity/-/identity-4.14.0.tgz", - "integrity": "sha512-8utCLdTZn14CiAe0HW4JbtzUMsc0mdDwnjUvStFMrR4IxQP8S2eL9zVAdplpfORVJGYmidZElpeXRYjJQ4UyUw==", + "version": "4.14.1", + "resolved": "https://registry.npmjs.org/@azure/identity/-/identity-4.14.1.tgz", + "integrity": "sha512-HHuuFrmN1uuF9D5A6aAo5eHzNFNX4Q+P4SksZqDKse5YaJFFy/zDLG3wXHEV2FVGgetZ3QM8jGURNBtnQYf1NQ==", "license": "MIT", "dependencies": { "@azure/abort-controller": "^2.0.0", @@ -520,7 +520,7 @@ "@azure/core-util": "^1.11.0", "@azure/logger": "^1.0.0", "@azure/msal-browser": "^5.5.0", - "@azure/msal-node": "^6.0.0", + "@azure/msal-node": "^7.1.0", "open": "^11.0.0", "tslib": "^2.2.0" }, @@ -1075,15 +1075,15 @@ } }, "node_modules/@google-cloud/secret-manager": { - "version": "6.1.3", - "resolved": "https://registry.npmjs.org/@google-cloud/secret-manager/-/secret-manager-6.1.3.tgz", - "integrity": "sha512-3e/5GLusy1sWBEUvIlJbJpaaUlaf4MeeGQDUBdIVCqWYnn0lNPtbO6ZbJhTPiOkct2yxi8DXWgzWDbCJdDq9Bw==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@google-cloud/secret-manager/-/secret-manager-7.2.0.tgz", + "integrity": "sha512-SQ/e9mo7Pl5QpFIn3GOa8K/PhS+3HgQnlWpMZbaE1UiZBa42AFB+EqxWQZOljv0kNwemo/PWiesAh8TywU9uVw==", "license": "Apache-2.0", "dependencies": { - "google-gax": "^5.0.0" + "google-gax": "^6.5.0" }, "engines": { - "node": ">=18" + "node": ">=22" } }, "node_modules/@grpc/grpc-js": { @@ -1197,6 +1197,7 @@ "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, "license": "ISC", "dependencies": { "string-width": "^5.1.2", @@ -1214,6 +1215,7 @@ "version": "6.2.2", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -1226,6 +1228,7 @@ "version": "6.2.3", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -1238,12 +1241,14 @@ "version": "9.2.2", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, "license": "MIT" }, "node_modules/@isaacs/cliui/node_modules/string-width": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, "license": "MIT", "dependencies": { "eastasianwidth": "^0.2.0", @@ -1261,6 +1266,7 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^6.2.2" @@ -1276,6 +1282,7 @@ "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, "license": "MIT", "dependencies": { "ansi-styles": "^6.1.0", @@ -2603,6 +2610,7 @@ "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, "license": "MIT", "optional": true, "engines": { @@ -4353,6 +4361,7 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -4782,6 +4791,7 @@ "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true, "license": "MIT" }, "node_modules/ecdsa-sig-formatter": { @@ -6372,6 +6382,7 @@ "version": "3.3.1", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "dev": true, "license": "ISC", "dependencies": { "cross-spawn": "^7.0.6", @@ -6388,6 +6399,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, "license": "ISC", "engines": { "node": ">=14" @@ -6587,9 +6599,9 @@ } }, "node_modules/gaxios": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.5.tgz", - "integrity": "sha512-5FZy72Rh8LhtjmvDrKkI+lVhrsQrVKVsItxMoDm5mNQE+xR0WVIIs+jzPSJgBvKVsLi24fZhXJIsNI0bihDzFg==", + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-8.3.2.tgz", + "integrity": "sha512-7VsaTExxjbDv2ZK1YuC4jbgfN33NI/6/7zdYWUHB6mcg51v4tCBZe+xzjqPzOpVzI+C5k1Kk9OQ80WVrXAHOqw==", "license": "Apache-2.0", "dependencies": { "extend": "^3.0.2", @@ -6597,7 +6609,7 @@ "node-fetch": "^3.3.2" }, "engines": { - "node": ">=18" + "node": ">=22" } }, "node_modules/gaxios/node_modules/node-fetch": { @@ -6619,50 +6631,17 @@ } }, "node_modules/gcp-metadata": { - "version": "8.1.3", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.3.tgz", - "integrity": "sha512-ziTrzUhhpL9Zk5k0HHzgP/KIpWDJT0VMBC/ynt/QIBvTW+UUcSivQRl6VlwTf/EilDxtSWklHoRsKy1c4k+59w==", + "version": "9.2.3", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-9.2.3.tgz", + "integrity": "sha512-d2OI/dJJ3IIaeOz3c9jvr5j5G5beI5fQzbgilNiWhDKGwvJN9o10Qub70NkbF6PNJSUoNKZ77JKYGz0Fs4+9Lg==", "license": "Apache-2.0", "dependencies": { - "gaxios": "7.1.3", - "google-logging-utils": "1.1.3", + "gaxios": "^8.3.1", + "google-logging-utils": "^2.1.0", "json-bigint": "^1.0.0" }, "engines": { - "node": ">=18" - } - }, - "node_modules/gcp-metadata/node_modules/gaxios": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.3.tgz", - "integrity": "sha512-YGGyuEdVIjqxkxVH1pUTMY/XtmmsApXrCVv5EU25iX6inEPbV+VakJfLealkBtJN69AQmh1eGOdCl9Sm1UP6XQ==", - "license": "Apache-2.0", - "dependencies": { - "extend": "^3.0.2", - "https-proxy-agent": "^7.0.1", - "node-fetch": "^3.3.2", - "rimraf": "^5.0.1" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/gcp-metadata/node_modules/node-fetch": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", - "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", - "license": "MIT", - "dependencies": { - "data-uri-to-buffer": "^4.0.0", - "fetch-blob": "^3.1.4", - "formdata-polyfill": "^4.0.10" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/node-fetch" + "node": ">=22" } }, "node_modules/generate-function": { @@ -6814,6 +6793,7 @@ "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, "license": "ISC", "dependencies": { "foreground-child": "^3.1.0", @@ -6847,6 +6827,7 @@ "version": "9.0.9", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "dev": true, "license": "ISC", "dependencies": { "brace-expansion": "^2.0.2" @@ -6905,43 +6886,42 @@ } }, "node_modules/google-auth-library": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.5.0.tgz", - "integrity": "sha512-7ABviyMOlX5hIVD60YOfHw4/CxOfBhyduaYB+wbFWCWoni4N7SLcV46hrVRktuBbZjFC9ONyqamZITN7q3n32w==", + "version": "11.3.3", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-11.3.3.tgz", + "integrity": "sha512-VxjQ5+zHeR4RcRi001qnT/6KRKy2CIjQ5I7/wFErvRqr0+setlRqjDOAzvjzWEzyvsWswZE6WMQJtS8OpeTqAQ==", "license": "Apache-2.0", "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^7.0.0", - "gcp-metadata": "^8.0.0", - "google-logging-utils": "^1.0.0", - "gtoken": "^8.0.0", + "gaxios": "^8.3.1", + "gcp-metadata": "^9.2.1", + "google-logging-utils": "^2.1.0", "jws": "^4.0.0" }, "engines": { - "node": ">=18" + "node": ">=22" } }, "node_modules/google-gax": { - "version": "5.0.7", - "resolved": "https://registry.npmjs.org/google-gax/-/google-gax-5.0.7.tgz", - "integrity": "sha512-EhiqaWWJ+9h7sCcKJTsoo6tMcjokVHhWsbSuWCnZJT4vIBP3y4mAoFLnt9SzgkVZeq24ZsFaArr06nnYYku2yA==", + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/google-gax/-/google-gax-6.16.0.tgz", + "integrity": "sha512-qJz0RSuLgaPhiZDStTv04Q5MryjBNX6DJk7t3RlcOTHkLm3R3XxRhSjcSp1eDtU415IuBlV/bncyD5vnBFje1w==", "license": "Apache-2.0", "dependencies": { "@grpc/grpc-js": "^1.12.6", "@grpc/proto-loader": "^0.8.0", + "@opentelemetry/api": "^1.9.0", "duplexify": "^4.1.3", - "google-auth-library": "10.5.0", - "google-logging-utils": "1.1.3", + "google-auth-library": "^11.3.1", + "google-logging-utils": "^2.1.0", "node-fetch": "^3.3.2", "object-hash": "^3.0.0", - "proto3-json-serializer": "3.0.4", + "proto3-json-serializer": "^4.1.0", "protobufjs": "^7.5.4", - "retry-request": "^8.0.2", - "rimraf": "^5.0.1" + "retry-request": "^9.1.0" }, "engines": { - "node": ">=18" + "node": ">=22" } }, "node_modules/google-gax/node_modules/node-fetch": { @@ -6963,12 +6943,12 @@ } }, "node_modules/google-logging-utils": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz", - "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-2.1.1.tgz", + "integrity": "sha512-jYZOPMaRGS3Hldyudft6bdibW9ZWUKBkMdB2TeSETkV1c2T9TR4zxEWZETHv9xJ8KHr2hgkNLaSa8kcEcwlpeQ==", "license": "Apache-2.0", "engines": { - "node": ">=14" + "node": ">=22" } }, "node_modules/gopd": { @@ -6997,19 +6977,6 @@ "dev": true, "license": "MIT" }, - "node_modules/gtoken": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-8.0.0.tgz", - "integrity": "sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==", - "license": "MIT", - "dependencies": { - "gaxios": "^7.0.0", - "jws": "^4.0.0" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/has-bigints": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", @@ -8326,6 +8293,7 @@ "version": "3.4.3", "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, "license": "BlueOak-1.0.0", "dependencies": { "@isaacs/cliui": "^8.0.2" @@ -10460,6 +10428,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, "license": "BlueOak-1.0.0" }, "node_modules/parent-module": { @@ -10522,6 +10491,7 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -10538,6 +10508,7 @@ "version": "1.11.1", "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, "license": "BlueOak-1.0.0", "dependencies": { "lru-cache": "^10.2.0", @@ -10554,6 +10525,7 @@ "version": "10.4.3", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, "license": "ISC" }, "node_modules/path-to-regexp": { @@ -11116,15 +11088,15 @@ "license": "ISC" }, "node_modules/proto3-json-serializer": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/proto3-json-serializer/-/proto3-json-serializer-3.0.4.tgz", - "integrity": "sha512-E1sbAYg3aEbXrq0n1ojJkRHQJGE1kaE/O6GLA94y8rnJBfgvOPTOd1b9hOceQK1FFZI9qMh1vBERCyO2ifubcw==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/proto3-json-serializer/-/proto3-json-serializer-4.1.0.tgz", + "integrity": "sha512-Z0Blk2BTZTPp9ZXOWnRG/P3bkEs53FtMv59sl4xU44xcDdYhKlVO/AqAHTYXAlW9HdislqQxjSornP3457wkag==", "license": "Apache-2.0", "dependencies": { - "protobufjs": "^7.4.0" + "protobufjs": "^7.5.4" }, "engines": { - "node": ">=18" + "node": ">=22" } }, "node_modules/protobufjs": { @@ -11496,16 +11468,15 @@ "license": "MIT" }, "node_modules/retry-request": { - "version": "8.0.3", - "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-8.0.3.tgz", - "integrity": "sha512-qqoc4kkGgP9cmQDWELlOpAmfgJOg0Yi7MT82ZjiPWu451ayju4itwomjM4/dBEliify8C1b3tSaeCOldugtwPQ==", + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-9.1.0.tgz", + "integrity": "sha512-FILyVbis+DTo3KRbtKceqpj1595wIF+XQFW/+AVOBdCQmxwNDgcNXXr2FNM0Ej2qD7zVXbJGfH7lo4jB0wwhKA==", "license": "MIT", "dependencies": { - "extend": "^3.0.2", - "teeny-request": "^10.0.0" + "extend": "^3.0.2" }, "engines": { - "node": ">=18" + "node": ">=22" } }, "node_modules/reusify": { @@ -11557,21 +11528,6 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, - "node_modules/rimraf": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-5.0.10.tgz", - "integrity": "sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==", - "license": "ISC", - "dependencies": { - "glob": "^10.3.7" - }, - "bin": { - "rimraf": "dist/esm/bin.mjs" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/run-applescript": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz", @@ -12005,6 +11961,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -12017,6 +11974,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -12785,15 +12743,6 @@ "node": ">= 0.10.0" } }, - "node_modules/stream-events": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/stream-events/-/stream-events-1.0.5.tgz", - "integrity": "sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==", - "license": "MIT", - "dependencies": { - "stubs": "^3.0.0" - } - }, "node_modules/stream-shift": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz", @@ -12850,6 +12799,7 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", @@ -12976,6 +12926,7 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" @@ -13016,12 +12967,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/stubs": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/stubs/-/stubs-3.0.0.tgz", - "integrity": "sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==", - "license": "MIT" - }, "node_modules/superagent": { "version": "8.1.2", "resolved": "https://registry.npmjs.org/superagent/-/superagent-8.1.2.tgz", @@ -13198,39 +13143,6 @@ "streamx": "^2.15.0" } }, - "node_modules/teeny-request": { - "version": "10.1.3", - "resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-10.1.3.tgz", - "integrity": "sha512-5yDliI1uWkYPo7W+Zvrxg6YmoWuj5iC5EydewqrRTvc68nyMTZhlPPlLg6cptUGfbQAb+N9XDPDPzF6N081lug==", - "license": "Apache-2.0", - "dependencies": { - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.1", - "node-fetch": "^3.3.2", - "stream-events": "^1.0.5" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/teeny-request/node_modules/node-fetch": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", - "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", - "license": "MIT", - "dependencies": { - "data-uri-to-buffer": "^4.0.0", - "fetch-blob": "^3.1.4", - "formdata-polyfill": "^4.0.10" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/node-fetch" - } - }, "node_modules/teex": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", @@ -13828,6 +13740,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -13999,6 +13912,7 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", diff --git a/package.json b/package.json index 9ab1e7f1..7a6d0f3e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "controller", - "version": "3.9.4", + "version": "3.9.5-dev", "description": "A cloud-native operations controller for managing edge computing workloads, edgelet nodes, and deployments across Eclipse IoFog and Datasance PoT.", "main": "./src/main.js", "author": "Eclipse ioFog Project", @@ -78,9 +78,9 @@ }, "dependencies": { "@aws-sdk/client-secrets-manager": "^3.1156.0", - "@azure/identity": "^4.14.0", + "@azure/identity": "^4.14.1", "@azure/keyvault-secrets": "^4.11.2", - "@google-cloud/secret-manager": "^6.1.1", + "@google-cloud/secret-manager": "^7.2.0", "@kubernetes/client-node": "^1.4.0", "@msgpack/msgpack": "^3.1.2", "@nats-io/jwt": "^0.0.10-5", @@ -163,7 +163,6 @@ "type": "commonjs", "overrides": { "@grpc/grpc-js": "1.14.5", - "@azure/msal-node": "7.1.1", "tar": "^7.5.19", "protobufjs": "^7.6.5", "js-yaml": "4.3.2", From e64f6100bae0cc6db8c9b564a83f299b83f4643a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Durmu=C5=9F?= Date: Sun, 8 Nov 2026 21:06:12 +0300 Subject: [PATCH 8/9] Bump the embedded EdgeOps Console default to v1.1.4 and refresh the Node 24 and UBI9 base image digests. --- .env.example | 2 +- .github/actions/set-build-env/action.yml | 2 +- Dockerfile | 10 +++++----- Makefile | 4 ++-- scripts/build-console-dev.js | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.env.example b/.env.example index 5d6a7907..18a6b4ba 100644 --- a/.env.example +++ b/.env.example @@ -6,7 +6,7 @@ NODE_ENV=development # EdgeOps Console static embed (npm run build:console → dev/console/build) EDGEOPS_CONSOLE_PATH=dev/console/build # must be absolute path -EDGEOPS_CONSOLE_VERSION=v1.1.3 +EDGEOPS_CONSOLE_VERSION=v1.1.4 # EDGEOPS_CONSOLE_REPO=https://github.com/Datasance/edgeops-console # EDGEOPS_CONSOLE_FLAVOR=datasance diff --git a/.github/actions/set-build-env/action.yml b/.github/actions/set-build-env/action.yml index 8828fc6a..86d1c109 100644 --- a/.github/actions/set-build-env/action.yml +++ b/.github/actions/set-build-env/action.yml @@ -8,7 +8,7 @@ runs: shell: bash run: | VERSION="${{ env.EDGEOPS_CONSOLE_VERSION }}" - if [ -z "$VERSION" ]; then VERSION="1.1.3"; fi + if [ -z "$VERSION" ]; then VERSION="1.1.4"; fi echo "EDGEOPS_CONSOLE_VERSION=$VERSION" >> "${GITHUB_ENV}" REPO="${{ env.EDGEOPS_CONSOLE_REPO }}" diff --git a/Dockerfile b/Dockerfile index ca4fe130..db54fe5a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,10 +2,10 @@ # ioFog overrides: EDGEOPS_CONSOLE_REPO=https://github.com/eclipse-iofog/edgeops-console # EDGEOPS_CONSOLE_FLAVOR=iofog # node:24-bookworm — pin manifest list digest for reproducible multi-arch builds -FROM node:24-bookworm@sha256:d862bb5d082c5ae0210ac07e8c0344cb8cf7bef6d78e9b8c50c179da923108ea AS console-builder +FROM node:24-bookworm@sha256:8fa96264f302f58bbb13aa7339c541547b56975766ce956c875da149452a3e40 AS console-builder ARG EDGEOPS_CONSOLE_REPO=https://github.com/Datasance/edgeops-console -ARG EDGEOPS_CONSOLE_VERSION=v1.1.3 +ARG EDGEOPS_CONSOLE_VERSION=v1.1.4 ARG EDGEOPS_CONSOLE_FLAVOR=datasance RUN apt-get update \ @@ -28,7 +28,7 @@ RUN test -f build/index.html \ && cp -a build /tmp/console/build -FROM node:24-bookworm@sha256:d862bb5d082c5ae0210ac07e8c0344cb8cf7bef6d78e9b8c50c179da923108ea AS builder +FROM node:24-bookworm@sha256:8fa96264f302f58bbb13aa7339c541547b56975766ce956c875da149452a3e40 AS builder ARG PKG_VERSION @@ -48,9 +48,9 @@ RUN npm pack # ubi9/nodejs-24-minimal:latest — pin manifest list digest for reproducible multi-arch builds -FROM registry.access.redhat.com/ubi9/nodejs-24-minimal@sha256:18afd48c9af3c1f3df52cf72d1d0ea5bd3f07c50e4731ffd56b5b46bf4bb6639 +FROM registry.access.redhat.com/ubi9/nodejs-24-minimal@sha256:da724df0db4baceb0b89ebdc160dfe330fe3b215925742ee9e65efdfc6038850 -ARG EDGEOPS_CONSOLE_VERSION=v1.1.3 +ARG EDGEOPS_CONSOLE_VERSION=v1.1.4 ARG IMAGE_REGISTRY ARG OCI_SOURCE_REPO ARG CONTROLLER_DISTRIBUTION=iofog diff --git a/Makefile b/Makefile index 8f192dd8..d84d55ce 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ # Local Docker build — mirrors CI/release build-args (see .github/actions/set-build-env). -# Override any variable: make build FLAVOR=iofog EDGEOPS_CONSOLE_VERSION=v1.1.3 +# Override any variable: make build FLAVOR=iofog EDGEOPS_CONSOLE_VERSION=v1.1.4 FLAVOR ?= datasance IMAGE_NAME ?= controller @@ -25,7 +25,7 @@ else $(error FLAVOR must be "datasance" or "iofog", got "$(FLAVOR)") endif -EDGEOPS_CONSOLE_VERSION ?= v1.1.3 +EDGEOPS_CONSOLE_VERSION ?= v1.1.4 IMAGE_REF = $(IMAGE_REGISTRY)/$(IMAGE_NAME):$(DOCKER_TAG) diff --git a/scripts/build-console-dev.js b/scripts/build-console-dev.js index f61fc47f..3a8069ae 100644 --- a/scripts/build-console-dev.js +++ b/scripts/build-console-dev.js @@ -9,7 +9,7 @@ const CONSOLE_DIR = path.join(DEV_DIR, 'console') const BUILD_OUT = path.join(CONSOLE_DIR, 'build') const REPO = process.env.EDGEOPS_CONSOLE_REPO || 'https://github.com/Datasance/edgeops-console' -const VERSION = process.env.EDGEOPS_CONSOLE_VERSION || 'v1.1.3' +const VERSION = process.env.EDGEOPS_CONSOLE_VERSION || 'v1.1.4' const FLAVOR = process.env.EDGEOPS_CONSOLE_FLAVOR || 'datasance' function normalizeTag (version) { From 64a89b223368dc2a2fd5e1354930ce3540e37fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Durmu=C5=9F?= Date: Sun, 8 Nov 2026 21:06:16 +0300 Subject: [PATCH 9/9] Record the unreleased NATS leaf, service bridge, topology, and dependency notes. --- CHANGELOG.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c984e9f..a52aad6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog +## [Unreleased] + +### Added + +- **NATS topology `jsDomain`** — each NATS node on `/api/v3/network-topology/nats/nodes`, the NATS overview, the subgraph, and node detail includes `jsDomain`. A hub or server reports the Controller namespace. A leaf reports the agent name, or `null` when the agent row is missing. + +### Fixed + +- **NATS operator rotation on Kubernetes** — resolver reconciliation writes the new operator JWT into `iofog-nats-config` when that line differs. The NATS image reloads `server.conf`. The `nats` StatefulSet is not rolled for this change. + +### Changed + +- **Service `defaultBridge`** — a `microservice` or `agent` service accepts the agent name or the agent uuid of an interior that agent's router can reach. Uuid is matched first, then the agent name. The stored value is that agent's uuid. `default-router` stays the literal hub id. Reachability walks the interior mesh in both directions, so a bridge behind another interior is accepted and a bridge in another island is rejected. On Kubernetes, `k8sType`, `servicePort`, and the cluster Service are used only for `default-router`. A named bridge stores the listener on that router and sets `serviceEndpoint` to its host. +- **NATS leaf solicit list** — a leaf keeps one remote per application account. Every named upstream is a URL on that remote, dialed one at a time. Naming several servers in the same cluster no longer opens a connection per server. +- **Leaf upstreams** — omitted on create attaches to `default-nats-hub` only. `[]` attaches to nothing. A later update that omits the field still keeps the stored list. A list is either servers or leaves. A mix, a cycle, or two leaf parents that do not share the same next hop is rejected. A leaf may attach to a leaf that itself has no upstream. +- **Leaf listener** — a leaf listens for child leaves on the leafnode port, with TLS and advertise set to the agent host. A changed leaf broker config is written to the ConfigMap. The leaf container is not rebuilt. +- **Server cluster** — `upstreamNatsServers` on a server is not used and is not stored. Every server is connected to every other server, and cluster routes are that mesh. On Kubernetes, `iofog-nats-config` is patched when that route list changes, including a server that becomes a leaf. The `nats` StatefulSet rolls when the list gains its first route or loses a route. Adding a route to a cluster that already has routes does not roll it. +- **Parent leaf accounts** — a leaf's resolver, upward remotes, and leaf credentials include the application accounts of the leaves below it. Changing a leaf's upstream list refreshes every leaf above the parents that were added or removed. Turning an application's NATS access on or off, deleting the application, or creating, deleting, or moving one of its microservices, refreshes that agent, every leaf above it, and the servers. +- **`@google-cloud/secret-manager` ^6.1.1 → ^7.2.0** — drop production `glob` 10.5.0 and nested `minimatch` 9.0.9 pulled in through `google-gax` 5 and `rimraf` 5 (GHSA-3g3m-2fjr-6pw4, GHSA-g3hv-75wg-m249). Secret Manager client calls are unchanged. The same advisories remain on dev-only `mocha`, `nyc`, and `sequelize-cli`. `better-npm-audit audit -p` is clean. +- Dockerfile base image digest pins refreshed for **`node:24-bookworm`** (console-builder and builder) and **`ubi9/nodejs-24-minimal`**. +- Embedded **EdgeOps Console** default **v1.1.3 → v1.1.4** + +### Unchanged + +- JetStream domains stay the Controller namespace on a server and the agent name on a leaf. + ## [v3.9.4] ### Added @@ -13,7 +39,7 @@ ### Changed -- Embedded **EdgeOps Console** default **v1.1.1 → v1.1.2** +- Embedded **EdgeOps Console** default **v1.1.2 → v1.1.3** - Dockerfile runtime base image digest pin refreshed for **`ubi9/nodejs-24-minimal`**. - **`node-forge` ^1.4.0 → ^1.4.2** — address CVE-2026-85393 (GHSA-86w9-cpqp-85rv, PKCS#1 v1.5 signature verification) and the PEM and ASN.1 denial-of-service fixes in 1.4.1. Certificate generation and PEM parsing are unchanged. - **`qs` 6.16.0 → 6.16.1**, including the `qs` override — address GHSA-6pq8-jhm2-2vcw (`stringify` with `arrayFormat: 'comma'` throws on a non-callable `toString`).