Skip to content
smallPict
Start free

Engineering9 min read

One API, Seven SDKs: How We Keep Request Signatures Consistent

Seven official SDKs, one HMAC signing scheme, and the test vectors that keep them in sync, including the gaps we found while auditing them.

smallPict Team

Engineering

Seven official SDKs, one signing scheme, and a test suite that has to agree across seven different crypto libraries. This is how the smallPict SDKs stay in sync, what the tests actually assert today, and the gaps we found while auditing them.

If you ship an API with more than one client library, the real risk is not the endpoint list. It is the small canonical details: how a timestamp is formatted, how the body is hashed, which part of the URL is signed, how an error message quotes a secret. Those drift silently, one language at a time, and they only show up when someone's upload fails with a 401 at 2 a.m.

The seven SDKs

All of them expose the same four operations: optimize, getQuota, purgeCdn and validateKey, spelled the way each language expects (get_quota in Python and Ruby, GetQuota in Go). Same arguments, same returns, so a snippet can move between them with little translation.

LanguagePackageTransport
Node.js / TypeScript@smallpict/sdk (npm)native fetch + Web Crypto, runs on Node 18+, Bun, Workers
Pythonsmallpict (PyPI)httpx, sync and async clients
PHPsmallpict/smallpict-php (Packagist)native cURL, PHP 7.4 to 8.5
Gogithub.com/smallpict/smallpict-gostandard library only, context.Context on every call
Rustsmallpict (crates.io)rustls-tls, tokio async plus a blocking client
Rubysmallpict (RubyGems)Ruby 3.2+, SmallPict.configure block
Javaapp.smallpict:smallpict-java (Maven Central)Java 17+ HttpClient, sync plus CompletableFuture

Seven languages means seven HMAC implementations. Node uses Web Crypto, Python uses hmac with hashlib, PHP uses hash_hmac, Go uses crypto/hmac, Rust uses the hmac and sha2 crates, Ruby uses OpenSSL::HMAC, Java uses javax.crypto.Mac. If any one of those is called with the wrong key encoding, or with a hex string instead of bytes, the request fails and the error points at the API, not at the client.

The part that must not drift: the string to sign

Every request carries a signature computed over a canonical string built from four pieces, joined by newlines:

TEXT
METHOD \n PATH \n TIMESTAMP \n SHA256_HEX(body)

PATH is the request path without the query string. An empty body has a fixed hash, so the empty string is never special-cased per language. The same applies to a JSON body: the bytes that get hashed have to be the bytes that get sent, which is why the SDKs serialize once and reuse the buffer instead of serializing twice.

The test for this exists in all seven repositories, and it asserts an exact string, not a shape:

TEXT
POST/v1/optimize1716301234e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

That last line is the SHA-256 of an empty body, and it is a constant in each SDK: EMPTY_SHA256 in Node, Python, PHP, Rust and Java, EmptySHA256 in Go, SmallPict::Crypto::EMPTY_SHA256 in Ruby. If a language ever formatted the timestamp as milliseconds, inserted a trailing newline, or hashed a string instead of bytes, this assertion breaks in that repository alone, before any request leaves a test runner.

Two hash values are pinned in all seven:

  • sha256("hello world") must equal b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
  • the empty body hash must equal e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

The first one catches a hasher that silently returns base64, or an implementation that mixes up UTF-8 and UTF-16 input. The second one catches a client that treats a null body as "null".

Where the tests disagreed, and how we found it

Auditing the crypto tests, we noticed that the HMAC call itself was asserted differently in different languages. Four of the seven (Python, Rust, Ruby and Java) assert a published known answer, RFC 4231 test case 2:

TEXT
HMAC-SHA256(key="Jefe", data="what do ya want for nothing?")5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843

The other three (Node, PHP and Go) test their signer against our own fixtures only. A test like that still passes when the HMAC runs over the wrong bytes but produces a well-formed hex string of the right length. The RFC vector is an external number that does not depend on our code, so it catches a wrong key encoding, a truncated digest, or an accidental SHA-1.

That is the kind of gap that never shows up in a green build. Nothing was broken in those three repositories, but their tests were weaker than they looked. The fix is one assertion per repository, and this post is the public note that the gap existed.

Secrets in error messages

An HMAC scheme has two secrets in play, the API key and the secret key, and both can end up inside error strings when a request fails. Logging that string verbatim writes a credential into your logs.

Every SDK runs error messages through a sanitizer, and the tests feed it a message containing sp_sdk_1234567890abcdef1234567890abcdef and sec_secret123456. In six of the seven (Node, Python, PHP, Rust, Ruby and Java), the test asserts the exact redacted form: the key shortened to sp_sdk_123...cdef. Rust goes one step further and asserts that its secret wrapper prints [REDACTED] in both {} and {:?} formatting.

