|
1 | 1 | import { describe, expect, it } from "vitest"; |
| 2 | +import { faviconUrl } from "./favicon"; |
2 | 3 | import { |
3 | 4 | BASE_IMG_SRC_SOURCES, |
4 | 5 | buildImgSrcDirective, |
5 | 6 | parseCspImageOrigins, |
6 | 7 | withImgSrc, |
7 | 8 | } from "./cspImageOrigins"; |
8 | 9 |
|
| 10 | +/** True if a source expression in the directive would match the given image URL. */ |
| 11 | +function directivePermits(directive: string, imageUrl: string): boolean { |
| 12 | + const url = new URL(imageUrl); |
| 13 | + return directive |
| 14 | + .split(" ") |
| 15 | + .slice(1) |
| 16 | + .some((source) => { |
| 17 | + if (!source.startsWith("http")) return false; |
| 18 | + const parsed = new URL(source); |
| 19 | + if (parsed.protocol !== url.protocol || parsed.host !== url.host) return false; |
| 20 | + return parsed.pathname === "/" || parsed.pathname === url.pathname; |
| 21 | + }); |
| 22 | +} |
| 23 | + |
9 | 24 | describe("parseCspImageOrigins", () => { |
10 | 25 | it("accepts exact https origins, with or without a port", () => { |
11 | 26 | const { origins, rejected } = parseCspImageOrigins( |
@@ -75,12 +90,28 @@ describe("parseCspImageOrigins", () => { |
75 | 90 | }); |
76 | 91 |
|
77 | 92 | describe("buildImgSrcDirective", () => { |
78 | | - it("is self, data, blob and the SSO avatar hosts by default", () => { |
| 93 | + it("is self, data, blob, the SSO avatar hosts and the favicon endpoint by default", () => { |
79 | 94 | expect(buildImgSrcDirective()).toBe( |
80 | | - "img-src 'self' data: blob: https://avatars.githubusercontent.com https://lh3.googleusercontent.com" |
| 95 | + "img-src 'self' data: blob: https://avatars.githubusercontent.com https://lh3.googleusercontent.com https://www.google.com/s2/favicons" |
81 | 96 | ); |
82 | 97 | }); |
83 | 98 |
|
| 99 | + it("permits the org avatar URL the app actually stores", () => { |
| 100 | + expect(directivePermits(buildImgSrcDirective(), faviconUrl("example.com"))).toBe(true); |
| 101 | + }); |
| 102 | + |
| 103 | + it("permits nothing else on the favicon host", () => { |
| 104 | + expect(directivePermits(buildImgSrcDirective(), "https://www.google.com/beacon.png")).toBe( |
| 105 | + false |
| 106 | + ); |
| 107 | + }); |
| 108 | + |
| 109 | + it("permits both OAuth avatar hosts", () => { |
| 110 | + const directive = buildImgSrcDirective(); |
| 111 | + expect(directivePermits(directive, "https://avatars.githubusercontent.com/u/1?v=4")).toBe(true); |
| 112 | + expect(directivePermits(directive, "https://lh3.googleusercontent.com/a/abc=s96-c")).toBe(true); |
| 113 | + }); |
| 114 | + |
84 | 115 | it("has no wildcard host and no bare scheme host", () => { |
85 | 116 | const directive = buildImgSrcDirective(parseCspImageOrigins("https://sso.example.com").origins); |
86 | 117 | expect(directive).not.toContain("*"); |
|
0 commit comments