Skip to content
This repository was archived by the owner on Feb 6, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Service Networking Connections delete override
// This resource requires:
// - Constructing name from parent + peering
// - POST method with consumerNetwork in request body
async function main(component: Input): Promise<Output> {
const serviceAccountJson = requestStorage.getEnv("GOOGLE_APPLICATION_CREDENTIALS_JSON");
if (!serviceAccountJson) {
throw new Error("Google Cloud Credential not found. Please ensure a Google Cloud Credential is attached to this component.");
}

const { token } = await getAccessToken(serviceAccountJson);
const baseUrl = _.get(component.properties, ["domain", "extra", "baseUrl"], "");

// Construct the connection name from parent + peering
const parent = _.get(component.properties, ["domain", "parent"]) ||
_.get(component.properties, ["resource", "payload", "parent"]);
const peering = _.get(component.properties, ["resource", "payload", "peering"]) ||
_.get(component.properties, ["domain", "peering"]);
const network = _.get(component.properties, ["domain", "network"]) ||
_.get(component.properties, ["resource", "payload", "network"]);

if (!parent || !peering) {
return {
status: "error",
message: "Cannot delete: missing parent or peering information",
};
}

const connectionName = `${parent}/connections/${peering}`;
const url = `${baseUrl}v1/${connectionName}`;

// Service Networking delete requires consumerNetwork in request body
const requestBody = network ? JSON.stringify({ consumerNetwork: network }) : undefined;

// Make the API request with retry logic
const response = await siExec.withRetry(async () => {
const resp = await fetch(url, {
method: "POST", // Service Networking uses POST for deleteConnection
headers: {
"Authorization": `Bearer ${token}`,
...(requestBody ? { "Content-Type": "application/json" } : {}),
},
body: requestBody,
});

if (!resp.ok) {
// If already deleted (404), consider it success
if (resp.status === 404) {
return resp;
}

const errorText = await resp.text();
const error = new Error(`Unable to delete resource;
Called "${url}"
API returned ${resp.status} ${resp.statusText}:
${errorText}`
) as any;
error.status = resp.status;
error.body = errorText;
throw error;
}

return resp;
}, {
isRateLimitedFn: (error) => error.status === 429
}).then((r) => r.result);

// Handle 404 as success for delete operations
if (response.status === 404) {
return { status: "ok" };
}

// Handle 204 No Content
if (response.status === 204) {
return { status: "ok" };
}

// Try to parse response body
const responseText = await response.text();
if (!responseText) {
return { status: "ok" };
}

const responseJson = JSON.parse(responseText);

// Handle Long-Running Operation if returned
if (responseJson.name && responseJson.name.includes("operations")) {
console.log(`[DELETE] LRO detected, polling for completion...`);

const pollingUrl = `${baseUrl}v1/${responseJson.name}`;

await siExec.pollLRO({
url: pollingUrl,
headers: { "Authorization": `Bearer ${token}` },
maxAttempts: 20,
baseDelay: 2000,
maxDelay: 30000,
isCompleteFn: (response, body) => body.done === true,
isErrorFn: (response, body) => !!body.error,
extractResultFn: async (response, body) => {
if (body.error) {
throw new Error(`Delete operation failed: ${JSON.stringify(body.error)}`);
}
return body;
}
});

console.log(`[DELETE] Operation complete`);
}

return { status: "ok" };
}

