Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
175 changes: 175 additions & 0 deletions apps/api/src/api/routes/jira-attachment-targets.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { describe, expect, it } from "bun:test";
import {
attachmentContentUrl,
isAtlassianHost,
isAtlassianUrl,
parseAttachmentId,
resolveCloudId,
safeContentDisposition,
} from "./jira-attachment-targets";

describe("parseAttachmentId", () => {
it("accepts a numeric id", () => {
expect(parseAttachmentId("41356")).toBe("41356");
});

it("rejects everything that could steer the upstream path", () => {
for (const bad of [
undefined,
"",
"../../secret",
"41356/../../x",
"41356?x=1",
"https://evil.test/x",
"41356 ",
"abc",
"-1",
"4e3",
"1".repeat(21),
]) {
expect(parseAttachmentId(bad)).toBeNull();
}
});
});

describe("isAtlassianHost", () => {
it("accepts Atlassian hosts and their subdomains", () => {
for (const host of [
"atlassian.com",
"atlassian.net",
"api.atlassian.com",
"api.media.atlassian.com",
"osklenbr.atlassian.net",
"API.Atlassian.COM",
]) {
expect(isAtlassianHost(host)).toBe(true);
}
});

it("rejects look-alikes that a suffix match without a dot boundary would pass", () => {
for (const host of [
"atlassian.com.evil.test",
"notatlassian.com",
"evilatlassian.net",
"atlassian.co",
"",
]) {
expect(isAtlassianHost(host)).toBe(false);
}
});
});

describe("isAtlassianUrl", () => {
it("is false for a null, empty, or unparseable url", () => {
expect(isAtlassianUrl(null)).toBe(false);
expect(isAtlassianUrl(undefined)).toBe(false);
expect(isAtlassianUrl("")).toBe(false);
expect(isAtlassianUrl("not a url")).toBe(false);
});

it("is true for the MCP connection url and a media redirect", () => {
expect(isAtlassianUrl("https://mcp.atlassian.com/v1/mcp/authv2")).toBe(
true,
);
expect(
isAtlassianUrl("https://api.media.atlassian.com/file/abc/binary?token=x"),
).toBe(true);
});

it("is false for a non-Atlassian connection — the credential-leak guard", () => {
expect(isAtlassianUrl("https://mcp.notion.com/mcp")).toBe(false);
expect(isAtlassianUrl("https://evil.test/?x=atlassian.com")).toBe(false);
});

it("is false for a non-http scheme", () => {
expect(isAtlassianUrl("file:///etc/passwd")).toBe(false);
expect(isAtlassianUrl("ftp://api.atlassian.com/x")).toBe(false);
});
});

describe("resolveCloudId", () => {
const one = [{ id: "cd4e853c-d029-41c2-907e-bef24605b986" }];
const two = [...one, { id: "11111111-2222-3333-4444-555555555555" }];

it("uses the only site when none was requested", () => {
expect(resolveCloudId(null, one)).toEqual({
ok: true,
cloudId: "cd4e853c-d029-41c2-907e-bef24605b986",
});
});

it("accepts a requested site the token can see", () => {
expect(resolveCloudId(two[1]!.id, two)).toEqual({
ok: true,
cloudId: two[1]!.id,
});
});

it("refuses a site the token cannot see", () => {
const out = resolveCloudId("99999999-0000-0000-0000-000000000000", two);
expect(out.ok).toBe(false);
if (!out.ok) expect(out.status).toBe(403);
});

it("refuses to guess between several sites", () => {
const out = resolveCloudId(null, two);
expect(out.ok).toBe(false);
if (!out.ok) {
expect(out.status).toBe(400);
// The caller has to be able to act on the error.
expect(out.error).toContain(two[0]!.id);
expect(out.error).toContain(two[1]!.id);
}
});

it("refuses when the token reaches nothing", () => {
const out = resolveCloudId(null, []);
expect(out.ok).toBe(false);
if (!out.ok) expect(out.status).toBe(403);
});

it("ignores blank ids rather than selecting one", () => {
const out = resolveCloudId(null, [{ id: "" }]);
expect(out.ok).toBe(false);
});
});

describe("attachmentContentUrl", () => {
it("builds the cloud REST url", () => {
expect(attachmentContentUrl("cloud-1", "41356")).toBe(
"https://api.atlassian.com/ex/jira/cloud-1/rest/api/3/attachment/content/41356",
);
});

it("encodes the cloudId so a hostile value cannot open a new path segment", () => {
expect(attachmentContentUrl("a/../b", "1")).toBe(
"https://api.atlassian.com/ex/jira/a%2F..%2Fb/rest/api/3/attachment/content/1",
);
});
});

describe("safeContentDisposition", () => {
it("keeps a plain upstream filename", () => {
expect(
safeContentDisposition('attachment; filename="antes-desktop.png"', "9"),
).toBe('attachment; filename="antes-desktop.png"');
});

it("falls back to the attachment id when there is no filename", () => {
expect(safeContentDisposition(null, "41356")).toBe(
'attachment; filename="attachment-41356"',
);
});

it("drops a filename carrying a path, a quote, or a newline", () => {
for (const hostile of [
'attachment; filename="../../etc/passwd"',
'attachment; filename="a\\"; rm -rf /"',
'attachment; filename="a\nb.png"',
]) {
expect(safeContentDisposition(hostile, "7")).toBe(
'attachment; filename="attachment-7"',
);
}
});
});
158 changes: 158 additions & 0 deletions apps/api/src/api/routes/jira-attachment-targets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/**
* Pure addressing + validation helpers for the Jira attachment proxy
* (`jira-attachments.ts`). Split out so the unit test can cover the guards
* without loading the route — and with it Better Auth and the storage layer.
*
* Every function here decides where a request may go or what may be echoed
* back, so each one fails closed on input it does not recognize.
*/

