Selaa lähdekoodia

fix: a policy save silently WIPED ip_allow, and the new control was invisible

Asked whether I had updated the docs, I had - llms.txt and openapi.json, both
verified present. Checking for docs I had MISSED found a defect instead, and
it is worse than the missing documentation would have been.

THE WEB UI NEVER MODELLED `ip_allow`. `pages/Functions.tsx` built its policy
from a literal of four fields and PUT it at a route that REPLACES the whole
policy, so every field the type did not know became a server-side default on
save. An admin editing a rate limit silently removed that function's address
allow-list - a security control deleted by an unrelated edit, with a success
toast and nothing anywhere to say so. `allow_same_origin_host` (0.21.0) was
lost the same way, and `rate_limit_per_caller_per_min` would have been.

The editor now SPREADS what it loaded before overriding the fields it owns, so
a field added to the policy later survives by construction rather than by
somebody remembering this file exists.

PINNED WHERE A UI FIX CANNOT REACH. Two tests assert the SERVER contract a
read-modify-write client depends on: everything `fromJson` reads must appear in
`toJson`, and the wire shape must NAME every field even at its default. The
second is the pairing - the first alone still passes if a field is dropped from
both sides at once, which is exactly what "tidying up an unused member" does.
Falsified by deleting ip_allow from the emitter: both go red.

The key path was checked and is SAFE: the PATCH handler only touches scope when
the body contains it, and the UI's updateKey sends only {projects, admin}.

AND THE CONTROL IS NOW VISIBLE, which is the other half of shipping a policy
field. `rate_limit_per_caller_per_min` has an input beside the per-function
one, because the pair only means anything read together, and the summary line
names both plus any address ranges - an operator who cannot see an allow-list
cannot notice it vanishing. This codebase already recorded that lesson for
`network_egress`, where a control reachable only by curl meant an operator
could not tell whether a project had egress.

Three instrument failures of my own, in sequence, each caught by the next
check. A `grep -n "rateLimit"` reported the new state as absent because the new
identifiers capitalise the R. My insertion anchor had the WRONG INDENTATION
because I copied it out of my own `sed 's/^/  /'` display, which had added two
spaces - so the edit failed while a sibling edit in the same command succeeded,
and `npm run build` then passed, green about a control that was not there. The
file's real indent was read back before inserting by line.

1537/1537 serial; webui build clean.
fszontagh 6 päivää sitten
vanhempi
sitoutus
b1579213ae
3 muutettua tiedostoa jossa 104 lisäystä ja 0 poistoa
  1. 54 0
      tests/test_apikey.cpp
  2. 43 0
      webui/src/pages/Functions.tsx
  3. 7 0
      webui/src/types/index.ts

+ 54 - 0
tests/test_apikey.cpp

@@ -101,3 +101,57 @@ TEST(KeyScopeReserved, ThisIsWhyItMattersForAnythingAddedLater) {
     EXPECT_EQ(scope.findRule("_conn:some_mailbox", svapi::KeyOp::Insert), nullptr)
         << "a future reserved prefix must inherit the literal-grant rule automatically";
 }
+
+// ─── A READ-MODIFY-WRITE CLIENT MUST NOT BE ABLE TO LOSE A FIELD ──────────
+//
+// The function policy route is a full REPLACE, so the web UI reads a policy,
+// edits one control and sends the whole thing back. Every field `fromJson`
+// understands therefore has to appear in `toJson`, or the client cannot
+// return what it was given and the save silently resets it to a default.
+//
+// This was NOT hypothetical. `pages/Functions.tsx` built its policy object
+// from a literal of four fields, so saving an unrelated control wiped
+// `ip_allow` - an address allow-list removed by editing a rate limit, with a
+// success toast. The UI now spreads what it loaded; this test is what stops
+// the next field being added to the parser and not to the emitter, which is
+// the half a UI fix cannot protect.
+
+TEST(KeyScopeRoundTrip, EveryFieldFromJsonReadsIsAlsoEmittedByToJson) {
+    svapi::KeyScope s;
+    s.rules.push_back({"c", {svapi::KeyOp::Read}, false});
+    s.origins = {"https://example.test"};
+    s.ipAllow = {"203.0.113.0/24"};
+    s.allowSameOriginHost = true;
+    s.rateLimitPerMin = 60;
+    s.rateLimitPerCallerPerMin = 5;
+    s.expiresAt = 1790000000ull;
+
+    // The trip a read-modify-write client makes, with NO edit at all: whatever
+    // comes out must go back in unchanged.
+    const svapi::KeyScope back = svapi::KeyScope::fromJson(s.toJson());
+
+    EXPECT_EQ(back.rules.size(), 1u);
+    EXPECT_EQ(back.origins, s.origins);
+    EXPECT_EQ(back.ipAllow, s.ipAllow) << "an allow-list lost here is a security control "
+                                          "removed by an unrelated edit";
+    EXPECT_EQ(back.allowSameOriginHost, s.allowSameOriginHost);
+    EXPECT_EQ(back.rateLimitPerMin, s.rateLimitPerMin);
+    EXPECT_EQ(back.rateLimitPerCallerPerMin, s.rateLimitPerCallerPerMin);
+    EXPECT_EQ(back.expiresAt, s.expiresAt);
+}
+
+// THE PAIRING, naming the fields explicitly. The test above would still pass
+// if a field were dropped from BOTH sides at once, which is exactly what
+// happens when someone "tidies up" an unused member - so assert the key is
+// actually present in the wire shape rather than only that a round trip
+// agrees with itself.
+TEST(KeyScopeRoundTrip, TheWireShapeNamesEveryFieldEvenAtItsDefault) {
+    const nlohmann::json j = svapi::KeyScope{}.toJson();
+    for (const char* k : {"rules", "origins", "ip_allow", "allow_same_origin_host",
+                          "rate_limit_per_min", "rate_limit_per_caller_per_min",
+                          "expires_at"}) {
+        EXPECT_TRUE(j.contains(k))
+            << k << " is absent from the wire shape, so a client that reads a policy "
+                    "and sends it back cannot preserve it";
+    }
+}