async function getAccessToken(serviceAccountJson: string): Promise<{ token: string; projectId: string | undefined }> {
let projectId: string | undefined;
try {
const serviceAccount = JSON.parse(serviceAccountJson);
projectId = serviceAccount.project_id;
} catch {
projectId = undefined;
}

const activateResult = await siExec.waitUntilEnd("gcloud", [
"auth", "activate-service-account", "--key-file=-", "--quiet"
], { input: serviceAccountJson });

if (activateResult.exitCode !== 0) {
throw new Error(`Failed to activate service account: ${activateResult.stderr}`);
}

const tokenResult = await siExec.waitUntilEnd("gcloud", ["auth", "print-access-token"]);
if (tokenResult.exitCode !== 0) {
throw new Error(`Failed to get access token: ${tokenResult.stderr}`);
}

return { token: tokenResult.stdout.trim(), projectId };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Service Networking Connections refresh override
// This resource is list-only (no get API) and identified by network field, not name/id
async function main(component: Input): Promise<Output> {
const serviceAccountJson = requestStorage.getEnv("GOOGLE_APPLICATION_CREDENTIALS_JSON");
if (!serviceAccountJson) {
throw new Error("Google Cloud Credential not found. Please ensure a Google Cloud Credential is attached to this component.");
}

const { token } = await getAccessToken(serviceAccountJson);
const baseUrl = _.get(component.properties, ["domain", "extra", "baseUrl"], "");
const parent = _.get(component.properties, ["domain", "parent"]);
const domainNetwork = _.get(component.properties, ["domain", "network"]);

if (!parent) {
return { status: "error", message: "No parent found for refresh" };
}

// Build list URL - Service Networking requires network as query parameter
let listUrl = `${baseUrl}v1/${parent}/connections`;
if (domainNetwork) {
listUrl += `?network=${encodeURIComponent(domainNetwork)}`;
}

// Fetch connections list
const response = await siExec.withRetry(async () => {
const resp = await fetch(listUrl, {
method: "GET",
headers: { "Authorization": `Bearer ${token}` },
});

if (!resp.ok) {
const errorText = await resp.text();
const error = new Error(`Unable to refresh resource;
Called "${listUrl}"
API returned ${resp.status} ${resp.statusText}:
${errorText}`
) as any;
error.status = resp.status;
error.body = errorText;
throw error;
}
return resp;
}, {
isRateLimitedFn: (error) => error.status === 429
}).then((r) => r.result);

const listData = await response.json();

// Find the array containing connections
let connections = listData.connections;
if (!connections) {
for (const [key, value] of Object.entries(listData)) {
if (Array.isArray(value) && key !== "unreachable" && key !== "warnings") {
connections = value;
break;
}
}
}

// Match by network field (Service Networking Connections don't have standard name/id)
for (const connection of connections || []) {
if (domainNetwork && connection.network) {
// Normalize both for comparison (handle project number vs project name differences)
const domainNetworkName = domainNetwork.split("/").pop();
const connectionNetworkName = connection.network.split("/").pop();
if (domainNetworkName && connectionNetworkName && domainNetworkName === connectionNetworkName) {
return { payload: normalizeGcpResourceValues(connection), status: "ok" };
}
}
}

// Resource not found - may have been deleted
console.log(`[REFRESH] Service Networking Connection for network ${domainNetwork} not found - may have been deleted`);
return { status: "ok", payload: null };
}

async function getAccessToken(serviceAccountJson: string): Promise<{ token: string; projectId: string | undefined }> {
let projectId: string | undefined;
try {
const serviceAccount = JSON.parse(serviceAccountJson);
projectId = serviceAccount.project_id;
} catch {
projectId = undefined;
}

const activateResult = await siExec.waitUntilEnd("gcloud", [
"auth", "activate-service-account", "--key-file=-", "--quiet"
], { input: serviceAccountJson });

if (activateResult.exitCode !== 0) {
throw new Error(`Failed to activate service account: ${activateResult.stderr}`);
}

const tokenResult = await siExec.waitUntilEnd("gcloud", ["auth", "print-access-token"]);
if (tokenResult.exitCode !== 0) {
throw new Error(`Failed to get access token: ${tokenResult.stderr}`);
}

return { token: tokenResult.stdout.trim(), projectId };
}

// URL normalization for GCP resource values
const GCP_URL_PATTERN = /^https:\/\/[^/]*\.?googleapis\.com\//;
const LOCATION_SEGMENTS = new Set(["regions", "zones", "locations"]);

function normalizeGcpResourceValues<T>(obj: T): T {
if (obj === null || obj === undefined) return obj;
if (Array.isArray(obj)) return obj.map(item => normalizeGcpResourceValues(item)) as T;
if (typeof obj === "object") {
const normalized: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
if (typeof value === "string" && GCP_URL_PATTERN.test(value)) {
const pathParts = new URL(value).pathname.split("/").filter(Boolean);
if (pathParts.length >= 2 && LOCATION_SEGMENTS.has(pathParts[pathParts.length - 2])) {
normalized[key] = pathParts[pathParts.length - 1];
} else {
const projectsIdx = pathParts.indexOf("projects");
if (projectsIdx !== -1) {
normalized[key] = pathParts.slice(projectsIdx).join("/");
} else {
const versionIdx = pathParts.findIndex(p => /^v\d+/.test(p));
normalized[key] = versionIdx !== -1 && versionIdx + 1 < pathParts.length
? pathParts.slice(versionIdx + 1).join("/")
: pathParts[pathParts.length - 1] || value;
}
}
} else if (typeof value === "object" && value !== null) {
normalized[key] = normalizeGcpResourceValues(value);
} else {
normalized[key] = value;
}
}
return normalized as T;
}
return obj;
}
Loading
Loading