repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/obs_conf.go | third-party/github.com/letsencrypt/boulder/observer/obs_conf.go | package observer
import (
"errors"
"fmt"
"net"
"strconv"
"github.com/prometheus/client_golang/prometheus"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/observer/probers"
)
var (
countMonitors = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "obs_monitors",
Help: "details of each configured monitor",
},
[]string{"kind", "valid"},
)
histObservations *prometheus.HistogramVec
)
// ObsConf is exported to receive YAML configuration.
type ObsConf struct {
DebugAddr string `yaml:"debugaddr" validate:"omitempty,hostname_port"`
Buckets []float64 `yaml:"buckets" validate:"min=1,dive"`
Syslog cmd.SyslogConfig `yaml:"syslog"`
OpenTelemetry cmd.OpenTelemetryConfig
MonConfs []*MonConf `yaml:"monitors" validate:"min=1,dive"`
}
// validateSyslog ensures the `Syslog` field received by `ObsConf`
// contains valid log levels.
func (c *ObsConf) validateSyslog() error {
syslog, stdout := c.Syslog.SyslogLevel, c.Syslog.StdoutLevel
if stdout < 0 || stdout > 7 || syslog < 0 || syslog > 7 {
return fmt.Errorf(
"invalid 'syslog', '%+v', valid log levels are 0-7", c.Syslog)
}
return nil
}
// validateDebugAddr ensures the `debugAddr` received by `ObsConf` is
// properly formatted and a valid port.
func (c *ObsConf) validateDebugAddr() error {
_, p, err := net.SplitHostPort(c.DebugAddr)
if err != nil {
return fmt.Errorf(
"invalid 'debugaddr', %q, not expected format", c.DebugAddr)
}
port, _ := strconv.Atoi(p)
if port <= 0 || port > 65535 {
return fmt.Errorf(
"invalid 'debugaddr','%d' is not a valid port", port)
}
return nil
}
func (c *ObsConf) makeMonitors(metrics prometheus.Registerer) ([]*monitor, []error, error) {
var errs []error
var monitors []*monitor
proberSpecificMetrics := make(map[string]map[string]prometheus.Collector)
for e, m := range c.MonConfs {
entry := strconv.Itoa(e + 1)
proberConf, err := probers.GetConfigurer(m.Kind)
if err != nil {
// append error to errs
errs = append(errs, fmt.Errorf("'monitors' entry #%s couldn't be validated: %w", entry, err))
// increment metrics
countMonitors.WithLabelValues(m.Kind, "false").Inc()
// bail out before constructing the monitor. with no configurer, it will fail
continue
}
kind := proberConf.Kind()
// set up custom metrics internal to each prober kind
_, exist := proberSpecificMetrics[kind]
if !exist {
// we haven't seen this prober kind before, so we need to request
// any custom metrics it may have and register them with the
// prometheus registry
proberSpecificMetrics[kind] = make(map[string]prometheus.Collector)
for name, collector := range proberConf.Instrument() {
// register the collector with the prometheus registry
metrics.MustRegister(collector)
// store the registered collector so we can pass it to every
// monitor that will construct this kind of prober
proberSpecificMetrics[kind][name] = collector
}
}
monitor, err := m.makeMonitor(proberSpecificMetrics[kind])
if err != nil {
// append validation error to errs
errs = append(errs, fmt.Errorf("'monitors' entry #%s couldn't be validated: %w", entry, err))
// increment metrics
countMonitors.WithLabelValues(kind, "false").Inc()
} else {
// append monitor to monitors
monitors = append(monitors, monitor)
// increment metrics
countMonitors.WithLabelValues(kind, "true").Inc()
}
}
if len(c.MonConfs) == len(errs) {
return nil, errs, errors.New("no valid monitors, cannot continue")
}
return monitors, errs, nil
}
// MakeObserver constructs an `Observer` object from the contents of the
// bound `ObsConf`. If the `ObsConf` cannot be validated, an error
// appropriate for end-user consumption is returned instead.
func (c *ObsConf) MakeObserver() (*Observer, error) {
err := c.validateSyslog()
if err != nil {
return nil, err
}
err = c.validateDebugAddr()
if err != nil {
return nil, err
}
if len(c.MonConfs) == 0 {
return nil, errors.New("no monitors provided")
}
if len(c.Buckets) == 0 {
return nil, errors.New("no histogram buckets provided")
}
// Start monitoring and logging.
metrics, logger, shutdown := cmd.StatsAndLogging(c.Syslog, c.OpenTelemetry, c.DebugAddr)
histObservations = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "obs_observations",
Help: "details of each probe attempt",
Buckets: c.Buckets,
}, []string{"name", "kind", "success"})
metrics.MustRegister(countMonitors)
metrics.MustRegister(histObservations)
defer cmd.AuditPanic()
logger.Info(cmd.VersionString())
logger.Infof("Initializing boulder-observer daemon")
logger.Debugf("Using config: %+v", c)
monitors, errs, err := c.makeMonitors(metrics)
if len(errs) != 0 {
logger.Errf("%d of %d monitors failed validation", len(errs), len(c.MonConfs))
for _, err := range errs {
logger.Errf("%s", err)
}
} else {
logger.Info("all monitors passed validation")
}
if err != nil {
return nil, err
}
return &Observer{logger, monitors, shutdown}, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/observer.go | third-party/github.com/letsencrypt/boulder/observer/observer.go | package observer
import (
"context"
"github.com/letsencrypt/boulder/cmd"
blog "github.com/letsencrypt/boulder/log"
_ "github.com/letsencrypt/boulder/observer/probers/crl"
_ "github.com/letsencrypt/boulder/observer/probers/dns"
_ "github.com/letsencrypt/boulder/observer/probers/http"
_ "github.com/letsencrypt/boulder/observer/probers/tcp"
_ "github.com/letsencrypt/boulder/observer/probers/tls"
)
// Observer is the steward of goroutines started for each `monitor`.
type Observer struct {
logger blog.Logger
monitors []*monitor
shutdown func(ctx context.Context)
}
// Start spins off a goroutine for each monitor, and waits for a signal to exit
func (o Observer) Start() {
for _, mon := range o.monitors {
go mon.start(o.logger)
}
defer o.shutdown(context.Background())
cmd.WaitForSignal()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/mon_conf.go | third-party/github.com/letsencrypt/boulder/observer/mon_conf.go | package observer
import (
"errors"
"time"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/yaml.v3"
"github.com/letsencrypt/boulder/config"
"github.com/letsencrypt/boulder/observer/probers"
)
// MonConf is exported to receive YAML configuration in `ObsConf`.
type MonConf struct {
Period config.Duration `yaml:"period"`
Kind string `yaml:"kind" validate:"required,oneof=DNS HTTP CRL TLS TCP"`
Settings probers.Settings `yaml:"settings" validate:"min=1,dive"`
}
// validatePeriod ensures the received `Period` field is at least 1µs.
func (c *MonConf) validatePeriod() error {
if c.Period.Duration < 1*time.Microsecond {
return errors.New("period must be at least 1µs")
}
return nil
}
// unmarshalConfigurer constructs a `Configurer` by marshaling the
// value of the `Settings` field back to bytes, then passing it to the
// `UnmarshalSettings` method of the `Configurer` type specified by the
// `Kind` field.
func (c MonConf) unmarshalConfigurer() (probers.Configurer, error) {
configurer, err := probers.GetConfigurer(c.Kind)
if err != nil {
return nil, err
}
settings, _ := yaml.Marshal(c.Settings)
configurer, err = configurer.UnmarshalSettings(settings)
if err != nil {
return nil, err
}
return configurer, nil
}
// makeMonitor constructs a `monitor` object from the contents of the
// bound `MonConf`. If the `MonConf` cannot be validated, an error
// appropriate for end-user consumption is returned instead.
func (c MonConf) makeMonitor(collectors map[string]prometheus.Collector) (*monitor, error) {
err := c.validatePeriod()
if err != nil {
return nil, err
}
probeConf, err := c.unmarshalConfigurer()
if err != nil {
return nil, err
}
prober, err := probeConf.MakeProber(collectors)
if err != nil {
return nil, err
}
return &monitor{c.Period.Duration, prober}, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/mon_conf_test.go | third-party/github.com/letsencrypt/boulder/observer/mon_conf_test.go | package observer
import (
"testing"
"time"
"github.com/letsencrypt/boulder/config"
"github.com/letsencrypt/boulder/test"
)
func TestMonConf_validatePeriod(t *testing.T) {
type fields struct {
Period config.Duration
}
tests := []struct {
name string
fields fields
wantErr bool
}{
{"valid", fields{config.Duration{Duration: 1 * time.Microsecond}}, false},
{"1 nanosecond", fields{config.Duration{Duration: 1 * time.Nanosecond}}, true},
{"none supplied", fields{config.Duration{}}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &MonConf{
Period: tt.fields.Period,
}
err := c.validatePeriod()
if tt.wantErr {
test.AssertError(t, err, "MonConf.validatePeriod() should have errored")
} else {
test.AssertNotError(t, err, "MonConf.validatePeriod() shouldn't have errored")
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/monitor.go | third-party/github.com/letsencrypt/boulder/observer/monitor.go | package observer
import (
"strconv"
"time"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/observer/probers"
)
type monitor struct {
period time.Duration
prober probers.Prober
}
// start spins off a 'Prober' goroutine on an interval of `m.period`
// with a timeout of half `m.period`
func (m monitor) start(logger blog.Logger) {
ticker := time.NewTicker(m.period)
timeout := m.period / 2
for {
go func() {
// Attempt to probe the configured target.
success, dur := m.prober.Probe(timeout)
// Produce metrics to be scraped by Prometheus.
histObservations.WithLabelValues(
m.prober.Name(), m.prober.Kind(), strconv.FormatBool(success),
).Observe(dur.Seconds())
// Log the outcome of the probe attempt.
logger.Infof(
"kind=[%s] success=[%v] duration=[%f] name=[%s]",
m.prober.Kind(), success, dur.Seconds(), m.prober.Name())
}()
<-ticker.C
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/prober.go | third-party/github.com/letsencrypt/boulder/observer/probers/prober.go | package probers
import (
"fmt"
"strings"
"time"
"github.com/letsencrypt/boulder/cmd"
"github.com/prometheus/client_golang/prometheus"
)
var (
// Registry is the global mapping of all `Configurer` types. Types
// are added to this mapping on import by including a call to
// `Register` in their `init` function.
Registry = make(map[string]Configurer)
)
// Prober is the interface for `Prober` types.
type Prober interface {
// Name returns a name that uniquely identifies the monitor that
// configured this `Prober`.
Name() string
// Kind returns a name that uniquely identifies the `Kind` of
// `Prober`.
Kind() string
// Probe attempts the configured request or query, Each `Prober`
// must treat the duration passed to it as a timeout.
Probe(time.Duration) (bool, time.Duration)
}
// Configurer is the interface for `Configurer` types.
type Configurer interface {
// Kind returns a name that uniquely identifies the `Kind` of
// `Configurer`.
Kind() string
// UnmarshalSettings unmarshals YAML as bytes to a `Configurer`
// object.
UnmarshalSettings([]byte) (Configurer, error)
// MakeProber constructs a `Prober` object from the contents of the
// bound `Configurer` object. If the `Configurer` cannot be
// validated, an error appropriate for end-user consumption is
// returned instead. The map of `prometheus.Collector` objects passed to
// MakeProber should be the same as the return value from Instrument()
MakeProber(map[string]prometheus.Collector) (Prober, error)
// Instrument constructs any `prometheus.Collector` objects that a prober of
// the configured type will need to report its own metrics. A map is
// returned containing the constructed objects, indexed by the name of the
// prometheus metric. If no objects were constructed, nil is returned.
Instrument() map[string]prometheus.Collector
}
// Settings is exported as a temporary receiver for the `settings` field
// of `MonConf`. `Settings` is always marshaled back to bytes and then
// unmarshalled into the `Configurer` specified by the `Kind` field of
// the `MonConf`.
type Settings map[string]interface{}
// normalizeKind normalizes the input string by stripping spaces and
// transforming it into lowercase
func normalizeKind(kind string) string {
return strings.Trim(strings.ToLower(kind), " ")
}
// GetConfigurer returns the probe configurer specified by name from
// `Registry`.
func GetConfigurer(kind string) (Configurer, error) {
name := normalizeKind(kind)
// check if exists
if _, ok := Registry[name]; ok {
return Registry[name], nil
}
return nil, fmt.Errorf("%s is not a registered Prober type", kind)
}
// Register is called by the `init` function of every `Configurer` to
// add the caller to the global `Registry` map. If the caller attempts
// to add a `Configurer` to the registry using the same name as a prior
// `Configurer` Observer will exit after logging an error.
func Register(c Configurer) {
name := normalizeKind(c.Kind())
// check for name collision
if _, exists := Registry[name]; exists {
cmd.Fail(fmt.Sprintf(
"problem registering configurer %s: name collision", c.Kind()))
}
Registry[name] = c
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/tls/tls_conf.go | third-party/github.com/letsencrypt/boulder/observer/probers/tls/tls_conf.go | package probers
import (
"fmt"
"net"
"net/url"
"strconv"
"strings"
"github.com/prometheus/client_golang/prometheus"
"github.com/letsencrypt/boulder/observer/probers"
"github.com/letsencrypt/boulder/strictyaml"
)
const (
notAfterName = "obs_tls_not_after"
notBeforeName = "obs_tls_not_before"
reasonName = "obs_tls_reason"
)
// TLSConf is exported to receive YAML configuration.
type TLSConf struct {
Hostname string `yaml:"hostname"`
RootOrg string `yaml:"rootOrg"`
RootCN string `yaml:"rootCN"`
Response string `yaml:"response"`
}
// Kind returns a name that uniquely identifies the `Kind` of `Configurer`.
func (c TLSConf) Kind() string {
return "TLS"
}
// UnmarshalSettings takes YAML as bytes and unmarshals it to the to an TLSConf
// object.
func (c TLSConf) UnmarshalSettings(settings []byte) (probers.Configurer, error) {
var conf TLSConf
err := strictyaml.Unmarshal(settings, &conf)
if err != nil {
return nil, err
}
return conf, nil
}
func (c TLSConf) validateHostname() error {
hostname := c.Hostname
if strings.Contains(c.Hostname, ":") {
host, port, err := net.SplitHostPort(c.Hostname)
if err != nil {
return fmt.Errorf("invalid 'hostname', got %q, expected a valid hostport: %s", c.Hostname, err)
}
_, err = strconv.Atoi(port)
if err != nil {
return fmt.Errorf("invalid 'hostname', got %q, expected a valid hostport: %s", c.Hostname, err)
}
hostname = host
}
url, err := url.Parse(hostname)
if err != nil {
return fmt.Errorf("invalid 'hostname', got %q, expected a valid hostname: %s", c.Hostname, err)
}
if url.Scheme != "" {
return fmt.Errorf("invalid 'hostname', got: %q, should not include scheme", c.Hostname)
}
return nil
}
func (c TLSConf) validateResponse() error {
acceptable := []string{"valid", "expired", "revoked"}
for _, a := range acceptable {
if strings.ToLower(c.Response) == a {
return nil
}
}
return fmt.Errorf(
"invalid `response`, got %q. Must be one of %s", c.Response, acceptable)
}
// MakeProber constructs a `TLSProbe` object from the contents of the bound
// `TLSConf` object. If the `TLSConf` cannot be validated, an error appropriate
// for end-user consumption is returned instead.
func (c TLSConf) MakeProber(collectors map[string]prometheus.Collector) (probers.Prober, error) {
// Validate `hostname`
err := c.validateHostname()
if err != nil {
return nil, err
}
// Valid `response`
err = c.validateResponse()
if err != nil {
return nil, err
}
// Validate the Prometheus collectors that were passed in
coll, ok := collectors[notAfterName]
if !ok {
return nil, fmt.Errorf("tls prober did not receive collector %q", notAfterName)
}
notAfterColl, ok := coll.(*prometheus.GaugeVec)
if !ok {
return nil, fmt.Errorf("tls prober received collector %q of wrong type, got: %T, expected *prometheus.GaugeVec", notAfterName, coll)
}
coll, ok = collectors[notBeforeName]
if !ok {
return nil, fmt.Errorf("tls prober did not receive collector %q", notBeforeName)
}
notBeforeColl, ok := coll.(*prometheus.GaugeVec)
if !ok {
return nil, fmt.Errorf("tls prober received collector %q of wrong type, got: %T, expected *prometheus.GaugeVec", notBeforeName, coll)
}
coll, ok = collectors[reasonName]
if !ok {
return nil, fmt.Errorf("tls prober did not receive collector %q", reasonName)
}
reasonColl, ok := coll.(*prometheus.CounterVec)
if !ok {
return nil, fmt.Errorf("tls prober received collector %q of wrong type, got: %T, expected *prometheus.CounterVec", reasonName, coll)
}
return TLSProbe{c.Hostname, c.RootOrg, c.RootCN, strings.ToLower(c.Response), notAfterColl, notBeforeColl, reasonColl}, nil
}
// Instrument constructs any `prometheus.Collector` objects the `TLSProbe` will
// need to report its own metrics. A map is returned containing the constructed
// objects, indexed by the name of the Promtheus metric. If no objects were
// constructed, nil is returned.
func (c TLSConf) Instrument() map[string]prometheus.Collector {
notBefore := prometheus.Collector(prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: notBeforeName,
Help: "Certificate notBefore value as a Unix timestamp in seconds",
}, []string{"hostname"},
))
notAfter := prometheus.Collector(prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: notAfterName,
Help: "Certificate notAfter value as a Unix timestamp in seconds",
}, []string{"hostname"},
))
reason := prometheus.Collector(prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: reasonName,
Help: fmt.Sprintf("Reason for TLS Prober check failure. Can be one of %s", getReasons()),
}, []string{"hostname", "reason"},
))
return map[string]prometheus.Collector{
notAfterName: notAfter,
notBeforeName: notBefore,
reasonName: reason,
}
}
// init is called at runtime and registers `TLSConf`, a `Prober` `Configurer`
// type, as "TLS".
func init() {
probers.Register(TLSConf{})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/tls/tls_conf_test.go | third-party/github.com/letsencrypt/boulder/observer/probers/tls/tls_conf_test.go | package probers
import (
"reflect"
"testing"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/yaml.v3"
"github.com/letsencrypt/boulder/observer/probers"
)
func TestTLSConf_MakeProber(t *testing.T) {
goodHostname, goodRootCN, goodResponse := "example.com", "ISRG Root X1", "valid"
colls := TLSConf{}.Instrument()
badColl := prometheus.Collector(prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "obs_crl_foo",
Help: "Hmmm, this shouldn't be here...",
},
[]string{},
))
type fields struct {
Hostname string
RootCN string
Response string
}
tests := []struct {
name string
fields fields
colls map[string]prometheus.Collector
wantErr bool
}{
// valid
{"valid hostname", fields{"example.com", goodRootCN, "valid"}, colls, false},
{"valid hostname with path", fields{"example.com/foo/bar", "ISRG Root X2", "Revoked"}, colls, false},
{"valid hostname with port", fields{"example.com:8080", goodRootCN, "expired"}, colls, false},
// invalid hostname
{"bad hostname", fields{":::::", goodRootCN, goodResponse}, colls, true},
{"included scheme", fields{"https://example.com", goodRootCN, goodResponse}, colls, true},
{"included scheme and port", fields{"https://example.com:443", goodRootCN, goodResponse}, colls, true},
// invalid response
{"empty response", fields{goodHostname, goodRootCN, ""}, colls, true},
{"unaccepted response", fields{goodHostname, goodRootCN, "invalid"}, colls, true},
// invalid collector
{
"unexpected collector",
fields{"http://example.com", goodRootCN, goodResponse},
map[string]prometheus.Collector{"obs_crl_foo": badColl},
true,
},
{
"missing collectors",
fields{"http://example.com", goodRootCN, goodResponse},
map[string]prometheus.Collector{},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := TLSConf{
Hostname: tt.fields.Hostname,
RootCN: tt.fields.RootCN,
Response: tt.fields.Response,
}
if _, err := c.MakeProber(tt.colls); (err != nil) != tt.wantErr {
t.Errorf("TLSConf.Validate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestTLSConf_UnmarshalSettings(t *testing.T) {
type fields struct {
hostname interface{}
rootOrg interface{}
rootCN interface{}
response interface{}
}
tests := []struct {
name string
fields fields
want probers.Configurer
wantErr bool
}{
{"valid", fields{"google.com", "", "ISRG Root X1", "valid"}, TLSConf{"google.com", "", "ISRG Root X1", "valid"}, false},
{"invalid hostname (map)", fields{make(map[string]interface{}), 42, 42, 42}, nil, true},
{"invalid rootOrg (list)", fields{42, make([]string, 0), 42, 42}, nil, true},
{"invalid response (list)", fields{42, 42, 42, make([]string, 0)}, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
settings := probers.Settings{
"hostname": tt.fields.hostname,
"rootOrg": tt.fields.rootOrg,
"rootCN": tt.fields.rootCN,
"response": tt.fields.response,
}
settingsBytes, _ := yaml.Marshal(settings)
c := TLSConf{}
got, err := c.UnmarshalSettings(settingsBytes)
if (err != nil) != tt.wantErr {
t.Errorf("DNSConf.UnmarshalSettings() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("DNSConf.UnmarshalSettings() = %v, want %v", got, tt.want)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/tls/tls.go | third-party/github.com/letsencrypt/boulder/observer/probers/tls/tls.go | package probers
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/ocsp"
"github.com/letsencrypt/boulder/observer/obsdialer"
)
type reason int
const (
none reason = iota
internalError
revocationStatusError
rootDidNotMatch
statusDidNotMatch
)
var reasonToString = map[reason]string{
none: "nil",
internalError: "internalError",
revocationStatusError: "revocationStatusError",
rootDidNotMatch: "rootDidNotMatch",
statusDidNotMatch: "statusDidNotMatch",
}
func getReasons() []string {
var allReasons []string
for _, v := range reasonToString {
allReasons = append(allReasons, v)
}
return allReasons
}
// TLSProbe is the exported `Prober` object for monitors configured to perform
// TLS protocols.
type TLSProbe struct {
hostname string
rootOrg string
rootCN string
response string
notAfter *prometheus.GaugeVec
notBefore *prometheus.GaugeVec
reason *prometheus.CounterVec
}
// Name returns a string that uniquely identifies the monitor.
func (p TLSProbe) Name() string {
return p.hostname
}
// Kind returns a name that uniquely identifies the `Kind` of `Prober`.
func (p TLSProbe) Kind() string {
return "TLS"
}
// Get OCSP status (good, revoked or unknown) of certificate
func checkOCSP(ctx context.Context, cert, issuer *x509.Certificate, want int) (bool, error) {
req, err := ocsp.CreateRequest(cert, issuer, nil)
if err != nil {
return false, err
}
url := fmt.Sprintf("%s/%s", cert.OCSPServer[0], base64.StdEncoding.EncodeToString(req))
r, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return false, err
}
res, err := http.DefaultClient.Do(r)
if err != nil {
return false, err
}
output, err := io.ReadAll(res.Body)
if err != nil {
return false, err
}
ocspRes, err := ocsp.ParseResponseForCert(output, cert, issuer)
if err != nil {
return false, err
}
return ocspRes.Status == want, nil
}
func checkCRL(ctx context.Context, cert, issuer *x509.Certificate, want int) (bool, error) {
if len(cert.CRLDistributionPoints) != 1 {
return false, errors.New("cert does not contain CRLDP URI")
}
req, err := http.NewRequestWithContext(ctx, "GET", cert.CRLDistributionPoints[0], nil)
if err != nil {
return false, fmt.Errorf("creating HTTP request: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false, fmt.Errorf("downloading CRL: %w", err)
}
defer resp.Body.Close()
der, err := io.ReadAll(resp.Body)
if err != nil {
return false, fmt.Errorf("reading CRL: %w", err)
}
crl, err := x509.ParseRevocationList(der)
if err != nil {
return false, fmt.Errorf("parsing CRL: %w", err)
}
err = crl.CheckSignatureFrom(issuer)
if err != nil {
return false, fmt.Errorf("validating CRL: %w", err)
}
for _, entry := range crl.RevokedCertificateEntries {
if entry.SerialNumber.Cmp(cert.SerialNumber) == 0 {
return want == ocsp.Revoked, nil
}
}
return want == ocsp.Good, nil
}
// Return an error if the root settings are nonempty and do not match the
// expected root.
func (p TLSProbe) checkRoot(rootOrg, rootCN string) error {
if (p.rootCN == "" && p.rootOrg == "") || (rootOrg == p.rootOrg && rootCN == p.rootCN) {
return nil
}
return fmt.Errorf("Expected root does not match.")
}
// Export expiration timestamp and reason to Prometheus.
func (p TLSProbe) exportMetrics(cert *x509.Certificate, reason reason) {
if cert != nil {
p.notAfter.WithLabelValues(p.hostname).Set(float64(cert.NotAfter.Unix()))
p.notBefore.WithLabelValues(p.hostname).Set(float64(cert.NotBefore.Unix()))
}
p.reason.WithLabelValues(p.hostname, reasonToString[reason]).Inc()
}
func (p TLSProbe) probeExpired(timeout time.Duration) bool {
addr := p.hostname
_, _, err := net.SplitHostPort(addr)
if err != nil {
addr = net.JoinHostPort(addr, "443")
}
tlsDialer := tls.Dialer{
NetDialer: &obsdialer.Dialer,
Config: &tls.Config{
// Set InsecureSkipVerify to skip the default validation we are
// replacing. This will not disable VerifyConnection.
InsecureSkipVerify: true,
VerifyConnection: func(cs tls.ConnectionState) error {
issuers := x509.NewCertPool()
for _, cert := range cs.PeerCertificates[1:] {
issuers.AddCert(cert)
}
opts := x509.VerifyOptions{
// We set the current time to be the cert's expiration date so that
// the validation routine doesn't complain that the cert is expired.
CurrentTime: cs.PeerCertificates[0].NotAfter,
// By settings roots and intermediates to be whatever was presented
// in the handshake, we're saying that we don't care about the cert
// chaining up to the system trust store. This is safe because we
// check the root ourselves in checkRoot().
Intermediates: issuers,
Roots: issuers,
}
_, err := cs.PeerCertificates[0].Verify(opts)
return err
},
},
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
conn, err := tlsDialer.DialContext(ctx, "tcp", addr)
if err != nil {
p.exportMetrics(nil, internalError)
return false
}
defer conn.Close()
// tls.Dialer.DialContext is documented to always return *tls.Conn
peers := conn.(*tls.Conn).ConnectionState().PeerCertificates
if time.Until(peers[0].NotAfter) > 0 {
p.exportMetrics(peers[0], statusDidNotMatch)
return false
}
root := peers[len(peers)-1].Issuer
err = p.checkRoot(root.Organization[0], root.CommonName)
if err != nil {
p.exportMetrics(peers[0], rootDidNotMatch)
return false
}
p.exportMetrics(peers[0], none)
return true
}
func (p TLSProbe) probeUnexpired(timeout time.Duration) bool {
addr := p.hostname
_, _, err := net.SplitHostPort(addr)
if err != nil {
addr = net.JoinHostPort(addr, "443")
}
tlsDialer := tls.Dialer{
NetDialer: &obsdialer.Dialer,
Config: &tls.Config{
// Set InsecureSkipVerify to skip the default validation we are
// replacing. This will not disable VerifyConnection.
InsecureSkipVerify: true,
VerifyConnection: func(cs tls.ConnectionState) error {
issuers := x509.NewCertPool()
for _, cert := range cs.PeerCertificates[1:] {
issuers.AddCert(cert)
}
opts := x509.VerifyOptions{
// By settings roots and intermediates to be whatever was presented
// in the handshake, we're saying that we don't care about the cert
// chaining up to the system trust store. This is safe because we
// check the root ourselves in checkRoot().
Intermediates: issuers,
Roots: issuers,
}
_, err := cs.PeerCertificates[0].Verify(opts)
return err
},
},
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
conn, err := tlsDialer.DialContext(ctx, "tcp", addr)
if err != nil {
p.exportMetrics(nil, internalError)
return false
}
defer conn.Close()
// tls.Dialer.DialContext is documented to always return *tls.Conn
peers := conn.(*tls.Conn).ConnectionState().PeerCertificates
root := peers[len(peers)-1].Issuer
err = p.checkRoot(root.Organization[0], root.CommonName)
if err != nil {
p.exportMetrics(peers[0], rootDidNotMatch)
return false
}
var wantStatus int
switch p.response {
case "valid":
wantStatus = ocsp.Good
case "revoked":
wantStatus = ocsp.Revoked
}
var statusMatch bool
if len(peers[0].OCSPServer) != 0 {
statusMatch, err = checkOCSP(ctx, peers[0], peers[1], wantStatus)
} else {
statusMatch, err = checkCRL(ctx, peers[0], peers[1], wantStatus)
}
if err != nil {
p.exportMetrics(peers[0], revocationStatusError)
return false
}
if !statusMatch {
p.exportMetrics(peers[0], statusDidNotMatch)
return false
}
p.exportMetrics(peers[0], none)
return true
}
// Probe performs the configured TLS probe. Return true if the root has the
// expected Subject (or if no root is provided for comparison in settings), and
// the end entity certificate has the correct expiration status (either expired
// or unexpired, depending on what is configured). Exports metrics for the
// NotAfter timestamp of the end entity certificate and the reason for the Probe
// returning false ("none" if returns true).
func (p TLSProbe) Probe(timeout time.Duration) (bool, time.Duration) {
start := time.Now()
var success bool
if p.response == "expired" {
success = p.probeExpired(timeout)
} else {
success = p.probeUnexpired(timeout)
}
return success, time.Since(start)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/tcp/tcp.go | third-party/github.com/letsencrypt/boulder/observer/probers/tcp/tcp.go | package tcp
import (
"context"
"time"
"github.com/letsencrypt/boulder/observer/obsdialer"
)
type TCPProbe struct {
hostport string
}
// Name returns a string that uniquely identifies the monitor.
func (p TCPProbe) Name() string {
return p.hostport
}
// Kind returns a name that uniquely identifies the `Kind` of `Prober`.
func (p TCPProbe) Kind() string {
return "TCP"
}
// Probe performs the configured TCP dial.
func (p TCPProbe) Probe(timeout time.Duration) (bool, time.Duration) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
start := time.Now()
c, err := obsdialer.Dialer.DialContext(ctx, "tcp", p.hostport)
if err != nil {
return false, time.Since(start)
}
c.Close()
return true, time.Since(start)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/tcp/tcp_conf.go | third-party/github.com/letsencrypt/boulder/observer/probers/tcp/tcp_conf.go | package tcp
import (
"github.com/letsencrypt/boulder/observer/probers"
"github.com/letsencrypt/boulder/strictyaml"
"github.com/prometheus/client_golang/prometheus"
)
// TCPConf is exported to receive YAML configuration.
type TCPConf struct {
Hostport string `yaml:"hostport"`
}
// Kind returns a name that uniquely identifies the `Kind` of `Configurer`.
func (c TCPConf) Kind() string {
return "TCP"
}
// UnmarshalSettings takes YAML as bytes and unmarshals it to the to an
// TCPConf object.
func (c TCPConf) UnmarshalSettings(settings []byte) (probers.Configurer, error) {
var conf TCPConf
err := strictyaml.Unmarshal(settings, &conf)
if err != nil {
return nil, err
}
return conf, nil
}
// MakeProber constructs a `TCPPProbe` object from the contents of the
// bound `TCPPConf` object.
func (c TCPConf) MakeProber(_ map[string]prometheus.Collector) (probers.Prober, error) {
return TCPProbe{c.Hostport}, nil
}
// Instrument is a no-op to implement the `Configurer` interface.
func (c TCPConf) Instrument() map[string]prometheus.Collector {
return nil
}
// init is called at runtime and registers `TCPConf`, a `Prober`
// `Configurer` type, as "TCP".
func init() {
probers.Register(TCPConf{})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/mock/mock_conf.go | third-party/github.com/letsencrypt/boulder/observer/probers/mock/mock_conf.go | package probers
import (
"errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/letsencrypt/boulder/config"
"github.com/letsencrypt/boulder/observer/probers"
"github.com/letsencrypt/boulder/strictyaml"
)
type MockConfigurer struct {
Valid bool `yaml:"valid"`
ErrMsg string `yaml:"errmsg"`
PName string `yaml:"pname"`
PKind string `yaml:"pkind"`
PTook config.Duration `yaml:"ptook"`
PSuccess bool `yaml:"psuccess"`
}
// Kind returns a name that uniquely identifies the `Kind` of `Configurer`.
func (c MockConfigurer) Kind() string {
return "Mock"
}
func (c MockConfigurer) UnmarshalSettings(settings []byte) (probers.Configurer, error) {
var conf MockConfigurer
err := strictyaml.Unmarshal(settings, &conf)
if err != nil {
return nil, err
}
return conf, nil
}
func (c MockConfigurer) MakeProber(_ map[string]prometheus.Collector) (probers.Prober, error) {
if !c.Valid {
return nil, errors.New("could not be validated")
}
return MockProber{c.PName, c.PKind, c.PTook, c.PSuccess}, nil
}
func (c MockConfigurer) Instrument() map[string]prometheus.Collector {
return nil
}
func init() {
probers.Register(MockConfigurer{})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/mock/mock_prober.go | third-party/github.com/letsencrypt/boulder/observer/probers/mock/mock_prober.go | package probers
import (
"time"
"github.com/letsencrypt/boulder/config"
)
type MockProber struct {
name string
kind string
took config.Duration
success bool
}
func (p MockProber) Name() string {
return p.name
}
func (p MockProber) Kind() string {
return p.kind
}
func (p MockProber) Probe(timeout time.Duration) (bool, time.Duration) {
return p.success, p.took.Duration
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/crl/crl_conf.go | third-party/github.com/letsencrypt/boulder/observer/probers/crl/crl_conf.go | package probers
import (
"fmt"
"net/url"
"github.com/prometheus/client_golang/prometheus"
"github.com/letsencrypt/boulder/observer/probers"
"github.com/letsencrypt/boulder/strictyaml"
)
const (
nextUpdateName = "obs_crl_next_update"
thisUpdateName = "obs_crl_this_update"
certCountName = "obs_crl_revoked_cert_count"
)
// CRLConf is exported to receive YAML configuration
type CRLConf struct {
URL string `yaml:"url"`
Partitioned bool `yaml:"partitioned"`
}
// Kind returns a name that uniquely identifies the `Kind` of `Configurer`.
func (c CRLConf) Kind() string {
return "CRL"
}
// UnmarshalSettings constructs a CRLConf object from YAML as bytes.
func (c CRLConf) UnmarshalSettings(settings []byte) (probers.Configurer, error) {
var conf CRLConf
err := strictyaml.Unmarshal(settings, &conf)
if err != nil {
return nil, err
}
return conf, nil
}
func (c CRLConf) validateURL() error {
url, err := url.Parse(c.URL)
if err != nil {
return fmt.Errorf(
"invalid 'url', got: %q, expected a valid url", c.URL)
}
if url.Scheme == "" {
return fmt.Errorf(
"invalid 'url', got: %q, missing scheme", c.URL)
}
return nil
}
// MakeProber constructs a `CRLProbe` object from the contents of the
// bound `CRLConf` object. If the `CRLConf` cannot be validated, an
// error appropriate for end-user consumption is returned instead.
func (c CRLConf) MakeProber(collectors map[string]prometheus.Collector) (probers.Prober, error) { // validate `url` err := c.validateURL()
// validate `url`
err := c.validateURL()
if err != nil {
return nil, err
}
// validate the prometheus collectors that were passed in
coll, ok := collectors[nextUpdateName]
if !ok {
return nil, fmt.Errorf("crl prober did not receive collector %q", nextUpdateName)
}
nextUpdateColl, ok := coll.(*prometheus.GaugeVec)
if !ok {
return nil, fmt.Errorf("crl prober received collector %q of wrong type, got: %T, expected *prometheus.GaugeVec", nextUpdateName, coll)
}
coll, ok = collectors[thisUpdateName]
if !ok {
return nil, fmt.Errorf("crl prober did not receive collector %q", thisUpdateName)
}
thisUpdateColl, ok := coll.(*prometheus.GaugeVec)
if !ok {
return nil, fmt.Errorf("crl prober received collector %q of wrong type, got: %T, expected *prometheus.GaugeVec", thisUpdateName, coll)
}
coll, ok = collectors[certCountName]
if !ok {
return nil, fmt.Errorf("crl prober did not receive collector %q", certCountName)
}
certCountColl, ok := coll.(*prometheus.GaugeVec)
if !ok {
return nil, fmt.Errorf("crl prober received collector %q of wrong type, got: %T, expected *prometheus.GaugeVec", certCountName, coll)
}
return CRLProbe{c.URL, c.Partitioned, nextUpdateColl, thisUpdateColl, certCountColl}, nil
}
// Instrument constructs any `prometheus.Collector` objects the `CRLProbe` will
// need to report its own metrics. A map is returned containing the constructed
// objects, indexed by the name of the prometheus metric. If no objects were
// constructed, nil is returned.
func (c CRLConf) Instrument() map[string]prometheus.Collector {
nextUpdate := prometheus.Collector(prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: nextUpdateName,
Help: "CRL nextUpdate Unix timestamp in seconds",
}, []string{"url"},
))
thisUpdate := prometheus.Collector(prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: thisUpdateName,
Help: "CRL thisUpdate Unix timestamp in seconds",
}, []string{"url"},
))
certCount := prometheus.Collector(prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: certCountName,
Help: "number of certificates revoked in CRL",
}, []string{"url"},
))
return map[string]prometheus.Collector{
nextUpdateName: nextUpdate,
thisUpdateName: thisUpdate,
certCountName: certCount,
}
}
// init is called at runtime and registers `CRLConf`, a `Prober`
// `Configurer` type, as "CRL".
func init() {
probers.Register(CRLConf{})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/crl/crl.go | third-party/github.com/letsencrypt/boulder/observer/probers/crl/crl.go | package probers
import (
"crypto/x509"
"io"
"net/http"
"slices"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/letsencrypt/boulder/crl/idp"
)
// CRLProbe is the exported 'Prober' object for monitors configured to
// monitor CRL availability & characteristics.
type CRLProbe struct {
url string
partitioned bool
cNextUpdate *prometheus.GaugeVec
cThisUpdate *prometheus.GaugeVec
cCertCount *prometheus.GaugeVec
}
// Name returns a string that uniquely identifies the monitor.
func (p CRLProbe) Name() string {
return p.url
}
// Kind returns a name that uniquely identifies the `Kind` of `Prober`.
func (p CRLProbe) Kind() string {
return "CRL"
}
// Probe requests the configured CRL and publishes metrics about it if found.
func (p CRLProbe) Probe(timeout time.Duration) (bool, time.Duration) {
start := time.Now()
resp, err := http.Get(p.url)
if err != nil {
return false, time.Since(start)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return false, time.Since(start)
}
dur := time.Since(start)
crl, err := x509.ParseRevocationList(body)
if err != nil {
return false, dur
}
// Partitioned CRLs MUST contain an issuingDistributionPoint extension, which
// MUST contain the URL from which they were fetched, to prevent substitution
// attacks.
if p.partitioned {
idps, err := idp.GetIDPURIs(crl.Extensions)
if err != nil {
return false, dur
}
if !slices.Contains(idps, p.url) {
return false, dur
}
}
// Report metrics for this CRL
p.cThisUpdate.WithLabelValues(p.url).Set(float64(crl.ThisUpdate.Unix()))
p.cNextUpdate.WithLabelValues(p.url).Set(float64(crl.NextUpdate.Unix()))
p.cCertCount.WithLabelValues(p.url).Set(float64(len(crl.RevokedCertificateEntries)))
return true, dur
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/crl/crl_conf_test.go | third-party/github.com/letsencrypt/boulder/observer/probers/crl/crl_conf_test.go | package probers
import (
"testing"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/yaml.v3"
"github.com/letsencrypt/boulder/observer/probers"
"github.com/letsencrypt/boulder/test"
)
func TestCRLConf_MakeProber(t *testing.T) {
conf := CRLConf{}
colls := conf.Instrument()
badColl := prometheus.Collector(prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "obs_crl_foo",
Help: "Hmmm, this shouldn't be here...",
},
[]string{},
))
type fields struct {
URL string
}
tests := []struct {
name string
fields fields
colls map[string]prometheus.Collector
wantErr bool
}{
// valid
{"valid fqdn", fields{"http://example.com"}, colls, false},
{"valid fqdn with path", fields{"http://example.com/foo/bar"}, colls, false},
{"valid hostname", fields{"http://example"}, colls, false},
// invalid
{"bad fqdn", fields{":::::"}, colls, true},
{"missing scheme", fields{"example.com"}, colls, true},
{
"unexpected collector",
fields{"http://example.com"},
map[string]prometheus.Collector{"obs_crl_foo": badColl},
true,
},
{
"missing collectors",
fields{"http://example.com"},
map[string]prometheus.Collector{},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := CRLConf{
URL: tt.fields.URL,
}
p, err := c.MakeProber(tt.colls)
if tt.wantErr {
test.AssertError(t, err, "CRLConf.MakeProber()")
} else {
test.AssertNotError(t, err, "CRLConf.MakeProber()")
test.AssertNotNil(t, p, "CRLConf.MakeProber(): nil prober")
prober := p.(CRLProbe)
test.AssertNotNil(t, prober.cThisUpdate, "CRLConf.MakeProber(): nil cThisUpdate")
test.AssertNotNil(t, prober.cNextUpdate, "CRLConf.MakeProber(): nil cNextUpdate")
test.AssertNotNil(t, prober.cCertCount, "CRLConf.MakeProber(): nil cCertCount")
}
})
}
}
func TestCRLConf_UnmarshalSettings(t *testing.T) {
tests := []struct {
name string
fields probers.Settings
want probers.Configurer
wantErr bool
}{
{"valid", probers.Settings{"url": "google.com"}, CRLConf{"google.com", false}, false},
{"valid with partitioned", probers.Settings{"url": "google.com", "partitioned": true}, CRLConf{"google.com", true}, false},
{"invalid (map)", probers.Settings{"url": make(map[string]interface{})}, nil, true},
{"invalid (list)", probers.Settings{"url": make([]string, 0)}, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
settingsBytes, _ := yaml.Marshal(tt.fields)
t.Log(string(settingsBytes))
c := CRLConf{}
got, err := c.UnmarshalSettings(settingsBytes)
if tt.wantErr {
test.AssertError(t, err, "CRLConf.UnmarshalSettings()")
} else {
test.AssertNotError(t, err, "CRLConf.UnmarshalSettings()")
}
test.AssertDeepEquals(t, got, tt.want)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/dns/dns.go | third-party/github.com/letsencrypt/boulder/observer/probers/dns/dns.go | package probers
import (
"fmt"
"time"
"github.com/miekg/dns"
)
// DNSProbe is the exported 'Prober' object for monitors configured to
// perform DNS requests.
type DNSProbe struct {
proto string
server string
recurse bool
qname string
qtype uint16
}
// Name returns a string that uniquely identifies the monitor.
func (p DNSProbe) Name() string {
recursion := func() string {
if p.recurse {
return "recurse"
}
return "no-recurse"
}()
return fmt.Sprintf(
"%s-%s-%s-%s-%s", p.server, p.proto, recursion, dns.TypeToString[p.qtype], p.qname)
}
// Kind returns a name that uniquely identifies the `Kind` of `Prober`.
func (p DNSProbe) Kind() string {
return "DNS"
}
// Probe performs the configured DNS query.
func (p DNSProbe) Probe(timeout time.Duration) (bool, time.Duration) {
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(p.qname), p.qtype)
m.RecursionDesired = p.recurse
c := dns.Client{Timeout: timeout, Net: p.proto}
start := time.Now()
r, _, err := c.Exchange(m, p.server)
if err != nil {
return false, time.Since(start)
}
if r == nil {
return false, time.Since(start)
}
if r.Rcode != dns.RcodeSuccess {
return false, time.Since(start)
}
return true, time.Since(start)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/dns/dns_conf.go | third-party/github.com/letsencrypt/boulder/observer/probers/dns/dns_conf.go | package probers
import (
"fmt"
"net"
"net/netip"
"strconv"
"strings"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
"github.com/letsencrypt/boulder/observer/probers"
"github.com/letsencrypt/boulder/strictyaml"
)
var (
validQTypes = map[string]uint16{"A": 1, "TXT": 16, "AAAA": 28, "CAA": 257}
)
// DNSConf is exported to receive YAML configuration
type DNSConf struct {
Proto string `yaml:"protocol"`
Server string `yaml:"server"`
Recurse bool `yaml:"recurse"`
QName string `yaml:"query_name"`
QType string `yaml:"query_type"`
}
// Kind returns a name that uniquely identifies the `Kind` of `Configurer`.
func (c DNSConf) Kind() string {
return "DNS"
}
// UnmarshalSettings constructs a DNSConf object from YAML as bytes.
func (c DNSConf) UnmarshalSettings(settings []byte) (probers.Configurer, error) {
var conf DNSConf
err := strictyaml.Unmarshal(settings, &conf)
if err != nil {
return nil, err
}
return conf, nil
}
func (c DNSConf) validateServer() error {
server := strings.Trim(strings.ToLower(c.Server), " ")
// Ensure `server` contains a port.
host, port, err := net.SplitHostPort(server)
if err != nil || port == "" {
return fmt.Errorf(
"invalid `server`, %q, could not be split: %s", c.Server, err)
}
// Ensure `server` port is valid.
portNum, err := strconv.Atoi(port)
if err != nil {
return fmt.Errorf(
"invalid `server`, %q, port must be a number", c.Server)
}
if portNum <= 0 || portNum > 65535 {
return fmt.Errorf(
"invalid `server`, %q, port number must be one in [1-65535]", c.Server)
}
// Ensure `server` is a valid FQDN or IP address.
_, err = netip.ParseAddr(host)
FQDN := dns.IsFqdn(dns.Fqdn(host))
if err != nil && !FQDN {
return fmt.Errorf(
"invalid `server`, %q, is not an FQDN or IP address", c.Server)
}
return nil
}
func (c DNSConf) validateProto() error {
validProtos := []string{"udp", "tcp"}
proto := strings.Trim(strings.ToLower(c.Proto), " ")
for _, i := range validProtos {
if proto == i {
return nil
}
}
return fmt.Errorf(
"invalid `protocol`, got: %q, expected one in: %s", c.Proto, validProtos)
}
func (c DNSConf) validateQType() error {
validQTypes = map[string]uint16{"A": 1, "TXT": 16, "AAAA": 28, "CAA": 257}
qtype := strings.Trim(strings.ToUpper(c.QType), " ")
q := make([]string, 0, len(validQTypes))
for i := range validQTypes {
q = append(q, i)
if qtype == i {
return nil
}
}
return fmt.Errorf(
"invalid `query_type`, got: %q, expected one in %s", c.QType, q)
}
// MakeProber constructs a `DNSProbe` object from the contents of the
// bound `DNSConf` object. If the `DNSConf` cannot be validated, an
// error appropriate for end-user consumption is returned instead.
func (c DNSConf) MakeProber(_ map[string]prometheus.Collector) (probers.Prober, error) {
// validate `query_name`
if !dns.IsFqdn(dns.Fqdn(c.QName)) {
return nil, fmt.Errorf(
"invalid `query_name`, %q is not an fqdn", c.QName)
}
// validate `server`
err := c.validateServer()
if err != nil {
return nil, err
}
// validate `protocol`
err = c.validateProto()
if err != nil {
return nil, err
}
// validate `query_type`
err = c.validateQType()
if err != nil {
return nil, err
}
return DNSProbe{
proto: strings.Trim(strings.ToLower(c.Proto), " "),
recurse: c.Recurse,
qname: c.QName,
server: c.Server,
qtype: validQTypes[strings.Trim(strings.ToUpper(c.QType), " ")],
}, nil
}
// Instrument is a no-op to implement the `Configurer` interface.
func (c DNSConf) Instrument() map[string]prometheus.Collector {
return nil
}
// init is called at runtime and registers `DNSConf`, a `Prober`
// `Configurer` type, as "DNS".
func init() {
probers.Register(DNSConf{})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/dns/dns_conf_test.go | third-party/github.com/letsencrypt/boulder/observer/probers/dns/dns_conf_test.go | package probers
import (
"reflect"
"testing"
"github.com/letsencrypt/boulder/observer/probers"
"github.com/letsencrypt/boulder/test"
"gopkg.in/yaml.v3"
)
func TestDNSConf_validateServer(t *testing.T) {
type fields struct {
Server string
}
tests := []struct {
name string
fields fields
wantErr bool
}{
// ipv4 cases
{"ipv4 with port", fields{"1.1.1.1:53"}, false},
{"ipv4 without port", fields{"1.1.1.1"}, true},
{"ipv4 port num missing", fields{"1.1.1.1:"}, true},
{"ipv4 string for port", fields{"1.1.1.1:foo"}, true},
{"ipv4 port out of range high", fields{"1.1.1.1:65536"}, true},
{"ipv4 port out of range low", fields{"1.1.1.1:0"}, true},
// ipv6 cases
{"ipv6 with port", fields{"[2606:4700:4700::1111]:53"}, false},
{"ipv6 without port", fields{"[2606:4700:4700::1111]"}, true},
{"ipv6 port num missing", fields{"[2606:4700:4700::1111]:"}, true},
{"ipv6 string for port", fields{"[2606:4700:4700::1111]:foo"}, true},
{"ipv6 port out of range high", fields{"[2606:4700:4700::1111]:65536"}, true},
{"ipv6 port out of range low", fields{"[2606:4700:4700::1111]:0"}, true},
// hostname cases
{"hostname with port", fields{"foo:53"}, false},
{"hostname without port", fields{"foo"}, true},
{"hostname port num missing", fields{"foo:"}, true},
{"hostname string for port", fields{"foo:bar"}, true},
{"hostname port out of range high", fields{"foo:65536"}, true},
{"hostname port out of range low", fields{"foo:0"}, true},
// fqdn cases
{"fqdn with port", fields{"bar.foo.baz:53"}, false},
{"fqdn without port", fields{"bar.foo.baz"}, true},
{"fqdn port num missing", fields{"bar.foo.baz:"}, true},
{"fqdn string for port", fields{"bar.foo.baz:bar"}, true},
{"fqdn port out of range high", fields{"bar.foo.baz:65536"}, true},
{"fqdn port out of range low", fields{"bar.foo.baz:0"}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := DNSConf{
Server: tt.fields.Server,
}
err := c.validateServer()
if tt.wantErr {
test.AssertError(t, err, "DNSConf.validateServer() should have errored")
} else {
test.AssertNotError(t, err, "DNSConf.validateServer() shouldn't have errored")
}
})
}
}
func TestDNSConf_validateQType(t *testing.T) {
type fields struct {
QType string
}
tests := []struct {
name string
fields fields
wantErr bool
}{
// valid
{"A", fields{"A"}, false},
{"AAAA", fields{"AAAA"}, false},
{"TXT", fields{"TXT"}, false},
// invalid
{"AAA", fields{"AAA"}, true},
{"TXTT", fields{"TXTT"}, true},
{"D", fields{"D"}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := DNSConf{
QType: tt.fields.QType,
}
err := c.validateQType()
if tt.wantErr {
test.AssertError(t, err, "DNSConf.validateQType() should have errored")
} else {
test.AssertNotError(t, err, "DNSConf.validateQType() shouldn't have errored")
}
})
}
}
func TestDNSConf_validateProto(t *testing.T) {
type fields struct {
Proto string
}
tests := []struct {
name string
fields fields
wantErr bool
}{
// valid
{"tcp", fields{"tcp"}, false},
{"udp", fields{"udp"}, false},
// invalid
{"foo", fields{"foo"}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := DNSConf{
Proto: tt.fields.Proto,
}
err := c.validateProto()
if tt.wantErr {
test.AssertError(t, err, "DNSConf.validateProto() should have errored")
} else {
test.AssertNotError(t, err, "DNSConf.validateProto() shouldn't have errored")
}
})
}
}
func TestDNSConf_MakeProber(t *testing.T) {
type fields struct {
Proto string
Server string
Recurse bool
QName string
QType string
}
tests := []struct {
name string
fields fields
wantErr bool
}{
// valid
{"valid", fields{"udp", "1.1.1.1:53", true, "google.com", "A"}, false},
// invalid
{"bad proto", fields{"can with string", "1.1.1.1:53", true, "google.com", "A"}, true},
{"bad server", fields{"udp", "1.1.1.1:9000000", true, "google.com", "A"}, true},
{"bad qtype", fields{"udp", "1.1.1.1:9000000", true, "google.com", "BAZ"}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := DNSConf{
Proto: tt.fields.Proto,
Server: tt.fields.Server,
Recurse: tt.fields.Recurse,
QName: tt.fields.QName,
QType: tt.fields.QType,
}
_, err := c.MakeProber(nil)
if tt.wantErr {
test.AssertError(t, err, "DNSConf.MakeProber() should have errored")
} else {
test.AssertNotError(t, err, "DNSConf.MakeProber() shouldn't have errored")
}
})
}
}
func TestDNSConf_UnmarshalSettings(t *testing.T) {
type fields struct {
protocol interface{}
server interface{}
recurse interface{}
query_name interface{}
query_type interface{}
}
tests := []struct {
name string
fields fields
want probers.Configurer
wantErr bool
}{
{"valid", fields{"udp", "1.1.1.1:53", true, "google.com", "A"}, DNSConf{"udp", "1.1.1.1:53", true, "google.com", "A"}, false},
{"invalid", fields{42, 42, 42, 42, 42}, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
settings := probers.Settings{
"protocol": tt.fields.protocol,
"server": tt.fields.server,
"recurse": tt.fields.recurse,
"query_name": tt.fields.query_name,
"query_type": tt.fields.query_type,
}
settingsBytes, _ := yaml.Marshal(settings)
c := DNSConf{}
got, err := c.UnmarshalSettings(settingsBytes)
if (err != nil) != tt.wantErr {
t.Errorf("DNSConf.UnmarshalSettings() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("DNSConf.UnmarshalSettings() = %v, want %v", got, tt.want)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/http/http_conf_test.go | third-party/github.com/letsencrypt/boulder/observer/probers/http/http_conf_test.go | package probers
import (
"reflect"
"testing"
"github.com/letsencrypt/boulder/observer/probers"
"github.com/letsencrypt/boulder/test"
"gopkg.in/yaml.v3"
)
func TestHTTPConf_MakeProber(t *testing.T) {
type fields struct {
URL string
RCodes []int
}
tests := []struct {
name string
fields fields
wantErr bool
}{
// valid
{"valid fqdn valid rcode", fields{"http://example.com", []int{200}}, false},
{"valid hostname valid rcode", fields{"example", []int{200}}, true},
// invalid
{"valid fqdn no rcode", fields{"http://example.com", nil}, true},
{"valid fqdn invalid rcode", fields{"http://example.com", []int{1000}}, true},
{"valid fqdn 1 invalid rcode", fields{"http://example.com", []int{200, 1000}}, true},
{"bad fqdn good rcode", fields{":::::", []int{200}}, true},
{"missing scheme", fields{"example.com", []int{200}}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := HTTPConf{
URL: tt.fields.URL,
RCodes: tt.fields.RCodes,
}
if _, err := c.MakeProber(nil); (err != nil) != tt.wantErr {
t.Errorf("HTTPConf.Validate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestHTTPConf_UnmarshalSettings(t *testing.T) {
type fields struct {
url interface{}
rcodes interface{}
useragent interface{}
insecure interface{}
}
tests := []struct {
name string
fields fields
want probers.Configurer
wantErr bool
}{
{"valid", fields{"google.com", []int{200}, "boulder_observer", false}, HTTPConf{"google.com", []int{200}, "boulder_observer", false}, false},
{"invalid", fields{42, 42, 42, 42}, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
settings := probers.Settings{
"url": tt.fields.url,
"rcodes": tt.fields.rcodes,
"useragent": tt.fields.useragent,
"insecure": tt.fields.insecure,
}
settingsBytes, _ := yaml.Marshal(settings)
c := HTTPConf{}
got, err := c.UnmarshalSettings(settingsBytes)
if (err != nil) != tt.wantErr {
t.Errorf("DNSConf.UnmarshalSettings() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("DNSConf.UnmarshalSettings() = %v, want %v", got, tt.want)
}
})
}
}
func TestHTTPProberName(t *testing.T) {
// Test with blank `useragent`
proberYAML := `
url: https://www.google.com
rcodes: [ 200 ]
useragent: ""
insecure: true
`
c := HTTPConf{}
configurer, err := c.UnmarshalSettings([]byte(proberYAML))
test.AssertNotError(t, err, "Got error for valid prober config")
prober, err := configurer.MakeProber(nil)
test.AssertNotError(t, err, "Got error for valid prober config")
test.AssertEquals(t, prober.Name(), "https://www.google.com-[200]-letsencrypt/boulder-observer-http-client-insecure")
// Test with custom `useragent`
proberYAML = `
url: https://www.google.com
rcodes: [ 200 ]
useragent: fancy-custom-http-client
`
c = HTTPConf{}
configurer, err = c.UnmarshalSettings([]byte(proberYAML))
test.AssertNotError(t, err, "Got error for valid prober config")
prober, err = configurer.MakeProber(nil)
test.AssertNotError(t, err, "Got error for valid prober config")
test.AssertEquals(t, prober.Name(), "https://www.google.com-[200]-fancy-custom-http-client")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/http/http_conf.go | third-party/github.com/letsencrypt/boulder/observer/probers/http/http_conf.go | package probers
import (
"fmt"
"net/url"
"github.com/letsencrypt/boulder/observer/probers"
"github.com/letsencrypt/boulder/strictyaml"
"github.com/prometheus/client_golang/prometheus"
)
// HTTPConf is exported to receive YAML configuration.
type HTTPConf struct {
URL string `yaml:"url"`
RCodes []int `yaml:"rcodes"`
UserAgent string `yaml:"useragent"`
Insecure bool `yaml:"insecure"`
}
// Kind returns a name that uniquely identifies the `Kind` of `Configurer`.
func (c HTTPConf) Kind() string {
return "HTTP"
}
// UnmarshalSettings takes YAML as bytes and unmarshals it to the to an
// HTTPConf object.
func (c HTTPConf) UnmarshalSettings(settings []byte) (probers.Configurer, error) {
var conf HTTPConf
err := strictyaml.Unmarshal(settings, &conf)
if err != nil {
return nil, err
}
return conf, nil
}
func (c HTTPConf) validateURL() error {
url, err := url.Parse(c.URL)
if err != nil {
return fmt.Errorf(
"invalid 'url', got: %q, expected a valid url", c.URL)
}
if url.Scheme == "" {
return fmt.Errorf(
"invalid 'url', got: %q, missing scheme", c.URL)
}
return nil
}
func (c HTTPConf) validateRCodes() error {
if len(c.RCodes) == 0 {
return fmt.Errorf(
"invalid 'rcodes', got: %q, please specify at least one", c.RCodes)
}
for _, c := range c.RCodes {
// ensure rcode entry is in range 100-599
if c < 100 || c > 599 {
return fmt.Errorf(
"'rcodes' contains an invalid HTTP response code, '%d'", c)
}
}
return nil
}
// MakeProber constructs a `HTTPProbe` object from the contents of the
// bound `HTTPConf` object. If the `HTTPConf` cannot be validated, an
// error appropriate for end-user consumption is returned instead.
func (c HTTPConf) MakeProber(_ map[string]prometheus.Collector) (probers.Prober, error) {
// validate `url`
err := c.validateURL()
if err != nil {
return nil, err
}
// validate `rcodes`
err = c.validateRCodes()
if err != nil {
return nil, err
}
// Set default User-Agent if none set.
if c.UserAgent == "" {
c.UserAgent = "letsencrypt/boulder-observer-http-client"
}
return HTTPProbe{c.URL, c.RCodes, c.UserAgent, c.Insecure}, nil
}
// Instrument is a no-op to implement the `Configurer` interface.
func (c HTTPConf) Instrument() map[string]prometheus.Collector {
return nil
}
// init is called at runtime and registers `HTTPConf`, a `Prober`
// `Configurer` type, as "HTTP".
func init() {
probers.Register(HTTPConf{})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/probers/http/http.go | third-party/github.com/letsencrypt/boulder/observer/probers/http/http.go | package probers
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"time"
"github.com/letsencrypt/boulder/observer/obsdialer"
)
// HTTPProbe is the exported 'Prober' object for monitors configured to
// perform HTTP requests.
type HTTPProbe struct {
url string
rcodes []int
useragent string
insecure bool
}
// Name returns a string that uniquely identifies the monitor.
func (p HTTPProbe) Name() string {
insecure := ""
if p.insecure {
insecure = "-insecure"
}
return fmt.Sprintf("%s-%d-%s%s", p.url, p.rcodes, p.useragent, insecure)
}
// Kind returns a name that uniquely identifies the `Kind` of `Prober`.
func (p HTTPProbe) Kind() string {
return "HTTP"
}
// isExpected ensures that the received HTTP response code matches one
// that's expected.
func (p HTTPProbe) isExpected(received int) bool {
for _, c := range p.rcodes {
if received == c {
return true
}
}
return false
}
// Probe performs the configured HTTP request.
func (p HTTPProbe) Probe(timeout time.Duration) (bool, time.Duration) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
client := http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: p.insecure},
DialContext: obsdialer.Dialer.DialContext,
}}
req, err := http.NewRequestWithContext(ctx, "GET", p.url, nil)
if err != nil {
return false, 0
}
req.Header.Set("User-Agent", p.useragent)
start := time.Now()
// TODO(@beautifulentropy): add support for more than HTTP GET
resp, err := client.Do(req)
if err != nil {
return false, time.Since(start)
}
return p.isExpected(resp.StatusCode), time.Since(start)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/observer/obsdialer/obsdialer.go | third-party/github.com/letsencrypt/boulder/observer/obsdialer/obsdialer.go | // package obsdialer contains a custom dialer for use in observers.
package obsdialer
import "net"
// Dialer is a custom dialer for use in observers. It disables IPv6-to-IPv4
// fallback so we don't mask failures of IPv6 connectivity.
var Dialer = net.Dialer{
FallbackDelay: -1, // Disable IPv6-to-IPv4 fallback
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/publisher/publisher_test.go | third-party/github.com/letsencrypt/boulder/publisher/publisher_test.go | package publisher
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/base64"
"encoding/json"
"fmt"
"math/big"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
ct "github.com/google/certificate-transparency-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/letsencrypt/boulder/core"
"github.com/letsencrypt/boulder/issuance"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
pubpb "github.com/letsencrypt/boulder/publisher/proto"
"github.com/letsencrypt/boulder/test"
)
var log = blog.UseMock()
var ctx = context.Background()
func getPort(srvURL string) (int, error) {
url, err := url.Parse(srvURL)
if err != nil {
return 0, err
}
_, portString, err := net.SplitHostPort(url.Host)
if err != nil {
return 0, err
}
port, err := strconv.ParseInt(portString, 10, 64)
if err != nil {
return 0, err
}
return int(port), nil
}
type testLogSrv struct {
*httptest.Server
submissions int64
}
func logSrv(k *ecdsa.PrivateKey) *testLogSrv {
testLog := &testLogSrv{}
m := http.NewServeMux()
m.HandleFunc("/ct/", func(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var jsonReq ctSubmissionRequest
err := decoder.Decode(&jsonReq)
if err != nil {
return
}
precert := false
if r.URL.Path == "/ct/v1/add-pre-chain" {
precert = true
}
sct := CreateTestingSignedSCT(jsonReq.Chain, k, precert, time.Now())
fmt.Fprint(w, string(sct))
atomic.AddInt64(&testLog.submissions, 1)
})
testLog.Server = httptest.NewUnstartedServer(m)
testLog.Server.Start()
return testLog
}
// lyingLogSrv always signs SCTs with the timestamp it was given.
func lyingLogSrv(k *ecdsa.PrivateKey, timestamp time.Time) *testLogSrv {
testLog := &testLogSrv{}
m := http.NewServeMux()
m.HandleFunc("/ct/", func(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var jsonReq ctSubmissionRequest
err := decoder.Decode(&jsonReq)
if err != nil {
return
}
precert := false
if r.URL.Path == "/ct/v1/add-pre-chain" {
precert = true
}
sct := CreateTestingSignedSCT(jsonReq.Chain, k, precert, timestamp)
fmt.Fprint(w, string(sct))
atomic.AddInt64(&testLog.submissions, 1)
})
testLog.Server = httptest.NewUnstartedServer(m)
testLog.Server.Start()
return testLog
}
func errorBodyLogSrv() *httptest.Server {
m := http.NewServeMux()
m.HandleFunc("/ct/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("well this isn't good now is it."))
})
server := httptest.NewUnstartedServer(m)
server.Start()
return server
}
func setup(t *testing.T) (*Impl, *x509.Certificate, *ecdsa.PrivateKey) {
// Load chain: R3 <- Root DST
chain1, err := issuance.LoadChain([]string{
"../test/hierarchy/int-r3-cross.cert.pem",
"../test/hierarchy/root-dst.cert.pem",
})
test.AssertNotError(t, err, "failed to load chain1.")
// Load chain: R3 <- Root X1
chain2, err := issuance.LoadChain([]string{
"../test/hierarchy/int-r3.cert.pem",
"../test/hierarchy/root-x1.cert.pem",
})
test.AssertNotError(t, err, "failed to load chain2.")
// Load chain: E1 <- Root X2
chain3, err := issuance.LoadChain([]string{
"../test/hierarchy/int-e1.cert.pem",
"../test/hierarchy/root-x2.cert.pem",
})
test.AssertNotError(t, err, "failed to load chain3.")
// Create an example issuerNameID to CT bundle mapping
issuerBundles := map[issuance.NameID][]ct.ASN1Cert{
chain1[0].NameID(): GetCTBundleForChain(chain1),
chain2[0].NameID(): GetCTBundleForChain(chain2),
chain3[0].NameID(): GetCTBundleForChain(chain3),
}
pub := New(
issuerBundles,
"test-user-agent/1.0",
log,
metrics.NoopRegisterer)
// Load leaf certificate
leaf, err := core.LoadCert("../test/hierarchy/ee-r3.cert.pem")
test.AssertNotError(t, err, "unable to load leaf certificate.")
k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "Couldn't generate test key")
return pub, leaf, k
}
func addLog(t *testing.T, port int, pubKey *ecdsa.PublicKey) *Log {
uri := fmt.Sprintf("http://localhost:%d", port)
der, err := x509.MarshalPKIXPublicKey(pubKey)
test.AssertNotError(t, err, "Failed to marshal key")
newLog, err := NewLog(uri, base64.StdEncoding.EncodeToString(der), "test-user-agent/1.0", log)
test.AssertNotError(t, err, "Couldn't create log")
test.AssertEquals(t, newLog.uri, fmt.Sprintf("http://localhost:%d", port))
return newLog
}
func makePrecert(k *ecdsa.PrivateKey) (map[issuance.NameID][]ct.ASN1Cert, []byte, error) {
rootTmpl := x509.Certificate{
SerialNumber: big.NewInt(0),
Subject: pkix.Name{CommonName: "root"},
BasicConstraintsValid: true,
IsCA: true,
}
rootBytes, err := x509.CreateCertificate(rand.Reader, &rootTmpl, &rootTmpl, k.Public(), k)
if err != nil {
return nil, nil, err
}
root, err := x509.ParseCertificate(rootBytes)
if err != nil {
return nil, nil, err
}
precertTmpl := x509.Certificate{
SerialNumber: big.NewInt(0),
ExtraExtensions: []pkix.Extension{
{Id: asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3}, Critical: true, Value: []byte{0x05, 0x00}},
},
}
precert, err := x509.CreateCertificate(rand.Reader, &precertTmpl, root, k.Public(), k)
if err != nil {
return nil, nil, err
}
precertX509, err := x509.ParseCertificate(precert)
if err != nil {
return nil, nil, err
}
precertIssuerNameID := issuance.IssuerNameID(precertX509)
bundles := map[issuance.NameID][]ct.ASN1Cert{
precertIssuerNameID: {
ct.ASN1Cert{Data: rootBytes},
},
}
return bundles, precert, err
}
func TestTimestampVerificationFuture(t *testing.T) {
pub, _, k := setup(t)
server := lyingLogSrv(k, time.Now().Add(time.Hour))
defer server.Close()
port, err := getPort(server.URL)
test.AssertNotError(t, err, "Failed to get test server port")
testLog := addLog(t, port, &k.PublicKey)
// Precert
issuerBundles, precert, err := makePrecert(k)
test.AssertNotError(t, err, "Failed to create test leaf")
pub.issuerBundles = issuerBundles
_, err = pub.SubmitToSingleCTWithResult(ctx, &pubpb.Request{
LogURL: testLog.uri,
LogPublicKey: testLog.logID,
Der: precert,
Kind: pubpb.SubmissionType_sct,
})
if err == nil {
t.Fatal("Expected error for lying log server, got none")
}
if !strings.HasPrefix(err.Error(), "SCT Timestamp was too far in the future") {
t.Fatalf("Got wrong error: %s", err)
}
}
func TestTimestampVerificationPast(t *testing.T) {
pub, _, k := setup(t)
server := lyingLogSrv(k, time.Now().Add(-time.Hour))
defer server.Close()
port, err := getPort(server.URL)
test.AssertNotError(t, err, "Failed to get test server port")
testLog := addLog(t, port, &k.PublicKey)
// Precert
issuerBundles, precert, err := makePrecert(k)
test.AssertNotError(t, err, "Failed to create test leaf")
pub.issuerBundles = issuerBundles
_, err = pub.SubmitToSingleCTWithResult(ctx, &pubpb.Request{
LogURL: testLog.uri,
LogPublicKey: testLog.logID,
Der: precert,
Kind: pubpb.SubmissionType_sct,
})
if err == nil {
t.Fatal("Expected error for lying log server, got none")
}
if !strings.HasPrefix(err.Error(), "SCT Timestamp was too far in the past") {
t.Fatalf("Got wrong error: %s", err)
}
}
func TestLogCache(t *testing.T) {
cache := logCache{
logs: make(map[cacheKey]*Log),
}
// Adding a log with an invalid base64 public key should error
_, err := cache.AddLog("www.test.com", "1234", "test-user-agent/1.0", log)
test.AssertError(t, err, "AddLog() with invalid base64 pk didn't error")
// Adding a log with an invalid URI should error
_, err = cache.AddLog(":", "", "test-user-agent/1.0", log)
test.AssertError(t, err, "AddLog() with an invalid log URI didn't error")
// Create one keypair & base 64 public key
k1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k1")
der1, err := x509.MarshalPKIXPublicKey(&k1.PublicKey)
test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der1) failed")
k1b64 := base64.StdEncoding.EncodeToString(der1)
// Create a second keypair & base64 public key
k2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k2")
der2, err := x509.MarshalPKIXPublicKey(&k2.PublicKey)
test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der2) failed")
k2b64 := base64.StdEncoding.EncodeToString(der2)
// Adding the first log should not produce an error
l1, err := cache.AddLog("http://log.one.example.com", k1b64, "test-user-agent/1.0", log)
test.AssertNotError(t, err, "cache.AddLog() failed for log 1")
test.AssertEquals(t, cache.Len(), 1)
test.AssertEquals(t, l1.uri, "http://log.one.example.com")
test.AssertEquals(t, l1.logID, k1b64)
// Adding it again should not produce any errors, or increase the Len()
l1, err = cache.AddLog("http://log.one.example.com", k1b64, "test-user-agent/1.0", log)
test.AssertNotError(t, err, "cache.AddLog() failed for second add of log 1")
test.AssertEquals(t, cache.Len(), 1)
test.AssertEquals(t, l1.uri, "http://log.one.example.com")
test.AssertEquals(t, l1.logID, k1b64)
// Adding a second log should not error and should increase the Len()
l2, err := cache.AddLog("http://log.two.example.com", k2b64, "test-user-agent/1.0", log)
test.AssertNotError(t, err, "cache.AddLog() failed for log 2")
test.AssertEquals(t, cache.Len(), 2)
test.AssertEquals(t, l2.uri, "http://log.two.example.com")
test.AssertEquals(t, l2.logID, k2b64)
}
func TestLogErrorBody(t *testing.T) {
pub, leaf, k := setup(t)
srv := errorBodyLogSrv()
defer srv.Close()
port, err := getPort(srv.URL)
test.AssertNotError(t, err, "Failed to get test server port")
log.Clear()
logURI := fmt.Sprintf("http://localhost:%d", port)
pkDER, err := x509.MarshalPKIXPublicKey(&k.PublicKey)
test.AssertNotError(t, err, "Failed to marshal key")
pkB64 := base64.StdEncoding.EncodeToString(pkDER)
_, err = pub.SubmitToSingleCTWithResult(context.Background(), &pubpb.Request{
LogURL: logURI,
LogPublicKey: pkB64,
Der: leaf.Raw,
Kind: pubpb.SubmissionType_final,
})
test.AssertError(t, err, "SubmitToSingleCTWithResult didn't fail")
test.AssertEquals(t, len(log.GetAllMatching("well this isn't good now is it")), 1)
}
// TestErrorMetrics checks that the ct_errors_count and
// ct_submission_time_seconds metrics are updated with the correct labels when
// the publisher encounters errors.
func TestErrorMetrics(t *testing.T) {
pub, leaf, k := setup(t)
pkDER, err := x509.MarshalPKIXPublicKey(&k.PublicKey)
test.AssertNotError(t, err, "Failed to marshal key")
pkB64 := base64.StdEncoding.EncodeToString(pkDER)
// Set up a bad server that will always produce errors.
badSrv := errorBodyLogSrv()
defer badSrv.Close()
port, err := getPort(badSrv.URL)
test.AssertNotError(t, err, "Failed to get test server port")
logURI := fmt.Sprintf("http://localhost:%d", port)
_, err = pub.SubmitToSingleCTWithResult(context.Background(), &pubpb.Request{
LogURL: logURI,
LogPublicKey: pkB64,
Der: leaf.Raw,
Kind: pubpb.SubmissionType_sct,
})
test.AssertError(t, err, "SubmitToSingleCTWithResult didn't fail")
test.AssertMetricWithLabelsEquals(t, pub.metrics.submissionLatency, prometheus.Labels{
"log": logURI,
"type": "sct",
"status": "error",
"http_status": "400",
}, 1)
test.AssertMetricWithLabelsEquals(t, pub.metrics.errorCount, prometheus.Labels{
"log": logURI,
"type": "sct",
}, 1)
_, err = pub.SubmitToSingleCTWithResult(context.Background(), &pubpb.Request{
LogURL: logURI,
LogPublicKey: pkB64,
Der: leaf.Raw,
Kind: pubpb.SubmissionType_final,
})
test.AssertError(t, err, "SubmitToSingleCTWithResult didn't fail")
test.AssertMetricWithLabelsEquals(t, pub.metrics.submissionLatency, prometheus.Labels{
"log": logURI,
"type": "final",
"status": "error",
"http_status": "400",
}, 1)
test.AssertMetricWithLabelsEquals(t, pub.metrics.errorCount, prometheus.Labels{
"log": logURI,
"type": "final",
}, 1)
_, err = pub.SubmitToSingleCTWithResult(context.Background(), &pubpb.Request{
LogURL: logURI,
LogPublicKey: pkB64,
Der: leaf.Raw,
Kind: pubpb.SubmissionType_info,
})
test.AssertError(t, err, "SubmitToSingleCTWithResult didn't fail")
test.AssertMetricWithLabelsEquals(t, pub.metrics.submissionLatency, prometheus.Labels{
"log": logURI,
"type": "info",
"status": "error",
"http_status": "400",
}, 1)
test.AssertMetricWithLabelsEquals(t, pub.metrics.errorCount, prometheus.Labels{
"log": logURI,
"type": "info",
}, 1)
}
// TestSuccessMetrics checks that the ct_errors_count and
// ct_submission_time_seconds metrics are updated with the correct labels when
// the publisher succeeds.
func TestSuccessMetrics(t *testing.T) {
pub, leaf, k := setup(t)
pkDER, err := x509.MarshalPKIXPublicKey(&k.PublicKey)
test.AssertNotError(t, err, "Failed to marshal key")
pkB64 := base64.StdEncoding.EncodeToString(pkDER)
// Set up a working server that will succeed.
workingSrv := logSrv(k)
defer workingSrv.Close()
port, err := getPort(workingSrv.URL)
test.AssertNotError(t, err, "Failed to get test server port")
logURI := fmt.Sprintf("http://localhost:%d", port)
// Only the latency metric should be updated on a success.
_, err = pub.SubmitToSingleCTWithResult(context.Background(), &pubpb.Request{
LogURL: logURI,
LogPublicKey: pkB64,
Der: leaf.Raw,
Kind: pubpb.SubmissionType_final,
})
test.AssertNotError(t, err, "SubmitToSingleCTWithResult failed")
test.AssertMetricWithLabelsEquals(t, pub.metrics.submissionLatency, prometheus.Labels{
"log": logURI,
"type": "final",
"status": "success",
"http_status": "",
}, 1)
test.AssertMetricWithLabelsEquals(t, pub.metrics.errorCount, prometheus.Labels{
"log": logURI,
"type": "final",
}, 0)
}
func Test_GetCTBundleForChain(t *testing.T) {
chain, err := issuance.LoadChain([]string{
"../test/hierarchy/int-r3.cert.pem",
"../test/hierarchy/root-x1.cert.pem",
})
test.AssertNotError(t, err, "Failed to load chain.")
expect := []ct.ASN1Cert{{Data: chain[0].Raw}}
type args struct {
chain []*issuance.Certificate
}
tests := []struct {
name string
args args
want []ct.ASN1Cert
}{
{"Create a ct bundle with a single intermediate", args{chain}, expect},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
bundle := GetCTBundleForChain(tt.args.chain)
test.AssertDeepEquals(t, bundle, tt.want)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/publisher/publisher.go | third-party/github.com/letsencrypt/boulder/publisher/publisher.go | package publisher
import (
"context"
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/asn1"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math/big"
"net/http"
"net/url"
"strings"
"sync"
"time"
ct "github.com/google/certificate-transparency-go"
ctClient "github.com/google/certificate-transparency-go/client"
"github.com/google/certificate-transparency-go/jsonclient"
cttls "github.com/google/certificate-transparency-go/tls"
"github.com/prometheus/client_golang/prometheus"
"github.com/letsencrypt/boulder/core"
"github.com/letsencrypt/boulder/issuance"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
pubpb "github.com/letsencrypt/boulder/publisher/proto"
)
// Log contains the CT client for a particular CT log
type Log struct {
logID string
uri string
client *ctClient.LogClient
}
// cacheKey is a comparable type for use as a key within a logCache. It holds
// both the log URI and its log_id (base64 encoding of its pubkey), so that
// the cache won't interfere if the RA decides that a log's URI or pubkey has
// changed.
type cacheKey struct {
uri string
pubkey string
}
// logCache contains a cache of *Log's that are constructed as required by
// `SubmitToSingleCT`
type logCache struct {
sync.RWMutex
logs map[cacheKey]*Log
}
// AddLog adds a *Log to the cache by constructing the statName, client and
// verifier for the given uri & base64 public key.
func (c *logCache) AddLog(uri, b64PK, userAgent string, logger blog.Logger) (*Log, error) {
// Lock the mutex for reading to check the cache
c.RLock()
log, present := c.logs[cacheKey{uri, b64PK}]
c.RUnlock()
// If we have already added this log, give it back
if present {
return log, nil
}
// Lock the mutex for writing to add to the cache
c.Lock()
defer c.Unlock()
// Construct a Log, add it to the cache, and return it to the caller
log, err := NewLog(uri, b64PK, userAgent, logger)
if err != nil {
return nil, err
}
c.logs[cacheKey{uri, b64PK}] = log
return log, nil
}
// Len returns the number of logs in the logCache
func (c *logCache) Len() int {
c.RLock()
defer c.RUnlock()
return len(c.logs)
}
type logAdaptor struct {
blog.Logger
}
func (la logAdaptor) Printf(s string, args ...interface{}) {
la.Logger.Infof(s, args...)
}
// NewLog returns an initialized Log struct
func NewLog(uri, b64PK, userAgent string, logger blog.Logger) (*Log, error) {
url, err := url.Parse(uri)
if err != nil {
return nil, err
}
url.Path = strings.TrimSuffix(url.Path, "/")
derPK, err := base64.StdEncoding.DecodeString(b64PK)
if err != nil {
return nil, err
}
opts := jsonclient.Options{
Logger: logAdaptor{logger},
PublicKeyDER: derPK,
UserAgent: userAgent,
}
httpClient := &http.Client{
// We set the HTTP client timeout to about half of what we expect
// the gRPC timeout to be set to. This allows us to retry the
// request at least twice in the case where the server we are
// talking to is simply hanging indefinitely.
Timeout: time.Minute*2 + time.Second*30,
// We provide a new Transport for each Client so that different logs don't
// share a connection pool. This shouldn't matter, but we occasionally see a
// strange bug where submission to all logs hangs for about fifteen minutes.
// One possibility is that there is a strange bug in the locking on
// connection pools (possibly triggered by timed-out TCP connections). If
// that's the case, separate connection pools should prevent cross-log impact.
// We set some fields like TLSHandshakeTimeout to the values from
// DefaultTransport because the zero value for these fields means
// "unlimited," which would be bad.
Transport: &http.Transport{
MaxIdleConns: http.DefaultTransport.(*http.Transport).MaxIdleConns,
MaxIdleConnsPerHost: http.DefaultTransport.(*http.Transport).MaxIdleConns,
IdleConnTimeout: http.DefaultTransport.(*http.Transport).IdleConnTimeout,
TLSHandshakeTimeout: http.DefaultTransport.(*http.Transport).TLSHandshakeTimeout,
// In Boulder Issue 3821[0] we found that HTTP/2 support was causing hard
// to diagnose intermittent freezes in CT submission. Disabling HTTP/2 with
// an environment variable resolved the freezes but is not a stable fix.
//
// Per the Go `http` package docs we can make this change persistent by
// changing the `http.Transport` config:
// "Programs that must disable HTTP/2 can do so by setting
// Transport.TLSNextProto (for clients) or Server.TLSNextProto (for
// servers) to a non-nil, empty map"
//
// [0]: https://github.com/letsencrypt/boulder/issues/3821
TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{},
},
}
client, err := ctClient.New(url.String(), httpClient, opts)
if err != nil {
return nil, fmt.Errorf("making CT client: %s", err)
}
return &Log{
logID: b64PK,
uri: url.String(),
client: client,
}, nil
}
type ctSubmissionRequest struct {
Chain []string `json:"chain"`
}
type pubMetrics struct {
submissionLatency *prometheus.HistogramVec
probeLatency *prometheus.HistogramVec
errorCount *prometheus.CounterVec
}
func initMetrics(stats prometheus.Registerer) *pubMetrics {
submissionLatency := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "ct_submission_time_seconds",
Help: "Time taken to submit a certificate to a CT log",
Buckets: metrics.InternetFacingBuckets,
},
[]string{"log", "type", "status", "http_status"},
)
stats.MustRegister(submissionLatency)
probeLatency := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "ct_probe_time_seconds",
Help: "Time taken to probe a CT log",
Buckets: metrics.InternetFacingBuckets,
},
[]string{"log", "status"},
)
stats.MustRegister(probeLatency)
errorCount := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "ct_errors_count",
Help: "Count of errors by type",
},
[]string{"log", "type"},
)
stats.MustRegister(errorCount)
return &pubMetrics{submissionLatency, probeLatency, errorCount}
}
// Impl defines a Publisher
type Impl struct {
pubpb.UnsafePublisherServer
log blog.Logger
userAgent string
issuerBundles map[issuance.NameID][]ct.ASN1Cert
ctLogsCache logCache
metrics *pubMetrics
}
var _ pubpb.PublisherServer = (*Impl)(nil)
// New creates a Publisher that will submit certificates
// to requested CT logs
func New(
bundles map[issuance.NameID][]ct.ASN1Cert,
userAgent string,
logger blog.Logger,
stats prometheus.Registerer,
) *Impl {
return &Impl{
issuerBundles: bundles,
userAgent: userAgent,
ctLogsCache: logCache{
logs: make(map[cacheKey]*Log),
},
log: logger,
metrics: initMetrics(stats),
}
}
// SubmitToSingleCTWithResult will submit the certificate represented by certDER
// to the CT log specified by log URL and public key (base64) and return the SCT
// to the caller.
func (pub *Impl) SubmitToSingleCTWithResult(ctx context.Context, req *pubpb.Request) (*pubpb.Result, error) {
if core.IsAnyNilOrZero(req.Der, req.LogURL, req.LogPublicKey, req.Kind) {
return nil, errors.New("incomplete gRPC request message")
}
cert, err := x509.ParseCertificate(req.Der)
if err != nil {
pub.log.AuditErrf("Failed to parse certificate: %s", err)
return nil, err
}
chain := []ct.ASN1Cert{{Data: req.Der}}
id := issuance.IssuerNameID(cert)
issuerBundle, ok := pub.issuerBundles[id]
if !ok {
err := fmt.Errorf("No issuerBundle matching issuerNameID: %d", int64(id))
pub.log.AuditErrf("Failed to submit certificate to CT log: %s", err)
return nil, err
}
chain = append(chain, issuerBundle...)
// Add a log URL/pubkey to the cache, if already present the
// existing *Log will be returned, otherwise one will be constructed, added
// and returned.
ctLog, err := pub.ctLogsCache.AddLog(req.LogURL, req.LogPublicKey, pub.userAgent, pub.log)
if err != nil {
pub.log.AuditErrf("Making Log: %s", err)
return nil, err
}
sct, err := pub.singleLogSubmit(ctx, chain, req.Kind, ctLog)
if err != nil {
if core.IsCanceled(err) {
return nil, err
}
var body string
var rspErr jsonclient.RspError
if errors.As(err, &rspErr) && rspErr.StatusCode < 500 {
body = string(rspErr.Body)
}
pub.log.AuditErrf("Failed to submit certificate to CT log at %s: %s Body=%q",
ctLog.uri, err, body)
return nil, err
}
sctBytes, err := cttls.Marshal(*sct)
if err != nil {
return nil, err
}
return &pubpb.Result{Sct: sctBytes}, nil
}
func (pub *Impl) singleLogSubmit(
ctx context.Context,
chain []ct.ASN1Cert,
kind pubpb.SubmissionType,
ctLog *Log,
) (*ct.SignedCertificateTimestamp, error) {
submissionMethod := ctLog.client.AddChain
if kind == pubpb.SubmissionType_sct || kind == pubpb.SubmissionType_info {
submissionMethod = ctLog.client.AddPreChain
}
start := time.Now()
sct, err := submissionMethod(ctx, chain)
took := time.Since(start).Seconds()
if err != nil {
status := "error"
if core.IsCanceled(err) {
status = "canceled"
}
httpStatus := ""
var rspError ctClient.RspError
if errors.As(err, &rspError) && rspError.StatusCode != 0 {
httpStatus = fmt.Sprintf("%d", rspError.StatusCode)
}
pub.metrics.submissionLatency.With(prometheus.Labels{
"log": ctLog.uri,
"type": kind.String(),
"status": status,
"http_status": httpStatus,
}).Observe(took)
pub.metrics.errorCount.With(prometheus.Labels{
"log": ctLog.uri,
"type": kind.String(),
}).Inc()
return nil, err
}
pub.metrics.submissionLatency.With(prometheus.Labels{
"log": ctLog.uri,
"type": kind.String(),
"status": "success",
"http_status": "",
}).Observe(took)
threshold := uint64(time.Now().Add(time.Minute).UnixMilli()) //nolint: gosec // Current-ish timestamp is guaranteed to fit in a uint64
if sct.Timestamp > threshold {
return nil, fmt.Errorf("SCT Timestamp was too far in the future (%d > %d)", sct.Timestamp, threshold)
}
// For regular certificates, we could get an old SCT, but that shouldn't
// happen for precertificates.
threshold = uint64(time.Now().Add(-10 * time.Minute).UnixMilli()) //nolint: gosec // Current-ish timestamp is guaranteed to fit in a uint64
if kind != pubpb.SubmissionType_final && sct.Timestamp < threshold {
return nil, fmt.Errorf("SCT Timestamp was too far in the past (%d < %d)", sct.Timestamp, threshold)
}
return sct, nil
}
// CreateTestingSignedSCT is used by both the publisher tests and ct-test-serv, which is
// why it is exported. It creates a signed SCT based on the provided chain.
func CreateTestingSignedSCT(req []string, k *ecdsa.PrivateKey, precert bool, timestamp time.Time) []byte {
chain := make([]ct.ASN1Cert, len(req))
for i, str := range req {
b, err := base64.StdEncoding.DecodeString(str)
if err != nil {
panic("cannot decode chain")
}
chain[i] = ct.ASN1Cert{Data: b}
}
// Generate the internal leaf entry for the SCT
etype := ct.X509LogEntryType
if precert {
etype = ct.PrecertLogEntryType
}
leaf, err := ct.MerkleTreeLeafFromRawChain(chain, etype, 0)
if err != nil {
panic(fmt.Sprintf("failed to create leaf: %s", err))
}
// Sign the SCT
rawKey, _ := x509.MarshalPKIXPublicKey(&k.PublicKey)
logID := sha256.Sum256(rawKey)
timestampMillis := uint64(timestamp.UnixMilli()) //nolint: gosec // Current-ish timestamp is guaranteed to fit in a uint64
serialized, _ := ct.SerializeSCTSignatureInput(ct.SignedCertificateTimestamp{
SCTVersion: ct.V1,
LogID: ct.LogID{KeyID: logID},
Timestamp: timestampMillis,
}, ct.LogEntry{Leaf: *leaf})
hashed := sha256.Sum256(serialized)
var ecdsaSig struct {
R, S *big.Int
}
ecdsaSig.R, ecdsaSig.S, _ = ecdsa.Sign(rand.Reader, k, hashed[:])
sig, _ := asn1.Marshal(ecdsaSig)
// The ct.SignedCertificateTimestamp object doesn't have the needed
// `json` tags to properly marshal so we need to transform in into
// a struct that does before we can send it off
var jsonSCTObj struct {
SCTVersion ct.Version `json:"sct_version"`
ID string `json:"id"`
Timestamp uint64 `json:"timestamp"`
Extensions string `json:"extensions"`
Signature string `json:"signature"`
}
jsonSCTObj.SCTVersion = ct.V1
jsonSCTObj.ID = base64.StdEncoding.EncodeToString(logID[:])
jsonSCTObj.Timestamp = timestampMillis
ds := ct.DigitallySigned{
Algorithm: cttls.SignatureAndHashAlgorithm{
Hash: cttls.SHA256,
Signature: cttls.ECDSA,
},
Signature: sig,
}
jsonSCTObj.Signature, _ = ds.Base64String()
jsonSCT, _ := json.Marshal(jsonSCTObj)
return jsonSCT
}
// GetCTBundleForChain takes a slice of *issuance.Certificate(s)
// representing a certificate chain and returns a slice of
// ct.ASN1Cert(s) in the same order
func GetCTBundleForChain(chain []*issuance.Certificate) []ct.ASN1Cert {
var ctBundle []ct.ASN1Cert
for _, cert := range chain {
ctBundle = append(ctBundle, ct.ASN1Cert{Data: cert.Raw})
}
return ctBundle
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/publisher/proto/publisher.pb.go | third-party/github.com/letsencrypt/boulder/publisher/proto/publisher.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.5
// protoc v3.20.1
// source: publisher.proto
package proto
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type SubmissionType int32
const (
SubmissionType_unknown SubmissionType = 0
SubmissionType_sct SubmissionType = 1 // Submitting a precert with the intent of getting SCTs
SubmissionType_info SubmissionType = 2 // Submitting a precert on a best-effort basis
SubmissionType_final SubmissionType = 3 // Submitting a final cert on a best-effort basis
)
// Enum value maps for SubmissionType.
var (
SubmissionType_name = map[int32]string{
0: "unknown",
1: "sct",
2: "info",
3: "final",
}
SubmissionType_value = map[string]int32{
"unknown": 0,
"sct": 1,
"info": 2,
"final": 3,
}
)
func (x SubmissionType) Enum() *SubmissionType {
p := new(SubmissionType)
*p = x
return p
}
func (x SubmissionType) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (SubmissionType) Descriptor() protoreflect.EnumDescriptor {
return file_publisher_proto_enumTypes[0].Descriptor()
}
func (SubmissionType) Type() protoreflect.EnumType {
return &file_publisher_proto_enumTypes[0]
}
func (x SubmissionType) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use SubmissionType.Descriptor instead.
func (SubmissionType) EnumDescriptor() ([]byte, []int) {
return file_publisher_proto_rawDescGZIP(), []int{0}
}
type Request struct {
state protoimpl.MessageState `protogen:"open.v1"`
Der []byte `protobuf:"bytes,1,opt,name=der,proto3" json:"der,omitempty"`
LogURL string `protobuf:"bytes,2,opt,name=LogURL,proto3" json:"LogURL,omitempty"`
LogPublicKey string `protobuf:"bytes,3,opt,name=LogPublicKey,proto3" json:"LogPublicKey,omitempty"`
Kind SubmissionType `protobuf:"varint,5,opt,name=kind,proto3,enum=SubmissionType" json:"kind,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Request) Reset() {
*x = Request{}
mi := &file_publisher_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Request) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Request) ProtoMessage() {}
func (x *Request) ProtoReflect() protoreflect.Message {
mi := &file_publisher_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Request.ProtoReflect.Descriptor instead.
func (*Request) Descriptor() ([]byte, []int) {
return file_publisher_proto_rawDescGZIP(), []int{0}
}
func (x *Request) GetDer() []byte {
if x != nil {
return x.Der
}
return nil
}
func (x *Request) GetLogURL() string {
if x != nil {
return x.LogURL
}
return ""
}
func (x *Request) GetLogPublicKey() string {
if x != nil {
return x.LogPublicKey
}
return ""
}
func (x *Request) GetKind() SubmissionType {
if x != nil {
return x.Kind
}
return SubmissionType_unknown
}
type Result struct {
state protoimpl.MessageState `protogen:"open.v1"`
Sct []byte `protobuf:"bytes,1,opt,name=sct,proto3" json:"sct,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Result) Reset() {
*x = Result{}
mi := &file_publisher_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Result) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Result) ProtoMessage() {}
func (x *Result) ProtoReflect() protoreflect.Message {
mi := &file_publisher_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Result.ProtoReflect.Descriptor instead.
func (*Result) Descriptor() ([]byte, []int) {
return file_publisher_proto_rawDescGZIP(), []int{1}
}
func (x *Result) GetSct() []byte {
if x != nil {
return x.Sct
}
return nil
}
var File_publisher_proto protoreflect.FileDescriptor
var file_publisher_proto_rawDesc = string([]byte{
0x0a, 0x0f, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x22, 0x82, 0x01, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a,
0x03, 0x64, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x64, 0x65, 0x72, 0x12,
0x16, 0x0a, 0x06, 0x4c, 0x6f, 0x67, 0x55, 0x52, 0x4c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
0x06, 0x4c, 0x6f, 0x67, 0x55, 0x52, 0x4c, 0x12, 0x22, 0x0a, 0x0c, 0x4c, 0x6f, 0x67, 0x50, 0x75,
0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x4c,
0x6f, 0x67, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x12, 0x23, 0x0a, 0x04, 0x6b,
0x69, 0x6e, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x0f, 0x2e, 0x53, 0x75, 0x62, 0x6d,
0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x6b, 0x69, 0x6e, 0x64,
0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x22, 0x1a, 0x0a, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74,
0x12, 0x10, 0x0a, 0x03, 0x73, 0x63, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x73,
0x63, 0x74, 0x2a, 0x3b, 0x0a, 0x0e, 0x53, 0x75, 0x62, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e,
0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x75, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x10,
0x00, 0x12, 0x07, 0x0a, 0x03, 0x73, 0x63, 0x74, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x69, 0x6e,
0x66, 0x6f, 0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x10, 0x03, 0x32,
0x3e, 0x0a, 0x09, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x65, 0x72, 0x12, 0x31, 0x0a, 0x1a,
0x53, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x54, 0x6f, 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x43, 0x54,
0x57, 0x69, 0x74, 0x68, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x08, 0x2e, 0x52, 0x65, 0x71,
0x75, 0x65, 0x73, 0x74, 0x1a, 0x07, 0x2e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x22, 0x00, 0x42,
0x30, 0x5a, 0x2e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6c, 0x65,
0x74, 0x73, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x2f, 0x62, 0x6f, 0x75, 0x6c, 0x64, 0x65,
0x72, 0x2f, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
})
var (
file_publisher_proto_rawDescOnce sync.Once
file_publisher_proto_rawDescData []byte
)
func file_publisher_proto_rawDescGZIP() []byte {
file_publisher_proto_rawDescOnce.Do(func() {
file_publisher_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_publisher_proto_rawDesc), len(file_publisher_proto_rawDesc)))
})
return file_publisher_proto_rawDescData
}
var file_publisher_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_publisher_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_publisher_proto_goTypes = []any{
(SubmissionType)(0), // 0: SubmissionType
(*Request)(nil), // 1: Request
(*Result)(nil), // 2: Result
}
var file_publisher_proto_depIdxs = []int32{
0, // 0: Request.kind:type_name -> SubmissionType
1, // 1: Publisher.SubmitToSingleCTWithResult:input_type -> Request
2, // 2: Publisher.SubmitToSingleCTWithResult:output_type -> Result
2, // [2:3] is the sub-list for method output_type
1, // [1:2] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_publisher_proto_init() }
func file_publisher_proto_init() {
if File_publisher_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_publisher_proto_rawDesc), len(file_publisher_proto_rawDesc)),
NumEnums: 1,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_publisher_proto_goTypes,
DependencyIndexes: file_publisher_proto_depIdxs,
EnumInfos: file_publisher_proto_enumTypes,
MessageInfos: file_publisher_proto_msgTypes,
}.Build()
File_publisher_proto = out.File
file_publisher_proto_goTypes = nil
file_publisher_proto_depIdxs = nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/publisher/proto/publisher_grpc.pb.go | third-party/github.com/letsencrypt/boulder/publisher/proto/publisher_grpc.pb.go | // Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v3.20.1
// source: publisher.proto
package proto
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
Publisher_SubmitToSingleCTWithResult_FullMethodName = "/Publisher/SubmitToSingleCTWithResult"
)
// PublisherClient is the client API for Publisher service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type PublisherClient interface {
SubmitToSingleCTWithResult(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Result, error)
}
type publisherClient struct {
cc grpc.ClientConnInterface
}
func NewPublisherClient(cc grpc.ClientConnInterface) PublisherClient {
return &publisherClient{cc}
}
func (c *publisherClient) SubmitToSingleCTWithResult(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Result, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(Result)
err := c.cc.Invoke(ctx, Publisher_SubmitToSingleCTWithResult_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// PublisherServer is the server API for Publisher service.
// All implementations must embed UnimplementedPublisherServer
// for forward compatibility.
type PublisherServer interface {
SubmitToSingleCTWithResult(context.Context, *Request) (*Result, error)
mustEmbedUnimplementedPublisherServer()
}
// UnimplementedPublisherServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedPublisherServer struct{}
func (UnimplementedPublisherServer) SubmitToSingleCTWithResult(context.Context, *Request) (*Result, error) {
return nil, status.Errorf(codes.Unimplemented, "method SubmitToSingleCTWithResult not implemented")
}
func (UnimplementedPublisherServer) mustEmbedUnimplementedPublisherServer() {}
func (UnimplementedPublisherServer) testEmbeddedByValue() {}
// UnsafePublisherServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to PublisherServer will
// result in compilation errors.
type UnsafePublisherServer interface {
mustEmbedUnimplementedPublisherServer()
}
func RegisterPublisherServer(s grpc.ServiceRegistrar, srv PublisherServer) {
// If the following call pancis, it indicates UnimplementedPublisherServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&Publisher_ServiceDesc, srv)
}
func _Publisher_SubmitToSingleCTWithResult_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Request)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(PublisherServer).SubmitToSingleCTWithResult(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Publisher_SubmitToSingleCTWithResult_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(PublisherServer).SubmitToSingleCTWithResult(ctx, req.(*Request))
}
return interceptor(ctx, in, info, handler)
}
// Publisher_ServiceDesc is the grpc.ServiceDesc for Publisher service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Publisher_ServiceDesc = grpc.ServiceDesc{
ServiceName: "Publisher",
HandlerType: (*PublisherServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "SubmitToSingleCTWithResult",
Handler: _Publisher_SubmitToSingleCTWithResult_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "publisher.proto",
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/rollback.go | third-party/github.com/letsencrypt/boulder/db/rollback.go | package db
import (
"fmt"
)
// RollbackError is a combination of a database error and the error, if any,
// encountered while trying to rollback the transaction.
type RollbackError struct {
Err error
RollbackErr error
}
// Error implements the error interface
func (re *RollbackError) Error() string {
if re.RollbackErr == nil {
return re.Err.Error()
}
return fmt.Sprintf("%s (also, while rolling back: %s)", re.Err, re.RollbackErr)
}
// rollback rolls back the provided transaction. If the rollback fails for any
// reason a `RollbackError` error is returned wrapping the original error. If no
// rollback error occurs then the original error is returned.
func rollback(tx Transaction, err error) error {
if txErr := tx.Rollback(); txErr != nil {
return &RollbackError{
Err: err,
RollbackErr: txErr,
}
}
return err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/map_test.go | third-party/github.com/letsencrypt/boulder/db/map_test.go | package db
import (
"context"
"database/sql"
"errors"
"fmt"
"testing"
"github.com/letsencrypt/borp"
"github.com/go-sql-driver/mysql"
"github.com/letsencrypt/boulder/core"
"github.com/letsencrypt/boulder/test"
"github.com/letsencrypt/boulder/test/vars"
)
func TestErrDatabaseOpError(t *testing.T) {
testErr := errors.New("computers are cancelled")
testCases := []struct {
name string
err error
expected string
}{
{
name: "error with table",
err: ErrDatabaseOp{
Op: "test",
Table: "testTable",
Err: testErr,
},
expected: fmt.Sprintf("failed to test testTable: %s", testErr),
},
{
name: "error with no table",
err: ErrDatabaseOp{
Op: "test",
Err: testErr,
},
expected: fmt.Sprintf("failed to test: %s", testErr),
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
test.AssertEquals(t, tc.err.Error(), tc.expected)
})
}
}
func TestIsNoRows(t *testing.T) {
testCases := []struct {
name string
err ErrDatabaseOp
expectedNoRows bool
}{
{
name: "underlying err is sql.ErrNoRows",
err: ErrDatabaseOp{
Op: "test",
Table: "testTable",
Err: fmt.Errorf("some wrapper around %w", sql.ErrNoRows),
},
expectedNoRows: true,
},
{
name: "underlying err is not sql.ErrNoRows",
err: ErrDatabaseOp{
Op: "test",
Table: "testTable",
Err: fmt.Errorf("some wrapper around %w", errors.New("lots of rows. too many rows.")),
},
expectedNoRows: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
test.AssertEquals(t, IsNoRows(tc.err), tc.expectedNoRows)
})
}
}
func TestIsDuplicate(t *testing.T) {
testCases := []struct {
name string
err ErrDatabaseOp
expectDuplicate bool
}{
{
name: "underlying err has duplicate prefix",
err: ErrDatabaseOp{
Op: "test",
Table: "testTable",
Err: fmt.Errorf("some wrapper around %w", &mysql.MySQLError{Number: 1062}),
},
expectDuplicate: true,
},
{
name: "underlying err doesn't have duplicate prefix",
err: ErrDatabaseOp{
Op: "test",
Table: "testTable",
Err: fmt.Errorf("some wrapper around %w", &mysql.MySQLError{Number: 1234}),
},
expectDuplicate: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
test.AssertEquals(t, IsDuplicate(tc.err), tc.expectDuplicate)
})
}
}
func TestTableFromQuery(t *testing.T) {
// A sample of example queries logged by the SA during Boulder
// unit/integration tests.
testCases := []struct {
query string
expectedTable string
}{
{
query: "SELECT id, jwk, jwk_sha256, contact, agreement, createdAt, LockCol, status FROM registrations WHERE jwk_sha256 = ?",
expectedTable: "registrations",
},
{
query: "\n\t\t\t\t\tSELECT orderID, registrationID\n\t\t\t\t\tFROM orderFqdnSets\n\t\t\t\t\tWHERE setHash = ?\n\t\t\t\t\tAND expires > ?\n\t\t\t\t\tORDER BY expires ASC\n\t\t\t\t\tLIMIT 1",
expectedTable: "orderFqdnSets",
},
{
query: "SELECT id, identifierType, identifierValue, registrationID, status, expires, challenges, attempted, token, validationError, validationRecord FROM authz2 WHERE\n\t\t\tregistrationID = :regID AND\n\t\t\tstatus = :status AND\n\t\t\texpires > :validUntil AND\n\t\t\tidentifierType = :dnsType AND\n\t\t\tidentifierValue = :ident\n\t\t\tORDER BY expires ASC\n\t\t\tLIMIT 1 ",
expectedTable: "authz2",
},
{
query: "insert into `registrations` (`id`,`jwk`,`jw k_sha256`,`contact`,`agreement`,`createdAt`,`LockCol`,`status`) values (null,?,?,?,?,?,?,?,?);",
expectedTable: "`registrations`",
},
{
query: "update `registrations` set `jwk`=?, `jwk_sh a256`=?, `contact`=?, `agreement`=?, `createdAt`=?, `LockCol` =?, `status`=? where `id`=? and `LockCol`=?;",
expectedTable: "`registrations`",
},
{
query: "SELECT COUNT(*) FROM registrations WHERE ? < createdAt AND createdAt <= ?",
expectedTable: "registrations",
},
{
query: "SELECT COUNT(*) FROM orders WHERE registrationID = ? AND created >= ? AND created < ?",
expectedTable: "orders",
},
{
query: " SELECT id, identifierType, identifierValue, registrationID, status, expires, challenges, attempted, token, validationError, validationRecord FROM authz2 WHERE registrationID = ? AND status IN (?,?) AND expires > ? AND identifierType = ? AND identifierValue IN (?)",
expectedTable: "authz2",
},
{
query: "insert into `authz2` (`id`,`identifierType`,`identifierValue`,`registrationID`,`status`,`expires`,`challenges`,`attempted`,`token`,`validationError`,`validationRecord`) values (null,?,?,?,?,?,?,?,?,?,?);",
expectedTable: "`authz2`",
},
{
query: "insert into `orders` (`ID`,`RegistrationID`,`Expires`,`Created`,`Error`,`CertificateSerial`,`BeganProcessing`) values (null,?,?,?,?,?,?)",
expectedTable: "`orders`",
},
{
query: "insert into `orderToAuthz2` (`OrderID`,`AuthzID`) values (?,?);",
expectedTable: "`orderToAuthz2`",
},
{
query: "UPDATE authz2 SET status = :status, attempted = :attempted, validationRecord = :validationRecord, validationError = :validationError, expires = :expires WHERE id = :id AND status = :pending",
expectedTable: "authz2",
},
{
query: "insert into `precertificates` (`ID`,`Serial`,`RegistrationID`,`DER`,`Issued`,`Expires`) values (null,?,?,?,?,?);",
expectedTable: "`precertificates`",
},
{
query: "INSERT INTO certificateStatus (serial, status, ocspLastUpdated, revokedDate, revokedReason, lastExpirationNagSent, ocspResponse, notAfter, isExpired, issuerID) VALUES (?,?,?,?,?,?,?,?,?,?)",
expectedTable: "certificateStatus",
},
{
query: "INSERT INTO issuedNames (reversedName, serial, notBefore, renewal) VALUES (?, ?, ?, ?);",
expectedTable: "issuedNames",
},
{
query: "insert into `certificates` (`registrationID`,`serial`,`digest`,`der`,`issued`,`expires`) values (?,?,?,?,?,?);",
expectedTable: "`certificates`",
},
{
query: "insert into `fqdnSets` (`ID`,`SetHash`,`Serial`,`Issued`,`Expires`) values (null,?,?,?,?);",
expectedTable: "`fqdnSets`",
},
{
query: "UPDATE orders SET certificateSerial = ? WHERE id = ? AND beganProcessing = true",
expectedTable: "orders",
},
{
query: "DELETE FROM orderFqdnSets WHERE orderID = ?",
expectedTable: "orderFqdnSets",
},
{
query: "insert into `serials` (`ID`,`Serial`,`RegistrationID`,`Created`,`Expires`) values (null,?,?,?,?);",
expectedTable: "`serials`",
},
{
query: "UPDATE orders SET beganProcessing = ? WHERE id = ? AND beganProcessing = ?",
expectedTable: "orders",
},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("testCases.%d", i), func(t *testing.T) {
table := tableFromQuery(tc.query)
test.AssertEquals(t, table, tc.expectedTable)
})
}
}
func testDbMap(t *testing.T) *WrappedMap {
// NOTE(@cpu): We avoid using sa.NewDBMapFromConfig here because it would
// create a cyclic dependency. The `sa` package depends on `db` for
// `WithTransaction`. The `db` package can't depend on the `sa` for creating
// a DBMap. Since we only need a map for simple unit tests we can make our
// own dbMap by hand (how artisanal).
var config *mysql.Config
config, err := mysql.ParseDSN(vars.DBConnSA)
test.AssertNotError(t, err, "parsing DBConnSA DSN")
dbConn, err := sql.Open("mysql", config.FormatDSN())
test.AssertNotError(t, err, "opening DB connection")
dialect := borp.MySQLDialect{Engine: "InnoDB", Encoding: "UTF8"}
// NOTE(@cpu): We avoid giving a sa.BoulderTypeConverter to the DbMap field to
// avoid the cyclic dep. We don't need to convert any types in the db tests.
dbMap := &borp.DbMap{Db: dbConn, Dialect: dialect, TypeConverter: nil}
return &WrappedMap{dbMap: dbMap}
}
func TestWrappedMap(t *testing.T) {
mustDbErr := func(err error) ErrDatabaseOp {
t.Helper()
var dbOpErr ErrDatabaseOp
test.AssertErrorWraps(t, err, &dbOpErr)
return dbOpErr
}
ctx := context.Background()
testWrapper := func(dbMap Executor) {
reg := &core.Registration{}
// Test wrapped Get
_, err := dbMap.Get(ctx, reg)
test.AssertError(t, err, "expected err Getting Registration w/o type converter")
dbOpErr := mustDbErr(err)
test.AssertEquals(t, dbOpErr.Op, "get")
test.AssertEquals(t, dbOpErr.Table, "*core.Registration")
test.AssertError(t, dbOpErr.Err, "expected non-nil underlying err")
// Test wrapped Insert
err = dbMap.Insert(ctx, reg)
test.AssertError(t, err, "expected err Inserting Registration w/o type converter")
dbOpErr = mustDbErr(err)
test.AssertEquals(t, dbOpErr.Op, "insert")
test.AssertEquals(t, dbOpErr.Table, "*core.Registration")
test.AssertError(t, dbOpErr.Err, "expected non-nil underlying err")
// Test wrapped Update
_, err = dbMap.Update(ctx, reg)
test.AssertError(t, err, "expected err Updating Registration w/o type converter")
dbOpErr = mustDbErr(err)
test.AssertEquals(t, dbOpErr.Op, "update")
test.AssertEquals(t, dbOpErr.Table, "*core.Registration")
test.AssertError(t, dbOpErr.Err, "expected non-nil underlying err")
// Test wrapped Delete
_, err = dbMap.Delete(ctx, reg)
test.AssertError(t, err, "expected err Deleting Registration w/o type converter")
dbOpErr = mustDbErr(err)
test.AssertEquals(t, dbOpErr.Op, "delete")
test.AssertEquals(t, dbOpErr.Table, "*core.Registration")
test.AssertError(t, dbOpErr.Err, "expected non-nil underlying err")
// Test wrapped Select with a bogus query
_, err = dbMap.Select(ctx, reg, "blah")
test.AssertError(t, err, "expected err Selecting Registration w/o type converter")
dbOpErr = mustDbErr(err)
test.AssertEquals(t, dbOpErr.Op, "select")
test.AssertEquals(t, dbOpErr.Table, "*core.Registration (unknown table)")
test.AssertError(t, dbOpErr.Err, "expected non-nil underlying err")
// Test wrapped Select with a valid query
_, err = dbMap.Select(ctx, reg, "SELECT id, contact FROM registrationzzz WHERE id > 1;")
test.AssertError(t, err, "expected err Selecting Registration w/o type converter")
dbOpErr = mustDbErr(err)
test.AssertEquals(t, dbOpErr.Op, "select")
test.AssertEquals(t, dbOpErr.Table, "registrationzzz")
test.AssertError(t, dbOpErr.Err, "expected non-nil underlying err")
// Test wrapped SelectOne with a bogus query
err = dbMap.SelectOne(ctx, reg, "blah")
test.AssertError(t, err, "expected err SelectOne-ing Registration w/o type converter")
dbOpErr = mustDbErr(err)
test.AssertEquals(t, dbOpErr.Op, "select one")
test.AssertEquals(t, dbOpErr.Table, "*core.Registration (unknown table)")
test.AssertError(t, dbOpErr.Err, "expected non-nil underlying err")
// Test wrapped SelectOne with a valid query
err = dbMap.SelectOne(ctx, reg, "SELECT contact FROM doesNotExist WHERE id=1;")
test.AssertError(t, err, "expected err SelectOne-ing Registration w/o type converter")
dbOpErr = mustDbErr(err)
test.AssertEquals(t, dbOpErr.Op, "select one")
test.AssertEquals(t, dbOpErr.Table, "doesNotExist")
test.AssertError(t, dbOpErr.Err, "expected non-nil underlying err")
// Test wrapped Exec
_, err = dbMap.ExecContext(ctx, "INSERT INTO whatever (id) VALUES (?) WHERE id = ?", 10)
test.AssertError(t, err, "expected err Exec-ing bad query")
dbOpErr = mustDbErr(err)
test.AssertEquals(t, dbOpErr.Op, "exec")
test.AssertEquals(t, dbOpErr.Table, "whatever")
test.AssertError(t, dbOpErr.Err, "expected non-nil underlying err")
}
// Create a test wrapped map. It won't have a type converted registered.
dbMap := testDbMap(t)
// A top level WrappedMap should operate as expected with respect to wrapping
// database errors.
testWrapper(dbMap)
// Using Begin to start a transaction with the dbMap should return a
// transaction that continues to operate in the expected fashion.
tx, err := dbMap.BeginTx(ctx)
defer func() { _ = tx.Rollback() }()
test.AssertNotError(t, err, "unexpected error beginning transaction")
testWrapper(tx)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/transaction.go | third-party/github.com/letsencrypt/boulder/db/transaction.go | package db
import "context"
// txFunc represents a function that does work in the context of a transaction.
type txFunc func(tx Executor) (interface{}, error)
// WithTransaction runs the given function in a transaction, rolling back if it
// returns an error and committing if not. The provided context is also attached
// to the transaction. WithTransaction also passes through a value returned by
// `f`, if there is no error.
func WithTransaction(ctx context.Context, dbMap DatabaseMap, f txFunc) (interface{}, error) {
tx, err := dbMap.BeginTx(ctx)
if err != nil {
return nil, err
}
result, err := f(tx)
if err != nil {
return nil, rollback(tx, err)
}
err = tx.Commit()
if err != nil {
return nil, err
}
return result, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/interfaces.go | third-party/github.com/letsencrypt/boulder/db/interfaces.go | package db
import (
"context"
"database/sql"
"errors"
"reflect"
"github.com/letsencrypt/borp"
)
// These interfaces exist to aid in mocking database operations for unit tests.
//
// By convention, any function that takes a OneSelector, Selector,
// Inserter, Execer, or SelectExecer as as an argument expects
// that a context has already been applied to the relevant DbMap or
// Transaction object.
// A OneSelector is anything that provides a `SelectOne` function.
type OneSelector interface {
SelectOne(context.Context, interface{}, string, ...interface{}) error
}
// A Selector is anything that provides a `Select` function.
type Selector interface {
Select(context.Context, interface{}, string, ...interface{}) ([]interface{}, error)
}
// A Inserter is anything that provides an `Insert` function
type Inserter interface {
Insert(context.Context, ...interface{}) error
}
// A Execer is anything that provides an `ExecContext` function
type Execer interface {
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
}
// SelectExecer offers a subset of borp.SqlExecutor's methods: Select and
// ExecContext.
type SelectExecer interface {
Selector
Execer
}
// DatabaseMap offers the full combination of OneSelector, Inserter,
// SelectExecer, and a Begin function for creating a Transaction.
type DatabaseMap interface {
OneSelector
Inserter
SelectExecer
BeginTx(context.Context) (Transaction, error)
}
// Executor offers the full combination of OneSelector, Inserter, SelectExecer
// and adds a handful of other high level borp methods we use in Boulder.
type Executor interface {
OneSelector
Inserter
SelectExecer
Delete(context.Context, ...interface{}) (int64, error)
Get(context.Context, interface{}, ...interface{}) (interface{}, error)
Update(context.Context, ...interface{}) (int64, error)
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
}
// Transaction extends an Executor and adds Rollback and Commit
type Transaction interface {
Executor
Rollback() error
Commit() error
}
// MappedExecutor is anything that can map types to tables
type MappedExecutor interface {
TableFor(reflect.Type, bool) (*borp.TableMap, error)
QueryContext(ctx context.Context, clauses string, args ...interface{}) (*sql.Rows, error)
}
// MappedSelector is anything that can execute various kinds of SQL statements
// against a table automatically determined from the parameterized type.
type MappedSelector[T any] interface {
QueryContext(ctx context.Context, clauses string, args ...interface{}) (Rows[T], error)
QueryFrom(ctx context.Context, tablename string, clauses string, args ...interface{}) (Rows[T], error)
}
// Rows is anything which lets you iterate over the result rows of a SELECT
// query. It is similar to sql.Rows, but generic.
type Rows[T any] interface {
ForEach(func(*T) error) error
Next() bool
Get() (*T, error)
Err() error
Close() error
}
// MockSqlExecutor implement SqlExecutor by returning errors from every call.
//
// TODO: To mock out WithContext, we needed to be able to return objects that satisfy
// borp.SqlExecutor. That's a pretty big interface, so we specify one no-op mock
// that we can embed everywhere we need to satisfy it.
// Note: MockSqlExecutor does *not* implement WithContext. The expectation is
// that structs that embed MockSqlExecutor will define their own WithContext
// that returns a reference to themselves. That makes it easy for those structs
// to override the specific methods they need to implement (e.g. SelectOne).
type MockSqlExecutor struct{}
func (mse MockSqlExecutor) Get(ctx context.Context, i interface{}, keys ...interface{}) (interface{}, error) {
return nil, errors.New("unimplemented")
}
func (mse MockSqlExecutor) Insert(ctx context.Context, list ...interface{}) error {
return errors.New("unimplemented")
}
func (mse MockSqlExecutor) Update(ctx context.Context, list ...interface{}) (int64, error) {
return 0, errors.New("unimplemented")
}
func (mse MockSqlExecutor) Delete(ctx context.Context, list ...interface{}) (int64, error) {
return 0, errors.New("unimplemented")
}
func (mse MockSqlExecutor) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
return nil, errors.New("unimplemented")
}
func (mse MockSqlExecutor) Select(ctx context.Context, i interface{}, query string, args ...interface{}) ([]interface{}, error) {
return nil, errors.New("unimplemented")
}
func (mse MockSqlExecutor) SelectInt(ctx context.Context, query string, args ...interface{}) (int64, error) {
return 0, errors.New("unimplemented")
}
func (mse MockSqlExecutor) SelectNullInt(ctx context.Context, query string, args ...interface{}) (sql.NullInt64, error) {
return sql.NullInt64{}, errors.New("unimplemented")
}
func (mse MockSqlExecutor) SelectFloat(ctx context.Context, query string, args ...interface{}) (float64, error) {
return 0, errors.New("unimplemented")
}
func (mse MockSqlExecutor) SelectNullFloat(ctx context.Context, query string, args ...interface{}) (sql.NullFloat64, error) {
return sql.NullFloat64{}, errors.New("unimplemented")
}
func (mse MockSqlExecutor) SelectStr(ctx context.Context, query string, args ...interface{}) (string, error) {
return "", errors.New("unimplemented")
}
func (mse MockSqlExecutor) SelectNullStr(ctx context.Context, query string, args ...interface{}) (sql.NullString, error) {
return sql.NullString{}, errors.New("unimplemented")
}
func (mse MockSqlExecutor) SelectOne(ctx context.Context, holder interface{}, query string, args ...interface{}) error {
return errors.New("unimplemented")
}
func (mse MockSqlExecutor) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
return nil, errors.New("unimplemented")
}
func (mse MockSqlExecutor) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/rollback_test.go | third-party/github.com/letsencrypt/boulder/db/rollback_test.go | package db
import (
"context"
"testing"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/test"
)
func TestRollback(t *testing.T) {
ctx := context.Background()
dbMap := testDbMap(t)
tx, _ := dbMap.BeginTx(ctx)
// Commit the transaction so that a subsequent rollback will always fail.
_ = tx.Commit()
innerErr := berrors.NotFoundError("Gone, gone, gone")
result := rollback(tx, innerErr)
// Since the tx.Rollback will fail we expect the result to be a wrapped error
test.AssertNotEquals(t, result, innerErr)
if rbErr, ok := result.(*RollbackError); ok {
test.AssertEquals(t, rbErr.Err, innerErr)
test.AssertNotNil(t, rbErr.RollbackErr, "RollbackErr was nil")
} else {
t.Fatalf("Result was not a RollbackError: %#v", result)
}
// Create a new transaction and don't commit it this time. The rollback should
// succeed.
tx, _ = dbMap.BeginTx(ctx)
result = rollback(tx, innerErr)
// We expect that the err is returned unwrapped.
test.AssertEquals(t, result, innerErr)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/qmarks.go | third-party/github.com/letsencrypt/boulder/db/qmarks.go | package db
import "strings"
// QuestionMarks returns a string consisting of N question marks, joined by
// commas. If n is <= 0, panics.
func QuestionMarks(n int) string {
if n <= 0 {
panic("db.QuestionMarks called with n <=0")
}
var qmarks strings.Builder
qmarks.Grow(2 * n)
for i := range n {
if i == 0 {
qmarks.WriteString("?")
} else {
qmarks.WriteString(",?")
}
}
return qmarks.String()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/multi_test.go | third-party/github.com/letsencrypt/boulder/db/multi_test.go | package db
import (
"testing"
"github.com/letsencrypt/boulder/test"
)
func TestNewMulti(t *testing.T) {
_, err := NewMultiInserter("", []string{"colA"})
test.AssertError(t, err, "Empty table name should fail")
_, err = NewMultiInserter("myTable", nil)
test.AssertError(t, err, "Empty fields list should fail")
mi, err := NewMultiInserter("myTable", []string{"colA"})
test.AssertNotError(t, err, "Single-column construction should not fail")
test.AssertEquals(t, len(mi.fields), 1)
mi, err = NewMultiInserter("myTable", []string{"colA", "colB", "colC"})
test.AssertNotError(t, err, "Multi-column construction should not fail")
test.AssertEquals(t, len(mi.fields), 3)
_, err = NewMultiInserter("foo\"bar", []string{"colA"})
test.AssertError(t, err, "expected error for invalid table name")
_, err = NewMultiInserter("myTable", []string{"colA", "foo\"bar"})
test.AssertError(t, err, "expected error for invalid column name")
}
func TestMultiAdd(t *testing.T) {
mi, err := NewMultiInserter("table", []string{"a", "b", "c"})
test.AssertNotError(t, err, "Failed to create test MultiInserter")
err = mi.Add([]interface{}{})
test.AssertError(t, err, "Adding empty row should fail")
err = mi.Add([]interface{}{"foo"})
test.AssertError(t, err, "Adding short row should fail")
err = mi.Add([]interface{}{"foo", "bar", "baz", "bing", "boom"})
test.AssertError(t, err, "Adding long row should fail")
err = mi.Add([]interface{}{"one", "two", "three"})
test.AssertNotError(t, err, "Adding correct-length row shouldn't fail")
test.AssertEquals(t, len(mi.values), 1)
err = mi.Add([]interface{}{1, "two", map[string]int{"three": 3}})
test.AssertNotError(t, err, "Adding heterogeneous row shouldn't fail")
test.AssertEquals(t, len(mi.values), 2)
// Note that .Add does *not* enforce that each row is of the same types.
}
func TestMultiQuery(t *testing.T) {
mi, err := NewMultiInserter("table", []string{"a", "b", "c"})
test.AssertNotError(t, err, "Failed to create test MultiInserter")
err = mi.Add([]interface{}{"one", "two", "three"})
test.AssertNotError(t, err, "Failed to insert test row")
err = mi.Add([]interface{}{"egy", "kettö", "három"})
test.AssertNotError(t, err, "Failed to insert test row")
query, queryArgs := mi.query()
test.AssertEquals(t, query, "INSERT INTO table (a,b,c) VALUES (?,?,?),(?,?,?)")
test.AssertDeepEquals(t, queryArgs, []interface{}{"one", "two", "three", "egy", "kettö", "három"})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/multi.go | third-party/github.com/letsencrypt/boulder/db/multi.go | package db
import (
"context"
"fmt"
"strings"
)
// MultiInserter makes it easy to construct a
// `INSERT INTO table (...) VALUES ...;`
// query which inserts multiple rows into the same table. It can also execute
// the resulting query.
type MultiInserter struct {
// These are validated by the constructor as containing only characters
// that are allowed in an unquoted identifier.
// https://mariadb.com/kb/en/identifier-names/#unquoted
table string
fields []string
values [][]interface{}
}
// NewMultiInserter creates a new MultiInserter, checking for reasonable table
// name and list of fields.
// Safety: `table` and `fields` must contain only strings that are known at
// compile time. They must not contain user-controlled strings.
func NewMultiInserter(table string, fields []string) (*MultiInserter, error) {
if len(table) == 0 || len(fields) == 0 {
return nil, fmt.Errorf("empty table name or fields list")
}
err := validMariaDBUnquotedIdentifier(table)
if err != nil {
return nil, err
}
for _, field := range fields {
err := validMariaDBUnquotedIdentifier(field)
if err != nil {
return nil, err
}
}
return &MultiInserter{
table: table,
fields: fields,
values: make([][]interface{}, 0),
}, nil
}
// Add registers another row to be included in the Insert query.
func (mi *MultiInserter) Add(row []interface{}) error {
if len(row) != len(mi.fields) {
return fmt.Errorf("field count mismatch, got %d, expected %d", len(row), len(mi.fields))
}
mi.values = append(mi.values, row)
return nil
}
// query returns the formatted query string, and the slice of arguments for
// for borp to use in place of the query's question marks. Currently only
// used by .Insert(), below.
func (mi *MultiInserter) query() (string, []interface{}) {
var questionsBuf strings.Builder
var queryArgs []interface{}
for _, row := range mi.values {
// Safety: We are interpolating a string that will be used in a SQL
// query, but we constructed that string in this function and know it
// consists only of question marks joined with commas.
fmt.Fprintf(&questionsBuf, "(%s),", QuestionMarks(len(mi.fields)))
queryArgs = append(queryArgs, row...)
}
questions := strings.TrimRight(questionsBuf.String(), ",")
// Safety: we are interpolating `mi.table` and `mi.fields` into an SQL
// query. We know they contain, respectively, a valid unquoted identifier
// and a slice of valid unquoted identifiers because we verified that in
// the constructor. We know the query overall has valid syntax because we
// generate it entirely within this function.
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s", mi.table, strings.Join(mi.fields, ","), questions)
return query, queryArgs
}
// Insert inserts all the collected rows into the database represented by
// `queryer`.
func (mi *MultiInserter) Insert(ctx context.Context, db Execer) error {
if len(mi.values) == 0 {
return nil
}
query, queryArgs := mi.query()
res, err := db.ExecContext(ctx, query, queryArgs...)
if err != nil {
return err
}
affected, err := res.RowsAffected()
if err != nil {
return err
}
if affected != int64(len(mi.values)) {
return fmt.Errorf("unexpected number of rows inserted: %d != %d", affected, len(mi.values))
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/map.go | third-party/github.com/letsencrypt/boulder/db/map.go | package db
import (
"context"
"database/sql"
"errors"
"fmt"
"reflect"
"regexp"
"github.com/go-sql-driver/mysql"
"github.com/letsencrypt/borp"
)
// ErrDatabaseOp wraps an underlying err with a description of the operation
// that was being performed when the error occurred (insert, select, select
// one, exec, etc) and the table that the operation was being performed on.
type ErrDatabaseOp struct {
Op string
Table string
Err error
}
// Error for an ErrDatabaseOp composes a message with context about the
// operation and table as well as the underlying Err's error message.
func (e ErrDatabaseOp) Error() string {
// If there is a table, include it in the context
if e.Table != "" {
return fmt.Sprintf(
"failed to %s %s: %s",
e.Op,
e.Table,
e.Err)
}
return fmt.Sprintf(
"failed to %s: %s",
e.Op,
e.Err)
}
// Unwrap returns the inner error to allow inspection of error chains.
func (e ErrDatabaseOp) Unwrap() error {
return e.Err
}
// IsNoRows is a utility function for determining if an error wraps the go sql
// package's ErrNoRows, which is returned when a Scan operation has no more
// results to return, and as such is returned by many borp methods.
func IsNoRows(err error) bool {
return errors.Is(err, sql.ErrNoRows)
}
// IsDuplicate is a utility function for determining if an error wrap MySQL's
// Error 1062: Duplicate entry. This error is returned when inserting a row
// would violate a unique key constraint.
func IsDuplicate(err error) bool {
var dbErr *mysql.MySQLError
return errors.As(err, &dbErr) && dbErr.Number == 1062
}
// WrappedMap wraps a *borp.DbMap such that its major functions wrap error
// results in ErrDatabaseOp instances before returning them to the caller.
type WrappedMap struct {
dbMap *borp.DbMap
}
func NewWrappedMap(dbMap *borp.DbMap) *WrappedMap {
return &WrappedMap{dbMap: dbMap}
}
func (m *WrappedMap) TableFor(t reflect.Type, checkPK bool) (*borp.TableMap, error) {
return m.dbMap.TableFor(t, checkPK)
}
func (m *WrappedMap) Get(ctx context.Context, holder interface{}, keys ...interface{}) (interface{}, error) {
return WrappedExecutor{sqlExecutor: m.dbMap}.Get(ctx, holder, keys...)
}
func (m *WrappedMap) Insert(ctx context.Context, list ...interface{}) error {
return WrappedExecutor{sqlExecutor: m.dbMap}.Insert(ctx, list...)
}
func (m *WrappedMap) Update(ctx context.Context, list ...interface{}) (int64, error) {
return WrappedExecutor{sqlExecutor: m.dbMap}.Update(ctx, list...)
}
func (m *WrappedMap) Delete(ctx context.Context, list ...interface{}) (int64, error) {
return WrappedExecutor{sqlExecutor: m.dbMap}.Delete(ctx, list...)
}
func (m *WrappedMap) Select(ctx context.Context, holder interface{}, query string, args ...interface{}) ([]interface{}, error) {
return WrappedExecutor{sqlExecutor: m.dbMap}.Select(ctx, holder, query, args...)
}
func (m *WrappedMap) SelectOne(ctx context.Context, holder interface{}, query string, args ...interface{}) error {
return WrappedExecutor{sqlExecutor: m.dbMap}.SelectOne(ctx, holder, query, args...)
}
func (m *WrappedMap) SelectNullInt(ctx context.Context, query string, args ...interface{}) (sql.NullInt64, error) {
return WrappedExecutor{sqlExecutor: m.dbMap}.SelectNullInt(ctx, query, args...)
}
func (m *WrappedMap) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
return WrappedExecutor{sqlExecutor: m.dbMap}.QueryContext(ctx, query, args...)
}
func (m *WrappedMap) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
return WrappedExecutor{sqlExecutor: m.dbMap}.QueryRowContext(ctx, query, args...)
}
func (m *WrappedMap) SelectStr(ctx context.Context, query string, args ...interface{}) (string, error) {
return WrappedExecutor{sqlExecutor: m.dbMap}.SelectStr(ctx, query, args...)
}
func (m *WrappedMap) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
return WrappedExecutor{sqlExecutor: m.dbMap}.ExecContext(ctx, query, args...)
}
func (m *WrappedMap) BeginTx(ctx context.Context) (Transaction, error) {
tx, err := m.dbMap.BeginTx(ctx)
if err != nil {
return tx, ErrDatabaseOp{
Op: "begin transaction",
Err: err,
}
}
return WrappedTransaction{
transaction: tx,
}, err
}
func (m *WrappedMap) ColumnsForModel(model interface{}) ([]string, error) {
tbl, err := m.dbMap.TableFor(reflect.TypeOf(model), true)
if err != nil {
return nil, err
}
var columns []string
for _, col := range tbl.Columns {
columns = append(columns, col.ColumnName)
}
return columns, nil
}
// WrappedTransaction wraps a *borp.Transaction such that its major functions
// wrap error results in ErrDatabaseOp instances before returning them to the
// caller.
type WrappedTransaction struct {
transaction *borp.Transaction
}
func (tx WrappedTransaction) Commit() error {
return tx.transaction.Commit()
}
func (tx WrappedTransaction) Rollback() error {
return tx.transaction.Rollback()
}
func (tx WrappedTransaction) Get(ctx context.Context, holder interface{}, keys ...interface{}) (interface{}, error) {
return (WrappedExecutor{sqlExecutor: tx.transaction}).Get(ctx, holder, keys...)
}
func (tx WrappedTransaction) Insert(ctx context.Context, list ...interface{}) error {
return (WrappedExecutor{sqlExecutor: tx.transaction}).Insert(ctx, list...)
}
func (tx WrappedTransaction) Update(ctx context.Context, list ...interface{}) (int64, error) {
return (WrappedExecutor{sqlExecutor: tx.transaction}).Update(ctx, list...)
}
func (tx WrappedTransaction) Delete(ctx context.Context, list ...interface{}) (int64, error) {
return (WrappedExecutor{sqlExecutor: tx.transaction}).Delete(ctx, list...)
}
func (tx WrappedTransaction) Select(ctx context.Context, holder interface{}, query string, args ...interface{}) ([]interface{}, error) {
return (WrappedExecutor{sqlExecutor: tx.transaction}).Select(ctx, holder, query, args...)
}
func (tx WrappedTransaction) SelectOne(ctx context.Context, holder interface{}, query string, args ...interface{}) error {
return (WrappedExecutor{sqlExecutor: tx.transaction}).SelectOne(ctx, holder, query, args...)
}
func (tx WrappedTransaction) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
return (WrappedExecutor{sqlExecutor: tx.transaction}).QueryContext(ctx, query, args...)
}
func (tx WrappedTransaction) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
return (WrappedExecutor{sqlExecutor: tx.transaction}).ExecContext(ctx, query, args...)
}
// WrappedExecutor wraps a borp.SqlExecutor such that its major functions
// wrap error results in ErrDatabaseOp instances before returning them to the
// caller.
type WrappedExecutor struct {
sqlExecutor borp.SqlExecutor
}
func errForOp(operation string, err error, list []interface{}) ErrDatabaseOp {
table := "unknown"
if len(list) > 0 {
table = fmt.Sprintf("%T", list[0])
}
return ErrDatabaseOp{
Op: operation,
Table: table,
Err: err,
}
}
func errForQuery(query, operation string, err error, list []interface{}) ErrDatabaseOp {
// Extract the table from the query
table := tableFromQuery(query)
if table == "" && len(list) > 0 {
// If there's no table from the query but there was a list of holder types,
// use the type from the first element of the list and indicate we failed to
// extract a table from the query.
table = fmt.Sprintf("%T (unknown table)", list[0])
} else if table == "" {
// If there's no table from the query and no list of holders then all we can
// say is that the table is unknown.
table = "unknown table"
}
return ErrDatabaseOp{
Op: operation,
Table: table,
Err: err,
}
}
func (we WrappedExecutor) Get(ctx context.Context, holder interface{}, keys ...interface{}) (interface{}, error) {
res, err := we.sqlExecutor.Get(ctx, holder, keys...)
if err != nil {
return res, errForOp("get", err, []interface{}{holder})
}
return res, err
}
func (we WrappedExecutor) Insert(ctx context.Context, list ...interface{}) error {
err := we.sqlExecutor.Insert(ctx, list...)
if err != nil {
return errForOp("insert", err, list)
}
return nil
}
func (we WrappedExecutor) Update(ctx context.Context, list ...interface{}) (int64, error) {
updatedRows, err := we.sqlExecutor.Update(ctx, list...)
if err != nil {
return updatedRows, errForOp("update", err, list)
}
return updatedRows, err
}
func (we WrappedExecutor) Delete(ctx context.Context, list ...interface{}) (int64, error) {
deletedRows, err := we.sqlExecutor.Delete(ctx, list...)
if err != nil {
return deletedRows, errForOp("delete", err, list)
}
return deletedRows, err
}
func (we WrappedExecutor) Select(ctx context.Context, holder interface{}, query string, args ...interface{}) ([]interface{}, error) {
result, err := we.sqlExecutor.Select(ctx, holder, query, args...)
if err != nil {
return result, errForQuery(query, "select", err, []interface{}{holder})
}
return result, err
}
func (we WrappedExecutor) SelectOne(ctx context.Context, holder interface{}, query string, args ...interface{}) error {
err := we.sqlExecutor.SelectOne(ctx, holder, query, args...)
if err != nil {
return errForQuery(query, "select one", err, []interface{}{holder})
}
return nil
}
func (we WrappedExecutor) SelectNullInt(ctx context.Context, query string, args ...interface{}) (sql.NullInt64, error) {
rows, err := we.sqlExecutor.SelectNullInt(ctx, query, args...)
if err != nil {
return sql.NullInt64{}, errForQuery(query, "select", err, nil)
}
return rows, nil
}
func (we WrappedExecutor) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
// Note: we can't do error wrapping here because the error is passed via the `*sql.Row`
// object, and we can't produce a `*sql.Row` object with a custom error because it is unexported.
return we.sqlExecutor.QueryRowContext(ctx, query, args...)
}
func (we WrappedExecutor) SelectStr(ctx context.Context, query string, args ...interface{}) (string, error) {
str, err := we.sqlExecutor.SelectStr(ctx, query, args...)
if err != nil {
return "", errForQuery(query, "select", err, nil)
}
return str, nil
}
func (we WrappedExecutor) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
rows, err := we.sqlExecutor.QueryContext(ctx, query, args...)
if err != nil {
return nil, errForQuery(query, "select", err, nil)
}
return rows, nil
}
var (
// selectTableRegexp matches the table name from an SQL select statement
selectTableRegexp = regexp.MustCompile(`(?i)^\s*select\s+[a-z\d:\.\(\), \_\*` + "`" + `]+\s+from\s+([a-z\d\_,` + "`" + `]+)`)
// insertTableRegexp matches the table name from an SQL insert statement
insertTableRegexp = regexp.MustCompile(`(?i)^\s*insert\s+into\s+([a-z\d \_,` + "`" + `]+)\s+(?:set|\()`)
// updateTableRegexp matches the table name from an SQL update statement
updateTableRegexp = regexp.MustCompile(`(?i)^\s*update\s+([a-z\d \_,` + "`" + `]+)\s+set`)
// deleteTableRegexp matches the table name from an SQL delete statement
deleteTableRegexp = regexp.MustCompile(`(?i)^\s*delete\s+from\s+([a-z\d \_,` + "`" + `]+)\s+where`)
// tableRegexps is a list of regexps that tableFromQuery will try to use in
// succession to find the table name for an SQL query. While tableFromQuery
// isn't used by the higher level borp Insert/Update/Select/etc functions we
// include regexps for matching inserts, updates, selects, etc because we want
// to match the correct table when these types of queries are run through
// ExecContext().
tableRegexps = []*regexp.Regexp{
selectTableRegexp,
insertTableRegexp,
updateTableRegexp,
deleteTableRegexp,
}
)
// tableFromQuery uses the tableRegexps on the provided query to return the
// associated table name or an empty string if it can't be determined from the
// query.
func tableFromQuery(query string) string {
for _, r := range tableRegexps {
if matches := r.FindStringSubmatch(query); len(matches) >= 2 {
return matches[1]
}
}
return ""
}
func (we WrappedExecutor) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
res, err := we.sqlExecutor.ExecContext(ctx, query, args...)
if err != nil {
return res, errForQuery(query, "exec", err, args)
}
return res, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/gorm_test.go | third-party/github.com/letsencrypt/boulder/db/gorm_test.go | package db
import (
"testing"
"github.com/letsencrypt/boulder/test"
)
func TestValidMariaDBUnquotedIdentifier(t *testing.T) {
test.AssertError(t, validMariaDBUnquotedIdentifier("12345"), "expected error for 12345")
test.AssertError(t, validMariaDBUnquotedIdentifier("12345e"), "expected error for 12345e")
test.AssertError(t, validMariaDBUnquotedIdentifier("1e10"), "expected error for 1e10")
test.AssertError(t, validMariaDBUnquotedIdentifier("foo\\bar"), "expected error for foo\\bar")
test.AssertError(t, validMariaDBUnquotedIdentifier("zoom "), "expected error for identifier ending in space")
test.AssertNotError(t, validMariaDBUnquotedIdentifier("hi"), "expected no error for 'hi'")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/qmarks_test.go | third-party/github.com/letsencrypt/boulder/db/qmarks_test.go | package db
import (
"testing"
"github.com/letsencrypt/boulder/test"
)
func TestQuestionMarks(t *testing.T) {
test.AssertEquals(t, QuestionMarks(1), "?")
test.AssertEquals(t, QuestionMarks(2), "?,?")
test.AssertEquals(t, QuestionMarks(3), "?,?,?")
}
func TestQuestionMarksPanic(t *testing.T) {
defer func() { _ = recover() }()
QuestionMarks(0)
t.Errorf("calling QuestionMarks(0) did not panic as expected")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/db/gorm.go | third-party/github.com/letsencrypt/boulder/db/gorm.go | package db
import (
"context"
"database/sql"
"fmt"
"reflect"
"regexp"
"strings"
)
// Characters allowed in an unquoted identifier by MariaDB.
// https://mariadb.com/kb/en/identifier-names/#unquoted
var mariaDBUnquotedIdentifierRE = regexp.MustCompile("^[0-9a-zA-Z$_]+$")
func validMariaDBUnquotedIdentifier(s string) error {
if !mariaDBUnquotedIdentifierRE.MatchString(s) {
return fmt.Errorf("invalid MariaDB identifier %q", s)
}
allNumeric := true
startsNumeric := false
for i, c := range []byte(s) {
if c < '0' || c > '9' {
if startsNumeric && len(s) > i && s[i] == 'e' {
return fmt.Errorf("MariaDB identifier looks like floating point: %q", s)
}
allNumeric = false
break
}
startsNumeric = true
}
if allNumeric {
return fmt.Errorf("MariaDB identifier contains only numerals: %q", s)
}
return nil
}
// NewMappedSelector returns an object which can be used to automagically query
// the provided type-mapped database for rows of the parameterized type.
func NewMappedSelector[T any](executor MappedExecutor) (MappedSelector[T], error) {
var throwaway T
t := reflect.TypeOf(throwaway)
// We use a very strict mapping of struct fields to table columns here:
// - The struct must not have any embedded structs, only named fields.
// - The struct field names must be case-insensitively identical to the
// column names (no struct tags necessary).
// - The struct field names must be case-insensitively unique.
// - Every field of the struct must correspond to a database column.
// - Note that the reverse is not true: it's perfectly okay for there to be
// database columns which do not correspond to fields in the struct; those
// columns will be ignored.
// TODO: In the future, when we replace borp's TableMap with our own, this
// check should be performed at the time the mapping is declared.
columns := make([]string, 0)
seen := make(map[string]struct{})
for i := range t.NumField() {
field := t.Field(i)
if field.Anonymous {
return nil, fmt.Errorf("struct contains anonymous embedded struct %q", field.Name)
}
column := strings.ToLower(t.Field(i).Name)
err := validMariaDBUnquotedIdentifier(column)
if err != nil {
return nil, fmt.Errorf("struct field maps to unsafe db column name %q", column)
}
if _, found := seen[column]; found {
return nil, fmt.Errorf("struct fields map to duplicate column name %q", column)
}
seen[column] = struct{}{}
columns = append(columns, column)
}
return &mappedSelector[T]{wrapped: executor, columns: columns}, nil
}
type mappedSelector[T any] struct {
wrapped MappedExecutor
columns []string
}
// QueryContext performs a SELECT on the appropriate table for T. It combines the best
// features of borp, the go stdlib, and generics, using the type parameter of
// the typeSelector object to automatically look up the proper table name and
// columns to select. It returns an iterable which yields fully-populated
// objects of the parameterized type directly. The given clauses MUST be only
// the bits of a sql query from "WHERE ..." onwards; if they contain any of the
// "SELECT ... FROM ..." portion of the query it will result in an error. The
// args take the same kinds of values as borp's SELECT: either one argument per
// positional placeholder, or a map of placeholder names to their arguments
// (see https://pkg.go.dev/github.com/letsencrypt/borp#readme-ad-hoc-sql).
//
// The caller is responsible for calling `Rows.Close()` when they are done with
// the query. The caller is also responsible for ensuring that the clauses
// argument does not contain any user-influenced input.
func (ts mappedSelector[T]) QueryContext(ctx context.Context, clauses string, args ...interface{}) (Rows[T], error) {
// Look up the table to use based on the type of this TypeSelector.
var throwaway T
tableMap, err := ts.wrapped.TableFor(reflect.TypeOf(throwaway), false)
if err != nil {
return nil, fmt.Errorf("database model type not mapped to table name: %w", err)
}
return ts.QueryFrom(ctx, tableMap.TableName, clauses, args...)
}
// QueryFrom is the same as Query, but it additionally takes a table name to
// select from, rather than automatically computing the table name from borp's
// DbMap.
//
// The caller is responsible for calling `Rows.Close()` when they are done with
// the query. The caller is also responsible for ensuring that the clauses
// argument does not contain any user-influenced input.
func (ts mappedSelector[T]) QueryFrom(ctx context.Context, tablename string, clauses string, args ...interface{}) (Rows[T], error) {
err := validMariaDBUnquotedIdentifier(tablename)
if err != nil {
return nil, err
}
// Construct the query from the column names, table name, and given clauses.
// Note that the column names here are in the order given by
query := fmt.Sprintf(
"SELECT %s FROM %s %s",
strings.Join(ts.columns, ", "),
tablename,
clauses,
)
r, err := ts.wrapped.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("reading db: %w", err)
}
return &rows[T]{wrapped: r, numCols: len(ts.columns)}, nil
}
// rows is a wrapper around the stdlib's sql.rows, but with a more
// type-safe method to get actual row content.
type rows[T any] struct {
wrapped *sql.Rows
numCols int
}
// ForEach calls the given function with each model object retrieved by
// repeatedly calling .Get(). It closes the rows object when it hits an error
// or finishes iterating over the rows, so it can only be called once. This is
// the intended way to use the result of QueryContext or QueryFrom; the other
// methods on this type are lower-level and intended for advanced use only.
func (r rows[T]) ForEach(do func(*T) error) (err error) {
defer func() {
// Close the row reader when we exit. Use the named error return to combine
// any error from normal execution with any error from closing.
closeErr := r.Close()
if closeErr != nil && err != nil {
err = fmt.Errorf("%w; also while closing the row reader: %w", err, closeErr)
} else if closeErr != nil {
err = closeErr
}
// If closeErr is nil, then just leaving the existing named return alone
// will do the right thing.
}()
for r.Next() {
row, err := r.Get()
if err != nil {
return fmt.Errorf("reading row: %w", err)
}
err = do(row)
if err != nil {
return err
}
}
err = r.Err()
if err != nil {
return fmt.Errorf("iterating over row reader: %w", err)
}
return nil
}
// Next is a wrapper around sql.Rows.Next(). It must be called before every call
// to Get(), including the first.
func (r rows[T]) Next() bool {
return r.wrapped.Next()
}
// Get is a wrapper around sql.Rows.Scan(). Rather than populating an arbitrary
// number of &interface{} arguments, it returns a populated object of the
// parameterized type.
func (r rows[T]) Get() (*T, error) {
result := new(T)
v := reflect.ValueOf(result)
// Because sql.Rows.Scan(...) takes a variadic number of individual targets to
// read values into, build a slice that can be splatted into the call. Use the
// pre-computed list of in-order column names to populate it.
scanTargets := make([]interface{}, r.numCols)
for i := range scanTargets {
field := v.Elem().Field(i)
scanTargets[i] = field.Addr().Interface()
}
err := r.wrapped.Scan(scanTargets...)
if err != nil {
return nil, fmt.Errorf("reading db row: %w", err)
}
return result, nil
}
// Err is a wrapper around sql.Rows.Err(). It should be checked immediately
// after Next() returns false for any reason.
func (r rows[T]) Err() error {
return r.wrapped.Err()
}
// Close is a wrapper around sql.Rows.Close(). It must be called when the caller
// is done reading rows, regardless of success or error.
func (r rows[T]) Close() error {
return r.wrapped.Close()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/redis/metrics.go | third-party/github.com/letsencrypt/boulder/redis/metrics.go | package redis
import (
"errors"
"slices"
"strings"
"github.com/prometheus/client_golang/prometheus"
"github.com/redis/go-redis/v9"
)
// An interface satisfied by *redis.ClusterClient and also by a mock in our tests.
type poolStatGetter interface {
PoolStats() *redis.PoolStats
}
var _ poolStatGetter = (*redis.ClusterClient)(nil)
type metricsCollector struct {
statGetter poolStatGetter
// Stats accessible from the go-redis connector:
// https://pkg.go.dev/github.com/go-redis/redis@v6.15.9+incompatible/internal/pool#Stats
lookups *prometheus.Desc
totalConns *prometheus.Desc
idleConns *prometheus.Desc
staleConns *prometheus.Desc
}
// Describe is implemented with DescribeByCollect. That's possible because the
// Collect method will always return the same metrics with the same descriptors.
func (dbc metricsCollector) Describe(ch chan<- *prometheus.Desc) {
prometheus.DescribeByCollect(dbc, ch)
}
// Collect first triggers the Redis ClusterClient's PoolStats function.
// Then it creates constant metrics for each Stats value on the fly based
// on the returned data.
//
// Note that Collect could be called concurrently, so we depend on PoolStats()
// to be concurrency-safe.
func (dbc metricsCollector) Collect(ch chan<- prometheus.Metric) {
writeGauge := func(stat *prometheus.Desc, val uint32, labelValues ...string) {
ch <- prometheus.MustNewConstMetric(stat, prometheus.GaugeValue, float64(val), labelValues...)
}
stats := dbc.statGetter.PoolStats()
writeGauge(dbc.lookups, stats.Hits, "hit")
writeGauge(dbc.lookups, stats.Misses, "miss")
writeGauge(dbc.lookups, stats.Timeouts, "timeout")
writeGauge(dbc.totalConns, stats.TotalConns)
writeGauge(dbc.idleConns, stats.IdleConns)
writeGauge(dbc.staleConns, stats.StaleConns)
}
// newClientMetricsCollector is broken out for testing purposes.
func newClientMetricsCollector(statGetter poolStatGetter, labels prometheus.Labels) metricsCollector {
return metricsCollector{
statGetter: statGetter,
lookups: prometheus.NewDesc(
"redis_connection_pool_lookups",
"Number of lookups for a connection in the pool, labeled by hit/miss",
[]string{"result"}, labels),
totalConns: prometheus.NewDesc(
"redis_connection_pool_total_conns",
"Number of total connections in the pool.",
nil, labels),
idleConns: prometheus.NewDesc(
"redis_connection_pool_idle_conns",
"Number of idle connections in the pool.",
nil, labels),
staleConns: prometheus.NewDesc(
"redis_connection_pool_stale_conns",
"Number of stale connections removed from the pool.",
nil, labels),
}
}
// MustRegisterClientMetricsCollector registers a metrics collector for the
// given Redis client with the provided prometheus.Registerer. The collector
// will report metrics labelled by the provided addresses and username. If the
// collector is already registered, this function is a no-op.
func MustRegisterClientMetricsCollector(client poolStatGetter, stats prometheus.Registerer, addrs map[string]string, user string) {
var labelAddrs []string
for addr := range addrs {
labelAddrs = append(labelAddrs, addr)
}
// Keep the list of addresses sorted for consistency.
slices.Sort(labelAddrs)
labels := prometheus.Labels{
"addresses": strings.Join(labelAddrs, ", "),
"user": user,
}
err := stats.Register(newClientMetricsCollector(client, labels))
if err != nil {
are := prometheus.AlreadyRegisteredError{}
if errors.As(err, &are) {
// The collector is already registered using the same labels.
return
}
panic(err)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/redis/config.go | third-party/github.com/letsencrypt/boulder/redis/config.go | package redis
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/redis/go-redis/extra/redisotel/v9"
"github.com/redis/go-redis/v9"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/config"
blog "github.com/letsencrypt/boulder/log"
)
// Config contains the configuration needed to act as a Redis client.
type Config struct {
// TLS contains the configuration to speak TLS with Redis.
TLS cmd.TLSConfig
// Username used to authenticate to each Redis instance.
Username string `validate:"required"`
// PasswordFile is the path to a file holding the password used to
// authenticate to each Redis instance.
cmd.PasswordConfig
// ShardAddrs is a map of shard names to IP address:port pairs. The go-redis
// `Ring` client will shard reads and writes across the provided Redis
// Servers based on a consistent hashing algorithm.
ShardAddrs map[string]string `validate:"omitempty,required_without=Lookups,min=1,dive,hostname_port"`
// Lookups each entry contains a service and domain name that will be used
// to construct a SRV DNS query to lookup Redis backends. For example: if
// the resource record is 'foo.service.consul', then the 'Service' is 'foo'
// and the 'Domain' is 'service.consul'. The expected dNSName to be
// authenticated in the server certificate would be 'foo.service.consul'.
Lookups []cmd.ServiceDomain `validate:"omitempty,required_without=ShardAddrs,min=1,dive"`
// LookupFrequency is the frequency of periodic SRV lookups. Defaults to 30
// seconds.
LookupFrequency config.Duration `validate:"-"`
// LookupDNSAuthority can only be specified with Lookups. It's a single
// <hostname|IPv4|[IPv6]>:<port> of the DNS server to be used for resolution
// of Redis backends. If the address contains a hostname it will be resolved
// using system DNS. If the address contains a port, the client will use it
// directly, otherwise port 53 is used. If this field is left unspecified
// the system DNS will be used for resolution.
LookupDNSAuthority string `validate:"excluded_without=Lookups,omitempty,ip|hostname|hostname_port"`
// Enables read-only commands on replicas.
ReadOnly bool
// Allows routing read-only commands to the closest primary or replica.
// It automatically enables ReadOnly.
RouteByLatency bool
// Allows routing read-only commands to a random primary or replica.
// It automatically enables ReadOnly.
RouteRandomly bool
// PoolFIFO uses FIFO mode for each node connection pool GET/PUT (default LIFO).
PoolFIFO bool
// Maximum number of retries before giving up.
// Default is to not retry failed commands.
MaxRetries int `validate:"min=0"`
// Minimum backoff between each retry.
// Default is 8 milliseconds; -1 disables backoff.
MinRetryBackoff config.Duration `validate:"-"`
// Maximum backoff between each retry.
// Default is 512 milliseconds; -1 disables backoff.
MaxRetryBackoff config.Duration `validate:"-"`
// Dial timeout for establishing new connections.
// Default is 5 seconds.
DialTimeout config.Duration `validate:"-"`
// Timeout for socket reads. If reached, commands will fail
// with a timeout instead of blocking. Use value -1 for no timeout and 0 for default.
// Default is 3 seconds.
ReadTimeout config.Duration `validate:"-"`
// Timeout for socket writes. If reached, commands will fail
// with a timeout instead of blocking.
// Default is ReadTimeout.
WriteTimeout config.Duration `validate:"-"`
// Maximum number of socket connections.
// Default is 5 connections per every CPU as reported by runtime.NumCPU.
// If this is set to an explicit value, that's not multiplied by NumCPU.
// PoolSize applies per cluster node and not for the whole cluster.
// https://pkg.go.dev/github.com/go-redis/redis#ClusterOptions
PoolSize int `validate:"min=0"`
// Minimum number of idle connections which is useful when establishing
// new connection is slow.
MinIdleConns int `validate:"min=0"`
// Connection age at which client retires (closes) the connection.
// Default is to not close aged connections.
MaxConnAge config.Duration `validate:"-"`
// Amount of time client waits for connection if all connections
// are busy before returning an error.
// Default is ReadTimeout + 1 second.
PoolTimeout config.Duration `validate:"-"`
// Amount of time after which client closes idle connections.
// Should be less than server's timeout.
// Default is 5 minutes. -1 disables idle timeout check.
IdleTimeout config.Duration `validate:"-"`
// Frequency of idle checks made by idle connections reaper.
// Default is 1 minute. -1 disables idle connections reaper,
// but idle connections are still discarded by the client
// if IdleTimeout is set.
// Deprecated: This field has been deprecated and will be removed.
IdleCheckFrequency config.Duration `validate:"-"`
}
// Ring is a wrapper around the go-redis/v9 Ring client that adds support for
// (optional) periodic SRV lookups.
type Ring struct {
*redis.Ring
lookup *lookup
}
// NewRingFromConfig returns a new *redis.Ring client. If periodic SRV lookups
// are supplied, a goroutine will be started to periodically perform lookups.
// Callers should defer a call to StopLookups() to ensure that this goroutine is
// gracefully shutdown.
func NewRingFromConfig(c Config, stats prometheus.Registerer, log blog.Logger) (*Ring, error) {
password, err := c.Pass()
if err != nil {
return nil, fmt.Errorf("loading password: %w", err)
}
tlsConfig, err := c.TLS.Load(stats)
if err != nil {
return nil, fmt.Errorf("loading TLS config: %w", err)
}
inner := redis.NewRing(&redis.RingOptions{
Addrs: c.ShardAddrs,
Username: c.Username,
Password: password,
TLSConfig: tlsConfig,
MaxRetries: c.MaxRetries,
MinRetryBackoff: c.MinRetryBackoff.Duration,
MaxRetryBackoff: c.MaxRetryBackoff.Duration,
DialTimeout: c.DialTimeout.Duration,
ReadTimeout: c.ReadTimeout.Duration,
WriteTimeout: c.WriteTimeout.Duration,
PoolSize: c.PoolSize,
MinIdleConns: c.MinIdleConns,
ConnMaxLifetime: c.MaxConnAge.Duration,
PoolTimeout: c.PoolTimeout.Duration,
ConnMaxIdleTime: c.IdleTimeout.Duration,
})
if len(c.ShardAddrs) > 0 {
// Client was statically configured with a list of shards.
MustRegisterClientMetricsCollector(inner, stats, c.ShardAddrs, c.Username)
}
var lookup *lookup
if len(c.Lookups) != 0 {
lookup, err = newLookup(c.Lookups, c.LookupDNSAuthority, c.LookupFrequency.Duration, inner, log, stats)
if err != nil {
return nil, err
}
lookup.start()
}
err = redisotel.InstrumentTracing(inner)
if err != nil {
return nil, err
}
return &Ring{
Ring: inner,
lookup: lookup,
}, nil
}
// StopLookups stops the goroutine responsible for keeping the shards of the
// inner *redis.Ring up-to-date. It is a no-op if the Ring was not constructed
// with periodic lookups or if the lookups have already been stopped.
func (r *Ring) StopLookups() {
if r == nil || r.lookup == nil {
// No-op.
return
}
r.lookup.stop()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/redis/lookup_test.go | third-party/github.com/letsencrypt/boulder/redis/lookup_test.go | package redis
import (
"context"
"testing"
"time"
"github.com/letsencrypt/boulder/cmd"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
"github.com/letsencrypt/boulder/test"
"github.com/redis/go-redis/v9"
)
func newTestRedisRing() *redis.Ring {
CACertFile := "../test/certs/ipki/minica.pem"
CertFile := "../test/certs/ipki/localhost/cert.pem"
KeyFile := "../test/certs/ipki/localhost/key.pem"
tlsConfig := cmd.TLSConfig{
CACertFile: CACertFile,
CertFile: CertFile,
KeyFile: KeyFile,
}
tlsConfig2, err := tlsConfig.Load(metrics.NoopRegisterer)
if err != nil {
panic(err)
}
client := redis.NewRing(&redis.RingOptions{
Username: "unittest-rw",
Password: "824968fa490f4ecec1e52d5e34916bdb60d45f8d",
TLSConfig: tlsConfig2,
})
return client
}
func TestNewLookup(t *testing.T) {
t.Parallel()
logger := blog.NewMock()
ring := newTestRedisRing()
_, err := newLookup([]cmd.ServiceDomain{
{
Service: "redisratelimits",
Domain: "service.consul",
},
},
"consul.service.consul",
250*time.Millisecond,
ring,
logger,
metrics.NoopRegisterer,
)
test.AssertNotError(t, err, "Expected newLookup construction to succeed")
}
func TestStart(t *testing.T) {
t.Parallel()
logger := blog.NewMock()
ring := newTestRedisRing()
lookup, err := newLookup([]cmd.ServiceDomain{
{
Service: "redisratelimits",
Domain: "service.consul",
},
},
"consul.service.consul",
250*time.Millisecond,
ring,
logger,
metrics.NoopRegisterer,
)
test.AssertNotError(t, err, "Expected newLookup construction to succeed")
lookup.start()
lookup.stop()
}
func TestNewLookupWithOneFailingSRV(t *testing.T) {
t.Parallel()
logger := blog.NewMock()
ring := newTestRedisRing()
_, err := newLookup([]cmd.ServiceDomain{
{
Service: "doesnotexist",
Domain: "service.consuls",
},
{
Service: "redisratelimits",
Domain: "service.consul",
},
},
"consul.service.consul",
250*time.Millisecond,
ring,
logger,
metrics.NoopRegisterer,
)
test.AssertNotError(t, err, "Expected newLookup construction to succeed")
}
func TestNewLookupWithAllFailingSRV(t *testing.T) {
t.Parallel()
logger := blog.NewMock()
ring := newTestRedisRing()
_, err := newLookup([]cmd.ServiceDomain{
{
Service: "doesnotexist",
Domain: "service.consuls",
},
{
Service: "doesnotexist2",
Domain: "service.consuls",
},
},
"consul.service.consul",
250*time.Millisecond,
ring,
logger,
metrics.NoopRegisterer,
)
test.AssertError(t, err, "Expected newLookup construction to fail")
}
func TestUpdateNowWithAllFailingSRV(t *testing.T) {
t.Parallel()
logger := blog.NewMock()
ring := newTestRedisRing()
lookup, err := newLookup([]cmd.ServiceDomain{
{
Service: "redisratelimits",
Domain: "service.consul",
},
},
"consul.service.consul",
250*time.Millisecond,
ring,
logger,
metrics.NoopRegisterer,
)
test.AssertNotError(t, err, "Expected newLookup construction to succeed")
lookup.srvLookups = []cmd.ServiceDomain{
{
Service: "doesnotexist1",
Domain: "service.consul",
},
{
Service: "doesnotexist2",
Domain: "service.consul",
},
}
testCtx, cancel := context.WithCancel(context.Background())
defer cancel()
tempErr, nonTempErr := lookup.updateNow(testCtx)
test.AssertNotError(t, tempErr, "Expected no temporary errors")
test.AssertError(t, nonTempErr, "Expected non-temporary errors to have occurred")
}
func TestUpdateNowWithAllFailingSRVs(t *testing.T) {
t.Parallel()
logger := blog.NewMock()
ring := newTestRedisRing()
lookup, err := newLookup([]cmd.ServiceDomain{
{
Service: "redisratelimits",
Domain: "service.consul",
},
},
"consul.service.consul",
250*time.Millisecond,
ring,
logger,
metrics.NoopRegisterer,
)
test.AssertNotError(t, err, "Expected newLookup construction to succeed")
// Replace the dnsAuthority with a non-existent DNS server, this will cause
// a timeout error, which is technically a temporary error, but will
// eventually result in a non-temporary error when no shards are resolved.
lookup.dnsAuthority = "consuls.services.consuls:53"
testCtx, cancel := context.WithCancel(context.Background())
defer cancel()
tempErr, nonTempErr := lookup.updateNow(testCtx)
test.AssertError(t, tempErr, "Expected temporary errors")
test.AssertError(t, nonTempErr, "Expected a non-temporary error")
test.AssertErrorIs(t, nonTempErr, ErrNoShardsResolved)
}
func TestUpdateNowWithOneFailingSRV(t *testing.T) {
t.Parallel()
logger := blog.NewMock()
ring := newTestRedisRing()
lookup, err := newLookup([]cmd.ServiceDomain{
{
Service: "doesnotexist",
Domain: "service.consuls",
},
{
Service: "redisratelimits",
Domain: "service.consul",
},
},
"consul.service.consul",
250*time.Millisecond,
ring,
logger,
metrics.NoopRegisterer,
)
test.AssertNotError(t, err, "Expected newLookup construction to succeed")
// The Consul service entry for 'redisratelimits' is configured to return
// two SRV targets. We should only have two shards in the ring.
test.Assert(t, ring.Len() == 2, "Expected 2 shards in the ring")
testCtx, cancel := context.WithCancel(context.Background())
defer cancel()
// Ensure we can reach both shards using the PING command.
err = ring.ForEachShard(testCtx, func(ctx context.Context, shard *redis.Client) error {
return shard.Ping(ctx).Err()
})
test.AssertNotError(t, err, "Expected PING to succeed for both shards")
// Drop both Shards from the ring.
ring.SetAddrs(map[string]string{})
test.Assert(t, ring.Len() == 0, "Expected 0 shards in the ring")
// Force a lookup to occur.
tempErr, nonTempErr := lookup.updateNow(testCtx)
test.AssertNotError(t, tempErr, "Expected no temporary errors")
test.AssertNotError(t, nonTempErr, "Expected no non-temporary errors")
// The ring should now have two shards again.
test.Assert(t, ring.Len() == 2, "Expected 2 shards in the ring")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/redis/lookup.go | third-party/github.com/letsencrypt/boulder/redis/lookup.go | package redis
import (
"context"
"errors"
"fmt"
"net"
"strings"
"time"
"github.com/letsencrypt/boulder/cmd"
blog "github.com/letsencrypt/boulder/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/redis/go-redis/v9"
)
var ErrNoShardsResolved = errors.New("0 shards were resolved")
// lookup wraps a Redis ring client by reference and keeps the Redis ring shards
// up to date via periodic SRV lookups.
type lookup struct {
// srvLookups is a list of SRV records to be looked up.
srvLookups []cmd.ServiceDomain
// updateFrequency is the frequency of periodic SRV lookups. Defaults to 30
// seconds.
updateFrequency time.Duration
// updateTimeout is the timeout for each SRV lookup. Defaults to 90% of the
// update frequency.
updateTimeout time.Duration
// dnsAuthority is the single <hostname|IPv4|[IPv6]>:<port> of the DNS
// server to be used for SRV lookups. If the address contains a hostname it
// will be resolved via the system DNS. If the port is left unspecified it
// will default to '53'. If this field is left unspecified the system DNS
// will be used for resolution.
dnsAuthority string
// stop is a context.CancelFunc that can be used to stop the goroutine
// responsible for performing periodic SRV lookups.
stop context.CancelFunc
resolver *net.Resolver
ring *redis.Ring
logger blog.Logger
stats prometheus.Registerer
}
// newLookup constructs and returns a new lookup instance. An initial SRV lookup
// is performed to populate the Redis ring shards. If this lookup fails or
// otherwise results in an empty set of resolved shards, an error is returned.
func newLookup(srvLookups []cmd.ServiceDomain, dnsAuthority string, frequency time.Duration, ring *redis.Ring, logger blog.Logger, stats prometheus.Registerer) (*lookup, error) {
updateFrequency := frequency
if updateFrequency <= 0 {
// Set default frequency.
updateFrequency = 30 * time.Second
}
// Set default timeout to 90% of the update frequency.
updateTimeout := updateFrequency - updateFrequency/10
lookup := &lookup{
srvLookups: srvLookups,
ring: ring,
logger: logger,
stats: stats,
updateFrequency: updateFrequency,
updateTimeout: updateTimeout,
dnsAuthority: dnsAuthority,
}
if dnsAuthority == "" {
// Use the system DNS resolver.
lookup.resolver = net.DefaultResolver
} else {
// Setup a custom DNS resolver.
host, port, err := net.SplitHostPort(dnsAuthority)
if err != nil {
// Assume only hostname or IPv4 address was specified.
host = dnsAuthority
port = "53"
}
lookup.dnsAuthority = net.JoinHostPort(host, port)
lookup.resolver = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
// The custom resolver closes over the lookup.dnsAuthority field
// so it can be swapped out in testing.
return net.Dial(network, lookup.dnsAuthority)
},
}
}
ctx, cancel := context.WithTimeout(context.Background(), updateTimeout)
defer cancel()
tempErr, nonTempErr := lookup.updateNow(ctx)
if tempErr != nil {
// Log and discard temporary errors, as they're likely to be transient
// (e.g. network connectivity issues).
logger.Warningf("resolving ring shards: %s", tempErr)
}
if nonTempErr != nil && errors.Is(nonTempErr, ErrNoShardsResolved) {
// Non-temporary errors are always logged inside of updateNow(), so we
// only need return the error here if it's ErrNoShardsResolved.
return nil, nonTempErr
}
return lookup, nil
}
// updateNow resolves and updates the Redis ring shards accordingly. If all
// lookups fail or otherwise result in an empty set of resolved shards, the
// Redis ring is left unmodified and any errors are returned. If at least one
// lookup succeeds, the Redis ring is updated, and all errors are discarded.
// Non-temporary DNS errors are always logged as they occur, as they're likely
// to be indicative of a misconfiguration.
func (look *lookup) updateNow(ctx context.Context) (tempError, nonTempError error) {
var tempErrs []error
handleDNSError := func(err error, srv cmd.ServiceDomain) {
var dnsErr *net.DNSError
if errors.As(err, &dnsErr) && (dnsErr.IsTimeout || dnsErr.IsTemporary) {
tempErrs = append(tempErrs, err)
return
}
// Log non-temporary DNS errors as they occur, as they're likely to be
// indicative of misconfiguration.
look.logger.Errf("resolving service _%s._tcp.%s: %s", srv.Service, srv.Domain, err)
}
nextAddrs := make(map[string]string)
for _, srv := range look.srvLookups {
_, targets, err := look.resolver.LookupSRV(ctx, srv.Service, "tcp", srv.Domain)
if err != nil {
handleDNSError(err, srv)
// Skip to the next SRV lookup.
continue
}
if len(targets) <= 0 {
tempErrs = append(tempErrs, fmt.Errorf("0 targets resolved for service \"_%s._tcp.%s\"", srv.Service, srv.Domain))
// Skip to the next SRV lookup.
continue
}
for _, target := range targets {
host := strings.TrimRight(target.Target, ".")
if look.dnsAuthority != "" {
// Lookup A/AAAA records for the SRV target using the custom DNS
// authority.
hostAddrs, err := look.resolver.LookupHost(ctx, host)
if err != nil {
handleDNSError(err, srv)
// Skip to the next A/AAAA lookup.
continue
}
if len(hostAddrs) <= 0 {
tempErrs = append(tempErrs, fmt.Errorf("0 addrs resolved for target %q of service \"_%s._tcp.%s\"", host, srv.Service, srv.Domain))
// Skip to the next A/AAAA lookup.
continue
}
// Use the first resolved IP address.
host = hostAddrs[0]
}
addr := fmt.Sprintf("%s:%d", host, target.Port)
nextAddrs[addr] = addr
}
}
// Only return errors if we failed to resolve any shards.
if len(nextAddrs) <= 0 {
return errors.Join(tempErrs...), ErrNoShardsResolved
}
// Some shards were resolved, update the Redis ring and discard all errors.
look.ring.SetAddrs(nextAddrs)
// Update the Redis client metrics.
MustRegisterClientMetricsCollector(look.ring, look.stats, nextAddrs, look.ring.Options().Username)
return nil, nil
}
// start starts a goroutine that keeps the Redis ring shards up-to-date by
// periodically performing SRV lookups.
func (look *lookup) start() {
var lookupCtx context.Context
lookupCtx, look.stop = context.WithCancel(context.Background())
go func() {
ticker := time.NewTicker(look.updateFrequency)
defer ticker.Stop()
for {
// Check for context cancellation before we do any work.
if lookupCtx.Err() != nil {
return
}
timeoutCtx, cancel := context.WithTimeout(lookupCtx, look.updateTimeout)
tempErrs, nonTempErrs := look.updateNow(timeoutCtx)
cancel()
if tempErrs != nil {
look.logger.Warningf("resolving ring shards, temporary errors: %s", tempErrs)
continue
}
if nonTempErrs != nil {
look.logger.Errf("resolving ring shards, non-temporary errors: %s", nonTempErrs)
continue
}
select {
case <-ticker.C:
continue
case <-lookupCtx.Done():
return
}
}
}()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/redis/metrics_test.go | third-party/github.com/letsencrypt/boulder/redis/metrics_test.go | package redis
import (
"strings"
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/redis/go-redis/v9"
"github.com/letsencrypt/boulder/metrics"
)
type mockPoolStatGetter struct{}
var _ poolStatGetter = mockPoolStatGetter{}
func (mockPoolStatGetter) PoolStats() *redis.PoolStats {
return &redis.PoolStats{
Hits: 13,
Misses: 7,
Timeouts: 4,
TotalConns: 1000,
IdleConns: 500,
StaleConns: 10,
}
}
func TestMetrics(t *testing.T) {
mets := newClientMetricsCollector(mockPoolStatGetter{},
prometheus.Labels{
"foo": "bar",
})
// Check that it has the correct type to satisfy MustRegister
metrics.NoopRegisterer.MustRegister(mets)
expectedMetrics := 6
outChan := make(chan prometheus.Metric, expectedMetrics)
mets.Collect(outChan)
results := make(map[string]bool)
for range expectedMetrics {
metric := <-outChan
t.Log(metric.Desc().String())
results[metric.Desc().String()] = true
}
expected := strings.Split(
`Desc{fqName: "redis_connection_pool_lookups", help: "Number of lookups for a connection in the pool, labeled by hit/miss", constLabels: {foo="bar"}, variableLabels: {result}}
Desc{fqName: "redis_connection_pool_lookups", help: "Number of lookups for a connection in the pool, labeled by hit/miss", constLabels: {foo="bar"}, variableLabels: {result}}
Desc{fqName: "redis_connection_pool_lookups", help: "Number of lookups for a connection in the pool, labeled by hit/miss", constLabels: {foo="bar"}, variableLabels: {result}}
Desc{fqName: "redis_connection_pool_total_conns", help: "Number of total connections in the pool.", constLabels: {foo="bar"}, variableLabels: {}}
Desc{fqName: "redis_connection_pool_idle_conns", help: "Number of idle connections in the pool.", constLabels: {foo="bar"}, variableLabels: {}}
Desc{fqName: "redis_connection_pool_stale_conns", help: "Number of stale connections removed from the pool.", constLabels: {foo="bar"}, variableLabels: {}}`,
"\n")
for _, e := range expected {
if !results[e] {
t.Errorf("expected metrics to contain %q, but they didn't", e)
}
}
if len(results) > len(expected) {
t.Errorf("expected metrics to contain %d entries, but they contained %d",
len(expected), len(results))
}
}
func TestMustRegisterClientMetricsCollector(t *testing.T) {
client := mockPoolStatGetter{}
stats := prometheus.NewRegistry()
// First registration should succeed.
MustRegisterClientMetricsCollector(client, stats, map[string]string{"foo": "bar"}, "baz")
// Duplicate registration should succeed.
MustRegisterClientMetricsCollector(client, stats, map[string]string{"foo": "bar"}, "baz")
// Registration with different label values should succeed.
MustRegisterClientMetricsCollector(client, stats, map[string]string{"f00": "b4r"}, "b4z")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/metrics/scope.go | third-party/github.com/letsencrypt/boulder/metrics/scope.go | package metrics
import "github.com/prometheus/client_golang/prometheus"
// InternetFacingBuckets are the histogram buckets that should be used when
// measuring latencies that involve traversing the public internet.
var InternetFacingBuckets = []float64{.1, .5, 1, 5, 10, 30, 45}
// noopRegisterer mocks prometheus.Registerer. It is used when we need to
// register prometheus metrics in tests where multiple registrations would
// cause a panic.
type noopRegisterer struct{}
func (np *noopRegisterer) MustRegister(_ ...prometheus.Collector) {}
func (np *noopRegisterer) Register(_ prometheus.Collector) error { return nil }
func (np *noopRegisterer) Unregister(_ prometheus.Collector) bool { return true }
var NoopRegisterer = &noopRegisterer{}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/metrics/measured_http/http_test.go | third-party/github.com/letsencrypt/boulder/metrics/measured_http/http_test.go | package measured_http
import (
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/jmhodges/clock"
"github.com/prometheus/client_golang/prometheus"
io_prometheus_client "github.com/prometheus/client_model/go"
)
type sleepyHandler struct {
clk clock.FakeClock
}
func (h sleepyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.clk.Sleep(999 * time.Second)
w.WriteHeader(302)
}
func collect(m prometheus.Collector) *io_prometheus_client.Metric {
ch := make(chan prometheus.Metric, 10)
m.Collect(ch)
result := <-ch
var iom = new(io_prometheus_client.Metric)
_ = result.Write(iom)
return iom
}
func TestMeasuring(t *testing.T) {
clk := clock.NewFake()
// Create a local histogram stat with the same labels as the real one, but
// don't register it; we will collect its data here in the test to verify it.
stat := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "fake",
Help: "fake",
},
[]string{"endpoint", "method", "code"})
inFlightRequestsGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "in_flight_requests",
Help: "Tracks the number of WFE requests currently in flight, labeled by endpoint.",
},
[]string{"endpoint"},
)
mux := http.NewServeMux()
mux.Handle("/foo", sleepyHandler{clk})
mh := MeasuredHandler{
serveMux: mux,
clk: clk,
stat: stat,
inFlightRequestsGauge: inFlightRequestsGauge,
}
mh.ServeHTTP(httptest.NewRecorder(), &http.Request{
URL: &url.URL{Path: "/foo"},
Method: "GET",
})
iom := collect(stat)
hist := iom.Histogram
if *hist.SampleCount != 1 {
t.Errorf("SampleCount = %d (expected 1)", *hist.SampleCount)
}
if *hist.SampleSum != 999 {
t.Errorf("SampleSum = %g (expected 999)", *hist.SampleSum)
}
expectedLabels := map[string]string{
"endpoint": "/foo",
"method": "GET",
"code": "302",
}
for _, labelPair := range iom.Label {
if expectedLabels[*labelPair.Name] == "" {
t.Errorf("Unexpected label %s", *labelPair.Name)
} else if expectedLabels[*labelPair.Name] != *labelPair.Value {
t.Errorf("labels[%q] = %q (expected %q)", *labelPair.Name, *labelPair.Value,
expectedLabels[*labelPair.Name])
}
delete(expectedLabels, *labelPair.Name)
}
if len(expectedLabels) != 0 {
t.Errorf("Some labels were expected, but not observed: %v", expectedLabels)
}
}
// Make an HTTP request with an unknown method and ensure we use the appropriate
// label value.
func TestUnknownMethod(t *testing.T) {
clk := clock.NewFake()
// Create a local histogram stat with the same labels as the real one, but
// don't register it; we will collect its data here in the test to verify it.
stat := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "fake",
Help: "fake",
},
[]string{"endpoint", "method", "code"})
inFlightRequestsGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "in_flight_requests",
Help: "Tracks the number of WFE requests currently in flight, labeled by endpoint.",
},
[]string{"endpoint"},
)
mux := http.NewServeMux()
mux.Handle("/foo", sleepyHandler{clk})
mh := MeasuredHandler{
serveMux: mux,
clk: clk,
stat: stat,
inFlightRequestsGauge: inFlightRequestsGauge,
}
mh.ServeHTTP(httptest.NewRecorder(), &http.Request{
URL: &url.URL{Path: "/foo"},
Method: "POKE",
})
iom := collect(stat)
expectedLabels := map[string]string{
"endpoint": "/foo",
"method": "unknown",
"code": "302",
}
for _, labelPair := range iom.Label {
if expectedLabels[*labelPair.Name] == "" {
t.Errorf("Unexpected label %s", *labelPair.Name)
} else if expectedLabels[*labelPair.Name] != *labelPair.Value {
t.Errorf("labels[%q] = %q (expected %q)", *labelPair.Name, *labelPair.Value,
expectedLabels[*labelPair.Name])
}
delete(expectedLabels, *labelPair.Name)
}
if len(expectedLabels) != 0 {
t.Errorf("Some labels were expected, but not observed: %v", expectedLabels)
}
}
func TestWrite(t *testing.T) {
clk := clock.NewFake()
// Create a local histogram stat with the same labels as the real one, but
// don't register it; we will collect its data here in the test to verify it.
stat := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "fake",
Help: "fake",
},
[]string{"endpoint", "method", "code"})
inFlightRequestsGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "in_flight_requests",
Help: "Tracks the number of WFE requests currently in flight, labeled by endpoint.",
},
[]string{"endpoint"})
mux := http.NewServeMux()
mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte{})
})
mh := MeasuredHandler{
serveMux: mux,
clk: clk,
stat: stat,
inFlightRequestsGauge: inFlightRequestsGauge,
}
mh.ServeHTTP(httptest.NewRecorder(), &http.Request{
URL: &url.URL{Path: "/foo"},
Method: "GET",
})
iom := collect(stat)
stat = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "fake",
Help: "fake",
},
[]string{"endpoint", "method", "code"})
mh.stat = stat
mh.inFlightRequestsGauge = inFlightRequestsGauge
expectedLabels := map[string]string{
"endpoint": "/foo",
"method": "GET",
"code": "200",
}
for _, labelPair := range iom.Label {
if expectedLabels[*labelPair.Name] == "" {
t.Errorf("Unexpected label %s", *labelPair.Name)
} else if expectedLabels[*labelPair.Name] != *labelPair.Value {
t.Errorf("labels[%q] = %q (expected %q)", *labelPair.Name, *labelPair.Value,
expectedLabels[*labelPair.Name])
}
delete(expectedLabels, *labelPair.Name)
}
if len(expectedLabels) != 0 {
t.Errorf("Some labels were expected, but not observed: %v", expectedLabels)
}
mux.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(202)
w.Write([]byte{})
})
mh.ServeHTTP(httptest.NewRecorder(), &http.Request{
URL: &url.URL{Path: "/bar"},
Method: "GET",
})
iom = collect(stat)
expectedLabels = map[string]string{
"endpoint": "/bar",
"method": "GET",
"code": "202",
}
for _, labelPair := range iom.Label {
if expectedLabels[*labelPair.Name] == "" {
t.Errorf("Unexpected label %s", *labelPair.Name)
} else if expectedLabels[*labelPair.Name] != *labelPair.Value {
t.Errorf("labels[%q] = %q (expected %q)", *labelPair.Name, *labelPair.Value,
expectedLabels[*labelPair.Name])
}
delete(expectedLabels, *labelPair.Name)
}
if len(expectedLabels) != 0 {
t.Errorf("Some labels were expected, but not observed: %v", expectedLabels)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/metrics/measured_http/http.go | third-party/github.com/letsencrypt/boulder/metrics/measured_http/http.go | package measured_http
import (
"net/http"
"strconv"
"github.com/jmhodges/clock"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
// responseWriterWithStatus satisfies http.ResponseWriter, but keeps track of the
// status code for gathering stats.
type responseWriterWithStatus struct {
http.ResponseWriter
code int
}
// WriteHeader stores a status code for generating stats.
func (r *responseWriterWithStatus) WriteHeader(code int) {
r.code = code
r.ResponseWriter.WriteHeader(code)
}
// Write writes the body and sets the status code to 200 if a status code
// has not already been set.
func (r *responseWriterWithStatus) Write(body []byte) (int, error) {
if r.code == 0 {
r.code = http.StatusOK
}
return r.ResponseWriter.Write(body)
}
// serveMux is a partial interface wrapper for the method http.ServeMux
// exposes that we use. This is needed so that we can replace the default
// http.ServeMux in ocsp-responder where we don't want to use its path
// canonicalization.
type serveMux interface {
Handler(*http.Request) (http.Handler, string)
}
// MeasuredHandler wraps an http.Handler and records prometheus stats
type MeasuredHandler struct {
serveMux
clk clock.Clock
// Normally this is always responseTime, but we override it for testing.
stat *prometheus.HistogramVec
// inFlightRequestsGauge is a gauge that tracks the number of requests
// currently in flight, labeled by endpoint.
inFlightRequestsGauge *prometheus.GaugeVec
}
func New(m serveMux, clk clock.Clock, stats prometheus.Registerer, opts ...otelhttp.Option) http.Handler {
responseTime := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "response_time",
Help: "Time taken to respond to a request",
},
[]string{"endpoint", "method", "code"})
stats.MustRegister(responseTime)
inFlightRequestsGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "in_flight_requests",
Help: "Tracks the number of WFE requests currently in flight, labeled by endpoint.",
},
[]string{"endpoint"},
)
stats.MustRegister(inFlightRequestsGauge)
return otelhttp.NewHandler(&MeasuredHandler{
serveMux: m,
clk: clk,
stat: responseTime,
inFlightRequestsGauge: inFlightRequestsGauge,
}, "server", opts...)
}
func (h *MeasuredHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
begin := h.clk.Now()
rwws := &responseWriterWithStatus{w, 0}
subHandler, pattern := h.Handler(r)
h.inFlightRequestsGauge.WithLabelValues(pattern).Inc()
defer h.inFlightRequestsGauge.WithLabelValues(pattern).Dec()
// Use the method string only if it's a recognized HTTP method. This avoids
// ballooning timeseries with invalid methods from public input.
var method string
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut,
http.MethodPatch, http.MethodDelete, http.MethodConnect,
http.MethodOptions, http.MethodTrace:
method = r.Method
default:
method = "unknown"
}
defer func() {
h.stat.With(prometheus.Labels{
"endpoint": pattern,
"method": method,
"code": strconv.Itoa(rwws.code),
}).Observe(h.clk.Since(begin).Seconds())
}()
subHandler.ServeHTTP(rwws, r)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/csr/csr.go | third-party/github.com/letsencrypt/boulder/csr/csr.go | package csr
import (
"context"
"crypto"
"crypto/x509"
"errors"
"net/netip"
"strings"
"github.com/letsencrypt/boulder/core"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/goodkey"
"github.com/letsencrypt/boulder/identifier"
)
// maxCNLength is the maximum length allowed for the common name as specified in RFC 5280
const maxCNLength = 64
// This map is used to decide which CSR signing algorithms we consider
// strong enough to use. Significantly the missing algorithms are:
// * No algorithms using MD2, MD5, or SHA-1
// * No DSA algorithms
var goodSignatureAlgorithms = map[x509.SignatureAlgorithm]bool{
x509.SHA256WithRSA: true,
x509.SHA384WithRSA: true,
x509.SHA512WithRSA: true,
x509.ECDSAWithSHA256: true,
x509.ECDSAWithSHA384: true,
x509.ECDSAWithSHA512: true,
}
var (
invalidPubKey = berrors.BadCSRError("invalid public key in CSR")
unsupportedSigAlg = berrors.BadCSRError("signature algorithm not supported")
invalidSig = berrors.BadCSRError("invalid signature on CSR")
invalidEmailPresent = berrors.BadCSRError("CSR contains one or more email address fields")
invalidURIPresent = berrors.BadCSRError("CSR contains one or more URI fields")
invalidNoIdent = berrors.BadCSRError("at least one identifier is required")
)
// VerifyCSR checks the validity of a x509.CertificateRequest. It uses
// identifier.FromCSR to normalize the DNS names before checking whether we'll
// issue for them.
func VerifyCSR(ctx context.Context, csr *x509.CertificateRequest, maxNames int, keyPolicy *goodkey.KeyPolicy, pa core.PolicyAuthority) error {
key, ok := csr.PublicKey.(crypto.PublicKey)
if !ok {
return invalidPubKey
}
err := keyPolicy.GoodKey(ctx, key)
if err != nil {
if errors.Is(err, goodkey.ErrBadKey) {
return berrors.BadCSRError("invalid public key in CSR: %s", err)
}
return berrors.InternalServerError("error checking key validity: %s", err)
}
if !goodSignatureAlgorithms[csr.SignatureAlgorithm] {
return unsupportedSigAlg
}
err = csr.CheckSignature()
if err != nil {
return invalidSig
}
if len(csr.EmailAddresses) > 0 {
return invalidEmailPresent
}
if len(csr.URIs) > 0 {
return invalidURIPresent
}
// FromCSR also performs normalization, returning values that may not match
// the literal CSR contents.
idents := identifier.FromCSR(csr)
if len(idents) == 0 {
return invalidNoIdent
}
if len(idents) > maxNames {
return berrors.BadCSRError("CSR contains more than %d identifiers", maxNames)
}
err = pa.WillingToIssue(idents)
if err != nil {
return err
}
return nil
}
// CNFromCSR returns the lower-cased Subject Common Name from the CSR, if a
// short enough CN was provided. If it was too long or appears to be an IP,
// there will be no CN. If none was provided, the CN will be the first SAN that
// is short enough, which is done only for backwards compatibility with prior
// Let's Encrypt behaviour.
func CNFromCSR(csr *x509.CertificateRequest) string {
if len(csr.Subject.CommonName) > maxCNLength {
return ""
}
if csr.Subject.CommonName != "" {
_, err := netip.ParseAddr(csr.Subject.CommonName)
if err == nil { // inverted; we're looking for successful parsing here
return ""
}
return strings.ToLower(csr.Subject.CommonName)
}
// If there's no CN already, but we want to set one, promote the first dnsName
// SAN which is shorter than the maximum acceptable CN length (if any). We
// will never promote an ipAddress SAN to the CN.
for _, name := range csr.DNSNames {
if len(name) <= maxCNLength {
return strings.ToLower(name)
}
}
return ""
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/csr/csr_test.go | third-party/github.com/letsencrypt/boulder/csr/csr_test.go | package csr
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"errors"
"net"
"net/netip"
"net/url"
"strings"
"testing"
"github.com/letsencrypt/boulder/core"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/features"
"github.com/letsencrypt/boulder/goodkey"
"github.com/letsencrypt/boulder/identifier"
"github.com/letsencrypt/boulder/test"
)
type mockPA struct{}
func (pa *mockPA) ChallengeTypesFor(ident identifier.ACMEIdentifier) ([]core.AcmeChallenge, error) {
return []core.AcmeChallenge{}, nil
}
func (pa *mockPA) WillingToIssue(idents identifier.ACMEIdentifiers) error {
for _, ident := range idents {
if ident.Value == "bad-name.com" || ident.Value == "other-bad-name.com" {
return errors.New("policy forbids issuing for identifier")
}
}
return nil
}
func (pa *mockPA) ChallengeTypeEnabled(t core.AcmeChallenge) bool {
return true
}
func (pa *mockPA) CheckAuthzChallenges(a *core.Authorization) error {
return nil
}
func TestVerifyCSR(t *testing.T) {
private, err := rsa.GenerateKey(rand.Reader, 2048)
test.AssertNotError(t, err, "error generating test key")
signedReqBytes, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{PublicKey: private.PublicKey, SignatureAlgorithm: x509.SHA256WithRSA}, private)
test.AssertNotError(t, err, "error generating test CSR")
signedReq, err := x509.ParseCertificateRequest(signedReqBytes)
test.AssertNotError(t, err, "error parsing test CSR")
brokenSignedReq := new(x509.CertificateRequest)
*brokenSignedReq = *signedReq
brokenSignedReq.Signature = []byte{1, 1, 1, 1}
signedReqWithHosts := new(x509.CertificateRequest)
*signedReqWithHosts = *signedReq
signedReqWithHosts.DNSNames = []string{"a.com", "b.com"}
signedReqWithLongCN := new(x509.CertificateRequest)
*signedReqWithLongCN = *signedReq
signedReqWithLongCN.Subject.CommonName = strings.Repeat("a", maxCNLength+1)
signedReqWithBadNames := new(x509.CertificateRequest)
*signedReqWithBadNames = *signedReq
signedReqWithBadNames.DNSNames = []string{"bad-name.com", "other-bad-name.com"}
signedReqWithEmailAddress := new(x509.CertificateRequest)
*signedReqWithEmailAddress = *signedReq
signedReqWithEmailAddress.EmailAddresses = []string{"foo@bar.com"}
signedReqWithIPAddress := new(x509.CertificateRequest)
*signedReqWithIPAddress = *signedReq
signedReqWithIPAddress.IPAddresses = []net.IP{net.IPv4(1, 2, 3, 4)}
signedReqWithURI := new(x509.CertificateRequest)
*signedReqWithURI = *signedReq
testURI, _ := url.ParseRequestURI("https://example.com/")
signedReqWithURI.URIs = []*url.URL{testURI}
signedReqWithAllLongSANs := new(x509.CertificateRequest)
*signedReqWithAllLongSANs = *signedReq
signedReqWithAllLongSANs.DNSNames = []string{"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com"}
keyPolicy, err := goodkey.NewPolicy(nil, nil)
test.AssertNotError(t, err, "creating test keypolicy")
cases := []struct {
csr *x509.CertificateRequest
maxNames int
pa core.PolicyAuthority
expectedError error
}{
{
&x509.CertificateRequest{},
100,
&mockPA{},
invalidPubKey,
},
{
&x509.CertificateRequest{PublicKey: &private.PublicKey},
100,
&mockPA{},
unsupportedSigAlg,
},
{
brokenSignedReq,
100,
&mockPA{},
invalidSig,
},
{
signedReq,
100,
&mockPA{},
invalidNoIdent,
},
{
signedReqWithLongCN,
100,
&mockPA{},
nil,
},
{
signedReqWithHosts,
1,
&mockPA{},
berrors.BadCSRError("CSR contains more than 1 identifiers"),
},
{
signedReqWithBadNames,
100,
&mockPA{},
errors.New("policy forbids issuing for identifier"),
},
{
signedReqWithEmailAddress,
100,
&mockPA{},
invalidEmailPresent,
},
{
signedReqWithIPAddress,
100,
&mockPA{},
nil,
},
{
signedReqWithURI,
100,
&mockPA{},
invalidURIPresent,
},
{
signedReqWithAllLongSANs,
100,
&mockPA{},
nil,
},
}
for _, c := range cases {
err := VerifyCSR(context.Background(), c.csr, c.maxNames, &keyPolicy, c.pa)
test.AssertDeepEquals(t, c.expectedError, err)
}
}
func TestCNFromCSR(t *testing.T) {
tooLongString := strings.Repeat("a", maxCNLength+1)
cases := []struct {
name string
csr *x509.CertificateRequest
expectedCN string
}{
{
"no explicit CN",
&x509.CertificateRequest{DNSNames: []string{"a.com"}},
"a.com",
},
{
"explicit uppercase CN",
&x509.CertificateRequest{Subject: pkix.Name{CommonName: "A.com"}, DNSNames: []string{"a.com"}},
"a.com",
},
{
"no explicit CN, uppercase SAN",
&x509.CertificateRequest{DNSNames: []string{"A.com"}},
"a.com",
},
{
"duplicate SANs",
&x509.CertificateRequest{DNSNames: []string{"b.com", "b.com", "a.com", "a.com"}},
"b.com",
},
{
"explicit CN not found in SANs",
&x509.CertificateRequest{Subject: pkix.Name{CommonName: "a.com"}, DNSNames: []string{"b.com"}},
"a.com",
},
{
"no explicit CN, all SANs too long to be the CN",
&x509.CertificateRequest{DNSNames: []string{
tooLongString + ".a.com",
tooLongString + ".b.com",
}},
"",
},
{
"no explicit CN, leading SANs too long to be the CN",
&x509.CertificateRequest{DNSNames: []string{
tooLongString + ".a.com",
tooLongString + ".b.com",
"a.com",
"b.com",
}},
"a.com",
},
{
"explicit CN, leading SANs too long to be the CN",
&x509.CertificateRequest{
Subject: pkix.Name{CommonName: "A.com"},
DNSNames: []string{
tooLongString + ".a.com",
tooLongString + ".b.com",
"a.com",
"b.com",
}},
"a.com",
},
{
"explicit CN that's too long to be the CN",
&x509.CertificateRequest{
Subject: pkix.Name{CommonName: tooLongString + ".a.com"},
},
"",
},
{
"explicit CN that's too long to be the CN, with a SAN",
&x509.CertificateRequest{
Subject: pkix.Name{CommonName: tooLongString + ".a.com"},
DNSNames: []string{
"b.com",
}},
"",
},
{
"explicit CN that's an IP",
&x509.CertificateRequest{
Subject: pkix.Name{CommonName: "127.0.0.1"},
},
"",
},
{
"no CN, only IP SANs",
&x509.CertificateRequest{
IPAddresses: []net.IP{
netip.MustParseAddr("127.0.0.1").AsSlice(),
},
},
"",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
test.AssertEquals(t, CNFromCSR(tc.csr), tc.expectedCN)
})
}
}
func TestSHA1Deprecation(t *testing.T) {
features.Reset()
keyPolicy, err := goodkey.NewPolicy(nil, nil)
test.AssertNotError(t, err, "creating test keypolicy")
private, err := rsa.GenerateKey(rand.Reader, 2048)
test.AssertNotError(t, err, "error generating test key")
makeAndVerifyCsr := func(alg x509.SignatureAlgorithm) error {
csrBytes, err := x509.CreateCertificateRequest(rand.Reader,
&x509.CertificateRequest{
DNSNames: []string{"example.com"},
SignatureAlgorithm: alg,
PublicKey: &private.PublicKey,
}, private)
test.AssertNotError(t, err, "creating test CSR")
csr, err := x509.ParseCertificateRequest(csrBytes)
test.AssertNotError(t, err, "parsing test CSR")
return VerifyCSR(context.Background(), csr, 100, &keyPolicy, &mockPA{})
}
err = makeAndVerifyCsr(x509.SHA256WithRSA)
test.AssertNotError(t, err, "SHA256 CSR should verify")
err = makeAndVerifyCsr(x509.SHA1WithRSA)
test.AssertError(t, err, "SHA1 CSR should not verify")
}
func TestDuplicateExtensionRejection(t *testing.T) {
private, err := rsa.GenerateKey(rand.Reader, 2048)
test.AssertNotError(t, err, "error generating test key")
csrBytes, err := x509.CreateCertificateRequest(rand.Reader,
&x509.CertificateRequest{
DNSNames: []string{"example.com"},
SignatureAlgorithm: x509.SHA256WithRSA,
PublicKey: &private.PublicKey,
ExtraExtensions: []pkix.Extension{
{Id: asn1.ObjectIdentifier{2, 5, 29, 1}, Value: []byte("hello")},
{Id: asn1.ObjectIdentifier{2, 5, 29, 1}, Value: []byte("world")},
},
}, private)
test.AssertNotError(t, err, "creating test CSR")
_, err = x509.ParseCertificateRequest(csrBytes)
test.AssertError(t, err, "CSR with duplicate extension OID should fail to parse")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/pkcs11helpers/helpers_test.go | third-party/github.com/letsencrypt/boulder/pkcs11helpers/helpers_test.go | package pkcs11helpers
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/asn1"
"errors"
"math/big"
"strings"
"testing"
"github.com/letsencrypt/boulder/test"
"github.com/miekg/pkcs11"
)
func TestGetECDSAPublicKey(t *testing.T) {
ctx := &MockCtx{}
s := &Session{ctx, 0}
// test attribute retrieval failing
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return nil, errors.New("yup")
}
_, err := s.GetECDSAPublicKey(0)
test.AssertError(t, err, "ecPub didn't fail on GetAttributeValue error")
// test we fail to construct key with missing params and point
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{}, nil
}
_, err = s.GetECDSAPublicKey(0)
test.AssertError(t, err, "ecPub didn't fail with empty attribute list")
// test we fail to construct key with unknown curve
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{1, 2, 3}),
}, nil
}
_, err = s.GetECDSAPublicKey(0)
test.AssertError(t, err, "ecPub didn't fail with unknown curve")
// test we fail to construct key with invalid EC point (invalid encoding)
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{6, 8, 42, 134, 72, 206, 61, 3, 1, 7}),
pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, []byte{255}),
}, nil
}
_, err = s.GetECDSAPublicKey(0)
test.AssertError(t, err, "ecPub didn't fail with invalid EC point (invalid encoding)")
// test we fail to construct key with invalid EC point (empty octet string)
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{6, 8, 42, 134, 72, 206, 61, 3, 1, 7}),
pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, []byte{4, 0}),
}, nil
}
_, err = s.GetECDSAPublicKey(0)
test.AssertError(t, err, "ecPub didn't fail with invalid EC point (empty octet string)")
// test we fail to construct key with invalid EC point (octet string, invalid contents)
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{6, 8, 42, 134, 72, 206, 61, 3, 1, 7}),
pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, []byte{4, 4, 4, 1, 2, 3}),
}, nil
}
_, err = s.GetECDSAPublicKey(0)
test.AssertError(t, err, "ecPub didn't fail with invalid EC point (octet string, invalid contents)")
// test we don't fail with the correct attributes (traditional encoding)
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{6, 5, 43, 129, 4, 0, 33}),
pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, []byte{4, 217, 225, 246, 210, 153, 134, 246, 104, 95, 79, 122, 206, 135, 241, 37, 114, 199, 87, 56, 167, 83, 56, 136, 174, 6, 145, 97, 239, 221, 49, 67, 148, 13, 126, 65, 90, 208, 195, 193, 171, 105, 40, 98, 132, 124, 30, 189, 215, 197, 178, 226, 166, 238, 240, 57, 215}),
}, nil
}
_, err = s.GetECDSAPublicKey(0)
test.AssertNotError(t, err, "ecPub failed with valid attributes (traditional encoding)")
// test we don't fail with the correct attributes (non-traditional encoding)
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{6, 5, 43, 129, 4, 0, 33}),
pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, []byte{4, 57, 4, 217, 225, 246, 210, 153, 134, 246, 104, 95, 79, 122, 206, 135, 241, 37, 114, 199, 87, 56, 167, 83, 56, 136, 174, 6, 145, 97, 239, 221, 49, 67, 148, 13, 126, 65, 90, 208, 195, 193, 171, 105, 40, 98, 132, 124, 30, 189, 215, 197, 178, 226, 166, 238, 240, 57, 215}),
}, nil
}
_, err = s.GetECDSAPublicKey(0)
test.AssertNotError(t, err, "ecPub failed with valid attributes (non-traditional encoding)")
}
func TestRSAPublicKey(t *testing.T) {
ctx := &MockCtx{}
s := &Session{ctx, 0}
// test attribute retrieval failing
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return nil, errors.New("yup")
}
_, err := s.GetRSAPublicKey(0)
test.AssertError(t, err, "rsaPub didn't fail on GetAttributeValue error")
// test we fail to construct key with missing modulus and exp
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{}, nil
}
_, err = s.GetRSAPublicKey(0)
test.AssertError(t, err, "rsaPub didn't fail with empty attribute list")
// test we don't fail with the correct attributes
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{1, 0, 1}),
pkcs11.NewAttribute(pkcs11.CKA_MODULUS, []byte{255}),
}, nil
}
_, err = s.GetRSAPublicKey(0)
test.AssertNotError(t, err, "rsaPub failed with valid attributes")
}
func findObjectsInitOK(pkcs11.SessionHandle, []*pkcs11.Attribute) error {
return nil
}
func findObjectsOK(pkcs11.SessionHandle, int) ([]pkcs11.ObjectHandle, bool, error) {
return []pkcs11.ObjectHandle{1}, false, nil
}
func findObjectsFinalOK(pkcs11.SessionHandle) error {
return nil
}
func newMock() *MockCtx {
return &MockCtx{
FindObjectsInitFunc: findObjectsInitOK,
FindObjectsFunc: findObjectsOK,
FindObjectsFinalFunc: findObjectsFinalOK,
}
}
func newSessionWithMock() (*Session, *MockCtx) {
ctx := newMock()
return &Session{ctx, 0}, ctx
}
func TestFindObjectFailsOnFailedInit(t *testing.T) {
ctx := MockCtx{}
ctx.FindObjectsFinalFunc = findObjectsFinalOK
ctx.FindObjectsFunc = func(pkcs11.SessionHandle, int) ([]pkcs11.ObjectHandle, bool, error) {
return []pkcs11.ObjectHandle{1}, false, nil
}
// test FindObject fails when FindObjectsInit fails
ctx.FindObjectsInitFunc = func(pkcs11.SessionHandle, []*pkcs11.Attribute) error {
return errors.New("broken")
}
s := &Session{ctx, 0}
_, err := s.FindObject(nil)
test.AssertError(t, err, "FindObject didn't fail when FindObjectsInit failed")
}
func TestFindObjectFailsOnFailedFindObjects(t *testing.T) {
ctx := MockCtx{}
ctx.FindObjectsInitFunc = findObjectsInitOK
ctx.FindObjectsFinalFunc = findObjectsFinalOK
// test FindObject fails when FindObjects fails
ctx.FindObjectsFunc = func(pkcs11.SessionHandle, int) ([]pkcs11.ObjectHandle, bool, error) {
return nil, false, errors.New("broken")
}
s := &Session{ctx, 0}
_, err := s.FindObject(nil)
test.AssertError(t, err, "FindObject didn't fail when FindObjects failed")
}
func TestFindObjectFailsOnNoHandles(t *testing.T) {
ctx := MockCtx{}
ctx.FindObjectsInitFunc = findObjectsInitOK
ctx.FindObjectsFinalFunc = findObjectsFinalOK
// test FindObject fails when no handles are returned
ctx.FindObjectsFunc = func(pkcs11.SessionHandle, int) ([]pkcs11.ObjectHandle, bool, error) {
return []pkcs11.ObjectHandle{}, false, nil
}
s := &Session{ctx, 0}
_, err := s.FindObject(nil)
test.AssertEquals(t, err, ErrNoObject)
}
func TestFindObjectFailsOnMultipleHandles(t *testing.T) {
ctx := MockCtx{}
ctx.FindObjectsInitFunc = findObjectsInitOK
ctx.FindObjectsFinalFunc = findObjectsFinalOK
// test FindObject fails when multiple handles are returned
ctx.FindObjectsFunc = func(pkcs11.SessionHandle, int) ([]pkcs11.ObjectHandle, bool, error) {
return []pkcs11.ObjectHandle{1, 2, 3}, false, nil
}
s := &Session{ctx, 0}
_, err := s.FindObject(nil)
test.AssertError(t, err, "FindObject didn't fail when FindObjects returns multiple handles")
test.Assert(t, strings.HasPrefix(err.Error(), "too many objects"), "FindObject failed with wrong error")
}
func TestFindObjectFailsOnFinalizeFailure(t *testing.T) {
ctx := MockCtx{}
ctx.FindObjectsInitFunc = findObjectsInitOK
// test FindObject fails when FindObjectsFinal fails
ctx.FindObjectsFunc = func(pkcs11.SessionHandle, int) ([]pkcs11.ObjectHandle, bool, error) {
return []pkcs11.ObjectHandle{1}, false, nil
}
ctx.FindObjectsFinalFunc = func(pkcs11.SessionHandle) error {
return errors.New("broken")
}
s := &Session{ctx, 0}
_, err := s.FindObject(nil)
test.AssertError(t, err, "FindObject didn't fail when FindObjectsFinal fails")
}
func TestFindObjectSucceeds(t *testing.T) {
ctx := MockCtx{}
ctx.FindObjectsInitFunc = findObjectsInitOK
ctx.FindObjectsFinalFunc = findObjectsFinalOK
ctx.FindObjectsFunc = func(pkcs11.SessionHandle, int) ([]pkcs11.ObjectHandle, bool, error) {
return []pkcs11.ObjectHandle{1}, false, nil
}
s := &Session{ctx, 0}
// test FindObject works
handle, err := s.FindObject(nil)
test.AssertNotError(t, err, "FindObject failed when everything worked as expected")
test.AssertEquals(t, handle, pkcs11.ObjectHandle(1))
}
func TestX509Signer(t *testing.T) {
ctx := MockCtx{}
// test that x509Signer.Sign properly converts the PKCS#11 format signature to
// the RFC 5480 format signature
ctx.SignInitFunc = func(pkcs11.SessionHandle, []*pkcs11.Mechanism, pkcs11.ObjectHandle) error {
return nil
}
tk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "Failed to generate test key")
ctx.SignFunc = func(_ pkcs11.SessionHandle, digest []byte) ([]byte, error) {
r, s, err := ecdsa.Sign(rand.Reader, tk, digest[:])
if err != nil {
return nil, err
}
rBytes := r.Bytes()
sBytes := s.Bytes()
// http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/os/pkcs11-curr-v2.40-os.html
// Section 2.3.1: EC Signatures
// "If r and s have different octet length, the shorter of both must be padded with
// leading zero octets such that both have the same octet length."
switch {
case len(rBytes) < len(sBytes):
padding := make([]byte, len(sBytes)-len(rBytes))
rBytes = append(padding, rBytes...)
case len(rBytes) > len(sBytes):
padding := make([]byte, len(rBytes)-len(sBytes))
sBytes = append(padding, sBytes...)
}
return append(rBytes, sBytes...), nil
}
digest := sha256.Sum256([]byte("hello"))
s := &Session{ctx, 0}
signer := &x509Signer{session: s, keyType: ECDSAKey, pub: tk.Public()}
signature, err := signer.Sign(nil, digest[:], crypto.SHA256)
test.AssertNotError(t, err, "x509Signer.Sign failed")
var rfcFormat struct {
R, S *big.Int
}
rest, err := asn1.Unmarshal(signature, &rfcFormat)
test.AssertNotError(t, err, "asn1.Unmarshal failed trying to parse signature")
test.Assert(t, len(rest) == 0, "Signature had trailing garbage")
verified := ecdsa.Verify(&tk.PublicKey, digest[:], rfcFormat.R, rfcFormat.S)
test.Assert(t, verified, "Failed to verify RFC format signature")
// For the sake of coverage
test.AssertEquals(t, signer.Public(), tk.Public())
}
func TestGetKeyWhenLabelIsWrong(t *testing.T) {
s, ctx := newSessionWithMock()
pubKey := &rsa.PublicKey{N: big.NewInt(1), E: 1}
rightLabel := "label"
var objectsToReturn []pkcs11.ObjectHandle
ctx.FindObjectsInitFunc = func(_ pkcs11.SessionHandle, attr []*pkcs11.Attribute) error {
objectsToReturn = []pkcs11.ObjectHandle{1}
for _, a := range attr {
if a.Type == pkcs11.CKA_LABEL && !bytes.Equal(a.Value, []byte(rightLabel)) {
objectsToReturn = nil
}
}
return nil
}
ctx.FindObjectsFunc = func(_ pkcs11.SessionHandle, _ int) ([]pkcs11.ObjectHandle, bool, error) {
return objectsToReturn, false, nil
}
ctx.FindObjectsFinalFunc = func(_ pkcs11.SessionHandle) error {
return nil
}
_, err := s.NewSigner("wrong-label", pubKey)
test.AssertError(t, err, "newSigner didn't fail when label was a mismatch for public key")
expected := "no objects found matching provided template"
if !strings.Contains(err.Error(), expected) {
t.Errorf("expected error to contain %q but it was %q", expected, err)
}
}
func TestGetKeyWhenGetAttributeValueFails(t *testing.T) {
s, ctx := newSessionWithMock()
pubKey := &rsa.PublicKey{N: big.NewInt(1), E: 1}
// test newSigner fails when GetAttributeValue fails
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return nil, errors.New("broken")
}
_, err := s.NewSigner("label", pubKey)
test.AssertError(t, err, "newSigner didn't fail when GetAttributeValue for private key type failed")
}
func TestGetKeyWhenGetAttributeValueReturnsNone(t *testing.T) {
s, ctx := newSessionWithMock()
pubKey := &rsa.PublicKey{N: big.NewInt(1), E: 1}
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return nil, errors.New("broken")
}
// test newSigner fails when GetAttributeValue returns no attributes
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return nil, nil
}
_, err := s.NewSigner("label", pubKey)
test.AssertError(t, err, "newSigner didn't fail when GetAttributeValue for private key type returned no attributes")
}
func TestGetKeyWhenFindObjectForPublicKeyFails(t *testing.T) {
s, ctx := newSessionWithMock()
pubKey := &rsa.PublicKey{N: big.NewInt(1), E: 1}
// test newSigner fails when FindObject for public key
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_EC)}, nil
}
ctx.FindObjectsInitFunc = func(_ pkcs11.SessionHandle, tmpl []*pkcs11.Attribute) error {
if bytes.Equal(tmpl[0].Value, []byte{2, 0, 0, 0, 0, 0, 0, 0}) {
return errors.New("broken")
}
return nil
}
_, err := s.NewSigner("label", pubKey)
test.AssertError(t, err, "newSigner didn't fail when FindObject for public key handle failed")
}
func TestGetKeyWhenFindObjectForPrivateKeyReturnsUnknownType(t *testing.T) {
s, ctx := newSessionWithMock()
pubKey := &rsa.PublicKey{N: big.NewInt(1), E: 1}
// test newSigner fails when FindObject for private key returns unknown CKA_KEY_TYPE
ctx.FindObjectsInitFunc = func(_ pkcs11.SessionHandle, tmpl []*pkcs11.Attribute) error {
return nil
}
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, []byte{2, 0, 0, 0, 0, 0, 0, 0})}, nil
}
_, err := s.NewSigner("label", pubKey)
test.AssertError(t, err, "newSigner didn't fail when GetAttributeValue for private key returned unknown key type")
}
func TestGetKeyWhenFindObjectForPrivateKeyFails(t *testing.T) {
s, ctx := newSessionWithMock()
pubKey := &rsa.PublicKey{N: big.NewInt(1), E: 1}
// test newSigner fails when FindObject for private key fails
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, []byte{0, 0, 0, 0, 0, 0, 0, 0})}, nil
}
_, err := s.NewSigner("label", pubKey)
test.AssertError(t, err, "newSigner didn't fail when GetRSAPublicKey fails")
// test newSigner fails when GetECDSAPublicKey fails
ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return []*pkcs11.Attribute{pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, []byte{3, 0, 0, 0, 0, 0, 0, 0})}, nil
}
_, err = s.NewSigner("label", pubKey)
test.AssertError(t, err, "newSigner didn't fail when GetECDSAPublicKey fails")
}
func TestGetKeySucceeds(t *testing.T) {
s, ctx := newSessionWithMock()
pubKey := &rsa.PublicKey{N: big.NewInt(1), E: 1}
// test newSigner works when everything... works
ctx.GetAttributeValueFunc = func(_ pkcs11.SessionHandle, _ pkcs11.ObjectHandle, attrs []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
var returns []*pkcs11.Attribute
for _, attr := range attrs {
switch attr.Type {
case pkcs11.CKA_ID:
returns = append(returns, pkcs11.NewAttribute(pkcs11.CKA_ID, []byte{99}))
default:
return nil, errors.New("GetAttributeValue got unexpected attribute type")
}
}
return returns, nil
}
_, err := s.NewSigner("label", pubKey)
test.AssertNotError(t, err, "newSigner failed when everything worked properly")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/pkcs11helpers/helpers.go | third-party/github.com/letsencrypt/boulder/pkcs11helpers/helpers.go | package pkcs11helpers
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"encoding/asn1"
"errors"
"fmt"
"io"
"math/big"
"github.com/miekg/pkcs11"
)
type PKCtx interface {
GenerateKeyPair(pkcs11.SessionHandle, []*pkcs11.Mechanism, []*pkcs11.Attribute, []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error)
GetAttributeValue(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error)
SignInit(pkcs11.SessionHandle, []*pkcs11.Mechanism, pkcs11.ObjectHandle) error
Sign(pkcs11.SessionHandle, []byte) ([]byte, error)
GenerateRandom(pkcs11.SessionHandle, int) ([]byte, error)
FindObjectsInit(sh pkcs11.SessionHandle, temp []*pkcs11.Attribute) error
FindObjects(sh pkcs11.SessionHandle, max int) ([]pkcs11.ObjectHandle, bool, error)
FindObjectsFinal(sh pkcs11.SessionHandle) error
}
// Session represents a session with a given PKCS#11 module. It is not safe for
// concurrent access.
type Session struct {
Module PKCtx
Session pkcs11.SessionHandle
}
func Initialize(module string, slot uint, pin string) (*Session, error) {
ctx := pkcs11.New(module)
if ctx == nil {
return nil, errors.New("failed to load module")
}
err := ctx.Initialize()
if err != nil {
return nil, fmt.Errorf("couldn't initialize context: %s", err)
}
session, err := ctx.OpenSession(slot, pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION)
if err != nil {
return nil, fmt.Errorf("couldn't open session: %s", err)
}
err = ctx.Login(session, pkcs11.CKU_USER, pin)
if err != nil {
return nil, fmt.Errorf("couldn't login: %s", err)
}
return &Session{ctx, session}, nil
}
// https://tools.ietf.org/html/rfc5759#section-3.2
var curveOIDs = map[string]asn1.ObjectIdentifier{
"P-256": {1, 2, 840, 10045, 3, 1, 7},
"P-384": {1, 3, 132, 0, 34},
}
// getPublicKeyID looks up the given public key in the PKCS#11 token, and
// returns its ID as a []byte, for use in looking up the corresponding private
// key.
func (s *Session) getPublicKeyID(label string, publicKey crypto.PublicKey) ([]byte, error) {
var template []*pkcs11.Attribute
switch key := publicKey.(type) {
case *rsa.PublicKey:
template = []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),
pkcs11.NewAttribute(pkcs11.CKA_LABEL, []byte(label)),
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),
pkcs11.NewAttribute(pkcs11.CKA_MODULUS, key.N.Bytes()),
pkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, big.NewInt(int64(key.E)).Bytes()),
}
case *ecdsa.PublicKey:
// http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/os/pkcs11-curr-v2.40-os.html#_ftn1
// PKCS#11 v2.20 specified that the CKA_EC_POINT was to be store in a DER-encoded
// OCTET STRING.
rawValue := asn1.RawValue{
Tag: asn1.TagOctetString,
Bytes: elliptic.Marshal(key.Curve, key.X, key.Y),
}
marshalledPoint, err := asn1.Marshal(rawValue)
if err != nil {
return nil, err
}
curveOID, err := asn1.Marshal(curveOIDs[key.Curve.Params().Name])
if err != nil {
return nil, err
}
template = []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),
pkcs11.NewAttribute(pkcs11.CKA_LABEL, []byte(label)),
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_EC),
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, curveOID),
pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, marshalledPoint),
}
default:
return nil, fmt.Errorf("unsupported public key of type %T", publicKey)
}
publicKeyHandle, err := s.FindObject(template)
if err != nil {
return nil, err
}
attrs, err := s.Module.GetAttributeValue(s.Session, publicKeyHandle, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_ID, nil),
})
if err != nil {
return nil, err
}
if len(attrs) == 1 && attrs[0].Type == pkcs11.CKA_ID {
return attrs[0].Value, nil
}
return nil, fmt.Errorf("invalid result from GetAttributeValue")
}
// getPrivateKey gets a handle to the private key whose CKA_ID matches the
// provided publicKeyID.
func (s *Session) getPrivateKey(publicKeyID []byte) (pkcs11.ObjectHandle, error) {
return s.FindObject([]*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),
pkcs11.NewAttribute(pkcs11.CKA_ID, publicKeyID),
})
}
func (s *Session) GetAttributeValue(object pkcs11.ObjectHandle, attributes []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return s.Module.GetAttributeValue(s.Session, object, attributes)
}
func (s *Session) GenerateKeyPair(m []*pkcs11.Mechanism, pubAttrs []*pkcs11.Attribute, privAttrs []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {
return s.Module.GenerateKeyPair(s.Session, m, pubAttrs, privAttrs)
}
func (s *Session) GetRSAPublicKey(object pkcs11.ObjectHandle) (*rsa.PublicKey, error) {
// Retrieve the public exponent and modulus for the public key
attrs, err := s.Module.GetAttributeValue(s.Session, object, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, nil),
pkcs11.NewAttribute(pkcs11.CKA_MODULUS, nil),
})
if err != nil {
return nil, fmt.Errorf("Failed to retrieve key attributes: %s", err)
}
// Attempt to build the public key from the retrieved attributes
pubKey := &rsa.PublicKey{}
gotMod, gotExp := false, false
for _, a := range attrs {
switch a.Type {
case pkcs11.CKA_PUBLIC_EXPONENT:
pubKey.E = int(big.NewInt(0).SetBytes(a.Value).Int64())
gotExp = true
case pkcs11.CKA_MODULUS:
pubKey.N = big.NewInt(0).SetBytes(a.Value)
gotMod = true
}
}
// Fail if we are missing either the public exponent or modulus
if !gotExp || !gotMod {
return nil, errors.New("Couldn't retrieve modulus and exponent")
}
return pubKey, nil
}
// oidDERToCurve maps the hex of the DER encoding of the various curve OIDs to
// the relevant curve parameters
var oidDERToCurve = map[string]elliptic.Curve{
"06052B81040021": elliptic.P224(),
"06082A8648CE3D030107": elliptic.P256(),
"06052B81040022": elliptic.P384(),
"06052B81040023": elliptic.P521(),
}
func (s *Session) GetECDSAPublicKey(object pkcs11.ObjectHandle) (*ecdsa.PublicKey, error) {
// Retrieve the curve and public point for the generated public key
attrs, err := s.Module.GetAttributeValue(s.Session, object, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, nil),
pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, nil),
})
if err != nil {
return nil, fmt.Errorf("Failed to retrieve key attributes: %s", err)
}
pubKey := &ecdsa.PublicKey{}
var pointBytes []byte
for _, a := range attrs {
switch a.Type {
case pkcs11.CKA_EC_PARAMS:
rCurve, present := oidDERToCurve[fmt.Sprintf("%X", a.Value)]
if !present {
return nil, errors.New("Unknown curve OID value returned")
}
pubKey.Curve = rCurve
case pkcs11.CKA_EC_POINT:
pointBytes = a.Value
}
}
if pointBytes == nil || pubKey.Curve == nil {
return nil, errors.New("Couldn't retrieve EC point and EC parameters")
}
x, y := elliptic.Unmarshal(pubKey.Curve, pointBytes)
if x == nil {
// http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/os/pkcs11-curr-v2.40-os.html#_ftn1
// PKCS#11 v2.20 specified that the CKA_EC_POINT was to be stored in a DER-encoded
// OCTET STRING.
var point asn1.RawValue
_, err = asn1.Unmarshal(pointBytes, &point)
if err != nil {
return nil, fmt.Errorf("Failed to unmarshal returned CKA_EC_POINT: %s", err)
}
if len(point.Bytes) == 0 {
return nil, errors.New("Invalid CKA_EC_POINT value returned, OCTET string is empty")
}
x, y = elliptic.Unmarshal(pubKey.Curve, point.Bytes)
if x == nil {
return nil, errors.New("Invalid CKA_EC_POINT value returned, point is malformed")
}
}
pubKey.X, pubKey.Y = x, y
return pubKey, nil
}
type keyType int
const (
RSAKey keyType = iota
ECDSAKey
)
// Hash identifiers required for PKCS#11 RSA signing. Only support SHA-256, SHA-384,
// and SHA-512
var hashIdents = map[crypto.Hash][]byte{
crypto.SHA256: {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
crypto.SHA384: {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
crypto.SHA512: {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
}
func (s *Session) Sign(object pkcs11.ObjectHandle, keyType keyType, digest []byte, hash crypto.Hash) ([]byte, error) {
if len(digest) != hash.Size() {
return nil, errors.New("digest length doesn't match hash length")
}
mech := make([]*pkcs11.Mechanism, 1)
switch keyType {
case RSAKey:
mech[0] = pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS, nil)
prefix, ok := hashIdents[hash]
if !ok {
return nil, errors.New("unsupported hash function")
}
digest = append(prefix, digest...)
case ECDSAKey:
mech[0] = pkcs11.NewMechanism(pkcs11.CKM_ECDSA, nil)
}
err := s.Module.SignInit(s.Session, mech, object)
if err != nil {
return nil, fmt.Errorf("failed to initialize signing operation: %s", err)
}
signature, err := s.Module.Sign(s.Session, digest)
if err != nil {
return nil, fmt.Errorf("failed to sign data: %s", err)
}
return signature, nil
}
var ErrNoObject = errors.New("no objects found matching provided template")
// FindObject looks up a PKCS#11 object handle based on the provided template.
// In the case where zero or more than one objects are found to match the
// template an error is returned.
func (s *Session) FindObject(tmpl []*pkcs11.Attribute) (pkcs11.ObjectHandle, error) {
err := s.Module.FindObjectsInit(s.Session, tmpl)
if err != nil {
return 0, err
}
handles, _, err := s.Module.FindObjects(s.Session, 2)
if err != nil {
return 0, err
}
err = s.Module.FindObjectsFinal(s.Session)
if err != nil {
return 0, err
}
if len(handles) == 0 {
return 0, ErrNoObject
}
if len(handles) > 1 {
return 0, fmt.Errorf("too many objects (%d) that match the provided template", len(handles))
}
return handles[0], nil
}
// x509Signer is a convenience wrapper used for converting between the
// PKCS#11 ECDSA signature format and the RFC 5480 one which is required
// for X.509 certificates
type x509Signer struct {
session *Session
objectHandle pkcs11.ObjectHandle
keyType keyType
pub crypto.PublicKey
}
// Sign signs a digest. If the signing key is ECDSA then the signature
// is converted from the PKCS#11 format to the RFC 5480 format. For RSA keys a
// conversion step is not needed.
func (p *x509Signer) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
signature, err := p.session.Sign(p.objectHandle, p.keyType, digest, opts.HashFunc())
if err != nil {
return nil, err
}
if p.keyType == ECDSAKey {
// Convert from the PKCS#11 format to the RFC 5480 format so that
// it can be used in a X.509 certificate
r := big.NewInt(0).SetBytes(signature[:len(signature)/2])
s := big.NewInt(0).SetBytes(signature[len(signature)/2:])
signature, err = asn1.Marshal(struct {
R, S *big.Int
}{R: r, S: s})
if err != nil {
return nil, fmt.Errorf("failed to convert signature to RFC 5480 format: %s", err)
}
}
return signature, nil
}
func (p *x509Signer) Public() crypto.PublicKey {
return p.pub
}
// NewSigner constructs an x509Signer for the private key object associated with the
// given label and public key.
func (s *Session) NewSigner(label string, publicKey crypto.PublicKey) (crypto.Signer, error) {
var kt keyType
switch publicKey.(type) {
case *rsa.PublicKey:
kt = RSAKey
case *ecdsa.PublicKey:
kt = ECDSAKey
default:
return nil, fmt.Errorf("unsupported public key of type %T", publicKey)
}
publicKeyID, err := s.getPublicKeyID(label, publicKey)
if err != nil {
return nil, fmt.Errorf("looking up public key: %s", err)
}
// Fetch the private key by matching its id to the public key handle.
privateKeyHandle, err := s.getPrivateKey(publicKeyID)
if err != nil {
return nil, fmt.Errorf("getting private key: %s", err)
}
return &x509Signer{
session: s,
objectHandle: privateKeyHandle,
keyType: kt,
pub: publicKey,
}, nil
}
func NewMock() *MockCtx {
return &MockCtx{}
}
func NewSessionWithMock() (*Session, *MockCtx) {
ctx := NewMock()
return &Session{ctx, 0}, ctx
}
type MockCtx struct {
GenerateKeyPairFunc func(pkcs11.SessionHandle, []*pkcs11.Mechanism, []*pkcs11.Attribute, []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error)
GetAttributeValueFunc func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error)
SignInitFunc func(pkcs11.SessionHandle, []*pkcs11.Mechanism, pkcs11.ObjectHandle) error
SignFunc func(pkcs11.SessionHandle, []byte) ([]byte, error)
GenerateRandomFunc func(pkcs11.SessionHandle, int) ([]byte, error)
FindObjectsInitFunc func(sh pkcs11.SessionHandle, temp []*pkcs11.Attribute) error
FindObjectsFunc func(sh pkcs11.SessionHandle, max int) ([]pkcs11.ObjectHandle, bool, error)
FindObjectsFinalFunc func(sh pkcs11.SessionHandle) error
}
func (mc MockCtx) GenerateKeyPair(s pkcs11.SessionHandle, m []*pkcs11.Mechanism, a1 []*pkcs11.Attribute, a2 []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {
return mc.GenerateKeyPairFunc(s, m, a1, a2)
}
func (mc MockCtx) GetAttributeValue(s pkcs11.SessionHandle, o pkcs11.ObjectHandle, a []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
return mc.GetAttributeValueFunc(s, o, a)
}
func (mc MockCtx) SignInit(s pkcs11.SessionHandle, m []*pkcs11.Mechanism, o pkcs11.ObjectHandle) error {
return mc.SignInitFunc(s, m, o)
}
func (mc MockCtx) Sign(s pkcs11.SessionHandle, m []byte) ([]byte, error) {
return mc.SignFunc(s, m)
}
func (mc MockCtx) GenerateRandom(s pkcs11.SessionHandle, c int) ([]byte, error) {
return mc.GenerateRandomFunc(s, c)
}
func (mc MockCtx) FindObjectsInit(sh pkcs11.SessionHandle, temp []*pkcs11.Attribute) error {
return mc.FindObjectsInitFunc(sh, temp)
}
func (mc MockCtx) FindObjects(sh pkcs11.SessionHandle, max int) ([]pkcs11.ObjectHandle, bool, error) {
return mc.FindObjectsFunc(sh, max)
}
func (mc MockCtx) FindObjectsFinal(sh pkcs11.SessionHandle) error {
return mc.FindObjectsFinalFunc(sh)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/asserts.go | third-party/github.com/letsencrypt/boulder/test/asserts.go | package test
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus"
io_prometheus_client "github.com/prometheus/client_model/go"
)
// Assert a boolean
func Assert(t *testing.T, result bool, message string) {
t.Helper()
if !result {
t.Fatal(message)
}
}
// AssertNil checks that an object is nil. Being a "boxed nil" (a nil value
// wrapped in a non-nil interface type) is not good enough.
func AssertNil(t *testing.T, obj interface{}, message string) {
t.Helper()
if obj != nil {
t.Fatal(message)
}
}
// AssertNotNil checks an object to be non-nil. Being a "boxed nil" (a nil value
// wrapped in a non-nil interface type) is not good enough.
// Note that there is a gap between AssertNil and AssertNotNil. Both fail when
// called with a boxed nil. This is intentional: we want to avoid boxed nils.
func AssertNotNil(t *testing.T, obj interface{}, message string) {
t.Helper()
if obj == nil {
t.Fatal(message)
}
switch reflect.TypeOf(obj).Kind() {
// .IsNil() only works on chan, func, interface, map, pointer, and slice.
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
if reflect.ValueOf(obj).IsNil() {
t.Fatal(message)
}
}
}
// AssertBoxedNil checks that an inner object is nil. This is intentional for
// testing purposes only.
func AssertBoxedNil(t *testing.T, obj interface{}, message string) {
t.Helper()
typ := reflect.TypeOf(obj).Kind()
switch typ {
// .IsNil() only works on chan, func, interface, map, pointer, and slice.
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
if !reflect.ValueOf(obj).IsNil() {
t.Fatal(message)
}
default:
t.Fatalf("Cannot check type \"%s\". Needs to be of type chan, func, interface, map, pointer, or slice.", typ)
}
}
// AssertNotError checks that err is nil
func AssertNotError(t *testing.T, err error, message string) {
t.Helper()
if err != nil {
t.Fatalf("%s: %s", message, err)
}
}
// AssertError checks that err is non-nil
func AssertError(t *testing.T, err error, message string) {
t.Helper()
if err == nil {
t.Fatalf("%s: expected error but received none", message)
}
}
// AssertErrorWraps checks that err can be unwrapped into the given target.
// NOTE: Has the side effect of actually performing that unwrapping.
func AssertErrorWraps(t *testing.T, err error, target interface{}) {
t.Helper()
if !errors.As(err, target) {
t.Fatalf("error does not wrap an error of the expected type: %q !> %+T", err.Error(), target)
}
}
// AssertErrorIs checks that err wraps the given error
func AssertErrorIs(t *testing.T, err error, target error) {
t.Helper()
if err == nil {
t.Fatal("err was unexpectedly nil and should not have been")
}
if !errors.Is(err, target) {
t.Fatalf("error does not wrap expected error: %q !> %q", err.Error(), target.Error())
}
}
// AssertEquals uses the equality operator (==) to measure one and two
func AssertEquals(t *testing.T, one interface{}, two interface{}) {
t.Helper()
if reflect.TypeOf(one) != reflect.TypeOf(two) {
t.Fatalf("cannot test equality of different types: %T != %T", one, two)
}
if one != two {
t.Fatalf("%#v != %#v", one, two)
}
}
// AssertDeepEquals uses the reflect.DeepEqual method to measure one and two
func AssertDeepEquals(t *testing.T, one interface{}, two interface{}) {
t.Helper()
if !reflect.DeepEqual(one, two) {
t.Fatalf("[%#v] !(deep)= [%#v]", one, two)
}
}
// AssertMarshaledEquals marshals one and two to JSON, and then uses
// the equality operator to measure them
func AssertMarshaledEquals(t *testing.T, one interface{}, two interface{}) {
t.Helper()
oneJSON, err := json.Marshal(one)
AssertNotError(t, err, "Could not marshal 1st argument")
twoJSON, err := json.Marshal(two)
AssertNotError(t, err, "Could not marshal 2nd argument")
if !bytes.Equal(oneJSON, twoJSON) {
t.Fatalf("[%s] !(json)= [%s]", oneJSON, twoJSON)
}
}
// AssertUnmarshaledEquals unmarshals two JSON strings (got and expected) to
// a map[string]interface{} and then uses reflect.DeepEqual to check they are
// the same
func AssertUnmarshaledEquals(t *testing.T, got, expected string) {
t.Helper()
var gotMap, expectedMap map[string]interface{}
err := json.Unmarshal([]byte(got), &gotMap)
AssertNotError(t, err, "Could not unmarshal 'got'")
err = json.Unmarshal([]byte(expected), &expectedMap)
AssertNotError(t, err, "Could not unmarshal 'expected'")
if len(gotMap) != len(expectedMap) {
t.Errorf("Expected %d keys, but got %d", len(expectedMap), len(gotMap))
}
for k, v := range expectedMap {
if !reflect.DeepEqual(v, gotMap[k]) {
t.Errorf("Field %q: Expected \"%v\", got \"%v\"", k, v, gotMap[k])
}
}
}
// AssertNotEquals uses the equality operator to measure that one and two
// are different
func AssertNotEquals(t *testing.T, one interface{}, two interface{}) {
t.Helper()
if one == two {
t.Fatalf("%#v == %#v", one, two)
}
}
// AssertByteEquals uses bytes.Equal to measure one and two for equality.
func AssertByteEquals(t *testing.T, one []byte, two []byte) {
t.Helper()
if !bytes.Equal(one, two) {
t.Fatalf("Byte [%s] != [%s]",
base64.StdEncoding.EncodeToString(one),
base64.StdEncoding.EncodeToString(two))
}
}
// AssertContains determines whether needle can be found in haystack
func AssertContains(t *testing.T, haystack string, needle string) {
t.Helper()
if !strings.Contains(haystack, needle) {
t.Fatalf("String [%s] does not contain [%s]", haystack, needle)
}
}
// AssertNotContains determines if needle is not found in haystack
func AssertNotContains(t *testing.T, haystack string, needle string) {
t.Helper()
if strings.Contains(haystack, needle) {
t.Fatalf("String [%s] contains [%s]", haystack, needle)
}
}
// AssertSliceContains determines if needle can be found in haystack
func AssertSliceContains[T comparable](t *testing.T, haystack []T, needle T) {
t.Helper()
for _, item := range haystack {
if item == needle {
return
}
}
t.Fatalf("Slice %v does not contain %v", haystack, needle)
}
// AssertMetricWithLabelsEquals determines whether the value held by a prometheus Collector
// (e.g. Gauge, Counter, CounterVec, etc) is equal to the expected float64.
// In order to make useful assertions about just a subset of labels (e.g. for a
// CounterVec with fields "host" and "valid", being able to assert that two
// "valid": "true" increments occurred, without caring which host was tagged in
// each), takes a set of labels and ignores any metrics which have different
// label values.
// Only works for simple metrics (Counters and Gauges), or for the *count*
// (not value) of data points in a Histogram.
func AssertMetricWithLabelsEquals(t *testing.T, c prometheus.Collector, l prometheus.Labels, expected float64) {
t.Helper()
ch := make(chan prometheus.Metric)
done := make(chan struct{})
go func() {
c.Collect(ch)
close(done)
}()
var total float64
timeout := time.After(time.Second)
loop:
for {
metric:
select {
case <-timeout:
t.Fatal("timed out collecting metrics")
case <-done:
break loop
case m := <-ch:
var iom io_prometheus_client.Metric
_ = m.Write(&iom)
for _, lp := range iom.Label {
// If any of the labels on this metric have the same name as but
// different value than a label in `l`, skip this metric.
val, ok := l[lp.GetName()]
if ok && lp.GetValue() != val {
break metric
}
}
// Exactly one of the Counter, Gauge, or Histogram values will be set by
// the .Write() operation, so add them all because the others will be 0.
total += iom.Counter.GetValue()
total += iom.Gauge.GetValue()
total += float64(iom.Histogram.GetSampleCount())
}
}
if total != expected {
t.Errorf("metric with labels %+v: got %g, want %g", l, total, expected)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/certs.go | third-party/github.com/letsencrypt/boulder/test/certs.go | package test
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"os"
"testing"
"time"
"github.com/jmhodges/clock"
)
// LoadSigner loads a PEM private key specified by filename or returns an error.
// Can be paired with issuance.LoadCertificate to get both a CA cert and its
// associated private key for use in signing throwaway test certs.
func LoadSigner(filename string) (crypto.Signer, error) {
keyBytes, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
// pem.Decode does not return an error as its 2nd arg, but instead the "rest"
// that was leftover from parsing the PEM block. We only care if the decoded
// PEM block was empty for this test function.
block, _ := pem.Decode(keyBytes)
if block == nil {
return nil, errors.New("Unable to decode private key PEM bytes")
}
// Try decoding as an RSA private key
if rsaKey, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
return rsaKey, nil
}
// Try decoding as a PKCS8 private key
if key, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
// Determine the key's true type and return it as a crypto.Signer
switch k := key.(type) {
case *rsa.PrivateKey:
return k, nil
case *ecdsa.PrivateKey:
return k, nil
}
}
// Try as an ECDSA private key
if ecdsaKey, err := x509.ParseECPrivateKey(block.Bytes); err == nil {
return ecdsaKey, nil
}
// Nothing worked! Fail hard.
return nil, errors.New("Unable to decode private key PEM bytes")
}
// ThrowAwayCert is a small test helper function that creates a self-signed
// certificate with one SAN. It returns the parsed certificate and its serial
// in string form for convenience.
// The certificate returned from this function is the bare minimum needed for
// most tests and isn't a robust example of a complete end entity certificate.
func ThrowAwayCert(t *testing.T, clk clock.Clock) (string, *x509.Certificate) {
var nameBytes [3]byte
_, _ = rand.Read(nameBytes[:])
name := fmt.Sprintf("%s.example.com", hex.EncodeToString(nameBytes[:]))
// Generate a random IPv6 address under the RFC 3849 space.
// https://www.rfc-editor.org/rfc/rfc3849.txt
var ipBytes [12]byte
_, _ = rand.Read(ipBytes[:])
ipPrefix, _ := hex.DecodeString("20010db8")
ip := net.IP(bytes.Join([][]byte{ipPrefix, ipBytes[:]}, nil))
var serialBytes [16]byte
_, _ = rand.Read(serialBytes[:])
serial := big.NewInt(0).SetBytes(serialBytes[:])
key, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
AssertNotError(t, err, "rsa.GenerateKey failed")
template := &x509.Certificate{
SerialNumber: serial,
DNSNames: []string{name},
IPAddresses: []net.IP{ip},
NotBefore: clk.Now(),
NotAfter: clk.Now().Add(6 * 24 * time.Hour),
IssuingCertificateURL: []string{"http://localhost:4001/acme/issuer-cert/1234"},
}
testCertDER, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key)
AssertNotError(t, err, "x509.CreateCertificate failed")
testCert, err := x509.ParseCertificate(testCertDER)
AssertNotError(t, err, "failed to parse self-signed cert DER")
return fmt.Sprintf("%036x", serial), testCert
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/db.go | third-party/github.com/letsencrypt/boulder/test/db.go | package test
import (
"context"
"database/sql"
"fmt"
"io"
"testing"
)
var (
_ CleanUpDB = &sql.DB{}
)
// CleanUpDB is an interface with only what is needed to delete all
// rows in all tables in a database plus close the database
// connection. It is satisfied by *sql.DB.
type CleanUpDB interface {
BeginTx(context.Context, *sql.TxOptions) (*sql.Tx, error)
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
io.Closer
}
// ResetBoulderTestDatabase returns a cleanup function which deletes all rows in
// all tables of the 'boulder_sa_test' database. Omits the 'gorp_migrations'
// table as this is used by sql-migrate (https://github.com/rubenv/sql-migrate)
// to track migrations. If it encounters an error it fails the tests.
func ResetBoulderTestDatabase(t testing.TB) func() {
return resetTestDatabase(t, context.Background(), "boulder")
}
// ResetIncidentsTestDatabase returns a cleanup function which deletes all rows
// in all tables of the 'incidents_sa_test' database. Omits the
// 'gorp_migrations' table as this is used by sql-migrate
// (https://github.com/rubenv/sql-migrate) to track migrations. If it encounters
// an error it fails the tests.
func ResetIncidentsTestDatabase(t testing.TB) func() {
return resetTestDatabase(t, context.Background(), "incidents")
}
func resetTestDatabase(t testing.TB, ctx context.Context, dbPrefix string) func() {
db, err := sql.Open("mysql", fmt.Sprintf("test_setup@tcp(boulder-proxysql:6033)/%s_sa_test", dbPrefix))
if err != nil {
t.Fatalf("Couldn't create db: %s", err)
}
err = deleteEverythingInAllTables(ctx, db)
if err != nil {
t.Fatalf("Failed to delete everything: %s", err)
}
return func() {
err := deleteEverythingInAllTables(ctx, db)
if err != nil {
t.Fatalf("Failed to truncate tables after the test: %s", err)
}
_ = db.Close()
}
}
// clearEverythingInAllTables deletes all rows in the tables
// available to the CleanUpDB passed in and resets the autoincrement
// counters. See allTableNamesInDB for what is meant by "all tables
// available". To be used only in test code.
func deleteEverythingInAllTables(ctx context.Context, db CleanUpDB) error {
ts, err := allTableNamesInDB(ctx, db)
if err != nil {
return err
}
for _, tn := range ts {
// We do this in a transaction to make sure that the foreign
// key checks remain disabled even if the db object chooses
// another connection to make the deletion on. Note that
// `alter table` statements will silently cause transactions
// to commit, so we do them outside of the transaction.
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("unable to start transaction to delete all rows from table %#v: %s", tn, err)
}
_, err = tx.ExecContext(ctx, "set FOREIGN_KEY_CHECKS = 0")
if err != nil {
return fmt.Errorf("unable to disable FOREIGN_KEY_CHECKS to delete all rows from table %#v: %s", tn, err)
}
// 1 = 1 here prevents the MariaDB i_am_a_dummy setting from
// rejecting the DELETE for not having a WHERE clause.
_, err = tx.ExecContext(ctx, "delete from `"+tn+"` where 1 = 1")
if err != nil {
return fmt.Errorf("unable to delete all rows from table %#v: %s", tn, err)
}
_, err = tx.ExecContext(ctx, "set FOREIGN_KEY_CHECKS = 1")
if err != nil {
return fmt.Errorf("unable to re-enable FOREIGN_KEY_CHECKS to delete all rows from table %#v: %s", tn, err)
}
err = tx.Commit()
if err != nil {
return fmt.Errorf("unable to commit transaction to delete all rows from table %#v: %s", tn, err)
}
_, err = db.ExecContext(ctx, "alter table `"+tn+"` AUTO_INCREMENT = 1")
if err != nil {
return fmt.Errorf("unable to reset autoincrement on table %#v: %s", tn, err)
}
}
return err
}
// allTableNamesInDB returns the names of the tables available to the passed
// CleanUpDB. Omits the 'gorp_migrations' table as this is used by sql-migrate
// (https://github.com/rubenv/sql-migrate) to track migrations.
func allTableNamesInDB(ctx context.Context, db CleanUpDB) ([]string, error) {
r, err := db.QueryContext(ctx, "select table_name from information_schema.tables t where t.table_schema = DATABASE() and t.table_name != 'gorp_migrations';")
if err != nil {
return nil, err
}
defer r.Close()
var ts []string
for r.Next() {
tableName := ""
err = r.Scan(&tableName)
if err != nil {
return nil, err
}
ts = append(ts, tableName)
}
return ts, r.Err()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/chall-test-srv/mockdns.go | third-party/github.com/letsencrypt/boulder/test/chall-test-srv/mockdns.go | // addDNS01 handles an HTTP POST request to add a new DNS-01 challenge TXT
package main
import (
"net/http"
"strings"
"github.com/letsencrypt/challtestsrv"
)
// setDefaultDNSIPv4 handles an HTTP POST request to set the default IPv4
// address used for all A query responses that do not match more-specific mocked
// responses.
//
// The POST body is expected to have one parameter:
// "ip" - the string representation of an IPv4 address to use for all A queries
// that do not match more specific mocks.
//
// Providing an empty string as the IP value will disable the default
// A responses.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) setDefaultDNSIPv4(w http.ResponseWriter, r *http.Request) {
var request struct {
IP string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Set the challenge server's default IPv4 address - we allow request.IP to be
// the empty string so that the default can be cleared using the same
// method.
srv.challSrv.SetDefaultDNSIPv4(request.IP)
srv.log.Printf("Set default IPv4 address for DNS A queries to %q\n", request.IP)
w.WriteHeader(http.StatusOK)
}
// setDefaultDNSIPv6 handles an HTTP POST request to set the default IPv6
// address used for all AAAA query responses that do not match more-specific
// mocked responses.
//
// The POST body is expected to have one parameter:
// "ip" - the string representation of an IPv6 address to use for all AAAA
// queries that do not match more specific mocks.
//
// Providing an empty string as the IP value will disable the default
// A responses.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) setDefaultDNSIPv6(w http.ResponseWriter, r *http.Request) {
var request struct {
IP string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Set the challenge server's default IPv6 address - we allow request.IP to be
// the empty string so that the default can be cleared using the same
// method.
srv.challSrv.SetDefaultDNSIPv6(request.IP)
srv.log.Printf("Set default IPv6 address for DNS AAAA queries to %q\n", request.IP)
w.WriteHeader(http.StatusOK)
}
// addDNSARecord handles an HTTP POST request to add a mock A query response record
// for a host.
//
// The POST body is expected to have two non-empty parameters:
// "host" - the hostname that when queried should return the mocked A record.
// "addresses" - an array of IPv4 addresses in string representation that should
// be used for the A records returned for the query.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) addDNSARecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
Addresses []string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has no addresses or an empty host it's a bad request
if len(request.Addresses) == 0 || request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.AddDNSARecord(request.Host, request.Addresses)
srv.log.Printf("Added response for DNS A queries to %q : %s\n",
request.Host, strings.Join(request.Addresses, ", "))
w.WriteHeader(http.StatusOK)
}
// delDNSARecord handles an HTTP POST request to delete an existing mock A
// policy record for a host.
//
// The POST body is expected to have one non-empty parameter:
// "host" - the hostname to remove the mock A record for.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) delDNSARecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty host it's a bad request
if request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.DeleteDNSARecord(request.Host)
srv.log.Printf("Removed response for DNS A queries to %q", request.Host)
w.WriteHeader(http.StatusOK)
}
// addDNSAAAARecord handles an HTTP POST request to add a mock AAAA query
// response record for a host.
//
// The POST body is expected to have two non-empty parameters:
// "host" - the hostname that when queried should return the mocked A record.
// "addresses" - an array of IPv6 addresses in string representation that should
// be used for the AAAA records returned for the query.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) addDNSAAAARecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
Addresses []string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has no addresses or an empty host it's a bad request
if len(request.Addresses) == 0 || request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.AddDNSAAAARecord(request.Host, request.Addresses)
srv.log.Printf("Added response for DNS AAAA queries to %q : %s\n",
request.Host, strings.Join(request.Addresses, ", "))
w.WriteHeader(http.StatusOK)
}
// delDNSAAAARecord handles an HTTP POST request to delete an existing mock AAAA
// policy record for a host.
//
// The POST body is expected to have one non-empty parameter:
// "host" - the hostname to remove the mock AAAA record for.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) delDNSAAAARecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty host it's a bad request
if request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.DeleteDNSAAAARecord(request.Host)
srv.log.Printf("Removed response for DNS AAAA queries to %q", request.Host)
w.WriteHeader(http.StatusOK)
}
// addDNSCAARecord handles an HTTP POST request to add a mock CAA query
// response record for a host.
//
// The POST body is expected to have two non-empty parameters:
// "host" - the hostname that when queried should return the mocked CAA record.
// "policies" - an array of CAA policy objects. Each policy object is expected
// to have two non-empty keys, "tag" and "value".
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) addDNSCAARecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
Policies []challtestsrv.MockCAAPolicy
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has no host or no caa policies it's a bad request
if request.Host == "" || len(request.Policies) == 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.AddDNSCAARecord(request.Host, request.Policies)
srv.log.Printf("Added response for DNS CAA queries to %q", request.Host)
w.WriteHeader(http.StatusOK)
}
// delDNSCAARecord handles an HTTP POST request to delete an existing mock CAA
// policy record for a host.
//
// The POST body is expected to have one non-empty parameter:
// "host" - the hostname to remove the mock CAA policy for.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) delDNSCAARecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty host it's a bad request
if request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.DeleteDNSCAARecord(request.Host)
srv.log.Printf("Removed response for DNS CAA queries to %q", request.Host)
w.WriteHeader(http.StatusOK)
}
// addDNSCNAMERecord handles an HTTP POST request to add a mock CNAME query
// response record and alias for a host.
//
// The POST body is expected to have two non-empty parameters:
// "host" - the hostname that should be treated as an alias to the target
// "target" - the hostname whose mocked DNS records should be returned
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) addDNSCNAMERecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
Target string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has no host or no caa policies it's a bad request
if request.Host == "" || request.Target == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.AddDNSCNAMERecord(request.Host, request.Target)
srv.log.Printf("Added response for DNS CNAME queries to %q targeting %q", request.Host, request.Target)
w.WriteHeader(http.StatusOK)
}
// delDNSCNAMERecord handles an HTTP POST request to delete an existing mock
// CNAME record for a host.
//
// The POST body is expected to have one non-empty parameters:
// "host" - the hostname to remove the mock CNAME alias for.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) delDNSCNAMERecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty host it's a bad request
if request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.DeleteDNSCNAMERecord(request.Host)
srv.log.Printf("Removed response for DNS CNAME queries to %q", request.Host)
w.WriteHeader(http.StatusOK)
}
// addDNSServFailRecord handles an HTTP POST request to add a mock SERVFAIL
// response record for a host. All queries for that host will subsequently
// result in SERVFAIL responses, overriding any other mocks.
//
// The POST body is expected to have one non-empty parameter:
// "host" - the hostname that should return SERVFAIL responses.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) addDNSServFailRecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has no host it's a bad request
if request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.AddDNSServFailRecord(request.Host)
srv.log.Printf("Added SERVFAIL response for DNS queries to %q", request.Host)
w.WriteHeader(http.StatusOK)
}
// delDNSServFailRecord handles an HTTP POST request to delete an existing mock
// SERVFAIL record for a host.
//
// The POST body is expected to have one non-empty parameters:
// "host" - the hostname to remove the mock SERVFAIL response from.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) delDNSServFailRecord(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty host it's a bad request
if request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.challSrv.DeleteDNSServFailRecord(request.Host)
srv.log.Printf("Removed SERVFAIL response for DNS queries to %q", request.Host)
w.WriteHeader(http.StatusOK)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/chall-test-srv/httpone.go | third-party/github.com/letsencrypt/boulder/test/chall-test-srv/httpone.go | package main
import "net/http"
// addHTTP01 handles an HTTP POST request to add a new HTTP-01 challenge
// response for a given token.
//
// The POST body is expected to have two non-empty parameters:
// "token" - the HTTP-01 challenge token to add the mock HTTP-01 response under
// in the `/.well-known/acme-challenge/` path.
//
// "content" - the key authorization value to return in the HTTP response.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) addHTTP01(w http.ResponseWriter, r *http.Request) {
// Unmarshal the request body JSON as a request object
var request struct {
Token string
Content string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty token or content it's a bad request
if request.Token == "" || request.Content == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Add the HTTP-01 challenge to the challenge server
srv.challSrv.AddHTTPOneChallenge(request.Token, request.Content)
srv.log.Printf("Added HTTP-01 challenge for token %q - key auth %q\n",
request.Token, request.Content)
w.WriteHeader(http.StatusOK)
}
// delHTTP01 handles an HTTP POST request to delete an existing HTTP-01
// challenge response for a given token.
//
// The POST body is expected to have one non-empty parameter:
// "token" - the HTTP-01 challenge token to remove the mock HTTP-01 response
// from.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) delHTTP01(w http.ResponseWriter, r *http.Request) {
// Unmarshal the request body JSON as a request object
var request struct {
Token string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty token it's a bad request
if request.Token == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Delete the HTTP-01 challenge for the given token from the challenge server
srv.challSrv.DeleteHTTPOneChallenge(request.Token)
srv.log.Printf("Removed HTTP-01 challenge for token %q\n", request.Token)
w.WriteHeader(http.StatusOK)
}
// addHTTPRedirect handles an HTTP POST request to add a new 301 redirect to be
// served for the given path to the given target URL.
//
// The POST body is expected to have two non-empty parameters:
// "path" - the path that when matched in an HTTP request will return the
// redirect.
//
// "targetURL" - the URL that the client will be redirected to when making HTTP
// requests for the redirected path.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) addHTTPRedirect(w http.ResponseWriter, r *http.Request) {
// Unmarshal the request body JSON as a request object
var request struct {
Path string
TargetURL string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty path or target URL it's a bad request
if request.Path == "" || request.TargetURL == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Add the HTTP redirect to the challenge server
srv.challSrv.AddHTTPRedirect(request.Path, request.TargetURL)
srv.log.Printf("Added HTTP redirect for path %q to %q\n",
request.Path, request.TargetURL)
w.WriteHeader(http.StatusOK)
}
// delHTTPRedirect handles an HTTP POST request to delete an existing HTTP
// redirect for a given path.
//
// The POST body is expected to have one non-empty parameter:
// "path" - the path to remove a redirect for.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) delHTTPRedirect(w http.ResponseWriter, r *http.Request) {
// Unmarshal the request body JSON as a request object
var request struct {
Path string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if request.Path == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Delete the HTTP redirect for the given path from the challenge server
srv.challSrv.DeleteHTTPRedirect(request.Path)
srv.log.Printf("Removed HTTP redirect for path %q\n", request.Path)
w.WriteHeader(http.StatusOK)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/chall-test-srv/dnsone.go | third-party/github.com/letsencrypt/boulder/test/chall-test-srv/dnsone.go | package main
import "net/http"
// addDNS01 handles an HTTP POST request to add a new DNS-01 challenge TXT
// record for a given host/value.
//
// The POST body is expected to have two non-empty parameters:
// "host" - the hostname to add the mock TXT response under.
// "value" - the key authorization value to return in the TXT response.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) addDNS01(w http.ResponseWriter, r *http.Request) {
// Unmarshal the request body JSON as a request object
var request struct {
Host string
Value string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty host or value it's a bad request
if request.Host == "" || request.Value == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Add the DNS-01 challenge response TXT to the challenge server
srv.challSrv.AddDNSOneChallenge(request.Host, request.Value)
srv.log.Printf("Added DNS-01 TXT challenge for Host %q - Value %q\n",
request.Host, request.Value)
w.WriteHeader(http.StatusOK)
}
// delDNS01 handles an HTTP POST request to delete an existing DNS-01 challenge
// TXT record for a given host.
//
// The POST body is expected to have one non-empty parameter:
// "host" - the hostname to remove the mock TXT response for.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) delDNS01(w http.ResponseWriter, r *http.Request) {
// Unmarshal the request body JSON as a request object
var request struct {
Host string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty host value it's a bad request
if request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Delete the DNS-01 challenge response TXT for the given host from the
// challenge server
srv.challSrv.DeleteDNSOneChallenge(request.Host)
srv.log.Printf("Removed DNS-01 TXT challenge for Host %q\n", request.Host)
w.WriteHeader(http.StatusOK)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/chall-test-srv/history.go | third-party/github.com/letsencrypt/boulder/test/chall-test-srv/history.go | package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/letsencrypt/challtestsrv"
)
// clearHistory handles an HTTP POST request to clear the challenge server
// request history for a specific hostname and type of event.
//
// The POST body is expected to have two parameters:
// "host" - the hostname to clear history for.
// "type" - the type of event to clear. May be "http", "dns", or "tlsalpn".
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) clearHistory(w http.ResponseWriter, r *http.Request) {
var request struct {
Host string
Type string `json:"type"`
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
typeMap := map[string]challtestsrv.RequestEventType{
"http": challtestsrv.HTTPRequestEventType,
"dns": challtestsrv.DNSRequestEventType,
"tlsalpn": challtestsrv.TLSALPNRequestEventType,
}
if request.Host == "" {
http.Error(w, "host parameter must not be empty", http.StatusBadRequest)
return
}
if code, ok := typeMap[request.Type]; ok {
srv.challSrv.ClearRequestHistory(request.Host, code)
srv.log.Printf("Cleared challenge server request history for %q %q events\n",
request.Host, request.Type)
w.WriteHeader(http.StatusOK)
return
}
http.Error(w, fmt.Sprintf("%q event type unknown", request.Type), http.StatusBadRequest)
}
// getHTTPHistory returns only the HTTPRequestEvents for the given hostname
// from the challenge server's request history in JSON form.
func (srv *managementServer) getHTTPHistory(w http.ResponseWriter, r *http.Request) {
host, err := requestHost(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
srv.writeHistory(
srv.challSrv.RequestHistory(host, challtestsrv.HTTPRequestEventType),
w)
}
// getDNSHistory returns only the DNSRequestEvents from the challenge
// server's request history in JSON form.
func (srv *managementServer) getDNSHistory(w http.ResponseWriter, r *http.Request) {
host, err := requestHost(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
srv.writeHistory(
srv.challSrv.RequestHistory(host, challtestsrv.DNSRequestEventType),
w)
}
// getTLSALPNHistory returns only the TLSALPNRequestEvents from the challenge
// server's request history in JSON form.
func (srv *managementServer) getTLSALPNHistory(w http.ResponseWriter, r *http.Request) {
host, err := requestHost(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
srv.writeHistory(
srv.challSrv.RequestHistory(host, challtestsrv.TLSALPNRequestEventType),
w)
}
// requestHost extracts the Host parameter of a JSON POST body in the provided
// request, or returns an error.
func requestHost(r *http.Request) (string, error) {
var request struct {
Host string
}
if err := mustParsePOST(&request, r); err != nil {
return "", err
}
if request.Host == "" {
return "", errors.New("host parameter of POST body must not be empty")
}
return request.Host, nil
}
// writeHistory writes the provided list of challtestsrv.RequestEvents to the
// provided http.ResponseWriter in JSON form.
func (srv *managementServer) writeHistory(
history []challtestsrv.RequestEvent, w http.ResponseWriter,
) {
// Always write an empty JSON list instead of `null`
if history == nil {
history = []challtestsrv.RequestEvent{}
}
jsonHistory, err := json.MarshalIndent(history, "", " ")
if err != nil {
srv.log.Printf("Error marshaling history: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(jsonHistory)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/chall-test-srv/tlsalpnone.go | third-party/github.com/letsencrypt/boulder/test/chall-test-srv/tlsalpnone.go | package main
import "net/http"
// addTLSALPN01 handles an HTTP POST request to add a new TLS-ALPN-01 challenge
// response certificate for a given host.
//
// The POST body is expected to have two non-empty parameters:
// "host" - the hostname to add the challenge response certificate for.
// "content" - the key authorization value to use to construct the TLS-ALPN-01
// challenge response certificate.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) addTLSALPN01(w http.ResponseWriter, r *http.Request) {
// Unmarshal the request body JSON as a request object
var request struct {
Host string
Content string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty host or content it's a bad request
if request.Host == "" || request.Content == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Add the TLS-ALPN-01 challenge to the challenge server
srv.challSrv.AddTLSALPNChallenge(request.Host, request.Content)
srv.log.Printf("Added TLS-ALPN-01 challenge for host %q - key auth %q\n",
request.Host, request.Content)
w.WriteHeader(http.StatusOK)
}
// delTLSALPN01 handles an HTTP POST request to delete an existing TLS-ALPN-01
// challenge response for a given host.
//
// The POST body is expected to have one non-empty parameter:
// "host" - the hostname to remove the TLS-ALPN-01 challenge response for.
//
// A successful POST will write http.StatusOK to the client.
func (srv *managementServer) delTLSALPN01(w http.ResponseWriter, r *http.Request) {
// Unmarshal the request body JSON as a request object
var request struct {
Host string
}
if err := mustParsePOST(&request, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If the request has an empty host it's a bad request
if request.Host == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Delete the TLS-ALPN-01 challenge for the given host from the challenge server
srv.challSrv.DeleteTLSALPNChallenge(request.Host)
srv.log.Printf("Removed TLS-ALPN-01 challenge for host %q\n", request.Host)
w.WriteHeader(http.StatusOK)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/chall-test-srv/http.go | third-party/github.com/letsencrypt/boulder/test/chall-test-srv/http.go | package main
import (
"encoding/json"
"errors"
"io"
"net/http"
)
// mustParsePOST will attempt to read a JSON POST body from the provided request
// and unmarshal it into the provided ob. If an error occurs at any point it
// will be returned.
func mustParsePOST(ob interface{}, request *http.Request) error {
jsonBody, err := io.ReadAll(request.Body)
if err != nil {
return err
}
if string(jsonBody) == "" {
return errors.New("Expected JSON POST body, was empty")
}
return json.Unmarshal(jsonBody, ob)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/chall-test-srv/main.go | third-party/github.com/letsencrypt/boulder/test/chall-test-srv/main.go | package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/letsencrypt/challtestsrv"
"github.com/letsencrypt/boulder/cmd"
)
// managementServer is a small HTTP server that can control a challenge server,
// adding and deleting challenge responses as required
type managementServer struct {
// A managementServer is a http.Server
*http.Server
log *log.Logger
// The challenge server that is under control by the management server
challSrv *challtestsrv.ChallSrv
}
func (srv *managementServer) Run() {
srv.log.Printf("Starting management server on %s", srv.Server.Addr)
// Start the HTTP server in its own dedicated Go routine
go func() {
err := srv.ListenAndServe()
if err != nil && !strings.Contains(err.Error(), "Server closed") {
srv.log.Print(err)
}
}()
}
func (srv *managementServer) Shutdown() {
if err := srv.Server.Shutdown(context.Background()); err != nil {
srv.log.Printf("Err shutting down management server")
}
}
func filterEmpty(input []string) []string {
var output []string
for _, val := range input {
trimmed := strings.TrimSpace(val)
if trimmed != "" {
output = append(output, trimmed)
}
}
return output
}
func main() {
httpOneBind := flag.String("http01", ":5002",
"Comma separated bind addresses/ports for HTTP-01 challenges. Set empty to disable.")
httpsOneBind := flag.String("https01", ":5003",
"Comma separated bind addresses/ports for HTTPS HTTP-01 challenges. Set empty to disable.")
dohBind := flag.String("doh", ":8443",
"Comma separated bind addresses/ports for DoH queries. Set empty to disable.")
dohCert := flag.String("doh-cert", "", "Path to certificate file for DoH server.")
dohCertKey := flag.String("doh-cert-key", "", "Path to certificate key file for DoH server.")
dnsOneBind := flag.String("dns01", ":8053",
"Comma separated bind addresses/ports for DNS-01 challenges and fake DNS data. Set empty to disable.")
tlsAlpnOneBind := flag.String("tlsalpn01", ":5001",
"Comma separated bind addresses/ports for TLS-ALPN-01 and HTTPS HTTP-01 challenges. Set empty to disable.")
managementBind := flag.String("management", ":8055",
"Bind address/port for management HTTP interface")
defaultIPv4 := flag.String("defaultIPv4", "127.0.0.1",
"Default IPv4 address for mock DNS responses to A queries")
defaultIPv6 := flag.String("defaultIPv6", "::1",
"Default IPv6 address for mock DNS responses to AAAA queries")
flag.Parse()
if len(flag.Args()) > 0 {
fmt.Printf("invalid command line arguments: %s\n", strings.Join(flag.Args(), " "))
flag.Usage()
os.Exit(1)
}
httpOneAddresses := filterEmpty(strings.Split(*httpOneBind, ","))
httpsOneAddresses := filterEmpty(strings.Split(*httpsOneBind, ","))
dohAddresses := filterEmpty(strings.Split(*dohBind, ","))
dnsOneAddresses := filterEmpty(strings.Split(*dnsOneBind, ","))
tlsAlpnOneAddresses := filterEmpty(strings.Split(*tlsAlpnOneBind, ","))
logger := log.New(os.Stdout, "chall-test-srv - ", log.Ldate|log.Ltime)
// Create a new challenge server with the provided config
srv, err := challtestsrv.New(challtestsrv.Config{
HTTPOneAddrs: httpOneAddresses,
HTTPSOneAddrs: httpsOneAddresses,
DOHAddrs: dohAddresses,
DOHCert: *dohCert,
DOHCertKey: *dohCertKey,
DNSOneAddrs: dnsOneAddresses,
TLSALPNOneAddrs: tlsAlpnOneAddresses,
Log: logger,
})
cmd.FailOnError(err, "Unable to construct challenge server")
// Create a new management server with the provided config
oobSrv := managementServer{
Server: &http.Server{
Addr: *managementBind,
ReadTimeout: 30 * time.Second,
},
challSrv: srv,
log: logger,
}
// Register handlers on the management server for adding challenge responses
// for the configured challenges.
if *httpOneBind != "" || *httpsOneBind != "" {
http.HandleFunc("/add-http01", oobSrv.addHTTP01)
http.HandleFunc("/del-http01", oobSrv.delHTTP01)
http.HandleFunc("/add-redirect", oobSrv.addHTTPRedirect)
http.HandleFunc("/del-redirect", oobSrv.delHTTPRedirect)
}
if *dnsOneBind != "" {
http.HandleFunc("/set-default-ipv4", oobSrv.setDefaultDNSIPv4)
http.HandleFunc("/set-default-ipv6", oobSrv.setDefaultDNSIPv6)
// TODO(@cpu): It might make sense to revisit this API in the future to have
// one endpoint that accepts the mock type required (A, AAAA, CNAME, etc)
// instead of having separate endpoints per type.
http.HandleFunc("/set-txt", oobSrv.addDNS01)
http.HandleFunc("/clear-txt", oobSrv.delDNS01)
http.HandleFunc("/add-a", oobSrv.addDNSARecord)
http.HandleFunc("/clear-a", oobSrv.delDNSARecord)
http.HandleFunc("/add-aaaa", oobSrv.addDNSAAAARecord)
http.HandleFunc("/clear-aaaa", oobSrv.delDNSAAAARecord)
http.HandleFunc("/add-caa", oobSrv.addDNSCAARecord)
http.HandleFunc("/clear-caa", oobSrv.delDNSCAARecord)
http.HandleFunc("/set-cname", oobSrv.addDNSCNAMERecord)
http.HandleFunc("/clear-cname", oobSrv.delDNSCNAMERecord)
http.HandleFunc("/set-servfail", oobSrv.addDNSServFailRecord)
http.HandleFunc("/clear-servfail", oobSrv.delDNSServFailRecord)
srv.SetDefaultDNSIPv4(*defaultIPv4)
srv.SetDefaultDNSIPv6(*defaultIPv6)
if *defaultIPv4 != "" {
logger.Printf("Answering A queries with %s by default",
*defaultIPv4)
}
if *defaultIPv6 != "" {
logger.Printf("Answering AAAA queries with %s by default",
*defaultIPv6)
}
}
if *tlsAlpnOneBind != "" {
http.HandleFunc("/add-tlsalpn01", oobSrv.addTLSALPN01)
http.HandleFunc("/del-tlsalpn01", oobSrv.delTLSALPN01)
}
http.HandleFunc("/clear-request-history", oobSrv.clearHistory)
http.HandleFunc("/http-request-history", oobSrv.getHTTPHistory)
http.HandleFunc("/dns-request-history", oobSrv.getDNSHistory)
http.HandleFunc("/tlsalpn01-request-history", oobSrv.getTLSALPNHistory)
// Start all of the sub-servers in their own Go routines so that the main Go
// routine can spin forever looking for signals to catch.
go srv.Run()
go oobSrv.Run()
cmd.CatchSignals(func() {
srv.Shutdown()
oobSrv.Shutdown()
})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/wfe_test.go | third-party/github.com/letsencrypt/boulder/test/integration/wfe_test.go | //go:build integration
package integration
import (
"io"
"net/http"
"testing"
"github.com/letsencrypt/boulder/test"
)
// TestWFECORS is a small integration test that checks that the
// Access-Control-Allow-Origin header is returned for a GET request to the
// directory endpoint that has an Origin request header of "*".
func TestWFECORS(t *testing.T) {
// Construct a GET request with an Origin header to sollicit an
// Access-Control-Allow-Origin response header.
getReq, _ := http.NewRequest("GET", "http://boulder.service.consul:4001/directory", nil)
getReq.Header.Set("Origin", "*")
// Performing the GET should return status 200.
client := &http.Client{}
resp, err := client.Do(getReq)
test.AssertNotError(t, err, "GET directory")
test.AssertEquals(t, resp.StatusCode, http.StatusOK)
// We expect that the response has the correct Access-Control-Allow-Origin
// header.
corsAllowOrigin := resp.Header.Get("Access-Control-Allow-Origin")
test.AssertEquals(t, corsAllowOrigin, "*")
}
// TestWFEHTTPMetrics verifies that the measured_http metrics we collect
// for boulder-wfe and boulder-wfe2 are being properly collected. In order
// to initialize the prometheus metrics we make a call to the /directory
// endpoint before checking the /metrics endpoint.
func TestWFEHTTPMetrics(t *testing.T) {
// Check boulder-wfe2
resp, err := http.Get("http://boulder.service.consul:4001/directory")
test.AssertNotError(t, err, "GET boulder-wfe2 directory")
test.AssertEquals(t, resp.StatusCode, http.StatusOK)
resp.Body.Close()
resp, err = http.Get("http://boulder.service.consul:8013/metrics")
test.AssertNotError(t, err, "GET boulder-wfe2 metrics")
test.AssertEquals(t, resp.StatusCode, http.StatusOK)
body, err := io.ReadAll(resp.Body)
test.AssertNotError(t, err, "Reading boulder-wfe2 metrics response")
test.AssertContains(t, string(body), `response_time_count{code="200",endpoint="/directory",method="GET"}`)
resp.Body.Close()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/srv_resolver_test.go | third-party/github.com/letsencrypt/boulder/test/integration/srv_resolver_test.go | //go:build integration
package integration
import (
"context"
"testing"
"github.com/jmhodges/clock"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/letsencrypt/boulder/cmd"
bgrpc "github.com/letsencrypt/boulder/grpc"
"github.com/letsencrypt/boulder/metrics"
"github.com/letsencrypt/boulder/nonce"
"github.com/letsencrypt/boulder/test"
)
type srvResolverTestConfig struct {
WebFooEnd struct {
TLS cmd.TLSConfig
// CaseOne config will have 2 SRV records. The first will have 0
// backends, the second will have 1.
CaseOne *cmd.GRPCClientConfig
// CaseTwo config will have 2 SRV records. The first will not be
// configured in Consul, the second will have 1 backend.
CaseTwo *cmd.GRPCClientConfig
// CaseThree config will have 2 SRV records. Neither will be configured
// in Consul.
CaseThree *cmd.GRPCClientConfig
// CaseFour config will have 2 SRV records. Neither will have backends.
CaseFour *cmd.GRPCClientConfig
}
}
func TestSRVResolver_CaseOne(t *testing.T) {
t.Parallel()
var c srvResolverTestConfig
err := cmd.ReadConfigFile("test/integration/testdata/srv-resolver-config.json", &c)
test.AssertNotError(t, err, "Could not read config file")
tlsConfig, err := c.WebFooEnd.TLS.Load(metrics.NoopRegisterer)
test.AssertNotError(t, err, "Could not load TLS config")
clk := clock.New()
getNonceConn, err := bgrpc.ClientSetup(c.WebFooEnd.CaseOne, tlsConfig, metrics.NoopRegisterer, clk)
test.AssertNotError(t, err, "Could not set up gRPC client")
// This should succeed, even though the first SRV record has no backends.
gnc := nonce.NewGetter(getNonceConn)
_, err = gnc.Nonce(context.Background(), &emptypb.Empty{})
test.AssertNotError(t, err, "Unexpected error getting nonce")
}
func TestSRVResolver_CaseTwo(t *testing.T) {
t.Parallel()
var c srvResolverTestConfig
err := cmd.ReadConfigFile("test/integration/testdata/srv-resolver-config.json", &c)
test.AssertNotError(t, err, "Could not read config file")
tlsConfig, err := c.WebFooEnd.TLS.Load(metrics.NoopRegisterer)
test.AssertNotError(t, err, "Could not load TLS config")
clk := clock.New()
getNonceConn, err := bgrpc.ClientSetup(c.WebFooEnd.CaseTwo, tlsConfig, metrics.NoopRegisterer, clk)
test.AssertNotError(t, err, "Could not set up gRPC client")
// This should succeed, even though the first SRV record is not configured
// in Consul.
gnc := nonce.NewGetter(getNonceConn)
_, err = gnc.Nonce(context.Background(), &emptypb.Empty{})
test.AssertNotError(t, err, "Unexpected error getting nonce")
}
func TestSRVResolver_CaseThree(t *testing.T) {
t.Parallel()
var c srvResolverTestConfig
err := cmd.ReadConfigFile("test/integration/testdata/srv-resolver-config.json", &c)
test.AssertNotError(t, err, "Could not read config file")
tlsConfig, err := c.WebFooEnd.TLS.Load(metrics.NoopRegisterer)
test.AssertNotError(t, err, "Could not load TLS config")
clk := clock.New()
getNonceConn, err := bgrpc.ClientSetup(c.WebFooEnd.CaseThree, tlsConfig, metrics.NoopRegisterer, clk)
test.AssertNotError(t, err, "Could not set up gRPC client")
// This should fail, neither SRV record is configured in Consul and the
// resolver will not return any backends.
gnc := nonce.NewGetter(getNonceConn)
_, err = gnc.Nonce(context.Background(), &emptypb.Empty{})
test.AssertError(t, err, "Expected error getting nonce")
test.AssertContains(t, err.Error(), "no children to pick from")
}
func TestSRVResolver_CaseFour(t *testing.T) {
t.Parallel()
var c srvResolverTestConfig
err := cmd.ReadConfigFile("test/integration/testdata/srv-resolver-config.json", &c)
test.AssertNotError(t, err, "Could not read config file")
tlsConfig, err := c.WebFooEnd.TLS.Load(metrics.NoopRegisterer)
test.AssertNotError(t, err, "Could not load TLS config")
clk := clock.New()
getNonceConn4, err := bgrpc.ClientSetup(c.WebFooEnd.CaseFour, tlsConfig, metrics.NoopRegisterer, clk)
test.AssertNotError(t, err, "Could not set up gRPC client")
// This should fail, neither SRV record resolves to backends.
gnc := nonce.NewGetter(getNonceConn4)
_, err = gnc.Nonce(context.Background(), &emptypb.Empty{})
test.AssertError(t, err, "Expected error getting nonce")
test.AssertContains(t, err.Error(), "no children to pick from")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/cert_storage_failed_test.go | third-party/github.com/letsencrypt/boulder/test/integration/cert_storage_failed_test.go | //go:build integration
package integration
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"database/sql"
"errors"
"fmt"
"os"
"os/exec"
"path"
"strings"
"testing"
"time"
"github.com/eggsampler/acme/v3"
_ "github.com/go-sql-driver/mysql"
"golang.org/x/crypto/ocsp"
"github.com/letsencrypt/boulder/core"
"github.com/letsencrypt/boulder/sa"
"github.com/letsencrypt/boulder/test"
ocsp_helper "github.com/letsencrypt/boulder/test/ocsp/helper"
"github.com/letsencrypt/boulder/test/vars"
)
// getPrecertByName finds and parses a precertificate using the given hostname.
// It returns the most recent one.
func getPrecertByName(db *sql.DB, reversedName string) (*x509.Certificate, error) {
reversedName = sa.EncodeIssuedName(reversedName)
// Find the certificate from the precertificates table. We don't know the serial so
// we have to look it up by name.
var der []byte
rows, err := db.Query(`
SELECT der
FROM issuedNames JOIN precertificates
USING (serial)
WHERE reversedName = ?
ORDER BY issuedNames.id DESC
LIMIT 1
`, reversedName)
for rows.Next() {
err = rows.Scan(&der)
if err != nil {
return nil, err
}
}
if der == nil {
return nil, fmt.Errorf("no precertificate found for %q", reversedName)
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, err
}
return cert, nil
}
// expectOCSP500 queries OCSP for the given certificate and expects a 500 error.
func expectOCSP500(cert *x509.Certificate) error {
_, err := ocsp_helper.Req(cert, ocspConf())
if err == nil {
return errors.New("Expected error getting OCSP for certificate that failed status storage")
}
var statusCodeError ocsp_helper.StatusCodeError
if !errors.As(err, &statusCodeError) {
return fmt.Errorf("Got wrong kind of error for OCSP. Expected status code error, got %s", err)
} else if statusCodeError.Code != 500 {
return fmt.Errorf("Got wrong error status for OCSP. Expected 500, got %d", statusCodeError.Code)
}
return nil
}
// TestIssuanceCertStorageFailed tests what happens when a storage RPC fails
// during issuance. Specifically, it tests that case where we successfully
// prepared and stored a linting certificate plus metadata, but after
// issuing the precertificate we failed to mark the certificate as "ready"
// to serve an OCSP "good" response.
//
// To do this, we need to mess with the database, because we want to cause
// a failure in one specific query, without control ever returning to the
// client. Fortunately we can do this with MySQL triggers.
//
// We also want to make sure we can revoke the precertificate, which we will
// assume exists (note that this different from the root program assumption
// that a final certificate exists for any precertificate, though it is
// similar in spirit).
func TestIssuanceCertStorageFailed(t *testing.T) {
os.Setenv("DIRECTORY", "http://boulder.service.consul:4001/directory")
ctx := context.Background()
db, err := sql.Open("mysql", vars.DBConnSAIntegrationFullPerms)
test.AssertNotError(t, err, "failed to open db connection")
_, err = db.ExecContext(ctx, `DROP TRIGGER IF EXISTS fail_ready`)
test.AssertNotError(t, err, "failed to drop trigger")
// Make a specific update to certificateStatus fail, for this test but not others.
// To limit the effect to this one test, we make the trigger aware of a specific
// hostname used in this test. Since the UPDATE to the certificateStatus table
// doesn't include the hostname, we look it up in the issuedNames table, keyed
// off of the serial being updated.
// We limit this to UPDATEs that set the status to "good" because otherwise we
// would fail to revoke the certificate later.
// NOTE: CREATE and DROP TRIGGER do not work in prepared statements. Go's
// database/sql will automatically try to use a prepared statement if you pass
// any arguments to Exec besides the query itself, so don't do that.
_, err = db.ExecContext(ctx, `
CREATE TRIGGER fail_ready
BEFORE UPDATE ON certificateStatus
FOR EACH ROW BEGIN
DECLARE reversedName1 VARCHAR(255);
SELECT reversedName
INTO reversedName1
FROM issuedNames
WHERE serial = NEW.serial
AND reversedName LIKE "com.wantserror.%";
IF NEW.status = "good" AND reversedName1 != "" THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Pretend there was an error updating the certificateStatus';
END IF;
END
`)
test.AssertNotError(t, err, "failed to create trigger")
defer db.ExecContext(ctx, `DROP TRIGGER IF EXISTS fail_ready`)
certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// ---- Test revocation by serial ----
revokeMeDomain := "revokeme.wantserror.com"
// This should fail because the trigger prevented setting the certificate status to "ready"
_, err = authAndIssue(nil, certKey, []acme.Identifier{{Type: "dns", Value: revokeMeDomain}}, true, "")
test.AssertError(t, err, "expected authAndIssue to fail")
cert, err := getPrecertByName(db, revokeMeDomain)
test.AssertNotError(t, err, "failed to get certificate by name")
err = expectOCSP500(cert)
test.AssertNotError(t, err, "expected 500 error from OCSP")
// Revoke by invoking admin-revoker
config := fmt.Sprintf("%s/%s", os.Getenv("BOULDER_CONFIG_DIR"), "admin.json")
output, err := exec.Command(
"./bin/admin",
"-config", config,
"-dry-run=false",
"revoke-cert",
"-serial", core.SerialToString(cert.SerialNumber),
"-reason", "unspecified",
).CombinedOutput()
test.AssertNotError(t, err, fmt.Sprintf("revoking via admin-revoker: %s", string(output)))
_, err = ocsp_helper.Req(cert,
ocsp_helper.DefaultConfig.WithExpectStatus(ocsp.Revoked).WithExpectReason(ocsp.Unspecified))
// ---- Test revocation by key ----
blockMyKeyDomain := "blockmykey.wantserror.com"
// This should fail because the trigger prevented setting the certificate status to "ready"
_, err = authAndIssue(nil, certKey, []acme.Identifier{{Type: "dns", Value: blockMyKeyDomain}}, true, "")
test.AssertError(t, err, "expected authAndIssue to fail")
cert, err = getPrecertByName(db, blockMyKeyDomain)
test.AssertNotError(t, err, "failed to get certificate by name")
err = expectOCSP500(cert)
test.AssertNotError(t, err, "expected 500 error from OCSP")
// Time to revoke! We'll do it by creating a different, successful certificate
// with the same key, then revoking that certificate for keyCompromise.
revokeClient, err := makeClient()
test.AssertNotError(t, err, "creating second acme client")
res, err := authAndIssue(nil, certKey, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
test.AssertNotError(t, err, "issuing second cert")
successfulCert := res.certs[0]
successfulCertIssuer := res.certs[1]
err = revokeClient.RevokeCertificate(
revokeClient.Account,
successfulCert,
certKey,
1,
)
test.AssertNotError(t, err, "revoking second certificate")
runUpdater(t, path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "crl-updater.json"))
fetchAndCheckRevoked(t, successfulCert, successfulCertIssuer, ocsp.KeyCompromise)
for range 300 {
_, err = ocsp_helper.Req(successfulCert,
ocspConf().WithExpectStatus(ocsp.Revoked).WithExpectReason(ocsp.KeyCompromise))
if err == nil {
break
}
time.Sleep(15 * time.Millisecond)
}
test.AssertNotError(t, err, "expected status to eventually become revoked")
// Try to issue again with the same key, expecting an error because of the key is blocked.
_, err = authAndIssue(nil, certKey, []acme.Identifier{{Type: "dns", Value: "123.example.com"}}, true, "")
test.AssertError(t, err, "expected authAndIssue to fail")
if !strings.Contains(err.Error(), "public key is forbidden") {
t.Errorf("expected issuance to be rejected with a bad pubkey")
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/key_rollover_test.go | third-party/github.com/letsencrypt/boulder/test/integration/key_rollover_test.go | //go:build integration
package integration
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"testing"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/test"
)
// TestAccountKeyChange tests that the whole account key rollover process works,
// including between different kinds of keys.
func TestAccountKeyChange(t *testing.T) {
t.Parallel()
c, err := acme.NewClient("http://boulder.service.consul:4001/directory")
test.AssertNotError(t, err, "creating client")
// We could test all five key types (RSA 2048, 3072, and 4096, and ECDSA P-256
// and P-384) supported by go-jose and goodkey, but doing so results in a very
// slow integration test. Instead, just test rollover once in each direction,
// ECDSA->RSA and vice versa.
key1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating P-256 account key")
acct1, err := c.NewAccount(key1, false, true)
test.AssertNotError(t, err, "creating account")
key2, err := rsa.GenerateKey(rand.Reader, 2048)
test.AssertNotError(t, err, "creating RSA 2048 account key")
acct2, err := c.AccountKeyChange(acct1, key2)
test.AssertNotError(t, err, "rolling over account key")
test.AssertEquals(t, acct2.URL, acct1.URL)
key3, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
test.AssertNotError(t, err, "creating P-384 account key")
acct3, err := c.AccountKeyChange(acct1, key3)
test.AssertNotError(t, err, "rolling over account key")
test.AssertEquals(t, acct3.URL, acct1.URL)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/common_test.go | third-party/github.com/letsencrypt/boulder/test/integration/common_test.go | //go:build integration
package integration
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/hex"
"fmt"
"net"
"os"
challTestSrvClient "github.com/letsencrypt/boulder/test/chall-test-srv-client"
"github.com/eggsampler/acme/v3"
)
var testSrvClient = challTestSrvClient.NewClient("")
func init() {
// Go tests get run in the directory their source code lives in. For these
// test cases, that would be "test/integration." However, it's easier to
// reference test data and config files for integration tests relative to the
// root of the Boulder repo, so we run all of these tests from there instead.
os.Chdir("../../")
}
var (
OIDExtensionCTPoison = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3}
)
func random_domain() string {
var bytes [3]byte
rand.Read(bytes[:])
return hex.EncodeToString(bytes[:]) + ".com"
}
type client struct {
acme.Account
acme.Client
}
func makeClient(contacts ...string) (*client, error) {
c, err := acme.NewClient("http://boulder.service.consul:4001/directory")
if err != nil {
return nil, fmt.Errorf("Error connecting to acme directory: %v", err)
}
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, fmt.Errorf("error creating private key: %v", err)
}
account, err := c.NewAccount(privKey, false, true, contacts...)
if err != nil {
return nil, err
}
return &client{account, c}, nil
}
func makeClientAndOrder(c *client, csrKey *ecdsa.PrivateKey, idents []acme.Identifier, cn bool, profile string, certToReplace *x509.Certificate) (*client, *acme.Order, error) {
var err error
if c == nil {
c, err = makeClient()
if err != nil {
return nil, nil, err
}
}
var order acme.Order
if certToReplace != nil {
order, err = c.Client.ReplacementOrderExtension(c.Account, certToReplace, idents, acme.OrderExtension{Profile: profile})
} else {
order, err = c.Client.NewOrderExtension(c.Account, idents, acme.OrderExtension{Profile: profile})
}
if err != nil {
return nil, nil, err
}
for _, authUrl := range order.Authorizations {
auth, err := c.Client.FetchAuthorization(c.Account, authUrl)
if err != nil {
return nil, nil, fmt.Errorf("fetching authorization at %s: %s", authUrl, err)
}
chal, ok := auth.ChallengeMap[acme.ChallengeTypeHTTP01]
if !ok {
return nil, nil, fmt.Errorf("no HTTP challenge at %s", authUrl)
}
_, err = testSrvClient.AddHTTP01Response(chal.Token, chal.KeyAuthorization)
if err != nil {
return nil, nil, err
}
chal, err = c.Client.UpdateChallenge(c.Account, chal)
if err != nil {
testSrvClient.RemoveHTTP01Response(chal.Token)
return nil, nil, err
}
_, err = testSrvClient.RemoveHTTP01Response(chal.Token)
if err != nil {
return nil, nil, err
}
}
csr, err := makeCSR(csrKey, idents, cn)
if err != nil {
return nil, nil, err
}
order, err = c.Client.FinalizeOrder(c.Account, order, csr)
if err != nil {
return nil, nil, fmt.Errorf("finalizing order: %s", err)
}
return c, &order, nil
}
type issuanceResult struct {
acme.Order
certs []*x509.Certificate
}
func authAndIssue(c *client, csrKey *ecdsa.PrivateKey, idents []acme.Identifier, cn bool, profile string) (*issuanceResult, error) {
var err error
c, order, err := makeClientAndOrder(c, csrKey, idents, cn, profile, nil)
if err != nil {
return nil, err
}
certs, err := c.Client.FetchCertificates(c.Account, order.Certificate)
if err != nil {
return nil, fmt.Errorf("fetching certificates: %s", err)
}
return &issuanceResult{*order, certs}, nil
}
type issuanceResultAllChains struct {
acme.Order
certs map[string][]*x509.Certificate
}
func authAndIssueFetchAllChains(c *client, csrKey *ecdsa.PrivateKey, idents []acme.Identifier, cn bool) (*issuanceResultAllChains, error) {
c, order, err := makeClientAndOrder(c, csrKey, idents, cn, "", nil)
if err != nil {
return nil, err
}
// Retrieve all the certificate chains served by the WFE2.
certs, err := c.Client.FetchAllCertificates(c.Account, order.Certificate)
if err != nil {
return nil, fmt.Errorf("fetching certificates: %s", err)
}
return &issuanceResultAllChains{*order, certs}, nil
}
func makeCSR(k *ecdsa.PrivateKey, idents []acme.Identifier, cn bool) (*x509.CertificateRequest, error) {
var err error
if k == nil {
k, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, fmt.Errorf("generating certificate key: %s", err)
}
}
var names []string
var ips []net.IP
for _, ident := range idents {
switch ident.Type {
case "dns":
names = append(names, ident.Value)
case "ip":
ips = append(ips, net.ParseIP(ident.Value))
default:
return nil, fmt.Errorf("unrecognized identifier type %q", ident.Type)
}
}
tmpl := &x509.CertificateRequest{
SignatureAlgorithm: x509.ECDSAWithSHA256,
PublicKeyAlgorithm: x509.ECDSA,
PublicKey: k.Public(),
DNSNames: names,
IPAddresses: ips,
}
if cn && len(names) > 0 {
tmpl.Subject = pkix.Name{CommonName: names[0]}
}
csrDer, err := x509.CreateCertificateRequest(rand.Reader, tmpl, k)
if err != nil {
return nil, fmt.Errorf("making csr: %s", err)
}
csr, err := x509.ParseCertificateRequest(csrDer)
if err != nil {
return nil, fmt.Errorf("parsing csr: %s", err)
}
return csr, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/ratelimit_test.go | third-party/github.com/letsencrypt/boulder/test/integration/ratelimit_test.go | //go:build integration
package integration
import (
"crypto/rand"
"encoding/hex"
"fmt"
"os"
"testing"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/test"
)
func TestDuplicateFQDNRateLimit(t *testing.T) {
t.Parallel()
idents := []acme.Identifier{{Type: "dns", Value: random_domain()}}
// TODO(#8235): Remove this conditional once IP address identifiers are
// enabled in test/config.
if os.Getenv("BOULDER_CONFIG_DIR") == "test/config-next" {
idents = append(idents, acme.Identifier{Type: "ip", Value: "64.112.117.122"})
}
// The global rate limit for a duplicate certificates is 2 per 3 hours.
_, err := authAndIssue(nil, nil, idents, true, "shortlived")
test.AssertNotError(t, err, "Failed to issue first certificate")
_, err = authAndIssue(nil, nil, idents, true, "shortlived")
test.AssertNotError(t, err, "Failed to issue second certificate")
_, err = authAndIssue(nil, nil, idents, true, "shortlived")
test.AssertError(t, err, "Somehow managed to issue third certificate")
test.AssertContains(t, err.Error(), "too many certificates (2) already issued for this exact set of identifiers in the last 3h0m0s")
}
func TestCertificatesPerDomain(t *testing.T) {
t.Parallel()
randomDomain := random_domain()
randomSubDomain := func() string {
var bytes [3]byte
rand.Read(bytes[:])
return fmt.Sprintf("%s.%s", hex.EncodeToString(bytes[:]), randomDomain)
}
firstSubDomain := randomSubDomain()
_, err := authAndIssue(nil, nil, []acme.Identifier{{Type: "dns", Value: firstSubDomain}}, true, "")
test.AssertNotError(t, err, "Failed to issue first certificate")
_, err = authAndIssue(nil, nil, []acme.Identifier{{Type: "dns", Value: randomSubDomain()}}, true, "")
test.AssertNotError(t, err, "Failed to issue second certificate")
_, err = authAndIssue(nil, nil, []acme.Identifier{{Type: "dns", Value: randomSubDomain()}}, true, "")
test.AssertError(t, err, "Somehow managed to issue third certificate")
test.AssertContains(t, err.Error(), fmt.Sprintf("too many certificates (2) already issued for %q in the last 2160h0m0s", randomDomain))
// Issue a certificate for the first subdomain, which should succeed because
// it's a renewal.
_, err = authAndIssue(nil, nil, []acme.Identifier{{Type: "dns", Value: firstSubDomain}}, true, "")
test.AssertNotError(t, err, "Failed to issue renewal certificate")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/errors_test.go | third-party/github.com/letsencrypt/boulder/test/integration/errors_test.go | //go:build integration
package integration
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"slices"
"strings"
"testing"
"github.com/eggsampler/acme/v3"
"github.com/go-jose/go-jose/v4"
"github.com/letsencrypt/boulder/test"
)
// TestTooBigOrderError tests that submitting an order with more than 100
// identifiers produces the expected problem result.
func TestTooBigOrderError(t *testing.T) {
t.Parallel()
var idents []acme.Identifier
for i := range 101 {
idents = append(idents, acme.Identifier{Type: "dns", Value: fmt.Sprintf("%d.example.com", i)})
}
_, err := authAndIssue(nil, nil, idents, true, "")
test.AssertError(t, err, "authAndIssue failed")
var prob acme.Problem
test.AssertErrorWraps(t, err, &prob)
test.AssertEquals(t, prob.Type, "urn:ietf:params:acme:error:malformed")
test.AssertContains(t, prob.Detail, "Order cannot contain more than 100 identifiers")
}
// TestAccountEmailError tests that registering a new account, or updating an
// account, with invalid contact information produces the expected problem
// result to ACME clients.
func TestAccountEmailError(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
contacts []string
expectedProbType string
expectedProbDetail string
}{
{
name: "empty contact",
contacts: []string{"mailto:valid@valid.com", ""},
expectedProbType: "urn:ietf:params:acme:error:invalidContact",
expectedProbDetail: `empty contact`,
},
{
name: "empty proto",
contacts: []string{"mailto:valid@valid.com", " "},
expectedProbType: "urn:ietf:params:acme:error:unsupportedContact",
expectedProbDetail: `only contact scheme 'mailto:' is supported`,
},
{
name: "empty mailto",
contacts: []string{"mailto:valid@valid.com", "mailto:"},
expectedProbType: "urn:ietf:params:acme:error:invalidContact",
expectedProbDetail: `unable to parse email address`,
},
{
name: "non-ascii mailto",
contacts: []string{"mailto:valid@valid.com", "mailto:cpu@l̴etsencrypt.org"},
expectedProbType: "urn:ietf:params:acme:error:invalidContact",
expectedProbDetail: `contact email contains non-ASCII characters`,
},
{
name: "too many contacts",
contacts: slices.Repeat([]string{"mailto:lots@valid.com"}, 11),
expectedProbType: "urn:ietf:params:acme:error:malformed",
expectedProbDetail: `too many contacts provided`,
},
{
name: "invalid contact",
contacts: []string{"mailto:valid@valid.com", "mailto:a@"},
expectedProbType: "urn:ietf:params:acme:error:invalidContact",
expectedProbDetail: `unable to parse email address`,
},
{
name: "forbidden contact domain",
contacts: []string{"mailto:valid@valid.com", "mailto:a@example.com"},
expectedProbType: "urn:ietf:params:acme:error:invalidContact",
expectedProbDetail: "contact email has forbidden domain \"example.com\"",
},
{
name: "contact domain invalid TLD",
contacts: []string{"mailto:valid@valid.com", "mailto:a@example.cpu"},
expectedProbType: "urn:ietf:params:acme:error:invalidContact",
expectedProbDetail: `contact email has invalid domain: Domain name does not end with a valid public suffix (TLD)`,
},
{
name: "contact domain invalid",
contacts: []string{"mailto:valid@valid.com", "mailto:a@example./.com"},
expectedProbType: "urn:ietf:params:acme:error:invalidContact",
expectedProbDetail: "contact email has invalid domain: Domain name contains an invalid character",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
var prob acme.Problem
_, err := makeClient(tc.contacts...)
if err != nil {
test.AssertErrorWraps(t, err, &prob)
test.AssertEquals(t, prob.Type, tc.expectedProbType)
test.AssertContains(t, prob.Detail, "Error validating contact(s)")
test.AssertContains(t, prob.Detail, tc.expectedProbDetail)
} else {
t.Errorf("expected %s type problem for %q, got nil",
tc.expectedProbType, strings.Join(tc.contacts, ","))
}
})
}
}
func TestRejectedIdentifier(t *testing.T) {
t.Parallel()
// When a single malformed name is provided, we correctly reject it.
idents := []acme.Identifier{
{Type: "dns", Value: "яџ–Х6яяdь}"},
}
_, err := authAndIssue(nil, nil, idents, true, "")
test.AssertError(t, err, "issuance should fail for one malformed name")
var prob acme.Problem
test.AssertErrorWraps(t, err, &prob)
test.AssertEquals(t, prob.Type, "urn:ietf:params:acme:error:rejectedIdentifier")
test.AssertContains(t, prob.Detail, "Domain name contains an invalid character")
// When multiple malformed names are provided, we correctly reject all of
// them and reflect this in suberrors. This test ensures that the way we
// encode these errors across the gRPC boundary is resilient to non-ascii
// characters.
idents = []acme.Identifier{
{Type: "dns", Value: "o-"},
{Type: "dns", Value: "ш№Ў"},
{Type: "dns", Value: "р±y"},
{Type: "dns", Value: "яџ–Х6яя"},
{Type: "dns", Value: "яџ–Х6яя`ь"},
}
_, err = authAndIssue(nil, nil, idents, true, "")
test.AssertError(t, err, "issuance should fail for multiple malformed names")
test.AssertErrorWraps(t, err, &prob)
test.AssertEquals(t, prob.Type, "urn:ietf:params:acme:error:rejectedIdentifier")
test.AssertContains(t, prob.Detail, "Domain name contains an invalid character")
test.AssertContains(t, prob.Detail, "and 4 more problems")
}
// TestBadSignatureAlgorithm tests that supplying an unacceptable value for the
// "alg" field of the JWS Protected Header results in a problem document with
// the set of acceptable "alg" values listed in a custom extension field named
// "algorithms". Creating a request with an unacceptable "alg" field requires
// us to do some shenanigans.
func TestBadSignatureAlgorithm(t *testing.T) {
t.Parallel()
client, err := makeClient()
if err != nil {
t.Fatal("creating test client")
}
header, err := json.Marshal(&struct {
Alg string `json:"alg"`
KID string `json:"kid"`
Nonce string `json:"nonce"`
URL string `json:"url"`
}{
Alg: string(jose.RS512), // This is the important bit; RS512 is unacceptable.
KID: client.Account.URL,
Nonce: "deadbeef", // This nonce would fail, but that check comes after the alg check.
URL: client.Directory().NewAccount,
})
if err != nil {
t.Fatalf("creating JWS protected header: %s", err)
}
protected := base64.RawURLEncoding.EncodeToString(header)
payload := base64.RawURLEncoding.EncodeToString([]byte(`{"onlyReturnExisting": true}`))
hash := crypto.SHA512.New()
hash.Write([]byte(protected + "." + payload))
sig, err := client.Account.PrivateKey.Sign(rand.Reader, hash.Sum(nil), crypto.SHA512)
if err != nil {
t.Fatalf("creating fake signature: %s", err)
}
data, err := json.Marshal(&struct {
Protected string `json:"protected"`
Payload string `json:"payload"`
Signature string `json:"signature"`
}{
Protected: protected,
Payload: payload,
Signature: base64.RawURLEncoding.EncodeToString(sig),
})
req, err := http.NewRequest(http.MethodPost, client.Directory().NewAccount, bytes.NewReader(data))
if err != nil {
t.Fatalf("creating HTTP request: %s", err)
}
req.Header.Set("Content-Type", "application/jose+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("making HTTP request: %s", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("reading HTTP response: %s", err)
}
var prob struct {
Type string `json:"type"`
Detail string `json:"detail"`
Status int `json:"status"`
Algorithms []jose.SignatureAlgorithm `json:"algorithms"`
}
err = json.Unmarshal(body, &prob)
if err != nil {
t.Fatalf("parsing HTTP response: %s", err)
}
if prob.Type != "urn:ietf:params:acme:error:badSignatureAlgorithm" {
t.Errorf("problem document has wrong type: want badSignatureAlgorithm, got %s", prob.Type)
}
if prob.Status != http.StatusBadRequest {
t.Errorf("problem document has wrong status: want 400, got %d", prob.Status)
}
if len(prob.Algorithms) == 0 {
t.Error("problem document MUST contain acceptable algorithms, got none")
}
}
// TestOrderFinalizeEarly tests that finalizing an order before it is fully
// authorized results in an orderNotReady error.
func TestOrderFinalizeEarly(t *testing.T) {
t.Parallel()
client, err := makeClient()
if err != nil {
t.Fatalf("creating acme client: %s", err)
}
idents := []acme.Identifier{{Type: "dns", Value: randomDomain(t)}}
order, err := client.Client.NewOrder(client.Account, idents)
if err != nil {
t.Fatalf("creating order: %s", err)
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("generating key: %s", err)
}
csr, err := makeCSR(key, idents, false)
if err != nil {
t.Fatalf("generating CSR: %s", err)
}
order, err = client.Client.FinalizeOrder(client.Account, order, csr)
if err == nil {
t.Fatal("expected finalize to fail, but got success")
}
var prob acme.Problem
ok := errors.As(err, &prob)
if !ok {
t.Fatalf("expected error to be of type acme.Problem, got: %T", err)
}
if prob.Type != "urn:ietf:params:acme:error:orderNotReady" {
t.Errorf("expected problem type 'urn:ietf:params:acme:error:orderNotReady', got: %s", prob.Type)
}
if order.Status != "pending" {
t.Errorf("expected order status to be pending, got: %s", order.Status)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/akamai_purger_drain_queue_test.go | third-party/github.com/letsencrypt/boulder/test/integration/akamai_purger_drain_queue_test.go | //go:build integration
package integration
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"syscall"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/balancer/roundrobin"
"google.golang.org/grpc/connectivity"
akamaipb "github.com/letsencrypt/boulder/akamai/proto"
"github.com/letsencrypt/boulder/cmd"
bcreds "github.com/letsencrypt/boulder/grpc/creds"
"github.com/letsencrypt/boulder/metrics"
"github.com/letsencrypt/boulder/test"
)
func setup() (*exec.Cmd, *bytes.Buffer, akamaipb.AkamaiPurgerClient, error) {
purgerCmd := exec.Command("./bin/boulder", "akamai-purger", "--config", "test/integration/testdata/akamai-purger-queue-drain-config.json")
var outputBuffer bytes.Buffer
purgerCmd.Stdout = &outputBuffer
purgerCmd.Stderr = &outputBuffer
purgerCmd.Start()
// If we error, we need to kill the process we started or the test command
// will never exit.
sigterm := func() {
purgerCmd.Process.Signal(syscall.SIGTERM)
purgerCmd.Wait()
}
tlsConfig, err := (&cmd.TLSConfig{
CACertFile: "test/certs/ipki/minica.pem",
CertFile: "test/certs/ipki/ra.boulder/cert.pem",
KeyFile: "test/certs/ipki/ra.boulder/key.pem",
}).Load(metrics.NoopRegisterer)
if err != nil {
sigterm()
return nil, nil, nil, err
}
creds := bcreds.NewClientCredentials(tlsConfig.RootCAs, tlsConfig.Certificates, "akamai-purger.boulder")
conn, err := grpc.Dial(
"dns:///akamai-purger.service.consul:9199",
grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"loadBalancingConfig": [{"%s":{}}]}`, roundrobin.Name)),
grpc.WithTransportCredentials(creds),
)
if err != nil {
sigterm()
return nil, nil, nil, err
}
for i := range 42 {
if conn.GetState() == connectivity.Ready {
break
}
if i > 40 {
sigterm()
return nil, nil, nil, fmt.Errorf("timed out waiting for akamai-purger to come up: %s", outputBuffer.String())
}
time.Sleep(50 * time.Millisecond)
}
purgerClient := akamaipb.NewAkamaiPurgerClient(conn)
return purgerCmd, &outputBuffer, purgerClient, nil
}
func TestAkamaiPurgerDrainQueueFails(t *testing.T) {
purgerCmd, outputBuffer, purgerClient, err := setup()
if err != nil {
t.Fatal(err)
}
// We know that the purger is configured to only process two items per batch,
// so submitting 10 items should give it enough of a backlog to guarantee
// that our SIGTERM reaches the process before it's fully cleared the queue.
for i := range 10 {
_, err = purgerClient.Purge(context.Background(), &akamaipb.PurgeRequest{
Urls: []string{fmt.Sprintf("http://example%d.com/", i)},
})
if err != nil {
// Don't use t.Fatal here because we need to get as far as the SIGTERM or
// we'll hang on exit.
t.Error(err)
}
}
purgerCmd.Process.Signal(syscall.SIGTERM)
err = purgerCmd.Wait()
if err == nil {
t.Error("expected error shutting down akamai-purger that could not reach backend")
}
// Use two asserts because we're not sure what integer (10? 8?) will come in
// the middle of the error message.
test.AssertContains(t, outputBuffer.String(), "failed to purge OCSP responses for")
test.AssertContains(t, outputBuffer.String(), "certificates before exit: all attempts to submit purge request failed")
}
func TestAkamaiPurgerDrainQueueSucceeds(t *testing.T) {
purgerCmd, outputBuffer, purgerClient, err := setup()
if err != nil {
t.Fatal(err)
}
for range 10 {
_, err := purgerClient.Purge(context.Background(), &akamaipb.PurgeRequest{
Urls: []string{"http://example.com/"},
})
if err != nil {
t.Error(err)
}
}
time.Sleep(200 * time.Millisecond)
purgerCmd.Process.Signal(syscall.SIGTERM)
akamaiTestSrvCmd := exec.Command("./bin/akamai-test-srv", "--listen", "localhost:6889",
"--secret", "its-a-secret")
akamaiTestSrvCmd.Stdout = os.Stdout
akamaiTestSrvCmd.Stderr = os.Stderr
akamaiTestSrvCmd.Start()
err = purgerCmd.Wait()
if err != nil {
t.Errorf("unexpected error shutting down akamai-purger: %s. Output was:\n%s", err, outputBuffer.String())
}
test.AssertContains(t, outputBuffer.String(), "Shutting down; finished purging OCSP responses")
akamaiTestSrvCmd.Process.Signal(syscall.SIGTERM)
_ = akamaiTestSrvCmd.Wait()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/observer_test.go | third-party/github.com/letsencrypt/boulder/test/integration/observer_test.go | //go:build integration
package integration
import (
"bufio"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/eggsampler/acme/v3"
)
func streamOutput(t *testing.T, c *exec.Cmd) (<-chan string, func()) {
t.Helper()
outChan := make(chan string)
stdout, err := c.StdoutPipe()
if err != nil {
t.Fatalf("getting stdout handle: %s", err)
}
outScanner := bufio.NewScanner(stdout)
go func() {
for outScanner.Scan() {
outChan <- outScanner.Text()
}
}()
stderr, err := c.StderrPipe()
if err != nil {
t.Fatalf("getting stderr handle: %s", err)
}
errScanner := bufio.NewScanner(stderr)
go func() {
for errScanner.Scan() {
outChan <- errScanner.Text()
}
}()
err = c.Start()
if err != nil {
t.Fatalf("starting cmd: %s", err)
}
return outChan, func() {
c.Cancel()
c.Wait()
}
}
func TestTLSProbe(t *testing.T) {
t.Parallel()
// We can't use random_domain(), because the observer needs to be able to
// resolve this hostname within the docker-compose environment.
hostname := "integration.trust"
tempdir := t.TempDir()
// Create the certificate that the prober will inspect.
client, err := makeClient()
if err != nil {
t.Fatalf("creating test acme client: %s", err)
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("generating test key: %s", err)
}
res, err := authAndIssue(client, key, []acme.Identifier{{Type: "dns", Value: hostname}}, true, "")
if err != nil {
t.Fatalf("issuing test cert: %s", err)
}
// Set up the HTTP server that the prober will be pointed at.
certFile, err := os.Create(path.Join(tempdir, "fullchain.pem"))
if err != nil {
t.Fatalf("creating cert file: %s", err)
}
err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: res.certs[0].Raw})
if err != nil {
t.Fatalf("writing test cert to file: %s", err)
}
err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: res.certs[1].Raw})
if err != nil {
t.Fatalf("writing test issuer cert to file: %s", err)
}
err = certFile.Close()
if err != nil {
t.Errorf("closing cert file: %s", err)
}
keyFile, err := os.Create(path.Join(tempdir, "privkey.pem"))
if err != nil {
t.Fatalf("creating key file: %s", err)
}
keyDER, err := x509.MarshalECPrivateKey(key)
if err != nil {
t.Fatalf("marshalling test key: %s", err)
}
err = pem.Encode(keyFile, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
if err != nil {
t.Fatalf("writing test key to file: %s", err)
}
err = keyFile.Close()
if err != nil {
t.Errorf("closing key file: %s", err)
}
go http.ListenAndServeTLS(":8675", certFile.Name(), keyFile.Name(), http.DefaultServeMux)
// Kick off the prober, pointed at the server presenting our test cert.
configFile, err := os.Create(path.Join(tempdir, "observer.yml"))
if err != nil {
t.Fatalf("creating config file: %s", err)
}
_, err = configFile.WriteString(fmt.Sprintf(`---
buckets: [.001, .002, .005, .01, .02, .05, .1, .2, .5, 1, 2, 5, 10]
syslog:
stdoutlevel: 6
sysloglevel: 0
monitors:
-
period: 1s
kind: TLS
settings:
response: valid
hostname: "%s:8675"`, hostname))
if err != nil {
t.Fatalf("writing test config: %s", err)
}
binPath, err := filepath.Abs("bin/boulder")
if err != nil {
t.Fatalf("computing boulder binary path: %s", err)
}
c := exec.CommandContext(context.Background(), binPath, "boulder-observer", "-config", configFile.Name(), "-debug-addr", ":8024")
output, cancel := streamOutput(t, c)
defer cancel()
timeout := time.NewTimer(5 * time.Second)
for {
select {
case <-timeout.C:
t.Fatalf("timed out before getting desired log line from boulder-observer")
case line := <-output:
t.Log(line)
if strings.Contains(line, "name=[integration.trust:8675]") && strings.Contains(line, "success=[true]") {
return
}
}
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/revocation_test.go | third-party/github.com/letsencrypt/boulder/test/integration/revocation_test.go | //go:build integration
package integration
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"strings"
"sync"
"testing"
"time"
"github.com/eggsampler/acme/v3"
"golang.org/x/crypto/ocsp"
"github.com/letsencrypt/boulder/core"
"github.com/letsencrypt/boulder/crl/idp"
"github.com/letsencrypt/boulder/revocation"
"github.com/letsencrypt/boulder/test"
ocsp_helper "github.com/letsencrypt/boulder/test/ocsp/helper"
)
// isPrecert returns true if the provided cert has an extension with the OID
// equal to OIDExtensionCTPoison.
func isPrecert(cert *x509.Certificate) bool {
for _, ext := range cert.Extensions {
if ext.Id.Equal(OIDExtensionCTPoison) {
return true
}
}
return false
}
// ocspConf returns an OCSP helper config with a fallback URL that matches what is
// configured for our CA / OCSP responder. If an OCSP URL is present in a certificate,
// ocsp_helper will use that; otherwise it will use the URLFallback. This allows
// continuing to test OCSP service even after we stop including OCSP URLs in certificates.
func ocspConf() ocsp_helper.Config {
return ocsp_helper.DefaultConfig.WithURLFallback("http://ca.example.org:4002/")
}
// getALLCRLs fetches and parses each certificate for each configured CA.
// Returns a map from issuer SKID (hex) to a list of that issuer's CRLs.
func getAllCRLs(t *testing.T) map[string][]*x509.RevocationList {
t.Helper()
b, err := os.ReadFile(path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "ca.json"))
if err != nil {
t.Fatalf("reading CA config: %s", err)
}
var conf struct {
CA struct {
Issuance struct {
Issuers []struct {
CRLURLBase string
Location struct {
CertFile string
}
}
}
}
}
err = json.Unmarshal(b, &conf)
if err != nil {
t.Fatalf("unmarshaling CA config: %s", err)
}
ret := make(map[string][]*x509.RevocationList)
for _, issuer := range conf.CA.Issuance.Issuers {
issuerPEMBytes, err := os.ReadFile(issuer.Location.CertFile)
if err != nil {
t.Fatalf("reading CRL issuer: %s", err)
}
block, _ := pem.Decode(issuerPEMBytes)
issuerCert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
t.Fatalf("parsing CRL issuer: %s", err)
}
issuerSKID := hex.EncodeToString(issuerCert.SubjectKeyId)
// 10 is the number of shards configured in test/config*/crl-updater.json
for i := range 10 {
crlURL := fmt.Sprintf("%s%d.crl", issuer.CRLURLBase, i+1)
list := getCRL(t, crlURL, issuerCert)
ret[issuerSKID] = append(ret[issuerSKID], list)
}
}
return ret
}
// getCRL fetches a CRL, parses it, and checks the signature.
func getCRL(t *testing.T, crlURL string, issuerCert *x509.Certificate) *x509.RevocationList {
t.Helper()
resp, err := http.Get(crlURL)
if err != nil {
t.Fatalf("getting CRL from %s: %s", crlURL, err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("fetching %s: status code %d", crlURL, resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("reading CRL from %s: %s", crlURL, err)
}
resp.Body.Close()
list, err := x509.ParseRevocationList(body)
if err != nil {
t.Fatalf("parsing CRL from %s: %s (bytes: %x)", crlURL, err, body)
}
err = list.CheckSignatureFrom(issuerCert)
if err != nil {
t.Errorf("checking CRL signature on %s from %s: %s",
crlURL, issuerCert.Subject, err)
}
idpURIs, err := idp.GetIDPURIs(list.Extensions)
if err != nil {
t.Fatalf("getting IDP URIs: %s", err)
}
if len(idpURIs) != 1 {
t.Errorf("CRL at %s: expected 1 IDP URI, got %s", crlURL, idpURIs)
}
if idpURIs[0] != crlURL {
t.Errorf("fetched CRL from %s, got IDP of %s (should be same)", crlURL, idpURIs[0])
}
return list
}
func fetchAndCheckRevoked(t *testing.T, cert, issuer *x509.Certificate, expectedReason int) {
t.Helper()
if len(cert.CRLDistributionPoints) != 1 {
t.Errorf("expected certificate to have one CRLDistributionPoints field")
}
crlURL := cert.CRLDistributionPoints[0]
list := getCRL(t, crlURL, issuer)
for _, entry := range list.RevokedCertificateEntries {
if entry.SerialNumber.Cmp(cert.SerialNumber) == 0 {
if entry.ReasonCode != expectedReason {
t.Errorf("serial %x found on CRL %s with reason %d, want %d", entry.SerialNumber, crlURL, entry.ReasonCode, expectedReason)
}
return
}
}
t.Errorf("serial %x not found on CRL %s, expected it to be revoked with reason %d", cert.SerialNumber, crlURL, expectedReason)
}
func checkUnrevoked(t *testing.T, revocations map[string][]*x509.RevocationList, cert *x509.Certificate) {
for _, singleIssuerCRLs := range revocations {
for _, crl := range singleIssuerCRLs {
for _, entry := range crl.RevokedCertificateEntries {
if entry.SerialNumber == cert.SerialNumber {
t.Errorf("expected %x to be unrevoked, but found it on a CRL", cert.SerialNumber)
}
}
}
}
}
func checkRevoked(t *testing.T, revocations map[string][]*x509.RevocationList, cert *x509.Certificate, expectedReason int) {
t.Helper()
akid := hex.EncodeToString(cert.AuthorityKeyId)
if len(revocations[akid]) == 0 {
t.Errorf("no CRLs found for authorityKeyID %s", akid)
}
var matchingCRLs []string
var count int
for _, list := range revocations[akid] {
for _, entry := range list.RevokedCertificateEntries {
count++
if entry.SerialNumber.Cmp(cert.SerialNumber) == 0 {
idpURIs, err := idp.GetIDPURIs(list.Extensions)
if err != nil {
t.Errorf("getting IDP URIs: %s", err)
}
idpURI := idpURIs[0]
if entry.ReasonCode != expectedReason {
t.Errorf("revoked certificate %x in CRL %s: revocation reason %d, want %d", cert.SerialNumber, idpURI, entry.ReasonCode, expectedReason)
}
matchingCRLs = append(matchingCRLs, idpURI)
}
}
}
if len(matchingCRLs) == 0 {
t.Errorf("searching for %x in CRLs: no entry on combined CRLs of length %d", cert.SerialNumber, count)
}
// If the cert has a CRLDP, it must be listed on the CRL served at that URL.
if len(cert.CRLDistributionPoints) > 0 {
expectedCRLDP := cert.CRLDistributionPoints[0]
found := false
for _, crl := range matchingCRLs {
if crl == expectedCRLDP {
found = true
}
}
if !found {
t.Errorf("revoked certificate %x: seen on CRLs %s, want to see on CRL %s", cert.SerialNumber, matchingCRLs, expectedCRLDP)
}
}
}
// TestRevocation tests that a certificate can be revoked using all of the
// RFC 8555 revocation authentication mechanisms. It does so for both certs and
// precerts (with no corresponding final cert), and for both the Unspecified and
// keyCompromise revocation reasons.
func TestRevocation(t *testing.T) {
type authMethod string
var (
byAccount authMethod = "byAccount"
byAuth authMethod = "byAuth"
byKey authMethod = "byKey"
byAdmin authMethod = "byAdmin"
)
type certKind string
var (
finalcert certKind = "cert"
precert certKind = "precert"
)
type testCase struct {
method authMethod
reason int
kind certKind
}
issueAndRevoke := func(tc testCase) *x509.Certificate {
issueClient, err := makeClient()
test.AssertNotError(t, err, "creating acme client")
certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
domain := random_domain()
// Try to issue a certificate for the name.
var cert *x509.Certificate
switch tc.kind {
case finalcert:
res, err := authAndIssue(issueClient, certKey, []acme.Identifier{{Type: "dns", Value: domain}}, true, "")
test.AssertNotError(t, err, "authAndIssue failed")
cert = res.certs[0]
case precert:
// Make sure the ct-test-srv will reject generating SCTs for the domain,
// so we only get a precert and no final cert.
err := ctAddRejectHost(domain)
test.AssertNotError(t, err, "adding ct-test-srv reject host")
_, err = authAndIssue(issueClient, certKey, []acme.Identifier{{Type: "dns", Value: domain}}, true, "")
test.AssertError(t, err, "expected error from authAndIssue, was nil")
if !strings.Contains(err.Error(), "urn:ietf:params:acme:error:serverInternal") ||
!strings.Contains(err.Error(), "SCT embedding") {
t.Fatal(err)
}
// Instead recover the precertificate from CT.
cert, err = ctFindRejection([]string{domain})
if err != nil || cert == nil {
t.Fatalf("couldn't find rejected precert for %q", domain)
}
// And make sure the cert we found is in fact a precert.
if !isPrecert(cert) {
t.Fatal("precert was missing poison extension")
}
default:
t.Fatalf("unrecognized cert kind %q", tc.kind)
}
// Initially, the cert should have a Good OCSP response (only via OCSP; the CRL is unchanged by issuance).
ocspConfig := ocspConf().WithExpectStatus(ocsp.Good)
_, err = ocsp_helper.ReqDER(cert.Raw, ocspConfig)
test.AssertNotError(t, err, "requesting OCSP for precert")
// Set up the account and key that we'll use to revoke the cert.
switch tc.method {
case byAccount:
// When revoking by account, use the same client and key as were used
// for the original issuance.
err = issueClient.RevokeCertificate(
issueClient.Account,
cert,
issueClient.PrivateKey,
tc.reason,
)
test.AssertNotError(t, err, "revocation should have succeeded")
case byAuth:
// When revoking by auth, create a brand new client, authorize it for
// the same domain, and use that account and key for revocation. Ignore
// errors from authAndIssue because all we need is the auth, not the
// issuance.
newClient, err := makeClient()
test.AssertNotError(t, err, "creating second acme client")
_, _ = authAndIssue(newClient, certKey, []acme.Identifier{{Type: "dns", Value: domain}}, true, "")
err = newClient.RevokeCertificate(
newClient.Account,
cert,
newClient.PrivateKey,
tc.reason,
)
test.AssertNotError(t, err, "revocation should have succeeded")
case byKey:
// When revoking by key, create a brand new client and use it with
// the cert's key for revocation.
newClient, err := makeClient()
test.AssertNotError(t, err, "creating second acme client")
err = newClient.RevokeCertificate(
newClient.Account,
cert,
certKey,
tc.reason,
)
test.AssertNotError(t, err, "revocation should have succeeded")
case byAdmin:
// Invoke the admin tool to perform the revocation via gRPC, rather than
// using the external-facing ACME API.
config := fmt.Sprintf("%s/%s", os.Getenv("BOULDER_CONFIG_DIR"), "admin.json")
cmd := exec.Command(
"./bin/admin",
"-config", config,
"-dry-run=false",
"revoke-cert",
"-serial", core.SerialToString(cert.SerialNumber),
"-reason", revocation.ReasonToString[revocation.Reason(tc.reason)])
output, err := cmd.CombinedOutput()
t.Logf("admin revoke-cert output: %s\n", string(output))
test.AssertNotError(t, err, "revocation should have succeeded")
default:
t.Fatalf("unrecognized revocation method %q", tc.method)
}
return cert
}
// revocationCheck represents a deferred that a specific certificate is revoked.
//
// We defer these checks for performance reasons: we want to run crl-updater once,
// after all certificates have been revoked.
type revocationCheck func(t *testing.T, allCRLs map[string][]*x509.RevocationList)
var revocationChecks []revocationCheck
var rcMu sync.Mutex
var wg sync.WaitGroup
for _, kind := range []certKind{precert, finalcert} {
for _, reason := range []int{ocsp.Unspecified, ocsp.KeyCompromise, ocsp.Superseded} {
for _, method := range []authMethod{byAccount, byAuth, byKey, byAdmin} {
wg.Add(1)
go func() {
defer wg.Done()
cert := issueAndRevoke(testCase{
method: method,
reason: reason,
kind: kind,
// We do not expect any of these revocation requests to error.
// The ones done byAccount will succeed as requested, but will not
// result in the key being blocked for future issuance.
// The ones done byAuth will succeed, but will be overwritten to have
// reason code 5 (cessationOfOperation).
// The ones done byKey will succeed, but will be overwritten to have
// reason code 1 (keyCompromise), and will block the key.
})
// If the request was made by demonstrating control over the
// names, the reason should be overwritten to CessationOfOperation (5),
// and if the request was made by key, then the reason should be set to
// KeyCompromise (1).
expectedReason := reason
switch method {
case byAuth:
expectedReason = ocsp.CessationOfOperation
case byKey:
expectedReason = ocsp.KeyCompromise
default:
}
check := func(t *testing.T, allCRLs map[string][]*x509.RevocationList) {
ocspConfig := ocspConf().WithExpectStatus(ocsp.Revoked).WithExpectReason(expectedReason)
_, err := ocsp_helper.ReqDER(cert.Raw, ocspConfig)
test.AssertNotError(t, err, "requesting OCSP for revoked cert")
checkRevoked(t, allCRLs, cert, expectedReason)
}
rcMu.Lock()
revocationChecks = append(revocationChecks, check)
rcMu.Unlock()
}()
}
}
}
wg.Wait()
runUpdater(t, path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "crl-updater.json"))
allCRLs := getAllCRLs(t)
for _, check := range revocationChecks {
check(t, allCRLs)
}
}
// TestReRevocation verifies that a certificate can have its revocation
// information updated only when both of the following are true:
// a) The certificate was not initially revoked for reason keyCompromise; and
// b) The second request is authenticated using the cert's keypair.
// In which case the revocation reason (but not revocation date) will be
// updated to be keyCompromise.
func TestReRevocation(t *testing.T) {
type authMethod string
var (
byAccount authMethod = "byAccount"
byKey authMethod = "byKey"
)
type testCase struct {
method1 authMethod
reason1 int
method2 authMethod
reason2 int
expectError bool
}
testCases := []testCase{
{method1: byAccount, reason1: 0, method2: byAccount, reason2: 0, expectError: true},
{method1: byAccount, reason1: 1, method2: byAccount, reason2: 1, expectError: true},
{method1: byAccount, reason1: 0, method2: byKey, reason2: 1, expectError: false},
{method1: byAccount, reason1: 1, method2: byKey, reason2: 1, expectError: true},
{method1: byKey, reason1: 1, method2: byKey, reason2: 1, expectError: true},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
issueClient, err := makeClient()
test.AssertNotError(t, err, "creating acme client")
certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// Try to issue a certificate for the name.
res, err := authAndIssue(issueClient, certKey, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
test.AssertNotError(t, err, "authAndIssue failed")
cert := res.certs[0]
issuer := res.certs[1]
// Initially, the cert should have a Good OCSP response (only via OCSP; the CRL is unchanged by issuance).
ocspConfig := ocspConf().WithExpectStatus(ocsp.Good)
_, err = ocsp_helper.ReqDER(cert.Raw, ocspConfig)
test.AssertNotError(t, err, "requesting OCSP for precert")
// Set up the account and key that we'll use to revoke the cert.
var revokeClient *client
var revokeKey crypto.Signer
switch tc.method1 {
case byAccount:
// When revoking by account, use the same client and key as were used
// for the original issuance.
revokeClient = issueClient
revokeKey = revokeClient.PrivateKey
case byKey:
// When revoking by key, create a brand new client and use it with
// the cert's key for revocation.
revokeClient, err = makeClient()
test.AssertNotError(t, err, "creating second acme client")
revokeKey = certKey
default:
t.Fatalf("unrecognized revocation method %q", tc.method1)
}
// Revoke the cert using the specified key and client.
err = revokeClient.RevokeCertificate(
revokeClient.Account,
cert,
revokeKey,
tc.reason1,
)
test.AssertNotError(t, err, "initial revocation should have succeeded")
// Check the CRL for the certificate again. It should now be
// revoked.
runUpdater(t, path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "crl-updater.json"))
fetchAndCheckRevoked(t, cert, issuer, tc.reason1)
// Set up the account and key that we'll use to *re*-revoke the cert.
switch tc.method2 {
case byAccount:
// When revoking by account, use the same client and key as were used
// for the original issuance.
revokeClient = issueClient
revokeKey = revokeClient.PrivateKey
case byKey:
// When revoking by key, create a brand new client and use it with
// the cert's key for revocation.
revokeClient, err = makeClient()
test.AssertNotError(t, err, "creating second acme client")
revokeKey = certKey
default:
t.Fatalf("unrecognized revocation method %q", tc.method2)
}
// Re-revoke the cert using the specified key and client.
err = revokeClient.RevokeCertificate(
revokeClient.Account,
cert,
revokeKey,
tc.reason2,
)
switch tc.expectError {
case true:
test.AssertError(t, err, "second revocation should have failed")
// Check the OCSP response for the certificate again. It should still be
// revoked, with the same reason.
ocspConfig := ocspConf().WithExpectStatus(ocsp.Revoked).WithExpectReason(tc.reason1)
_, err = ocsp_helper.ReqDER(cert.Raw, ocspConfig)
// Check the CRL for the certificate again. It should still be
// revoked, with the same reason.
runUpdater(t, path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "crl-updater.json"))
fetchAndCheckRevoked(t, cert, issuer, tc.reason1)
case false:
test.AssertNotError(t, err, "second revocation should have succeeded")
// Check the OCSP response for the certificate again. It should now be
// revoked with reason keyCompromise.
ocspConfig := ocspConf().WithExpectStatus(ocsp.Revoked).WithExpectReason(tc.reason2)
_, err = ocsp_helper.ReqDER(cert.Raw, ocspConfig)
// Check the CRL for the certificate again. It should now be
// revoked with reason keyCompromise.
runUpdater(t, path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "crl-updater.json"))
fetchAndCheckRevoked(t, cert, issuer, tc.reason2)
}
})
}
}
func TestRevokeWithKeyCompromiseBlocksKey(t *testing.T) {
type authMethod string
var (
byAccount authMethod = "byAccount"
byKey authMethod = "byKey"
)
// Test keyCompromise revocation both when revoking by certificate key and
// revoking by subscriber key. Both should work, although with slightly
// different behavior.
for _, method := range []authMethod{byKey, byAccount} {
c, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "failed to generate cert key")
res, err := authAndIssue(c, certKey, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
test.AssertNotError(t, err, "authAndIssue failed")
cert := res.certs[0]
issuer := res.certs[1]
ocspConfig := ocspConf().WithExpectStatus(ocsp.Good)
_, err = ocsp_helper.ReqDER(cert.Raw, ocspConfig)
test.AssertNotError(t, err, "requesting OCSP for not yet revoked cert")
// Revoke the cert with reason keyCompromise, either authenticated via the
// issuing account, or via the certificate key itself.
switch method {
case byAccount:
err = c.RevokeCertificate(c.Account, cert, c.PrivateKey, ocsp.KeyCompromise)
case byKey:
err = c.RevokeCertificate(acme.Account{}, cert, certKey, ocsp.KeyCompromise)
}
test.AssertNotError(t, err, "failed to revoke certificate")
// Check the OCSP response. It should be revoked with reason = 1 (keyCompromise).
ocspConfig = ocspConf().WithExpectStatus(ocsp.Revoked).WithExpectReason(ocsp.KeyCompromise)
_, err = ocsp_helper.ReqDER(cert.Raw, ocspConfig)
test.AssertNotError(t, err, "requesting OCSP for revoked cert")
runUpdater(t, path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "crl-updater.json"))
fetchAndCheckRevoked(t, cert, issuer, ocsp.KeyCompromise)
// Attempt to create a new account using the compromised key. This should
// work when the key was just *reported* as compromised, but fail when
// the compromise was demonstrated/proven.
_, err = c.NewAccount(certKey, false, true)
switch method {
case byAccount:
test.AssertNotError(t, err, "NewAccount failed with a non-blocklisted key")
case byKey:
test.AssertError(t, err, "NewAccount didn't fail with a blocklisted key")
test.AssertEquals(t, err.Error(), `acme: error code 400 "urn:ietf:params:acme:error:badPublicKey": Unable to validate JWS :: invalid request signing key: public key is forbidden`)
}
}
}
func TestBadKeyRevoker(t *testing.T) {
revokerClient, err := makeClient()
test.AssertNotError(t, err, "creating acme client")
revokeeClient, err := makeClient()
test.AssertNotError(t, err, "creating acme client")
certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "failed to generate cert key")
res, err := authAndIssue(revokerClient, certKey, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
test.AssertNotError(t, err, "authAndIssue failed")
badCert := res.certs[0]
t.Logf("Generated to-be-revoked cert with serial %x", badCert.SerialNumber)
bundles := []*issuanceResult{}
for _, c := range []*client{revokerClient, revokeeClient} {
bundle, err := authAndIssue(c, certKey, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
t.Logf("TestBadKeyRevoker: Issued cert with serial %x", bundle.certs[0].SerialNumber)
test.AssertNotError(t, err, "authAndIssue failed")
bundles = append(bundles, bundle)
}
err = revokerClient.RevokeCertificate(
acme.Account{},
badCert,
certKey,
ocsp.KeyCompromise,
)
test.AssertNotError(t, err, "failed to revoke certificate")
ocspConfig := ocspConf().WithExpectStatus(ocsp.Revoked).WithExpectReason(ocsp.KeyCompromise)
_, err = ocsp_helper.ReqDER(badCert.Raw, ocspConfig)
test.AssertNotError(t, err, "ReqDER failed")
for _, bundle := range bundles {
cert := bundle.certs[0]
for i := range 5 {
t.Logf("TestBadKeyRevoker: Requesting OCSP for cert with serial %x (attempt %d)", cert.SerialNumber, i)
_, err := ocsp_helper.ReqDER(cert.Raw, ocspConfig)
if err != nil {
t.Logf("TestBadKeyRevoker: Got bad response: %s", err.Error())
if i >= 4 {
t.Fatal("timed out waiting for correct OCSP status")
}
time.Sleep(time.Second)
continue
}
break
}
}
runUpdater(t, path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "crl-updater.json"))
for _, bundle := range bundles {
cert := bundle.certs[0]
issuer := bundle.certs[1]
fetchAndCheckRevoked(t, cert, issuer, ocsp.KeyCompromise)
}
}
func TestBadKeyRevokerByAccount(t *testing.T) {
revokerClient, err := makeClient()
test.AssertNotError(t, err, "creating acme client")
revokeeClient, err := makeClient()
test.AssertNotError(t, err, "creating acme client")
certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "failed to generate cert key")
res, err := authAndIssue(revokerClient, certKey, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
test.AssertNotError(t, err, "authAndIssue failed")
badCert := res.certs[0]
t.Logf("Generated to-be-revoked cert with serial %x", badCert.SerialNumber)
bundles := []*issuanceResult{}
for _, c := range []*client{revokerClient, revokeeClient} {
bundle, err := authAndIssue(c, certKey, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
t.Logf("TestBadKeyRevokerByAccount: Issued cert with serial %x", bundle.certs[0].SerialNumber)
test.AssertNotError(t, err, "authAndIssue failed")
bundles = append(bundles, bundle)
}
err = revokerClient.RevokeCertificate(
revokerClient.Account,
badCert,
revokerClient.PrivateKey,
ocsp.KeyCompromise,
)
test.AssertNotError(t, err, "failed to revoke certificate")
ocspConfig := ocspConf().WithExpectStatus(ocsp.Revoked).WithExpectReason(ocsp.KeyCompromise)
_, err = ocsp_helper.ReqDER(badCert.Raw, ocspConfig)
test.AssertNotError(t, err, "ReqDER failed")
// Note: this test is inherently racy because we don't have a signal
// for when the bad-key-revoker has completed a run after the revocation. However,
// the bad-key-revoker's configured interval is 50ms, so sleeping 1s should be good enough.
time.Sleep(time.Second)
runUpdater(t, path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "crl-updater.json"))
allCRLs := getAllCRLs(t)
ocspConfig = ocspConf().WithExpectStatus(ocsp.Good)
for _, bundle := range bundles {
cert := bundle.certs[0]
t.Logf("TestBadKeyRevoker: Requesting OCSP for cert with serial %x", cert.SerialNumber)
_, err := ocsp_helper.ReqDER(cert.Raw, ocspConfig)
if err != nil {
t.Error(err)
}
checkUnrevoked(t, allCRLs, cert)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/email_exporter_test.go | third-party/github.com/letsencrypt/boulder/test/integration/email_exporter_test.go | //go:build integration
package integration
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"slices"
"strings"
"testing"
"time"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/test"
)
// randomDomain creates a random domain name for testing.
func randomDomain(t *testing.T) string {
t.Helper()
var bytes [4]byte
_, err := rand.Read(bytes[:])
if err != nil {
test.AssertNotError(t, err, "Failed to generate random domain")
}
return fmt.Sprintf("%x.mail.com", bytes[:])
}
// getOAuthToken queries the pardot-test-srv for the current OAuth token.
func getOAuthToken(t *testing.T) string {
t.Helper()
data, err := os.ReadFile("test/secrets/salesforce_client_id")
test.AssertNotError(t, err, "Failed to read Salesforce client ID")
clientId := string(data)
data, err = os.ReadFile("test/secrets/salesforce_client_secret")
test.AssertNotError(t, err, "Failed to read Salesforce client secret")
clientSecret := string(data)
httpClient := http.DefaultClient
resp, err := httpClient.PostForm("http://localhost:9601/services/oauth2/token", url.Values{
"grant_type": {"client_credentials"},
"client_id": {strings.TrimSpace(clientId)},
"client_secret": {strings.TrimSpace(clientSecret)},
})
test.AssertNotError(t, err, "Failed to fetch OAuth token")
test.AssertEquals(t, resp.StatusCode, http.StatusOK)
defer resp.Body.Close()
var response struct {
AccessToken string `json:"access_token"`
}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&response)
test.AssertNotError(t, err, "Failed to decode OAuth token")
return response.AccessToken
}
// getCreatedContacts queries the pardot-test-srv for the list of created
// contacts.
func getCreatedContacts(t *testing.T, token string) []string {
t.Helper()
httpClient := http.DefaultClient
req, err := http.NewRequest("GET", "http://localhost:9602/contacts", nil)
test.AssertNotError(t, err, "Failed to create request")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := httpClient.Do(req)
test.AssertNotError(t, err, "Failed to query contacts")
test.AssertEquals(t, resp.StatusCode, http.StatusOK)
defer resp.Body.Close()
var got struct {
Contacts []string `json:"contacts"`
}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&got)
test.AssertNotError(t, err, "Failed to decode contacts")
return got.Contacts
}
// assertAllContactsReceived waits for the expected contacts to be received by
// pardot-test-srv. Retries every 50ms for up to 2 seconds and fails if the
// expected contacts are not received.
func assertAllContactsReceived(t *testing.T, token string, expect []string) {
t.Helper()
for attempt := range 20 {
if attempt > 0 {
time.Sleep(50 * time.Millisecond)
}
got := getCreatedContacts(t, token)
allFound := true
for _, e := range expect {
if !slices.Contains(got, e) {
allFound = false
break
}
}
if allFound {
break
}
if attempt >= 19 {
t.Fatalf("Expected contacts=%v to be received by pardot-test-srv, got contacts=%v", expect, got)
}
}
}
// TestContactsSentForNewAccount tests that contacts are dispatched to
// pardot-test-srv by the email-exporter when a new account is created.
func TestContactsSentForNewAccount(t *testing.T) {
t.Parallel()
if os.Getenv("BOULDER_CONFIG_DIR") != "test/config-next" {
t.Skip("Test requires WFE to be configured to use email-exporter")
}
token := getOAuthToken(t)
domain := randomDomain(t)
tests := []struct {
name string
contacts []string
expectContacts []string
}{
{
name: "Single email",
contacts: []string{"mailto:example@" + domain},
expectContacts: []string{"example@" + domain},
},
{
name: "Multiple emails",
contacts: []string{"mailto:example1@" + domain, "mailto:example2@" + domain},
expectContacts: []string{"example1@" + domain, "example2@" + domain},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c, err := acme.NewClient("http://boulder.service.consul:4001/directory")
if err != nil {
t.Fatalf("failed to connect to acme directory: %s", err)
}
acctKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("failed to generate account key: %s", err)
}
_, err = c.NewAccount(acctKey, false, true, tt.contacts...)
test.AssertNotError(t, err, "Failed to create initial account with contacts")
assertAllContactsReceived(t, token, tt.expectContacts)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/bad_key_test.go | third-party/github.com/letsencrypt/boulder/test/integration/bad_key_test.go | //go:build integration
package integration
import (
"crypto/x509"
"encoding/pem"
"os"
"testing"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/test"
)
// TestFermat ensures that a certificate public key which can be factored using
// less than 100 rounds of Fermat's Algorithm is rejected.
func TestFermat(t *testing.T) {
t.Parallel()
// Create a client and complete an HTTP-01 challenge for a fake domain.
c, err := makeClient()
test.AssertNotError(t, err, "creating acme client")
domain := random_domain()
order, err := c.Client.NewOrder(
c.Account, []acme.Identifier{{Type: "dns", Value: domain}})
test.AssertNotError(t, err, "creating new order")
test.AssertEquals(t, len(order.Authorizations), 1)
authUrl := order.Authorizations[0]
auth, err := c.Client.FetchAuthorization(c.Account, authUrl)
test.AssertNotError(t, err, "fetching authorization")
chal, ok := auth.ChallengeMap[acme.ChallengeTypeHTTP01]
test.Assert(t, ok, "getting HTTP-01 challenge")
_, err = testSrvClient.AddHTTP01Response(chal.Token, chal.KeyAuthorization)
test.AssertNotError(t, err, "")
defer func() {
_, err = testSrvClient.RemoveHTTP01Response(chal.Token)
test.AssertNotError(t, err, "")
}()
chal, err = c.Client.UpdateChallenge(c.Account, chal)
test.AssertNotError(t, err, "updating HTTP-01 challenge")
// Load the Fermat-weak CSR that we'll submit for finalize. This CSR was
// generated using test/integration/testdata/fermat_csr.go, has prime factors
// that differ by only 2^516 + 254, and can be factored in 42 rounds.
csrPem, err := os.ReadFile("test/integration/testdata/fermat_csr.pem")
test.AssertNotError(t, err, "reading CSR PEM from disk")
csrDer, _ := pem.Decode(csrPem)
if csrDer == nil {
t.Fatal("failed to decode CSR PEM")
}
csr, err := x509.ParseCertificateRequest(csrDer.Bytes)
test.AssertNotError(t, err, "parsing CSR")
// Finalizing the order should fail as we reject the public key.
_, err = c.Client.FinalizeOrder(c.Account, order, csr)
test.AssertError(t, err, "finalizing order")
test.AssertContains(t, err.Error(), "urn:ietf:params:acme:error:badCSR")
test.AssertContains(t, err.Error(), "key generated with factors too close together")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/nonce_test.go | third-party/github.com/letsencrypt/boulder/test/integration/nonce_test.go | //go:build integration
package integration
import (
"context"
"testing"
"github.com/jmhodges/clock"
"google.golang.org/grpc/status"
"github.com/letsencrypt/boulder/cmd"
bgrpc "github.com/letsencrypt/boulder/grpc"
nb "github.com/letsencrypt/boulder/grpc/noncebalancer"
"github.com/letsencrypt/boulder/metrics"
"github.com/letsencrypt/boulder/nonce"
noncepb "github.com/letsencrypt/boulder/nonce/proto"
"github.com/letsencrypt/boulder/test"
)
type nonceBalancerTestConfig struct {
NotWFE struct {
TLS cmd.TLSConfig
GetNonceService *cmd.GRPCClientConfig
RedeemNonceService *cmd.GRPCClientConfig
NonceHMACKey cmd.HMACKeyConfig
}
}
func TestNonceBalancer_NoBackendMatchingPrefix(t *testing.T) {
t.Parallel()
// We're going to use a minimal nonce service client called "notwfe" which
// masquerades as a wfe for the purpose of redeeming nonces.
// Load the test config.
var c nonceBalancerTestConfig
err := cmd.ReadConfigFile("test/integration/testdata/nonce-client.json", &c)
test.AssertNotError(t, err, "Could not read config file")
tlsConfig, err := c.NotWFE.TLS.Load(metrics.NoopRegisterer)
test.AssertNotError(t, err, "Could not load TLS config")
rncKey, err := c.NotWFE.NonceHMACKey.Load()
test.AssertNotError(t, err, "Failed to load nonceHMACKey")
clk := clock.New()
redeemNonceConn, err := bgrpc.ClientSetup(c.NotWFE.RedeemNonceService, tlsConfig, metrics.NoopRegisterer, clk)
test.AssertNotError(t, err, "Failed to load credentials and create gRPC connection to redeem nonce service")
rnc := nonce.NewRedeemer(redeemNonceConn)
// Attempt to redeem a nonce with a prefix that doesn't match any backends.
ctx := context.WithValue(context.Background(), nonce.PrefixCtxKey{}, "12345678")
ctx = context.WithValue(ctx, nonce.HMACKeyCtxKey{}, rncKey)
_, err = rnc.Redeem(ctx, &noncepb.NonceMessage{Nonce: "0123456789"})
// We expect to get a specific gRPC status error with code NotFound.
gotRPCStatus, ok := status.FromError(err)
test.Assert(t, ok, "Failed to convert error to status")
test.AssertEquals(t, gotRPCStatus, nb.ErrNoBackendsMatchPrefix)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/account_test.go | third-party/github.com/letsencrypt/boulder/test/integration/account_test.go | //go:build integration
package integration
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"strings"
"testing"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/core"
)
// TestNewAccount tests that various new-account requests are handled correctly.
// It does not test malformed account contacts, as we no longer care about
// how well-formed the contact string is, since we no longer store them.
func TestNewAccount(t *testing.T) {
t.Parallel()
c, err := acme.NewClient("http://boulder.service.consul:4001/directory")
if err != nil {
t.Fatalf("failed to connect to acme directory: %s", err)
}
for _, tc := range []struct {
name string
tos bool
contact []string
wantErr string
}{
{
name: "No TOS agreement",
tos: false,
contact: nil,
wantErr: "must agree to terms of service",
},
{
name: "No contacts",
tos: true,
contact: nil,
},
{
name: "One contact",
tos: true,
contact: []string{"mailto:single@chisel.com"},
},
{
name: "Many contacts",
tos: true,
contact: []string{"mailto:one@chisel.com", "mailto:two@chisel.com", "mailto:three@chisel.com"},
},
} {
t.Run(tc.name, func(t *testing.T) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("failed to generate account key: %s", err)
}
acct, err := c.NewAccount(key, false, tc.tos, tc.contact...)
if tc.wantErr == "" {
if err != nil {
t.Fatalf("NewAccount(tos: %t, contact: %#v) = %s, but want no err", tc.tos, tc.contact, err)
}
if len(acct.Contact) != 0 {
t.Errorf("NewAccount(tos: %t, contact: %#v) = %#v, but want empty contacts", tc.tos, tc.contact, acct)
}
} else if tc.wantErr != "" {
if err == nil {
t.Fatalf("NewAccount(tos: %t, contact: %#v) = %#v, but want error %q", tc.tos, tc.contact, acct, tc.wantErr)
}
if !strings.Contains(err.Error(), tc.wantErr) {
t.Errorf("NewAccount(tos: %t, contact: %#v) = %q, but want error %q", tc.tos, tc.contact, err, tc.wantErr)
}
}
})
}
}
func TestNewAccount_DuplicateKey(t *testing.T) {
t.Parallel()
c, err := acme.NewClient("http://boulder.service.consul:4001/directory")
if err != nil {
t.Fatalf("failed to connect to acme directory: %s", err)
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("failed to generate account key: %s", err)
}
// OnlyReturnExisting: true with a never-before-used key should result in an error.
acct, err := c.NewAccount(key, true, true)
if err == nil {
t.Fatalf("NewAccount(key: 1, ore: true) = %#v, but want error notFound", acct)
}
// Create an account.
acct, err = c.NewAccount(key, false, true)
if err != nil {
t.Fatalf("NewAccount(key: 1, ore: false) = %#v, but want success", err)
}
// A duplicate request should just return the same account.
acct, err = c.NewAccount(key, false, true)
if err != nil {
t.Fatalf("NewAccount(key: 1, ore: false) = %#v, but want success", err)
}
// Specifying OnlyReturnExisting should do the same.
acct, err = c.NewAccount(key, true, true)
if err != nil {
t.Fatalf("NewAccount(key: 1, ore: true) = %#v, but want success", err)
}
// Deactivate the account.
acct, err = c.DeactivateAccount(acct)
if err != nil {
t.Fatalf("DeactivateAccount(acct: 1) = %#v, but want success", err)
}
// Now a new account request should return an error.
acct, err = c.NewAccount(key, false, true)
if err == nil {
t.Fatalf("NewAccount(key: 1, ore: false) = %#v, but want error deactivated", acct)
}
// Specifying OnlyReturnExisting should do the same.
acct, err = c.NewAccount(key, true, true)
if err == nil {
t.Fatalf("NewAccount(key: 1, ore: true) = %#v, but want error deactivated", acct)
}
}
// TestAccountDeactivate tests that account deactivation works. It does not test
// that we reject requests for other account statuses, because eggsampler/acme
// wisely does not allow us to construct such malformed requests.
func TestAccountDeactivate(t *testing.T) {
t.Parallel()
c, err := acme.NewClient("http://boulder.service.consul:4001/directory")
if err != nil {
t.Fatalf("failed to connect to acme directory: %s", err)
}
acctKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("failed to generate account key: %s", err)
}
account, err := c.NewAccount(acctKey, false, true, "mailto:hello@blackhole.net")
if err != nil {
t.Fatalf("failed to create initial account: %s", err)
}
got, err := c.DeactivateAccount(account)
if err != nil {
t.Errorf("unexpected error while deactivating account: %s", err)
}
if got.Status != string(core.StatusDeactivated) {
t.Errorf("account deactivation should have set status to %q, instead got %q", core.StatusDeactivated, got.Status)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/otel_test.go | third-party/github.com/letsencrypt/boulder/test/integration/otel_test.go | //go:build integration
package integration
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"testing"
"time"
"github.com/eggsampler/acme/v3"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
"github.com/letsencrypt/boulder/cmd"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/test"
)
// TraceResponse is the list of traces returned from Jaeger's trace search API
// We always search for a single trace by ID, so this should be length 1.
// This is a specialization of Jaeger's structuredResponse type which
// uses []interface{} upstream.
type TraceResponse struct {
Data []Trace
}
// Trace represents a single trace in Jaeger's API
// See https://pkg.go.dev/github.com/jaegertracing/jaeger/model/json#Trace
type Trace struct {
TraceID string
Spans []Span
Processes map[string]struct {
ServiceName string
}
Warnings []string
}
// Span represents a single span in Jaeger's API
// See https://pkg.go.dev/github.com/jaegertracing/jaeger/model/json#Span
type Span struct {
SpanID string
OperationName string
Warnings []string
ProcessID string
References []struct {
RefType string
TraceID string
SpanID string
}
}
func getTraceFromJaeger(t *testing.T, traceID trace.TraceID) Trace {
t.Helper()
traceURL := "http://bjaeger:16686/api/traces/" + traceID.String()
resp, err := http.Get(traceURL)
test.AssertNotError(t, err, "failed to trace from jaeger: "+traceID.String())
if resp.StatusCode == http.StatusNotFound {
t.Fatalf("jaeger returned 404 for trace %s", traceID)
}
test.AssertEquals(t, resp.StatusCode, http.StatusOK)
body, err := io.ReadAll(resp.Body)
test.AssertNotError(t, err, "failed to read trace body")
var parsed TraceResponse
err = json.Unmarshal(body, &parsed)
test.AssertNotError(t, err, "failed to decode traces body")
if len(parsed.Data) != 1 {
t.Fatalf("expected to get exactly one trace from jaeger for %s: %v", traceID, parsed)
}
return parsed.Data[0]
}
type expectedSpans struct {
Operation string
Service string
Children []expectedSpans
}
// isParent returns true if the given span has a parent of ParentID
// The empty string means no ParentID
func isParent(parentID string, span Span) bool {
if len(span.References) == 0 {
return parentID == ""
}
for _, ref := range span.References {
// In OpenTelemetry, CHILD_OF is the only reference, but Jaeger supports other systems.
if ref.RefType == "CHILD_OF" {
return ref.SpanID == parentID
}
}
return false
}
func missingChildren(trace Trace, spanID string, children []expectedSpans) bool {
for _, child := range children {
if !findSpans(trace, spanID, child) {
// Missing Child
return true
}
}
return false
}
// findSpans checks if the expectedSpan and its expected children are found in trace
func findSpans(trace Trace, parentSpan string, expectedSpan expectedSpans) bool {
for _, span := range trace.Spans {
if !isParent(parentSpan, span) {
continue
}
if trace.Processes[span.ProcessID].ServiceName != expectedSpan.Service {
continue
}
if span.OperationName != expectedSpan.Operation {
continue
}
if missingChildren(trace, span.SpanID, expectedSpan.Children) {
continue
}
// This span has the correct parent, service, operation, and children
return true
}
fmt.Printf("did not find span %s::%s with parent '%s'\n", expectedSpan.Service, expectedSpan.Operation, parentSpan)
return false
}
// ContextInjectingRoundTripper holds a context that is added to every request
// sent through this RoundTripper, propagating the OpenTelemetry trace through
// the requests made with it.
//
// This is useful for tracing HTTP clients which don't pass through a context,
// notably including the eggsampler ACME client used in this test.
//
// This test uses a trace started in the test to connect all the outgoing
// requests into a trace that is retrieved from Jaeger's API to make assertions
// about the spans from Boulder.
type ContextInjectingRoundTripper struct {
ctx context.Context
}
// RoundTrip implements http.RoundTripper, injecting c.ctx and the OpenTelemetry
// propagation headers into the request. This ensures all requests are traced.
func (c *ContextInjectingRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
// RoundTrip is not permitted to modify the request, so we clone with this context
r := request.Clone(c.ctx)
// Inject the otel propagation headers
otel.GetTextMapPropagator().Inject(c.ctx, propagation.HeaderCarrier(r.Header))
return http.DefaultTransport.RoundTrip(r)
}
// rpcSpan is a helper for constructing an RPC span where we have both a client and server rpc operation
func rpcSpan(op, client, server string, children ...expectedSpans) expectedSpans {
return expectedSpans{
Operation: op,
Service: client,
Children: []expectedSpans{
{
Operation: op,
Service: server,
Children: children,
},
},
}
}
func httpSpan(endpoint string, children ...expectedSpans) expectedSpans {
return expectedSpans{
Operation: endpoint,
Service: "boulder-wfe2",
Children: append(children,
rpcSpan("nonce.NonceService/Nonce", "boulder-wfe2", "nonce-service"),
rpcSpan("nonce.NonceService/Redeem", "boulder-wfe2", "nonce-service"),
),
}
}
func redisPipelineSpan(op, service string, children ...expectedSpans) expectedSpans {
return expectedSpans{
Operation: "redis.pipeline " + op,
Service: service,
Children: children,
}
}
// TestTraces tests that all the expected spans are present and properly connected
func TestTraces(t *testing.T) {
t.Parallel()
if !strings.Contains(os.Getenv("BOULDER_CONFIG_DIR"), "test/config-next") {
t.Skip("OpenTelemetry is only configured in config-next")
}
traceID := traceIssuingTestCert(t)
wfe := "boulder-wfe2"
ra := "boulder-ra"
ca := "boulder-ca"
// A very stripped-down version of the expected call graph of a full issuance
// flow: just enough to ensure that our otel tracing is working without
// asserting too much about the exact set of RPCs we use under the hood.
expectedSpans := expectedSpans{
Operation: "TraceTest",
Service: "integration.test",
Children: []expectedSpans{
{Operation: "/directory", Service: wfe},
{Operation: "/acme/new-nonce", Service: wfe, Children: []expectedSpans{
rpcSpan("nonce.NonceService/Nonce", wfe, "nonce-service")}},
httpSpan("/acme/new-acct",
redisPipelineSpan("get", wfe)),
httpSpan("/acme/new-order"),
httpSpan("/acme/authz/"),
httpSpan("/acme/chall/"),
httpSpan("/acme/finalize/",
rpcSpan("ra.RegistrationAuthority/FinalizeOrder", wfe, ra,
rpcSpan("ca.CertificateAuthority/IssueCertificate", ra, ca))),
},
}
// Retry checking for spans. Span submission is batched asynchronously, so we
// may have to wait for the DefaultScheduleDelay (5 seconds) for results to
// be available. Rather than always waiting, we retry a few times.
// Empirically, this test passes on the second or third try.
var trace Trace
found := false
const retries = 10
for range retries {
trace := getTraceFromJaeger(t, traceID)
if findSpans(trace, "", expectedSpans) {
found = true
break
}
time.Sleep(sdktrace.DefaultScheduleDelay / 5 * time.Millisecond)
}
test.Assert(t, found, fmt.Sprintf("Failed to find expected spans in Jaeger for trace %s", traceID))
test.AssertEquals(t, len(trace.Warnings), 0)
for _, span := range trace.Spans {
for _, warning := range span.Warnings {
if strings.Contains(warning, "clock skew adjustment disabled; not applying calculated delta") {
continue
}
t.Errorf("Span %s (%s) warning: %v", span.SpanID, span.OperationName, warning)
}
}
}
func traceIssuingTestCert(t *testing.T) trace.TraceID {
// Configure this integration test to trace to jaeger:4317 like Boulder will
shutdown := cmd.NewOpenTelemetry(cmd.OpenTelemetryConfig{
Endpoint: "bjaeger:4317",
SampleRatio: 1,
}, blog.Get())
defer shutdown(context.Background())
tracer := otel.GetTracerProvider().Tracer("TraceTest")
ctx, span := tracer.Start(context.Background(), "TraceTest")
defer span.End()
// Provide an HTTP client with otel spans.
// The acme client doesn't pass contexts through, so we inject one.
option := acme.WithHTTPClient(&http.Client{
Timeout: 60 * time.Second,
Transport: &ContextInjectingRoundTripper{ctx},
})
c, err := acme.NewClient("http://boulder.service.consul:4001/directory", option)
test.AssertNotError(t, err, "acme.NewClient failed")
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "Generating ECDSA key failed")
account, err := c.NewAccount(privKey, false, true)
test.AssertNotError(t, err, "newAccount failed")
_, err = authAndIssue(&client{account, c}, nil, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
test.AssertNotError(t, err, "authAndIssue failed")
return span.SpanContext().TraceID()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/subordinate_ca_chains_test.go | third-party/github.com/letsencrypt/boulder/test/integration/subordinate_ca_chains_test.go | //go:build integration
package integration
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"strings"
"testing"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/test"
)
func TestSubordinateCAChainsServedByWFE(t *testing.T) {
t.Parallel()
client, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
chains, err := authAndIssueFetchAllChains(client, key, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true)
test.AssertNotError(t, err, "failed to issue test cert")
// An ECDSA intermediate signed by an ECDSA root, and an ECDSA cross-signed by an RSA root.
test.AssertEquals(t, len(chains.certs), 2)
seenECDSAIntermediate := false
seenECDSACrossSignedIntermediate := false
for _, certUrl := range chains.certs {
for _, cert := range certUrl {
if strings.Contains(cert.Subject.CommonName, "int ecdsa") && cert.Issuer.CommonName == "root ecdsa" {
seenECDSAIntermediate = true
}
if strings.Contains(cert.Subject.CommonName, "int ecdsa") && cert.Issuer.CommonName == "root rsa" {
seenECDSACrossSignedIntermediate = true
}
}
}
test.Assert(t, seenECDSAIntermediate, "did not see ECDSA intermediate and should have")
test.Assert(t, seenECDSACrossSignedIntermediate, "did not see ECDSA by RSA cross-signed intermediate and should have")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/ocsp_test.go | third-party/github.com/letsencrypt/boulder/test/integration/ocsp_test.go | //go:build integration
package integration
import (
"strings"
"testing"
"golang.org/x/crypto/ocsp"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/core"
ocsp_helper "github.com/letsencrypt/boulder/test/ocsp/helper"
)
func TestOCSPHappyPath(t *testing.T) {
t.Parallel()
cert, err := authAndIssue(nil, nil, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
if err != nil || len(cert.certs) < 1 {
t.Fatal("failed to issue cert for OCSP testing")
}
resp, err := ocsp_helper.Req(cert.certs[0], ocspConf())
if err != nil {
t.Fatalf("want ocsp response, but got error: %s", err)
}
if resp.Status != ocsp.Good {
t.Errorf("want ocsp status %#v, got %#v", ocsp.Good, resp.Status)
}
}
func TestOCSPBadSerialPrefix(t *testing.T) {
t.Parallel()
res, err := authAndIssue(nil, nil, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
if err != nil || len(res.certs) < 1 {
t.Fatal("Failed to issue dummy cert for OCSP testing")
}
cert := res.certs[0]
// Increment the first byte of the cert's serial number by 1, making the
// prefix invalid. This works because ocsp_helper.Req (and the underlying
// ocsp.CreateRequest) completely ignore the cert's .Raw value.
serialStr := []byte(core.SerialToString(cert.SerialNumber))
serialStr[0] = serialStr[0] + 1
cert.SerialNumber.SetString(string(serialStr), 16)
_, err = ocsp_helper.Req(cert, ocspConf())
if err == nil {
t.Fatal("Expected error getting OCSP for request with invalid serial")
}
}
func TestOCSPRejectedPrecertificate(t *testing.T) {
t.Parallel()
domain := random_domain()
err := ctAddRejectHost(domain)
if err != nil {
t.Fatalf("adding ct-test-srv reject host: %s", err)
}
_, err = authAndIssue(nil, nil, []acme.Identifier{{Type: "dns", Value: domain}}, true, "")
if err != nil {
if !strings.Contains(err.Error(), "urn:ietf:params:acme:error:serverInternal") ||
!strings.Contains(err.Error(), "SCT embedding") {
t.Fatal(err)
}
}
if err == nil {
t.Fatal("expected error issuing for domain rejected by CT servers; got none")
}
// Try to find a precertificate matching the domain from one of the
// configured ct-test-srv instances.
cert, err := ctFindRejection([]string{domain})
if err != nil || cert == nil {
t.Fatalf("couldn't find rejected precert for %q", domain)
}
ocspConfig := ocspConf().WithExpectStatus(ocsp.Good)
_, err = ocsp_helper.ReqDER(cert.Raw, ocspConfig)
if err != nil {
t.Errorf("requesting OCSP for rejected precertificate: %s", err)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/crl_test.go | third-party/github.com/letsencrypt/boulder/test/integration/crl_test.go | //go:build integration
package integration
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"database/sql"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/eggsampler/acme/v3"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/core"
"github.com/letsencrypt/boulder/test"
"github.com/letsencrypt/boulder/test/vars"
)
// crlUpdaterMu controls access to `runUpdater`, because two crl-updaters running
// at once will result in errors trying to lease shards that are already leased.
var crlUpdaterMu sync.Mutex
// runUpdater executes the crl-updater binary with the -runOnce flag, and
// returns when it completes.
func runUpdater(t *testing.T, configFile string) {
t.Helper()
crlUpdaterMu.Lock()
defer crlUpdaterMu.Unlock()
// Reset the s3-test-srv so that it only knows about serials contained in
// this new batch of CRLs.
resp, err := http.Post("http://localhost:4501/reset", "", bytes.NewReader([]byte{}))
test.AssertNotError(t, err, "opening database connection")
test.AssertEquals(t, resp.StatusCode, http.StatusOK)
// Reset the "leasedUntil" column so this can be done alongside other
// updater runs without worrying about unclean state.
fc := clock.NewFake()
db, err := sql.Open("mysql", vars.DBConnSAIntegrationFullPerms)
test.AssertNotError(t, err, "opening database connection")
_, err = db.Exec(`UPDATE crlShards SET leasedUntil = ?`, fc.Now().Add(-time.Minute))
test.AssertNotError(t, err, "resetting leasedUntil column")
binPath, err := filepath.Abs("bin/boulder")
test.AssertNotError(t, err, "computing boulder binary path")
c := exec.Command(binPath, "crl-updater", "-config", configFile, "-debug-addr", ":8022", "-runOnce")
out, err := c.CombinedOutput()
for _, line := range strings.Split(string(out), "\n") {
// Print the updater's stdout for debugging, but only if the test fails.
t.Log(line)
}
test.AssertNotError(t, err, "crl-updater failed")
}
// TestCRLUpdaterStartup ensures that the crl-updater can start in daemon mode.
// We do this here instead of in startservers so that we can shut it down after
// we've confirmed it is running. It's important that it not be running while
// other CRL integration tests are running, because otherwise they fight over
// database leases, leading to flaky test failures.
func TestCRLUpdaterStartup(t *testing.T) {
t.Parallel()
crlUpdaterMu.Lock()
defer crlUpdaterMu.Unlock()
ctx, cancel := context.WithCancel(context.Background())
binPath, err := filepath.Abs("bin/boulder")
test.AssertNotError(t, err, "computing boulder binary path")
configDir, ok := os.LookupEnv("BOULDER_CONFIG_DIR")
test.Assert(t, ok, "failed to look up test config directory")
configFile := path.Join(configDir, "crl-updater.json")
c := exec.CommandContext(ctx, binPath, "crl-updater", "-config", configFile, "-debug-addr", ":8021")
var wg sync.WaitGroup
wg.Add(1)
go func() {
out, err := c.CombinedOutput()
// Log the output and error, but only if the main goroutine couldn't connect
// and declared the test failed.
for _, line := range strings.Split(string(out), "\n") {
t.Log(line)
}
t.Log(err)
wg.Done()
}()
for attempt := range 10 {
time.Sleep(core.RetryBackoff(attempt, 10*time.Millisecond, 1*time.Second, 2))
conn, err := net.DialTimeout("tcp", "localhost:8021", 100*time.Millisecond)
if errors.Is(err, syscall.ECONNREFUSED) {
t.Logf("Connection attempt %d failed: %s", attempt, err)
continue
}
if err != nil {
t.Logf("Connection attempt %d failed unrecoverably: %s", attempt, err)
t.Fail()
break
}
t.Logf("Connection attempt %d succeeded", attempt)
defer conn.Close()
break
}
cancel()
wg.Wait()
}
// TestCRLPipeline runs an end-to-end test of the crl issuance process, ensuring
// that the correct number of properly-formed and validly-signed CRLs are sent
// to our fake S3 service.
func TestCRLPipeline(t *testing.T) {
// Basic setup.
configDir, ok := os.LookupEnv("BOULDER_CONFIG_DIR")
test.Assert(t, ok, "failed to look up test config directory")
configFile := path.Join(configDir, "crl-updater.json")
// Create a database connection so we can pretend to jump forward in time.
db, err := sql.Open("mysql", vars.DBConnSAIntegrationFullPerms)
test.AssertNotError(t, err, "creating database connection")
// Issue a test certificate and save its serial number.
client, err := makeClient()
test.AssertNotError(t, err, "creating acme client")
res, err := authAndIssue(client, nil, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
test.AssertNotError(t, err, "failed to create test certificate")
cert := res.certs[0]
serial := core.SerialToString(cert.SerialNumber)
// Confirm that the cert does not yet show up as revoked in the CRLs.
runUpdater(t, configFile)
resp, err := http.Get("http://localhost:4501/query?serial=" + serial)
test.AssertNotError(t, err, "s3-test-srv GET /query failed")
test.AssertEquals(t, resp.StatusCode, 404)
resp.Body.Close()
// Revoke the certificate.
err = client.RevokeCertificate(client.Account, cert, client.PrivateKey, 5)
test.AssertNotError(t, err, "failed to revoke test certificate")
// Confirm that the cert now *does* show up in the CRLs, with the right reason.
runUpdater(t, configFile)
resp, err = http.Get("http://localhost:4501/query?serial=" + serial)
test.AssertNotError(t, err, "s3-test-srv GET /query failed")
test.AssertEquals(t, resp.StatusCode, 200)
reason, err := io.ReadAll(resp.Body)
test.AssertNotError(t, err, "reading revocation reason")
test.AssertEquals(t, string(reason), "5")
resp.Body.Close()
// Manipulate the database so it appears that the certificate is going to
// expire very soon. The cert should still appear on the CRL.
_, err = db.Exec("UPDATE revokedCertificates SET notAfterHour = ? WHERE serial = ?", time.Now().Add(time.Hour).Truncate(time.Hour).Format(time.DateTime), serial)
test.AssertNotError(t, err, "updating expiry to near future")
runUpdater(t, configFile)
resp, err = http.Get("http://localhost:4501/query?serial=" + serial)
test.AssertNotError(t, err, "s3-test-srv GET /query failed")
test.AssertEquals(t, resp.StatusCode, 200)
reason, err = io.ReadAll(resp.Body)
test.AssertNotError(t, err, "reading revocation reason")
test.AssertEquals(t, string(reason), "5")
resp.Body.Close()
// Again update the database so that the certificate has expired in the
// very recent past. The cert should still appear on the CRL.
_, err = db.Exec("UPDATE revokedCertificates SET notAfterHour = ? WHERE serial = ?", time.Now().Add(-time.Hour).Truncate(time.Hour).Format(time.DateTime), serial)
test.AssertNotError(t, err, "updating expiry to recent past")
runUpdater(t, configFile)
resp, err = http.Get("http://localhost:4501/query?serial=" + serial)
test.AssertNotError(t, err, "s3-test-srv GET /query failed")
test.AssertEquals(t, resp.StatusCode, 200)
reason, err = io.ReadAll(resp.Body)
test.AssertNotError(t, err, "reading revocation reason")
test.AssertEquals(t, string(reason), "5")
resp.Body.Close()
// Finally update the database so that the certificate expired several CRL
// update cycles ago. The cert should now vanish from the CRL.
_, err = db.Exec("UPDATE revokedCertificates SET notAfterHour = ? WHERE serial = ?", time.Now().Add(-48*time.Hour).Truncate(time.Hour).Format(time.DateTime), serial)
test.AssertNotError(t, err, "updating expiry to far past")
runUpdater(t, configFile)
resp, err = http.Get("http://localhost:4501/query?serial=" + serial)
test.AssertNotError(t, err, "s3-test-srv GET /query failed")
test.AssertEquals(t, resp.StatusCode, 404)
resp.Body.Close()
}
func TestCRLTemporalAndExplicitShardingCoexist(t *testing.T) {
db, err := sql.Open("mysql", vars.DBConnSAIntegrationFullPerms)
if err != nil {
t.Fatalf("sql.Open: %s", err)
}
// Insert an old, revoked certificate in the certificateStatus table. Importantly this
// serial has the 7f prefix, which is in test/config-next/crl-updater.json in the
// `temporallyShardedPrefixes` list.
// Random serial that is unique to this test.
oldSerial := "7faa39be44fc95f3d19befe3cb715848e601"
// This is hardcoded to match one of the issuer names in our integration test environment's
// ca.json.
issuerID := 43104258997432926
_, err = db.Exec(`DELETE FROM certificateStatus WHERE serial = ?`, oldSerial)
if err != nil {
t.Fatalf("deleting old certificateStatus row: %s", err)
}
_, err = db.Exec(`
INSERT INTO certificateStatus (serial, issuerID, notAfter, status, ocspLastUpdated, revokedDate, revokedReason, lastExpirationNagSent)
VALUES (?, ?, ?, "revoked", NOW(), NOW(), 0, 0);`,
oldSerial, issuerID, time.Now().Add(24*time.Hour).Format("2006-01-02 15:04:05"))
if err != nil {
t.Fatalf("inserting old certificateStatus row: %s", err)
}
client, err := makeClient()
if err != nil {
t.Fatalf("creating acme client: %s", err)
}
certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("creating cert key: %s", err)
}
// Issue and revoke a certificate. In the config-next world, this will be an explicitly
// sharded certificate. In the config world, this will be a temporally sharded certificate
// (until we move `config` to explicit sharding). This means that in the config world,
// this test only handles temporal sharding, but we don't config-gate it because it passes
// in both worlds.
result, err := authAndIssue(client, certKey, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
if err != nil {
t.Fatalf("authAndIssue: %s", err)
}
cert := result.certs[0]
err = client.RevokeCertificate(
client.Account,
cert,
client.PrivateKey,
0,
)
if err != nil {
t.Fatalf("revoking: %s", err)
}
runUpdater(t, path.Join(os.Getenv("BOULDER_CONFIG_DIR"), "crl-updater.json"))
allCRLs := getAllCRLs(t)
seen := make(map[string]bool)
// Range over CRLs from all issuers, because the "old" certificate (7faa...) has a
// different issuer than the "new" certificate issued by `authAndIssue`, which
// has a random issuer.
for _, crls := range allCRLs {
for _, crl := range crls {
for _, entry := range crl.RevokedCertificateEntries {
serial := fmt.Sprintf("%x", entry.SerialNumber)
if seen[serial] {
t.Errorf("revoked certificate %s seen on multiple CRLs", serial)
}
seen[serial] = true
}
}
}
newSerial := fmt.Sprintf("%x", cert.SerialNumber)
if !seen[newSerial] {
t.Errorf("revoked certificate %s not seen on any CRL", newSerial)
}
if !seen[oldSerial] {
t.Errorf("revoked certificate %s not seen on any CRL", oldSerial)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/validation_test.go | third-party/github.com/letsencrypt/boulder/test/integration/validation_test.go | //go:build integration
package integration
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"database/sql"
"slices"
"strings"
"testing"
"time"
"github.com/eggsampler/acme/v3"
"github.com/miekg/dns"
challtestsrvclient "github.com/letsencrypt/boulder/test/chall-test-srv-client"
"github.com/letsencrypt/boulder/test/vars"
)
var expectedUserAgents = []string{"boulder", "remoteva-a", "remoteva-b", "remoteva-c"}
func collectUserAgentsFromDNSRequests(requests []challtestsrvclient.DNSRequest) []string {
userAgents := make([]string, len(requests))
for i, request := range requests {
userAgents[i] = request.UserAgent
}
return userAgents
}
func assertUserAgentsLength(t *testing.T, got []string, checkType string) {
t.Helper()
if len(got) != 4 {
t.Errorf("During %s, expected 4 User-Agents, got %d", checkType, len(got))
}
}
func assertExpectedUserAgents(t *testing.T, got []string, checkType string) {
t.Helper()
for _, ua := range expectedUserAgents {
if !slices.Contains(got, ua) {
t.Errorf("During %s, expected User-Agent %q in %s (got %v)", checkType, ua, expectedUserAgents, got)
}
}
}
func TestMPICTLSALPN01(t *testing.T) {
t.Parallel()
client, err := makeClient()
if err != nil {
t.Fatalf("creating acme client: %s", err)
}
domain := randomDomain(t)
order, err := client.Client.NewOrder(client.Account, []acme.Identifier{{Type: "dns", Value: domain}})
if err != nil {
t.Fatalf("creating order: %s", err)
}
authz, err := client.Client.FetchAuthorization(client.Account, order.Authorizations[0])
if err != nil {
t.Fatalf("fetching authorization: %s", err)
}
chal, ok := authz.ChallengeMap[acme.ChallengeTypeTLSALPN01]
if !ok {
t.Fatalf("no TLS-ALPN-01 challenge found in %#v", authz)
}
_, err = testSrvClient.AddARecord(domain, []string{"64.112.117.134"})
if err != nil {
t.Fatalf("adding A record: %s", err)
}
defer func() {
testSrvClient.RemoveARecord(domain)
}()
_, err = testSrvClient.AddTLSALPN01Response(domain, chal.KeyAuthorization)
if err != nil {
t.Fatal(err)
}
defer func() {
_, err = testSrvClient.RemoveTLSALPN01Response(domain)
if err != nil {
t.Fatal(err)
}
}()
chal, err = client.Client.UpdateChallenge(client.Account, chal)
if err != nil {
t.Fatalf("completing TLS-ALPN-01 validation: %s", err)
}
validationEvents, err := testSrvClient.TLSALPN01RequestHistory(domain)
if err != nil {
t.Fatal(err)
}
if len(validationEvents) != 4 {
t.Errorf("expected 4 validation events got %d", len(validationEvents))
}
dnsEvents, err := testSrvClient.DNSRequestHistory(domain)
if err != nil {
t.Fatal(err)
}
var caaEvents []challtestsrvclient.DNSRequest
for _, event := range dnsEvents {
if event.Question.Qtype == dns.TypeCAA {
caaEvents = append(caaEvents, event)
}
}
assertUserAgentsLength(t, collectUserAgentsFromDNSRequests(caaEvents), "CAA check")
assertExpectedUserAgents(t, collectUserAgentsFromDNSRequests(caaEvents), "CAA check")
}
func TestMPICDNS01(t *testing.T) {
t.Parallel()
client, err := makeClient()
if err != nil {
t.Fatalf("creating acme client: %s", err)
}
domain := randomDomain(t)
order, err := client.Client.NewOrder(client.Account, []acme.Identifier{{Type: "dns", Value: domain}})
if err != nil {
t.Fatalf("creating order: %s", err)
}
authz, err := client.Client.FetchAuthorization(client.Account, order.Authorizations[0])
if err != nil {
t.Fatalf("fetching authorization: %s", err)
}
chal, ok := authz.ChallengeMap[acme.ChallengeTypeDNS01]
if !ok {
t.Fatalf("no DNS challenge found in %#v", authz)
}
_, err = testSrvClient.AddDNS01Response(domain, chal.KeyAuthorization)
if err != nil {
t.Fatal(err)
}
defer func() {
_, err = testSrvClient.RemoveDNS01Response(domain)
if err != nil {
t.Fatal(err)
}
}()
chal, err = client.Client.UpdateChallenge(client.Account, chal)
if err != nil {
t.Fatalf("completing DNS-01 validation: %s", err)
}
challDomainDNSEvents, err := testSrvClient.DNSRequestHistory("_acme-challenge." + domain)
if err != nil {
t.Fatal(err)
}
var validationEvents []challtestsrvclient.DNSRequest
for _, event := range challDomainDNSEvents {
if event.Question.Qtype == dns.TypeTXT && event.Question.Name == "_acme-challenge."+domain+"." {
validationEvents = append(validationEvents, event)
}
}
assertUserAgentsLength(t, collectUserAgentsFromDNSRequests(validationEvents), "DNS-01 validation")
assertExpectedUserAgents(t, collectUserAgentsFromDNSRequests(validationEvents), "DNS-01 validation")
domainDNSEvents, err := testSrvClient.DNSRequestHistory(domain)
if err != nil {
t.Fatal(err)
}
var caaEvents []challtestsrvclient.DNSRequest
for _, event := range domainDNSEvents {
if event.Question.Qtype == dns.TypeCAA {
caaEvents = append(caaEvents, event)
}
}
assertUserAgentsLength(t, collectUserAgentsFromDNSRequests(caaEvents), "CAA check")
assertExpectedUserAgents(t, collectUserAgentsFromDNSRequests(caaEvents), "CAA check")
}
func TestMPICHTTP01(t *testing.T) {
t.Parallel()
client, err := makeClient()
if err != nil {
t.Fatalf("creating acme client: %s", err)
}
domain := randomDomain(t)
order, err := client.Client.NewOrder(client.Account, []acme.Identifier{{Type: "dns", Value: domain}})
if err != nil {
t.Fatalf("creating order: %s", err)
}
authz, err := client.Client.FetchAuthorization(client.Account, order.Authorizations[0])
if err != nil {
t.Fatalf("fetching authorization: %s", err)
}
chal, ok := authz.ChallengeMap[acme.ChallengeTypeHTTP01]
if !ok {
t.Fatalf("no HTTP challenge found in %#v", authz)
}
_, err = testSrvClient.AddHTTP01Response(chal.Token, chal.KeyAuthorization)
if err != nil {
t.Fatal(err)
}
defer func() {
_, err = testSrvClient.RemoveHTTP01Response(chal.Token)
if err != nil {
t.Fatal(err)
}
}()
chal, err = client.Client.UpdateChallenge(client.Account, chal)
if err != nil {
t.Fatalf("completing HTTP-01 validation: %s", err)
}
validationEvents, err := testSrvClient.HTTPRequestHistory(domain)
if err != nil {
t.Fatal(err)
}
var validationUAs []string
for _, event := range validationEvents {
if event.URL == "/.well-known/acme-challenge/"+chal.Token {
validationUAs = append(validationUAs, event.UserAgent)
}
}
assertUserAgentsLength(t, validationUAs, "HTTP-01 validation")
assertExpectedUserAgents(t, validationUAs, "HTTP-01 validation")
dnsEvents, err := testSrvClient.DNSRequestHistory(domain)
if err != nil {
t.Fatal(err)
}
var caaEvents []challtestsrvclient.DNSRequest
for _, event := range dnsEvents {
if event.Question.Qtype == dns.TypeCAA {
caaEvents = append(caaEvents, event)
}
}
assertUserAgentsLength(t, collectUserAgentsFromDNSRequests(caaEvents), "CAA check")
assertExpectedUserAgents(t, collectUserAgentsFromDNSRequests(caaEvents), "CAA check")
}
func TestCAARechecking(t *testing.T) {
t.Parallel()
domain := randomDomain(t)
idents := []acme.Identifier{{Type: "dns", Value: domain}}
// Create an order and authorization, and fulfill the associated challenge.
// This should put the authz into the "valid" state, since CAA checks passed.
client, err := makeClient()
if err != nil {
t.Fatalf("creating acme client: %s", err)
}
order, err := client.Client.NewOrder(client.Account, idents)
if err != nil {
t.Fatalf("creating order: %s", err)
}
authz, err := client.Client.FetchAuthorization(client.Account, order.Authorizations[0])
if err != nil {
t.Fatalf("fetching authorization: %s", err)
}
chal, ok := authz.ChallengeMap[acme.ChallengeTypeHTTP01]
if !ok {
t.Fatalf("no HTTP challenge found in %#v", authz)
}
_, err = testSrvClient.AddHTTP01Response(chal.Token, chal.KeyAuthorization)
if err != nil {
t.Fatal(err)
}
defer func() {
_, err = testSrvClient.RemoveHTTP01Response(chal.Token)
if err != nil {
t.Fatal(err)
}
}()
chal, err = client.Client.UpdateChallenge(client.Account, chal)
if err != nil {
t.Fatalf("completing HTTP-01 validation: %s", err)
}
// Manipulate the database so that it looks like the authz was validated
// more than 8 hours ago.
db, err := sql.Open("mysql", vars.DBConnSAIntegrationFullPerms)
if err != nil {
t.Fatalf("sql.Open: %s", err)
}
_, err = db.Exec(`UPDATE authz2 SET attemptedAt = ? WHERE identifierValue = ?`, time.Now().Add(-24*time.Hour).Format(time.DateTime), domain)
if err != nil {
t.Fatalf("updating authz attemptedAt timestamp: %s", err)
}
// Change the CAA record to now forbid issuance.
_, err = testSrvClient.AddCAAIssue(domain, ";")
if err != nil {
t.Fatal(err)
}
// Try to finalize the order created above. Due to our db manipulation, this
// should trigger a CAA recheck. And due to our challtestsrv manipulation,
// that CAA recheck should fail. Therefore the whole finalize should fail.
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("generating cert key: %s", err)
}
csr, err := makeCSR(key, idents, false)
if err != nil {
t.Fatalf("generating finalize csr: %s", err)
}
_, err = client.Client.FinalizeOrder(client.Account, order, csr)
if err == nil {
t.Errorf("expected finalize to fail, but got success")
}
if !strings.Contains(err.Error(), "CAA") {
t.Errorf("expected finalize to fail due to CAA, but got: %s", err)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/common_mock.go | third-party/github.com/letsencrypt/boulder/test/integration/common_mock.go | //go:build integration
package integration
import (
"bytes"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
berrors "github.com/letsencrypt/boulder/errors"
)
var ctSrvPorts = []int{4600, 4601, 4602, 4603, 4604, 4605, 4606, 4607, 4608, 4609}
// ctAddRejectHost adds a domain to all of the CT test server's reject-host
// lists. If this fails the test is aborted with a fatal error.
func ctAddRejectHost(domain string) error {
for _, port := range ctSrvPorts {
url := fmt.Sprintf("http://boulder.service.consul:%d/add-reject-host", port)
body := []byte(fmt.Sprintf(`{"host": %q}`, domain))
resp, err := http.Post(url, "", bytes.NewBuffer(body))
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("adding reject host: %d", resp.StatusCode)
}
resp.Body.Close()
}
return nil
}
// ctGetRejections returns a slice of base64 encoded certificates that were
// rejected by the CT test server at the specified port or an error.
func ctGetRejections(port int) ([]string, error) {
url := fmt.Sprintf("http://boulder.service.consul:%d/get-rejections", port)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(
"getting rejections: status %d", resp.StatusCode)
}
var rejections []string
err = json.NewDecoder(resp.Body).Decode(&rejections)
if err != nil {
return nil, err
}
return rejections, nil
}
// ctFindRejection returns a parsed x509.Certificate matching the given domains
// from the base64 certificates any CT test server rejected. If no rejected
// certificate matching the provided domains is found an error is returned.
func ctFindRejection(domains []string) (*x509.Certificate, error) {
// Collect up rejections from all of the ctSrvPorts
var rejections []string
for _, port := range ctSrvPorts {
r, err := ctGetRejections(port)
if err != nil {
continue
}
rejections = append(rejections, r...)
}
// Parse each rejection cert
var cert *x509.Certificate
RejectionLoop:
for _, r := range rejections {
precertDER, err := base64.StdEncoding.DecodeString(r)
if err != nil {
return nil, err
}
c, err := x509.ParseCertificate(precertDER)
if err != nil {
return nil, err
}
// If the cert doesn't have the right number of names it won't be a match.
if len(c.DNSNames) != len(domains) {
continue
}
// If any names don't match, it isn't a match
for i, name := range c.DNSNames {
if name != domains[i] {
continue RejectionLoop
}
}
// It's a match!
cert = c
break
}
if cert == nil {
return nil, berrors.NotFoundError("no matching ct-test-srv rejection found")
}
return cert, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/pausing_test.go | third-party/github.com/letsencrypt/boulder/test/integration/pausing_test.go | //go:build integration
package integration
import (
"context"
"strconv"
"strings"
"testing"
"time"
"github.com/eggsampler/acme/v3"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/config"
bgrpc "github.com/letsencrypt/boulder/grpc"
"github.com/letsencrypt/boulder/identifier"
"github.com/letsencrypt/boulder/metrics"
sapb "github.com/letsencrypt/boulder/sa/proto"
"github.com/letsencrypt/boulder/test"
)
func TestIdentifiersPausedForAccount(t *testing.T) {
t.Parallel()
tlsCerts := &cmd.TLSConfig{
CACertFile: "test/certs/ipki/minica.pem",
CertFile: "test/certs/ipki/ra.boulder/cert.pem",
KeyFile: "test/certs/ipki/ra.boulder/key.pem",
}
tlsConf, err := tlsCerts.Load(metrics.NoopRegisterer)
test.AssertNotError(t, err, "Failed to load TLS config")
saConn, err := bgrpc.ClientSetup(
&cmd.GRPCClientConfig{
DNSAuthority: "consul.service.consul",
SRVLookup: &cmd.ServiceDomain{
Service: "sa",
Domain: "service.consul",
},
Timeout: config.Duration{Duration: 5 * time.Second},
NoWaitForReady: true,
HostOverride: "sa.boulder",
},
tlsConf,
metrics.NoopRegisterer,
clock.NewFake(),
)
cmd.FailOnError(err, "Failed to load credentials and create gRPC connection to SA")
saClient := sapb.NewStorageAuthorityClient(saConn)
c, err := makeClient()
parts := strings.SplitAfter(c.URL, "/")
regID, err := strconv.ParseInt(parts[len(parts)-1], 10, 64)
domain := random_domain()
serverIdents := identifier.ACMEIdentifiers{identifier.NewDNS(domain)}
clientIdents := []acme.Identifier{{Type: "dns", Value: domain}}
_, err = saClient.PauseIdentifiers(context.Background(), &sapb.PauseRequest{
RegistrationID: regID,
Identifiers: serverIdents.ToProtoSlice(),
})
test.AssertNotError(t, err, "Failed to pause domain")
_, err = authAndIssue(c, nil, clientIdents, true, "")
test.AssertError(t, err, "Should not be able to issue a certificate for a paused domain")
test.AssertContains(t, err.Error(), "Your account is temporarily prevented from requesting certificates for")
test.AssertContains(t, err.Error(), "https://boulder.service.consul:4003/sfe/v1/unpause?jwt=")
_, err = saClient.UnpauseAccount(context.Background(), &sapb.RegistrationID{
Id: regID,
})
test.AssertNotError(t, err, "Failed to unpause domain")
_, err = authAndIssue(c, nil, clientIdents, true, "")
test.AssertNotError(t, err, "Should be able to issue a certificate for an unpaused domain")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/ari_test.go | third-party/github.com/letsencrypt/boulder/test/integration/ari_test.go | //go:build integration
package integration
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509/pkix"
"math/big"
"os"
"testing"
"time"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/test"
)
// certID matches the ASN.1 structure of the CertID sequence defined by RFC6960.
type certID struct {
HashAlgorithm pkix.AlgorithmIdentifier
IssuerNameHash []byte
IssuerKeyHash []byte
SerialNumber *big.Int
}
func TestARIAndReplacement(t *testing.T) {
t.Parallel()
// Setup
client, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// Issue a cert, request ARI, and check that both the suggested window and
// the retry-after header are approximately the right amount of time in the
// future.
name := random_domain()
ir, err := authAndIssue(client, key, []acme.Identifier{{Type: "dns", Value: name}}, true, "")
test.AssertNotError(t, err, "failed to issue test cert")
cert := ir.certs[0]
ari, err := client.GetRenewalInfo(cert)
test.AssertNotError(t, err, "ARI request should have succeeded")
test.AssertEquals(t, ari.SuggestedWindow.Start.Sub(time.Now()).Round(time.Hour), 1418*time.Hour)
test.AssertEquals(t, ari.SuggestedWindow.End.Sub(time.Now()).Round(time.Hour), 1461*time.Hour)
test.AssertEquals(t, ari.RetryAfter.Sub(time.Now()).Round(time.Hour), 6*time.Hour)
// Make a new order which indicates that it replaces the cert issued above,
// and verify that the replacement order succeeds.
_, order, err := makeClientAndOrder(client, key, []acme.Identifier{{Type: "dns", Value: name}}, true, "", cert)
test.AssertNotError(t, err, "failed to issue test cert")
replaceID, err := acme.GenerateARICertID(cert)
test.AssertNotError(t, err, "failed to generate ARI certID")
test.AssertEquals(t, order.Replaces, replaceID)
test.AssertNotEquals(t, order.Replaces, "")
// Retrieve the order and verify that it has the correct replaces field.
resp, err := client.FetchOrder(client.Account, order.URL)
test.AssertNotError(t, err, "failed to fetch order")
if os.Getenv("BOULDER_CONFIG_DIR") == "test/config-next" {
test.AssertEquals(t, resp.Replaces, order.Replaces)
} else {
test.AssertEquals(t, resp.Replaces, "")
}
// Try another replacement order and verify that it fails.
_, order, err = makeClientAndOrder(client, key, []acme.Identifier{{Type: "dns", Value: name}}, true, "", cert)
test.AssertError(t, err, "subsequent ARI replacements for a replaced cert should fail, but didn't")
test.AssertContains(t, err.Error(), "urn:ietf:params:acme:error:alreadyReplaced")
test.AssertContains(t, err.Error(), "already has a replacement order")
test.AssertContains(t, err.Error(), "error code 409")
}
func TestARIShortLived(t *testing.T) {
t.Parallel()
// Setup
client, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// Issue a short-lived cert, request ARI, and check that both the suggested
// window and the retry-after header are approximately the right amount of
// time in the future.
ir, err := authAndIssue(client, key, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "shortlived")
test.AssertNotError(t, err, "failed to issue test cert")
cert := ir.certs[0]
ari, err := client.GetRenewalInfo(cert)
test.AssertNotError(t, err, "ARI request should have succeeded")
test.AssertEquals(t, ari.SuggestedWindow.Start.Sub(time.Now()).Round(time.Hour), 78*time.Hour)
test.AssertEquals(t, ari.SuggestedWindow.End.Sub(time.Now()).Round(time.Hour), 81*time.Hour)
test.AssertEquals(t, ari.RetryAfter.Sub(time.Now()).Round(time.Hour), 6*time.Hour)
}
func TestARIRevoked(t *testing.T) {
t.Parallel()
// Setup
client, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// Issue a cert, revoke it, request ARI, and check that the suggested window
// is in the past, indicating that a renewal should happen immediately.
ir, err := authAndIssue(client, key, []acme.Identifier{{Type: "dns", Value: random_domain()}}, true, "")
test.AssertNotError(t, err, "failed to issue test cert")
cert := ir.certs[0]
err = client.RevokeCertificate(client.Account, cert, client.PrivateKey, 0)
test.AssertNotError(t, err, "failed to revoke cert")
ari, err := client.GetRenewalInfo(cert)
test.AssertNotError(t, err, "ARI request should have succeeded")
test.Assert(t, ari.SuggestedWindow.End.Before(time.Now()), "suggested window should end in the past")
test.Assert(t, ari.SuggestedWindow.Start.Before(ari.SuggestedWindow.End), "suggested window should start before it ends")
}
func TestARIForPrecert(t *testing.T) {
t.Parallel()
// Setup
client, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// Try to make a new cert for a new domain, but sabotage the CT logs so
// issuance fails.
name := random_domain()
err = ctAddRejectHost(name)
test.AssertNotError(t, err, "failed to add ct-test-srv reject host")
_, err = authAndIssue(client, key, []acme.Identifier{{Type: "dns", Value: name}}, true, "")
test.AssertError(t, err, "expected error from authAndIssue, was nil")
// Recover the precert from CT, then request ARI and check
// that it fails, because we don't serve ARI for non-issued certs.
cert, err := ctFindRejection([]string{name})
test.AssertNotError(t, err, "failed to find rejected precert")
_, err = client.GetRenewalInfo(cert)
test.AssertError(t, err, "ARI request should have failed")
test.AssertEquals(t, err.(acme.Problem).Status, 404)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/issuance_test.go | third-party/github.com/letsencrypt/boulder/test/integration/issuance_test.go | //go:build integration
package integration
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"fmt"
"os"
"strings"
"testing"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/test"
)
// TestCommonNameInCSR ensures that CSRs which have a CN set result in certs
// with the same CN set.
func TestCommonNameInCSR(t *testing.T) {
t.Parallel()
// Create an account.
client, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
// Create a private key.
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// Put together some names.
cn := random_domain()
san1 := random_domain()
san2 := random_domain()
idents := []acme.Identifier{
{Type: "dns", Value: cn},
{Type: "dns", Value: san1},
{Type: "dns", Value: san2},
}
// Issue a cert. authAndIssue includes the 0th name as the CN by default.
ir, err := authAndIssue(client, key, idents, true, "")
test.AssertNotError(t, err, "failed to issue test cert")
cert := ir.certs[0]
// Ensure that the CN is incorporated into the SANs.
test.AssertSliceContains(t, cert.DNSNames, cn)
test.AssertSliceContains(t, cert.DNSNames, san1)
test.AssertSliceContains(t, cert.DNSNames, san2)
// Ensure that the CN is preserved as the CN.
test.AssertEquals(t, cert.Subject.CommonName, cn)
}
// TestFirstCSRSANHoistedToCN ensures that CSRs which have no CN set result in
// certs with the first CSR SAN hoisted into the CN field.
func TestFirstCSRSANHoistedToCN(t *testing.T) {
t.Parallel()
// Create an account.
client, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
// Create a private key.
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// Create some names that we can sort.
san1 := "a" + random_domain()
san2 := "b" + random_domain()
idents := []acme.Identifier{
{Type: "dns", Value: san2},
{Type: "dns", Value: san1},
}
// Issue a cert using a CSR with no CN set, and the SANs in *non*-alpha order.
ir, err := authAndIssue(client, key, idents, false, "")
test.AssertNotError(t, err, "failed to issue test cert")
cert := ir.certs[0]
// Ensure that the SANs are correct, and sorted alphabetically.
test.AssertEquals(t, cert.DNSNames[0], san1)
test.AssertEquals(t, cert.DNSNames[1], san2)
// Ensure that the first SAN from the CSR is the CN.
test.Assert(t, cert.Subject.CommonName == san2, "first SAN should have been hoisted")
}
// TestCommonNameSANsTooLong tests that, when the names in an order and CSR are
// too long to be hoisted into the CN, the correct behavior results.
func TestCommonNameSANsTooLong(t *testing.T) {
t.Parallel()
// Create an account.
client, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
// Create a private key.
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// Put together some names.
san1 := fmt.Sprintf("thisdomainnameis.morethan64characterslong.forthesakeoftesting.%s", random_domain())
san2 := fmt.Sprintf("thisdomainnameis.morethan64characterslong.forthesakeoftesting.%s", random_domain())
idents := []acme.Identifier{
{Type: "dns", Value: san1},
{Type: "dns", Value: san2},
}
// Issue a cert using a CSR with no CN set.
ir, err := authAndIssue(client, key, idents, false, "")
test.AssertNotError(t, err, "failed to issue test cert")
cert := ir.certs[0]
// Ensure that the SANs are correct.
test.AssertSliceContains(t, cert.DNSNames, san1)
test.AssertSliceContains(t, cert.DNSNames, san2)
// Ensure that the CN is empty.
test.AssertEquals(t, cert.Subject.CommonName, "")
}
// TestIssuanceProfiles verifies that profile selection works, and results in
// measurable differences between certificates issued under different profiles.
// It does not test the omission of the keyEncipherment KU, because all of our
// integration test framework assumes ECDSA pubkeys for the sake of speed,
// and ECDSA certs don't get the keyEncipherment KU in either profile.
func TestIssuanceProfiles(t *testing.T) {
t.Parallel()
// Create an account.
client, err := makeClient("mailto:example@letsencrypt.org")
test.AssertNotError(t, err, "creating acme client")
profiles := client.Directory().Meta.Profiles
if len(profiles) < 2 {
t.Fatal("ACME server not advertising multiple profiles")
}
// Create a private key.
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "creating random cert key")
// Create a set of identifiers to request.
idents := []acme.Identifier{
{Type: "dns", Value: random_domain()},
}
// Get one cert for each profile that we know the test server advertises.
res, err := authAndIssue(client, key, idents, true, "legacy")
test.AssertNotError(t, err, "failed to issue under legacy profile")
test.AssertEquals(t, res.Order.Profile, "legacy")
legacy := res.certs[0]
res, err = authAndIssue(client, key, idents, true, "modern")
test.AssertNotError(t, err, "failed to issue under modern profile")
test.AssertEquals(t, res.Order.Profile, "modern")
modern := res.certs[0]
// Check that each profile worked as expected.
test.AssertEquals(t, legacy.Subject.CommonName, idents[0].Value)
test.AssertEquals(t, modern.Subject.CommonName, "")
test.AssertDeepEquals(t, legacy.ExtKeyUsage, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth})
test.AssertDeepEquals(t, modern.ExtKeyUsage, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth})
test.AssertEquals(t, len(legacy.SubjectKeyId), 20)
test.AssertEquals(t, len(modern.SubjectKeyId), 0)
}
// TestIPShortLived verifies that we will allow IP address identifiers only in
// orders that use the shortlived profile.
func TestIPShortLived(t *testing.T) {
t.Parallel()
// Create an account.
client, err := makeClient("mailto:example@letsencrypt.org")
if err != nil {
t.Fatalf("creating acme client: %s", err)
}
// Create a private key.
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("creating random cert key: %s", err)
}
// Create an IP address identifier to request.
ip := "64.112.117.122"
idents := []acme.Identifier{
{Type: "ip", Value: ip},
}
// Ensure we fail under each other profile that we know the test server advertises.
_, err = authAndIssue(client, key, idents, false, "legacy")
if err == nil {
t.Error("issued for IP address identifier under legacy profile")
}
if !strings.Contains(err.Error(), "Profile \"legacy\" does not permit ip type identifiers") {
t.Fatalf("issuing under legacy profile failed for the wrong reason: %s", err)
}
_, err = authAndIssue(client, key, idents, false, "modern")
if err == nil {
t.Error("issued for IP address identifier under modern profile")
}
if !strings.Contains(err.Error(), "Profile \"modern\" does not permit ip type identifiers") {
t.Fatalf("issuing under legacy profile failed for the wrong reason: %s", err)
}
// Get one cert for the shortlived profile.
res, err := authAndIssue(client, key, idents, false, "shortlived")
if os.Getenv("BOULDER_CONFIG_DIR") == "test/config-next" {
if err != nil {
t.Errorf("issuing under shortlived profile: %s", err)
}
if res.Order.Profile != "shortlived" {
t.Errorf("got '%s' profile, wanted 'shortlived'", res.Order.Profile)
}
cert := res.certs[0]
// Check that the shortlived profile worked as expected.
if cert.IPAddresses[0].String() != ip {
t.Errorf("got cert with first IP SAN '%s', wanted '%s'", cert.IPAddresses[0], ip)
}
} else {
if !strings.Contains(err.Error(), "Profile \"shortlived\" does not permit ip type identifiers") {
t.Errorf("issuing under shortlived profile failed for the wrong reason: %s", err)
}
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/authz_test.go | third-party/github.com/letsencrypt/boulder/test/integration/authz_test.go | //go:build integration
package integration
import (
"testing"
"time"
"github.com/eggsampler/acme/v3"
"github.com/letsencrypt/boulder/test"
)
const (
// validAuthorizationLifetime is the expected valid authorization lifetime. It
// should match the value in the RA config's "authorizationLifetimeDays"
// configuration field.
validAuthorizationLifetime = 30
)
// TestValidAuthzExpires checks that a valid authorization has the expected
// expires time.
func TestValidAuthzExpires(t *testing.T) {
t.Parallel()
c, err := makeClient()
test.AssertNotError(t, err, "makeClient failed")
// Issue for a random domain
idents := []acme.Identifier{{Type: "dns", Value: random_domain()}}
result, err := authAndIssue(c, nil, idents, true, "")
// There should be no error
test.AssertNotError(t, err, "authAndIssue failed")
// The order should be valid
test.AssertEquals(t, result.Order.Status, "valid")
// There should be one authorization URL
test.AssertEquals(t, len(result.Order.Authorizations), 1)
// Fetching the authz by URL shouldn't fail
authzURL := result.Order.Authorizations[0]
authzOb, err := c.FetchAuthorization(c.Account, authzURL)
test.AssertNotError(t, err, "FetchAuthorization failed")
// The authz should be valid and for the correct identifier
test.AssertEquals(t, authzOb.Status, "valid")
test.AssertEquals(t, authzOb.Identifier.Type, idents[0].Type)
test.AssertEquals(t, authzOb.Identifier.Value, idents[0].Value)
// The authz should have the expected expiry date, plus or minus a minute
expectedExpiresMin := time.Now().AddDate(0, 0, validAuthorizationLifetime).Add(-time.Minute)
expectedExpiresMax := expectedExpiresMin.Add(2 * time.Minute)
actualExpires := authzOb.Expires
if actualExpires.Before(expectedExpiresMin) || actualExpires.After(expectedExpiresMax) {
t.Errorf("Wrong expiry. Got %s, expected it to be between %s and %s",
actualExpires, expectedExpiresMin, expectedExpiresMax)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/integration/testdata/fermat_csr.go | third-party/github.com/letsencrypt/boulder/test/integration/testdata/fermat_csr.go | package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log"
"math/big"
"os"
)
const (
// bits is the size of the resulting RSA key, also known as "nlen" or "Length
// of the modulus N". Usually 1024, 2048, or 4096.
bits = 2048
// gap is the exponent of the different between the prime factors of the RSA
// key, i.e. |p-q| ~= 2^gap. For FIPS compliance, set this to (bits/2 - 100).
gap = 516
)
func main() {
// Generate q, which will be the smaller of the two factors. We set its length
// so that the product of two similarly-sized factors will be the desired
// bit length.
q, err := rand.Prime(rand.Reader, (bits+1)/2)
if err != nil {
log.Fatalln(err)
}
// Our starting point for p is q + 2^gap.
p := new(big.Int).Add(q, new(big.Int).Exp(big.NewInt(2), big.NewInt(gap), nil))
// Now we just keep incrementing P until we find a prime. You might think
// this would take a while, but it won't: there are a lot of primes.
attempts := 0
for {
// Using 34 rounds of Miller-Rabin primality testing is enough for the go
// stdlib, so it's enough for us.
if p.ProbablyPrime(34) {
break
}
// We know P is odd because it started as a prime (odd) plus a power of two
// (even), so we can increment by 2 to remain odd.
p.Add(p, big.NewInt(2))
attempts++
}
fmt.Println("p:", p.String())
fmt.Println("q:", q.String())
fmt.Println("Differ by", fmt.Sprintf("2^%d + %d", gap, 2*attempts))
// Construct the public modulus N from the prime factors.
n := new(big.Int).Mul(p, q)
// Construct the public key from the modulus and (fixed) public exponent.
pubkey := rsa.PublicKey{
N: n,
E: 65537,
}
// Construct the private exponent D from the prime factors.
p_1 := new(big.Int).Sub(p, big.NewInt(1))
q_1 := new(big.Int).Sub(q, big.NewInt(1))
field := new(big.Int).Mul(p_1, q_1)
d := new(big.Int).ModInverse(big.NewInt(65537), field)
// Construct the private key from the factors and private exponent.
privkey := rsa.PrivateKey{
PublicKey: pubkey,
D: d,
Primes: []*big.Int{p, q},
}
privkey.Precompute()
// Sign a CSR using this key, so we can use it in integration tests.
// Note that this step *only works on go1.23 and earlier*. Later versions of
// go detect that the prime factors are too close together and refuse to
// produce a signature.
csrDER, err := x509.CreateCertificateRequest(
rand.Reader,
&x509.CertificateRequest{
Subject: pkix.Name{CommonName: "example.com"},
PublicKey: &pubkey,
},
&privkey)
if err != nil {
log.Fatalln(err)
}
csrPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csrDER,
})
fmt.Fprint(os.Stdout, string(csrPEM))
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/ct-test-srv/main.go | third-party/github.com/letsencrypt/boulder/test/ct-test-srv/main.go | // This is a test server that implements the subset of RFC6962 APIs needed to
// run Boulder's CT log submission code. Currently it only implements add-chain.
// This is used by startservers.py.
package main
import (
"crypto/ecdsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"math/rand/v2"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/publisher"
)
type ctSubmissionRequest struct {
Chain []string `json:"chain"`
}
type integrationSrv struct {
sync.Mutex
submissions map[string]int64
// Hostnames where we refuse to provide an SCT. This is to exercise the code
// path where all CT servers fail.
rejectHosts map[string]bool
// A list of entries that we rejected based on rejectHosts.
rejected []string
key *ecdsa.PrivateKey
flakinessRate int
userAgent string
}
func readJSON(r *http.Request, output interface{}) error {
if r.Method != "POST" {
return fmt.Errorf("incorrect method; only POST allowed")
}
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
return err
}
err = json.Unmarshal(bodyBytes, output)
if err != nil {
return err
}
return nil
}
func (is *integrationSrv) addChain(w http.ResponseWriter, r *http.Request) {
is.addChainOrPre(w, r, false)
}
// addRejectHost takes a JSON POST with a "host" field; any subsequent
// submissions for that host will get a 400 error.
func (is *integrationSrv) addRejectHost(w http.ResponseWriter, r *http.Request) {
var rejectHostReq struct {
Host string
}
err := readJSON(r, &rejectHostReq)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
is.Lock()
defer is.Unlock()
is.rejectHosts[rejectHostReq.Host] = true
w.Write([]byte{})
}
// getRejections returns a JSON array containing strings; those strings are
// base64 encodings of certificates or precertificates that were rejected due to
// the rejectHosts mechanism.
func (is *integrationSrv) getRejections(w http.ResponseWriter, r *http.Request) {
is.Lock()
defer is.Unlock()
output, err := json.Marshal(is.rejected)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
w.Write(output)
}
// shouldReject checks if the given host is in the rejectHosts list for the
// integrationSrv. If it is, then the chain is appended to the integrationSrv
// rejected list and true is returned indicating the request should be rejected.
func (is *integrationSrv) shouldReject(host, chain string) bool {
is.Lock()
defer is.Unlock()
if is.rejectHosts[host] {
is.rejected = append(is.rejected, chain)
return true
}
return false
}
func (is *integrationSrv) addPreChain(w http.ResponseWriter, r *http.Request) {
is.addChainOrPre(w, r, true)
}
func (is *integrationSrv) addChainOrPre(w http.ResponseWriter, r *http.Request, precert bool) {
if is.userAgent != "" && r.UserAgent() != is.userAgent {
http.Error(w, "invalid user-agent", http.StatusBadRequest)
return
}
if r.Method != "POST" {
http.NotFound(w, r)
return
}
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var addChainReq ctSubmissionRequest
err = json.Unmarshal(bodyBytes, &addChainReq)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(addChainReq.Chain) == 0 {
w.WriteHeader(400)
return
}
b, err := base64.StdEncoding.DecodeString(addChainReq.Chain[0])
if err != nil {
w.WriteHeader(400)
return
}
cert, err := x509.ParseCertificate(b)
if err != nil {
w.WriteHeader(400)
return
}
hostnames := strings.Join(cert.DNSNames, ",")
for _, h := range cert.DNSNames {
if is.shouldReject(h, addChainReq.Chain[0]) {
w.WriteHeader(400)
return
}
}
is.Lock()
is.submissions[hostnames]++
is.Unlock()
if is.flakinessRate != 0 && rand.IntN(100) < is.flakinessRate {
time.Sleep(10 * time.Second)
}
w.WriteHeader(http.StatusOK)
w.Write(publisher.CreateTestingSignedSCT(addChainReq.Chain, is.key, precert, time.Now()))
}
func (is *integrationSrv) getSubmissions(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.NotFound(w, r)
return
}
is.Lock()
hostnames := r.URL.Query().Get("hostnames")
submissions := is.submissions[hostnames]
is.Unlock()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%d", submissions)
}
type config struct {
Personalities []Personality
}
type Personality struct {
// If present, the expected UserAgent of the reporter to this test CT log.
UserAgent string
// Port (and optionally IP) to listen on
Addr string
// Private key for signing SCTs
// Generate your own with:
// openssl ecparam -name prime256v1 -genkey -outform der -noout | base64 -w 0
PrivKey string
// FlakinessRate is an integer between 0-100 that controls how often the log
// "flakes", i.e. fails to respond in a reasonable time frame.
FlakinessRate int
}
func runPersonality(p Personality) {
keyDER, err := base64.StdEncoding.DecodeString(p.PrivKey)
if err != nil {
log.Fatal(err)
}
key, err := x509.ParseECPrivateKey(keyDER)
if err != nil {
log.Fatal(err)
}
pubKeyBytes, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
log.Fatal(err)
}
is := integrationSrv{
key: key,
flakinessRate: p.FlakinessRate,
submissions: make(map[string]int64),
rejectHosts: make(map[string]bool),
userAgent: p.UserAgent,
}
m := http.NewServeMux()
m.HandleFunc("/submissions", is.getSubmissions)
m.HandleFunc("/ct/v1/add-pre-chain", is.addPreChain)
m.HandleFunc("/ct/v1/add-chain", is.addChain)
m.HandleFunc("/add-reject-host", is.addRejectHost)
m.HandleFunc("/get-rejections", is.getRejections)
srv := &http.Server{ //nolint: gosec // No ReadHeaderTimeout is fine for test-only code.
Addr: p.Addr,
Handler: m,
}
logID := sha256.Sum256(pubKeyBytes)
log.Printf("ct-test-srv on %s with pubkey: %s, log ID: %s, flakiness: %d%%", p.Addr,
base64.StdEncoding.EncodeToString(pubKeyBytes), base64.StdEncoding.EncodeToString(logID[:]), p.FlakinessRate)
log.Fatal(srv.ListenAndServe())
}
func main() {
configFile := flag.String("config", "", "Path to config file.")
flag.Parse()
data, err := os.ReadFile(*configFile)
if err != nil {
log.Fatal(err)
}
var c config
err = json.Unmarshal(data, &c)
if err != nil {
log.Fatal(err)
}
for _, p := range c.Personalities {
go runPersonality(p)
}
cmd.WaitForSignal()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/inmem/nonce/nonce.go | third-party/github.com/letsencrypt/boulder/test/inmem/nonce/nonce.go | package inmemnonce
import (
"context"
"github.com/go-jose/go-jose/v4"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/letsencrypt/boulder/nonce"
noncepb "github.com/letsencrypt/boulder/nonce/proto"
)
// Service implements noncepb.NonceServiceClient for tests.
type Service struct {
*nonce.NonceService
}
var _ noncepb.NonceServiceClient = &Service{}
// Nonce implements proto.NonceServiceClient
func (imns *Service) Nonce(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*noncepb.NonceMessage, error) {
n, err := imns.NonceService.Nonce()
if err != nil {
return nil, err
}
return &noncepb.NonceMessage{Nonce: n}, nil
}
// Redeem implements proto.NonceServiceClient
func (imns *Service) Redeem(ctx context.Context, in *noncepb.NonceMessage, opts ...grpc.CallOption) (*noncepb.ValidMessage, error) {
valid := imns.NonceService.Valid(in.Nonce)
return &noncepb.ValidMessage{Valid: valid}, nil
}
// AsSource returns a wrapper type that implements jose.NonceSource using this
// inmemory service. This is useful so that tests can get nonces for signing
// their JWS that will be accepted by the test WFE configured using this service.
func (imns *Service) AsSource() jose.NonceSource {
return nonceServiceAdapter{imns}
}
// nonceServiceAdapter changes the gRPC nonce service interface to the one
// required by jose. Used only for tests.
type nonceServiceAdapter struct {
noncepb.NonceServiceClient
}
// Nonce returns a nonce, implementing the jose.NonceSource interface
func (nsa nonceServiceAdapter) Nonce() (string, error) {
resp, err := nsa.NonceServiceClient.Nonce(context.Background(), &emptypb.Empty{})
if err != nil {
return "", err
}
return resp.Nonce, nil
}
var _ jose.NonceSource = nonceServiceAdapter{}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/inmem/sa/sa.go | third-party/github.com/letsencrypt/boulder/test/inmem/sa/sa.go | package sa
import (
"context"
"io"
corepb "github.com/letsencrypt/boulder/core/proto"
"github.com/letsencrypt/boulder/sa"
sapb "github.com/letsencrypt/boulder/sa/proto"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
)
// SA meets the `sapb.StorageAuthorityClient` interface and acts as a
// wrapper for an inner `sa.SQLStorageAuthority` (which in turn meets
// the `sapb.StorageAuthorityServer` interface). Only methods used by
// unit tests need to be implemented.
type SA struct {
sapb.StorageAuthorityClient
Impl *sa.SQLStorageAuthority
}
func (sa SA) NewRegistration(ctx context.Context, req *corepb.Registration, _ ...grpc.CallOption) (*corepb.Registration, error) {
return sa.Impl.NewRegistration(ctx, req)
}
func (sa SA) GetRegistration(ctx context.Context, req *sapb.RegistrationID, _ ...grpc.CallOption) (*corepb.Registration, error) {
return sa.Impl.GetRegistration(ctx, req)
}
func (sa SA) DeactivateRegistration(ctx context.Context, req *sapb.RegistrationID, _ ...grpc.CallOption) (*corepb.Registration, error) {
return sa.Impl.DeactivateRegistration(ctx, req)
}
func (sa SA) GetAuthorization2(ctx context.Context, req *sapb.AuthorizationID2, _ ...grpc.CallOption) (*corepb.Authorization, error) {
return sa.Impl.GetAuthorization2(ctx, req)
}
func (sa SA) GetAuthorizations2(ctx context.Context, req *sapb.GetAuthorizationsRequest, _ ...grpc.CallOption) (*sapb.Authorizations, error) {
return sa.Impl.GetAuthorizations2(ctx, req)
}
func (sa SA) GetValidAuthorizations2(ctx context.Context, req *sapb.GetValidAuthorizationsRequest, _ ...grpc.CallOption) (*sapb.Authorizations, error) {
return sa.Impl.GetValidAuthorizations2(ctx, req)
}
func (sa SA) GetValidOrderAuthorizations2(ctx context.Context, req *sapb.GetValidOrderAuthorizationsRequest, _ ...grpc.CallOption) (*sapb.Authorizations, error) {
return sa.Impl.GetValidOrderAuthorizations2(ctx, req)
}
func (sa SA) CountPendingAuthorizations2(ctx context.Context, req *sapb.RegistrationID, _ ...grpc.CallOption) (*sapb.Count, error) {
return sa.Impl.CountPendingAuthorizations2(ctx, req)
}
func (sa SA) DeactivateAuthorization2(ctx context.Context, req *sapb.AuthorizationID2, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return sa.Impl.DeactivateAuthorization2(ctx, req)
}
func (sa SA) FinalizeAuthorization2(ctx context.Context, req *sapb.FinalizeAuthorizationRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return sa.Impl.FinalizeAuthorization2(ctx, req)
}
func (sa SA) NewOrderAndAuthzs(ctx context.Context, req *sapb.NewOrderAndAuthzsRequest, _ ...grpc.CallOption) (*corepb.Order, error) {
return sa.Impl.NewOrderAndAuthzs(ctx, req)
}
func (sa SA) GetOrder(ctx context.Context, req *sapb.OrderRequest, _ ...grpc.CallOption) (*corepb.Order, error) {
return sa.Impl.GetOrder(ctx, req)
}
func (sa SA) GetOrderForNames(ctx context.Context, req *sapb.GetOrderForNamesRequest, _ ...grpc.CallOption) (*corepb.Order, error) {
return sa.Impl.GetOrderForNames(ctx, req)
}
func (sa SA) SetOrderError(ctx context.Context, req *sapb.SetOrderErrorRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return sa.Impl.SetOrderError(ctx, req)
}
func (sa SA) SetOrderProcessing(ctx context.Context, req *sapb.OrderRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return sa.Impl.SetOrderProcessing(ctx, req)
}
func (sa SA) FinalizeOrder(ctx context.Context, req *sapb.FinalizeOrderRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return sa.Impl.FinalizeOrder(ctx, req)
}
func (sa SA) AddPrecertificate(ctx context.Context, req *sapb.AddCertificateRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return sa.Impl.AddPrecertificate(ctx, req)
}
func (sa SA) AddCertificate(ctx context.Context, req *sapb.AddCertificateRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return sa.Impl.AddCertificate(ctx, req)
}
func (sa SA) RevokeCertificate(ctx context.Context, req *sapb.RevokeCertificateRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return sa.Impl.RevokeCertificate(ctx, req)
}
func (sa SA) GetLintPrecertificate(ctx context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*corepb.Certificate, error) {
return sa.Impl.GetLintPrecertificate(ctx, req)
}
func (sa SA) GetCertificateStatus(ctx context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*corepb.CertificateStatus, error) {
return sa.Impl.GetCertificateStatus(ctx, req)
}
func (sa SA) AddBlockedKey(ctx context.Context, req *sapb.AddBlockedKeyRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return sa.Impl.AddBlockedKey(ctx, req)
}
func (sa SA) FQDNSetExists(ctx context.Context, req *sapb.FQDNSetExistsRequest, _ ...grpc.CallOption) (*sapb.Exists, error) {
return sa.Impl.FQDNSetExists(ctx, req)
}
func (sa SA) FQDNSetTimestampsForWindow(ctx context.Context, req *sapb.CountFQDNSetsRequest, _ ...grpc.CallOption) (*sapb.Timestamps, error) {
return sa.Impl.FQDNSetTimestampsForWindow(ctx, req)
}
func (sa SA) PauseIdentifiers(ctx context.Context, req *sapb.PauseRequest, _ ...grpc.CallOption) (*sapb.PauseIdentifiersResponse, error) {
return sa.Impl.PauseIdentifiers(ctx, req)
}
type mockStreamResult[T any] struct {
val T
err error
}
type mockClientStream[T any] struct {
grpc.ClientStream
stream <-chan mockStreamResult[T]
}
func (c mockClientStream[T]) Recv() (T, error) {
result := <-c.stream
return result.val, result.err
}
type mockServerStream[T any] struct {
grpc.ServerStream
context context.Context
stream chan<- mockStreamResult[T]
}
func (s mockServerStream[T]) Send(val T) error {
s.stream <- mockStreamResult[T]{val: val, err: nil}
return nil
}
func (s mockServerStream[T]) Context() context.Context {
return s.context
}
func (sa SA) SerialsForIncident(ctx context.Context, req *sapb.SerialsForIncidentRequest, _ ...grpc.CallOption) (grpc.ServerStreamingClient[sapb.IncidentSerial], error) {
streamChan := make(chan mockStreamResult[*sapb.IncidentSerial])
client := mockClientStream[*sapb.IncidentSerial]{stream: streamChan}
server := mockServerStream[*sapb.IncidentSerial]{context: ctx, stream: streamChan}
go func() {
err := sa.Impl.SerialsForIncident(req, server)
if err != nil {
streamChan <- mockStreamResult[*sapb.IncidentSerial]{nil, err}
}
streamChan <- mockStreamResult[*sapb.IncidentSerial]{nil, io.EOF}
close(streamChan)
}()
return client, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/inmem/ra/ra.go | third-party/github.com/letsencrypt/boulder/test/inmem/ra/ra.go | package ra
import (
"context"
"github.com/letsencrypt/boulder/ra"
rapb "github.com/letsencrypt/boulder/ra/proto"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
)
// RA meets the `rapb.RegistrationAuthorityClient` interface and acts as a
// wrapper for an inner `*ra.RegistrationAuthorityImpl` (which in turn meets
// the `rapb.RegistrationAuthorityServer` interface). Only methods used by
// unit tests need to be implemented.
type RA struct {
rapb.RegistrationAuthorityClient
Impl *ra.RegistrationAuthorityImpl
}
// AdministrativelyRevokeCertificate is a wrapper for `*ra.RegistrationAuthorityImpl.AdministrativelyRevokeCertificate`.
func (ra RA) AdministrativelyRevokeCertificate(ctx context.Context, req *rapb.AdministrativelyRevokeCertificateRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
return ra.Impl.AdministrativelyRevokeCertificate(ctx, req)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/s3-test-srv/main.go | third-party/github.com/letsencrypt/boulder/test/s3-test-srv/main.go | package main
import (
"context"
"crypto/x509"
"flag"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/core"
"github.com/letsencrypt/boulder/revocation"
)
type s3TestSrv struct {
sync.RWMutex
allSerials map[string]revocation.Reason
allShards map[string][]byte
}
func (srv *s3TestSrv) handleS3(w http.ResponseWriter, r *http.Request) {
if r.Method == "PUT" {
srv.handleUpload(w, r)
} else if r.Method == "GET" {
srv.handleDownload(w, r)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func (srv *s3TestSrv) handleUpload(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("failed to read request body"))
return
}
crl, err := x509.ParseRevocationList(body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("failed to parse body: %s", err)))
return
}
srv.Lock()
defer srv.Unlock()
srv.allShards[r.URL.Path] = body
for _, rc := range crl.RevokedCertificateEntries {
srv.allSerials[core.SerialToString(rc.SerialNumber)] = revocation.Reason(rc.ReasonCode)
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
}
func (srv *s3TestSrv) handleDownload(w http.ResponseWriter, r *http.Request) {
srv.RLock()
defer srv.RUnlock()
body, ok := srv.allShards[r.URL.Path]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
w.Write(body)
}
func (srv *s3TestSrv) handleQuery(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
serial := r.URL.Query().Get("serial")
if serial == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
srv.RLock()
defer srv.RUnlock()
reason, ok := srv.allSerials[serial]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("%d", reason)))
}
func (srv *s3TestSrv) handleReset(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
srv.Lock()
defer srv.Unlock()
srv.allSerials = make(map[string]revocation.Reason)
srv.allShards = make(map[string][]byte)
w.WriteHeader(http.StatusOK)
}
func main() {
listenAddr := flag.String("listen", "0.0.0.0:4501", "Address to listen on")
flag.Parse()
srv := s3TestSrv{
allSerials: make(map[string]revocation.Reason),
allShards: make(map[string][]byte),
}
http.HandleFunc("/", srv.handleS3)
http.HandleFunc("/query", srv.handleQuery)
http.HandleFunc("/reset", srv.handleReset)
s := http.Server{
ReadTimeout: 30 * time.Second,
Addr: *listenAddr,
}
go func() {
err := s.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
cmd.FailOnError(err, "Running TLS server")
}
}()
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = s.Shutdown(ctx)
}()
cmd.WaitForSignal()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/aia-test-srv/main.go | third-party/github.com/letsencrypt/boulder/test/aia-test-srv/main.go | package main
import (
"context"
"flag"
"fmt"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strings"
"time"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/issuance"
)
type aiaTestSrv struct {
issuersByName map[string]*issuance.Certificate
}
func (srv *aiaTestSrv) handleIssuer(w http.ResponseWriter, r *http.Request) {
issuerName, err := url.PathUnescape(r.URL.Path[1:])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
issuerName = strings.ReplaceAll(issuerName, "-", " ")
issuer, ok := srv.issuersByName[issuerName]
if !ok {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(fmt.Sprintf("issuer %q not found", issuerName)))
return
}
w.Header().Set("Content-Type", "application/pkix-cert")
w.WriteHeader(http.StatusOK)
w.Write(issuer.Certificate.Raw)
}
// This regex excludes the "...-cross.cert.pem" files, since we don't serve our
// cross-signed certs at AIA URLs.
var issuerCertRegex = regexp.MustCompile(`int-(rsa|ecdsa)-[a-z]\.cert\.pem$`)
func main() {
listenAddr := flag.String("addr", "", "Address to listen on")
hierarchyDir := flag.String("hierarchy", "", "Directory to load certs from")
flag.Parse()
files, err := os.ReadDir(*hierarchyDir)
cmd.FailOnError(err, "opening hierarchy directory")
byName := make(map[string]*issuance.Certificate)
for _, file := range files {
if issuerCertRegex.Match([]byte(file.Name())) {
cert, err := issuance.LoadCertificate(path.Join(*hierarchyDir, file.Name()))
cmd.FailOnError(err, "loading issuer certificate")
name := cert.Certificate.Subject.CommonName
if _, found := byName[name]; found {
cmd.FailOnError(fmt.Errorf("loaded two certs with CN %q", name), "")
}
byName[name] = cert
}
}
srv := aiaTestSrv{
issuersByName: byName,
}
http.HandleFunc("/", srv.handleIssuer)
s := http.Server{
ReadTimeout: 30 * time.Second,
Addr: *listenAddr,
}
go func() {
err := s.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
cmd.FailOnError(err, "Running TLS server")
}
}()
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = s.Shutdown(ctx)
}()
cmd.WaitForSignal()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/boulder-tools/flushredis/main.go | third-party/github.com/letsencrypt/boulder/test/boulder-tools/flushredis/main.go | package main
import (
"context"
"fmt"
"os"
"github.com/letsencrypt/boulder/cmd"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
bredis "github.com/letsencrypt/boulder/redis"
"github.com/redis/go-redis/v9"
)
func main() {
rc := bredis.Config{
Username: "unittest-rw",
TLS: cmd.TLSConfig{
CACertFile: "test/certs/ipki/minica.pem",
CertFile: "test/certs/ipki/localhost/cert.pem",
KeyFile: "test/certs/ipki/localhost/key.pem",
},
Lookups: []cmd.ServiceDomain{
{
Service: "redisratelimits",
Domain: "service.consul",
},
},
LookupDNSAuthority: "consul.service.consul",
}
rc.PasswordConfig = cmd.PasswordConfig{
PasswordFile: "test/secrets/ratelimits_redis_password",
}
stats := metrics.NoopRegisterer
log := blog.NewMock()
ring, err := bredis.NewRingFromConfig(rc, stats, log)
if err != nil {
fmt.Printf("while constructing ring client: %v\n", err)
os.Exit(1)
}
err = ring.ForEachShard(context.Background(), func(ctx context.Context, shard *redis.Client) error {
cmd := shard.FlushAll(ctx)
_, err := cmd.Result()
if err != nil {
return err
}
return nil
})
if err != nil {
fmt.Printf("while flushing redis shards: %v\n", err)
os.Exit(1)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/health-checker/main.go | third-party/github.com/letsencrypt/boulder/test/health-checker/main.go | package main
import (
"context"
"flag"
"fmt"
"os"
"strings"
"time"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"github.com/letsencrypt/boulder/cmd"
bgrpc "github.com/letsencrypt/boulder/grpc"
"github.com/letsencrypt/boulder/metrics"
)
type config struct {
GRPC *cmd.GRPCClientConfig
TLS *cmd.TLSConfig
}
func main() {
defer cmd.AuditPanic()
// Flag and config parsing and validation.
configFile := flag.String("config", "", "Path to the TLS configuration file")
serverAddr := flag.String("addr", "", "Address of the gRPC server to check")
hostOverride := flag.String("host-override", "", "Hostname to use for TLS certificate validation")
flag.Parse()
if *configFile == "" {
flag.Usage()
os.Exit(1)
}
var c config
err := cmd.ReadConfigFile(*configFile, &c)
cmd.FailOnError(err, "failed to read json config")
if c.GRPC.ServerAddress == "" && *serverAddr == "" {
cmd.Fail("must specify either -addr flag or client.ServerAddress config")
} else if c.GRPC.ServerAddress != "" && *serverAddr != "" {
cmd.Fail("cannot specify both -addr flag and client.ServerAddress config")
} else if c.GRPC.ServerAddress == "" {
c.GRPC.ServerAddress = *serverAddr
}
tlsConfig, err := c.TLS.Load(metrics.NoopRegisterer)
cmd.FailOnError(err, "failed to load TLS credentials")
if *hostOverride != "" {
c.GRPC.HostOverride = *hostOverride
}
// GRPC connection prerequisites.
clk := cmd.Clock()
// Health check retry and timeout.
ticker := time.NewTicker(100 * time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 10*c.GRPC.Timeout.Duration)
defer cancel()
for {
select {
case <-ticker.C:
_, hostOverride, err := c.GRPC.MakeTargetAndHostOverride()
cmd.FailOnError(err, "")
// Set the hostOverride to match the dNSName in the server certificate.
c.GRPC.HostOverride = strings.Replace(hostOverride, ".service.consul", ".boulder", 1)
fmt.Fprintf(os.Stderr, "health checking %s (%s)\n", c.GRPC.HostOverride, *serverAddr)
// Set up the GRPC connection.
conn, err := bgrpc.ClientSetup(c.GRPC, tlsConfig, metrics.NoopRegisterer, clk)
cmd.FailOnError(err, "failed to connect to service")
client := healthpb.NewHealthClient(conn)
ctx2, cancel2 := context.WithTimeout(ctx, c.GRPC.Timeout.Duration)
defer cancel2()
// Make the health check.
req := &healthpb.HealthCheckRequest{
Service: "",
}
resp, err := client.Check(ctx2, req)
if err != nil {
if strings.Contains(err.Error(), "authentication handshake failed") {
cmd.Fail(fmt.Sprintf("health checking %s (%s): %s\n", c.GRPC.HostOverride, *serverAddr, err))
}
fmt.Fprintf(os.Stderr, "health checking %s (%s): %s\n", c.GRPC.HostOverride, *serverAddr, err)
} else if resp.Status == healthpb.HealthCheckResponse_SERVING {
return
} else {
cmd.Fail(fmt.Sprintf("service %s failed health check with status %s", *serverAddr, resp.Status))
}
case <-ctx.Done():
cmd.Fail(fmt.Sprintf("timed out waiting for %s health check", *serverAddr))
}
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/ocsp/ocsp_forever/main.go | third-party/github.com/letsencrypt/boulder/test/ocsp/ocsp_forever/main.go | package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"time"
prom "github.com/prometheus/client_golang/prometheus"
promhttp "github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/letsencrypt/boulder/test/ocsp/helper"
)
var listenAddress = flag.String("listen", ":8080", "Port to listen on")
var interval = flag.String("interval", "1m", "Time to sleep between fetches")
var (
response_count = prom.NewCounterVec(prom.CounterOpts{
Name: "responses",
Help: "completed responses",
}, nil)
errors_count = prom.NewCounterVec(prom.CounterOpts{
Name: "errors",
Help: "errored responses",
}, nil)
request_time_seconds_hist = prom.NewHistogram(prom.HistogramOpts{
Name: "request_time_seconds",
Help: "time a request takes",
})
request_time_seconds_summary = prom.NewSummary(prom.SummaryOpts{
Name: "request_time_seconds_summary",
Help: "time a request takes",
})
response_age_seconds = prom.NewHistogram(prom.HistogramOpts{
Name: "response_age_seconds",
Help: "how old OCSP responses were",
Buckets: []float64{24 * time.Hour.Seconds(), 48 * time.Hour.Seconds(),
72 * time.Hour.Seconds(), 96 * time.Hour.Seconds(), 120 * time.Hour.Seconds()},
})
response_age_seconds_summary = prom.NewSummary(prom.SummaryOpts{
Name: "response_age_seconds_summary",
Help: "how old OCSP responses were",
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001, 1: 0.0001},
})
)
func init() {
prom.MustRegister(response_count)
prom.MustRegister(request_time_seconds_hist)
prom.MustRegister(request_time_seconds_summary)
prom.MustRegister(response_age_seconds)
prom.MustRegister(response_age_seconds_summary)
}
func do(f string, config helper.Config) {
start := time.Now()
resp, err := helper.ReqFile(f, config)
latency := time.Since(start)
if err != nil {
errors_count.With(prom.Labels{}).Inc()
fmt.Fprintf(os.Stderr, "error for %s: %s\n", f, err)
}
request_time_seconds_hist.Observe(latency.Seconds())
response_count.With(prom.Labels{}).Inc()
request_time_seconds_summary.Observe(latency.Seconds())
if resp != nil {
response_age_seconds.Observe(time.Since(resp.ThisUpdate).Seconds())
response_age_seconds_summary.Observe(time.Since(resp.ThisUpdate).Seconds())
}
}
func main() {
helper.RegisterFlags()
flag.Parse()
config, err := helper.ConfigFromFlags()
if err != nil {
log.Fatal(err)
}
sleepTime, err := time.ParseDuration(*interval)
if err != nil {
log.Fatal(err)
}
http.Handle("/metrics", promhttp.Handler())
go func() {
err := http.ListenAndServe(*listenAddress, nil) //nolint: gosec // No request timeout is fine for test-only code.
if err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}()
for {
for _, pattern := range flag.Args() {
// Note: re-glob this pattern on each run, in case new certificates have
// been added. This makes it easy to keep the list of certificates to be
// checked fresh.
files, err := filepath.Glob(pattern)
if err != nil {
log.Fatal(err)
}
// Loop through the available files (potentially hundreds or thousands),
// requesting one response per `sleepTime`
for _, f := range files {
do(f, config)
time.Sleep(sleepTime)
}
}
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/ocsp/checkocsp/checkocsp.go | third-party/github.com/letsencrypt/boulder/test/ocsp/checkocsp/checkocsp.go | package main
import (
"encoding/hex"
"flag"
"fmt"
"log"
"math/big"
"os"
"strings"
"github.com/letsencrypt/boulder/test/ocsp/helper"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, `
checkocsp [OPTION]... FILE [FILE]...
OCSP-checking tool. Provide a list of filenames for certificates in PEM format,
and this tool will check OCSP for each certificate based on its AIA field.
It will return an error if the OCSP server fails to respond for any request,
if any response is invalid or has a bad signature, or if any response is too
stale.
`)
flag.PrintDefaults()
}
helper.RegisterFlags()
serials := flag.Bool("serials", false, "Parameters are hex-encoded serial numbers instead of filenames. Requires --issuer-file and --url.")
flag.Parse()
var errors bool
if len(flag.Args()) == 0 {
flag.Usage()
os.Exit(0)
}
config, err := helper.ConfigFromFlags()
if err != nil {
log.Fatal(err)
}
for _, a := range flag.Args() {
var err error
var bytes []byte
if *serials {
bytes, err = hex.DecodeString(strings.Replace(a, ":", "", -1))
if err != nil {
log.Printf("error for %s: %s\n", a, err)
}
serialNumber := big.NewInt(0).SetBytes(bytes)
_, err = helper.ReqSerial(serialNumber, config)
} else {
_, err = helper.ReqFile(a, config)
}
if err != nil {
log.Printf("error for %s: %s\n", a, err)
errors = true
}
}
if errors {
os.Exit(1)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/ocsp/checkari/main.go | third-party/github.com/letsencrypt/boulder/test/ocsp/checkari/main.go | package main
import (
"crypto"
_ "crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"math/big"
"net/http"
"os"
"github.com/letsencrypt/boulder/core"
)
// certID matches the ASN.1 structure of the CertID sequence defined by RFC6960.
type certID struct {
HashAlgorithm pkix.AlgorithmIdentifier
IssuerNameHash []byte
IssuerKeyHash []byte
SerialNumber *big.Int
}
func createRequest(cert *x509.Certificate) ([]byte, error) {
if !crypto.SHA256.Available() {
return nil, x509.ErrUnsupportedAlgorithm
}
h := crypto.SHA256.New()
h.Write(cert.RawIssuer)
issuerNameHash := h.Sum(nil)
req := certID{
pkix.AlgorithmIdentifier{ // SHA256
Algorithm: asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1},
Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */},
},
issuerNameHash,
cert.AuthorityKeyId,
cert.SerialNumber,
}
return asn1.Marshal(req)
}
func parseResponse(resp *http.Response) (*core.RenewalInfo, error) {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var res core.RenewalInfo
err = json.Unmarshal(body, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func checkARI(baseURL string, certPath string) (*core.RenewalInfo, error) {
cert, err := core.LoadCert(certPath)
if err != nil {
return nil, err
}
req, err := createRequest(cert)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/%s", baseURL, base64.RawURLEncoding.EncodeToString(req))
resp, err := http.Get(url)
if err != nil {
return nil, err
}
ri, err := parseResponse(resp)
if err != nil {
return nil, err
}
return ri, nil
}
func getARIURL(directory string) (string, error) {
resp, err := http.Get(directory)
if err != nil {
return "", err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var dir struct {
RenewalInfo string `json:"renewalInfo"`
}
err = json.Unmarshal(body, &dir)
if err != nil {
return "", err
}
return dir.RenewalInfo, nil
}
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, `
checkari [-url https://acme.api/directory] FILE [FILE]...
Tool for querying ARI. Provide a list of filenames for certificates in PEM
format, and this tool will query for and output the suggested renewal window
for each certificate.
`)
flag.PrintDefaults()
}
directory := flag.String("url", "https://acme-v02.api.letsencrypt.org/directory", "ACME server's Directory URL")
flag.Parse()
if len(flag.Args()) == 0 {
flag.Usage()
os.Exit(1)
}
ariPath, err := getARIURL(*directory)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
for _, cert := range flag.Args() {
fmt.Printf("%s:\n", cert)
window, err := checkARI(ariPath, cert)
if err != nil {
fmt.Printf("\t%s\n", err)
} else {
fmt.Printf("\tRenew after : %s\n", window.SuggestedWindow.Start)
fmt.Printf("\tRenew before: %s\n", window.SuggestedWindow.End)
}
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/ocsp/helper/helper.go | third-party/github.com/letsencrypt/boulder/test/ocsp/helper/helper.go | package helper
import (
"bytes"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/base64"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"math/big"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"golang.org/x/crypto/ocsp"
)
var (
method *string
urlOverride *string
hostOverride *string
tooSoon *int
ignoreExpiredCerts *bool
expectStatus *int
expectReason *int
issuerFile *string
)
// Config contains fields which control various behaviors of the
// checker's behavior.
type Config struct {
method string
// This URL will always be used in place of the URL in a certificate.
urlOverride string
// This URL will be used if no urlOverride is present and no OCSP URL is in the certificate.
urlFallback string
hostOverride string
tooSoon int
ignoreExpiredCerts bool
expectStatus int
expectReason int
output io.Writer
issuerFile string
}
// DefaultConfig is a Config populated with a set of curated default values
// intended for library test usage of this package.
var DefaultConfig = Config{
method: "GET",
urlOverride: "",
urlFallback: "",
hostOverride: "",
tooSoon: 76,
ignoreExpiredCerts: false,
expectStatus: -1,
expectReason: -1,
output: io.Discard,
issuerFile: "",
}
var parseFlagsOnce sync.Once
// RegisterFlags registers command-line flags that affect OCSP checking.
func RegisterFlags() {
method = flag.String("method", DefaultConfig.method, "Method to use for fetching OCSP")
urlOverride = flag.String("url", DefaultConfig.urlOverride, "URL of OCSP responder to override")
hostOverride = flag.String("host", DefaultConfig.hostOverride, "Host header to override in HTTP request")
tooSoon = flag.Int("too-soon", DefaultConfig.tooSoon, "If NextUpdate is fewer than this many hours in future, warn.")
ignoreExpiredCerts = flag.Bool("ignore-expired-certs", DefaultConfig.ignoreExpiredCerts, "If a cert is expired, don't bother requesting OCSP.")
expectStatus = flag.Int("expect-status", DefaultConfig.expectStatus, "Expect response to have this numeric status (0=Good, 1=Revoked, 2=Unknown); or -1 for no enforcement.")
expectReason = flag.Int("expect-reason", DefaultConfig.expectReason, "Expect response to have this numeric revocation reason (0=Unspecified, 1=KeyCompromise, etc); or -1 for no enforcement.")
issuerFile = flag.String("issuer-file", DefaultConfig.issuerFile, "Path to issuer file. Use as an alternative to automatic fetch of issuer from the certificate.")
}
// ConfigFromFlags returns a Config whose values are populated from any command
// line flags passed by the user, or default values if not passed. However, it
// replaces io.Discard with os.Stdout so that CLI usages of this package
// will produce output on stdout by default.
func ConfigFromFlags() (Config, error) {
parseFlagsOnce.Do(func() {
flag.Parse()
})
if method == nil || urlOverride == nil || hostOverride == nil || tooSoon == nil || ignoreExpiredCerts == nil || expectStatus == nil || expectReason == nil || issuerFile == nil {
return DefaultConfig, errors.New("ConfigFromFlags was called without registering flags. Call RegisterFlags before flag.Parse()")
}
return Config{
method: *method,
urlOverride: *urlOverride,
hostOverride: *hostOverride,
tooSoon: *tooSoon,
ignoreExpiredCerts: *ignoreExpiredCerts,
expectStatus: *expectStatus,
expectReason: *expectReason,
output: os.Stdout,
issuerFile: *issuerFile,
}, nil
}
// WithExpectStatus returns a new Config with the given expectStatus,
// and all other fields the same as the receiver.
func (template Config) WithExpectStatus(status int) Config {
ret := template
ret.expectStatus = status
return ret
}
// WithExpectReason returns a new Config with the given expectReason,
// and all other fields the same as the receiver.
func (template Config) WithExpectReason(reason int) Config {
ret := template
ret.expectReason = reason
return ret
}
func (template Config) WithURLFallback(url string) Config {
ret := template
ret.urlFallback = url
return ret
}
// WithOutput returns a new Config with the given output,
// and all other fields the same as the receiver.
func (template Config) WithOutput(w io.Writer) Config {
ret := template
ret.output = w
return ret
}
func GetIssuerFile(f string) (*x509.Certificate, error) {
certFileBytes, err := os.ReadFile(f)
if err != nil {
return nil, fmt.Errorf("reading issuer file: %w", err)
}
block, _ := pem.Decode(certFileBytes)
if block == nil {
return nil, fmt.Errorf("no pem data found in issuer file")
}
issuer, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parsing issuer certificate: %w", err)
}
return issuer, nil
}
func GetIssuer(cert *x509.Certificate) (*x509.Certificate, error) {
if cert == nil {
return nil, fmt.Errorf("nil certificate")
}
if len(cert.IssuingCertificateURL) == 0 {
return nil, fmt.Errorf("No AIA information available, can't get issuer")
}
issuerURL := cert.IssuingCertificateURL[0]
resp, err := http.Get(issuerURL)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("got http status code %d from AIA issuer url %q", resp.StatusCode, resp.Request.URL)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var issuer *x509.Certificate
contentType := resp.Header.Get("Content-Type")
if contentType == "application/x-pkcs7-mime" || contentType == "application/pkcs7-mime" {
issuer, err = parseCMS(body)
} else {
issuer, err = parse(body)
}
if err != nil {
return nil, fmt.Errorf("from %s: %w", issuerURL, err)
}
return issuer, nil
}
// parse tries to parse the bytes as a PEM or DER-encoded certificate.
func parse(body []byte) (*x509.Certificate, error) {
block, _ := pem.Decode(body)
var der []byte
if block == nil {
der = body
} else {
der = block.Bytes
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, err
}
return cert, nil
}
// parseCMS parses certificates from CMS messages of type SignedData.
func parseCMS(body []byte) (*x509.Certificate, error) {
type signedData struct {
Version int
Digests asn1.RawValue
EncapContentInfo asn1.RawValue
Certificates asn1.RawValue
}
type cms struct {
ContentType asn1.ObjectIdentifier
SignedData signedData `asn1:"explicit,tag:0"`
}
var msg cms
_, err := asn1.Unmarshal(body, &msg)
if err != nil {
return nil, fmt.Errorf("parsing CMS: %s", err)
}
cert, err := x509.ParseCertificate(msg.SignedData.Certificates.Bytes)
if err != nil {
return nil, fmt.Errorf("parsing CMS: %s", err)
}
return cert, nil
}
// ReqFile makes an OCSP request using the given config for the PEM-encoded
// certificate in fileName, and returns the response.
func ReqFile(fileName string, config Config) (*ocsp.Response, error) {
contents, err := os.ReadFile(fileName)
if err != nil {
return nil, err
}
return ReqDER(contents, config)
}
// ReqDER makes an OCSP request using the given config for the given DER-encoded
// certificate, and returns the response.
func ReqDER(der []byte, config Config) (*ocsp.Response, error) {
cert, err := parse(der)
if err != nil {
return nil, fmt.Errorf("parsing certificate: %s", err)
}
if time.Now().After(cert.NotAfter) {
if config.ignoreExpiredCerts {
return nil, nil
}
return nil, fmt.Errorf("certificate expired %s ago: %s", time.Since(cert.NotAfter), cert.NotAfter)
}
return Req(cert, config)
}
// ReqSerial makes an OCSP request using the given config for a certificate only identified by
// serial number. It requires that the Config have issuerFile set.
func ReqSerial(serialNumber *big.Int, config Config) (*ocsp.Response, error) {
if config.issuerFile == "" {
return nil, errors.New("checking OCSP by serial number requires --issuer-file")
}
return Req(&x509.Certificate{SerialNumber: serialNumber}, config)
}
// Req makes an OCSP request using the given config for the given in-memory
// certificate, and returns the response.
func Req(cert *x509.Certificate, config Config) (*ocsp.Response, error) {
var issuer *x509.Certificate
var err error
if config.issuerFile == "" {
issuer, err = GetIssuer(cert)
if err != nil {
return nil, fmt.Errorf("problem getting issuer (try --issuer-file flag instead): %w", err)
}
} else {
issuer, err = GetIssuerFile(config.issuerFile)
}
if err != nil {
return nil, fmt.Errorf("getting issuer: %s", err)
}
req, err := ocsp.CreateRequest(cert, issuer, nil)
if err != nil {
return nil, fmt.Errorf("creating OCSP request: %s", err)
}
ocspURL, err := getOCSPURL(cert, config.urlOverride, config.urlFallback)
if err != nil {
return nil, err
}
httpResp, err := sendHTTPRequest(req, ocspURL, config.method, config.hostOverride, config.output)
if err != nil {
return nil, err
}
respBytes, err := io.ReadAll(httpResp.Body)
defer httpResp.Body.Close()
if err != nil {
return nil, err
}
fmt.Fprintf(config.output, "HTTP %d\n", httpResp.StatusCode)
for k, v := range httpResp.Header {
for _, vv := range v {
fmt.Fprintf(config.output, "%s: %s\n", k, vv)
}
}
if httpResp.StatusCode != 200 {
return nil, StatusCodeError{httpResp.StatusCode, respBytes}
}
if len(respBytes) == 0 {
return nil, fmt.Errorf("empty response body")
}
return parseAndPrint(respBytes, cert, issuer, config)
}
type StatusCodeError struct {
Code int
Body []byte
}
func (e StatusCodeError) Error() string {
return fmt.Sprintf("HTTP status code %d, body: %s", e.Code, e.Body)
}
func sendHTTPRequest(
req []byte,
ocspURL *url.URL,
method string,
host string,
output io.Writer,
) (*http.Response, error) {
encodedReq := base64.StdEncoding.EncodeToString(req)
var httpRequest *http.Request
var err error
if method == "GET" {
ocspURL.Path = encodedReq
fmt.Fprintf(output, "Fetching %s\n", ocspURL.String())
httpRequest, err = http.NewRequest("GET", ocspURL.String(), http.NoBody)
} else if method == "POST" {
fmt.Fprintf(output, "POSTing request, reproduce with: curl -i --data-binary @- %s < <(base64 -d <<<%s)\n",
ocspURL, encodedReq)
httpRequest, err = http.NewRequest("POST", ocspURL.String(), bytes.NewBuffer(req))
} else {
return nil, fmt.Errorf("invalid method %s, expected GET or POST", method)
}
if err != nil {
return nil, err
}
httpRequest.Header.Add("Content-Type", "application/ocsp-request")
if host != "" {
httpRequest.Host = host
}
client := http.Client{
Timeout: 5 * time.Second,
}
return client.Do(httpRequest)
}
func getOCSPURL(cert *x509.Certificate, urlOverride, urlFallback string) (*url.URL, error) {
var ocspServer string
if urlOverride != "" {
ocspServer = urlOverride
} else if len(cert.OCSPServer) > 0 {
ocspServer = cert.OCSPServer[0]
} else if len(urlFallback) > 0 {
ocspServer = urlFallback
} else {
return nil, fmt.Errorf("no ocsp servers in cert")
}
ocspURL, err := url.Parse(ocspServer)
if err != nil {
return nil, fmt.Errorf("parsing URL: %s", err)
}
return ocspURL, nil
}
// checkSignerTimes checks that the OCSP response is within the
// validity window of whichever certificate signed it, and that that
// certificate is currently valid.
func checkSignerTimes(resp *ocsp.Response, issuer *x509.Certificate, output io.Writer) error {
var ocspSigner = issuer
if delegatedSigner := resp.Certificate; delegatedSigner != nil {
ocspSigner = delegatedSigner
fmt.Fprintf(output, "Using delegated OCSP signer from response: %s\n",
base64.StdEncoding.EncodeToString(ocspSigner.Raw))
}
if resp.NextUpdate.After(ocspSigner.NotAfter) {
return fmt.Errorf("OCSP response is valid longer than OCSP signer (%s): %s is after %s",
ocspSigner.Subject, resp.NextUpdate, ocspSigner.NotAfter)
}
if resp.ThisUpdate.Before(ocspSigner.NotBefore) {
return fmt.Errorf("OCSP response's validity begins before the OCSP signer's (%s): %s is before %s",
ocspSigner.Subject, resp.ThisUpdate, ocspSigner.NotBefore)
}
if time.Now().After(ocspSigner.NotAfter) {
return fmt.Errorf("OCSP signer (%s) expired at %s", ocspSigner.Subject, ocspSigner.NotAfter)
}
if time.Now().Before(ocspSigner.NotBefore) {
return fmt.Errorf("OCSP signer (%s) not valid until %s", ocspSigner.Subject, ocspSigner.NotBefore)
}
return nil
}
func parseAndPrint(respBytes []byte, cert, issuer *x509.Certificate, config Config) (*ocsp.Response, error) {
fmt.Fprintf(config.output, "\nDecoding body: %s\n", base64.StdEncoding.EncodeToString(respBytes))
resp, err := ocsp.ParseResponseForCert(respBytes, cert, issuer)
if err != nil {
return nil, fmt.Errorf("parsing response: %s", err)
}
var errs []error
if config.expectStatus != -1 && resp.Status != config.expectStatus {
errs = append(errs, fmt.Errorf("wrong CertStatus %d, expected %d", resp.Status, config.expectStatus))
}
if config.expectReason != -1 && resp.RevocationReason != config.expectReason {
errs = append(errs, fmt.Errorf("wrong RevocationReason %d, expected %d", resp.RevocationReason, config.expectReason))
}
timeTilExpiry := time.Until(resp.NextUpdate)
tooSoonDuration := time.Duration(config.tooSoon) * time.Hour
if timeTilExpiry < tooSoonDuration {
errs = append(errs, fmt.Errorf("NextUpdate is too soon: %s", timeTilExpiry))
}
err = checkSignerTimes(resp, issuer, config.output)
if err != nil {
errs = append(errs, fmt.Errorf("checking signature on delegated signer: %s", err))
}
fmt.Fprint(config.output, PrettyResponse(resp))
if len(errs) > 0 {
fmt.Fprint(config.output, "Errors:\n")
err := errs[0]
fmt.Fprintf(config.output, " %v\n", err.Error())
for _, e := range errs[1:] {
err = fmt.Errorf("%w; %v", err, e)
fmt.Fprintf(config.output, " %v\n", e.Error())
}
return nil, err
}
fmt.Fprint(config.output, "No errors found.\n")
return resp, nil
}
func PrettyResponse(resp *ocsp.Response) string {
var builder strings.Builder
pr := func(s string, v ...interface{}) {
fmt.Fprintf(&builder, s, v...)
}
pr("\n")
pr("Response:\n")
pr(" SerialNumber %036x\n", resp.SerialNumber)
pr(" CertStatus %d\n", resp.Status)
pr(" RevocationReason %d\n", resp.RevocationReason)
pr(" RevokedAt %s\n", resp.RevokedAt)
pr(" ProducedAt %s\n", resp.ProducedAt)
pr(" ThisUpdate %s\n", resp.ThisUpdate)
pr(" NextUpdate %s\n", resp.NextUpdate)
pr(" SignatureAlgorithm %s\n", resp.SignatureAlgorithm)
pr(" IssuerHash %s\n", resp.IssuerHash)
if resp.Extensions != nil {
pr(" Extensions %#v\n", resp.Extensions)
}
if resp.Certificate != nil {
pr(" Certificate:\n")
pr(" Subject: %s\n", resp.Certificate.Subject)
pr(" Issuer: %s\n", resp.Certificate.Issuer)
pr(" NotBefore: %s\n", resp.Certificate.NotBefore)
pr(" NotAfter: %s\n", resp.Certificate.NotAfter)
}
var responder pkix.RDNSequence
_, err := asn1.Unmarshal(resp.RawResponderName, &responder)
if err != nil {
pr(" Responder: error (%s)\n", err)
} else {
pr(" Responder: %s\n", responder)
}
return builder.String()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/list-features/list-features.go | third-party/github.com/letsencrypt/boulder/test/list-features/list-features.go | package main
import (
"fmt"
"reflect"
"github.com/letsencrypt/boulder/features"
)
func main() {
for _, flag := range reflect.VisibleFields(reflect.TypeOf(features.Config{})) {
fmt.Println(flag.Name)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/test/certs/webpki.go | third-party/github.com/letsencrypt/boulder/test/certs/webpki.go | // generate.go is a helper utility for integration tests.
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"text/template"
"github.com/letsencrypt/boulder/cmd"
blog "github.com/letsencrypt/boulder/log"
)
// createSlot initializes a SoftHSM slot and token. SoftHSM chooses the highest empty
// slot, initializes it, and then assigns it a new randomly chosen slot ID. Since we can't
// predict this ID we need to parse out the new ID so that we can use it in the ceremony
// configs.
func createSlot(label string) (string, error) {
output, err := exec.Command("softhsm2-util", "--init-token", "--free", "--label", label, "--pin", "1234", "--so-pin", "5678").CombinedOutput()
if err != nil {
return "", err
}
re := regexp.MustCompile(`to slot (\d+)`)
matches := re.FindSubmatch(output)
if len(matches) != 2 {
return "", errors.New("unexpected number of slot matches")
}
return string(matches[1]), nil
}
// genKey is used to run a root key ceremony with a given config, replacing
// SlotID in the YAML with a specific slot ID.
func genKey(path string, inSlot string) error {
tmpPath, err := rewriteConfig(path, map[string]string{"SlotID": inSlot})
if err != nil {
return err
}
output, err := exec.Command("./bin/ceremony", "-config", tmpPath).CombinedOutput()
if err != nil {
return fmt.Errorf("error running ceremony for %s: %s:\n%s", tmpPath, err, string(output))
}
return nil
}
// rewriteConfig creates a temporary config based on the template at path
// using the variables in rewrites.
func rewriteConfig(path string, rewrites map[string]string) (string, error) {
tmplBytes, err := os.ReadFile(path)
if err != nil {
return "", err
}
tmp, err := os.CreateTemp(os.TempDir(), "ceremony-config")
if err != nil {
return "", err
}
defer tmp.Close()
tmpl, err := template.New("config").Parse(string(tmplBytes))
if err != nil {
return "", err
}
err = tmpl.Execute(tmp, rewrites)
if err != nil {
return "", err
}
return tmp.Name(), nil
}
// runCeremony is used to run a ceremony with a given config.
func runCeremony(path string) error {
output, err := exec.Command("./bin/ceremony", "-config", path).CombinedOutput()
if err != nil {
return fmt.Errorf("error running ceremony for %s: %s:\n%s", path, err, string(output))
}
return nil
}
func main() {
_ = blog.Set(blog.StdoutLogger(6))
defer cmd.AuditPanic()
// Create SoftHSM slots for the root signing keys
rsaRootKeySlot, err := createSlot("Root RSA")
cmd.FailOnError(err, "failed creating softhsm2 slot for RSA root key")
ecdsaRootKeySlot, err := createSlot("Root ECDSA")
cmd.FailOnError(err, "failed creating softhsm2 slot for ECDSA root key")
// Generate the root signing keys and certificates
err = genKey("test/certs/root-ceremony-rsa.yaml", rsaRootKeySlot)
cmd.FailOnError(err, "failed to generate RSA root key + root cert")
err = genKey("test/certs/root-ceremony-ecdsa.yaml", ecdsaRootKeySlot)
cmd.FailOnError(err, "failed to generate ECDSA root key + root cert")
// Do everything for all of the intermediates
for _, alg := range []string{"rsa", "ecdsa"} {
rootKeySlot := rsaRootKeySlot
if alg == "ecdsa" {
rootKeySlot = ecdsaRootKeySlot
}
for _, inst := range []string{"a", "b", "c"} {
name := fmt.Sprintf("int %s %s", alg, inst)
// Note: The file names produced by this script (as a combination of this
// line, and the rest of the file name as specified in the various yaml
// template files) are meaningful and are consumed by aia-test-srv. If
// you change the structure of these file names, you will need to change
// aia-test-srv as well to recognize and consume the resulting files.
fileName := strings.Replace(name, " ", "-", -1)
// Create SoftHSM slot
keySlot, err := createSlot(name)
cmd.FailOnError(err, "failed to create softhsm2 slot for intermediate key")
// Generate key
keyConfigTemplate := fmt.Sprintf("test/certs/intermediate-key-ceremony-%s.yaml", alg)
keyConfig, err := rewriteConfig(keyConfigTemplate, map[string]string{
"SlotID": keySlot,
"Label": name,
"FileName": fileName,
})
cmd.FailOnError(err, "failed to rewrite intermediate key ceremony config")
err = runCeremony(keyConfig)
cmd.FailOnError(err, "failed to generate intermediate key")
// Generate cert
certConfigTemplate := fmt.Sprintf("test/certs/intermediate-cert-ceremony-%s.yaml", alg)
certConfig, err := rewriteConfig(certConfigTemplate, map[string]string{
"SlotID": rootKeySlot,
"CommonName": name,
"FileName": fileName,
})
cmd.FailOnError(err, "failed to rewrite intermediate cert ceremony config")
err = runCeremony(certConfig)
cmd.FailOnError(err, "failed to generate intermediate cert")
// Generate cross-certs, if necessary
if alg == "rsa" {
continue
}
crossConfigTemplate := fmt.Sprintf("test/certs/intermediate-cert-ceremony-%s-cross.yaml", alg)
crossConfig, err := rewriteConfig(crossConfigTemplate, map[string]string{
"SlotID": rsaRootKeySlot,
"CommonName": name,
"FileName": fileName,
})
cmd.FailOnError(err, "failed to rewrite intermediate cross-cert ceremony config")
err = runCeremony(crossConfig)
cmd.FailOnError(err, "failed to generate intermediate cross-cert")
}
}
// Create CRLs stating that the intermediates are not revoked.
rsaTmpCRLConfig, err := rewriteConfig("test/certs/root-crl-rsa.yaml", map[string]string{
"SlotID": rsaRootKeySlot,
})
cmd.FailOnError(err, "failed to rewrite RSA root CRL config with key ID")
err = runCeremony(rsaTmpCRLConfig)
cmd.FailOnError(err, "failed to generate RSA root CRL")
ecdsaTmpCRLConfig, err := rewriteConfig("test/certs/root-crl-ecdsa.yaml", map[string]string{
"SlotID": ecdsaRootKeySlot,
})
cmd.FailOnError(err, "failed to rewrite ECDSA root CRL config with key ID")
err = runCeremony(ecdsaTmpCRLConfig)
cmd.FailOnError(err, "failed to generate ECDSA root CRL")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.