|
| 1 | +import { Effect, Exit } from "effect"; |
| 2 | +import { describe, expect, it } from "vitest"; |
| 3 | + |
| 4 | +import { |
| 5 | + type BearerIdentity, |
| 6 | + BearerVerifierService, |
| 7 | + StaticBearerVerifier, |
| 8 | + staticBearerVerifierLayer, |
| 9 | + TaggedUnauthenticated, |
| 10 | + UnauthenticatedError, |
| 11 | +} from "@arcp/core"; |
| 12 | + |
| 13 | +const ALICE: BearerIdentity = { principal: "alice" }; |
| 14 | + |
| 15 | +describe("staticBearerVerifierLayer (Effect surface)", () => { |
| 16 | + const table = new Map<string, BearerIdentity>([["tok-good", ALICE]]); |
| 17 | + const layer = staticBearerVerifierLayer(table); |
| 18 | + |
| 19 | + it("verifies a known token", async () => { |
| 20 | + const program = Effect.gen(function* () { |
| 21 | + const v = yield* BearerVerifierService; |
| 22 | + return yield* v.verify("tok-good"); |
| 23 | + }).pipe(Effect.provide(layer)); |
| 24 | + const identity = await Effect.runPromise(program); |
| 25 | + expect(identity).toEqual(ALICE); |
| 26 | + }); |
| 27 | + |
| 28 | + it("fails with TaggedUnauthenticated for unknown tokens", async () => { |
| 29 | + const program = Effect.gen(function* () { |
| 30 | + const v = yield* BearerVerifierService; |
| 31 | + return yield* v.verify("tok-bad"); |
| 32 | + }).pipe(Effect.provide(layer)); |
| 33 | + const exit = await Effect.runPromiseExit(program); |
| 34 | + expect(Exit.isFailure(exit)).toBe(true); |
| 35 | + if (Exit.isFailure(exit)) { |
| 36 | + const err = exit.cause._tag === "Fail" ? exit.cause.error : undefined; |
| 37 | + expect(err).toBeInstanceOf(TaggedUnauthenticated); |
| 38 | + } |
| 39 | + }); |
| 40 | +}); |
| 41 | + |
| 42 | +describe("BearerVerifierService default provider", () => { |
| 43 | + it("rejects every token until a layer is supplied", async () => { |
| 44 | + const program = Effect.gen(function* () { |
| 45 | + const v = yield* BearerVerifierService; |
| 46 | + return yield* v.verify("anything"); |
| 47 | + }).pipe(Effect.provide(BearerVerifierService.Default)); |
| 48 | + const exit = await Effect.runPromiseExit(program); |
| 49 | + expect(Exit.isFailure(exit)).toBe(true); |
| 50 | + }); |
| 51 | +}); |
| 52 | + |
| 53 | +describe("StaticBearerVerifier (legacy Promise surface)", () => { |
| 54 | + it("resolves known tokens to the identity", async () => { |
| 55 | + const v = new StaticBearerVerifier( |
| 56 | + new Map([["tok-good", ALICE]]), |
| 57 | + ); |
| 58 | + await expect(v.verify("tok-good")).resolves.toEqual(ALICE); |
| 59 | + }); |
| 60 | + |
| 61 | + it("throws UnauthenticatedError for unknown tokens", async () => { |
| 62 | + const v = new StaticBearerVerifier(new Map()); |
| 63 | + await expect(v.verify("nope")).rejects.toBeInstanceOf( |
| 64 | + UnauthenticatedError, |
| 65 | + ); |
| 66 | + }); |
| 67 | +}); |
0 commit comments