certmagic Documentation

Automatic HTTPS for any Go program: fully-managed TLS certificate issuance and renewal

5,610 stars Go Go 2 files ยท ~14,286 tokens #acme#automatic-https#go#golang#https#letsencrypt#tls#tls-certificate
RAW Doc

File: README.md

Easy and Powerful TLS Automation

Caddy's automagic TLS features—now for your own Go programs—in one powerful and easy-to-use library!

CertMagic is the most mature, robust, and powerful ACME client integration for Go... and perhaps ever.

With CertMagic, you can add one line to your Go application to serve securely over TLS, without ever having to touch certificates.

Instead of:

go
// plaintext HTTP, gross ๐Ÿคข
http.ListenAndServe(":80", mux)

Use CertMagic:

go
// encrypted HTTPS with HTTP->HTTPS redirects - yay! ๐Ÿ”’๐Ÿ˜
certmagic.HTTPS([]string{"example.com"}, mux)

That line of code will serve your HTTP router mux over HTTPS, complete with HTTP->HTTPS redirects. It obtains and renews the TLS certificates. It staples OCSP responses for greater privacy and security. As long as your domain name points to your server, CertMagic will keep its connections secure.

Compared to other ACME client libraries for Go, only CertMagic supports the full suite of ACME features, and no other library matches CertMagic's maturity and reliability.

CertMagic - Automatic HTTPS using Let's Encrypt

Features

  • Fully automated certificate management including issuance and renewal
  • One-line, fully managed HTTPS servers
  • Full control over almost every aspect of the system
  • HTTP->HTTPS redirects
  • Multiple issuers supported: get certificates from multiple sources/CAs for redundancy and resiliency
  • Solves all 3 common ACME challenges: HTTP, TLS-ALPN, and DNS (and capable of others)
  • Most robust error handling of any ACME client
    • Challenges are randomized to avoid accidental dependence
    • Challenges are rotated to overcome certain network blockages
    • Robust retries for up to 30 days
    • Exponential backoff with carefully-tuned intervals
    • Retries with optional test/staging CA endpoint instead of production, to avoid rate limits
  • Written in Go, a language with memory-safety guarantees
  • Powered by ACMEz, the premier ACME client library for Go
  • All libdns DNS providers work out-of-the-box
  • Pluggable storage backends (default: file system)
  • Pluggable key sources
  • Wildcard certificates
  • Automatic OCSP stapling (done right) keeps your sites online!
  • Distributed solving of all challenges (works behind load balancers)
    • Highly efficient, coordinated management in a fleet
    • Active locking
    • Smart queueing
  • Supports "on-demand" issuance of certificates (during TLS handshakes!)
    • Caddy / CertMagic pioneered this technology
    • Custom decision functions to regulate and throttle on-demand behavior
  • Optional event hooks for observation
  • One-time private keys by default (new key for each cert) to discourage pinning and reduce scope of key compromise
  • Works with any certificate authority (CA) compliant with the ACME specification RFC 8555
  • Certificate revocation (please, only if private key is compromised)
  • Must-Staple (optional; not default)
  • Cross-platform support! Mac, Windows, Linux, BSD, Android...
  • Scales to hundreds of thousands of names/certificates per instance
  • Use in conjunction with your own certificates
  • Full support for RFC 9773 (ACME Renewal Information; ARI) extension

Requirements

  1. ACME server (can be a publicly-trusted CA, or your own)
  2. Public DNS name(s) you control
  3. Server reachable from public Internet
    • Or use the DNS challenge to waive this requirement
  4. Control over port 80 (HTTP) and/or 443 (HTTPS)
    • Or they can be forwarded to other ports you control
    • Or use the DNS challenge to waive this requirement
    • (This is a requirement of the ACME protocol, not a library limitation)
  5. Persistent storage
    • Typically the local file system (default)
    • Other integrations available/possible
  6. Go 1.21 or newer

Before using this library, your domain names MUST be pointed (A/AAAA records) at your server (unless you use the DNS challenge)!

Installation

bash
$ go get github.com/caddyserver/certmagic

Usage

Package Overview

Certificate authority

This library uses Let's Encrypt by default, but you can use any certificate authority that conforms to the ACME specification. Known/common CAs are provided as consts in the package, for example LetsEncryptStagingCA and LetsEncryptProductionCA.

The `Config` type

The certmagic.Config struct is how you can wield the power of this fully armed and operational battle station. However, an empty/uninitialized Config is not a valid one! In time, you will learn to use the force of certmagic.NewDefault() as I have.

Defaults

The default Config value is called certmagic.Default. Change its fields to suit your needs, then call certmagic.NewDefault() when you need a valid Config value. In other words, certmagic.Default is a template and is not valid for use directly.

You can set the default values easily, for example: certmagic.Default.Issuer = ....

Similarly, to configure ACME-specific defaults, use certmagic.DefaultACME.

The high-level functions in this package (HTTPS(), Listen(), ManageSync(), and ManageAsync()) use the default config exclusively. This is how most of you will interact with the package. This is suitable when all your certificates are managed the same way. However, if you need to manage certificates differently depending on their name, you will need to make your own cache and configs (keep reading).

