97 lines
6.9 KiB
TypeScript
97 lines
6.9 KiB
TypeScript
/** Genuine Fastify/JWT provenance; only the host execution is a test double.
|
|
* Configured pools cannot dispatch anything except the exact revocation read. */
|
|
import assert from "node:assert/strict"
|
|
import Fastify, { type FastifyInstance } from "fastify"
|
|
import { SignJWT } from "jose"
|
|
import { mkdtemp, realpath, rm } from "node:fs/promises"
|
|
import { tmpdir } from "node:os"
|
|
import { join, dirname, basename } from "node:path"
|
|
import { spawn } from "node:child_process"
|
|
import { fileURLToPath } from "node:url"
|
|
const local = process.env.MM_TEST_POLL_HTTP_LOCAL === "true"
|
|
process.env.NODE_ENV = "test"; process.env.AUTH_REQUIRED = String(!local)
|
|
process.env.AUTH_JWT_SECRET = "owned-poll-http-acceptance-secret"
|
|
process.env.AUTH_ISSUER = "https://owned-poll-http.example.invalid"
|
|
const parent = await realpath(tmpdir()), root = await mkdtemp(join(parent,"mm-poll-http-"))
|
|
process.env.MCP_STATE_DIR = root
|
|
const { default: auth, requireApiAuth } = await import("../plugins/auth.js")
|
|
const { createDurableServerPollHttpForTests } = await import("./server-poll-http.js")
|
|
const { pool, closePool } = await import("../db/index.js")
|
|
const originalQuery = pool.query, cutoff = new Map<string,number>()
|
|
let portalReads = 0, dispatches = 0, afterExecution: (()=>void|Promise<void>) | undefined
|
|
const contexts: Parameters<Parameters<typeof createDurableServerPollHttpForTests>[0]>[1][] = []
|
|
pool.query = (async (sql:string,args:unknown[]) => {
|
|
assert.equal(sql,"SELECT invalid_before FROM mcp_owner_revocations WHERE owner_id=$1")
|
|
portalReads++; const at = cutoff.get(String(args[0])); return {rows:at?[{invalid_before:new Date(at)}]:[]}
|
|
}) as typeof pool.query
|
|
const apps:FastifyInstance[]=[]
|
|
const secret = new TextEncoder().encode(process.env.AUTH_JWT_SECRET)
|
|
const mint = (permissions=["mm:servers:write"]) => new SignJWT({sub:"original-owner",apps:["mm"],permissions,
|
|
iat:Math.floor(Date.now()/1000)-10,exp:Math.floor(Date.now()/1000)+3600}).setProtectedHeader({alg:"HS256"}).setIssuer(process.env.AUTH_ISSUER!).sign(secret)
|
|
let cases=0
|
|
async function check(name:string,work:()=>Promise<void>){await work();cases++;console.log("ok",name)}
|
|
async function app(withPlugin=true) {
|
|
const instance=Fastify();apps.push(instance)
|
|
if(withPlugin){await instance.register(auth);instance.addHook("preHandler",requireApiAuth)}
|
|
instance.addHook("preHandler",async request=>{
|
|
// A mutable convenience field cannot replace the signed original claims.
|
|
request.authUser={id:"forged-owner",email:"",name:"",apps:["mm"],permissions:["mm:admin"],issuedAt:1,expiresAt:9999999999999}
|
|
})
|
|
instance.post("/api/servers/:id/poll",createDurableServerPollHttpForTests(async (id,context)=>{
|
|
dispatches++;contexts.push(context);assert.equal(id,"7");context.assertRequestActive?.();await afterExecution?.()
|
|
return {statusCode:200,body:{id:3,serverId:7,status:"online"}}
|
|
}))
|
|
return instance
|
|
}
|
|
try {
|
|
const server=await app(),token=await mint(),headers={authorization:"Bearer "+token,"x-request-id":"forged-request-id"}
|
|
if(!local)await check("401/403 before host, including valid read-only JWT",async()=>{
|
|
const before=dispatches
|
|
assert.equal((await server.inject({method:"POST",url:"/api/servers/7/poll"})).statusCode,401)
|
|
assert.equal((await server.inject({method:"POST",url:"/api/servers/7/poll",headers:{authorization:"Bearer "+await mint(["mm:servers:read"])}})).statusCode,403)
|
|
assert.equal(dispatches,before)
|
|
})
|
|
await check("original JWT/local identity; body/headers/authUser cannot assign authority",async()=>{
|
|
const reply=await server.inject({method:"POST",url:"/api/servers/7/poll",headers,payload:{serverId:999,authRequired:false,actor:{id:"injected"},requestId:"injected",deadlineAt:9999999999999}})
|
|
assert.equal(reply.statusCode,200,reply.body);assert.deepEqual(reply.json(),{id:3,serverId:7,status:"online"})
|
|
const context=contexts.at(-1)!;assert.equal(context.authRequired,!local);assert.notEqual(context.requestId,"forged-request-id")
|
|
assert.match(context.requestId,/^[a-f0-9-]{36}$/)
|
|
assert(context.deadlineAt!<=context.acceptedAt+180000)
|
|
if(local)assert.equal(context.actor,undefined)
|
|
else{assert.equal(context.actor?.id,"original-owner");assert.deepEqual(context.actor?.permissions,["mm:servers:write"])}
|
|
assert(context.signal?.aborted,"The route must retire its own signal after completion")
|
|
assert.throws(context.assertRequestActive!)
|
|
})
|
|
if(!local)await check("late owner revocation blocks HTTP publication after host completion",async()=>{
|
|
afterExecution=()=>cutoff.set("original-owner",Date.now())
|
|
try{const reply=await server.inject({method:"POST",url:"/api/servers/7/poll",headers});assert.equal(reply.statusCode,401);assert(!reply.body.includes('"serverId"'))}
|
|
finally{afterExecution=undefined;cutoff.clear()}
|
|
})
|
|
await check("a handler without genuine auth hooks refuses before execution",async()=>{
|
|
const isolated=await app(false),before=dispatches
|
|
const reply=await isolated.inject({method:"POST",url:"/api/servers/7/poll",headers,payload:{authRequired:false}})
|
|
assert.equal(reply.statusCode,403);assert.equal(dispatches,before)
|
|
})
|
|
await check("actual HTTP disconnect retires the original host context",async()=>{
|
|
let ready!:()=>void
|
|
const entered = new Promise<void>(done=>{ready=done})
|
|
afterExecution=async()=>{const signal=contexts.at(-1)!.signal!;ready();if(!signal.aborted)await new Promise<void>(done=>signal.addEventListener("abort",()=>done(),{once:true}))}
|
|
try{
|
|
await server.listen({host:"127.0.0.1",port:0})
|
|
const address=server.server.address();assert(address&&typeof address!=="string")
|
|
const controller=new AbortController(),response=fetch(`http://127.0.0.1:${address.port}/api/servers/7/poll`,{method:"POST",headers,signal:controller.signal})
|
|
await entered;controller.abort();await assert.rejects(response)
|
|
const context=contexts.at(-1)!
|
|
for(let index=0;!context.signal?.aborted&&index<100;index++)await new Promise(done=>setTimeout(done,10))
|
|
assert(context.signal?.aborted);assert.throws(context.assertRequestActive!)
|
|
}finally{afterExecution=undefined}
|
|
})
|
|
console.log("Full poll HTTP provenance:",JSON.stringify({cases,mode:local?"local":"jwt",actualFastify:true,actualSignedJwt:!local,hostExecutionTestDouble:true,portalReads,productionDatabaseTouched:false,nativeRequests:0}))
|
|
if(!local){const code=await new Promise<number>((done,reject)=>{
|
|
const child=spawn(process.execPath,["--import","tsx",fileURLToPath(import.meta.url)],{windowsHide:true,env:{...process.env,MM_TEST_POLL_HTTP_LOCAL:"true"},stdio:"inherit"})
|
|
child.once("error",reject);child.once("exit",code=>done(code??1))
|
|
});assert.equal(code,0,"Local auth mode must be verified in an independent process")}
|
|
}finally{
|
|
try{for(const instance of apps)await instance.close()}finally{pool.query=originalQuery;await closePool();const actual=await realpath(root);assert.equal(dirname(actual),parent);assert.match(basename(actual),/^mm-poll-http-/);await rm(actual,{recursive:true,force:true})}
|
|
}
|