镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit 058483b

Browse files
chrisbbreuerclaude
andcommitted
feat(dns): a registrar can be pointed at a Route 53 hosted zone
Delegation moved a zone to Cloudflare only. Route 53 is now a destination too: the public hosted zone of the domain's exact name is created or reused, the registrar's records are copied and read back, and only then are the nameservers changed, as for Cloudflare. A registrar's own DNS is refused as a destination with the reason. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 4d86d66 commit 058483b

5 files changed

Lines changed: 315 additions & 19 deletions

File tree

‎packages/core/src/types.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2284,6 +2284,11 @@ export interface DnsConfig {
22842284
* it" — and lets a deploy perform that move instead of an operator doing it
22852285
* by hand at two dashboards and hoping the record sets match.
22862286
*
2287+
* `provider` may be `cloudflare` or `route53`: the two that host a zone for
2288+
* a domain registered elsewhere. On Route 53 the hosted zone is created, or
2289+
* the public one of that exact name reused, and `registrar.proxied` means
2290+
* nothing, as there is no edge.
2291+
*
22872292
* On deploy, when the registrar's nameservers do not already point at
22882293
* `provider`, ts-cloud creates the zone, copies the registrar's records
22892294
* across, verifies record for record that they arrived, and only then

‎packages/ts-cloud/src/dns/delegate-from-config.test.ts‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,139 @@ describe('describeZoneSettings', () => {
179179
expect(lines).toContain('already as declared')
180180
})
181181
})
182+
183+
describe('delegating to Route 53', () => {
184+
const NAMESERVERS = ['ns-1.awsdns-01.org', 'ns-2.awsdns-02.com', 'ns-3.awsdns-03.net', 'ns-4.awsdns-04.co.uk']
185+
186+
/** A zone host that keeps what it is given, as a hosted zone would. */
187+
function hostedZone(options: { drops?: (record: any) => boolean } = {}) {
188+
const records: any[] = []
189+
const created: string[] = []
190+
const add = async (_domain: string, record: any) => {
191+
if (!options.drops?.(record))
192+
records.push({ ...record })
193+
return { success: true }
194+
}
195+
return {
196+
name: 'route53',
197+
records,
198+
created,
199+
createZone: async (domain: string) => {
200+
created.push(domain)
201+
return { id: 'Z123', name: domain, status: 'active', nameServers: NAMESERVERS, created: true }
202+
},
203+
createRecord: add,
204+
upsertRecord: add,
205+
deleteRecord: async () => ({ success: true }),
206+
listRecords: async () => ({ success: true, records: records.map(r => ({ ...r })) }),
207+
canManageDomain: async () => true,
208+
listDomains: async () => ['example.com'],
209+
}
210+
}
211+
212+
/** A registrar holding a zone and a set of nameservers. */
213+
function registrarWith(records: any[], nameservers = ['a.ns.porkbun.com', 'b.ns.porkbun.com']) {
214+
const state = { nameservers }
215+
return {
216+
name: 'porkbun',
217+
state,
218+
getNameServers: async () => state.nameservers,
219+
updateNameServers: async (_domain: string, next: string[]) => {
220+
state.nameservers = next
221+
return true
222+
},
223+
createRecord: async () => ({ success: true }),
224+
upsertRecord: async () => ({ success: true }),
225+
deleteRecord: async () => ({ success: true }),
226+
listRecords: async () => ({ success: true, records }),
227+
canManageDomain: async () => true,
228+
listDomains: async () => ['example.com'],
229+
}
230+
}
231+
232+
const RECORDS = [
233+
{ name: 'example.com', type: 'A', content: '203.0.113.7', ttl: 600 },
234+
{ name: 'example.com', type: 'MX', content: 'mail.example.com', priority: 10, ttl: 600 },
235+
{ name: 'example.com', type: 'TXT', content: 'v=spf1 mx -all', ttl: 600 },
236+
{ name: 'example.com', type: 'NS', content: 'a.ns.porkbun.com', ttl: 600 },
237+
]
238+
const CONFIG = { domain: 'example.com', provider: 'route53' as const, registrar: { provider: 'porkbun' as const } }
239+
240+
it('creates the zone, copies the records and points the registrar at it', async () => {
241+
const host = hostedZone()
242+
const registrar = registrarWith(RECORDS)
243+
const result = await delegateZoneFromConfig(CONFIG, { credentials: CREDS, hosts: { route53: host as any }, registrar: registrar as any })
244+
245+
expect(result).toMatchObject({ status: 'delegated', domain: 'example.com', targetNameservers: NAMESERVERS })
246+
expect(host.created).toEqual(['example.com'])
247+
// The registrar's own NS records are the delegation being replaced: never copied.
248+
expect(host.records.map(r => r.type).sort()).toEqual(['A', 'MX', 'TXT'])
249+
expect(registrar.state.nameservers).toEqual(NAMESERVERS)
250+
expect(describeDelegation(result)[0]).toContain('delegated to ns-1.awsdns-01.org')
251+
})
252+
253+
it('leaves the nameservers alone when a record did not arrive', async () => {
254+
const host = hostedZone({ drops: record => record.type === 'MX' })
255+
const registrar = registrarWith(RECORDS)
256+
const result = await delegateZoneFromConfig(CONFIG, { credentials: CREDS, hosts: { route53: host as any }, registrar: registrar as any })
257+
258+
expect(result.status).toBe('blocked')
259+
expect(registrar.state.nameservers).toEqual(['a.ns.porkbun.com', 'b.ns.porkbun.com'])
260+
expect((result as any).missing.map((r: any) => r.type)).toEqual(['MX'])
261+
})
262+
263+
it('is a no-op once the registrar points at the hosted zone', async () => {
264+
const host = hostedZone()
265+
const registrar = registrarWith(RECORDS, NAMESERVERS.map(ns => `${ns.toUpperCase()}.`))
266+
const result = await delegateZoneFromConfig(CONFIG, { credentials: CREDS, hosts: { route53: host as any }, registrar: registrar as any })
267+
268+
expect(result.status).toBe('already-delegated')
269+
expect(host.records).toHaveLength(0)
270+
})
271+
272+
it('a dry run copies nothing and moves nothing', async () => {
273+
const host = hostedZone()
274+
const registrar = registrarWith(RECORDS)
275+
const result = await delegateZoneFromConfig(
276+
{ ...CONFIG, registrar: { provider: 'porkbun', dryRun: true } },
277+
{ credentials: CREDS, hosts: { route53: host as any }, registrar: registrar as any },
278+
)
279+
expect(result.status).toBe('ready')
280+
expect(host.records).toHaveLength(0)
281+
expect(registrar.state.nameservers).toEqual(['a.ns.porkbun.com', 'b.ns.porkbun.com'])
282+
})
283+
284+
it('says that proxied hosts mean nothing where there is no edge', async () => {
285+
const host = hostedZone()
286+
const result = await delegateZoneFromConfig(
287+
{ ...CONFIG, registrar: { provider: 'porkbun', proxied: ['example.com'] } },
288+
{ credentials: CREDS, hosts: { route53: host as any }, registrar: registrarWith(RECORDS) as any },
289+
)
290+
expect(result.status).toBe('delegated')
291+
expect(host.records.every(r => r.proxied !== true)).toBe(true)
292+
expect((result as any).warnings.join(' ')).toContain('proxied is ignored')
293+
})
294+
295+
it('skips, rather than throws, without AWS credentials', async () => {
296+
const result = await delegateZoneFromConfig(CONFIG, { credentials: { ...CREDS, aws: false } })
297+
expect(result).toMatchObject({ status: 'skipped' })
298+
expect((result as any).reason).toContain('AWS')
299+
})
300+
301+
it('finds AWS credentials in the environment in any of the usual forms', async () => {
302+
const skipped = await delegateZoneFromConfig(CONFIG, { env: { PORKBUN_API_KEY: 'pk', PORKBUN_SECRET_KEY: 'sk' } })
303+
expect((skipped as any).reason).toContain('AWS')
304+
// A profile is enough to get past the credential check to the registrar's.
305+
const next = await delegateZoneFromConfig(CONFIG, { env: { AWS_PROFILE: 'work' } })
306+
expect((next as any).reason).toContain('PORKBUN')
307+
})
308+
309+
it('does not delegate to a registrar\'s own nameservers', async () => {
310+
const result = await delegateZoneFromConfig(
311+
{ domain: 'example.com', provider: 'godaddy', registrar: { provider: 'porkbun' } },
312+
{ credentials: CREDS },
313+
)
314+
expect(result).toMatchObject({ status: 'skipped' })
315+
expect((result as any).reason).toContain('delegation to godaddy is not supported')
316+
})
317+
})

