Skip to content
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

Add support to customizing certbot cert command #2019

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
83 changes: 57 additions & 26 deletions src/user/system/CertbotManager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ApiStatusCodes from '../../api/ApiStatusCodes'
import DockerApi from '../../docker/DockerApi'
import CaptainConstants from '../../utils/CaptainConstants'
import CaptainConstants, { type CertbotCertCommandRule } from '../../utils/CaptainConstants'
import Logger from '../../utils/Logger'
import Utils from '../../utils/Utils'
import fs = require('fs-extra')
Expand All @@ -12,8 +12,36 @@ const WEBROOT_PATH_IN_CAPTAIN =

const shouldUseStaging = false // CaptainConstants.isDebug;

function isCertCommandSuccess(output: string) {
ZeekoZhu marked this conversation as resolved.
Show resolved Hide resolved
// https://github.com/certbot/certbot/blob/099c6c8b240400b928d6b349e023e5e8414611e6/certbot/certbot/_internal/main.py#L516
if (
output.indexOf(
'Congratulations! Your certificate and chain have been saved',
) >= 0
) {
return true
}

// https://github.com/certbot/certbot/blob/f4e031f5055fc6bf8c87eb0b18f927f7f5ba36a8/certbot/certbot/_internal/main.py#L632
if (output.indexOf('Successfully received certificate') >= 0) {
return true
}

// https://github.com/certbot/certbot/blob/f4e031f5055fc6bf8c87eb0b18f927f7f5ba36a8/certbot/certbot/_internal/main.py#L1596
if (
output.indexOf(
'Certificate not yet due for renewal; no action taken',
) >= 0
) {
return true
}

return false
}

