-
-
Notifications
You must be signed in to change notification settings - Fork 131
custom domains - middleware and verification #2145
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
Open
Soxasora
wants to merge
51
commits into
stackernews:master
Choose a base branch
from
Soxasora:custom_domains_base
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 19 commits
Commits
Show all changes
51 commits
Select commit
Hold shift + click to select a range
c50509a
Custom Domains CRUD, Verification
Soxasora 5e80c3f
Domains refactor, Domain Verification normalization
Soxasora 4d24845
Domains normalization: Attempts, Records, Certificates
Soxasora b624c59
Domain Verification worker adjusted to new schema; use triggers to ch…
Soxasora 89f1eb4
wip: Domain Verification worker, log all verification steps
Soxasora 9d1c137
wip: clearer Domain Verification flow, surround AWS calls with try ca…
Soxasora dc119a8
Domain Verification schema updates
Soxasora 67fb2c8
HOLD the domain and delete the certificate when a territory expires
Soxasora 725ce81
delete the certificate from ACM when we're about to STOP a territory
Soxasora f3930f7
Domain resolver refactor, use transactions, add comments
Soxasora 01e319e
Stages for Domain Verification attempts logging, fix certificate dele…
Soxasora e132ad0
separate ACM certificate requests and validation values
Soxasora cd9cb68
Domains UI/UX enhancements; core fixes to schema; general cleanup
Soxasora 9e96d7c
delete any existing domain verification jobs if we're updating the do…
Soxasora 82a71f5
Log AWS-related error messages; fix deleteCertificate recursion
Soxasora f95ab6a
fix missing await on async customDomainMiddleware
Soxasora 4f49382
Merge branch 'master' into custom_domains_base
Soxasora 2382f3b
hotfix: delete certificate from ACM also on domain removal
Soxasora c732135
Merge branch 'master' into custom_domains_base
huumn ca13d80
prepare for dnsmasq, light cleanup
Soxasora 2a77fd1
fix DNS server typo
Soxasora 072c1ae
don't ask ACM to delete a certificate in a db transaction
Soxasora 7da660a
fix typo
Soxasora d0b9467
better handling of territory changes, ACM certificates and domains in…
Soxasora 2c4ca44
address plpgsql syntax issues, move INSERT for pgboss.schedule in a f…
Soxasora 52dd035
fallback to system's default DNS servers if dnsmasq is not available/…
Soxasora 0a7eda2
better error handling of node:dns resolver
Soxasora e6bd73b
Merge branch 'master' into custom_domains_base
huumn 76be3ae
hotfix: remove the port in dev for domain mapping
Soxasora e0e2dea
add aws container to domains profile
huumn 807c2d3
move existingTXT on a more appropriate place, TODOs on prisma schema
Soxasora e8d97ba
territory redirects and rewrites for middleware, adjust navbar reacti…
Soxasora 476c10b
30 seconds of interval between verification jobs, after 1 hour of dom…
Soxasora ef549a9
also get records when getting the existing domain, recreate the domai…
Soxasora 1e3b1c6
hotfix: use validateSchema the correct way, change from domain to dom…
Soxasora 25674c2
hide custom domains from the world but the admins
Soxasora eddd453
debounce next verification jobs with a singleton key, avoiding other …
Soxasora bbf2b0a
ELBv2 implementation to attach a certificate to a load balancer; Mock…
Soxasora f36eef4
use directly the interested ELB Listener ARN via env vars; get rid of…
Soxasora 51aadf2
throw database and AWS-related errors; don't log the STAGE on critica…
Soxasora 5bf8aba
remove unused certificate attachment to ELB checks
Soxasora 1643c09
remove unused ELB env var, remove useless console.logs
Soxasora d579b55
eradicate TXT records from custom domains; adjust functions to expect…
Soxasora 102b2f2
Merge branch 'master' into custom_domains_base
Soxasora 093910b
pass CNAME record directly instead of the whole records map
Soxasora 0ad0b33
don't delete the domain if resuming from HOLD
Soxasora ebf2c8b
wip: custom domains documentation
Soxasora f361958
docs: explain all the triggers, ACM and ALB implementations, fix head…
Soxasora 6a0b2cc
docs: clearer explanations
Soxasora ac03f32
use locally scoped configs for ACM and ELB APIs
Soxasora 55357e6
cleanup: remove unused domainMapping query from domain resolver
Soxasora File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import AWS from 'aws-sdk' | ||
|
||
AWS.config.update({ | ||
region: 'us-east-1' | ||
}) | ||
|
||
const config = {} | ||
|
||
export async function requestCertificate (domain) { | ||
// for local development, we use the LOCALSTACK_ENDPOINT | ||
if (process.env.NODE_ENV === 'development') { | ||
config.endpoint = process.env.LOCALSTACK_ENDPOINT | ||
} | ||
|
||
const acm = new AWS.ACM(config) | ||
const params = { | ||
DomainName: domain, | ||
ValidationMethod: 'DNS', | ||
Tags: [ | ||
{ | ||
Key: 'ManagedBy', | ||
Value: 'stacker.news' | ||
} | ||
] | ||
} | ||
|
||
const certificate = await acm.requestCertificate(params).promise() | ||
return certificate.CertificateArn | ||
} | ||
|
||
export async function describeCertificate (certificateArn) { | ||
if (process.env.NODE_ENV === 'development') { | ||
config.endpoint = process.env.LOCALSTACK_ENDPOINT | ||
} | ||
Soxasora marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const acm = new AWS.ACM(config) | ||
const certificate = await acm.describeCertificate({ CertificateArn: certificateArn }).promise() | ||
return certificate | ||
} | ||
|
||
export async function getCertificateStatus (certificateArn) { | ||
const certificate = await describeCertificate(certificateArn) | ||
return certificate.Certificate.Status | ||
} | ||
|
||
export async function deleteCertificate (certificateArn) { | ||
if (process.env.NODE_ENV === 'development') { | ||
config.endpoint = process.env.LOCALSTACK_ENDPOINT | ||
} | ||
const acm = new AWS.ACM(config) | ||
const result = await acm.deleteCertificate({ CertificateArn: certificateArn }).promise() | ||
console.log(`delete certificate attempt for ${certificateArn}, result: ${JSON.stringify(result)}`) | ||
return result | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
import { validateSchema, customDomainSchema } from '@/lib/validate' | ||
import { GqlAuthenticationError, GqlInputError } from '@/lib/error' | ||
import { randomBytes } from 'node:crypto' | ||
import { getDomainMapping } from '@/lib/domains' | ||
import { deleteDomainCertificate } from '@/lib/domain-verification' | ||
|
||
async function cleanDomainVerificationJobs (domain, models) { | ||
// delete any existing domain verification job left | ||
await models.$queryRaw` | ||
DELETE FROM pgboss.job | ||
WHERE name = 'domainVerification' | ||
AND data->>'domainId' = ${domain.id}::TEXT` | ||
} | ||
|
||
export default { | ||
Query: { | ||
domain: async (parent, { subName }, { models }) => { | ||
return models.domain.findUnique({ | ||
where: { subName }, | ||
include: { records: true, attempts: true, certificate: true } | ||
}) | ||
}, | ||
domainMapping: async (parent, { domainName }, { models }) => { | ||
const mapping = await getDomainMapping(domainName) | ||
return mapping | ||
} | ||
}, | ||
Mutation: { | ||
setDomain: async (parent, { subName, domainName }, { me, models }) => { | ||
if (!me) { | ||
throw new GqlAuthenticationError() | ||
} | ||
|
||
const sub = await models.sub.findUnique({ where: { name: subName } }) | ||
if (!sub) { | ||
throw new GqlInputError('sub not found') | ||
} | ||
|
||
if (sub.userId !== me.id) { | ||
throw new GqlInputError('you do not own this sub') | ||
} | ||
|
||
domainName = domainName.trim() // protect against trailing spaces | ||
if (domainName && !validateSchema(customDomainSchema, { domainName })) { | ||
throw new GqlInputError('invalid domain format') | ||
} | ||
|
||
// we need to get the existing domain if we're updating or re-verifying | ||
const existing = await models.domain.findUnique({ where: { subName } }) | ||
|
||
if (domainName) { | ||
// updating the domain name and recovering from HOLD is allowed | ||
if (existing && existing.domainName === domainName && existing.status !== 'HOLD') { | ||
throw new GqlInputError('domain already set') | ||
} | ||
|
||
// we should always make sure to get a new updatedAt timestamp | ||
// to know when should we put the domain in HOLD during verification | ||
const initializeDomain = { | ||
domainName, | ||
updatedAt: new Date(), | ||
status: 'PENDING' | ||
} | ||
|
||
const updatedDomain = await models.$transaction(async tx => { | ||
// clean any existing domain verification job left | ||
if (existing && existing.status === 'HOLD') { | ||
await cleanDomainVerificationJobs(existing, tx) | ||
} | ||
|
||
const domain = await tx.domain.upsert({ | ||
where: { subName }, | ||
update: initializeDomain, | ||
create: { | ||
...initializeDomain, | ||
sub: { connect: { name: subName } } | ||
} | ||
}) | ||
|
||
// if on HOLD, get the existing TXT record | ||
const existingTXT = existing && existing.status === 'HOLD' | ||
? await tx.domainVerificationRecord.findUnique({ | ||
where: { | ||
domainId_type_recordName: { | ||
domainId: existing.id, | ||
type: 'TXT', | ||
recordName: '_snverify.' + existing.domainName | ||
} | ||
} | ||
}) | ||
: null | ||
huumn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// create the verification records | ||
const verificationRecords = [ | ||
{ | ||
domainId: domain.id, | ||
type: 'CNAME', | ||
recordName: domainName, | ||
recordValue: new URL(process.env.NEXT_PUBLIC_URL).host | ||
}, | ||
{ | ||
domainId: domain.id, | ||
type: 'TXT', | ||
recordName: '_snverify.' + domainName, | ||
recordValue: existingTXT // if we're resuming from HOLD, use the existing TXT record | ||
? existingTXT.recordValue | ||
: randomBytes(32).toString('base64') | ||
} | ||
] | ||
|
||
// create the verification records | ||
for (const record of verificationRecords) { | ||
await tx.domainVerificationRecord.upsert({ | ||
where: { | ||
domainId_type_recordName: { | ||
domainId: domain.id, | ||
type: record.type, | ||
recordName: record.recordName | ||
} | ||
}, | ||
update: record, | ||
create: record | ||
}) | ||
} | ||
|
||
// create the job to verify the domain in 30 seconds | ||
await tx.$executeRaw` | ||
INSERT INTO pgboss.job (name, data, retrylimit, retrydelay, startafter, keepuntil) | ||
VALUES ('domainVerification', | ||
jsonb_build_object('domainId', ${domain.id}::INTEGER), | ||
3, | ||
60, | ||
now() + interval '30 seconds', | ||
now() + interval '2 days' | ||
)` | ||
|
||
return domain | ||
}) | ||
|
||
return updatedDomain | ||
} else { | ||
try { | ||
// Delete any existing domain verification jobs | ||
if (existing) { | ||
return await models.$transaction(async tx => { | ||
// delete any existing domain verification job left | ||
await cleanDomainVerificationJobs(existing, tx) | ||
|
||
// deleting a domain will also delete the domain certificate | ||
// but we need to make sure to delete the certificate from ACM | ||
if (existing.certificate) { | ||
await deleteDomainCertificate(existing.certificate.certificateArn) | ||
} | ||
Soxasora marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// delete the domain | ||
return await tx.domain.delete({ where: { subName } }) | ||
}) | ||
} | ||
return null | ||
} catch (error) { | ||
console.error(error) | ||
throw new GqlInputError('failed to delete domain') | ||
} | ||
} | ||
} | ||
}, | ||
Domain: { | ||
records: async (domain) => { | ||
if (!domain.records) return [] | ||
|
||
// O(1) lookups by type, simpler checks for CNAME, TXT and ACM validation records. | ||
return Object.fromEntries(domain.records.map(record => [record.type, record])) | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.