+ 43 - 0
webui/src/pages/Functions.tsx

@@ -488,6 +488,7 @@ function PolicyTab({
   const [rules, setRules] = useState<KeyScopeRule[]>(fn.policy.rules)
   const [origins, setOrigins] = useState(fn.policy.origins.join(', '))
   const [rateLimit, setRateLimit] = useState(fn.policy.rate_limit_per_min)
+  const [callerRateLimit, setCallerRateLimit] = useState(fn.policy.rate_limit_per_caller_per_min ?? 0)
   const [expiresAt, setExpiresAt] = useState(fn.policy.expires_at)
   const [saving, setSaving] = useState(false)
   const [err, setErr] = useState<ApiError | null>(null)
@@ -496,6 +497,7 @@ function PolicyTab({
     setRules(fn.policy.rules)
     setOrigins(fn.policy.origins.join(', '))
     setRateLimit(fn.policy.rate_limit_per_min)
+    setCallerRateLimit(fn.policy.rate_limit_per_caller_per_min ?? 0)
     setExpiresAt(fn.policy.expires_at)
     setErr(null)
     // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -526,11 +528,19 @@ function PolicyTab({
     setErr(null)
     try {
       const policy: KeyScope = {
+        // SPREAD FIRST, so a field this editor does not model survives the
+        // save. This route REPLACES the whole policy, and this object used to
+        // be a literal of four fields - so saving a rate limit silently wiped
+        // `ip_allow`, removing an address allow-list with a success toast and
+        // nothing to tell the operator. Anything added to the policy later is
+        // now preserved by default rather than by somebody remembering.
+        ...fn.policy,
         // require_human_token is dropped: it is an HTTP-header check and a
         // function never presents one, so storing it would be decoration.
         rules: usableRules(rules, false),
         origins: origins.split(',').map((o) => o.trim()).filter((o) => o.length > 0),
         rate_limit_per_min: rateLimit,
+        rate_limit_per_caller_per_min: callerRateLimit,
         expires_at: expiresAt,
       }
       await api.setFunctionPolicy(project, fn.function_id, policy)
@@ -595,6 +605,31 @@ function PolicyTab({
             className={inputCls}
           />
         </div>
+        {/* The per-CALLER ceiling, beside the per-function one because the
+            pair only means anything read together: the first bounds the total
+            damage and says nothing about who caused it, the second stops one
+            caller consuming the whole allowance. A control nobody can see is a
+            control nobody knows exists, so it ships with the field. */}
+        <div className="flex-1 min-w-40">
+          <label className="block text-xs font-medium text-slate-400 mb-1">
+            Rate limit / min per caller{' '}
+            <span className="text-slate-500">(0 = unlimited)</span>
+          </label>
+          <input
+            type="number"
+            min={0}
+            step={1}
+            value={callerRateLimit}
+            onChange={(e) =>
+              setCallerRateLimit(Math.max(0, Math.floor(Number(e.target.value) || 0)))
+            }
+            className={inputCls}
+          />
+          <p className="mt-1 text-xs text-slate-500">
+            Keyed on the caller's resolved address. HTTP calls only; a cron or job run
+            has no caller.
+          </p>
+        </div>
         <div className="flex-1 min-w-40">
           <label className="block text-xs font-medium text-slate-400 mb-1">
             Expires at <span className="text-slate-500">(epoch seconds; 0 = never)</span>
@@ -634,6 +669,14 @@ function PolicyLimitsView({ policy }: { policy: KeyScope }) {
       <dt className="text-slate-500">Rate limit</dt>
       <dd className="text-slate-300 font-mono">
         {policy.rate_limit_per_min > 0 ? `${policy.rate_limit_per_min}/min` : 'unlimited'}
+        {(policy.rate_limit_per_caller_per_min ?? 0) > 0
+          ? ` · ${policy.rate_limit_per_caller_per_min}/min per caller`
+          : ''}
+        {/* Surfaced because this is the field a policy save used to wipe: an
+            operator who cannot see an allow-list cannot notice it vanishing. */}
+        {policy.ip_allow && policy.ip_allow.length > 0
+          ? ` · ${policy.ip_allow.length} address range${policy.ip_allow.length === 1 ? '' : 's'}`
+          : ''}
       </dd>
       <dt className="text-slate-500">Expires</dt>
       <dd className="text-slate-300 font-mono">

+ 7 - 0
webui/src/types/index.ts

@@ -60,7 +60,14 @@ export interface KeyScopeRule {
 export interface KeyScope {
   rules: KeyScopeRule[]
   origins: string[]
+  /// CIDRs the caller's resolved address must fall inside. Modelled here
+  /// because the policy route is a full REPLACE: a field this type does not
+  /// know is a field an editor silently resets to its default on save.
+  ip_allow?: string[]
+  allow_same_origin_host?: boolean
   rate_limit_per_min: number
+  /// Per CALLER, keyed on the resolved address. 0 = unlimited.
+  rate_limit_per_caller_per_min?: number
   expires_at: number
 }
 export interface ApiKeyPublic {