‎packages/ts-cloud/src/dns/delegate-from-config.ts‎

Lines changed: 75 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import type { DelegationReport } from './delegation'
1515
import { CloudflareProvider } from './cloudflare'
1616
import { GoDaddyProvider } from './godaddy'
1717
import { PorkbunProvider } from './porkbun'
18+
import { Route53Provider } from './route53-adapter'
1819
import { delegateZone, isNameserverRegistrar, isZoneHost } from './delegation'
1920

2021
/** The slice of `infrastructure.dns` this needs. */
@@ -58,8 +59,18 @@ export interface DelegationCredentials {
5859
godaddyApiSecret?: string
5960
cloudflareApiToken?: string
6061
cloudflareAccountId?: string
62+
/**
63+
* Whether AWS credentials are to hand for a Route 53 destination. Read from
64+
* the environment when left out; the AWS client resolves the keys itself.
65+
*/
66+
aws?: boolean
67+
/** The AWS region the Route 53 client signs for. @default 'us-east-1' */
68+
awsRegion?: string
6169
}
6270

71+
/** A destination a zone can be moved to, built for a config. */
72+
type DelegationHost = DnsProvider & { createZone: (domain: string, options?: { accountId?: string, jumpStart?: boolean }) => Promise<{ id: string, name: string, status: string, nameServers: string[], created: boolean }> }
73+
6374
/** Why a delegation was not attempted. Never a failure — just not applicable. */
6475
export interface DelegationSkipped {
6576
status: 'skipped'
@@ -74,7 +85,48 @@ function credentialsFromEnv(env: Record<string, string | undefined>): Delegation
7485
godaddyApiSecret: env.GODADDY_API_SECRET,
7586
cloudflareApiToken: env.CLOUDFLARE_API_TOKEN,
7687
cloudflareAccountId: env.CLOUDFLARE_ACCOUNT_ID,
88+
// Any of the ways the AWS client finds its keys: static, a profile, a role.
89+
aws: Boolean(
90+
(env.AWS_ACCESS_KEY_ID && env.AWS_SECRET_ACCESS_KEY)
91+
|| env.AWS_PROFILE
92+
|| env.AWS_ROLE_ARN
93+
|| env.AWS_WEB_IDENTITY_TOKEN_FILE
94+
|| env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
95+
|| env.AWS_CONTAINER_CREDENTIALS_FULL_URI,
96+
),
97+
awsRegion: env.AWS_REGION || env.AWS_DEFAULT_REGION,
98+
}
99+
}
100+
101+
/**
102+
* The provider a zone is moving to, or the reason it cannot be built.
103+
*
104+
* Every destination is the same thing to `delegateZone`: somewhere a zone can
105+
* be created, written to and read back, that reports its nameservers.
106+
*/
107+
function buildHost(
108+
provider: 'route53' | 'cloudflare' | 'porkbun' | 'godaddy',
109+
credentials: DelegationCredentials,
110+
hosts: { route53?: DelegationHost } = {},
111+
): DelegationHost | string {
112+
if (provider === 'cloudflare') {
113+
if (!credentials.cloudflareApiToken)
114+
return 'CLOUDFLARE_API_TOKEN is not set'
115+
const cloudflare = new CloudflareProvider(credentials.cloudflareApiToken, { accountId: credentials.cloudflareAccountId })
116+
return isZoneHost(cloudflare) ? cloudflare as unknown as DelegationHost : 'the Cloudflare provider cannot create zones'
117+
}
118+
119+
if (provider === 'route53') {
120+
if (hosts.route53)
121+
return hosts.route53
122+
if (!credentials.aws)
123+
return 'no AWS credentials are set (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, or AWS_PROFILE)'
124+
return new Route53Provider(credentials.awsRegion || 'us-east-1') as unknown as DelegationHost
77125
}
126+
127+
// A registrar's own DNS is where a domain already is. Moving a zone from one
128+
// registrar's nameservers to another's is a transfer of the domain itself.
129+
return `delegation to ${provider} is not supported: it hosts zones only for domains registered with it`
78130
}
79131

