javascript.lang.correctness.no-stringify-keys.no-stringify-keys

profile photo of semgrepsemgrep
Author
unknown
Download Count*

JSON stringify does not produce a stable key ordering, and should not be relied on for producing object keys. Consider using json-stable-stringify instead.

Run Locally

Run in CI

Defintion

rules:
  - id: no-stringify-keys
    mode: taint
    pattern-sources:
      - pattern: JSON.stringify(...)
      - patterns:
          - pattern-inside: |
              $STRINGIFY = JSON.stringify
              ...
              $STRINGIFY(...)
          - pattern: $STRINGIFY(...)
    pattern-sinks:
      - pattern: $OBJECT[...]
    message: JSON stringify does not produce a stable key ordering, and should not
      be relied on for producing object keys. Consider using
      json-stable-stringify instead.
    languages:
      - javascript
      - typescript
    severity: WARNING
    metadata:
      category: correctness
      references:
        - https://www.npmjs.com/package/json-stable-stringify
        - https://stackoverflow.com/a/16168003
      technology:
        - javascript
        - typescript
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

no-stringify-keys.jsx

import stableStringify from "json-stable-stringify";

const stringify = JSON.stringify;

// ruleid:no-stringify-keys
hashed[JSON.stringify(obj)] = obj;

// ruleid:no-stringify-keys
const result = hashed[JSON.stringify(obj)];

// ruleid:no-stringify-keys
hashed[stringify(obj)] = obj;

// ruleid:no-stringify-keys
const result = hashed[stringify(obj)];

//ok
hashed[stableStringify(obj)] = obj;

//ok
const result = hashed[stableStringify(obj)]