Parcourir la source

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 <noreply@anthropic.com>
pull/1/head
Daniel Covington il y a 18 heures
Parent
révision
7c9c114d29
6 fichiers modifiés avec 67 ajouts et 6 suppressions
  1. +1
    -1
      AGENTS.md
  2. +1
    -2
      README.md
  3. +26
    -1
      app/controllers/ErrorController.asp
  4. +29
    -0
      core/lib.Router.asp
  5. +8
    -0
      tests/phase1-api.sh
  6. +2
    -2
      tests/phase3-learning.sh

+ 1
- 1
AGENTS.md Voir le fichier

@@ -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). - **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". - **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`). - **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. - **`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. - **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. - **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.


+ 1
- 2
README.md Voir le fichier

@@ -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\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\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). - `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)** **Next (not started)**
1. Use feedback in ranking (today it is recorded only), and consolidation of related experiences into candidates. 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`). 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 ## Configuration




+ 26
- 1
app/controllers/ErrorController.asp Voir le fichier

@@ -6,10 +6,19 @@ Class ErrorController_Class
m_useLayout = True m_useLayout = True
End Sub End Sub


' JSON API requests (/api/...) get JSON errors without the HTML layout
Public Property Get useLayout Public Property Get useLayout
useLayout = m_useLayout
If IsApiRequest() Then
useLayout = False
Else
useLayout = m_useLayout
End If
End Property End Property


Private Function IsApiRequest()
IsApiRequest = (LCase(Left(GetRequestPath(), 5)) = "/api/")
End Function

Public Property Let useLayout(v) Public Property Let useLayout(v)
m_useLayout = v m_useLayout = v
End Property End Property
@@ -19,18 +28,34 @@ Class ErrorController_Class
End Sub End Sub


Public Sub NotFound() Public Sub NotFound()
If IsApiRequest() Then
Api_Error 404, "not_found", "No such endpoint."
Exit Sub
End If
Response.Status = "404 Not Found" Response.Status = "404 Not Found"
%> %>
<!--#include file="../views/Error/NotFound.asp" --> <!--#include file="../views/Error/NotFound.asp" -->
<% <%
End Sub 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 "<p>Method not allowed. Use one of: " & Server.HTMLEncode(allow) & ".</p>"
End If
Response.AddHeader "Allow", allow
End Sub

' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls), ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls),
' called through <Name>Controller_Invoke at the bottom of this file. ' called through <Name>Controller_Invoke at the bottom of this file.
Public Sub Invoke(actionName, args) Public Sub Invoke(actionName, args)
Select Case LCase(actionName) Select Case LCase(actionName)
Case "index" : Index Case "index" : Index
Case "notfound" : NotFound Case "notfound" : NotFound
Case "methodnotallowed" : MethodNotAllowed args(0)
Case Else Case Else
Err.Raise 438, "ErrorController_Class", "Action '" & actionName & "' not found" Err.Raise 438, "ErrorController_Class", "Action '" & actionName & "' not found"
End Select End Select


+ 29
- 0
core/lib.Router.asp Voir le fichier

@@ -90,10 +90,39 @@ Public Function Resolve(method, path)
End If End If
Next 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 ' 404 fallback
Resolve = Array("ErrorController", "NotFound", emptyParams) Resolve = Array("ErrorController", "NotFound", emptyParams)
End Function 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()) ' INTERNAL IsMatch(requestPath, routePattern, values())
' Returns True/False and fills values() with parameters ' Returns True/False and fills values() with parameters


+ 8
- 0
tests/phase1-api.sh Voir le fichier

@@ -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: 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)" 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" echo "passed: $PASS failed: $FAIL"
for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
[ "$FAIL" -eq 0 ] [ "$FAIL" -eq 0 ]

+ 2
- 2
tests/phase3-learning.sh Voir le fichier

@@ -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 "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 "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 "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) SID2=$(body "$WK" POST /sessions -d "{\"namespace_id\":\"$NS\",\"objective\":\"done\"}" | jget id)
code "$WK" POST /sessions/$SID2/complete -d '{"outcome":"ok"}' >/dev/null 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"}')" 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 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 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 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" \ 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.\"}" -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"}') R=$(body "$RK" POST /search -d '{"query":"quillfeather daemon gentle"}')


Chargement…
Annuler
Enregistrer

Powered by TurnKey Linux.