/** Where Atlassian's cloud REST + OAuth resource discovery live. */
export const ATLASSIAN_API_HOST = "api.atlassian.com";

/**
* Ceiling on a proxied attachment. Jira's own default limit is 10MB but it is
* configurable per site, and the point of the cap is the pod's disk and this
* process's memory, not Jira's policy.
*
* ponytail: enforced from `content-length` only, then streamed. A response that
* lies about its length gets through — that is Atlassian lying to us, not the
* threat this bounds. Wrap the stream in a counting transform if that changes.
*/
export const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;

/** Bounded so a wedged upstream can't hold a request open indefinitely. */
export const UPSTREAM_TIMEOUT_MS = 30_000;

/**
* Numeric Jira attachment id, or null. Digits only: this value lands in the
* upstream URL path, so anything else — a traversal segment, a query, an
* absolute URL — must not survive. Pure; the unit test owns the shape.
*/
export function parseAttachmentId(raw: string | undefined): string | null {
return raw && /^[0-9]{1,20}$/.test(raw) ? raw : null;
}

/**
* True for a host that belongs to Atlassian. Used twice, for two different
* reasons: to confirm a connection really is Atlassian before its token is
* spent, and to confirm the 303 from the content endpoint lands on Atlassian's
* media CDN rather than somewhere the redirect could carry the request.
*
* Suffix match on a dot boundary — `atlassian.com.evil.test` must not pass.
*/
export function isAtlassianHost(host: string): boolean {
const h = host.toLowerCase();
return (
h === "atlassian.com" ||
h === "atlassian.net" ||
h.endsWith(".atlassian.com") ||
h.endsWith(".atlassian.net")
);
}

/** True when `url` parses and its host is Atlassian's. Pure. */
export function isAtlassianUrl(url: string | null | undefined): boolean {
if (!url) return false;
try {
const parsed = new URL(url);
return (
(parsed.protocol === "https:" || parsed.protocol === "http:") &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: When an Atlassian connection URL or attachment redirect uses HTTP, this guard allows it and the route can perform credential discovery/refresh or fetch the media over plaintext. Require HTTPS for both connection validation and redirect validation.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/api/routes/jira-attachment-targets.ts, line 60:

<comment>When an Atlassian connection URL or attachment redirect uses HTTP, this guard allows it and the route can perform credential discovery/refresh or fetch the media over plaintext. Require HTTPS for both connection validation and redirect validation.</comment>

<file context>
@@ -0,0 +1,158 @@
+  try {
+    const parsed = new URL(url);
+    return (
+      (parsed.protocol === "https:" || parsed.protocol === "http:") &&
+      isAtlassianHost(parsed.hostname)
+    );
</file context>
Suggested change
(parsed.protocol === "https:" || parsed.protocol === "http:") &&
parsed.protocol === "https:" &&

isAtlassianHost(parsed.hostname)
);
} catch {
return false;
}
}

/** One entry of Atlassian's `/oauth/token/accessible-resources`. */
export interface AccessibleResource {
id: string;
url?: string;
name?: string;
}

export type CloudIdResolution =
| { ok: true; cloudId: string }
| { ok: false; status: 400 | 403; error: string };

/**
* Pick the Jira site to read from: the requested `cloudId` if the token can
* actually see it, or the only one when there is exactly one and the caller
* named none.
*
* Validating against the token's own accessible-resources list — rather than
* shape-checking a caller-supplied id — is what keeps the upstream URL from
* being steerable: an id the token cannot see is refused instead of fetched.
* Ambiguity is an error, never a guess: silently picking the first of several
* sites would serve BR data for a GLOBAL card and look like a Jira bug.
*
* Pure; the unit test owns every branch.
*/
export function resolveCloudId(
requested: string | null | undefined,
accessible: readonly AccessibleResource[],
): CloudIdResolution {
const ids = accessible.map((r) => r.id).filter((id) => id.length > 0);
if (ids.length === 0) {
return {
ok: false,
status: 403,
error:
"This connection's Atlassian token can reach no sites. Reconnect it.",
};
}
if (requested) {
if (!ids.includes(requested)) {
return {
ok: false,
status: 403,
error: `cloudId ${requested} is not reachable with this connection's token`,
};
}
return { ok: true, cloudId: requested };
}
if (ids.length > 1) {
return {
ok: false,
status: 400,
error: `This connection reaches ${ids.length} Atlassian sites — pass ?cloudId= one of: ${ids.join(", ")}`,
};
}
// Non-null: length is exactly 1 here, but noUncheckedIndexedAccess doesn't
// know that.
const only = ids[0];
return only
? { ok: true, cloudId: only }
: { ok: false, status: 403, error: "No usable Atlassian site" };
}

/** The attachment-content endpoint for one site. Pure. */
export function attachmentContentUrl(
cloudId: string,
attachmentId: string,
): string {
return `https://${ATLASSIAN_API_HOST}/ex/jira/${encodeURIComponent(
cloudId,
)}/rest/api/3/attachment/content/${encodeURIComponent(attachmentId)}`;
}

/**
* `content-disposition` safe to echo back: keep the upstream's filename when it
* is a plain one, otherwise name the file after the attachment id. The header
* reaches a shell that may redirect it to disk, so a quoted path or a newline
* does not get to pass through.
*
* Pure; the unit test owns it.
*/
export function safeContentDisposition(
upstream: string | null,
attachmentId: string,
): string {
const name = upstream?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i)?.[1];
const safe =
name && /^[A-Za-z0-9._ -]{1,120}$/.test(name)
? name
: `attachment-${attachmentId}`;
return `attachment; filename="${safe}"`;
}
Loading
Loading