Skip to content

Using timingSafeEqual examples are not safe? #23623

@imcotton

Description

@imcotton

Existing documentation URL(s)

What changes are you suggesting?

The purpose of timing safety is defeated by returning earlier on two different lengths.

It should be handled somewhat like:

  async fetch(req: Request, env: Environment) {
    if (!env.MY_SECRET_VALUE) {
      return new Response("Missing secret binding", { status: 500 });
    }

    const authToken = req.headers.get("Authorization") || "";

    const encoder = new TextEncoder();

    const user = encoder.encode(authToken);
    const safe = encoder.encode(env.MY_SECRET_VALUE);

    const succeed = user.byteLength === safe.byteLength
      ?  crypto.subtle.timingSafeEqual(user, safe)
      : !crypto.subtle.timingSafeEqual(user, user)
    ;

    if (succeed) {
      return new Response("Welcome!");
    }

    return new Response("Unauthorized", { status: 401 });

  }

Additional information

No response

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions