| 1 |
import { expect, test } from "bun:test"; |
| 2 |
import { sign, who, whoAtTty } from "./who.ts"; |
| 3 |
|
| 4 |
const KEY = "a-key-only-the-forge-holds"; |
| 5 |
const later = Date.now() + 60_000; |
| 6 |
const request = (identity: string, signature: string): Request => |
| 7 |
new Request("http://app/", { |
| 8 |
headers: { "x-forge-identity": identity, "x-forge-signature": signature }, |
| 9 |
}); |
| 10 |
|
| 11 |
test("a signed identity is who it says", () => { |
| 12 |
const identity = `u1|alice|admin|${later}`; |
| 13 |
expect(who(request(identity, sign(identity, KEY)), KEY)).toEqual({ |
| 14 |
role: "admin", |
| 15 |
id: "u1", |
| 16 |
name: "alice", |
| 17 |
}); |
| 18 |
}); |
| 19 |
|
| 20 |
test("a forged, tampered, expired or unsigned identity is anonymous", () => { |
| 21 |
const identity = `u1|alice|admin|${later}`; |
| 22 |
expect(who(request(identity, sign(identity, "another key")), KEY)).toEqual({ |
| 23 |
role: "anon", |
| 24 |
}); |
| 25 |
expect( |
| 26 |
who(request(`u1|alice|admin|${later + 1}`, sign(identity, KEY)), KEY), |
| 27 |
).toEqual({ role: "anon" }); |
| 28 |
const expired = `u1|alice|user|${Date.now() - 1}`; |
| 29 |
expect(who(request(expired, sign(expired, KEY)), KEY)).toEqual({ |
| 30 |
role: "anon", |
| 31 |
}); |
| 32 |
const odd = `u1|alice|owner|${later}`; |
| 33 |
expect(who(request(odd, sign(odd, KEY)), KEY)).toEqual({ role: "anon" }); |
| 34 |
expect(who(new Request("http://app/"), KEY)).toEqual({ role: "anon" }); |
| 35 |
|
| 36 |
expect(who(request(identity, sign(identity, KEY)), "")).toEqual({ |
| 37 |
role: "anon", |
| 38 |
}); |
| 39 |
}); |
| 40 |
|
| 41 |
test("the terminal trusts its environment", () => { |
| 42 |
expect(whoAtTty({})).toEqual({ role: "anon" }); |
| 43 |
expect(whoAtTty({ FORGE_APP_USER: "alice" })).toEqual({ |
| 44 |
role: "user", |
| 45 |
id: "alice", |
| 46 |
name: "alice", |
| 47 |
}); |
| 48 |
expect( |
| 49 |
whoAtTty({ |
| 50 |
FORGE_APP_USER: "alice", |
| 51 |
FORGE_APP_USER_ID: "u1", |
| 52 |
FORGE_APP_USER_ROLE: "admin", |
| 53 |
}), |
| 54 |
).toEqual({ |
| 55 |
role: "admin", |
| 56 |
id: "u1", |
| 57 |
name: "alice", |
| 58 |
}); |
| 59 |
}); |