Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
fix(common): agent Set-Cookie header fallback (#6586)
Shreyas5f2e1f25f956
diff --git a/packages/hoppscotch-common/src/services/__tests__/cookie-jar.service.spec.ts b/packages/hoppscotch-common/src/services/__tests__/cookie-jar.service.spec.tsindex 02294964a..364ba75d0 100644--- a/packages/hoppscotch-common/src/services/__tests__/cookie-jar.service.spec.ts+++ b/packages/hoppscotch-common/src/services/__tests__/cookie-jar.service.spec.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it } from "vitest"+import { beforeEach, describe, expect, it, vi } from "vitest"import { TestContainer } from "dioc/testing"import { Cookie } from "@hoppscotch/data"@@ -399,6 +399,48 @@ describe("CookieJarService", () => {expect(service.cookieJar.value.size).toBe(0)})+ it("rejects a Domain the response host does not domain-match", async () => {+ await service.extractFromResponse(+ [{ name: "sid", value: "attacker", domain: "example.com" }],+ new URL("https://attacker.invalid/")+ )+ expect(service.cookieJar.value.size).toBe(0)+ expect(+ service.getCookiesForURL(new URL("https://example.com/"))+ ).toHaveLength(0)+ })++ it("accepts a parent Domain from a subdomain host", async () => {+ await service.extractFromResponse(+ [{ name: "sid", value: "1", domain: "example.com" }],+ new URL("https://api.example.com/")+ )+ expect(+ service.getCookiesForURL(new URL("https://example.com/"))+ ).toHaveLength(1)+ })++ it("rejects a partial IP suffix as a Domain attribute", async () => {+ await service.extractFromResponse(+ [{ name: "sid", value: "1", domain: "1.1" }],+ new URL("https://192.168.1.1/")+ )+ expect(service.cookieJar.value.size).toBe(0)+ expect(+ service.getCookiesForURL(new URL("https://10.0.1.1/"))+ ).toHaveLength(0)+ })++ it("accepts a Domain attribute equal to the IP host", async () => {+ await service.extractFromResponse(+ [{ name: "sid", value: "1", domain: "192.168.1.1" }],+ new URL("https://192.168.1.1/")+ )+ expect(+ service.getCookiesForURL(new URL("https://192.168.1.1/"))+ ).toHaveLength(1)+ })+it("falls back to default-path when the Path attribute does not start with /", async () => {await service.extractFromResponse([{ name: "a", value: "1", path: "foo" }],@@ -409,6 +451,104 @@ describe("CookieJarService", () => {})})+ describe("captureResponseCookies header fallback", () => {+ it("parses the Set-Cookie header when structured cookies are undefined", async () => {+ await service.captureResponseCookies(+ { headers: { "set-cookie": "sid=abc123; Path=/; HttpOnly" } },+ "https://example.com/"+ )+ const stored = service.getCookiesForURL(new URL("https://example.com/"))+ expect(stored).toHaveLength(1)+ expect(stored[0].name).toBe("sid")+ expect(stored[0].value).toBe("abc123")+ })++ it("resolves Max-Age into an expiry on the header fallback", async () => {+ await service.captureResponseCookies(+ { headers: { "set-cookie": "sid=abc; Max-Age=60; Path=/" } },+ "https://example.com/"+ )+ const stored = service.getCookiesForURL(new URL("https://example.com/"))+ expect(stored).toHaveLength(1)+ expect(stored[0].expires).toBeDefined()+ expect(new Date(stored[0].expires!).getTime()).toBeGreaterThan(Date.now())+ })++ it("keeps a percent-encoded value undecoded on the header fallback", async () => {+ await service.captureResponseCookies(+ { headers: { "set-cookie": "sid=abc%20123; Path=/" } },+ "https://example.com/"+ )+ const stored = service.getCookiesForURL(new URL("https://example.com/"))+ expect(stored).toHaveLength(1)+ expect(stored[0].value).toBe("abc%20123")+ })++ it("splits newline-joined Set-Cookie headers the agent relay concatenates", async () => {+ await service.captureResponseCookies(+ { headers: { "set-cookie": "a=1; Path=/\nb=2; Path=/" } },+ "https://example.com/"+ )+ const stored = service.getCookiesForURL(new URL("https://example.com/"))+ expect(stored).toHaveLength(2)+ expect(stored.map((c) => c.name).sort()).toEqual(["a", "b"])+ })++ it("drops an existing cookie on a Max-Age=0 fallback capture", async () => {+ // Frozen so the read happens at the same instant as the+ // capture, which is the only window in which an expiry equal+ // to the capture time still reads as live.+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"))+ try {+ await service.captureResponseCookies(+ { headers: { "set-cookie": "sid=abc; Path=/" } },+ "https://example.com/"+ )+ await service.captureResponseCookies(+ { headers: { "set-cookie": "sid=abc; Max-Age=0; Path=/" } },+ "https://example.com/"+ )+ expect(+ service.getCookiesForURL(new URL("https://example.com/"))+ ).toHaveLength(0)+ } finally {+ vi.useRealTimers()+ }+ })++ it("rejects a cross-domain Domain on the header fallback", async () => {+ await service.captureResponseCookies(+ {+ headers: {+ "set-cookie": "sid=attacker; Domain=example.com; Path=/",+ },+ },+ "https://attacker.invalid/"+ )+ expect(service.cookieJar.value.size).toBe(0)+ expect(+ service.getCookiesForURL(new URL("https://example.com/"))+ ).toHaveLength(0)+ })++ it("does not re-parse headers when cookies is a defined empty array", async () => {+ await service.captureResponseCookies(+ { cookies: [], headers: { "set-cookie": "sid=abc123; Path=/" } },+ "https://example.com/"+ )+ expect(service.cookieJar.value.size).toBe(0)+ })++ it("does nothing when cookies is undefined and no Set-Cookie header is present", async () => {+ await service.captureResponseCookies(+ { headers: { "content-type": "application/json" } },+ "https://example.com/"+ )+ expect(service.cookieJar.value.size).toBe(0)+ })+ })+describe("serializeCookieHeader", () => {it("joins `name=value` pairs with `; `", () => {expect(diff --git a/packages/hoppscotch-common/src/services/cookie-jar.service.ts b/packages/hoppscotch-common/src/services/cookie-jar.service.tsindex f0b18a3b0..a073bc18d 100644--- a/packages/hoppscotch-common/src/services/cookie-jar.service.ts+++ b/packages/hoppscotch-common/src/services/cookie-jar.service.ts@@ -4,6 +4,7 @@ import { parseString as setCookieParse } from "set-cookie-parser-es"import { Cookie } from "@hoppscotch/data"import * as E from "fp-ts/Either"import { Store } from "~/kernel/store"+import type { SetCookieValues } from "set-cookie-parser-es"// Cookies are per-organization state, so they persist through the// org-scoped `Store` (`~/kernel/store`), which resolves to@@ -441,6 +442,32 @@ export class CookieJarService extends Service {return stripped.toLowerCase()}+ // Whether a response from `host` may set a cookie for `domain`.+ // RFC 6265 5.3 step 5 treats an IP-literal host as an address+ // rather than as a label chain, so only an exact match is allowed+ // there. Running `domainMatches` on `192.168.1.1` would accept+ // `Domain=1.1` as a parent, and the cookie would then attach to+ // the unrelated address `10.0.1.1`, which shares the suffix and+ // nothing else. Everything else is the 5.1.3 comparison, so a+ // subdomain setting its parent domain still passes.+ private hostAcceptsDomain(host: string, domain: string): boolean {+ if (this.isIPLiteral(host)) {+ return host === domain+ }+ return this.domainMatches(host, domain)+ }++ // `URL.hostname` renders an IPv6 address bracketed, so the two+ // forms are recognized separately. An IPv4 check on the four+ // dotted fields is enough here, since a host that reached this+ // point already parsed as a URL.+ private isIPLiteral(host: string): boolean {+ if (host.startsWith("[") && host.endsWith("]")) {+ return true+ }+ return /^\d{1,3}(\.\d{1,3}){3}$/.test(host)+ }+// Canonicalizes a cookie domain that came from a Set-Cookie// `Domain` attribute. Calls `canonStoreDomain` then rejects a// single-label domain that would let the cookie attach to every@@ -496,6 +523,21 @@ export class CookieJarService extends Service {let domain: string | nullif (c.domain) {domain = this.canonAttrDomain(c.domain)+ // RFC 6265 5.3 step 6 rejects a `Domain` attribute the+ // request host does not domain-match. Without it a response+ // from one host writes a cookie stored under another, and+ // the next request to that other host attaches it, which is+ // a cross-origin write for every capture path that reaches+ // here. `api.example.com` setting `Domain=example.com` still+ // passes, since `domainMatches` is the same 5.1.3 comparison+ // the read side uses.+ if (domain !== null && !this.hostAcceptsDomain(requestHost, domain)) {+ console.warn(+ "[CookieJar] Dropped cookie with a cross-domain Domain:",+ c.domain+ )+ continue+ }} else {domain = this.canonHostOnly(requestHost)}@@ -822,10 +864,97 @@ export class CookieJarService extends Service {request.headers["Cookie"] = serialized}+ // Maps the `set-cookie-parser-es` SameSite union (lowercase or a+ // bare boolean) onto the `@hoppscotch/data` casing+ // `extractFromResponse` expects. An unrecognized or boolean value+ // yields undefined so the extractor applies its "Lax" default.+ private normalizeSameSite(+ raw: SetCookieValues["sameSite"]+ ): ResponseCookie["sameSite"] {+ if (typeof raw !== "string") {+ return undefined+ }+ switch (raw.toLowerCase()) {+ case "strict":+ return "Strict"+ case "lax":+ return "Lax"+ case "none":+ return "None"+ default:+ return undefined+ }+ }++ // Parses raw Set-Cookie header strings into the response-cookie+ // objects `extractFromResponse` canonicalizes. The agent relay joins+ // multiple Set-Cookie headers with newlines (see the agent+ // interceptor's multiHeaders split), so each line is parsed on its+ // own. Lines the parser cannot resolve to a name are dropped rather+ // than stored as `undefined=...`. Returns undefined when there is no+ // Set-Cookie header to read, empty value included, and an array+ // otherwise. `decodeValues` is off so a percent-encoded value is+ // stored exactly as the relay's structured path stores it, since a+ // decoded value would be re-emitted unencoded by+ // `serializeCookieHeader`.+ private cookiesFromSetCookieHeader(+ headers: Record<string, string> | undefined+ ): ResponseCookie[] | undefined {+ if (!headers) {+ return undefined+ }+ const key = Object.keys(headers).find(+ (h) => h.toLowerCase() === "set-cookie"+ )+ if (key === undefined) {+ return undefined+ }+ const raw = headers[key]+ if (!raw) {+ return undefined+ }+ const cookies: ResponseCookie[] = []+ for (const line of raw+ .split("\n")+ .map((s) => s.trim())+ .filter(Boolean)) {+ const parsed = setCookieParse(line, { decodeValues: false })+ if (!parsed.name) {+ continue+ }+ cookies.push({+ name: parsed.name,+ value: parsed.value,+ domain: parsed.domain,+ path: parsed.path,+ // RFC 6265 4.1.2.2, Max-Age takes precedence over Expires, and+ // the structured relay path has already resolved it into an+ // expiry by the time cookies arrive that way. Converting here+ // keeps a `Max-Age` cookie from being stored as a session+ // cookie, and lets `Max-Age=0` expire an entry on capture.+ // A non-positive age resolves one millisecond behind the+ // capture instant rather than onto it, since `pruneExpired`+ // and the read filter both keep an entry while its expiry+ // equals the current time, which would carry a deleted+ // cookie into a read taken in that same millisecond.+ expires:+ parsed.maxAge !== undefined && Number.isFinite(parsed.maxAge)+ ? new Date(+ Date.now() + (parsed.maxAge > 0 ? parsed.maxAge * 1000 : -1)+ )+ : parsed.expires,+ secure: parsed.secure,+ httpOnly: parsed.httpOnly,+ sameSite: this.normalizeSameSite(parsed.sameSite),+ })+ }+ return cookies+ }+// The one shared receive path. Captures structured cookies the// relay parsed out of the response into the jar.public async captureResponseCookies(- response: { cookies?: ResponseCookie[] },+ response: { cookies?: ResponseCookie[]; headers?: Record<string, string> },requestUrl: string | undefined): Promise<void> {if (!requestUrl) {@@ -835,6 +964,21 @@ export class CookieJarService extends Service {if (url === null) {return}+ // Agent binaries built against a relay revision without+ // `parse_cookies` return no structured `cookies` while the+ // Set-Cookie headers are still present in `headers`. Parsing the+ // header string in that case keeps the jar working on older agent+ // builds. The fallback runs only when `cookies` is absent, since a+ // present array (even empty) is the relay's own answer that the+ // response had no cookies, and re-parsing headers would risk+ // double-counting.+ if (response.cookies === undefined) {+ await this.extractFromResponse(+ this.cookiesFromSetCookieHeader(response.headers),+ url+ )+ return+ }await this.extractFromResponse(response.cookies, url)}}