116 lines · 5.3 KB
import { describe, expect, mock, test } from "bun:test";

mock.module("cloudflare:workers", () => ({
  env: { SECRETS_KEY: "test-secret", PUBLIC_URL: "https://forge.example.com" },
}));

const { renderMarkdown } = await import("./markdown");
const { verifyCamoPath } = await import("./camo-sign");

const context = { owner: "acme", repo: "app", ref: "main", basePath: "docs" };

function camoTargets(html: string): string[] {
  return [...html.matchAll(/src="(\/camo\/[^"]+)"/g)].map((match) => verifyCamoPath(match[1]) ?? "INVALID");
}

describe("renderMarkdown hardening", () => {
  test("external markdown images are rewritten to signed camo URLs", () => {
    const html = renderMarkdown("![x](https://evil.example/pixel.gif)", context);
    expect(html).not.toContain("https://evil.example/pixel.gif");
    expect(camoTargets(html)).toEqual(["https://evil.example/pixel.gif"]);
  });

  test("raw <img> and protocol-relative sources are proxied too", () => {
    const html = renderMarkdown('<img src="//tracker.example/p.png"><img src="http://a.example/b.jpg">', context);
    expect(camoTargets(html)).toEqual(["https://tracker.example/p.png", "http://a.example/b.jpg"]);
  });

  test("slashless and backslash external images are proxied, not loaded directly", () => {
    const html = renderMarkdown("![a](http:evil.example/a.gif) ![b](https:/evil.example/b.gif)", context);
    expect(html).not.toMatch(/src="https?:/);
    expect(camoTargets(html)).toEqual(["http://evil.example/a.gif", "https://evil.example/b.gif"]);
    const bare = renderMarkdown("![c](/\\evil.example/c.gif)", null);
    expect(bare).not.toContain('src="/\\evil');
  });

  test("entity-encoded raw image sources are decoded before the camo decision", () => {
    const html = renderMarkdown(
      '<img src="&#47;&#47;evil.example/x.gif"><img src="https&#58;//evil.example/y.gif">',
      null,
    );