auth.test.ts
This file
Path
apps/platform/test/auth.test.ts
484 lines · 14.8 KiB · TypeScript
Last changed by
Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–26why, one step back1import { describe, expect, it } from "@effect/vitest";2import { Contracts } from "@repo/protocol/contracts";3import { AskId, Handle, ProjectName } from "@repo/protocol/ids";4import {5 Anonymous,6 CurrentPrincipal,7 Person,8 Unauthenticated,9} from "@repo/protocol/principal";10import type { Principal } from "@repo/protocol/principal";11import { UnknownProject } from "@repo/protocol/refusal";12import { Effect, Exit, Layer, Option, Redacted, Ref, Schema } from "effect";1314import { Sessions } from "../src/sessions.ts";15import { firstOf } from "../src/sessions/first-of.ts";16import { MemorySessions } from "../src/sessions/memory.ts";17import { sessionTable, TableSessions } from "../src/sessions/table.ts";18import {19 noProjects,20 origin,21 rpcClient,22 served,23 toolCall,24 toolResult,25} from "./harness.ts";26Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 27why, one step back27const project = ProjectName.make("alice/datekit");Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 28–148why, one step back2829const alice = Handle.make("alice");3031const operator = Handle.make("oscabriel");3233const aliceToken = "alice-token-0123456789abcdef01234567";3435const operatorToken = "operator-token-0123456789abcdef0123";3637const sessions = MemorySessions.layer({ [aliceToken]: alice });3839const metadataUrl = `${origin}/.well-known/oauth-protected-resource`;4041const isPerson = Schema.is(Person);4243const noting = (seen: Ref.Ref<readonly Principal[]>) => {44 const note = Effect.flatMap(Effect.service(CurrentPrincipal), (principal) =>45 Ref.update(seen, (principals) => [...principals, principal])46 );4748 return Layer.mergeAll(49 noProjects,50 Contracts.toLayerHandler("listAsks", () => Effect.as(note, { asks: [] })),51 Contracts.toLayerHandler("status", () =>52 Effect.andThen(note, Effect.service(CurrentPrincipal)).pipe(53 Effect.flatMap((principal) =>54 isPerson(principal)55 ? Effect.succeed({56 answers: [],57 claims: [],58 handle: principal.handle,59 })60 : Effect.die("status is for people signed in")61 )62 )63 )64 );65};6667const counting = Effect.gen(function* () {68 const verified = yield* Ref.make(0);6970 const inner = MemorySessions.service({ [aliceToken]: alice });7172 const layer = Layer.succeed(73 Sessions,74 Sessions.of({75 verify: (token) =>76 Effect.andThen(77 Ref.update(verified, (count) => count + 1),78 inner.verify(token)79 ),80 })81 );8283 return { layer, verified };84});8586const challengeOf = (response: Response) => ({87 challenge: response.headers.get("www-authenticate"),88 status: response.status,89});9091describe("discovering how to sign in", () => {92 it.effect(93 "names the platform as its own protected resource and authorization server, without a credential",94 () =>95 Effect.gen(function* () {96 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));9798 const response = yield* fetch(new Request(metadataUrl));99100 expect(response.status).toBe(200);101 expect(yield* Effect.promise(() => response.json())).toStrictEqual({102 authorization_servers: [origin],103 bearer_methods_supported: ["header"],104 resource: origin,105 });106 })107 );108109 it.effect(110 "never turns away /health or the sign-in paths, whatever credential they carry",111 () =>112 Effect.gen(function* () {113 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));114115 const stale = { authorization: "Bearer a-token-nobody-knows" };116117 const client = { authorization: `Basic ${btoa("cli:secret")}` };118119 const responses = [120 yield* fetch(new Request(`${origin}/health`, { headers: stale })),121 yield* fetch(new Request(metadataUrl, { headers: stale })),122 yield* fetch(123 new Request(`${origin}/.well-known/oauth-authorization-server`, {124 headers: stale,125 })126 ),127 yield* fetch(128 new Request(`${origin}/token`, { headers: client, method: "POST" })129 ),130 yield* fetch(new Request(`${origin}/authorize`, { headers: stale })),131 yield* fetch(new Request(`${origin}/signup`, { headers: stale })),132 yield* fetch(133 new Request(`${origin}/oauth/callback`, { headers: stale })134 ),135 ];136137 expect(responses.map(({ status }) => status)).not.toContain(401);138 })139 );140141 it.effect(142 "leaves git's paths to the gateway, whatever credential they carry",143 () =>144 Effect.gen(function* () {145 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));146147 const response = yield* fetch(148 new Request(Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 149why, one step back149 `${origin}/alice/datekit.git/info/refs?service=git-upload-pack`,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 150–202why, one step back150 { headers: { authorization: "Bearer a-token-nobody-knows" } }151 )152 );153154 expect(response.headers.get("www-authenticate") ?? "").not.toContain(155 "Bearer"156 );157 })158 );159});160161describe("reading without signing in", () => {162 it.effect("lists a project's asks as anyone", () =>163 Effect.gen(function* () {164 const seen = yield* Ref.make<readonly Principal[]>([]);165166 const { handler } = yield* served(Layer.mergeAll(noting(seen), sessions));167168 const anyone = yield* rpcClient(handler);169170 expect(yield* Effect.exit(anyone.listAsks({ project }))).toStrictEqual(171 Exit.succeed({ asks: [] })172 );173 expect(yield* Ref.get(seen)).toStrictEqual([Anonymous.make({})]);174 })175 );176177 it.effect(178 "reads the front page, an ask and a verdict as anyone: each reaches its contract",179 () =>180 Effect.gen(function* () {181 const { handler } = yield* served(Layer.mergeAll(noProjects, sessions));182183 const anyone = yield* rpcClient(handler);184185 const ask = AskId.make("fix-parser");186187 expect(yield* Effect.exit(anyone.frontPage({}))).toStrictEqual(188 Exit.succeed({ entries: [] })189 );190 expect(yield* Effect.exit(anyone.listProjects({}))).toStrictEqual(191 Exit.succeed({ projects: [] })192 );193 expect(194 yield* Effect.flip(anyone.showAsk({ ask, project }))195 ).toStrictEqual(new UnknownProject({ project }));196 expect(197 yield* Effect.flip(anyone.verdict({ ask, project }))198 ).toStrictEqual(new UnknownProject({ project }));199 })200 );201202 it.effect(Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
line 203why, one step back203 "refuses a signed-in or maintainer contract to anyone as Unauthenticated",Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 204–484why, one step back204 () =>205 Effect.gen(function* () {206 const seen = yield* Ref.make<readonly Principal[]>([]);207208 const { handler } = yield* served(209 Layer.mergeAll(noting(seen), sessions)210 );211212 const anyone = yield* rpcClient(handler);213214 expect(yield* Effect.exit(anyone.status({}))).toStrictEqual(215 Exit.fail(new Unauthenticated())216 );217 expect(yield* Effect.exit(anyone.today({}))).toStrictEqual(218 Exit.fail(new Unauthenticated())219 );220 expect(yield* Ref.get(seen)).toStrictEqual([]);221 })222 );223});224225describe("the 401", () => {226 it.effect(227 "turns away an RPC call whose bearer the platform does not know",228 () =>229 Effect.gen(function* () {230 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));231232 const response = yield* fetch(233 new Request(`${origin}/rpc`, {234 body: "[]",235 headers: {236 authorization: "Bearer a-token-nobody-knows",237 "content-type": "application/json",238 },239 method: "POST",240 })241 );242243 expect(challengeOf(response)).toStrictEqual({244 challenge: `Bearer error="invalid_token", resource_metadata="${metadataUrl}"`,245 status: 401,246 });247 })248 );249250 it.effect(251 "asks MCP for a credential, naming where to learn how to get one",252 () =>253 Effect.gen(function* () {254 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));255256 const response = yield* fetch(toolCall("listAsks", { project }));257258 expect(challengeOf(response)).toStrictEqual({259 challenge: `Bearer resource_metadata="${metadataUrl}"`,260 status: 401,261 });262 })263 );264265 it.effect(266 "turns away an RPC call whose credential is not a bearer token, with no error code",267 () =>268 Effect.gen(function* () {269 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));270271 const response = yield* fetch(272 new Request(`${origin}/rpc`, {273 body: "[]",274 headers: {275 authorization: `Basic ${btoa(`alice:${aliceToken}`)}`,276 "content-type": "application/json",277 },278 method: "POST",279 })280 );281282 expect(challengeOf(response)).toStrictEqual({283 challenge: `Bearer resource_metadata="${metadataUrl}"`,284 status: 401,285 });286 })287 );288289 it.effect("asks for a credential however MCP's path is spelled", () =>290 Effect.gen(function* () {291 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));292293 const call = toolCall("listProjects", {});294295 const body = yield* Effect.promise(() => call.text());296297 const statuses = yield* Effect.forEach(298 ["/mcp/", "//mcp", "/MCP", "/mc%70", "/mcp;x"],299 (path) =>300 Effect.map(301 fetch(302 new Request(`${origin}${path}`, {303 body,304 headers: call.headers,305 method: "POST",306 })307 ),308 ({ status }) => status309 )310 );311312 expect(statuses).toStrictEqual([401, 401, 401, 401, 401]);313 })314 );315316 it.effect(317 "runs a call as the credential its request was let in with, never one the call adds",318 () =>319 Effect.gen(function* () {320 const seen = yield* Ref.make<readonly Principal[]>([]);321322 const { fetch } = yield* served(323 Layer.mergeAll(324 noting(seen),325 MemorySessions.layer({326 [aliceToken]: alice,327 [operatorToken]: operator,328 })329 )330 );331332 const message = `{"_tag":"Request","id":"1","tag":"status","payload":{},"headers":[["authorization","Bearer ${aliceToken}"]]}`;333334 const status = (headers: Readonly<Record<string, string>>) =>335 fetch(336 new Request(`${origin}/rpc`, {337 body: message,338 headers: { "content-type": "application/json", ...headers },339 method: "POST",340 })341 ).pipe(342 Effect.flatMap((response) => Effect.promise(() => response.text()))343 );344345 expect(yield* status({})).toContain('"_tag":"Unauthenticated"');346 expect(347 yield* status({ authorization: `Bearer ${operatorToken}` })348 ).toContain('"_tag":"Unauthenticated"');349 expect(yield* Ref.get(seen)).toStrictEqual([]);350 })351 );352});353354describe("verifying a token", () => {355 it.effect(356 "verifies an MCP request's token once, and calls as its person",357 () =>358 Effect.gen(function* () {359 const seen = yield* Ref.make<readonly Principal[]>([]);360361 const { layer, verified } = yield* counting;362363 const { fetch } = yield* served(Layer.mergeAll(noting(seen), layer));364365 const result = yield* toolResult(366 yield* fetch(toolCall("status", {}, aliceToken))367 );368369 expect(result).toStrictEqual({370 isError: false,371 json: { answers: [], claims: [], handle: alice },372 });373 expect(yield* Ref.get(seen)).toStrictEqual([374 Person.make({ handle: alice }),375 ]);376 expect(yield* Ref.get(verified)).toBe(1);377 })378 );379380 it.effect("verifies an RPC call's token once, and calls as its person", () =>381 Effect.gen(function* () {382 const seen = yield* Ref.make<readonly Principal[]>([]);383384 const { layer, verified } = yield* counting;385386 const { handler } = yield* served(Layer.mergeAll(noting(seen), layer));387388 const asAlice = yield* rpcClient(handler, aliceToken);389390 expect(yield* Effect.exit(asAlice.status({}))).toStrictEqual(391 Exit.succeed({ answers: [], claims: [], handle: alice })392 );393 expect(yield* Ref.get(seen)).toStrictEqual([394 Person.make({ handle: alice }),395 ]);396 expect(yield* Ref.get(verified)).toBe(1);397 })398 );399});400401describe("sessions", () => {402 it.effect(403 "lets a named session call as its handle, and the operator as theirs",404 () =>405 Effect.gen(function* () {406 const seen = yield* Ref.make<readonly Principal[]>([]);407408 const table = TableSessions([409 { handle: operator, token: Redacted.make(operatorToken) },410 { handle: alice, token: Redacted.make(aliceToken) },411 ]);412413 const { handler } = yield* served(Layer.mergeAll(noting(seen), table));414415 const asAlice = yield* rpcClient(handler, aliceToken);416 const asOperator = yield* rpcClient(handler, operatorToken);417418 expect(yield* Effect.exit(asAlice.status({}))).toStrictEqual(419 Exit.succeed({ answers: [], claims: [], handle: alice })420 );421 expect(yield* Effect.exit(asOperator.status({}))).toStrictEqual(422 Exit.succeed({ answers: [], claims: [], handle: operator })423 );424425 expect(yield* Ref.get(seen)).toStrictEqual([426 Person.make({ handle: alice }),427 Person.make({ handle: operator }),428 ]);429 })430 );431432 it.effect("takes the first entry when two name one token", () =>433 Effect.gen(function* () {434 const table = sessionTable([435 { handle: operator, token: Redacted.make(operatorToken) },436 { handle: alice, token: Redacted.make(operatorToken) },437 ]);438439 expect(yield* table.verify(operatorToken)).toStrictEqual(440 Option.some(Person.make({ handle: operator }))441 );442 })443 );444445 it.effect("asks each in turn and takes the first that knows the token", () =>446 Effect.gen(function* () {447 const asked = yield* Ref.make<readonly string[]>([]);448449 const named = (name: string, tokens: Record<string, Handle>) => {450 const inner = MemorySessions.service(tokens);451452 return Sessions.of({453 verify: (token) =>454 Effect.andThen(455 Ref.update(asked, (names) => [...names, name]),456 inner.verify(token)457 ),458 });459 };460461 const both = firstOf([462 named("a", { "shared-token": alice }),463 named("b", { "b-token": operator, "shared-token": operator }),464 ]);465466 expect(yield* both.verify("shared-token")).toStrictEqual(467 Option.some(Person.make({ handle: alice }))468 );469 expect(yield* both.verify("b-token")).toStrictEqual(470 Option.some(Person.make({ handle: operator }))471 );472 expect(yield* both.verify("nobody-token")).toStrictEqual(Option.none());473 expect(yield* Ref.get(asked)).toStrictEqual(["a", "a", "b", "a", "b"]);474 })475 );476477 it.effect("knows nobody when it asks nobody", () =>478 Effect.gen(function* () {479 expect(yield* firstOf([]).verify(aliceToken)).toStrictEqual(480 Option.none()481 );482 })483 );484});