Skip to content
This repository was archived by the owner on Feb 6, 2026. It is now read-only.

Commit 61feee1

Browse files
Merge pull request #8240 from systeminit/feat/clover/gcp/service-networking-fixes
fix(clover): handle google cloud service networking actions
2 parents 03fe761 + e81f96d commit 61feee1

6 files changed

Lines changed: 812 additions & 0 deletions

File tree

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
// Service Networking Connections delete override
2+
// This resource requires:
3+
// - Constructing name from parent + peering
4+
// - POST method with consumerNetwork in request body
5+
async function main(component: Input): Promise<Output> {
6+
const serviceAccountJson = requestStorage.getEnv("GOOGLE_APPLICATION_CREDENTIALS_JSON");
7+
if (!serviceAccountJson) {
8+
throw new Error("Google Cloud Credential not found. Please ensure a Google Cloud Credential is attached to this component.");
9+
}
10+
11+
const { token } = await getAccessToken(serviceAccountJson);
12+
const baseUrl = _.get(component.properties, ["domain", "extra", "baseUrl"], "");
13+
14+
// Construct the connection name from parent + peering
15+
const parent = _.get(component.properties, ["domain", "parent"]) ||
16+
_.get(component.properties, ["resource", "payload", "parent"]);
17+
const peering = _.get(component.properties, ["resource", "payload", "peering"]) ||
18+
_.get(component.properties, ["domain", "peering"]);
19+
const network = _.get(component.properties, ["domain", "network"]) ||
20+
_.get(component.properties, ["resource", "payload", "network"]);
21+
22+
if (!parent || !peering) {
23+
return {
24+
status: "error",
25+
message: "Cannot delete: missing parent or peering information",
26+
};
27+
}
28+
29+
const connectionName = `${parent}/connections/${peering}`;
30+
const url = `${baseUrl}v1/${connectionName}`;
31+
32+
// Service Networking delete requires consumerNetwork in request body
33+
const requestBody = network ? JSON.stringify({ consumerNetwork: network }) : undefined;
34+
35+
// Make the API request with retry logic
36+
const response = await siExec.withRetry(async () => {
37+
const resp = await fetch(url, {
38+
method: "POST", // Service Networking uses POST for deleteConnection
39+
headers: {
40+
"Authorization": `Bearer ${token}`,
41+
...(requestBody ? { "Content-Type": "application/json" } : {}),
42+
},
43+
body: requestBody,
44+
});
45+
46+
if (!resp.ok) {
47+
// If already deleted (404), consider it success
48+
if (resp.status === 404) {
49+
return resp;
50+
}
51+
52+
const errorText = await resp.text();
53+
const error = new Error(`Unable to delete resource;
54+
Called "${url}"
55+
API returned ${resp.status} ${resp.statusText}:
56+
${errorText}`
57+
) as any;
58+
error.status = resp.status;
59+
error.body = errorText;
60+
throw error;
61+
}
62+
63+
return resp;
64+
}, {
65+
isRateLimitedFn: (error) => error.status === 429
66+
}).then((r) => r.result);
67+
68+
// Handle 404 as success for delete operations
69+
if (response.status === 404) {
70+
return { status: "ok" };
71+
}
72+
73+
// Handle 204 No Content
74+
if (response.status === 204) {
75+
return { status: "ok" };
76+
}
77+
78+
// Try to parse response body
79+
const responseText = await response.text();
80+
if (!responseText) {
81+
return { status: "ok" };
82+
}
83+
84+
const responseJson = JSON.parse(responseText);
85+
86+
// Handle Long-Running Operation if returned
87+
if (responseJson.name && responseJson.name.includes("operations")) {
88+
console.log(`[DELETE] LRO detected, polling for completion...`);
89+
90+
const pollingUrl = `${baseUrl}v1/${responseJson.name}`;
91+
92+
await siExec.pollLRO({
93+
url: pollingUrl,
94+
headers: { "Authorization": `Bearer ${token}` },
95+
maxAttempts: 20,
96+
baseDelay: 2000,
97+
maxDelay: 30000,
98+
isCompleteFn: (response, body) => body.done === true,
99+
isErrorFn: (response, body) => !!body.error,
100+
extractResultFn: async (response, body) => {
101+
if (body.error) {
102+
throw new Error(`Delete operation failed: ${JSON.stringify(body.error)}`);
103+
}
104+
return body;
105+
}
106+
});
107+
108+
console.log(`[DELETE] Operation complete`);
109+
}
110+
111+
return { status: "ok" };
112+
}
113+
114+
async function getAccessToken(serviceAccountJson: string): Promise<{ token: string; projectId: string | undefined }> {
115+
let projectId: string | undefined;
116+
try {
117+
const serviceAccount = JSON.parse(serviceAccountJson);
118+
projectId = serviceAccount.project_id;
119+
} catch {
120+
projectId = undefined;
121+
}
122+
123+
const activateResult = await siExec.waitUntilEnd("gcloud", [
124+
"auth", "activate-service-account", "--key-file=-", "--quiet"
125+
], { input: serviceAccountJson });
126+
127+
if (activateResult.exitCode !== 0) {
128+
throw new Error(`Failed to activate service account: ${activateResult.stderr}`);
129+
}
130+
131+
const tokenResult = await siExec.waitUntilEnd("gcloud", ["auth", "print-access-token"]);
132+
if (tokenResult.exitCode !== 0) {
133+
throw new Error(`Failed to get access token: ${tokenResult.stderr}`);
134+
}
135+
136+
return { token: tokenResult.stdout.trim(), projectId };
137+
}
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
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

Comments
 (0)