Providing an email address

Although not strictly required, this is highly recommended best practice. It allows you to receive expiration emails if your certificates are expiring for some reason, and also allows the CA's engineers to potentially get in touch with you if something is wrong. I recommend setting certmagic.DefaultACME.Email or always setting the Email field of a new Config struct.

Rate limiting

To avoid firehosing the CA's servers, CertMagic has built-in rate limiting. Currently, its default limit is up to 10 transactions (obtain or renew) every 1 minute (sliding window). This can be changed by setting the RateLimitEvents and RateLimitEventsWindow variables, if desired.

The CA may still enforce their own rate limits, and there's nothing (well, nothing ethical) CertMagic can do to bypass them for you.

Additionally, CertMagic will retry failed validations with exponential backoff for up to 30 days, with a reasonable maximum interval between attempts (an "attempt" means trying each enabled challenge type once).

Development and Testing

Note that Let's Encrypt imposes strict rate limits at its production endpoint, so using it while developing your application may lock you out for a few days if you aren't careful!

While developing your application and testing it, use their staging endpoint which has much higher rate limits. Even then, don't hammer it: but it's much safer for when you're testing. When deploying, though, use their production CA because their staging CA doesn't issue trusted certificates.

To use staging, set certmagic.DefaultACME.CA = certmagic.LetsEncryptStagingCA or set CA of every ACMEIssuer struct.

Examples

There are many ways to use this library. We'll start with the highest-level (simplest) and work down (more control).

All these high-level examples use certmagic.Default and certmagic.DefaultACME for the config and the default cache and storage for serving up certificates.

First, we'll follow best practices and do the following:

go
// read and agree to your CA's legal documents
certmagic.DefaultACME.Agreed = true

// provide an email address
certmagic.DefaultACME.Email = "[email protected]"

// use the staging endpoint while we're developing
certmagic.DefaultACME.CA = certmagic.LetsEncryptStagingCA

For fully-functional program examples, check out this X thread (or read it unrolled into a single post). (Note that the package API has changed slightly since these posts.)

Serving HTTP handlers with HTTPS

go
err := certmagic.HTTPS([]string{"example.com", "www.example.com"}, mux)
if err != nil {
	return err
}

This starts HTTP and HTTPS listeners and redirects HTTP to HTTPS!

Starting a TLS listener

go
ln, err := certmagic.Listen([]string{"example.com"})
if err != nil {
	return err
}

Getting a tls.Config

go
tlsConfig, err := certmagic.TLS([]string{"example.com"})
if err != nil {
	return err
}
// be sure to customize NextProtos if serving a specific
// application protocol after the TLS handshake, for example:
tlsConfig.NextProtos = append([]string{"h2", "http/1.1"}, tlsConfig.NextProtos...)

Advanced use

For more control (particularly, if you need a different way of managing each certificate), you'll make and use a Cache and a Config like so:

go
// First make a pointer to a Cache as we need to reference the same Cache in
// GetConfigForCert below.
var cache *certmagic.Cache
cache = certmagic.NewCache(certmagic.CacheOptions{
	GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) {
		// Here we use New to get a valid Config associated with the same cache.
		// The provided Config is used as a template and will be completed with
		// any defaults that are set in the Default config.
		return certmagic.New(cache, certmagic.Config{
			// ...
		}), nil
	},
	...
})

magic := certmagic.New(cache, certmagic.Config{
	// any customizations you need go here
})

myACME := certmagic.NewACMEIssuer(magic, certmagic.ACMEIssuer{
	CA:     certmagic.LetsEncryptStagingCA,
	Email:  "[email protected]",
	Agreed: true,
	// plus any other customizations you need
})

magic.Issuers = []certmagic.Issuer{myACME}

// this obtains certificates or renews them if necessary
err := magic.ManageSync(context.TODO(), []string{"example.com", "sub.example.com"})
if err != nil {
	return err
}

// to use its certificates and solve the TLS-ALPN challenge,
// you can get a TLS config to use in a TLS listener!
tlsConfig := magic.TLSConfig()

// be sure to customize NextProtos if serving a specific
// application protocol after the TLS handshake, for example:
tlsConfig.NextProtos = append([]string{"h2", "http/1.1"}, tlsConfig.NextProtos...)

//// OR ////

// if you already have a TLS config you don't want to replace,
// we can simply set its GetCertificate field and append the
// TLS-ALPN challenge protocol to the NextProtos
myTLSConfig.GetCertificate = magic.GetCertificate
myTLSConfig.NextProtos = append(myTLSConfig.NextProtos, acmez.ACMETLS1Protocol)

// the HTTP challenge has to be handled by your HTTP server;
// if you don't have one, you should have disabled it earlier
// when you made the certmagic.Config
httpMux = myACME.HTTPChallengeHandler(httpMux)

Great! This example grants you much more flexibility for advanced programs. However, the vast majority of you will only use the high-level functions described earlier, especially since you can still customize them by setting the package-level Default config.

Wildcard certificates