80132
function buildRegistrar(
@@ -106,7 +158,14 @@ function buildRegistrar(
106158
*/
107159
export async function delegateZoneFromConfig(
108160
config: DelegationConfig,
109-
options: { credentials?: DelegationCredentials, env?: Record<string, string | undefined> } = {},
161+
options: {
162+
credentials?: DelegationCredentials
163+
env?: Record<string, string | undefined>
164+
/** Destinations to use in place of the ones built from credentials. For tests. */
165+
hosts?: { route53?: DelegationHost }
166+
/** The registrar to use in place of the one built from credentials. For tests. */
167+
registrar?: DnsProvider & { getNameServers: (d: string) => Promise<string[]>, updateNameServers: (d: string, ns: string[]) => Promise<boolean> }
168+
} = {},
110169
): Promise<DelegationReport | DelegationSkipped> {
111170
const registrarConfig = config.registrar
112171
if (!registrarConfig)
@@ -123,33 +182,32 @@ export async function delegateZoneFromConfig(
123182
if (!config.provider || config.provider === registrarConfig.provider)
124183
return { status: 'skipped', reason: `dns.provider is already ${registrarConfig.provider}` }
125184

126-
if (config.provider !== 'cloudflare')
127-
return { status: 'skipped', reason: `delegation to ${config.provider} is not supported yet` }
128-
129185
const credentials = options.credentials ?? credentialsFromEnv(options.env ?? process.env)
130186

131-
if (!credentials.cloudflareApiToken)
132-
return { status: 'skipped', reason: 'CLOUDFLARE_API_TOKEN is not set' }
187+
const host = buildHost(config.provider, credentials, options.hosts)
188+
if (typeof host === 'string')
189+
return { status: 'skipped', reason: host }
133190

134-
const registrar = buildRegistrar(registrarConfig.provider, credentials)
191+
const registrar = options.registrar ?? buildRegistrar(registrarConfig.provider, credentials)
135192
if (typeof registrar === 'string')
136193
return { status: 'skipped', reason: registrar }
137194

138-
const host = new CloudflareProvider(credentials.cloudflareApiToken, {
139-
accountId: credentials.cloudflareAccountId,
140-
})
141-
142-
if (!isZoneHost(host))
143-
return { status: 'skipped', reason: 'the Cloudflare provider cannot create zones' }
144-
145-
return delegateZone({
195+
// Only Cloudflare has an edge to put a host behind. Elsewhere `proxied` is
196+
// not passed on, and saying so beats a config that quietly means nothing.
197+
const proxies = config.provider === 'cloudflare'
198+
const report = await delegateZone({
146199
domain: config.domain,
147200
registrar,
148201
host: host as any,
149-
proxiedHosts: registrarConfig.proxied,
150-
accountId: credentials.cloudflareAccountId,
202+
proxiedHosts: proxies ? registrarConfig.proxied : undefined,
203+
accountId: proxies ? credentials.cloudflareAccountId : undefined,
151204
dryRun: registrarConfig.dryRun,
152205
})
206+
207+
if (!proxies && registrarConfig.proxied?.length)
208+
report.warnings.push(`dns.registrar.proxied is ignored: ${config.provider} has no edge proxy, so every record is served as it is.`)
209+
210+
return report
153211
}
154212

155213
/** One line per outcome, for a deploy log. */

‎packages/ts-cloud/src/dns/route53-adapter.ts‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,57 @@ export class Route53Provider implements DnsProvider {
1111
private hostedZoneCache: Map<string, string> = new Map()
1212
private providedHostedZoneId?: string
1313

14-
constructor(region: string = 'us-east-1', hostedZoneId?: string) {
15-
this.client = new Route53Client(region)
14+
constructor(region: string = 'us-east-1', hostedZoneId?: string, client?: Route53Client) {
15+
this.client = client ?? new Route53Client(region)
1616
this.providedHostedZoneId = hostedZoneId
1717
}
1818

19+
/**
20+
* Make sure a PUBLIC hosted zone exists for exactly `domain`, and report the
21+
* nameservers Route 53 assigned it.
22+
*
23+
* This is what lets a registrar be pointed here (`delegateZone`). The zone is
24+
* looked up by its own name and never by walking up to a parent: a deploy
25+
* for `app.example.com` must not delegate into, or create records in, the
26+
* zone of `example.com`. A private zone of the same name does not count, as
27+
* no registrar can delegate to it. Route 53 will happily create a second
28+
* zone of a name it already hosts, each billed and each with different
29+
* nameservers, so an existing one is always reused.
30+
*/
31+
async createZone(domain: string): Promise<{ id: string, name: string, status: string, nameServers: string[], created: boolean }> {
32+
const name = domain.replace(/\.$/, '').toLowerCase()
33+
const listed = await this.client.listHostedZonesByName({ DNSName: `${name}.` })
34+
const existing = listed.HostedZones.find(zone => zone.Name.toLowerCase() === `${name}.` && !zone.Config?.PrivateZone)
35+
36+
const strip = (id: string): string => id.replace('/hostedzone/', '')
37+
const hosts = (servers: string[]): string[] => servers.map(server => server.replace(/\.$/, '').toLowerCase())
38+
39+
if (existing) {
40+
const details = await this.client.getHostedZone({ Id: existing.Id })
41+
this.remember(name, strip(existing.Id))
42+
return { id: strip(existing.Id), name, status: 'active', nameServers: hosts(details.DelegationSet?.NameServers ?? []), created: false }
43+
}
44+
45+
const created = await this.client.createHostedZone({
46+
Name: `${name}.`,
47+
HostedZoneConfig: { Comment: `Hosted zone for ${name}, created by ts-cloud`, PrivateZone: false },
48+
})
49+
this.remember(name, strip(created.HostedZone.Id))
50+
return { id: strip(created.HostedZone.Id), name, status: 'active', nameServers: hosts(created.DelegationSet?.NameServers ?? []), created: true }
51+
}
52+
53+
/**
54+
* Keep a zone's id for the record calls that follow. The cache is keyed by
55+
* registrable domain, so a zone for a deeper name (`app.example.com`) is
56+
* pinned instead: cached, it would answer for `example.com` too.
57+
*/
58+
private remember(name: string, zoneId: string): void {
59+
if (this.getRootDomain(name) === name)
60+
this.hostedZoneCache.set(name, zoneId)
61+
else
62+
this.providedHostedZoneId ??= zoneId
63+
}
64+
1965
/**
2066
* Get the root domain from a full domain name
2167
*/

0 commit comments

Comments
 (0)