소스 검색

docs: document static serving and hostnames; stop tests littering the shared DB

TWO ROUTES WERE LIVE AND UNDOCUMENTED, and static serving was absent from
api/llms.txt entirely. This repo's own rule is that a SILENCE in llms.txt
propagates as confidently as a wrong sentence and is harder to find, because
you cannot grep for an absence - so both are written up with the things a
caller would otherwise have to discover by experiment:

- the served path comes from per-file METADATA, not the name, set with
  `X-File-Path` at upload; a file with no path is NOT reachable over the mount
  and stays private
- `index: ""` is a VALUE meaning "no SPA fallback", not an absent key
- the service's own surfaces always win over a `/` mount
- ETag is the stored checksum; If-None-Match gives a 304
- GET only - HEAD is not implemented and answers 404
- `served` on the hostnames route distinguishes "stored and in force" from
  "stored and INERT", which no other field can
- the PUT replaces the whole list, so a partial body drops the rest
- the 5000-record alias scan, and that it disappears by itself on database
  2.21.8 with no caller change

Both routes added to openapi.json, modelled on the existing per-project
settings path rather than invented.

A ROUTE SWEEP CONFIRMS THE DOCS ARE COMPLETE - and the first version of that
sweep was worthless: `R"\((/api/v1[^)]*)\)"` stops at the first `)`, which
every route pattern contains, so it found ONE route and reported "0
undocumented". A check that cannot fail. Fixed and re-run: 41 routes in source,
all documented once `{x}` and `{project}` are normalised.

TESTS NO LONGER LITTER THE SHARED DATABASE. The encryption-upgrade test dropped
its two collections on every path its author thought about - success and skip -
and an ASSERT failure reaches neither. A single red run leaked two collections
into the shared `default` project permanently, one of which requests an
encryption RESEAL at the next restart. They accumulated until another team
auditing that instance reported them as unexplained data.

Replaced with an RAII guard registered BEFORE anything is created, so cleanup
runs however the test exits. Falsified: with a deliberate ASSERT failure
injected mid-test, the run goes red and leaves ZERO collections behind, where
the old code leaked two.

The general shape, worth keeping: a test that cleans up only when it passes
litters precisely when something is already wrong.
fszontagh 6 일 전
부모
커밋
fb7b91f0fd
3개의 변경된 파일과 355개의 추가작업 그리고 4개의 파일을 삭제
  1. 66 0
      api/llms.txt
  2. 260 0
      api/openapi.json
  3. 29 4
      tests/test_api_integration.cpp

+ 66 - 0
api/llms.txt

@@ -35,6 +35,72 @@ name-mismatch error on an unrelated tenant's hostname.
 If TLS is configured and cannot be set up, the server REFUSES TO START rather
 than serving plain HTTP on a port callers reach over https.
 
+## Static files: serving a project's own assets
+
+OFF by default and it needs TWO independent things, neither of which implies
+the other: the request must arrive on a hostname registered to the project,
+AND that project must have static serving explicitly enabled. A project may
+hold a hostname and serve nothing; a project may hold files and no hostname, in
+which case they stay private.
+
+It is UNAUTHENTICATED, because a browser fetching an image carries no
+credential. That is why enabling it is an act rather than an inherited state:
+turning it on publishes files that were private a moment earlier.
+
+- `GET /api/v1/projects/{p}/settings/static` (admin)
+- `PUT /api/v1/projects/{p}/settings/static` (admin) - body
+  `{"enabled": bool, "mount": "/", "index": "index.html", "cache_control": "public, max-age=300"}`
+
+`mount` is where the tree appears (`/` or `/something`). A mount under `/api`,
+`/fn` or `/healthz` is refused 422 `invalid_mount`: **the service's own
+surfaces always win**, whatever the mount, so a `/` mount never shadows the API.
+
+`index` is the SPA fallback for a path matching no file. **`""` is a VALUE
+meaning "no fallback - an unmatched path answers a plain 404", not an absent
+key.** An absent key leaves the stored value alone; a present empty string is
+stored.
+
+### The path a file is served at comes from its METADATA, not its name
+
+File names are a single path segment, so `assets/index-a1b2.js` cannot be a
+name. The served path lives in the database's per-file metadata under `path`:
+
+    POST /api/v1/projects/{p}/files   with header  X-File-Path: /img/logo.png
+
+**A file with no `path` metadata is not reachable over the static mount at
+all** - it stays private, addressable only through the authenticated files
+route. Absence means private; it never falls back to serving by name. A PUT
+replaces rather than merges, so re-uploading without the header makes a file
+private again.
+
+### Caching, and what is not implemented
+
+`ETag` is the stored checksum, as a strong validator. `If-None-Match` is
+honoured with a 304 carrying the ETag and `Cache-Control` and no body - which
+is the highest-value part of this for an SPA, since the alternative is
+re-sending every chunk on every load.
+
+`Content-Type` is the type stored at upload and is NEVER sniffed from the
+extension. A file stored with the wrong type is a tenant's to fix; guessing
+would make the stored value a lie that sometimes works.
+
+**GET only. HEAD is not implemented and answers 404.** There is no directory
+listing, ever, and a path matching no file answers the same 404 whether the
+project has one file or a thousand.
+
+Per-file ceiling is `max_file_bytes` (global setting, default 2 MiB) - the same
+number that bounds storage, deliberately not a second number meaning nearly the
+same thing. The per-run 1 MiB `ctx.files` limit does NOT apply here: that bounds
+what one function may load into a JS heap, and this path never enters the
+runtime.
+
+**Known cost, until database 2.21.8 is everywhere:** resolving an alias needs
+the per-file metadata, which older servers omit from the files LISTING while
+returning it from `getFileInfo`. The lookup therefore re-fetches per record
+when the listing comes back empty, capped at 5000 records. A fast path keeps
+the common case at two calls. This disappears by itself on 2.21.8 with no
+change to any caller.
+
 ## Hostnames: the short path form
 
 Every project-scoped route accepts TWO shapes:

