std/autocert
import std/autocert to use it. Source: src/std/autocert.iyi at v0.22.0.
import std/autocert::{AutocertManager, AutocertDirCache}
import std/http::{Server, Response}
import std/socket::{IyiSocket} cache = AutocertDirCache.new("/var/lib/app/certs")
manager = AutocertManager.new("https://acme-v02.api.letsencrypt.org/directory", cache, ["example.com", "www.example.com"])
manager.accept_terms = true # the CA's terms of service, agreed to
manager.email = "[email protected]"
group do |g|
g.spawn { manager.run; 0 } # renewals, until `manager.stop`
# Port 80's block calls the manager, whose state is one thread's.
g.spawn { Server.serve(IyiSocket.listen(80), workers: 1) { |r| manager.answer(r) || Response.new(404, "") }; 0 }
Server.serve(IyiSocket.listen(443), tls: manager.frozen_tls_config) { |r| Response.new(200, "hello") }
0
end**A certificate per name, on demand.** tls_config is a std/tls server config whose identity_source is the manager: each ClientHello's server_name is looked up, and the first handshake for a name with no certificate held gets one - from the cache if one there is valid for the name and not expired, or by an order from the CA - while the handshake waits. One P-256 key and one name per certificate, as Go's manager makes them. A client that names no host, or one the host policy refuses, is refused (unrecognized_name) before the cache or the CA is asked, and one whose certificate could not be had is refused with internal_error: host_policy, unless replaced, allows the names given to new and no other, as Go's HostWhitelist does, each name compared as server_name carries it - ASCII, its A-labels for a Unicode one, without the trailing dot, in lower case.
**One order at a time for a name.** Handshakes that ask for a name while its order runs wait for that order and take what it ends with; they do not place their own. An order that fails is remembered for its name: the handshakes after it are refused at once with its error until retry_ms has passed, and twice that after a second failure in a row, up to an hour - so a name the CA will not issue for is not asked for on every handshake. The manager's state is plain fields changed between its tasks' parks: it is for one thread's tasks, as std/http's server's connections are, and Share keeps it out of a block spawn(unit: :new) runs.
**On every worker.** frozen_tls_config is tls_config frozen (std/tls's TlsFrozenServerConfig) for a server whose handshakes run on every worker, and the manager's state stays on the thread run runs on. What the workers share with it is Share by its fields: the certificates held, and the tls-alpn-01 challenges up, each a table behind a Mutex that the manager writes as it keeps a certificate or puts a challenge up, and a Channel to run. A handshake for a name whose certificate is held and current is answered on its worker from the table, a challenge under acme-tls/1 alone the same; any other - a name not held yet, one expired, one refused - is sent to run as an ask, which a task of its group answers with identity_for, so one order serves however many workers ask for a name at once and a failure is remembered as under workers: 1. The worker waits for the answer no longer than its handshake's time and wait_ms. So run must run: an ask nothing takes is refused with internal_error once that time is up. A name held is answered without asking host_policy again.
**A handshake waits no longer than its deadline.** std/tls tells the manager what is left of the handshake's time (HANDSHAKE_TIMEOUT_MS, or the server's own), and a handshake's wait for an order is cut to that, and to wait_ms: the handshake is refused with internal_error then, and lets its socket go. While run runs, every order runs in its group, not in the handshake that asked for it, so an order that takes longer than one handshake goes on and the handshakes after it wait for the same order and take its certificate. Without run there is no task for it to go on in: the handshake that asked runs it, and at its deadline the order is cancelled, not remembered as a failure, and the next handshake starts it again. An order asked for outside a handshake (certificate) is waited for wait_ms at most, and without run runs to its end.
**Chains checked.** A chain the CA issues is checked by std/x509 for the name, to roots - the system's unless set - before it is cached or shown, and so is one read from the cache: a chain from any other CA is refused (internal_error), not kept.
**Challenges.** challenges names those offered to the CA in the order tried, tls-alpn-01 then http-01 unless set: each a fresh order, the next tried when one's authorization fails. tls-alpn-01 (RFC 8737) is answered by this same listener: tls_config adds acme-tls/1 to the protocols it speaks by ALPN, and a client that offers it alone - the CA's validation, nothing else does - is shown the challenge certificate for the name while its order runs and refused otherwise; a client that offers anything beside it never is. http-01 is answered on port 80 by answer, from a std/http server's block; dns-01 is not offered, since its record goes in a zone this cannot reach.
**Renewal.** run, in a task of the caller's group, renews each certificate the manager holds renew_before (thirty days unless set) before it expires - or, for one whose whole life is no longer than that, once two thirds of it have passed - with a new key, and swaps it in for the handshakes after; it retries a failed renewal after retry_ms, doubling to an hour. stop ends it. Without run a certificate is ordered again only once it has expired.
**The cache** (AutocertCache) keeps the account key under acme_account+key and each name's key and chain, as PEM, under the name. AutocertDirCache is a directory, made 0700 where it is not there, each entry written to a file of its own and renamed over the old - so a reader sees the old or the new whole - and created 0600: every entry holds a private key. On Windows a mode says nothing of who may read a file - a file has the access list of the directory it is made in, and under C:\ProgramData that lets every user read - so the directory is given a list of its own instead, there already or not, before the first entry is written: its owner, the account the program runs as, SYSTEM and the Administrators, and nothing inherited from above it; an entry inherits that, and a directory whose list cannot be set is not written to. A program can hold them elsewhere with a class of its own that implements the trait.
Not here: ACME Renewal Information (RFC 9773) - renewal is by the certificate's dates alone; jitter on the renewal time; RSA certificate keys beside ECDSA ones for clients that take no ECDSA; external account binding; deactivating an authorization left pending by a failed order; revocation; dns-01, and so wildcard names; several names on one certificate. A failure is remembered in this process alone.
bench/std_autocert_exercise.sh holds it to Python's ssl and Let's Encrypt's Pebble: chains verified to Pebble's root, a refused name with no order in Pebble's log, ten first handshakes making one order, a restart that orders nothing, a renewal of a short-lived certificate seen as a new serial before the old one expires, a chain from a CA the manager does not trust refused and not cached, a handshake's wait cut to its deadline, and the cache's modes.
AutocertCachetrait
Where a manager keeps its account key and its certificates: text by key, nil for a key not held. Every value it is given holds a private key.
pub trait AutocertCache
abstract def delete(key : String) : AutocertError | ::Nil
abstract def get(key : String) : String | AutocertError | Nil
abstract def put(key : String, data : String) : AutocertError | ::Nil
endAutocertDirCacheclass
A cache in a directory: an entry a file named by its key. The directory is made, 0700, the first time it is written to where it is not there; an entry is written to a file of its own in it, created 0600 (the umask may take more away, never less), then renamed over the old one. On Windows, where those modes keep nobody out, the directory's access list is set before the first entry is written (AutocertFiles.keep).
pub class AutocertDirCache
def dir : String
def initialize(dir : String)
endAutocertErrorstruct
Why a certificate could not be had, or the cache not read or written.
pub struct AutocertError
def detail : String
def initialize(detail : String)
def to_s : String
endAutocertHeldclass
A certificate a manager holds for a name: the identity handshakes are shown, its dates, and when renewal is next tried.
pub class AutocertHeld
# Whether a handshake at *now_ms* may be shown it.
def current?(now_ms : Int64) : Bool
def failures : Int32
def failures=(value : Int32) : Int32
def identity : TlsIdentity
def initialize(identity : TlsIdentity, renew_at_ms : Int64)
def not_after_ms : Int64
def not_before_ms : Int64
# When renewal is next tried: its due time, later after failures.
def renew_at_ms : Int64
# When renewal is next tried: its due time, later after failures.
def renew_at_ms=(value : Int64) : Int64
endAutocertManagerclass
Gets, keeps and renews certificates for a server's names from an ACME CA, and shows them to std/tls handshakes by server_name.
pub class AutocertManager
# Whether the CA's terms of service are agreed to when the account is
# made: a CA that has terms refuses an account without.
def accept_terms : Bool
# Whether the CA's terms of service are agreed to when the account is
# made: a CA that has terms refuses an account without.
def accept_terms=(value : Bool) : Bool
# Puts up the answers to *name*'s challenge: tls-alpn-01's certificate
# for *key_authorization*, shown under `acme-tls/1`, and http-01's
# answer for *token* (`answer`). An order puts them up while the CA
# checks; a program answering a challenge of its own can too.
def add_challenge(name : String, token : String, key_authorization : String) : AutocertError | ::Nil
# http-01's answer to a request on port 80
# (`/.well-known/acme-challenge/<token>`), or nil for any other path:
# `Server.serve(listener, workers: 1) { |r| manager.answer(r) || ... }`,
# on one thread, since the manager's state is that thread's.
def answer(request : Request) : Response | ::Nil
def cache : AutocertCache
# The certificate for *name*, normalized as `normalize` does: the one
# held while it is current; else one the cache holds for it, or a new
# one from the CA - by one order however many ask at once, waited for
# *left_ms* at most when it is given - unless the host policy refuses
# the name or its last order failed too recently.
def certificate(name : String, left_ms : Int32 | ::Nil = nil) : AutocertHeld | AutocertError
# The challenges offered, in the order tried.
def challenges : Array(String)
# The challenges offered, in the order tried.
def challenges=(value : Array(String)) : Array(String)
def directory_url : String
# The account's contact address, without `mailto:`; none when empty.
def email : String
# The account's contact address, without `mailto:`; none when empty.
def email=(value : String) : String
# *config* - `tls_config`'s, or one the program got from it and set
# more of, a `min_version` or `groups` - frozen for std/http's
# `Server.serve(tls:)` on more than one worker: its identity source
# runs on every worker, answers what this manager holds there, and
# asks `run` for the rest (the header says how). `run` must run while
# it serves.
def frozen_tls_config(config : TlsServerConfig = tls_config) : TlsFrozenServerConfig
# Whether a name may have a certificate; asked before the cache or the
# CA. The names given to `new` and no other, unless replaced.
def host_policy : Proc(String, Bool)
# Whether a name may have a certificate; asked before the cache or the
# CA. The names given to `new` and no other, unless replaced.
def host_policy=(value : Proc(String, Bool)) : Proc(String, Bool)
# The identity a handshake for *server_name*, offering *alpn*, is shown:
# tls-alpn-01's certificate to a client offering `acme-tls/1` alone, the
# name's certificate - got now if it must be, waiting *left_ms* at most
# - to any other; or why there is none, as the error the handshake is
# refused with: unrecognized_name for a name not answered for,
# internal_error for one whose certificate could not be had in time.
def identity_for(server_name : String | ::Nil, alpn : Array(String) | ::Nil, left_ms : Int32 | ::Nil = nil) : TlsIdentity | TlsError
# A manager for the CA whose directory is at *directory_url*, keeping
# its keys and certificates in *cache*, that answers for *hosts* alone.
def initialize(directory_url : String, cache : AutocertCache, hosts : Array(String))
# *host* as a server_name is compared: IDNA's A-labels for a Unicode
# name, no trailing dot, lower case. A name IDNA refuses is compared as
# it is written.
def self.normalize(host : String) : String
# Certificates ordered, and renewed, by this manager.
def orders : Int32
def remove_challenge(name : String, token : String) : Nil
# How long before expiry a certificate is renewed.
def renew_before : Span
# How long before expiry a certificate is renewed.
def renew_before=(value : Span) : Span
# When a certificate valid from *not_before_ms* to *not_after_ms* is
# due for renewal: `renew_before` ahead of its end, or two thirds into
# a life no longer than `renew_before`.
def renew_time(not_before_ms : Int64, not_after_ms : Int64) : Int64
def renewals : Int32
# How long a failed order is remembered, and a failed renewal put off;
# doubled for each failure after, to `MAX_RETRY_MS`.
def retry_ms : Int32
# How long a failed order is remembered, and a failed renewal put off;
# doubled for each failure after, to `MAX_RETRY_MS`.
def retry_ms=(value : Int32) : Int32
# The roots a chain the CA issues, or the cache holds, must reach to be
# kept and shown: the system's when nil.
def roots : Array(Certificate) | ::Nil
# The roots a chain the CA issues, or the cache holds, must reach to be
# kept and shown: the system's when nil.
def roots=(value : Array(Certificate) | ::Nil) : Array(Certificate) | ::Nil
# Renews certificates as they come due, until `stop`: run it in a task
# of a group that lives as long as the server. Each held certificate is
# looked at when it is due and whenever one is added; a renewal that
# fails is tried again `retry_ms` later, doubling to an hour. While it
# runs, the orders handshakes ask for run in its group too, so that one
# outlives the handshake that asked; `stop` cancels those still running.
# It answers a `frozen_tls_config`'s workers too, each ask in a task of
# its group.
def run : Nil
# Ends `run`.
def stop : Nil
# A std/tls server config that shows this manager's certificates, and
# speaks *alpn*'s protocols with `acme-tls/1` after them. Its own
# `identity` is a self-signed certificate for `autocert.invalid` that
# no handshake is shown: the manager answers each one itself.
def tls_config(alpn : Array(String) = ["http/1.1"]) : TlsServerConfig
# The longest a handshake waits for an order - less when its deadline
# is nearer - and an order for the CA's polls.
def wait_ms : Int32
# The longest a handshake waits for an order - less when its deadline
# is nearer - and an order for the CA's polls.
def wait_ms=(value : Int32) : Int32
endError for AutocertErrorimpl
impl Error for AutocertError
def message : String
endAutocertCache for AutocertDirCacheimpl
impl AutocertCache for AutocertDirCache
def get(key : String) : String | AutocertError | Nil
def put(key : String, data : String) : AutocertError | ::Nil
def delete(key : String) : AutocertError | ::Nil
end
Certificates got and renewed as they are asked for: an HTTPS server that names the hosts it may answer for and a CA's ACME directory, and nothing else - Go's golang.org/x/crypto/acme/autocert, over std/acme, std/tls and std/http.