Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Fix CheckRelease to hide databases outside project (#21320)

Danny Xu64dc25a321cf
diff --git a/backend/api/v1/project_instance_release_check_test.go b/backend/api/v1/project_instance_release_check_test.go
index 9376d88bf5..f921446fc8 100644
--- a/backend/api/v1/project_instance_release_check_test.go
+++ b/backend/api/v1/project_instance_release_check_test.go
@@ -37,7 +37,7 @@ func TestCheckReleaseDatabaseTargetsKeepCanonicalNames(t *testing.T) {
Release: declarativeReleaseWithDisallowedStatement(),
Targets: []string{workspaceTarget},
}))
- require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+ require.Equal(t, connect.CodeNotFound, connect.CodeOf(err))
}
func TestCheckReleaseRejectsCrossProjectTargets(t *testing.T) {
@@ -60,6 +60,45 @@ func TestCheckReleaseRejectsCrossProjectTargets(t *testing.T) {
}
}
+func TestCheckReleaseHidesDatabasesOutsideProject(t *testing.T) {
+ ctx, stores, _, _ := setupProjectInstanceReleaseCheckTest(t)
+ sharedInstanceID := "shared-instance"
+ _, err := stores.CreateInstance(ctx, &store.InstanceMessage{
+ ResourceID: sharedInstanceID,
+ Workspace: "default",
+ Metadata: &storepb.Instance{
+ Engine: storepb.Engine_POSTGRES,
+ DataSources: []*storepb.DataSource{{
+ Id: "admin",
+ Type: storepb.DataSourceType_ADMIN,
+ }},
+ },
+ })
+ require.NoError(t, err)
+ _, err = stores.UpsertDatabase(ctx, &store.DatabaseMessage{
+ InstanceID: sharedInstanceID,
+ DatabaseName: "other",
+ ProjectID: "project-b",
+ Metadata: &storepb.DatabaseMetadata{},
+ })
+ require.NoError(t, err)
+
+ // A database in another project and one that does not exist must be
+ // indistinguishable, or the check maps databases workspace-wide.
+ service := NewReleaseService(stores, sheet.NewManager(), nil, nil)
+ for _, target := range []string{
+ common.FormatDatabase(sharedInstanceID, "other"),
+ common.FormatDatabase(sharedInstanceID, "missing"),
+ } {
+ _, err := service.CheckRelease(ctx, connect.NewRequest(&v1pb.CheckReleaseRequest{
+ Parent: common.FormatProject("project-a"),
+ Release: declarativeReleaseWithDisallowedStatement(),
+ Targets: []string{target},
+ }))
+ require.EqualError(t, err, fmt.Sprintf("not_found: database %s not found", target))
+ }
+}
+
func TestCheckReleaseRejectsArchivedProject(t *testing.T) {
ctx, stores, instanceID, databaseName := setupProjectInstanceReleaseCheckTest(t)
archived := true
diff --git a/backend/api/v1/release_service_check.go b/backend/api/v1/release_service_check.go
index b0577df20c..b9d42e1805 100644
--- a/backend/api/v1/release_service_check.go
+++ b/backend/api/v1/release_service_check.go
@@ -89,11 +89,12 @@ func (s *ReleaseService) CheckRelease(ctx context.Context, req *connect.Request[
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to found database %v", target))
}
- if database == nil {
- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("database %v not found", target))
- }
- if database.ProjectID != projectID {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("database target %q does not belong to project %q", target, projectID))
+ // One error for missing, foreign, archived, and non-canonical: a
+ // distinct one would confirm what lives in a project the caller
+ // cannot see.
+ notFound := connect.NewError(connect.CodeNotFound, errors.Errorf("database %v not found", target))
+ if database == nil || database.ProjectID != projectID {
+ return nil, notFound
}
instance, err := s.store.GetInstance(ctx, &store.FindInstanceMessage{
Workspace: workspaceID,
@@ -102,12 +103,8 @@ func (s *ReleaseService) CheckRelease(ctx context.Context, req *connect.Request[
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
- if instance == nil || instance.Deleted {
- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("instance %q not found", instanceID))
- }
- if (targetProjectID == nil) != (instance.ProjectID == nil) ||
- targetProjectID != nil && *targetProjectID != *instance.ProjectID {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("database target %q is not canonical for its instance", target))
+ if instance == nil || instance.Deleted || database.ResourceName() != target {
+ return nil, notFound
}
targets = append(targets, &releaseCheckTarget{database: database, name: target})
continue
diff --git a/docs/design/v1-api-audit-2026-08.md b/docs/design/v1-api-audit-2026-08.md
index dc6d66fc91..a17a54e81c 100644
--- a/docs/design/v1-api-audit-2026-08.md
+++ b/docs/design/v1-api-audit-2026-08.md
@@ -11,7 +11,6 @@ where noted. Fixed findings are removed and listed at the end.
| | Problem | Severity |
|---|---|---|
| T12 | Anonymous callers can read your LDAP config | MED |
-| T18c-iii | `CheckRelease` error codes leak existence | MED |
| T18c-iv | `BatchDeleteProjects` checks its permission against the workspace, not the named projects — latent, no predefined role reaches it | LOW |
---
@@ -94,16 +93,6 @@ by anything stated — and nothing in the proto says the batch form needs worksp
still distinguishes any workspace with non-default auth settings. `auth_service.go:107-157`,
`auth_service.go:449` (ID generation)
-### T18c-iii · `CheckRelease` error codes leak existence — MED · ✅ read myself
-
-Point it at a database in someone else's project and you get `InvalidArgument`; point it at one that
-doesn't exist and you get `NotFound`. So permission to check releases on any single project lets you
-map which databases exist workspace-wide. [#21102](https://github.com/bytebase/bytebase/pull/21102)
-added a third distinguishable error that also leaks instance ownership.
-
-**Fix:** return `NotFound` for both, matching the convention `BatchCreateRevisions` already adopted,
-with a regression test. `release_service_check.go:77-110`
-
---
## Structural / AIP (not re-run)
@@ -149,7 +138,7 @@ constraints.
| T19 `UpdateDatabaseCatalog` | The interceptor now reads `catalog.name`, so the permission is checked against the named database's project instead of the workspace — the route resolver already drops the trailing `/catalog`. Strictly additive: workspace holders are unaffected and Project Owner, whose role carries `bb.databaseCatalogs.update`, is no longer denied. Separate and still open: `bb.databaseCatalogs.create` does not exist, so the `allow_missing` secondary check denies every caller. Dead rather than harmful — no UI sets the flag and the RPC is MCP-`EXCLUDED` |
| T11 | `UpdateGroup(allow_missing=true)` now checks `bb.groups.create` itself, the shape `UpdatePlan` and `UpdateUser` already had. The interceptor never covered it: `doIAMPermissionCheck` returns true for every non-IAM auth method, so the `allow_missing` secondary block evaluated to nothing on a CUSTOM RPC, and the create path calls `CreateGroup` in-process, which bypasses the interceptor anyway — while the comment above it claimed both permissions were verified. The exposure was narrower and differently shaped than first written: Workspace Member does hold `bb.groups.create`, but Workspace DBA and every project role do not, so a DBA-only principal could create a group and name itself OWNER, which `checkPermission` then honors for that group. It stops there — a group confers nothing until someone with IAM-policy rights binds a role to it. The interceptor's block is now gated on `AuthMethod == IAM` so it no longer reads as protection where it verifies nothing (behavior-preserving: it already returned true there). Found tracing the same mechanism, and fixed with it: the `.update` → `.create` string rewrite is unvalidated, and `UpdateDatabase` derived `bb.databases.create`, which does not exist — `CheckPermission` never matches an unknown string, so `allow_missing=true` denied every caller including Workspace Admin, on a flag `database_service.go` never read and the proto documented as working. The field is removed and the proto now says never to add it back, since a database is not independently creatable. `TestAllowMissingCreatePermission` walks the descriptors and makes all four silent failure modes a build failure — an RPC that gains the flag with nothing authorizing its create path, a derived permission that does not exist, a declared permission the rewrite leaves unchanged (`bb.settings.set` is one, and vacuous if it ever went IAM), and a nested `allow_missing` sub-request the interceptor's hand-written type switch does not name, which it proves by building the request and asserting `hasAllowMissingEnabled` reads it. Still open, and the other half of the original finding: 15 of the 52 CUSTOM RPCs declare a `permission` annotation the interceptor does not enforce. Fourteen check that same permission by hand, so what is missing is anything binding the two — a handler can drift from its annotation and nothing fails. `SearchMyAccessGrants` has already drifted: it declares `bb.accessGrants.get` and checks nothing, scoping to `Creator == caller` instead |
| T5, T6 | [#21143](https://github.com/bytebase/bytebase/pull/21143) — `sheet_blob_ref` gives sheets per-project ownership; `BatchCreateRevisions` rejects foreign-project provenance without echoing the hash |
-| T7 | [#21102](https://github.com/bytebase/bytebase/pull/21102) — every `CheckRelease` target validated against the parent project before any schema read (its error codes still leak existence — T18c-iii) |
+| T7 | [#21102](https://github.com/bytebase/bytebase/pull/21102) — every `CheckRelease` target validated against the parent project before any schema read (its error codes still leaked existence, closed as T18c-iii) |
| T8 `CreateWorksheet` | [#21169](https://github.com/bytebase/bytebase/pull/21169) — `CreateSavedQuery` is now IAM-enforced; Workspace Member holds no saved-query permission, and new queries start creator-private |
| T12 `GetActuatorInfo` | [#21184](https://github.com/bytebase/bytebase/pull/21184) — anonymous access and the `name` field removed; workspace now comes from the token (the narrower surface that replaced it is T12) |
| T12 email enumeration, mail relay | Two of the four anonymous surfaces; LDAP disclosure and the existence oracle stay open and are what T12 is now. **`Signup`** checks the restriction before it checks existence, so a workspace that refuses every signup — every SaaS workspace, since the override always sets `DisallowSignup` — no longer answers `AlreadyExists` for registered addresses and `PermissionDenied` for the rest. The duplicate is still reported where signup is allowed; only the order moved, and denied duplicates now reach the deferred `SetAuditWorkspaceID` they used to return ahead of. **`SendEmailLoginCode`** caps sign-in-code mail at 1000/hour for the whole deployment, whatever workspace the caller names: SaaS copies `EMAIL_CONFIG` into every workspace it creates, so naming one does not change the sender, and keying on the workspace would hand each tenant its own budget against a shared reputation — with a caller-supplied key besides. The 60s per-recipient cooldown already bounded one address; only a sender-wide cap bounds a campaign, which writes each address exactly once. Claimed before the code row is written, so a refusal leaves a pending code intact, and before the cooldown is consulted, so the answer never depends on whether that recipient has a recent code. Reuses `login_attempt` under a new `EMAIL_CODE_SEND` kind — no migration, `kind` is text — but not its semantics: a lockout resets only after a quiet window, which for a volume budget would turn "1000 per hour" into "1000 ever, until an hour of silence", so this kind reads `last_attempt_at` as the window's start. Accepted: spending the cap delays sign-in codes deployment-wide until the window passes, and one address can spend it as cheaply as many since the cost is the requests — bounded and recoverable, unlike the deliverability damage it prevents. Nothing here varies by recipient: a member exemption, a redeemability gate and a cooldown pre-check were each implemented and removed, because on an endpoint answering anonymous callers any recipient-dependent branch is an oracle |
@@ -166,6 +155,7 @@ constraints.
| T10 | [#21252](https://github.com/bytebase/bytebase/pull/21252) + [#21258](https://github.com/bytebase/bytebase/pull/21258) — password change and MFA lifecycle move off `UpdateUser` onto their own methods, each requiring a `CredentialProof`: current password, live OTP, recovery code, or a Cloud-only emailed re-auth code. Every proof claims a T9 login-attempt slot, so no proof channel is an unbounded guessing oracle, and a factor-touching method refuses the password while a live factor exists. Accepted with it: **the stolen access token still answers until it expires (≤1h)** — credential generation and the fenced transaction were cut or deferred, password change revokes only the account's web refresh tokens (best-effort, OAuth grants untouched), and an MFA change revokes nothing. What this closes is the credential being *spent* on its own replacement, not the session. Design, and the shipped-vs-designed delta: [`reauthenticate-credential-changes.md`](reauthenticate-credential-changes.md) |
| T18b | The etag is now read wherever the caller presents it: `policy.etag` — the only place `GetIamPolicy` returns one, and so the only place a read-modify-write round-trips it — as well as the request field, with two that disagree rejected. Both handlers write through `store.SetIamPolicy`, which compares under `SELECT ... FOR UPDATE` inside the write transaction. Comparing against the handler's own earlier read would not have been enough: that is a check-then-act, and two requests reading the same policy both pass it before either writes. (An earlier revision justified this by replica cache skew, which does not exist: `store.New(ctx, pgURL, !profile.HA)` disables read caching in the only mode that runs more than one process.) The same lock closed two merges that present no etag at all and so could never be compared — `PatchWorkspaceIamPolicy` (signup, SSO provisioning, workspace-leave) and the role-grant issue approval in `backend/utils` — each of which read the policy, merged one member in, and wrote the whole thing back, so either could resurrect a member an admin had just revoked; both now merge inside the locked transaction through `store.PatchIamPolicy`. Fixed with it: workspace `SetIamPolicy` wrote to `request.Resource` while every read and check used the workspace from the token, so a request naming anything else matched no row and returned 200 having written nothing — the write now targets the workspace the reads did, which is what `GetIamPolicy` already does by ignoring the field. The audit delta and the invite emails are now derived from the policy the write actually replaced rather than the pre-validation snapshot, so they describe what happened even for an etag-less caller, and the workspace seat guard counts against that same locked policy through a `ValidateReplaced` hook rather than against a read the write does not hold. Accepted with it: an etag-less caller still gets last-write-wins, which is what AIP-154 optional-etag semantics mean and what existing API clients rely on; and the etag is still `updated_at` in milliseconds, so a write landing in the same millisecond as the one before it leaves the etag unmoved and a stale write racing that pair is accepted — too narrow to justify the wire change to a content hash, unlike the saved-query policy, which has no timestamp to derive one from. Also left as is: `validateIAMPolicy` grandfathers bindings found in the policy the handler read before the write, so an etag-less caller racing a concurrent removal re-adds that binding without the `allUsers`, role-existence, CEL and maximum-expiration checks — pre-existing, and closing it means splitting the function into a fetch half and a pure half that runs under the lock |
| T18c-ii | **The query-history `instance ==` filter matches now.** The CEL translation compared the stored `instances/{id}/databases/{db}` against the caller's `instances/{id}` with `LIKE` and no wildcard, so the documented form returned nothing and the only form that worked was the undocumented `instances/{id}/%`. The value is now validated as an instance name — the wildcard form is `InvalidArgument`, as a malformed `project ==` already was — and translated to an escaped `instances/{id}/databases/%` prefix, so the caller never supplies the pattern — or `projects/{project}/instances/{id}/databases/%` for a project-scoped instance, whose rows carry the project-scoped name; Codex caught on the PR that the first cut only handled the workspace form, so the filter would still have matched nothing for every project-scoped instance. **`statement ==` is plain equality**, which is what `==` means and closes the `%`/`_` over-match that T17's `.contains()` fix left; the proto lists it beside `.contains()` now. Found on the way and fixed with it: every equality literal is type-checked once at the top of the switch, so `type == 1` is an error where it was a panic. `FindQueryHistoryMessage.Instance`, the second copy of the missing wildcard, is deleted rather than fixed — nothing set it. **`ListTaskRuns` is paginated**: `page_size`/`page_token` on the request, `next_page_token` on the response, `parseLimitAndOffset` in the handler and `LIMIT`/`OFFSET` in the store, ordered by `(task_run.project, task_run.id)` — the primary key, so the order is total for the cross-project runner lists as well, which sorted on `id` alone. One deliberate departure from the other lists: an unspecified `page_size` means the 1000 maximum, not 10. The wildcard parent's callers read a whole rollout in one call — the issue and plan pages, and `bytebase-action`'s `cancelRollout`, which finds the runs to cancel that way — and action binaries inside their compatibility window ([`docs/pre-pr-checklist.md`](../../docs/pre-pr-checklist.md) §6) cannot be updated with the server, so a default of 10 would have silently left every run past the tenth uncancelled. Every in-tree caller now follows the token: `listAllTaskRuns` in `frontend/src/api/taskRun.ts` behind the five frontend sites, and the action's own `listAllTaskRuns`. The two token fields join `auditRecordedFields` as ordinary recorded fields, as every other list's do. Tests: the filter SQL at the store level, both filters end to end in `TestListQueryHistories`, `TestListTaskRunsPagination` for the page and order contract at the store, and a `page_size: 1` token walk in `TestBatchCancelTaskRuns_RejectsTaskRunFromAnotherStage`. Accepted with it: a caller past 1000 task runs that ignores `next_page_token` now sees a truncated rollout where it saw everything — the bound is the point. Offset paging still drifts under concurrent inserts, as every list here does |
+| T18c-iii | `CheckRelease` answers `NotFound` with the one `database {target} not found` the missing case already used for a database target that is missing, belongs to another project, sits on an archived instance, or is not the canonical name for its instance, where the four cases returned three distinguishable errors. Only the code and message change: the lookups and their order are as [#21102](https://github.com/bytebase/bytebase/pull/21102) left them, the canonical test reads `database.ResourceName() != target` instead of comparing scopes by hand, and a project-form target naming a different project is still `InvalidArgument`, decided before any read and so confirming nothing. `TestCheckReleaseHidesDatabasesOutsideProject` asserts a foreign database and a missing one come back with byte-identical errors |
**`AIService.Chat` — accepted, not fixed** (2026-08-18). `Chat` requires an authenticated workspace
principal and touches no database or sheet, so the only exposure is LLM spend. On Cloud the feature