Go: package httpsig
Generated from the Go source by scripts/gen-docs.sh — do not edit; run it to regenerate. Canonical deep reference: pkg.go.dev/github.com/dnsid-ai/dnsid-go/httpsig. Guides and account setup: https://docs.dnsid.ai.
import "github.com/dnsid-ai/dnsid-go/httpsig"Package httpsig implements RFC 9421 HTTP Message Signatures for DNSid agents: signing outbound HTTP requests with an agent’s operational key and verifying inbound signatures against the signer’s published DNSid identity.
The main entry type is Profile. A Profile combines an identity resolver (usually a dnsid.IdentityManager), a local agent domain, and a dnsid.KeyProvider. The resolver is required for verification; the local domain and key provider are required for signing. Config bounds signature freshness; its zero value applies the profile defaults.
A typical exchange signs a request on one side and verifies it on the other:
signer := httpsig.NewFromIdentityManagerKeyProvider(idm, httpsig.Config{})
req, _ := http.NewRequest(http.MethodGet, "https://api.example/data", nil)signed, err := signer.CreateSignedHTTPRequest(req, httpsig.SigningOptions{})// ... dispatch signed; the receiver runs:
vd, err := verifier.VerifyHTTPRequest(ctx, signed)// vd identifies the verified signer domain.CreateSignedHTTPClient wraps an *http.Client so every outbound request is signed automatically. Lower-level helpers (BuildSignatureInput, SignHTTPMessage, ParseSignatureInput, ParseSignature) expose the RFC 9421 signature base and header handling used by other DNSid profiles such as Web Bot Auth.
Response authentication is opt-in; a signed request alone does not authenticate its responder. Enable SigningOptions.ResponseSignature with a locally selected ResponseSignatureOptions.ExpectedDomain to request and require a DNSid signed response. The expected agent domain may differ from the HTTP host. Configure entity acceptance separately on the resolver. HTTPS is required, and responder authentication happens only after the request has been sent.
The server calls SignRequestedHTTPResponse after verifying the caller and authorizing the operation, before sending the finalized status, headers, and content. It uses the operational key, covers the originating request signature fields, sets SHA-256 Content-Digest, and adds Cache-Control: no-store. It does not authorize callers or permit unsigned fallback on signing errors.
The response covers the client’s own request signature member through “signature-input”;req;key=“<label>” and “signature”;req;key=“<label>”, so an intermediary that adds its own request signature does not break it. Responses use a fixed 60-second lifetime, independent of either peer’s MaxAge. ResponseSigningMiddleware buffers and signs negotiated http.Handler responses.
CreateSignedHTTPClient verifies responses automatically, including errors and redirects. Negotiated mode does not follow redirects, decode content, or cache responses. Connection reuse and HTTP/2 remain enabled. Custom round trippers are used as supplied; one that decodes, caches, or rewrites covered fields causes a verification failure. Standalone CreateSignedHTTPRequest callers must retain an unmodified prepared request and independent original response-policy snapshot, then call VerifySignedHTTPResponse with trusted current-server peer evidence. Never use echoed request metadata, a discovery certificate, or a previous connection’s certificate as that snapshot or evidence.
Only covered fields are authenticated. Content-Type, Content-Encoding, and Location are not covered by default; request them through AdditionalComponents when application behavior depends on them. Middleware must finalize content coding before signing and must not alter covered bytes afterward.
Negotiation and signature fields are capped at 16 KiB each, combined headers at 1 MiB, request-target inputs at 64 KiB, and response content at 8 MiB. The nonce is canonical unpadded base64url, 43 to 1024 characters, decoding to at least 32 bytes. Negotiation permits at most 64 components. Sending, reads, and verification share a finite request context budget (default 30 seconds). Custom body readers/providers must be finite and interruptible; hosts must impose read deadlines. HEAD, 204, 205, and 304 digest empty content; an unavailable ordinary body is rejected, not treated as empty.
See https://docs.dnsid.ai for protocol guides and account setup.
Example
Example signs an HTTP request with a locally generated key. A resolver is only needed for verification, so this signing-only profile passes nil.
package main
import ( "fmt" "net/http" "strings"
dnsid "github.com/dnsid-ai/dnsid-go" "github.com/dnsid-ai/dnsid-go/httpsig")
func main() { key := dnsid.GenerateEd25519KeyProvider() profile := httpsig.New(nil, "agent.example", key, httpsig.Config{})
req, err := http.NewRequest(http.MethodGet, "https://api.example/search?q=dnsid", nil) if err != nil { panic(err) } signed, err := profile.CreateSignedHTTPRequest(req, httpsig.SigningOptions{}) if err != nil { panic(err) }
// Signature-Input records the covered components. Its created, keyid, // alg, and nonce parameters vary per run, so only the component list is // printed here. components, _, _ := strings.Cut(signed.Header.Get("Signature-Input"), ";created") fmt.Println(components) fmt.Println("signature present:", signed.Header.Get("Signature") != "")}Output
Section titled “Output”sig1=("@method" "@authority" "@target-uri")signature present: true- func AppendComponent(components *[]ComponentIdentifier, component ComponentIdentifier) error
- func BuildSignatureInput(msg any, params SignatureParams) (string, error)
- func JoseAlgToHTTPSigAlg(alg dnsid.JoseAlg) (string, error)
- func ParseSignature(input string) (map[string][]byte, error)
- func ParseSignatureInput(sigInput string) (map[string]SignatureParams, error)
- func SignHTTPMessage(msg any, params SignatureParams, kp dnsid.KeyProvider) error
- type ComponentIdentifier
- type Config
- type Profile
- func New(resolver dnsid.IdentityResolver, localDomain string, kp dnsid.KeyProvider, cfg Config) *Profile
- func NewFromIdentityManager(manager identityManager, kp dnsid.KeyProvider, cfg Config) *Profile
- func NewFromIdentityManagerKeyProvider(manager identityManagerWithKeyProvider, cfg Config) *Profile
- func (p *Profile) CreateSignedHTTPClient(base *http.Client, opts SigningOptions) *http.Client
- func (p *Profile) CreateSignedHTTPRequest(req *http.Request, opts SigningOptions) (*http.Request, error)
- func (p *Profile) ResponseSigningMiddleware(next http.Handler) http.Handler
- func (p *Profile) SignRequestedHTTPResponse(req *http.Request, res *http.Response) (*http.Response, error)
- func (p *Profile) VerifyHTTPRequest(ctx context.Context, req *http.Request) (*dnsid.VerifiedDomain, error)
- func (p *Profile) VerifySignedHTTPResponse(ctx context.Context, req *http.Request, res *http.Response, opts ResponseSignatureOptions, peer …dnsid.VerifyDomainOpts) (verified *dnsid.VerifiedDomain, err error)
- type ResponseSignatureOptions
- type SignatureParameter
- type SignatureParams
- type SigningOptions
func AppendComponent(components *[]ComponentIdentifier, component ComponentIdentifier) errorAppendComponent validates and appends one component.
func BuildSignatureInput(msg any, params SignatureParams) (string, error)BuildSignatureInput builds the RFC 9421 signature base for requests or responses.
func JoseAlgToHTTPSigAlg(alg dnsid.JoseAlg) (string, error)JoseAlgToHTTPSigAlg maps SDK JOSE algorithms to RFC 9421 algorithm names.
func ParseSignature(input string) (map[string][]byte, error)ParseSignature parses a Signature dictionary into bytes by label.
func ParseSignatureInput(sigInput string) (map[string]SignatureParams, error)ParseSignatureInput parses a Signature-Input dictionary.
func SignHTTPMessage(msg any, params SignatureParams, kp dnsid.KeyProvider) errorSignHTTPMessage signs a request or response and sets Signature-Input/Signature.
ComponentIdentifier identifies an RFC 9421 covered component.
type ComponentIdentifier struct { // Name is the component name, such as "@method", "@authority", or a // lowercase field name like "content-digest". Name string
// Params holds RFC 9421 component parameters. This SDK supports the // req, key, and name parameters in their profile-defined contexts. Params map[string]any
// ParamOrder preserves the serialization order of Params keys. ParamOrder []string
// Raw is retained for source compatibility. Parsed and constructed // identifiers are always serialized canonically from Name and Params. // Deprecated: raw component serialization is not part of RFC 9421's // parsed data model. Raw string}func ParseComponentIdentifier(s string) ComponentIdentifierParseComponentIdentifier parses the subset of component identifiers this SDK emits.
func (ComponentIdentifier) String
Section titled “func (ComponentIdentifier) String”func (c ComponentIdentifier) String() stringString serializes a component identifier as it appears in Signature-Input.
Config contains HTTP Message Signatures profile policy. The zero value applies the profile defaults.
type Config struct { // MaxAge bounds signature freshness during verification: a signature's // created parameter must be no older than MaxAge, and when an expires // parameter is present its distance from created must not exceed // MaxAge. Zero means the default of 5 minutes; negative is invalid. // Response signatures use a fixed 60-second lifetime; MaxAge bounds only // the age of their created parameter. MaxAge time.Duration
// ClockSkew is the tolerance applied to signature timestamp checks // during verification. Zero means the default of 5 seconds; negative is // invalid. ClockSkew time.Duration // contains filtered or unexported fields}func (c Config) WithClockSkew(skew time.Duration) ConfigWithClockSkew returns a copy configured with skew, including an explicit zero value. This distinguishes strict zero-skew verification from Config’s zero-value default of 5 seconds.
Profile implements the DNSid HTTP Message Signatures profile.
type Profile struct { // contains filtered or unexported fields}func New(resolver dnsid.IdentityResolver, localDomain string, kp dnsid.KeyProvider, cfg Config) *ProfileNew constructs an HTTP Message Signatures profile.
func NewFromIdentityManager(manager identityManager, kp dnsid.KeyProvider, cfg Config) *ProfileNewFromIdentityManager constructs a profile from an IdentityManager-like core manager.
func NewFromIdentityManagerKeyProvider(manager identityManagerWithKeyProvider, cfg Config) *ProfileNewFromIdentityManagerKeyProvider constructs a profile from a manager that exposes its KeyProvider.
func (p *Profile) CreateSignedHTTPClient(base *http.Client, opts SigningOptions) *http.ClientCreateSignedHTTPClient wraps base so outbound requests are signed before dispatch. With ResponseSignature enabled, it snapshots options and each outgoing request, verifies every final response (including HTTP errors), and returns only verified bounded content. It does not follow redirects or cache responses. A *http.Transport (nil uses the default) is cloned with transparent decoding disabled; connection reuse and HTTP/2 remain enabled. Other round trippers are used as supplied: one that decodes, caches, or rewrites covered fields causes a verification failure. Sending, reads, and verification share the request context budget; absent a deadline the default is dnsid.DefaultVerificationTimeout (30 seconds). Each explicit retry needs a replayable original unsigned request.
func (p *Profile) CreateSignedHTTPRequest(req *http.Request, opts SigningOptions) (*http.Request, error)CreateSignedHTTPRequest signs req using the DNSid HTTP Message Signatures profile. ResponseSignature prepares opt-in HTTPS response negotiation but does not send or verify a response. Retain an unmodified prepared request and independent original response-policy snapshot for VerifySignedHTTPResponse. Each explicit attempt must start with a replayable original unsigned request.
func (p *Profile) ResponseSigningMiddleware(next http.Handler) http.HandlerResponseSigningMiddleware signs responses for requests that carry Accept-Signature. Requests without negotiation pass through unbuffered. Negotiated responses are buffered up to 8 MiB and signed with SignRequestedHTTPResponse before any header is sent. On a signing failure or an exceeded bound it sends a 500 without the handler’s headers or content; it never sends the unsigned response. Place it after request verification and authorization, and after any middleware that changes the status, covered headers, or content coding. Buffered handlers cannot flush, hijack, or send informational responses.
func (p *Profile) SignRequestedHTTPResponse(req *http.Request, res *http.Response) (*http.Response, error)SignRequestedHTTPResponse fulfills one DNSid Accept-Signature request using the current operational key. No negotiation returns res unchanged, even for verification-only profiles. On success it returns a copy with finalized fields and replayable content. Call before sending headers, after content coding; middleware must not change covered bytes afterward. It does not authenticate or authorize the caller. Failures must not become unsigned-success fallbacks.
func (p *Profile) VerifyHTTPRequest(ctx context.Context, req *http.Request) (*dnsid.VerifiedDomain, error)VerifyHTTPRequest verifies a DNSid HTTP Message Signature and returns the verified signer domain. At most two eligible signatures may be supplied; applications should also rate-limit inbound requests.
func (p *Profile) VerifySignedHTTPResponse(ctx context.Context, req *http.Request, res *http.Response, opts ResponseSignatureOptions, peer ...dnsid.VerifyDomainOpts) (verified *dnsid.VerifiedDomain, err error)VerifySignedHTTPResponse verifies the requested label against local policy and the saved originating request, never res.Request. The caller must retain an unmodified prepared request and an independent original options snapshot when using standalone helpers. Supply only trusted current-connection peer evidence in peer; discovery certificates cannot substitute for it. Response TLS evidence is used when peer is omitted. Rejected response bodies are closed. On success the content is restored for the caller, who owns closing it.
ResponseSignatureOptions configures opt-in RFC 9421 negotiated response authentication. Only covered fields are authenticated: Content-Type, Content-Encoding, and Location are not covered unless requested explicitly. ExpectedDomain is local policy, independent of the HTTP endpoint hostname. Configure entity acceptance separately on the identity resolver.
type ResponseSignatureOptions struct { // ExpectedDomain is the required locally selected DNSid agent FQDN. ExpectedDomain string // AdditionalComponents requests extra authenticated metadata in caller order. AdditionalComponents []ComponentIdentifier}SignatureParameter is one ordered RFC 8941 parameter on a Signature-Input inner list. Value is an RFC 8941 bare item: bool, int64, string, []byte, or sfv.Token.
type SignatureParameter struct { Name string Value any}SignatureParams contains one RFC 9421 Signature-Input member.
type SignatureParams struct { // Label is the member's dictionary key in Signature-Input and // Signature. Empty means the profile default label "sig1". Label string
// Components lists the covered components in signature-base order. Components []ComponentIdentifier
// KeyID and Alg are the RFC 9421 keyid and alg signature parameters. // This SDK uses "<domain>#<kid>" key identifiers and the algorithm // names "ed25519" and "ecdsa-p256-sha256". KeyID, Alg string
// Created and Expires are the created and expires signature parameters // as Unix timestamps. Zero means the parameter is absent. Created, Expires int64
// Nonce and Tag are the nonce and tag signature parameters. Empty // means the parameter is absent. Nonce, Tag string
// Parameters is the complete ordered Signature-Input parameter list. // Parsed values always populate this field, including unknown registered // extensions. When nil, the typed fields above are serialized in their // historical order for source compatibility with constructed values. Parameters []SignatureParameter
// RawSignatureInputMember is retained for source compatibility and is // ignored. RFC 9421 signature bases canonically serialize the parsed data // model rather than reusing an arbitrary raw header substring. // Deprecated: use Parameters. RawSignatureInputMember string
// ExpectedSignerKid and ExpectedSignerAlg, when non-empty, make // SignHTTPMessage fail if the KeyProvider signs with a different key // id or algorithm (for example after a concurrent key rotation). ExpectedSignerKid string ExpectedSignerAlg dnsid.JoseAlg}SigningOptions configures HTTP request signing.
type SigningOptions struct { // Label identifies the Signature-Input dictionary member. Empty uses sig1. Label string
// ExpiresIn adds an expires parameter relative to created. Zero omits it. ExpiresIn time.Duration
// Tag adds the RFC 9421 tag signature parameter. Tag string
// AdditionalComponents lists extra component names to cover beyond the // profile's defaults. Unknown names cause signing to fail. AdditionalComponents []string
// AdditionalComponentIDs lists extra components, with parameters, to // cover beyond the profile's defaults. AdditionalComponentIDs []ComponentIdentifier
// ResponseSignature enables mandatory negotiated response authentication. ResponseSignature *ResponseSignatureOptions}Generated by gomarkdoc