class CertbotManager {
private isOperationInProcess: boolean
private certCommandGenerator = new CertCommandGenerator(CaptainConstants.configs.certbotCertCommand ?? [], ['certbot', 'certonly', '--webroot', '-w', '${webroot}', '-d', '${domain}'])

constructor(private dockerApi: DockerApi) {
this.dockerApi = dockerApi
Expand Down Expand Up @@ -46,7 +74,6 @@ class CertbotManager {

return `/live/${domainName}/privkey.pem`
}

enableSsl(domainName: string) {
const self = this

Expand All @@ -58,15 +85,10 @@ class CertbotManager {
return self.ensureDomainHasDirectory(domainName)
})
.then(function () {
const cmd = [
'certbot',
'certonly',
'--webroot',
'-w',
`${WEBROOT_PATH_IN_CERTBOT}/${domainName}`,
'-d',
domainName,
]
const cmd = self.certCommandGenerator.getCertbotCertCommand(domainName, {
domain: domainName,
webroot: WEBROOT_PATH_IN_CERTBOT + '/' + domainName
})

if (shouldUseStaging) {
cmd.push('--staging')
Expand All @@ -75,19 +97,7 @@ class CertbotManager {
return self.runCommand(cmd).then(function (output) {
Logger.d(output)

if (
output.indexOf(
'Congratulations! Your certificate and chain have been saved'
) >= 0
) {
return true
}

if (
output.indexOf(
'Certificate not yet due for renewal; no action taken'
) >= 0
) {
if (isCertCommandSuccess(output)) {
return true
}

Expand Down Expand Up @@ -295,7 +305,7 @@ class CertbotManager {

return dockerApi
.createServiceOnNodeId(
CaptainConstants.certbotImageName,
CaptainConstants.configs.certbotImageName,
CaptainConstants.certbotServiceName,
undefined,
nodeId,
Expand Down Expand Up @@ -373,7 +383,7 @@ class CertbotManager {

return dockerApi.updateService(
CaptainConstants.certbotServiceName,
CaptainConstants.certbotImageName,
CaptainConstants.configs.certbotImageName,
[
{
hostPath: CaptainConstants.letsEncryptEtcPath,
Expand Down Expand Up @@ -410,3 +420,24 @@ class CertbotManager {
}

export default CertbotManager

export class CertCommandGenerator {
constructor(private rules: CertbotCertCommandRule[], private defaultCommand: string[]) {
}

private getCertbotCertCommandTemplate(domainName: string): string[] {
for (const rule of this.rules) {
if (rule.domain === '*'
|| domainName === rule.domain
|| domainName.endsWith('.' + rule.domain)
) {
return rule.command ?? this.defaultCommand
}
}
return this.defaultCommand
}
getCertbotCertCommand(domainName: string, variables: Record<string, string> = {}): string[] {
ZeekoZhu marked this conversation as resolved.
Show resolved Hide resolved
const command = this.getCertbotCertCommandTemplate(domainName)
return command.map(c => c.replace(/\$\{(\w+)}/g, (match, p1) => variables[p1] ?? match))
}
}
17 changes: 15 additions & 2 deletions src/utils/CaptainConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,21 @@ const configs = {
proApiDomains: ['https://pro.caprover.com'],

analyticsDomain: 'https://analytics-v1.caprover.com',

certbotImageName: 'caprover/certbot-sleeping:v1.6.0',

certbotCertCommand: undefined as CertbotCertCommandRule[] | undefined,
ZeekoZhu marked this conversation as resolved.
Show resolved Hide resolved
}

export interface CertbotCertCommandRule {
/**
* Matches both *.<domain> and <domain>, use '*' to match all domains
*/
domain: string;
/**
* The Certbot command to execute, in Docker exec form, uses `${domain}` as the placeholder for the actual domain name
*/
command?: string[];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use command?: string, when passing to exec, we can do command.trim().split(' ')

This will make it much easier to override and read.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good! We can use shell-quote to parse the command string before passing it to exec. It's more robust than using String.split.

}

const data = {
Expand Down Expand Up @@ -133,8 +148,6 @@ const data = {

// ********************* Local Docker Constants ************************

certbotImageName: 'caprover/certbot-sleeping:v1.6.0',

captainSaltSecretKey: 'captain-salt',

nginxServiceName: 'captain-nginx',
Expand Down
2 changes: 1 addition & 1 deletion src/utils/CaptainInstaller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ export function install() {
return DockerApi.get().pullImage(imageName, undefined)
})
.then(function () {
const imageName = CaptainConstants.certbotImageName
const imageName = CaptainConstants.configs.certbotImageName
console.log(`Pulling: ${imageName}`)
return DockerApi.get().pullImage(imageName, undefined)
})
Expand Down
55 changes: 55 additions & 0 deletions tests/CertCommandGenerator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { CertCommandGenerator } from '../src/user/system/CertbotManager'

const defaultCommand = [ 'certbot', 'certonly', '--domain', '${domain}' ]
const exampleRule = {
domain: 'example.com',
command: [ 'certbot', 'certonly', '--manual', '--preferred-challenges=dns', '--domain', '${domain}' ],
}
const wildcardRule = {
domain: '*',
command: [ 'certbot', 'renew' ],
}
const nullCommandRule = {
domain: 'fallback.com',
}

test('uses default command when no rules match', () => {
const generator = new CertCommandGenerator([], defaultCommand)
expect(generator.getCertbotCertCommand('nonmatching.com')).toEqual(defaultCommand)
})

test('uses specific rule when domain matches exactly', () => {
const generator = new CertCommandGenerator([ exampleRule ], defaultCommand)
expect(generator.getCertbotCertCommand('example.com')).toEqual(exampleRule.command)
})

test('uses wildcard rule for any domain', () => {
const generator = new CertCommandGenerator([ wildcardRule ], defaultCommand)
expect(generator.getCertbotCertCommand('anything.com')).toEqual(wildcardRule.command)
})

test('matches subdomain to rule', () => {
const generator = new CertCommandGenerator([ exampleRule ], defaultCommand)
expect(generator.getCertbotCertCommand('sub.example.com')).toEqual(exampleRule.command)
})

test('replaces variables in command template', () => {
const generator = new CertCommandGenerator([], defaultCommand)
expect(generator.getCertbotCertCommand('example.com', { 'domain': 'example.com' }))
.toEqual([ 'certbot', 'certonly', '--domain', 'example.com' ])
})

test('leaves unreplaced placeholders unchanged', () => {
const generator = new CertCommandGenerator([], [ 'echo', '${missing}' ])
expect(generator.getCertbotCertCommand('example.com')).toEqual([ 'echo', '${missing}' ])
})

test('first matching rule is used when multiple rules could apply', () => {
const generator = new CertCommandGenerator([ exampleRule, wildcardRule ], defaultCommand)
expect(generator.getCertbotCertCommand('example.com')).toEqual(exampleRule.command)
})

test('falls back to default command when rule command is null', () => {
const generator = new CertCommandGenerator([ nullCommandRule ], defaultCommand)
expect(generator.getCertbotCertCommand('nullcommand.com')).toEqual(defaultCommand)
})