Debian Codegraph @

caddyconfig/httpcaddyfile/tlsapp.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package httpcaddyfile
16
17 import (
18 "bytes"
19 "encoding/json"
20 "fmt"
21 "reflect"
22 "slices"
23 "sort"
24 "strconv"
25 "strings"
26
27 "github.com/caddyserver/certmagic"
28 "github.com/mholt/acmez/v3/acme"
29
30 "github.com/caddyserver/caddy/v2"
31 "github.com/caddyserver/caddy/v2/caddyconfig"
32 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
33 "github.com/caddyserver/caddy/v2/modules/caddytls"
34 )
35
36 func (st ServerType) buildTLSApp(
37 pairings []sbAddrAssociation,
38 options map[string]any,
39 warnings []caddyconfig.Warning,
40 ) (*caddytls.TLS, []caddyconfig.Warning, error) {
41 tlsApp := &caddytls.TLS{CertificatesRaw: make(caddy.ModuleMap)}
42 var certLoaders []caddytls.CertificateLoader
43
44 httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort)
45 if hp, ok := options["http_port"].(int); ok {
46 httpPort = strconv.Itoa(hp)
47 }
48 autoHTTPS := []string{}
49 if ah, ok := options["auto_https"].([]string); ok {
50 autoHTTPS = ah
51 }
52
53 // find all hosts that share a server block with a hostless
54 // key, so that they don't get forgotten/omitted by auto-HTTPS
55 // (since they won't appear in route matchers)
56 httpsHostsSharedWithHostlessKey := make(map[string]struct{})
57 if !slices.Contains(autoHTTPS, "off") {
58 for _, pair := range pairings {
59 for _, sb := range pair.serverBlocks {
60 for _, addr := range sb.parsedKeys {
61 if addr.Host != "" {
62 continue
63 }
64
65 // this server block has a hostless key, now
66 // go through and add all the hosts to the set
67 for _, otherAddr := range sb.parsedKeys {
68 if otherAddr.Original == addr.Original {
69 continue
70 }
71 if otherAddr.Host != "" && otherAddr.Scheme != "http" && otherAddr.Port != httpPort {
72 httpsHostsSharedWithHostlessKey[otherAddr.Host] = struct{}{}
73 }
74 }
75 break
76 }
77 }
78 }
79 }
80
81 // a catch-all automation policy is used as a "default" for all subjects that
82 // don't have custom configuration explicitly associated with them; this
83 // is only to add if the global settings or defaults are non-empty
84 catchAllAP, err := newBaseAutomationPolicy(options, warnings, false)
85 if err != nil {
86 return nil, warnings, err
87 }
88 if catchAllAP != nil {
89 if tlsApp.Automation == nil {
90 tlsApp.Automation = new(caddytls.AutomationConfig)
91 }
92 tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, catchAllAP)
93 }
94
95 forcedAutomatedNames := make(map[string]struct{}) // explicitly configured to be automated, even if covered by a wildcard
96
97 for _, p := range pairings {
98 // avoid setting up TLS automation policies for a server that is HTTP-only
99 var addresses []string
100 for _, addressWithProtocols := range p.addressesWithProtocols {
101 addresses = append(addresses, addressWithProtocols.address)
102 }
103 if !listenersUseAnyPortOtherThan(addresses, httpPort) {
104 continue
105 }
106
107 for _, sblock := range p.serverBlocks {
108 // check the scheme of all the site addresses,
109 // skip building AP if they all had http://
110 if sblock.isAllHTTP() {
111 continue
112 }
113
114 // get values that populate an automation policy for this block
115 ap, err := newBaseAutomationPolicy(options, warnings, true)
116 if err != nil {
117 return nil, warnings, err
118 }
119
120 sblockHosts := sblock.hostsFromKeys(false)
121 if len(sblockHosts) == 0 && catchAllAP != nil {
122 ap = catchAllAP
123 }
124
125 // on-demand tls
126 if _, ok := sblock.pile["tls.on_demand"]; ok {
127 ap.OnDemand = true
128 }
129
130 // collect hosts that are forced to have certs automated for their specific name
131 if _, ok := sblock.pile["tls.force_automate"]; ok {
132 for _, host := range sblockHosts {
133 forcedAutomatedNames[host] = struct{}{}
134 }
135 }
136
137 // reuse private keys tls
138 if _, ok := sblock.pile["tls.reuse_private_keys"]; ok {
139 ap.ReusePrivateKeys = true
140 }
141
142 if keyTypeVals, ok := sblock.pile["tls.key_type"]; ok {
143 ap.KeyType = keyTypeVals[0].Value.(string)
144 }
145
146 if renewalWindowRatioVals, ok := sblock.pile["tls.renewal_window_ratio"]; ok {
147 ap.RenewalWindowRatio = renewalWindowRatioVals[0].Value.(float64)
148 } else if globalRenewalWindowRatio, ok := options["renewal_window_ratio"]; ok {
149 ap.RenewalWindowRatio = globalRenewalWindowRatio.(float64)
150 }
151
152 // certificate issuers
153 if issuerVals, ok := sblock.pile["tls.cert_issuer"]; ok {
154 var issuers []certmagic.Issuer
155 for _, issuerVal := range issuerVals {
156 issuers = append(issuers, issuerVal.Value.(certmagic.Issuer))
157 }
158 if ap == catchAllAP && !reflect.DeepEqual(ap.Issuers, issuers) {
159 // this more correctly implements an error check that was removed
160 // below; try it with this config:
161 //
162 // :443 {
163 // bind 127.0.0.1
164 // }
165 //
166 // :443 {
167 // bind ::1
168 // tls {
169 // issuer acme
170 // }
171 // }
172 return nil, warnings, fmt.Errorf("automation policy from site block is also default/catch-all policy because of key without hostname, and the two are in conflict: %#v != %#v", ap.Issuers, issuers)
173 }
174 ap.Issuers = issuers
175 }
176
177 // certificate managers
178 if certManagerVals, ok := sblock.pile["tls.cert_manager"]; ok {
179 for _, certManager := range certManagerVals {
180 certGetterName := certManager.Value.(caddy.Module).CaddyModule().ID.Name()
181 ap.ManagersRaw = append(ap.ManagersRaw, caddyconfig.JSONModuleObject(certManager.Value, "via", certGetterName, &warnings))
182 }
183 }
184 // custom bind host
185 for _, cfgVal := range sblock.pile["bind"] {
186 for _, iss := range ap.Issuers {
187 // if an issuer was already configured and it is NOT an ACME issuer,
188 // skip, since we intend to adjust only ACME issuers; ensure we
189 // include any issuer that embeds/wraps an underlying ACME issuer
190 var acmeIssuer *caddytls.ACMEIssuer
191 if acmeWrapper, ok := iss.(acmeCapable); ok {
192 acmeIssuer = acmeWrapper.GetACMEIssuer()
193 }
194 if acmeIssuer == nil {
195 continue
196 }
197
198 // proceed to configure the ACME issuer's bind host, without
199 // overwriting any existing settings
200 if acmeIssuer.Challenges == nil {
201 acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
202 }
203 if acmeIssuer.Challenges.BindHost == "" {
204 // only binding to one host is supported
205 var bindHost string
206 if asserted, ok := cfgVal.Value.(addressesWithProtocols); ok && len(asserted.addresses) > 0 {
207 bindHost = asserted.addresses[0]
208 }
209 acmeIssuer.Challenges.BindHost = bindHost
210 }
211 }
212 }
213
214 // we used to ensure this block is allowed to create an automation policy;
215 // doing so was forbidden if it has a key with no host (i.e. ":443")
216 // and if there is a different server block that also has a key with no
217 // host -- since a key with no host matches any host, we need its
218 // associated automation policy to have an empty Subjects list, i.e. no
219 // host filter, which is indistinguishable between the two server blocks
220 // because automation is not done in the context of a particular server...
221 // this is an example of a poor mapping from Caddyfile to JSON but that's
222 // the least-leaky abstraction I could figure out -- however, this check
223 // was preventing certain listeners, like those provided by plugins, from
224 // being used as desired (see the Tailscale listener plugin), so I removed
225 // the check: and I think since I originally wrote the check I added a new
226 // check above which *properly* detects this ambiguity without breaking the
227 // listener plugin; see the check above with a commented example config
228 if len(sblockHosts) == 0 && catchAllAP == nil {
229 // this server block has a key with no hosts, but there is not yet
230 // a catch-all automation policy (probably because no global options
231 // were set), so this one becomes it
232 catchAllAP = ap
233 }
234
235 hostsNotHTTP := sblock.hostsFromKeysNotHTTP(httpPort)
236 sort.Strings(hostsNotHTTP) // solely for deterministic test results
237
238 // associate our new automation policy with this server block's hosts
239 ap.SubjectsRaw = hostsNotHTTP
240
241 // if a combination of public and internal names were given
242 // for this same server block and no issuer was specified, we
243 // need to separate them out in the automation policies so
244 // that the internal names can use the internal issuer and
245 // the other names can use the default/public/ACME issuer
246 var ap2 *caddytls.AutomationPolicy
247 if len(ap.Issuers) == 0 {
248 var internal, external []string
249 for _, s := range ap.SubjectsRaw {
250 // do not create Issuers for Tailscale domains; they will be given a Manager instead
251 if isTailscaleDomain(s) {
252 continue
253 }
254 if !certmagic.SubjectQualifiesForCert(s) {
255 return nil, warnings, fmt.Errorf("subject does not qualify for certificate: '%s'", s)
256 }
257 // we don't use certmagic.SubjectQualifiesForPublicCert() because of one nuance:
258 // names like *.*.tld that may not qualify for a public certificate are actually
259 // fine when used with OnDemand, since OnDemand (currently) does not obtain
260 // wildcards (if it ever does, there will be a separate config option to enable
261 // it that we would need to check here) since the hostname is known at handshake;
262 // and it is unexpected to switch to internal issuer when the user wants to get
263 // regular certificates on-demand for a class of certs like *.*.tld.
264 if subjectQualifiesForPublicCert(ap, s) {
265 external = append(external, s)
266 } else {
267 internal = append(internal, s)
268 }
269 }
270 if len(external) > 0 && len(internal) > 0 {
271 ap.SubjectsRaw = external
272 apCopy := *ap
273 ap2 = &apCopy
274 ap2.SubjectsRaw = internal
275 ap2.IssuersRaw = []json.RawMessage{caddyconfig.JSONModuleObject(caddytls.InternalIssuer{}, "module", "internal", &warnings)}
276 }
277 }
278
279 if tlsApp.Automation == nil {
280 tlsApp.Automation = new(caddytls.AutomationConfig)
281 }
282 tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, ap)
283 if ap2 != nil {
284 tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, ap2)
285 }
286
287 // certificate loaders
288 if clVals, ok := sblock.pile["tls.cert_loader"]; ok {
289 for _, clVal := range clVals {
290 certLoaders = append(certLoaders, clVal.Value.(caddytls.CertificateLoader))
291 }
292 }
293 }
294 }
295
296 // group certificate loaders by module name, then add to config
297 if len(certLoaders) > 0 {
298 loadersByName := make(map[string]caddytls.CertificateLoader)
299 for _, cl := range certLoaders {
300 name := caddy.GetModuleName(cl)
301 // ugh... technically, we may have multiple FileLoader and FolderLoader
302 // modules (because the tls directive returns one per occurrence), but
303 // the config structure expects only one instance of each kind of loader
304 // module, so we have to combine them... instead of enumerating each
305 // possible cert loader module in a type switch, we can use reflection,
306 // which works on any cert loaders that are slice types
307 if reflect.TypeOf(cl).Kind() == reflect.Slice {
308 combined := reflect.ValueOf(loadersByName[name])
309 if !combined.IsValid() {
310 combined = reflect.New(reflect.TypeOf(cl)).Elem()
311 }
312 clVal := reflect.ValueOf(cl)
313 for i := range clVal.Len() {
314 combined = reflect.Append(combined, clVal.Index(i))
315 }
316 loadersByName[name] = combined.Interface().(caddytls.CertificateLoader)
317 }
318 }
319 for certLoaderName, loaders := range loadersByName {
320 tlsApp.CertificatesRaw[certLoaderName] = caddyconfig.JSON(loaders, &warnings)
321 }
322 }
323
324 // set any of the on-demand options, for if/when on-demand TLS is enabled
325 if onDemand, ok := options["on_demand_tls"].(*caddytls.OnDemandConfig); ok {
326 if tlsApp.Automation == nil {
327 tlsApp.Automation = new(caddytls.AutomationConfig)
328 }
329 tlsApp.Automation.OnDemand = onDemand
330 }
331
332 // set up "global" (to the TLS app) DNS provider config
333 if globalDNS, ok := options["dns"]; ok && globalDNS != nil {
334 tlsApp.DNSRaw = caddyconfig.JSONModuleObject(globalDNS, "name", globalDNS.(caddy.Module).CaddyModule().ID.Name(), nil)
335 }
336
337 // set up "global" (to the TLS app) DNS resolvers config
338 if globalResolvers, ok := options["tls_resolvers"]; ok && globalResolvers != nil {
339 tlsApp.Resolvers = globalResolvers.([]string)
340 }
341
342 // set up ECH from Caddyfile options
343 if ech, ok := options["ech"].(*caddytls.ECH); ok {
344 tlsApp.EncryptedClientHello = ech
345
346 // outer server names will need certificates, so make sure they're included
347 // in an automation policy for them that applies any global options
348 ap, err := newBaseAutomationPolicy(options, warnings, true)
349 if err != nil {
350 return nil, warnings, err
351 }
352 for _, cfg := range ech.Configs {
353 if cfg.PublicName != "" {
354 ap.SubjectsRaw = append(ap.SubjectsRaw, cfg.PublicName)
355 }
356 }
357 if tlsApp.Automation == nil {
358 tlsApp.Automation = new(caddytls.AutomationConfig)
359 }
360 tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, ap)
361 }
362
363 // if the storage clean interval is a boolean, then it's "off" to disable cleaning
364 if sc, ok := options["storage_check"].(string); ok && sc == "off" {
365 tlsApp.DisableStorageCheck = true
366 }
367
368 // if the storage clean interval is a boolean, then it's "off" to disable cleaning
369 if sci, ok := options["storage_clean_interval"].(bool); ok && !sci {
370 tlsApp.DisableStorageClean = true
371 }
372
373 // set the storage clean interval if configured
374 if storageCleanInterval, ok := options["storage_clean_interval"].(caddy.Duration); ok {
375 if tlsApp.Automation == nil {
376 tlsApp.Automation = new(caddytls.AutomationConfig)
377 }
378 tlsApp.Automation.StorageCleanInterval = storageCleanInterval
379 }
380
381 // set the expired certificates renew interval if configured
382 if renewCheckInterval, ok := options["renew_interval"].(caddy.Duration); ok {
383 if tlsApp.Automation == nil {
384 tlsApp.Automation = new(caddytls.AutomationConfig)
385 }
386 tlsApp.Automation.RenewCheckInterval = renewCheckInterval
387 }
388
389 // set the OCSP check interval if configured
390 if ocspCheckInterval, ok := options["ocsp_interval"].(caddy.Duration); ok {
391 if tlsApp.Automation == nil {
392 tlsApp.Automation = new(caddytls.AutomationConfig)
393 }
394 tlsApp.Automation.OCSPCheckInterval = ocspCheckInterval
395 }
396
397 // set whether OCSP stapling should be disabled for manually-managed certificates
398 if ocspConfig, ok := options["ocsp_stapling"].(certmagic.OCSPConfig); ok {
399 tlsApp.DisableOCSPStapling = ocspConfig.DisableStapling
400 }
401
402 // if any hostnames appear on the same server block as a key with
403 // no host, they will not be used with route matchers because the
404 // hostless key matches all hosts, therefore, it wouldn't be
405 // considered for auto-HTTPS, so we need to make sure those hosts
406 // are manually considered for managed certificates; we also need
407 // to make sure that any of these names which are internal-only
408 // get internal certificates by default rather than ACME
409 var al caddytls.AutomateLoader
410 internalAP := &caddytls.AutomationPolicy{
411 IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)},
412 }
413 if !slices.Contains(autoHTTPS, "off") && !slices.Contains(autoHTTPS, "disable_certs") {
414 for h := range httpsHostsSharedWithHostlessKey {
415 al = append(al, h)
416 if !certmagic.SubjectQualifiesForPublicCert(h) {
417 internalAP.SubjectsRaw = append(internalAP.SubjectsRaw, h)
418 }
419 }
420 }
421 for name := range forcedAutomatedNames {
422 if slices.Contains(al, name) {
423 continue
424 }
425 al = append(al, name)
426 }
427 slices.Sort(al) // to stabilize the adapt output
428 if len(al) > 0 {
429 tlsApp.CertificatesRaw["automate"] = caddyconfig.JSON(al, &warnings)
430 }
431 if len(internalAP.SubjectsRaw) > 0 {
432 if tlsApp.Automation == nil {
433 tlsApp.Automation = new(caddytls.AutomationConfig)
434 }
435 tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, internalAP)
436 }
437
438 // if there are any global options set for issuers (ACME ones in particular), make sure they
439 // take effect in every automation policy that does not have any issuers
440 if tlsApp.Automation != nil {
441 globalEmail := options["email"]
442 globalACMECA := options["acme_ca"]
443 globalACMECARoot := options["acme_ca_root"]
444 _, globalACMEDNS := options["acme_dns"] // can be set to nil (to use globally-defined "dns" value instead), but it is still set
445 globalACMEEAB := options["acme_eab"]
446 globalPreferredChains := options["preferred_chains"]
447 hasGlobalACMEDefaults := globalEmail != nil || globalACMECA != nil || globalACMECARoot != nil || globalACMEDNS || globalACMEEAB != nil || globalPreferredChains != nil
448 if hasGlobalACMEDefaults {
449 for i := range tlsApp.Automation.Policies {
450 ap := tlsApp.Automation.Policies[i]
451 if len(ap.Issuers) == 0 && automationPolicyHasAllPublicNames(ap) {
452 // for public names, create default issuers which will later be filled in with configured global defaults
453 // (internal names will implicitly use the internal issuer at auto-https time)
454 emailStr, _ := globalEmail.(string)
455 ap.Issuers = caddytls.DefaultIssuers(emailStr)
456
457 // if a specific endpoint is configured, can't use multiple default issuers
458 if globalACMECA != nil {
459 ap.Issuers = []certmagic.Issuer{new(caddytls.ACMEIssuer)}
460 }
461 }
462 }
463 }
464 }
465
466 // finalize and verify policies; do cleanup
467 if tlsApp.Automation != nil {
468 for i, ap := range tlsApp.Automation.Policies {
469 // ensure all issuers have global defaults filled in
470 for j, issuer := range ap.Issuers {
471 err := fillInGlobalACMEDefaults(issuer, options)
472 if err != nil {
473 return nil, warnings, fmt.Errorf("filling in global issuer defaults for AP %d, issuer %d: %v", i, j, err)
474 }
475 }
476
477 // encode all issuer values we created, so they will be rendered in the output
478 if len(ap.Issuers) > 0 && ap.IssuersRaw == nil {
479 for _, iss := range ap.Issuers {
480 issuerName := iss.(caddy.Module).CaddyModule().ID.Name()
481 ap.IssuersRaw = append(ap.IssuersRaw, caddyconfig.JSONModuleObject(iss, "module", issuerName, &warnings))
482 }
483 }
484 }
485
486 // consolidate automation policies that are the exact same
487 tlsApp.Automation.Policies = consolidateAutomationPolicies(tlsApp.Automation.Policies)
488
489 // ensure automation policies don't overlap subjects (this should be
490 // an error at provision-time as well, but catch it in the adapt phase
491 // for convenience)
492 automationHostSet := make(map[string]struct{})
493 for _, ap := range tlsApp.Automation.Policies {
494 for _, s := range ap.SubjectsRaw {
495 if _, ok := automationHostSet[s]; ok {
496 return nil, warnings, fmt.Errorf("hostname appears in more than one automation policy, making certificate management ambiguous: %s", s)
497 }
498 automationHostSet[s] = struct{}{}
499 }
500 }
501
502 // if nothing remains, remove any excess values to clean up the resulting config
503 if len(tlsApp.Automation.Policies) == 0 {
504 tlsApp.Automation.Policies = nil
505 }
506 if reflect.DeepEqual(tlsApp.Automation, new(caddytls.AutomationConfig)) {
507 tlsApp.Automation = nil
508 }
509 }
510
511 return tlsApp, warnings, nil
512 }
513
514 type acmeCapable interface{ GetACMEIssuer() *caddytls.ACMEIssuer }
515
516 func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) error {
517 acmeWrapper, ok := issuer.(acmeCapable)
518 if !ok {
519 return nil
520 }
521 acmeIssuer := acmeWrapper.GetACMEIssuer()
522 if acmeIssuer == nil {
523 return nil
524 }
525
526 globalEmail := options["email"]
527 globalACMECA := options["acme_ca"]
528 globalACMECARoot := options["acme_ca_root"]
529 globalACMEDNS, globalACMEDNSok := options["acme_dns"] // can be set to nil (to use globally-defined "dns" value instead), but it is still set
530 globalACMEEAB := options["acme_eab"]
531 globalPreferredChains := options["preferred_chains"]
532 globalCertLifetime := options["cert_lifetime"]
533 globalHTTPPort, globalHTTPSPort := options["http_port"], options["https_port"]
534 globalDefaultBind := options["default_bind"]
535
536 if globalEmail != nil && acmeIssuer.Email == "" {
537 acmeIssuer.Email = globalEmail.(string)
538 }
539 if globalACMECA != nil && acmeIssuer.CA == "" {
540 acmeIssuer.CA = globalACMECA.(string)
541 }
542 if globalACMECARoot != nil && !slices.Contains(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string)) {
543 acmeIssuer.TrustedRootsPEMFiles = append(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string))
544 }
545 if globalACMEDNSok && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.DNS == nil || acmeIssuer.Challenges.DNS.ProviderRaw == nil) {
546 globalDNS := options["dns"]
547 if globalDNS == nil && globalACMEDNS == nil {
548 return fmt.Errorf("acme_dns specified without DNS provider config, but no provider specified with 'dns' global option")
549 }
550 if acmeIssuer.Challenges == nil {
551 acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
552 }
553 if acmeIssuer.Challenges.DNS == nil {
554 acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
555 }
556 if globalACMEDNS != nil && acmeIssuer.Challenges.DNS.ProviderRaw == nil {
557 // Set a global DNS provider if `acme_dns` is set
558 acmeIssuer.Challenges.DNS.ProviderRaw = caddyconfig.JSONModuleObject(globalACMEDNS, "name", globalACMEDNS.(caddy.Module).CaddyModule().ID.Name(), nil)
559 }
560 }
561 if globalACMEEAB != nil && acmeIssuer.ExternalAccount == nil {
562 acmeIssuer.ExternalAccount = globalACMEEAB.(*acme.EAB)
563 }
564 if globalPreferredChains != nil && acmeIssuer.PreferredChains == nil {
565 acmeIssuer.PreferredChains = globalPreferredChains.(*caddytls.ChainPreference)
566 }
567 // only configure alt HTTP and TLS-ALPN ports if the DNS challenge is not enabled (wouldn't hurt, but isn't necessary since the DNS challenge is exclusive of others)
568 if globalHTTPPort != nil && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.DNS == nil) && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.HTTP == nil || acmeIssuer.Challenges.HTTP.AlternatePort == 0) {
569 if acmeIssuer.Challenges == nil {
570 acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
571 }
572 if acmeIssuer.Challenges.HTTP == nil {
573 acmeIssuer.Challenges.HTTP = new(caddytls.HTTPChallengeConfig)
574 }
575 acmeIssuer.Challenges.HTTP.AlternatePort = globalHTTPPort.(int)
576 }
577 if globalHTTPSPort != nil && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.DNS == nil) && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.TLSALPN == nil || acmeIssuer.Challenges.TLSALPN.AlternatePort == 0) {
578 if acmeIssuer.Challenges == nil {
579 acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
580 }
581 if acmeIssuer.Challenges.TLSALPN == nil {
582 acmeIssuer.Challenges.TLSALPN = new(caddytls.TLSALPNChallengeConfig)
583 }
584 acmeIssuer.Challenges.TLSALPN.AlternatePort = globalHTTPSPort.(int)
585 }
586 // If BindHost is still unset, fall back to the first default_bind address if set
587 // This avoids binding the automation policy to the wildcard socket, which is unexpected behavior when a more selective socket is specified via default_bind
588 // In BSD it is valid to bind to the wildcard socket even though a more selective socket is already open (still unexpected behavior by the caller though)
589 // In Linux the same call will error with EADDRINUSE whenever the listener for the automation policy is opened
590 if acmeIssuer.Challenges == nil || (acmeIssuer.Challenges.DNS == nil && acmeIssuer.Challenges.BindHost == "") {
591 if defBinds, ok := globalDefaultBind.([]ConfigValue); ok && len(defBinds) > 0 {
592 if abp, ok := defBinds[0].Value.(addressesWithProtocols); ok && len(abp.addresses) > 0 {
593 if acmeIssuer.Challenges == nil {
594 acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
595 }
596 acmeIssuer.Challenges.BindHost = abp.addresses[0]
597 }
598 }
599 }
600 if globalCertLifetime != nil && acmeIssuer.CertificateLifetime == 0 {
601 acmeIssuer.CertificateLifetime = globalCertLifetime.(caddy.Duration)
602 }
603 // apply global resolvers if DNS challenge is configured and resolvers are not already set
604 globalResolvers := options["tls_resolvers"]
605 if globalResolvers != nil && acmeIssuer.Challenges != nil && acmeIssuer.Challenges.DNS != nil {
606 // Check if DNS challenge is actually configured
607 hasDNSChallenge := globalACMEDNSok || acmeIssuer.Challenges.DNS.ProviderRaw != nil
608 if hasDNSChallenge && len(acmeIssuer.Challenges.DNS.Resolvers) == 0 {
609 acmeIssuer.Challenges.DNS.Resolvers = globalResolvers.([]string)
610 }
611 }
612 return nil
613 }
614
615 // implicitACMEIssuers returns the issuers to use for ACME-related tls
616 // shortcuts such as ca, ca_root, and dns. If any global cert_issuer options
617 // configure ACME issuers, those become the templates for the local shortcut
618 // configuration; otherwise, default ACME issuers are used.
619 func implicitACMEIssuers(h Helper, acmeIssuer *caddytls.ACMEIssuer) []certmagic.Issuer {
620 globalIssuers, _ := h.Option("cert_issuer").([]certmagic.Issuer)
621
622 var implicitIssuers []certmagic.Issuer
623 for _, issuer := range globalIssuers {
624 acmeWrapper, ok := issuer.(acmeCapable)
625 if !ok {
626 continue
627 }
628 baseIssuer := acmeWrapper.GetACMEIssuer()
629 if baseIssuer == nil {
630 continue
631 }
632 implicitIssuers = append(implicitIssuers, mergeACMEIssuers(baseIssuer, acmeIssuer))
633 }
634 if len(implicitIssuers) > 0 {
635 return implicitIssuers
636 }
637
638 // If an ACME CA endpoint was set locally, the user expects to use only that
639 // CA rather than the usual default fallback issuers.
640 defaultIssuers := caddytls.DefaultIssuers(acmeIssuer.Email)
641 if acmeIssuer.CA != "" {
642 defaultIssuers = []certmagic.Issuer{new(caddytls.ACMEIssuer)}
643 }
644
645 implicitIssuers = make([]certmagic.Issuer, 0, len(defaultIssuers))
646 for _, issuer := range defaultIssuers {
647 acmeWrapper, ok := issuer.(acmeCapable)
648 if !ok {
649 implicitIssuers = append(implicitIssuers, issuer)
650 continue
651 }
652 baseIssuer := acmeWrapper.GetACMEIssuer()
653 if baseIssuer == nil {
654 implicitIssuers = append(implicitIssuers, issuer)
655 continue
656 }
657 implicitIssuers = append(implicitIssuers, mergeACMEIssuers(baseIssuer, acmeIssuer))
658 }
659 return implicitIssuers
660 }
661
662 func mergeACMEIssuers(base, overrides *caddytls.ACMEIssuer) *caddytls.ACMEIssuer {
663 if base == nil {
664 return cloneACMEIssuer(overrides)
665 }
666
667 merged := cloneACMEIssuer(base)
668 if overrides == nil {
669 return merged
670 }
671
672 if overrides.CA != "" {
673 merged.CA = overrides.CA
674 }
675 if overrides.TestCA != "" {
676 merged.TestCA = overrides.TestCA
677 }
678 if overrides.Email != "" {
679 merged.Email = overrides.Email
680 }
681 if overrides.Profile != "" {
682 merged.Profile = overrides.Profile
683 }
684 if overrides.AccountKey != "" {
685 merged.AccountKey = overrides.AccountKey
686 }
687 if overrides.ExternalAccount != nil {
688 merged.ExternalAccount = cloneACMEEAB(overrides.ExternalAccount)
689 }
690 if overrides.ACMETimeout != 0 {
691 merged.ACMETimeout = overrides.ACMETimeout
692 }
693 if len(overrides.TrustedRootsPEMFiles) > 0 {
694 merged.TrustedRootsPEMFiles = appendUniqueStrings(merged.TrustedRootsPEMFiles, overrides.TrustedRootsPEMFiles...)
695 }
696 if overrides.PreferredChains != nil {
697 merged.PreferredChains = cloneChainPreference(overrides.PreferredChains)
698 }
699 if overrides.CertificateLifetime != 0 {
700 merged.CertificateLifetime = overrides.CertificateLifetime
701 }
702 if len(overrides.NetworkProxyRaw) > 0 {
703 merged.NetworkProxyRaw = slices.Clone(overrides.NetworkProxyRaw)
704 }
705 merged.Challenges = mergeChallengesConfig(merged.Challenges, overrides.Challenges)
706
707 return merged
708 }
709
710 func mergeChallengesConfig(base, overrides *caddytls.ChallengesConfig) *caddytls.ChallengesConfig {
711 if base == nil {
712 return cloneChallengesConfig(overrides)
713 }
714 merged := cloneChallengesConfig(base)
715 if overrides == nil {
716 return merged
717 }
718
719 merged.HTTP = mergeHTTPChallengeConfig(merged.HTTP, overrides.HTTP)
720 merged.TLSALPN = mergeTLSALPNChallengeConfig(merged.TLSALPN, overrides.TLSALPN)
721 merged.DNS = mergeDNSChallengeConfig(merged.DNS, overrides.DNS)
722 if overrides.BindHost != "" {
723 merged.BindHost = overrides.BindHost
724 }
725 if overrides.Distributed != nil {
726 value := *overrides.Distributed
727 merged.Distributed = &value
728 }
729
730 return merged
731 }
732
733 func mergeHTTPChallengeConfig(base, overrides *caddytls.HTTPChallengeConfig) *caddytls.HTTPChallengeConfig {
734 if base == nil {
735 return cloneHTTPChallengeConfig(overrides)
736 }
737 merged := cloneHTTPChallengeConfig(base)
738 if overrides == nil {
739 return merged
740 }
741
742 if overrides.Disabled {
743 merged.Disabled = true
744 }
745 if overrides.AlternatePort != 0 {
746 merged.AlternatePort = overrides.AlternatePort
747 }
748
749 return merged
750 }
751
752 func mergeTLSALPNChallengeConfig(base, overrides *caddytls.TLSALPNChallengeConfig) *caddytls.TLSALPNChallengeConfig {
753 if base == nil {
754 return cloneTLSALPNChallengeConfig(overrides)
755 }
756 merged := cloneTLSALPNChallengeConfig(base)
757 if overrides == nil {
758 return merged
759 }
760
761 if overrides.Disabled {
762 merged.Disabled = true
763 }
764 if overrides.AlternatePort != 0 {
765 merged.AlternatePort = overrides.AlternatePort
766 }
767
768 return merged
769 }
770
771 func mergeDNSChallengeConfig(base, overrides *caddytls.DNSChallengeConfig) *caddytls.DNSChallengeConfig {
772 if base == nil {
773 return cloneDNSChallengeConfig(overrides)
774 }
775 merged := cloneDNSChallengeConfig(base)
776 if overrides == nil {
777 return merged
778 }
779
780 if len(overrides.ProviderRaw) > 0 {
781 merged.ProviderRaw = slices.Clone(overrides.ProviderRaw)
782 }
783 if overrides.PropagationDelay != 0 {
784 merged.PropagationDelay = overrides.PropagationDelay
785 }
786 if overrides.PropagationTimeout != 0 {
787 merged.PropagationTimeout = overrides.PropagationTimeout
788 }
789 if overrides.Resolvers != nil {
790 merged.Resolvers = slices.Clone(overrides.Resolvers)
791 }
792 if overrides.OverrideDomain != "" {
793 merged.OverrideDomain = overrides.OverrideDomain
794 }
795 if overrides.TTL != 0 {
796 merged.TTL = overrides.TTL
797 }
798
799 return merged
800 }
801
802 func cloneACMEIssuer(iss *caddytls.ACMEIssuer) *caddytls.ACMEIssuer {
803 if iss == nil {
804 return nil
805 }
806
807 cloned := *iss
808 cloned.Challenges = cloneChallengesConfig(iss.Challenges)
809 cloned.ExternalAccount = cloneACMEEAB(iss.ExternalAccount)
810 cloned.TrustedRootsPEMFiles = slices.Clone(iss.TrustedRootsPEMFiles)
811 cloned.PreferredChains = cloneChainPreference(iss.PreferredChains)
812 cloned.NetworkProxyRaw = slices.Clone(iss.NetworkProxyRaw)
813
814 return &cloned
815 }
816
817 func cloneChallengesConfig(cfg *caddytls.ChallengesConfig) *caddytls.ChallengesConfig {
818 if cfg == nil {
819 return nil
820 }
821
822 cloned := *cfg
823 cloned.HTTP = cloneHTTPChallengeConfig(cfg.HTTP)
824 cloned.TLSALPN = cloneTLSALPNChallengeConfig(cfg.TLSALPN)
825 cloned.DNS = cloneDNSChallengeConfig(cfg.DNS)
826 if cfg.Distributed != nil {
827 value := *cfg.Distributed
828 cloned.Distributed = &value
829 }
830
831 return &cloned
832 }
833
834 func cloneHTTPChallengeConfig(cfg *caddytls.HTTPChallengeConfig) *caddytls.HTTPChallengeConfig {
835 if cfg == nil {
836 return nil
837 }
838
839 cloned := *cfg
840 return &cloned
841 }
842
843 func cloneTLSALPNChallengeConfig(cfg *caddytls.TLSALPNChallengeConfig) *caddytls.TLSALPNChallengeConfig {
844 if cfg == nil {
845 return nil
846 }
847
848 cloned := *cfg
849 return &cloned
850 }
851
852 func cloneDNSChallengeConfig(cfg *caddytls.DNSChallengeConfig) *caddytls.DNSChallengeConfig {
853 if cfg == nil {
854 return nil
855 }
856
857 cloned := *cfg
858 cloned.ProviderRaw = slices.Clone(cfg.ProviderRaw)
859 cloned.Resolvers = slices.Clone(cfg.Resolvers)
860
861 return &cloned
862 }
863
864 func cloneACMEEAB(eab *acme.EAB) *acme.EAB {
865 if eab == nil {
866 return nil
867 }
868
869 cloned := *eab
870 return &cloned
871 }
872
873 func cloneChainPreference(pref *caddytls.ChainPreference) *caddytls.ChainPreference {
874 if pref == nil {
875 return nil
876 }
877
878 cloned := *pref
879 cloned.RootCommonName = slices.Clone(pref.RootCommonName)
880 cloned.AnyCommonName = slices.Clone(pref.AnyCommonName)
881 if pref.Smallest != nil {
882 value := *pref.Smallest
883 cloned.Smallest = &value
884 }
885
886 return &cloned
887 }
888
889 func appendUniqueStrings(existing []string, additions ...string) []string {
890 for _, value := range additions {
891 if !slices.Contains(existing, value) {
892 existing = append(existing, value)
893 }
894 }
895 return existing
896 }
897
898 // newBaseAutomationPolicy returns a new TLS automation policy that gets
899 // its values from the global options map. It should be used as the base
900 // for any other automation policies. A nil policy (and no error) will be
901 // returned if there are no default/global options. However, if always is
902 // true, a non-nil value will always be returned (unless there is an error).
903 func newBaseAutomationPolicy(
904 options map[string]any,
905 _ []caddyconfig.Warning,
906 always bool,
907 ) (*caddytls.AutomationPolicy, error) {
908 issuers, hasIssuers := options["cert_issuer"]
909 _, hasLocalCerts := options["local_certs"]
910 keyType, hasKeyType := options["key_type"]
911 ocspStapling, hasOCSPStapling := options["ocsp_stapling"]
912 renewalWindowRatio, hasRenewalWindowRatio := options["renewal_window_ratio"]
913 hasGlobalAutomationOpts := hasIssuers || hasLocalCerts || hasKeyType || hasOCSPStapling || hasRenewalWindowRatio
914
915 globalACMECA := options["acme_ca"]
916 globalACMECARoot := options["acme_ca_root"]
917 _, globalACMEDNS := options["acme_dns"] // can be set to nil (to use globally-defined "dns" value instead), but it is still set
918 globalACMEEAB := options["acme_eab"]
919 globalPreferredChains := options["preferred_chains"]
920 hasGlobalACMEDefaults := globalACMECA != nil || globalACMECARoot != nil || globalACMEDNS || globalACMEEAB != nil || globalPreferredChains != nil
921
922 // if there are no global options related to automation policies
923 // set, then we can just return right away
924 if !hasGlobalAutomationOpts && !hasGlobalACMEDefaults {
925 if always {
926 return new(caddytls.AutomationPolicy), nil
927 }
928 return nil, nil
929 }
930
931 ap := new(caddytls.AutomationPolicy)
932 if hasKeyType {
933 ap.KeyType = keyType.(string)
934 }
935
936 if hasIssuers && hasLocalCerts {
937 return nil, fmt.Errorf("global options are ambiguous: local_certs is confusing when combined with cert_issuer, because local_certs is also a specific kind of issuer")
938 }
939
940 if hasIssuers {
941 ap.Issuers = issuers.([]certmagic.Issuer)
942 } else if hasLocalCerts {
943 ap.Issuers = []certmagic.Issuer{new(caddytls.InternalIssuer)}
944 }
945
946 if hasGlobalACMEDefaults {
947 for i := range ap.Issuers {
948 if err := fillInGlobalACMEDefaults(ap.Issuers[i], options); err != nil {
949 return nil, fmt.Errorf("filling in global issuer defaults for issuer %d: %v", i, err)
950 }
951 }
952 }
953
954 if hasOCSPStapling {
955 ocspConfig := ocspStapling.(certmagic.OCSPConfig)
956 ap.DisableOCSPStapling = ocspConfig.DisableStapling
957 ap.OCSPOverrides = ocspConfig.ResponderOverrides
958 }
959
960 if hasRenewalWindowRatio {
961 ap.RenewalWindowRatio = renewalWindowRatio.(float64)
962 }
963
964 return ap, nil
965 }
966
967 // consolidateAutomationPolicies combines automation policies that are the same,
968 // for a cleaner overall output.
969 func consolidateAutomationPolicies(aps []*caddytls.AutomationPolicy) []*caddytls.AutomationPolicy {
970 // sort from most specific to least specific; we depend on this ordering
971 sort.SliceStable(aps, func(i, j int) bool {
972 if automationPolicyIsSubset(aps[i], aps[j]) {
973 return true
974 }
975 if automationPolicyIsSubset(aps[j], aps[i]) {
976 return false
977 }
978 return len(aps[i].SubjectsRaw) > len(aps[j].SubjectsRaw)
979 })
980
981 emptyAPCount := 0
982 origLenAPs := len(aps)
983 // compute the number of empty policies (disregarding subjects) - see #4128
984 // while we're at it,
985 emptyAP := new(caddytls.AutomationPolicy)
986 for i := 0; i < len(aps); i++ {
987 emptyAP.SubjectsRaw = aps[i].SubjectsRaw
988 emptyAP.ManagersRaw = nil
989 if reflect.DeepEqual(aps[i], emptyAP) {
990 // AP is empty
991 emptyAPCount++
992
993 // see if this AP shadows something later
994 shadowIdx := automationPolicyShadows(i, aps)
995 emptyAP.SubjectsRaw = nil
996 if shadowIdx >= 0 {
997 emptyAP.SubjectsRaw = aps[shadowIdx].SubjectsRaw
998 // allow the later policy, which is likely for a wildcard, to have cert
999 // managers ("get_certificate"), since wildcards now cover specific
1000 // subdomains by default, when configured (see discussion in #7559)
1001 emptyAP.ManagersRaw = aps[shadowIdx].ManagersRaw
1002 }
1003
1004 // if this is the last AP, we can delete it, since auto-https should
1005 // pick it up; if it shadows something later that is also empty, we
1006 // can similarly delete this; but if it shadows something that is NOT
1007 // empty, we must not delete it since the shadowing has a purpose
1008 if i == len(aps)-1 || (shadowIdx >= 0 && reflect.DeepEqual(aps[shadowIdx], emptyAP)) {
1009 aps = slices.Delete(aps, i, i+1)
1010 i--
1011 }
1012 }
1013 }
1014 // If all policies are empty, we can return nil, as there is no need to set any policy
1015 if emptyAPCount == origLenAPs {
1016 return nil
1017 }
1018
1019 // remove or combine duplicate policies
1020 outer:
1021 for i := 0; i < len(aps); i++ {
1022 // compare only with next policies; we sorted by specificity so we must not delete earlier policies
1023 for j := i + 1; j < len(aps); j++ {
1024 // if they're exactly equal in every way, just keep one of them
1025 if reflect.DeepEqual(aps[i], aps[j]) {
1026 aps = slices.Delete(aps, j, j+1)
1027 // must re-evaluate current i against next j; can't skip it!
1028 // even if i decrements to -1, will be incremented to 0 immediately
1029 i--
1030 continue outer
1031 }
1032
1033 // if the policy is the same, we can keep just one, but we have
1034 // to be careful which one we keep; if only one has any hostnames
1035 // defined, then we need to keep the one without any hostnames,
1036 // otherwise the one without any subjects (a catch-all) would be
1037 // eaten up by the one with subjects; and if both have subjects, we
1038 // need to combine their lists
1039 if automationPoliciesHaveSameIssuers(aps[i], aps[j]) &&
1040 reflect.DeepEqual(aps[i].ManagersRaw, aps[j].ManagersRaw) &&
1041 bytes.Equal(aps[i].StorageRaw, aps[j].StorageRaw) &&
1042 aps[i].MustStaple == aps[j].MustStaple &&
1043 aps[i].KeyType == aps[j].KeyType &&
1044 aps[i].OnDemand == aps[j].OnDemand &&
1045 aps[i].ReusePrivateKeys == aps[j].ReusePrivateKeys &&
1046 aps[i].RenewalWindowRatio == aps[j].RenewalWindowRatio {
1047 if len(aps[i].SubjectsRaw) > 0 && len(aps[j].SubjectsRaw) == 0 {
1048 // later policy (at j) has no subjects ("catch-all"), so we can
1049 // remove the identical-but-more-specific policy that comes first
1050 // AS LONG AS it is not shadowed by another policy before it; e.g.
1051 // if policy i is for example.com, policy i+1 is '*.com', and policy
1052 // j is catch-all, we cannot remove policy i because that would
1053 // cause example.com to be served by the less specific policy for
1054 // '*.com', which might be different (yes we've seen this happen)
1055 if automationPolicyShadows(i, aps) >= j {
1056 aps = slices.Delete(aps, i, i+1)
1057 i--
1058 continue outer
1059 }
1060 } else {
1061 // avoid repeated subjects
1062 for _, subj := range aps[j].SubjectsRaw {
1063 if !slices.Contains(aps[i].SubjectsRaw, subj) {
1064 aps[i].SubjectsRaw = append(aps[i].SubjectsRaw, subj)
1065 }
1066 }
1067 aps = slices.Delete(aps, j, j+1)
1068 j--
1069 }
1070 }
1071 }
1072 }
1073
1074 return aps
1075 }
1076
1077 // automationPolicyIsSubset returns true if a's subjects are a subset
1078 // of b's subjects.
1079 func automationPolicyIsSubset(a, b *caddytls.AutomationPolicy) bool {
1080 if len(b.SubjectsRaw) == 0 {
1081 return true
1082 }
1083 if len(a.SubjectsRaw) == 0 {
1084 return false
1085 }
1086 for _, aSubj := range a.SubjectsRaw {
1087 inSuperset := slices.ContainsFunc(b.SubjectsRaw, func(bSubj string) bool {
1088 return certmagic.MatchWildcard(aSubj, bSubj)
1089 })
1090 if !inSuperset {
1091 return false
1092 }
1093 }
1094 return true
1095 }
1096
1097 // automationPolicyShadows returns the index of a policy that aps[i] shadows;
1098 // in other words, for all policies after position i, if that policy covers
1099 // the same subjects but is less specific, that policy's position is returned,
1100 // or -1 if no shadowing is found. For example, if policy i is for
1101 // "foo.example.com" and policy i+2 is for "*.example.com", then i+2 will be
1102 // returned, since that policy is shadowed by i, which is in front.
1103 func automationPolicyShadows(i int, aps []*caddytls.AutomationPolicy) int {
1104 for j := i + 1; j < len(aps); j++ {
1105 if automationPolicyIsSubset(aps[i], aps[j]) {
1106 return j
1107 }
1108 }
1109 return -1
1110 }
1111
1112 // subjectQualifiesForPublicCert is like certmagic.SubjectQualifiesForPublicCert() except
1113 // that this allows domains with multiple wildcard levels like '*.*.example.com' to qualify
1114 // if the automation policy has OnDemand enabled (i.e. this function is more lenient).
1115 //
1116 // IP subjects are considered as non-qualifying for public certs. Technically, there are
1117 // now public ACME CAs as well as non-ACME CAs that issue IP certificates. But this function
1118 // is used solely for implicit automation (defaults), where it gets really complicated to
1119 // keep track of which issuers support IP certificates in which circumstances. Currently,
1120 // issuers that support IP certificates are very few, and all require some sort of config
1121 // from the user anyway (such as an account credential). Since we cannot implicitly and
1122 // automatically get public IP certs without configuration from the user, we treat IPs as
1123 // not qualifying for public certificates. Users should expressly configure an issuer
1124 // that supports IP certs for that purpose.
1125 func subjectQualifiesForPublicCert(ap *caddytls.AutomationPolicy, subj string) bool {
1126 return !certmagic.SubjectIsIP(subj) &&
1127 !certmagic.SubjectIsInternal(subj) &&
1128 (strings.Count(subj, "*.") < 2 || ap.OnDemand)
1129 }
1130
1131 func automationPoliciesHaveSameIssuers(a, b *caddytls.AutomationPolicy) bool {
1132 if reflect.DeepEqual(a.IssuersRaw, b.IssuersRaw) {
1133 return automationPoliciesHaveCompatibleImplicitIssuers(a, b)
1134 }
1135 return automationPolicyUsesDefaultInternalIssuer(a) && automationPolicyUsesDefaultInternalIssuer(b)
1136 }
1137
1138 func automationPolicyUsesDefaultInternalIssuer(ap *caddytls.AutomationPolicy) bool {
1139 if len(ap.IssuersRaw) == 0 && len(ap.Issuers) == 0 {
1140 return automationPolicyImplicitIssuerClass(ap) == "internal"
1141 }
1142 return len(ap.IssuersRaw) == 1 &&
1143 len(ap.Issuers) == 0 &&
1144 string(bytes.TrimSpace(ap.IssuersRaw[0])) == `{"module":"internal"}`
1145 }
1146
1147 // automationPoliciesHaveCompatibleImplicitIssuers returns whether two policies
1148 // without explicit issuers can be consolidated without changing default issuer
1149 // selection for their subjects.
1150 func automationPoliciesHaveCompatibleImplicitIssuers(a, b *caddytls.AutomationPolicy) bool {
1151 if len(a.IssuersRaw) > 0 || len(a.Issuers) > 0 ||
1152 len(b.IssuersRaw) > 0 || len(b.Issuers) > 0 {
1153 return true
1154 }
1155
1156 aClass := automationPolicyImplicitIssuerClass(a)
1157 bClass := automationPolicyImplicitIssuerClass(b)
1158 return aClass == "catch-all" || bClass == "catch-all" || aClass == bClass
1159 }
1160
1161 func automationPolicyImplicitIssuerClass(ap *caddytls.AutomationPolicy) string {
1162 if len(ap.SubjectsRaw) == 0 {
1163 return "catch-all"
1164 }
1165
1166 hasPublic := slices.ContainsFunc(ap.SubjectsRaw, func(subj string) bool {
1167 return subjectQualifiesForPublicCert(ap, subj)
1168 })
1169 hasInternal := slices.ContainsFunc(ap.SubjectsRaw, func(subj string) bool {
1170 return !subjectQualifiesForPublicCert(ap, subj)
1171 })
1172
1173 switch {
1174 case hasPublic && hasInternal:
1175 return "mixed"
1176 case hasPublic:
1177 return "public"
1178 default:
1179 return "internal"
1180 }
1181 }
1182
1183 // automationPolicyHasAllPublicNames returns true if all the names on the policy
1184 // do NOT qualify for public certs OR are tailscale domains.
1185 func automationPolicyHasAllPublicNames(ap *caddytls.AutomationPolicy) bool {
1186 return !slices.ContainsFunc(ap.SubjectsRaw, func(i string) bool {
1187 return !subjectQualifiesForPublicCert(ap, i) || isTailscaleDomain(i)
1188 })
1189 }
1190
1191 func isTailscaleDomain(name string) bool {
1192 return strings.HasSuffix(strings.ToLower(name), ".ts.net")
1193 }