Skip to content

Commit 3e301ea

Browse files
committed
further readme updates
1 parent c63ee96 commit 3e301ea

1 file changed

Lines changed: 87 additions & 55 deletions

File tree

‎README.md‎

Lines changed: 87 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,30 @@
44

55
## Introduction and Scope
66

7-
`httpsig` is a library that facilitates the signing and verification of HTTP requests in compliance with the [RFC 9421 HTTP Message Signatures](https://www.rfc-editor.org/rfc/rfc9421.html) standard.
7+
`httpsig` is a library for signing and verifying HTTP requests and responses according to [RFC 9421 (HTTP Message Signatures)](https://www.rfc-editor.org/rfc/rfc9421.html). It combines reusable signing and verification policies with support for application-specific signature requirements and signature negotiation using `Accept-Signature`.
88

9-
Its `Message` abstraction allows integration with different HTTP frameworks.
9+
The `Message` abstraction keeps these capabilities independent of any particular HTTP framework. For API details and option semantics, see the [Go reference](https://pkg.go.dev/github.com/dadrus/httpsig).
1010

1111
## Usage
1212

1313
### Standalone Signing and Verification
1414

15-
To sign an HTTP request, first, create a `Signer` instance using your preferred key and signing algorithm:
15+
The following snippets show two independent flows: signing an outgoing request and verifying a received response. They assume application-provided keys and other values; routine error handling is abbreviated.
16+
17+
To sign a request, configure a `Signer` with the signing key and the HTTP components to protect:
1618

1719
```go
18-
// Create a signer.
19-
signer, err := httpsig.NewSigner(
20+
// Configure the signing policy.
21+
signer, err := httpsig.NewSigner(
2022
// specify a key
21-
httpsig.Key{Material: privKey, Algorithm: httpsig.EcdsaP256Sha256},
23+
httpsig.Key{Material: privKey, Algorithm: httpsig.EcdsaP256Sha256},
2224
// the keyid parameter for the above key
2325
httpsig.WithKeyID("key1"),
2426
// specify the required options
2527
// duration for which the signature should be valid
26-
httpsig.WithTTL(5 * time.Second),
28+
httpsig.WithTTL(5 * time.Second),
2729
// which components should be protected by a signature
28-
httpsig.WithComponents("@authority", "@method", "x-my-fancy-header"),
30+
httpsig.WithComponents("@authority", "@method", "x-my-fancy-header"),
2931
// a tag for your specific application
3032
httpsig.WithTag("myapp"),
3133
)
@@ -34,20 +36,24 @@ signer, err := httpsig.NewSigner(
3436
// Create a request
3537
req, err := http.NewRequestWithContext(context.Background(), "GET", "https://some-url.com", nil)
3638
// error handling goes here
39+
req.Header.Set("X-My-Fancy-Header", "example-value")
40+
41+
nonce := ... // generate a nonce
3742

3843
// Sign the request
3944
header, err := signer.Sign(
40-
httpsig.MessageFromRequest(req),
45+
httpsig.MessageFromRequest(req),
4146
// add a nonce if required
42-
httpsig.WithParameter("nonce", someNonce)
47+
httpsig.WithParameter(httpsig.Nonce, nonce),
4348
)
4449
// error handling goes here
4550

46-
// Add the signature to the request
51+
// MessageFromRequest clones the headers; use the headers returned by Sign.
4752
req.Header = header
53+
// send the request
4854
```
4955

50-
To verify a response, create a `Verifier` using your preferred key and signing algorithm:
56+
To verify a response, create a `Verifier` with a `KeyResolver` that supplies trusted verification keys (see [Key Resolution](#key-resolution)). `WithValidateAllSignatures` checks every signature present in the message; use `WithRequiredTag` instead when your protocol expects particular signed tags.
5157

5258
```go
5359
// Receive a response from the server
@@ -56,7 +62,7 @@ resp, err := client.Post("https://some-url.com", "application/json", &buf)
5662

5763
// Create a verifier
5864
verifier, err := httpsig.NewVerifier(
59-
// specify a key resolver to resolve the key used by the client
65+
// specify a key resolver to resolve the key
6066
keyResolver,
6167
// specify the required options
6268
// which response components are expected to be protected
@@ -79,9 +85,9 @@ verified, err := verifier.Verify(httpsig.MessageFromResponse(resp))
7985

8086
```
8187

82-
Once `Verify` succeeds, the application can inspect the `verified` object and perform its own policies, like e.g., the nonce correlation and replay checks.
88+
Once `Verify` succeeds, your application can inspect the `verified` object and enforce protocol-specific rules, such as nonce correlation, replay protection, and authorization.
8389

84-
If you need to validate a signature created by a specific application (identified by a tag), use the `WithRequiredTag` option when creating the verifier. This option allows you to specify a tag along with the same options as the `NewVerifier` function. Here’s an example:
90+
If a protocol requires a signature with a particular `tag`, use `WithRequiredTag`. Unlike `WithValidateAllSignatures`, tag-based verification selects signatures carrying the required tag; unrelated signatures are not verified unless all-signature verification is also enabled. For example:
8591

8692
```go
8793
verifier, err := httpsig.NewVerifier(
@@ -105,21 +111,20 @@ verified, err := verifier.Verify(msg)
105111
// error handling goes here
106112
```
107113

108-
Global verifier options act as defaults for all required tags. Explicit tag-specific options take precedence (for example, a tag's `WithComponents` replaces the global component list), while required, forbidden, and expected signature parameters are additive. Automatic signature negotiation reflects the effective requirements for each tag.
114+
Global verifier options act as defaults for required tags. Tag-specific options take precedence (for example, `WithComponents` replaces the global component list), while required, forbidden, and expected signature-parameter constraints are additive. Automatic signature negotiation uses these effective per-tag requirements.
109115

110-
While the examples demonstrate signing a request and verifying a response, you can also verify requests and sign responses. Both the `Verifier.Verify()` and `Signer.Sign()` methods require a `Message` object, which can be created for requests and responses on both client and server sides using the following functions:
116+
The same APIs also verify incoming requests and sign outgoing responses. Both `Signer.Sign` and `Verifier.Verify` operate on a `Message`, created for the corresponding HTTP direction:
111117

112-
* `MessageFromRequest` - creates a `Message` from an `http.Request`. Can be used for outbound (client-side) and inbound (server-side) requests.
113-
* `MessageFromResponse` - creates a `Message` from an `http.Response`. Can be used for inbound (client-side) responses from a server.
114-
* `MessageForResponse` - creates a Message from an outbound (server-side) response.
118+
* `MessageFromRequest` — outbound client requests or inbound server requests.
119+
* `MessageFromResponse` — responses received by clients.
120+
* `MessageForResponse` — responses produced by servers.
115121

116122
For middleware integration, see [HTTP Frameworks](#http-frameworks).
117123

118-
Both the `Signer` and `Verifier` respect the `"content-digest"` component identifier as highlighted in the [Security Considerations](https://www.rfc-editor.org/rfc/rfc9421.html#name-message-content) of the RFC. This is handled as follows:
119-
120-
* On the `Signer` side, if `"content-digest"` is configured to be included via the `WithComponents` option and the `WithContentDigestAlgorithm` option is not used, the implementation will calculate a message digest over the body using the `sha-256` and `sha-512` algorithms (the only supported algorithms according to [RFC 9530](https://www.rfc-editor.org/rfc/rfc9530.html)). It will then create or replace the `"Content-Digest"` header with the calculated values in addition to the signature-related headers. If the `WithContentDigestAlgorithm` option is used, the message digest will be calculated using the specified algorithm and the `"Content-Digest"` header will be created or replaced with that value.
124+
To protect a message body, include `"content-digest"` among the covered components (see [RFC 9421's discussion of message content](https://www.rfc-editor.org/rfc/rfc9421.html#name-message-content)):
121125

122-
* On the `Verifier` side, verification of the corresponding hash values is done by default with no additional configuration required. If the `"Signature-Input"` header value contains a `"content-digest"` component, the implementation expects the `"Content-Digest"` header to be present and uses the supplied algorithm names and values to calculate the digest over the body and compare these values to the received ones. If the `"Content-Digest"` header is missing, references unsupported hash algorithms (only `sha-256` and `sha-512` are supported), or there is a mismatch between the calculated and provided values, the message verification will fail with an error.
126+
* **Signing:** The `Signer` calculates the digest and creates or replaces `Content-Digest` before signing. By default, it uses both `sha-256` and `sha-512` (as defined in [RFC 9530](https://www.rfc-editor.org/rfc/rfc9530.html)); `WithContentDigestAlgorithm` selects a single algorithm.
127+
* **Verification:** If the signature covers `content-digest`, the `Verifier` also checks the digest against the body. Verification fails if the header is missing, no supported digest is present, or any supported digest mismatches. Only `sha-256` and `sha-512` are checked.
123128

124129
> [!IMPORTANT]
125130
> Signing or verifying `"content-digest"` requires reading the message body. Since request and response bodies may be attacker-controlled input, callers are responsible for enforcing appropriate body size limits before passing messages to this library.
@@ -156,32 +161,23 @@ After `Verify` succeeds, `VerifiedSignature` provides the verified signature par
156161

157162
### Signature Negotiation
158163

159-
The library not only supports signing and verifying HTTP messages but also facilitates signature negotiation, as defined in the [RFC 9421 HTTP Message Signatures - Requesting Signatures](https://www.rfc-editor.org/rfc/rfc9421.html#name-requesting-signatures), by utilizing the `"Accept-Signature"` header.
164+
Signature negotiation uses the `Accept-Signature` header defined in [RFC 9421](https://www.rfc-editor.org/rfc/rfc9421.html#name-requesting-signatures). A client can explicitly request a signed response; a server can derive a request for missing client signatures from its verification policy.
160165

161-
> [!NOTE]
162-
> While [Chapter 5.2 - Processing an Accept-Signature](https://www.rfc-editor.org/rfc/rfc9421.html#name-processing-an-accept-signat) of the RFC mandates that
163-
>
164-
> > ... a target message MUST have the same label ...
165-
>
166-
> this requirement conflicts with [Chapter 7.2.5 - Signature Labels](https://www.rfc-editor.org/rfc/rfc9421.html#name-signature-labels), which clearly states:
167-
>
168-
> > An intermediary is allowed to relabel an existing signature when processing the message.
169-
> > Therefore, applications **should not** rely on specific labels being present, and applications **should not** put semantic meaning on the labels themselves. Instead, additional signature parameters can be used to convey whatever additional meaning is required to be attached to, and covered by, the signature. In particular, the `tag` parameter can be used to define an application-specific value.
170-
>
171-
> As a result, the current implementation does not enforce label consistency, even though you can specify them. The only reliable method to ensure effective signature negotiation is by utilizing the `tag` parameter, as also recommended in the statement above.
166+
> [!NOTE]
167+
> [RFC 9421 §5.2](https://www.rfc-editor.org/rfc/rfc9421.html#name-processing-an-accept-signat) requires a negotiated signature to use the requested label, but [§7.2.5](https://www.rfc-editor.org/rfc/rfc9421.html#name-signature-labels) permits intermediaries to relabel signatures and warns against assigning labels application semantics. `httpsig` therefore does not enforce label consistency. Use the signed `tag` parameter to identify application-specific signatures instead.
172168
173169
#### Requesting Signatures on the Client-Side from the Server
174170

175-
On the client side, you can request the server to sign the response by using the `AcceptSignatureBuilder`. This builder can be created with the `NewAcceptSignature` function, which accepts several options to specify parameters and components that you want the server to include in the response. Here’s an example:
171+
Use `AcceptSignatureBuilder` when a client needs to request a signed response. It constructs the `Accept-Signature` header independently of any verifier policy, so the client can specify the components and parameters it expects the server to sign:
176172

177173
```go
178174
// create a builder (all options are optional)
179175
builder, err := httpsig.NewAcceptSignature(
180-
// request a key ID and signing algorithm
176+
// request a key identifier and signing algorithm
181177
httpsig.WithKeyID("foo"),
182178
// specify which signature algorithm the peer should use
183179
httpsig.WithSignatureAlgorithm(httpsig.EcdsaP256Sha256),
184-
// specify which label should the server use when creating the response
180+
// request the label and covered components
185181
httpsig.WithLabel("bar"),
186182
// specify which components should be covered by the signature
187183
httpsig.WithComponents("@status", "content-digest;req", "content-digest"),
@@ -203,11 +199,20 @@ err = builder.Build(req.Context(), req.Header, httpsig.WithParameter("nonce", no
203199
// error handling goes here
204200
```
205201

206-
When the above code executes, it will add an `"Accept-Signature"` header to the request with a value like: `bar=("@status", "content-digest";req, "content-digest");keyid="foo";alg="ecdsa-p256-sha256";nonce="...";tag="awesome-app";created;expires`.
202+
This adds an `Accept-Signature` header with a value such as:
203+
204+
```http
205+
Accept-Signature: bar=("@status" "content-digest";req "content-digest");created;expires;keyid="foo";alg="ecdsa-p256-sha256";nonce="...";tag="awesome-app"
206+
Want-Content-Digest: sha-256=2
207+
```
208+
209+
The `Want-Content-Digest` header is also added because the requested signature covers `content-digest`.
207210

208211
#### Requesting Signatures on the Server-Side from the Client
209212

210-
Signature negotiation on the server side works differently from the client-side. Instead of using the `AcceptSignatureBuilder`, you specify the corresponding options when creating the `Verifier`. This ensures that there are no discrepancies between what the `Verifier` expects and what is included in the `"Accept-Signature"` response header if an expected signature is not present or required parameters/components are missing. Here’s an example, building on the earlier `Verifier` creation example:
213+
On the server side, the `Verifier` can derive `Accept-Signature` requirements from its configured policy. This avoids defining component and parameter requirements separately for verification and negotiation. If a required signature, component, or parameter is missing, `Verify` returns an error wrapping `NoApplicableSignatureError`; use `errors.As` to retrieve it and call `Negotiate` to add the prepared headers to the response. An invalid cryptographic signature is still a verification failure, not a negotiation request.
214+
215+
For example, extending the earlier tag-based verifier:
211216

212217
```go
213218
verifier, err := httpsig.NewVerifier(
@@ -310,18 +315,18 @@ signer, err := httpsig.NewSigner(
310315

311316
req.Header, err = signer.Sign(httpsig.MessageFromRequest(req))
312317

313-
// Recipient
318+
// Recipient: resolve the covered Signature-Agent member dynamically.
314319
verifier, err := httpsig.NewVerifier(webBotKeyResolver,
315320
httpsig.WithRequiredTag("web-bot-auth",
316-
httpsig.WithComponents("@authority"),
321+
httpsig.WithComponents("@authority", `signature-agent;key="sig1"`),
317322
httpsig.WithRequiredParameters(httpsig.KeyID),
318323
),
319324
)
320325

321326
verified, err := verifier.Verify(httpsig.MessageFromRequest(req))
322327
```
323328

324-
`webBotKeyResolver` resolves keys from `Signature-Agent` and validates their thumbprints.
329+
`webBotKeyResolver` implementation needs to resolve the signing key using the `Signature-Agent` member covered by the signature.
325330

326331
### AAuth
327332

@@ -380,7 +385,7 @@ verifier, err := httpsig.NewVerifier(tokenBoundKeyResolver,
380385
_, err = verifier.Verify(httpsig.MessageFromRequest(req))
381386
```
382387

383-
The resource server validates the access token, supplies its bound key through `KeyResolver`, and checks nonce reuse. For requests with bodies, also cover `content-digest`.
388+
The resource server validates the access token, supplies its bound key through `KeyResolver`, and checks nonce reuse. For requests with bodies, also cover `content-digest`. When verifying `@target-uri` on incoming requests, use the externally visible absolute URL, reconstructed from trusted server or proxy configuration.
384389

385390
## HTTP Frameworks
386391

@@ -390,13 +395,16 @@ The examples below verify incoming requests. The same signing, verification, and
390395

391396
```go
392397
http.Handle("/api", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
393-
// Retain Verify's result if a principal is needed for the next handler.
394-
if _, err := verifier.Verify(httpsig.MessageFromRequest(r)); err != nil {
398+
result, err := verifier.Verify(httpsig.MessageFromRequest(r))
399+
if err != nil {
395400
http.Error(w, "Unauthorized", http.StatusUnauthorized)
396401

397402
return
398403
}
399404

405+
// establish a principal from the result object
406+
// and propagate it downstream
407+
400408
handler.ServeHTTP(w, r)
401409
}))
402410
```
@@ -405,13 +413,16 @@ http.Handle("/api", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request
405413

406414
```go
407415
router.Use(func(c *gin.Context) {
408-
// Retain Verify's result if a principal is needed downstream.
409-
if _, err := verifier.Verify(httpsig.MessageFromRequest(c.Request)); err != nil {
416+
result, err := verifier.Verify(httpsig.MessageFromRequest(c.Request))
417+
if err != nil {
410418
c.AbortWithStatus(http.StatusUnauthorized)
411419

412420
return
413421
}
414422

423+
// establish a principal from the result object
424+
// and propagate it downstream
425+
415426
c.Next()
416427
})
417428
```
@@ -420,26 +431,47 @@ router.Use(func(c *gin.Context) {
420431

421432
```go
422433
app.Use(func(c fiber.Ctx) error {
423-
req, err := adaptor.ConvertRequest(c, true)
434+
targetURL, err := url.Parse(c.FullURL())
424435
if err != nil {
425436
return err
426437
}
427438

428-
// Retain Verify's result if a principal is needed downstream.
429-
if _, err := verifier.Verify(httpsig.MessageFromRequest(req)); err != nil {
439+
headers := make(http.Header)
440+
for name, values := range c.GetReqHeaders() {
441+
for _, value := range values {
442+
headers.Add(name, value)
443+
}
444+
}
445+
446+
msg := &httpsig.Message{
447+
Context: c.Context(),
448+
Method: c.Method(),
449+
Authority: c.Host(),
450+
URL: targetURL,
451+
Header: headers,
452+
Body: func() (io.ReadCloser, error) {
453+
return io.NopCloser(bytes.NewReader(c.BodyRaw())), nil
454+
},
455+
IsRequest: true,
456+
}
457+
458+
result, err := verifier.Verify(msg)
459+
if err != nil {
430460
return c.SendStatus(fiber.StatusUnauthorized)
431461
}
432462

463+
// establish a principal from the result object
464+
// and propagate it downstream
465+
433466
return c.Next()
434467
})
435468
```
436469

437470
## Security Considerations
438471

439472
* **Coverage:** Require the components your application relies on. For messages with bodies, sign and verify `content-digest` when body integrity matters.
440-
* **Key trust:** `KeyResolver` receives unverified message data. Select and validate keys according to the application protocol; never treat a reported key ID as proof of identity.
441-
* **Replay:** Enforce the required freshness and nonce checks after successful signature verification.
473+
* **Key trust:** `KeyResolver` receives unverified message data. Select and validate keys according to your application protocol.
474+
* **Replay:** Enforce the required nonce checks after successful signature verification.
442475
* **Multiple signatures:** Labels are not signed, and `VerificationResult` has no defined order. Choose the required tags or validate all signatures as appropriate.
443-
* **HTTP intermediaries:** Proxies can rewrite covered components. Apply the body-size limits described above before hashing untrusted content.
444476

445477
See [RFC 9421 Security Considerations](https://www.rfc-editor.org/rfc/rfc9421.html#section-7).

0 commit comments

Comments
 (0)