Skip to content

refactor!: Signing and verification API refactored - #166

Merged
dadrus merged 33 commits into
mainfrom
refactor/public_api
Nov 4, 2026
Merged

dadrus merged 33 commits into
mainfrom
refactor/public_api

Conversation

@dadrus

@dadrus dadrus commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Related FRs

closes #130
closes #153

Summary

Refactored the public API to provide richer signature context, clearer separation of responsibilities, and reusable signing and verification configurations.

  • Exposed covered components, transmitted signature parameters, and application-defined key-resolution metadata.
  • Consolidated options across signing, verification, and Accept-Signature negotiation.
  • Made nonce handling application-controlled and added per-call signing parameters.
  • Reduced allocations in query canonicalization, signature-base serialization, and signer identifier handling.

⚠️ Breaking changes

Core API

Area Before After
Key Key{KeyID, Key, Algorithm} Key{Material, Algorithm}. Set the signature's keyid separately with WithKeyID(...).
Key resolution ResolveKey(ctx, keyID string) (Key, error) ResolveKey(ctx, info SignatureInfo) (KeyInfo, error). The resolver receives the message, signature label, covered components, and parameters. It returns a trusted key and optional metadata.
Verification Verify(msg) error Verify(msg) (VerificationResult, error). Successful verification returns a VerifiedSignature for each selected signature, including components, parameters, label, and resolver metadata. No partial result is returned on failure.
Signing Sign(msg) Sign(msg, ...SignOption). WithLabel(...) and WithParameter(...) can provide values for an individual call. Extension parameters can also be configured on NewSigner().
Signer nonce Automatic random nonce; optional WithNonce(NonceGetter) No nonce by default. Supply an application-generated value with Sign(msg, WithParameter("nonce", value)).
alg parameter Included automatically Omitted by default; explicitly enabled with WithAlg() on NewSigner().
Nonce validation NonceChecker, NonceValue, NonceCheckerFunc, WithNonceChecker(...) Removed. Applications perform nonce correlation and replay checks using successfully verified signature parameters.
Option types Function-based option types Context-specific interfaces with private implementation methods; applications use the provided option factories.

Security boundary: SignatureInfo is supplied to the key resolver before cryptographic verification and must be treated as untrusted. The values returned in VerificationResult are available only after successful verification. Signature labels remain unsigned technical identifiers.

Option migration

Context Before After
Required components WithRequiredComponents(...) WithComponents(...)
Timestamp requirements WithCreatedTimestampRequired(...), WithExpiredTimestampRequired(...) WithCreatedTimestamp(...), WithExpiredTimestamp(...)
Accept-Signature key request WithExpectedKey(Key{KeyID, Algorithm}) WithKeyID(...) and WithSignatureAlgorithm(...)
Accept-Signature options WithExpectedLabel, WithExpectedComponents, WithExpectedTag, WithExpectedCreatedTimestamp, WithExpectedExpiresTimestamp WithLabel, WithComponents, WithTag, WithCreatedTimestamp, WithExpiredTimestamp
Accept-Signature nonce WithExpectedNonce(getter); automatic nonce by default WithNonceGetter(getter) or Build(ctx, header, WithParameter("nonce", value)). No automatic nonce by default; an explicit value overrides the configured getter.
Signature negotiation WithRequestedKey, WithRequestedNonce, WithRequestedLabel, WithRequestedContentDigestAlgorithmPreferences WithKeyID + WithSignatureAlgorithm, WithNonceGetter, WithLabel, WithContentDigestAlgorithmPreferences

Additionally, WithRequiredTag("") is now rejected during verifier construction. SignatureParameters and Token are exposed for inspecting typed Structured Fields values, including extension parameters.

@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.47716% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.67%. Comparing base (d2cd73b) to head (3e301ea).
⚠️ Report is 4 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
verification_policy.go 96.10% 6 Missing ⚠️
signature_base.go 95.91% 2 Missing ⚠️
signer.go 97.67% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #166      +/-   ##
==========================================
+ Coverage   96.70%   97.67%   +0.97%     
==========================================
  Files          19       20       +1     
  Lines        1153     1377     +224     
==========================================
+ Hits         1115     1345     +230     
+ Misses         38       32       -6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@dadrus

dadrus commented Nov 3, 2026

Copy link
Copy Markdown
Owner Author

@mariusor, @jvongxay0308: This PR addresses the FRs you both submitted. Would you be willing to review the PR and try out the updated API? I'd be particularly interested in your feedback:

  • Do the changes address the challenges you were facing?
  • How does the updated API feel to use?
  • Is there anything you think could still be improved?

Looking forward to hearing your thoughts. Thanks in advance for taking the time!

@dadrus

dadrus commented Nov 3, 2026

Copy link
Copy Markdown
Owner Author

@newtosh, @rosylilly, @faustbrian: Since you're also using httpsig in your projects, I'd naturally be very interested in your feedback on the changes introduced by this PR as well ;)

@rosylilly

Copy link
Copy Markdown
Contributor

Thanks for the ping, and for this PR! For context, I use httpsig in my ActivityPub server (mycroblog/my) as the RFC 9421 sign/verify primitive. The acceptance policy lives outside the library, since keys are fetched from remote actors and the fediverse doesn't use tags.

How it feels: Good. I tried porting my adapter to this branch in a local copy. The change was small and confined to one file, and my adapter and federation tests pass. Per-call WithParameter("nonce", ...) lets me drop my fixed NonceGetter wrapper, and Key still works as a static KeyResolver, which suits me. I also like that the time and component checks run before ResolveKey, so cheap rejections happen before any key fetch.

Claude Code helped me review this PR and translate this comment into English.

Feedback on the API

  1. VerificationResult order isn't deterministic. Verify ranges over a map, so with several signatures the result order changes between calls: verifying six signatures 50 times gave me six different orders. The resolver call order and which error is reported depend on the same loop. Could it follow the Signature-Input order?
  2. The SignatureParameter constants can't index SignatureParameters, because the map is keyed by string: params[httpsig.KeyID] doesn't compile. Resolvers end up with info.Parameters["keyid"].(string). Typed accessors such as KeyID() (string, bool) would be nice.
  3. A naming nit: WithExpiredTimestamp controls the expires parameter, and the constant is Expires. WithExpiresTimestamp would be more consistent.

Small things I noticed in the code

  • Message.addSignature: the second UnmarshalDictionary overwrites err from the first, so Sign panics with a nil pointer dereference on a malformed Signature with a valid Signature-Input. I reproduced this on both this branch and main. It only affects signing, so Verify isn't involved, but it could matter for a proxy that adds a signature to a forwarded request.
  • signatureInput.parameters() calls si.value.Params.Names() before its nil check, so the check can't protect against a nil Params.

Not blockers, but they would remove workarounds on my side. These API shapes are only suggestions.

  • WithClock(now func() time.Time), accepted by both NewSigner and NewVerifier and defaulting to time.Now. I apply the time window with my own injected clock, so I currently set WithMaxAge and WithValidityTolerance to 100 years, and created still comes from the system clock.
  • Verify(msg *Message, opts ...VerifyOption), mirroring Sign, with WithLabel(label) as a VerifyOption. Only that signature would be selected, and a missing label would return NoApplicableSignatureError. Without tags, I have to use WithValidateAllSignatures, where one unrelated signature fails the whole call, so I currently rebuild the headers with only the label I want. The label isn't signed, but it would only choose what to check: the signature must still verify, and a changed label fails closed.
  • ParseAcceptSignature(header http.Header) ([]SignatureRequest, error), with SignatureRequest{Label string; Components []string; Parameters SignatureParameters} and components in the form WithComponents accepts. The library builds Accept-Signature, but I parse it myself. signatureRequirements.fromInnerList looks close already, though it rejects the extension parameters that WithParameter can now add.

