Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/bruno-converters/tests/common/diff-kind.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Kinds of structural diff produced when comparing two collections during a round-trip test
// (e.g. Postman -> Bruno -> Postman).
//
// NODE_ONLY_IN_ORIGINAL -> a node exists only in the original collection
// NODE_ONLY_IN_ROUNDTRIP -> a node exists only in the round-tripped collection
// TYPE_MISMATCH -> the node exists on both sides but its type differs
// KEY_MISSING_IN_ROUNDTRIP -> a field present in the original was dropped on round-trip
// KEY_ONLY_IN_ROUNDTRIP -> a field absent in the original was added on round-trip
// VALUE_MISMATCH -> a field exists on both sides but its value differs
export const DiffKind = Object.freeze({
NODE_ONLY_IN_ORIGINAL: 'node-only-in-original',
NODE_ONLY_IN_ROUNDTRIP: 'node-only-in-roundtrip',
TYPE_MISMATCH: 'type-mismatch',
KEY_MISSING_IN_ROUNDTRIP: 'key-missing-in-roundtrip',
KEY_ONLY_IN_ROUNDTRIP: 'key-only-in-roundtrip',
VALUE_MISMATCH: 'value-mismatch'
});
153 changes: 153 additions & 0 deletions packages/bruno-converters/tests/postman/round-trip/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
# Round-trip conversion tests

This directory tests conversion **fidelity** by sending a real collection through both converters and
comparing the result against the input:

```
Postman export ──postmanToBruno──▶ Bruno collection ──brunoToPostman──▶ Postman export
(input) (output)
└──────────────────── compared, subtree by subtree ──────────────────┘
```
Comment thread
morsh-bruno marked this conversation as resolved.
Resolved