+ 260 - 0
api/openapi.json

@@ -5319,6 +5319,266 @@
           }
         }
       }
+    },
+    "/api/v1/projects/{project}/settings/hostnames": {
+      "get": {
+        "summary": "Project hostnames (read)",
+        "description": "Hostnames this project answers on. A request arriving on one is scoped to THIS project, so this is a tenancy boundary rather than routing. Wildcards are refused here and belong only in certificate selection.",
+        "tags": [
+          "projects"
+        ],
+        "parameters": [
+          {
+            "name": "project",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "current configuration",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "project": {
+                      "type": "string"
+                    },
+                    "hostnames": {
+                      "type": "array",
+                      "items": {
+                        "type": "object",
+                        "properties": {
+                          "host": {
+                            "type": "string",
+                            "example": "nt.kb.smartbotics.ai"
+                          },
+                          "path_style": {
+                            "type": "string",
+                            "enum": [
+                              "short",
+                              "full"
+                            ],
+                            "default": "short"
+                          }
+                        }
+                      }
+                    },
+                    "served": {
+                      "type": "boolean",
+                      "description": "Whether host gating is IN FORCE. False means the hostnames are stored but inert, because the deployment has not named itself (admin_hostname / global_hostnames). A stored-and-inert list is indistinguishable from a live one without this field."
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "403": {
+            "description": "admin key required"
+          }
+        }
+      },
+      "put": {
+        "summary": "Project hostnames (replace)",
+        "description": "Hostnames this project answers on. A request arriving on one is scoped to THIS project, so this is a tenancy boundary rather than routing. Wildcards are refused here and belong only in certificate selection.\n\nAdmin only. The PUT REPLACES the whole configuration; a partial body drops what it omits.",
+        "tags": [
+          "projects"
+        ],
+        "parameters": [
+          {
+            "name": "project",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          }
+        ],
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": {
+                  "project": {
+                    "type": "string"
+                  },
+                  "hostnames": {
+                    "type": "array",
+                    "items": {
+                      "type": "object",
+                      "properties": {
+                        "host": {
+                          "type": "string",
+                          "example": "nt.kb.smartbotics.ai"
+                        },
+                        "path_style": {
+                          "type": "string",
+                          "enum": [
+                            "short",
+                            "full"
+                          ],
+                          "default": "short"
+                        }
+                      }
+                    }
+                  },
+                  "served": {
+                    "type": "boolean",
+                    "description": "Whether host gating is IN FORCE. False means the hostnames are stored but inert, because the deployment has not named itself (admin_hostname / global_hostnames). A stored-and-inert list is indistinguishable from a live one without this field."
+                  }
+                }
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "stored; the response is the configuration read back"
+          },
+          "403": {
+            "description": "admin key required"
+          },
+          "422": {
+            "description": "refused: `invalid_hostname` (change the value), `hostname_taken` (another project holds it), `hostname_reserved` (it is the deployment's own admin or global name)"
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/settings/static": {
+      "get": {
+        "summary": "Project static file serving (read)",
+        "description": "Serve the project's stored files over HTTP on its own hostname. UNAUTHENTICATED, so it requires BOTH a registered project hostname AND an explicit enable; off by default. The served path of each file comes from its metadata `path`, set with the X-File-Path header at upload; a file without one is not reachable here.",
+        "tags": [
+          "projects"
+        ],
+        "parameters": [
+          {
+            "name": "project",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "current configuration",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "project": {
+                      "type": "string"
+                    },
+                    "enabled": {
+                      "type": "boolean",
+                      "default": false
+                    },
+                    "mount": {
+                      "type": "string",
+                      "default": "/"
+                    },
+                    "index": {
+                      "type": "string",
+                      "default": "index.html",
+                      "description": "SPA fallback. An empty string is a VALUE meaning 'no fallback; an unmatched path answers 404', not an absent key."
+                    },
+                    "cache_control": {
+                      "type": "string",
+                      "default": "public, max-age=300"
+                    },
+                    "has_hostname": {
+                      "type": "boolean",
+                      "description": "Static serving requires at least one project hostname."
+                    },
+                    "served": {
+                      "type": "boolean"
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "403": {
+            "description": "admin key required"
+          }
+        }
+      },
+      "put": {
+        "summary": "Project static file serving (replace)",
+        "description": "Serve the project's stored files over HTTP on its own hostname. UNAUTHENTICATED, so it requires BOTH a registered project hostname AND an explicit enable; off by default. The served path of each file comes from its metadata `path`, set with the X-File-Path header at upload; a file without one is not reachable here.\n\nAdmin only. The PUT REPLACES the whole configuration; a partial body drops what it omits.",
+        "tags": [
+          "projects"
+        ],
+        "parameters": [
+          {
+            "name": "project",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          }
+        ],
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": {
+                  "project": {
+                    "type": "string"
+                  },
+                  "enabled": {
+                    "type": "boolean",
+                    "default": false
+                  },
+                  "mount": {
+                    "type": "string",
+                    "default": "/"
+                  },
+                  "index": {
+                    "type": "string",
+                    "default": "index.html",
+                    "description": "SPA fallback. An empty string is a VALUE meaning 'no fallback; an unmatched path answers 404', not an absent key."
+                  },
+                  "cache_control": {
+                    "type": "string",
+                    "default": "public, max-age=300"
+                  },
+                  "has_hostname": {
+                    "type": "boolean",
+                    "description": "Static serving requires at least one project hostname."
+                  },
+                  "served": {
+                    "type": "boolean"
+                  }
+                }
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "stored; the response is the configuration read back"
+          },
+          "403": {
+            "description": "admin key required"
+          },
+          "422": {
+            "description": "refused: `invalid_mount` (a mount under /api, /fn or /healthz; the service's own surfaces always win)"
+          }
+        }
+      }
     }
   }
 }

