fix(auth): закрыть обход JWT через закодированные URL

This commit is contained in:
Denozordec committed 2026-10-13 21:23:51 +07:00
1 parent 727e35f985
commit 7d86af7e8b
19 files changed
+1656 -23

No files matched your search

+1 -1
View File
@@ -17,7 +17,7 @@
"facts:rebuild": "tsx src/scripts/rebuild-flow-facts.ts",
"test:probes": "tsx src/routes/probes.test.ts && tsx src/routes/probes.cancel.test.ts && tsx src/services/ping-measurement.test.ts && tsx src/services/uptime-probe-observations.test.ts && tsx src/services/ping-measurement-sql.test.ts",
"test:exec": "tsx src/services/mikrotik-logs.test.ts && tsx src/routes/exec.test.ts && tsx src/plugins/auth.exec.test.ts",
"test:auth": "tsx src/lib/permissions.test.ts && tsx src/plugins/auth.smoke.test.ts && tsx src/plugins/auth.ospf-optimizer.test.ts",
"test:auth": "tsx src/plugins/auth-path.test.ts && tsx src/lib/permissions.test.ts && tsx src/plugins/auth.smoke.test.ts && tsx src/plugins/auth.ospf-optimizer.test.ts",
"test:wireguard": "npx tsx src/services/wireguard-config.test.ts && npx tsx src/services/wireguard-ipv6.test.ts && npx tsx --test src/services/wireguard-import.test.ts src/services/wireguard-import-apply.test.ts src/services/wireguard-import-revision.test.ts src/services/wireguard-delete.test.ts && npx tsx src/routes/wireguard-import.test.ts",
"test:traffic-rate": "tsx src/services/traffic-rate.test.ts && tsx src/services/traffic-observation.test.ts && tsx src/services/traffic-freshness.test.ts && tsx src/services/traffic-live.test.ts && tsx src/services/traffic-observation-sql.test.ts && tsx src/services/traffic-history-sql.test.ts && tsx src/services/traffic-live-sql.test.ts && tsx src/services/traffic-volume-sql.test.ts && tsx src/services/traffic-binding-status.test.ts && tsx src/services/traffic-status-sql.test.ts && tsx src/services/traffic-gap.test.ts && tsx src/services/traffic-identity.test.ts && tsx src/services/traffic-membership.test.ts && tsx src/services/traffic-aggregate-peak.test.ts && tsx src/services/traffic-users-cache.test.ts && tsx src/services/traffic-collection-lock.test.ts && tsx src/services/traffic-concurrency-sql.test.ts",
"test:traffic-flow": "tsx src/routes/traffic-flow-query.test.ts && tsx src/services/traffic-flow-month.test.ts && tsx src/services/traffic-flow-parse.test.ts && tsx src/services/traffic-flow-ipv6-pipeline.test.ts && tsx src/services/traffic-flow-map-exporter.test.ts && tsx src/services/traffic-flow-ifaces.test.ts && tsx src/services/traffic-flow-ifindex.test.ts && tsx src/services/traffic-flow-dedup.test.ts && tsx src/services/traffic-flow-planes.test.ts && tsx src/services/traffic-flow-ip.test.ts && tsx src/services/traffic-flow-dest.test.ts && tsx src/services/traffic-flow-classify.test.ts && tsx src/services/traffic-flow-ripe.test.ts && tsx src/services/traffic-flow-brands.test.ts && tsx src/services/traffic-flow-ingest.test.ts && tsx src/services/traffic-flow-analytics.test.ts && tsx src/services/traffic-flow-map-hops.test.ts && tsx src/services/traffic-flow-purge.test.ts && tsx src/services/traffic-flow-geoip.test.ts && tsx src/services/traffic-flow-facts.test.ts && tsx src/services/traffic-flow-facts-filter.test.ts && tsx src/services/traffic-flow-facts-rebuild.test.ts && tsx src/services/statistics-aggregate.test.ts",
@@ -0,0 +1,19 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import {createServer} from 'node:http'
import {randomBytes} from 'node:crypto'
const database=process.env.MMAPP_OWN_SQL_DB,url=new URL(process.env.DATABASE_URL)
assert(/^mm_accept_166_\d+$/.test(database??''));assert.equal(url.pathname,'/'+database);assert.equal(url.username,database)
process.env.AUTH_REQUIRED='true';process.env.AUTH_JWT_SECRET=randomBytes(32).toString('hex');process.env.AUTH_ISSUER='https://own211.invalid';process.env.AUTH_PORTAL_URL='https://own211.invalid'
const {pool,closePool}=await import('/app/backend/dist/db/index.js'),{initDatabase}=await import('/app/backend/dist/db/bootstrap.js'),{buildApp}=await import('/app/backend/dist/index.js')
assert.equal((await pool.query('SELECT current_database() AS name')).rows[0].name,database);assert(Object.values((await pool.query('SELECT rolsuper,rolcreatedb,rolcreaterole,rolbypassrls FROM pg_roles WHERE rolname=current_user')).rows[0]).every(v=>v===false))
const psk='own211-'+randomBytes(24).toString('base64url'),baseline=false,cases=[];let app,serverId,nativeWrites=0,nativeCalls=0
const native=createServer((req,res)=>{nativeCalls++;if(req.method!=='GET')nativeWrites++;res.setHeader('content-type','application/json');res.end(JSON.stringify(req.url.endsWith('/interface/gre')?[{'.id':'*1',name:'own211-encrypted','local-address':'192.0.2.1','remote-address':'192.0.2.2','ipsec-secret':psk,mtu:'1476',keepalive:'10s,3',disabled:'false',running:'true','allow-fast-path':'false'},{'.id':'*2',name:'own211-plain','remote-address':'192.0.2.3','ipsec-secret':'',disabled:'false',running:'true'}]:[]))});await new Promise(r=>native.listen(0,'127.0.0.1',r))
const report={date:'2026-10-13',block:'12.5.211',database,baseline,cases,scope:'Production compiled canonical auth/RBAC using own restricted PostgreSQL, local native HTTP fixture and synthetic JWT/PSK',passed:false}
try{await initDatabase();serverId=Number((await pool.query("INSERT INTO servers(name,host,port,use_ssl,enabled,username,password) VALUES('own211-native','127.0.0.1',$1,false,true,'fixture','fixture') RETURNING id",[native.address().port])).rows[0].id);app=await buildApp({logger:false,startScheduler:false});await app.ready()
for(const path of ['/api/servers','/api/%73ervers','/%61pi/servers','/%61%70%69/servers','/api/gre/tunnels','/%61pi/gre/tunnels'])for(const method of ['GET','HEAD']){const before=nativeCalls;const r=await app.inject({method,url:path});assert.equal(r.statusCode,401);assert.equal(nativeCalls,before);cases.push({path,method,role:'anonymous',status:401})}
for(const path of ['/api/gre/tunnels','/api/%67re/tunnels','/%61pi/gre/tunnels'])for(const role of ['dashboard','reader','writer']){const permissions=role==='dashboard'?['mm:dashboard:read']:role==='reader'?['mm:network:read']:['mm:network:write'],token=app.jwt.sign({sub:'own211-'+role,apps:['mm'],permissions,iss:process.env.AUTH_ISSUER},{expiresIn:'5m'});const r=await app.inject({method:'GET',url:path+'?serverId='+serverId,headers:{authorization:'Bearer '+token}});assert.equal(r.statusCode,role==='dashboard'?403:200);if(role!=='dashboard')assert.equal(r.json().tunnels.find(t=>t.name==='own211-encrypted').ipsec.secret,role==='writer'?psk:'');cases.push({path,method:'GET',role,status:r.statusCode,privateMaterialStored:false});if(role!=='writer'){const patch=await app.inject({method:'PATCH',url:path,headers:{authorization:'Bearer '+token},payload:{serverId:String(serverId),rosId:'*1',comment:'not applied'}});assert.equal(patch.statusCode,403);cases.push({path,method:'PATCH',role,status:403})}}
for(const path of ['/api/auth/config','/%61pi/auth/config']){assert.equal((await app.inject({url:path})).statusCode,200);cases.push({path,role:'anonymous',status:200,publicConfig:true})}
assert.equal(nativeWrites,0);report.nativeWrites=0;report.passed=true
}catch(e){report.errorName=e.name;fs.writeFileSync('/app/backend/acceptance/gre211-private.log',String(e.stack??e),{mode:0o600})}finally{if(app)await app.close();native.closeAllConnections();await new Promise(r=>native.close(r));await closePool();fs.writeFileSync('/app/backend/acceptance/auth211-production-result.json',JSON.stringify(report,null,2));console.log(JSON.stringify(report))}
if(!report.passed)process.exitCode=1
+2 -8
View File
@@ -5,7 +5,7 @@ import { monitorEventLoopDelay } from "node:perf_hooks"
import { env } from "./config.js"
import { initDatabase } from "./db/bootstrap.js"
import { closePool } from "./db/index.js"
import authPlugin, { requireAuth } from "./plugins/auth.js"
import authPlugin, { requireApiAuth } from "./plugins/auth.js"
import { installDatabaseRequestGate } from "./plugins/database-request-gate.js"
import serversRoutes from "./routes/servers.js"
import bgpRoutes from "./routes/bgp.js"
@@ -108,13 +108,7 @@ export async function buildApp(opts?: {
}))
if (env.authRequired) {
app.addHook("preHandler", async (request, reply) => {
const pathname = request.url.split("?")[0] ?? request.url
if (!pathname.startsWith("/api/")) return
if (pathname === "/api/auth/config") return
await requireAuth(request, reply)
if (reply.sent) return
})
app.addHook("preHandler", requireApiAuth)
}
installDatabaseRequestGate(app)
+4 -4
View File
@@ -47,17 +47,17 @@ const RULES: Rule[] = [
{ methods: ["PUT", "POST"], match: path => path === "/api/geoip" || path === "/api/geoip/update", permission: "mm:traffic:write" },
{
methods: ["GET"],
match: p => /^\/api\/servers\/\d+\/ospf(?:\/|$)/.test(p),
match: p => /^\/api\/servers\/(?:\d+|:[A-Za-z]\w*)\/ospf(?:\/|$)/.test(p),
permission: "mm:network:read",
},
{
methods: ["POST"],
match: p => /^\/api\/servers\/\d+\/ospf\/optimize\/preview$/.test(p),
match: p => /^\/api\/servers\/(?:\d+|:[A-Za-z]\w*)\/ospf\/optimize\/preview$/.test(p),
permission: "mm:network:read",
},
{
methods: ["POST", "PUT", "PATCH", "DELETE"],
match: p => /^\/api\/servers\/\d+\/ospf(?:\/|$)/.test(p),
match: p => /^\/api\/servers\/(?:\d+|:[A-Za-z]\w*)\/ospf(?:\/|$)/.test(p),
permission: "mm:network:write",
},
@@ -201,7 +201,7 @@ export function permissionForRequest(
method: string,
path: string,
): string | null {
const m = method.toUpperCase()
const m = method.toUpperCase() === "HEAD" ? "GET" : method.toUpperCase()
const pathname = path.split("?")[0] ?? path
for (const rule of RULES) {
if (!rule.methods.includes(m)) continue
+16
View File
@@ -0,0 +1,16 @@
import assert from 'node:assert/strict'
import Fastify from 'fastify'
process.env.AUTH_REQUIRED='true';process.env.AUTH_JWT_SECRET='own211-synthetic-secret';process.env.AUTH_ISSUER='https://own211.invalid';process.env.NODE_ENV='test'
const {default:authPlugin,requireApiAuth}=await import('./auth.js')
const app=Fastify();await app.register(authPlugin);app.addHook('preHandler',requireApiAuth);let calls=0
for(const url of ['/api/servers','/api/gre/tunnels','/api/servers/:id/ospf'])app.get(url,async()=>{calls++;return{ok:true}})
app.patch('/api/gre/tunnels',async()=>{calls++;return{ok:true}})
app.post('/api/servers/:id/ospf/optimize/preview',async()=>{calls++;return{ok:true}})
app.get('/api/auth/config',async()=>({public:true}));app.get('/health',async()=>({public:true}));await app.ready()
const token=(permissions:string[])=>app.jwt.sign({sub:'own211',apps:['mm'],permissions,iss:process.env.AUTH_ISSUER},{expiresIn:'5m'})
let cases=0
for(const url of ['/api/servers','/api/%73ervers','/%61pi/servers','/%61%70%69/%73ervers'])for(const method of ['GET','HEAD'] as const){const before=calls,r=await app.inject({method,url});assert.equal(r.statusCode,401,url);assert.equal(calls,before);cases++}
for(const url of ['/api/gre/tunnels','/api/%67re/tunnels','/%61pi/gre/tunnels'])for(const method of ['GET','HEAD','PATCH'] as const)for(const role of ['dashboard','reader','writer']){const before=calls,permissions=role==='dashboard'?['mm:dashboard:read']:role==='reader'?['mm:network:read']:['mm:network:write'],allowed=role==='writer'||(role==='reader'&&method!=='PATCH'),r=await app.inject({method,url,headers:{authorization:'Bearer '+token(permissions)}});assert.equal(r.statusCode,allowed?200:403,url+' '+method+' '+role);assert.equal(calls,before+(allowed?1:0));cases++}
for(const method of ['GET','POST'] as const){const url=method==='GET'?'/api/servers/1/ospf':'/api/servers/1/ospf/optimize/preview';assert.equal((await app.inject({method,url,headers:{authorization:'Bearer '+token(['mm:network:read'])}})).statusCode,200);assert.equal((await app.inject({method,url,headers:{authorization:'Bearer '+token(['mm:servers:read'])}})).statusCode,403);cases+=2}
for(const url of ['/health','/api/auth/config','/%61pi/auth/config']){assert.equal((await app.inject({url})).statusCode,200);cases++}
await app.close();console.log('Canonical API auth: '+cases+' cases, denied handlers not called, HEAD and OSPF matched templates preserved')
+8 -1
View File
@@ -74,7 +74,7 @@ export async function requireAuth(
): Promise<void> {
if (!env.authRequired) return
const pathname = (request.url.split("?")[0] ?? request.url)
const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url
if (pathname === "/api/auth/config") return
const authHeader = request.headers.authorization ?? ""
@@ -116,4 +116,11 @@ export async function requireAuth(
}
}
/** Gate the matched route, including encoded static segments in the raw URL. */
export async function requireApiAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url
if (!pathname.startsWith("/api/") || pathname === "/api/auth/config") return
await requireAuth(request, reply)
}
export default fp(authPlugin, { name: "auth" })