From 7c9c114d29078004433e3354aa42f66b3844bab6 Mon Sep 17 00:00:00 2001 From: Daniel Covington Date: Sat, 5 Dec 2026 07:03:23 -0500 Subject: [PATCH] Router: 405 with Allow for known paths, JSON 404/405 for /api requests Router_Class.Resolve falls back to ErrorController.MethodNotAllowed when the path is routed for other methods; ErrorController answers /api/... without the layout in the API error format. Tests: phase1 (79 checks) and phase3-learning assert 405. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- README.md | 3 +-- app/controllers/ErrorController.asp | 27 ++++++++++++++++++++++++++- core/lib.Router.asp | 29 +++++++++++++++++++++++++++++ tests/phase1-api.sh | 8 ++++++++ tests/phase3-learning.sh | 4 ++-- 6 files changed, 67 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7c23ff3..dab935d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -170,7 +170,7 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o - **Static files under `public/`** (for example `public/api/*.openapi.json`) are served directly; the rewrite rule skips existing files and directories. Only routes in `public/Default.asp` go through the MVC dispatcher; a route needs the controller in `autoload_controllers.asp` **and** in `ControllerRegistry` (the generators do both). - **Swagger UI:** the multi-spec dropdown (`urls: [...]`) only works with `presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]` and `layout: "StandaloneLayout"`. Without them the page says "No API definition provided". - **Git Bash:** `curl` sends non-ASCII literals as cp1252, not UTF-8 (use `\u00fc` escapes or a file with `--data-binary @file`); read CSRF tokens from the form with a cookie jar (`-c/-b`); strip `\r` from values printed by Python on Windows before putting them in URLs. Python on Windows also reads piped stdin as cp1252: tests that compare non-ASCII text must call `sys.stdin.reconfigure(encoding='utf-8')` (`python -I` ignores `PYTHONIOENCODING`). -- **No 405 from the router.** A known path with an unrouted method answers 404, like an unknown path. Tests assert 404 for now. +- **405 and API 404s come from the router.** `Router_Class.Resolve` returns `ErrorController.MethodNotAllowed` (with an `Allow` header) when the path is routed for other methods; `ErrorController` answers `/api/...` requests with the JSON error format and no layout. Routing happens before authentication, so a wrong method is 405 even without a key. - **`Api_ToInt` clamps** to its range instead of rejecting, so use it for limits and paging only; validate values that must be rejected when out of range (for example `?revision=`) explicitly. - **SQLite NOT NULL columns and the 8-parameter limit.** Every NOT NULL column without a default must be in the INSERT; when the parameters run out, inline server-generated values that cannot contain user input (for example `Api_Now()` timestamps) rather than moving them to the follow-up UPDATE. - **Include order matters for class methods.** A class method cannot see a global Function/Class defined in a file included *after* the class's file (`GetRouter()`, `Flash()` failed with "Object required" / "doesn't support this property or method"). `core/autoload_core.asp` therefore includes `mvc.asp` last. diff --git a/README.md b/README.md index 7803440..c6dca83 100644 --- a/README.md +++ b/README.md @@ -67,12 +67,11 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec - `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Quote permission lists in PowerShell: `'"read,write"'`. - `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`). - `scripts\embed.cmd status|run|reindex`: semantic index status, catch up on pending/failed items, or rebuild (after changing the model). -- Tests (containers must be running): `bash tests/phase1-api.sh` (74 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (85). Each creates and purges its own tenants. +- Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (85). Each creates and purges its own tenants. **Next (not started)** 1. Use feedback in ranking (today it is recorded only), and consolidation of related experiences into candidates. 2. Import/export API, and management endpoints for namespaces, principals and grants (today only via `provision.cmd`). -3. 405 for a known path with the wrong method (the router answers 404 today). ## Configuration diff --git a/app/controllers/ErrorController.asp b/app/controllers/ErrorController.asp index 3cc2833..0057aed 100644 --- a/app/controllers/ErrorController.asp +++ b/app/controllers/ErrorController.asp @@ -6,10 +6,19 @@ Class ErrorController_Class m_useLayout = True End Sub + ' JSON API requests (/api/...) get JSON errors without the HTML layout Public Property Get useLayout - useLayout = m_useLayout + If IsApiRequest() Then + useLayout = False + Else + useLayout = m_useLayout + End If End Property + Private Function IsApiRequest() + IsApiRequest = (LCase(Left(GetRequestPath(), 5)) = "/api/") + End Function + Public Property Let useLayout(v) m_useLayout = v End Property @@ -19,18 +28,34 @@ Class ErrorController_Class End Sub Public Sub NotFound() + If IsApiRequest() Then + Api_Error 404, "not_found", "No such endpoint." + Exit Sub + End If Response.Status = "404 Not Found" %> <% End Sub + ' The path exists, but not for this HTTP method (resolved by Router_Class.AllowedMethods) + Public Sub MethodNotAllowed(allow) + If IsApiRequest() Then + Api_Error 405, "method_not_allowed", "Use one of: " & allow & "." + Else + Response.Status = "405 Method Not Allowed" + Response.Write "

Method not allowed. Use one of: " & Server.HTMLEncode(allow) & ".