+ 29 - 4
tests/test_api_integration.cpp

@@ -3942,12 +3942,41 @@ TEST_F(ApiFixture, EachCredentialStoreSetsTheEncryptedFLAG_whichProtectsNothing)
 // The fix is to call createCollection unconditionally. 2.17.0 turns encryption
 // ON for an existing collection (never off); older servers treat the re-call
 // as a no-op.
+namespace {
+
+/// Drop a list of qualified collections however the test exits.
+///
+/// WHY RAII AND NOT A DROP AT THE END: the drops WERE at the end, on every
+/// path the author thought about - success and skip. An ASSERT_* failure
+/// returns immediately and reaches none of them, so a single red run leaked two
+/// collections into the SHARED `default` project and left them there forever.
+/// They accumulated until another team auditing that instance reported them as
+/// unexplained data, and one of them requests an encryption RESEAL at the next
+/// restart, so the cost was a compaction nobody asked for.
+///
+/// A test that cleans up only when it passes is a test that litters precisely
+/// when something is already wrong.
+struct DropCollections {
+    svapi::DbGateway* db;
+    std::vector<std::string> qualified;
+    ~DropCollections() {
+        for (const std::string& q : qualified) {
+            try { db->client().dropCollection(q); } catch (...) {}
+        }
+    }
+};
+
+} // namespace
+
 TEST_F(ApiFixture, BootstrapAsksForEncryptionOnAnAlreadyEXISTINGCollection) {
     const std::string suffix = std::to_string(::getpid()) + "_" + std::to_string(::time(nullptr));
     const std::string target  = "enc_upgrade_target_" + suffix;
     const std::string control = "enc_upgrade_control_" + suffix;
     const std::string qTarget  = svapi::qualify("default", target);
     const std::string qControl = svapi::qualify("default", control);
+    // Registered BEFORE anything is created, so an ASSERT between here and the
+    // end still cleans up.
+    DropCollections cleanup{db_.get(), {qTarget, qControl}};
 
     // Both collections are created PLAIN and by hand, standing in for one the
     // database made implicitly before our store ever ran.
@@ -3987,8 +4016,6 @@ TEST_F(ApiFixture, BootstrapAsksForEncryptionOnAnAlreadyEXISTINGCollection) {
            "not measuring what it claims to";
 
     if (!target_info->encrypted) {
-        db_->client().dropCollection(qTarget);
-        db_->client().dropCollection(qControl);
         GTEST_SKIP() << "this server does not switch encryption on for an existing collection "
                         "(database 2.17.0 and later do); our side asked for it, which is all "
                         "this code controls - verify the bytes with `smartbotic-db-cli "
@@ -3997,8 +4024,6 @@ TEST_F(ApiFixture, BootstrapAsksForEncryptionOnAnAlreadyEXISTINGCollection) {
 
     // Reached only on 2.17.0+: the upgrade happened, driven by our re-call.
     EXPECT_TRUE(target_info->encrypted);
-    db_->client().dropCollection(qTarget);
-    db_->client().dropCollection(qControl);
 }