Currently only the **auth** subtree is covered ([`auth.spec.js`](./auth.spec.js)), but the harness is
built so other subtrees (body, headers, scripts, params, …) can be added as sibling files with no new
plumbing. See [Extending](#extending) below.

---

## Why round-trip, and why this direction

The per-converter unit specs (`process-auth`, `request-auth`, `bruno-to-postman`, …) each exercise
**one** converter in isolation and assert a hand-written expected object. That has two blind spots:

1. **Asymmetry between the two converters** — a field renamed on import (`tokenName` → `credentialsId`)
but not renamed back on export is invisible to a one-sided test. A round-trip is the only thing that
exercises both mappings against each other.
2. **Circular expectations** — a hand-written "expected" object is only as correct as the author's
reading of the converter. If you misread it, the test encodes the misreading.

We focus on **Postman → Bruno → Postman** (not Bruno → Postman → Bruno) because that is the direction
where a **real exported `.postman_collection.json`** is the input. Real exports carry the exact key
names, the full v2.1 array-backed auth format, and even fields Bruno doesn't model — ground truth that
a hand-built object can't reproduce.

---

## Why the fixture approach

Tests are **data-driven off the files in [`fixtures/`](./fixtures)**. Every `*.postman_collection.json`
is discovered automatically and run through the round-trip. This is deliberate:

- **No hand-written expected values.** The input fixture's own auth is the source of truth — the test
asserts the output equals the input (minus documented exceptions), so adding coverage is "drop a
file", not "write an expectation".
- **Real-world shape.** Fixtures are actual Postman exports, so they include the quirks (omitted
defaults, extra keys, ordering) that synthetic objects miss.

### Extending

- **More auth coverage:** export a collection of the desired auth type from Postman, drop it into
`fixtures/`. It's picked up automatically. A new whitelist entry is only needed if it exercises a
field Bruno doesn't model yet (see below).
- **Another subtree** (e.g. body): add `body.spec.js` alongside `auth.spec.js`, reusing the same
fixtures. Factor the shared "walk + diff by node path" logic the way [`compare-auth.js`](./compare-auth.js)
does for auth, keeping each subtree's normalization rules in its own module.

---

## The whitelist and its categories

Comparison is **strict**: any difference in the auth subtree fails the test. Differences that are
expected today are recorded in `AUTH_ROUNDTRIP_WHITELIST` in [`auth.spec.js`](./auth.spec.js), each
tagged with a `category`. The category is the whole point — it separates "bug we haven't fixed" from
"working as intended":

| Category | Meaning | Trend | Action |
| --- | --- | --- | --- |
| **`feature-gap`** | Bruno has no field to hold this Postman value, so it's dropped on import. | **Should shrink** as Bruno adds support. | **This is the list to focus on.** Each entry is a concrete, user-visible data loss. |
| **`normalization`** | Intentional, semantically-lossless transformation. | **Permanent** — will never reach zero. | Leave alone. Documents *why* the round-trip isn't byte-identical. |

**Where to focus: the `feature-gap` count.** It's the number of Postman auth capabilities Bruno can't
represent. Driving it down is real product work; when a gap is filled, delete its whitelist entry and
the test stays green. The `normalization` entries are not a backlog — they're the documented contract
of what round-tripping intentionally changes.

### The two flavors of `normalization`

- **Grant-scoped pruning** (oauth2): Bruno stores grant-type-specific fields, so a field unused by the
grant (`authUrl` on a `client_credentials` grant, `username` on anything but `password`) is dropped.
These entries carry a `grantType` list and are accepted **only** for grants that don't use the field —
so the *same* drop on a grant that *does* use it (e.g. `authUrl` on `authorization_code`) still fails.
That keeps the exception tight instead of blanket-allowing the field to vanish.
- **Default materialization**: Postman omits a field and relies on a default; Bruno stores it
explicitly and re-emits it (apikey `in: header`, oauth1 `version`). Whitelisted only where **Bruno's
default equals Postman's default**, so materializing it changes nothing semantically.

### Whitelist entry matching

Each entry matches a diff on `(fixture, node, authType, key, kind)`:

- `fixture` and `node` accept `'*'` — a field-level gap that recurs across many requests/fixtures is
**one wildcard entry**, not dozens of near-duplicates.
- `grantType` (oauth2, optional) restricts an entry to specific grant types (grant-scoped pruning).
- Matching is **value-agnostic** (`kind` + `key`, never the value) so a whitelisted field tolerates any
value — we're asserting "this field is *expected* to differ", not pinning a specific value.

---

## Comparison mechanics (`compare-auth.js`)

### `stableStringify`

Auth values are compared by a **canonical stringification** — object keys sorted, array order
preserved — rather than by `JSON.stringify` or reference equality. Two reasons:

1. **Key order is not semantic.** Postman and Bruno emit auth params in different orders; a plain
string compare would flag every reorder as a diff. Sorting keys makes the compare structural.
2. **Nested values must compare by content.** The oauth2 `additionalParameters` arrays
(`authRequestParams` / `tokenRequestParams` / `refreshRequestParams`) are arrays of objects. We need
deep, order-insensitive-on-keys but order-*sensitive*-on-arrays comparison, which `stableStringify`
gives: object keys are sorted (order-insensitive), array element order is preserved (array order *is*
semantic for these params).

### `normalizeAuth` — array-backed → map

Postman's v2.1 auth is an array of `{key, value, type}`. We collapse it to a plain `{key: value}` map so
that (a) param ordering doesn't matter and (b) the `type` tag (always `'string'`/`'any'`, never
semantically meaningful) doesn't create false diffs. Missing auth normalizes to `null` so "no auth"
compares equal on both sides.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

### `absent === ""` collapse

An absent key and an empty-string value are treated as **equal**. Postman treats a missing auth param as
unset, and `brunoToPostman` drops empty params on export — so `state: ""` disappearing on round-trip is a
lossless no-op, not a diff. Collapsing this structurally (rather than whitelisting each empty field)
keeps the whitelist focused on real differences and avoids churn when a fixture's empty fields change.
Confirmed safe: Postman's importer defaults any missing auth param, so omitting empties never errors.

### `grantType` on oauth2 diffs

Each oauth2 diff is tagged with the node's grant type (from the original, falling back to the
round-tripped side). This is what lets grant-scoped-pruning whitelist entries be conditional — the diff
carries enough context to say "dropped `authUrl`, and this was a `client_credentials` grant, so it's
fine."

### Node-path walk

`collectAuthNodes` walks the whole collection — collection-level auth, folder-level auth, and
request-level auth — keying each by a stable path (`collection`, `collection/Folder`,
`collection/Folder/Request`). Comparison is per-node by path, so a request that gains or loses auth, or
inherits differently, is caught rather than averaged away.

---

## Running

```bash
# from packages/bruno-converters
npx jest tests/postman/round-trip/auth.spec.js
```

