From 87009ec86190df7c90f3642b05365e8c60693514 Mon Sep 17 00:00:00 2001 From: Daniel Covington Date: Fri, 4 Dec 2026 16:45:08 -0500 Subject: [PATCH] Add Phase 1 memory API: auth, memories, sessions, health - lib.Api.asp: bearer-key auth (SHA-256 only), namespace grants with inheritance, audit trail, idempotency, JSON error format - ApiMemoriesController: remember (duplicate detection), list with cursor paging, fetch by revision, correct (If-Match), retire, forget, versions - ApiSessionsController: start, checkpoint save/restore with If-Match concurrency, complete - ApiHealthController: live/ready - JsonLite: raw nested capture, string arrays, surrogate-pair escapes - scripts/provision.*: tenants, principals, keys, namespaces, grants, purge; CLI tools now run as the server user (db ownership) - tests/phase1-api.sh: 71 checks incl. tenant isolation, permissions, idempotency, checkpoints, UTF-8, restart persistence Co-Authored-By: Claude Sonnet 5.5 --- app/controllers/ApiHealthController.asp | 64 ++ app/controllers/ApiMemoriesController.asp | 748 ++++++++++++++++++++++ app/controllers/ApiSessionsController.asp | 331 ++++++++++ app/controllers/autoload_controllers.asp | 3 + core/autoload_core.asp | 1 + core/lib.Api.asp | 451 +++++++++++++ core/lib.ControllerRegistry.asp | 3 + core/lib.JsonLite.asp | 116 +++- public/Default.asp | 19 + scripts/gen.cmd | 4 +- scripts/migrate.cmd | 2 +- scripts/provision.asp | 203 ++++++ scripts/provision.cmd | 19 + tests/phase1-api.sh | 168 +++++ 14 files changed, 2125 insertions(+), 7 deletions(-) create mode 100644 app/controllers/ApiHealthController.asp create mode 100644 app/controllers/ApiMemoriesController.asp create mode 100644 app/controllers/ApiSessionsController.asp create mode 100644 core/lib.Api.asp create mode 100644 scripts/provision.asp create mode 100644 scripts/provision.cmd create mode 100644 tests/phase1-api.sh diff --git a/app/controllers/ApiHealthController.asp b/app/controllers/ApiHealthController.asp new file mode 100644 index 0000000..777f70f --- /dev/null +++ b/app/controllers/ApiHealthController.asp @@ -0,0 +1,64 @@ +<% +' ApiHealthController: liveness and readiness probes (spec 9, health). No authentication, no tenant data. +' +' GET /api/v1/health/live Live 200 while the process answers +' GET /api/v1/health/ready Ready 200 when the database answers, else 503 +Class ApiHealthController_Class + Public Property Get useLayout() + useLayout = False + End Property + + Public Property Let useLayout(v) + End Property + + Public Property Get Title() + Title = "Health" + End Property + + Public Sub Live() + Api_Send 200, "{""status"":""live""}" + End Sub + + Public Sub Ready() + Dim rs, ok + ok = False + On Error Resume Next + Set rs = DAL().Query("SELECT 1", Empty) + If Err.Number = 0 Then + ok = Not rs.EOF + rs.Close + End If + Err.Clear + On Error GoTo 0 + If ok Then + Api_Send 200, "{""status"":""ready""}" + Else + Api_Send 503, "{""status"":""unavailable""}" + End If + End Sub + + ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) + Public Sub Invoke(actionName, args) + Select Case LCase(actionName) + Case "live" : Live + Case "ready" : Ready + Case Else + Err.Raise 438, "ApiHealthController_Class", "Action '" & actionName & "' not found" + End Select + End Sub + +End Class + +Dim ApiHealthController_Class__Singleton +Function ApiHealthController() + If IsEmpty(ApiHealthController_Class__Singleton) Then + Set ApiHealthController_Class__Singleton = New ApiHealthController_Class + End If + Set ApiHealthController = ApiHealthController_Class__Singleton +End Function + +' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) +Sub ApiHealthController_Invoke(actionName, args) + ApiHealthController().Invoke actionName, args +End Sub +%> diff --git a/app/controllers/ApiMemoriesController.asp b/app/controllers/ApiMemoriesController.asp new file mode 100644 index 0000000..c5b975c --- /dev/null +++ b/app/controllers/ApiMemoriesController.asp @@ -0,0 +1,748 @@ +<% +' ApiMemoriesController: canonical memory records (spec FR-001..FR-005, FR-011, FR-015). +' Stateless JSON API, no layout. Helpers (auth, errors, idempotency) are in core/lib.Api.asp. +' +' POST /api/v1/remember Remember create a memory (Idempotency-Key supported; exact duplicates detected) +' GET /api/v1/memories Recent list/filter, newest first, cursor pagination +' GET /api/v1/memories/:id Fetch one memory (?revision=n for an older revision) +' PATCH /api/v1/memories/:id Correct new revision; needs If-Match: (or "expected_revision") +' DELETE /api/v1/memories/:id Forget permanent delete incl. revision history +' POST /api/v1/memories/:id/retire Retire exclude from ordinary retrieval +' GET /api/v1/memories/:id/versions Versions revision history +' +' Permissions on the memory's namespace: read (Fetch/Recent/Versions), write (Remember/Correct/Retire), delete (Forget). +' Anything the caller may not see is a 404. +Class ApiMemoriesController_Class + Private m_errs + + Public Property Get useLayout() + useLayout = False + End Property + + Public Property Let useLayout(v) + End Property + + Public Property Get Title() + Title = "Memories API" + End Property + + '--------------------------------------------------------------- + ' POST /api/v1/remember + '--------------------------------------------------------------- + Public Sub Remember() + Dim body, input, idemKey, reqHash, nsId, memType, title, content, summary, tagsRaw, attrRaw + Dim confidence, importance, hash, memId, revId, ts, resp, rs, errs, k, warnings + + If Not Api_Authenticate() Then Exit Sub + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + + idemKey = Api_Header("Idempotency-Key") + If Len(idemKey) > 200 Then + Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters." + Exit Sub + End If + reqHash = Api_Sha256(body) + If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub + + m_errs = "" + nsId = ReqString(input, "namespace_id", 64) + memType = ReqString(input, "type", 40) + title = ReqString(input, "title", 200) + content = ReqString(input, "content", 100000) + summary = OptString(input, "summary", 2000) + tagsRaw = TagsJson(input) + attrRaw = AttributesJson(input) + confidence = OptUnit(input, "confidence") + importance = OptUnit(input, "importance") + If Len(m_errs) > 0 Then + Api_Invalid Split(m_errs, Chr(30)) + Exit Sub + End If + + ' Concealment: a namespace the caller cannot write to looks the same as one that does not exist. + If Not Api_CanAccessNamespace(nsId, "write") Then + Api_Audit "memory.remember", "namespace", nsId, "denied" + Api_Error 404, "namespace_not_found", "Namespace not found." + Exit Sub + End If + + Set rs = DAL().Query("SELECT 1 FROM memory_types WHERE code = ?", memType) + If rs.EOF Then + rs.Close + Api_Invalid Array("type '" & memType & "' is not a known memory type.") + Exit Sub + End If + rs.Close + + hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content) + + ' Exact duplicate of an active memory in the same namespace: return it instead of creating another. + Set rs = DAL().Query("SELECT m.id, m.current_revision, r.verification_status FROM memories m " & _ + "JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _ + "WHERE m.tenant_id = ? AND m.namespace_id = ? AND m.type = ? AND m.lifecycle_status = 'active' AND r.content_hash = ?", _ + Array(Api_TenantId, nsId, memType, hash)) + If Not rs.EOF Then + resp = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""revision"":" & CLng(rs(1)) & ",""status"":""active"",""verification_status"":" & _ + JsonLite_Quote("" & rs(2)) & ",""indexing_status"":""not_indexed"",""duplicate"":true}" + rs.Close + StoreIdem idemKey, reqHash, 200, resp + Api_Send 200, resp + Exit Sub + End If + rs.Close + + memId = Api_NewId() + revId = Api_NewId() + ts = Api_Now() + + On Error Resume Next + DAL().BeginTransaction + DAL().Execute "INSERT INTO memories (id, tenant_id, namespace_id, type, current_revision, lifecycle_status, creator_principal_id, created_at, updated_at) " & _ + "VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts) + InsertRevision revId, memId, 1, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, "created", ts + resp = "{""id"":" & JsonLite_Quote(memId) & ",""revision"":1,""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""not_indexed"",""duplicate"":false}" + StoreIdem idemKey, reqHash, 201, resp + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + DAL().RollbackTransaction + Api_DbFailed k, "" + Exit Sub + End If + DAL().CommitTransaction + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Api_DbFailed k, "" + Exit Sub + End If + On Error GoTo 0 + + Api_Audit "memory.remember", "memory", memId, "ok" + Response.AddHeader "Location", "/api/v1/memories/" & memId + Api_Send 201, resp + End Sub + + '--------------------------------------------------------------- + ' GET /api/v1/memories ?namespace_id= &type= &status=active|retired|superseded|all &verification_status= &limit= &cursor= + '--------------------------------------------------------------- + Public Sub Recent() + Dim nsId, memType, status, ver, lim, cursor, allowed, sql, params(), n, rs, out, count, lastTs, lastId, p, cts, cid, nextCursor + + If Not Api_Authenticate() Then Exit Sub + + nsId = Trim("" & Request.QueryString("namespace_id")) + memType = Trim("" & Request.QueryString("type")) + status = LCase(Trim("" & Request.QueryString("status"))) + ver = LCase(Trim("" & Request.QueryString("verification_status"))) + lim = Api_ToInt(Request.QueryString("limit"), 20, 1, 100) + cursor = Trim("" & Request.QueryString("cursor")) + If Len(status) = 0 Then status = "active" + + If status <> "active" And status <> "retired" And status <> "superseded" And status <> "all" Then + Api_Invalid Array("status must be active, retired, superseded or all.") + Exit Sub + End If + If Len(ver) > 0 And ver <> "unverified" And ver <> "verified" And ver <> "disputed" And ver <> "rejected" Then + Api_Invalid Array("verification_status must be unverified, verified, disputed or rejected.") + Exit Sub + End If + + If Len(nsId) > 0 Then + If Not Api_CanAccessNamespace(nsId, "read") Then + Api_Error 404, "namespace_not_found", "Namespace not found." + Exit Sub + End If + allowed = "'" & nsId & "'" + Else + allowed = Api_AllowedNamespaceIds("read") + End If + + If Len(allowed) = 0 Then + Api_Send 200, "{""data"":[],""next_cursor"":null}" + Exit Sub + End If + + sql = MemorySelect() & " WHERE m.tenant_id = ? AND m.namespace_id IN (" & allowed & ")" + ReDim params(0) + params(0) = Api_TenantId + n = 1 + If Len(memType) > 0 Then + sql = sql & " AND m.type = ?" + ReDim Preserve params(n) + params(n) = memType + n = n + 1 + End If + If status <> "all" Then + sql = sql & " AND m.lifecycle_status = ?" + ReDim Preserve params(n) + params(n) = status + n = n + 1 + End If + If Len(ver) > 0 Then + sql = sql & " AND r.verification_status = ?" + ReDim Preserve params(n) + params(n) = ver + n = n + 1 + End If + If Len(cursor) > 0 Then + p = InStr(cursor, "|") + cts = "" + cid = "" + If p > 0 Then + cts = Left(cursor, p - 1) + cid = Mid(cursor, p + 1) + End If + If Len(cts) = 0 Or Not Api_IsId(cid) Then + Api_Error 400, "invalid_cursor", "The cursor is not valid." + Exit Sub + End If + sql = sql & " AND (m.created_at < ? OR (m.created_at = ? AND m.id < ?))" + ReDim Preserve params(n + 2) + params(n) = cts + params(n + 1) = cts + params(n + 2) = cid + n = n + 3 + End If + ' G3DB accepts at most 8 parameters (tenant + type + status + verification + 3 cursor = 7) + sql = sql & " ORDER BY m.created_at DESC, m.id DESC LIMIT " & (lim + 1) + + Set rs = DAL().Query(sql, params) + out = "" + count = 0 + lastTs = "" + lastId = "" + nextCursor = "null" + Do While Not rs.EOF + If count >= lim Then + nextCursor = JsonLite_Quote(lastTs & "|" & lastId) + Exit Do + End If + If count > 0 Then out = out & "," + out = out & MemoryJson(rs, True) + lastTs = "" & rs(8) + lastId = "" & rs(0) + count = count + 1 + rs.MoveNext + Loop + rs.Close + Api_Send 200, "{""data"":[" & out & "],""next_cursor"":" & nextCursor & "}" + End Sub + + '--------------------------------------------------------------- + ' GET /api/v1/memories/:id (?revision=n) + '--------------------------------------------------------------- + Public Sub Fetch(id) + Dim rs, nsId, revParam, rev, json + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + + ' The row is copied out and the result set closed BEFORE the permission check: a second query while a + ' result set is still open hangs the request under G3DB/SQLite (script timeout). + Set rs = DAL().Query(MemorySelect() & " WHERE m.id = ? AND m.tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Sub + End If + nsId = "" & rs(1) + json = MemoryJson(rs, False) + rs.Close + If Not Api_CanAccessNamespace(nsId, "read") Then + Api_NotFound + Exit Sub + End If + + revParam = Trim("" & Request.QueryString("revision")) + If Len(revParam) = 0 Then + Api_Send 200, "{""data"":" & json & "}" + Exit Sub + End If + + If Not IsNumeric(revParam) Then + Api_Invalid Array("revision must be a positive integer.") + Exit Sub + End If + rev = CLng(revParam) + Set rs = DAL().Query(MemorySelectRevision() & " WHERE m.id = ? AND m.tenant_id = ?", Array(rev, id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Sub + End If + json = MemoryJson(rs, False) + rs.Close + Api_Send 200, "{""data"":" & json & "}" + End Sub + + '--------------------------------------------------------------- + ' PATCH /api/v1/memories/:id creates revision n+1 (unverified) + '--------------------------------------------------------------- + Public Sub Correct(id) + Dim body, input, rs, nsId, curRev, expected, ifMatch, lifecycle + Dim title, content, summary, tagsRaw, attrRaw, confidence, importance, reason, hash, ts, newRev, memType, k, resp + Dim hasTitle, hasContent, hasSummary, hasTags, hasAttr, hasConf, hasImp + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + + Set rs = DAL().Query("SELECT m.namespace_id, m.current_revision, m.lifecycle_status, m.type, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance " & _ + "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _ + "WHERE m.id = ? AND m.tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Sub + End If + nsId = "" & rs(0) + curRev = CLng(rs(1)) + lifecycle = "" & rs(2) + memType = "" & rs(3) + title = rs(4) + summary = rs(5) + content = rs(6) + attrRaw = rs(7) + tagsRaw = rs(8) + confidence = rs(9) + importance = rs(10) + rs.Close + + If Not Api_CanAccessNamespace(nsId, "write") Then + Api_NotFound + Exit Sub + End If + + ' Optimistic concurrency: the caller must say which revision they edited. + ifMatch = Replace(Replace(Api_Header("If-Match"), """", ""), "W/", "") + expected = ifMatch + If Len(expected) = 0 And input.Exists("expected_revision") Then expected = "" & input.Item("expected_revision") + If Len(expected) = 0 Then + Api_Error 428, "precondition_required", "Send If-Match: (or ""expected_revision"" in the body)." + Exit Sub + End If + If Not IsNumeric(expected) Then + Api_Error 400, "invalid_revision", "If-Match / expected_revision must be a revision number." + Exit Sub + End If + If CLng(expected) <> curRev Then + Response.AddHeader "ETag", """" & curRev & """" + Api_Error 412, "stale_revision", "The memory is at revision " & curRev & ", not " & CLng(expected) & ". Re-read it and retry." + Exit Sub + End If + If lifecycle <> "active" Then + Api_Error 409, "not_active", "A " & lifecycle & " memory cannot be corrected." + Exit Sub + End If + + m_errs = "" + hasTitle = input.Exists("title") + hasContent = input.Exists("content") + hasSummary = input.Exists("summary") + hasTags = input.Exists("tags") Or input.HasRaw("tags") + hasAttr = input.Exists("attributes") Or input.HasRaw("attributes") + hasConf = input.Exists("confidence") + hasImp = input.Exists("importance") + If hasTitle Then title = ReqString(input, "title", 200) + If hasContent Then content = ReqString(input, "content", 100000) + If hasSummary Then summary = OptString(input, "summary", 2000) + If hasTags Then tagsRaw = TagsJson(input) + If hasAttr Then attrRaw = AttributesJson(input) + If hasConf Then confidence = OptUnit(input, "confidence") + If hasImp Then importance = OptUnit(input, "importance") + reason = OptString(input, "change_reason", 500) + If Not (hasTitle Or hasContent Or hasSummary Or hasTags Or hasAttr Or hasConf Or hasImp) Then + m_errs = m_errs & Chr(30) & "Send at least one field to change." + End If + If Left(m_errs, 1) = Chr(30) Then m_errs = Mid(m_errs, 2) + If Len(m_errs) > 0 Then + Api_Invalid Split(m_errs, Chr(30)) + Exit Sub + End If + If IsNull(reason) Or Len("" & reason) = 0 Then reason = "corrected" + + hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content) + ts = Api_Now() + newRev = curRev + 1 + + On Error Resume Next + DAL().BeginTransaction + InsertRevision Api_NewId(), id, newRev, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts + DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _ + Array(newRev, ts, id, Api_TenantId, curRev) + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + DAL().RollbackTransaction + Api_DbFailed k, "" + Exit Sub + End If + DAL().CommitTransaction + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Api_DbFailed k, "" + Exit Sub + End If + On Error GoTo 0 + + Api_Audit "memory.correct", "memory", id, "ok" + Response.AddHeader "ETag", """" & newRev & """" + resp = "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""not_indexed""}" + Api_Send 200, resp + End Sub + + '--------------------------------------------------------------- + ' DELETE /api/v1/memories/:id + '--------------------------------------------------------------- + Public Sub Forget(id) + Dim rs, nsId, k + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Sub + End If + nsId = "" & rs(0) + rs.Close + If Not Api_CanAccessNamespace(nsId, "delete") Then + Api_Audit "memory.forget", "memory", id, "denied" + Api_NotFound + Exit Sub + End If + + On Error Resume Next + DAL().BeginTransaction + DAL().Execute "DELETE FROM memory_revisions WHERE memory_id = ?", id + DAL().Execute "DELETE FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId) + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + DAL().RollbackTransaction + Api_DbFailed k, "" + Exit Sub + End If + DAL().CommitTransaction + On Error GoTo 0 + + Api_Audit "memory.forget", "memory", id, "ok" + Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}" + End Sub + + '--------------------------------------------------------------- + ' POST /api/v1/memories/:id/retire + '--------------------------------------------------------------- + Public Sub Retire(id) + Dim rs, nsId, k + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Sub + End If + nsId = "" & rs(0) + rs.Close + If Not Api_CanAccessNamespace(nsId, "write") Then + Api_NotFound + Exit Sub + End If + + On Error Resume Next + DAL().Execute "UPDATE memories SET lifecycle_status = 'retired', updated_at = ? WHERE id = ? AND tenant_id = ?", Array(Api_Now(), id, Api_TenantId) + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Api_DbFailed k, "" + Exit Sub + End If + On Error GoTo 0 + + Api_Audit "memory.retire", "memory", id, "ok" + Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""status"":""retired""}" + End Sub + + '--------------------------------------------------------------- + ' GET /api/v1/memories/:id/versions + '--------------------------------------------------------------- + Public Sub Versions(id) + Dim rs, nsId, out, count + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Sub + End If + nsId = "" & rs(0) + rs.Close + If Not Api_CanAccessNamespace(nsId, "read") Then + Api_NotFound + Exit Sub + End If + + Set rs = DAL().Query("SELECT revision, title, summary, content, tags, confidence, importance, verification_status, change_reason, created_by, created_at " & _ + "FROM memory_revisions WHERE memory_id = ? ORDER BY revision DESC", id) + out = "" + count = 0 + Do While Not rs.EOF + If count > 0 Then out = out & "," + out = out & "{""revision"":" & CLng(rs(0)) & ",""title"":" & JsonLite_Quote("" & rs(1)) & ",""summary"":" & JStr(rs(2)) & _ + ",""content"":" & JsonLite_Quote("" & rs(3)) & ",""tags"":" & JRaw(rs(4), "[]") & ",""confidence"":" & JNum(rs(5)) & _ + ",""importance"":" & JNum(rs(6)) & ",""verification_status"":" & JsonLite_Quote("" & rs(7)) & _ + ",""change_reason"":" & JStr(rs(8)) & ",""created_by"":" & JsonLite_Quote("" & rs(9)) & ",""created_at"":" & JsonLite_Quote("" & rs(10)) & "}" + count = count + 1 + rs.MoveNext + Loop + rs.Close + Api_Send 200, "{""data"":[" & out & "]}" + End Sub + + '=============================================================== + ' Helpers + '=============================================================== + ' Memory + current revision. Column order is relied on by MemoryJson: + ' 0 id, 1 namespace_id, 2 type, 3 current_revision, 4 lifecycle_status, 5 valid_from, 6 valid_until, 7 creator, 8 created_at, 9 updated_at, + ' 10 revision, 11 title, 12 summary, 13 content, 14 attributes, 15 tags, 16 confidence, 17 importance, 18 verification_status, 19 change_reason + Private Function MemorySelect() + MemorySelect = "SELECT m.id, m.namespace_id, m.type, m.current_revision, m.lifecycle_status, m.valid_from, m.valid_until, m.creator_principal_id, m.created_at, m.updated_at, " & _ + "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _ + "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision" + End Function + + ' Same columns but a specific revision (first parameter is the revision number) + Private Function MemorySelectRevision() + MemorySelectRevision = "SELECT m.id, m.namespace_id, m.type, m.current_revision, m.lifecycle_status, m.valid_from, m.valid_until, m.creator_principal_id, m.created_at, m.updated_at, " & _ + "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _ + "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = ?" + End Function + + Private Function MemoryJson(rs, brief) + Dim s + s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _ + ",""status"":" & JsonLite_Quote("" & rs(4)) & ",""current_revision"":" & CLng(rs(3)) & ",""revision"":" & CLng(rs(10)) & _ + ",""verification_status"":" & JsonLite_Quote("" & rs(18)) & ",""title"":" & JsonLite_Quote("" & rs(11)) & ",""summary"":" & JStr(rs(12)) + If Not brief Then + s = s & ",""content"":" & JsonLite_Quote("" & rs(13)) & ",""attributes"":" & JRaw(rs(14), "null") & ",""change_reason"":" & JStr(rs(19)) & _ + ",""valid_from"":" & JStr(rs(5)) & ",""valid_until"":" & JStr(rs(6)) & ",""created_by"":" & JsonLite_Quote("" & rs(7)) + End If + s = s & ",""tags"":" & JRaw(rs(15), "[]") & ",""confidence"":" & JNum(rs(16)) & ",""importance"":" & JNum(rs(17)) & _ + ",""created_at"":" & JsonLite_Quote("" & rs(8)) & ",""updated_at"":" & JsonLite_Quote("" & rs(9)) & "}" + MemoryJson = s + End Function + + Private Function JStr(v) + If IsNull(v) Then + JStr = "null" + Else + JStr = JsonLite_Quote("" & v) + End If + End Function + + Private Function JNum(v) + If IsNull(v) Then + JNum = "null" + ElseIf Len("" & v) = 0 Then + JNum = "null" + Else + JNum = JsonLite_Num(v) + End If + End Function + + ' Stored raw JSON text (validated on the way in) or a default + Private Function JRaw(v, dflt) + If IsNull(v) Then + JRaw = dflt + ElseIf Len("" & v) = 0 Then + JRaw = dflt + Else + JRaw = "" & v + End If + End Function + + Private Sub AddErr(msg) + If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30) + m_errs = m_errs & msg + End Sub + + Private Function ReqString(input, name, maxLen) + Dim v + ReqString = "" + If Not input.Exists(name) Then + AddErr name & " is required." + Exit Function + End If + v = input.Item(name) + If IsNull(v) Then + AddErr name & " is required." + Exit Function + End If + If VarType(v) <> vbString Then + AddErr name & " must be a string." + Exit Function + End If + v = Trim(v) + If Len(v) = 0 Then + AddErr name & " must not be empty." + Exit Function + End If + If Len(v) > maxLen Then + AddErr name & " must be at most " & maxLen & " characters." + Exit Function + End If + ReqString = v + End Function + + ' Optional string: Null when absent or null + Private Function OptString(input, name, maxLen) + Dim v + OptString = Null + If Not input.Exists(name) Then Exit Function + v = input.Item(name) + If IsNull(v) Then Exit Function + If VarType(v) <> vbString Then + AddErr name & " must be a string." + Exit Function + End If + If Len(v) > maxLen Then + AddErr name & " must be at most " & maxLen & " characters." + Exit Function + End If + OptString = v + End Function + + ' Optional number in 0..1: Null when absent or null + Private Function OptUnit(input, name) + Dim v + OptUnit = Null + If Not input.Exists(name) Then Exit Function + v = input.Item(name) + If IsNull(v) Then Exit Function + If VarType(v) <> vbDouble Then + AddErr name & " must be a number between 0 and 1." + Exit Function + End If + If v < 0 Or v > 1 Then + AddErr name & " must be between 0 and 1." + Exit Function + End If + OptUnit = v + End Function + + ' tags: optional array of non-empty strings; returns compact JSON text or Null + Private Function TagsJson(input) + Dim arr, i, out, t + TagsJson = Null + If Not input.HasRaw("tags") Then + If input.Exists("tags") Then + If Not IsNull(input.Item("tags")) Then AddErr "tags must be an array of strings." + End If + Exit Function + End If + arr = JsonLite_ParseStringArray(input.Raw("tags")) + If IsNull(arr) Then + AddErr "tags must be an array of strings." + Exit Function + End If + If UBound(arr) > 31 Then + AddErr "tags may contain at most 32 entries." + Exit Function + End If + out = "" + For i = 0 To UBound(arr) + t = Trim(arr(i)) + If Len(t) = 0 Or Len(t) > 64 Then + AddErr "each tag must be 1 to 64 characters." + Exit Function + End If + If i > 0 Then out = out & "," + out = out & JsonLite_Quote(t) + Next + TagsJson = "[" & out & "]" + End Function + + ' attributes: optional JSON object, stored as its raw text (max 16 KB) or Null + Private Function AttributesJson(input) + Dim raw + AttributesJson = Null + If Not input.HasRaw("attributes") Then + If input.Exists("attributes") Then + If Not IsNull(input.Item("attributes")) Then AddErr "attributes must be a JSON object." + End If + Exit Function + End If + raw = input.Raw("attributes") + If Left(raw, 1) <> "{" Then + AddErr "attributes must be a JSON object." + Exit Function + End If + If Len(raw) > 16384 Then + AddErr "attributes must be at most 16 KB." + Exit Function + End If + AttributesJson = raw + End Function + + ' G3DB allows at most 8 parameters per statement, so a revision is written in two steps (same transaction). + Private Sub InsertRevision(revId, memId, revNo, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts) + DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) " & _ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Array(revId, memId, revNo, title, content, hash, Api_PrincipalId, ts) + DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ? WHERE id = ?", _ + Array(summary, attrRaw, tagsRaw, confidence, importance, reason, revId) + End Sub + + Private Sub StoreIdem(idemKey, reqHash, status, resp) + Api_IdempotencyStore idemKey, reqHash, status, resp + End Sub + + ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) + Public Sub Invoke(actionName, args) + Select Case LCase(actionName) + Case "remember" : Remember + Case "recent" : Recent + Case "fetch" : Fetch args(0) + Case "correct" : Correct args(0) + Case "forget" : Forget args(0) + Case "retire" : Retire args(0) + Case "versions" : Versions args(0) + Case Else + Err.Raise 438, "ApiMemoriesController_Class", "Action '" & actionName & "' not found" + End Select + End Sub + +End Class + +Dim ApiMemoriesController_Class__Singleton +Function ApiMemoriesController() + If IsEmpty(ApiMemoriesController_Class__Singleton) Then + Set ApiMemoriesController_Class__Singleton = New ApiMemoriesController_Class + End If + Set ApiMemoriesController = ApiMemoriesController_Class__Singleton +End Function + +' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) +Sub ApiMemoriesController_Invoke(actionName, args) + ApiMemoriesController().Invoke actionName, args +End Sub +%> diff --git a/app/controllers/ApiSessionsController.asp b/app/controllers/ApiSessionsController.asp new file mode 100644 index 0000000..c411963 --- /dev/null +++ b/app/controllers/ApiSessionsController.asp @@ -0,0 +1,331 @@ +<% +' ApiSessionsController: agent sessions and working-state checkpoints (spec FR-012, AC-09, AC-10). +' Stateless JSON API, no layout. Helpers (auth, errors, idempotency) are in core/lib.Api.asp. +' +' POST /api/v1/sessions Start {"namespace_id","objective"} -> 201 {"id","status","revision":0} +' PUT /api/v1/sessions/:id/state SaveState {"state":{...}} with If-Match: (0 = none yet) +' GET /api/v1/sessions/:id/state RestoreState latest checkpoint (revision 0 / state null when none) +' POST /api/v1/sessions/:id/complete Complete {"outcome":"..."} optional +' +' Permissions on the session's namespace: write (Start/SaveState/Complete), read (RestoreState). Any principal with +' access to the namespace may resume the session. Stale revisions get 412 and never overwrite a newer checkpoint. +Class ApiSessionsController_Class + Public Property Get useLayout() + useLayout = False + End Property + + Public Property Let useLayout(v) + End Property + + Public Property Get Title() + Title = "Sessions API" + End Property + + '--------------------------------------------------------------- + ' POST /api/v1/sessions + '--------------------------------------------------------------- + Public Sub Start() + Dim body, input, nsId, objective, idemKey, reqHash, id, ts, resp, k, errs + + If Not Api_Authenticate() Then Exit Sub + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + + idemKey = Api_Header("Idempotency-Key") + If Len(idemKey) > 200 Then + Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters." + Exit Sub + End If + reqHash = Api_Sha256(body) + If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub + + errs = "" + nsId = StringField(input, "namespace_id", 64, errs) + objective = StringField(input, "objective", 2000, errs) + If Len(errs) > 0 Then + Api_Invalid Split(errs, Chr(30)) + Exit Sub + End If + If Not Api_CanAccessNamespace(nsId, "write") Then + Api_Error 404, "namespace_not_found", "Namespace not found." + Exit Sub + End If + + id = Api_NewId() + ts = Api_Now() + resp = "{""id"":" & JsonLite_Quote(id) & ",""status"":""active"",""revision"":0}" + + On Error Resume Next + DAL().BeginTransaction + DAL().Execute "INSERT INTO sessions (id, tenant_id, namespace_id, principal_id, objective, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'active', ?, ?)", _ + Array(id, Api_TenantId, nsId, Api_PrincipalId, objective, ts, ts) + Api_IdempotencyStore idemKey, reqHash, 201, resp + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + DAL().RollbackTransaction + Api_DbFailed k, "" + Exit Sub + End If + DAL().CommitTransaction + On Error GoTo 0 + + Api_Audit "session.start", "session", id, "ok" + Response.AddHeader "Location", "/api/v1/sessions/" & id + Api_Send 201, resp + End Sub + + '--------------------------------------------------------------- + ' PUT /api/v1/sessions/:id/state + '--------------------------------------------------------------- + Public Sub SaveState(id) + Dim body, input, nsId, status, curRev, ifMatch, expected, rs, stateRaw, ts, newRev, k, resp + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + + If Not LoadSession(id, nsId, status, curRev) Then Exit Sub + If Not Api_CanAccessNamespace(nsId, "write") Then + Api_NotFound + Exit Sub + End If + If status <> "active" Then + Api_Error 409, "session_closed", "The session is " & status & "; its state can no longer change." + Exit Sub + End If + + If Not input.HasRaw("state") Then + Api_Invalid Array("state is required and must be a JSON object.") + Exit Sub + End If + stateRaw = input.Raw("state") + If Left(stateRaw, 1) <> "{" Then + Api_Invalid Array("state must be a JSON object.") + Exit Sub + End If + If Len(stateRaw) > 65536 Then + Api_Invalid Array("state must be at most 64 KB.") + Exit Sub + End If + + ifMatch = Replace(Replace(Api_Header("If-Match"), """", ""), "W/", "") + expected = ifMatch + If Len(expected) = 0 And input.Exists("expected_revision") Then expected = "" & input.Item("expected_revision") + If Len(expected) = 0 Then + Api_Error 428, "precondition_required", "Send If-Match: (0 when there is none), or ""expected_revision"" in the body." + Exit Sub + End If + If Not IsNumeric(expected) Then + Api_Error 400, "invalid_revision", "If-Match / expected_revision must be a revision number." + Exit Sub + End If + If CLng(expected) <> curRev Then + Response.AddHeader "ETag", """" & curRev & """" + Api_Error 412, "stale_revision", "The session state is at revision " & curRev & ", not " & CLng(expected) & ". Restore it again before saving." + Exit Sub + End If + + newRev = curRev + 1 + ts = Api_Now() + On Error Resume Next + ' UNIQUE (session_id, revision) rejects a concurrent writer that passed the check above + DAL().Execute "INSERT INTO checkpoints (id, session_id, revision, state, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)", _ + Array(Api_NewId(), id, newRev, stateRaw, Api_PrincipalId, ts) + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Err.Clear + On Error GoTo 0 + If InStr(LCase(Api_LastDbError), "unique") > 0 Then + Api_Error 412, "stale_revision", "Another checkpoint was saved first. Restore the state again before saving." + Else + Api_DbFailed k, "" + End If + Exit Sub + End If + DAL().Execute "UPDATE sessions SET updated_at = ? WHERE id = ?", Array(ts, id) + On Error GoTo 0 + + Api_Audit "session.save_state", "session", id, "ok" + Response.AddHeader "ETag", """" & newRev & """" + resp = "{""session_id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""saved_at"":" & JsonLite_Quote(ts) & "}" + Api_Send 200, resp + End Sub + + '--------------------------------------------------------------- + ' GET /api/v1/sessions/:id/state + '--------------------------------------------------------------- + Public Sub RestoreState(id) + Dim nsId, status, curRev, rs, objective, stateJson, savedAt, savedBy, json + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + If Not LoadSession(id, nsId, status, curRev) Then Exit Sub + If Not Api_CanAccessNamespace(nsId, "read") Then + Api_NotFound + Exit Sub + End If + + Set rs = DAL().Query("SELECT objective FROM sessions WHERE id = ?", id) + objective = "" + If Not rs.EOF Then objective = "" & rs(0) + rs.Close + + stateJson = "null" + savedAt = "null" + savedBy = "null" + If curRev > 0 Then + Set rs = DAL().Query("SELECT state, created_at, created_by FROM checkpoints WHERE session_id = ? AND revision = ?", Array(id, curRev)) + If Not rs.EOF Then + stateJson = "" & rs(0) + savedAt = JsonLite_Quote("" & rs(1)) + savedBy = JsonLite_Quote("" & rs(2)) + End If + rs.Close + End If + + Response.AddHeader "ETag", """" & curRev & """" + json = "{""session_id"":" & JsonLite_Quote(id) & ",""status"":" & JsonLite_Quote(status) & ",""objective"":" & JsonLite_Quote(objective) & _ + ",""revision"":" & curRev & ",""state"":" & stateJson & ",""saved_at"":" & savedAt & ",""saved_by"":" & savedBy & "}" + Api_Send 200, json + End Sub + + '--------------------------------------------------------------- + ' POST /api/v1/sessions/:id/complete + '--------------------------------------------------------------- + Public Sub Complete(id) + Dim nsId, status, curRev, outcome, body, input, ts, k + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + If Not LoadSession(id, nsId, status, curRev) Then Exit Sub + If Not Api_CanAccessNamespace(nsId, "write") Then + Api_NotFound + Exit Sub + End If + If status <> "active" Then + Api_Error 409, "session_closed", "The session is already " & status & "." + Exit Sub + End If + + outcome = Null + If Request.TotalBytes > 0 Then + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + If input.Exists("outcome") Then + If Not IsNull(input.Item("outcome")) Then + If VarType(input.Item("outcome")) <> vbString Or Len(input.Item("outcome")) > 4000 Then + Api_Invalid Array("outcome must be a string of at most 4000 characters.") + Exit Sub + End If + outcome = input.Item("outcome") + End If + End If + End If + + ts = Api_Now() + On Error Resume Next + DAL().Execute "UPDATE sessions SET status = 'completed', outcome = ?, completed_at = ?, updated_at = ? WHERE id = ? AND tenant_id = ?", _ + Array(outcome, ts, ts, id, Api_TenantId) + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Api_DbFailed k, "" + Exit Sub + End If + On Error GoTo 0 + + Api_Audit "session.complete", "session", id, "ok" + Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""status"":""completed"",""completed_at"":" & JsonLite_Quote(ts) & "}" + End Sub + + '=============================================================== + ' Helpers + '=============================================================== + ' Loads a session of the caller's tenant. Sends 404 and returns False when absent. Closes its result sets before returning. + Private Function LoadSession(id, ByRef nsId, ByRef status, ByRef curRev) + Dim rs + LoadSession = False + Set rs = DAL().Query("SELECT namespace_id, status FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Function + End If + nsId = "" & rs(0) + status = "" & rs(1) + rs.Close + curRev = 0 + Set rs = DAL().Query("SELECT MAX(revision) FROM checkpoints WHERE session_id = ?", id) + If Not rs.EOF Then + If Not IsNull(rs(0)) Then curRev = CLng(rs(0)) + End If + rs.Close + LoadSession = True + End Function + + ' Required non-empty string; appends to errs (Chr(30)-separated) when invalid + Private Function StringField(input, name, maxLen, ByRef errs) + Dim v, msg + StringField = "" + msg = "" + If Not input.Exists(name) Then + msg = name & " is required." + Else + v = input.Item(name) + If IsNull(v) Then + msg = name & " is required." + ElseIf VarType(v) <> vbString Then + msg = name & " must be a string." + ElseIf Len(Trim(v)) = 0 Then + msg = name & " must not be empty." + ElseIf Len(v) > maxLen Then + msg = name & " must be at most " & maxLen & " characters." + Else + StringField = Trim(v) + End If + End If + If Len(msg) > 0 Then + If Len(errs) > 0 Then errs = errs & Chr(30) + errs = errs & msg + End If + End Function + + ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) + Public Sub Invoke(actionName, args) + Select Case LCase(actionName) + Case "start" : Start + Case "savestate" : SaveState args(0) + Case "restorestate" : RestoreState args(0) + Case "complete" : Complete args(0) + Case Else + Err.Raise 438, "ApiSessionsController_Class", "Action '" & actionName & "' not found" + End Select + End Sub + +End Class + +Dim ApiSessionsController_Class__Singleton +Function ApiSessionsController() + If IsEmpty(ApiSessionsController_Class__Singleton) Then + Set ApiSessionsController_Class__Singleton = New ApiSessionsController_Class + End If + Set ApiSessionsController = ApiSessionsController_Class__Singleton +End Function + +' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) +Sub ApiSessionsController_Invoke(actionName, args) + ApiSessionsController().Invoke actionName, args +End Sub +%> diff --git a/app/controllers/autoload_controllers.asp b/app/controllers/autoload_controllers.asp index 76b3c7d..8739b7e 100644 --- a/app/controllers/autoload_controllers.asp +++ b/app/controllers/autoload_controllers.asp @@ -1,3 +1,6 @@ + + + diff --git a/core/autoload_core.asp b/core/autoload_core.asp index 9a7f66f..c0f6150 100644 --- a/core/autoload_core.asp +++ b/core/autoload_core.asp @@ -16,6 +16,7 @@ + diff --git a/core/lib.Api.asp b/core/lib.Api.asp new file mode 100644 index 0000000..ee760d4 --- /dev/null +++ b/core/lib.Api.asp @@ -0,0 +1,451 @@ +<% +'======================================================================================================================= +' Api support for the memory platform JSON API (/api/v1/...). +' +' Plain global functions (no native object is held across calls: G3CRYPTO is created per use, see AGENTS.md). +' Per-request identity lives in Api_TenantId / Api_PrincipalId, set by Api_Authenticate(). +' +' Authentication : "Authorization: Bearer "; only the SHA-256 of a key is stored (table api_keys). +' Authorization : scope is not permission. A principal can touch a namespace only through an access_grants row +' on that namespace (or an ancestor when the grant has inherit = 1). Permissions: read, write, +' delete, admin (admin implies all). Anything the caller may not see is reported as 404. +' Errors : {"error":{"code":"...","message":"...","request_id":"..."}} +'======================================================================================================================= +Dim Api_TenantId, Api_PrincipalId, Api_RequestIdValue +Api_TenantId = "" +Api_PrincipalId = "" +Api_RequestIdValue = "" + +'----------------------------------------------------------------------------------------------------------------------- +' Identifiers, time, hashing +'----------------------------------------------------------------------------------------------------------------------- +Function Api_NewId() + Dim c + Set c = Server.CreateObject("G3CRYPTO") + Api_NewId = LCase(c.UUID()) +End Function + +Function Api_Sha256(text) + Dim c + Set c = Server.CreateObject("G3CRYPTO") + Api_Sha256 = LCase(c.SHA256("" & text)) +End Function + +' UTC timestamp as 'YYYY-MM-DD HH:MM:SS'. The container runs in UTC, so Now() is UTC. +Function Api_Now() + Dim d + d = Now() + Api_Now = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2) & " " & _ + Right("0" & Hour(d), 2) & ":" & Right("0" & Minute(d), 2) & ":" & Right("0" & Second(d), 2) +End Function + +Function Api_RequestId() + If Len(Api_RequestIdValue) = 0 Then + Api_RequestIdValue = "req-" & Api_NewId() + End If + Api_RequestId = Api_RequestIdValue +End Function + +' True for the opaque ids this API issues (UUID text). Used before an id goes anywhere near SQL or a path. +Function Api_IsId(s) + Dim t, i, c + Api_IsId = False + t = "" & s + If Len(t) <> 36 Then Exit Function + For i = 1 To 36 + c = Mid(t, i, 1) + If i = 9 Or i = 14 Or i = 19 Or i = 24 Then + If c <> "-" Then Exit Function + Else + If Not ((c >= "0" And c <= "9") Or (c >= "a" And c <= "f")) Then Exit Function + End If + Next + Api_IsId = True +End Function + +'----------------------------------------------------------------------------------------------------------------------- +' Responses +'----------------------------------------------------------------------------------------------------------------------- +Function Api_StatusLine(status) + Select Case status + Case 200: Api_StatusLine = "200 OK" + Case 201: Api_StatusLine = "201 Created" + Case 400: Api_StatusLine = "400 Bad Request" + Case 401: Api_StatusLine = "401 Unauthorized" + Case 403: Api_StatusLine = "403 Forbidden" + Case 404: Api_StatusLine = "404 Not Found" + Case 405: Api_StatusLine = "405 Method Not Allowed" + Case 409: Api_StatusLine = "409 Conflict" + Case 412: Api_StatusLine = "412 Precondition Failed" + Case 422: Api_StatusLine = "422 Unprocessable Entity" + Case 428: Api_StatusLine = "428 Precondition Required" + Case 500: Api_StatusLine = "500 Internal Server Error" + Case 503: Api_StatusLine = "503 Service Unavailable" + Case Else: Api_StatusLine = status & " Status" + End Select +End Function + +Sub Api_Send(status, jsonText) + Response.Clear + Response.Status = Api_StatusLine(status) + Response.ContentType = "application/json" + Response.Charset = "utf-8" + Response.AddHeader "X-Request-Id", Api_RequestId() + Response.AddHeader "Cache-Control", "no-store" + Response.Write jsonText +End Sub + +Sub Api_Error(status, code, message) + Api_Send status, "{""error"":{""code"":" & JsonLite_Quote(code) & ",""message"":" & JsonLite_Quote(message) & _ + ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}" +End Sub + +Sub Api_NotFound() + Api_Error 404, "not_found", "Resource not found." +End Sub + +Dim Api_LastDbError +Api_LastDbError = "" + +' Call straight after a failing statement (before any rollback) so the description is kept for Api_DbFailed. +Sub Api_NoteDbError() + Api_LastDbError = "" & Err.Description +End Sub + +' A failed database call becomes a JSON 500. The database text is only included when Environment = Development. +Sub Api_DbFailed(errNumber, errDescription) + Dim msg + Err.Clear + On Error GoTo 0 + msg = "Internal error (" & errNumber & "). The request was not completed." + If LCase(GetAppSetting("Environment")) = "development" And Len(Api_LastDbError) > 0 Then + msg = msg & " [dev] " & Api_LastDbError + End If + Api_Error 500, "internal_error", msg +End Sub + +'----------------------------------------------------------------------------------------------------------------------- +' Request helpers +'----------------------------------------------------------------------------------------------------------------------- +Function Api_Header(name) + Api_Header = Trim("" & Request.ServerVariables("HTTP_" & UCase(Replace(name, "-", "_")))) +End Function + +' Request body as UTF-8 text, or Empty after sending a 400. +Function Api_ReadBody() + Dim n, text + Api_ReadBody = Empty + n = Request.TotalBytes + If n = 0 Then + Api_Error 400, "empty_body", "Request body is empty. Send a JSON object." + Exit Function + End If + If n > 1048576 Then + Api_Error 400, "body_too_large", "Request body exceeds 1 MiB." + Exit Function + End If + text = Api_Utf8Decode(CStr(Request.BinaryRead(n))) + If JsonLite_Parse(text) Is Nothing Then + Api_Error 400, "invalid_json", "Body must be a valid JSON object." + Exit Function + End If + Api_ReadBody = text +End Function + +' Decodes a string holding raw UTF-8 bytes (one byte per character, as AxonASP BinaryRead returns) into Unicode text. +Function Api_Utf8Decode(ByVal s) + Dim i, n, c, cp, extra, out, k, ok, b + n = Len(s) + out = "" + i = 1 + Do While i <= n + c = AscW(Mid(s, i, 1)) And 255 + If c < 128 Then + out = out & Chr(c) + i = i + 1 + Else + extra = -1 + cp = 0 + If c >= 240 And c <= 247 Then + extra = 3 + cp = c And 7 + ElseIf c >= 224 And c <= 239 Then + extra = 2 + cp = c And 15 + ElseIf c >= 194 And c <= 223 Then + extra = 1 + cp = c And 31 + End If + ok = (extra > 0 And i + extra <= n) + If ok Then + For k = 1 To extra + b = AscW(Mid(s, i + k, 1)) And 255 + If b < 128 Or b > 191 Then + ok = False + Else + cp = cp * 64 + (b And 63) + End If + Next + End If + If ok And cp <= 1114111 Then + ' AxonASP strings hold whole code points: ChrW(cp) works above U+FFFF, while a UTF-16 + ' surrogate pair would be stored as two U+FFFD characters. + out = out & ChrW(cp) + i = i + extra + 1 + Else + out = out & ChrW(65533) + i = i + 1 + End If + End If + Loop + Api_Utf8Decode = out +End Function + +Function Api_ToInt(v, dflt, lo, hi) + Dim s + s = Trim("" & v) + Api_ToInt = dflt + If Len(s) > 0 Then + If IsNumeric(s) Then + Api_ToInt = CLng(s) + End If + End If + If Api_ToInt < lo Then Api_ToInt = lo + If Api_ToInt > hi Then Api_ToInt = hi +End Function + +'----------------------------------------------------------------------------------------------------------------------- +' Authentication. Returns True and sets Api_TenantId / Api_PrincipalId; otherwise sends 401 and returns False. +'----------------------------------------------------------------------------------------------------------------------- +Function Api_Authenticate() + Dim h, key, rs, expires, keyId + Api_Authenticate = False + Api_TenantId = "" + Api_PrincipalId = "" + h = Api_Header("Authorization") + If LCase(Left(h, 7)) <> "bearer " Then + Response.AddHeader "WWW-Authenticate", "Bearer" + Api_Error 401, "unauthenticated", "Missing or malformed Authorization header. Use: Authorization: Bearer ." + Exit Function + End If + key = Trim(Mid(h, 8)) + If Len(key) < 16 Or Len(key) > 200 Then + Response.AddHeader "WWW-Authenticate", "Bearer" + Api_Error 401, "unauthenticated", "Invalid API key." + Exit Function + End If + + Set rs = DAL().Query("SELECT k.id, p.id, p.tenant_id, k.expires_at FROM api_keys k " & _ + "JOIN principals p ON p.id = k.principal_id JOIN tenants t ON t.id = p.tenant_id " & _ + "WHERE k.key_hash = ? AND k.status = 'active' AND p.status = 'active' AND t.status = 'active'", Api_Sha256(key)) + If rs.EOF Then + rs.Close + Response.AddHeader "WWW-Authenticate", "Bearer" + Api_Error 401, "unauthenticated", "Invalid API key." + Exit Function + End If + keyId = "" & rs(0) + Api_PrincipalId = "" & rs(1) + Api_TenantId = "" & rs(2) + expires = rs(3) + rs.Close + + If Not IsNull(expires) Then + If Len("" & expires) > 0 Then + If "" & expires <= Api_Now() Then + Api_TenantId = "" + Api_PrincipalId = "" + Response.AddHeader "WWW-Authenticate", "Bearer" + Api_Error 401, "unauthenticated", "API key has expired." + Exit Function + End If + End If + End If + + DAL().Execute "UPDATE api_keys SET last_used_at = ? WHERE id = ?", Array(Api_Now(), keyId) + Api_Authenticate = True +End Function + +'----------------------------------------------------------------------------------------------------------------------- +' Authorization +'----------------------------------------------------------------------------------------------------------------------- +' Path of a namespace in the caller's tenant, or Null when it does not exist there. +Function Api_NamespacePath(namespaceId) + Dim rs + Api_NamespacePath = Null + If Not Api_IsId(namespaceId) Then Exit Function + Set rs = DAL().Query("SELECT path FROM namespaces WHERE id = ? AND tenant_id = ?", Array(namespaceId, Api_TenantId)) + If Not rs.EOF Then + Api_NamespacePath = "" & rs(0) + End If + rs.Close +End Function + +' True when the principal holds `perm` (or admin) on the path itself, or on an ancestor via an inheriting grant. +Function Api_PathAllows(targetPath, perm) + Dim rs, gPath, perms, inherit, allowed, expires, now_ + Api_PathAllows = False + now_ = Api_Now() + Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _ + "JOIN namespaces n ON n.id = g.namespace_id " & _ + "WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId)) + Do While Not rs.EOF + gPath = "" & rs(0) + perms = "," & LCase(Replace("" & rs(1), " ", "")) & "," + inherit = rs(2) + expires = rs(3) + allowed = True + If Not IsNull(expires) Then + If Len("" & expires) > 0 Then + If "" & expires <= now_ Then allowed = False + End If + End If + If allowed Then + If targetPath = gPath Then + allowed = True + ElseIf CLng(inherit) = 1 And Left(targetPath, Len(gPath) + 1) = gPath & "/" Then + allowed = True + ElseIf gPath = "/" And CLng(inherit) = 1 Then + allowed = True + Else + allowed = False + End If + End If + If allowed Then + If InStr(perms, "," & LCase(perm) & ",") > 0 Or InStr(perms, ",admin,") > 0 Then + Api_PathAllows = True + Exit Do + End If + End If + rs.MoveNext + Loop + rs.Close +End Function + +' True when the namespace exists in the caller's tenant AND the caller holds `perm` on it. +Function Api_CanAccessNamespace(namespaceId, perm) + Dim p + Api_CanAccessNamespace = False + p = Api_NamespacePath(namespaceId) + If IsNull(p) Then Exit Function + Api_CanAccessNamespace = Api_PathAllows(p, perm) +End Function + +'----------------------------------------------------------------------------------------------------------------------- +' Audit trail (security-relevant actions; never log secrets or content) +'----------------------------------------------------------------------------------------------------------------------- +Sub Api_Audit(action, resourceType, resourceId, outcome) + On Error Resume Next + DAL().Execute "INSERT INTO audit_events (id, tenant_id, principal_id, action, resource_type, resource_id, outcome, request_id, created_at) " & _ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", _ + Array(Api_NewId(), Api_TenantId, Api_PrincipalId, action, resourceType, resourceId, outcome, Api_RequestId(), Api_Now()) + Err.Clear + On Error GoTo 0 +End Sub + +' 422 with a list of messages. details: array of strings. +Sub Api_Invalid(details) + Dim i, list + list = "" + For i = 0 To UBound(details) + If i > 0 Then list = list & "," + list = list & JsonLite_Quote(details(i)) + Next + Api_Send 422, "{""error"":{""code"":""validation_failed"",""message"":""Validation failed."",""details"":[" & list & "],""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}" +End Sub + +' SQL list of the caller's namespace ids on which `perm` is held, e.g. 'id1','id2' (ids are UUIDs, safe to inline). +' Empty string when there are none. One grants query plus one namespaces query. +Function Api_AllowedNamespaceIds(perm) + Dim rs, gPaths(), gPerms(), gInh(), n, i, now_, expires, okGrant, p, out, id, path, hit + Api_AllowedNamespaceIds = "" + now_ = Api_Now() + n = 0 + ReDim gPaths(7) + ReDim gPerms(7) + ReDim gInh(7) + Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _ + "JOIN namespaces n ON n.id = g.namespace_id WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId)) + Do While Not rs.EOF + okGrant = True + expires = rs(3) + If Not IsNull(expires) Then + If Len("" & expires) > 0 Then + If "" & expires <= now_ Then okGrant = False + End If + End If + p = "," & LCase(Replace("" & rs(1), " ", "")) & "," + If okGrant And (InStr(p, "," & LCase(perm) & ",") > 0 Or InStr(p, ",admin,") > 0) Then + If n > UBound(gPaths) Then + ReDim Preserve gPaths(n * 2) + ReDim Preserve gPerms(n * 2) + ReDim Preserve gInh(n * 2) + End If + gPaths(n) = "" & rs(0) + gInh(n) = CLng(rs(2)) + n = n + 1 + End If + rs.MoveNext + Loop + rs.Close + If n = 0 Then Exit Function + + out = "" + Set rs = DAL().Query("SELECT id, path FROM namespaces WHERE tenant_id = ?", Api_TenantId) + Do While Not rs.EOF + id = "" & rs(0) + path = "" & rs(1) + hit = False + For i = 0 To n - 1 + If path = gPaths(i) Then + hit = True + ElseIf gInh(i) = 1 Then + If gPaths(i) = "/" Then + hit = True + ElseIf Left(path, Len(gPaths(i)) + 1) = gPaths(i) & "/" Then + hit = True + End If + End If + If hit Then Exit For + Next + If hit And Api_IsId(id) Then + If Len(out) > 0 Then out = out & "," + out = out & "'" & id & "'" + End If + rs.MoveNext + Loop + rs.Close + Api_AllowedNamespaceIds = out +End Function + +' Replays the stored response for an Idempotency-Key. Returns True when the request may proceed (key unseen); +' False after sending the replayed response (same body) or a 409 (key reused with a different body). +Function Api_IdempotencyGate(idemKey, requestHash) + Dim rs + Api_IdempotencyGate = True + If Len(idemKey) = 0 Then Exit Function + Set rs = DAL().Query("SELECT request_hash, status_code, response_body FROM idempotency_keys WHERE tenant_id = ? AND idem_key = ?", Array(Api_TenantId, idemKey)) + If Not rs.EOF Then + Api_IdempotencyGate = False + If "" & rs(0) = requestHash Then + Dim st, bodyText + st = CLng(rs(1)) + bodyText = "" & rs(2) + rs.Close + Api_Send st, bodyText + Response.AddHeader "Idempotent-Replayed", "true" + Else + rs.Close + Api_Error 409, "idempotency_conflict", "This Idempotency-Key was already used with a different request body." + End If + Exit Function + End If + rs.Close +End Function + +Sub Api_IdempotencyStore(idemKey, requestHash, status, bodyText) + If Len(idemKey) = 0 Then Exit Sub + DAL().Execute "INSERT INTO idempotency_keys (tenant_id, idem_key, request_hash, status_code, response_body, created_at) VALUES (?, ?, ?, ?, ?, ?)", _ + Array(Api_TenantId, idemKey, requestHash, status, bodyText, Api_Now()) +End Sub +%> \ No newline at end of file diff --git a/core/lib.ControllerRegistry.asp b/core/lib.ControllerRegistry.asp index cd86a92..fe2f484 100644 --- a/core/lib.ControllerRegistry.asp +++ b/core/lib.ControllerRegistry.asp @@ -15,6 +15,9 @@ Class ControllerRegistry_Class ' Format: m_controllers.Add "controllername", True RegisterController "homecontroller" RegisterController "errorcontroller" + RegisterController "apihealthcontroller" + RegisterController "apisessionscontroller" + RegisterController "apimemoriescontroller" RegisterController "docscontroller" End Sub diff --git a/core/lib.JsonLite.asp b/core/lib.JsonLite.asp index 9ebd631..56c2312 100644 --- a/core/lib.JsonLite.asp +++ b/core/lib.JsonLite.asp @@ -11,17 +11,55 @@ ' JsonLite_Quote(s) ' "text" with JSON escaping ' JsonLite_Num(n) ' locale-independent number literal ' -' Values: String, Double (numbers), Boolean, Null. Nested objects/arrays are parsed and stored as Null. +' Values: String, Double (numbers), Boolean, Null. Nested objects/arrays are parsed and stored as Null, but the raw +' text of top-level ones is kept: obj.HasRaw(k) / obj.Raw(k); JsonLite_ParseStringArray(raw) reads an array of strings. '======================================================================================================================= Class JsonLite_Object Private m_keys(), m_vals(), m_count + Private m_rawKeys(), m_rawVals(), m_rawCount Private Sub Class_Initialize() m_count = 0 ReDim m_keys(7) ReDim m_vals(7) + m_rawCount = 0 + ReDim m_rawKeys(3) + ReDim m_rawVals(3) End Sub + ' Raw JSON text of a top-level nested object/array value (Item returns Null for those). + Public Sub AddRaw(k, rawText) + If m_rawCount > UBound(m_rawKeys) Then + ReDim Preserve m_rawKeys(m_rawCount * 2) + ReDim Preserve m_rawVals(m_rawCount * 2) + End If + m_rawKeys(m_rawCount) = k + m_rawVals(m_rawCount) = rawText + m_rawCount = m_rawCount + 1 + End Sub + + Public Function HasRaw(k) + Dim i + HasRaw = False + For i = 0 To m_rawCount - 1 + If LCase(m_rawKeys(i)) = LCase(k) Then + HasRaw = True + Exit Function + End If + Next + End Function + + Public Function Raw(k) + Dim i + Raw = Null + For i = 0 To m_rawCount - 1 + If LCase(m_rawKeys(i)) = LCase(k) Then + Raw = m_rawVals(i) + Exit Function + End If + Next + End Function + Public Sub Add(k, v) Dim i For i = 0 To m_count - 1 @@ -82,6 +120,51 @@ Class JsonLite_Parser Set Run = obj End Function + ' Parses text that must be a JSON array of strings. Returns an array of strings, or Null if it is anything else. + Public Function RunStringArray(text) + Dim items(), n, c, v + m_s = "" & text + m_len = Len(m_s) + m_pos = 1 + m_ok = True + RunStringArray = Null + n = 0 + ReDim items(-1) + SkipWs + If m_pos > m_len Then Exit Function + If Mid(m_s, m_pos, 1) <> "[" Then Exit Function + m_pos = m_pos + 1 + SkipWs + If m_pos <= m_len Then + If Mid(m_s, m_pos, 1) = "]" Then + m_pos = m_pos + 1 + SkipWs + If m_pos <= m_len Then Exit Function + RunStringArray = items + Exit Function + End If + End If + Do + SkipWs + If m_pos > m_len Then Exit Function + If Mid(m_s, m_pos, 1) <> """" Then Exit Function + v = ReadString() + If Not m_ok Then Exit Function + ReDim Preserve items(n) + items(n) = v + n = n + 1 + SkipWs + If m_pos > m_len Then Exit Function + c = Mid(m_s, m_pos, 1) + m_pos = m_pos + 1 + If c = "]" Then Exit Do + If c <> "," Then Exit Function + Loop + SkipWs + If m_pos <= m_len Then Exit Function + RunStringArray = items + End Function + Private Sub SkipWs() Dim c Do While m_pos <= m_len @@ -95,7 +178,7 @@ Class JsonLite_Parser End Sub Private Function ReadObject() - Dim obj, k, v, c + Dim obj, k, v, c, rawStart, c0 Set obj = New JsonLite_Object Set ReadObject = obj m_pos = m_pos + 1 ' { @@ -128,9 +211,15 @@ Class JsonLite_Parser Exit Function End If m_pos = m_pos + 1 + SkipWs + rawStart = m_pos + c0 = Mid(m_s, m_pos, 1) v = ReadValue() If Not m_ok Then Exit Function obj.Add k, v + If c0 = "{" Or c0 = "[" Then + obj.AddRaw k, Mid(m_s, rawStart, m_pos - rawStart) + End If SkipWs If m_pos > m_len Then m_ok = False @@ -227,7 +316,7 @@ Class JsonLite_Parser End Sub Private Function ReadString() - Dim out, c, e, h + Dim out, c, e, h, cu, h2, lo out = "" m_pos = m_pos + 1 ' opening quote Do While m_pos <= m_len @@ -255,8 +344,20 @@ Class JsonLite_Parser m_ok = False Exit Function End If - out = out & ChrW(CLng("&H" & h)) + cu = CLng("&H" & h) m_pos = m_pos + 4 + ' A UTF-16 surrogate pair (backslash-u D83D, backslash-u DE00) is one code point; AxonASP strings need it combined. + If cu >= 55296 And cu <= 56319 And Mid(m_s, m_pos, 2) = "\u" Then + h2 = Mid(m_s, m_pos + 2, 4) + If Len(h2) = 4 And IsHex(h2) Then + lo = CLng("&H" & h2) + If lo >= 56320 And lo <= 57343 Then + cu = 65536 + (cu - 55296) * 1024 + (lo - 56320) + m_pos = m_pos + 6 + End If + End If + End If + out = out & ChrW(cu) Case Else m_ok = False Exit Function @@ -281,6 +382,13 @@ Class JsonLite_Parser End Function End Class +' Array of strings from the raw text of a JSON array, or Null when it is not an array of strings +Function JsonLite_ParseStringArray(text) + Dim p + Set p = New JsonLite_Parser + JsonLite_ParseStringArray = p.RunStringArray(text) +End Function + Function JsonLite_Parse(text) Dim p Set p = New JsonLite_Parser diff --git a/public/Default.asp b/public/Default.asp index fd65121..2626cc3 100644 --- a/public/Default.asp +++ b/public/Default.asp @@ -10,6 +10,25 @@ ' API docs (Swagger UI) router.AddRoute "GET", "/api/docs", "DocsController", "Index" + ' Memory platform API v1 (JSON): memories + router.AddRoute "POST", "/api/v1/remember", "ApiMemoriesController", "Remember" + router.AddRoute "GET", "/api/v1/memories", "ApiMemoriesController", "Recent" + router.AddRoute "GET", "/api/v1/memories/:id", "ApiMemoriesController", "Fetch" + router.AddRoute "PATCH", "/api/v1/memories/:id", "ApiMemoriesController", "Correct" + router.AddRoute "DELETE", "/api/v1/memories/:id", "ApiMemoriesController", "Forget" + router.AddRoute "POST", "/api/v1/memories/:id/retire", "ApiMemoriesController", "Retire" + router.AddRoute "GET", "/api/v1/memories/:id/versions", "ApiMemoriesController", "Versions" + + ' Sessions and working state + router.AddRoute "POST", "/api/v1/sessions", "ApiSessionsController", "Start" + router.AddRoute "PUT", "/api/v1/sessions/:id/state", "ApiSessionsController", "SaveState" + router.AddRoute "GET", "/api/v1/sessions/:id/state", "ApiSessionsController", "RestoreState" + router.AddRoute "POST", "/api/v1/sessions/:id/complete", "ApiSessionsController", "Complete" + + ' Health probes + router.AddRoute "GET", "/api/v1/health/live", "ApiHealthController", "Live" + router.AddRoute "GET", "/api/v1/health/ready", "ApiHealthController", "Ready" + ' Dispatch the request (resolves route and executes controller action). ' MVC() is called with parentheses: AxonASP cannot use "MVC.Method args" on a parameterless function. MVC().DispatchRequest Request.ServerVariables("REQUEST_METHOD"), GetRequestPath() diff --git a/scripts/gen.cmd b/scripts/gen.cmd index 805ae99..14c2e72 100644 --- a/scripts/gen.cmd +++ b/scripts/gen.cmd @@ -33,10 +33,10 @@ set "A2=%A2%;%CUR%" shift goto collect :run -docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e "ARG1=%A1%" -e "ARG2=%A2%" axonasp ./axonasp-cli -m vbscript -r /opt/axonasp/site/scripts/%SCRIPT% +docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "ARG1=%A1%" -e "ARG2=%A2%" axonasp ./axonasp-cli -m vbscript -r /opt/axonasp/site/scripts/%SCRIPT% if not "%GEN%"=="api" exit /b %errorlevel% rem api: the repo/POBO were generated above, now the controller, routes and spec -docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e "ARG1=%A1%" -e "ARG2=%A2%" axonasp ./axonasp-cli -m vbscript -r /opt/axonasp/site/scripts/GenerateApi.vbs +docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "ARG1=%A1%" -e "ARG2=%A2%" axonasp ./axonasp-cli -m vbscript -r /opt/axonasp/site/scripts/GenerateApi.vbs exit /b %errorlevel% :usage echo Usage: scripts\gen.cmd (migration^|controller^|repo^|api) args... diff --git a/scripts/migrate.cmd b/scripts/migrate.cmd index fe99885..6587054 100644 --- a/scripts/migrate.cmd +++ b/scripts/migrate.cmd @@ -3,4 +3,4 @@ rem Usage: scripts\migrate.cmd [up|down|status] (default: up) rem Runs the migrator inside the running "axonasp" container. set CMD=%1 if "%CMD%"=="" set CMD=up -docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e MIGRATE=%CMD% axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/migrate.asp +docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e MIGRATE=%CMD% axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/migrate.asp diff --git a/scripts/provision.asp b/scripts/provision.asp new file mode 100644 index 0000000..3e683bc --- /dev/null +++ b/scripts/provision.asp @@ -0,0 +1,203 @@ +<% +' Provisioning for the memory API (tenants, principals, API keys, namespaces, grants). +' Run through scripts\provision.cmd, which sets PROV_ACTION and PROV_ARG1..PROV_ARG4: +' +' tenant -> creates a tenant, prints its id +' principal +' -> creates a principal and one API key (key shown ONCE) +' key -> adds another API key for a principal (shown ONCE) +' namespace -> creates the namespace and any missing parents +' grant [inherit 1|0] +' -> perms: comma list of read,write,delete,admin +' revoke -> disables an API key +' list -> prints principals, namespaces and grants +' purge -> DELETES the tenant and everything it owns (tests, cleanup) +' +' The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site +%> + +<% +Dim sh : Set sh = CreateObject("WScript.Shell") + +Function Arg(name) + Dim v + v = sh.ExpandEnvironmentStrings("%" & name & "%") + If v = "%" & name & "%" Then v = "" + Arg = Trim(v) +End Function + +Sub Fail(msg) + Response.Write "ERROR: " & msg & vbCrLf +End Sub + +Function TenantExists(id) + Dim rs + TenantExists = False + If Not Api_IsId(id) Then Exit Function + Set rs = DAL().Query("SELECT 1 FROM tenants WHERE id = ?", id) + TenantExists = Not rs.EOF + rs.Close +End Function + +' Creates the namespace at `path` (and missing parents) in the tenant; returns the leaf id. +Function EnsureNamespace(tenantId, path) + Dim parts, i, cur, parentId, rs, id, name + parts = Split(Mid(path, 2), "/") + cur = "" + parentId = Null + For i = 0 To UBound(parts) + name = parts(i) + cur = cur & "/" & name + Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(tenantId, cur)) + If rs.EOF Then + rs.Close + id = Api_NewId() + DAL().Execute "INSERT INTO namespaces (id, tenant_id, parent_id, name, path, created_at) VALUES (?, ?, ?, ?, ?, ?)", _ + Array(id, tenantId, parentId, name, cur, Api_Now()) + Else + id = "" & rs(0) + rs.Close + End If + parentId = id + Next + EnsureNamespace = id +End Function + +Function ValidPath(p) + Dim i, c + ValidPath = False + If Len(p) < 2 Or Left(p, 1) <> "/" Or Right(p, 1) = "/" Or InStr(p, "//") > 0 Then Exit Function + For i = 1 To Len(p) + c = Mid(p, i, 1) + If Not ((c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or c = "/" Or c = "-" Or c = "_" Or c = ".") Then Exit Function + Next + ValidPath = True +End Function + +Function NewKey(principalId) + Dim c, plain, id + Set c = Server.CreateObject("G3CRYPTO") + plain = "amk_" & c.RandomHex(32) + id = Api_NewId() + DAL().Execute "INSERT INTO api_keys (id, principal_id, key_hash, key_prefix, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _ + Array(id, principalId, Api_Sha256(plain), Left(plain, 8), Api_Now()) + Response.Write "api_key_id: " & id & vbCrLf + Response.Write "api_key: " & plain & " (shown once, store it now)" & vbCrLf + NewKey = id +End Function + +Dim action : action = LCase(Arg("PROV_ACTION")) +Dim a1 : a1 = Arg("PROV_ARG1") +Dim a2 : a2 = Arg("PROV_ARG2") +Dim a3 : a3 = Arg("PROV_ARG3") +Dim a4 : a4 = Arg("PROV_ARG4") +Dim id, rs, nsId, found + +Select Case action + Case "tenant" + If Len(a1) = 0 Then + Fail "usage: tenant " + Else + id = Api_NewId() + DAL().Execute "INSERT INTO tenants (id, name, status, created_at) VALUES (?, ?, 'active', ?)", Array(id, a1, Api_Now()) + Response.Write "tenant_id: " & id & vbCrLf + End If + + Case "principal" + If Not TenantExists(a1) Or Len(a2) = 0 Then + Fail "usage: principal (tenant must exist)" + ElseIf a3 <> "human" And a3 <> "agent" And a3 <> "service" Then + Fail "type must be human, agent or service" + Else + id = Api_NewId() + DAL().Execute "INSERT INTO principals (id, tenant_id, type, name, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _ + Array(id, a1, a3, a2, Api_Now()) + Response.Write "principal_id: " & id & vbCrLf + nsId = NewKey(id) + End If + + Case "key" + Set rs = DAL().Query("SELECT 1 FROM principals WHERE id = ? AND status = 'active'", a1) + found = Not rs.EOF + rs.Close ' close before writing: a write while a result set is open is lost under G3DB/SQLite + If found Then + nsId = NewKey(a1) + Else + Fail "usage: key (active principal must exist)" + End If + + Case "namespace" + If Not TenantExists(a1) Or Not ValidPath(a2) Then + Fail "usage: namespace (a-z 0-9 - _ . only)" + Else + Response.Write "namespace_id: " & EnsureNamespace(a1, a2) & vbCrLf + End If + + Case "grant" + Dim inh : inh = 1 + If a4 = "0" Then inh = 0 + Set rs = DAL().Query("SELECT tenant_id FROM principals WHERE id = ?", a1) + If rs.EOF Or Not ValidPath(a2) Or Len(a3) = 0 Then + Fail "usage: grant [inherit 1|0]" + rs.Close + Else + Dim tid : tid = "" & rs(0) + rs.Close + nsId = EnsureNamespace(tid, a2) + id = Api_NewId() + DAL().Execute "INSERT INTO access_grants (id, principal_id, namespace_id, permissions, inherit, created_at) VALUES (?, ?, ?, ?, ?, ?)", _ + Array(id, a1, nsId, LCase(Replace(a3, " ", "")), inh, Api_Now()) + Response.Write "grant_id: " & id & " namespace_id: " & nsId & vbCrLf + End If + + Case "revoke" + DAL().Execute "UPDATE api_keys SET status = 'revoked' WHERE id = ?", a1 + Response.Write "revoked (if the key existed): " & a1 & vbCrLf + + Case "list" + Set rs = DAL().Query("SELECT id, type, name, status FROM principals WHERE tenant_id = ? ORDER BY created_at", a1) + Response.Write "principals:" & vbCrLf + Do While Not rs.EOF + Response.Write " " & rs(0) & " " & rs(1) & " " & rs(2) & " " & rs(3) & vbCrLf + rs.MoveNext + Loop + rs.Close + Set rs = DAL().Query("SELECT id, path FROM namespaces WHERE tenant_id = ? ORDER BY path", a1) + Response.Write "namespaces:" & vbCrLf + Do While Not rs.EOF + Response.Write " " & rs(0) & " " & rs(1) & vbCrLf + rs.MoveNext + Loop + rs.Close + Set rs = DAL().Query("SELECT g.principal_id, n.path, g.permissions, g.inherit FROM access_grants g JOIN namespaces n ON n.id = g.namespace_id WHERE n.tenant_id = ?", a1) + Response.Write "grants:" & vbCrLf + Do While Not rs.EOF + Response.Write " " & rs(0) & " " & rs(1) & " " & rs(2) & " inherit=" & rs(3) & vbCrLf + rs.MoveNext + Loop + rs.Close + + Case "purge" + If Not TenantExists(a1) Then + Fail "usage: purge (tenant must exist)" + Else + DAL().BeginTransaction + DAL().Execute "DELETE FROM checkpoints WHERE session_id IN (SELECT id FROM sessions WHERE tenant_id = ?)", a1 + DAL().Execute "DELETE FROM sessions WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM memory_revisions WHERE memory_id IN (SELECT id FROM memories WHERE tenant_id = ?)", a1 + DAL().Execute "DELETE FROM memories WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM idempotency_keys WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM audit_events WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM access_grants WHERE principal_id IN (SELECT id FROM principals WHERE tenant_id = ?)", a1 + DAL().Execute "DELETE FROM api_keys WHERE principal_id IN (SELECT id FROM principals WHERE tenant_id = ?)", a1 + DAL().Execute "DELETE FROM namespaces WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM principals WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM tenants WHERE id = ?", a1 + DAL().CommitTransaction + Response.Write "purged tenant " & a1 & vbCrLf + End If + + Case Else + Response.Write "Unknown action '" & action & "'. Use tenant, principal, key, namespace, grant, revoke, list or purge." & vbCrLf +End Select +%> diff --git a/scripts/provision.cmd b/scripts/provision.cmd new file mode 100644 index 0000000..807e593 --- /dev/null +++ b/scripts/provision.cmd @@ -0,0 +1,19 @@ +@echo off +rem Provisioning for the memory API, run inside the "axonasp" container. +rem +rem scripts\provision.cmd tenant +rem scripts\provision.cmd principal (prints an API key once) +rem scripts\provision.cmd key (another API key, printed once) +rem scripts\provision.cmd namespace +rem scripts\provision.cmd grant [inherit 1^|0] +rem scripts\provision.cmd revoke +rem scripts\provision.cmd list +rem scripts\provision.cmd purge (deletes the tenant and all its data) +rem Quote a permission list in PowerShell: grant /dev '"read,write"' +setlocal +if "%~1"=="" goto usage +docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "PROV_ACTION=%~1" -e "PROV_ARG1=%~2" -e "PROV_ARG2=%~3" -e "PROV_ARG3=%~4" -e "PROV_ARG4=%~5" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp +exit /b %errorlevel% +:usage +echo Usage: scripts\provision.cmd (tenant^|principal^|key^|namespace^|grant^|revoke^|list^|purge) args... +exit /b 1 diff --git a/tests/phase1-api.sh b/tests/phase1-api.sh new file mode 100644 index 0000000..2a40c8f --- /dev/null +++ b/tests/phase1-api.sh @@ -0,0 +1,168 @@ +#!/usr/bin/env bash +# Phase 1 API checks: authentication, tenant isolation (AC-06), namespace permissions, memory lifecycle, +# idempotency, sessions/checkpoints (AC-09, AC-10) and persistence across a restart (AC-01). +# +# Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801), curl, and Git Bash/bash. +# It provisions two throw-away tenants and deletes them at the end (even on failure). +# bash tests/phase1-api.sh +set -u +BASE=${BASE:-http://localhost:8801/api/v1} +PASS=0; FAIL=0; FAILED=() +TENANTS=() + +prov() { # prov [arg1 arg2 arg3 arg4] + MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \ + -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \ + axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r' +} +field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; } # field from provision output +jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; } # first "name":"value" in a JSON text + +cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; } +trap cleanup EXIT + +check() { # check + if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi +} +code() { # code [curl args...] -> HTTP status + local key=$1 m=$2 p=$3; shift 3 + curl -s -o /dev/null -w '%{http_code}' -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p" +} +body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; } + +# ---- setup ----------------------------------------------------------------------------------------------- +TA=$(prov tenant "test-A" | field tenant_id); TB=$(prov tenant "test-B" | field tenant_id); TENANTS=("$TA" "$TB") +mk() { # mk -> sets P_ID and P_KEY + local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key) +} +mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY +mk "$TA" reader agent; RID=$P_ID; RK=$P_KEY +mk "$TA" other agent; OID=$P_ID; OK=$P_KEY +mk "$TA" nobody agent; NID=$P_ID; NK=$P_KEY +mk "$TA" sub agent; SID_=$P_ID; SK=$P_KEY +mk "$TA" noinh agent; XID=$P_ID; XK=$P_KEY +mk "$TB" writerB agent; BID=$P_ID; BK=$P_KEY +prov grant "$WID" /proj "read,write,delete" 1 >/dev/null +prov grant "$RID" /proj "read" 1 >/dev/null +prov grant "$OID" /other "read,write" 1 >/dev/null +prov grant "$SID_" /proj/sub "read,write" 1 >/dev/null +prov grant "$XID" /proj "read,write" 0 >/dev/null +prov grant "$BID" /proj "read,write,delete" 1 >/dev/null +NSA=$(prov namespace "$TA" /proj | field namespace_id); NSSUB=$(prov namespace "$TA" /proj/sub | field namespace_id) +NSB=$(prov namespace "$TB" /proj | field namespace_id) +[ -n "$NSA" ] && [ -n "$NSB" ] && [ -n "$WK" ] || { echo "setup failed"; exit 2; } + +mem() { printf '{"namespace_id":"%s","type":"semantic","title":"%s","content":"%s"}' "$1" "$2" "$3"; } + +# ---- first request after provisioning is a write (cold-start habit) --------------------------------------- +R=$(body "$WK" POST /remember -d "$(mem "$NSA" "Fact one" "The sky is blue")") +M1=$(echo "$R" | jget id) +check "writer remember -> 201 with id" "yes" "$([ -n "$M1" ] && echo yes || echo no)" +check "remember 201" "201" "$(code "$WK" POST /remember -d "$(mem "$NSA" "Fact two" "Grass is green")")" + +# ---- authentication --------------------------------------------------------------------------------------- +check "no auth header -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/memories")" +check "bad key -> 401" "401" "$(code amk_00000000000000000000000000000000 GET /memories)" +check "short key -> 401" "401" "$(code abc GET /memories)" + +# ---- isolation between tenants --------------------------------------------------------------------------- +check "B fetch A memory -> 404" "404" "$(code "$BK" GET /memories/$M1)" +check "B versions of A memory -> 404" "404" "$(code "$BK" GET /memories/$M1/versions)" +check "B correct A memory -> 404" "404" "$(code "$BK" PATCH /memories/$M1 -H 'If-Match: 1' -d '{"content":"hack"}')" +check "B retire A memory -> 404" "404" "$(code "$BK" POST /memories/$M1/retire)" +check "B forget A memory -> 404" "404" "$(code "$BK" DELETE /memories/$M1)" +check "B remember into A namespace -> 404" "404" "$(code "$BK" POST /remember -d "$(mem "$NSA" x y)")" +check "B list with A namespace_id -> 404" "404" "$(code "$BK" GET "/memories?namespace_id=$NSA")" +check "B list sees nothing of A" '{"data":[],"next_cursor":null}' "$(body "$BK" GET /memories)" +check "A memory still intact after B attempts" "200" "$(code "$WK" GET /memories/$M1)" + +# ---- permissions inside a tenant ------------------------------------------------------------------------- +check "reader fetch -> 200" "200" "$(code "$RK" GET /memories/$M1)" +check "reader list -> has data" "yes" "$(body "$RK" GET /memories | grep -q "$M1" && echo yes || echo no)" +check "reader remember -> 404" "404" "$(code "$RK" POST /remember -d "$(mem "$NSA" x y)")" +check "reader correct -> 404" "404" "$(code "$RK" PATCH /memories/$M1 -H 'If-Match: 1' -d '{"content":"no"}')" +check "reader forget -> 404" "404" "$(code "$RK" DELETE /memories/$M1)" +check "other-namespace principal fetch -> 404" "404" "$(code "$OK" GET /memories/$M1)" +check "no-grant principal fetch -> 404" "404" "$(code "$NK" GET /memories/$M1)" +check "no-grant principal list -> empty" '{"data":[],"next_cursor":null}' "$(body "$NK" GET /memories)" +check "writer without delete grant semantics: writer has delete" "200" "$(code "$WK" POST /memories/$M1/retire)" + +# ---- namespace inheritance ------------------------------------------------------------------------------- +check "writer (inherit) remember in /proj/sub -> 201" "201" "$(code "$WK" POST /remember -d "$(mem "$NSSUB" "Sub fact" "in sub")")" +check "sub-only principal remember in /proj/sub -> 201" "201" "$(code "$SK" POST /remember -d "$(mem "$NSSUB" "Sub fact 2" "in sub too")")" +check "sub-only principal remember in /proj -> 404" "404" "$(code "$SK" POST /remember -d "$(mem "$NSA" x y)")" +check "non-inherit grant on /proj: remember in /proj -> 201" "201" "$(code "$XK" POST /remember -d "$(mem "$NSA" "Direct only" "direct")")" +check "non-inherit grant on /proj: remember in /proj/sub -> 404" "404" "$(code "$XK" POST /remember -d "$(mem "$NSSUB" x y)")" + +# ---- validation / limits --------------------------------------------------------------------------------- +check "unknown type -> 422" "422" "$(code "$WK" POST /remember -d "{\"namespace_id\":\"$NSA\",\"type\":\"nope\",\"title\":\"t\",\"content\":\"c\"}")" +check "missing fields -> 422" "422" "$(code "$WK" POST /remember -d '{}')" +check "bad json -> 400" "400" "$(code "$WK" POST /remember -d '{bad')" +check "empty body -> 400" "400" "$(code "$WK" POST /remember)" +check "malformed id -> 404" "404" "$(code "$WK" GET "/memories/1;DROP")" +check "sql-ish namespace_id -> 404" "404" "$(code "$WK" GET "/memories?namespace_id=x'%20OR%20'1'='1")" + +# ---- lifecycle: correct, versions, forget ----------------------------------------------------------------- +R=$(body "$WK" POST /remember -d "$(mem "$NSA" "Lifecycle" "first")"); M2=$(echo "$R" | jget id) +check "correct w/o If-Match -> 428" "428" "$(code "$WK" PATCH /memories/$M2 -d '{"content":"second"}')" +check "correct stale -> 412" "412" "$(code "$WK" PATCH /memories/$M2 -H 'If-Match: 5' -d '{"content":"second"}')" +check "correct ok -> 200" "200" "$(code "$WK" PATCH /memories/$M2 -H 'If-Match: "1"' -d '{"content":"second"}')" +check "second correct with old revision -> 412" "412" "$(code "$WK" PATCH /memories/$M2 -H 'If-Match: 1' -d '{"content":"third"}')" +check "current revision is 2" "2" "$(body "$WK" GET /memories/$M2 | sed -n 's/.*"revision":\([0-9]*\).*/\1/p')" +check "old revision readable" "yes" "$(body "$WK" GET "/memories/$M2?revision=1" | grep -q '"content":"first"' && echo yes || echo no)" +check "versions list has both" "2" "$(body "$WK" GET /memories/$M2/versions | grep -o '"revision":' | wc -l | tr -d ' ')" +check "corrected revision is unverified" "yes" "$(body "$WK" GET /memories/$M2 | grep -q '"verification_status":"unverified"' && echo yes || echo no)" +check "forget by principal without delete -> 404" "404" "$(code "$XK" DELETE /memories/$M2)" +check "forget -> 200" "200" "$(code "$WK" DELETE /memories/$M2)" +check "fetch after forget -> 404" "404" "$(code "$WK" GET /memories/$M2)" +check "versions after forget -> 404" "404" "$(code "$WK" GET /memories/$M2/versions)" + +# ---- duplicates and idempotency -------------------------------------------------------------------------- +D1=$(body "$WK" POST /remember -d "$(mem "$NSA" "Dup" "same")" | jget id) +D2=$(body "$WK" POST /remember -d "$(mem "$NSA" "Dup" "same")") +check "exact duplicate returns same id" "$D1" "$(echo "$D2" | jget id)" +check "exact duplicate flagged" "yes" "$(echo "$D2" | grep -q '"duplicate":true' && echo yes || echo no)" +I1=$(body "$WK" POST /remember -H 'Idempotency-Key: idem-1' -d "$(mem "$NSA" "Idem" "once")" | jget id) +I2=$(body "$WK" POST /remember -H 'Idempotency-Key: idem-1' -d "$(mem "$NSA" "Idem" "once")" | jget id) +check "idempotent replay returns original id" "$I1" "$I2" +check "idempotency key reuse with other body -> 409" "409" "$(code "$WK" POST /remember -H 'Idempotency-Key: idem-1' -d "$(mem "$NSA" "Idem" "changed")")" +check "same idempotency key in another tenant is independent" "201" "$(code "$BK" POST /remember -H 'Idempotency-Key: idem-1' -d "$(mem "$NSB" "Idem" "once")")" + +# ---- sessions and checkpoints ---------------------------------------------------------------------------- +SID=$(body "$WK" POST /sessions -d "{\"namespace_id\":\"$NSA\",\"objective\":\"Build it\"}" | jget id) +check "session start" "yes" "$([ -n "$SID" ] && echo yes || echo no)" +check "other tenant cannot restore session -> 404" "404" "$(code "$BK" GET /sessions/$SID/state)" +check "other tenant cannot save session -> 404" "404" "$(code "$BK" PUT /sessions/$SID/state -H 'If-Match: 0' -d '{"state":{"a":1}}')" +check "no-grant principal cannot restore -> 404" "404" "$(code "$NK" GET /sessions/$SID/state)" +check "save without If-Match -> 428" "428" "$(code "$WK" PUT /sessions/$SID/state -d '{"state":{"a":1}}')" +check "save rev 0 -> 200" "200" "$(code "$WK" PUT /sessions/$SID/state -H 'If-Match: 0' -d '{"state":{"step":1,"next":"api"}}')" +check "stale save -> 412" "412" "$(code "$WK" PUT /sessions/$SID/state -H 'If-Match: 0' -d '{"state":{"step":99}}')" +check "reader can restore" "yes" "$(body "$RK" GET /sessions/$SID/state | grep -q '"next":"api"' && echo yes || echo no)" +check "reader cannot save -> 404" "404" "$(code "$RK" PUT /sessions/$SID/state -H 'If-Match: 1' -d '{"state":{"x":1}}')" +check "different authorized agent resumes and saves -> 200" "200" "$(code "$XK" PUT /sessions/$SID/state -H 'If-Match: 1' -d '{"state":{"step":2}}')" +check "restore shows latest accepted revision" "2" "$(body "$WK" GET /sessions/$SID/state | sed -n 's/.*"revision":\([0-9]*\),"state".*/\1/p')" +check "state must be object -> 422" "422" "$(code "$WK" PUT /sessions/$SID/state -H 'If-Match: 2' -d '{"state":"x"}')" +check "complete -> 200" "200" "$(code "$WK" POST /sessions/$SID/complete -d '{"outcome":"ok"}')" +check "save after complete -> 409" "409" "$(code "$WK" PUT /sessions/$SID/state -H 'If-Match: 2' -d '{"state":{"s":3}}')" + +# ---- UTF-8 round trip (BMP and beyond) ------------------------------------------------------------------- +U=$'caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac \xf0\x9f\x98\x80' +UJ=$(printf '{"namespace_id":"%s","type":"semantic","title":"utf8","content":"%s"}' "$NSA" "$U") +UID_=$(printf '%s' "$UJ" | curl -s -X POST -H "Authorization: Bearer $WK" --data-binary @- "$BASE/remember" | jget id) +check "utf-8 content round trip" "yes" "$(body "$WK" GET /memories/$UID_ | grep -qF "$U" && echo yes || echo no)" + +# ---- revoked key, restart persistence (AC-01), cold first request ---------------------------------------- +KID=$(prov key "$WID" | field api_key_id); KK=$(prov key "$WID" | field api_key) +check "fresh key works" "200" "$(code "$KK" GET /memories)" +KID2=$(prov key "$WID"); KEYID2=$(echo "$KID2" | field api_key_id); KEY2=$(echo "$KID2" | field api_key) +prov revoke "$KEYID2" >/dev/null +check "revoked key -> 401" "401" "$(code "$KEY2" GET /memories)" + +docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done +check "after restart: write works first (cold)" "201" "$(code "$WK" POST /remember -d "$(mem "$NSA" "After restart" "cold write")")" +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)" + +echo "passed: $PASS failed: $FAIL" +for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done +[ "$FAIL" -eq 0 ]