diff --git a/README.md b/README.md index 0da14b7b..50318503 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Currently, the `cert-controller-manager` supports certificate authorities via: - [Requesting a Certificate](#requesting-a-certificate) - [Using `commonName` and optional `dnsNames`](#using-commonname-and-optional-dnsnames) - [Follow CNAME](#follow-cname) + - [Preferred Chain](#preferred-chain) - [Using a certificate signing request (CSR)](#using-a-certificate-signing-request-csr) - [Creating JKS or PKCS#12 keystores](#creating-jks-or-pkcs12-keystores) - [Requesting a Certificate for Ingress](#requesting-a-certificate-for-ingress) @@ -311,6 +312,25 @@ DNS challenge to the target, i.e. `_acme-challenge.my-service.sandbox.other-doma If you are using an annotated ingress or service resource, the option is set by the annotation `cert.gardener.cloud/follow-cname=true`. +### Preferred Chain + +If the CA offers multiple certificate chains, you can select the chain with the optional `preferredChain` field. +The value is the Subject Common Name of the issuer. If no match, the default offered chain will be used. +Please consult the documentation of the ACME server about offered certificate chains. + +Example: + +```yaml +apiVersion: cert.gardener.cloud/v1alpha1 +kind: Certificate +metadata: + name: cert-follow + namespace: default +spec: + commonName: my-service.example-domain.com + preferredChain: "ISRG Root X1" +``` + ### Secret Labels The `secretLabels` section allows to specify labels to be set for the certificate secret. @@ -448,12 +468,13 @@ See also [examples/40-ingress-echoheaders.yaml](./examples/40-ingress-echoheader annotations: # Let Gardener manage certificates for this Ingress. cert.gardener.cloud/purpose: managed - #dns.gardener.cloud/class: garden # needed on Gardener shoot clusters for managed DNS record creation (if not covered by `*.ingress...shoot.example.com) - #cert.gardener.cloud/commonname: "*.demo.mydomain.com" # optional, if not specified the first name from spec.tls[].hosts is used as common name - #cert.gardener.cloud/dnsnames: "" # optional, if not specified the names from spec.tls[].hosts are used - #cert.gardener.cloud/follow-cname: "true" # optional, to activate CNAME following for the DNS challenge + #dns.gardener.cloud/class: garden # needed on Gardener shoot clusters for managed DNS record creation (if not covered by `*.ingress...shoot.example.com) + #cert.gardener.cloud/commonname: "*.demo.mydomain.com" # optional, if not specified the first name from spec.tls[].hosts is used as common name + #cert.gardener.cloud/dnsnames: "" # optional, if not specified the names from spec.tls[].hosts are used + #cert.gardener.cloud/follow-cname: "true" # optional, to activate CNAME following for the DNS challenge #cert.gardener.cloud/secret-labels: "key1=value1,key2=value2" # optional labels for the certificate secret - #cert.gardener.cloud/issuer: issuer-name # optional to specify custom issuer (use namespace/name for shoot issuers) + #cert.gardener.cloud/issuer: issuer-name # optional to specify custom issuer (use namespace/name for shoot issuers) + #cert.gardener.cloud/preferred-chain: "chain name" # optional to specify preferred-chain (value is the Subject Common Name of the root issuer) spec: tls: - hosts: @@ -499,12 +520,13 @@ metadata: annotations: cert.gardener.cloud/secretname: test-service-secret dns.gardener.cloud/dnsnames: test-service.demo.mydomain.com - #dns.gardener.cloud/class: garden # needed on Gardener shoot clusters for managed DNS record creation - #cert.gardener.cloud/commonname: "*.demo.mydomain.com" # optional, if not specified the first name from dns.gardener.cloud/dnsnames is used as common name - #cert.gardener.cloud/dnsnames: "" # optional, if specified overrides dns.gardener.cloud/dnsnames annotation for certificate names - #cert.gardener.cloud/follow-cname: "true" # optional, to activate CNAME following for the DNS challenge + #dns.gardener.cloud/class: garden # needed on Gardener shoot clusters for managed DNS record creation + #cert.gardener.cloud/commonname: "*.demo.mydomain.com" # optional, if not specified the first name from dns.gardener.cloud/dnsnames is used as common name + #cert.gardener.cloud/dnsnames: "" # optional, if specified overrides dns.gardener.cloud/dnsnames annotation for certificate names + #cert.gardener.cloud/follow-cname: "true" # optional, to activate CNAME following for the DNS challenge #cert.gardener.cloud/secret-labels: "key1=value1,key2=value2" # optional labels for the certificate secret - #cert.gardener.cloud/issuer: issuer-name # optional to specify custom issuer (use namespace/name for shoot issuers) + #cert.gardener.cloud/issuer: issuer-name # optional to specify custom issuer (use namespace/name for shoot issuers) + #cert.gardener.cloud/preferred-chain: "chain name" # optional to specify preferred-chain (value is the Subject Common Name of the root issuer) dns.gardener.cloud/ttl: "600" name: test-service namespace: default diff --git a/charts/cert-management/templates/cert.gardener.cloud_certificates.yaml b/charts/cert-management/templates/cert.gardener.cloud_certificates.yaml index 3279430e..9dc38525 100644 --- a/charts/cert-management/templates/cert.gardener.cloud_certificates.yaml +++ b/charts/cert-management/templates/cert.gardener.cloud_certificates.yaml @@ -178,6 +178,12 @@ spec: - passwordSecretRef type: object type: object + preferredChain: + description: 'PreferredChain allows to specify the preferred certificate + chain: if the CA offers multiple certificate chains, prefer the + chain with an issuer matching this Subject Common Name. If no match, + the default offered chain will be used.' + type: string renew: description: Renew triggers a renewal if set to true type: boolean diff --git a/examples/30-cert-simple.yaml b/examples/30-cert-simple.yaml index 088d44c2..f8edcba9 100644 --- a/examples/30-cert-simple.yaml +++ b/examples/30-cert-simple.yaml @@ -33,3 +33,6 @@ spec: # For example: If a CNAME record exists '_acme-challenge.cert1.mydomain.com' => '_acme-challenge.writable.domain.com', # the DNS challenge will be written to '_acme-challenge.writable.domain.com'. #followCNAME: true + + # Optionally specify the preferred certificate chain: if the CA offers multiple certificate chains, prefer the chain with an issuer matching this Subject Common Name. If no match, the default offered chain will be used. + #preferredChain: "ISRG Root X1" \ No newline at end of file diff --git a/examples/40-ingress-echoheaders.yaml b/examples/40-ingress-echoheaders.yaml index 006aab96..5a84c7ee 100644 --- a/examples/40-ingress-echoheaders.yaml +++ b/examples/40-ingress-echoheaders.yaml @@ -9,12 +9,13 @@ metadata: namespace: default annotations: cert.gardener.cloud/purpose: managed - #dns.gardener.cloud/class: garden # needed on Gardener shoot clusters for managed DNS record creation - #cert.gardener.cloud/commonname: "*.demo.mydomain.com" # optional, if not specified the first name from spec.tls[].hosts is used as common name - #cert.gardener.cloud/dnsnames: "" # optional, if not specified the names from spec.tls[].hosts are used - #cert.gardener.cloud/follow-cname: "true" # optional, same as spec.followCNAME in certificates + #dns.gardener.cloud/class: garden # needed on Gardener shoot clusters for managed DNS record creation + #cert.gardener.cloud/commonname: "*.demo.mydomain.com" # optional, if not specified the first name from spec.tls[].hosts is used as common name + #cert.gardener.cloud/dnsnames: "" # optional, if not specified the names from spec.tls[].hosts are used + #cert.gardener.cloud/follow-cname: "true" # optional, same as spec.followCNAME in certificates #cert.gardener.cloud/secret-labels: "key1=value1,key2=value2" # optional labels for the certificate secret - #cert.gardener.cloud/issuer: issuer-name # optional to specify custom issuer (use namespace/name for shoot issuers) + #cert.gardener.cloud/issuer: issuer-name # optional to specify custom issuer (use namespace/name for shoot issuers) + #cert.gardener.cloud/preferred-chain: "chain name" # optional to specify preferred-chain (value is the Subject Common Name of the root issuer) spec: tls: - hosts: diff --git a/examples/40-service-loadbalancer.yaml b/examples/40-service-loadbalancer.yaml index 33ec2b60..61301ca0 100644 --- a/examples/40-service-loadbalancer.yaml +++ b/examples/40-service-loadbalancer.yaml @@ -9,12 +9,13 @@ metadata: cert.gardener.cloud/secretname: test-service-secret dns.gardener.cloud/dnsnames: test-service.demo.mydomain.com dns.gardener.cloud/ttl: "600" - #dns.gardener.cloud/class: garden # needed on Gardener shoot clusters for managed DNS record creation - #cert.gardener.cloud/commonname: "*.demo.mydomain.com" # optional, if not specified the first name from dns.gardener.cloud/dnsnames is used as common name - #cert.gardener.cloud/dnsnames: "" # optional, if specified overrides dns.gardener.cloud/dnsnames annotation for certificate names - #cert.gardener.cloud/follow-cname: "true" # optional, same as spec.followCNAME in certificates + #dns.gardener.cloud/class: garden # needed on Gardener shoot clusters for managed DNS record creation + #cert.gardener.cloud/commonname: "*.demo.mydomain.com" # optional, if not specified the first name from dns.gardener.cloud/dnsnames is used as common name + #cert.gardener.cloud/dnsnames: "" # optional, if specified overrides dns.gardener.cloud/dnsnames annotation for certificate names + #cert.gardener.cloud/follow-cname: "true" # optional, same as spec.followCNAME in certificates #cert.gardener.cloud/secret-labels: "key1=value1,key2=value2" # optional labels for the certificate secret - #cert.gardener.cloud/issuer: issuer-name # optional to specify custom issuer (use namespace/name for shoot issuers) + #cert.gardener.cloud/issuer: issuer-name # optional to specify custom issuer (use namespace/name for shoot issuers) + #cert.gardener.cloud/preferred-chain: "chain name" # optional to specify preferred-chain (value is the Subject Common Name of the root issuer) name: test-service namespace: default spec: diff --git a/go.mod b/go.mod index 9f610715..ffe8ae69 100644 --- a/go.mod +++ b/go.mod @@ -8,8 +8,8 @@ require ( github.com/cert-manager/cert-manager v1.11.0 github.com/gardener/controller-manager-library v0.2.1-0.20230504074505-cf120e9a982d github.com/gardener/external-dns-management v0.15.3 - github.com/go-acme/lego/v4 v4.8.0 - github.com/miekg/dns v1.1.51 + github.com/go-acme/lego/v4 v4.14.0 + github.com/miekg/dns v1.1.55 github.com/onsi/ginkgo/v2 v2.8.3 github.com/onsi/gomega v1.27.1 github.com/pavlo-v-chernykh/keystore-go/v4 v4.4.0 @@ -27,11 +27,11 @@ require ( require ( github.com/Azure/go-ntlmssp v0.0.0-20220621081337-cb9428e4ac1e // indirect - github.com/BurntSushi/toml v1.1.0 // indirect + github.com/BurntSushi/toml v1.3.2 // indirect github.com/alessio/shellescape v1.4.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver/v4 v4.0.0 // indirect - github.com/cenkalti/backoff/v4 v4.1.3 // indirect + github.com/cenkalti/backoff/v4 v4.2.1 // indirect github.com/cespare/xxhash/v2 v2.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect @@ -39,6 +39,7 @@ require ( github.com/evanphx/json-patch/v5 v5.6.0 // indirect github.com/fatih/color v1.13.0 // indirect github.com/go-asn1-ber/asn1-ber v1.5.4 // indirect + github.com/go-jose/go-jose/v3 v3.0.0 // indirect github.com/go-ldap/ldap/v3 v3.4.4 // indirect github.com/go-logr/logr v1.2.3 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect @@ -60,7 +61,7 @@ require ( github.com/json-iterator/go v1.1.12 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.16 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect @@ -74,20 +75,19 @@ require ( github.com/sirupsen/logrus v1.9.0 // indirect github.com/spf13/cobra v1.6.1 // indirect github.com/spf13/pflag v1.0.5 // indirect - golang.org/x/crypto v0.5.0 // indirect - golang.org/x/mod v0.8.0 // indirect - golang.org/x/net v0.7.0 // indirect - golang.org/x/oauth2 v0.4.0 // indirect - golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.5.0 // indirect - golang.org/x/term v0.5.0 // indirect - golang.org/x/text v0.7.0 // indirect + golang.org/x/crypto v0.10.0 // indirect + golang.org/x/mod v0.11.0 // indirect + golang.org/x/net v0.11.0 // indirect + golang.org/x/oauth2 v0.9.0 // indirect + golang.org/x/sync v0.3.0 // indirect + golang.org/x/sys v0.9.0 // indirect + golang.org/x/term v0.9.0 // indirect + golang.org/x/text v0.10.0 // indirect golang.org/x/time v0.3.0 // indirect - golang.org/x/tools v0.6.0 // indirect + golang.org/x/tools v0.10.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/protobuf v1.28.1 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - gopkg.in/square/go-jose.v2 v2.6.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/apiextensions-apiserver v0.26.4 // indirect diff --git a/go.sum b/go.sum index f4e1fb88..dcd6333a 100644 --- a/go.sum +++ b/go.sum @@ -35,8 +35,8 @@ github.com/Azure/go-ntlmssp v0.0.0-20220621081337-cb9428e4ac1e h1:NeAW1fUYUEWhft github.com/Azure/go-ntlmssp v0.0.0-20220621081337-cb9428e4ac1e/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= -github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I= -github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= +github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g= github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= @@ -58,8 +58,8 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= -github.com/cenkalti/backoff/v4 v4.1.3 h1:cFAlzYUlVYDysBEH2T5hyJZMh3+5+WCBvSnK6Q8UtC4= -github.com/cenkalti/backoff/v4 v4.1.3/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= +github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= +github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cert-manager/cert-manager v1.11.0 h1:sChJmoj9hhWuFkQMDYHnLHgYA/sSVil+hY+A1lnD3jY= github.com/cert-manager/cert-manager v1.11.0/go.mod h1:JCy2jvRi3Kp+qnRfw8TVYkOocj1thw/aDWFEHPpv4Q4= @@ -102,13 +102,15 @@ github.com/gardener/controller-manager-library v0.2.1-0.20230504074505-cf120e9a9 github.com/gardener/external-dns-management v0.15.3 h1:w7DSzUQY3iC4bKAy4RoP2Lmt/kKYAhpDEZDZr1lxluY= github.com/gardener/external-dns-management v0.15.3/go.mod h1:8Bvwsirq6BsUiCL1wEE0i2yj+BALOCI6TPOru/+ozeU= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-acme/lego/v4 v4.8.0 h1:XienkuT6ZKHe0DE/LXeGP4ZY+ft+7ZMlqtiJ7XJs2pI= -github.com/go-acme/lego/v4 v4.8.0/go.mod h1:MXCdgHuQh25bfi/tPpyOV/9k2p1JVu6oxXcylAwkouI= +github.com/go-acme/lego/v4 v4.14.0 h1:/skZoRHgVh0d2RK7l1g3Ch8HqeqP9LB8ZEjLdGEpcDE= +github.com/go-acme/lego/v4 v4.14.0/go.mod h1:zjmvNCDLGz7GrC1OqdVpVmZFKSRabEDtWbdzmcpBsGo= github.com/go-asn1-ber/asn1-ber v1.5.4 h1:vXT6d/FNDiELJnLb6hGNa309LMsrCoYFvpwHDF0+Y1A= github.com/go-asn1-ber/asn1-ber v1.5.4/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-jose/go-jose/v3 v3.0.0 h1:s6rrhirfEP/CGIoc6p+PZAeogN2SxKav6Wp7+dyMWVo= +github.com/go-jose/go-jose/v3 v3.0.0/go.mod h1:RNkWWRld676jZEYoV3+XK8L2ZnNSvIsxFMht0mSX+u8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= @@ -251,13 +253,14 @@ github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxec github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= -github.com/miekg/dns v1.1.51 h1:0+Xg7vObnhrz/4ZCZcZh7zPXlmU0aveS2HDBd0m0qSo= -github.com/miekg/dns v1.1.51/go.mod h1:2Z9d3CP1LQWihRZUf29mQ19yDThaI4DAYzte2CaQW5c= +github.com/miekg/dns v1.1.55 h1:GoQ4hpsj0nFLYe+bWiCToyrBEJXkQfOOIvFGFy0lEgo= +github.com/miekg/dns v1.1.55/go.mod h1:uInx36IzPl7FYnDcMeVWxj9byh7DutNykX4G9Sj60FY= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -343,7 +346,7 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= @@ -351,7 +354,6 @@ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -362,13 +364,13 @@ golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE= -golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= +golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM= +golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -401,10 +403,8 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU= +golang.org/x/mod v0.11.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -434,17 +434,14 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= -golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= -golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.11.0 h1:Gi2tvZIJyBtO9SDr1q9h5hEQCp/4L2RQ+ar0qjx2oNU= +golang.org/x/net v0.11.0/go.mod h1:2L/ixqYpgIVXmeoSA/4Lu7BzTG4KIyPIryS4IsOd1oQ= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -452,8 +449,8 @@ golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4Iltr golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= -golang.org/x/oauth2 v0.4.0 h1:NF0gk8LVPg1Ml7SSbGyySuoxdsXitj7TvgvuRxIMc/M= -golang.org/x/oauth2 v0.4.0/go.mod h1:RznEsdpjGAINPTOF0UH/t+xJ75L18YO3Ho6Pyn+uRec= +golang.org/x/oauth2 v0.9.0 h1:BPpt2kU7oMRq3kCHAA1tbSEshXRw1LpG2ztgDwrzuAs= +golang.org/x/oauth2 v0.9.0/go.mod h1:qYgFZaFiu6Wg24azG8bdV52QJXJGbZzIIsRCdVKzbLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -464,9 +461,8 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -510,18 +506,15 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s= +golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= -golang.org/x/term v0.5.0 h1:n2a8QNdAb0sZNpU9R1ALUXBbY+w51fCQDN+7EdxNBsY= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.9.0 h1:GRRCnKYhdQrD8kfRAdQ6Zcw1P0OcELxGLKJvtjVMZ28= +golang.org/x/term v0.9.0/go.mod h1:M6DEAAIenWoTxdKrOltXcmDY3rSplQUkrvaDU5FcQyo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -530,9 +523,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.10.0 h1:UpjohKhiEgNc0CSauXmwYftY1+LlaC75SJwh0SgCX58= +golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -581,10 +573,8 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k= -golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.10.0 h1:tvDr/iQoUqNdohiYm0LmmKcBk+q86lb9EprIUFhHHGg= +golang.org/x/tools v0.10.0/go.mod h1:UJwyiVBsOA2uwvK/e5OY3GTpDUJriEd+/YlqAwLPmyM= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -684,8 +674,6 @@ gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -gopkg.in/square/go-jose.v2 v2.6.0 h1:NGk74WTnPKBNUhNzQX7PYcTLUjoq7mzKk2OKbvwk2iI= -gopkg.in/square/go-jose.v2 v2.6.0/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/pkg/apis/cert/crds/cert.gardener.cloud_certificates.yaml b/pkg/apis/cert/crds/cert.gardener.cloud_certificates.yaml index 994aa6a1..6965b5c6 100644 --- a/pkg/apis/cert/crds/cert.gardener.cloud_certificates.yaml +++ b/pkg/apis/cert/crds/cert.gardener.cloud_certificates.yaml @@ -172,6 +172,12 @@ spec: - passwordSecretRef type: object type: object + preferredChain: + description: 'PreferredChain allows to specify the preferred certificate + chain: if the CA offers multiple certificate chains, prefer the + chain with an issuer matching this Subject Common Name. If no match, + the default offered chain will be used.' + type: string renew: description: Renew triggers a renewal if set to true type: boolean diff --git a/pkg/apis/cert/crds/zz_generated_crds.go b/pkg/apis/cert/crds/zz_generated_crds.go index 228ec6b8..69ab98a8 100644 --- a/pkg/apis/cert/crds/zz_generated_crds.go +++ b/pkg/apis/cert/crds/zz_generated_crds.go @@ -475,6 +475,12 @@ spec: - passwordSecretRef type: object type: object + preferredChain: + description: 'PreferredChain allows to specify the preferred certificate + chain: if the CA offers multiple certificate chains, prefer the + chain with an issuer matching this Subject Common Name. If no match, + the default offered chain will be used.' + type: string renew: description: Renew triggers a renewal if set to true type: boolean diff --git a/pkg/apis/cert/v1alpha1/certificate.go b/pkg/apis/cert/v1alpha1/certificate.go index c841c7d3..ff357d77 100644 --- a/pkg/apis/cert/v1alpha1/certificate.go +++ b/pkg/apis/cert/v1alpha1/certificate.go @@ -77,6 +77,9 @@ type CertificateSpec struct { // Keystores configures additional keystore output formats stored in the `secretName`/`secretRef` Secret resource. // +optional Keystores *CertificateKeystores `json:"keystores,omitempty"` + // PreferredChain allows to specify the preferred certificate chain: if the CA offers multiple certificate chains, prefer the chain with an issuer matching this Subject Common Name. If no match, the default offered chain will be used. + // +optional + PreferredChain *string `json:"preferredChain,omitempty"` } // IssuerRef is the reference of the issuer by name. diff --git a/pkg/apis/cert/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/cert/v1alpha1/zz_generated.deepcopy.go index 2a505682..a2741d13 100644 --- a/pkg/apis/cert/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/apis/cert/v1alpha1/zz_generated.deepcopy.go @@ -419,6 +419,11 @@ func (in *CertificateSpec) DeepCopyInto(out *CertificateSpec) { *out = new(CertificateKeystores) (*in).DeepCopyInto(*out) } + if in.PreferredChain != nil { + in, out := &in.PreferredChain, &out.PreferredChain + *out = new(string) + **out = **in + } return } diff --git a/pkg/cert/legobridge/certificate.go b/pkg/cert/legobridge/certificate.go index 121f49aa..d21fb7f2 100644 --- a/pkg/cert/legobridge/certificate.go +++ b/pkg/cert/legobridge/certificate.go @@ -57,6 +57,8 @@ type ObtainInput struct { RenewCert *certificate.Resource // AlwaysDeactivateAuthorizations deactivates authorizations to avoid their caching AlwaysDeactivateAuthorizations bool + // PreferredChain + PreferredChain string } // DNSControllerSettings are the settings for the DNSController. @@ -124,16 +126,17 @@ func NewObtainer() Obtainer { return &obtainer{pendingDomains: map[string]time.Time{}} } -func obtainForDomains(client *lego.Client, domains []string, deactivateAuthz bool) (*certificate.Resource, error) { +func obtainForDomains(client *lego.Client, domains []string, deactivateAuthz bool, preferredChain string) (*certificate.Resource, error) { request := certificate.ObtainRequest{ Domains: domains, Bundle: true, AlwaysDeactivateAuthorizations: deactivateAuthz, + PreferredChain: preferredChain, } return client.Certificate.Obtain(request) } -func obtainForCSR(client *lego.Client, csr []byte, deactivateAuthz bool) (*certificate.Resource, error) { +func obtainForCSR(client *lego.Client, csr []byte, deactivateAuthz bool, preferredChain string) (*certificate.Resource, error) { cert, err := extractCertificateRequest(csr) if err != nil { return nil, err @@ -141,7 +144,7 @@ func obtainForCSR(client *lego.Client, csr []byte, deactivateAuthz bool) (*certi return client.Certificate.ObtainForCSR(certificate.ObtainForCSRRequest{ CSR: cert, Bundle: true, - PreferredChain: "", + PreferredChain: preferredChain, AlwaysDeactivateAuthorizations: deactivateAuthz, }) } @@ -240,9 +243,9 @@ func (o *obtainer) ObtainACME(input ObtainInput) error { } else { if input.CSR == nil { domains := append([]string{*input.CommonName}, input.DNSNames...) - certificates, err = obtainForDomains(client, domains, input.AlwaysDeactivateAuthorizations) + certificates, err = obtainForDomains(client, domains, input.AlwaysDeactivateAuthorizations, input.PreferredChain) } else { - certificates, err = obtainForCSR(client, input.CSR, input.AlwaysDeactivateAuthorizations) + certificates, err = obtainForCSR(client, input.CSR, input.AlwaysDeactivateAuthorizations, input.PreferredChain) } } count := provider.GetChallengesCount() diff --git a/pkg/cert/source/controller.go b/pkg/cert/source/controller.go index d3707ccd..4324acbc 100644 --- a/pkg/cert/source/controller.go +++ b/pkg/cert/source/controller.go @@ -42,6 +42,8 @@ const ( // AnnotCertSecretLabels is the annotation for setting labels for the secret resource // comma-separated format "key1=value1,key2=value2" AnnotCertSecretLabels = "cert.gardener.cloud/secret-labels" + // AnnotPreferredChain is the annotation for the certificate preferred chain + AnnotPreferredChain = "cert.gardener.cloud/preferred-chain" // OptClass is the cert-class command line option OptClass = "cert-class" diff --git a/pkg/cert/source/defaults.go b/pkg/cert/source/defaults.go index bd340427..cfdba277 100644 --- a/pkg/cert/source/defaults.go +++ b/pkg/cert/source/defaults.go @@ -195,13 +195,15 @@ func (s *DefaultCertSource) GetCertsInfo(logger logger.LogContext, obj resources if value, ok := resources.GetAnnotation(obj.Data(), AnnotFollowCNAME); ok { followCNAME, _ = strconv.ParseBool(value) } + preferredChain, _ := resources.GetAnnotation(obj.Data(), AnnotPreferredChain) info.Certs[secretName] = CertInfo{ - SecretName: secretName, - Domains: annotatedDomains, - IssuerName: issuer, - FollowCNAME: followCNAME, - SecretLabels: ExtractSecretLabels(obj), + SecretName: secretName, + Domains: annotatedDomains, + IssuerName: issuer, + FollowCNAME: followCNAME, + SecretLabels: ExtractSecretLabels(obj), + PreferredChain: preferredChain, } return info, nil } diff --git a/pkg/cert/source/interface.go b/pkg/cert/source/interface.go index 6f92a287..0b143aab 100644 --- a/pkg/cert/source/interface.go +++ b/pkg/cert/source/interface.go @@ -20,11 +20,12 @@ import ( // CertInfo contains basic certificate data. type CertInfo struct { - SecretName string - Domains []string - IssuerName *string - FollowCNAME bool - SecretLabels map[string]string + SecretName string + Domains []string + IssuerName *string + FollowCNAME bool + SecretLabels map[string]string + PreferredChain string } // CertsInfo contains a map of CertInfo. diff --git a/pkg/cert/source/reconciler.go b/pkg/cert/source/reconciler.go index 0a350a40..7a4c9de8 100644 --- a/pkg/cert/source/reconciler.go +++ b/pkg/cert/source/reconciler.go @@ -333,6 +333,9 @@ func (r *sourceReconciler) createEntryFor(logger logger.LogContext, obj resource cert.Spec.FollowCNAME = &info.FollowCNAME } cert.Spec.SecretLabels = info.SecretLabels + if info.PreferredChain != "" { + cert.Spec.PreferredChain = &info.PreferredChain + } e, _ := r.SlaveResoures()[0].Wrap(cert) @@ -409,6 +412,27 @@ func (r *sourceReconciler) updateEntry(logger logger.LogContext, info CertInfo, spec.SecretLabels = info.SecretLabels mod.Modify(true) } + oldFollow := spec.FollowCNAME != nil && *spec.FollowCNAME + if info.FollowCNAME != oldFollow { + if info.FollowCNAME { + spec.FollowCNAME = &info.FollowCNAME + } else { + spec.FollowCNAME = nil + } + mod.Modify(true) + } + oldPreferredChain := "" + if spec.PreferredChain != nil { + oldPreferredChain = *spec.PreferredChain + } + if info.PreferredChain != oldPreferredChain { + if info.PreferredChain != "" { + spec.PreferredChain = &info.PreferredChain + } else { + spec.PreferredChain = nil + } + mod.Modify(true) + } if mod.IsModified() { logger.Infof("update certificate object %s", obj.ObjectName()) } diff --git a/pkg/controller/issuer/certificate/reconciler.go b/pkg/controller/issuer/certificate/reconciler.go index b490b4f6..c59832e7 100644 --- a/pkg/controller/issuer/certificate/reconciler.go +++ b/pkg/controller/issuer/certificate/reconciler.go @@ -473,10 +473,14 @@ func (r *certReconciler) obtainCertificateAndPendingACME(logctx logger.LogContex if r.dnsClass != nil { targetDNSClass = *r.dnsClass } + preferredChain := "" + if cert.Spec.PreferredChain != nil { + preferredChain = *cert.Spec.PreferredChain + } input := legobridge.ObtainInput{User: reguser, DNSSettings: dnsSettings, IssuerKey: issuerKey, CommonName: cert.Spec.CommonName, DNSNames: cert.Spec.DNSNames, CSR: cert.Spec.CSR, TargetClass: targetDNSClass, Callback: callback, RequestName: objectName, RenewCert: renewCert, - AlwaysDeactivateAuthorizations: r.alwaysDeactivateAuthorizations, + AlwaysDeactivateAuthorizations: r.alwaysDeactivateAuthorizations, PreferredChain: preferredChain, } err = r.obtainer.Obtain(input) diff --git a/pkg/controller/source/ingress/handler.go b/pkg/controller/source/ingress/handler.go index abbe259a..3567527e 100644 --- a/pkg/controller/source/ingress/handler.go +++ b/pkg/controller/source/ingress/handler.go @@ -67,6 +67,8 @@ func (s *CIngressSource) GetCertsInfo(logger logger.LogContext, obj resources.Ob followCNAME, _ = strconv.ParseBool(value) } + preferredChain, _ := resources.GetAnnotation(obj.Data(), source.AnnotPreferredChain) + cn, _ := resources.GetAnnotation(obj.Data(), source.AnnotCommonName) cn = strings.TrimSpace(cn) var issuer *string @@ -95,11 +97,12 @@ func (s *CIngressSource) GetCertsInfo(logger logger.LogContext, obj resources.Ob domains = mergeCommonName(cn, tls.Hosts) } info.Certs[tls.SecretName] = source.CertInfo{ - SecretName: tls.SecretName, - Domains: domains, - IssuerName: issuer, - FollowCNAME: followCNAME, - SecretLabels: source.ExtractSecretLabels(obj), + SecretName: tls.SecretName, + Domains: domains, + IssuerName: issuer, + FollowCNAME: followCNAME, + SecretLabels: source.ExtractSecretLabels(obj), + PreferredChain: preferredChain, } } return info, err diff --git a/vendor/github.com/BurntSushi/toml/.gitignore b/vendor/github.com/BurntSushi/toml/.gitignore index cd11be96..fe79e3ad 100644 --- a/vendor/github.com/BurntSushi/toml/.gitignore +++ b/vendor/github.com/BurntSushi/toml/.gitignore @@ -1,2 +1,2 @@ -toml.test +/toml.test /toml-test diff --git a/vendor/github.com/BurntSushi/toml/COMPATIBLE b/vendor/github.com/BurntSushi/toml/COMPATIBLE deleted file mode 100644 index f621b011..00000000 --- a/vendor/github.com/BurntSushi/toml/COMPATIBLE +++ /dev/null @@ -1 +0,0 @@ -Compatible with TOML version [v1.0.0](https://toml.io/en/v1.0.0). diff --git a/vendor/github.com/BurntSushi/toml/README.md b/vendor/github.com/BurntSushi/toml/README.md index a999c356..3651cfa9 100644 --- a/vendor/github.com/BurntSushi/toml/README.md +++ b/vendor/github.com/BurntSushi/toml/README.md @@ -1,6 +1,5 @@ TOML stands for Tom's Obvious, Minimal Language. This Go package provides a -reflection interface similar to Go's standard library `json` and `xml` -packages. +reflection interface similar to Go's standard library `json` and `xml` packages. Compatible with TOML version [v1.0.0](https://toml.io/en/v1.0.0). @@ -10,7 +9,7 @@ See the [releases page](https://github.com/BurntSushi/toml/releases) for a changelog; this information is also in the git tag annotations (e.g. `git show v0.4.0`). -This library requires Go 1.13 or newer; install it with: +This library requires Go 1.13 or newer; add it to your go.mod with: % go get github.com/BurntSushi/toml@latest @@ -19,16 +18,7 @@ It also comes with a TOML validator CLI tool: % go install github.com/BurntSushi/toml/cmd/tomlv@latest % tomlv some-toml-file.toml -### Testing -This package passes all tests in [toml-test] for both the decoder and the -encoder. - -[toml-test]: https://github.com/BurntSushi/toml-test - ### Examples -This package works similar to how the Go standard library handles XML and JSON. -Namely, data is loaded into Go values via reflection. - For the simplest example, consider some TOML file as just a list of keys and values: @@ -40,7 +30,7 @@ Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z ``` -Which could be defined in Go as: +Which can be decoded with: ```go type Config struct { @@ -48,20 +38,15 @@ type Config struct { Cats []string Pi float64 Perfection []int - DOB time.Time // requires `import time` + DOB time.Time } -``` - -And then decoded with: -```go var conf Config _, err := toml.Decode(tomlData, &conf) -// handle error ``` -You can also use struct tags if your struct field name doesn't map to a TOML -key value directly: +You can also use struct tags if your struct field name doesn't map to a TOML key +value directly: ```toml some_key_NAME = "wat" @@ -73,139 +58,63 @@ type TOML struct { } ``` -Beware that like other most other decoders **only exported fields** are -considered when encoding and decoding; private fields are silently ignored. +Beware that like other decoders **only exported fields** are considered when +encoding and decoding; private fields are silently ignored. ### Using the `Marshaler` and `encoding.TextUnmarshaler` interfaces -Here's an example that automatically parses duration strings into -`time.Duration` values: +Here's an example that automatically parses values in a `mail.Address`: ```toml -[[song]] -name = "Thunder Road" -duration = "4m49s" - -[[song]] -name = "Stairway to Heaven" -duration = "8m03s" -``` - -Which can be decoded with: - -```go -type song struct { - Name string - Duration duration -} -type songs struct { - Song []song -} -var favorites songs -if _, err := toml.Decode(blob, &favorites); err != nil { - log.Fatal(err) -} - -for _, s := range favorites.Song { - fmt.Printf("%s (%s)\n", s.Name, s.Duration) -} +contacts = [ + "Donald Duck ", + "Scrooge McDuck ", +] ``` -And you'll also need a `duration` type that satisfies the -`encoding.TextUnmarshaler` interface: +Can be decoded with: ```go -type duration struct { - time.Duration +// Create address type which satisfies the encoding.TextUnmarshaler interface. +type address struct { + *mail.Address } -func (d *duration) UnmarshalText(text []byte) error { +func (a *address) UnmarshalText(text []byte) error { var err error - d.Duration, err = time.ParseDuration(string(text)) + a.Address, err = mail.ParseAddress(string(text)) return err } + +// Decode it. +func decode() { + blob := ` + contacts = [ + "Donald Duck ", + "Scrooge McDuck ", + ] + ` + + var contacts struct { + Contacts []address + } + + _, err := toml.Decode(blob, &contacts) + if err != nil { + log.Fatal(err) + } + + for _, c := range contacts.Contacts { + fmt.Printf("%#v\n", c.Address) + } + + // Output: + // &mail.Address{Name:"Donald Duck", Address:"donald@duckburg.com"} + // &mail.Address{Name:"Scrooge McDuck", Address:"scrooge@duckburg.com"} +} ``` To target TOML specifically you can implement `UnmarshalTOML` TOML interface in a similar way. ### More complex usage -Here's an example of how to load the example from the official spec page: - -```toml -# This is a TOML document. Boom. - -title = "TOML Example" - -[owner] -name = "Tom Preston-Werner" -organization = "GitHub" -bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." -dob = 1979-05-27T07:32:00Z # First class dates? Why not? - -[database] -server = "192.168.1.1" -ports = [ 8001, 8001, 8002 ] -connection_max = 5000 -enabled = true - -[servers] - - # You can indent as you please. Tabs or spaces. TOML don't care. - [servers.alpha] - ip = "10.0.0.1" - dc = "eqdc10" - - [servers.beta] - ip = "10.0.0.2" - dc = "eqdc10" - -[clients] -data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it - -# Line breaks are OK when inside arrays -hosts = [ - "alpha", - "omega" -] -``` - -And the corresponding Go types are: - -```go -type tomlConfig struct { - Title string - Owner ownerInfo - DB database `toml:"database"` - Servers map[string]server - Clients clients -} - -type ownerInfo struct { - Name string - Org string `toml:"organization"` - Bio string - DOB time.Time -} - -type database struct { - Server string - Ports []int - ConnMax int `toml:"connection_max"` - Enabled bool -} - -type server struct { - IP string - DC string -} - -type clients struct { - Data [][]interface{} - Hosts []string -} -``` - -Note that a case insensitive match will be tried if an exact match can't be -found. - -A working example of the above can be found in `_example/example.{go,toml}`. +See the [`_example/`](/_example) directory for a more complex example. diff --git a/vendor/github.com/BurntSushi/toml/decode.go b/vendor/github.com/BurntSushi/toml/decode.go index 6a871507..4d38f3bf 100644 --- a/vendor/github.com/BurntSushi/toml/decode.go +++ b/vendor/github.com/BurntSushi/toml/decode.go @@ -3,13 +3,16 @@ package toml import ( "bytes" "encoding" + "encoding/json" "fmt" "io" "io/ioutil" "math" "os" "reflect" + "strconv" "strings" + "time" ) // Unmarshaler is the interface implemented by objects that can unmarshal a @@ -18,7 +21,9 @@ type Unmarshaler interface { UnmarshalTOML(interface{}) error } -// Unmarshal decodes the contents of `p` in TOML format into a pointer `v`. +// Unmarshal decodes the contents of data in TOML format into a pointer v. +// +// See [Decoder] for a description of the decoding process. func Unmarshal(data []byte, v interface{}) error { _, err := NewDecoder(bytes.NewReader(data)).Decode(v) return err @@ -26,13 +31,12 @@ func Unmarshal(data []byte, v interface{}) error { // Decode the TOML data in to the pointer v. // -// See the documentation on Decoder for a description of the decoding process. +// See [Decoder] for a description of the decoding process. func Decode(data string, v interface{}) (MetaData, error) { return NewDecoder(strings.NewReader(data)).Decode(v) } -// DecodeFile is just like Decode, except it will automatically read the -// contents of the file at path and decode it for you. +// DecodeFile reads the contents of a file and decodes it with [Decode]. func DecodeFile(path string, v interface{}) (MetaData, error) { fp, err := os.Open(path) if err != nil { @@ -45,7 +49,7 @@ func DecodeFile(path string, v interface{}) (MetaData, error) { // Primitive is a TOML value that hasn't been decoded into a Go value. // // This type can be used for any value, which will cause decoding to be delayed. -// You can use the PrimitiveDecode() function to "manually" decode these values. +// You can use [PrimitiveDecode] to "manually" decode these values. // // NOTE: The underlying representation of a `Primitive` value is subject to // change. Do not rely on it. @@ -67,13 +71,16 @@ const ( // Decoder decodes TOML data. // -// TOML tables correspond to Go structs or maps (dealer's choice – they can be -// used interchangeably). +// TOML tables correspond to Go structs or maps; they can be used +// interchangeably, but structs offer better type safety. // // TOML table arrays correspond to either a slice of structs or a slice of maps. // -// TOML datetimes correspond to Go time.Time values. Local datetimes are parsed -// in the local timezone. +// TOML datetimes correspond to [time.Time]. Local datetimes are parsed in the +// local timezone. +// +// [time.Duration] types are treated as nanoseconds if the TOML value is an +// integer, or they're parsed with time.ParseDuration() if they're strings. // // All other TOML types (float, string, int, bool and array) correspond to the // obvious Go types. @@ -82,9 +89,9 @@ const ( // interface, in which case any primitive TOML value (floats, strings, integers, // booleans, datetimes) will be converted to a []byte and given to the value's // UnmarshalText method. See the Unmarshaler example for a demonstration with -// time duration strings. +// email addresses. // -// Key mapping +// # Key mapping // // TOML keys can map to either keys in a Go map or field names in a Go struct. // The special `toml` struct tag can be used to map TOML keys to struct fields @@ -111,6 +118,7 @@ func NewDecoder(r io.Reader) *Decoder { var ( unmarshalToml = reflect.TypeOf((*Unmarshaler)(nil)).Elem() unmarshalText = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() + primitiveType = reflect.TypeOf((*Primitive)(nil)).Elem() ) // Decode TOML data in to the pointer `v`. @@ -122,10 +130,10 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) { s = "%v" } - return MetaData{}, e("cannot decode to non-pointer "+s, reflect.TypeOf(v)) + return MetaData{}, fmt.Errorf("toml: cannot decode to non-pointer "+s, reflect.TypeOf(v)) } if rv.IsNil() { - return MetaData{}, e("cannot decode to nil value of %q", reflect.TypeOf(v)) + return MetaData{}, fmt.Errorf("toml: cannot decode to nil value of %q", reflect.TypeOf(v)) } // Check if this is a supported type: struct, map, interface{}, or something @@ -135,7 +143,7 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) { if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map && !(rv.Kind() == reflect.Interface && rv.NumMethod() == 0) && !rt.Implements(unmarshalToml) && !rt.Implements(unmarshalText) { - return MetaData{}, e("cannot decode to type %s", rt) + return MetaData{}, fmt.Errorf("toml: cannot decode to type %s", rt) } // TODO: parser should read from io.Reader? Or at the very least, make it @@ -152,25 +160,25 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) { md := MetaData{ mapping: p.mapping, - types: p.types, + keyInfo: p.keyInfo, keys: p.ordered, decoded: make(map[string]struct{}, len(p.ordered)), context: nil, + data: data, } return md, md.unify(p.mapping, rv) } -// PrimitiveDecode is just like the other `Decode*` functions, except it -// decodes a TOML value that has already been parsed. Valid primitive values -// can *only* be obtained from values filled by the decoder functions, -// including this method. (i.e., `v` may contain more `Primitive` -// values.) +// PrimitiveDecode is just like the other Decode* functions, except it decodes a +// TOML value that has already been parsed. Valid primitive values can *only* be +// obtained from values filled by the decoder functions, including this method. +// (i.e., v may contain more [Primitive] values.) // -// Meta data for primitive values is included in the meta data returned by -// the `Decode*` functions with one exception: keys returned by the Undecoded -// method will only reflect keys that were decoded. Namely, any keys hidden -// behind a Primitive will be considered undecoded. Executing this method will -// update the undecoded keys in the meta data. (See the example.) +// Meta data for primitive values is included in the meta data returned by the +// Decode* functions with one exception: keys returned by the Undecoded method +// will only reflect keys that were decoded. Namely, any keys hidden behind a +// Primitive will be considered undecoded. Executing this method will update the +// undecoded keys in the meta data. (See the example.) func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error { md.context = primValue.context defer func() { md.context = nil }() @@ -185,7 +193,7 @@ func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error { func (md *MetaData) unify(data interface{}, rv reflect.Value) error { // Special case. Look for a `Primitive` value. // TODO: #76 would make this superfluous after implemented. - if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() { + if rv.Type() == primitiveType { // Save the undecoded data and the key context into the primitive // value. context := make(Key, len(md.context)) @@ -197,17 +205,14 @@ func (md *MetaData) unify(data interface{}, rv reflect.Value) error { return nil } - // Special case. Unmarshaler Interface support. - if rv.CanAddr() { - if v, ok := rv.Addr().Interface().(Unmarshaler); ok { - return v.UnmarshalTOML(data) - } + rvi := rv.Interface() + if v, ok := rvi.(Unmarshaler); ok { + return v.UnmarshalTOML(data) } - - // Special case. Look for a value satisfying the TextUnmarshaler interface. - if v, ok := rv.Interface().(encoding.TextUnmarshaler); ok { + if v, ok := rvi.(encoding.TextUnmarshaler); ok { return md.unifyText(data, v) } + // TODO: // The behavior here is incorrect whenever a Go type satisfies the // encoding.TextUnmarshaler interface but also corresponds to a TOML hash or @@ -218,7 +223,6 @@ func (md *MetaData) unify(data interface{}, rv reflect.Value) error { k := rv.Kind() - // laziness if k >= reflect.Int && k <= reflect.Uint64 { return md.unifyInt(data, rv) } @@ -244,15 +248,14 @@ func (md *MetaData) unify(data interface{}, rv reflect.Value) error { case reflect.Bool: return md.unifyBool(data, rv) case reflect.Interface: - // we only support empty interfaces. - if rv.NumMethod() > 0 { - return e("unsupported type %s", rv.Type()) + if rv.NumMethod() > 0 { /// Only empty interfaces are supported. + return md.e("unsupported type %s", rv.Type()) } return md.unifyAnything(data, rv) case reflect.Float32, reflect.Float64: return md.unifyFloat64(data, rv) } - return e("unsupported type %s", rv.Kind()) + return md.e("unsupported type %s", rv.Kind()) } func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { @@ -261,7 +264,7 @@ func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { if mapping == nil { return nil } - return e("type mismatch for %s: expected table but found %T", + return md.e("type mismatch for %s: expected table but found %T", rv.Type().String(), mapping) } @@ -287,13 +290,14 @@ func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { if isUnifiable(subv) { md.decoded[md.context.add(key).String()] = struct{}{} md.context = append(md.context, key) + err := md.unify(datum, subv) if err != nil { return err } md.context = md.context[0 : len(md.context)-1] } else if f.name != "" { - return e("cannot write unexported field %s.%s", rv.Type().String(), f.name) + return md.e("cannot write unexported field %s.%s", rv.Type().String(), f.name) } } } @@ -301,10 +305,10 @@ func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { } func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { - if k := rv.Type().Key().Kind(); k != reflect.String { - return fmt.Errorf( - "toml: cannot decode to a map with non-string key type (%s in %q)", - k, rv.Type()) + keyType := rv.Type().Key().Kind() + if keyType != reflect.String && keyType != reflect.Interface { + return fmt.Errorf("toml: cannot decode to a map with non-string key type (%s in %q)", + keyType, rv.Type()) } tmap, ok := mapping.(map[string]interface{}) @@ -322,13 +326,22 @@ func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { md.context = append(md.context, k) rvval := reflect.Indirect(reflect.New(rv.Type().Elem())) - if err := md.unify(v, rvval); err != nil { + + err := md.unify(v, indirect(rvval)) + if err != nil { return err } md.context = md.context[0 : len(md.context)-1] rvkey := indirect(reflect.New(rv.Type().Key())) - rvkey.SetString(k) + + switch keyType { + case reflect.Interface: + rvkey.Set(reflect.ValueOf(k)) + case reflect.String: + rvkey.SetString(k) + } + rv.SetMapIndex(rvkey, rvval) } return nil @@ -343,7 +356,7 @@ func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error { return md.badtype("slice", data) } if l := datav.Len(); l != rv.Len() { - return e("expected array length %d; got TOML array of length %d", rv.Len(), l) + return md.e("expected array length %d; got TOML array of length %d", rv.Len(), l) } return md.unifySliceArray(datav, rv) } @@ -376,6 +389,18 @@ func (md *MetaData) unifySliceArray(data, rv reflect.Value) error { } func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { + _, ok := rv.Interface().(json.Number) + if ok { + if i, ok := data.(int64); ok { + rv.SetString(strconv.FormatInt(i, 10)) + } else if f, ok := data.(float64); ok { + rv.SetString(strconv.FormatFloat(f, 'f', -1, 64)) + } else { + return md.badtype("string", data) + } + return nil + } + if s, ok := data.(string); ok { rv.SetString(s) return nil @@ -384,11 +409,13 @@ func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { } func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { + rvk := rv.Kind() + if num, ok := data.(float64); ok { - switch rv.Kind() { + switch rvk { case reflect.Float32: if num < -math.MaxFloat32 || num > math.MaxFloat32 { - return e("value %f is out of range for float32", num) + return md.parseErr(errParseRange{i: num, size: rvk.String()}) } fallthrough case reflect.Float64: @@ -400,20 +427,11 @@ func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { } if num, ok := data.(int64); ok { - switch rv.Kind() { - case reflect.Float32: - if num < -maxSafeFloat32Int || num > maxSafeFloat32Int { - return e("value %d is out of range for float32", num) - } - fallthrough - case reflect.Float64: - if num < -maxSafeFloat64Int || num > maxSafeFloat64Int { - return e("value %d is out of range for float64", num) - } - rv.SetFloat(float64(num)) - default: - panic("bug") + if (rvk == reflect.Float32 && (num < -maxSafeFloat32Int || num > maxSafeFloat32Int)) || + (rvk == reflect.Float64 && (num < -maxSafeFloat64Int || num > maxSafeFloat64Int)) { + return md.parseErr(errParseRange{i: num, size: rvk.String()}) } + rv.SetFloat(float64(num)) return nil } @@ -421,50 +439,46 @@ func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { } func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error { - if num, ok := data.(int64); ok { - if rv.Kind() >= reflect.Int && rv.Kind() <= reflect.Int64 { - switch rv.Kind() { - case reflect.Int, reflect.Int64: - // No bounds checking necessary. - case reflect.Int8: - if num < math.MinInt8 || num > math.MaxInt8 { - return e("value %d is out of range for int8", num) - } - case reflect.Int16: - if num < math.MinInt16 || num > math.MaxInt16 { - return e("value %d is out of range for int16", num) - } - case reflect.Int32: - if num < math.MinInt32 || num > math.MaxInt32 { - return e("value %d is out of range for int32", num) - } + _, ok := rv.Interface().(time.Duration) + if ok { + // Parse as string duration, and fall back to regular integer parsing + // (as nanosecond) if this is not a string. + if s, ok := data.(string); ok { + dur, err := time.ParseDuration(s) + if err != nil { + return md.parseErr(errParseDuration{s}) } - rv.SetInt(num) - } else if rv.Kind() >= reflect.Uint && rv.Kind() <= reflect.Uint64 { - unum := uint64(num) - switch rv.Kind() { - case reflect.Uint, reflect.Uint64: - // No bounds checking necessary. - case reflect.Uint8: - if num < 0 || unum > math.MaxUint8 { - return e("value %d is out of range for uint8", num) - } - case reflect.Uint16: - if num < 0 || unum > math.MaxUint16 { - return e("value %d is out of range for uint16", num) - } - case reflect.Uint32: - if num < 0 || unum > math.MaxUint32 { - return e("value %d is out of range for uint32", num) - } - } - rv.SetUint(unum) - } else { - panic("unreachable") + rv.SetInt(int64(dur)) + return nil } - return nil } - return md.badtype("integer", data) + + num, ok := data.(int64) + if !ok { + return md.badtype("integer", data) + } + + rvk := rv.Kind() + switch { + case rvk >= reflect.Int && rvk <= reflect.Int64: + if (rvk == reflect.Int8 && (num < math.MinInt8 || num > math.MaxInt8)) || + (rvk == reflect.Int16 && (num < math.MinInt16 || num > math.MaxInt16)) || + (rvk == reflect.Int32 && (num < math.MinInt32 || num > math.MaxInt32)) { + return md.parseErr(errParseRange{i: num, size: rvk.String()}) + } + rv.SetInt(num) + case rvk >= reflect.Uint && rvk <= reflect.Uint64: + unum := uint64(num) + if rvk == reflect.Uint8 && (num < 0 || unum > math.MaxUint8) || + rvk == reflect.Uint16 && (num < 0 || unum > math.MaxUint16) || + rvk == reflect.Uint32 && (num < 0 || unum > math.MaxUint32) { + return md.parseErr(errParseRange{i: num, size: rvk.String()}) + } + rv.SetUint(unum) + default: + panic("unreachable") + } + return nil } func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error { @@ -489,7 +503,7 @@ func (md *MetaData) unifyText(data interface{}, v encoding.TextUnmarshaler) erro return err } s = string(text) - case TextMarshaler: + case encoding.TextMarshaler: text, err := sdata.MarshalText() if err != nil { return err @@ -515,7 +529,30 @@ func (md *MetaData) unifyText(data interface{}, v encoding.TextUnmarshaler) erro } func (md *MetaData) badtype(dst string, data interface{}) error { - return e("incompatible types: TOML key %q has type %T; destination has type %s", md.context, data, dst) + return md.e("incompatible types: TOML value has type %T; destination has type %s", data, dst) +} + +func (md *MetaData) parseErr(err error) error { + k := md.context.String() + return ParseError{ + LastKey: k, + Position: md.keyInfo[k].pos, + Line: md.keyInfo[k].pos.Line, + err: err, + input: string(md.data), + } +} + +func (md *MetaData) e(format string, args ...interface{}) error { + f := "toml: " + if len(md.context) > 0 { + f = fmt.Sprintf("toml: (last key %q): ", md.context) + p := md.keyInfo[md.context.String()].pos + if p.Line > 0 { + f = fmt.Sprintf("toml: line %d (last key %q): ", p.Line, md.context) + } + } + return fmt.Errorf(f+format, args...) } // rvalue returns a reflect.Value of `v`. All pointers are resolved. @@ -534,7 +571,11 @@ func indirect(v reflect.Value) reflect.Value { if v.Kind() != reflect.Ptr { if v.CanSet() { pv := v.Addr() - if _, ok := pv.Interface().(encoding.TextUnmarshaler); ok { + pvi := pv.Interface() + if _, ok := pvi.(encoding.TextUnmarshaler); ok { + return pv + } + if _, ok := pvi.(Unmarshaler); ok { return pv } } @@ -550,12 +591,12 @@ func isUnifiable(rv reflect.Value) bool { if rv.CanSet() { return true } - if _, ok := rv.Interface().(encoding.TextUnmarshaler); ok { + rvi := rv.Interface() + if _, ok := rvi.(encoding.TextUnmarshaler); ok { + return true + } + if _, ok := rvi.(Unmarshaler); ok { return true } return false } - -func e(format string, args ...interface{}) error { - return fmt.Errorf("toml: "+format, args...) -} diff --git a/vendor/github.com/BurntSushi/toml/decode_go116.go b/vendor/github.com/BurntSushi/toml/decode_go116.go index eddfb641..086d0b68 100644 --- a/vendor/github.com/BurntSushi/toml/decode_go116.go +++ b/vendor/github.com/BurntSushi/toml/decode_go116.go @@ -7,8 +7,8 @@ import ( "io/fs" ) -// DecodeFS is just like Decode, except it will automatically read the contents -// of the file at `path` from a fs.FS instance. +// DecodeFS reads the contents of a file from [fs.FS] and decodes it with +// [Decode]. func DecodeFS(fsys fs.FS, path string, v interface{}) (MetaData, error) { fp, err := fsys.Open(path) if err != nil { diff --git a/vendor/github.com/BurntSushi/toml/deprecated.go b/vendor/github.com/BurntSushi/toml/deprecated.go index c6af3f23..b9e30971 100644 --- a/vendor/github.com/BurntSushi/toml/deprecated.go +++ b/vendor/github.com/BurntSushi/toml/deprecated.go @@ -5,17 +5,25 @@ import ( "io" ) +// TextMarshaler is an alias for encoding.TextMarshaler. +// // Deprecated: use encoding.TextMarshaler type TextMarshaler encoding.TextMarshaler +// TextUnmarshaler is an alias for encoding.TextUnmarshaler. +// // Deprecated: use encoding.TextUnmarshaler type TextUnmarshaler encoding.TextUnmarshaler +// PrimitiveDecode is an alias for MetaData.PrimitiveDecode(). +// // Deprecated: use MetaData.PrimitiveDecode. func PrimitiveDecode(primValue Primitive, v interface{}) error { md := MetaData{decoded: make(map[string]struct{})} return md.unify(primValue.undecoded, rvalue(v)) } +// DecodeReader is an alias for NewDecoder(r).Decode(v). +// // Deprecated: use NewDecoder(reader).Decode(&value). func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { return NewDecoder(r).Decode(v) } diff --git a/vendor/github.com/BurntSushi/toml/doc.go b/vendor/github.com/BurntSushi/toml/doc.go index 099c4a77..81a7c0fe 100644 --- a/vendor/github.com/BurntSushi/toml/doc.go +++ b/vendor/github.com/BurntSushi/toml/doc.go @@ -1,13 +1,11 @@ -/* -Package toml implements decoding and encoding of TOML files. - -This package supports TOML v1.0.0, as listed on https://toml.io - -There is also support for delaying decoding with the Primitive type, and -querying the set of keys in a TOML document with the MetaData type. - -The github.com/BurntSushi/toml/cmd/tomlv package implements a TOML validator, -and can be used to verify if TOML document is valid. It can also be used to -print the type of each key. -*/ +// Package toml implements decoding and encoding of TOML files. +// +// This package supports TOML v1.0.0, as specified at https://toml.io +// +// There is also support for delaying decoding with the Primitive type, and +// querying the set of keys in a TOML document with the MetaData type. +// +// The github.com/BurntSushi/toml/cmd/tomlv package implements a TOML validator, +// and can be used to verify if TOML document is valid. It can also be used to +// print the type of each key. package toml diff --git a/vendor/github.com/BurntSushi/toml/encode.go b/vendor/github.com/BurntSushi/toml/encode.go index e7d4eeb4..9cd25d75 100644 --- a/vendor/github.com/BurntSushi/toml/encode.go +++ b/vendor/github.com/BurntSushi/toml/encode.go @@ -3,6 +3,7 @@ package toml import ( "bufio" "encoding" + "encoding/json" "errors" "fmt" "io" @@ -63,6 +64,12 @@ var dblQuotedReplacer = strings.NewReplacer( "\x7f", `\u007f`, ) +var ( + marshalToml = reflect.TypeOf((*Marshaler)(nil)).Elem() + marshalText = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() + timeType = reflect.TypeOf((*time.Time)(nil)).Elem() +) + // Marshaler is the interface implemented by types that can marshal themselves // into valid TOML. type Marshaler interface { @@ -72,9 +79,12 @@ type Marshaler interface { // Encoder encodes a Go to a TOML document. // // The mapping between Go values and TOML values should be precisely the same as -// for the Decode* functions. +// for [Decode]. +// +// time.Time is encoded as a RFC 3339 string, and time.Duration as its string +// representation. // -// The toml.Marshaler and encoder.TextMarshaler interfaces are supported to +// The [Marshaler] and [encoding.TextMarshaler] interfaces are supported to // encoding the value as custom TOML. // // If you want to write arbitrary binary data then you will need to use @@ -85,6 +95,17 @@ type Marshaler interface { // // Go maps will be sorted alphabetically by key for deterministic output. // +// The toml struct tag can be used to provide the key name; if omitted the +// struct field name will be used. If the "omitempty" option is present the +// following value will be skipped: +// +// - arrays, slices, maps, and string with len of 0 +// - struct with all zero values +// - bool false +// +// If omitzero is given all int and float types with a value of 0 will be +// skipped. +// // Encoding Go values without a corresponding TOML representation will return an // error. Examples of this includes maps with non-string keys, slices with nil // elements, embedded non-struct types, and nested slices containing maps or @@ -109,13 +130,14 @@ func NewEncoder(w io.Writer) *Encoder { } } -// Encode writes a TOML representation of the Go value to the Encoder's writer. +// Encode writes a TOML representation of the Go value to the [Encoder]'s writer. // // An error is returned if the value given cannot be encoded to a valid TOML // document. func (enc *Encoder) Encode(v interface{}) error { rv := eindirect(reflect.ValueOf(v)) - if err := enc.safeEncode(Key([]string{}), rv); err != nil { + err := enc.safeEncode(Key([]string{}), rv) + if err != nil { return err } return enc.w.Flush() @@ -136,18 +158,15 @@ func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) { } func (enc *Encoder) encode(key Key, rv reflect.Value) { - // Special case: time needs to be in ISO8601 format. - // - // Special case: if we can marshal the type to text, then we used that. This - // prevents the encoder for handling these types as generic structs (or - // whatever the underlying type of a TextMarshaler is). - switch t := rv.Interface().(type) { - case time.Time, encoding.TextMarshaler, Marshaler: + // If we can marshal the type to text, then we use that. This prevents the + // encoder for handling these types as generic structs (or whatever the + // underlying type of a TextMarshaler is). + switch { + case isMarshaler(rv): enc.writeKeyValue(key, rv, false) return - // TODO: #76 would make this superfluous after implemented. - case Primitive: - enc.encode(key, reflect.ValueOf(t.undecoded)) + case rv.Type() == primitiveType: // TODO: #76 would make this superfluous after implemented. + enc.encode(key, reflect.ValueOf(rv.Interface().(Primitive).undecoded)) return } @@ -212,6 +231,9 @@ func (enc *Encoder) eElement(rv reflect.Value) { if err != nil { encPanic(err) } + if s == nil { + encPanic(errors.New("MarshalTOML returned nil and no error")) + } enc.w.Write(s) return case encoding.TextMarshaler: @@ -219,11 +241,34 @@ func (enc *Encoder) eElement(rv reflect.Value) { if err != nil { encPanic(err) } + if s == nil { + encPanic(errors.New("MarshalText returned nil and no error")) + } enc.writeQuoted(string(s)) return + case time.Duration: + enc.writeQuoted(v.String()) + return + case json.Number: + n, _ := rv.Interface().(json.Number) + + if n == "" { /// Useful zero value. + enc.w.WriteByte('0') + return + } else if v, err := n.Int64(); err == nil { + enc.eElement(reflect.ValueOf(v)) + return + } else if v, err := n.Float64(); err == nil { + enc.eElement(reflect.ValueOf(v)) + return + } + encPanic(fmt.Errorf("unable to convert %q to int64 or float64", n)) } switch rv.Kind() { + case reflect.Ptr: + enc.eElement(rv.Elem()) + return case reflect.String: enc.writeQuoted(rv.String()) case reflect.Bool: @@ -259,7 +304,7 @@ func (enc *Encoder) eElement(rv reflect.Value) { case reflect.Interface: enc.eElement(rv.Elem()) default: - encPanic(fmt.Errorf("unexpected primitive type: %T", rv.Interface())) + encPanic(fmt.Errorf("unexpected type: %T", rv.Interface())) } } @@ -280,7 +325,7 @@ func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) { length := rv.Len() enc.wf("[") for i := 0; i < length; i++ { - elem := rv.Index(i) + elem := eindirect(rv.Index(i)) enc.eElement(elem) if i != length-1 { enc.wf(", ") @@ -294,7 +339,7 @@ func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) { encPanic(errNoKey) } for i := 0; i < rv.Len(); i++ { - trv := rv.Index(i) + trv := eindirect(rv.Index(i)) if isNil(trv) { continue } @@ -319,7 +364,7 @@ func (enc *Encoder) eTable(key Key, rv reflect.Value) { } func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value, inline bool) { - switch rv := eindirect(rv); rv.Kind() { + switch rv.Kind() { case reflect.Map: enc.eMap(key, rv, inline) case reflect.Struct: @@ -341,7 +386,7 @@ func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) { var mapKeysDirect, mapKeysSub []string for _, mapKey := range rv.MapKeys() { k := mapKey.String() - if typeIsTable(tomlTypeOfGo(rv.MapIndex(mapKey))) { + if typeIsTable(tomlTypeOfGo(eindirect(rv.MapIndex(mapKey)))) { mapKeysSub = append(mapKeysSub, k) } else { mapKeysDirect = append(mapKeysDirect, k) @@ -351,7 +396,7 @@ func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) { var writeMapKeys = func(mapKeys []string, trailC bool) { sort.Strings(mapKeys) for i, mapKey := range mapKeys { - val := rv.MapIndex(reflect.ValueOf(mapKey)) + val := eindirect(rv.MapIndex(reflect.ValueOf(mapKey))) if isNil(val) { continue } @@ -379,6 +424,13 @@ func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) { const is32Bit = (32 << (^uint(0) >> 63)) == 32 +func pointerTo(t reflect.Type) reflect.Type { + if t.Kind() == reflect.Ptr { + return pointerTo(t.Elem()) + } + return t +} + func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { // Write keys for fields directly under this key first, because if we write // a field that creates a new table then all keys under it will be in that @@ -395,7 +447,8 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { addFields = func(rt reflect.Type, rv reflect.Value, start []int) { for i := 0; i < rt.NumField(); i++ { f := rt.Field(i) - if f.PkgPath != "" && !f.Anonymous { /// Skip unexported fields. + isEmbed := f.Anonymous && pointerTo(f.Type).Kind() == reflect.Struct + if f.PkgPath != "" && !isEmbed { /// Skip unexported fields. continue } opts := getOptions(f.Tag) @@ -403,44 +456,33 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { continue } - frv := rv.Field(i) + frv := eindirect(rv.Field(i)) + + if is32Bit { + // Copy so it works correct on 32bit archs; not clear why this + // is needed. See #314, and https://www.reddit.com/r/golang/comments/pnx8v4 + // This also works fine on 64bit, but 32bit archs are somewhat + // rare and this is a wee bit faster. + copyStart := make([]int, len(start)) + copy(copyStart, start) + start = copyStart + } // Treat anonymous struct fields with tag names as though they are // not anonymous, like encoding/json does. // // Non-struct anonymous fields use the normal encoding logic. - if f.Anonymous { - t := f.Type - switch t.Kind() { - case reflect.Struct: - if getOptions(f.Tag).name == "" { - addFields(t, frv, append(start, f.Index...)) - continue - } - case reflect.Ptr: - if t.Elem().Kind() == reflect.Struct && getOptions(f.Tag).name == "" { - if !frv.IsNil() { - addFields(t.Elem(), frv.Elem(), append(start, f.Index...)) - } - continue - } + if isEmbed { + if getOptions(f.Tag).name == "" && frv.Kind() == reflect.Struct { + addFields(frv.Type(), frv, append(start, f.Index...)) + continue } } if typeIsTable(tomlTypeOfGo(frv)) { fieldsSub = append(fieldsSub, append(start, f.Index...)) } else { - // Copy so it works correct on 32bit archs; not clear why this - // is needed. See #314, and https://www.reddit.com/r/golang/comments/pnx8v4 - // This also works fine on 64bit, but 32bit archs are somewhat - // rare and this is a wee bit faster. - if is32Bit { - copyStart := make([]int, len(start)) - copy(copyStart, start) - fieldsDirect = append(fieldsDirect, append(copyStart, f.Index...)) - } else { - fieldsDirect = append(fieldsDirect, append(start, f.Index...)) - } + fieldsDirect = append(fieldsDirect, append(start, f.Index...)) } } } @@ -451,21 +493,25 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { fieldType := rt.FieldByIndex(fieldIndex) fieldVal := rv.FieldByIndex(fieldIndex) - if isNil(fieldVal) { /// Don't write anything for nil fields. + opts := getOptions(fieldType.Tag) + if opts.skip { + continue + } + if opts.omitempty && isEmpty(fieldVal) { continue } - opts := getOptions(fieldType.Tag) - if opts.skip { + fieldVal = eindirect(fieldVal) + + if isNil(fieldVal) { /// Don't write anything for nil fields. continue } + keyName := fieldType.Name if opts.name != "" { keyName = opts.name } - if opts.omitempty && isEmpty(fieldVal) { - continue - } + if opts.omitzero && isZero(fieldVal) { continue } @@ -502,6 +548,21 @@ func tomlTypeOfGo(rv reflect.Value) tomlType { if isNil(rv) || !rv.IsValid() { return nil } + + if rv.Kind() == reflect.Struct { + if rv.Type() == timeType { + return tomlDatetime + } + if isMarshaler(rv) { + return tomlString + } + return tomlHash + } + + if isMarshaler(rv) { + return tomlString + } + switch rv.Kind() { case reflect.Bool: return tomlBool @@ -513,7 +574,7 @@ func tomlTypeOfGo(rv reflect.Value) tomlType { case reflect.Float32, reflect.Float64: return tomlFloat case reflect.Array, reflect.Slice: - if typeEqual(tomlHash, tomlArrayType(rv)) { + if isTableArray(rv) { return tomlArrayHash } return tomlArray @@ -523,67 +584,35 @@ func tomlTypeOfGo(rv reflect.Value) tomlType { return tomlString case reflect.Map: return tomlHash - case reflect.Struct: - if _, ok := rv.Interface().(time.Time); ok { - return tomlDatetime - } - if isMarshaler(rv) { - return tomlString - } - return tomlHash default: - if isMarshaler(rv) { - return tomlString - } - encPanic(errors.New("unsupported type: " + rv.Kind().String())) panic("unreachable") } } func isMarshaler(rv reflect.Value) bool { - switch rv.Interface().(type) { - case encoding.TextMarshaler: - return true - case Marshaler: - return true - } - - // Someone used a pointer receiver: we can make it work for pointer values. - if rv.CanAddr() { - if _, ok := rv.Addr().Interface().(encoding.TextMarshaler); ok { - return true - } - if _, ok := rv.Addr().Interface().(Marshaler); ok { - return true - } - } - return false + return rv.Type().Implements(marshalText) || rv.Type().Implements(marshalToml) } -// tomlArrayType returns the element type of a TOML array. The type returned -// may be nil if it cannot be determined (e.g., a nil slice or a zero length -// slize). This function may also panic if it finds a type that cannot be -// expressed in TOML (such as nil elements, heterogeneous arrays or directly -// nested arrays of tables). -func tomlArrayType(rv reflect.Value) tomlType { - if isNil(rv) || !rv.IsValid() || rv.Len() == 0 { - return nil +// isTableArray reports if all entries in the array or slice are a table. +func isTableArray(arr reflect.Value) bool { + if isNil(arr) || !arr.IsValid() || arr.Len() == 0 { + return false } - /// Don't allow nil. - rvlen := rv.Len() - for i := 1; i < rvlen; i++ { - if tomlTypeOfGo(rv.Index(i)) == nil { + ret := true + for i := 0; i < arr.Len(); i++ { + tt := tomlTypeOfGo(eindirect(arr.Index(i))) + // Don't allow nil. + if tt == nil { encPanic(errArrayNilElement) } - } - firstType := tomlTypeOfGo(rv.Index(0)) - if firstType == nil { - encPanic(errArrayNilElement) + if ret && !typeEqual(tomlHash, tt) { + ret = false + } } - return firstType + return ret } type tagOptions struct { @@ -628,8 +657,26 @@ func isEmpty(rv reflect.Value) bool { switch rv.Kind() { case reflect.Array, reflect.Slice, reflect.Map, reflect.String: return rv.Len() == 0 + case reflect.Struct: + if rv.Type().Comparable() { + return reflect.Zero(rv.Type()).Interface() == rv.Interface() + } + // Need to also check if all the fields are empty, otherwise something + // like this with uncomparable types will always return true: + // + // type a struct{ field b } + // type b struct{ s []string } + // s := a{field: b{s: []string{"AAA"}}} + for i := 0; i < rv.NumField(); i++ { + if !isEmpty(rv.Field(i)) { + return false + } + } + return true case reflect.Bool: return !rv.Bool() + case reflect.Ptr: + return rv.IsNil() } return false } @@ -642,19 +689,21 @@ func (enc *Encoder) newline() { // Write a key/value pair: // -// key = +// key = // // This is also used for "k = v" in inline tables; so something like this will // be written in three calls: // -// ┌────────────────────┐ -// │ ┌───┐ ┌─────┐│ -// v v v v vv -// key = {k = v, k2 = v2} -// +// ┌───────────────────┐ +// │ ┌───┐ ┌────┐│ +// v v v v vv +// key = {k = 1, k2 = 2} func (enc *Encoder) writeKeyValue(key Key, val reflect.Value, inline bool) { + /// Marshaler used on top-level document; call eElement() to just call + /// Marshal{TOML,Text}. if len(key) == 0 { - encPanic(errNoKey) + enc.eElement(val) + return } enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1)) enc.eElement(val) @@ -679,13 +728,25 @@ func encPanic(err error) { panic(tomlEncodeError{err}) } +// Resolve any level of pointers to the actual value (e.g. **string → string). func eindirect(v reflect.Value) reflect.Value { - switch v.Kind() { - case reflect.Ptr, reflect.Interface: - return eindirect(v.Elem()) - default: + if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface { + if isMarshaler(v) { + return v + } + if v.CanAddr() { /// Special case for marshalers; see #358. + if pv := v.Addr(); isMarshaler(pv) { + return pv + } + } + return v + } + + if v.IsNil() { return v } + + return eindirect(v.Elem()) } func isNil(rv reflect.Value) bool { diff --git a/vendor/github.com/BurntSushi/toml/error.go b/vendor/github.com/BurntSushi/toml/error.go index d5728a41..efd68865 100644 --- a/vendor/github.com/BurntSushi/toml/error.go +++ b/vendor/github.com/BurntSushi/toml/error.go @@ -5,57 +5,60 @@ import ( "strings" ) -// ParseError is returned when there is an error parsing the TOML syntax. -// -// For example invalid syntax, duplicate keys, etc. +// ParseError is returned when there is an error parsing the TOML syntax such as +// invalid syntax, duplicate keys, etc. // // In addition to the error message itself, you can also print detailed location -// information with context by using ErrorWithPosition(): +// information with context by using [ErrorWithPosition]: // -// toml: error: Key 'fruit' was already created and cannot be used as an array. +// toml: error: Key 'fruit' was already created and cannot be used as an array. // -// At line 4, column 2-7: +// At line 4, column 2-7: // -// 2 | fruit = [] -// 3 | -// 4 | [[fruit]] # Not allowed -// ^^^^^ +// 2 | fruit = [] +// 3 | +// 4 | [[fruit]] # Not allowed +// ^^^^^ // -// Furthermore, the ErrorWithUsage() can be used to print the above with some -// more detailed usage guidance: +// [ErrorWithUsage] can be used to print the above with some more detailed usage +// guidance: // -// toml: error: newlines not allowed within inline tables +// toml: error: newlines not allowed within inline tables // -// At line 1, column 18: +// At line 1, column 18: // -// 1 | x = [{ key = 42 # -// ^ +// 1 | x = [{ key = 42 # +// ^ // -// Error help: +// Error help: // -// Inline tables must always be on a single line: +// Inline tables must always be on a single line: // -// table = {key = 42, second = 43} +// table = {key = 42, second = 43} // -// It is invalid to split them over multiple lines like so: +// It is invalid to split them over multiple lines like so: // -// # INVALID -// table = { -// key = 42, -// second = 43 -// } +// # INVALID +// table = { +// key = 42, +// second = 43 +// } // -// Use regular for this: +// Use regular for this: // -// [table] -// key = 42 -// second = 43 +// [table] +// key = 42 +// second = 43 type ParseError struct { Message string // Short technical message. Usage string // Longer message with usage guidance; may be blank. Position Position // Position of the error LastKey string // Last parsed key, may be blank. - Line int // Line the error occurred. Deprecated: use Position. + + // Line the error occurred. + // + // Deprecated: use [Position]. + Line int err error input string @@ -81,9 +84,9 @@ func (pe ParseError) Error() string { pe.Position.Line, pe.LastKey, msg) } -// ErrorWithUsage() returns the error with detailed location context. +// ErrorWithPosition returns the error with detailed location context. // -// See the documentation on ParseError. +// See the documentation on [ParseError]. func (pe ParseError) ErrorWithPosition() string { if pe.input == "" { // Should never happen, but just in case. return pe.Error() @@ -121,16 +124,20 @@ func (pe ParseError) ErrorWithPosition() string { return b.String() } -// ErrorWithUsage() returns the error with detailed location context and usage +// ErrorWithUsage returns the error with detailed location context and usage // guidance. // -// See the documentation on ParseError. +// See the documentation on [ParseError]. func (pe ParseError) ErrorWithUsage() string { m := pe.ErrorWithPosition() if u, ok := pe.err.(interface{ Usage() string }); ok && u.Usage() != "" { - return m + "Error help:\n\n " + - strings.ReplaceAll(strings.TrimSpace(u.Usage()), "\n", "\n ") + - "\n" + lines := strings.Split(strings.TrimSpace(u.Usage()), "\n") + for i := range lines { + if lines[i] != "" { + lines[i] = " " + lines[i] + } + } + return m + "Error help:\n\n" + strings.Join(lines, "\n") + "\n" } return m } @@ -160,6 +167,11 @@ type ( errLexInvalidDate struct{ v string } errLexInlineTableNL struct{} errLexStringNL struct{} + errParseRange struct { + i interface{} // int or float + size string // "int64", "uint16", etc. + } + errParseDuration struct{ d string } ) func (e errLexControl) Error() string { @@ -179,6 +191,10 @@ func (e errLexInlineTableNL) Error() string { return "newlines not allowed withi func (e errLexInlineTableNL) Usage() string { return usageInlineNewline } func (e errLexStringNL) Error() string { return "strings cannot contain newlines" } func (e errLexStringNL) Usage() string { return usageStringNewline } +func (e errParseRange) Error() string { return fmt.Sprintf("%v is out of range for %s", e.i, e.size) } +func (e errParseRange) Usage() string { return usageIntOverflow } +func (e errParseDuration) Error() string { return fmt.Sprintf("invalid duration: %q", e.d) } +func (e errParseDuration) Usage() string { return usageDuration } const usageEscape = ` A '\' inside a "-delimited string is interpreted as an escape character. @@ -227,3 +243,37 @@ Instead use """ or ''' to split strings over multiple lines: string = """Hello, world!""" ` + +const usageIntOverflow = ` +This number is too large; this may be an error in the TOML, but it can also be a +bug in the program that uses too small of an integer. + +The maximum and minimum values are: + + size │ lowest │ highest + ───────┼────────────────┼────────── + int8 │ -128 │ 127 + int16 │ -32,768 │ 32,767 + int32 │ -2,147,483,648 │ 2,147,483,647 + int64 │ -9.2 × 10¹⁷ │ 9.2 × 10¹⁷ + uint8 │ 0 │ 255 + uint16 │ 0 │ 65535 + uint32 │ 0 │ 4294967295 + uint64 │ 0 │ 1.8 × 10¹⁸ + +int refers to int32 on 32-bit systems and int64 on 64-bit systems. +` + +const usageDuration = ` +A duration must be as "number", without any spaces. Valid units are: + + ns nanoseconds (billionth of a second) + us, µs microseconds (millionth of a second) + ms milliseconds (thousands of a second) + s seconds + m minutes + h hours + +You can combine multiple units; for example "5m10s" for 5 minutes and 10 +seconds. +` diff --git a/vendor/github.com/BurntSushi/toml/lex.go b/vendor/github.com/BurntSushi/toml/lex.go index ce7f546b..3545a6ad 100644 --- a/vendor/github.com/BurntSushi/toml/lex.go +++ b/vendor/github.com/BurntSushi/toml/lex.go @@ -46,12 +46,13 @@ func (p Position) String() string { } type lexer struct { - input string - start int - pos int - line int - state stateFn - items chan item + input string + start int + pos int + line int + state stateFn + items chan item + tomlNext bool // Allow for backing up up to 4 runes. This is necessary because TOML // contains 3-rune tokens (""" and '''). @@ -82,18 +83,19 @@ func (lx *lexer) nextItem() item { return item default: lx.state = lx.state(lx) - //fmt.Printf(" STATE %-24s current: %-10q stack: %s\n", lx.state, lx.current(), lx.stack) + //fmt.Printf(" STATE %-24s current: %-10s stack: %s\n", lx.state, lx.current(), lx.stack) } } } -func lex(input string) *lexer { +func lex(input string, tomlNext bool) *lexer { lx := &lexer{ - input: input, - state: lexTop, - items: make(chan item, 10), - stack: make([]stateFn, 0, 10), - line: 1, + input: input, + state: lexTop, + items: make(chan item, 10), + stack: make([]stateFn, 0, 10), + line: 1, + tomlNext: tomlNext, } return lx } @@ -408,7 +410,7 @@ func lexTableNameEnd(lx *lexer) stateFn { // Lexes only one part, e.g. only 'a' inside 'a.b'. func lexBareName(lx *lexer) stateFn { r := lx.next() - if isBareKeyChar(r) { + if isBareKeyChar(r, lx.tomlNext) { return lexBareName } lx.backup() @@ -618,6 +620,9 @@ func lexInlineTableValue(lx *lexer) stateFn { case isWhitespace(r): return lexSkip(lx, lexInlineTableValue) case isNL(r): + if lx.tomlNext { + return lexSkip(lx, lexInlineTableValue) + } return lx.errorPrevLine(errLexInlineTableNL{}) case r == '#': lx.push(lexInlineTableValue) @@ -640,6 +645,9 @@ func lexInlineTableValueEnd(lx *lexer) stateFn { case isWhitespace(r): return lexSkip(lx, lexInlineTableValueEnd) case isNL(r): + if lx.tomlNext { + return lexSkip(lx, lexInlineTableValueEnd) + } return lx.errorPrevLine(errLexInlineTableNL{}) case r == '#': lx.push(lexInlineTableValueEnd) @@ -648,6 +656,9 @@ func lexInlineTableValueEnd(lx *lexer) stateFn { lx.ignore() lx.skip(isWhitespace) if lx.peek() == '}' { + if lx.tomlNext { + return lexInlineTableValueEnd + } return lx.errorf("trailing comma not allowed in inline tables") } return lexInlineTableValue @@ -716,7 +727,17 @@ func lexMultilineString(lx *lexer) stateFn { if lx.peek() == '"' { /// Check if we already lexed 5 's; if so we have 6 now, and /// that's just too many man! - if strings.HasSuffix(lx.current(), `"""""`) { + /// + /// Second check is for the edge case: + /// + /// two quotes allowed. + /// vv + /// """lol \"""""" + /// ^^ ^^^---- closing three + /// escaped + /// + /// But ugly, but it works + if strings.HasSuffix(lx.current(), `"""""`) && !strings.HasSuffix(lx.current(), `\"""""`) { return lx.errorf(`unexpected '""""""'`) } lx.backup() @@ -760,8 +781,8 @@ func lexRawString(lx *lexer) stateFn { } } -// lexMultilineRawString consumes a raw string. Nothing can be escaped in such -// a string. It assumes that the beginning "'''" has already been consumed and +// lexMultilineRawString consumes a raw string. Nothing can be escaped in such a +// string. It assumes that the beginning triple-' has already been consumed and // ignored. func lexMultilineRawString(lx *lexer) stateFn { r := lx.next() @@ -807,8 +828,7 @@ func lexMultilineRawString(lx *lexer) stateFn { // lexMultilineStringEscape consumes an escaped character. It assumes that the // preceding '\\' has already been consumed. func lexMultilineStringEscape(lx *lexer) stateFn { - // Handle the special case first: - if isNL(lx.next()) { + if isNL(lx.next()) { /// \ escaping newline. return lexMultilineString } lx.backup() @@ -819,6 +839,11 @@ func lexMultilineStringEscape(lx *lexer) stateFn { func lexStringEscape(lx *lexer) stateFn { r := lx.next() switch r { + case 'e': + if !lx.tomlNext { + return lx.error(errLexEscape{r}) + } + fallthrough case 'b': fallthrough case 't': @@ -837,6 +862,11 @@ func lexStringEscape(lx *lexer) stateFn { fallthrough case '\\': return lx.pop() + case 'x': + if !lx.tomlNext { + return lx.error(errLexEscape{r}) + } + return lexHexEscape case 'u': return lexShortUnicodeEscape case 'U': @@ -845,6 +875,19 @@ func lexStringEscape(lx *lexer) stateFn { return lx.error(errLexEscape{r}) } +func lexHexEscape(lx *lexer) stateFn { + var r rune + for i := 0; i < 2; i++ { + r = lx.next() + if !isHexadecimal(r) { + return lx.errorf( + `expected two hexadecimal digits after '\x', but got %q instead`, + lx.current()) + } + } + return lx.pop() +} + func lexShortUnicodeEscape(lx *lexer) stateFn { var r rune for i := 0; i < 4; i++ { @@ -1216,7 +1259,23 @@ func isOctal(r rune) bool { return r >= '0' && r <= '7' } func isHexadecimal(r rune) bool { return (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F') } -func isBareKeyChar(r rune) bool { + +func isBareKeyChar(r rune, tomlNext bool) bool { + if tomlNext { + return (r >= 'A' && r <= 'Z') || + (r >= 'a' && r <= 'z') || + (r >= '0' && r <= '9') || + r == '_' || r == '-' || + r == 0xb2 || r == 0xb3 || r == 0xb9 || (r >= 0xbc && r <= 0xbe) || + (r >= 0xc0 && r <= 0xd6) || (r >= 0xd8 && r <= 0xf6) || (r >= 0xf8 && r <= 0x037d) || + (r >= 0x037f && r <= 0x1fff) || + (r >= 0x200c && r <= 0x200d) || (r >= 0x203f && r <= 0x2040) || + (r >= 0x2070 && r <= 0x218f) || (r >= 0x2460 && r <= 0x24ff) || + (r >= 0x2c00 && r <= 0x2fef) || (r >= 0x3001 && r <= 0xd7ff) || + (r >= 0xf900 && r <= 0xfdcf) || (r >= 0xfdf0 && r <= 0xfffd) || + (r >= 0x10000 && r <= 0xeffff) + } + return (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || diff --git a/vendor/github.com/BurntSushi/toml/meta.go b/vendor/github.com/BurntSushi/toml/meta.go index 868619fb..2e78b24e 100644 --- a/vendor/github.com/BurntSushi/toml/meta.go +++ b/vendor/github.com/BurntSushi/toml/meta.go @@ -12,10 +12,11 @@ import ( type MetaData struct { context Key // Used only during decoding. + keyInfo map[string]keyInfo mapping map[string]interface{} - types map[string]tomlType keys []Key decoded map[string]struct{} + data []byte // Input file; for errors. } // IsDefined reports if the key exists in the TOML data. @@ -50,8 +51,8 @@ func (md *MetaData) IsDefined(key ...string) bool { // Type will return the empty string if given an empty key or a key that does // not exist. Keys are case sensitive. func (md *MetaData) Type(key ...string) string { - if typ, ok := md.types[Key(key).String()]; ok { - return typ.typeString() + if ki, ok := md.keyInfo[Key(key).String()]; ok { + return ki.tomlType.typeString() } return "" } @@ -70,7 +71,7 @@ func (md *MetaData) Keys() []Key { // Undecoded returns all keys that have not been decoded in the order in which // they appear in the original TOML document. // -// This includes keys that haven't been decoded because of a Primitive value. +// This includes keys that haven't been decoded because of a [Primitive] value. // Once the Primitive value is decoded, the keys will be considered decoded. // // Also note that decoding into an empty interface will result in no decoding, @@ -88,7 +89,7 @@ func (md *MetaData) Undecoded() []Key { return undecoded } -// Key represents any TOML key, including key groups. Use (MetaData).Keys to get +// Key represents any TOML key, including key groups. Use [MetaData.Keys] to get // values of this type. type Key []string @@ -105,7 +106,7 @@ func (k Key) maybeQuoted(i int) string { return `""` } for _, c := range k[i] { - if !isBareKeyChar(c) { + if !isBareKeyChar(c, false) { return `"` + dblQuotedReplacer.Replace(k[i]) + `"` } } diff --git a/vendor/github.com/BurntSushi/toml/parse.go b/vendor/github.com/BurntSushi/toml/parse.go index 0420b5ba..9c191536 100644 --- a/vendor/github.com/BurntSushi/toml/parse.go +++ b/vendor/github.com/BurntSushi/toml/parse.go @@ -2,6 +2,7 @@ package toml import ( "fmt" + "os" "strconv" "strings" "time" @@ -15,14 +16,23 @@ type parser struct { context Key // Full key for the current hash in scope. currentKey string // Base key name for everything except hashes. pos Position // Current position in the TOML file. + tomlNext bool - ordered []Key // List of keys in the order that they appear in the TOML data. + ordered []Key // List of keys in the order that they appear in the TOML data. + + keyInfo map[string]keyInfo // Map keyname → info about the TOML key. mapping map[string]interface{} // Map keyname → key value. - types map[string]tomlType // Map keyname → TOML type. implicits map[string]struct{} // Record implicit keys (e.g. "key.group.names"). } +type keyInfo struct { + pos Position + tomlType tomlType +} + func parse(data string) (p *parser, err error) { + _, tomlNext := os.LookupEnv("BURNTSUSHI_TOML_110") + defer func() { if r := recover(); r != nil { if pErr, ok := r.(ParseError); ok { @@ -35,9 +45,12 @@ func parse(data string) (p *parser, err error) { }() // Read over BOM; do this here as the lexer calls utf8.DecodeRuneInString() - // which mangles stuff. - if strings.HasPrefix(data, "\xff\xfe") || strings.HasPrefix(data, "\xfe\xff") { + // which mangles stuff. UTF-16 BOM isn't strictly valid, but some tools add + // it anyway. + if strings.HasPrefix(data, "\xff\xfe") || strings.HasPrefix(data, "\xfe\xff") { // UTF-16 data = data[2:] + } else if strings.HasPrefix(data, "\xef\xbb\xbf") { // UTF-8 + data = data[3:] } // Examine first few bytes for NULL bytes; this probably means it's a UTF-16 @@ -57,11 +70,12 @@ func parse(data string) (p *parser, err error) { } p = &parser{ + keyInfo: make(map[string]keyInfo), mapping: make(map[string]interface{}), - types: make(map[string]tomlType), - lx: lex(data), + lx: lex(data, tomlNext), ordered: make([]Key, 0), implicits: make(map[string]struct{}), + tomlNext: tomlNext, } for { item := p.next() @@ -74,6 +88,15 @@ func parse(data string) (p *parser, err error) { return p, nil } +func (p *parser) panicErr(it item, err error) { + panic(ParseError{ + err: err, + Position: it.pos, + Line: it.pos.Len, + LastKey: p.current(), + }) +} + func (p *parser) panicItemf(it item, format string, v ...interface{}) { panic(ParseError{ Message: fmt.Sprintf(format, v...), @@ -94,7 +117,7 @@ func (p *parser) panicf(format string, v ...interface{}) { func (p *parser) next() item { it := p.lx.nextItem() - //fmt.Printf("ITEM %-18s line %-3d │ %q\n", it.typ, it.line, it.val) + //fmt.Printf("ITEM %-18s line %-3d │ %q\n", it.typ, it.pos.Line, it.val) if it.typ == itemError { if it.err != nil { panic(ParseError{ @@ -146,7 +169,7 @@ func (p *parser) topLevel(item item) { p.assertEqual(itemTableEnd, name.typ) p.addContext(key, false) - p.setType("", tomlHash) + p.setType("", tomlHash, item.pos) p.ordered = append(p.ordered, key) case itemArrayTableStart: // [[ .. ]] name := p.nextPos() @@ -158,7 +181,7 @@ func (p *parser) topLevel(item item) { p.assertEqual(itemArrayTableEnd, name.typ) p.addContext(key, true) - p.setType("", tomlArrayHash) + p.setType("", tomlArrayHash, item.pos) p.ordered = append(p.ordered, key) case itemKeyStart: // key = .. outerContext := p.context @@ -179,11 +202,12 @@ func (p *parser) topLevel(item item) { for i := range context { p.addImplicitContext(append(p.context, context[i:i+1]...)) } + p.ordered = append(p.ordered, p.context.add(p.currentKey)) /// Set value. - val, typ := p.value(p.next(), false) - p.set(p.currentKey, val, typ) - p.ordered = append(p.ordered, p.context.add(p.currentKey)) + vItem := p.next() + val, typ := p.value(vItem, false) + p.set(p.currentKey, val, typ, vItem.pos) /// Remove the context we added (preserving any context from [tbl] lines). p.context = outerContext @@ -220,7 +244,7 @@ func (p *parser) value(it item, parentIsArray bool) (interface{}, tomlType) { case itemString: return p.replaceEscapes(it, it.val), p.typeOfPrimitive(it) case itemMultilineString: - return p.replaceEscapes(it, stripFirstNewline(p.stripEscapedNewlines(it.val))), p.typeOfPrimitive(it) + return p.replaceEscapes(it, p.stripEscapedNewlines(stripFirstNewline(it.val))), p.typeOfPrimitive(it) case itemRawString: return it.val, p.typeOfPrimitive(it) case itemRawMultilineString: @@ -266,7 +290,7 @@ func (p *parser) valueInteger(it item) (interface{}, tomlType) { // So mark the former as a bug but the latter as a legitimate user // error. if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { - p.panicItemf(it, "Integer '%s' is out of the range of 64-bit signed integers.", it.val) + p.panicErr(it, errParseRange{i: it.val, size: "int64"}) } else { p.bug("Expected integer value, but got '%s'.", it.val) } @@ -304,7 +328,7 @@ func (p *parser) valueFloat(it item) (interface{}, tomlType) { num, err := strconv.ParseFloat(val, 64) if err != nil { if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { - p.panicItemf(it, "Float '%s' is out of the range of 64-bit IEEE-754 floating-point numbers.", it.val) + p.panicErr(it, errParseRange{i: it.val, size: "float64"}) } else { p.panicItemf(it, "Invalid float value: %q", it.val) } @@ -315,11 +339,17 @@ func (p *parser) valueFloat(it item) (interface{}, tomlType) { var dtTypes = []struct { fmt string zone *time.Location + next bool }{ - {time.RFC3339Nano, time.Local}, - {"2006-01-02T15:04:05.999999999", internal.LocalDatetime}, - {"2006-01-02", internal.LocalDate}, - {"15:04:05.999999999", internal.LocalTime}, + {time.RFC3339Nano, time.Local, false}, + {"2006-01-02T15:04:05.999999999", internal.LocalDatetime, false}, + {"2006-01-02", internal.LocalDate, false}, + {"15:04:05.999999999", internal.LocalTime, false}, + + // tomlNext + {"2006-01-02T15:04Z07:00", time.Local, true}, + {"2006-01-02T15:04", internal.LocalDatetime, true}, + {"15:04", internal.LocalTime, true}, } func (p *parser) valueDatetime(it item) (interface{}, tomlType) { @@ -330,6 +360,9 @@ func (p *parser) valueDatetime(it item) (interface{}, tomlType) { err error ) for _, dt := range dtTypes { + if dt.next && !p.tomlNext { + continue + } t, err = time.ParseInLocation(dt.fmt, it.val, dt.zone) if err == nil { ok = true @@ -343,9 +376,8 @@ func (p *parser) valueDatetime(it item) (interface{}, tomlType) { } func (p *parser) valueArray(it item) (interface{}, tomlType) { - p.setType(p.currentKey, tomlArray) + p.setType(p.currentKey, tomlArray, it.pos) - // p.setType(p.currentKey, typ) var ( types []tomlType @@ -369,6 +401,7 @@ func (p *parser) valueArray(it item) (interface{}, tomlType) { // // Not entirely sure how to best store this; could use "key[0]", // "key[1]" notation, or maybe store it on the Array type? + _ = types } return array, tomlArray } @@ -411,11 +444,11 @@ func (p *parser) valueInlineTable(it item, parentIsArray bool) (interface{}, tom for i := range context { p.addImplicitContext(append(p.context, context[i:i+1]...)) } + p.ordered = append(p.ordered, p.context.add(p.currentKey)) /// Set the value. val, typ := p.value(p.next(), false) - p.set(p.currentKey, val, typ) - p.ordered = append(p.ordered, p.context.add(p.currentKey)) + p.set(p.currentKey, val, typ, it.pos) hash[p.currentKey] = val /// Restore context. @@ -533,9 +566,9 @@ func (p *parser) addContext(key Key, array bool) { } // set calls setValue and setType. -func (p *parser) set(key string, val interface{}, typ tomlType) { +func (p *parser) set(key string, val interface{}, typ tomlType, pos Position) { p.setValue(key, val) - p.setType(key, typ) + p.setType(key, typ, pos) } // setValue sets the given key to the given value in the current context. @@ -599,7 +632,7 @@ func (p *parser) setValue(key string, value interface{}) { // // Note that if `key` is empty, then the type given will be applied to the // current context (which is either a table or an array of tables). -func (p *parser) setType(key string, typ tomlType) { +func (p *parser) setType(key string, typ tomlType, pos Position) { keyContext := make(Key, 0, len(p.context)+1) keyContext = append(keyContext, p.context...) if len(key) > 0 { // allow type setting for hashes @@ -611,19 +644,16 @@ func (p *parser) setType(key string, typ tomlType) { if len(keyContext) == 0 { keyContext = Key{""} } - p.types[keyContext.String()] = typ + p.keyInfo[keyContext.String()] = keyInfo{tomlType: typ, pos: pos} } // Implicit keys need to be created when tables are implied in "a.b.c.d = 1" and // "[a.b.c]" (the "a", "b", and "c" hashes are never created explicitly). -func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = struct{}{} } -func (p *parser) removeImplicit(key Key) { delete(p.implicits, key.String()) } -func (p *parser) isImplicit(key Key) bool { _, ok := p.implicits[key.String()]; return ok } -func (p *parser) isArray(key Key) bool { return p.types[key.String()] == tomlArray } -func (p *parser) addImplicitContext(key Key) { - p.addImplicit(key) - p.addContext(key, false) -} +func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = struct{}{} } +func (p *parser) removeImplicit(key Key) { delete(p.implicits, key.String()) } +func (p *parser) isImplicit(key Key) bool { _, ok := p.implicits[key.String()]; return ok } +func (p *parser) isArray(key Key) bool { return p.keyInfo[key.String()].tomlType == tomlArray } +func (p *parser) addImplicitContext(key Key) { p.addImplicit(key); p.addContext(key, false) } // current returns the full key name of the current context. func (p *parser) current() string { @@ -646,49 +676,54 @@ func stripFirstNewline(s string) string { return s } -// Remove newlines inside triple-quoted strings if a line ends with "\". +// stripEscapedNewlines removes whitespace after line-ending backslashes in +// multiline strings. +// +// A line-ending backslash is an unescaped \ followed only by whitespace until +// the next newline. After a line-ending backslash, all whitespace is removed +// until the next non-whitespace character. func (p *parser) stripEscapedNewlines(s string) string { - split := strings.Split(s, "\n") - if len(split) < 1 { - return s - } - - escNL := false // Keep track of the last non-blank line was escaped. - for i, line := range split { - line = strings.TrimRight(line, " \t\r") - - if len(line) == 0 || line[len(line)-1] != '\\' { - split[i] = strings.TrimRight(split[i], "\r") - if !escNL && i != len(split)-1 { - split[i] += "\n" - } - continue + var b strings.Builder + var i int + for { + ix := strings.Index(s[i:], `\`) + if ix < 0 { + b.WriteString(s) + return b.String() } + i += ix - escBS := true - for j := len(line) - 1; j >= 0 && line[j] == '\\'; j-- { - escBS = !escBS + if len(s) > i+1 && s[i+1] == '\\' { + // Escaped backslash. + i += 2 + continue } - if escNL { - line = strings.TrimLeft(line, " \t\r") + // Scan until the next non-whitespace. + j := i + 1 + whitespaceLoop: + for ; j < len(s); j++ { + switch s[j] { + case ' ', '\t', '\r', '\n': + default: + break whitespaceLoop + } } - escNL = !escBS - - if escBS { - split[i] += "\n" + if j == i+1 { + // Not a whitespace escape. + i++ continue } - - if i == len(split)-1 { - p.panicf("invalid escape: '\\ '") - } - - split[i] = line[:len(line)-1] // Remove \ - if len(split)-1 > i { - split[i+1] = strings.TrimLeft(split[i+1], " \t\r") + if !strings.Contains(s[i:j], "\n") { + // This is not a line-ending backslash. + // (It's a bad escape sequence, but we can let + // replaceEscapes catch it.) + i++ + continue } + b.WriteString(s[:i]) + s = s[j:] + i = 0 } - return strings.Join(split, "") } func (p *parser) replaceEscapes(it item, str string) string { @@ -710,10 +745,8 @@ func (p *parser) replaceEscapes(it item, str string) string { switch s[r] { default: p.bug("Expected valid escape code after \\, but got %q.", s[r]) - return "" case ' ', '\t': p.panicItemf(it, "invalid escape: '\\%c'", s[r]) - return "" case 'b': replaced = append(replaced, rune(0x0008)) r += 1 @@ -729,12 +762,23 @@ func (p *parser) replaceEscapes(it item, str string) string { case 'r': replaced = append(replaced, rune(0x000D)) r += 1 + case 'e': + if p.tomlNext { + replaced = append(replaced, rune(0x001B)) + r += 1 + } case '"': replaced = append(replaced, rune(0x0022)) r += 1 case '\\': replaced = append(replaced, rune(0x005C)) r += 1 + case 'x': + if p.tomlNext { + escaped := p.asciiEscapeToUnicode(it, s[r+1:r+3]) + replaced = append(replaced, escaped) + r += 3 + } case 'u': // At this point, we know we have a Unicode escape of the form // `uXXXX` at [r, r+5). (Because the lexer guarantees this diff --git a/vendor/github.com/cenkalti/backoff/v4/.travis.yml b/vendor/github.com/cenkalti/backoff/v4/.travis.yml deleted file mode 100644 index c79105c2..00000000 --- a/vendor/github.com/cenkalti/backoff/v4/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go: - - 1.13 - - 1.x - - tip -before_install: - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover -script: - - $HOME/gopath/bin/goveralls -service=travis-ci diff --git a/vendor/github.com/cenkalti/backoff/v4/retry.go b/vendor/github.com/cenkalti/backoff/v4/retry.go index 1ce2507e..b9c0c51c 100644 --- a/vendor/github.com/cenkalti/backoff/v4/retry.go +++ b/vendor/github.com/cenkalti/backoff/v4/retry.go @@ -5,10 +5,20 @@ import ( "time" ) +// An OperationWithData is executing by RetryWithData() or RetryNotifyWithData(). +// The operation will be retried using a backoff policy if it returns an error. +type OperationWithData[T any] func() (T, error) + // An Operation is executing by Retry() or RetryNotify(). // The operation will be retried using a backoff policy if it returns an error. type Operation func() error +func (o Operation) withEmptyData() OperationWithData[struct{}] { + return func() (struct{}, error) { + return struct{}{}, o() + } +} + // Notify is a notify-on-error function. It receives an operation error and // backoff delay if the operation failed (with an error). // @@ -28,18 +38,41 @@ func Retry(o Operation, b BackOff) error { return RetryNotify(o, b, nil) } +// RetryWithData is like Retry but returns data in the response too. +func RetryWithData[T any](o OperationWithData[T], b BackOff) (T, error) { + return RetryNotifyWithData(o, b, nil) +} + // RetryNotify calls notify function with the error and wait duration // for each failed attempt before sleep. func RetryNotify(operation Operation, b BackOff, notify Notify) error { return RetryNotifyWithTimer(operation, b, notify, nil) } +// RetryNotifyWithData is like RetryNotify but returns data in the response too. +func RetryNotifyWithData[T any](operation OperationWithData[T], b BackOff, notify Notify) (T, error) { + return doRetryNotify(operation, b, notify, nil) +} + // RetryNotifyWithTimer calls notify function with the error and wait duration using the given Timer // for each failed attempt before sleep. // A default timer that uses system timer is used when nil is passed. func RetryNotifyWithTimer(operation Operation, b BackOff, notify Notify, t Timer) error { - var err error - var next time.Duration + _, err := doRetryNotify(operation.withEmptyData(), b, notify, t) + return err +} + +// RetryNotifyWithTimerAndData is like RetryNotifyWithTimer but returns data in the response too. +func RetryNotifyWithTimerAndData[T any](operation OperationWithData[T], b BackOff, notify Notify, t Timer) (T, error) { + return doRetryNotify(operation, b, notify, t) +} + +func doRetryNotify[T any](operation OperationWithData[T], b BackOff, notify Notify, t Timer) (T, error) { + var ( + err error + next time.Duration + res T + ) if t == nil { t = &defaultTimer{} } @@ -52,21 +85,22 @@ func RetryNotifyWithTimer(operation Operation, b BackOff, notify Notify, t Timer b.Reset() for { - if err = operation(); err == nil { - return nil + res, err = operation() + if err == nil { + return res, nil } var permanent *PermanentError if errors.As(err, &permanent) { - return permanent.Err + return res, permanent.Err } if next = b.NextBackOff(); next == Stop { if cerr := ctx.Err(); cerr != nil { - return cerr + return res, cerr } - return err + return res, err } if notify != nil { @@ -77,7 +111,7 @@ func RetryNotifyWithTimer(operation Operation, b BackOff, notify Notify, t Timer select { case <-ctx.Done(): - return ctx.Err() + return res, ctx.Err() case <-t.C(): } } diff --git a/vendor/github.com/go-acme/lego/v4/acme/api/api.go b/vendor/github.com/go-acme/lego/v4/acme/api/api.go index 69dda009..b8c9cf0c 100644 --- a/vendor/github.com/go-acme/lego/v4/acme/api/api.go +++ b/vendor/github.com/go-acme/lego/v4/acme/api/api.go @@ -117,7 +117,7 @@ func (a *Core) signedPost(uri string, content []byte, response interface{}) (*ht return nil, fmt.Errorf("failed to post JWS message: failed to sign content: %w", err) } - signedBody := bytes.NewBuffer([]byte(signedContent.FullSerialize())) + signedBody := bytes.NewBufferString(signedContent.FullSerialize()) resp, err := a.doer.Post(uri, signedBody, "application/jose+json", response) diff --git a/vendor/github.com/go-acme/lego/v4/acme/api/certificate.go b/vendor/github.com/go-acme/lego/v4/acme/api/certificate.go index baf5a385..5f31968c 100644 --- a/vendor/github.com/go-acme/lego/v4/acme/api/certificate.go +++ b/vendor/github.com/go-acme/lego/v4/acme/api/certificate.go @@ -1,6 +1,7 @@ package api import ( + "bytes" "crypto/x509" "encoding/pem" "errors" @@ -87,6 +88,11 @@ func (c *CertificateService) getCertificateChain(cert []byte, headers http.Heade // See https://community.letsencrypt.org/t/acme-v2-no-up-link-in-response/64962 _, issuer := pem.Decode(cert) if issuer != nil { + // If bundle is false, we want to return a single certificate. + // To do this, we remove the issuer cert(s) from the issued cert. + if !bundle { + cert = bytes.TrimSuffix(cert, issuer) + } return &acme.RawCertificate{Cert: cert, Issuer: issuer} } diff --git a/vendor/github.com/go-acme/lego/v4/acme/api/internal/nonces/nonce_manager.go b/vendor/github.com/go-acme/lego/v4/acme/api/internal/nonces/nonce_manager.go index 154cc5ea..d089cf07 100644 --- a/vendor/github.com/go-acme/lego/v4/acme/api/internal/nonces/nonce_manager.go +++ b/vendor/github.com/go-acme/lego/v4/acme/api/internal/nonces/nonce_manager.go @@ -63,7 +63,7 @@ func (n *Manager) getNonce() (string, error) { return GetFromResponse(resp) } -// GetFromResponse Extracts a nonce from a HTTP response. +// GetFromResponse Extracts a nonce from an HTTP response. func GetFromResponse(resp *http.Response) (string, error) { if resp == nil { return "", errors.New("nil response") diff --git a/vendor/github.com/go-acme/lego/v4/acme/api/internal/secure/jws.go b/vendor/github.com/go-acme/lego/v4/acme/api/internal/secure/jws.go index 8bc0831e..a9a924d4 100644 --- a/vendor/github.com/go-acme/lego/v4/acme/api/internal/secure/jws.go +++ b/vendor/github.com/go-acme/lego/v4/acme/api/internal/secure/jws.go @@ -9,7 +9,7 @@ import ( "fmt" "github.com/go-acme/lego/v4/acme/api/internal/nonces" - jose "gopkg.in/square/go-jose.v2" + jose "github.com/go-jose/go-jose/v3" ) // JWS Represents a JWS. diff --git a/vendor/github.com/go-acme/lego/v4/acme/api/internal/sender/sender.go b/vendor/github.com/go-acme/lego/v4/acme/api/internal/sender/sender.go index 9b5c5041..29cd7c9b 100644 --- a/vendor/github.com/go-acme/lego/v4/acme/api/internal/sender/sender.go +++ b/vendor/github.com/go-acme/lego/v4/acme/api/internal/sender/sender.go @@ -133,6 +133,10 @@ func checkError(req *http.Request, resp *http.Response) error { errorDetails.Method = req.Method errorDetails.URL = req.URL.String() + if errorDetails.HTTPStatus == 0 { + errorDetails.HTTPStatus = resp.StatusCode + } + // Check for errors we handle specifically if errorDetails.HTTPStatus == http.StatusBadRequest && errorDetails.Type == acme.BadNonceErr { return &acme.NonceError{ProblemDetails: errorDetails} diff --git a/vendor/github.com/go-acme/lego/v4/acme/api/internal/sender/useragent.go b/vendor/github.com/go-acme/lego/v4/acme/api/internal/sender/useragent.go index a89693c6..f3f104ff 100644 --- a/vendor/github.com/go-acme/lego/v4/acme/api/internal/sender/useragent.go +++ b/vendor/github.com/go-acme/lego/v4/acme/api/internal/sender/useragent.go @@ -5,7 +5,7 @@ package sender const ( // ourUserAgent is the User-Agent of this underlying library package. - ourUserAgent = "xenolf-acme/4.8.0" + ourUserAgent = "xenolf-acme/4.14.0" // ourUserAgentComment is part of the UA comment linked to the version status of this underlying library package. // values: detach|release diff --git a/vendor/github.com/go-acme/lego/v4/acme/api/order.go b/vendor/github.com/go-acme/lego/v4/acme/api/order.go index 7b2a2be7..fe1be94f 100644 --- a/vendor/github.com/go-acme/lego/v4/acme/api/order.go +++ b/vendor/github.com/go-acme/lego/v4/acme/api/order.go @@ -3,21 +3,50 @@ package api import ( "encoding/base64" "errors" + "net" + "time" "github.com/go-acme/lego/v4/acme" ) +// OrderOptions used to create an order (optional). +type OrderOptions struct { + NotBefore time.Time + NotAfter time.Time +} + type OrderService service // New Creates a new order. func (o *OrderService) New(domains []string) (acme.ExtendedOrder, error) { + return o.NewWithOptions(domains, nil) +} + +// NewWithOptions Creates a new order. +func (o *OrderService) NewWithOptions(domains []string, opts *OrderOptions) (acme.ExtendedOrder, error) { var identifiers []acme.Identifier for _, domain := range domains { - identifiers = append(identifiers, acme.Identifier{Type: "dns", Value: domain}) + ident := acme.Identifier{Value: domain, Type: "dns"} + + if net.ParseIP(domain) != nil { + ident.Type = "ip" + } + + identifiers = append(identifiers, ident) } orderReq := acme.Order{Identifiers: identifiers} + if opts != nil { + if !opts.NotAfter.IsZero() { + orderReq.NotAfter = opts.NotAfter.Format(time.RFC3339) + } + + if !opts.NotBefore.IsZero() { + orderReq.NotBefore = opts.NotBefore.Format(time.RFC3339) + } + } + var order acme.Order resp, err := o.core.post(o.core.GetDirectory().NewOrderURL, orderReq, &order) if err != nil { diff --git a/vendor/github.com/go-acme/lego/v4/acme/api/renewal.go b/vendor/github.com/go-acme/lego/v4/acme/api/renewal.go new file mode 100644 index 00000000..7a5c5985 --- /dev/null +++ b/vendor/github.com/go-acme/lego/v4/acme/api/renewal.go @@ -0,0 +1,53 @@ +package api + +import ( + "errors" + "net/http" + + "github.com/go-acme/lego/v4/acme" +) + +// ErrNoARI is returned when the server does not advertise a renewal info endpoint. +var ErrNoARI = errors.New("renewalInfo[get/post]: server does not advertise a renewal info endpoint") + +// GetRenewalInfo GETs renewal information for a certificate from the renewalInfo endpoint. +// This is used to determine if a certificate needs to be renewed. +// +// Note: this endpoint is part of a draft specification, not all ACME servers will implement it. +// This method will return api.ErrNoARI if the server does not advertise a renewal info endpoint. +// +// https://datatracker.ietf.org/doc/draft-ietf-acme-ari +func (c *CertificateService) GetRenewalInfo(certID string) (*http.Response, error) { + if c.core.GetDirectory().RenewalInfo == "" { + return nil, ErrNoARI + } + + if certID == "" { + return nil, errors.New("renewalInfo[get]: 'certID' cannot be empty") + } + + return c.core.HTTPClient.Get(c.core.GetDirectory().RenewalInfo + "/" + certID) +} + +// UpdateRenewalInfo POSTs updated renewal information for a certificate to the renewalInfo endpoint. +// This is used to indicate that a certificate has been replaced. +// +// Note: this endpoint is part of a draft specification, not all ACME servers will implement it. +// This method will return api.ErrNoARI if the server does not advertise a renewal info endpoint. +// +// https://datatracker.ietf.org/doc/draft-ietf-acme-ari +func (c *CertificateService) UpdateRenewalInfo(req acme.RenewalInfoUpdateRequest) (*http.Response, error) { + if c.core.GetDirectory().RenewalInfo == "" { + return nil, ErrNoARI + } + + if req.CertID == "" { + return nil, errors.New("renewalInfo[post]: 'certID' cannot be empty") + } + + if !req.Replaced { + return nil, errors.New("renewalInfo[post]: 'replaced' cannot be false") + } + + return c.core.post(c.core.GetDirectory().RenewalInfo, req, nil) +} diff --git a/vendor/github.com/go-acme/lego/v4/acme/commons.go b/vendor/github.com/go-acme/lego/v4/acme/commons.go index b37fa07d..03b5db6d 100644 --- a/vendor/github.com/go-acme/lego/v4/acme/commons.go +++ b/vendor/github.com/go-acme/lego/v4/acme/commons.go @@ -38,6 +38,7 @@ const ( // Directory the ACME directory object. // - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.1.1 +// - https://datatracker.ietf.org/doc/draft-ietf-acme-ari/ type Directory struct { NewNonceURL string `json:"newNonce"` NewAccountURL string `json:"newAccount"` @@ -46,6 +47,7 @@ type Directory struct { RevokeCertURL string `json:"revokeCert"` KeyChangeURL string `json:"keyChange"` Meta Meta `json:"meta"` + RenewalInfo string `json:"renewalInfo"` } // Meta the ACME meta object (related to Directory). @@ -69,12 +71,12 @@ type Meta struct { // externalAccountRequired (optional, boolean): // If this field is present and set to "true", - // then the CA requires that all new- account requests include an "externalAccountBinding" field + // then the CA requires that all new-account requests include an "externalAccountBinding" field // associating the new account with an external account. ExternalAccountRequired bool `json:"externalAccountRequired"` } -// ExtendedAccount a extended Account. +// ExtendedAccount an extended Account. type ExtendedAccount struct { Account // Contains the value of the response header `Location` @@ -89,7 +91,7 @@ type Account struct { // The status of this account. // Possible values are: "valid", "deactivated", and "revoked". // The value "deactivated" should be used to indicate client-initiated deactivation - // whereas "revoked" should be used to indicate server- initiated deactivation. (See Section 7.1.6) + // whereas "revoked" should be used to indicate server-initiated deactivation. (See Section 7.1.6) Status string `json:"status,omitempty"` // contact (optional, array of string): @@ -306,3 +308,34 @@ type RawCertificate struct { Cert []byte Issuer []byte } + +// Window is a window of time. +type Window struct { + Start time.Time `json:"start"` + End time.Time `json:"end"` +} + +// RenewalInfoResponse is the response to GET requests made the renewalInfo endpoint. +// - (4.1. Getting Renewal Information) https://datatracker.ietf.org/doc/draft-ietf-acme-ari/ +type RenewalInfoResponse struct { + // SuggestedWindow contains two fields, start and end, + // whose values are timestamps which bound the window of time in which the CA recommends renewing the certificate. + SuggestedWindow Window `json:"suggestedWindow"` + // ExplanationURL is an optional URL pointing to a page which may explain why the suggested renewal window is what it is. + // For example, it may be a page explaining the CA's dynamic load-balancing strategy, + // or a page documenting which certificates are affected by a mass revocation event. + // Callers SHOULD provide this URL to their operator, if present. + ExplanationURL string `json:"explanationURL"` +} + +// RenewalInfoUpdateRequest is the JWS payload for POST requests made to the renewalInfo endpoint. +// - (4.2. Updating Renewal Information) https://datatracker.ietf.org/doc/draft-ietf-acme-ari/ +type RenewalInfoUpdateRequest struct { + // CertID is the base64url-encoded [RFC4648] bytes of a DER-encoded CertID ASN.1 sequence [RFC6960] with any trailing '=' characters stripped. + CertID string `json:"certID"` + // Replaced is required and indicates whether or not the client considers the certificate to have been replaced. + // A certificate is considered replaced when its revocation would not disrupt any ongoing services, + // for instance because it has been renewed and the new certificate is in use, or because it is no longer in use. + // Clients SHOULD NOT send a request where this value is false. + Replaced bool `json:"replaced"` +} diff --git a/vendor/github.com/go-acme/lego/v4/certcrypto/crypto.go b/vendor/github.com/go-acme/lego/v4/certcrypto/crypto.go index 31e31f1d..2d531630 100644 --- a/vendor/github.com/go-acme/lego/v4/certcrypto/crypto.go +++ b/vendor/github.com/go-acme/lego/v4/certcrypto/crypto.go @@ -14,6 +14,7 @@ import ( "errors" "fmt" "math/big" + "net" "strings" "time" @@ -25,6 +26,7 @@ const ( EC256 = KeyType("P256") EC384 = KeyType("P384") RSA2048 = KeyType("2048") + RSA3072 = KeyType("3072") RSA4096 = KeyType("4096") RSA8192 = KeyType("8192") ) @@ -82,7 +84,7 @@ func ParsePEMBundle(bundle []byte) ([]*x509.Certificate, error) { // ParsePEMPrivateKey parses a private key from key, which is a PEM block. // Borrowed from Go standard library, to handle various private key and PEM block types. // https://github.com/golang/go/blob/693748e9fa385f1e2c3b91ca9acbb6c0ad2d133d/src/crypto/tls/tls.go#L291-L308 -// https://github.com/golang/go/blob/693748e9fa385f1e2c3b91ca9acbb6c0ad2d133d/src/crypto/tls/tls.go#L238) +// https://github.com/golang/go/blob/693748e9fa385f1e2c3b91ca9acbb6c0ad2d133d/src/crypto/tls/tls.go#L238 func ParsePEMPrivateKey(key []byte) (crypto.PrivateKey, error) { keyBlockDER, _ := pem.Decode(key) if keyBlockDER == nil { @@ -121,6 +123,8 @@ func GeneratePrivateKey(keyType KeyType) (crypto.PrivateKey, error) { return ecdsa.GenerateKey(elliptic.P384(), rand.Reader) case RSA2048: return rsa.GenerateKey(rand.Reader, 2048) + case RSA3072: + return rsa.GenerateKey(rand.Reader, 3072) case RSA4096: return rsa.GenerateKey(rand.Reader, 4096) case RSA8192: @@ -131,9 +135,20 @@ func GeneratePrivateKey(keyType KeyType) (crypto.PrivateKey, error) { } func GenerateCSR(privateKey crypto.PrivateKey, domain string, san []string, mustStaple bool) ([]byte, error) { + var dnsNames []string + var ipAddresses []net.IP + for _, altname := range san { + if ip := net.ParseIP(altname); ip != nil { + ipAddresses = append(ipAddresses, ip) + } else { + dnsNames = append(dnsNames, altname) + } + } + template := x509.CertificateRequest{ - Subject: pkix.Name{CommonName: domain}, - DNSNames: san, + Subject: pkix.Name{CommonName: domain}, + DNSNames: dnsNames, + IPAddresses: ipAddresses, } if mustStaple { @@ -215,6 +230,13 @@ func ExtractDomains(cert *x509.Certificate) []string { domains = append(domains, sanDomain) } + commonNameIP := net.ParseIP(cert.Subject.CommonName) + for _, sanIP := range cert.IPAddresses { + if !commonNameIP.Equal(sanIP) { + domains = append(domains, sanIP.String()) + } + } + return domains } @@ -235,6 +257,13 @@ func ExtractDomainsCSR(csr *x509.CertificateRequest) []string { domains = append(domains, sanName) } + cnip := net.ParseIP(csr.Subject.CommonName) + for _, sanIP := range csr.IPAddresses { + if !cnip.Equal(sanIP) { + domains = append(domains, sanIP.String()) + } + } + return domains } @@ -277,9 +306,15 @@ func generateDerCert(privateKey *rsa.PrivateKey, expiration time.Time, domain st KeyUsage: x509.KeyUsageKeyEncipherment, BasicConstraintsValid: true, - DNSNames: []string{domain}, ExtraExtensions: extensions, } + // handling SAN filling as type suspected + if ip := net.ParseIP(domain); ip != nil { + template.IPAddresses = []net.IP{ip} + } else { + template.DNSNames = []string{domain} + } + return x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) } diff --git a/vendor/github.com/go-acme/lego/v4/certificate/authorization.go b/vendor/github.com/go-acme/lego/v4/certificate/authorization.go index 452db0d9..de9988ad 100644 --- a/vendor/github.com/go-acme/lego/v4/certificate/authorization.go +++ b/vendor/github.com/go-acme/lego/v4/certificate/authorization.go @@ -35,13 +35,14 @@ func (c *Certifier) getAuthorizations(order acme.ExtendedOrder) ([]acme.Authoriz } var responses []acme.Authorization - failures := make(obtainError) + + failures := newObtainError() for i := 0; i < len(order.Authorizations); i++ { select { case res := <-resc: responses = append(responses, res) case err := <-errc: - failures[err.Domain] = err.Error + failures.Add(err.Domain, err.Error) } } @@ -52,12 +53,7 @@ func (c *Certifier) getAuthorizations(order acme.ExtendedOrder) ([]acme.Authoriz close(resc) close(errc) - // be careful to not return an empty failures map; - // even if empty, they become non-nil error values - if len(failures) > 0 { - return responses, failures - } - return responses, nil + return responses, failures.Join() } func (c *Certifier) deactivateAuthorizations(order acme.ExtendedOrder, force bool) { diff --git a/vendor/github.com/go-acme/lego/v4/certificate/certificates.go b/vendor/github.com/go-acme/lego/v4/certificate/certificates.go index d6ab4b41..2d0fa8d2 100644 --- a/vendor/github.com/go-acme/lego/v4/certificate/certificates.go +++ b/vendor/github.com/go-acme/lego/v4/certificate/certificates.go @@ -54,10 +54,13 @@ type Resource struct { // If `AlwaysDeactivateAuthorizations` is true, the authorizations are also relinquished if the obtain request was successful. // See https://datatracker.ietf.org/doc/html/rfc8555#section-7.5.2. type ObtainRequest struct { - Domains []string + Domains []string + PrivateKey crypto.PrivateKey + MustStaple bool + + NotBefore time.Time + NotAfter time.Time Bundle bool - PrivateKey crypto.PrivateKey - MustStaple bool PreferredChain string AlwaysDeactivateAuthorizations bool } @@ -69,7 +72,10 @@ type ObtainRequest struct { // If `AlwaysDeactivateAuthorizations` is true, the authorizations are also relinquished if the obtain request was successful. // See https://datatracker.ietf.org/doc/html/rfc8555#section-7.5.2. type ObtainForCSRRequest struct { - CSR *x509.CertificateRequest + CSR *x509.CertificateRequest + + NotBefore time.Time + NotAfter time.Time Bundle bool PreferredChain string AlwaysDeactivateAuthorizations bool @@ -117,7 +123,12 @@ func (c *Certifier) Obtain(request ObtainRequest) (*Resource, error) { log.Infof("[%s] acme: Obtaining SAN certificate", strings.Join(domains, ", ")) } - order, err := c.core.Orders.New(domains) + orderOpts := &api.OrderOptions{ + NotBefore: request.NotBefore, + NotAfter: request.NotAfter, + } + + order, err := c.core.Orders.NewWithOptions(domains, orderOpts) if err != nil { return nil, err } @@ -138,11 +149,11 @@ func (c *Certifier) Obtain(request ObtainRequest) (*Resource, error) { log.Infof("[%s] acme: Validations succeeded; requesting certificates", strings.Join(domains, ", ")) - failures := make(obtainError) + failures := newObtainError() cert, err := c.getForOrder(domains, order, request.Bundle, request.PrivateKey, request.MustStaple, request.PreferredChain) if err != nil { for _, auth := range authz { - failures[challenge.GetTargetedDomain(auth)] = err + failures.Add(challenge.GetTargetedDomain(auth), err) } } @@ -150,12 +161,7 @@ func (c *Certifier) Obtain(request ObtainRequest) (*Resource, error) { c.deactivateAuthorizations(order, true) } - // Do not return an empty failures map, because - // it would still be a non-nil error value - if len(failures) > 0 { - return cert, failures - } - return cert, nil + return cert, failures.Join() } // ObtainForCSR tries to obtain a certificate matching the CSR passed into it. @@ -182,7 +188,12 @@ func (c *Certifier) ObtainForCSR(request ObtainForCSRRequest) (*Resource, error) log.Infof("[%s] acme: Obtaining SAN certificate given a CSR", strings.Join(domains, ", ")) } - order, err := c.core.Orders.New(domains) + orderOpts := &api.OrderOptions{ + NotBefore: request.NotBefore, + NotAfter: request.NotAfter, + } + + order, err := c.core.Orders.NewWithOptions(domains, orderOpts) if err != nil { return nil, err } @@ -203,11 +214,11 @@ func (c *Certifier) ObtainForCSR(request ObtainForCSRRequest) (*Resource, error) log.Infof("[%s] acme: Validations succeeded; requesting certificates", strings.Join(domains, ", ")) - failures := make(obtainError) + failures := newObtainError() cert, err := c.getForCSR(domains, order, request.Bundle, request.CSR.Raw, nil, request.PreferredChain) if err != nil { for _, auth := range authz { - failures[challenge.GetTargetedDomain(auth)] = err + failures.Add(challenge.GetTargetedDomain(auth), err) } } @@ -220,12 +231,7 @@ func (c *Certifier) ObtainForCSR(request ObtainForCSRRequest) (*Resource, error) cert.CSR = certcrypto.PEMEncode(request.CSR) } - // Do not return an empty failures map, - // because it would still be a non-nil error value - if len(failures) > 0 { - return cert, failures - } - return cert, nil + return cert, failures.Join() } func (c *Certifier) getForOrder(domains []string, order acme.ExtendedOrder, bundle bool, privateKey crypto.PrivateKey, mustStaple bool, preferredChain string) (*Resource, error) { @@ -276,7 +282,7 @@ func (c *Certifier) getForCSR(domains []string, order acme.ExtendedOrder, bundle } if respOrder.Status == acme.StatusValid { - // if the certificate is available right away, short cut! + // if the certificate is available right away, shortcut! ok, errR := c.checkResponse(respOrder, certRes, bundle, preferredChain) if errR != nil { return nil, errR @@ -388,6 +394,18 @@ func (c *Certifier) RevokeWithReason(cert []byte, reason *uint) error { return c.core.Certificates.Revoke(revokeMsg) } +// RenewOptions options used by Certifier.RenewWithOptions. +type RenewOptions struct { + NotBefore time.Time + NotAfter time.Time + // If true, the []byte contains both the issuer certificate and your issued certificate as a bundle. + Bundle bool + PreferredChain string + AlwaysDeactivateAuthorizations bool + // Not supported for CSR request. + MustStaple bool +} + // Renew takes a Resource and tries to renew the certificate. // // If the renewal process succeeds, the new certificate will be returned in a new CertResource. @@ -398,7 +416,26 @@ func (c *Certifier) RevokeWithReason(cert []byte, reason *uint) error { // If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle. // // For private key reuse the PrivateKey property of the passed in Resource should be non-nil. +// Deprecated: use RenewWithOptions instead. func (c *Certifier) Renew(certRes Resource, bundle, mustStaple bool, preferredChain string) (*Resource, error) { + return c.RenewWithOptions(certRes, &RenewOptions{ + Bundle: bundle, + PreferredChain: preferredChain, + MustStaple: mustStaple, + }) +} + +// RenewWithOptions takes a Resource and tries to renew the certificate. +// +// If the renewal process succeeds, the new certificate will be returned in a new CertResource. +// Please be aware that this function will return a new certificate in ANY case that is not an error. +// If the server does not provide us with a new cert on a GET request to the CertURL +// this function will start a new-cert flow where a new certificate gets generated. +// +// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle. +// +// For private key reuse the PrivateKey property of the passed in Resource should be non-nil. +func (c *Certifier) RenewWithOptions(certRes Resource, options *RenewOptions) (*Resource, error) { // Input certificate is PEM encoded. // Decode it here as we may need the decoded cert later on in the renewal process. // The input may be a bundle or a single certificate. @@ -425,11 +462,17 @@ func (c *Certifier) Renew(certRes Resource, bundle, mustStaple bool, preferredCh return nil, errP } - return c.ObtainForCSR(ObtainForCSRRequest{ - CSR: csr, - Bundle: bundle, - PreferredChain: preferredChain, - }) + request := ObtainForCSRRequest{CSR: csr} + + if options != nil { + request.NotBefore = options.NotBefore + request.NotAfter = options.NotAfter + request.Bundle = options.Bundle + request.PreferredChain = options.PreferredChain + request.AlwaysDeactivateAuthorizations = options.AlwaysDeactivateAuthorizations + } + + return c.ObtainForCSR(request) } var privateKey crypto.PrivateKey @@ -440,14 +483,21 @@ func (c *Certifier) Renew(certRes Resource, bundle, mustStaple bool, preferredCh } } - query := ObtainRequest{ - Domains: certcrypto.ExtractDomains(x509Cert), - Bundle: bundle, - PrivateKey: privateKey, - MustStaple: mustStaple, - PreferredChain: preferredChain, + request := ObtainRequest{ + Domains: certcrypto.ExtractDomains(x509Cert), + PrivateKey: privateKey, + } + + if options != nil { + request.MustStaple = options.MustStaple + request.NotBefore = options.NotBefore + request.NotAfter = options.NotAfter + request.Bundle = options.Bundle + request.PreferredChain = options.PreferredChain + request.AlwaysDeactivateAuthorizations = options.AlwaysDeactivateAuthorizations } - return c.Obtain(query) + + return c.Obtain(request) } // GetOCSP takes a PEM encoded cert or cert bundle returning the raw OCSP response, diff --git a/vendor/github.com/go-acme/lego/v4/certificate/errors.go b/vendor/github.com/go-acme/lego/v4/certificate/errors.go index 3adbc783..f305524d 100644 --- a/vendor/github.com/go-acme/lego/v4/certificate/errors.go +++ b/vendor/github.com/go-acme/lego/v4/certificate/errors.go @@ -1,27 +1,37 @@ package certificate import ( - "bytes" + "errors" "fmt" - "sort" ) -// obtainError is returned when there are specific errors available per domain. -type obtainError map[string]error +type obtainError struct { + data map[string]error +} + +func newObtainError() *obtainError { + return &obtainError{data: make(map[string]error)} +} -func (e obtainError) Error() string { - buffer := bytes.NewBufferString("error: one or more domains had a problem:\n") +func (e *obtainError) Add(domain string, err error) { + e.data[domain] = err +} - var domains []string - for domain := range e { - domains = append(domains, domain) +func (e *obtainError) Join() error { + if e == nil { + return nil } - sort.Strings(domains) - for _, domain := range domains { - buffer.WriteString(fmt.Sprintf("[%s] %s\n", domain, e[domain])) + if len(e.data) == 0 { + return nil } - return buffer.String() + + var err error + for d, e := range e.data { + err = errors.Join(err, fmt.Errorf("%s: %w", d, e)) + } + + return fmt.Errorf("error: one or more domains had a problem:\n%w", err) } type domainError struct { diff --git a/vendor/github.com/go-acme/lego/v4/certificate/renewal.go b/vendor/github.com/go-acme/lego/v4/certificate/renewal.go new file mode 100644 index 00000000..26160672 --- /dev/null +++ b/vendor/github.com/go-acme/lego/v4/certificate/renewal.go @@ -0,0 +1,204 @@ +package certificate + +import ( + "crypto" + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" + "encoding/base64" + "encoding/json" + "fmt" + "math/big" + "math/rand" + "strings" + "time" + + "github.com/go-acme/lego/v4/acme" +) + +// RenewalInfoRequest contains the necessary renewal information. +type RenewalInfoRequest struct { + Cert *x509.Certificate + Issuer *x509.Certificate + // HashName must be the string representation of a crypto.Hash constant in the golang.org/x/crypto package (e.g. "SHA-256"). + // The correct value depends on the algorithm expected by the ACME server's ARI implementation. + HashName string +} + +// RenewalInfoResponse is a wrapper around acme.RenewalInfoResponse that provides a method for determining when to renew a certificate. +type RenewalInfoResponse struct { + acme.RenewalInfoResponse +} + +// ShouldRenewAt determines the optimal renewal time based on the current time (UTC),renewal window suggest by ARI, and the client's willingness to sleep. +// It returns a pointer to a time.Time value indicating when the renewal should be attempted or nil if deferred until the next normal wake time. +// This method implements the RECOMMENDED algorithm described in draft-ietf-acme-ari. +// +// - (4.1-11. Getting Renewal Information) https://datatracker.ietf.org/doc/draft-ietf-acme-ari/ +func (r *RenewalInfoResponse) ShouldRenewAt(now time.Time, willingToSleep time.Duration) *time.Time { + // Explicitly convert all times to UTC. + now = now.UTC() + start := r.SuggestedWindow.Start.UTC() + end := r.SuggestedWindow.End.UTC() + + // Select a uniform random time within the suggested window. + window := end.Sub(start) + randomDuration := time.Duration(rand.Int63n(int64(window))) + rt := start.Add(randomDuration) + + // If the selected time is in the past, attempt renewal immediately. + if rt.Before(now) { + return &now + } + + // Otherwise, if the client can schedule itself to attempt renewal at exactly the selected time, do so. + willingToSleepUntil := now.Add(willingToSleep) + if willingToSleepUntil.After(rt) || willingToSleepUntil.Equal(rt) { + return &rt + } + + // TODO: Otherwise, if the selected time is before the next time that the client would wake up normally, attempt renewal immediately. + + // Otherwise, sleep until the next normal wake time, re-check ARI, and return to Step 1. + return nil +} + +// GetRenewalInfo sends a request to the ACME server's renewalInfo endpoint to obtain a suggested renewal window. +// The caller MUST provide the certificate and issuer certificate for the certificate they wish to renew. +// The caller should attempt to renew the certificate at the time indicated by the ShouldRenewAt method of the returned RenewalInfoResponse object. +// +// Note: this endpoint is part of a draft specification, not all ACME servers will implement it. +// This method will return api.ErrNoARI if the server does not advertise a renewal info endpoint. +// +// https://datatracker.ietf.org/doc/draft-ietf-acme-ari +func (c *Certifier) GetRenewalInfo(req RenewalInfoRequest) (*RenewalInfoResponse, error) { + certID, err := makeCertID(req.Cert, req.Issuer, req.HashName) + if err != nil { + return nil, fmt.Errorf("error making certID: %w", err) + } + + resp, err := c.core.Certificates.GetRenewalInfo(certID) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + var info RenewalInfoResponse + err = json.NewDecoder(resp.Body).Decode(&info) + if err != nil { + return nil, err + } + return &info, nil +} + +// UpdateRenewalInfo sends an update to the ACME server's renewal info endpoint to indicate that the client has successfully replaced a certificate. +// A certificate is considered replaced when its revocation would not disrupt any ongoing services, +// for instance because it has been renewed and the new certificate is in use, or because it is no longer in use. +// +// Note: this endpoint is part of a draft specification, not all ACME servers will implement it. +// This method will return api.ErrNoARI if the server does not advertise a renewal info endpoint. +// +// https://datatracker.ietf.org/doc/draft-ietf-acme-ari +func (c *Certifier) UpdateRenewalInfo(req RenewalInfoRequest) error { + certID, err := makeCertID(req.Cert, req.Issuer, req.HashName) + if err != nil { + return fmt.Errorf("error making certID: %w", err) + } + + _, err = c.core.Certificates.UpdateRenewalInfo(acme.RenewalInfoUpdateRequest{ + CertID: certID, + Replaced: true, + }) + if err != nil { + return err + } + + return nil +} + +// makeCertID returns a base64url-encoded string that uniquely identifies a certificate to endpoints +// that implement the draft-ietf-acme-ari specification: https://datatracker.ietf.org/doc/draft-ietf-acme-ari. +// hashName must be the string representation of a crypto.Hash constant in the golang.org/x/crypto package. +// Supported hash functions are SHA-1, SHA-256, SHA-384, and SHA-512. +func makeCertID(leaf, issuer *x509.Certificate, hashName string) (string, error) { + if leaf == nil { + return "", fmt.Errorf("leaf certificate is nil") + } + if issuer == nil { + return "", fmt.Errorf("issuer certificate is nil") + } + + var hashFunc crypto.Hash + var oid asn1.ObjectIdentifier + + switch hashName { + // The following correlation of hashFunc to OID is copied from a private mapping in golang.org/x/crypto/ocsp: + // https://cs.opensource.google/go/x/crypto/+/refs/tags/v0.8.0:ocsp/ocsp.go;l=156 + case crypto.SHA1.String(): + hashFunc = crypto.SHA1 + oid = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}) + + case crypto.SHA256.String(): + hashFunc = crypto.SHA256 + oid = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 1}) + + case crypto.SHA384.String(): + hashFunc = crypto.SHA384 + oid = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 2}) + + case crypto.SHA512.String(): + hashFunc = crypto.SHA512 + oid = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 3}) + + default: + return "", fmt.Errorf("hashName %q is not supported by this package", hashName) + } + + if !hashFunc.Available() { + // This should never happen. + return "", fmt.Errorf("hash function %q is not available on your platform", hashFunc) + } + + var spki struct { + Algorithm pkix.AlgorithmIdentifier + PublicKey asn1.BitString + } + + _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &spki) + if err != nil { + return "", err + } + h := hashFunc.New() + h.Write(spki.PublicKey.RightAlign()) + issuerKeyHash := h.Sum(nil) + + h.Reset() + h.Write(issuer.RawSubject) + issuerNameHash := h.Sum(nil) + + type certID struct { + HashAlgorithm pkix.AlgorithmIdentifier + IssuerNameHash []byte + IssuerKeyHash []byte + SerialNumber *big.Int + } + + // DER-encode the CertID ASN.1 sequence [RFC6960]. + certIDBytes, err := asn1.Marshal(certID{ + HashAlgorithm: pkix.AlgorithmIdentifier{ + Algorithm: oid, + }, + IssuerNameHash: issuerNameHash, + IssuerKeyHash: issuerKeyHash, + SerialNumber: leaf.SerialNumber, + }) + if err != nil { + return "", err + } + + // base64url-encode [RFC4648] the bytes of the DER-encoded CertID ASN.1 sequence [RFC6960]. + encodedBytes := base64.URLEncoding.EncodeToString(certIDBytes) + + // Any trailing '=' characters MUST be stripped. + return strings.TrimRight(encodedBytes, "="), nil +} diff --git a/vendor/github.com/go-acme/lego/v4/challenge/dns01/cname.go b/vendor/github.com/go-acme/lego/v4/challenge/dns01/cname.go index ab35ee84..26fe1501 100644 --- a/vendor/github.com/go-acme/lego/v4/challenge/dns01/cname.go +++ b/vendor/github.com/go-acme/lego/v4/challenge/dns01/cname.go @@ -1,12 +1,16 @@ package dns01 -import "github.com/miekg/dns" +import ( + "strings" + + "github.com/miekg/dns" +) // Update FQDN with CNAME if any. func updateDomainWithCName(r *dns.Msg, fqdn string) string { for _, rr := range r.Answer { if cn, ok := rr.(*dns.CNAME); ok { - if cn.Hdr.Name == fqdn { + if strings.EqualFold(cn.Hdr.Name, fqdn) { return cn.Target } } diff --git a/vendor/github.com/go-acme/lego/v4/challenge/dns01/dns_challenge.go b/vendor/github.com/go-acme/lego/v4/challenge/dns01/dns_challenge.go index e46e9bac..3364b934 100644 --- a/vendor/github.com/go-acme/lego/v4/challenge/dns01/dns_challenge.go +++ b/vendor/github.com/go-acme/lego/v4/challenge/dns01/dns_challenge.go @@ -114,7 +114,7 @@ func (c *Challenge) Solve(authz acme.Authorization) error { return err } - fqdn, value := GetRecord(authz.Identifier.Value, keyAuth) + info := GetChallengeInfo(authz.Identifier.Value, keyAuth) var timeout, interval time.Duration switch provider := c.provider.(type) { @@ -129,7 +129,7 @@ func (c *Challenge) Solve(authz acme.Authorization) error { time.Sleep(interval) err = wait.For("propagation", timeout, interval, func() (bool, error) { - stop, errP := c.preCheck.call(domain, fqdn, value) + stop, errP := c.preCheck.call(domain, info.EffectiveFQDN, info.Value) if !stop || errP != nil { log.Infof("[%s] acme: Waiting for DNS record propagation.", domain) } @@ -172,19 +172,67 @@ type sequential interface { } // GetRecord returns a DNS record which will fulfill the `dns-01` challenge. +// Deprecated: use GetChallengeInfo instead. func GetRecord(domain, keyAuth string) (fqdn, value string) { + info := GetChallengeInfo(domain, keyAuth) + + return info.EffectiveFQDN, info.Value +} + +// ChallengeInfo contains the information use to create the TXT record. +type ChallengeInfo struct { + // FQDN is the full-qualified challenge domain (i.e. `_acme-challenge.[domain].`) + FQDN string + + // EffectiveFQDN contains the resulting FQDN after the CNAMEs resolutions. + EffectiveFQDN string + + // Value contains the value for the TXT record. + Value string +} + +// GetChallengeInfo returns information used to create a DNS record which will fulfill the `dns-01` challenge. +func GetChallengeInfo(domain, keyAuth string) ChallengeInfo { keyAuthShaBytes := sha256.Sum256([]byte(keyAuth)) // base64URL encoding without padding - value = base64.RawURLEncoding.EncodeToString(keyAuthShaBytes[:sha256.Size]) - fqdn = fmt.Sprintf("_acme-challenge.%s.", domain) + value := base64.RawURLEncoding.EncodeToString(keyAuthShaBytes[:sha256.Size]) + + ok, _ := strconv.ParseBool(os.Getenv("LEGO_DISABLE_CNAME_SUPPORT")) - if ok, _ := strconv.ParseBool(os.Getenv("LEGO_EXPERIMENTAL_CNAME_SUPPORT")); ok { + return ChallengeInfo{ + Value: value, + FQDN: getChallengeFQDN(domain, false), + EffectiveFQDN: getChallengeFQDN(domain, !ok), + } +} + +func getChallengeFQDN(domain string, followCNAME bool) string { + fqdn := fmt.Sprintf("_acme-challenge.%s.", domain) + + if !followCNAME { + return fqdn + } + + // recursion counter so it doesn't spin out of control + for limit := 0; limit < 50; limit++ { + // Keep following CNAMEs r, err := dnsQuery(fqdn, dns.TypeCNAME, recursiveNameservers, true) - // Check if the domain has CNAME then return that - if err == nil && r.Rcode == dns.RcodeSuccess { - fqdn = updateDomainWithCName(r, fqdn) + + if err != nil || r.Rcode != dns.RcodeSuccess { + // No more CNAME records to follow, exit + break } + + // Check if the domain has CNAME then use that + cname := updateDomainWithCName(r, fqdn) + if cname == fqdn { + break + } + + log.Infof("Found CNAME entry for %q: %q", fqdn, cname) + + fqdn = cname } - return + return fqdn } diff --git a/vendor/github.com/go-acme/lego/v4/challenge/dns01/dns_challenge_manual.go b/vendor/github.com/go-acme/lego/v4/challenge/dns01/dns_challenge_manual.go index ced3ab58..6f211fbb 100644 --- a/vendor/github.com/go-acme/lego/v4/challenge/dns01/dns_challenge_manual.go +++ b/vendor/github.com/go-acme/lego/v4/challenge/dns01/dns_challenge_manual.go @@ -21,15 +21,15 @@ func NewDNSProviderManual() (*DNSProviderManual, error) { // Present prints instructions for manually creating the TXT record. func (*DNSProviderManual) Present(domain, token, keyAuth string) error { - fqdn, value := GetRecord(domain, keyAuth) + info := GetChallengeInfo(domain, keyAuth) - authZone, err := FindZoneByFqdn(fqdn) + authZone, err := FindZoneByFqdn(info.EffectiveFQDN) if err != nil { return err } fmt.Printf("lego: Please create the following TXT record in your %s zone:\n", authZone) - fmt.Printf(dnsTemplate+"\n", fqdn, DefaultTTL, value) + fmt.Printf(dnsTemplate+"\n", info.EffectiveFQDN, DefaultTTL, info.Value) fmt.Printf("lego: Press 'Enter' when you are done\n") _, err = bufio.NewReader(os.Stdin).ReadBytes('\n') @@ -39,15 +39,15 @@ func (*DNSProviderManual) Present(domain, token, keyAuth string) error { // CleanUp prints instructions for manually removing the TXT record. func (*DNSProviderManual) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := GetRecord(domain, keyAuth) + info := GetChallengeInfo(domain, keyAuth) - authZone, err := FindZoneByFqdn(fqdn) + authZone, err := FindZoneByFqdn(info.EffectiveFQDN) if err != nil { return err } fmt.Printf("lego: You can now remove this TXT record from your %s zone:\n", authZone) - fmt.Printf(dnsTemplate+"\n", fqdn, DefaultTTL, "...") + fmt.Printf(dnsTemplate+"\n", info.EffectiveFQDN, DefaultTTL, "...") return nil } diff --git a/vendor/github.com/go-acme/lego/v4/challenge/dns01/domain.go b/vendor/github.com/go-acme/lego/v4/challenge/dns01/domain.go new file mode 100644 index 00000000..e9b0cec5 --- /dev/null +++ b/vendor/github.com/go-acme/lego/v4/challenge/dns01/domain.go @@ -0,0 +1,24 @@ +package dns01 + +import ( + "fmt" + "strings" + + "github.com/miekg/dns" +) + +// ExtractSubDomain extracts the subdomain part from a domain and a zone. +func ExtractSubDomain(domain, zone string) (string, error) { + canonDomain := dns.Fqdn(domain) + canonZone := dns.Fqdn(zone) + + if canonDomain == canonZone { + return "", fmt.Errorf("no subdomain because the domain and the zone are identical: %s", canonDomain) + } + + if !dns.IsSubDomain(canonZone, canonDomain) { + return "", fmt.Errorf("%s is not a subdomain of %s", canonDomain, canonZone) + } + + return strings.TrimSuffix(canonDomain, "."+canonZone), nil +} diff --git a/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver.go b/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver.go index a6947e9c..3e2ba78e 100644 --- a/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver.go +++ b/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "net" + "os" + "strconv" "strings" "sync" "time" @@ -13,9 +15,6 @@ import ( const defaultResolvConf = "/etc/resolv.conf" -// dnsTimeout is used to override the default DNS timeout of 10 seconds. -var dnsTimeout = 10 * time.Second - var ( fqdnSoaCache = map[string]*soaCacheEntry{} muFqdnSoaCache sync.Mutex @@ -253,12 +252,19 @@ func createDNSMsg(fqdn string, rtype uint16, recursive bool) *dns.Msg { } func sendDNSQuery(m *dns.Msg, ns string) (*dns.Msg, error) { + if ok, _ := strconv.ParseBool(os.Getenv("LEGO_EXPERIMENTAL_DNS_TCP_ONLY")); ok { + tcp := &dns.Client{Net: "tcp", Timeout: dnsTimeout} + in, _, err := tcp.Exchange(m, ns) + + return in, err + } + udp := &dns.Client{Net: "udp", Timeout: dnsTimeout} in, _, err := udp.Exchange(m, ns) if in != nil && in.Truncated { tcp := &dns.Client{Net: "tcp", Timeout: dnsTimeout} - // If the TCP request succeeds, the err will reset to nil + // If the TCP request succeeds, the "err" will reset to nil in, _, err = tcp.Exchange(m, ns) } diff --git a/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver_unix.go b/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver_unix.go new file mode 100644 index 00000000..a3cbad13 --- /dev/null +++ b/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver_unix.go @@ -0,0 +1,8 @@ +//go:build !windows + +package dns01 + +import "time" + +// dnsTimeout is used to override the default DNS timeout of 10 seconds. +var dnsTimeout = 10 * time.Second diff --git a/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver_windows.go b/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver_windows.go new file mode 100644 index 00000000..739e54a4 --- /dev/null +++ b/vendor/github.com/go-acme/lego/v4/challenge/dns01/nameserver_windows.go @@ -0,0 +1,8 @@ +//go:build windows + +package dns01 + +import "time" + +// dnsTimeout is used to override the default DNS timeout of 20 seconds. +var dnsTimeout = 20 * time.Second diff --git a/vendor/github.com/go-acme/lego/v4/challenge/http01/domain_matcher.go b/vendor/github.com/go-acme/lego/v4/challenge/http01/domain_matcher.go index 231f02d7..ae681c64 100644 --- a/vendor/github.com/go-acme/lego/v4/challenge/http01/domain_matcher.go +++ b/vendor/github.com/go-acme/lego/v4/challenge/http01/domain_matcher.go @@ -27,10 +27,13 @@ import ( // // Note: RFC7239 also reminds us, "that an HTTP list [...] may be split over multiple header fields" (section 7.1), // meaning that -// X-Header: a -// X-Header: b +// +// X-Header: a +// X-Header: b +// // is equal to -// X-Header: a, b +// +// X-Header: a, b // // All matcher implementations (explicitly not excluding arbitraryMatcher!) // have in common that they only match against the first value in such lists. diff --git a/vendor/github.com/go-acme/lego/v4/challenge/resolver/errors.go b/vendor/github.com/go-acme/lego/v4/challenge/resolver/errors.go index e9da1ebf..94ccbd76 100644 --- a/vendor/github.com/go-acme/lego/v4/challenge/resolver/errors.go +++ b/vendor/github.com/go-acme/lego/v4/challenge/resolver/errors.go @@ -19,7 +19,7 @@ func (e obtainError) Error() string { sort.Strings(domains) for _, domain := range domains { - buffer.WriteString(fmt.Sprintf("[%s] %s\n", domain, e[domain])) + _, _ = fmt.Fprintf(buffer, "[%s] %s\n", domain, e[domain]) } return buffer.String() } diff --git a/vendor/github.com/go-acme/lego/v4/challenge/resolver/prober.go b/vendor/github.com/go-acme/lego/v4/challenge/resolver/prober.go index 42c2029c..021facbb 100644 --- a/vendor/github.com/go-acme/lego/v4/challenge/resolver/prober.go +++ b/vendor/github.com/go-acme/lego/v4/challenge/resolver/prober.go @@ -128,7 +128,7 @@ func sequentialSolve(authSolvers []*selectedAuthSolver, failures obtainError) { } func parallelSolve(authSolvers []*selectedAuthSolver, failures obtainError) { - // For all valid preSolvers, first submit the challenges so they have max time to propagate + // For all valid preSolvers, first submit the challenges, so they have max time to propagate for _, authSolver := range authSolvers { authz := authSolver.authz if solvr, ok := authSolver.solver.(preSolver); ok { diff --git a/vendor/github.com/go-acme/lego/v4/challenge/resolver/solver_manager.go b/vendor/github.com/go-acme/lego/v4/challenge/resolver/solver_manager.go index 9709e891..138060bc 100644 --- a/vendor/github.com/go-acme/lego/v4/challenge/resolver/solver_manager.go +++ b/vendor/github.com/go-acme/lego/v4/challenge/resolver/solver_manager.go @@ -53,7 +53,7 @@ func (c *SolverManager) SetDNS01Provider(p challenge.Provider, opts ...dns01.Cha return nil } -// Remove Remove a challenge type from the available solvers. +// Remove removes a challenge type from the available solvers. func (c *SolverManager) Remove(chlgType challenge.Type) { delete(c.solvers, chlgType) } diff --git a/vendor/github.com/go-acme/lego/v4/challenge/tlsalpn01/tls_alpn_challenge_server.go b/vendor/github.com/go-acme/lego/v4/challenge/tlsalpn01/tls_alpn_challenge_server.go index e0976a6b..e5581b1e 100644 --- a/vendor/github.com/go-acme/lego/v4/challenge/tlsalpn01/tls_alpn_challenge_server.go +++ b/vendor/github.com/go-acme/lego/v4/challenge/tlsalpn01/tls_alpn_challenge_server.go @@ -40,7 +40,7 @@ func (s *ProviderServer) GetAddress() string { return net.JoinHostPort(s.iface, s.port) } -// Present generates a certificate with a SHA-256 digest of the keyAuth provided +// Present generates a certificate with an SHA-256 digest of the keyAuth provided // as the acmeValidation-v1 extension value to conform to the ACME-TLS-ALPN spec. func (s *ProviderServer) Present(domain, token, keyAuth string) error { if s.port == "" { diff --git a/vendor/github.com/go-acme/lego/v4/lego/client_config.go b/vendor/github.com/go-acme/lego/v4/lego/client_config.go index e75739c1..27bc1872 100644 --- a/vendor/github.com/go-acme/lego/v4/lego/client_config.go +++ b/vendor/github.com/go-acme/lego/v4/lego/client_config.go @@ -29,7 +29,7 @@ const ( // caServerNameEnvVar is the environment variable name that can be used to // specify the CA server name that can be used to - // authenticate an ACME server with a HTTPS certificate not issued by a CA in + // authenticate an ACME server with an HTTPS certificate not issued by a CA in // the system-wide trusted root list. caServerNameEnvVar = "LEGO_CA_SERVER_NAME" diff --git a/vendor/github.com/go-acme/lego/v4/platform/wait/wait.go b/vendor/github.com/go-acme/lego/v4/platform/wait/wait.go index d0c078b8..6ad817b2 100644 --- a/vendor/github.com/go-acme/lego/v4/platform/wait/wait.go +++ b/vendor/github.com/go-acme/lego/v4/platform/wait/wait.go @@ -1,7 +1,6 @@ package wait import ( - "errors" "fmt" "time" @@ -18,9 +17,9 @@ func For(msg string, timeout, interval time.Duration, f func() (bool, error)) er select { case <-timeUp: if lastErr == nil { - return errors.New("time limit exceeded") + return fmt.Errorf("%s: time limit exceeded", msg) } - return fmt.Errorf("time limit exceeded: last error: %w", lastErr) + return fmt.Errorf("%s: time limit exceeded: last error: %w", msg, lastErr) default: } diff --git a/vendor/github.com/go-acme/lego/v4/registration/registar.go b/vendor/github.com/go-acme/lego/v4/registration/registar.go index 25a1b7df..76920818 100644 --- a/vendor/github.com/go-acme/lego/v4/registration/registar.go +++ b/vendor/github.com/go-acme/lego/v4/registration/registar.go @@ -11,7 +11,7 @@ import ( // Resource represents all important information about a registration // of which the client needs to keep track itself. -// WARNING: will be remove in the future (acme.ExtendedAccount), https://github.com/go-acme/lego/issues/855. +// WARNING: will be removed in the future (acme.ExtendedAccount), https://github.com/go-acme/lego/issues/855. type Resource struct { Body acme.Account `json:"body,omitempty"` URI string `json:"uri,omitempty"` diff --git a/vendor/gopkg.in/square/go-jose.v2/.gitignore b/vendor/github.com/go-jose/go-jose/v3/.gitignore similarity index 50% rename from vendor/gopkg.in/square/go-jose.v2/.gitignore rename to vendor/github.com/go-jose/go-jose/v3/.gitignore index 95a85158..eb29ebae 100644 --- a/vendor/gopkg.in/square/go-jose.v2/.gitignore +++ b/vendor/github.com/go-jose/go-jose/v3/.gitignore @@ -1,8 +1,2 @@ -*~ -.*.swp -*.out -*.test -*.pem -*.cov jose-util/jose-util jose-util.t.err \ No newline at end of file diff --git a/vendor/github.com/go-jose/go-jose/v3/.golangci.yml b/vendor/github.com/go-jose/go-jose/v3/.golangci.yml new file mode 100644 index 00000000..2a577a8f --- /dev/null +++ b/vendor/github.com/go-jose/go-jose/v3/.golangci.yml @@ -0,0 +1,53 @@ +# https://github.com/golangci/golangci-lint + +run: + skip-files: + - doc_test.go + modules-download-mode: readonly + +linters: + enable-all: true + disable: + - gochecknoglobals + - goconst + - lll + - maligned + - nakedret + - scopelint + - unparam + - funlen # added in 1.18 (requires go-jose changes before it can be enabled) + +linters-settings: + gocyclo: + min-complexity: 35 + +issues: + exclude-rules: + - text: "don't use ALL_CAPS in Go names" + linters: + - golint + - text: "hardcoded credentials" + linters: + - gosec + - text: "weak cryptographic primitive" + linters: + - gosec + - path: json/ + linters: + - dupl + - errcheck + - gocritic + - gocyclo + - golint + - govet + - ineffassign + - staticcheck + - structcheck + - stylecheck + - unused + - path: _test\.go + linters: + - scopelint + - path: jwk.go + linters: + - gocyclo diff --git a/vendor/github.com/go-jose/go-jose/v3/.travis.yml b/vendor/github.com/go-jose/go-jose/v3/.travis.yml new file mode 100644 index 00000000..48de631b --- /dev/null +++ b/vendor/github.com/go-jose/go-jose/v3/.travis.yml @@ -0,0 +1,33 @@ +language: go + +matrix: + fast_finish: true + allow_failures: + - go: tip + +go: + - "1.13.x" + - "1.14.x" + - tip + +before_script: + - export PATH=$HOME/.local/bin:$PATH + +before_install: + - go get -u github.com/mattn/goveralls github.com/wadey/gocovmerge + - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.18.0 + - pip install cram --user + +script: + - go test -v -covermode=count -coverprofile=profile.cov . + - go test -v -covermode=count -coverprofile=cryptosigner/profile.cov ./cryptosigner + - go test -v -covermode=count -coverprofile=cipher/profile.cov ./cipher + - go test -v -covermode=count -coverprofile=jwt/profile.cov ./jwt + - go test -v ./json # no coverage for forked encoding/json package + - golangci-lint run + - cd jose-util && go build && PATH=$PWD:$PATH cram -v jose-util.t # cram tests jose-util + - cd .. + +after_success: + - gocovmerge *.cov */*.cov > merged.coverprofile + - goveralls -coverprofile merged.coverprofile -service=travis-ci diff --git a/vendor/gopkg.in/square/go-jose.v2/BUG-BOUNTY.md b/vendor/github.com/go-jose/go-jose/v3/BUG-BOUNTY.md similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/BUG-BOUNTY.md rename to vendor/github.com/go-jose/go-jose/v3/BUG-BOUNTY.md diff --git a/vendor/gopkg.in/square/go-jose.v2/CONTRIBUTING.md b/vendor/github.com/go-jose/go-jose/v3/CONTRIBUTING.md similarity index 75% rename from vendor/gopkg.in/square/go-jose.v2/CONTRIBUTING.md rename to vendor/github.com/go-jose/go-jose/v3/CONTRIBUTING.md index 61b18365..b63e1f8f 100644 --- a/vendor/gopkg.in/square/go-jose.v2/CONTRIBUTING.md +++ b/vendor/github.com/go-jose/go-jose/v3/CONTRIBUTING.md @@ -9,6 +9,7 @@ sure all tests pass by running `go test`, and format your code with `go fmt`. We also recommend using `golint` and `errcheck`. Before your code can be accepted into the project you must also sign the -[Individual Contributor License Agreement][1]. +Individual Contributor License Agreement. We use [cla-assistant.io][1] and you +will be prompted to sign once a pull request is opened. - [1]: https://spreadsheets.google.com/spreadsheet/viewform?formkey=dDViT2xzUHAwRkI3X3k5Z0lQM091OGc6MQ&ndplr=1 +[1]: https://cla-assistant.io/ diff --git a/vendor/gopkg.in/square/go-jose.v2/LICENSE b/vendor/github.com/go-jose/go-jose/v3/LICENSE similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/LICENSE rename to vendor/github.com/go-jose/go-jose/v3/LICENSE diff --git a/vendor/gopkg.in/square/go-jose.v2/README.md b/vendor/github.com/go-jose/go-jose/v3/README.md similarity index 63% rename from vendor/gopkg.in/square/go-jose.v2/README.md rename to vendor/github.com/go-jose/go-jose/v3/README.md index 1791bfa8..b90c7e5c 100644 --- a/vendor/gopkg.in/square/go-jose.v2/README.md +++ b/vendor/github.com/go-jose/go-jose/v3/README.md @@ -1,10 +1,10 @@ -# Go JOSE +# Go JOSE -[![godoc](http://img.shields.io/badge/godoc-version_1-blue.svg?style=flat)](https://godoc.org/gopkg.in/square/go-jose.v1) -[![godoc](http://img.shields.io/badge/godoc-version_2-blue.svg?style=flat)](https://godoc.org/gopkg.in/square/go-jose.v2) -[![license](http://img.shields.io/badge/license-apache_2.0-blue.svg?style=flat)](https://raw.githubusercontent.com/square/go-jose/master/LICENSE) -[![build](https://travis-ci.org/square/go-jose.svg?branch=v2)](https://travis-ci.org/square/go-jose) -[![coverage](https://coveralls.io/repos/github/square/go-jose/badge.svg?branch=v2)](https://coveralls.io/r/square/go-jose) +[![godoc](http://img.shields.io/badge/godoc-jose_package-blue.svg?style=flat)](https://godoc.org/gopkg.in/go-jose/go-jose.v2) +[![godoc](http://img.shields.io/badge/godoc-jwt_package-blue.svg?style=flat)](https://godoc.org/gopkg.in/go-jose/go-jose.v2/jwt) +[![license](http://img.shields.io/badge/license-apache_2.0-blue.svg?style=flat)](https://raw.githubusercontent.com/go-jose/go-jose/master/LICENSE) +[![build](https://travis-ci.org/go-jose/go-jose.svg?branch=master)](https://travis-ci.org/go-jose/go-jose) +[![coverage](https://coveralls.io/repos/github/go-jose/go-jose/badge.svg?branch=master)](https://coveralls.io/r/go-jose/go-jose) Package jose aims to provide an implementation of the Javascript Object Signing and Encryption set of standards. This includes support for JSON Web Encryption, @@ -23,11 +23,11 @@ US maintained blocked list. The implementation follows the [JSON Web Encryption](http://dx.doi.org/10.17487/RFC7516) (RFC 7516), [JSON Web Signature](http://dx.doi.org/10.17487/RFC7515) (RFC 7515), and -[JSON Web Token](http://dx.doi.org/10.17487/RFC7519) (RFC 7519). +[JSON Web Token](http://dx.doi.org/10.17487/RFC7519) (RFC 7519) specifications. Tables of supported algorithms are shown below. The library supports both -the compact and full serialization formats, and has optional support for +the compact and JWS/JWE JSON Serialization formats, and has optional support for multiple recipients. It also comes with a small command-line utility -([`jose-util`](https://github.com/square/go-jose/tree/v2/jose-util)) +([`jose-util`](https://github.com/go-jose/go-jose/tree/master/jose-util)) for dealing with JOSE messages in a shell. **Note**: We use a forked version of the `encoding/json` package from the Go @@ -38,20 +38,24 @@ libraries in other languages. ### Versions -We use [gopkg.in](https://gopkg.in) for versioning. +[Version 2](https://gopkg.in/go-jose/go-jose.v2) +([branch](https://github.com/go-jose/go-jose/tree/v2), +[doc](https://godoc.org/gopkg.in/go-jose/go-jose.v2)) is the current stable version: -[Version 2](https://gopkg.in/square/go-jose.v2) -([branch](https://github.com/square/go-jose/tree/v2), -[doc](https://godoc.org/gopkg.in/square/go-jose.v2)) is the current version: + import "gopkg.in/go-jose/go-jose.v2" - import "gopkg.in/square/go-jose.v2" +[Version 3](https://github.com/go-jose/go-jose) +([branch](https://github.com/go-jose/go-jose/tree/master), +[doc](https://godoc.org/github.com/go-jose/go-jose)) is the under development/unstable version (not released yet): -The old `v1` branch ([go-jose.v1](https://gopkg.in/square/go-jose.v1)) will -still receive backported bug fixes and security fixes, but otherwise -development is frozen. All new feature development takes place on the `v2` -branch. Version 2 also contains additional sub-packages such as the -[jwt](https://godoc.org/gopkg.in/square/go-jose.v2/jwt) implementation -contributed by [@shaxbee](https://github.com/shaxbee). + import "github.com/go-jose/go-jose/v3" + +All new feature development takes place on the `master` branch, which we are +preparing to release as version 3 soon. Version 2 will continue to receive +critical bug and security fixes. Note that starting with version 3 we are +using Go modules for versioning instead of `gopkg.in` as before. Version 3 also will require Go version 1.13 or higher. + +Version 1 (on the `v1` branch) is frozen and not supported anymore. ### Supported algorithms @@ -84,7 +88,7 @@ standard where possible. The Godoc reference has a list of constants. Content encryption | Algorithm identifier(s) :------------------------- | :------------------------------ AES-CBC+HMAC | A128CBC-HS256, A192CBC-HS384, A256CBC-HS512 - AES-GCM | A128GCM, A192GCM, A256GCM + AES-GCM | A128GCM, A192GCM, A256GCM Compression | Algorithm identifiers(s) :------------------------- | ------------------------------- @@ -101,18 +105,18 @@ allows attaching a key id. :------------------------- | ------------------------------- RSA | *[rsa.PublicKey](http://golang.org/pkg/crypto/rsa/#PublicKey), *[rsa.PrivateKey](http://golang.org/pkg/crypto/rsa/#PrivateKey) ECDH, ECDSA | *[ecdsa.PublicKey](http://golang.org/pkg/crypto/ecdsa/#PublicKey), *[ecdsa.PrivateKey](http://golang.org/pkg/crypto/ecdsa/#PrivateKey) - EdDSA1 | [ed25519.PublicKey](https://godoc.org/golang.org/x/crypto/ed25519#PublicKey), [ed25519.PrivateKey](https://godoc.org/golang.org/x/crypto/ed25519#PrivateKey) + EdDSA1 | [ed25519.PublicKey](https://godoc.org/pkg/crypto/ed25519#PublicKey), [ed25519.PrivateKey](https://godoc.org/pkg/crypto/ed25519#PrivateKey) AES, HMAC | []byte -1. Only available in version 2 of the package +1. Only available in version 2 or later of the package ## Examples -[![godoc](http://img.shields.io/badge/godoc-version_1-blue.svg?style=flat)](https://godoc.org/gopkg.in/square/go-jose.v1) -[![godoc](http://img.shields.io/badge/godoc-version_2-blue.svg?style=flat)](https://godoc.org/gopkg.in/square/go-jose.v2) +[![godoc](http://img.shields.io/badge/godoc-jose_package-blue.svg?style=flat)](https://godoc.org/gopkg.in/go-jose/go-jose.v2) +[![godoc](http://img.shields.io/badge/godoc-jwt_package-blue.svg?style=flat)](https://godoc.org/gopkg.in/go-jose/go-jose.v2/jwt) Examples can be found in the Godoc reference for this package. The -[`jose-util`](https://github.com/square/go-jose/tree/v2/jose-util) +[`jose-util`](https://github.com/go-jose/go-jose/tree/master/jose-util) subdirectory also contains a small command-line utility which might be useful -as an example. +as an example as well. diff --git a/vendor/gopkg.in/square/go-jose.v2/asymmetric.go b/vendor/github.com/go-jose/go-jose/v3/asymmetric.go similarity index 94% rename from vendor/gopkg.in/square/go-jose.v2/asymmetric.go rename to vendor/github.com/go-jose/go-jose/v3/asymmetric.go index b69aa036..78abc326 100644 --- a/vendor/gopkg.in/square/go-jose.v2/asymmetric.go +++ b/vendor/github.com/go-jose/go-jose/v3/asymmetric.go @@ -20,6 +20,7 @@ import ( "crypto" "crypto/aes" "crypto/ecdsa" + "crypto/ed25519" "crypto/rand" "crypto/rsa" "crypto/sha1" @@ -28,9 +29,8 @@ import ( "fmt" "math/big" - "golang.org/x/crypto/ed25519" - josecipher "gopkg.in/square/go-jose.v2/cipher" - "gopkg.in/square/go-jose.v2/json" + josecipher "github.com/go-jose/go-jose/v3/cipher" + "github.com/go-jose/go-jose/v3/json" ) // A generic RSA-based encrypter/verifier @@ -413,28 +413,28 @@ func (ctx ecKeyGenerator) genKey() ([]byte, rawHeader, error) { func (ctx ecDecrypterSigner) decryptKey(headers rawHeader, recipient *recipientInfo, generator keyGenerator) ([]byte, error) { epk, err := headers.getEPK() if err != nil { - return nil, errors.New("square/go-jose: invalid epk header") + return nil, errors.New("go-jose/go-jose: invalid epk header") } if epk == nil { - return nil, errors.New("square/go-jose: missing epk header") + return nil, errors.New("go-jose/go-jose: missing epk header") } publicKey, ok := epk.Key.(*ecdsa.PublicKey) if publicKey == nil || !ok { - return nil, errors.New("square/go-jose: invalid epk header") + return nil, errors.New("go-jose/go-jose: invalid epk header") } if !ctx.privateKey.Curve.IsOnCurve(publicKey.X, publicKey.Y) { - return nil, errors.New("square/go-jose: invalid public key in epk header") + return nil, errors.New("go-jose/go-jose: invalid public key in epk header") } apuData, err := headers.getAPU() if err != nil { - return nil, errors.New("square/go-jose: invalid apu header") + return nil, errors.New("go-jose/go-jose: invalid apu header") } apvData, err := headers.getAPV() if err != nil { - return nil, errors.New("square/go-jose: invalid apv header") + return nil, errors.New("go-jose/go-jose: invalid apv header") } deriveKey := func(algID string, size int) []byte { @@ -489,7 +489,7 @@ func (ctx edEncrypterVerifier) verifyPayload(payload []byte, signature []byte, a } ok := ed25519.Verify(ctx.publicKey, payload, signature) if !ok { - return errors.New("square/go-jose: ed25519 signature failed to verify") + return errors.New("go-jose/go-jose: ed25519 signature failed to verify") } return nil } @@ -513,7 +513,7 @@ func (ctx ecDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm) curveBits := ctx.privateKey.Curve.Params().BitSize if expectedBitSize != curveBits { - return Signature{}, fmt.Errorf("square/go-jose: expected %d bit key, got %d bits instead", expectedBitSize, curveBits) + return Signature{}, fmt.Errorf("go-jose/go-jose: expected %d bit key, got %d bits instead", expectedBitSize, curveBits) } hasher := hash.New() @@ -571,7 +571,7 @@ func (ctx ecEncrypterVerifier) verifyPayload(payload []byte, signature []byte, a } if len(signature) != 2*keySize { - return fmt.Errorf("square/go-jose: invalid signature size, have %d bytes, wanted %d", len(signature), 2*keySize) + return fmt.Errorf("go-jose/go-jose: invalid signature size, have %d bytes, wanted %d", len(signature), 2*keySize) } hasher := hash.New() @@ -585,7 +585,7 @@ func (ctx ecEncrypterVerifier) verifyPayload(payload []byte, signature []byte, a match := ecdsa.Verify(ctx.publicKey, hashed, r, s) if !match { - return errors.New("square/go-jose: ecdsa signature failed to verify") + return errors.New("go-jose/go-jose: ecdsa signature failed to verify") } return nil diff --git a/vendor/gopkg.in/square/go-jose.v2/cipher/cbc_hmac.go b/vendor/github.com/go-jose/go-jose/v3/cipher/cbc_hmac.go similarity index 91% rename from vendor/gopkg.in/square/go-jose.v2/cipher/cbc_hmac.go rename to vendor/github.com/go-jose/go-jose/v3/cipher/cbc_hmac.go index f6465c04..af029cec 100644 --- a/vendor/gopkg.in/square/go-jose.v2/cipher/cbc_hmac.go +++ b/vendor/github.com/go-jose/go-jose/v3/cipher/cbc_hmac.go @@ -101,23 +101,23 @@ func (ctx *cbcAEAD) Seal(dst, nonce, plaintext, data []byte) []byte { // Open decrypts and authenticates the ciphertext. func (ctx *cbcAEAD) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) { if len(ciphertext) < ctx.authtagBytes { - return nil, errors.New("square/go-jose: invalid ciphertext (too short)") + return nil, errors.New("go-jose/go-jose: invalid ciphertext (too short)") } offset := len(ciphertext) - ctx.authtagBytes expectedTag := ctx.computeAuthTag(data, nonce, ciphertext[:offset]) match := subtle.ConstantTimeCompare(expectedTag, ciphertext[offset:]) if match != 1 { - return nil, errors.New("square/go-jose: invalid ciphertext (auth tag mismatch)") + return nil, errors.New("go-jose/go-jose: invalid ciphertext (auth tag mismatch)") } cbc := cipher.NewCBCDecrypter(ctx.blockCipher, nonce) // Make copy of ciphertext buffer, don't want to modify in place - buffer := append([]byte{}, []byte(ciphertext[:offset])...) + buffer := append([]byte{}, ciphertext[:offset]...) if len(buffer)%ctx.blockCipher.BlockSize() > 0 { - return nil, errors.New("square/go-jose: invalid ciphertext (invalid length)") + return nil, errors.New("go-jose/go-jose: invalid ciphertext (invalid length)") } cbc.CryptBlocks(buffer, buffer) @@ -177,19 +177,19 @@ func padBuffer(buffer []byte, blockSize int) []byte { // Remove padding func unpadBuffer(buffer []byte, blockSize int) ([]byte, error) { if len(buffer)%blockSize != 0 { - return nil, errors.New("square/go-jose: invalid padding") + return nil, errors.New("go-jose/go-jose: invalid padding") } last := buffer[len(buffer)-1] count := int(last) if count == 0 || count > blockSize || count > len(buffer) { - return nil, errors.New("square/go-jose: invalid padding") + return nil, errors.New("go-jose/go-jose: invalid padding") } padding := bytes.Repeat([]byte{last}, count) if !bytes.HasSuffix(buffer, padding) { - return nil, errors.New("square/go-jose: invalid padding") + return nil, errors.New("go-jose/go-jose: invalid padding") } return buffer[:len(buffer)-count], nil diff --git a/vendor/gopkg.in/square/go-jose.v2/cipher/concat_kdf.go b/vendor/github.com/go-jose/go-jose/v3/cipher/concat_kdf.go similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/cipher/concat_kdf.go rename to vendor/github.com/go-jose/go-jose/v3/cipher/concat_kdf.go diff --git a/vendor/gopkg.in/square/go-jose.v2/cipher/ecdh_es.go b/vendor/github.com/go-jose/go-jose/v3/cipher/ecdh_es.go similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/cipher/ecdh_es.go rename to vendor/github.com/go-jose/go-jose/v3/cipher/ecdh_es.go diff --git a/vendor/gopkg.in/square/go-jose.v2/cipher/key_wrap.go b/vendor/github.com/go-jose/go-jose/v3/cipher/key_wrap.go similarity index 88% rename from vendor/gopkg.in/square/go-jose.v2/cipher/key_wrap.go rename to vendor/github.com/go-jose/go-jose/v3/cipher/key_wrap.go index 1d36d501..b9effbca 100644 --- a/vendor/gopkg.in/square/go-jose.v2/cipher/key_wrap.go +++ b/vendor/github.com/go-jose/go-jose/v3/cipher/key_wrap.go @@ -28,7 +28,7 @@ var defaultIV = []byte{0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6} // KeyWrap implements NIST key wrapping; it wraps a content encryption key (cek) with the given block cipher. func KeyWrap(block cipher.Block, cek []byte) ([]byte, error) { if len(cek)%8 != 0 { - return nil, errors.New("square/go-jose: key wrap input must be 8 byte blocks") + return nil, errors.New("go-jose/go-jose: key wrap input must be 8 byte blocks") } n := len(cek) / 8 @@ -51,7 +51,7 @@ func KeyWrap(block cipher.Block, cek []byte) ([]byte, error) { binary.BigEndian.PutUint64(tBytes, uint64(t+1)) for i := 0; i < 8; i++ { - buffer[i] = buffer[i] ^ tBytes[i] + buffer[i] ^= tBytes[i] } copy(r[t%n], buffer[8:]) } @@ -68,7 +68,7 @@ func KeyWrap(block cipher.Block, cek []byte) ([]byte, error) { // KeyUnwrap implements NIST key unwrapping; it unwraps a content encryption key (cek) with the given block cipher. func KeyUnwrap(block cipher.Block, ciphertext []byte) ([]byte, error) { if len(ciphertext)%8 != 0 { - return nil, errors.New("square/go-jose: key wrap input must be 8 byte blocks") + return nil, errors.New("go-jose/go-jose: key wrap input must be 8 byte blocks") } n := (len(ciphertext) / 8) - 1 @@ -87,7 +87,7 @@ func KeyUnwrap(block cipher.Block, ciphertext []byte) ([]byte, error) { binary.BigEndian.PutUint64(tBytes, uint64(t+1)) for i := 0; i < 8; i++ { - buffer[i] = buffer[i] ^ tBytes[i] + buffer[i] ^= tBytes[i] } copy(buffer[8:], r[t%n]) @@ -97,7 +97,7 @@ func KeyUnwrap(block cipher.Block, ciphertext []byte) ([]byte, error) { } if subtle.ConstantTimeCompare(buffer[:8], defaultIV) == 0 { - return nil, errors.New("square/go-jose: failed to unwrap key") + return nil, errors.New("go-jose/go-jose: failed to unwrap key") } out := make([]byte, n*8) diff --git a/vendor/gopkg.in/square/go-jose.v2/crypter.go b/vendor/github.com/go-jose/go-jose/v3/crypter.go similarity index 91% rename from vendor/gopkg.in/square/go-jose.v2/crypter.go rename to vendor/github.com/go-jose/go-jose/v3/crypter.go index be7433e2..6901137e 100644 --- a/vendor/gopkg.in/square/go-jose.v2/crypter.go +++ b/vendor/github.com/go-jose/go-jose/v3/crypter.go @@ -23,7 +23,7 @@ import ( "fmt" "reflect" - "gopkg.in/square/go-jose.v2/json" + "github.com/go-jose/go-jose/v3/json" ) // Encrypter represents an encrypter which produces an encrypted JWE object. @@ -201,8 +201,8 @@ func NewMultiEncrypter(enc ContentEncryption, rcpts []Recipient, opts *Encrypter if cipher == nil { return nil, ErrUnsupportedAlgorithm } - if rcpts == nil || len(rcpts) == 0 { - return nil, fmt.Errorf("square/go-jose: recipients is nil or empty") + if len(rcpts) == 0 { + return nil, fmt.Errorf("go-jose/go-jose: recipients is nil or empty") } encrypter := &genericEncrypter{ @@ -234,7 +234,7 @@ func (ctx *genericEncrypter) addRecipient(recipient Recipient) (err error) { switch recipient.Algorithm { case DIRECT, ECDH_ES: - return fmt.Errorf("square/go-jose: key algorithm '%s' not supported in multi-recipient mode", recipient.Algorithm) + return fmt.Errorf("go-jose/go-jose: key algorithm '%s' not supported in multi-recipient mode", recipient.Algorithm) } recipientInfo, err = makeJWERecipient(recipient.Algorithm, recipient.Key) @@ -326,7 +326,7 @@ func (ctx *genericEncrypter) EncryptWithAuthData(plaintext, aad []byte) (*JSONWe obj.recipients = make([]recipientInfo, len(ctx.recipients)) if len(ctx.recipients) == 0 { - return nil, fmt.Errorf("square/go-jose: no recipients to encrypt to") + return nil, fmt.Errorf("go-jose/go-jose: no recipients to encrypt to") } cek, headers, err := ctx.keyGenerator.genKey() @@ -410,26 +410,27 @@ func (obj JSONWebEncryption) Decrypt(decryptionKey interface{}) ([]byte, error) headers := obj.mergedHeaders(nil) if len(obj.recipients) > 1 { - return nil, errors.New("square/go-jose: too many recipients in payload; expecting only one") + return nil, errors.New("go-jose/go-jose: too many recipients in payload; expecting only one") } critical, err := headers.getCritical() if err != nil { - return nil, fmt.Errorf("square/go-jose: invalid crit header") + return nil, fmt.Errorf("go-jose/go-jose: invalid crit header") } if len(critical) > 0 { - return nil, fmt.Errorf("square/go-jose: unsupported crit header") + return nil, fmt.Errorf("go-jose/go-jose: unsupported crit header") } - decrypter, err := newDecrypter(decryptionKey) + key := tryJWKS(decryptionKey, obj.Header) + decrypter, err := newDecrypter(key) if err != nil { return nil, err } cipher := getContentCipher(headers.getEncryption()) if cipher == nil { - return nil, fmt.Errorf("square/go-jose: unsupported enc value '%s'", string(headers.getEncryption())) + return nil, fmt.Errorf("go-jose/go-jose: unsupported enc value '%s'", string(headers.getEncryption())) } generator := randomKeyGenerator{ @@ -475,14 +476,15 @@ func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Heade critical, err := globalHeaders.getCritical() if err != nil { - return -1, Header{}, nil, fmt.Errorf("square/go-jose: invalid crit header") + return -1, Header{}, nil, fmt.Errorf("go-jose/go-jose: invalid crit header") } if len(critical) > 0 { - return -1, Header{}, nil, fmt.Errorf("square/go-jose: unsupported crit header") + return -1, Header{}, nil, fmt.Errorf("go-jose/go-jose: unsupported crit header") } - decrypter, err := newDecrypter(decryptionKey) + key := tryJWKS(decryptionKey, obj.Header) + decrypter, err := newDecrypter(key) if err != nil { return -1, Header{}, nil, err } @@ -490,7 +492,7 @@ func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Heade encryption := globalHeaders.getEncryption() cipher := getContentCipher(encryption) if cipher == nil { - return -1, Header{}, nil, fmt.Errorf("square/go-jose: unsupported enc value '%s'", string(encryption)) + return -1, Header{}, nil, fmt.Errorf("go-jose/go-jose: unsupported enc value '%s'", string(encryption)) } generator := randomKeyGenerator{ @@ -524,18 +526,18 @@ func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Heade } } - if plaintext == nil || err != nil { + if plaintext == nil { return -1, Header{}, nil, ErrCryptoFailure } // The "zip" header parameter may only be present in the protected header. if comp := obj.protected.getCompression(); comp != "" { - plaintext, err = decompress(comp, plaintext) + plaintext, _ = decompress(comp, plaintext) } sanitized, err := headers.sanitized() if err != nil { - return -1, Header{}, nil, fmt.Errorf("square/go-jose: failed to sanitize header: %v", err) + return -1, Header{}, nil, fmt.Errorf("go-jose/go-jose: failed to sanitize header: %v", err) } return index, sanitized, plaintext, err diff --git a/vendor/gopkg.in/square/go-jose.v2/doc.go b/vendor/github.com/go-jose/go-jose/v3/doc.go similarity index 84% rename from vendor/gopkg.in/square/go-jose.v2/doc.go rename to vendor/github.com/go-jose/go-jose/v3/doc.go index dd1387f3..71ec1c41 100644 --- a/vendor/gopkg.in/square/go-jose.v2/doc.go +++ b/vendor/github.com/go-jose/go-jose/v3/doc.go @@ -18,9 +18,9 @@ Package jose aims to provide an implementation of the Javascript Object Signing and Encryption set of standards. It implements encryption and signing based on -the JSON Web Encryption and JSON Web Signature standards, with optional JSON -Web Token support available in a sub-package. The library supports both the -compact and full serialization formats, and has optional support for multiple +the JSON Web Encryption and JSON Web Signature standards, with optional JSON Web +Token support available in a sub-package. The library supports both the compact +and JWS/JWE JSON Serialization formats, and has optional support for multiple recipients. */ diff --git a/vendor/gopkg.in/square/go-jose.v2/encoding.go b/vendor/github.com/go-jose/go-jose/v3/encoding.go similarity index 90% rename from vendor/gopkg.in/square/go-jose.v2/encoding.go rename to vendor/github.com/go-jose/go-jose/v3/encoding.go index 70f7385c..968a4249 100644 --- a/vendor/gopkg.in/square/go-jose.v2/encoding.go +++ b/vendor/github.com/go-jose/go-jose/v3/encoding.go @@ -26,7 +26,7 @@ import ( "strings" "unicode" - "gopkg.in/square/go-jose.v2/json" + "github.com/go-jose/go-jose/v3/json" ) // Helper function to serialize known-good objects. @@ -41,7 +41,7 @@ func mustSerializeJSON(value interface{}) []byte { // MarshalJSON will happily serialize it as the top-level value "null". If // that value is then embedded in another operation, for instance by being // base64-encoded and fed as input to a signing algorithm - // (https://github.com/square/go-jose/issues/22), the result will be + // (https://github.com/go-jose/go-jose/issues/22), the result will be // incorrect. Because this method is intended for known-good objects, and a nil // pointer is not a known-good object, we are free to panic in this case. // Note: It's not possible to directly check whether the data pointed at by an @@ -127,7 +127,7 @@ func newBuffer(data []byte) *byteBuffer { func newFixedSizeBuffer(data []byte, length int) *byteBuffer { if len(data) > length { - panic("square/go-jose: invalid call to newFixedSizeBuffer (len(data) > length)") + panic("go-jose/go-jose: invalid call to newFixedSizeBuffer (len(data) > length)") } pad := make([]byte, length-len(data)) return newBuffer(append(pad, data...)) @@ -154,7 +154,7 @@ func (b *byteBuffer) UnmarshalJSON(data []byte) error { return nil } - decoded, err := base64.RawURLEncoding.DecodeString(encoded) + decoded, err := base64URLDecode(encoded) if err != nil { return err } @@ -183,3 +183,9 @@ func (b byteBuffer) bigInt() *big.Int { func (b byteBuffer) toInt() int { return int(b.bigInt().Int64()) } + +// base64URLDecode is implemented as defined in https://www.rfc-editor.org/rfc/rfc7515.html#appendix-C +func base64URLDecode(value string) ([]byte, error) { + value = strings.TrimRight(value, "=") + return base64.RawURLEncoding.DecodeString(value) +} diff --git a/vendor/gopkg.in/square/go-jose.v2/json/LICENSE b/vendor/github.com/go-jose/go-jose/v3/json/LICENSE similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/json/LICENSE rename to vendor/github.com/go-jose/go-jose/v3/json/LICENSE diff --git a/vendor/gopkg.in/square/go-jose.v2/json/README.md b/vendor/github.com/go-jose/go-jose/v3/json/README.md similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/json/README.md rename to vendor/github.com/go-jose/go-jose/v3/json/README.md diff --git a/vendor/gopkg.in/square/go-jose.v2/json/decode.go b/vendor/github.com/go-jose/go-jose/v3/json/decode.go similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/json/decode.go rename to vendor/github.com/go-jose/go-jose/v3/json/decode.go diff --git a/vendor/gopkg.in/square/go-jose.v2/json/encode.go b/vendor/github.com/go-jose/go-jose/v3/json/encode.go similarity index 99% rename from vendor/gopkg.in/square/go-jose.v2/json/encode.go rename to vendor/github.com/go-jose/go-jose/v3/json/encode.go index 1dae8bb7..ea0a1361 100644 --- a/vendor/gopkg.in/square/go-jose.v2/json/encode.go +++ b/vendor/github.com/go-jose/go-jose/v3/json/encode.go @@ -648,7 +648,7 @@ func encodeByteSlice(e *encodeState, v reflect.Value, _ bool) { // for large buffers, avoid unnecessary extra temporary // buffer space. enc := base64.NewEncoder(base64.StdEncoding, e) - enc.Write(s) + _, _ = enc.Write(s) enc.Close() } e.WriteByte('"') diff --git a/vendor/gopkg.in/square/go-jose.v2/json/indent.go b/vendor/github.com/go-jose/go-jose/v3/json/indent.go similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/json/indent.go rename to vendor/github.com/go-jose/go-jose/v3/json/indent.go diff --git a/vendor/gopkg.in/square/go-jose.v2/json/scanner.go b/vendor/github.com/go-jose/go-jose/v3/json/scanner.go similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/json/scanner.go rename to vendor/github.com/go-jose/go-jose/v3/json/scanner.go diff --git a/vendor/gopkg.in/square/go-jose.v2/json/stream.go b/vendor/github.com/go-jose/go-jose/v3/json/stream.go similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/json/stream.go rename to vendor/github.com/go-jose/go-jose/v3/json/stream.go diff --git a/vendor/gopkg.in/square/go-jose.v2/json/tags.go b/vendor/github.com/go-jose/go-jose/v3/json/tags.go similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/json/tags.go rename to vendor/github.com/go-jose/go-jose/v3/json/tags.go diff --git a/vendor/gopkg.in/square/go-jose.v2/jwe.go b/vendor/github.com/go-jose/go-jose/v3/jwe.go similarity index 88% rename from vendor/gopkg.in/square/go-jose.v2/jwe.go rename to vendor/github.com/go-jose/go-jose/v3/jwe.go index b5a6dcdf..bce30450 100644 --- a/vendor/gopkg.in/square/go-jose.v2/jwe.go +++ b/vendor/github.com/go-jose/go-jose/v3/jwe.go @@ -21,7 +21,7 @@ import ( "fmt" "strings" - "gopkg.in/square/go-jose.v2/json" + "github.com/go-jose/go-jose/v3/json" ) // rawJSONWebEncryption represents a raw JWE JSON object. Used for parsing/serializing. @@ -86,11 +86,12 @@ func (obj JSONWebEncryption) mergedHeaders(recipient *recipientInfo) rawHeader { func (obj JSONWebEncryption) computeAuthData() []byte { var protected string - if obj.original != nil && obj.original.Protected != nil { + switch { + case obj.original != nil && obj.original.Protected != nil: protected = obj.original.Protected.base64() - } else if obj.protected != nil { + case obj.protected != nil: protected = base64.RawURLEncoding.EncodeToString(mustSerializeJSON((obj.protected))) - } else { + default: protected = "" } @@ -103,7 +104,7 @@ func (obj JSONWebEncryption) computeAuthData() []byte { return output } -// ParseEncrypted parses an encrypted message in compact or full serialization format. +// ParseEncrypted parses an encrypted message in compact or JWE JSON Serialization format. func ParseEncrypted(input string) (*JSONWebEncryption, error) { input = stripWhitespace(input) if strings.HasPrefix(input, "{") { @@ -146,7 +147,7 @@ func (parsed *rawJSONWebEncryption) sanitized() (*JSONWebEncryption, error) { if parsed.Protected != nil && len(parsed.Protected.bytes()) > 0 { err := json.Unmarshal(parsed.Protected.bytes(), &obj.protected) if err != nil { - return nil, fmt.Errorf("square/go-jose: invalid protected header: %s, %s", err, parsed.Protected.base64()) + return nil, fmt.Errorf("go-jose/go-jose: invalid protected header: %s, %s", err, parsed.Protected.base64()) } } @@ -156,7 +157,7 @@ func (parsed *rawJSONWebEncryption) sanitized() (*JSONWebEncryption, error) { mergedHeaders := obj.mergedHeaders(nil) obj.Header, err = mergedHeaders.sanitized() if err != nil { - return nil, fmt.Errorf("square/go-jose: cannot sanitize merged headers: %v (%v)", err, mergedHeaders) + return nil, fmt.Errorf("go-jose/go-jose: cannot sanitize merged headers: %v (%v)", err, mergedHeaders) } if len(parsed.Recipients) == 0 { @@ -169,7 +170,7 @@ func (parsed *rawJSONWebEncryption) sanitized() (*JSONWebEncryption, error) { } else { obj.recipients = make([]recipientInfo, len(parsed.Recipients)) for r := range parsed.Recipients { - encryptedKey, err := base64.RawURLEncoding.DecodeString(parsed.Recipients[r].EncryptedKey) + encryptedKey, err := base64URLDecode(parsed.Recipients[r].EncryptedKey) if err != nil { return nil, err } @@ -187,7 +188,7 @@ func (parsed *rawJSONWebEncryption) sanitized() (*JSONWebEncryption, error) { for _, recipient := range obj.recipients { headers := obj.mergedHeaders(&recipient) if headers.getAlgorithm() == "" || headers.getEncryption() == "" { - return nil, fmt.Errorf("square/go-jose: message is missing alg/enc headers") + return nil, fmt.Errorf("go-jose/go-jose: message is missing alg/enc headers") } } @@ -203,30 +204,30 @@ func (parsed *rawJSONWebEncryption) sanitized() (*JSONWebEncryption, error) { func parseEncryptedCompact(input string) (*JSONWebEncryption, error) { parts := strings.Split(input, ".") if len(parts) != 5 { - return nil, fmt.Errorf("square/go-jose: compact JWE format must have five parts") + return nil, fmt.Errorf("go-jose/go-jose: compact JWE format must have five parts") } - rawProtected, err := base64.RawURLEncoding.DecodeString(parts[0]) + rawProtected, err := base64URLDecode(parts[0]) if err != nil { return nil, err } - encryptedKey, err := base64.RawURLEncoding.DecodeString(parts[1]) + encryptedKey, err := base64URLDecode(parts[1]) if err != nil { return nil, err } - iv, err := base64.RawURLEncoding.DecodeString(parts[2]) + iv, err := base64URLDecode(parts[2]) if err != nil { return nil, err } - ciphertext, err := base64.RawURLEncoding.DecodeString(parts[3]) + ciphertext, err := base64URLDecode(parts[3]) if err != nil { return nil, err } - tag, err := base64.RawURLEncoding.DecodeString(parts[4]) + tag, err := base64URLDecode(parts[4]) if err != nil { return nil, err } diff --git a/vendor/gopkg.in/square/go-jose.v2/jwk.go b/vendor/github.com/go-jose/go-jose/v3/jwk.go similarity index 79% rename from vendor/gopkg.in/square/go-jose.v2/jwk.go rename to vendor/github.com/go-jose/go-jose/v3/jwk.go index 222e260c..78ff5aca 100644 --- a/vendor/gopkg.in/square/go-jose.v2/jwk.go +++ b/vendor/github.com/go-jose/go-jose/v3/jwk.go @@ -20,6 +20,7 @@ import ( "bytes" "crypto" "crypto/ecdsa" + "crypto/ed25519" "crypto/elliptic" "crypto/rsa" "crypto/sha1" @@ -34,9 +35,7 @@ import ( "reflect" "strings" - "golang.org/x/crypto/ed25519" - - "gopkg.in/square/go-jose.v2/json" + "github.com/go-jose/go-jose/v3/json" ) // rawJSONWebKey represents a public or private key in JWK format, used for parsing/serializing. @@ -63,7 +62,7 @@ type rawJSONWebKey struct { Qi *byteBuffer `json:"qi,omitempty"` // Certificates X5c []string `json:"x5c,omitempty"` - X5u *url.URL `json:"x5u,omitempty"` + X5u string `json:"x5u,omitempty"` X5tSHA1 string `json:"x5t,omitempty"` X5tSHA256 string `json:"x5t#S256,omitempty"` } @@ -110,7 +109,7 @@ func (k JSONWebKey) MarshalJSON() ([]byte, error) { case []byte: raw, err = fromSymmetricKey(key) default: - return nil, fmt.Errorf("square/go-jose: unknown key type '%s'", reflect.TypeOf(key)) + return nil, fmt.Errorf("go-jose/go-jose: unknown key type '%s'", reflect.TypeOf(key)) } if err != nil { @@ -129,13 +128,13 @@ func (k JSONWebKey) MarshalJSON() ([]byte, error) { x5tSHA256Len := len(k.CertificateThumbprintSHA256) if x5tSHA1Len > 0 { if x5tSHA1Len != sha1.Size { - return nil, fmt.Errorf("square/go-jose: invalid SHA-1 thumbprint (must be %d bytes, not %d)", sha1.Size, x5tSHA1Len) + return nil, fmt.Errorf("go-jose/go-jose: invalid SHA-1 thumbprint (must be %d bytes, not %d)", sha1.Size, x5tSHA1Len) } raw.X5tSHA1 = base64.RawURLEncoding.EncodeToString(k.CertificateThumbprintSHA1) } if x5tSHA256Len > 0 { if x5tSHA256Len != sha256.Size { - return nil, fmt.Errorf("square/go-jose: invalid SHA-256 thumbprint (must be %d bytes, not %d)", sha256.Size, x5tSHA256Len) + return nil, fmt.Errorf("go-jose/go-jose: invalid SHA-256 thumbprint (must be %d bytes, not %d)", sha256.Size, x5tSHA256Len) } raw.X5tSHA256 = base64.RawURLEncoding.EncodeToString(k.CertificateThumbprintSHA256) } @@ -149,14 +148,16 @@ func (k JSONWebKey) MarshalJSON() ([]byte, error) { expectedSHA256 := sha256.Sum256(k.Certificates[0].Raw) if len(k.CertificateThumbprintSHA1) > 0 && !bytes.Equal(k.CertificateThumbprintSHA1, expectedSHA1[:]) { - return nil, errors.New("square/go-jose: invalid SHA-1 thumbprint, does not match cert chain") + return nil, errors.New("go-jose/go-jose: invalid SHA-1 thumbprint, does not match cert chain") } if len(k.CertificateThumbprintSHA256) > 0 && !bytes.Equal(k.CertificateThumbprintSHA256, expectedSHA256[:]) { - return nil, errors.New("square/go-jose: invalid or SHA-256 thumbprint, does not match cert chain") + return nil, errors.New("go-jose/go-jose: invalid or SHA-256 thumbprint, does not match cert chain") } } - raw.X5u = k.CertificatesURL + if k.CertificatesURL != nil { + raw.X5u = k.CertificatesURL.String() + } return json.Marshal(raw) } @@ -171,7 +172,7 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) { certs, err := parseCertificateChain(raw.X5c) if err != nil { - return fmt.Errorf("square/go-jose: failed to unmarshal x5c field: %s", err) + return fmt.Errorf("go-jose/go-jose: failed to unmarshal x5c field: %s", err) } var key interface{} @@ -211,7 +212,7 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) { } case "oct": if certPub != nil { - return errors.New("square/go-jose: invalid JWK, found 'oct' (symmetric) key with cert chain") + return errors.New("go-jose/go-jose: invalid JWK, found 'oct' (symmetric) key with cert chain") } key, err = raw.symmetricKey() case "OKP": @@ -226,10 +227,10 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) { keyPub = key } } else { - err = fmt.Errorf("square/go-jose: unknown curve %s'", raw.Crv) + err = fmt.Errorf("go-jose/go-jose: unknown curve %s'", raw.Crv) } default: - err = fmt.Errorf("square/go-jose: unknown json web key type '%s'", raw.Kty) + err = fmt.Errorf("go-jose/go-jose: unknown json web key type '%s'", raw.Kty) } if err != nil { @@ -238,19 +239,24 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) { if certPub != nil && keyPub != nil { if !reflect.DeepEqual(certPub, keyPub) { - return errors.New("square/go-jose: invalid JWK, public keys in key and x5c fields do not match") + return errors.New("go-jose/go-jose: invalid JWK, public keys in key and x5c fields do not match") } } *k = JSONWebKey{Key: key, KeyID: raw.Kid, Algorithm: raw.Alg, Use: raw.Use, Certificates: certs} - k.CertificatesURL = raw.X5u + if raw.X5u != "" { + k.CertificatesURL, err = url.Parse(raw.X5u) + if err != nil { + return fmt.Errorf("go-jose/go-jose: invalid JWK, x5u header is invalid URL: %w", err) + } + } // x5t parameters are base64url-encoded SHA thumbprints // See RFC 7517, Section 4.8, https://tools.ietf.org/html/rfc7517#section-4.8 - x5tSHA1bytes, err := base64.RawURLEncoding.DecodeString(raw.X5tSHA1) + x5tSHA1bytes, err := base64URLDecode(raw.X5tSHA1) if err != nil { - return errors.New("square/go-jose: invalid JWK, x5t header has invalid encoding") + return errors.New("go-jose/go-jose: invalid JWK, x5t header has invalid encoding") } // RFC 7517, Section 4.8 is ambiguous as to whether the digest output should be byte or hex, @@ -260,7 +266,7 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) { if len(x5tSHA1bytes) == 2*sha1.Size { hx, err := hex.DecodeString(string(x5tSHA1bytes)) if err != nil { - return fmt.Errorf("square/go-jose: invalid JWK, unable to hex decode x5t: %v", err) + return fmt.Errorf("go-jose/go-jose: invalid JWK, unable to hex decode x5t: %v", err) } x5tSHA1bytes = hx @@ -268,15 +274,15 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) { k.CertificateThumbprintSHA1 = x5tSHA1bytes - x5tSHA256bytes, err := base64.RawURLEncoding.DecodeString(raw.X5tSHA256) + x5tSHA256bytes, err := base64URLDecode(raw.X5tSHA256) if err != nil { - return errors.New("square/go-jose: invalid JWK, x5t#S256 header has invalid encoding") + return errors.New("go-jose/go-jose: invalid JWK, x5t#S256 header has invalid encoding") } if len(x5tSHA256bytes) == 2*sha256.Size { hx256, err := hex.DecodeString(string(x5tSHA256bytes)) if err != nil { - return fmt.Errorf("square/go-jose: invalid JWK, unable to hex decode x5t#S256: %v", err) + return fmt.Errorf("go-jose/go-jose: invalid JWK, unable to hex decode x5t#S256: %v", err) } x5tSHA256bytes = hx256 } @@ -286,10 +292,10 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) { x5tSHA1Len := len(k.CertificateThumbprintSHA1) x5tSHA256Len := len(k.CertificateThumbprintSHA256) if x5tSHA1Len > 0 && x5tSHA1Len != sha1.Size { - return errors.New("square/go-jose: invalid JWK, x5t header is of incorrect size") + return errors.New("go-jose/go-jose: invalid JWK, x5t header is of incorrect size") } if x5tSHA256Len > 0 && x5tSHA256Len != sha256.Size { - return errors.New("square/go-jose: invalid JWK, x5t#S256 header is of incorrect size") + return errors.New("go-jose/go-jose: invalid JWK, x5t#S256 header is of incorrect size") } // If certificate chain *and* thumbprints are set, verify correctness. @@ -299,11 +305,11 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) { sha256sum := sha256.Sum256(leaf.Raw) if len(k.CertificateThumbprintSHA1) > 0 && !bytes.Equal(sha1sum[:], k.CertificateThumbprintSHA1) { - return errors.New("square/go-jose: invalid JWK, x5c thumbprint does not match x5t value") + return errors.New("go-jose/go-jose: invalid JWK, x5c thumbprint does not match x5t value") } if len(k.CertificateThumbprintSHA256) > 0 && !bytes.Equal(sha256sum[:], k.CertificateThumbprintSHA256) { - return errors.New("square/go-jose: invalid JWK, x5c thumbprint does not match x5t#S256 value") + return errors.New("go-jose/go-jose: invalid JWK, x5c thumbprint does not match x5t#S256 value") } } @@ -342,7 +348,7 @@ func ecThumbprintInput(curve elliptic.Curve, x, y *big.Int) (string, error) { } if len(x.Bytes()) > coordLength || len(y.Bytes()) > coordLength { - return "", errors.New("square/go-jose: invalid elliptic key (too large)") + return "", errors.New("go-jose/go-jose: invalid elliptic key (too large)") } return fmt.Sprintf(ecThumbprintTemplate, crv, @@ -359,7 +365,7 @@ func rsaThumbprintInput(n *big.Int, e int) (string, error) { func edThumbprintInput(ed ed25519.PublicKey) (string, error) { crv := "Ed25519" if len(ed) > 32 { - return "", errors.New("square/go-jose: invalid elliptic key (too large)") + return "", errors.New("go-jose/go-jose: invalid elliptic key (too large)") } return fmt.Sprintf(edThumbprintTemplate, crv, newFixedSizeBuffer(ed, 32).base64()), nil @@ -384,7 +390,7 @@ func (k *JSONWebKey) Thumbprint(hash crypto.Hash) ([]byte, error) { case ed25519.PrivateKey: input, err = edThumbprintInput(ed25519.PublicKey(key[32:])) default: - return nil, fmt.Errorf("square/go-jose: unknown key type '%s'", reflect.TypeOf(key)) + return nil, fmt.Errorf("go-jose/go-jose: unknown key type '%s'", reflect.TypeOf(key)) } if err != nil { @@ -392,7 +398,7 @@ func (k *JSONWebKey) Thumbprint(hash crypto.Hash) ([]byte, error) { } h := hash.New() - h.Write([]byte(input)) + _, _ = h.Write([]byte(input)) return h.Sum(nil), nil } @@ -463,7 +469,7 @@ func (k *JSONWebKey) Valid() bool { func (key rawJSONWebKey) rsaPublicKey() (*rsa.PublicKey, error) { if key.N == nil || key.E == nil { - return nil, fmt.Errorf("square/go-jose: invalid RSA key, missing n/e values") + return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, missing n/e values") } return &rsa.PublicKey{ @@ -498,29 +504,29 @@ func (key rawJSONWebKey) ecPublicKey() (*ecdsa.PublicKey, error) { case "P-521": curve = elliptic.P521() default: - return nil, fmt.Errorf("square/go-jose: unsupported elliptic curve '%s'", key.Crv) + return nil, fmt.Errorf("go-jose/go-jose: unsupported elliptic curve '%s'", key.Crv) } if key.X == nil || key.Y == nil { - return nil, errors.New("square/go-jose: invalid EC key, missing x/y values") + return nil, errors.New("go-jose/go-jose: invalid EC key, missing x/y values") } // The length of this octet string MUST be the full size of a coordinate for // the curve specified in the "crv" parameter. // https://tools.ietf.org/html/rfc7518#section-6.2.1.2 if curveSize(curve) != len(key.X.data) { - return nil, fmt.Errorf("square/go-jose: invalid EC public key, wrong length for x") + return nil, fmt.Errorf("go-jose/go-jose: invalid EC public key, wrong length for x") } if curveSize(curve) != len(key.Y.data) { - return nil, fmt.Errorf("square/go-jose: invalid EC public key, wrong length for y") + return nil, fmt.Errorf("go-jose/go-jose: invalid EC public key, wrong length for y") } x := key.X.bigInt() y := key.Y.bigInt() if !curve.IsOnCurve(x, y) { - return nil, errors.New("square/go-jose: invalid EC key, X/Y are not on declared curve") + return nil, errors.New("go-jose/go-jose: invalid EC key, X/Y are not on declared curve") } return &ecdsa.PublicKey{ @@ -532,7 +538,7 @@ func (key rawJSONWebKey) ecPublicKey() (*ecdsa.PublicKey, error) { func fromEcPublicKey(pub *ecdsa.PublicKey) (*rawJSONWebKey, error) { if pub == nil || pub.X == nil || pub.Y == nil { - return nil, fmt.Errorf("square/go-jose: invalid EC key (nil, or X/Y missing)") + return nil, fmt.Errorf("go-jose/go-jose: invalid EC key (nil, or X/Y missing)") } name, err := curveName(pub.Curve) @@ -546,7 +552,7 @@ func fromEcPublicKey(pub *ecdsa.PublicKey) (*rawJSONWebKey, error) { yBytes := pub.Y.Bytes() if len(xBytes) > size || len(yBytes) > size { - return nil, fmt.Errorf("square/go-jose: invalid EC key (X/Y too large)") + return nil, fmt.Errorf("go-jose/go-jose: invalid EC key (X/Y too large)") } key := &rawJSONWebKey{ @@ -569,7 +575,7 @@ func (key rawJSONWebKey) edPrivateKey() (ed25519.PrivateKey, error) { } if len(missing) > 0 { - return nil, fmt.Errorf("square/go-jose: invalid Ed25519 private key, missing %s value(s)", strings.Join(missing, ", ")) + return nil, fmt.Errorf("go-jose/go-jose: invalid Ed25519 private key, missing %s value(s)", strings.Join(missing, ", ")) } privateKey := make([]byte, ed25519.PrivateKeySize) @@ -581,7 +587,7 @@ func (key rawJSONWebKey) edPrivateKey() (ed25519.PrivateKey, error) { func (key rawJSONWebKey) edPublicKey() (ed25519.PublicKey, error) { if key.X == nil { - return nil, fmt.Errorf("square/go-jose: invalid Ed key, missing x value") + return nil, fmt.Errorf("go-jose/go-jose: invalid Ed key, missing x value") } publicKey := make([]byte, ed25519.PublicKeySize) copy(publicKey[0:32], key.X.bytes()) @@ -605,7 +611,7 @@ func (key rawJSONWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) { } if len(missing) > 0 { - return nil, fmt.Errorf("square/go-jose: invalid RSA private key, missing %s value(s)", strings.Join(missing, ", ")) + return nil, fmt.Errorf("go-jose/go-jose: invalid RSA private key, missing %s value(s)", strings.Join(missing, ", ")) } rv := &rsa.PrivateKey{ @@ -675,34 +681,34 @@ func (key rawJSONWebKey) ecPrivateKey() (*ecdsa.PrivateKey, error) { case "P-521": curve = elliptic.P521() default: - return nil, fmt.Errorf("square/go-jose: unsupported elliptic curve '%s'", key.Crv) + return nil, fmt.Errorf("go-jose/go-jose: unsupported elliptic curve '%s'", key.Crv) } if key.X == nil || key.Y == nil || key.D == nil { - return nil, fmt.Errorf("square/go-jose: invalid EC private key, missing x/y/d values") + return nil, fmt.Errorf("go-jose/go-jose: invalid EC private key, missing x/y/d values") } // The length of this octet string MUST be the full size of a coordinate for // the curve specified in the "crv" parameter. // https://tools.ietf.org/html/rfc7518#section-6.2.1.2 if curveSize(curve) != len(key.X.data) { - return nil, fmt.Errorf("square/go-jose: invalid EC private key, wrong length for x") + return nil, fmt.Errorf("go-jose/go-jose: invalid EC private key, wrong length for x") } if curveSize(curve) != len(key.Y.data) { - return nil, fmt.Errorf("square/go-jose: invalid EC private key, wrong length for y") + return nil, fmt.Errorf("go-jose/go-jose: invalid EC private key, wrong length for y") } // https://tools.ietf.org/html/rfc7518#section-6.2.2.1 if dSize(curve) != len(key.D.data) { - return nil, fmt.Errorf("square/go-jose: invalid EC private key, wrong length for d") + return nil, fmt.Errorf("go-jose/go-jose: invalid EC private key, wrong length for d") } x := key.X.bigInt() y := key.Y.bigInt() if !curve.IsOnCurve(x, y) { - return nil, errors.New("square/go-jose: invalid EC key, X/Y are not on declared curve") + return nil, errors.New("go-jose/go-jose: invalid EC key, X/Y are not on declared curve") } return &ecdsa.PrivateKey{ @@ -722,7 +728,7 @@ func fromEcPrivateKey(ec *ecdsa.PrivateKey) (*rawJSONWebKey, error) { } if ec.D == nil { - return nil, fmt.Errorf("square/go-jose: invalid EC private key") + return nil, fmt.Errorf("go-jose/go-jose: invalid EC private key") } raw.D = newFixedSizeBuffer(ec.D.Bytes(), dSize(ec.PublicKey.Curve)) @@ -740,7 +746,7 @@ func dSize(curve elliptic.Curve) int { bitLen := order.BitLen() size := bitLen / 8 if bitLen%8 != 0 { - size = size + 1 + size++ } return size } @@ -754,7 +760,39 @@ func fromSymmetricKey(key []byte) (*rawJSONWebKey, error) { func (key rawJSONWebKey) symmetricKey() ([]byte, error) { if key.K == nil { - return nil, fmt.Errorf("square/go-jose: invalid OCT (symmetric) key, missing k value") + return nil, fmt.Errorf("go-jose/go-jose: invalid OCT (symmetric) key, missing k value") } return key.K.bytes(), nil } + +func tryJWKS(key interface{}, headers ...Header) interface{} { + var jwks JSONWebKeySet + + switch jwksType := key.(type) { + case *JSONWebKeySet: + jwks = *jwksType + case JSONWebKeySet: + jwks = jwksType + default: + return key + } + + var kid string + for _, header := range headers { + if header.KeyID != "" { + kid = header.KeyID + break + } + } + + if kid == "" { + return key + } + + keys := jwks.Key(kid) + if len(keys) == 0 { + return key + } + + return keys[0].Key +} diff --git a/vendor/gopkg.in/square/go-jose.v2/jws.go b/vendor/github.com/go-jose/go-jose/v3/jws.go similarity index 93% rename from vendor/gopkg.in/square/go-jose.v2/jws.go rename to vendor/github.com/go-jose/go-jose/v3/jws.go index 7e261f93..865f16ad 100644 --- a/vendor/gopkg.in/square/go-jose.v2/jws.go +++ b/vendor/github.com/go-jose/go-jose/v3/jws.go @@ -23,7 +23,7 @@ import ( "fmt" "strings" - "gopkg.in/square/go-jose.v2/json" + "github.com/go-jose/go-jose/v3/json" ) // rawJSONWebSignature represents a raw JWS JSON object. Used for parsing/serializing. @@ -75,7 +75,7 @@ type Signature struct { original *rawSignatureInfo } -// ParseSigned parses a signed message in compact or full serialization format. +// ParseSigned parses a signed message in compact or JWS JSON Serialization format. func ParseSigned(signature string) (*JSONWebSignature, error) { signature = stripWhitespace(signature) if strings.HasPrefix(signature, "{") { @@ -88,7 +88,7 @@ func ParseSigned(signature string) (*JSONWebSignature, error) { // ParseDetached parses a signed message in compact serialization format with detached payload. func ParseDetached(signature string, payload []byte) (*JSONWebSignature, error) { if payload == nil { - return nil, errors.New("square/go-jose: nil payload") + return nil, errors.New("go-jose/go-jose: nil payload") } return parseSignedCompact(stripWhitespace(signature), payload) } @@ -151,7 +151,7 @@ func parseSignedFull(input string) (*JSONWebSignature, error) { // sanitized produces a cleaned-up JWS object from the raw JSON. func (parsed *rawJSONWebSignature) sanitized() (*JSONWebSignature, error) { if parsed.Payload == nil { - return nil, fmt.Errorf("square/go-jose: missing payload in JWS message") + return nil, fmt.Errorf("go-jose/go-jose: missing payload in JWS message") } obj := &JSONWebSignature{ @@ -215,7 +215,7 @@ func (parsed *rawJSONWebSignature) sanitized() (*JSONWebSignature, error) { // As per RFC 7515 Section 4.1.3, only public keys are allowed to be embedded. jwk := signature.Header.JSONWebKey if jwk != nil && (!jwk.Valid() || !jwk.IsPublic()) { - return nil, errors.New("square/go-jose: invalid embedded jwk, must be public key") + return nil, errors.New("go-jose/go-jose: invalid embedded jwk, must be public key") } obj.Signatures = append(obj.Signatures, signature) @@ -260,7 +260,7 @@ func (parsed *rawJSONWebSignature) sanitized() (*JSONWebSignature, error) { // As per RFC 7515 Section 4.1.3, only public keys are allowed to be embedded. jwk := obj.Signatures[i].Header.JSONWebKey if jwk != nil && (!jwk.Valid() || !jwk.IsPublic()) { - return nil, errors.New("square/go-jose: invalid embedded jwk, must be public key") + return nil, errors.New("go-jose/go-jose: invalid embedded jwk, must be public key") } // Copy value of sig @@ -277,26 +277,26 @@ func (parsed *rawJSONWebSignature) sanitized() (*JSONWebSignature, error) { func parseSignedCompact(input string, payload []byte) (*JSONWebSignature, error) { parts := strings.Split(input, ".") if len(parts) != 3 { - return nil, fmt.Errorf("square/go-jose: compact JWS format must have three parts") + return nil, fmt.Errorf("go-jose/go-jose: compact JWS format must have three parts") } if parts[1] != "" && payload != nil { - return nil, fmt.Errorf("square/go-jose: payload is not detached") + return nil, fmt.Errorf("go-jose/go-jose: payload is not detached") } - rawProtected, err := base64.RawURLEncoding.DecodeString(parts[0]) + rawProtected, err := base64URLDecode(parts[0]) if err != nil { return nil, err } if payload == nil { - payload, err = base64.RawURLEncoding.DecodeString(parts[1]) + payload, err = base64URLDecode(parts[1]) if err != nil { return nil, err } } - signature, err := base64.RawURLEncoding.DecodeString(parts[2]) + signature, err := base64URLDecode(parts[2]) if err != nil { return nil, err } diff --git a/vendor/gopkg.in/square/go-jose.v2/opaque.go b/vendor/github.com/go-jose/go-jose/v3/opaque.go similarity index 100% rename from vendor/gopkg.in/square/go-jose.v2/opaque.go rename to vendor/github.com/go-jose/go-jose/v3/opaque.go diff --git a/vendor/gopkg.in/square/go-jose.v2/shared.go b/vendor/github.com/go-jose/go-jose/v3/shared.go similarity index 93% rename from vendor/gopkg.in/square/go-jose.v2/shared.go rename to vendor/github.com/go-jose/go-jose/v3/shared.go index f72e5a53..fc2505e0 100644 --- a/vendor/gopkg.in/square/go-jose.v2/shared.go +++ b/vendor/github.com/go-jose/go-jose/v3/shared.go @@ -23,7 +23,7 @@ import ( "errors" "fmt" - "gopkg.in/square/go-jose.v2/json" + "github.com/go-jose/go-jose/v3/json" ) // KeyAlgorithm represents a key management algorithm. @@ -45,32 +45,32 @@ var ( // ErrCryptoFailure represents an error in cryptographic primitive. This // occurs when, for example, a message had an invalid authentication tag or // could not be decrypted. - ErrCryptoFailure = errors.New("square/go-jose: error in cryptographic primitive") + ErrCryptoFailure = errors.New("go-jose/go-jose: error in cryptographic primitive") // ErrUnsupportedAlgorithm indicates that a selected algorithm is not // supported. This occurs when trying to instantiate an encrypter for an // algorithm that is not yet implemented. - ErrUnsupportedAlgorithm = errors.New("square/go-jose: unknown/unsupported algorithm") + ErrUnsupportedAlgorithm = errors.New("go-jose/go-jose: unknown/unsupported algorithm") // ErrUnsupportedKeyType indicates that the given key type/format is not // supported. This occurs when trying to instantiate an encrypter and passing // it a key of an unrecognized type or with unsupported parameters, such as // an RSA private key with more than two primes. - ErrUnsupportedKeyType = errors.New("square/go-jose: unsupported key type/format") + ErrUnsupportedKeyType = errors.New("go-jose/go-jose: unsupported key type/format") // ErrInvalidKeySize indicates that the given key is not the correct size // for the selected algorithm. This can occur, for example, when trying to // encrypt with AES-256 but passing only a 128-bit key as input. - ErrInvalidKeySize = errors.New("square/go-jose: invalid key size for algorithm") + ErrInvalidKeySize = errors.New("go-jose/go-jose: invalid key size for algorithm") // ErrNotSupported serialization of object is not supported. This occurs when // trying to compact-serialize an object which can't be represented in // compact form. - ErrNotSupported = errors.New("square/go-jose: compact serialization not supported for object") + ErrNotSupported = errors.New("go-jose/go-jose: compact serialization not supported for object") // ErrUnprotectedNonce indicates that while parsing a JWS or JWE object, a // nonce header parameter was included in an unprotected header object. - ErrUnprotectedNonce = errors.New("square/go-jose: Nonce parameter included in unprotected header") + ErrUnprotectedNonce = errors.New("go-jose/go-jose: Nonce parameter included in unprotected header") ) // Key management algorithms @@ -133,8 +133,8 @@ const ( type HeaderKey string const ( - HeaderType HeaderKey = "typ" // string - HeaderContentType = "cty" // string + HeaderType = "typ" // string + HeaderContentType = "cty" // string // These are set by go-jose and shouldn't need to be set by consumers of the // library. @@ -194,7 +194,7 @@ type Header struct { // not be validated with the given verify options. func (h Header) Certificates(opts x509.VerifyOptions) ([][]*x509.Certificate, error) { if len(h.certificates) == 0 { - return nil, errors.New("square/go-jose: no x5c header present in message") + return nil, errors.New("go-jose/go-jose: no x5c header present in message") } leaf := h.certificates[0] @@ -452,8 +452,8 @@ func parseCertificateChain(chain []string) ([]*x509.Certificate, error) { return out, nil } -func (dst rawHeader) isSet(k HeaderKey) bool { - dvr := dst[k] +func (parsed rawHeader) isSet(k HeaderKey) bool { + dvr := parsed[k] if dvr == nil { return false } @@ -472,17 +472,17 @@ func (dst rawHeader) isSet(k HeaderKey) bool { } // Merge headers from src into dst, giving precedence to headers from l. -func (dst rawHeader) merge(src *rawHeader) { +func (parsed rawHeader) merge(src *rawHeader) { if src == nil { return } for k, v := range *src { - if dst.isSet(k) { + if parsed.isSet(k) { continue } - dst[k] = v + parsed[k] = v } } @@ -496,7 +496,7 @@ func curveName(crv elliptic.Curve) (string, error) { case elliptic.P521(): return "P-521", nil default: - return "", fmt.Errorf("square/go-jose: unsupported/unknown elliptic curve") + return "", fmt.Errorf("go-jose/go-jose: unsupported/unknown elliptic curve") } } diff --git a/vendor/gopkg.in/square/go-jose.v2/signing.go b/vendor/github.com/go-jose/go-jose/v3/signing.go similarity index 93% rename from vendor/gopkg.in/square/go-jose.v2/signing.go rename to vendor/github.com/go-jose/go-jose/v3/signing.go index bad820ce..81d55f58 100644 --- a/vendor/gopkg.in/square/go-jose.v2/signing.go +++ b/vendor/github.com/go-jose/go-jose/v3/signing.go @@ -19,14 +19,13 @@ package jose import ( "bytes" "crypto/ecdsa" + "crypto/ed25519" "crypto/rsa" "encoding/base64" "errors" "fmt" - "golang.org/x/crypto/ed25519" - - "gopkg.in/square/go-jose.v2/json" + "github.com/go-jose/go-jose/v3/json" ) // NonceSource represents a source of random nonces to go into JWS objects @@ -227,7 +226,7 @@ func newJWKSigner(alg SignatureAlgorithm, signingKey JSONWebKey) (recipientSigIn // This should be impossible, but let's check anyway. if !recipient.publicKey().IsPublic() { - return recipientSigInfo{}, errors.New("square/go-jose: public key was unexpectedly not public") + return recipientSigInfo{}, errors.New("go-jose/go-jose: public key was unexpectedly not public") } } return recipient, nil @@ -251,7 +250,7 @@ func (ctx *genericSigner) Sign(payload []byte) (*JSONWebSignature, error) { // result of the JOSE spec. We've decided that this library will only include one or // the other to avoid this confusion. // - // See https://github.com/square/go-jose/issues/157 for more context. + // See https://github.com/go-jose/go-jose/issues/157 for more context. if ctx.embedJWK { protected[headerJWK] = recipient.publicKey() } else { @@ -265,7 +264,7 @@ func (ctx *genericSigner) Sign(payload []byte) (*JSONWebSignature, error) { if ctx.nonceSource != nil { nonce, err := ctx.nonceSource.Nonce() if err != nil { - return nil, fmt.Errorf("square/go-jose: Error generating nonce: %v", err) + return nil, fmt.Errorf("go-jose/go-jose: Error generating nonce: %v", err) } protected[headerNonce] = nonce } @@ -279,7 +278,7 @@ func (ctx *genericSigner) Sign(payload []byte) (*JSONWebSignature, error) { if b64, ok := protected[headerB64]; ok { if needsBase64, ok = b64.(bool); !ok { - return nil, errors.New("square/go-jose: Invalid b64 header parameter") + return nil, errors.New("go-jose/go-jose: Invalid b64 header parameter") } } @@ -303,7 +302,7 @@ func (ctx *genericSigner) Sign(payload []byte) (*JSONWebSignature, error) { for k, v := range protected { b, err := json.Marshal(v) if err != nil { - return nil, fmt.Errorf("square/go-jose: Error marshalling item %#v: %v", k, err) + return nil, fmt.Errorf("go-jose/go-jose: Error marshalling item %#v: %v", k, err) } (*signatureInfo.protected)[k] = makeRawMessage(b) } @@ -348,13 +347,14 @@ func (obj JSONWebSignature) UnsafePayloadWithoutVerification() []byte { // is only useful if you have a payload and signature that are separated from // each other. func (obj JSONWebSignature) DetachedVerify(payload []byte, verificationKey interface{}) error { - verifier, err := newVerifier(verificationKey) + key := tryJWKS(verificationKey, obj.headers()...) + verifier, err := newVerifier(key) if err != nil { return err } if len(obj.Signatures) > 1 { - return errors.New("square/go-jose: too many signatures in payload; expecting only one") + return errors.New("go-jose/go-jose: too many signatures in payload; expecting only one") } signature := obj.Signatures[0] @@ -406,7 +406,8 @@ func (obj JSONWebSignature) VerifyMulti(verificationKey interface{}) (int, Signa // separated from each other, and the signature can have multiple signers at the // same time. func (obj JSONWebSignature) DetachedVerifyMulti(payload []byte, verificationKey interface{}) (int, Signature, error) { - verifier, err := newVerifier(verificationKey) + key := tryJWKS(verificationKey, obj.headers()...) + verifier, err := newVerifier(key) if err != nil { return -1, Signature{}, err } @@ -439,3 +440,11 @@ outer: return -1, Signature{}, ErrCryptoFailure } + +func (obj JSONWebSignature) headers() []Header { + headers := make([]Header, len(obj.Signatures)) + for i, sig := range obj.Signatures { + headers[i] = sig.Header + } + return headers +} diff --git a/vendor/gopkg.in/square/go-jose.v2/symmetric.go b/vendor/github.com/go-jose/go-jose/v3/symmetric.go similarity index 89% rename from vendor/gopkg.in/square/go-jose.v2/symmetric.go rename to vendor/github.com/go-jose/go-jose/v3/symmetric.go index 264a0fe3..fb54775e 100644 --- a/vendor/gopkg.in/square/go-jose.v2/symmetric.go +++ b/vendor/github.com/go-jose/go-jose/v3/symmetric.go @@ -31,10 +31,11 @@ import ( "io" "golang.org/x/crypto/pbkdf2" - "gopkg.in/square/go-jose.v2/cipher" + + josecipher "github.com/go-jose/go-jose/v3/cipher" ) -// Random reader (stubbed out in tests) +// RandReader is a cryptographically secure random number generator (stubbed out in tests). var RandReader = rand.Reader const ( @@ -278,8 +279,14 @@ func (ctx *symmetricKeyCipher) encryptKey(cek []byte, alg KeyAlgorithm) (recipie } header := &rawHeader{} - header.set(headerIV, newBuffer(parts.iv)) - header.set(headerTag, newBuffer(parts.tag)) + + if err = header.set(headerIV, newBuffer(parts.iv)); err != nil { + return recipientInfo{}, err + } + + if err = header.set(headerTag, newBuffer(parts.tag)); err != nil { + return recipientInfo{}, err + } return recipientInfo{ header: header, @@ -332,8 +339,14 @@ func (ctx *symmetricKeyCipher) encryptKey(cek []byte, alg KeyAlgorithm) (recipie } header := &rawHeader{} - header.set(headerP2C, ctx.p2c) - header.set(headerP2S, newBuffer(ctx.p2s)) + + if err = header.set(headerP2C, ctx.p2c); err != nil { + return recipientInfo{}, err + } + + if err = header.set(headerP2S, newBuffer(ctx.p2s)); err != nil { + return recipientInfo{}, err + } return recipientInfo{ encryptedKey: jek, @@ -356,11 +369,11 @@ func (ctx *symmetricKeyCipher) decryptKey(headers rawHeader, recipient *recipien iv, err := headers.getIV() if err != nil { - return nil, fmt.Errorf("square/go-jose: invalid IV: %v", err) + return nil, fmt.Errorf("go-jose/go-jose: invalid IV: %v", err) } tag, err := headers.getTag() if err != nil { - return nil, fmt.Errorf("square/go-jose: invalid tag: %v", err) + return nil, fmt.Errorf("go-jose/go-jose: invalid tag: %v", err) } parts := &aeadParts{ @@ -389,18 +402,18 @@ func (ctx *symmetricKeyCipher) decryptKey(headers rawHeader, recipient *recipien case PBES2_HS256_A128KW, PBES2_HS384_A192KW, PBES2_HS512_A256KW: p2s, err := headers.getP2S() if err != nil { - return nil, fmt.Errorf("square/go-jose: invalid P2S: %v", err) + return nil, fmt.Errorf("go-jose/go-jose: invalid P2S: %v", err) } if p2s == nil || len(p2s.data) == 0 { - return nil, fmt.Errorf("square/go-jose: invalid P2S: must be present") + return nil, fmt.Errorf("go-jose/go-jose: invalid P2S: must be present") } p2c, err := headers.getP2C() if err != nil { - return nil, fmt.Errorf("square/go-jose: invalid P2C: %v", err) + return nil, fmt.Errorf("go-jose/go-jose: invalid P2C: %v", err) } if p2c <= 0 { - return nil, fmt.Errorf("square/go-jose: invalid P2C: must be a positive integer") + return nil, fmt.Errorf("go-jose/go-jose: invalid P2C: must be a positive integer") } // salt is UTF8(Alg) || 0x00 || Salt Input @@ -431,7 +444,7 @@ func (ctx *symmetricKeyCipher) decryptKey(headers rawHeader, recipient *recipien func (ctx symmetricMac) signPayload(payload []byte, alg SignatureAlgorithm) (Signature, error) { mac, err := ctx.hmac(payload, alg) if err != nil { - return Signature{}, errors.New("square/go-jose: failed to compute hmac") + return Signature{}, errors.New("go-jose/go-jose: failed to compute hmac") } return Signature{ @@ -444,16 +457,16 @@ func (ctx symmetricMac) signPayload(payload []byte, alg SignatureAlgorithm) (Sig func (ctx symmetricMac) verifyPayload(payload []byte, mac []byte, alg SignatureAlgorithm) error { expected, err := ctx.hmac(payload, alg) if err != nil { - return errors.New("square/go-jose: failed to compute hmac") + return errors.New("go-jose/go-jose: failed to compute hmac") } if len(mac) != len(expected) { - return errors.New("square/go-jose: invalid hmac") + return errors.New("go-jose/go-jose: invalid hmac") } match := subtle.ConstantTimeCompare(mac, expected) if match != 1 { - return errors.New("square/go-jose: invalid hmac") + return errors.New("go-jose/go-jose: invalid hmac") } return nil diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go index 39bbcf00..d569c0c9 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ b/vendor/github.com/mattn/go-isatty/isatty_bsd.go @@ -1,5 +1,5 @@ -//go:build (darwin || freebsd || openbsd || netbsd || dragonfly) && !appengine -// +build darwin freebsd openbsd netbsd dragonfly +//go:build (darwin || freebsd || openbsd || netbsd || dragonfly || hurd) && !appengine +// +build darwin freebsd openbsd netbsd dragonfly hurd // +build !appengine package isatty diff --git a/vendor/github.com/miekg/dns/README.md b/vendor/github.com/miekg/dns/README.md index ec954039..06bea9fa 100644 --- a/vendor/github.com/miekg/dns/README.md +++ b/vendor/github.com/miekg/dns/README.md @@ -78,7 +78,7 @@ A not-so-up-to-date-list-that-may-be-actually-current: * https://fleetdeck.io/ * https://github.com/markdingo/autoreverse * https://github.com/slackhq/nebula -* https://github.com/dnschecktool/dow-proxy +* https://addr.tools/ * https://dnscheck.tools/ * https://github.com/egbakou/domainverifier diff --git a/vendor/github.com/miekg/dns/client.go b/vendor/github.com/miekg/dns/client.go index f694ea58..9549fa92 100644 --- a/vendor/github.com/miekg/dns/client.go +++ b/vendor/github.com/miekg/dns/client.go @@ -6,7 +6,6 @@ import ( "context" "crypto/tls" "encoding/binary" - "fmt" "io" "net" "strings" @@ -56,14 +55,20 @@ type Client struct { // Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout, // WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and // Client.Dialer) or context.Context.Deadline (see ExchangeContext) - Timeout time.Duration - DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds, or net.Dialer.Timeout if expiring earlier - overridden by Timeout when that value is non-zero - ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero - WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero - TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2) - TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations. - SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass - group singleflight + Timeout time.Duration + DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds, or net.Dialer.Timeout if expiring earlier - overridden by Timeout when that value is non-zero + ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero + WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero + TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2) + TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations. + + // SingleInflight previously serialised multiple concurrent queries for the + // same Qname, Qtype and Qclass to ensure only one would be in flight at a + // time. + // + // Deprecated: This is a no-op. Callers should implement their own in flight + // query caching if needed. See github.com/miekg/dns/issues/1449. + SingleInflight bool } // Exchange performs a synchronous UDP query. It sends the message m to the address @@ -106,7 +111,6 @@ func (c *Client) Dial(address string) (conn *Conn, err error) { } // DialContext connects to the address on the named network, with a context.Context. -// For TLS over TCP (DoT) the context isn't used yet. This will be enabled when Go 1.18 is released. func (c *Client) DialContext(ctx context.Context, address string) (conn *Conn, err error) { // create a new dialer with the appropriate timeout var d net.Dialer @@ -127,15 +131,11 @@ func (c *Client) DialContext(ctx context.Context, address string) (conn *Conn, e if useTLS { network = strings.TrimSuffix(network, "-tls") - // TODO(miekg): Enable after Go 1.18 is released, to be able to support two prev. releases. - /* - tlsDialer := tls.Dialer{ - NetDialer: &d, - Config: c.TLSConfig, - } - conn.Conn, err = tlsDialer.DialContext(ctx, network, address) - */ - conn.Conn, err = tls.DialWithDialer(&d, network, address, c.TLSConfig) + tlsDialer := tls.Dialer{ + NetDialer: &d, + Config: c.TLSConfig, + } + conn.Conn, err = tlsDialer.DialContext(ctx, network, address) } else { conn.Conn, err = d.DialContext(ctx, network, address) } @@ -183,33 +183,13 @@ func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, er // This allows users of the library to implement their own connection management, // as opposed to Exchange, which will always use new connections and incur the added overhead // that entails when using "tcp" and especially "tcp-tls" clients. -// -// When the singleflight is set for this client the context is _not_ forwarded to the (shared) exchange, to -// prevent one cancellation from canceling all outstanding requests. func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) { - return c.exchangeWithConnContext(context.Background(), m, conn) + return c.ExchangeWithConnContext(context.Background(), m, conn) } -func (c *Client) exchangeWithConnContext(ctx context.Context, m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) { - if !c.SingleInflight { - return c.exchangeContext(ctx, m, conn) - } - - q := m.Question[0] - key := fmt.Sprintf("%s:%d:%d", q.Name, q.Qtype, q.Qclass) - r, rtt, err, shared := c.group.Do(key, func() (*Msg, time.Duration, error) { - // When we're doing singleflight we don't want one context cancellation, cancel _all_ outstanding queries. - // Hence we ignore the context and use Background(). - return c.exchangeContext(context.Background(), m, conn) - }) - if r != nil && shared { - r = r.Copy() - } - - return r, rtt, err -} - -func (c *Client) exchangeContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) { +// ExchangeWithConnContext has the same behaviour as ExchangeWithConn and +// additionally obeys deadlines from the passed Context. +func (c *Client) ExchangeWithConnContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) { opt := m.IsEdns0() // If EDNS0 is used use that for size. if opt != nil && opt.UDPSize() >= MinMsgSize { @@ -479,5 +459,5 @@ func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, } defer conn.Close() - return c.exchangeWithConnContext(ctx, m, conn) + return c.ExchangeWithConnContext(ctx, m, conn) } diff --git a/vendor/github.com/miekg/dns/clientconfig.go b/vendor/github.com/miekg/dns/clientconfig.go index e11b630d..d00ac62f 100644 --- a/vendor/github.com/miekg/dns/clientconfig.go +++ b/vendor/github.com/miekg/dns/clientconfig.go @@ -68,7 +68,7 @@ func ClientConfigFromReader(resolvconf io.Reader) (*ClientConfig, error) { } case "search": // set search path to given servers - c.Search = append([]string(nil), f[1:]...) + c.Search = cloneSlice(f[1:]) case "options": // magic options for _, s := range f[1:] { diff --git a/vendor/github.com/miekg/dns/defaults.go b/vendor/github.com/miekg/dns/defaults.go index f2cdbf43..c1558b79 100644 --- a/vendor/github.com/miekg/dns/defaults.go +++ b/vendor/github.com/miekg/dns/defaults.go @@ -208,7 +208,7 @@ func IsDomainName(s string) (labels int, ok bool) { } // check for \DDD - if i+3 < len(s) && isDigit(s[i+1]) && isDigit(s[i+2]) && isDigit(s[i+3]) { + if isDDD(s[i+1:]) { i += 3 begin += 3 } else { @@ -272,18 +272,24 @@ func IsMsg(buf []byte) error { // IsFqdn checks if a domain name is fully qualified. func IsFqdn(s string) bool { - s2 := strings.TrimSuffix(s, ".") - if s == s2 { + // Check for (and remove) a trailing dot, returning if there isn't one. + if s == "" || s[len(s)-1] != '.' { return false } + s = s[:len(s)-1] - i := strings.LastIndexFunc(s2, func(r rune) bool { + // If we don't have an escape sequence before the final dot, we know it's + // fully qualified and can return here. + if s == "" || s[len(s)-1] != '\\' { + return true + } + + // Otherwise we have to check if the dot is escaped or not by checking if + // there are an odd or even number of escape sequences before the dot. + i := strings.LastIndexFunc(s, func(r rune) bool { return r != '\\' }) - - // Test whether we have an even number of escape sequences before - // the dot or none. - return (len(s2)-i)%2 != 0 + return (len(s)-i)%2 != 0 } // IsRRset checks if a set of RRs is a valid RRset as defined by RFC 2181. diff --git a/vendor/github.com/miekg/dns/dnssec.go b/vendor/github.com/miekg/dns/dnssec.go index ea01aa81..1be87eae 100644 --- a/vendor/github.com/miekg/dns/dnssec.go +++ b/vendor/github.com/miekg/dns/dnssec.go @@ -128,10 +128,6 @@ type dnskeyWireFmt struct { /* Nothing is left out */ } -func divRoundUp(a, b int) int { - return (a + b - 1) / b -} - // KeyTag calculates the keytag (or key-id) of the DNSKEY. func (k *DNSKEY) KeyTag() uint16 { if k == nil { @@ -417,11 +413,11 @@ func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error { return err } - sigbuf := rr.sigBuf() // Get the binary signature data - if rr.Algorithm == PRIVATEDNS { // PRIVATEOID - // TODO(miek) - // remove the domain name and assume its ours? - } + sigbuf := rr.sigBuf() // Get the binary signature data + // TODO(miek) + // remove the domain name and assume its ours? + // if rr.Algorithm == PRIVATEDNS { // PRIVATEOID + // } h, cryptohash, err := hashFromAlgorithm(rr.Algorithm) if err != nil { diff --git a/vendor/github.com/miekg/dns/edns.go b/vendor/github.com/miekg/dns/edns.go index 1c0677c8..b5bdac81 100644 --- a/vendor/github.com/miekg/dns/edns.go +++ b/vendor/github.com/miekg/dns/edns.go @@ -263,7 +263,7 @@ func (e *EDNS0_NSID) copy() EDNS0 { return &EDNS0_NSID{e.Code, e.Nsid} // o.Hdr.Name = "." // o.Hdr.Rrtype = dns.TypeOPT // e := new(dns.EDNS0_SUBNET) -// e.Code = dns.EDNS0SUBNET // by default this is filled in through unpacking OPT packets (unpackDataOpt) +// e.Code = dns.EDNS0SUBNET // by default this is filled in through unpacking OPT packets (unpackDataOpt) // e.Family = 1 // 1 for IPv4 source address, 2 for IPv6 // e.SourceNetmask = 32 // 32 for IPV4, 128 for IPv6 // e.SourceScope = 0 @@ -520,8 +520,8 @@ type EDNS0_DAU struct { // Option implements the EDNS0 interface. func (e *EDNS0_DAU) Option() uint16 { return EDNS0DAU } -func (e *EDNS0_DAU) pack() ([]byte, error) { return e.AlgCode, nil } -func (e *EDNS0_DAU) unpack(b []byte) error { e.AlgCode = b; return nil } +func (e *EDNS0_DAU) pack() ([]byte, error) { return cloneSlice(e.AlgCode), nil } +func (e *EDNS0_DAU) unpack(b []byte) error { e.AlgCode = cloneSlice(b); return nil } func (e *EDNS0_DAU) String() string { s := "" @@ -544,8 +544,8 @@ type EDNS0_DHU struct { // Option implements the EDNS0 interface. func (e *EDNS0_DHU) Option() uint16 { return EDNS0DHU } -func (e *EDNS0_DHU) pack() ([]byte, error) { return e.AlgCode, nil } -func (e *EDNS0_DHU) unpack(b []byte) error { e.AlgCode = b; return nil } +func (e *EDNS0_DHU) pack() ([]byte, error) { return cloneSlice(e.AlgCode), nil } +func (e *EDNS0_DHU) unpack(b []byte) error { e.AlgCode = cloneSlice(b); return nil } func (e *EDNS0_DHU) String() string { s := "" @@ -568,8 +568,8 @@ type EDNS0_N3U struct { // Option implements the EDNS0 interface. func (e *EDNS0_N3U) Option() uint16 { return EDNS0N3U } -func (e *EDNS0_N3U) pack() ([]byte, error) { return e.AlgCode, nil } -func (e *EDNS0_N3U) unpack(b []byte) error { e.AlgCode = b; return nil } +func (e *EDNS0_N3U) pack() ([]byte, error) { return cloneSlice(e.AlgCode), nil } +func (e *EDNS0_N3U) unpack(b []byte) error { e.AlgCode = cloneSlice(b); return nil } func (e *EDNS0_N3U) String() string { // Re-use the hash map @@ -646,30 +646,21 @@ type EDNS0_LOCAL struct { // Option implements the EDNS0 interface. func (e *EDNS0_LOCAL) Option() uint16 { return e.Code } + func (e *EDNS0_LOCAL) String() string { return strconv.FormatInt(int64(e.Code), 10) + ":0x" + hex.EncodeToString(e.Data) } + func (e *EDNS0_LOCAL) copy() EDNS0 { - b := make([]byte, len(e.Data)) - copy(b, e.Data) - return &EDNS0_LOCAL{e.Code, b} + return &EDNS0_LOCAL{e.Code, cloneSlice(e.Data)} } func (e *EDNS0_LOCAL) pack() ([]byte, error) { - b := make([]byte, len(e.Data)) - copied := copy(b, e.Data) - if copied != len(e.Data) { - return nil, ErrBuf - } - return b, nil + return cloneSlice(e.Data), nil } func (e *EDNS0_LOCAL) unpack(b []byte) error { - e.Data = make([]byte, len(b)) - copied := copy(e.Data, b) - if copied != len(b) { - return ErrBuf - } + e.Data = cloneSlice(b) return nil } @@ -732,14 +723,10 @@ type EDNS0_PADDING struct { // Option implements the EDNS0 interface. func (e *EDNS0_PADDING) Option() uint16 { return EDNS0PADDING } -func (e *EDNS0_PADDING) pack() ([]byte, error) { return e.Padding, nil } -func (e *EDNS0_PADDING) unpack(b []byte) error { e.Padding = b; return nil } +func (e *EDNS0_PADDING) pack() ([]byte, error) { return cloneSlice(e.Padding), nil } +func (e *EDNS0_PADDING) unpack(b []byte) error { e.Padding = cloneSlice(b); return nil } func (e *EDNS0_PADDING) String() string { return fmt.Sprintf("%0X", e.Padding) } -func (e *EDNS0_PADDING) copy() EDNS0 { - b := make([]byte, len(e.Padding)) - copy(b, e.Padding) - return &EDNS0_PADDING{b} -} +func (e *EDNS0_PADDING) copy() EDNS0 { return &EDNS0_PADDING{cloneSlice(e.Padding)} } // Extended DNS Error Codes (RFC 8914). const ( @@ -826,7 +813,7 @@ func (e *EDNS0_EDE) String() string { func (e *EDNS0_EDE) pack() ([]byte, error) { b := make([]byte, 2+len(e.ExtraText)) binary.BigEndian.PutUint16(b[0:], e.InfoCode) - copy(b[2:], []byte(e.ExtraText)) + copy(b[2:], e.ExtraText) return b, nil } diff --git a/vendor/github.com/miekg/dns/listen_no_reuseport.go b/vendor/github.com/miekg/dns/listen_no_reuseport.go index 65ac9102..6ed50f86 100644 --- a/vendor/github.com/miekg/dns/listen_no_reuseport.go +++ b/vendor/github.com/miekg/dns/listen_no_reuseport.go @@ -1,5 +1,5 @@ -//go:build !go1.11 || (!aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd) -// +build !go1.11 !aix,!darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd +//go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd +// +build !aix,!darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd package dns diff --git a/vendor/github.com/miekg/dns/listen_reuseport.go b/vendor/github.com/miekg/dns/listen_reuseport.go index 89e6c98b..89bac903 100644 --- a/vendor/github.com/miekg/dns/listen_reuseport.go +++ b/vendor/github.com/miekg/dns/listen_reuseport.go @@ -1,5 +1,4 @@ -//go:build go1.11 && (aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd) -// +build go1.11 +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd // +build aix darwin dragonfly freebsd linux netbsd openbsd package dns diff --git a/vendor/github.com/miekg/dns/msg.go b/vendor/github.com/miekg/dns/msg.go index f4d334e4..d5049a4f 100644 --- a/vendor/github.com/miekg/dns/msg.go +++ b/vendor/github.com/miekg/dns/msg.go @@ -252,7 +252,7 @@ loop: } // check for \DDD - if i+3 < ls && isDigit(bs[i+1]) && isDigit(bs[i+2]) && isDigit(bs[i+3]) { + if isDDD(bs[i+1:]) { bs[i] = dddToByte(bs[i+1:]) copy(bs[i+1:ls-3], bs[i+4:]) ls -= 3 @@ -448,7 +448,7 @@ Loop: return string(s), off1, nil } -func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) { +func packTxt(txt []string, msg []byte, offset int) (int, error) { if len(txt) == 0 { if offset >= len(msg) { return offset, ErrBuf @@ -458,10 +458,7 @@ func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) { } var err error for _, s := range txt { - if len(s) > len(tmp) { - return offset, ErrBuf - } - offset, err = packTxtString(s, msg, offset, tmp) + offset, err = packTxtString(s, msg, offset) if err != nil { return offset, err } @@ -469,32 +466,30 @@ func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) { return offset, nil } -func packTxtString(s string, msg []byte, offset int, tmp []byte) (int, error) { +func packTxtString(s string, msg []byte, offset int) (int, error) { lenByteOffset := offset - if offset >= len(msg) || len(s) > len(tmp) { + if offset >= len(msg) || len(s) > 256*4+1 /* If all \DDD */ { return offset, ErrBuf } offset++ - bs := tmp[:len(s)] - copy(bs, s) - for i := 0; i < len(bs); i++ { + for i := 0; i < len(s); i++ { if len(msg) <= offset { return offset, ErrBuf } - if bs[i] == '\\' { + if s[i] == '\\' { i++ - if i == len(bs) { + if i == len(s) { break } // check for \DDD - if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) { - msg[offset] = dddToByte(bs[i:]) + if isDDD(s[i:]) { + msg[offset] = dddToByte(s[i:]) i += 2 } else { - msg[offset] = bs[i] + msg[offset] = s[i] } } else { - msg[offset] = bs[i] + msg[offset] = s[i] } offset++ } @@ -522,7 +517,7 @@ func packOctetString(s string, msg []byte, offset int, tmp []byte) (int, error) break } // check for \DDD - if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) { + if isDDD(bs[i:]) { msg[offset] = dddToByte(bs[i:]) i += 2 } else { @@ -551,12 +546,11 @@ func unpackTxt(msg []byte, off0 int) (ss []string, off int, err error) { // Helpers for dealing with escaped bytes func isDigit(b byte) bool { return b >= '0' && b <= '9' } -func dddToByte(s []byte) byte { - _ = s[2] // bounds check hint to compiler; see golang.org/issue/14808 - return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0')) +func isDDD[T ~[]byte | ~string](s T) bool { + return len(s) >= 3 && isDigit(s[0]) && isDigit(s[1]) && isDigit(s[2]) } -func dddStringToByte(s string) byte { +func dddToByte[T ~[]byte | ~string](s T) byte { _ = s[2] // bounds check hint to compiler; see golang.org/issue/14808 return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0')) } @@ -866,7 +860,7 @@ func (dns *Msg) unpack(dh Header, msg []byte, off int) (err error) { // The header counts might have been wrong so we need to update it dh.Nscount = uint16(len(dns.Ns)) if err == nil { - dns.Extra, off, err = unpackRRslice(int(dh.Arcount), msg, off) + dns.Extra, _, err = unpackRRslice(int(dh.Arcount), msg, off) } // The header counts might have been wrong so we need to update it dh.Arcount = uint16(len(dns.Extra)) @@ -876,11 +870,11 @@ func (dns *Msg) unpack(dh Header, msg []byte, off int) (err error) { dns.Rcode |= opt.ExtendedRcode() } - if off != len(msg) { - // TODO(miek) make this an error? - // use PackOpt to let people tell how detailed the error reporting should be? - // println("dns: extra bytes in dns packet", off, "<", len(msg)) - } + // TODO(miek) make this an error? + // use PackOpt to let people tell how detailed the error reporting should be? + // if off != len(msg) { + // // println("dns: extra bytes in dns packet", off, "<", len(msg)) + // } return err } @@ -1024,7 +1018,7 @@ func escapedNameLen(s string) int { continue } - if i+3 < len(s) && isDigit(s[i+1]) && isDigit(s[i+2]) && isDigit(s[i+3]) { + if isDDD(s[i+1:]) { nameLen -= 3 i += 3 } else { @@ -1065,8 +1059,8 @@ func (dns *Msg) CopyTo(r1 *Msg) *Msg { r1.Compress = dns.Compress if len(dns.Question) > 0 { - r1.Question = make([]Question, len(dns.Question)) - copy(r1.Question, dns.Question) // TODO(miek): Question is an immutable value, ok to do a shallow-copy + // TODO(miek): Question is an immutable value, ok to do a shallow-copy + r1.Question = cloneSlice(dns.Question) } rrArr := make([]RR, len(dns.Answer)+len(dns.Ns)+len(dns.Extra)) diff --git a/vendor/github.com/miekg/dns/msg_helpers.go b/vendor/github.com/miekg/dns/msg_helpers.go index 42d5cd53..8582fc0a 100644 --- a/vendor/github.com/miekg/dns/msg_helpers.go +++ b/vendor/github.com/miekg/dns/msg_helpers.go @@ -299,8 +299,7 @@ func unpackString(msg []byte, off int) (string, int, error) { } func packString(s string, msg []byte, off int) (int, error) { - txtTmp := make([]byte, 256*4+1) - off, err := packTxtString(s, msg, off, txtTmp) + off, err := packTxtString(s, msg, off) if err != nil { return len(msg), err } @@ -402,8 +401,7 @@ func unpackStringTxt(msg []byte, off int) ([]string, int, error) { } func packStringTxt(s []string, msg []byte, off int) (int, error) { - txtTmp := make([]byte, 256*4+1) // If the whole string consists out of \DDD we need this many. - off, err := packTxt(s, msg, off, txtTmp) + off, err := packTxt(s, msg, off) if err != nil { return len(msg), err } @@ -625,7 +623,7 @@ func unpackDataSVCB(msg []byte, off int) ([]SVCBKeyValue, int, error) { } func packDataSVCB(pairs []SVCBKeyValue, msg []byte, off int) (int, error) { - pairs = append([]SVCBKeyValue(nil), pairs...) + pairs = cloneSlice(pairs) sort.Slice(pairs, func(i, j int) bool { return pairs[i].Key() < pairs[j].Key() }) diff --git a/vendor/github.com/miekg/dns/scan.go b/vendor/github.com/miekg/dns/scan.go index 57be9882..3083c3e5 100644 --- a/vendor/github.com/miekg/dns/scan.go +++ b/vendor/github.com/miekg/dns/scan.go @@ -10,13 +10,13 @@ import ( "strings" ) -const maxTok = 2048 // Largest token we can return. +const maxTok = 512 // Token buffer start size, and growth size amount. // The maximum depth of $INCLUDE directives supported by the // ZoneParser API. const maxIncludeDepth = 7 -// Tokinize a RFC 1035 zone file. The tokenizer will normalize it: +// Tokenize a RFC 1035 zone file. The tokenizer will normalize it: // * Add ownernames if they are left blank; // * Suppress sequences of spaces; // * Make each RR fit on one line (_NEWLINE is send as last) @@ -765,8 +765,8 @@ func (zl *zlexer) Next() (lex, bool) { } var ( - str [maxTok]byte // Hold string text - com [maxTok]byte // Hold comment text + str = make([]byte, maxTok) // Hold string text + com = make([]byte, maxTok) // Hold comment text stri int // Offset in str (0 means empty) comi int // Offset in com (0 means empty) @@ -785,14 +785,12 @@ func (zl *zlexer) Next() (lex, bool) { l.line, l.column = zl.line, zl.column if stri >= len(str) { - l.token = "token length insufficient for parsing" - l.err = true - return *l, true + // if buffer length is insufficient, increase it. + str = append(str[:], make([]byte, maxTok)...) } if comi >= len(com) { - l.token = "comment length insufficient for parsing" - l.err = true - return *l, true + // if buffer length is insufficient, increase it. + com = append(com[:], make([]byte, maxTok)...) } switch x { @@ -816,7 +814,7 @@ func (zl *zlexer) Next() (lex, bool) { if stri == 0 { // Space directly in the beginning, handled in the grammar } else if zl.owner { - // If we have a string and its the first, make it an owner + // If we have a string and it's the first, make it an owner l.value = zOwner l.token = string(str[:stri]) diff --git a/vendor/github.com/miekg/dns/scan_rr.go b/vendor/github.com/miekg/dns/scan_rr.go index 68dbff69..d08c8e6a 100644 --- a/vendor/github.com/miekg/dns/scan_rr.go +++ b/vendor/github.com/miekg/dns/scan_rr.go @@ -904,11 +904,18 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { c.Next() // zBlank l, _ = c.Next() - i, e := strconv.ParseUint(l.token, 10, 8) - if e != nil || l.err { + if l.err { return &ParseError{"", "bad RRSIG Algorithm", l} } - rr.Algorithm = uint8(i) + i, e := strconv.ParseUint(l.token, 10, 8) + rr.Algorithm = uint8(i) // if 0 we'll check the mnemonic in the if + if e != nil { + v, ok := StringToAlgorithm[l.token] + if !ok { + return &ParseError{"", "bad RRSIG Algorithm", l} + } + rr.Algorithm = v + } c.Next() // zBlank l, _ = c.Next() @@ -1249,7 +1256,7 @@ func (rr *IPSECKEY) parse(c *zlexer, o string) *ParseError { rr.GatewayAddr, rr.GatewayHost, err = parseAddrHostUnion(l.token, o, rr.GatewayType) if err != nil { - return &ParseError{"", "AMTRELAY " + err.Error(), l} + return &ParseError{"", "IPSECKEY " + err.Error(), l} } c.Next() // zBlank diff --git a/vendor/github.com/miekg/dns/server.go b/vendor/github.com/miekg/dns/server.go index 508e9cb3..64e38854 100644 --- a/vendor/github.com/miekg/dns/server.go +++ b/vendor/github.com/miekg/dns/server.go @@ -224,7 +224,7 @@ type Server struct { // Maximum number of TCP queries before we close the socket. Default is maxTCPQueries (unlimited if -1). MaxTCPQueries int // Whether to set the SO_REUSEPORT socket option, allowing multiple listeners to be bound to a single address. - // It is only supported on go1.11+ and when using ListenAndServe. + // It is only supported on certain GOOSes and when using ListenAndServe. ReusePort bool // AcceptMsgFunc will check the incoming message and will reject it early in the process. // By default DefaultMsgAcceptFunc will be used. diff --git a/vendor/github.com/miekg/dns/singleinflight.go b/vendor/github.com/miekg/dns/singleinflight.go deleted file mode 100644 index febcc300..00000000 --- a/vendor/github.com/miekg/dns/singleinflight.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Adapted for dns package usage by Miek Gieben. - -package dns - -import "sync" -import "time" - -// call is an in-flight or completed singleflight.Do call -type call struct { - wg sync.WaitGroup - val *Msg - rtt time.Duration - err error - dups int -} - -// singleflight represents a class of work and forms a namespace in -// which units of work can be executed with duplicate suppression. -type singleflight struct { - sync.Mutex // protects m - m map[string]*call // lazily initialized - - dontDeleteForTesting bool // this is only to be used by TestConcurrentExchanges -} - -// Do executes and returns the results of the given function, making -// sure that only one execution is in-flight for a given key at a -// time. If a duplicate comes in, the duplicate caller waits for the -// original to complete and receives the same results. -// The return value shared indicates whether v was given to multiple callers. -func (g *singleflight) Do(key string, fn func() (*Msg, time.Duration, error)) (v *Msg, rtt time.Duration, err error, shared bool) { - g.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - g.Unlock() - c.wg.Wait() - return c.val, c.rtt, c.err, true - } - c := new(call) - c.wg.Add(1) - g.m[key] = c - g.Unlock() - - c.val, c.rtt, c.err = fn() - c.wg.Done() - - if !g.dontDeleteForTesting { - g.Lock() - delete(g.m, key) - g.Unlock() - } - - return c.val, c.rtt, c.err, c.dups > 0 -} diff --git a/vendor/github.com/miekg/dns/svcb.go b/vendor/github.com/miekg/dns/svcb.go index e1713236..6d496d74 100644 --- a/vendor/github.com/miekg/dns/svcb.go +++ b/vendor/github.com/miekg/dns/svcb.go @@ -289,7 +289,7 @@ func (s *SVCBMandatory) String() string { } func (s *SVCBMandatory) pack() ([]byte, error) { - codes := append([]SVCBKey(nil), s.Code...) + codes := cloneSlice(s.Code) sort.Slice(codes, func(i, j int) bool { return codes[i] < codes[j] }) @@ -328,9 +328,7 @@ func (s *SVCBMandatory) len() int { } func (s *SVCBMandatory) copy() SVCBKeyValue { - return &SVCBMandatory{ - append([]SVCBKey(nil), s.Code...), - } + return &SVCBMandatory{cloneSlice(s.Code)} } // SVCBAlpn pair is used to list supported connection protocols. @@ -481,9 +479,7 @@ func (s *SVCBAlpn) len() int { } func (s *SVCBAlpn) copy() SVCBKeyValue { - return &SVCBAlpn{ - append([]string(nil), s.Alpn...), - } + return &SVCBAlpn{cloneSlice(s.Alpn)} } // SVCBNoDefaultAlpn pair signifies no support for default connection protocols. @@ -595,6 +591,7 @@ func (s *SVCBIPv4Hint) unpack(b []byte) error { if len(b) == 0 || len(b)%4 != 0 { return errors.New("dns: svcbipv4hint: ipv4 address byte array length is not a multiple of 4") } + b = cloneSlice(b) x := make([]net.IP, 0, len(b)/4) for i := 0; i < len(b); i += 4 { x = append(x, net.IP(b[i:i+4])) @@ -635,12 +632,9 @@ func (s *SVCBIPv4Hint) parse(b string) error { func (s *SVCBIPv4Hint) copy() SVCBKeyValue { hint := make([]net.IP, len(s.Hint)) for i, ip := range s.Hint { - hint[i] = copyIP(ip) - } - - return &SVCBIPv4Hint{ - Hint: hint, + hint[i] = cloneSlice(ip) } + return &SVCBIPv4Hint{Hint: hint} } // SVCBECHConfig pair contains the ECHConfig structure defined in draft-ietf-tls-esni [RFC xxxx]. @@ -660,19 +654,18 @@ func (s *SVCBECHConfig) String() string { return toBase64(s.ECH) } func (s *SVCBECHConfig) len() int { return len(s.ECH) } func (s *SVCBECHConfig) pack() ([]byte, error) { - return append([]byte(nil), s.ECH...), nil + return cloneSlice(s.ECH), nil } func (s *SVCBECHConfig) copy() SVCBKeyValue { - return &SVCBECHConfig{ - append([]byte(nil), s.ECH...), - } + return &SVCBECHConfig{cloneSlice(s.ECH)} } func (s *SVCBECHConfig) unpack(b []byte) error { - s.ECH = append([]byte(nil), b...) + s.ECH = cloneSlice(b) return nil } + func (s *SVCBECHConfig) parse(b string) error { x, err := fromBase64([]byte(b)) if err != nil { @@ -715,6 +708,7 @@ func (s *SVCBIPv6Hint) unpack(b []byte) error { if len(b) == 0 || len(b)%16 != 0 { return errors.New("dns: svcbipv6hint: ipv6 address byte array length not a multiple of 16") } + b = cloneSlice(b) x := make([]net.IP, 0, len(b)/16) for i := 0; i < len(b); i += 16 { ip := net.IP(b[i : i+16]) @@ -758,12 +752,9 @@ func (s *SVCBIPv6Hint) parse(b string) error { func (s *SVCBIPv6Hint) copy() SVCBKeyValue { hint := make([]net.IP, len(s.Hint)) for i, ip := range s.Hint { - hint[i] = copyIP(ip) - } - - return &SVCBIPv6Hint{ - Hint: hint, + hint[i] = cloneSlice(ip) } + return &SVCBIPv6Hint{Hint: hint} } // SVCBDoHPath pair is used to indicate the URI template that the @@ -831,11 +822,11 @@ type SVCBLocal struct { func (s *SVCBLocal) Key() SVCBKey { return s.KeyCode } func (s *SVCBLocal) String() string { return svcbParamToStr(s.Data) } -func (s *SVCBLocal) pack() ([]byte, error) { return append([]byte(nil), s.Data...), nil } +func (s *SVCBLocal) pack() ([]byte, error) { return cloneSlice(s.Data), nil } func (s *SVCBLocal) len() int { return len(s.Data) } func (s *SVCBLocal) unpack(b []byte) error { - s.Data = append([]byte(nil), b...) + s.Data = cloneSlice(b) return nil } @@ -849,9 +840,7 @@ func (s *SVCBLocal) parse(b string) error { } func (s *SVCBLocal) copy() SVCBKeyValue { - return &SVCBLocal{s.KeyCode, - append([]byte(nil), s.Data...), - } + return &SVCBLocal{s.KeyCode, cloneSlice(s.Data)} } func (rr *SVCB) String() string { @@ -867,8 +856,8 @@ func (rr *SVCB) String() string { // areSVCBPairArraysEqual checks if SVCBKeyValue arrays are equal after sorting their // copies. arrA and arrB have equal lengths, otherwise zduplicate.go wouldn't call this function. func areSVCBPairArraysEqual(a []SVCBKeyValue, b []SVCBKeyValue) bool { - a = append([]SVCBKeyValue(nil), a...) - b = append([]SVCBKeyValue(nil), b...) + a = cloneSlice(a) + b = cloneSlice(b) sort.Slice(a, func(i, j int) bool { return a[i].Key() < a[j].Key() }) sort.Slice(b, func(i, j int) bool { return b[i].Key() < b[j].Key() }) for i, e := range a { diff --git a/vendor/github.com/miekg/dns/types.go b/vendor/github.com/miekg/dns/types.go index a34ab602..03afeccd 100644 --- a/vendor/github.com/miekg/dns/types.go +++ b/vendor/github.com/miekg/dns/types.go @@ -198,7 +198,7 @@ const ( _CD = 1 << 4 // checking disabled ) -// Various constants used in the LOC RR. See RFC 1887. +// Various constants used in the LOC RR. See RFC 1876. const ( LOC_EQUATOR = 1 << 31 // RFC 1876, Section 2. LOC_PRIMEMERIDIAN = 1 << 31 // RFC 1876, Section 2. @@ -631,8 +631,8 @@ func nextByte(s string, offset int) (byte, int) { return 0, 0 case 2, 3: // too short to be \ddd default: // maybe \ddd - if isDigit(s[offset+1]) && isDigit(s[offset+2]) && isDigit(s[offset+3]) { - return dddStringToByte(s[offset+1:]), 4 + if isDDD(s[offset+1:]) { + return dddToByte(s[offset+1:]), 4 } } // not \ddd, just an RFC 1035 "quoted" character @@ -792,7 +792,10 @@ type LOC struct { // cmToM takes a cm value expressed in RFC 1876 SIZE mantissa/exponent // format and returns a string in m (two decimals for the cm). -func cmToM(m, e uint8) string { +func cmToM(x uint8) string { + m := x & 0xf0 >> 4 + e := x & 0x0f + if e < 2 { if e == 1 { m *= 10 @@ -848,10 +851,9 @@ func (rr *LOC) String() string { s += fmt.Sprintf("%.0fm ", alt) } - s += cmToM(rr.Size&0xf0>>4, rr.Size&0x0f) + "m " - s += cmToM(rr.HorizPre&0xf0>>4, rr.HorizPre&0x0f) + "m " - s += cmToM(rr.VertPre&0xf0>>4, rr.VertPre&0x0f) + "m" - + s += cmToM(rr.Size) + "m " + s += cmToM(rr.HorizPre) + "m " + s += cmToM(rr.VertPre) + "m" return s } @@ -1531,7 +1533,7 @@ func (a *APLPrefix) str() string { // equals reports whether two APL prefixes are identical. func (a *APLPrefix) equals(b *APLPrefix) bool { return a.Negation == b.Negation && - bytes.Equal(a.Network.IP, b.Network.IP) && + a.Network.IP.Equal(b.Network.IP) && bytes.Equal(a.Network.Mask, b.Network.Mask) } @@ -1599,21 +1601,19 @@ func euiToString(eui uint64, bits int) (hex string) { return } -// copyIP returns a copy of ip. -func copyIP(ip net.IP) net.IP { - p := make(net.IP, len(ip)) - copy(p, ip) - return p +// cloneSlice returns a shallow copy of s. +func cloneSlice[E any, S ~[]E](s S) S { + if s == nil { + return nil + } + return append(S(nil), s...) } // copyNet returns a copy of a subnet. func copyNet(n net.IPNet) net.IPNet { - m := make(net.IPMask, len(n.Mask)) - copy(m, n.Mask) - return net.IPNet{ - IP: copyIP(n.IP), - Mask: m, + IP: cloneSlice(n.IP), + Mask: cloneSlice(n.Mask), } } diff --git a/vendor/github.com/miekg/dns/udp_windows.go b/vendor/github.com/miekg/dns/udp_windows.go index 8dffc4bd..a259b67e 100644 --- a/vendor/github.com/miekg/dns/udp_windows.go +++ b/vendor/github.com/miekg/dns/udp_windows.go @@ -1,6 +1,9 @@ //go:build windows // +build windows +// TODO(tmthrgd): Remove this Windows-specific code if go.dev/issue/7175 and +// go.dev/issue/7174 are ever fixed. + package dns import "net" @@ -15,7 +18,6 @@ func (s *SessionUDP) RemoteAddr() net.Addr { return s.raddr } // ReadFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a // net.UDPAddr. -// TODO(fastest963): Once go1.10 is released, use ReadMsgUDP. func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error) { n, raddr, err := conn.ReadFrom(b) if err != nil { @@ -25,12 +27,9 @@ func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error) { } // WriteToSessionUDP acts just like net.UDPConn.WriteTo(), but uses a *SessionUDP instead of a net.Addr. -// TODO(fastest963): Once go1.10 is released, use WriteMsgUDP. func WriteToSessionUDP(conn *net.UDPConn, b []byte, session *SessionUDP) (int, error) { return conn.WriteTo(b, session.raddr) } -// TODO(fastest963): Once go1.10 is released and we can use *MsgUDP methods -// use the standard method in udp.go for these. func setUDPSocketOptions(*net.UDPConn) error { return nil } func parseDstFromOOB([]byte, net.IP) net.IP { return nil } diff --git a/vendor/github.com/miekg/dns/version.go b/vendor/github.com/miekg/dns/version.go index 55602221..5891044a 100644 --- a/vendor/github.com/miekg/dns/version.go +++ b/vendor/github.com/miekg/dns/version.go @@ -3,7 +3,7 @@ package dns import "fmt" // Version is current version of this library. -var Version = v{1, 1, 51} +var Version = v{1, 1, 55} // v holds the version of this library. type v struct { diff --git a/vendor/github.com/miekg/dns/ztypes.go b/vendor/github.com/miekg/dns/ztypes.go index 17543ea4..1b6f4320 100644 --- a/vendor/github.com/miekg/dns/ztypes.go +++ b/vendor/github.com/miekg/dns/ztypes.go @@ -263,6 +263,7 @@ func (rr *A) len(off int, compression map[string]struct{}) int { } return l } + func (rr *AAAA) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) if len(rr.AAAA) != 0 { @@ -270,12 +271,14 @@ func (rr *AAAA) len(off int, compression map[string]struct{}) int { } return l } + func (rr *AFSDB) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Subtype l += domainNameLen(rr.Hostname, off+l, compression, false) return l } + func (rr *AMTRELAY) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l++ // Precedence @@ -290,10 +293,12 @@ func (rr *AMTRELAY) len(off int, compression map[string]struct{}) int { } return l } + func (rr *ANY) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) return l } + func (rr *APL) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) for _, x := range rr.Prefixes { @@ -301,6 +306,7 @@ func (rr *APL) len(off int, compression map[string]struct{}) int { } return l } + func (rr *AVC) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) for _, x := range rr.Txt { @@ -308,6 +314,7 @@ func (rr *AVC) len(off int, compression map[string]struct{}) int { } return l } + func (rr *CAA) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l++ // Flag @@ -315,6 +322,7 @@ func (rr *CAA) len(off int, compression map[string]struct{}) int { l += len(rr.Value) return l } + func (rr *CERT) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Type @@ -323,21 +331,25 @@ func (rr *CERT) len(off int, compression map[string]struct{}) int { l += base64.StdEncoding.DecodedLen(len(rr.Certificate)) return l } + func (rr *CNAME) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Target, off+l, compression, true) return l } + func (rr *DHCID) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += base64.StdEncoding.DecodedLen(len(rr.Digest)) return l } + func (rr *DNAME) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Target, off+l, compression, false) return l } + func (rr *DNSKEY) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Flags @@ -346,6 +358,7 @@ func (rr *DNSKEY) len(off int, compression map[string]struct{}) int { l += base64.StdEncoding.DecodedLen(len(rr.PublicKey)) return l } + func (rr *DS) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // KeyTag @@ -354,26 +367,31 @@ func (rr *DS) len(off int, compression map[string]struct{}) int { l += len(rr.Digest) / 2 return l } + func (rr *EID) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += len(rr.Endpoint) / 2 return l } + func (rr *EUI48) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 6 // Address return l } + func (rr *EUI64) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 8 // Address return l } + func (rr *GID) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 4 // Gid return l } + func (rr *GPOS) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += len(rr.Longitude) + 1 @@ -381,12 +399,14 @@ func (rr *GPOS) len(off int, compression map[string]struct{}) int { l += len(rr.Altitude) + 1 return l } + func (rr *HINFO) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += len(rr.Cpu) + 1 l += len(rr.Os) + 1 return l } + func (rr *HIP) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l++ // HitLength @@ -399,6 +419,7 @@ func (rr *HIP) len(off int, compression map[string]struct{}) int { } return l } + func (rr *IPSECKEY) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l++ // Precedence @@ -415,12 +436,14 @@ func (rr *IPSECKEY) len(off int, compression map[string]struct{}) int { l += base64.StdEncoding.DecodedLen(len(rr.PublicKey)) return l } + func (rr *KX) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Preference l += domainNameLen(rr.Exchanger, off+l, compression, false) return l } + func (rr *L32) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Preference @@ -429,12 +452,14 @@ func (rr *L32) len(off int, compression map[string]struct{}) int { } return l } + func (rr *L64) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Preference l += 8 // Locator64 return l } + func (rr *LOC) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l++ // Version @@ -446,49 +471,58 @@ func (rr *LOC) len(off int, compression map[string]struct{}) int { l += 4 // Altitude return l } + func (rr *LP) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Preference l += domainNameLen(rr.Fqdn, off+l, compression, false) return l } + func (rr *MB) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Mb, off+l, compression, true) return l } + func (rr *MD) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Md, off+l, compression, true) return l } + func (rr *MF) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Mf, off+l, compression, true) return l } + func (rr *MG) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Mg, off+l, compression, true) return l } + func (rr *MINFO) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Rmail, off+l, compression, true) l += domainNameLen(rr.Email, off+l, compression, true) return l } + func (rr *MR) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Mr, off+l, compression, true) return l } + func (rr *MX) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Preference l += domainNameLen(rr.Mx, off+l, compression, true) return l } + func (rr *NAPTR) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Order @@ -499,17 +533,20 @@ func (rr *NAPTR) len(off int, compression map[string]struct{}) int { l += domainNameLen(rr.Replacement, off+l, compression, false) return l } + func (rr *NID) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Preference l += 8 // NodeID return l } + func (rr *NIMLOC) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += len(rr.Locator) / 2 return l } + func (rr *NINFO) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) for _, x := range rr.ZSData { @@ -517,16 +554,19 @@ func (rr *NINFO) len(off int, compression map[string]struct{}) int { } return l } + func (rr *NS) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Ns, off+l, compression, true) return l } + func (rr *NSAPPTR) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Ptr, off+l, compression, false) return l } + func (rr *NSEC3PARAM) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l++ // Hash @@ -536,21 +576,25 @@ func (rr *NSEC3PARAM) len(off int, compression map[string]struct{}) int { l += len(rr.Salt) / 2 return l } + func (rr *NULL) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += len(rr.Data) return l } + func (rr *OPENPGPKEY) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += base64.StdEncoding.DecodedLen(len(rr.PublicKey)) return l } + func (rr *PTR) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Ptr, off+l, compression, true) return l } + func (rr *PX) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Preference @@ -558,11 +602,13 @@ func (rr *PX) len(off int, compression map[string]struct{}) int { l += domainNameLen(rr.Mapx400, off+l, compression, false) return l } + func (rr *RFC3597) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += len(rr.Rdata) / 2 return l } + func (rr *RKEY) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Flags @@ -571,12 +617,14 @@ func (rr *RKEY) len(off int, compression map[string]struct{}) int { l += base64.StdEncoding.DecodedLen(len(rr.PublicKey)) return l } + func (rr *RP) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Mbox, off+l, compression, false) l += domainNameLen(rr.Txt, off+l, compression, false) return l } + func (rr *RRSIG) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // TypeCovered @@ -590,12 +638,14 @@ func (rr *RRSIG) len(off int, compression map[string]struct{}) int { l += base64.StdEncoding.DecodedLen(len(rr.Signature)) return l } + func (rr *RT) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Preference l += domainNameLen(rr.Host, off+l, compression, false) return l } + func (rr *SMIMEA) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l++ // Usage @@ -604,6 +654,7 @@ func (rr *SMIMEA) len(off int, compression map[string]struct{}) int { l += len(rr.Certificate) / 2 return l } + func (rr *SOA) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Ns, off+l, compression, true) @@ -615,6 +666,7 @@ func (rr *SOA) len(off int, compression map[string]struct{}) int { l += 4 // Minttl return l } + func (rr *SPF) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) for _, x := range rr.Txt { @@ -622,6 +674,7 @@ func (rr *SPF) len(off int, compression map[string]struct{}) int { } return l } + func (rr *SRV) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Priority @@ -630,6 +683,7 @@ func (rr *SRV) len(off int, compression map[string]struct{}) int { l += domainNameLen(rr.Target, off+l, compression, false) return l } + func (rr *SSHFP) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l++ // Algorithm @@ -637,6 +691,7 @@ func (rr *SSHFP) len(off int, compression map[string]struct{}) int { l += len(rr.FingerPrint) / 2 return l } + func (rr *SVCB) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Priority @@ -646,6 +701,7 @@ func (rr *SVCB) len(off int, compression map[string]struct{}) int { } return l } + func (rr *TA) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // KeyTag @@ -654,12 +710,14 @@ func (rr *TA) len(off int, compression map[string]struct{}) int { l += len(rr.Digest) / 2 return l } + func (rr *TALINK) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.PreviousName, off+l, compression, false) l += domainNameLen(rr.NextName, off+l, compression, false) return l } + func (rr *TKEY) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Algorithm, off+l, compression, false) @@ -673,6 +731,7 @@ func (rr *TKEY) len(off int, compression map[string]struct{}) int { l += len(rr.OtherData) / 2 return l } + func (rr *TLSA) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l++ // Usage @@ -681,6 +740,7 @@ func (rr *TLSA) len(off int, compression map[string]struct{}) int { l += len(rr.Certificate) / 2 return l } + func (rr *TSIG) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += domainNameLen(rr.Algorithm, off+l, compression, false) @@ -694,6 +754,7 @@ func (rr *TSIG) len(off int, compression map[string]struct{}) int { l += len(rr.OtherData) / 2 return l } + func (rr *TXT) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) for _, x := range rr.Txt { @@ -701,16 +762,19 @@ func (rr *TXT) len(off int, compression map[string]struct{}) int { } return l } + func (rr *UID) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 4 // Uid return l } + func (rr *UINFO) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += len(rr.Uinfo) + 1 return l } + func (rr *URI) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Priority @@ -718,11 +782,13 @@ func (rr *URI) len(off int, compression map[string]struct{}) int { l += len(rr.Target) return l } + func (rr *X25) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += len(rr.PSDNAddress) + 1 return l } + func (rr *ZONEMD) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 4 // Serial @@ -734,20 +800,31 @@ func (rr *ZONEMD) len(off int, compression map[string]struct{}) int { // copy() functions func (rr *A) copy() RR { - return &A{rr.Hdr, copyIP(rr.A)} + return &A{rr.Hdr, cloneSlice(rr.A)} } + func (rr *AAAA) copy() RR { - return &AAAA{rr.Hdr, copyIP(rr.AAAA)} + return &AAAA{rr.Hdr, cloneSlice(rr.AAAA)} } + func (rr *AFSDB) copy() RR { return &AFSDB{rr.Hdr, rr.Subtype, rr.Hostname} } + func (rr *AMTRELAY) copy() RR { - return &AMTRELAY{rr.Hdr, rr.Precedence, rr.GatewayType, copyIP(rr.GatewayAddr), rr.GatewayHost} + return &AMTRELAY{ + rr.Hdr, + rr.Precedence, + rr.GatewayType, + cloneSlice(rr.GatewayAddr), + rr.GatewayHost, + } } + func (rr *ANY) copy() RR { return &ANY{rr.Hdr} } + func (rr *APL) copy() RR { Prefixes := make([]APLPrefix, len(rr.Prefixes)) for i, e := range rr.Prefixes { @@ -755,153 +832,270 @@ func (rr *APL) copy() RR { } return &APL{rr.Hdr, Prefixes} } + func (rr *AVC) copy() RR { - Txt := make([]string, len(rr.Txt)) - copy(Txt, rr.Txt) - return &AVC{rr.Hdr, Txt} + return &AVC{rr.Hdr, cloneSlice(rr.Txt)} } + func (rr *CAA) copy() RR { - return &CAA{rr.Hdr, rr.Flag, rr.Tag, rr.Value} + return &CAA{ + rr.Hdr, + rr.Flag, + rr.Tag, + rr.Value, + } } + func (rr *CDNSKEY) copy() RR { return &CDNSKEY{*rr.DNSKEY.copy().(*DNSKEY)} } + func (rr *CDS) copy() RR { return &CDS{*rr.DS.copy().(*DS)} } + func (rr *CERT) copy() RR { - return &CERT{rr.Hdr, rr.Type, rr.KeyTag, rr.Algorithm, rr.Certificate} + return &CERT{ + rr.Hdr, + rr.Type, + rr.KeyTag, + rr.Algorithm, + rr.Certificate, + } } + func (rr *CNAME) copy() RR { return &CNAME{rr.Hdr, rr.Target} } + func (rr *CSYNC) copy() RR { - TypeBitMap := make([]uint16, len(rr.TypeBitMap)) - copy(TypeBitMap, rr.TypeBitMap) - return &CSYNC{rr.Hdr, rr.Serial, rr.Flags, TypeBitMap} + return &CSYNC{ + rr.Hdr, + rr.Serial, + rr.Flags, + cloneSlice(rr.TypeBitMap), + } } + func (rr *DHCID) copy() RR { return &DHCID{rr.Hdr, rr.Digest} } + func (rr *DLV) copy() RR { return &DLV{*rr.DS.copy().(*DS)} } + func (rr *DNAME) copy() RR { return &DNAME{rr.Hdr, rr.Target} } + func (rr *DNSKEY) copy() RR { - return &DNSKEY{rr.Hdr, rr.Flags, rr.Protocol, rr.Algorithm, rr.PublicKey} + return &DNSKEY{ + rr.Hdr, + rr.Flags, + rr.Protocol, + rr.Algorithm, + rr.PublicKey, + } } + func (rr *DS) copy() RR { - return &DS{rr.Hdr, rr.KeyTag, rr.Algorithm, rr.DigestType, rr.Digest} + return &DS{ + rr.Hdr, + rr.KeyTag, + rr.Algorithm, + rr.DigestType, + rr.Digest, + } } + func (rr *EID) copy() RR { return &EID{rr.Hdr, rr.Endpoint} } + func (rr *EUI48) copy() RR { return &EUI48{rr.Hdr, rr.Address} } + func (rr *EUI64) copy() RR { return &EUI64{rr.Hdr, rr.Address} } + func (rr *GID) copy() RR { return &GID{rr.Hdr, rr.Gid} } + func (rr *GPOS) copy() RR { - return &GPOS{rr.Hdr, rr.Longitude, rr.Latitude, rr.Altitude} + return &GPOS{ + rr.Hdr, + rr.Longitude, + rr.Latitude, + rr.Altitude, + } } + func (rr *HINFO) copy() RR { return &HINFO{rr.Hdr, rr.Cpu, rr.Os} } + func (rr *HIP) copy() RR { - RendezvousServers := make([]string, len(rr.RendezvousServers)) - copy(RendezvousServers, rr.RendezvousServers) - return &HIP{rr.Hdr, rr.HitLength, rr.PublicKeyAlgorithm, rr.PublicKeyLength, rr.Hit, rr.PublicKey, RendezvousServers} + return &HIP{ + rr.Hdr, + rr.HitLength, + rr.PublicKeyAlgorithm, + rr.PublicKeyLength, + rr.Hit, + rr.PublicKey, + cloneSlice(rr.RendezvousServers), + } } + func (rr *HTTPS) copy() RR { return &HTTPS{*rr.SVCB.copy().(*SVCB)} } + func (rr *IPSECKEY) copy() RR { - return &IPSECKEY{rr.Hdr, rr.Precedence, rr.GatewayType, rr.Algorithm, copyIP(rr.GatewayAddr), rr.GatewayHost, rr.PublicKey} + return &IPSECKEY{ + rr.Hdr, + rr.Precedence, + rr.GatewayType, + rr.Algorithm, + cloneSlice(rr.GatewayAddr), + rr.GatewayHost, + rr.PublicKey, + } } + func (rr *KEY) copy() RR { return &KEY{*rr.DNSKEY.copy().(*DNSKEY)} } + func (rr *KX) copy() RR { return &KX{rr.Hdr, rr.Preference, rr.Exchanger} } + func (rr *L32) copy() RR { - return &L32{rr.Hdr, rr.Preference, copyIP(rr.Locator32)} + return &L32{rr.Hdr, rr.Preference, cloneSlice(rr.Locator32)} } + func (rr *L64) copy() RR { return &L64{rr.Hdr, rr.Preference, rr.Locator64} } + func (rr *LOC) copy() RR { - return &LOC{rr.Hdr, rr.Version, rr.Size, rr.HorizPre, rr.VertPre, rr.Latitude, rr.Longitude, rr.Altitude} + return &LOC{ + rr.Hdr, + rr.Version, + rr.Size, + rr.HorizPre, + rr.VertPre, + rr.Latitude, + rr.Longitude, + rr.Altitude, + } } + func (rr *LP) copy() RR { return &LP{rr.Hdr, rr.Preference, rr.Fqdn} } + func (rr *MB) copy() RR { return &MB{rr.Hdr, rr.Mb} } + func (rr *MD) copy() RR { return &MD{rr.Hdr, rr.Md} } + func (rr *MF) copy() RR { return &MF{rr.Hdr, rr.Mf} } + func (rr *MG) copy() RR { return &MG{rr.Hdr, rr.Mg} } + func (rr *MINFO) copy() RR { return &MINFO{rr.Hdr, rr.Rmail, rr.Email} } + func (rr *MR) copy() RR { return &MR{rr.Hdr, rr.Mr} } + func (rr *MX) copy() RR { return &MX{rr.Hdr, rr.Preference, rr.Mx} } + func (rr *NAPTR) copy() RR { - return &NAPTR{rr.Hdr, rr.Order, rr.Preference, rr.Flags, rr.Service, rr.Regexp, rr.Replacement} + return &NAPTR{ + rr.Hdr, + rr.Order, + rr.Preference, + rr.Flags, + rr.Service, + rr.Regexp, + rr.Replacement, + } } + func (rr *NID) copy() RR { return &NID{rr.Hdr, rr.Preference, rr.NodeID} } + func (rr *NIMLOC) copy() RR { return &NIMLOC{rr.Hdr, rr.Locator} } + func (rr *NINFO) copy() RR { - ZSData := make([]string, len(rr.ZSData)) - copy(ZSData, rr.ZSData) - return &NINFO{rr.Hdr, ZSData} + return &NINFO{rr.Hdr, cloneSlice(rr.ZSData)} } + func (rr *NS) copy() RR { return &NS{rr.Hdr, rr.Ns} } + func (rr *NSAPPTR) copy() RR { return &NSAPPTR{rr.Hdr, rr.Ptr} } + func (rr *NSEC) copy() RR { - TypeBitMap := make([]uint16, len(rr.TypeBitMap)) - copy(TypeBitMap, rr.TypeBitMap) - return &NSEC{rr.Hdr, rr.NextDomain, TypeBitMap} + return &NSEC{rr.Hdr, rr.NextDomain, cloneSlice(rr.TypeBitMap)} } + func (rr *NSEC3) copy() RR { - TypeBitMap := make([]uint16, len(rr.TypeBitMap)) - copy(TypeBitMap, rr.TypeBitMap) - return &NSEC3{rr.Hdr, rr.Hash, rr.Flags, rr.Iterations, rr.SaltLength, rr.Salt, rr.HashLength, rr.NextDomain, TypeBitMap} + return &NSEC3{ + rr.Hdr, + rr.Hash, + rr.Flags, + rr.Iterations, + rr.SaltLength, + rr.Salt, + rr.HashLength, + rr.NextDomain, + cloneSlice(rr.TypeBitMap), + } } + func (rr *NSEC3PARAM) copy() RR { - return &NSEC3PARAM{rr.Hdr, rr.Hash, rr.Flags, rr.Iterations, rr.SaltLength, rr.Salt} + return &NSEC3PARAM{ + rr.Hdr, + rr.Hash, + rr.Flags, + rr.Iterations, + rr.SaltLength, + rr.Salt, + } } + func (rr *NULL) copy() RR { return &NULL{rr.Hdr, rr.Data} } + func (rr *OPENPGPKEY) copy() RR { return &OPENPGPKEY{rr.Hdr, rr.PublicKey} } + func (rr *OPT) copy() RR { Option := make([]EDNS0, len(rr.Option)) for i, e := range rr.Option { @@ -909,86 +1103,205 @@ func (rr *OPT) copy() RR { } return &OPT{rr.Hdr, Option} } + func (rr *PTR) copy() RR { return &PTR{rr.Hdr, rr.Ptr} } + func (rr *PX) copy() RR { - return &PX{rr.Hdr, rr.Preference, rr.Map822, rr.Mapx400} + return &PX{ + rr.Hdr, + rr.Preference, + rr.Map822, + rr.Mapx400, + } } + func (rr *RFC3597) copy() RR { return &RFC3597{rr.Hdr, rr.Rdata} } + func (rr *RKEY) copy() RR { - return &RKEY{rr.Hdr, rr.Flags, rr.Protocol, rr.Algorithm, rr.PublicKey} + return &RKEY{ + rr.Hdr, + rr.Flags, + rr.Protocol, + rr.Algorithm, + rr.PublicKey, + } } + func (rr *RP) copy() RR { return &RP{rr.Hdr, rr.Mbox, rr.Txt} } + func (rr *RRSIG) copy() RR { - return &RRSIG{rr.Hdr, rr.TypeCovered, rr.Algorithm, rr.Labels, rr.OrigTtl, rr.Expiration, rr.Inception, rr.KeyTag, rr.SignerName, rr.Signature} + return &RRSIG{ + rr.Hdr, + rr.TypeCovered, + rr.Algorithm, + rr.Labels, + rr.OrigTtl, + rr.Expiration, + rr.Inception, + rr.KeyTag, + rr.SignerName, + rr.Signature, + } } + func (rr *RT) copy() RR { return &RT{rr.Hdr, rr.Preference, rr.Host} } + func (rr *SIG) copy() RR { return &SIG{*rr.RRSIG.copy().(*RRSIG)} } + func (rr *SMIMEA) copy() RR { - return &SMIMEA{rr.Hdr, rr.Usage, rr.Selector, rr.MatchingType, rr.Certificate} + return &SMIMEA{ + rr.Hdr, + rr.Usage, + rr.Selector, + rr.MatchingType, + rr.Certificate, + } } + func (rr *SOA) copy() RR { - return &SOA{rr.Hdr, rr.Ns, rr.Mbox, rr.Serial, rr.Refresh, rr.Retry, rr.Expire, rr.Minttl} + return &SOA{ + rr.Hdr, + rr.Ns, + rr.Mbox, + rr.Serial, + rr.Refresh, + rr.Retry, + rr.Expire, + rr.Minttl, + } } + func (rr *SPF) copy() RR { - Txt := make([]string, len(rr.Txt)) - copy(Txt, rr.Txt) - return &SPF{rr.Hdr, Txt} + return &SPF{rr.Hdr, cloneSlice(rr.Txt)} } + func (rr *SRV) copy() RR { - return &SRV{rr.Hdr, rr.Priority, rr.Weight, rr.Port, rr.Target} + return &SRV{ + rr.Hdr, + rr.Priority, + rr.Weight, + rr.Port, + rr.Target, + } } + func (rr *SSHFP) copy() RR { - return &SSHFP{rr.Hdr, rr.Algorithm, rr.Type, rr.FingerPrint} + return &SSHFP{ + rr.Hdr, + rr.Algorithm, + rr.Type, + rr.FingerPrint, + } } + func (rr *SVCB) copy() RR { Value := make([]SVCBKeyValue, len(rr.Value)) for i, e := range rr.Value { Value[i] = e.copy() } - return &SVCB{rr.Hdr, rr.Priority, rr.Target, Value} + return &SVCB{ + rr.Hdr, + rr.Priority, + rr.Target, + Value, + } } + func (rr *TA) copy() RR { - return &TA{rr.Hdr, rr.KeyTag, rr.Algorithm, rr.DigestType, rr.Digest} + return &TA{ + rr.Hdr, + rr.KeyTag, + rr.Algorithm, + rr.DigestType, + rr.Digest, + } } + func (rr *TALINK) copy() RR { return &TALINK{rr.Hdr, rr.PreviousName, rr.NextName} } + func (rr *TKEY) copy() RR { - return &TKEY{rr.Hdr, rr.Algorithm, rr.Inception, rr.Expiration, rr.Mode, rr.Error, rr.KeySize, rr.Key, rr.OtherLen, rr.OtherData} + return &TKEY{ + rr.Hdr, + rr.Algorithm, + rr.Inception, + rr.Expiration, + rr.Mode, + rr.Error, + rr.KeySize, + rr.Key, + rr.OtherLen, + rr.OtherData, + } } + func (rr *TLSA) copy() RR { - return &TLSA{rr.Hdr, rr.Usage, rr.Selector, rr.MatchingType, rr.Certificate} + return &TLSA{ + rr.Hdr, + rr.Usage, + rr.Selector, + rr.MatchingType, + rr.Certificate, + } } + func (rr *TSIG) copy() RR { - return &TSIG{rr.Hdr, rr.Algorithm, rr.TimeSigned, rr.Fudge, rr.MACSize, rr.MAC, rr.OrigId, rr.Error, rr.OtherLen, rr.OtherData} + return &TSIG{ + rr.Hdr, + rr.Algorithm, + rr.TimeSigned, + rr.Fudge, + rr.MACSize, + rr.MAC, + rr.OrigId, + rr.Error, + rr.OtherLen, + rr.OtherData, + } } + func (rr *TXT) copy() RR { - Txt := make([]string, len(rr.Txt)) - copy(Txt, rr.Txt) - return &TXT{rr.Hdr, Txt} + return &TXT{rr.Hdr, cloneSlice(rr.Txt)} } + func (rr *UID) copy() RR { return &UID{rr.Hdr, rr.Uid} } + func (rr *UINFO) copy() RR { return &UINFO{rr.Hdr, rr.Uinfo} } + func (rr *URI) copy() RR { - return &URI{rr.Hdr, rr.Priority, rr.Weight, rr.Target} + return &URI{ + rr.Hdr, + rr.Priority, + rr.Weight, + rr.Target, + } } + func (rr *X25) copy() RR { return &X25{rr.Hdr, rr.PSDNAddress} } + func (rr *ZONEMD) copy() RR { - return &ZONEMD{rr.Hdr, rr.Serial, rr.Scheme, rr.Hash, rr.Digest} + return &ZONEMD{ + rr.Hdr, + rr.Serial, + rr.Scheme, + rr.Hash, + rr.Digest, + } } diff --git a/vendor/golang.org/x/crypto/ed25519/ed25519.go b/vendor/golang.org/x/crypto/ed25519/ed25519.go deleted file mode 100644 index a7828345..00000000 --- a/vendor/golang.org/x/crypto/ed25519/ed25519.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ed25519 implements the Ed25519 signature algorithm. See -// https://ed25519.cr.yp.to/. -// -// These functions are also compatible with the “Ed25519” function defined in -// RFC 8032. However, unlike RFC 8032's formulation, this package's private key -// representation includes a public key suffix to make multiple signing -// operations with the same key more efficient. This package refers to the RFC -// 8032 private key as the “seed”. -// -// Beginning with Go 1.13, the functionality of this package was moved to the -// standard library as crypto/ed25519. This package only acts as a compatibility -// wrapper. -package ed25519 - -import ( - "crypto/ed25519" - "io" -) - -const ( - // PublicKeySize is the size, in bytes, of public keys as used in this package. - PublicKeySize = 32 - // PrivateKeySize is the size, in bytes, of private keys as used in this package. - PrivateKeySize = 64 - // SignatureSize is the size, in bytes, of signatures generated and verified by this package. - SignatureSize = 64 - // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. - SeedSize = 32 -) - -// PublicKey is the type of Ed25519 public keys. -// -// This type is an alias for crypto/ed25519's PublicKey type. -// See the crypto/ed25519 package for the methods on this type. -type PublicKey = ed25519.PublicKey - -// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. -// -// This type is an alias for crypto/ed25519's PrivateKey type. -// See the crypto/ed25519 package for the methods on this type. -type PrivateKey = ed25519.PrivateKey - -// GenerateKey generates a public/private key pair using entropy from rand. -// If rand is nil, crypto/rand.Reader will be used. -func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { - return ed25519.GenerateKey(rand) -} - -// NewKeyFromSeed calculates a private key from a seed. It will panic if -// len(seed) is not SeedSize. This function is provided for interoperability -// with RFC 8032. RFC 8032's private keys correspond to seeds in this -// package. -func NewKeyFromSeed(seed []byte) PrivateKey { - return ed25519.NewKeyFromSeed(seed) -} - -// Sign signs the message with privateKey and returns a signature. It will -// panic if len(privateKey) is not PrivateKeySize. -func Sign(privateKey PrivateKey, message []byte) []byte { - return ed25519.Sign(privateKey, message) -} - -// Verify reports whether sig is a valid signature of message by publicKey. It -// will panic if len(publicKey) is not PublicKeySize. -func Verify(publicKey PublicKey, message, sig []byte) bool { - return ed25519.Verify(publicKey, message, sig) -} diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go deleted file mode 100644 index 37dc0cfd..00000000 --- a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ctxhttp provides helper functions for performing context-aware HTTP requests. -package ctxhttp // import "golang.org/x/net/context/ctxhttp" - -import ( - "context" - "io" - "net/http" - "net/url" - "strings" -) - -// Do sends an HTTP request with the provided http.Client and returns -// an HTTP response. -// -// If the client is nil, http.DefaultClient is used. -// -// The provided ctx must be non-nil. If it is canceled or times out, -// ctx.Err() will be returned. -func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { - if client == nil { - client = http.DefaultClient - } - resp, err := client.Do(req.WithContext(ctx)) - // If we got an error, and the context has been canceled, - // the context's error is probably more useful. - if err != nil { - select { - case <-ctx.Done(): - err = ctx.Err() - default: - } - } - return resp, err -} - -// Get issues a GET request via the Do function. -func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Head issues a HEAD request via the Do function. -func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Post issues a POST request via the Do function. -func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return Do(ctx, client, req) -} - -// PostForm issues a POST request via the Do function. -func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { - return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} diff --git a/vendor/golang.org/x/net/html/doc.go b/vendor/golang.org/x/net/html/doc.go index 822ed42a..2466ae3d 100644 --- a/vendor/golang.org/x/net/html/doc.go +++ b/vendor/golang.org/x/net/html/doc.go @@ -92,6 +92,27 @@ example, to process each anchor node in depth-first order: The relevant specifications include: https://html.spec.whatwg.org/multipage/syntax.html and https://html.spec.whatwg.org/multipage/syntax.html#tokenization + +# Security Considerations + +Care should be taken when parsing and interpreting HTML, whether full documents +or fragments, within the framework of the HTML specification, especially with +regard to untrusted inputs. + +This package provides both a tokenizer and a parser, which implement the +tokenization, and tokenization and tree construction stages of the WHATWG HTML +parsing specification respectively. While the tokenizer parses and normalizes +individual HTML tokens, only the parser constructs the DOM tree from the +tokenized HTML, as described in the tree construction stage of the +specification, dynamically modifying or extending the docuemnt's DOM tree. + +If your use case requires semantically well-formed HTML documents, as defined by +the WHATWG specification, the parser should be used rather than the tokenizer. + +In security contexts, if trust decisions are being made using the tokenized or +parsed content, the input must be re-serialized (for instance by using Render or +Token.String) in order for those trust decisions to hold, as the process of +tokenization or parsing may alter the content. */ package html // import "golang.org/x/net/html" diff --git a/vendor/golang.org/x/net/html/escape.go b/vendor/golang.org/x/net/html/escape.go index d8561396..04c6bec2 100644 --- a/vendor/golang.org/x/net/html/escape.go +++ b/vendor/golang.org/x/net/html/escape.go @@ -193,6 +193,87 @@ func lower(b []byte) []byte { return b } +// escapeComment is like func escape but escapes its input bytes less often. +// Per https://github.com/golang/go/issues/58246 some HTML comments are (1) +// meaningful and (2) contain angle brackets that we'd like to avoid escaping +// unless we have to. +// +// "We have to" includes the '&' byte, since that introduces other escapes. +// +// It also includes those bytes (not including EOF) that would otherwise end +// the comment. Per the summary table at the bottom of comment_test.go, this is +// the '>' byte that, per above, we'd like to avoid escaping unless we have to. +// +// Studying the summary table (and T actions in its '>' column) closely, we +// only need to escape in states 43, 44, 49, 51 and 52. State 43 is at the +// start of the comment data. State 52 is after a '!'. The other three states +// are after a '-'. +// +// Our algorithm is thus to escape every '&' and to escape '>' if and only if: +// - The '>' is after a '!' or '-' (in the unescaped data) or +// - The '>' is at the start of the comment data (after the opening ""); err != nil { diff --git a/vendor/golang.org/x/net/html/token.go b/vendor/golang.org/x/net/html/token.go index 50f7c6aa..5c2a1f4e 100644 --- a/vendor/golang.org/x/net/html/token.go +++ b/vendor/golang.org/x/net/html/token.go @@ -110,7 +110,7 @@ func (t Token) String() string { case SelfClosingTagToken: return "<" + t.tagString() + "/>" case CommentToken: - return "" + return "" case DoctypeToken: return "" } @@ -598,10 +598,10 @@ scriptDataDoubleEscapeEnd: // readComment reads the next comment token starting with "