On failure, each un-whitelisted diff prints a readable line — `DROPPED` (Bruno lost a field),
`ADDED` (Bruno emitted a field Postman didn't), or `CHANGED` (value differs) — so you can tell at a
glance whether it's a new feature gap to whitelist or a real regression to fix.
137 changes: 137 additions & 0 deletions packages/bruno-converters/tests/postman/round-trip/auth.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import fs from 'fs';
import path from 'path';
import postmanToBruno from '../../../src/postman/postman-to-bruno';
import brunoToPostman from '../../../src/postman/bruno-to-postman';
import { diffAuthNodes } from './compare-auth';
import { DiffKind } from '../../common/diff-kind';

/**
* Round-trip auth fidelity: Postman -> Bruno -> Postman.
*
* Every real Postman export in ./fixtures is imported to Bruno and exported back to Postman; the
* auth subtree of the result is compared against the auth subtree of the original export. This is
* the direction where a real-world Postman file matters, because the *input* shape then matches
* exactly what Postman emits (real key names, extra keys, v2.1 array format) instead of an
* approximation hand-written in a test.
*
* Comparison is STRICT: any difference in the auth subtree is a failure. Some differences are
* expected today. Those are recorded in AUTH_ROUNDTRIP_WHITELIST below with a category:
* - category 'feature-gap' -> Bruno can't represent this Postman field yet; SHOULD shrink as
* gaps are filled. This is the number to drive toward zero.
* - category 'normalization' -> intentional & permanent (default materialization, grant-scoped
* pruning); will NOT shrink.
* (Empty-value differences are handled structurally in compare-auth.js — absent == "" — and never
* reach the whitelist.)
*
* Whitelist entry matching:
* - fixture / node accept the literal value or '*' (wildcard) so a field-level gap that recurs
* across many nodes/fixtures is one entry, not dozens.
* - grantType (oauth2 only, optional): the diff is accepted ONLY when the node's grant type is in
* this list. This is how grant-scoped pruning is bounded — dropping authUrl is fine for
* client_credentials, but the SAME drop on an authorization_code grant is a real failure.
* - matching is value-agnostic (kind + key), so a whitelisted field tolerates any value.
*
* To add coverage: drop another *.postman_collection.json into ./fixtures — it is picked up
* automatically. New whitelist entries are only needed if it exercises an unmodelled field.
*/

const FIXTURES_DIR = path.join(__dirname, 'fixtures');

const AUTH_TYPES = Object.freeze({
BASIC: 'basic',
BEARER: 'bearer',
AWSV4: 'awsv4',
APIKEY: 'apikey',
DIGEST: 'digest',
NTLM: 'ntlm',
OAUTH1: 'oauth1',
OAUTH2: 'oauth2',
EDGEGRID: 'edgegrid',
NOAUTH: 'noauth'
});

// Shape: { fixture, node, authType, key, kind, category, reason, grantType? }
// fixture/node support '*'. grantType (array) restricts an oauth2 entry to those grant types.
const AUTH_ROUNDTRIP_WHITELIST = [
// --- feature-gap: Bruno does not model these Postman fields yet (drive this list to zero) ---
// oauth1: Bruno models currently don't support the following.
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH1, key: 'addEmptyParamsToSign', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no oauth1 addEmptyParamsToSign field' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH1, key: 'disableHeaderEncoding', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no oauth1 disableHeaderEncoding field' },
// digest: Bruno models only support username/password; the rest of Postman's digest params are dropped.
{ fixture: '*', node: '*', authType: AUTH_TYPES.DIGEST, key: 'algorithm', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no digest algorithm field' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.DIGEST, key: 'nonce', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no digest nonce field' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.DIGEST, key: 'nonceCount', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no digest nonceCount field' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.DIGEST, key: 'realm', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no digest realm field' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.DIGEST, key: 'qop', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no digest qop field' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.DIGEST, key: 'clientNonce', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no digest client nonce field' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.DIGEST, key: 'opaque', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no digest opaque field' },
// ntlm: Bruno models support username/password/domain only.
{ fixture: '*', node: '*', authType: AUTH_TYPES.NTLM, key: 'workstation', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no ntlm workstation field' },
// oauth2: Bruno models currently don't support the following.
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH2, key: 'useBrowser', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no oauth2 useBrowser field' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH2, key: 'code_verifier', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no oauth2 code_verifier (PKCE) field' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH2, key: 'challengeAlgorithm', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, category: 'feature-gap', reason: 'Bruno has no oauth2 code verifier - challenge algorithm' },

// --- normalization: grant-scoped pruning (accepted ONLY for grants that don't use the field) ---
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH2, key: 'authUrl', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, grantType: ['client_credentials', 'password_credentials'], category: 'normalization', reason: 'authorizationUrl is unused by client_credentials/password grants, so Bruno drops it' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH2, key: 'redirect_uri', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, grantType: ['client_credentials', 'password_credentials'], category: 'normalization', reason: 'callbackUrl is unused by client_credentials/password grants, so Bruno drops it' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH2, key: 'username', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, grantType: ['client_credentials', 'authorization_code', 'authorization_code_with_pkce', 'implicit'], category: 'normalization', reason: 'username is used only by the password grant, so Bruno drops it elsewhere' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH2, key: 'password', kind: DiffKind.KEY_MISSING_IN_ROUNDTRIP, grantType: ['client_credentials', 'authorization_code', 'authorization_code_with_pkce', 'implicit'], category: 'normalization', reason: 'password is used only by the password grant, so Bruno drops it elsewhere' },

// --- normalization: default materialization (Postman omits, defaults it; Bruno emits explicitly) ---
{ fixture: '*', node: '*', authType: AUTH_TYPES.APIKEY, key: 'in', kind: DiffKind.KEY_ONLY_IN_ROUNDTRIP, category: 'normalization', reason: 'Postman defaults apikey placement to header when omitted; Bruno emits it' },
{ fixture: '*', node: '*', authType: AUTH_TYPES.OAUTH1, key: 'version', kind: DiffKind.KEY_ONLY_IN_ROUNDTRIP, category: 'normalization', reason: 'Bruno materializes default version=1.0 (== Postman default)' }
];