At time of writing (December 2018), Let's Encrypt only issues wildcard certificates with the DNS challenge. You can easily enable the DNS challenge with CertMagic for numerous providers (see the relevant section in the docs).

Behind a load balancer (or in a cluster)

CertMagic runs effectively behind load balancers and/or in cluster/fleet environments. In other words, you can have 10 or 1,000 servers all serving the same domain names, all sharing certificates and OCSP staples.

To do so, simply ensure that each instance is using the same Storage. That is the sole criteria for determining whether an instance is part of a cluster.

The default Storage is implemented using the file system, so mounting the same shared folder is sufficient (see Storage for more on that)! If you need an alternate Storage implementation, feel free to use one, provided that all the instances use the same one. :)

See Storage and the associated pkg.go.dev for more information!

The ACME Challenges

This section describes how to solve the ACME challenges. Challenges are how you demonstrate to the certificate authority some control over your domain name, thus authorizing them to grant you a certificate for that name. The great innovation of ACME is that verification by CAs can now be automated, rather than having to click links in emails (who ever thought that was a good idea??).

If you're using the high-level convenience functions like HTTPS(), Listen(), or TLS(), the HTTP and/or TLS-ALPN challenges are solved for you because they also start listeners. However, if you're making a Config and you start your own server manually, you'll need to be sure the ACME challenges can be solved so certificates can be renewed.

The HTTP and TLS-ALPN challenges are the defaults because they don't require configuration from you, but they require that your server is accessible from external IPs on low ports. If that is not possible in your situation, you can enable the DNS challenge, which will disable the HTTP and TLS-ALPN challenges and use the DNS challenge exclusively.

Technically, only one challenge needs to be enabled for things to work, but using multiple is good for reliability in case a challenge is discontinued by the CA. This happened to the TLS-SNI challenge in early 2018—many popular ACME clients such as Traefik and Autocert broke, resulting in downtime for some sites, until new releases were made and patches deployed, because they used only one challenge; Caddy, however—this library's forerunner—was unaffected because it also used the HTTP challenge. If multiple challenges are enabled, they are chosen randomly to help prevent false reliance on a single challenge type. And if one fails, any remaining enabled challenges are tried before giving up.

HTTP Challenge

Per the ACME spec, the HTTP challenge requires port 80, or at least packet forwarding from port 80. It works by serving a specific HTTP response that only the genuine server would have to a normal HTTP request at a special endpoint.

If you are running an HTTP server, solving this challenge is very easy: just wrap your handler in HTTPChallengeHandler or call SolveHTTPChallenge() inside your own ServeHTTP() method.

For example, if you're using the standard library:

go
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "Lookit my cool website over HTTPS!")
})

http.ListenAndServe(":80", myACME.HTTPChallengeHandler(mux))

If wrapping your handler is not a good solution, try this inside your ServeHTTP() instead:

go
magic := certmagic.NewDefault()
myACME := certmagic.NewACMEIssuer(magic, certmagic.DefaultACME)

func ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if myACME.HandleHTTPChallenge(w, r) {
		return // challenge handled; nothing else to do
	}
	...
}

If you are not running an HTTP server, you should disable the HTTP challenge or run an HTTP server whose sole job it is to solve the HTTP challenge.

TLS-ALPN Challenge

Per the ACME spec, the TLS-ALPN challenge requires port 443, or at least packet forwarding from port 443. It works by providing a special certificate using a standard TLS extension, Application Layer Protocol Negotiation (ALPN), having a special value. This is the most convenient challenge type because it usually requires no extra configuration and uses the standard TLS port which is where the certificates are used, also.

This challenge is easy to solve: just use the provided tls.Config when you make your TLS listener:

go
// use this to configure a TLS listener
tlsConfig := magic.TLSConfig()

Or make two simple changes to an existing tls.Config:

go
myTLSConfig.GetCertificate = magic.GetCertificate
myTLSConfig.NextProtos = append(myTLSConfig.NextProtos, acmez.ACMETLS1Protocol}

Then just make sure your TLS listener is listening on port 443:

go
ln, err := tls.Listen("tcp", ":443", myTLSConfig)

DNS Challenge

The DNS challenge is perhaps the most useful challenge because it allows you to obtain certificates without your server needing to be publicly accessible on the Internet, and it's the only challenge by which Let's Encrypt will issue wildcard certificates.

This challenge works by setting a special record in the domain's zone. To do this automatically, your DNS provider needs to offer an API by which changes can be made to domain names, and the changes need to take effect immediately for best results. CertMagic supports all DNS providers with libdns implementations! It always cleans up the temporary record after the challenge completes.

To enable it, just set the DNS01Solver field on a certmagic.ACMEIssuer struct, or set the default certmagic.ACMEIssuer.DNS01Solver variable. For example, if my domains' DNS was served by Cloudflare:

go
import "github.com/libdns/cloudflare"

certmagic.DefaultACME.DNS01Solver = &certmagic.DNS01Solver{
	DNSManager: certmagic.DNSManager{
		DNSProvider: &cloudflare.Provider{
			APIToken: "topsecret",
		},
	},
}

Now the DNS challenge will be used by default, and I can obtain certificates for wildcard domains, too. Enabling the DNS challenge disables the other challenges for that certmagic.ACMEIssuer instance.