" + End If + Response.AddHeader "Allow", allow + End Sub + ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls), ' called through Controller_Invoke at the bottom of this file. Public Sub Invoke(actionName, args) Select Case LCase(actionName) Case "index" : Index Case "notfound" : NotFound + Case "methodnotallowed" : MethodNotAllowed args(0) Case Else Err.Raise 438, "ErrorController_Class", "Action '" & actionName & "' not found" End Select diff --git a/core/lib.Router.asp b/core/lib.Router.asp index 93e9ec6..05fecf3 100644 --- a/core/lib.Router.asp +++ b/core/lib.Router.asp @@ -90,10 +90,39 @@ Public Function Resolve(method, path) End If Next + ' The path exists for other methods: 405 with the allowed methods (Allow header) + Dim allow + allow = AllowedMethods(path) + If Len(allow) > 0 Then + Resolve = Array("ErrorController", "MethodNotAllowed", Array(allow)) + Exit Function + End If + ' 404 fallback Resolve = Array("ErrorController", "NotFound", emptyParams) End Function +'------------------------------------------------------------ +' AllowedMethods(path) -> "GET, POST" (methods routed for this path), or "" +'------------------------------------------------------------ +Public Function AllowedMethods(path) + Dim r, routeMethod, routePattern, dummy, out + out = "" + For Each r In routes.Keys + routeMethod = Split(r, ":")(0) + routePattern = Mid(r, Len(routeMethod) + 2) + If IsMatch(LCase(path), routePattern, dummy) Then + If InStr(", " & out & ",", ", " & routeMethod & ",") = 0 Then + If Len(out) > 0 Then + out = out & ", " + End If + out = out & routeMethod + End If + End If + Next + AllowedMethods = out +End Function + '------------------------------------------------------------ ' INTERNAL IsMatch(requestPath, routePattern, values()) ' Returns True/False and fills values() with parameters diff --git a/tests/phase1-api.sh b/tests/phase1-api.sh index 81b2622..8aa91f5 100644 --- a/tests/phase1-api.sh +++ b/tests/phase1-api.sh @@ -170,6 +170,14 @@ check "after restart: write works first (cold)" "201" "$(code "$WK" POST /rememb check "after restart: memory persisted" "200" "$(code "$WK" GET /memories/$M1)" check "after restart: checkpoint persisted" "yes" "$(body "$WK" GET /sessions/$SID/state | grep -q '"step":2' && echo yes || echo no)" +# ---- routing: wrong method and unknown API path ------------------------------------------------------------ +R=$(curl -s -i -X DELETE "$BASE/recall") +check "wrong method -> 405" "yes" "$(grep -q '^HTTP/1.1 405' <<<"$R" && echo yes || echo no)" +check "405 carries Allow" "yes" "$(grep -qi '^Allow: POST' <<<"$R" && echo yes || echo no)" +check "405 body is JSON error" "yes" "$(has '"code":"method_not_allowed"' "$R")" +check "unknown API path -> JSON 404" "yes" "$(curl -s "$BASE/no-such-endpoint" | grep -q '"code":"not_found"' && echo yes || echo no)" +check "unknown page stays 404" "404" "$(curl -s -o /dev/null -w '%{http_code}' "${BASE%/api/v1}/no-such-page")" + echo "passed: $PASS failed: $FAIL" for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done [ "$FAIL" -eq 0 ] diff --git a/tests/phase3-learning.sh b/tests/phase3-learning.sh index e0bc54e..23a7f97 100644 --- a/tests/phase3-learning.sh +++ b/tests/phase3-learning.sh @@ -78,7 +78,7 @@ check "event by reader (no write) -> 404" "404" "$(code "$RK" POST /sessions/$SI check "event from other tenant -> 404" "404" "$(code "$BK" POST /sessions/$SID/events -d '{"task":"x","outcome":"success"}')" check "events read by blind -> 404" "404" "$(code "$BLK" GET /sessions/$SID/events)" check "event unknown session -> 404" "404" "$(code "$WK" POST /sessions/00000000-0000-4000-8000-000000000000/events -d '{"task":"x","outcome":"success"}')" -check "events wrong method -> 404 (router has no 405)" "404" "$(code "$WK" DELETE /sessions/$SID/events)" +check "events wrong method -> 405" "405" "$(code "$WK" DELETE /sessions/$SID/events)" SID2=$(body "$WK" POST /sessions -d "{\"namespace_id\":\"$NS\",\"objective\":\"done\"}" | jget id) code "$WK" POST /sessions/$SID2/complete -d '{"outcome":"ok"}' >/dev/null check "event on completed session -> 409" "409" "$(code "$WK" POST /sessions/$SID2/events -d '{"task":"x","outcome":"success"}')" @@ -180,7 +180,7 @@ check "feedback on result not in query -> 404" "404" "$(code "$RK" POST /feedbac check "feedback from other tenant -> 404" "404" "$(code "$BK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MEM1\",\"usefulness\":\"useful\"}")" check "feedback bad usefulness -> 422" "422" "$(code "$RK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MEM1\",\"usefulness\":\"meh\"}")" check "feedback bad query id -> 422" "422" "$(code "$RK" POST /feedback -d "{\"query_id\":\"abc\",\"result_id\":\"$MEM1\",\"usefulness\":\"useful\"}")" -check "feedback wrong method -> 404 (router has no 405)" "404" "$(code "$RK" GET /feedback)" +check "feedback wrong method -> 405" "405" "$(code "$RK" GET /feedback)" curl -s -o /dev/null -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" \ -d "{\"namespace_id\":\"$NS\",\"title\":\"Runbook\",\"source_uri\":\"kb://rb\",\"format\":\"markdown\",\"content\":\"# Runbook\n\nRestart the quillfeather daemon with the gentle flag.\"}" R=$(body "$RK" POST /search -d '{"query":"quillfeather daemon gentle"}')