Skip to content

chore: Add domainName to instance configuration, part of #421. #425

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 17, 2025
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
50 changes: 50 additions & 0 deletions src/dns-lookup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import dns from 'node:dns';
import {CloudSQLConnectorError} from './errors';

export async function resolveTxtRecord(name: string): Promise<string> {
return new Promise((resolve, reject) => {
dns.resolveTxt(name, (err, addresses) => {
if (err) {
reject(
new CloudSQLConnectorError({
code: 'EDOMAINNAMELOOKUPERROR',
message: 'Error looking up TXT record for domain ' + name,
errors: [err],
})
);
return;
}

if (!addresses || addresses.length === 0) {
reject(
new CloudSQLConnectorError({
code: 'EDOMAINNAMELOOKUPFAILED',
message: 'No records returned for domain ' + name,
})
);
return;
}

// Each result may be split into multiple strings. Join the strings.
const joinedAddresses = addresses.map(strs => strs.join(''));
// Sort the results alphabetically for consistency,
joinedAddresses.sort((a, b) => a.localeCompare(b));
// Return the first result.
resolve(joinedAddresses[0]);
});
});
}
1 change: 1 addition & 0 deletions src/instance-connection-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ export interface InstanceConnectionInfo {
projectId: string;
regionId: string;
instanceId: string;
domainName?: string;
}
92 changes: 79 additions & 13 deletions src/parse-instance-connection-name.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,83 @@

import {InstanceConnectionInfo} from './instance-connection-info';
import {CloudSQLConnectorError} from './errors';
import {resolveTxtRecord} from './dns-lookup';

export function isSameInstance(
a: InstanceConnectionInfo,
b: InstanceConnectionInfo
): boolean {
return (
a.instanceId === b.instanceId &&
a.regionId === b.regionId &&
a.projectId === b.projectId &&
a.domainName === b.domainName
);
}

export async function resolveInstanceName(
instanceConnectionName?: string,
domainName?: string
): Promise<InstanceConnectionInfo> {
if (!instanceConnectionName && !domainName) {
throw new CloudSQLConnectorError({
message:
'Missing instance connection name, expected: "PROJECT:REGION:INSTANCE" or a valid domain name.',
code: 'ENOCONNECTIONNAME',
});
} else if (
instanceConnectionName &&
isInstanceConnectionName(instanceConnectionName)
) {
return parseInstanceConnectionName(instanceConnectionName);
} else if (domainName && isValidDomainName(domainName)) {
return await resolveDomainName(domainName);
} else {
throw new CloudSQLConnectorError({
message:
'Malformed Instance connection name, expected an instance connection name in the form "PROJECT:REGION:INSTANCE" or a valid domain name',
code: 'EBADCONNECTIONNAME',
});
}
}

const connectionNameRegex =
/^(?<projectId>[^:]+(:[^:]+)?):(?<regionId>[^:]+):(?<instanceId>[^:]+)$/;

// The domain name pattern in accordance with RFC 1035, RFC 1123 and RFC 2181.
// From Go Connector:
const domainNameRegex =
/^(?:[_a-z0-9](?:[_a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/;

export function isValidDomainName(name: string): boolean {
const matches = String(name).match(domainNameRegex);
return Boolean(matches);
}

export function isInstanceConnectionName(name: string): boolean {
const matches = String(name).match(connectionNameRegex);
return Boolean(matches);
}

export async function resolveDomainName(
name: string
): Promise<InstanceConnectionInfo> {
const icn = await resolveTxtRecord(name);
if (!isInstanceConnectionName(icn)) {
throw new CloudSQLConnectorError({
message:
'Malformed instance connection name returned for domain ' +
name +
' : ' +
icn,
code: 'EBADDOMAINCONNECTIONNAME',
});
}

const info = parseInstanceConnectionName(icn);
info.domainName = name;
return info;
}

export function parseInstanceConnectionName(
instanceConnectionName: string | undefined
Expand All @@ -26,20 +103,8 @@ export function parseInstanceConnectionName(
});
}

const connectionNameRegex =
/(?<projectId>[^:]+(:[^:]+)?):(?<regionId>[^:]+):(?<instanceId>[^:]+)/;
const matches = String(instanceConnectionName).match(connectionNameRegex);
if (!matches) {
throw new CloudSQLConnectorError({
message:
'Malformed instance connection name provided: expected format ' +
`of "PROJECT:REGION:INSTANCE", got ${instanceConnectionName}`,
code: 'EBADCONNECTIONNAME',
});
}

const unmatchedItems = matches[0] !== matches.input;
if (unmatchedItems || !matches.groups) {
if (!matches || !matches.groups) {
throw new CloudSQLConnectorError({
message:
'Malformed instance connection name provided: expected format ' +
Expand All @@ -52,5 +117,6 @@ export function parseInstanceConnectionName(
projectId: matches.groups.projectId,
regionId: matches.groups.regionId,
instanceId: matches.groups.instanceId,
domainName: undefined,
};
}
1 change: 1 addition & 0 deletions test/cloud-sql-instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ t.test('CloudSQLInstance', async t => {
projectId: 'my-project',
regionId: 'us-east1',
instanceId: 'my-instance',
domainName: undefined,
},
'should have expected connection info'
);
Expand Down
79 changes: 79 additions & 0 deletions test/dns-lookup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import t from 'tap';

t.test('lookup dns with mock responses', async t => {
const {resolveTxtRecord} = t.mockRequire('../src/dns-lookup.ts', {
'node:dns': {
resolveTxt: (name, callback) => {
switch (name) {
case 'db.example.com':
callback(null, [['my-project:region-1:instance']]);
return;
case 'multiple.example.com':
callback(null, [
['my-project:region-1:instance'],
['another-project:region-1:instance'],
]);
return;
case 'split.example.com':
callback(null, [['my-project:', 'region-1:instance']]);
return;
case 'empty.example.com':
callback(null, []);
return;
default:
callback(new Error('not found'), null);
return;
}
},
},
});

t.same(
await resolveTxtRecord('db.example.com'),
'my-project:region-1:instance',
'valid domain name'
);
t.same(
await resolveTxtRecord('split.example.com'),
'my-project:region-1:instance',
'valid domain name'
);
t.same(
await resolveTxtRecord('multiple.example.com'),
'another-project:region-1:instance',
'valid domain name'
);
t.rejects(
async () => await resolveTxtRecord('not-found.example.com'),
{code: 'EDOMAINNAMELOOKUPERROR'},
'should throw type error if an extra item is provided'
);
t.rejects(
async () => await resolveTxtRecord('empty.example.com'),
{code: 'EDOMAINNAMELOOKUPFAILED'},
'should throw type error if an extra item is provided'
);
});

t.test('lookup dns with real responses', async t => {
const {resolveTxtRecord} = t.mockRequire('../src/dns-lookup.ts', {});
t.same(
await resolveTxtRecord('valid-san-test.csqlconnectortest.com'),
'cloud-sql-connector-testing:us-central1:postgres-customer-cas-test',
'valid domain name'
);
});
Loading
Loading