module HTTPSignatures
http-signatures
HTTP Signatures for Quarz, written in Quarz over its
standard library: signing an HTTP request with the Signature header of
draft-cavage-http-signatures-12,
verifying a request signed so, and the Digest header (RFC 3230) of the
body it covers.
# Cog.toml of an application
[dependencies]
HTTPSignatures = { git = "https://github.com/quarz-lang/http-signatures", tag = "v0.1.0" }
The API reference of the main branch is at https://http-signatures.api.quarz.dev.
Work in progress: the design is issue #1. Nothing is released yet.
License
MIT No Attribution: see LICENSE.
Functions
def sign(request: HTTP::Client::Request, *, key_id: String, key: Crypto::RSA::PrivateKey, headers: Array[String] = …, algorithm: String = …, hs2019_pss: Bool = …, created: Time? = …, expires: Time? = …, now: Time = …) -> HTTP::Client::Request
request signed with HTTP Signatures (draft-cavage-http-signatures-12):
a copy with a Signature header over the covered names, and the headers
the signature needs added.
- The Date header is set to
now(an HTTP date) whendateis covered and the request has none; - the Digest header is set to the body's SHA-256 (
SHA-256=…) whendigestis covered and the request has none; (request-target)andhostare what the client sends:HTTP::Client::Request#targetandHTTP::Client::Request#host.
algorithm is "rsa-sha256" (RSASSA-PKCS1-v1_5 with SHA-256, what
most verifiers accept) or "hs2019", which signs the same way unless
hs2019_pss (RSASSA-PSS with SHA-512). created and expires are
written when given; with hs2019, (created) covered without created
takes now.
key = Crypto::RSA::PrivateKey.from_pem(File.read("private.pem"))
req = HTTP::Client::Request.post("https://example.com/inbox", body: "{}", content_type: "application/json")
signed = HTTPSignatures.sign(req, key_id: "https://example.com/actor#main-key", key: key)
HTTP::Client.default.request(signed)
Raises
ArgumentError for another algorithm, a covered header the request
does not have, a covered name that is no header name, (created) or
(expires) with rsa-sha256, (expires) without expires, or a
digest to compute for a streamed body.
def signing_string(method: String, target: String, headers: HTTP::Headers, covered: Array[String], created: String? = …, expires: String? = …) -> String
The signing string of draft-cavage-http-signatures-12 (§2.3): for each
covered name in order, a line name: value, the lines joined by \n.
(request-target): the method lowercased, a space and the target as sent (path and query):post /foo?param=value&pet=dog;(created),(expires): the signature's parameter, as written;- a header: its values with leading and trailing spaces and tabs
removed, joined by
,in the request's order (cache-control: max-age=60, must-revalidate); an empty value givesname:.
Names are compared without regard to case and written lowercased. A
covered name is (request-target), (created), (expires) or an HTTP
field name (token characters, RFC 9110 §5.1).
headers = HTTP::Headers.of({"Host" => "example.com", "Date" => "Sun, 05 Jan 2014 21:31:40 GMT"})
HTTPSignatures.signing_string("POST", "/foo?param=value&pet=dog", headers, ["(request-target)", "host", "date"])
# => "(request-target): post /foo?param=value&pet=dog\nhost: example.com\ndate: Sun, 05 Jan 2014 21:31:40 GMT"
Raises
MissingHeader for a covered header the request does not have, and
MalformedSignature for (created) or (expires) without its value,
an empty list of names, or a name that is none of the above (the
message gives its position in the list, never the name itself, which
may come from a peer).
def verify(request: HTTP::Server::Request, *, required: Array[String] = …, max_skew: Duration = …, max_body_bytes: Int? = …, require_digest: Bool = …, now: Time = …, &key: (String) -> Crypto::RSA::PublicKey?) -> HTTPSignatures::Verified
Verifies the HTTP Signature (draft-cavage-http-signatures-12) of
request, from its Signature header or, without one, its
Authorization header of the Signature scheme. The block gives the
public key of a keyId, or nil for none; it may wait (fetch a key).
keys: Hash[String, Crypto::RSA::PublicKey] = {} # keyId => key
handler = HTTP.handler do |req|
begin
v = HTTPSignatures.verify(req) { |key_id| keys[key_id]? }
HTTP::Server::Response.text("signed by #{v.key_id}: #{v.body.size} bytes")
rescue HTTPSignatures::Error => e
HTTP::Server::Response.text(e.message, 401)
end
end
The block is given the peer's keyId before anything is verified (a
key is needed to verify): it is the peer's text. A block that fetches
a key by it must check it first: a URL to fetch is a request the peer
chose (restrict its scheme and host, and use a client made with
allow_address: HTTP::Client.public_only).
What is checked:
- the parameters:
keyIdandsignaturegiven, none twice, unknown ones ignored;algorithmisrsa-sha256orhs2019, and a signature naming none counts ashs2019. Every key is RSA:rsa-sha256is RSASSA-PKCS1-v1_5 with SHA-256, andhs2019is that or RSASSA-PSS with SHA-512; - the covered names:
headers, or by defaultdateforrsa-sha256and(created)forhs2019; at most 32, none twice, each inrequiredamong them.(created)and(expires)are refused withrsa-sha256; - the time: a covered Date header (one only) within
max_skewofnow;createdwithinmax_skewofnow(no older when a coveredexpireshas not passed: the signer's window then governs);expiresno earlier thannow - max_skew. Arequiredwithoutdateleaves freshness to(created)and(expires); - the signature of the signing string (
HTTPSignatures.signing_string) with the key; - the body, only once the signature has verified: read whole (
HTTP::Body#read_bytes(max: max_body_bytes), the server's limit at most) and, when it is not empty or a Digest header is covered, compared with that Digest (require_digest: falseaccepts a body no Digest covers).
Raises
An HTTPSignatures::Error saying why: MissingSignature,
MalformedSignature, UnsupportedAlgorithm, MissingHeader,
Expired, UnknownKey, BadSignature or DigestMismatch. Reading the
body raises as HTTP::Body#read_bytes does (HTTP::PayloadTooLarge past the
limit).
Classes and modules
HTTPSignatures::BadSignatureThe signature does not verify with the key.HTTPSignatures::DigestThe Digest header of RFC 3230 with its SHA-256 algorithm: what a signature covers to cover the body.HTTPSignatures::DigestMismatchThe body does not match the Digest the signature covers, the body has no covered Digest, or the Digest has no SHA-256 entry.HTTPSignatures::ErrorThe root of every error this cog raises when it verifies a request: rescue HTTPSignatures::Error catches them all (and a server answers 401). A message names the reason; it never quotes a header's value, and quotes a name only once it is known to be a field name. (An argument a method cannot take is an ArgumentError, as anywhere.)HTTPSignatures::ExpiredThe signature is not valid now: its Date header is too far from now, created is in the future, or expires has passed.HTTPSignatures::MalformedSignatureThe signature's parameters do not parse: a parameter given twice, no keyId or signature, a signature that is not Base64, an empty or repeated name in headers, (created) or (expires) without its parameter or with an algorithm that does not allow it.HTTPSignatures::MissingHeaderA header the signature covers is not in the request, or one that must be covered is not.HTTPSignatures::MissingSignatureThe request has no Signature header, nor an Authorization header of the Signature scheme.HTTPSignatures::UnknownKeyNo key for the signature's keyId.HTTPSignatures::UnsupportedAlgorithmThe signature's algorithm is not one this cog verifies.HTTPSignatures::VerifiedWhat a verified request was signed with, and its body.
Constants
VERSION: String
The version of the cog.