Forráskód Böngészése

feat(errors): map encrypted_field to its own slug, not generic validation

Database 2.17.0 will encrypt any field named password, secret, token,
api_key, apiKey or credentials at ANY depth in EVERY collection, and then
refuse a filter, sort, index, unique constraint, relation or increment on
one with INVALID_ARGUMENT / encrypted_field.

Without this it would have arrived as our generic `validation` 422, which
is accurate and useless: the request is well formed, the field name is
spelled correctly, and no amount of correcting the body helps. The caller
has to stop querying that field - store a non-sensitive duplicate to
query by, or rename it if it was never a credential. A `validation` slug
sends them hunting for a typo that does not exist.

Worth recording what it replaces, because the old behaviour was worse: a
top-level field of those names was plaintext and filterable, and a nested
one compared ciphertext and SILENTLY MATCHED NOTHING. So the refusal
converts a silently empty result into a visible error - an improvement
even for the caller who now gets a 422 where they used to get a 200.

Audited for exposure, source first: our /documents filter grammar, ?sort=
and the index route all accept any field name with no validation, so a
TENANT can trigger this. We cannot - our own tests use `password` only as
a ctx.mail option key, never as a stored field being queried, and nothing
in the service filters, sorts or indexes on such a name.

Sampled 25 rows per collection across all five prod projects for keys of
those names at any depth, reading names only and no values: none found.
That is a sample and not a proof, so the consumers are being asked
directly rather than inferred from.

The falsifying half of the test asserts an unrecognised InvalidArgument
reason still maps to `validation`, so the new branch cannot swallow the
general case.

1252/1252 green.
fszontagh 1 hónapja
szülő
commit
74ea722c72
3 módosított fájl, 53 hozzáadás és 0 törlés
  1. 1 0
      CLAUDE.md
  2. 20 0
      src/db_errors.cpp
  3. 32 0
      tests/test_db_errors.cpp

+ 1 - 0
CLAUDE.md

@@ -148,6 +148,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **Client ABI pin:** the server deb is compiled against `DB_CLIENT_VERSION` (`packaging/Dockerfile.base`). Every 2.x client shares one SONAME, so a deb built against a newer client installs fine and only segfaults on the next restart - keep the pin equal to the deploy target, and ship a DB upgrade and a vectorapi rebuild together.
 - **The apt repo now indexes EVERY published version, so a rollback is an ordinary apt command.** It used to list only the newest, which made `pkg=<old version>` uninstallable the moment anything newer was published - and that was never retention, only indexing: `dpkg-scanpackages` emits one version per package unless given `-m`, while the pool had kept every `.deb` all along (a publish reported "3 added, 309 unchanged"). Fixed 2026-10-08 in the deb-repo tooling; the trixie index went from 33 stanzas to 1191. **A downgrade needs `--allow-downgrades`** (`apt-get install --allow-downgrades pkg=0.7.1-1 ...`), and downgrade the three app packages TOGETHER or apt resolves a split version set. A plain `apt install pkg` still picks the newest, so ordinary installs are unaffected. The backup step still stages the installed `.deb`s out of `/var/cache/apt/archives/`, which stays the right belt-and-braces for a rollback when the repo itself is unreachable.
 - **"The dev host cannot build the C++" was a misdiagnosis - it was a stale `protoc`.** The host builds everything natively; use `scripts/host-build.sh`. The old symptom was real: generated protos wanted `google/protobuf/map_field_inl.h`, a header protobuf 35 removed. But nothing in the database's tree includes that header - an **old protoc emits the include**. The host had libprotobuf 35.1 and gRPC 1.83 from the distro, and a hand-dropped static **protoc 25.2 in `~/.local/bin`** shadowing everything, while the distro's compiler package (`protobuf-35.1`, separate from `protobuf-devel`, which ships no protoc) was never installed. `find_program(PROTOC protoc REQUIRED)` took the 25.2 binary from PATH, generated code for a protobuf 25 runtime and compiled it against 35 headers. With a matching protoc the client and all of vectorapi compile and link natively. `host-build.sh` therefore picks protoc **by version rather than PATH order** and refuses to run on a mismatch, because the failure otherwise surfaces as a missing header deep in generated code rather than as a version complaint.
