|
| 1 | +// Service Networking Connections refresh override |
| 2 | +// This resource is list-only (no get API) and identified by network field, not name/id |
| 3 | +async function main(component: Input): Promise<Output> { |
| 4 | + const serviceAccountJson = requestStorage.getEnv("GOOGLE_APPLICATION_CREDENTIALS_JSON"); |
| 5 | + if (!serviceAccountJson) { |
| 6 | + throw new Error("Google Cloud Credential not found. Please ensure a Google Cloud Credential is attached to this component."); |
| 7 | + } |
| 8 | + |
| 9 | + const { token } = await getAccessToken(serviceAccountJson); |
| 10 | + const baseUrl = _.get(component.properties, ["domain", "extra", "baseUrl"], ""); |
| 11 | + const parent = _.get(component.properties, ["domain", "parent"]); |
| 12 | + const domainNetwork = _.get(component.properties, ["domain", "network"]); |
| 13 | + |
| 14 | + if (!parent) { |
| 15 | + return { status: "error", message: "No parent found for refresh" }; |
| 16 | + } |
| 17 | + |
| 18 | + // Build list URL - Service Networking requires network as query parameter |
| 19 | + let listUrl = `${baseUrl}v1/${parent}/connections`; |
| 20 | + if (domainNetwork) { |
| 21 | + listUrl += `?network=${encodeURIComponent(domainNetwork)}`; |
| 22 | + } |
| 23 | + |
| 24 | + // Fetch connections list |
| 25 | + const response = await siExec.withRetry(async () => { |
| 26 | + const resp = await fetch(listUrl, { |
| 27 | + method: "GET", |
| 28 | + headers: { "Authorization": `Bearer ${token}` }, |
| 29 | + }); |
| 30 | + |
| 31 | + if (!resp.ok) { |
| 32 | + const errorText = await resp.text(); |
| 33 | + const error = new Error(`Unable to refresh resource; |
| 34 | +Called "${listUrl}" |
| 35 | +API returned ${resp.status} ${resp.statusText}: |
| 36 | +${errorText}` |
| 37 | + ) as any; |
| 38 | + error.status = resp.status; |
| 39 | + error.body = errorText; |
| 40 | + throw error; |
| 41 | + } |
| 42 | + return resp; |
| 43 | + }, { |
| 44 | + isRateLimitedFn: (error) => error.status === 429 |
| 45 | + }).then((r) => r.result); |
| 46 | + |
| 47 | + const listData = await response.json(); |
| 48 | + |
| 49 | + // Find the array containing connections |
| 50 | + let connections = listData.connections; |
| 51 | + if (!connections) { |
| 52 | + for (const [key, value] of Object.entries(listData)) { |
| 53 | + if (Array.isArray(value) && key !== "unreachable" && key !== "warnings") { |
| 54 | + connections = value; |
| 55 | + break; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // Match by network field (Service Networking Connections don't have standard name/id) |
| 61 | + for (const connection of connections || []) { |
| 62 | + if (domainNetwork && connection.network) { |
| 63 | + // Normalize both for comparison (handle project number vs project name differences) |
| 64 | + const domainNetworkName = domainNetwork.split("/").pop(); |
| 65 | + const connectionNetworkName = connection.network.split("/").pop(); |
| 66 | + if (domainNetworkName && connectionNetworkName && domainNetworkName === connectionNetworkName) { |
| 67 | + return { payload: normalizeGcpResourceValues(connection), status: "ok" }; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + // Resource not found - may have been deleted |
| 73 | + console.log(`[REFRESH] Service Networking Connection for network ${domainNetwork} not found - may have been deleted`); |
| 74 | + return { status: "ok", payload: null }; |
| 75 | +} |
| 76 | + |
| 77 | +async function getAccessToken(serviceAccountJson: string): Promise<{ token: string; projectId: string | undefined }> { |
| 78 | + let projectId: string | undefined; |
| 79 | + try { |
| 80 | + const serviceAccount = JSON.parse(serviceAccountJson); |
| 81 | + projectId = serviceAccount.project_id; |
| 82 | + } catch { |
| 83 | + projectId = undefined; |
| 84 | + } |
| 85 | + |
| 86 | + const activateResult = await siExec.waitUntilEnd("gcloud", [ |
| 87 | + "auth", "activate-service-account", "--key-file=-", "--quiet" |
| 88 | + ], { input: serviceAccountJson }); |
| 89 | + |
| 90 | + if (activateResult.exitCode !== 0) { |
| 91 | + throw new Error(`Failed to activate service account: ${activateResult.stderr}`); |
| 92 | + } |
| 93 | + |
| 94 | + const tokenResult = await siExec.waitUntilEnd("gcloud", ["auth", "print-access-token"]); |
| 95 | + if (tokenResult.exitCode !== 0) { |
| 96 | + throw new Error(`Failed to get access token: ${tokenResult.stderr}`); |
| 97 | + } |
| 98 | + |
| 99 | + return { token: tokenResult.stdout.trim(), projectId }; |
| 100 | +} |
| 101 | + |
| 102 | +// URL normalization for GCP resource values |
| 103 | +const GCP_URL_PATTERN = /^https:\/\/[^/]*\.?googleapis\.com\//; |
| 104 | +const LOCATION_SEGMENTS = new Set(["regions", "zones", "locations"]); |
| 105 | + |
| 106 | +function normalizeGcpResourceValues<T>(obj: T): T { |
| 107 | + if (obj === null || obj === undefined) return obj; |
| 108 | + if (Array.isArray(obj)) return obj.map(item => normalizeGcpResourceValues(item)) as T; |
| 109 | + if (typeof obj === "object") { |
| 110 | + const normalized: Record<string, unknown> = {}; |
| 111 | + for (const [key, value] of Object.entries(obj)) { |
| 112 | + if (typeof value === "string" && GCP_URL_PATTERN.test(value)) { |
| 113 | + const pathParts = new URL(value).pathname.split("/").filter(Boolean); |
| 114 | + if (pathParts.length >= 2 && LOCATION_SEGMENTS.has(pathParts[pathParts.length - 2])) { |
| 115 | + normalized[key] = pathParts[pathParts.length - 1]; |
| 116 | + } else { |
| 117 | + const projectsIdx = pathParts.indexOf("projects"); |
| 118 | + if (projectsIdx !== -1) { |
| 119 | + normalized[key] = pathParts.slice(projectsIdx).join("/"); |
| 120 | + } else { |
| 121 | + const versionIdx = pathParts.findIndex(p => /^v\d+/.test(p)); |
| 122 | + normalized[key] = versionIdx !== -1 && versionIdx + 1 < pathParts.length |
| 123 | + ? pathParts.slice(versionIdx + 1).join("/") |
| 124 | + : pathParts[pathParts.length - 1] || value; |
| 125 | + } |
| 126 | + } |
| 127 | + } else if (typeof value === "object" && value !== null) { |
| 128 | + normalized[key] = normalizeGcpResourceValues(value); |
| 129 | + } else { |
| 130 | + normalized[key] = value; |
| 131 | + } |
| 132 | + } |
| 133 | + return normalized as T; |
| 134 | + } |
| 135 | + return obj; |
| 136 | +} |
0 commit comments