Skip to content

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

fix(audit,instance): record denied validate-only calls, keep a keytab off a new destination (#21165)

Vincent Huang7578f203ce84
diff --git a/backend/api/v1/audit.go b/backend/api/v1/audit.go
index 85f84bb177..3baa7c76ee 100644
--- a/backend/api/v1/audit.go
+++ b/backend/api/v1/audit.go
@@ -195,8 +195,27 @@ type auditEntry struct {
}
func (in *AuditInterceptor) createAuditLog(ctx context.Context, e *auditEntry) error {
- // Skip audit logging for validate-only requests.
- if isValidateOnlyRequest(e.request) {
+ // Skip audit logging for validate-only requests that SUCCEEDED. A dry run
+ // that Bytebase accepted changed nothing, so recording it is noise — that
+ // is the whole reason for the skip.
+ //
+ // The outcome is what decides, not the flag. A refused attempt is worth
+ // exactly as much as any other refused attempt, and six request messages
+ // carry validate_only — UpdateDataSource, AddDataSource, CreateInstance,
+ // CreateIdentityProvider, UpdateSetting and CreateDatabaseGroup, every one
+ // of them audited, three of them on methods MCP forbids. Skipping on the
+ // flag alone made setting it a switch that turns off the record of being
+ // caught.
+ //
+ // EVERY failure records, not only a policy denial, and that is deliberate
+ // rather than incidental. The instance form runs a validate-only
+ // connection test before each save and on each Test Connection click, so
+ // the rows this adds are mostly failed connection tests, not refusals —
+ // a real volume change on a common flow. Keying on a denial code instead
+ // would be the same shape of hole this closes: it would record the
+ // refusals that happen to carry that code and silently drop every other
+ // rejected attempt.
+ if e.rerr == nil && isValidateOnlyRequest(e.request) {
return nil
}
diff --git a/backend/api/v1/audit_validate_only_test.go b/backend/api/v1/audit_validate_only_test.go
new file mode 100644
index 0000000000..5c4403615b
--- /dev/null
+++ b/backend/api/v1/audit_validate_only_test.go
@@ -0,0 +1,144 @@
+package v1
+
+import (
+ "context"
+ "encoding/base64"
+ "strings"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/config"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+// TestValidateOnlyAuditSkipAppliesOnlyToSuccess pins the boundary of the
+// validate-only skip in createAuditLog.
+//
+// The skip exists so a dry run — which changes nothing — does not spam the
+// audit log. It said nothing about the outcome, so it also swallowed every
+// FAILED attempt whose request carries validate_only. That handed an agent an
+// unlogged attempt at any forbidden method taking one of those six requests:
+// two identical denials of the same method, in the same session, differing only
+// in that flag, produced one row between them.
+//
+// The three cases below are the whole rule: outcome decides, not the flag
+// alone.
+func TestValidateOnlyAuditSkipAppliesOnlyToSuccess(t *testing.T) {
+ st := newAuditLiveStore(t)
+ in := NewAuditInterceptor(st, "test-secret", &config.Profile{})
+
+ // A retarget with the stored password left to ride along — the shape the
+ // MCP class refuses. The secrets are here so the redaction assertion below
+ // has something to catch.
+ const storedPassword = "stored-db-secret"
+ const storedKeytab = "stored-keytab-bytes"
+ retargetRequest := func(validateOnly bool) *v1pb.UpdateDataSourceRequest {
+ return &v1pb.UpdateDataSourceRequest{
+ Name: "instances/probe",
+ DataSource: &v1pb.DataSource{
+ Id: "admin-ds",
+ Host: "attacker.example.com",
+ Password: storedPassword,
+ SaslConfig: &v1pb.SASLConfig{
+ Mechanism: &v1pb.SASLConfig_KrbConfig{
+ KrbConfig: &v1pb.KerberosConfig{Keytab: []byte(storedKeytab)},
+ },
+ },
+ },
+ ValidateOnly: validateOnly,
+ }
+ }
+
+ invoke := func(t *testing.T, correlationID string, request *v1pb.UpdateDataSourceRequest, rerr error) {
+ t.Helper()
+ authCtx := &common.AuthContext{
+ Audit: true,
+ AuthMethod: common.AuthMethodIAM,
+ Resources: []*common.Resource{{Type: common.ResourceTypeWorkspace, ID: auditTestWorkspace}},
+ DelegatedGrant: &common.DelegatedGrant{CorrelationID: correlationID},
+ }
+ next := func(_ context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {
+ if rerr != nil {
+ return nil, rerr
+ }
+ return connect.NewResponse(&v1pb.Instance{Name: "instances/probe"}), nil
+ }
+ req := &specRequest{
+ AnyRequest: connect.NewRequest(request),
+ procedure: "/bytebase.v1.InstanceService/UpdateDataSource",
+ }
+ _, err := in.WrapUnary(next)(newAuditTestContext(authCtx), req)
+ if rerr == nil {
+ require.NoError(t, err)
+ } else {
+ require.Error(t, err)
+ }
+ }
+
+ t.Run("a denied validate-only call is recorded", func(t *testing.T) {
+ denial := connect.NewError(connect.CodePermissionDenied,
+ errors.New("InstanceService/UpdateDataSource is not available to MCP sessions"))
+ invoke(t, "corr-validate-only-denied", retargetRequest(true), denial)
+
+ rows := findRowsByCorrelation(t, st, "corr-validate-only-denied")
+ require.Len(t, rows, 1,
+ "a refused attempt must be auditable whether or not validate_only was set — "+
+ "otherwise the flag is a switch that turns off the record")
+ require.Equal(t, int32(connect.CodePermissionDenied), rows[0].Payload.GetStatus().GetCode(),
+ "the row must carry the denial, not a blank status")
+
+ // The newly-logged row goes through the same getRequestString
+ // redaction as every other UpdateDataSource row — that is why
+ // narrowing the skip exposes no field the plain path did not already
+ // write. It pins that the path runs, not that redactDataSource covers
+ // every secret: the iam_extension oneof and
+ // authentication_private_key_passphrase are unmasked there today, on
+ // this row and on every UpdateDataSource row that preceded it.
+ request := rows[0].Payload.GetRequest()
+ require.NotEmpty(t, request)
+ require.NotContains(t, request, storedPassword,
+ "the request payload must be redacted before it reaches the audit row")
+ // The row is protojson, which renders a bytes field base64, so the
+ // keytab has to be looked for in that form — searching for the ASCII
+ // literal would pass even with keytab redaction deleted outright.
+ require.NotContains(t, request, base64.StdEncoding.EncodeToString([]byte(storedKeytab)),
+ "the keytab reaches the row base64-encoded, and must be masked before it does")
+ require.Contains(t, request, "attacker.example.com",
+ "the destination is what an operator reads the row for — it must survive redaction")
+ })
+
+ t.Run("a succeeding validate-only call stays silent", func(t *testing.T) {
+ invoke(t, "corr-validate-only-ok", retargetRequest(true), nil)
+
+ require.Empty(t, findRowsByCorrelation(t, st, "corr-validate-only-ok"),
+ "a dry run that succeeded changed nothing — the original reason for the skip")
+ })
+
+ t.Run("a failed validate-only call is recorded, denial or not", func(t *testing.T) {
+ // The rule is any failure, not any refusal, and this is the case that
+ // pins it: a validate-only connection test that could not reach the
+ // host. It is also the bulk of what the change adds, since the
+ // instance form dials before every save.
+ failedDial := connect.NewError(connect.CodeInvalidArgument,
+ errors.New("failed to connect to attacker.example.com: connection refused"))
+ invoke(t, "corr-validate-only-dial-failed", retargetRequest(true), failedDial)
+
+ rows := findRowsByCorrelation(t, st, "corr-validate-only-dial-failed")
+ require.Len(t, rows, 1,
+ "keying on a denial code would drop every other rejected attempt — the hole this change closes")
+ require.Equal(t, int32(connect.CodeInvalidArgument), rows[0].Payload.GetStatus().GetCode())
+ })
+
+ t.Run("a denied ordinary call is recorded", func(t *testing.T) {
+ denial := connect.NewError(connect.CodePermissionDenied, errors.New("denied"))
+ invoke(t, "corr-plain-denied", retargetRequest(false), denial)
+
+ rows := findRowsByCorrelation(t, st, "corr-plain-denied")
+ require.Len(t, rows, 1, "control: the flag is the only difference between this and the first case")
+ require.True(t, strings.Contains(rows[0].Payload.GetMethod(), "UpdateDataSource"))
+ })
+}
diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.go
index 1fae047270..d6ad01da3d 100644
--- a/backend/api/v1/instance_service.go
+++ b/backend/api/v1/instance_service.go
@@ -850,7 +850,9 @@ func (s *InstanceService) UpdateInstance(ctx context.Context, req *connect.Reque
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
- retainStoredKeytabs(dataSources, instance.Metadata.GetDataSources())
+ if err := retainStoredKeytabs(dataSources, instance.Metadata.GetDataSources()); err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
normalizeGCPDataSources(instance.Metadata.GetEngine(), dataSources)
for _, ds := range dataSources {
if err := validateAndSanitizeDataSourceTLS(ds); err != nil {
@@ -1240,6 +1242,21 @@ func (s *InstanceService) UpdateDataSource(ctx context.Context, req *connect.Req
}
}
+ // dataSource points into the cloned metadata and is patched in place below,
+ // so keep the pre-image: keytab retention compares the whole merged result
+ // against it, which the mask loop cannot do while it is still running.
+ storedDataSource := proto.CloneOf(dataSource)
+
+ // Then drop the stored keytab off the value being patched. Only the
+ // sasl_config path writes one, so after the loop a keytab is present iff
+ // THIS request supplied it — which is what retention has to decide on.
+ // Left in place, a mask that never names sasl_config would carry the
+ // stored keytab through untouched and retention would read it as supplied,
+ // letting update_mask=["host"] alone move it to the caller's address.
+ if krb := dataSource.GetSaslConfig().GetKrbConfig(); krb != nil {
+ krb.Keytab = nil
+ }
+
for _, path := range req.Msg.UpdateMask.Paths {
switch path {
case "username":
@@ -1293,9 +1310,7 @@ func (s *InstanceService) UpdateDataSource(ctx context.Context, req *connect.Req
}
dataSource.ExternalSecret = externalSecret
case "sasl_config":
- saslConfig := convertV1DataSourceSaslConfig(req.Msg.DataSource.SaslConfig)
- retainStoredKeytabOnEmptyUpdate(saslConfig, dataSource.SaslConfig)
- dataSource.SaslConfig = saslConfig
+ dataSource.SaslConfig = convertV1DataSourceSaslConfig(req.Msg.DataSource.SaslConfig)
case "authentication_type":
dataSource.AuthenticationType = convertV1AuthenticationType(req.Msg.DataSource.AuthenticationType)
case "additional_addresses":
@@ -1376,6 +1391,13 @@ func (s *InstanceService) UpdateDataSource(ctx context.Context, req *connect.Req
}
}
+ // Run on the merged result, not inside the mask loop: whether the keytab
+ // may be inherited depends on the destination the request ends at, and the
+ // paths that move it can be applied after sasl_config.
+ if err := retainStoredKeytabOnEmptyUpdate(dataSource, storedDataSource); err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
+
clearDataSourceAuthentication(dataSource)
normalizeGCPDataSources(instance.Metadata.GetEngine(), []*storepb.DataSource{dataSource})
if err := validateAndSanitizeDataSourceTLS(dataSource); err != nil {
diff --git a/backend/api/v1/instance_service_converter.go b/backend/api/v1/instance_service_converter.go
index 72d02ca288..69307db2f2 100644
--- a/backend/api/v1/instance_service_converter.go
+++ b/backend/api/v1/instance_service_converter.go
@@ -6,6 +6,7 @@ import (
"connectrpc.com/connect"
"github.com/pkg/errors"
+ "google.golang.org/protobuf/proto"
"github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -451,32 +452,109 @@ func convertDataSourceSaslConfig(saslConfig *storepb.SASLConfig) *v1pb.SASLConfi
return storeSaslConfig
}
+// dataSourceDestination projects the fields through which a caller supplies an
+// address that the data source's own connection, or the keytab itself,
+// is made to. Two data sources with equal projections reach the same
+// caller-named endpoints.
+//
+// Both halves of that rule carry weight. external_secret.url is a
+// caller-supplied address Bytebase does dial (component/secret/vault.go), and
+// it is still out, because what travels there is the fetch of a password — the
+// keytab never does. A guard for the password would have to include it; this
+// one does not.
+//
+// In. host and port, plus each additional_addresses entry, are the data
+// source's own endpoints. ssh_host and ssh_port are the tunnel every byte
+// transits when it is set (plugin/db/util/ssh.go dials that pair). The
+// krb_config kdc_host and kdc_port are where kinit presents the keytab itself
+// (plugin/db/util/sasl.go writes them into krb5.conf), and that is the only
+// peer the keytab material reaches — the database server gets a ticket derived
+// from it, not the keytab. extra_connection_parameters is spliced verbatim
+// into the connection string the driver then parses, and both parsers take the
+// last key they read, so a host entry there overrides the host field on
+// PostgreSQL (plugin/db/pg/pg.go) and the server on SQL Server
+// (plugin/db/mssql/mssql.go).
+//
+// Out, and the line is one rule rather than a list of exceptions: a field is
+// out when the new endpoint comes from somewhere other than the caller.
+// direct_connection, replica_set, master_name and redis_type follow peers the
+// operator's own server advertises. srv resolves the operator's own hostname
+// through the operator's DNS. cloud_sql_ip_type and authentication_type pick
+// among the addresses Google resolves for an instance the operator named.
+// Reaching a host of the caller's choosing through any of them means moving
+// host or additional_addresses first, and those are in. Out for a second
+// reason — no endpoint at all — are database, authentication_database, sid,
+// service_name and warehouse_id, which name a target inside a server already
+// reached; region and project_id/instance_id, which select which cloud API
+// serves while host/port stay the dialed endpoint; and krb_config's primary,
+// instance and realm, which choose the principal kinit claims rather than
+// where it sends the claim, with kdc_transport_protocol reaching the same
+// kdc_host:kdc_port either way.
+func dataSourceDestination(ds *storepb.DataSource) *storepb.DataSource {
+ krb := ds.GetSaslConfig().GetKrbConfig()
+ return &storepb.DataSource{
+ Host: ds.GetHost(),
+ Port: ds.GetPort(),
+ AdditionalAddresses: ds.GetAdditionalAddresses(),
+ SshHost: ds.GetSshHost(),
+ SshPort: ds.GetSshPort(),
+ ExtraConnectionParameters: ds.GetExtraConnectionParameters(),
+ SaslConfig: &storepb.SASLConfig{
+ Mechanism: &storepb.SASLConfig_KrbConfig{
+ KrbConfig: &storepb.KerberosConfig{
+ KdcHost: krb.GetKdcHost(),
+ KdcPort: krb.GetKdcPort(),
+ },
+ },
+ },
+ }
+}
+
// retainStoredKeytabOnEmptyUpdate keeps the stored keytab when an update
// carries an empty one. The keytab is INPUT_ONLY — reads return it blank — so
// a read-modify-write client would otherwise wipe it on every update.
-func retainStoredKeytabOnEmptyUpdate(updated, stored *storepb.SASLConfig) {
- updatedKrb := updated.GetKrbConfig()
+//
+// It will not carry the keytab to a new destination. Retention exists to stop
+// a client from losing a credential it already holds, and an update that moves
+// where the data source connects is not that client: inheriting there would
+// hand the keytab to a host the caller picked, and among the data source's
+// secrets the keytab is the one that survives a wholesale replacement, so it
+// is the one worth moving. The caller has to supply it again, which is proof
+// they hold it.
+func retainStoredKeytabOnEmptyUpdate(updated, stored *storepb.DataSource) error {
+ updatedKrb := updated.GetSaslConfig().GetKrbConfig()
if updatedKrb == nil || len(updatedKrb.Keytab) > 0 {
- return
+ return nil
}
- if storedKrb := stored.GetKrbConfig(); storedKrb != nil {
- updatedKrb.Keytab = storedKrb.Keytab
+ storedKrb := stored.GetSaslConfig().GetKrbConfig()
+ if len(storedKrb.GetKeytab()) == 0 {
+ return nil
}
+ if !proto.Equal(dataSourceDestination(updated), dataSourceDestination(stored)) {
+ return errors.Errorf("data source %q connects somewhere new, so its Kerberos keytab must be supplied again", updated.GetId())
+ }
+ updatedKrb.Keytab = storedKrb.Keytab
+ return nil
}
// retainStoredKeytabs applies retainStoredKeytabOnEmptyUpdate across a full
// data source replacement (UpdateInstance with update_mask=data_sources),
// matching stored data sources by ID.
-func retainStoredKeytabs(updated, stored []*storepb.DataSource) {
+func retainStoredKeytabs(updated, stored []*storepb.DataSource) error {
storedByID := make(map[string]*storepb.DataSource, len(stored))
for _, ds := range stored {
storedByID[ds.GetId()] = ds
}
for _, ds := range updated {
- if existing, ok := storedByID[ds.GetId()]; ok {
- retainStoredKeytabOnEmptyUpdate(ds.GetSaslConfig(), existing.GetSaslConfig())
+ existing, ok := storedByID[ds.GetId()]
+ if !ok {
+ continue
+ }
+ if err := retainStoredKeytabOnEmptyUpdate(ds, existing); err != nil {
+ return err
}
}
+ return nil
}
func convertDataSourceAddresses(addresses []*storepb.DataSource_Address) []*v1pb.DataSource_Address {
diff --git a/backend/api/v1/instance_service_converter_test.go b/backend/api/v1/instance_service_converter_test.go
index f3c601d208..a0a0689776 100644
--- a/backend/api/v1/instance_service_converter_test.go
+++ b/backend/api/v1/instance_service_converter_test.go
@@ -181,73 +181,265 @@ func TestConvertDataSourceSaslConfigNeverReturnsKeytab(t *testing.T) {
require.Equal(t, "tcp", krb.KdcTransportProtocol)
}
-func TestRetainStoredKeytabOnEmptyUpdate(t *testing.T) {
- stored := &storepb.SASLConfig{
- Mechanism: &storepb.SASLConfig_KrbConfig{
- KrbConfig: &storepb.KerberosConfig{Keytab: []byte("stored-keytab")},
+// krbDataSource builds a data source at the given destination, carrying a
+// Kerberos config with the given keytab.
+func krbDataSource(id, host, keytab string) *storepb.DataSource {
+ return &storepb.DataSource{
+ Id: id,
+ Host: host,
+ Port: "10000",
+ SaslConfig: &storepb.SASLConfig{
+ Mechanism: &storepb.SASLConfig_KrbConfig{
+ KrbConfig: &storepb.KerberosConfig{
+ Primary: "hive",
+ Realm: "EXAMPLE.COM",
+ Keytab: []byte(keytab),
+ KdcHost: "kdc.example.com",
+ KdcPort: "88",
+ },
+ },
},
}
+}
+
+func TestRetainStoredKeytabOnEmptyUpdate(t *testing.T) {
+ const storedHost = "hive.internal.example.com"
+ stored := krbDataSource("admin", storedHost, "stored-keytab")
// An empty keytab on update keeps the stored one; other fields still apply.
- updated := &storepb.SASLConfig{
- Mechanism: &storepb.SASLConfig_KrbConfig{
- KrbConfig: &storepb.KerberosConfig{Realm: "NEW.COM"},
- },
- }
- retainStoredKeytabOnEmptyUpdate(updated, stored)
- require.Equal(t, []byte("stored-keytab"), updated.GetKrbConfig().Keytab)
- require.Equal(t, "NEW.COM", updated.GetKrbConfig().Realm)
+ updated := krbDataSource("admin", storedHost, "")
+ updated.GetSaslConfig().GetKrbConfig().Realm = "NEW.COM"
+ require.NoError(t, retainStoredKeytabOnEmptyUpdate(updated, stored))
+ require.Equal(t, []byte("stored-keytab"), updated.GetSaslConfig().GetKrbConfig().Keytab)
+ require.Equal(t, "NEW.COM", updated.GetSaslConfig().GetKrbConfig().Realm,
+ "the principal a keytab claims is not where it is sent — it must stay updatable")
// A newly uploaded keytab replaces the stored one.
- updated = &storepb.SASLConfig{
- Mechanism: &storepb.SASLConfig_KrbConfig{
- KrbConfig: &storepb.KerberosConfig{Keytab: []byte("new-keytab")},
- },
- }
- retainStoredKeytabOnEmptyUpdate(updated, stored)
- require.Equal(t, []byte("new-keytab"), updated.GetKrbConfig().Keytab)
+ updated = krbDataSource("admin", storedHost, "new-keytab")
+ require.NoError(t, retainStoredKeytabOnEmptyUpdate(updated, stored))
+ require.Equal(t, []byte("new-keytab"), updated.GetSaslConfig().GetKrbConfig().Keytab)
// Nothing stored: the empty keytab stays empty.
- updated = &storepb.SASLConfig{
- Mechanism: &storepb.SASLConfig_KrbConfig{
- KrbConfig: &storepb.KerberosConfig{},
+ updated = krbDataSource("admin", storedHost, "")
+ require.NoError(t, retainStoredKeytabOnEmptyUpdate(updated, krbDataSource("admin", storedHost, "")))
+ require.Empty(t, updated.GetSaslConfig().GetKrbConfig().Keytab)
+
+ // Clearing the whole SASL config is a no-op for retention.
+ require.NoError(t, retainStoredKeytabOnEmptyUpdate(&storepb.DataSource{Id: "admin"}, stored))
+}
+
+// TestRetainStoredKeytabRefusesANewDestination is the guard: a keytab is
+// inherited to keep a read-modify-write client from wiping it, never to carry
+// it somewhere the caller chose. Each case moves exactly one destination field
+// and leaves the keytab out.
+func TestRetainStoredKeytabRefusesANewDestination(t *testing.T) {
+ const storedHost = "hive.internal.example.com"
+
+ moved := map[string]func(ds *storepb.DataSource){
+ "host": func(ds *storepb.DataSource) { ds.Host = "attacker.example.com" },
+ "port": func(ds *storepb.DataSource) { ds.Port = "10001" },
+ "additional_addresses": func(ds *storepb.DataSource) {
+ ds.AdditionalAddresses = []*storepb.DataSource_Address{{Host: "attacker.example.com", Port: "10000"}}
+ },
+ "ssh_host": func(ds *storepb.DataSource) { ds.SshHost = "attacker.example.com" },
+ "ssh_port": func(ds *storepb.DataSource) { ds.SshPort = "2222" },
+ // Compared wholesale rather than by address-bearing key: the key
+ // names differ per driver, and a name this code does not know would
+ // be a hole. Over-refusing costs nothing — Hive, the only engine that
+ // reads a keytab, does not read this map at all.
+ "extra_connection_parameters": func(ds *storepb.DataSource) {
+ ds.ExtraConnectionParameters = map[string]string{"host": "attacker.example.com"}
+ },
+ "sasl_config.kdc_host": func(ds *storepb.DataSource) {
+ ds.GetSaslConfig().GetKrbConfig().KdcHost = "kdc.attacker.example.com"
+ },
+ "sasl_config.kdc_port": func(ds *storepb.DataSource) {
+ ds.GetSaslConfig().GetKrbConfig().KdcPort = "8888"
},
}
- retainStoredKeytabOnEmptyUpdate(updated, nil)
- require.Empty(t, updated.GetKrbConfig().Keytab)
- // Clearing the whole SASL config is a no-op for retention.
- retainStoredKeytabOnEmptyUpdate(nil, stored)
+ for field, move := range moved {
+ t.Run(field+" moved, keytab omitted", func(t *testing.T) {
+ stored := krbDataSource("admin", storedHost, "stored-keytab")
+ updated := krbDataSource("admin", storedHost, "")
+ move(updated)
+
+ err := retainStoredKeytabOnEmptyUpdate(updated, stored)
+ require.Error(t, err, "moving %s must not carry the stored keytab along", field)
+ require.Contains(t, err.Error(), "keytab")
+ require.Empty(t, updated.GetSaslConfig().GetKrbConfig().Keytab,
+ "the keytab must not reach the new destination")
+ })
+
+ t.Run(field+" moved, keytab re-supplied", func(t *testing.T) {
+ stored := krbDataSource("admin", storedHost, "stored-keytab")
+ updated := krbDataSource("admin", storedHost, "re-supplied-keytab")
+ move(updated)
+
+ require.NoError(t, retainStoredKeytabOnEmptyUpdate(updated, stored),
+ "re-supplying the keytab is what the guard asks for; %s may then move", field)
+ require.Equal(t, []byte("re-supplied-keytab"), updated.GetSaslConfig().GetKrbConfig().Keytab)
+ })
+ }
+
+ // Fields the caller cannot name an address through keep inheriting. Some
+ // of them do move the peer — a replica set follows what the operator's own
+ // server advertises, srv resolves the operator's own hostname through the
+ // operator's DNS, cloud_sql_ip_type picks among the addresses Google
+ // resolves for the instance already named — but none of them lets the
+ // caller choose where it lands, and treating them as a move would fire the
+ // guard on ordinary edits.
+ kept := map[string]func(ds *storepb.DataSource){
+ "username": func(ds *storepb.DataSource) { ds.Username = "someone-else" },
+ "database": func(ds *storepb.DataSource) { ds.Database = "other" },
+ "srv": func(ds *storepb.DataSource) { ds.Srv = true },
+ "replica_set": func(ds *storepb.DataSource) { ds.ReplicaSet = "rs1" },
+ "direct_connection": func(ds *storepb.DataSource) { ds.DirectConnection = true },
+ "region": func(ds *storepb.DataSource) { ds.Region = "us-east-1" },
+ "cloud_sql_ip_type": func(ds *storepb.DataSource) { ds.CloudSqlIpType = storepb.DataSource_PRIVATE },
+ "authentication_type": func(ds *storepb.DataSource) { ds.AuthenticationType = storepb.DataSource_AWS_RDS_IAM },
+ "sasl_config.realm": func(ds *storepb.DataSource) { ds.GetSaslConfig().GetKrbConfig().Realm = "OTHER.COM" },
+ "sasl_config.kdc_transport": func(ds *storepb.DataSource) { ds.GetSaslConfig().GetKrbConfig().KdcTransportProtocol = "tcp" },
+ "sasl_config.primary": func(ds *storepb.DataSource) { ds.GetSaslConfig().GetKrbConfig().Primary = "impala" },
+ "verify_tls_certificate": func(ds *storepb.DataSource) { ds.VerifyTlsCertificate = true },
+ "authentication_private_key": func(ds *storepb.DataSource) { ds.AuthenticationPrivateKey = "pem" },
+ }
+
+ for field, edit := range kept {
+ t.Run(field+" edited, keytab still inherited", func(t *testing.T) {
+ stored := krbDataSource("admin", storedHost, "stored-keytab")
+ updated := krbDataSource("admin", storedHost, "")
+ edit(updated)
+
+ require.NoError(t, retainStoredKeytabOnEmptyUpdate(updated, stored))
+ require.Equal(t, []byte("stored-keytab"), updated.GetSaslConfig().GetKrbConfig().Keytab,
+ "editing %s connects nowhere new, so a read-modify-write client must not be forced to re-upload", field)
+ })
+ }
}
-func TestRetainStoredKeytabs(t *testing.T) {
- krbDS := func(id string, keytab []byte) *storepb.DataSource {
- return &storepb.DataSource{
- Id: id,
- SaslConfig: &storepb.SASLConfig{
- Mechanism: &storepb.SASLConfig_KrbConfig{
- KrbConfig: &storepb.KerberosConfig{Keytab: keytab},
- },
- },
+// TestDataSourceDestinationClassifiesEveryField forces a decision on every
+// DataSource field. dataSourceDestination is a projection, so a field added
+// later is silently treated as "not a destination" — and if that field carries
+// an address, the keytab guard stops seeing the move. This fails until the new
+// field is named in one list or the other, which is the point: the choice gets
+// made by whoever adds it rather than defaulted.
+func TestDataSourceDestinationClassifiesEveryField(t *testing.T) {
+ // Fields the caller supplies an address through. Keep in step with
+ // dataSourceDestination.
+ inDestination := []string{
+ "host", "port", "additional_addresses",
+ "ssh_host", "ssh_port",
+ "extra_connection_parameters",
+ "sasl_config", // krb_config.kdc_host / kdc_port; see the projection
+ }
+ // Everything else, with the reason recorded beside it in
+ // dataSourceDestination's doc comment.
+ notDestination := []string{
+ "id", "type", "username", "password", "obfuscated_password",
+ "use_ssl", "verify_tls_certificate",
+ "ssl_ca", "obfuscated_ssl_ca", "ssl_cert", "obfuscated_ssl_cert",
+ "ssl_key", "obfuscated_ssl_key",
+ "ssl_ca_path", "obfuscated_ssl_ca_path",
+ "ssl_cert_path", "obfuscated_ssl_cert_path",
+ "ssl_key_path", "obfuscated_ssl_key_path",
+ "database", "srv", "authentication_database", "replica_set",
+ "sid", "service_name",
+ "ssh_user", "ssh_password", "obfuscated_ssh_password",
+ "ssh_private_key", "obfuscated_ssh_private_key",
+ "authentication_private_key", "obfuscated_authentication_private_key",
+ "authentication_private_key_passphrase", "obfuscated_authentication_private_key_passphrase",
+ "external_secret", "authentication_type", "cloud_sql_ip_type",
+ "azure_credential", "aws_credential", "gcp_credential",
+ "direct_connection", "region", "warehouse_id",
+ "master_name", "master_username", "master_password", "obfuscated_master_password",
+ "redis_type", "project_id", "instance_id",
+ }
+
+ classified := make(map[string]bool, len(inDestination)+len(notDestination))
+ for _, name := range append(append([]string{}, inDestination...), notDestination...) {
+ require.False(t, classified[name], "field %q listed twice", name)
+ classified[name] = true
+ }
+
+ fields := (&storepb.DataSource{}).ProtoReflect().Descriptor().Fields()
+ var unclassified []string
+ for i := 0; i < fields.Len(); i++ {
+ name := string(fields.Get(i).Name())
+ if !classified[name] {
+ unclassified = append(unclassified, name)
}
+ delete(classified, name)
+ }
+ require.Empty(t, unclassified,
+ "new DataSource field(s) %v: decide whether a caller supplies an address through them. "+
+ "If so, add them to dataSourceDestination — otherwise a keytab will follow them to a new host. "+
+ "If not, record the reason in its doc comment and list them here.", unclassified)
+ require.Empty(t, classified, "field(s) listed here no longer exist on DataSource: %v", classified)
+
+ // sasl_config is the one field the projection picks apart rather than
+ // copying whole, so the walk has to go a level down with it. Otherwise a
+ // new address on KerberosConfig defaults to "not a destination" at exactly
+ // the message holding the endpoint the keytab itself reaches, and this
+ // test stays green because "sasl_config" is already listed above.
+ krbClassified := map[string]bool{
+ // In the projection.
+ "kdc_host": true, "kdc_port": true,
+ // Out: the principal kinit claims, the transport to the same KDC, and
+ // the secret itself.
+ "primary": true, "instance": true, "realm": true,
+ "keytab": true, "kdc_transport_protocol": true,
+ }
+ krbFields := (&storepb.KerberosConfig{}).ProtoReflect().Descriptor().Fields()
+ for i := 0; i < krbFields.Len(); i++ {
+ name := string(krbFields.Get(i).Name())
+ require.True(t, krbClassified[name],
+ "new KerberosConfig field %q: decide whether it names an endpoint the keytab reaches, "+
+ "and add it to dataSourceDestination if so", name)
+ delete(krbClassified, name)
}
+ require.Empty(t, krbClassified, "field(s) listed here no longer exist on KerberosConfig: %v", krbClassified)
+
+ // A second SASL mechanism would carry its own endpoint, and the projection
+ // reads only krb_config.
+ saslOneofs := (&storepb.SASLConfig{}).ProtoReflect().Descriptor().Oneofs()
+ require.Equal(t, 1, saslOneofs.Len())
+ require.Equal(t, 1, saslOneofs.Get(0).Fields().Len(),
+ "a new SASL mechanism needs its endpoint fields added to dataSourceDestination")
+}
+
+func TestRetainStoredKeytabs(t *testing.T) {
+ const storedHost = "hive.internal.example.com"
stored := []*storepb.DataSource{
- krbDS("admin", []byte("admin-keytab")),
- krbDS("ro", []byte("ro-keytab")),
+ krbDataSource("admin", storedHost, "admin-keytab"),
+ krbDataSource("ro", storedHost, "ro-keytab"),
}
updated := []*storepb.DataSource{
- krbDS("admin", nil), // unchanged on read-modify-write
- krbDS("ro", []byte("new-ro-keytab")), // freshly uploaded
- krbDS("added", nil), // new data source, nothing stored
- {Id: "plain"}, // no SASL config at all
+ krbDataSource("admin", storedHost, ""), // unchanged on read-modify-write
+ krbDataSource("ro", storedHost, "new-ro-keytab"), // freshly uploaded
+ krbDataSource("added", "new.example.com", ""), // new data source, nothing stored
+ {Id: "plain", Host: storedHost}, // no SASL config at all
}
- retainStoredKeytabs(updated, stored)
+ require.NoError(t, retainStoredKeytabs(updated, stored))
require.Equal(t, []byte("admin-keytab"), updated[0].GetSaslConfig().GetKrbConfig().Keytab)
require.Equal(t, []byte("new-ro-keytab"), updated[1].GetSaslConfig().GetKrbConfig().Keytab)
require.Empty(t, updated[2].GetSaslConfig().GetKrbConfig().Keytab)
require.Nil(t, updated[3].GetSaslConfig())
+
+ // A full replacement that moves one data source is refused whole. The
+ // wholesale rebuild is exactly where a read-modify-write client sends every
+ // keytab back empty, so this is the path the inheritance was built for and
+ // the path a retarget rides.
+ moved := []*storepb.DataSource{
+ krbDataSource("admin", storedHost, ""),
+ krbDataSource("ro", "attacker.example.com", ""),
+ }
+ err := retainStoredKeytabs(moved, stored)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), `"ro"`, "the error must name the data source the caller has to fix")
+ require.Empty(t, moved[1].GetSaslConfig().GetKrbConfig().Keytab)
}
// assertNoInputOnlyValues walks every populated message field and requires
diff --git a/backend/api/v1/mcp_forbidden.go b/backend/api/v1/mcp_forbidden.go
index d5b96d0988..3456040347 100644
--- a/backend/api/v1/mcp_forbidden.go
+++ b/backend/api/v1/mcp_forbidden.go
@@ -89,12 +89,21 @@ var mcpForbiddenReasons = map[v1pb.MCPForbiddenReason]string{
// Its siblings are NOT here and the line is severity, not tidiness:
// UpdateInstance and BatchUpdateInstances rebuild the data-source list
// wholesale, so every secret is wiped unless resent — except the Kerberos
- // keytab, which retainStoredKeytabs inherits by data-source ID. That is a
- // narrower, persist-only version of the same vector, and it is filed
- // rather than swept in with instance management, which no one has yet
- // decided an agent should lose. AddDataSource and CreateInstance also dial
- // on validate_only but build the data source entirely from the request, so
- // they carry no stored secret and are not this class. BOT-57.
+ // keytab, which retainStoredKeytabs used to inherit by data-source ID.
+ // That narrower, persist-only version of the vector is now closed at the
+ // retention rule instead of at reachability: a keytab is not inherited to
+ // a destination the caller moved (instance_service_converter.go). It costs
+ // an agent no instance management, something no one has yet decided it
+ // should lose, and it binds human callers too — a Kerberos host edit now
+ // asks for the keytab again, on the console as much as on the API.
+ // The keytab is the ONLY secret that rule reaches, because it is the only
+ // one those two methods inherit. On UpdateDataSource above, every other
+ // stored secret still rides an update_mask that names only a destination,
+ // which is why that method is refused here rather than fixed there:
+ // requiring a password re-supplied on every host edit is a product call.
+ // AddDataSource and CreateInstance also dial on validate_only but build
+ // the data source entirely from the request, so they carry no stored
+ // secret and are not this class. BOT-57.
//
// The Undelete* family (user, service account, workload identity) is
// deliberately NOT in this group, and it is the nearest thing left out, so
@@ -142,7 +151,7 @@ const reasonForbiddenClass = "it is not reachable by an AI agent session"
//
// Sitting inside audit gets the denial a row for most of the annotated
// FORBIDDEN methods, but not all, and the exceptions are worth knowing because
-// none of them is visible from the annotations alone. Three mechanisms:
+// none of them is visible from the annotations alone. Two mechanisms remain:
//
// - No audit annotation, so needAudit refuses the row outright:
// SwitchWorkspace, Refresh, TestIdentityProvider, TestEmailSetting.
@@ -157,29 +166,25 @@ const reasonForbiddenClass = "it is not reachable by an AI agent session"
// runs and no parent is ever set. #21162 gave the first two the audit
// annotation; it did not give them rows.
//
-// - Annotated, audited, and not carved out, but the CALLER opted out per
-// request: createAuditLog returns on its first statement for anything whose
-// validate_only field is set, before it considers the denial at all.
-// Unlike the two above this is not a fixed set of methods — it is any
-// FORBIDDEN method whose request carries the field, today
-// CreateIdentityProvider, UpdateSetting and UpdateDataSource. The skip is
-// right for a permitted call, which changed nothing worth recording, and
-// backwards for a refused one; worse, validate_only is the variant that
-// leaves no other trace, because it dials the caller's host and persists
-// nothing.
+// A third way is CLOSED and kept here because it is the one a reader would
+// otherwise rediscover: createAuditLog used to return on its first statement
+// for anything whose validate_only field is set, before it considered the
+// denial at all. That silenced any FORBIDDEN method whose request carries the
+// field — CreateIdentityProvider, UpdateSetting and UpdateDataSource — and
+// validate_only is the variant that leaves no other trace, since it dials the
+// caller's host and persists nothing. The skip now applies only when the call
+// SUCCEEDED (audit.go), so a denial always records.
//
// The first group is 1b-2's typed policy-denial record. The second needs that
// too, or the audit path to accept the delegated credential's workspace, which
-// the internal chain has already verified. The third needs policy denials
-// exempted from the validate-only skip (BOT-57).
-// TestMCPResetFlowDenialsAreSilent pins the second and
-// TestMCPCannotRetargetADataSource pins the third — as an A/B on one flag, two
-// identical denials of one method, only one of them auditable — so the next
-// person to add an annotation learns it is not enough from a red test rather
-// than from an operator asking where the row went. The ones that sting are
-// TestIdentityProvider and TestEmailSetting, and the validate-only retarget:
-// each would carry a stored secret to an address the agent chose, and their
-// denials are the rows an operator would most want.
+// the internal chain has already verified.
+// TestMCPResetFlowDenialsAreSilent pins the second, so the next person to add
+// an annotation learns it is not enough from a red test rather than from an
+// operator asking where the row went; TestMCPCannotRetargetADataSource now
+// asserts the closed third, as an A/B on one flag — two identical denials of
+// one method, both auditable. The ones that sting are TestIdentityProvider and
+// TestEmailSetting: each would carry a stored secret to an address the agent
+// chose, and their denials are the rows an operator would most want.
func NewInternalMCPForbiddenInterceptor() connect.Interceptor {
return connect.UnaryInterceptorFunc(func(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
diff --git a/backend/tests/instance_keytab_retention_test.go b/backend/tests/instance_keytab_retention_test.go
new file mode 100644
index 0000000000..0a3696fa80
--- /dev/null
+++ b/backend/tests/instance_keytab_retention_test.go
@@ -0,0 +1,248 @@
+package tests
+
+import (
+ "context"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/fieldmaskpb"
+
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+const (
+ keytabRetentionHost = "hive.internal.example.com"
+ keytabRetentionID = "admin-ds"
+)
+
+// krbDataSource builds a Kerberos data source pointing at host. An empty
+// keytab is what a read-modify-write client sends back, since the field is
+// INPUT_ONLY and reads return it blank.
+func krbDataSource(host, keytab string) *v1pb.DataSource {
+ return &v1pb.DataSource{
+ Id: keytabRetentionID,
+ Type: v1pb.DataSourceType_ADMIN,
+ Username: "bytebase",
+ Host: host,
+ Port: "10000",
+ SaslConfig: &v1pb.SASLConfig{
+ Mechanism: &v1pb.SASLConfig_KrbConfig{
+ KrbConfig: &v1pb.KerberosConfig{
+ Primary: "hive",
+ Realm: "EXAMPLE.COM",
+ Keytab: []byte(keytab),
+ KdcHost: "kdc.example.com",
+ KdcPort: "88",
+ },
+ },
+ },
+ }
+}
+
+// createKeytabInstance stands up a Hive instance whose data source carries a
+// keytab. Nothing here dials: CreateInstance connects only when validate_only
+// is set, so a fabricated host is enough to give a retarget something to
+// inherit.
+func createKeytabInstance(ctx context.Context, t *testing.T, ctl *controller, instanceID string) *v1pb.Instance {
+ t.Helper()
+ resp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{
+ InstanceId: instanceID,
+ Instance: &v1pb.Instance{
+ Title: instanceID,
+ Engine: v1pb.Engine_HIVE,
+ Environment: new("environments/prod"),
+ DataSources: []*v1pb.DataSource{krbDataSource(keytabRetentionHost, "stored-keytab")},
+ },
+ }))
+ require.NoError(t, err, "precondition: an instance whose stored keytab a retarget could inherit")
+ return resp.Msg
+}
+
+// TestKeytabIsNotInheritedByANewDestination pins the retention rule on the
+// live paths. A keytab survives an update that omits it — the field is
+// INPUT_ONLY, so every read-modify-write client omits it — but it does not
+// travel: an update that moves where the data source connects has to supply it
+// again.
+//
+// Both paths that inherit are here. UpdateDataSource merges a partial request
+// onto the stored data source; UpdateInstance with update_mask=data_sources
+// replaces the list wholesale and matches by data source ID. Before the guard,
+// each of the four moving updates below succeeded and the keytab arrived at
+// the caller's host.
+func TestKeytabIsNotInheritedByANewDestination(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ // Not defer: the parallel subtests below outlive this function body, and a
+ // Cleanup runs only once they are all done.
+ t.Cleanup(func() { ctl.Close(ctx) })
+
+ t.Run("UpdateDataSource", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ instance := createKeytabInstance(ctx, t, ctl, "keytab-datasource")
+
+ // The destination stands still, so retention works as before: the
+ // client edits the realm, omits the keytab, and keeps it.
+ sameDestination := krbDataSource(keytabRetentionHost, "")
+ sameDestination.SaslConfig.GetKrbConfig().Realm = "OTHER.COM"
+ _, err := ctl.instanceServiceClient.UpdateDataSource(ctx, connect.NewRequest(&v1pb.UpdateDataSourceRequest{
+ Name: instance.Name,
+ DataSource: sameDestination,
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"sasl_config"}},
+ }))
+ a.NoError(err, "an update that connects nowhere new must still inherit the stored keytab")
+
+ // The move. update_mask names the host and the sasl_config that omits
+ // the keytab — the read-modify-write shape, one destination field apart.
+ _, err = ctl.instanceServiceClient.UpdateDataSource(ctx, connect.NewRequest(&v1pb.UpdateDataSourceRequest{
+ Name: instance.Name,
+ DataSource: krbDataSource("attacker.example.com", ""),
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"host", "sasl_config"}},
+ }))
+ a.Error(err, "the stored keytab must not follow the data source to a host the caller named")
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
+ a.Contains(err.Error(), "keytab")
+
+ // The same move naming ONLY the destination — the shortest version, and
+ // the one TestMCPCannotRetargetADataSource sends. The handler patches
+ // the stored data source in place, so a mask that never mentions
+ // sasl_config leaves the stored keytab sitting on the merged result.
+ // Deciding retention on that value would read a stored keytab as a
+ // supplied one and let the move through, so what the REQUEST carried
+ // is what has to decide.
+ destinationOnly := map[string]*v1pb.DataSource{
+ "host": {Id: keytabRetentionID, Host: "attacker.example.com"},
+ "port": {Id: keytabRetentionID, Port: "10001"},
+ "ssh_host": {Id: keytabRetentionID, SshHost: "tunnel.attacker.example.com"},
+ "ssh_port": {Id: keytabRetentionID, SshPort: "2222"},
+ "additional_addresses": {
+ Id: keytabRetentionID,
+ AdditionalAddresses: []*v1pb.DataSource_Address{{Host: "attacker.example.com", Port: "10000"}},
+ },
+ "extra_connection_parameters": {
+ Id: keytabRetentionID,
+ ExtraConnectionParameters: map[string]string{"host": "attacker.example.com"},
+ },
+ }
+ for path, moved := range destinationOnly {
+ _, err = ctl.instanceServiceClient.UpdateDataSource(ctx, connect.NewRequest(&v1pb.UpdateDataSourceRequest{
+ Name: instance.Name,
+ DataSource: moved,
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{path}},
+ }))
+ a.Error(err, "update_mask=[%q] alone must not carry the stored keytab to the new destination", path)
+ a.Contains(err.Error(), "keytab")
+ }
+
+ // The mask order must not decide the outcome: sasl_config is applied
+ // before host here, so a check inside the mask loop would see the old
+ // destination and inherit.
+ _, err = ctl.instanceServiceClient.UpdateDataSource(ctx, connect.NewRequest(&v1pb.UpdateDataSourceRequest{
+ Name: instance.Name,
+ DataSource: krbDataSource("attacker.example.com", ""),
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"sasl_config", "host"}},
+ }))
+ a.Error(err, "the destination is whatever the request ends at, not what the mask reached first")
+ a.Contains(err.Error(), "keytab")
+
+ after, err := ctl.instanceServiceClient.GetInstance(ctx, connect.NewRequest(&v1pb.GetInstanceRequest{
+ Name: instance.Name,
+ }))
+ a.NoError(err)
+ a.Len(after.Msg.DataSources, 1)
+ a.Equal(keytabRetentionHost, after.Msg.DataSources[0].Host,
+ "a refused move must leave the data source where the operator put it")
+
+ // An update that names neither the destination nor sasl_config must
+ // leave the keytab alone. The handler blanks it before the mask loop
+ // so that only a supplied one counts, and retention has to put it back
+ // — otherwise editing a username would quietly wipe the credential.
+ _, err = ctl.instanceServiceClient.UpdateDataSource(ctx, connect.NewRequest(&v1pb.UpdateDataSourceRequest{
+ Name: instance.Name,
+ DataSource: &v1pb.DataSource{Id: keytabRetentionID, Username: "someone-else"},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"username"}},
+ }))
+ a.NoError(err, "an unrelated edit must not need the keytab")
+
+ // The keytab is still there: the guard fires only when there is one to
+ // withhold, so a refusal here is what proves the edit above kept it.
+ _, err = ctl.instanceServiceClient.UpdateDataSource(ctx, connect.NewRequest(&v1pb.UpdateDataSourceRequest{
+ Name: instance.Name,
+ DataSource: &v1pb.DataSource{Id: keytabRetentionID, Host: "attacker3.example.com"},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"host"}},
+ }))
+ a.Error(err, "the unrelated edit must not have wiped the stored keytab")
+ a.Contains(err.Error(), "keytab",
+ "it has to be the keytab guard refusing — any other InvalidArgument would keep this "+
+ "green with the credential already destroyed")
+
+ // Supplying the keytab again is what the guard asks for, and it is
+ // proof the caller holds the credential. The move then goes through.
+ _, err = ctl.instanceServiceClient.UpdateDataSource(ctx, connect.NewRequest(&v1pb.UpdateDataSourceRequest{
+ Name: instance.Name,
+ DataSource: krbDataSource("hive2.internal.example.com", "re-supplied-keytab"),
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"host", "sasl_config"}},
+ }))
+ a.NoError(err, "re-supplying the keytab must let an operator move the instance")
+
+ moved, err := ctl.instanceServiceClient.GetInstance(ctx, connect.NewRequest(&v1pb.GetInstanceRequest{
+ Name: instance.Name,
+ }))
+ a.NoError(err)
+ a.Equal("hive2.internal.example.com", moved.Msg.DataSources[0].Host)
+ })
+
+ t.Run("UpdateInstance full replacement", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ instance := createKeytabInstance(ctx, t, ctl, "keytab-instance")
+
+ replace := func(ds *v1pb.DataSource) error {
+ _, err := ctl.instanceServiceClient.UpdateInstance(ctx, connect.NewRequest(&v1pb.UpdateInstanceRequest{
+ Instance: &v1pb.Instance{Name: instance.Name, DataSources: []*v1pb.DataSource{ds}},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"data_sources"}},
+ }))
+ return err
+ }
+ // Every refusal here has to be the keytab guard specifically. The
+ // handler can reject a merged data source for several unrelated
+ // reasons, and each of these assertions is standing in for "the stored
+ // keytab is still there" — a bare a.Error would stay green with the
+ // credential already gone.
+ refuses := func(ds *v1pb.DataSource, msg string) {
+ t.Helper()
+ err := replace(ds)
+ a.Error(err, msg)
+ a.Contains(err.Error(), "keytab", msg)
+ }
+
+ // The whole reason retention exists: the list is rebuilt from a read,
+ // which never returned the keytab.
+ a.NoError(replace(krbDataSource(keytabRetentionHost, "")),
+ "a wholesale replacement that stays put must keep the stored keytab")
+
+ refuses(krbDataSource("attacker.example.com", ""),
+ "matching by data source ID is not consent to move the keytab")
+
+ // The refusal must not have consumed the stored keytab. The guard
+ // fires only when there is one to withhold, so a second refusal is the
+ // evidence that it survived.
+ refuses(krbDataSource("attacker2.example.com", ""),
+ "a refused move must leave the stored keytab in place")
+
+ // The KDC is where kinit presents the keytab itself, so moving it is
+ // the most direct version of this move.
+ movedKDC := krbDataSource(keytabRetentionHost, "")
+ movedKDC.SaslConfig.GetKrbConfig().KdcHost = "kdc.attacker.example.com"
+ refuses(movedKDC, "the KDC is the endpoint the keytab material itself reaches")
+
+ a.NoError(replace(krbDataSource("hive2.internal.example.com", "re-supplied-keytab")),
+ "re-supplying the keytab must let an operator move the instance")
+ })
+}
diff --git a/backend/tests/mcp_forbidden_credential_mints_test.go b/backend/tests/mcp_forbidden_credential_mints_test.go
index 5dac90454d..e572b66ada 100644
--- a/backend/tests/mcp_forbidden_credential_mints_test.go
+++ b/backend/tests/mcp_forbidden_credential_mints_test.go
@@ -545,23 +545,24 @@ func TestMCPCannotRetargetADataSource(t *testing.T) {
rows := deniedMCPRows(ctx, t, ctl, workspace.Msg.Name, "/bytebase.v1.InstanceService/UpdateDataSource")
t.Logf("audit rows for the two denied retargets (one validate-only): %d", len(rows))
- // A THIRD way a denial goes unrecorded, distinct from the two the
- // interceptor's doc comment already names. UpdateDataSource carries
- // audit = true and is not carved out of workspace-parent resolution, so
- // the persisting attempt above is on the audit page. The validate-only one
- // is not: createAuditLog's first statement returns nil for any request
- // whose validate_only field is set (audit.go), before it does anything
- // with the denial.
+ // Both denials are on the audit page. UpdateDataSource carries audit = true
+ // and is not carved out of workspace-parent resolution, and createAuditLog
+ // now skips a validate-only request only when the call SUCCEEDED — a dry
+ // run Bytebase accepted changed nothing worth recording, a refused one is
+ // worth exactly as much as any other refusal.
//
- // That skip is right for a permitted call, which changed nothing worth
- // recording, and backwards for a refused one — and validate_only is
- // precisely the variant that leaves no other trace, since it dials the
- // caller's host and persists nothing. Fixing it means exempting policy
- // denials from the skip, which is interceptor work this PR does not do:
- // BOT-57. This assertion is what tells whoever does that it landed.
- a.Len(rows, 1,
- "exactly one of the two denials is auditable: the validate-only retarget is skipped "+
- "by createAuditLog before the denial is ever considered")
+ // This is the assertion that discriminates the two. Before, the
+ // validate-only denial returned from createAuditLog's first statement
+ // before the denial was ever considered, so this pair — same method, same
+ // session, same refusal, one flag apart — produced ONE row, and the
+ // validate-only variant is precisely the one that leaves no other trace:
+ // it dials the caller's host and persists nothing.
+ a.Len(rows, 2,
+ "both denials are auditable: setting validate_only must not turn off the record of being refused")
+ for _, row := range rows {
+ a.Equal(int32(connect.CodePermissionDenied), row.GetStatus().GetCode(),
+ "each row must carry the denial, not a blank status")
+ }
// The console keeps working — the gate is on the internal MCP chain only.
_, err = ctl.instanceServiceClient.UpdateDataSource(ctx, connect.NewRequest(&v1pb.UpdateDataSourceRequest{