+- **`encrypted_field` (422) is its own slug, not `validation`.** Database 2.17.0 encrypts any field named `password`, `secret`, `token`, `api_key`, `apiKey` or `credentials` at ANY depth in EVERY collection, and then REFUSES a filter, sort, index, unique constraint, relation or increment on one. It needs its own slug because the remedy is unlike every other validation failure: the request is well formed, the field name is correct, and no correction of the body helps - the caller must stop querying that field, storing a non-sensitive duplicate (a hash, or a boolean "set") or renaming it if it was never a credential. Folding it into `validation` would send them hunting a typo. Note what it REPLACES is worse than itself: before 2.17.0 a top-level field of those names was plaintext and filterable, and a NESTED one compared ciphertext and **silently matched nothing** - so the refusal turns a silently empty result into a visible error. **Our `/documents` filter grammar, `?sort=` and the index route all accept ANY field name with no validation, so a TENANT can trigger this; we cannot.** Our own tests use `password` only as a `ctx.mail` option key, never as a stored field being queried.
 - **`FailedPrecondition` means three different things** and must be branched on `FailureDetail.reason`: `missing_parent` and `delete_restricted` are 422, `read_only` is **503**, and an absent or unrecognised reason is **500**, never a guessed 422. Mapping the bare code to 422 told a caller that a read-only database was its own validation mistake, so it would fix its payload and retry forever instead of waiting. Use the `FailureDetail&` overloads wherever a call offers one - the reason-less `Failure` form cannot tell these apart.
 - **A version conflict is `ErrorCode::Aborted`** (client 2.12.0) carrying `currentVersion`, and maps to **409** `version_conflict`. It used to arrive as `Unknown` and fold into 503 "retry as-is", which is the opposite of the required instruction: re-read first. Never match on the message text for this.
 - **`patch` with a field set to null REMOVES the field** (RFC 7396 merge), it does not store null. Use `update` for an explicit null.

+ 20 - 0
src/db_errors.cpp

@@ -69,6 +69,26 @@ ApiError translate(Code code, const std::string& message, const std::string& not
             // `validation` answer would send a caller looking for.
             if (reason == "document_too_large")
                 return ApiError(ErrCode::Unprocessable, "document_too_large", message, details);
+            if (reason == "encrypted_field")
+                // database 2.17.0 encrypts any field named password, secret,
+                // token, api_key, apiKey or credentials at ANY depth, in EVERY
+                // collection, and then REFUSES a filter, sort, index, unique
+                // constraint, relation or increment on one.
+                //
+                // Its own slug, not the generic `validation`, because the
+                // remedy is unlike every other validation failure: the request
+                // is well formed and the field is spelled correctly, and no
+                // amount of correcting the body helps. The caller has to stop
+                // querying that field - store a non-sensitive duplicate to
+                // query by (a hash, or a boolean "set"), or rename the field if
+                // it was never a credential.
+                //
+                // Worth knowing what it REPLACES, because the old behaviour was
+                // worse: before 2.17.0 a top-level field of those names was
+                // plaintext and filterable, and a NESTED one compared ciphertext
+                // and silently matched nothing. So this refusal turns a silently
+                // empty result into a visible error.
+                return ApiError(ErrCode::Unprocessable, "encrypted_field", message, details);
             return ApiError(ErrCode::Unprocessable, "validation", message);
         case Code::OutOfRange:
             return ApiError(ErrCode::Unprocessable, "validation", message);

+ 32 - 0
tests/test_db_errors.cpp

@@ -320,3 +320,35 @@ TEST(DbErrors, UnavailableIsUnaffectedByTheDeadlineBranch) {
 }
 
 } // namespace
+
+TEST(DbErrors, AnEncryptedFieldQueryGetsItsOwnSlugNotGenericValidation) {
+    // database 2.17.0 refuses a filter, sort, index, unique constraint,
+    // relation or increment on a field it encrypts (password, secret, token,
+    // api_key, apiKey, credentials at any depth, in every collection).
+    //
+    // It needs its own slug because the remedy is unlike any other validation
+    // failure: the request is well formed and the field name is correct, and
+    // correcting the body cannot help - the caller must stop querying that
+    // field. Folding it into `validation` would send them looking for a typo.
+    smartbotic::database::Client::FailureDetail d;
+    d.code = smartbotic::database::Client::ErrorCode::InvalidArgument;
+    d.reason = "encrypted_field";
+    d.message = "cannot filter on encrypted field 'token'";
+    d.fields = {"token"};
+    const svapi::ApiError e = svapi::apiErrorFor(d, "no such document");
+    EXPECT_EQ(e.slug, "encrypted_field");
+    EXPECT_EQ(svapi::httpStatus(e.code), 422);
+    // The field must survive into details, so a client can say WHICH field.
+    ASSERT_TRUE(e.details.contains("field")) << e.details.dump();
+    EXPECT_EQ(e.details.at("field"), "token");
+}
+
+TEST(DbErrors, AnUnrecognisedInvalidArgumentReasonStaysGenericValidation) {
+    // The falsifying half: the new branch must not swallow the general case.
+    smartbotic::database::Client::FailureDetail d;
+    d.code = smartbotic::database::Client::ErrorCode::InvalidArgument;
+    d.reason = "something_new_we_do_not_know";
+    d.message = "whatever";
+    const svapi::ApiError e = svapi::apiErrorFor(d, "no such document");
+    EXPECT_EQ(e.slug, "validation");
+}