1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
import { describe, expect, it } from "bun:test";
import app from "../app";
import { readFileSync } from "fs";
async function postJson(path: string, body: unknown, headers: Record<string, string> = {}) {
return app.fetch(
new Request(`http://localhost${path}`, {
method: "POST",
headers: { "content-type": "application/json", ...headers },
body: JSON.stringify(body),
})
);
}
describe("POST /api/repos requires authentication", () => {
it("rejects an anonymous caller with 401, not 400/500", async () => {
const res = await postJson("/api/repos", {
name: "pwned",
owner: "someoneelse",
});
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error).toBe("Authentication required");
});
it("rejects before parsing the body, so a malformed body still 401s", async () => {
const res = await app.fetch(
new Request("http://localhost/api/repos", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{not json",
})
);
expect(res.status).toBe(401);
});
it("an invalid bearer token does not pass as authenticated", async () => {
const res = await postJson(
"/api/repos",
{ name: "pwned" },
{ authorization: "Bearer glc_deadbeefdeadbeefdeadbeefdeadbeef" }
);
expect(res.status).toBe(401);
});
});
describe("POST /api/setup is first-run only", () => {
it("404s on an instance that already has users", async () => {
const res = await postJson("/api/setup", {
username: "squatter",
email: "a@b.c",
repoName: "x",
});
expect([404, 503]).toContain(res.status);
expect(res.status).not.toBe(200);
});
});
describe("the namespace check itself", () => {
const SRC = readFileSync("src/routes/api.ts", "utf8");
const handler = SRC.slice(
SRC.indexOf('api.post("/repos"'),
SRC.indexOf('api.get("/repos")') > 0
? SRC.indexOf('api.get("/repos")')
: SRC.indexOf('api.get("/users/:username/repos"')
);
it("forces the owner to the authenticated user", () => {
expect(handler).toContain("body.owner = viewer.username");
});
it("refuses a mismatched owner rather than silently rewriting it", () => {
expect(handler).toContain("body.owner !== viewer.username");
expect(handler).toContain("403");
});
});
|