On-Demand TLS

Normally, certificates are obtained and renewed before a listener starts serving, and then those certificates are maintained throughout the lifetime of the program. In other words, the certificate names are static. But sometimes you don't know all the names ahead of time, or you don't want to manage all the certificates up front. This is where On-Demand TLS shines.

Originally invented for use in Caddy (which was the first program to use such technology), On-Demand TLS makes it possible and easy to serve certificates for arbitrary or specific names during the lifetime of the server. When a TLS handshake is received, CertMagic will read the Server Name Indication (SNI) value and either load and present that certificate in the ServerHello, or if one does not exist, it will obtain it from a CA right then-and-there.

Of course, this has some obvious security implications. You don't want to DoS a CA or allow arbitrary clients to fill your storage with spammy TLS handshakes. That's why, when you enable On-Demand issuance, you should set limits or policy to allow getting certificates. CertMagic has an implicit whitelist built-in which is sufficient for nearly everyone, but also has a more advanced way to control on-demand issuance.

The simplest way to enable on-demand issuance is to set the OnDemand field of a Config (or the default package-level value):

go
certmagic.Default.OnDemand = new(certmagic.OnDemandConfig)

By setting this to a non-nil value, on-demand TLS is enabled for that config. For convenient security, CertMagic's high-level abstraction functions such as HTTPS(), TLS(), ManageSync(), ManageAsync(), and Listen() (which all accept a list of domain names) will whitelist those names automatically so only certificates for those names can be obtained when using the Default config. Usually this is sufficient for most users.

However, if you require advanced control over which domains can be issued certificates on-demand (for example, if you do not know which domain names you are managing, or just need to defer their operations until later), you should implement your own DecisionFunc:

go
// if the decision function returns an error, a certificate
// may not be obtained for that name at that time
certmagic.Default.OnDemand = &certmagic.OnDemandConfig{
	DecisionFunc: func(name string) error {
		if name != "example.com" {
			return fmt.Errorf("not allowed")
		}
		return nil
	},
}

The pkg.go.dev describes how to use this in full detail, so please check it out!

Storage

CertMagic relies on storage to store certificates and other TLS assets (OCSP staple cache, coordinating locks, etc). Persistent storage is a requirement when using CertMagic: ephemeral storage will likely lead to rate limiting on the CA-side as CertMagic will always have to get new certificates.

By default, CertMagic stores assets on the local file system in $HOME/.local/share/certmagic (and honors $XDG_DATA_HOME if set). CertMagic will create the directory if it does not exist. If writes are denied, things will not be happy, so make sure CertMagic can write to it!

The notion of a "cluster" or "fleet" of instances that may be serving the same site and sharing certificates, etc, is tied to storage. Simply, any instances that use the same storage facilities are considered part of the cluster. So if you deploy 100 instances of CertMagic behind a load balancer, they are all part of the same cluster if they share the same storage configuration. Sharing storage could be mounting a shared folder, or implementing some other distributed storage system such as a database server or KV store.

The easiest way to change the storage being used is to set certmagic.Default.Storage to a value that satisfies the Storage interface. Keep in mind that a valid Storage must be able to implement some operations atomically in order to provide locking and synchronization.

If you write a Storage implementation, please add it to the project wiki so people can find it!

Cache

All of the certificates in use are de-duplicated and cached in memory for optimal performance at handshake-time. This cache must be backed by persistent storage as described above.

Most applications will not need to interact with certificate caches directly. Usually, the closest you will come is to set the package-wide certmagic.Default.Storage variable (before attempting to create any Configs) which defines how the cache is persisted. However, if your use case requires using different storage facilities for different Configs (that's highly unlikely and NOT recommended! Even Caddy doesn't get that crazy), you will need to call certmagic.NewCache() and pass in the storage you want to use, then get new Config structs with certmagic.NewWithCache() and pass in the cache.

Again, if you're needing to do this, you've probably over-complicated your application design.

Events

(Events are new and still experimental, so they may change.)

CertMagic emits events when possible things of interest happen. Set the OnEvent field of your Config to subscribe to events; ignore the ones you aren't interested in. Here are the events currently emitted along with their metadata you can use:

  • cached_unmanaged_cert An unmanaged certificate was cached
    • sans: The subject names on the certificate
  • cert_obtaining A certificate is about to be obtained
    • renewal: Whether this is a renewal
    • identifier: The name on the certificate
    • forced: Whether renewal is being forced (if renewal)
    • remaining: Time left on the certificate (if renewal)
    • issuer: The previous or current issuer
  • cert_obtained A certificate was successfully obtained
    • renewal: Whether this is a renewal
    • identifier: The name on the certificate
    • remaining: Time left on the certificate (if renewal)
    • issuer: The previous or current issuer
    • storage_path: The path to the folder containing the cert resources within storage
    • private_key_path: The path to the private key file in storage
    • certificate_path: The path to the public key file in storage
    • metadata_path: The path to the metadata file in storage
  • cert_failed An attempt to obtain a certificate failed
    • renewal: Whether this is a renewal
    • identifier: The name on the certificate
    • remaining: Time left on the certificate (if renewal)
    • issuers: The issuer(s) tried
    • error: The (final) error message
  • tls_get_certificate The GetCertificate phase of a TLS handshake is under way
    • client_hello: The tls.ClientHelloInfo struct
  • cert_ocsp_revoked A certificate's OCSP indicates it has been revoked
    • subjects: The subject names on the certificate
    • certificate: The Certificate struct
    • reason: The OCSP revocation reason
    • revoked_at: When the certificate was revoked