If you'd like any of these API changes or fixes, just mention me and I'll open a PR.

Separately, I found an issue in an existing check, unrelated to this PR, that I'd rather not discuss publicly first. Could you email me at rosylilly@aduca.org ? I'll send you the details and my test code.

@dadrus

dadrus commented Nov 4, 2026

Copy link
Copy Markdown
Owner Author

@rosylilly Awesome! Thanks for the detailed feedback, and especially for testing the changes!

As you can see from the updates above, your feedback has already led to a few changes. Both bugs are fixed, WithExpiredTimestamp has been renamed, and SignatureParameters now has typed keys and accessors. This makes the new API much more consistent.

Regarding the order of VerificationResult, I'd like to better understand your use case. What would you need deterministic ordering for?

As for the three nice-to-have API additions, would you mind opening a separate feature request for each of them? I'd prefer to discuss these independently of this PR, and it would also give other users a chance to share their thoughts. For WithClock in particular, I'd love to learn more about the underlying use case in the corresponding issue. You already described your workaround, but I'd like to understand the actual requirements before discussing the API.

I'll also follow up with you separately by email.

@rosylilly

Copy link
Copy Markdown
Contributor

@dadrus Thanks for the quick fixes! I've opened the three feature requests: #168 , #169 , and #170 .

On the order of VerificationResult, the use case I had in mind is bulk verification: when a message carries several signatures, it's convenient if the results come back in the same order as Signature-Input, so they can be processed in sequence alongside what was signed. It isn't a hard requirement. My adapter verifies a single signature today, and matching results by Label also works. If you'd rather keep it as it is, a doc comment saying the order isn't guaranteed would be enough for me.

@dadrus

dadrus commented Nov 4, 2026

Copy link
Copy Markdown
Owner Author

I'd prefer to keep the order unspecified for now and make that explicit in the GoDoc.

Nevertheless, I'm curious: why would you need the same order as in Signature-Input? httpsig already parses that header, but it sounds like you're parsing it yourself as well. Is there a particular reason for that?

@dadrus dadrus mentioned this pull request Nov 4, 2026

@mariusor mariusor left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Too late for my comment I guess.

Other than this, I'm still working on making the tests pass with the old signature vectors, but I'll come back if there's anything in the library that's at fault.

Comment thread options.go Resolved
@mariusor

mariusor commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

So everything is fine, the test errors were related to the changes to the nonce and the KeyResolver interface.

👍 from me.

@dadrus

dadrus commented Nov 4, 2026 •

Copy link
Copy Markdown
Owner Author

@mariusor Cool, thanks! Btw. the party is still ongoing - so, you're not too late ;)

The README has also received a bigger update. Feedback is appreciated ;)

Your last comment was pretty brief :) Does that mean the challenge you described in #130 is now resolved? Is there anything else you think we should address, beyond the points raised by @rosylilly?

@mariusor

mariusor commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

@dadrus yes, I think so. I can now do something like this in the ResolveKey() method:

alg, ok := sigInfo.Parameters.Alg()
if !ok {
	// defaults to PKCSv1 for RSA, and takes key size into consideration
	alg = rfcAlgorithmFromPublicKey(pkey) 
}
key.Alg = alg

I don't think there is something better that can be done.

@mariusor

mariusor commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

(Unrelated, and sorry for shilling: @rosylilly I don't know if you stumbled upon my library when you started the work on your project, but it's meant to solve exactly the problems you're dealing with right now :D. If you're interested in some collaboration there's a mailing list where you can reach me: https://lists.sr.ht/~mariusor/go-activitypub-discuss)

@dadrus
dadrus merged commit bf37e1d into main Nov 4, 2026
10 checks passed
@dadrus
dadrus deleted the refactor/public_api branch November 4, 2026 23:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Expose resolved key metadata through context.Context after successful verification Key Algorithm issues

3 participants