Go's test is the weaker one here: it checks that the message changed and is not empty, but not what it changed into. Same kind of gap as the RFC vector, and the same kind of one-assertion fix.

What the test suites cover outside crypto

Keeping signatures identical is necessary but not sufficient. A few behaviours are part of the contract in every language:

  • Folders: every repository has tests for grouping uploads by folder and purging a single folder.
  • Retries: a 429 or a 5xx is retried with backoff (honouring Retry-After); any other 4xx is not retried at all. The one 429 that is not retried is purge_rate_limited, an hourly limit a retry seconds later cannot clear. A client that retries a signature failure turns one misconfigured secret into a rate-limited account.
  • Compression modes: mode takes lossy, extreme or lossless in every SDK. In the WordPress plugin the same three appear as Balanced, Smallest files and Pixel-perfect.
  • File limits: a file above the plan's per-file limit is answered 400 file_too_large, and every SDK raises it as a validation error with the limit and an upgrade link in its details.

Reproducing the signature by hand

When a 401 arrives, the fastest way to find out whether the client or the server is wrong is to compute the signature outside the SDK. The recipe needs only openssl and a terminal.

Take the request you wanted to send: method, path without the query string, timestamp in seconds, and the exact body bytes. Then:

Shell
BODY_HASHprintf '%s' "$BODY"  openssl dgst -sha256 -hex  awk '{print $2}'STSprintf '%s\n%s\n%s\n%s' "$METHOD" "$PATH" "$TIMESTAMP" "$BODY_HASH"printf '%s' "$STS"  openssl dgst -sha256 -hmac "$SECRET_KEY" -hex

The last value is the signature the client should have sent. If your SDK produced a different one, compare the two intermediate values first. A body hash that differs usually means the JSON was re-serialized with a different key order or extra whitespace. A different string to sign almost always means the timestamp or the path changed after signing.

The path is the easy one to get wrong. The Ruby SDK used to sign its status poll with the query string included (/v1/optimize/status?job_id=...). It only worked because the server tolerated it, and the fix was to sign the path alone, as the contract says. A client that builds the string before it settles the final URL, for example when a base URL or a query is added afterwards, signs one path and requests another.

How the contract is versioned

The signing rules live in the API documentation, and each SDK has a test file that mirrors them. When the contract changes, each repository fails its own test until it matches. That is the whole mechanism: no shared code generation, no cross-language wrapper, just the same assertions written seven times in seven idioms.

We keep it that way for debuggability. A Go developer opening crypto_test.go sees the expected string to sign in the same repository as the implementation, without a generator or a template in between. A PHP developer reading tests/CryptoTest.php sees the same constants. When something breaks, the failing assertion sits next to the code that caused it, in the language the reader already knows.

The tradeoff is real: seven copies means seven places to update, and nothing enforces that on its own. What enforces it is each repository's test suite plus the habit of comparing the assertions across them, which is how the missing RFC 4231 vector in three of the seven, and the weaker sanitizer test in Go, were found.

What we do not claim

We make no speed or compression claims in this post. Everything here is about code that either passes or fails in a test runner, which anyone can check by reading the repositories.

We also do not claim that seven SDKs are seven products. They are one contract with seven bindings, and the contract is the string to sign, the empty body hash and the error format. When those three agree, the rest is language ergonomics.

Try it on one call

Each SDK authenticates with an API key and a secret key. The free Developer Sandbox (100 requests a month, up to 5 MB per file, JPEG XL included) is enough to run the whole signing path:

Shell
npm install @smallpict/sdk
TypeScript
import { SmallPictClient } from '@smallpict/sdk';
const client = new SmallPictClient({  apiKey: process.env.SMALLPICT_API_KEY as string,  secretKey: process.env.SMALLPICT_SECRET_KEY as string,});
if (!(await client.validateKey())) throw new Error('Check the API key and the secret key');console.log(await client.getQuota());

validateKey makes one signed call and returns false when the key or the signature is wrong, before you send a single image. It is the cheapest test in the whole API, and the first one we run in every language. Everything else is in the SDK docs and the API reference.

Written by smallPict Team

Engineering

We build image conversion and CDN delivery for websites and apps.

Try it on your own images.

100 MB a month free. About two minutes to set up on WordPress.

More on image performance, Core Web Vitals and cloud storage.

All articles

Engineering2 min read

One API Request, Several Image Formats

smallPict's API can now return WebP, AVIF, JPEG XL, JPEG and PNG from a single upload and job. Here is how target_formats works and what it costs.