OnEvent can return an error. Some events may be aborted by returning an error. For example, returning an error from cert_obtained can cancel obtaining the certificate. Only return an error from OnEvent if you want to abort program flow.

ZeroSSL

ZeroSSL has both ACME and HTTP API services for getting certificates. CertMagic works with both of them.

To use ZeroSSL's ACME server, configure CertMagic with an ACMEIssuer like you would with any other ACME CA (just adjust the directory URL). External Account Binding (EAB) is required for ZeroSSL. You can use the ZeroSSL API to generate one, or your account dashboard.

To use ZeroSSL's API instead, use the ZeroSSLIssuer. Here is a simple example:

go
magic := certmagic.NewDefault()

magic.Issuers = []certmagic.Issuer{
	certmagic.ZeroSSLIssuer{
		APIKey: "<your ZeroSSL API key>",
	}),
}

err := magic.ManageSync(ctx, []string{"example.com"})

FAQ

Can I use some of my own certificates while using CertMagic?

Yes, just call the relevant method on the Config to add your own certificate to the cache:

Keep in mind that unmanaged certificates are (obviously) not renewed for you, so you'll have to replace them when you do. However, OCSP stapling is performed even for unmanaged certificates that qualify.

Does CertMagic obtain SAN certificates?

Technically all certificates these days are SAN certificates because CommonName is deprecated. But if you're asking whether CertMagic issues and manages certificates with multiple SANs, the answer is no. But it does support serving them, if you provide your own.

How can I listen on ports 80 and 443? Do I have to run as root?

On Linux, you can use setcap to grant your binary the permission to bind low ports:

bash
$ sudo setcap cap_net_bind_service=+ep /path/to/your/binary

and then you will not need to run with root privileges.

Contributing

We welcome your contributions! Please see our contributing guidelines for instructions.

Project History

CertMagic is the core of Caddy's advanced TLS automation code, extracted into a library. The underlying ACME client implementation is ACMEz. CertMagic's code was originally a central part of Caddy even before Let's Encrypt entered public beta in 2015.

In the years since then, Caddy's TLS automation techniques have been widely adopted, tried and tested in production, and served millions of sites and secured trillions of connections.

Now, CertMagic is the actual library used by Caddy. It's incredibly powerful and feature-rich, but also easy to use for simple Go programs: one line of code can enable fully-automated HTTPS applications with HTTP->HTTPS redirects.

Caddy is known for its robust HTTPS+ACME features. When ACME certificate authorities have had outages, in some cases Caddy was the only major client that didn't experience any downtime. Caddy can weather OCSP outages lasting days, or CA outages lasting weeks, without taking your sites offline.

Caddy was also the first to sport "on-demand" issuance technology, which obtains certificates during the first TLS handshake for an allowed SNI name.

Consequently, CertMagic brings all these (and more) features and capabilities right into your own Go programs.

You can watch a 2016 dotGo talk by the author of this library about using ACME to automate certificate management in Go programs:

Credits and License

CertMagic is a project by Matthew Holt, who is the author; and various contributors, who are credited in the commit history of either CertMagic or Caddy.

CertMagic is licensed under Apache 2.0, an open source license. For convenience, its main points are summarized as follows (but this is no replacement for the actual license text):

  • The author owns the copyright to this code
  • Use, distribute, and modify the software freely
  • Private and internal use is allowed
  • License text and copyright notices must stay intact and be included with distributions
  • Any and all changes to the code must be documented

