Docker images / prepare-release (push) Successful in 9s
Docker images / updater-image (push) Successful in 42s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-test (push) Successful in 9m43s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 15m47s
Docker images / notify-webhook (push) Successful in 0s
Docker images / publish-release (push) Successful in 10s
285 lines
16 KiB
TypeScript
285 lines
16 KiB
TypeScript
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"
|
|
import fp from "fastify-plugin"
|
|
import { AsyncLocalStorage } from "node:async_hooks"
|
|
import { randomUUID } from "node:crypto"
|
|
import { performance } from "node:perf_hooks"
|
|
import { env } from "../config.js"
|
|
import {
|
|
hasPermission,
|
|
permissionForRequest,
|
|
type AuthUser,
|
|
} from "../lib/permissions.js"
|
|
|
|
declare const restRequestBrand: unique symbol
|
|
export type VerifiedRestRequest = Readonly<{ [restRequestBrand]: true }>
|
|
export interface RestRequestScope { readonly deadlineAt: number; readonly signal?: AbortSignal }
|
|
export interface VerifiedRestRequestAuthority {
|
|
readonly requestId: string; readonly authentication: "jwt" | "local"; readonly ownerId: string
|
|
readonly method: string; readonly path: string; readonly acceptedAt: number; readonly issuedAt: number; readonly expiresAt: number
|
|
/** Original process-local horizon; consumers must not reconstruct it after a wall-clock change. */
|
|
readonly monotonicDeadline: number
|
|
readonly apps: readonly string[]; readonly permissions: readonly string[]
|
|
/** Fixed private request/first-capture lifetime, for trusted native readers. */
|
|
readonly signal: AbortSignal
|
|
}
|
|
export class RestRequestProvenanceError extends Error {
|
|
readonly code = "REST_REQUEST_PROVENANCE_REFUSED"
|
|
constructor() { super("Исходный REST-контекст не подтверждён или завершён") }
|
|
}
|
|
type RequestEntry = {
|
|
active: boolean; authenticated: boolean; readonly realm: object; readonly request: FastifyRequest
|
|
readonly requestId: string; readonly acceptedAt: number; readonly monotonicAt: number; readonly method: string; readonly path: string
|
|
readonly authRequired: boolean; bearer?: string; readonly verify: (token: string) => unknown; readonly controller: AbortController
|
|
claims?: Readonly<Pick<AuthUser, "id" | "issuedAt" | "expiresAt"> & { readonly apps: readonly string[]; readonly permissions: readonly string[] }>
|
|
captureScope?: Readonly<RestRequestScope>; captureDeadline?: number; authoritySignal?: AbortSignal; cleanup(): void
|
|
}
|
|
type RestToken = { readonly entry: RequestEntry; readonly authority: Readonly<VerifiedRestRequestAuthority>; readonly signal?: AbortSignal; readonly monotonicEnd: number }
|
|
const restRequests = new WeakMap<object, RequestEntry>(), restTokens = new WeakMap<object, RestToken>()
|
|
const activeRestRequest = new AsyncLocalStorage<RequestEntry>()
|
|
const refuseProvenance = (): never => { throw new RestRequestProvenanceError() }
|
|
function scopeSnapshot(input: Readonly<RestRequestScope>): Readonly<RestRequestScope> {
|
|
if (!input || Object.getPrototypeOf(input) !== Object.prototype || Reflect.ownKeys(input).length !== Object.keys(input).length) refuseProvenance()
|
|
const fields = Object.getOwnPropertyDescriptors(input)
|
|
if (Object.keys(fields).some(key => !["deadlineAt", "signal"].includes(key)) || Object.values(fields).some(field => !("value" in field) || !field.enumerable)) refuseProvenance()
|
|
const deadlineAt = fields.deadlineAt?.value, signal = fields.signal?.value
|
|
if (typeof deadlineAt !== "number" || !Number.isSafeInteger(deadlineAt) || signal !== undefined && !(signal instanceof AbortSignal)) return refuseProvenance()
|
|
return Object.freeze({ deadlineAt, signal })
|
|
}
|
|
function permissionsSnapshot(input: string | readonly string[]): readonly string[] {
|
|
if (typeof input === "string") { if (!input || input.length > 200 || input.trim() !== input) refuseProvenance(); return Object.freeze([input]) }
|
|
if (!Array.isArray(input) || input.length < 1 || input.length > 1000 || Reflect.ownKeys(input).length !== input.length + 1) refuseProvenance()
|
|
const fields = Object.getOwnPropertyDescriptors(input), result: string[] = []
|
|
for (let index = 0; index < input.length; index++) {
|
|
const field = fields[String(index)]
|
|
if (!field || !("value" in field) || !field.enumerable || typeof field.value !== "string" || !field.value || field.value.length > 200 || field.value.trim() !== field.value) refuseProvenance()
|
|
result.push(field.value)
|
|
}
|
|
return Object.freeze(result)
|
|
}
|
|
function requestLive(entry: RequestEntry): void {
|
|
if (!entry.active || entry.controller.signal.aborted || activeRestRequest.getStore() !== entry || restRequests.get(entry.request) !== entry
|
|
|| entry.request.server.server !== entry.realm || Date.now() < entry.acceptedAt || Date.now() >= entry.acceptedAt + 300000 || performance.now() >= entry.monotonicAt + 300000) refuseProvenance()
|
|
}
|
|
function claimsSnapshot(value: unknown): NonNullable<RequestEntry["claims"]> {
|
|
if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) return refuseProvenance()
|
|
const fields = Object.getOwnPropertyDescriptors(value)
|
|
if (Reflect.ownKeys(value).length !== Object.keys(fields).length || Object.values(fields).some(field => !("value" in field) || !field.enumerable)) refuseProvenance()
|
|
if (typeof fields.iat?.value !== "number" || typeof fields.exp?.value !== "number") refuseProvenance()
|
|
const id = fields.sub?.value, issuedAt = fields.iat.value * 1000, expiresAt = fields.exp.value * 1000
|
|
if (typeof id !== "string" || !id.trim() || id.length > 200 || !Number.isSafeInteger(issuedAt) || issuedAt <= 0 || !Number.isSafeInteger(expiresAt) || expiresAt <= issuedAt) refuseProvenance()
|
|
const apps = permissionsSnapshot(fields.apps?.value), permissions = permissionsSnapshot(fields.permissions?.value)
|
|
if (!apps.includes("mm")) refuseProvenance()
|
|
return Object.freeze({ id, issuedAt, expiresAt, apps, permissions })
|
|
}
|
|
/** Bound current portal I/O too. Late continuations cannot mint or inspect a
|
|
* capability after timeout, cancellation or retirement of its actual request. */
|
|
async function provenanceWindow<T>(entry: RequestEntry, scope: Readonly<RestRequestScope>, expiresAt: number, monotonicEnd: number, originalSignal: AbortSignal | undefined, work: (live: () => void) => Promise<T>): Promise<T> {
|
|
const deadlineAt = Math.min(scope.deadlineAt, expiresAt, entry.acceptedAt + 300000)
|
|
const end = Math.min(monotonicEnd, performance.now() + Math.max(0, deadlineAt - Date.now()))
|
|
const signals = [...new Set([entry.controller.signal, scope.signal, originalSignal].filter((signal): signal is AbortSignal => !!signal))]
|
|
let active = true, rejectStopped!: (error: RestRequestProvenanceError) => void
|
|
const live = () => { requestLive(entry); if (!active || Date.now() >= deadlineAt || performance.now() >= end || signals.some(signal => signal.aborted)) refuseProvenance() }
|
|
const stopped = new Promise<never>((_resolve, reject) => { rejectStopped = reject })
|
|
const stop = () => { active = false; rejectStopped(new RestRequestProvenanceError()) }
|
|
const timer = setTimeout(stop, Math.max(1, Math.min(deadlineAt - Date.now(), end - performance.now())))
|
|
for (const signal of signals) signal.addEventListener("abort", stop, { once: true })
|
|
try { live(); return await Promise.race([Promise.resolve().then(async () => { live(); const result = await work(live); live(); return result }), stopped]) }
|
|
finally { active = false; clearTimeout(timer); for (const signal of signals) signal.removeEventListener("abort", stop) }
|
|
}
|
|
async function portalCurrent(entry: RequestEntry, live: () => void): Promise<void> {
|
|
live()
|
|
if (entry.authRequired) {
|
|
const claims = entry.claims ?? refuseProvenance()
|
|
const { assertPortalClaimsCurrent } = await import("../modules/mcp/portal-revocation.js"); live()
|
|
await assertPortalClaimsCurrent(claims); live()
|
|
}
|
|
}
|
|
/** Actual plugin hook + successful real authentication are prerequisites. Neither
|
|
* AuthUser JSON nor a request carrying its own jwtVerify function is a source. */
|
|
export async function captureVerifiedRestRequest(request: FastifyRequest, inputScope: Readonly<RestRequestScope>): Promise<VerifiedRestRequest> {
|
|
const scope = scopeSnapshot(inputScope), entry = request && typeof request === "object" ? restRequests.get(request) : undefined
|
|
if (!entry) return refuseProvenance()
|
|
requestLive(entry)
|
|
if (entry.authRequired && (!entry.authenticated || !entry.bearer)) refuseProvenance()
|
|
// This is one original request authority, not a new grant per capture. In
|
|
// particular replacing an aborted first signal cannot revive its request.
|
|
if (entry.captureScope && (scope.deadlineAt !== entry.captureScope.deadlineAt || scope.signal !== entry.captureScope.signal)) refuseProvenance()
|
|
entry.captureScope ??= scope
|
|
entry.authoritySignal ??= scope.signal ? AbortSignal.any([entry.controller.signal, scope.signal]) : entry.controller.signal
|
|
if (entry.authRequired && !entry.claims) {
|
|
try { entry.claims = claimsSnapshot(entry.verify(entry.bearer!)) } catch { return refuseProvenance() }
|
|
}
|
|
const claims = entry.claims
|
|
if (claims && claims.issuedAt! > Date.now()) refuseProvenance()
|
|
entry.captureDeadline ??= Math.min(scope.deadlineAt, claims?.expiresAt ?? Infinity, entry.acceptedAt + 300000)
|
|
const expiresAt = entry.captureDeadline, monotonicEnd = entry.monotonicAt + Math.max(0, expiresAt - entry.acceptedAt)
|
|
return provenanceWindow(entry, scope, expiresAt, monotonicEnd, entry.captureScope.signal, async live => {
|
|
await portalCurrent(entry, live)
|
|
const required = permissionForRequest(entry.method, entry.path)
|
|
if (entry.authRequired && (!claims?.apps.includes("mm") || required && !hasPermission(claims.permissions, required))) refuseProvenance()
|
|
const authority = Object.freeze({ requestId: entry.requestId, authentication: entry.authRequired ? "jwt" as const : "local" as const,
|
|
ownerId: claims?.id ?? "local-operator", method: entry.method, path: entry.path, acceptedAt: entry.acceptedAt,
|
|
issuedAt: claims?.issuedAt ?? entry.acceptedAt, expiresAt, monotonicDeadline: monotonicEnd, apps: claims?.apps ?? Object.freeze([]), permissions: claims?.permissions ?? Object.freeze([]), signal: entry.authoritySignal! })
|
|
live(); const token = Object.freeze(Object.create(null)) as VerifiedRestRequest
|
|
restTokens.set(token, Object.freeze({ entry, authority, signal: scope.signal, monotonicEnd })); return token
|
|
})
|
|
}
|
|
export async function inspectVerifiedRestRequest(token: unknown, inputScope: Readonly<RestRequestScope>, requiredPermissions: string | readonly string[]): Promise<Readonly<VerifiedRestRequestAuthority>> {
|
|
const scope = scopeSnapshot(inputScope), required = permissionsSnapshot(requiredPermissions)
|
|
const captured = token && typeof token === "object" ? restTokens.get(token) : undefined
|
|
if (!captured) return refuseProvenance()
|
|
return provenanceWindow(captured.entry, scope, captured.authority.expiresAt, captured.monotonicEnd, captured.signal, async live => {
|
|
const current = () => { live(); if (captured.authority.authentication === "jwt" && (!captured.authority.apps.includes("mm") || required.some(permission => !hasPermission(captured.authority.permissions, permission)))) refuseProvenance() }
|
|
current(); await portalCurrent(captured.entry, live); current(); return captured.authority
|
|
})
|
|
}
|
|
|
|
declare module "fastify" {
|
|
interface FastifyRequest {
|
|
authUser?: AuthUser
|
|
}
|
|
}
|
|
|
|
declare module "@fastify/jwt" {
|
|
interface FastifyJWT {
|
|
payload: {
|
|
sub: string
|
|
email?: string
|
|
name?: string
|
|
apps?: string[]
|
|
permissions?: string[]
|
|
is_admin?: boolean
|
|
iss?: string
|
|
exp?: number
|
|
iat?: number
|
|
}
|
|
user: {
|
|
sub: string
|
|
email?: string
|
|
name?: string
|
|
apps?: string[]
|
|
permissions?: string[]
|
|
is_admin?: boolean
|
|
iss?: string
|
|
exp?: number
|
|
iat?: number
|
|
}
|
|
}
|
|
}
|
|
|
|
async function authPlugin(app: FastifyInstance) {
|
|
if (env.authRequired && env.jwtSecret.length < 8) {
|
|
throw new Error("AUTH_JWT_SECRET / JWT_SECRET required when AUTH_REQUIRED=true")
|
|
}
|
|
|
|
await app.register(import("@fastify/jwt"), {
|
|
secret: env.jwtSecret,
|
|
...(env.authRequired
|
|
? {
|
|
verify: {
|
|
allowedIss: [env.authIssuer],
|
|
},
|
|
}
|
|
: {}),
|
|
})
|
|
|
|
// Callback continuation propagates this actual request scope through Fastify
|
|
// hooks and handler. A preHandler-only ALS.run would retire too early.
|
|
const authRequired = env.authRequired, realm = app.server, verifyJwt = app.jwt.verify.bind(app.jwt), entries = new Set<RequestEntry>()
|
|
const retire = (request: FastifyRequest) => {
|
|
const entry = restRequests.get(request)
|
|
if (!entry || entry.realm !== realm) return
|
|
entry.active = false; entry.authenticated = false; entry.bearer = undefined; entry.controller.abort(); entry.cleanup(); entries.delete(entry); restRequests.delete(request)
|
|
}
|
|
app.addHook("onRequest", (request, reply, done) => {
|
|
const authorization = request.headers.authorization, bearer = typeof authorization === "string" && authorization.startsWith("Bearer ") ? authorization.slice(7) : undefined
|
|
const aborted = () => retire(request), closed = () => { if (!reply.raw.writableEnded) retire(request) }
|
|
const entry: RequestEntry = { active: true, authenticated: false, realm, request, requestId: randomUUID(), acceptedAt: Date.now(), monotonicAt: performance.now(),
|
|
method: request.method, path: request.routeOptions.url ?? request.url.split("?")[0], authRequired, bearer, verify: verifyJwt, controller: new AbortController(),
|
|
cleanup() { request.raw.off("aborted", aborted); reply.raw.off("close", closed) } }
|
|
restRequests.set(request, entry); entries.add(entry)
|
|
request.raw.once("aborted", aborted); reply.raw.once("close", closed)
|
|
if (request.raw.aborted || reply.raw.destroyed) retire(request)
|
|
activeRestRequest.run(entry, done)
|
|
})
|
|
app.addHook("onResponse", async request => { retire(request) })
|
|
app.addHook("onError", async request => { retire(request) })
|
|
app.addHook("onClose", async () => { for (const entry of entries) retire(entry.request) })
|
|
|
|
if (env.authRequired) {
|
|
app.log.info(
|
|
{ issuer: env.authIssuer, portal: env.authPortalUrl },
|
|
"AUTH_REQUIRED=true — portal JWT middleware enabled",
|
|
)
|
|
} else {
|
|
app.log.info("AUTH_REQUIRED=false — /api/* open without JWT")
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Protect /api/* when AUTH_REQUIRED=true.
|
|
* Public: /health, /api/auth/config
|
|
*/
|
|
export async function requireAuth(
|
|
request: FastifyRequest,
|
|
reply: FastifyReply,
|
|
): Promise<void> {
|
|
if (!env.authRequired) return
|
|
|
|
const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url
|
|
if (pathname === "/api/auth/config") return
|
|
|
|
const authHeader = request.headers.authorization ?? ""
|
|
const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : ""
|
|
if (!token) {
|
|
return reply.code(401).send({ error: "Unauthorized" })
|
|
}
|
|
|
|
try {
|
|
await request.jwtVerify()
|
|
} catch {
|
|
return reply.code(401).send({ error: "Unauthorized" })
|
|
}
|
|
|
|
const payload = request.user
|
|
if (typeof payload.sub !== "string" || !payload.sub.trim()) return reply.code(401).send({ error: "Unauthorized" })
|
|
const apps = Array.isArray(payload.apps) ? payload.apps.map(String) : []
|
|
const permissions = Array.isArray(payload.permissions)
|
|
? payload.permissions.map(String)
|
|
: []
|
|
|
|
if (!apps.includes("mm")) {
|
|
return reply
|
|
.code(403)
|
|
.send({ error: "Нет доступа к приложению MikrotikManager" })
|
|
}
|
|
|
|
request.authUser = {
|
|
id: String(payload.sub),
|
|
email: String(payload.email ?? ""),
|
|
name: String(payload.name ?? ""),
|
|
apps,
|
|
permissions,
|
|
isAdmin: Boolean(payload.is_admin),
|
|
expiresAt: typeof payload.exp === "number" ? payload.exp * 1000 : undefined,
|
|
issuedAt: typeof payload.iat === "number" ? payload.iat * 1000 : undefined,
|
|
}
|
|
|
|
const required = permissionForRequest(request.method, pathname)
|
|
if (required && !hasPermission(permissions, required)) {
|
|
return reply.code(403).send({ error: `Недостаточно прав: ${required}` })
|
|
}
|
|
const entry = restRequests.get(request)
|
|
if (entry && entry.active && activeRestRequest.getStore() === entry && entry.authRequired && entry.bearer === token) entry.authenticated = true
|
|
}
|
|
|
|
/** 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" ||
|
|
request.method === "POST" && pathname === "/api/ix/import") return
|
|
await requireAuth(request, reply)
|
|
}
|
|
|
|
export default fp(authPlugin, { name: "auth" })
|