4
0
Эх сурвалжийг харах

Add external account binding to the ACME client

NewACMEClient created its account without one, so it could not order from
a provisioner that requires external account binding. WithExternalAccountBinding
adds the JWS RFC 8555 section 7.3.4 defines to the new account request.

Claude-Session: https://claude.ai/code/session_01CjfEMLuVfp2pZKDwHBZuyA
Josh Drake 4 долоо хоног өмнө
parent
commit
3e2f8d6f9a
3 өөрчлөгдсөн 138 нэмэгдсэн , 0 устгасан
  1. 36 0
      ca/acmeClient.go
  2. 86 0
      ca/acmeClient_test.go
  3. 16 0
      ca/client.go

+ 36 - 0
ca/acmeClient.go

@@ -75,6 +75,11 @@ func NewACMEClient(endpoint string, contact []string, opts ...ClientOption) (*AC
 		Contact:              contact,
 		TermsOfServiceAgreed: true,
 	}
+	if o.eabKeyID != "" {
+		if nar.ExternalAccountBinding, err = ac.externalAccountBinding(o.eabKeyID, o.eabHMACKey); err != nil {
+			return nil, err
+		}
+	}
 	payload, err := json.Marshal(nar)
 	if err != nil {
 		return nil, errors.Wrap(err, "error marshaling new account request")
@@ -98,6 +103,37 @@ func NewACMEClient(endpoint string, contact []string, opts ...ClientOption) (*AC
 	return ac, nil
 }
 
+// externalAccountBinding returns the external account binding of a new account
+// request (RFC 8555 section 7.3.4): a JWS over the account's public key, signed
+// with the HMAC key, whose kid is the key ID and whose url is the new account
+// URL.
+func (c *ACMEClient) externalAccountBinding(keyID string, hmacKey []byte) (*acmeAPI.ExternalAccountBinding, error) {
+	payload, err := json.Marshal(c.Key.Public())
+	if err != nil {
+		return nil, errors.Wrap(err, "error marshaling the account key")
+	}
+	so := new(jose.SignerOptions)
+	so.WithHeader("kid", keyID)
+	so.WithHeader("url", c.dir.NewAccount)
+	signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: hmacKey}, so)
+	if err != nil {
+		return nil, errors.Wrap(err, "error creating external account binding signer")
+	}
+	signed, err := signer.Sign(payload)
+	if err != nil {
+		return nil, errors.Errorf("error signing external account binding: %s", jose.TrimPrefix(err))
+	}
+	raw, err := serialize(signed)
+	if err != nil {
+		return nil, err
+	}
+	eab := new(acmeAPI.ExternalAccountBinding)
+	if err := json.Unmarshal([]byte(raw), eab); err != nil {
+		return nil, errors.Wrap(err, "error reading external account binding")
+	}
+	return eab, nil
+}
+
 // GetDirectory makes a directory request to the ACME api and returns an
 // ACME directory object.
 func (c *ACMEClient) GetDirectory() (*acmeAPI.Directory, error) {

+ 86 - 0
ca/acmeClient_test.go

@@ -1,6 +1,7 @@
 package ca
 
 import (
+	"crypto"
 	"crypto/x509"
 	"encoding/base64"
 	"encoding/json"
@@ -142,6 +143,91 @@ func TestNewACMEClient(t *testing.T) {
 	}
 }
 
+func TestNewACMEClient_externalAccountBinding(t *testing.T) {
+	var srv *httptest.Server
+	hmacKey := []byte("the external account key's hmac")
+
+	// newClient returns a client and the external account binding its new
+	// account request carried, verified by the outer JWS's key.
+	newClient := func(t *testing.T, ops ...ClientOption) (*ACMEClient, *acmeAPI.ExternalAccountBinding) {
+		t.Helper()
+		var eab *acmeAPI.ExternalAccountBinding
+		srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			switch r.URL.Path {
+			case "/nonce":
+				w.Header().Set("Replay-Nonce", "abc123")
+				w.WriteHeader(http.StatusOK)
+			case "/new-account":
+				body, err := io.ReadAll(r.Body)
+				assert.FatalError(t, err)
+				jws, err := jose.ParseJWS(string(body))
+				assert.FatalError(t, err)
+				payload, err := jws.Verify(jws.Signatures[0].Protected.JSONWebKey)
+				assert.FatalError(t, err)
+				var nar acmeAPI.NewAccountRequest
+				assert.FatalError(t, json.Unmarshal(payload, &nar))
+				eab = nar.ExternalAccountBinding
+				w.Header().Set("Location", "/account/1")
+				render.JSONStatus(w, r, acme.Account{Status: "valid"}, 201)
+			default:
+				render.JSONStatus(w, r, acmeAPI.Directory{
+					NewNonce:   srv.URL + "/nonce",
+					NewAccount: srv.URL + "/new-account",
+				}, 200)
+			}
+		}))
+		t.Cleanup(srv.Close)
+		client, err := NewACMEClient(srv.URL, nil, append(ops, WithTransport(http.DefaultTransport))...)
+		assert.FatalError(t, err)
+		return client, eab
+	}
+
+	t.Run("none without the option", func(t *testing.T) {
+		_, eab := newClient(t)
+		assert.Nil(t, eab)
+	})
+
+	t.Run("the account key, signed with the hmac key", func(t *testing.T) {
+		client, eab := newClient(t, WithExternalAccountBinding("key-id", hmacKey))
+		if !assert.NotNil(t, eab) {
+			t.FailNow()
+		}
+		raw, err := json.Marshal(eab)
+		assert.FatalError(t, err)
+		jws, err := jose.ParseJWS(string(raw))
+		assert.FatalError(t, err)
+
+		header := jws.Signatures[0].Protected
+		assert.Equals(t, string(jose.HS256), header.Algorithm)
+		assert.Equals(t, "key-id", header.KeyID)
+		assert.Equals(t, srv.URL+"/new-account", header.ExtraHeaders["url"])
+
+		_, err = jws.Verify([]byte("another hmac key"))
+		assert.NotNil(t, err)
+		payload, err := jws.Verify(hmacKey)
+		assert.FatalError(t, err)
+
+		var jwk jose.JSONWebKey
+		assert.FatalError(t, json.Unmarshal(payload, &jwk))
+		assert.True(t, jwk.IsPublic())
+		got, err := jwk.Thumbprint(crypto.SHA256)
+		assert.FatalError(t, err)
+		want, err := client.Key.Thumbprint(crypto.SHA256)
+		assert.FatalError(t, err)
+		assert.Equals(t, want, got)
+	})
+
+	t.Run("refused without a key", func(t *testing.T) {
+		for _, op := range []ClientOption{
+			WithExternalAccountBinding("", hmacKey),
+			WithExternalAccountBinding("key-id", nil),
+		} {
+			_, err := NewACMEClient("http://127.0.0.1:0", nil, op)
+			assert.NotNil(t, err)
+		}
+	})
+}
+
 func TestACMEClient_GetDirectory(t *testing.T) {
 	c := &ACMEClient{
 		dir: &acmeAPI.Directory{

+ 16 - 0
ca/client.go

@@ -171,6 +171,8 @@ type clientOptions struct {
 	x5cCertStrs          []string
 	x5cCert              *x509.Certificate
 	x5cSubject           string
+	eabKeyID             string
+	eabHMACKey           []byte
 }
 
 func (o *clientOptions) apply(opts []ClientOption) (err error) {
@@ -306,6 +308,20 @@ func WithInsecure() ClientOption {
 	}
 }
 
+// WithExternalAccountBinding binds the account NewACMEClient creates to an
+// external account key, as an ACME provisioner that requires external account
+// binding asks. The key ID and the HMAC key are the ones the CA minted.
+func WithExternalAccountBinding(keyID string, hmacKey []byte) ClientOption {
+	return func(o *clientOptions) error {
+		if keyID == "" || len(hmacKey) == 0 {
+			return errors.New("an external account binding needs a key ID and an HMAC key")
+		}
+		o.eabKeyID = keyID
+		o.eabHMACKey = hmacKey
+		return nil
+	}
+}
+
 // WithRootFile will create the transport using the given root certificate. It
 // will fail if a previous option to create the transport has been configured.
 func WithRootFile(filename string) ClientOption {