File: LICENSE.txt

Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

  1. Definitions.

    "License" shall mean the terms and conditions for use, reproduction,
    and distribution as defined by Sections 1 through 9 of this document.

    "Licensor" shall mean the copyright owner or entity authorized by
    the copyright owner that is granting the License.

    "Legal Entity" shall mean the union of the acting entity and all
    other entities that control, are controlled by, or are under common
    control with that entity. For the purposes of this definition,
    "control" means (i) the power, direct or indirect, to cause the
    direction or management of such entity, whether by contract or
    otherwise, or (ii) ownership of fifty percent (50%) or more of the
    outstanding shares, or (iii) beneficial ownership of such entity.

    "You" (or "Your") shall mean an individual or Legal Entity
    exercising permissions granted by this License.

    "Source" form shall mean the preferred form for making modifications,
    including but not limited to software source code, documentation
    source, and configuration files.

    "Object" form shall mean any form resulting from mechanical
    transformation or translation of a Source form, including but
    not limited to compiled object code, generated documentation,
    and conversions to other media types.

    "Work" shall mean the work of authorship, whether in Source or
    Object form, made available under the License, as indicated by a
    copyright notice that is included in or attached to the work
    (an example is provided in the Appendix below).

    "Derivative Works" shall mean any work, whether in Source or Object
    form, that is based on (or derived from) the Work and for which the
    editorial revisions, annotations, elaborations, or other modifications
    represent, as a whole, an original work of authorship. For the purposes
    of this License, Derivative Works shall not include works that remain
    separable from, or merely link (or bind by name) to the interfaces of,
    the Work and Derivative Works thereof.

    "Contribution" shall mean any work of authorship, including
    the original version of the Work and any modifications or additions
    to that Work or Derivative Works thereof, that is intentionally
    submitted to Licensor for inclusion in the Work by the copyright owner
    or by an individual or Legal Entity authorized to submit on behalf of
    the copyright owner. For the purposes of this definition, "submitted"
    means any form of electronic, verbal, or written communication sent
    to the Licensor or its representatives, including but not limited to
    communication on electronic mailing lists, source code control systems,
    and issue tracking systems that are managed by, or on behalf of, the
    Licensor for the purpose of discussing and improving the Work, but
    excluding communication that is conspicuously marked or otherwise
    designated in writing by the copyright owner as "Not a Contribution."

    "Contributor" shall mean Licensor and any individual or Legal Entity
    on behalf of whom a Contribution has been received by Licensor and
    subsequently incorporated within the Work.

  2. Grant of Copyright License. Subject to the terms and conditions of
    this License, each Contributor hereby grants to You a perpetual,
    worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    copyright license to reproduce, prepare Derivative Works of,
    publicly display, publicly perform, sublicense, and distribute the
    Work and such Derivative Works in Source or Object form.

  3. Grant of Patent License. Subject to the terms and conditions of
    this License, each Contributor hereby grants to You a perpetual,
    worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    (except as stated in this section) patent license to make, have made,
    use, offer to sell, sell, import, and otherwise transfer the Work,
    where such license applies only to those patent claims licensable
    by such Contributor that are necessarily infringed by their
    Contribution(s) alone or by combination of their Contribution(s)
    with the Work to which such Contribution(s) was submitted. If You
    institute patent litigation against any entity (including a
    cross-claim or counterclaim in a lawsuit) alleging that the Work
    or a Contribution incorporated within the Work constitutes direct
    or contributory patent infringement, then any patent licenses
    granted to You under this License for that Work shall terminate
    as of the date such litigation is filed.

  4. Redistribution. You may reproduce and distribute copies of the
    Work or Derivative Works thereof in any medium, with or without
    modifications, and in Source or Object form, provided that You
    meet the following conditions:

    (a) You must give any other recipients of the Work or
    Derivative Works a copy of this License; and

    (b) You must cause any modified files to carry prominent notices
    stating that You changed the files; and

    (c) You must retain, in the Source form of any Derivative Works
    that You distribute, all copyright, patent, trademark, and
    attribution notices from the Source form of the Work,
    excluding those notices that do not pertain to any part of
    the Derivative Works; and

    (d) If the Work includes a "NOTICE" text file as part of its
    distribution, then any Derivative Works that You distribute must
    include a readable copy of the attribution notices contained
    within such NOTICE file, excluding those notices that do not
    pertain to any part of the Derivative Works, in at least one
    of the following places: within a NOTICE text file distributed
    as part of the Derivative Works; within the Source form or
    documentation, if provided along with the Derivative Works; or,
    within a display generated by the Derivative Works, if and
    wherever such third-party notices normally appear. The contents
    of the NOTICE file are for informational purposes only and
    do not modify the License. You may add Your own attribution
    notices within Derivative Works that You distribute, alongside
    or as an addendum to the NOTICE text from the Work, provided
    that such additional attribution notices cannot be construed
    as modifying the License.

    You may add Your own copyright statement to Your modifications and
    may provide additional or different license terms and conditions
    for use, reproduction, or distribution of Your modifications, or
    for any such Derivative Works as a whole, provided Your use,
    reproduction, and distribution of the Work otherwise complies with
    the conditions stated in this License.

  5. Submission of Contributions. Unless You explicitly state otherwise,
    any Contribution intentionally submitted for inclusion in the Work
    by You to the Licensor shall be under the terms and conditions of
    this License, without any additional terms or conditions.
    Notwithstanding the above, nothing herein shall supersede or modify
    the terms of any separate license agreement you may have executed
    with Licensor regarding such Contributions.

  6. Trademarks. This License does not grant permission to use the trade
    names, trademarks, service marks, or product names of the Licensor,
    except as required for reasonable and customary use in describing the
    origin of the Work and reproducing the content of the NOTICE file.

  7. Disclaimer of Warranty. Unless required by applicable law or
    agreed to in writing, Licensor provides the Work (and each
    Contributor provides its Contributions) on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    implied, including, without limitation, any warranties or conditions
    of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    PARTICULAR PURPOSE. You are solely responsible for determining the
    appropriateness of using or redistributing the Work and assume any
    risks associated with Your exercise of permissions under this License.

  8. Limitation of Liability. In no event and under no legal theory,
    whether in tort (including negligence), contract, or otherwise,
    unless required by applicable law (such as deliberate and grossly
    negligent acts) or agreed to in writing, shall any Contributor be
    liable to You for damages, including any direct, indirect, special,
    incidental, or consequential damages of any character arising as a
    result of this License or out of the use or inability to use the
    Work (including but not limited to damages for loss of goodwill,
    work stoppage, computer failure or malfunction, or any and all
    other commercial damages or losses), even if such Contributor
    has been advised of the possibility of such damages.

  9. Accepting Warranty or Additional Liability. While redistributing
    the Work or Derivative Works thereof, You may choose to offer,
    and charge a fee for, acceptance of support, warranty, indemnity,
    or other liability obligations and/or rights consistent with this
    License. However, in accepting such obligations, You may act only
    on Your own behalf and on Your sole responsibility, not on behalf
    of any other Contributor, and only if You agree to indemnify,
    defend, and hold each Contributor harmless for any liability
    incurred by, or claims asserted against, such Contributor by reason
    of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