const readJson = (file) => JSON.parse(fs.readFileSync(path.join(FIXTURES_DIR, file), 'utf8'));

const matchesField = (w, v) => w === '*' || w === v;

const isWhitelisted = (fixture, diff) =>
AUTH_ROUNDTRIP_WHITELIST.some(
(w) =>
matchesField(w.fixture, fixture)
&& matchesField(w.node, diff.node)
&& (w.authType ?? null) === (diff.authType ?? null)
&& (w.key ?? null) === (diff.key ?? null)
&& w.kind === diff.kind
&& (!w.grantType || (diff.grantType != null && w.grantType.includes(diff.grantType)))
);

const fixtureFiles = fs.readdirSync(FIXTURES_DIR).filter((f) => f.endsWith('.postman_collection.json'));
Comment thread
morsh-bruno marked this conversation as resolved.
Resolved

// Readable one-liner for each diff, used in the failure message.
const formatDiff = (d) => {
const loc = `[${d.node}]${d.key ? ` ${d.authType}.${d.key}` : d.authType ? ` (${d.authType})` : ''}`;
switch (d.kind) {
case DiffKind.KEY_MISSING_IN_ROUNDTRIP:
return `${loc} DROPPED on round-trip (original=${JSON.stringify(d.original)})`;
case DiffKind.KEY_ONLY_IN_ROUNDTRIP:
return `${loc} ADDED on round-trip (roundtrip=${JSON.stringify(d.roundTripped)})`;
case DiffKind.VALUE_MISMATCH:
return `${loc} CHANGED original=${JSON.stringify(d.original)} roundtrip=${JSON.stringify(d.roundTripped)}`;
case DiffKind.TYPE_MISMATCH:
return `${loc} TYPE CHANGED original=${JSON.stringify(d.original)} roundtrip=${JSON.stringify(d.roundTripped)}`;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
default:
return `${loc} ${d.kind}`;
}
};

describe('auth round-trip (Postman -> Bruno -> Postman)', () => {
it.each(fixtureFiles)('preserves the auth subtree of %s', async (fixture) => {
const original = readJson(fixture);
const { collection } = await postmanToBruno(original);
const roundTripped = brunoToPostman(collection);

const allDiffs = diffAuthNodes(original, roundTripped);
const unexpected = allDiffs.filter((d) => !isWhitelisted(fixture, d));

if (unexpected.length) {
// Surface a human-readable summary alongside Jest's structured dump.
console.log(`\n[${fixture}] ${unexpected.length} un-whitelisted auth diff(s):`);
unexpected.forEach((d) => console.log(' ' + formatDiff(d)));
}

expect(unexpected).toEqual([]);
});
});
Loading
Loading