Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## Unreleased

- **Fewer false Health alarms on FastAPI:** a check added where a router is included, like `app.include_router(admin.router, dependencies=[Depends(require_admin)])`, now protects every endpoint of that router, as `app.use('/admin', requireStaff, adminRouter)` already did on Express. A database session added there still doesn't count as a sign-in check.
- **FastAPI routers found by the name they're imported under:** a router imported under another name (`from app.routes import campaigns as campaign_routes`) gets its prefix and its checks, and a package that shares a router's name (`from app.platform import pricing` beside a `platform` router) is no longer mistaken for it.

## 0.2.2 (2026-10-28)

- **Light mode:** a new **Theme** button in the top bar cycles **Auto → Light → Dark**. Auto follows your device's light or dark setting and changes with it. Your choice is remembered on this device, and the map shows the right colours from the first moment, with no flash. The button is a 44 px target, works from the keyboard with a visible focus ring, and the change is instant (nothing animates, so Reduce Motion is respected). Dark looks exactly as before. Requested in #9 and built by @menachem-kurkus in #10.
Expand Down
12 changes: 10 additions & 2 deletions skills/floorplan/scripts/lib/extract.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,16 @@ function extractPy(src) {
for (const m of all(/\b(?:re_)?path\(\s*r?["']([^"']*)["']\s*,\s*(?!include)/g, code)) routes.push({ method: 'ANY', path: '/' + m[1].replace(/^\^|\$$/g, ''), var: null, line: at(m.index), framework: 'django' });

const mounts = [];
for (const m of all(/\b(?:register_blueprint|include_router|mount)\(\s*([A-Za-z_][\w.]*)([^)]*)\)/g, code)) {
mounts.push({ var: m[1], prefix: /(?:url_)?prefix\s*=\s*["']([^"']*)["']/.exec(m[2])?.[1] || '', line: at(m.index) });
for (const m of all(/\b(register_blueprint|include_router|mount)\(\s*([A-Za-z_][\w.]*)/g, code)) {
// the call's arguments, up to its own closing bracket: dependencies=[Depends(x)] holds brackets of its own
let depth = 1, j = m.index + m[0].length;
while (j < code.length && depth && j - m.index < 2000) { if (code[j] === '(') depth++; else if (code[j] === ')') depth--; j++; }
const args = code.slice(m.index + m[0].length, j - 1);
// FastAPI checks applied to every route of the router where it's included:
// app.include_router(admin.router, dependencies=[Depends(require_admin)])
const deps = m[1] === 'include_router' ? /dependencies\s*=\s*\[([\s\S]*?)\]/.exec(args)?.[1] : null;
const mw = deps ? [...deps.matchAll(/\b(?:Depends|Security)\(\s*([\w.]+)/g)].map((d) => d[1].split('.').pop()) : [];
mounts.push({ var: m[2], prefix: /(?:url_)?prefix\s*=\s*["']([^"']*)["']/.exec(args)?.[1] || '', line: at(m.index), ...(mw.length ? { mw } : {}) });
}

const routeLine = /^\s*@\w+\.(route|get|post|put|patch|delete)\(/;
Expand Down
5 changes: 3 additions & 2 deletions skills/floorplan/scripts/lib/health.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -536,8 +536,9 @@ export function buildHealth({ graph, scan, arch, root }) {
if (!guardDefs.has(name)) guardDefs.set(name, []);
guardDefs.get(name).push({ file, alias: true, repo });
}
// a sign-in check applied where the route's router is mounted: app.use('/admin', requireStaff, adminRouter)
const mountGuard = new Map((scan.routes || []).filter((r) => r.mountMw?.some(isGuardName)).map((r) => [`${r.file}|${r.line}|${r.method}`, r.mountMw.find(isGuardName)]));
// a sign-in check applied where the route's router is mounted: app.use('/admin', requireStaff, adminRouter),
// or app.include_router(admin.router, dependencies=[Depends(require_admin)]) (a database session isn't one)
const mountGuard = new Map((scan.routes || []).filter((r) => r.mountMw?.some(isGuardDep)).map((r) => [`${r.file}|${r.line}|${r.method}`, r.mountMw.find(isGuardDep)]));
const perRepo = new Map(); // repo -> { guarded, open: [], guardCounts }
graph.routes.forEach((r, i) => {
const fnd = routeFinding.get(`${r.f}|${r.l}|${r.m}`);
Expand Down
11 changes: 11 additions & 0 deletions skills/floorplan/scripts/lib/routes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ function mountTarget(f, mount) {
const imp = imports.find((i) => i.locals && Object.hasOwn(i.locals, head));
return { file: imp ? imp.files[0] : f.path, v: '*' };
}
// First the import that binds the mounted name in this file: `from app.routes import campaigns as
// campaign_routes` binds campaign_routes (not campaigns), and wins over `from app.platform import pricing`
// whose module merely ends in a router's name (platform).
const bound = imports.find((imp) => imp.from
? Object.hasOwn(imp.aliases || {}, head) || (imp.names?.includes(head) && !Object.values(imp.aliases || {}).includes(head))
: (imp.alias || imp.spec?.split('.')[0]) === head);
if (bound && (attr || bound.from)) {
const orig = bound.aliases?.[head] || head;
const file = (bound.from && bound.files.length > 1 && bound.files[bound.names.indexOf(orig)]) || bound.files[0];
return { file, v: attr || orig };
}
for (const imp of imports) {
if (attr && (imp.alias === head || imp.spec?.split('.').pop() === head || imp.names?.includes(head))) {
return { file: imp.files[imp.names?.indexOf(head) ?? 0] || imp.files[0], v: attr };
Expand Down
Empty file.
11 changes: 11 additions & 0 deletions tests/fixtures/fastapi-include-router/app/deps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""Shared dependencies: one checks the caller, one only hands over a database session."""
from fastapi import Header, HTTPException


def get_db_session():
yield object()


def require_admin(authorization: str = Header(...)):
if authorization != "Bearer admin":
raise HTTPException(status_code=401)
19 changes: 19 additions & 0 deletions tests/fixtures/fastapi-include-router/app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from fastapi import Depends, FastAPI

from app.deps import get_db_session, require_admin
from app.staff import audit
from app.routers import orders, staff
from app.routers import items as item_routes

app = FastAPI()
audit.record("start")
# The check is added once, where each router is included, not on its routes.
app.include_router(staff.router, dependencies=[Depends(require_admin)])
# Imported under another name, included over several lines beside a database session.
app.include_router(
item_routes.router,
prefix="/items",
dependencies=[Depends(get_db_session), Depends(require_admin)],
)
# A database session is not a sign-in check: these routes are open.
app.include_router(orders.router, dependencies=[Depends(get_db_session)])
Empty file.
9 changes: 9 additions & 0 deletions tests/fixtures/fastapi-include-router/app/routers/items.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Guarded where it's included, alongside a database session, over several lines."""
from fastapi import APIRouter

router = APIRouter()


@router.delete("/{item_id}")
async def delete_item(item_id: int):
return {"deleted": item_id}
9 changes: 9 additions & 0 deletions tests/fixtures/fastapi-include-router/app/routers/orders.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Really open: only a database session is added where it's included. Health must still flag it."""
from fastapi import APIRouter

router = APIRouter()


@router.post("/orders")
async def place_order():
return {"ok": True}
14 changes: 14 additions & 0 deletions tests/fixtures/fastapi-include-router/app/routers/staff.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Guarded where it's included in main.py."""
from fastapi import APIRouter

router = APIRouter(prefix="/staff")


@router.post("/reset")
async def reset_everything():
return {"ok": True}


@router.get("/report")
async def report():
return {"rows": []}
Empty file.
5 changes: 5 additions & 0 deletions tests/fixtures/fastapi-include-router/app/staff/audit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""A package with the same name as a router (staff), imported before the routers."""


def record(event: str) -> None:
print(event)
11 changes: 11 additions & 0 deletions tests/health.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,14 @@ test('FastAPI: Annotated dependency aliases count as sign-in checks (#4)', () =>
// routes with only a database session (SessionDep, SqlSessionDep over get_sql_session) aren't
assert.deepEqual(openEndpoints(graph), ['POST /comments', 'POST /feedback']);
});

test('FastAPI: checks added where a router is included count as sign-in checks', () => {
const graph = buildFixture('fastapi-include-router');
assert.equal(graph.routes.length, 4, `expected the sample's 4 endpoints, found ${graph.routes.length}`);
// the router imported under another name (item_routes) still gets its prefix
assert.ok(graph.routes.some((r) => r.p === '/items/{item_id}'), 'expected /items/{item_id}');
// app.include_router(staff.router, dependencies=[Depends(require_admin)]) protects every staff route,
// even with a package also called staff imported first; so does a check beside a database session,
// over several lines; a database session alone (orders) protects nothing
assert.deepEqual(openEndpoints(graph), ['POST /orders']);
});