All resources
Web Security9 min read

Normalize URIs before comparing or signing them

A standards-aware guide to hostnames, paths, percent encoding, ports, and canonical forms at security boundaries.

A practical PingFlow guide for developers working at the boundary between systems.

At a glance

Key takeaways

  • Start with the boundary
  • Model the system before choosing a tool
  • Design for failure, misuse, and change
In this guide

Start with the boundary

Normalize URIs before comparing or signing them is easiest to get right when the boundary is named before the implementation begins. Decide which system owns the decision, which inputs are trusted, what the caller can observe, and what must remain private. That framing prevents a local optimization from quietly becoming an undocumented protocol.

Two strings can describe the same resource, while two strings that look similar can resolve to different resources. Redirect allowlists, signature bases, cache keys, and authorization checks fail when parsing and normalization happen in different layers. Define the URI components and canonical form your protocol actually needs instead of inventing a string comparison.

Model the system before choosing a tool

Parse with a standards-based URI library, then compare scheme, host, port, path, query, and fragment according to the boundary's rules. Normalize host casing and default ports intentionally, preserve path semantics where a server distinguishes them, and decide whether percent-encoded delimiters are decoded before comparison. Keep the canonical form alongside the original for diagnostics.

Write the model down as a small state diagram or table before selecting a library. Identify the durable state, the derived state, and the transitions that may be retried. This makes it easier to compare a managed service with an in-process implementation and to explain why a particular trade-off is acceptable for this workload.

Design for failure, misuse, and change

Double decoding, backslashes, dot segments, Unicode hostnames, userinfo, alternate ports, and an empty versus omitted query can change meaning. A proxy may normalize before the application sees a request. Signing one representation while serving another creates false failures or a signature that can be reused against a different path.

A resilient design assumes that inputs are incomplete, dependencies are slow, operators make mistakes, and requirements will change. Put limits at the boundary, return errors that a caller can act on, and preserve enough context to distinguish a bad request from an unavailable dependency. Avoid broad fallbacks that make an unsafe state look successful.

Implementation example

Create one canonicalization function per protocol and version it. Reject ambiguous inputs rather than applying a permissive guess. For signatures, define the exact bytes and encoding, including query ordering and repeated keys. For authorization, compare parsed components and trusted policy objects, not an attacker-controlled reserialized string.

Keep the first implementation narrow enough to review line by line. Make inputs, outputs, authorization context, and failure behavior explicit instead of hiding them behind a convenience helper. The example should be safe to run with synthetic data, emit a correlation identifier, and leave a durable artifact that another engineer can inspect after the request has finished.

text
parsed = URL(input)
canonical = origin + normalized_path + sorted_query
compare_components(canonical, policy)

Verify and troubleshoot

Test equivalent and non-equivalent forms, percent encodings, repeated parameters, Unicode, ports, dot segments, fragments, empty values, and proxy rewrites. Sign and verify through every deployment layer. Assert that a cache key, redirect decision, and authorization check agree on the destination.

Use a small test matrix that covers the ordinary path, an empty or missing input, a duplicate request, a timeout, a permission failure, and a version mismatch. Assert both the response and the side effects. When a test fails, compare the observed transition with the model rather than adding a retry or widening a timeout without evidence.

Operations and recovery

Monitor rejected normalization cases, signature mismatches by component, cache-key collisions, and proxy configuration changes. Keep a compatibility window when changing a canonical form and record which version produced a signature. During an incident, prefer rejecting ambiguous input over broadening the accepted grammar.

Give the operator a bounded recovery action: replay a safe event, rebuild a derived view, rotate a credential, drain a queue, or roll back a compatible revision. Record the owner, retention period, alert threshold, and rollback condition next to the implementation. A runbook is useful only when it can be followed without reconstructing the design from production logs.

A practical decision guide

For a small service, prefer the design with the fewest hidden states that still meets the web security requirement. Add a managed dependency when it removes a failure mode you can measure, not simply because it is popular. Keep the interface replaceable by isolating provider-specific code behind a narrow adapter and by testing the behavior your users depend on.

Revisit the decision when traffic shape, data sensitivity, team ownership, or recovery objectives change. A design that is excellent for a single tenant or a low-volume internal tool can be the wrong design for a public multi-tenant path. Record the assumptions so the next change starts with evidence rather than folklore.

An implementation checklist

Before publishing a change related to normalize uris before comparing or signing them, write down the input contract, authorization context, state transitions, limits, and user-visible errors. Identify the smallest synthetic dataset that demonstrates the normal path and the smallest dataset that demonstrates the dangerous path. Add a correlation ID to the example, make retries deliberate, and decide which artifacts can be retained for support without copying secrets or unnecessary personal data. This checklist is deliberately boring: repeatable release evidence is more valuable than a clever demo.

Use a disposable environment to exercise the implementation with realistic concurrency and a dependency failure. Compare the observed result with the contract, then record the measured latency, resource use, and recovery action. If a managed service or library is involved, pin its version and capture the relevant configuration. Ship behind a reversible change when the behavior is new, and schedule a follow-up review after real traffic reveals assumptions that a test fixture could not.

References and further reading

Use RFC 3986, the WHATWG URL standard, RFC 3987 for internationalized identifiers where applicable, and the signature specification for the protocol you implement. Test the runtime URL library against the actual proxy and database behavior.

Prefer primary protocol specifications, vendor security documentation, and measured behavior from a disposable environment. Read the failure and deprecation sections, not only the happy-path quick start. A short reference list attached to the code gives future maintainers a way to distinguish an intentional constraint from an accidental implementation detail.

Continue hands-on

Ready to inspect the problem?

Open the URL Parser

Keep exploring