text
To apply the Apache License to your work, attach the following
  boilerplate notice, with the fields enclosed by brackets "{}"
  replaced with your own identifying information. (Don't include
  the brackets!)  The text should be enclosed in the appropriate
  comment syntax for the file format. We also recommend that a
  file or class name and description of purpose be included on the
  same "printed page" as the copyright notice for easier
  identification within third-party archives.

Copyright {yyyy} {name of copyright owner}

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

text
http://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.


File: internal/testutil/readme.md

testutil

some testing functions copied out of github.com/stretchr/testify, which were originally used by atomicfile

text
MIT License

Copyright (c) 2012-2020 Mat Ryer, Tyler Bunnell and contributors.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

File: .github/CONTRIBUTING.md

Contributing to CertMagic

Common Tasks

Other menu items:

Contributing code

You can have a direct impact on the project by helping with its code. To contribute code to CertMagic, open a pull request (PR). If you're new to our community, that's okay: we gladly welcome pull requests from anyone, regardless of your native language or coding experience. You can get familiar with CertMagic's code base by using code search at Sourcegraph.

We hold contributions to a high standard for quality :bowtie:, so don't be surprised if we ask for revisions—even if it seems small or insignificant. Please don't take it personally. :wink: If your change is on the right track, we can guide you to make it mergable.

Here are some of the expectations we have of contributors:

  • If your change is more than just a minor alteration, open an issue to propose your change first. This way we can avoid confusion, coordinate what everyone is working on, and ensure that changes are in-line with the project's goals and the best interests of its users. If there's already an issue about it, comment on the existing issue to claim it.

  • Keep pull requests small. Smaller PRs are more likely to be merged because they are easier to review! We might ask you to break up large PRs into smaller ones. An example of what we DON'T do.

  • Don't "push" your pull requests. Basically, work with—not against—the maintainers -- theirs is not a glorious job. In fact, consider becoming a CertMagic maintainer yourself!

  • Keep related commits together in a PR. We do want pull requests to be small, but you should also keep multiple related commits in the same PR if they rely on each other.

  • Write tests. Tests are essential! Written properly, they ensure your change works, and that other changes in the future won't break your change. CI checks should pass.

  • Benchmarks should be included for optimizations. Optimizations sometimes make code harder to read or have changes that are less than obvious. They should be proven with benchmarks or profiling.

  • Squash insignificant commits. Every commit should be significant. Commits which merely rewrite a comment or fix a typo can be combined into another commit that has more substance. Interactive rebase can do this, or a simpler way is git reset --soft then git commit -s.

  • Maintain your contributions. Please help maintain your change after it is merged.

  • Use comments properly. We expect good godoc comments for package-level functions, types, and values. Comments are also useful whenever the purpose for a line of code is not obvious, and comments should not state the obvious.

We often grant collaborator status to contributors who author one or more significant, high-quality PRs that are merged into the code base!

HOW TO MAKE A PULL REQUEST TO CERTMAGIC

Contributing to Go projects on GitHub is fun and easy. We recommend the following workflow:

  1. Fork this repo. This makes a copy of the code you can write to.

  2. If you don't already have this repo (caddyserver/certmagic.git) repo on your computer, get it with go get github.com/caddyserver/certmagic.

  3. Tell git that it can push the caddyserver/certmagic.git repo to your fork by adding a remote: git remote add myfork https://github.com/you/certmagic.git

  4. Make your changes in the caddyserver/certmagic.git repo on your computer.

  5. Push your changes to your fork: git push myfork

  6. Create a pull request to merge your changes into caddyserver/certmagic @ master. (Click "compare across forks" and change the head fork.)

This workflow is nice because you don't have to change import paths. You can get fancier by using different branches if you want.

Reporting bugs

Like every software, CertMagic has its flaws. If you find one, search the issues to see if it has already been reported. If not, open a new issue and describe the bug clearly.

You can help stop bugs in their tracks! Speed up the patching process by identifying the bug in the code. This can sometimes be done by adding fmt.Println() statements (or similar) in relevant code paths to narrow down where the problem may be. It's a good way to introduce yourself to the Go language, too.

Please follow the issue template so we have all the needed information. Unredacted—yes, actual values matter. We need to be able to repeat the bug using your instructions. Please simplify the issue as much as possible. The burden is on you to convince us that it is actually a bug in CertMagic. This is easiest to do when you write clear, concise instructions so we can reproduce the behavior (even if it seems obvious). The more detailed and specific you are, the faster we will be able to help you!

Failure to fill out the issue template will probably result in the issue being closed.

We suggest reading How to Report Bugs Effectively.

Please be kind. :smile: Remember that CertMagic comes at no cost to you, and you're getting free support when we fix your issues. If we helped you, please consider helping someone else!

Suggesting features

First, search to see if your feature has already been requested. If it has, you can add a :+1: reaction to vote for it. If your feature idea is new, open an issue to request the feature. You don't have to follow the bug template for feature requests. Please describe your idea thoroughly so that we know how to implement it! Really vague requests may not be helpful or actionable and without clarification will have to be closed.

Please do not "bump" issues with comments that ask if there are any updates.

While we really do value your requests and implement many of them, not all features are a good fit for CertMagic. If a feature is not in the best interest of the CertMagic project or its users in general, we may politely decline to implement it.

Collaborator Instructions

Collabators have push rights to the repository. We grant this permission after one or more successful, high-quality PRs are merged! We thank them for their help.The expectations we have of collaborators are:

  • Help review pull requests. Be meticulous, but also kind. We love our contributors, but we critique the contribution to make it better. Multiple, thorough reviews make for the best contributions! Here are some questions to consider:

    • Can the change be made more elegant?
    • Is this a maintenance burden?
    • What assumptions does the code make?
    • Is it well-tested?
    • Is the change a good fit for the project?
    • Does it actually fix the problem or is it creating a special case instead?
    • Does the change incur any new dependencies? (Avoid these!)
  • Answer issues. If every collaborator helped out with issues, we could count the number of open issues on two hands. This means getting involved in the discussion, investigating the code, and yes, debugging it. It's fun. Really! :smile: Please, please help with open issues. Granted, some issues need to be done before others. And of course some are larger than others: you don't have to do it all yourself. Work with other collaborators as a team!

  • Do not merge pull requests until they have been approved by one or two other collaborators. If a project owner approves the PR, it can be merged (as long as the conversation has finished too).

  • Prefer squashed commits over a messy merge. If there are many little commits, please squash the commits so we don't clutter the commit history.

  • Don't accept new dependencies lightly. Dependencies can make the world crash and burn, but they are sometimes necessary. Choose carefully. Extremely small dependencies (a few lines of code) can be inlined. The rest may not be needed.

  • Make sure tests test the actual thing. Double-check that the tests fail without the change, and pass with it. It's important that they assert what they're purported to assert.

  • Recommended reading

Values

  • A person is always more important than code. People don't like being handled "efficiently". But we can still process issues and pull requests efficiently while being kind, patient, and considerate.

  • The ends justify the means, if the means are good. A good tree won't produce bad fruit. But if we cut corners or are hasty in our process, the end result will not be good.

Thank you

Thanks for your help! CertMagic would not be what it is today without your contributions.


File: .github/FUNDING.yml

These are supported funding model platforms

github: [mholt] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']


File: .github/ISSUE_TEMPLATE/bug_report.md


name: Bug report
about: For behaviors which violate documentation or cause incorrect results
title: ''
labels: ''
assignees: ''


What version of the package are you using?

What are you trying to do?

What steps did you take?

What did you expect to happen, and what actually happened instead?

How do you think this should be fixed?

Bonus: What do you use CertMagic for, and do you find it useful?


File: .github/ISSUE_TEMPLATE/feature_request.md


name: Feature request
about: Suggest an idea for this project
title: ''
labels: feature request
assignees: ''


What would you like to have changed?

Why is this feature a useful, necessary, and/or important addition to this project?

What alternatives are there, or what are you doing in the meantime to work around the lack of this feature?


File: .github/ISSUE_TEMPLATE/question.md


name: Question
about: For help or questions about this package
title: ''
labels: question
assignees: ''


What is your question?

What have you already tried?

Include any other information or discussion.

Bonus: What do you use this package for, and does it help you?


File: .github/workflows/ci.yml

Used as inspiration: https://github.com/mvdan/github-actions-golang

name: Tests

on:
push:
branches:
- master
pull_request:
branches:
- master

jobs:
test:
strategy:
matrix:
os: [ ubuntu-latest, macos-latest, windows-latest ]
go: [ '1.25', '1.26' ]

text
runs-on: ${{ matrix.os }}

steps:
- name: Checkout code
  uses: actions/checkout@v3

- name: Install Go
  uses: actions/setup-go@v4
  with:
    go-version: ${{ matrix.go }}

- name: Print Go version and environment
  id: vars
  run: |
    printf "Using go at: $(which go)\n"
    printf "Go version: $(go version)\n"
    printf "\n\nGo environment:\n\n"
    go env
    printf "\n\nSystem environment:\n\n"
    env

- name: Install dependencies
  run: go mod download

- name: Run tests
  run: go test -v -short -race ./...