Skip to content

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

fix: audit log for sa/wi actor (#21505)

ecmadao66cd91b06bbb
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 763838e713..a3bbd513ce 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -10189,12 +10189,12 @@ components:
- $ref: '#/components/schemas/google.protobuf.Timestamp'
title: create_time
description: The timestamp when the audit log was created.
- user:
+ actor:
type: string
- title: user
+ title: actor
description: |-
- The user who performed the action.
- Format: users/{email}
+ The principal who performed the action.
+ Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}
method:
type: string
title: method
@@ -20308,7 +20308,8 @@ components:
- method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
- resource: the resource the entry is about, support "==" operator.
- severity: support "==" operator, check Severity enum in AuditLog message for values.
- - user: the actor, should in "users/{email}" format, support "==" operator.
+ - actor: the actor, in users/{email}, serviceAccounts/{email}, or
+ workloadIdentities/{email} format. Support "==" operator.
- create_time: support ">=" and "<=" operator.
- mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
- mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
@@ -20316,7 +20317,7 @@ components:
For example:
- filter = "method == '/bytebase.v1.SQLService/Query'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
- - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
+ - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && actor == 'users/[email protected]'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
- filter = "mcp == true"
- filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
@@ -24676,15 +24677,10 @@ components:
enum:
- NULL_VALUE
description: |-
- Represents a JSON `null`.
-
- `NullValue` is a sentinel, using an enum with only one value to represent
- the null value for the `Value` type union.
+ `NullValue` is a singleton enumeration to represent the null value for the
+ `Value` type union.
- A field of type `NullValue` with any value other than `0` is considered
- invalid. Most ProtoJSON serializers will emit a Value with a `null_value` set
- as a JSON `null` regardless of the integer value, and so will round trip to
- a `0` value.
+ The JSON representation for `NullValue` is JSON `null`.
google.protobuf.Struct:
type: object
additionalProperties:
diff --git a/backend/api/v1/audit.go b/backend/api/v1/audit.go
index 66a5adf0d4..35dbf0cbe9 100644
--- a/backend/api/v1/audit.go
+++ b/backend/api/v1/audit.go
@@ -260,7 +260,7 @@ func (in *AuditInterceptor) buildAuditRows(ctx context.Context, e *auditEntry) (
var user string
if u, ok := GetUserFromContext(ctx); ok {
- user = common.FormatUserEmail(u.Email)
+ user = common.FormatPrincipalMember(u.Email, u.Type)
} else {
// Try to get user from successful login response.
if loginResponse, ok := e.response.(*v1pb.LoginResponse); ok {
diff --git a/backend/api/v1/audit_log_converter_test.go b/backend/api/v1/audit_log_converter_test.go
index 1900b6050a..5321357e2f 100644
--- a/backend/api/v1/audit_log_converter_test.go
+++ b/backend/api/v1/audit_log_converter_test.go
@@ -15,7 +15,7 @@ import (
func TestConvertToAuditLogsNamesRowsByPayloadParent(t *testing.T) {
t.Parallel()
logs := convertToAuditLogs([]*store.AuditLog{
- {ResourceID: "after-cutoff", CreatedAt: time.Unix(2, 0), Payload: &storepb.AuditLog{Parent: "projects/project-a"}},
+ {ResourceID: "after-cutoff", CreatedAt: time.Unix(2, 0), Payload: &storepb.AuditLog{Parent: "projects/project-a", User: "serviceAccounts/[email protected]"}},
{ResourceID: "at-cutoff", CreatedAt: time.Unix(1, 0), Payload: &storepb.AuditLog{Parent: "projects/project-a"}},
})
@@ -27,4 +27,5 @@ func TestConvertToAuditLogsNamesRowsByPayloadParent(t *testing.T) {
"projects/project-a/auditLogs/after-cutoff",
"projects/project-a/auditLogs/at-cutoff",
}, names)
+ require.Equal(t, "serviceAccounts/[email protected]", logs[0].Actor)
}
diff --git a/backend/api/v1/audit_log_service.go b/backend/api/v1/audit_log_service.go
index 68181f1170..73f7f89b22 100644
--- a/backend/api/v1/audit_log_service.go
+++ b/backend/api/v1/audit_log_service.go
@@ -126,12 +126,12 @@ func (s *AuditLogService) ExportAuditLogs(ctx context.Context, request *connect.
}
result := &v1pb.QueryResult{
- ColumnNames: []string{"time", "user", "method", "severity", "resource", "request", "response", "status"},
+ ColumnNames: []string{"time", "actor", "method", "severity", "resource", "request", "response", "status"},
}
for _, auditLog := range searchAuditLogsResult.Msg.AuditLogs {
queryRow := &v1pb.QueryRow{Values: []*v1pb.RowValue{
{Kind: &v1pb.RowValue_StringValue{StringValue: auditLog.CreateTime.AsTime().Format(time.RFC3339)}},
- {Kind: &v1pb.RowValue_StringValue{StringValue: auditLog.User}},
+ {Kind: &v1pb.RowValue_StringValue{StringValue: auditLog.Actor}},
{Kind: &v1pb.RowValue_StringValue{StringValue: auditLog.Method}},
{Kind: &v1pb.RowValue_StringValue{StringValue: auditLog.Severity.String()}},
{Kind: &v1pb.RowValue_StringValue{StringValue: auditLog.Resource}},
@@ -179,7 +179,7 @@ func convertToAuditLog(l *store.AuditLog) *v1pb.AuditLog {
return &v1pb.AuditLog{
Name: fmt.Sprintf("%s/%s%s", l.Payload.Parent, common.AuditLogPrefix, l.ResourceID),
CreateTime: timestamppb.New(l.CreatedAt),
- User: l.Payload.User,
+ Actor: l.Payload.User,
Method: l.Payload.Method,
Severity: convertToAuditLogSeverity(l.Payload.Severity),
Resource: l.Payload.Resource,
diff --git a/backend/api/v1/audit_test.go b/backend/api/v1/audit_test.go
index 459ea392ca..e66c694800 100644
--- a/backend/api/v1/audit_test.go
+++ b/backend/api/v1/audit_test.go
@@ -70,6 +70,59 @@ func TestFailedLoginWithHandlerWorkspaceCreatesSingleAuditRow(t *testing.T) {
require.Equal(t, "[email protected]", rows[0].payload.GetResource())
}
+func TestAuditRowsPreserveAuthenticatedPrincipalType(t *testing.T) {
+ t.Parallel()
+ in := NewAuditInterceptor(nil, "test-secret", &config.Profile{})
+
+ for _, tc := range []struct {
+ name string
+ user *store.UserMessage
+ }{
+ {
+ name: "end user",
+ user: &store.UserMessage{
+ Email: "[email protected]",
+ Type: storepb.PrincipalType_END_USER,
+ },
+ },
+ {
+ name: "service account",
+ user: &store.UserMessage{
+ Email: "[email protected]",
+ Type: storepb.PrincipalType_SERVICE_ACCOUNT,
+ },
+ },
+ {
+ name: "workload identity",
+ user: &store.UserMessage{
+ Email: "[email protected]",
+ Type: storepb.PrincipalType_WORKLOAD_IDENTITY,
+ },
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ ctx := newAuditTestContext(&common.AuthContext{
+ Audit: true,
+ Resources: []*common.Resource{{
+ Type: common.ResourceTypeWorkspace,
+ ID: auditTestWorkspace,
+ }},
+ })
+ ctx = context.WithValue(ctx, common.UserContextKey, tc.user)
+
+ rows, err := in.buildAuditRows(ctx, &auditEntry{
+ request: &v1pb.QueryRequest{Name: "instances/instance-a/databases/database-a"},
+ method: v1connect.SQLServiceQueryProcedure,
+ })
+ require.NoError(t, err)
+ require.Len(t, rows, 1)
+ require.Equal(t, common.FormatPrincipalMember(tc.user.Email, tc.user.Type), rows[0].payload.GetUser())
+ })
+ }
+}
+
// TestStreamingAuditPersistedBeforeSend pins the streaming audit contract: a
// client must not observe a successful streaming response before the
// corresponding audit entry is durably persisted. Regression test for the
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.go
index 47b5e6a996..69ef6f2416 100644
--- a/backend/api/v1/auth_service.go
+++ b/backend/api/v1/auth_service.go
@@ -241,6 +241,9 @@ func (s *AuthService) Login(ctx context.Context, req *connect.Request[v1pb.Login
if err != nil {
return nil, err
}
+ if err := rejectWebLoginForNonEndUser(request.Web, loginUser.Type); err != nil {
+ return nil, err
+ }
// 2. Reject deactivated users before any workspace provisioning.
if loginUser.MemberDeleted {
@@ -292,6 +295,13 @@ func (s *AuthService) Login(ctx context.Context, req *connect.Request[v1pb.Login
return s.finalizeLogin(ctx, req.Header(), request.Web, loginUser, token, workspaceID, requireResetPassword)
}
+func rejectWebLoginForNonEndUser(web bool, principalType storepb.PrincipalType) error {
+ if web && principalType != storepb.PrincipalType_END_USER {
+ return connect.NewError(connect.CodePermissionDenied, errors.Errorf("only users can use web login"))
+ }
+ return nil
+}
+
func (s *AuthService) needResetPassword(ctx context.Context, user *store.UserMessage, workspaceID string, restriction *v1pb.Restriction) bool {
// Reset password restriction only works for end user with email & password login.
if user.Type != storepb.PrincipalType_END_USER {
@@ -1112,9 +1122,6 @@ func (s *AuthService) finalizeLogin(ctx context.Context, header http.Header, web
resp := connect.NewResponse(response)
if web {
- if user.Type != storepb.PrincipalType_END_USER {
- return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("only users can use web login"))
- }
// A fresh session: the refresh token gets the full refresh duration.
d := auth.GetRefreshTokenDuration(ctx, s.store, s.licenseService, workspaceID)
if err := s.issueSessionCookies(ctx, resp.Header(), header.Get("Origin"), user.Email, workspaceID, token, time.Now().Add(d)); err != nil {
diff --git a/backend/api/v1/auth_service_test.go b/backend/api/v1/auth_service_test.go
index 9c068366c1..2a6ff9643c 100644
--- a/backend/api/v1/auth_service_test.go
+++ b/backend/api/v1/auth_service_test.go
@@ -13,6 +13,7 @@ import (
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/component/config"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/store"
)
@@ -143,6 +144,49 @@ func TestLoginAuthMethodRequiresPasswordReset(t *testing.T) {
}
}
+func TestRejectWebLoginForNonEndUser(t *testing.T) {
+ t.Parallel()
+ tests := []struct {
+ name string
+ principal storepb.PrincipalType
+ web bool
+ wantCode connect.Code
+ }{
+ {
+ name: "service account web login",
+ principal: storepb.PrincipalType_SERVICE_ACCOUNT,
+ web: true,
+ wantCode: connect.CodePermissionDenied,
+ },
+ {
+ name: "workload identity web login",
+ principal: storepb.PrincipalType_WORKLOAD_IDENTITY,
+ web: true,
+ wantCode: connect.CodePermissionDenied,
+ },
+ {
+ name: "service account API login",
+ principal: storepb.PrincipalType_SERVICE_ACCOUNT,
+ web: false,
+ wantCode: connect.CodeUnknown,
+ },
+ {
+ name: "end user web login",
+ principal: storepb.PrincipalType_END_USER,
+ web: true,
+ wantCode: connect.CodeUnknown,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+ err := rejectWebLoginForNonEndUser(test.web, test.principal)
+ require.Equal(t, test.wantCode, connect.CodeOf(err))
+ })
+ }
+}
+
func TestMFATempTokenPreservesLoginAuthMethod(t *testing.T) {
t.Parallel()
const secret = "test-secret"
diff --git a/backend/generated-go/store/audit_log.pb.go b/backend/generated-go/store/audit_log.pb.go
index ee142008c1..1273eef116 100644
--- a/backend/generated-go/store/audit_log.pb.go
+++ b/backend/generated-go/store/audit_log.pb.go
@@ -103,7 +103,8 @@ type AuditLog struct {
// The resource name.
// Example: projects/{project}
Resource string `protobuf:"bytes,3,opt,name=resource,proto3" json:"resource,omitempty"`
- // Format: users/{email}.
+ // The principal who performed the action.
+ // Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}.
User string `protobuf:"bytes,4,opt,name=user,proto3" json:"user,omitempty"`
Severity AuditLog_Severity `protobuf:"varint,5,opt,name=severity,proto3,enum=bytebase.store.AuditLog_Severity" json:"severity,omitempty"`
// Marshalled request.
diff --git a/backend/generated-go/v1/audit_log_service.pb.go b/backend/generated-go/v1/audit_log_service.pb.go
index 68347ca0e8..521fecd153 100644
--- a/backend/generated-go/v1/audit_log_service.pb.go
+++ b/backend/generated-go/v1/audit_log_service.pb.go
@@ -111,18 +111,19 @@ type SearchAuditLogsRequest struct {
// The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
//
// Supported filter:
- // - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
- // - resource: the resource the entry is about, support "==" operator.
- // - severity: support "==" operator, check Severity enum in AuditLog message for values.
- // - user: the actor, should in "users/{email}" format, support "==" operator.
- // - create_time: support ">=" and "<=" operator.
- // - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
- // - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
+ // - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
+ // - resource: the resource the entry is about, support "==" operator.
+ // - severity: support "==" operator, check Severity enum in AuditLog message for values.
+ // - actor: the actor, in users/{email}, serviceAccounts/{email}, or
+ // workloadIdentities/{email} format. Support "==" operator.
+ // - create_time: support ">=" and "<=" operator.
+ // - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
+ // - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
//
// For example:
// - filter = "method == '/bytebase.v1.SQLService/Query'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
- // - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
+ // - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && actor == 'users/[email protected]'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
// - filter = "mcp == true"
// - filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
@@ -432,9 +433,9 @@ type AuditLog struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// The timestamp when the audit log was created.
CreateTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"`
- // The user who performed the action.
- // Format: users/{email}
- User string `protobuf:"bytes,3,opt,name=user,proto3" json:"user,omitempty"`
+ // The principal who performed the action.
+ // Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}
+ Actor string `protobuf:"bytes,3,opt,name=actor,proto3" json:"actor,omitempty"`
// The method or action being audited.
// For example: /bytebase.v1.SQLService/Query or bb.project.repository.push
Method string `protobuf:"bytes,4,opt,name=method,proto3" json:"method,omitempty"`
@@ -507,9 +508,9 @@ func (x *AuditLog) GetCreateTime() *timestamppb.Timestamp {
return nil
}
-func (x *AuditLog) GetUser() string {
+func (x *AuditLog) GetActor() string {
if x != nil {
- return x.User
+ return x.Actor
}
return ""
}
@@ -794,12 +795,12 @@ const file_v1_audit_log_service_proto_rawDesc = "" +
"page_token\x18\x06 \x01(\tR\tpageToken\"a\n" +
"\x17ExportAuditLogsResponse\x12\x1e\n" +
"\acontent\x18\x01 \x01(\fB\x04\xd0\xea0\x02R\acontent\x12&\n" +
- "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\xd8\x05\n" +
+ "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\xda\x05\n" +
"\bAuditLog\x12\x17\n" +
"\x04name\x18\x01 \x01(\tB\x03\xe0A\x03R\x04name\x12@\n" +
"\vcreate_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampB\x03\xe0A\x03R\n" +
- "createTime\x12\x12\n" +
- "\x04user\x18\x03 \x01(\tR\x04user\x12\x16\n" +
+ "createTime\x12\x14\n" +
+ "\x05actor\x18\x03 \x01(\tR\x05actor\x12\x16\n" +
"\x06method\x18\x04 \x01(\tR\x06method\x12:\n" +
"\bseverity\x18\x05 \x01(\x0e2\x1e.bytebase.v1.AuditLog.SeverityR\bseverity\x12\x1a\n" +
"\bresource\x18\x06 \x01(\tR\bresource\x12\x18\n" +
diff --git a/backend/generated-go/v1/audit_log_service_equal.pb.go b/backend/generated-go/v1/audit_log_service_equal.pb.go
index 909668a965..8759db2e74 100644
--- a/backend/generated-go/v1/audit_log_service_equal.pb.go
+++ b/backend/generated-go/v1/audit_log_service_equal.pb.go
@@ -111,7 +111,7 @@ func (x *AuditLog) Equal(y *AuditLog) bool {
if p, q := x.CreateTime, y.CreateTime; (p == nil && q != nil) || (p != nil && (q == nil || p.Seconds != q.Seconds || p.Nanos != q.Nanos)) {
return false
}
- if x.User != y.User {
+ if x.Actor != y.Actor {
return false
}
if x.Method != y.Method {
diff --git a/backend/store/audit_log.go b/backend/store/audit_log.go
index efb9e6f346..29dbde0918 100644
--- a/backend/store/audit_log.go
+++ b/backend/store/audit_log.go
@@ -163,7 +163,7 @@ func auditLogEqualsFilter(variable string, rawValue any) (*qb.Query, error) {
}
return qb.Q().Space("NOT (payload ?? 'mcpDelegation')"), nil
- case "resource", "method", "user", "severity", "mcp_correlation_id":
+ case "resource", "method", "actor", "severity", "mcp_correlation_id":
value, ok := rawValue.(string)
if !ok {
return nil, errors.Errorf("expect string, got %T, hint: filter literals should be string", rawValue)
@@ -171,6 +171,9 @@ func auditLogEqualsFilter(variable string, rawValue any) (*qb.Query, error) {
if variable == "mcp_correlation_id" {
return qb.Q().Space("payload->'mcpDelegation'->>'correlationId' = ?", value), nil
}
+ if variable == "actor" {
+ return qb.Q().Space("payload->>'user' = ?", value), nil
+ }
return qb.Q().Space(fmt.Sprintf("payload->>'%s' = ?", variable), value), nil
default:
diff --git a/backend/store/audit_log_filter_test.go b/backend/store/audit_log_filter_test.go
index 816c09b85a..7b1cc057b7 100644
--- a/backend/store/audit_log_filter_test.go
+++ b/backend/store/audit_log_filter_test.go
@@ -5,6 +5,10 @@ import (
"time"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
func mustParseTime(t *testing.T, s string) time.Time {
@@ -14,10 +18,10 @@ func mustParseTime(t *testing.T, s string) time.Time {
return parsedTime
}
-func TestGetSearchAuditLogsFilter_WithoutUserLookup(t *testing.T) {
+func TestGetSearchAuditLogsFilter(t *testing.T) {
t.Parallel()
- // Note: This test skips user filter tests since they require database access
- // User filter functionality is tested in integration tests
+ // Note: This test skips principal lookup filters since they require database access.
+ // Principal lookup filtering is tested in integration tests.
tests := []struct {
name string
@@ -55,6 +59,19 @@ func TestGetSearchAuditLogsFilter_WithoutUserLookup(t *testing.T) {
wantArgs: []any{"INFO"},
wantErr: false,
},
+ {
+ name: "actor filter uses the legacy storage key",
+ filter: `actor == "serviceAccounts/[email protected]"`,
+ wantSQL: "(payload->>'user' = $1)",
+ wantArgs: []any{"serviceAccounts/[email protected]"},
+ wantErr: false,
+ },
+ {
+ name: "user filter is no longer supported",
+ filter: `user == "users/[email protected]"`,
+ wantErr: true,
+ errContains: "unknown variable user",
+ },
{
name: "create_time greater than or equal",
filter: `create_time >= "2024-01-01T00:00:00Z"`,
@@ -169,6 +186,20 @@ func TestGetSearchAuditLogsFilter_WithoutUserLookup(t *testing.T) {
}
}
+func TestAuditLogUserUsesProtoJSONName(t *testing.T) {
+ t.Parallel()
+
+ payload, err := protojson.Marshal(&storepb.AuditLog{
+ User: "serviceAccounts/[email protected]",
+ })
+ require.NoError(t, err)
+ require.JSONEq(t, `{"user":"serviceAccounts/[email protected]"}`, string(payload))
+
+ var auditLog storepb.AuditLog
+ require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal(payload, &auditLog))
+ require.Equal(t, "serviceAccounts/[email protected]", auditLog.User)
+}
+
func TestGetSearchAuditLogsFilter_EdgeCases(t *testing.T) {
t.Parallel()
tests := []struct {
diff --git a/backend/store/audit_log_retention_test.go b/backend/store/audit_log_retention_test.go
index bee518d283..3ff3ca5f34 100644
--- a/backend/store/audit_log_retention_test.go
+++ b/backend/store/audit_log_retention_test.go
@@ -78,7 +78,7 @@ func TestAuditLogRetentionFilteringEndToEnd(t *testing.T) {
require.Equal(t, fmt.Sprintf("%s/%s%s", testAuditLogParent, common.AuditLogPrefix, "new-log"), log.Name)
require.Equal(t, testAuditLogParent, log.Resource)
require.Equal(t, "/bytebase.v1.ProjectService/GetProject", log.Method)
- require.Equal(t, "users/[email protected]", log.User)
+ require.Equal(t, "users/[email protected]", log.Actor)
require.Equal(t, v1pb.AuditLog_INFO, log.Severity)
require.Equal(t, newLogTime.UnixNano(), log.CreateTime.AsTime().UnixNano())
})
diff --git a/backend/store/principal.go b/backend/store/principal.go
index 1f5a881576..a8f3503e8c 100644
--- a/backend/store/principal.go
+++ b/backend/store/principal.go
@@ -982,8 +982,8 @@ func (s *Store) UpdateUserEmail(ctx context.Context, user *UserMessage, newEmail
rows.Close()
// 5. Update Audit Logs
- // Update audit_log.payload to replace old user reference with new one.
- // User is stored in the 'user' field in "users/{email}" format.
+ // Update the audit log principal reference.
+ // AuditLog.User is stored in the 'user' field in "users/{email}" format.
query = qb.Q().Space(`
UPDATE audit_log
SET payload = jsonb_set(payload, '{user}', to_jsonb(?::text))
diff --git a/backend/tests/audit_sinks_test.go b/backend/tests/audit_sinks_test.go
index 9c120b90d8..1590a759c4 100644
--- a/backend/tests/audit_sinks_test.go
+++ b/backend/tests/audit_sinks_test.go
@@ -406,7 +406,7 @@ func auditSinkRows(ctx context.Context, t *testing.T, ctl *controller, p auditSi
require.NoError(t, err)
var rows []*v1pb.AuditLog
for _, row := range resp.Msg.AuditLogs {
- if row.User == user && (row.McpDelegation != nil) == p.mcp && (p.match == nil || p.match(row.Request)) {
+ if row.Actor == user && (row.McpDelegation != nil) == p.mcp && (p.match == nil || p.match(row.Request)) {
rows = append(rows, row)
}
}
diff --git a/backend/tests/login_audit_test.go b/backend/tests/login_audit_test.go
index e24859aa5b..3082a5f347 100644
--- a/backend/tests/login_audit_test.go
+++ b/backend/tests/login_audit_test.go
@@ -347,7 +347,7 @@ func TestAuditLogFormat(t *testing.T) {
a.True(strings.HasPrefix(entry.Name, workspace+"/auditLogs/"),
"audit log must be parented under the login workspace")
a.NotNil(entry.CreateTime, "CreateTime must be set")
- a.Equal("users/[email protected]", entry.User, "User must be users/{email}")
+ a.Equal("users/[email protected]", entry.Actor, "Actor must be users/{email}")
a.Equal("/bytebase.v1.AuthService/Login", entry.Method,
"Method is part of the filter API contract and must be the full procedure name")
a.Equal(v1pb.AuditLog_INFO, entry.Severity, "successful Login is INFO severity")
@@ -974,7 +974,7 @@ func TestAuditLogFormat(t *testing.T) {
a.True(strings.HasPrefix(projEntry.Name, projectResource+"/auditLogs/"),
"audit entry must be parented under the target project, not the workspace")
a.Equal("/bytebase.v1.ProjectService/SetIamPolicy", projEntry.Method)
- a.Equal("users/[email protected]", projEntry.User)
+ a.Equal("users/[email protected]", projEntry.Actor)
a.Equal(v1pb.AuditLog_INFO, projEntry.Severity)
a.Equal(projectResource, projEntry.Resource,
"SetIamPolicy's Resource is the target project name")
diff --git a/backend/tests/mcp_audit_provenance_test.go b/backend/tests/mcp_audit_provenance_test.go
index 3d9e7ad4ba..e64fce3b51 100644
--- a/backend/tests/mcp_audit_provenance_test.go
+++ b/backend/tests/mcp_audit_provenance_test.go
@@ -157,7 +157,7 @@ func TestMCPAuditProvenance(t *testing.T) {
a.NoError(err)
var rows []*v1pb.AuditLog
for _, l := range resp.Msg.AuditLogs {
- if l.User == "users/"+memberEmail {
+ if l.Actor == "users/"+memberEmail {
rows = append(rows, l)
}
}
@@ -217,7 +217,7 @@ func TestMCPAuditProvenance(t *testing.T) {
a.NoError(err)
var adminCreates int
for _, row := range adminRows.Msg.AuditLogs {
- if row.User == ctl.principalName {
+ if row.Actor == ctl.principalName {
adminCreates++
a.Nil(row.McpDelegation, "a public-chain row must never carry MCP provenance")
}
diff --git a/backend/tests/mcp_denial_audit_test.go b/backend/tests/mcp_denial_audit_test.go
index 5512885663..26847d5dd7 100644
--- a/backend/tests/mcp_denial_audit_test.go
+++ b/backend/tests/mcp_denial_audit_test.go
@@ -58,7 +58,7 @@ func TestMCPPolicyDenialsReachTheAuditPage(t *testing.T) {
connectionRows := searchMCP(`method == "/bytebase.mcp.Session/Authorize"`)
a.Len(connectionRows, 1, "the refused connection is on the audit page")
connection := connectionRows[0]
- a.Equal(ctl.principalName, connection.User)
+ a.Equal(ctl.principalName, connection.Actor)
a.NotNil(connection.Status)
a.Contains(connection.Status.Message, "turned MCP access off")
a.NotNil(connection.McpDelegation, "the row wears the MCP badge")
diff --git a/backend/tests/user_test.go b/backend/tests/user_test.go
index 89aec81662..084d30d64a 100644
--- a/backend/tests/user_test.go
+++ b/backend/tests/user_test.go
@@ -624,7 +624,7 @@ func TestUpdateUserEmail(t *testing.T) {
// Search for audit logs related to the project (audit logs were created when user created issue/comment)
auditLogs, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{
Parent: "projects/" + projectID,
- Filter: fmt.Sprintf(`user == "%s"`, common.FormatUserEmail(newEmail)),
+ Filter: fmt.Sprintf(`actor == "%s"`, common.FormatUserEmail(newEmail)),
}))
a.NoError(err)
// We should have at least some audit logs from the issue/comment creation
@@ -632,7 +632,7 @@ func TestUpdateUserEmail(t *testing.T) {
// Verify no audit logs have the old email
oldEmailAuditLogs, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{
Parent: "projects/" + projectID,
- Filter: fmt.Sprintf(`user == "%s"`, common.FormatUserEmail(originalEmail)),
+ Filter: fmt.Sprintf(`actor == "%s"`, common.FormatUserEmail(originalEmail)),
}))
a.NoError(err)
a.Empty(oldEmailAuditLogs.Msg.AuditLogs, "Should not have audit logs with old email")
diff --git a/frontend/src/api/middlewares/authInterceptorMiddleware.test.ts b/frontend/src/api/middlewares/authInterceptorMiddleware.test.ts
index 161f43ae9e..33067c414a 100644
--- a/frontend/src/api/middlewares/authInterceptorMiddleware.test.ts
+++ b/frontend/src/api/middlewares/authInterceptorMiddleware.test.ts
@@ -181,6 +181,20 @@ describe("authInterceptor", () => {
});
});
+ test("does not leave sign-in for a rejected web login", async () => {
+ const error = new ConnectError(
+ "only users can use web login",
+ Code.PermissionDenied
+ );
+ const next = vi.fn().mockRejectedValue(error);
+
+ await expect(
+ authInterceptor(next)(createRequest({ methodName: "Login" }))
+ ).rejects.toBe(error);
+
+ expect(mocks.routerPush).not.toHaveBeenCalled();
+ });
+
test("builds a permission denied route query from request and route metadata", async () => {
mocks.currentRoute.value = {
name: "workspace.database",
diff --git a/frontend/src/api/middlewares/authInterceptorMiddleware.ts b/frontend/src/api/middlewares/authInterceptorMiddleware.ts
index d8ddb9a4d9..c31c35b7b7 100644
--- a/frontend/src/api/middlewares/authInterceptorMiddleware.ts
+++ b/frontend/src/api/middlewares/authInterceptorMiddleware.ts
@@ -119,6 +119,7 @@ export const authInterceptor: Interceptor = (next) => async (req) => {
if (
!silent &&
code === Code.PermissionDenied &&
+ req.method.name !== "Login" &&
router.currentRoute.value.name !== WORKSPACE_ROUTE_403
) {
const errorDetail = extractPermissionDeniedDetail(error);
diff --git a/frontend/src/api/middlewares/errorNotificationMiddleware.test.ts b/frontend/src/api/middlewares/errorNotificationMiddleware.test.ts
index d3d06116e9..a6102976a8 100644
--- a/frontend/src/api/middlewares/errorNotificationMiddleware.test.ts
+++ b/frontend/src/api/middlewares/errorNotificationMiddleware.test.ts
@@ -33,15 +33,17 @@ import { errorNotificationInterceptor } from "./errorNotificationMiddleware";
const createRequest = ({
silent = false,
ignoredCodes = [],
+ methodName = "ListDatabases",
}: {
silent?: boolean;
ignoredCodes?: Code[];
+ methodName?: string;
} = {}) =>
({
contextValues: createContextValues()
.set(silentContextKey, silent)
.set(ignoredCodesContextKey, ignoredCodes),
- method: { name: "ListDatabases" },
+ method: { name: methodName },
service: { name: "DatabaseService" },
}) as never;
@@ -67,6 +69,25 @@ describe("errorNotificationInterceptor", () => {
expect(mocks.pushNotification).not.toHaveBeenCalled();
});
+ test("shows a rejected web login as a sign-in error", async () => {
+ const error = new ConnectError(
+ "only users can use web login",
+ Code.PermissionDenied
+ );
+ const next = vi.fn().mockRejectedValue(error);
+
+ await expect(
+ errorNotificationInterceptor(next)(createRequest({ methodName: "Login" }))
+ ).rejects.toBe(error);
+
+ expect(mocks.pushNotification).toHaveBeenCalledWith({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "auth.sign-in.failed",
+ description: "only users can use web login",
+ });
+ });
+
test("still toasts non-permission request failures", async () => {
const error = new ConnectError("failed", Code.Internal);
const next = vi.fn().mockRejectedValue(error);
diff --git a/frontend/src/api/middlewares/errorNotificationMiddleware.ts b/frontend/src/api/middlewares/errorNotificationMiddleware.ts
index 388abe0365..37cbe3eb28 100644
--- a/frontend/src/api/middlewares/errorNotificationMiddleware.ts
+++ b/frontend/src/api/middlewares/errorNotificationMiddleware.ts
@@ -42,8 +42,14 @@ export const errorNotificationInterceptor: Interceptor =
) {
// ignored
} else if (error.code === Code.PermissionDenied) {
- // The auth interceptor navigates permission failures to /403, where
- // the route-level guard displays the missing permission details.
+ if (req.method.name === "Login") {
+ maybePushNotification(
+ i18n.t("auth.sign-in.failed"),
+ error.rawMessage
+ );
+ }
+ // Other permission failures navigate to /403, where the route-level
+ // guard displays the missing permission details.
} else {
const details = [error.message];
maybePushNotification(
diff --git a/frontend/src/components/AccountMultiSelect.test.tsx b/frontend/src/components/AccountMultiSelect.test.tsx
index 09678696ba..edf7742300 100644
--- a/frontend/src/components/AccountMultiSelect.test.tsx
+++ b/frontend/src/components/AccountMultiSelect.test.tsx
@@ -142,7 +142,13 @@ describe("AccountMultiSelect", () => {
document.body.appendChild(container);
const root = createRoot(container);
act(() => {
- root.render(<AccountMultiSelect value={[]} onChange={() => {}} />);
+ root.render(
+ <AccountMultiSelect
+ value={[]}
+ onChange={() => {}}
+ accountParents={[]}
+ />
+ );
});
act(() => {
container.firstElementChild?.firstElementChild?.dispatchEvent(
@@ -215,6 +221,7 @@ describe("AccountMultiSelect", () => {
<AccountMultiSelect
value={[]}
onChange={() => {}}
+ accountParents={[]}
excludeAccounts={["user:[email protected]", "group:[email protected]"]}
/>
);
@@ -255,6 +262,7 @@ describe("AccountMultiSelect", () => {
<AccountMultiSelect
value={[]}
onChange={() => {}}
+ accountParents={[]}
excludeAccounts={["user:[email protected]"]}
/>
);
@@ -281,7 +289,13 @@ describe("AccountMultiSelect", () => {
const outerKeydown = vi.fn();
document.addEventListener("keydown", outerKeydown);
await act(async () => {
- root.render(<AccountMultiSelect value={[]} onChange={() => {}} />);
+ root.render(
+ <AccountMultiSelect
+ value={[]}
+ onChange={() => {}}
+ accountParents={[]}
+ />
+ );
await Promise.resolve();
await Promise.resolve();
});
@@ -314,6 +328,7 @@ describe("AccountMultiSelect", () => {
<AccountMultiSelect
value={[]}
onChange={() => {}}
+ accountParents={[]}
placeholder="Add users or groups"
/>
);
@@ -332,6 +347,7 @@ describe("AccountMultiSelect", () => {
<AccountMultiSelect
value={[]}
onChange={() => {}}
+ accountParents={[]}
includeAllUsers
/>
);
@@ -374,6 +390,7 @@ describe("AccountMultiSelect", () => {
"workloadIdentity:[email protected]",
]}
onChange={() => {}}
+ accountParents={[]}
/>
);
});
@@ -388,7 +405,13 @@ describe("AccountMultiSelect", () => {
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => {
- root.render(<AccountMultiSelect value={[]} onChange={() => {}} />);
+ root.render(
+ <AccountMultiSelect
+ value={[]}
+ onChange={() => {}}
+ accountParents={[]}
+ />
+ );
await Promise.resolve();
await Promise.resolve();
});
@@ -423,7 +446,13 @@ describe("AccountMultiSelect", () => {
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => {
- root.render(<AccountMultiSelect value={[]} onChange={() => {}} />);
+ root.render(
+ <AccountMultiSelect
+ value={[]}
+ onChange={() => {}}
+ accountParents={[]}
+ />
+ );
await Promise.resolve();
await Promise.resolve();
});
@@ -453,6 +482,49 @@ describe("AccountMultiSelect", () => {
act(() => root.unmount());
});
+ test("does not offer special accounts to resources that cannot grant them", async () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(
+ <AccountMultiSelect
+ value={[]}
+ onChange={() => {}}
+ accountParents={["workspaces/default", "projects/project-1"]}
+ includeSpecialAccounts={false}
+ />
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ container.firstElementChild?.firstElementChild?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true })
+ );
+ });
+
+ const input = container.querySelector(
+ '[data-testid="search"]'
+ ) as HTMLInputElement;
+ await act(async () => {
+ const valueSetter = Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ "value"
+ )?.set;
+ valueSetter?.call(input, "[email protected]");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mocks.listServiceAccounts).not.toHaveBeenCalled();
+ expect(mocks.listWorkloadIdentities).not.toHaveBeenCalled();
+ expect(container.textContent).not.toContain("[email protected]");
+
+ act(() => root.unmount());
+ });
+
test("discovers a service account by partial search and serializes its binding", async () => {
mocks.listServiceAccounts.mockResolvedValue({
serviceAccounts: [
diff --git a/frontend/src/components/AccountMultiSelect.tsx b/frontend/src/components/AccountMultiSelect.tsx
index b7bcf17543..31802c766f 100644
--- a/frontend/src/components/AccountMultiSelect.tsx
+++ b/frontend/src/components/AccountMultiSelect.tsx
@@ -180,6 +180,7 @@ export function AccountMultiSelect({
includeAllUsers,
excludeAccounts,
accountParents,
+ includeSpecialAccounts = true,
placeholder,
}: {
value: string[];
@@ -196,7 +197,9 @@ export function AccountMultiSelect({
*/
excludeAccounts?: string[];
/** Resource parents whose special accounts may be discovered. */
- accountParents?: string[];
+ accountParents: string[];
+ /** Whether this resource can grant service accounts and workload identities. */
+ includeSpecialAccounts?: boolean;
}) {
const { t } = useTranslation();
const listUsers = useAppStore((state) => state.listUsers);
@@ -214,7 +217,7 @@ export function AccountMultiSelect({
const [specialAccounts, setSpecialAccounts] = useState<SpecialAccount[]>([]);
const uniqueAccountParents = useMemo(
- () => [...new Set(accountParents?.filter(Boolean) ?? [])],
+ () => [...new Set(accountParents.filter(Boolean))],
[accountParents]
);
const workspaceAccountParent = useMemo(
@@ -310,7 +313,7 @@ export function AccountMultiSelect({
}, [search, listUsers, listGroups, excludeAccounts]);
useEffect(() => {
- if (permittedAccountParents.length === 0) {
+ if (!includeSpecialAccounts || permittedAccountParents.length === 0) {
setSpecialAccounts([]);
return;
}
@@ -368,6 +371,7 @@ export function AccountMultiSelect({
};
}, [
search,
+ includeSpecialAccounts,
permittedAccountParents,
listServiceAccounts,
listWorkloadIdentities,
@@ -464,6 +468,7 @@ export function AccountMultiSelect({
// Detect service account / workload identity typed in search
const specialAccountMatch = useMemo((): SpecialAccount | null => {
+ if (!includeSpecialAccounts) return null;
const match = detectSpecialAccount(search);
if (!match || !match.email) return null;
const prefix =
@@ -471,7 +476,7 @@ export function AccountMultiSelect({
? serviceAccountNamePrefix
: workloadIdentityNamePrefix;
return { ...match, fullname: `${prefix}${match.email}` };
- }, [search]);
+ }, [search, includeSpecialAccounts]);
// Allow selecting arbitrary user emails typed in the search box
// (for SaaS where admins grant access to emails before signup, or when
@@ -479,12 +484,13 @@ export function AccountMultiSelect({
const arbitraryEmailMatch = useMemo((): string | null => {
const trimmed = search.trim();
if (!trimmed || !isValidEmail(trimmed)) return null;
- // Don't show if it's a service account or workload identity
- if (specialAccountMatch) return null;
+ // Service accounts and workload identities must keep their IAM member
+ // kind; they cannot fall back to an inert user binding.
+ if (getSpecialAccountByEmail(trimmed)) return null;
// Don't show if it already matches a fetched user
if (users.some((u) => u.email === trimmed)) return null;
return trimmed;
- }, [search, specialAccountMatch, users]);
+ }, [search, users]);
const visibleSpecialAccountMatch =
specialAccountMatch &&
diff --git a/frontend/src/components/AuditLogTable.test.tsx b/frontend/src/components/AuditLogTable.test.tsx
index 661d643811..becce3a113 100644
--- a/frontend/src/components/AuditLogTable.test.tsx
+++ b/frontend/src/components/AuditLogTable.test.tsx
@@ -21,7 +21,23 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
pushNotification: vi.fn(),
usePlanFeature: vi.fn(() => true),
- listUsers: vi.fn(async () => ({ users: [] })),
+ listUsers: vi.fn(
+ async (): Promise<{
+ users: Array<{ name: string; email: string; title: string }>;
+ }> => ({ users: [] })
+ ),
+ listServiceAccounts: vi.fn(
+ async (): Promise<{
+ serviceAccounts: Array<{ name: string; email: string; title: string }>;
+ }> => ({ serviceAccounts: [] })
+ ),
+ listWorkloadIdentities: vi.fn(
+ async (): Promise<{
+ workloadIdentities: Array<{ name: string; email: string; title: string }>;
+ }> => ({ workloadIdentities: [] })
+ ),
+ scopeOptions: { value: undefined as unknown },
+ onSearchParamsChange: { value: undefined as unknown },
}));
vi.mock("react-i18next", () => ({
@@ -43,11 +59,17 @@ vi.mock("@/stores/app", () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
listUsers: mocks.listUsers,
+ listServiceAccounts: mocks.listServiceAccounts,
+ listWorkloadIdentities: mocks.listWorkloadIdentities,
+ projectsByName: { "projects/project-a": {} },
+ hasWorkspacePermission: () => true,
+ hasProjectPermission: () => true,
}),
}));
vi.mock("@/hooks/useAppState", () => ({
usePlanFeature: mocks.usePlanFeature,
+ useWorkspaceResourceName: () => "workspaces/default",
}));
vi.mock("@/stores/modules/v1/common", () => ({
@@ -59,11 +81,23 @@ vi.mock("@/stores/modules/v1/common", () => ({
],
planNamePrefix: "plans/",
projectNamePrefix: "projects/",
+ serviceAccountNamePrefix: "serviceAccounts/",
userNamePrefix: "users/",
+ workloadIdentityNamePrefix: "workloadIdentities/",
}));
vi.mock("@/components/AdvancedSearch", () => ({
- AdvancedSearch: () => <div data-testid="advanced-search" />,
+ AdvancedSearch: ({
+ scopeOptions,
+ onParamsChange,
+ }: {
+ scopeOptions: unknown;
+ onParamsChange: unknown;
+ }) => {
+ mocks.scopeOptions.value = scopeOptions;
+ mocks.onSearchParamsChange.value = onParamsChange;
+ return <div data-testid="advanced-search" />;
+ },
}));
vi.mock("@/components/TimeRangePicker", () => ({
@@ -138,6 +172,187 @@ afterEach(() => {
});
describe("AuditLogTable", () => {
+ test("searches only the matching special-account kind for a prefixed actor", async () => {
+ mocks.searchAuditLogs.mockResolvedValue({ auditLogs: [], nextPageToken: "" });
+ mocks.listServiceAccounts.mockResolvedValue({
+ serviceAccounts: [
+ {
+ name: "serviceAccounts/[email protected]",
+ email: "[email protected]",
+ title: "Deploy",
+ },
+ ],
+ });
+ mocks.listWorkloadIdentities.mockResolvedValue({
+ workloadIdentities: [
+ {
+ name: "workloadIdentities/[email protected]",
+ email: "[email protected]",
+ title: "CI",
+ },
+ ],
+ });
+
+ const { render, unmount } = renderIntoContainer(
+ <AuditLogTable parent="projects/project-a" canExport={false} />
+ );
+ await render();
+
+ const actorScope = (
+ mocks.scopeOptions.value as Array<{
+ id: string;
+ onSearch?: (keyword: string) => Promise<Array<{ value: string }>>;
+ }>
+ ).find((scope) => scope.id === "actor");
+ const serviceAccounts = await actorScope?.onSearch?.(
+ "serviceAccounts/deploy"
+ );
+
+ expect(serviceAccounts).toEqual([
+ expect.objectContaining({
+ value: "serviceAccounts/[email protected]",
+ }),
+ ]);
+ expect(mocks.listUsers).not.toHaveBeenCalled();
+ expect(mocks.listWorkloadIdentities).not.toHaveBeenCalled();
+
+ const workloadIdentities = await actorScope?.onSearch?.(
+ "workloadIdentities/ci"
+ );
+ expect(workloadIdentities).toEqual([
+ expect.objectContaining({
+ value: "workloadIdentities/[email protected]",
+ }),
+ ]);
+ expect(mocks.listUsers).not.toHaveBeenCalled();
+
+ await act(async () => {
+ (
+ mocks.onSearchParamsChange.value as
+ | ((params: {
+ query: string;
+ scopes: Array<{ id: string; value: string }>;
+ }) => void)
+ | undefined
+ )?.({
+ query: "",
+ scopes: [
+ {
+ id: "actor",
+ value: "serviceAccounts/[email protected]",
+ },
+ ],
+ });
+ await Promise.resolve();
+ });
+ expect(mocks.searchAuditLogs).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ filter:
+ '(actor == "serviceAccounts/[email protected]" || actor == "users/[email protected]")',
+ })
+ );
+
+ unmount();
+ });
+
+ test("falls back to users for an unprefixed actor", async () => {
+ mocks.searchAuditLogs.mockResolvedValue({ auditLogs: [], nextPageToken: "" });
+ mocks.listUsers.mockResolvedValue({
+ users: [
+ {
+ name: "users/[email protected]",
+ email: "[email protected]",
+ title: "Alice",
+ },
+ ],
+ });
+
+ const { render, unmount } = renderIntoContainer(
+ <AuditLogTable parent="projects/project-a" canExport={false} />
+ );
+ await render();
+
+ const actorScope = (
+ mocks.scopeOptions.value as Array<{
+ id: string;
+ onSearch?: (keyword: string) => Promise<Array<{ value: string }>>;
+ }>
+ ).find((scope) => scope.id === "actor");
+ const users = await actorScope?.onSearch?.("alice");
+
+ expect(users).toEqual([
+ expect.objectContaining({ value: "users/[email protected]" }),
+ ]);
+ expect(mocks.listServiceAccounts).not.toHaveBeenCalled();
+ expect(mocks.listWorkloadIdentities).not.toHaveBeenCalled();
+
+ unmount();
+ });
+
+ test("renders a special-account actor as its full principal name", async () => {
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: [
+ create(AuditLogSchema, {
+ name: "auditLogs/1",
+ method: "/bytebase.v1.SQLService/Query",
+ actor: "serviceAccounts/[email protected]",
+ }),
+ ],
+ nextPageToken: "",
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <AuditLogTable parent="projects/-" canExport={false} />
+ );
+ await render();
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain(
+ "serviceAccounts/[email protected]"
+ );
+ expect(container.querySelector("a")).toBeNull();
+
+ unmount();
+ });
+
+ test("shows the full actor value on hover", async () => {
+ vi.useFakeTimers();
+ const actor = "serviceAccounts/[email protected]";
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: [
+ create(AuditLogSchema, {
+ name: "auditLogs/1",
+ method: "/bytebase.v1.SQLService/Query",
+ actor,
+ }),
+ ],
+ nextPageToken: "",
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <AuditLogTable parent="projects/-" canExport={false} />
+ );
+ await render();
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ const trigger = [...container.querySelectorAll("span")].find(
+ (element) => element.textContent === actor
+ );
+ expect(trigger).toBeInstanceOf(HTMLSpanElement);
+ await act(async () => {
+ trigger?.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(document.getElementById("bb-react-layer-overlay")?.textContent).toContain(actor);
+
+ unmount();
+ });
+
test("renders status details with PermissionDeniedDetail", async () => {
const permissionDeniedDetail = create(PermissionDeniedDetailSchema, {
method: "/bytebase.v1.SQLService/Query",
@@ -153,7 +368,7 @@ describe("AuditLogTable", () => {
name: "auditLogs/1",
severity: AuditLog_Severity.ERROR,
method: "/bytebase.v1.SQLService/Query",
- user: "users/[email protected]",
+ actor: "users/[email protected]",
status,
});
mocks.searchAuditLogs.mockResolvedValue({
@@ -182,13 +397,13 @@ describe("AuditLogTable", () => {
create(AuditLogSchema, {
name: "auditLogs/1",
method: "/bytebase.v1.SQLService/Query",
- user: "users/[email protected]",
+ actor: "users/[email protected]",
mcpDelegation: { correlationId: "corr-1" },
}),
create(AuditLogSchema, {
name: "auditLogs/2",
method: "/bytebase.v1.SQLService/Query",
- user: "users/[email protected]",
+ actor: "users/[email protected]",
}),
],
nextPageToken: "",
@@ -221,7 +436,7 @@ describe("AuditLogTable", () => {
create(AuditLogSchema, {
name: "auditLogs/1",
method: "/bytebase.v1.SQLService/Query",
- user: "users/[email protected]",
+ actor: "users/[email protected]",
mcpDelegation: {},
}),
],
@@ -277,7 +492,7 @@ describe("AuditLogTable", () => {
create(AuditLogSchema, {
name: "auditLogs/1",
method: "/bytebase.v1.SQLService/Query",
- user: "users/[email protected]",
+ actor: "users/[email protected]",
mcpDelegation: {
clientId: "bb_oauth_client",
correlationId: "8b1f0a1e-corr",
@@ -319,7 +534,7 @@ describe("AuditLogTable", () => {
create(AuditLogSchema, {
name: "auditLogs/1",
method: "/bytebase.v1.SQLService/Query",
- user: "users/[email protected]",
+ actor: "users/[email protected]",
mcpDelegation: {
correlationId: "8b1f0a1e-corr",
resource: "https://example.com/mcp",
diff --git a/frontend/src/components/AuditLogTable.tsx b/frontend/src/components/AuditLogTable.tsx
index 0007f7229d..3f32318020 100644
--- a/frontend/src/components/AuditLogTable.tsx
+++ b/frontend/src/components/AuditLogTable.tsx
@@ -32,8 +32,8 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
-import { Tooltip } from "@/components/ui/tooltip";
-import { usePlanFeature } from "@/hooks/useAppState";
+import { BlockTooltip, Tooltip } from "@/components/ui/tooltip";
+import { usePlanFeature, useWorkspaceResourceName } from "@/hooks/useAppState";
import { useColumnWidths } from "@/hooks/useColumnWidths";
import { PagedTableFooter } from "@/hooks/usePagedData";
import {
@@ -43,11 +43,12 @@ import {
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import {
- extractUserEmail,
getProjectIdPlanUidStageUidFromRolloutName,
planNamePrefix,
projectNamePrefix,
+ serviceAccountNamePrefix,
userNamePrefix,
+ workloadIdentityNamePrefix,
} from "@/stores/modules/v1/common";
import { getDateForPbTimestampProtoEs } from "@/types";
import { StatusSchema } from "@/types/proto-es/google/rpc/status_pb";
@@ -83,18 +84,37 @@ dayjs.extend(utc);
interface AuditLogFilter {
method?: string;
level?: AuditLog_Severity;
- userEmail?: string;
+ actor?: string;
createdTsAfter?: number;
createdTsBefore?: number;
}
+function uniqueValueOptions(options: ValueOption[]): ValueOption[] {
+ return [...new Map(options.map((option) => [option.value, option])).values()];
+}
+
function buildFilterString(filter: AuditLogFilter): string {
const parts: string[] = [];
if (filter.method) parts.push(`method == ${celString(filter.method)}`);
if (filter.level !== undefined)
parts.push(`severity == ${celString(AuditLog_Severity[filter.level])}`);
- if (filter.userEmail)
- parts.push(`user == ${celString(`${userNamePrefix}${filter.userEmail}`)}`);
+ if (filter.actor) {
+ const legacyUser = `${userNamePrefix}${filter.actor.slice(
+ filter.actor.indexOf("/") + 1
+ )}`;
+ const matchesLegacyUser =
+ filter.actor.startsWith(serviceAccountNamePrefix) ||
+ filter.actor.startsWith(workloadIdentityNamePrefix);
+ parts.push(
+ matchesLegacyUser
+ ? `(actor == ${celString(filter.actor)} || actor == ${celString(legacyUser)})`
+ : `actor == ${celString(
+ filter.actor.startsWith(userNamePrefix)
+ ? filter.actor
+ : `${userNamePrefix}${filter.actor}`
+ )}`
+ );
+ }
if (filter.createdTsAfter)
parts.push(
`create_time >= ${celString(dayjs(filter.createdTsAfter).utc().format())}`
@@ -111,7 +131,7 @@ function buildAuditLogFilter(params: SearchParams): AuditLogFilter {
const method = params.scopes.find((s) => s.id === "method")?.value;
if (method) filter.method = method;
const actor = params.scopes.find((s) => s.id === "actor")?.value;
- if (actor) filter.userEmail = actor;
+ if (actor) filter.actor = actor;
const level = params.scopes.find((s) => s.id === "level")?.value;
if (level)
filter.level = AuditLog_Severity[level as keyof typeof AuditLog_Severity];
@@ -266,20 +286,16 @@ function McpProvenanceDetail({
// none.
function AuditLogActorCell({ log }: Readonly<{ log: AuditLog }>) {
const { t } = useTranslation();
- const email = extractUserEmail(log.user);
return (
<div className="flex items-center gap-x-1.5">
- {email ? (
- // As a flex item the anchor is blockified, so `truncate` now ellipses
- // where the bare inline anchor used to hard-clip; `title` keeps the
- // full address reachable.
- <a
- href={`mailto:${email}`}
- title={email}
- className="text-accent hover:underline truncate min-w-0"
+ {log.actor ? (
+ <BlockTooltip
+ content={log.actor}
+ popupClassName="break-all"
+ render={<span className="min-w-0" />}
>
- {email}
- </a>
+ <span className="block truncate">{log.actor}</span>
+ </BlockTooltip>
) : (
<span>-</span>
)}
@@ -580,6 +596,36 @@ export function AuditLogTable({
}: AuditLogTableProps) {
const { t } = useTranslation();
const hasAuditLogFeature = usePlanFeature(PlanFeature.FEATURE_AUDIT_LOG);
+ const workspaceResourceName = useWorkspaceResourceName();
+ const projectAccountParent =
+ parent !== `${projectNamePrefix}-` && parent.startsWith(projectNamePrefix)
+ ? parent
+ : "";
+ const project = useAppStore((state) =>
+ projectAccountParent
+ ? state.projectsByName[projectAccountParent]
+ : undefined
+ );
+ const canListWorkspaceServiceAccounts = useAppStore((state) =>
+ workspaceResourceName
+ ? state.hasWorkspacePermission("bb.serviceAccounts.list")
+ : false
+ );
+ const canListWorkspaceWorkloadIdentities = useAppStore((state) =>
+ workspaceResourceName
+ ? state.hasWorkspacePermission("bb.workloadIdentities.list")
+ : false
+ );
+ const canListProjectServiceAccounts = useAppStore((state) =>
+ project
+ ? state.hasProjectPermission(project, "bb.serviceAccounts.list")
+ : false
+ );
+ const canListProjectWorkloadIdentities = useAppStore((state) =>
+ project
+ ? state.hasProjectPermission(project, "bb.workloadIdentities.list")
+ : false
+ );
const columns = useColumnDefs();
const { widths, totalWidth, onResizeStart } = useColumnWidths(columns);
@@ -752,18 +798,98 @@ export function AuditLogTable({
return "";
}, [filter, t]);
const listUsers = useAppStore((state) => state.listUsers);
- const searchUsers = useCallback(
+ const listServiceAccounts = useAppStore((state) => state.listServiceAccounts);
+ const listWorkloadIdentities = useAppStore(
+ (state) => state.listWorkloadIdentities
+ );
+ const searchActors = useCallback(
async (keyword: string): Promise<ValueOption[]> => {
+ const query = keyword.trim();
+ const pageSize = getDefaultPagination();
+ const accountParams = (parent: string, filter: string) => ({
+ parent,
+ pageSize,
+ showDeleted: false,
+ filter: { query: filter },
+ skipCache: true,
+ });
+
+ if (query.startsWith(serviceAccountNamePrefix)) {
+ const accountQuery = query.slice(serviceAccountNamePrefix.length);
+ const serviceAccounts = await Promise.all([
+ ...(workspaceResourceName && canListWorkspaceServiceAccounts
+ ? [
+ listServiceAccounts(
+ accountParams(workspaceResourceName, accountQuery)
+ ),
+ ]
+ : []),
+ ...(projectAccountParent && canListProjectServiceAccounts
+ ? [
+ listServiceAccounts(
+ accountParams(projectAccountParent, accountQuery)
+ ),
+ ]
+ : []),
+ ]);
+ return uniqueValueOptions(
+ serviceAccounts.flatMap((result) =>
+ result.serviceAccounts.map((account) => ({
+ value: account.name,
+ keywords: [account.email, account.title],
+ }))
+ )
+ );
+ }
+
+ if (query.startsWith(workloadIdentityNamePrefix)) {
+ const identityQuery = query.slice(workloadIdentityNamePrefix.length);
+ const workloadIdentities = await Promise.all([
+ ...(workspaceResourceName && canListWorkspaceWorkloadIdentities
+ ? [
+ listWorkloadIdentities(
+ accountParams(workspaceResourceName, identityQuery)
+ ),
+ ]
+ : []),
+ ...(projectAccountParent && canListProjectWorkloadIdentities
+ ? [
+ listWorkloadIdentities(
+ accountParams(projectAccountParent, identityQuery)
+ ),
+ ]
+ : []),
+ ]);
+ return uniqueValueOptions(
+ workloadIdentities.flatMap((result) =>
+ result.workloadIdentities.map((identity) => ({
+ value: identity.name,
+ keywords: [identity.email, identity.title],
+ }))
+ )
+ );
+ }
+
const { users } = await listUsers({
- pageSize: getDefaultPagination(),
- filter: keyword.trim() ? { query: keyword } : undefined,
+ pageSize,
+ filter: query ? { query } : undefined,
});
- return users.map((u) => ({
- value: u.email,
- keywords: [u.email, u.title],
+ return users.map((user) => ({
+ value: user.name,
+ keywords: [user.email, user.title],
}));
},
- [listUsers]
+ [
+ listUsers,
+ listServiceAccounts,
+ listWorkloadIdentities,
+ workspaceResourceName,
+ projectAccountParent,
+ canListWorkspaceServiceAccounts,
+ canListWorkspaceWorkloadIdentities,
+ canListProjectServiceAccounts,
+ canListProjectWorkloadIdentities,
+ ]
);
const scopeOptions = useMemo((): ScopeOption[] => {
@@ -772,7 +898,7 @@ export function AuditLogTable({
id: "actor",
title: t("audit-log.advanced-search.scope.actor.title"),
description: t("audit-log.advanced-search.scope.actor.description"),
- onSearch: searchUsers,
+ onSearch: searchActors,
},
{
id: "method",
@@ -795,7 +921,7 @@ export function AuditLogTable({
})),
},
];
- }, [t, searchUsers]);
+ }, [t, searchActors]);
const pageSizeOptions = getPageSizeOptions();
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index f27a657254..1079c115fc 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -79,7 +79,7 @@
"advanced-search": {
"scope": {
"actor": {
- "description": "Search by the audit log actor",
+ "description": "Search users by email. Prefix with serviceAccounts/ or workloadIdentities/ to search those actors.",
"title": "Actor"
},
"level": {
@@ -153,6 +153,7 @@
"continue-with-email": "Continue with email",
"continue-with-idp": "Continue with {{idp}}",
"email-code-tab": "Email Code",
+ "failed": "Sign-in failed",
"failed-to-send-code": "Failed to send verification code. {{error}}",
"forget-password": "Forgot your password?",
"invited-email": "You've been invited. Please sign in with {{email}}",
@@ -2880,7 +2881,7 @@
"select-role_other": "Select roles",
"service-account": "Service Account",
"service-accounts": "Service Accounts",
- "service-key-copied": "Service Key copied to clipboard, please keep it in secret.",
+ "service-key-reset-and-copied": "Service key reset and copied",
"show-inactive": "Show inactive accounts",
"table": {
"account": "Account",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index fede7462a0..f45b7f561e 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -79,7 +79,7 @@
"advanced-search": {
"scope": {
"actor": {
- "description": "Buscar por el actor del registro de auditoría",
+ "description": "Busca usuarios por correo electrónico. Usa el prefijo serviceAccounts/ o workloadIdentities/ para buscar esos actores.",
"title": "Actor"
},
"level": {
@@ -153,6 +153,7 @@
"continue-with-email": "Continuar con email",
"continue-with-idp": "Continuar con {{idp}}",
"email-code-tab": "Código por email",
+ "failed": "No se pudo iniciar sesión",
"failed-to-send-code": "No se pudo enviar el código de verificación. {{error}}",
"forget-password": "¿Olvidaste tu contraseña?",
"invited-email": "Has sido invitado. Inicia sesión con {{email}}",
@@ -2880,7 +2881,7 @@
"select-role_other": "Seleccionar roles",
"service-account": "Cuenta de Servicio",
"service-accounts": "Cuentas de Servicio",
- "service-key-copied": "Clave de Servicio copiada al portapapeles, por favor manténgala en secreto.",
+ "service-key-reset-and-copied": "Clave de servicio restablecida y copiada",
"show-inactive": "Mostrar cuentas inactivas",
"table": {
"account": "Cuenta",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index a4b7fccfd0..ba355e548e 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -79,7 +79,7 @@
"advanced-search": {
"scope": {
"actor": {
- "description": "監査ログの操作者で検索",
+ "description": "メールアドレスでユーザーを検索します。サービスアカウントまたはワークロード ID を検索するには、serviceAccounts/ または workloadIdentities/ を付けます。",
"title": "操作者"
},
"level": {
@@ -153,6 +153,7 @@
"continue-with-email": "メールで続行",
"continue-with-idp": "{{idp}} で続行",
"email-code-tab": "メール認証コード",
+ "failed": "サインインに失敗しました",
"failed-to-send-code": "認証コードの送信に失敗しました。{{error}}",
"forget-password": "パスワードを忘れましたか?",
"invited-email": "招待されました。{{email}} でログインしてください",
@@ -2880,7 +2881,7 @@
"select-role_other": "ロールを選択",
"service-account": "サービスアカウント",
"service-accounts": "サービスアカウント",
- "service-key-copied": "サービスキーはコピーされています。公開しないでください",
+ "service-key-reset-and-copied": "サービスキーをリセットしてコピーしました",
"show-inactive": "非アクティブなアカウントを表示",
"table": {
"account": "アカウント",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 1b0a601375..801e120db6 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -79,7 +79,7 @@
"advanced-search": {
"scope": {
"actor": {
- "description": "Tìm kiếm theo người thực hiện",
+ "description": "Tìm người dùng theo email. Thêm tiền tố serviceAccounts/ hoặc workloadIdentities/ để tìm các tác nhân đó.",
"title": "Người thực hiện"
},
"level": {
@@ -153,6 +153,7 @@
"continue-with-email": "Tiếp tục bằng email",
"continue-with-idp": "Tiếp tục bằng {{idp}}",
"email-code-tab": "Mã qua email",
+ "failed": "Đăng nhập thất bại",
"failed-to-send-code": "Không gửi được mã xác minh. {{error}}",
"forget-password": "Quên mật khẩu?",
"invited-email": "Bạn đã được mời. Vui lòng đăng nhập bằng {{email}}",
@@ -2880,7 +2881,7 @@
"select-role_other": "Chọn vai trò",
"service-account": "Tài khoản dịch vụ",
"service-accounts": "Tài khoản dịch vụ",
- "service-key-copied": "Khóa Dịch vụ đã được sao chép vào khay nhớ tạm, vui lòng giữ bí mật.",
+ "service-key-reset-and-copied": "Đã đặt lại và sao chép khóa dịch vụ",
"show-inactive": "Hiển thị tài khoản không hoạt động",
"table": {
"account": "Tài khoản",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index e49517d7cf..9d34c3c0b2 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -79,7 +79,7 @@
"advanced-search": {
"scope": {
"actor": {
- "description": "按审计日志操作者搜索",
+ "description": "按邮箱搜索用户。使用 serviceAccounts/ 或 workloadIdentities/ 前缀搜索这些操作者。",
"title": "操作者"
},
"level": {
@@ -153,6 +153,7 @@
"continue-with-email": "使用邮箱继续",
"continue-with-idp": "使用 {{idp}} 继续",
"email-code-tab": "邮箱验证码",
+ "failed": "登录失败",
"failed-to-send-code": "发送验证码失败。{{error}}",
"forget-password": "忘记密码?",
"invited-email": "您已被邀请,请使用 {{email}} 登录",
@@ -2880,7 +2881,7 @@
"select-role_other": "选择角色",
"service-account": "服务账号",
"service-accounts": "服务账号",
- "service-key-copied": "Service Key 已复制,请勿泄漏",
+ "service-key-reset-and-copied": "Service Key 已重置并复制",
"show-inactive": "显示已停用账户",
"table": {
"account": "账户",
diff --git a/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.test.tsx b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.test.tsx
index e5a5e3770c..8ab2fc504c 100644
--- a/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.test.tsx
+++ b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.test.tsx
@@ -40,6 +40,7 @@ vi.mock("@/stores/app", () => {
batchGetOrFetchUsers: mocks.batchGetOrFetchUsers,
batchGetOrFetchGroups: mocks.batchGetOrFetchGroups,
notify: mocks.notify,
+ workspaceResourceName: () => "workspaces/default",
getUserByIdentifier: (identifier: string) =>
mocks.usersByBinding[identifier],
getGroupByIdentifier: (identifier: string) =>
@@ -63,6 +64,8 @@ vi.mock("@/components/AccountMultiSelect", () => ({
disabled?: boolean;
excludeAccounts?: string[];
placeholder?: string;
+ accountParents: string[];
+ includeSpecialAccounts?: boolean;
}) => {
mocks.pickerProps(props);
return createElement(
@@ -219,6 +222,8 @@ const lastPickerProps = () =>
value: string[];
excludeAccounts?: string[];
placeholder?: string;
+ accountParents: string[];
+ includeSpecialAccounts?: boolean;
};
const writtenBindings = () => {
@@ -462,6 +467,11 @@ describe("SavedQueryGrantEditor", () => {
expect(lastPickerProps().placeholder).toBe(
"sql-editor.saved-query-share.add-people"
);
+ expect(lastPickerProps().accountParents).toEqual([
+ "workspaces/default",
+ "projects/proj1",
+ ]);
+ expect(lastPickerProps().includeSpecialAccounts).toBe(false);
unmount();
});
diff --git a/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx
index 21095c7e7d..98a500d848 100644
--- a/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx
+++ b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx
@@ -82,6 +82,13 @@ export function SavedQueryGrantEditor({ savedQuery, canManage }: Props) {
const batchGetOrFetchGroups = useAppStore((s) => s.batchGetOrFetchGroups);
const notify = useAppStore((s) => s.notify);
const currentUserEmail = useAppStore((s) => s.currentUser?.email);
+ const workspaceResourceName = useAppStore((s) => s.workspaceResourceName());
+ const accountParents = useMemo(
+ () => [
+ ...new Set([workspaceResourceName, savedQuery.project].filter(Boolean)),
+ ],
+ [workspaceResourceName, savedQuery.project]
+ );
const [policy, setPolicy] = useState<SavedQueryPolicy | undefined>();
const [inviteLevel, setInviteLevel] = useState<SavedQueryBinding_Level>(
@@ -342,6 +349,8 @@ export function SavedQueryGrantEditor({ savedQuery, canManage }: Props) {
onChange={stagePending}
disabled={saving}
excludeAccounts={excludeAccounts}
+ accountParents={accountParents}
+ includeSpecialAccounts={false}
placeholder={t("sql-editor.saved-query-share.add-people")}
/>
{/* The commit controls exist only while an add is in progress —
diff --git a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx
index 4a2a2e6c28..06702b978e 100644
--- a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx
+++ b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx
@@ -35,6 +35,7 @@ const mocks = vi.hoisted(() => ({
(_resource: { table?: string }): string[] => []
),
routerBack: vi.fn(),
+ accountSelectProps: { value: undefined as { accountParents: string[] } | undefined },
}));
vi.mock("react-i18next", () => ({
@@ -52,16 +53,21 @@ vi.mock("@/components/AccountMultiSelect", () => ({
AccountMultiSelect: ({
value,
onChange,
+ accountParents,
}: {
value: string[];
onChange: (value: string[]) => void;
- }) => (
- <button
- data-testid="account-multi-select"
- onClick={() => onChange([...value, "users/alice"])}
- type="button"
- />
- ),
+ accountParents: string[];
+ }) => {
+ mocks.accountSelectProps.value = { accountParents };
+ return (
+ <button
+ data-testid="account-multi-select"
+ onClick={() => onChange([...value, "users/alice"])}
+ type="button"
+ />
+ );
+ },
}));
vi.mock("@/components/DatabaseResourceSelector", () => ({
@@ -175,12 +181,14 @@ vi.mock("@/stores/app", () => ({
projectsByName: Record<string, unknown>;
settingsByName: Record<string, unknown>;
hasFeature: () => boolean;
+ workspaceResourceName: () => string;
}) => unknown
) =>
selector({
projectsByName: {},
settingsByName: {},
hasFeature: () => true,
+ workspaceResourceName: () => "workspaces/default",
}),
{
getState: () => ({
@@ -311,6 +319,17 @@ describe("ProjectMaskingExemptionCreatePage builder (BYT-9788)", () => {
unmount();
});
+ test("discovers special accounts in the workspace and project scopes", () => {
+ const { unmount } = render();
+
+ expect(mocks.accountSelectProps.value?.accountParents).toEqual([
+ "workspaces/default",
+ "projects/proj1",
+ ]);
+
+ unmount();
+ });
+
test("SELECT mode: wraps the OR-group so the expiration binds to every resource", async () => {
const { container, unmount } = render();
await flush();
diff --git a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.tsx b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.tsx
index d97acebb29..5f51e14802 100644
--- a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.tsx
+++ b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.tsx
@@ -48,8 +48,13 @@ export function ProjectMaskingExemptionCreatePage({
}) {
const { t } = useTranslation();
const projectsByName = useAppStore((s) => s.projectsByName);
+ const workspaceResourceName = useAppStore((s) => s.workspaceResourceName());
const projectName = `${projectNamePrefix}${projectId}`;
+ const accountParents = useMemo(
+ () => [...new Set([workspaceResourceName, projectName].filter(Boolean))],
+ [workspaceResourceName, projectName]
+ );
// subscribe to re-render on project cache change
void projectsByName;
const project = useProjectByName(projectName);
@@ -301,7 +306,11 @@ export function ProjectMaskingExemptionCreatePage({
<CircleHelp className="size-4 textinfolabel" />
</Tooltip>
</div>
- <AccountMultiSelect value={memberList} onChange={setMemberList} />
+ <AccountMultiSelect
+ value={memberList}
+ onChange={setMemberList}
+ accountParents={accountParents}
+ />
</div>
</div>
</div>
diff --git a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx
index 12baa25212..7d610050bb 100644
--- a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx
+++ b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx
@@ -33,6 +33,7 @@ const mocks = vi.hoisted(() => {
featureToRef: vi.fn(() => ({ value: true })),
getOrFetchPolicyByParentAndType: vi.fn(),
upsertPolicy: vi.fn(),
+ accountSelectProps: { value: undefined as { accountParents: string[] } | undefined },
};
});
@@ -84,16 +85,21 @@ vi.mock("@/components/AccountMultiSelect", () => ({
AccountMultiSelect: ({
value,
onChange,
+ accountParents,
}: {
value: string[];
onChange: (value: string[]) => void;
- }) => (
- <button
- data-testid="account-multi-select"
- onClick={() => onChange([...value, "users/alice"])}
- type="button"
- />
- ),
+ accountParents: string[];
+ }) => {
+ mocks.accountSelectProps.value = { accountParents };
+ return (
+ <button
+ data-testid="account-multi-select"
+ onClick={() => onChange([...value, "users/alice"])}
+ type="button"
+ />
+ );
+ },
}));
vi.mock("@/components/DatabaseResourceSelector", () => ({
@@ -238,11 +244,13 @@ vi.mock("@/stores/app", () => ({
selector: (state: {
settingsByName: Record<string, unknown>;
hasInstanceFeature: () => boolean;
+ workspaceResourceName: () => string;
}) => unknown
) =>
selector({
settingsByName: {},
hasInstanceFeature: () => mocks.featureToRef().value,
+ workspaceResourceName: () => "workspaces/default",
}),
{
getState: () => ({
@@ -413,6 +421,17 @@ describe("GrantAccessDialog", () => {
unmount();
});
+ test("discovers special accounts in the workspace and project scopes", () => {
+ const { unmount } = renderGrantAccessDialog();
+
+ expect(mocks.accountSelectProps.value?.accountParents).toEqual([
+ "workspaces/default",
+ "projects/proj1",
+ ]);
+
+ unmount();
+ });
+
test("preserves selected scope when switching from select to expression mode", async () => {
const { container, unmount } = renderGrantAccessDialog();
await flush();
diff --git a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx
index 5aa0979ffc..81c5612352 100644
--- a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx
+++ b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx
@@ -71,6 +71,11 @@ export function GrantAccessDialog({
onDismiss,
}: GrantAccessDialogProps) {
const { t } = useTranslation();
+ const workspaceResourceName = useAppStore((s) => s.workspaceResourceName());
+ const accountParents = useMemo(
+ () => [...new Set([workspaceResourceName, projectName].filter(Boolean))],
+ [workspaceResourceName, projectName]
+ );
const hasRequiredFeature = useAppStore((s) =>
s.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING, instance)
@@ -506,7 +511,11 @@ export function GrantAccessDialog({
<CircleHelp className="size-4 textinfolabel" />
</Tooltip>
</div>
- <AccountMultiSelect value={memberList} onChange={setMemberList} />
+ <AccountMultiSelect
+ value={memberList}
+ onChange={setMemberList}
+ accountParents={accountParents}
+ />
</div>
</div>
diff --git a/frontend/src/routes/workspace/MembersPage.test.tsx b/frontend/src/routes/workspace/MembersPage.test.tsx
index 73a4b2a97d..dfd305a21d 100644
--- a/frontend/src/routes/workspace/MembersPage.test.tsx
+++ b/frontend/src/routes/workspace/MembersPage.test.tsx
@@ -24,7 +24,7 @@ const {
mockUpdateProjectIamPolicy: vi.fn(),
maximumRoleExpirationSeconds: { value: undefined as number | undefined },
maximumRequestExpirationSeconds: { value: undefined as number | undefined },
- accountSelectProps: { value: undefined as { accountParents?: string[] } | undefined },
+ accountSelectProps: { value: undefined as { accountParents: string[] } | undefined },
}));
vi.mock("@/components/AccountMultiSelect", () => ({
@@ -33,7 +33,7 @@ vi.mock("@/components/AccountMultiSelect", () => ({
accountParents,
}: {
onChange: (members: string[]) => void;
- accountParents?: string[];
+ accountParents: string[];
}) => {
accountSelectProps.value = { accountParents };
return createElement(
diff --git a/frontend/src/routes/workspace/ServiceAccountsPage.test.tsx b/frontend/src/routes/workspace/ServiceAccountsPage.test.tsx
new file mode 100644
index 0000000000..ecbbd2bd4e
--- /dev/null
+++ b/frontend/src/routes/workspace/ServiceAccountsPage.test.tsx
@@ -0,0 +1,367 @@
+import type { ButtonHTMLAttributes, ReactNode } from "react";
+import { act, createElement, useState } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const {
+ mockPushNotification,
+ mockUpdateCache,
+ mockUpdateServiceAccount,
+ mockWriteTextToClipboard,
+} = vi.hoisted(() => ({
+ mockPushNotification: vi.fn(),
+ mockUpdateCache: vi.fn(),
+ mockUpdateServiceAccount: vi.fn(),
+ mockWriteTextToClipboard: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/components/PermissionGuard", () => ({
+ PermissionGuard: ({ children }: { children: ReactNode }) => children,
+}));
+
+vi.mock("@/components/ProjectPageLayout", () => ({
+ ProjectPageLayout: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ ProjectPageToolbar: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+}));
+
+vi.mock("@/components/RoleSelect", () => ({
+ RoleSelect: () => null,
+}));
+
+vi.mock("@/components/UserCell", () => ({
+ UserCell: ({ title, subtitle, badges }: { title: string; subtitle: string; badges: ReactNode }) =>
+ createElement("div", {}, title, subtitle, badges),
+}));
+
+vi.mock("@/components/WorkspacePageLayout", () => ({
+ WorkspacePageLayout: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ WorkspacePageToolbar: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+}));
+
+vi.mock("@/components/ui/popover", async () => {
+ const { createContext, createElement, useContext } = await import("react");
+ const { createPortal } = await import("react-dom");
+ const { getLayerRoot } = await import("@/components/ui/layer");
+ const Context = createContext({
+ open: false,
+ onOpenChange: (_open: boolean) => {},
+ });
+ return {
+ Popover: ({
+ open,
+ onOpenChange,
+ children,
+ }: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ children: ReactNode;
+ }) =>
+ createElement(Context.Provider, { value: { open, onOpenChange } }, children),
+ PopoverTrigger: ({
+ children,
+ onClick,
+ }: {
+ children: ReactNode;
+ onClick?: React.MouseEventHandler<HTMLButtonElement>;
+ }) => {
+ const { open, onOpenChange } = useContext(Context);
+ return createElement(
+ "button",
+ {
+ onClick: (event: React.MouseEvent<HTMLButtonElement>) => {
+ onClick?.(event);
+ onOpenChange(!open);
+ },
+ },
+ children
+ );
+ },
+ PopoverContent: ({ children }: { children: ReactNode }) => {
+ const { open } = useContext(Context);
+ return open
+ ? createPortal(
+ createElement("div", { "data-testid": "reset-popover" }, children),
+ getLayerRoot("overlay")
+ )
+ : null;
+ },
+ };
+});
+
+vi.mock("@/components/ui/badge", () => ({
+ Badge: ({ children }: { children: ReactNode }) =>
+ createElement("span", {}, children),
+}));
+
+vi.mock("@/components/ui/button", () => ({
+ Button: ({
+ children,
+ appearance: _appearance,
+ size: _size,
+ variant: _variant,
+ ...props
+ }: ButtonHTMLAttributes<HTMLButtonElement> & {
+ appearance?: string;
+ size?: string;
+ variant?: string;
+ }) => createElement("button", props, children),
+}));
+
+vi.mock("@/components/ui/checkbox", () => ({
+ Checkbox: () => createElement("input", { type: "checkbox" }),
+}));
+
+vi.mock("@/components/ui/copy-button", () => ({
+ CopyButton: () => null,
+}));
+
+vi.mock("@/components/ui/form", () => ({
+ FormField: ({ children }: { children: ReactNode }) => children,
+}));
+
+vi.mock("@/components/ui/input", () => ({
+ Input: () => createElement("input"),
+}));
+
+vi.mock("@/components/ui/sheet", () => ({
+ Sheet: () => null,
+ SheetBody: () => null,
+ SheetContent: () => null,
+ SheetFooter: () => null,
+ SheetHeader: () => null,
+ SheetTitle: () => null,
+}));
+
+vi.mock("@/components/ui/table", () => ({
+ Table: ({ children }: { children: ReactNode }) => createElement("table", {}, children),
+ TableBody: ({ children }: { children: ReactNode }) => createElement("tbody", {}, children),
+ TableCell: ({ children, ...props }: { children: ReactNode }) =>
+ createElement("td", props, children),
+ TableHead: ({ children }: { children: ReactNode }) => createElement("th", {}, children),
+ TableHeader: ({ children }: { children: ReactNode }) => createElement("thead", {}, children),
+ TableRow: ({ children, ...props }: { children: ReactNode }) =>
+ createElement("tr", props, children),
+}));
+
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: ReactNode }) => children,
+}));
+
+vi.mock("@/hooks/usePagedData", () => ({
+ PagedTableFooter: () => null,
+ usePagedData: () => {
+ const [dataList, setDataList] = useState([
+ {
+ name: "serviceAccounts/[email protected]",
+ title: "bot",
+ email: "[email protected]",
+ state: 1,
+ serviceKey: "",
+ },
+ ]);
+ return {
+ dataList,
+ hasMore: false,
+ isFetchingMore: false,
+ isLoading: false,
+ loadMore: vi.fn(),
+ onPageSizeChange: vi.fn(),
+ pageSize: 20,
+ pageSizeOptions: [20],
+ removeCache: vi.fn(),
+ updateCache: (accounts: typeof dataList) => {
+ mockUpdateCache(accounts);
+ setDataList(accounts);
+ },
+ };
+ },
+}));
+
+vi.mock("@/hooks/useProjectByName", () => ({
+ useProjectByName: () => undefined,
+}));
+
+vi.mock("@/lib/clipboard", () => ({
+ writeTextToClipboard: mockWriteTextToClipboard,
+}));
+
+vi.mock("@/lib/utils", () => ({ cn: (...classes: unknown[]) => classes.filter(Boolean).join(" ") }));
+
+vi.mock("@/stores", () => ({ pushNotification: mockPushNotification }));
+
+vi.mock("@/stores/app", () => {
+ const state = {
+ createServiceAccount: vi.fn(),
+ deleteServiceAccount: vi.fn(),
+ getProjectIamPolicy: vi.fn(),
+ listServiceAccounts: vi.fn(),
+ patchWorkspaceIamPolicy: vi.fn(),
+ projectsByName: {},
+ undeleteServiceAccount: vi.fn(),
+ updateProjectIamPolicy: vi.fn(),
+ updateServiceAccount: mockUpdateServiceAccount,
+ workspaceResourceName: () => "workspaces/-",
+ };
+ return {
+ useAppStore: Object.assign(
+ <T,>(selector: (store: typeof state) => T) => selector(state),
+ { getState: () => state }
+ ),
+ };
+});
+
+vi.mock("@/stores/modules/v1/common", () => ({ projectNamePrefix: "projects/" }));
+
+vi.mock("@/types", () => ({
+ getServiceAccountNameInBinding: (email: string) => `serviceAccount:${email}`,
+ getServiceAccountSuffix: () => "service.bytebase.com",
+}));
+
+vi.mock("@/utils", () => ({
+ hasProjectPermissionV2: () => true,
+ hasWorkspacePermissionV2: () => true,
+}));
+
+import { ServiceAccountsPage } from "./ServiceAccountsPage";
+
+describe("ServiceAccountsPage", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ mockUpdateServiceAccount.mockResolvedValue({
+ name: "serviceAccounts/[email protected]",
+ title: "bot",
+ email: "[email protected]",
+ state: 1,
+ serviceKey: "new-service-key",
+ });
+ mockWriteTextToClipboard.mockResolvedValue(true);
+ });
+
+ afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ it("confirms and acknowledges a reset service key in the action", async () => {
+ await act(async () => root.render(createElement(ServiceAccountsPage)));
+
+ const resetButton = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("tbody button")
+ ).find(
+ (button) =>
+ button.textContent === "settings.members.reset-service-key"
+ );
+ expect(resetButton).toBeDefined();
+
+ await act(async () => resetButton?.click());
+ const popover = document.querySelector('[data-testid="reset-popover"]');
+ expect(popover).not.toBeNull();
+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();
+ expect(popover?.textContent).toContain(
+ "settings.members.reset-service-key-alert"
+ );
+ expect(container.querySelector("tbody")?.textContent).not.toContain(
+ "settings.members.reset-service-key-alert"
+ );
+
+ const confirmButton = Array.from(
+ popover?.querySelectorAll<HTMLButtonElement>("button") ?? []
+ ).find((button) => button.textContent === "common.reset");
+ expect(confirmButton).toBeDefined();
+
+ vi.useFakeTimers();
+ await act(async () => confirmButton?.click());
+
+ expect(mockUpdateServiceAccount).toHaveBeenCalledOnce();
+ expect(mockWriteTextToClipboard).toHaveBeenCalledWith("new-service-key");
+ expect(document.querySelector('[data-testid="reset-popover"]')).toBeNull();
+ expect(mockUpdateCache).toHaveBeenCalledWith([
+ expect.objectContaining({ serviceKey: "" }),
+ ]);
+ expect(mockPushNotification).toHaveBeenCalledWith(
+ expect.objectContaining({ style: "SUCCESS", title: "common.copied" })
+ );
+ expect(container.querySelector("tbody")?.textContent).toContain(
+ "settings.members.service-key-reset-and-copied"
+ );
+
+ await act(async () => vi.advanceTimersByTime(2000));
+ expect(container.querySelector("tbody")?.textContent).toContain(
+ "settings.members.reset-service-key"
+ );
+ expect(container.querySelector("tbody")?.textContent).not.toContain(
+ "settings.members.service-key-reset-and-copied"
+ );
+ });
+
+ it("keeps the new key available to copy when automatic copying fails", async () => {
+ mockWriteTextToClipboard.mockResolvedValue(false);
+ await act(async () => root.render(createElement(ServiceAccountsPage)));
+
+ const resetButton = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("tbody button")
+ ).find(
+ (button) =>
+ button.textContent === "settings.members.reset-service-key"
+ );
+ expect(resetButton).toBeDefined();
+ await act(async () => resetButton?.click());
+ const popover = document.querySelector('[data-testid="reset-popover"]');
+ const confirmButton = Array.from(
+ popover?.querySelectorAll<HTMLButtonElement>("button") ?? []
+ ).find((button) => button.textContent === "common.reset");
+ await act(async () => confirmButton?.click());
+
+ expect(mockUpdateCache).toHaveBeenCalledWith([
+ expect.objectContaining({ serviceKey: "new-service-key" }),
+ ]);
+ expect(mockPushNotification).toHaveBeenCalledWith(
+ expect.objectContaining({ style: "CRITICAL", title: "common.copy-failed" })
+ );
+ expect(container.querySelector("tbody")?.textContent).toContain(
+ "settings.members.copy-service-key"
+ );
+ });
+
+ it("closes the confirmation popover without resetting on cancel", async () => {
+ await act(async () => root.render(createElement(ServiceAccountsPage)));
+ const resetButton = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("tbody button")
+ ).find(
+ (button) =>
+ button.textContent === "settings.members.reset-service-key"
+ );
+ await act(async () => resetButton?.click());
+
+ const popover = document.querySelector('[data-testid="reset-popover"]');
+ const cancelButton = Array.from(
+ popover?.querySelectorAll<HTMLButtonElement>("button") ?? []
+ ).find((button) => button.textContent === "common.cancel");
+ await act(async () => cancelButton?.click());
+
+ expect(document.querySelector('[data-testid="reset-popover"]')).toBeNull();
+ expect(mockUpdateServiceAccount).not.toHaveBeenCalled();
+ expect(container.querySelector("tbody")?.textContent).toContain(
+ "settings.members.reset-service-key"
+ );
+ });
+});
diff --git a/frontend/src/routes/workspace/ServiceAccountsPage.tsx b/frontend/src/routes/workspace/ServiceAccountsPage.tsx
index 2e8bee440f..46096ceb0b 100644
--- a/frontend/src/routes/workspace/ServiceAccountsPage.tsx
+++ b/frontend/src/routes/workspace/ServiceAccountsPage.tsx
@@ -1,7 +1,7 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
-import { Copy, KeyRound, Plus, Trash2, Undo2 } from "lucide-react";
-import { useCallback, useMemo, useRef, useState } from "react";
+import { Check, Copy, KeyRound, Plus, Trash2, Undo2 } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { PermissionGuard } from "@/components/PermissionGuard";
import {
@@ -16,6 +16,11 @@ import { Checkbox } from "@/components/ui/checkbox";
import { CopyButton } from "@/components/ui/copy-button";
import { FormField } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
import {
Sheet,
SheetBody,
@@ -119,44 +124,113 @@ function ServiceAccountTable({
const [resetConfirmSa, setResetConfirmSa] = useState<
ServiceAccount | undefined
>();
- const [copiedKeys, setCopiedKeys] = useState<Set<string>>(new Set());
+ const [isResetting, setIsResetting] = useState(false);
+ const [keyFeedback, setKeyFeedback] = useState<Map<string, "reset" | "copy">>(
+ new Map()
+ );
+ const copiedKeyTimers = useRef(
+ new Map<string, ReturnType<typeof setTimeout>>()
+ );
+
+ useEffect(
+ () => () => {
+ for (const timer of copiedKeyTimers.current.values()) {
+ clearTimeout(timer);
+ }
+ },
+ []
+ );
+
+ const markKeyActionComplete = (name: string, action: "reset" | "copy") => {
+ setKeyFeedback((prev) => new Map(prev).set(name, action));
+ clearTimeout(copiedKeyTimers.current.get(name));
+ copiedKeyTimers.current.set(
+ name,
+ setTimeout(() => {
+ setKeyFeedback((prev) => {
+ const next = new Map(prev);
+ next.delete(name);
+ return next;
+ });
+ copiedKeyTimers.current.delete(name);
+ }, 2000)
+ );
+ };
+
+ const redactedServiceAccount = (sa: ServiceAccount) =>
+ create(ServiceAccountSchema, { ...sa, serviceKey: "" });
const handleResetKey = async (sa: ServiceAccount) => {
- setResetConfirmSa(undefined);
+ setIsResetting(true);
try {
const updated = await updateServiceAccount(
{ name: sa.name },
create(FieldMaskSchema, { paths: ["service_key"] })
);
- onUpdated(updated);
- if (
- updated.serviceKey &&
- (await writeTextToClipboard(updated.serviceKey))
- ) {
- setCopiedKeys((prev) => new Set(prev).add(updated.name));
+ setResetConfirmSa(undefined);
+ const copied =
+ !!updated.serviceKey &&
+ (await writeTextToClipboard(updated.serviceKey));
+ if (copied) {
+ onUpdated(redactedServiceAccount(updated));
+ markKeyActionComplete(updated.name, "reset");
pushNotification({
module: "bytebase",
- style: "INFO",
- title: t("settings.members.service-key-copied"),
+ style: "SUCCESS",
+ title: t("common.copied"),
});
+ return;
}
+
+ onUpdated(updated);
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.copy-failed"),
+ });
} catch {
// error shown by store
+ } finally {
+ setIsResetting(false);
}
};
const handleCopyKey = async (sa: ServiceAccount) => {
- if (!(await writeTextToClipboard(sa.serviceKey))) return;
- setCopiedKeys((prev) => new Set(prev).add(sa.name));
+ if (!(await writeTextToClipboard(sa.serviceKey))) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.copy-failed"),
+ });
+ return;
+ }
+ onUpdated(redactedServiceAccount(sa));
+ markKeyActionComplete(sa.name, "copy");
pushNotification({
module: "bytebase",
- style: "INFO",
- title: t("settings.members.service-key-copied"),
+ style: "SUCCESS",
+ title: t("common.copied"),
});
};
const renderKeyAction = (sa: ServiceAccount) => {
- if (sa.serviceKey && !copiedKeys.has(sa.name)) {
+ const feedback = keyFeedback.get(sa.name);
+ if (feedback) {
+ return (
+ <Button
+ appearance="outline"
+ size="xs"
+ disabled
+ className="text-success disabled:opacity-100"
+ >
+ <Check className="h-3 w-3 mr-1" />
+ {feedback === "reset"
+ ? t("settings.members.service-key-reset-and-copied")
+ : t("common.copied")}
+ </Button>
+ );
+ }
+ if (sa.serviceKey) {
return (
<Button
appearance="outline"
@@ -171,47 +245,50 @@ function ServiceAccountTable({
</Button>
);
}
- if (resetConfirmSa?.name === sa.name) {
- return (
- <div className="flex items-center gap-x-1">
- <span className="text-xs text-error">
- {t("settings.members.reset-service-key-alert")}
- </span>
- <Button
- variant="destructive"
- size="xs"
- onClick={(e) => {
- e.stopPropagation();
- handleResetKey(sa);
- }}
- >
- {t("common.reset")}
- </Button>
- <Button
- appearance="outline"
- size="xs"
- onClick={(e) => {
- e.stopPropagation();
- setResetConfirmSa(undefined);
- }}
- >
- {t("common.cancel")}
- </Button>
- </div>
- );
- }
return (
- <Button
- appearance="outline"
- size="xs"
- onClick={(e) => {
- e.stopPropagation();
- setResetConfirmSa(sa);
+ <Popover
+ open={resetConfirmSa?.name === sa.name}
+ onOpenChange={(open) => {
+ if (!isResetting) setResetConfirmSa(open ? sa : undefined);
}}
>
- <KeyRound className="h-3 w-3 mr-1" />
- {t("settings.members.reset-service-key")}
- </Button>
+ <PopoverTrigger
+ render={<Button appearance="outline" size="xs" />}
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ <KeyRound className="h-3 w-3 mr-1" />
+ {t("settings.members.reset-service-key")}
+ </PopoverTrigger>
+ <PopoverContent
+ aria-label={t("settings.members.reset-service-key")}
+ className="w-80 max-w-[calc(100vw-2rem)]"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ <p className="text-control-light">
+ {t("settings.members.reset-service-key-alert")}
+ </p>
+ <div className="mt-3 flex justify-end gap-x-2">
+ <Button
+ appearance="outline"
+ size="sm"
+ disabled={isResetting}
+ onClick={() => setResetConfirmSa(undefined)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ size="sm"
+ disabled={isResetting}
+ onClick={() => void handleResetKey(sa)}
+ >
+ {t("common.reset")}
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
);
};
diff --git a/frontend/src/types/proto-es/v1/audit_log_service_pb.d.ts b/frontend/src/types/proto-es/v1/audit_log_service_pb.d.ts
index 2649447770..844c1cd279 100644
--- a/frontend/src/types/proto-es/v1/audit_log_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/audit_log_service_pb.d.ts
@@ -33,7 +33,8 @@ export declare type SearchAuditLogsRequest = Message<"bytebase.v1.SearchAuditLog
* - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
* - resource: the resource the entry is about, support "==" operator.
* - severity: support "==" operator, check Severity enum in AuditLog message for values.
- * - user: the actor, should in "users/{email}" format, support "==" operator.
+ * - actor: the actor, in users/{email}, serviceAccounts/{email}, or
+ * workloadIdentities/{email} format. Support "==" operator.
* - create_time: support ">=" and "<=" operator.
* - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
* - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
@@ -41,7 +42,7 @@ export declare type SearchAuditLogsRequest = Message<"bytebase.v1.SearchAuditLog
* For example:
* - filter = "method == '/bytebase.v1.SQLService/Query'"
* - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
- * - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
+ * - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && actor == 'users/[email protected]'"
* - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
* - filter = "mcp == true"
* - filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
@@ -228,12 +229,12 @@ export declare type AuditLog = Message<"bytebase.v1.AuditLog"> & {
createTime?: Timestamp | undefined;
/**
- * The user who performed the action.
- * Format: users/{email}
+ * The principal who performed the action.
+ * Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}
*
- * @generated from field: string user = 3;
+ * @generated from field: string actor = 3;
*/
- user: string;
+ actor: string;
/**
* The method or action being audited.
diff --git a/frontend/src/types/proto-es/v1/audit_log_service_pb.js b/frontend/src/types/proto-es/v1/audit_log_service_pb.js
index d96b840a45..d5f5e85f4c 100644
--- a/frontend/src/types/proto-es/v1/audit_log_service_pb.js
+++ b/frontend/src/types/proto-es/v1/audit_log_service_pb.js
@@ -16,7 +16,7 @@ import { file_v1_iam_policy } from "./iam_policy_pb";
* Describes the file v1/audit_log_service.proto.
*/
export const file_v1_audit_log_service = /*@__PURE__*/
- fileDesc("Chp2MS9hdWRpdF9sb2dfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEikAEKFlNlYXJjaEF1ZGl0TG9nc1JlcXVlc3QSLQoGcGFyZW50GAUgASgJQh3gQQL6QRcSFWJ5dGViYXNlLmNvbS9BdWRpdExvZxIOCgZmaWx0ZXIYASABKAkSEAoIb3JkZXJfYnkYAiABKAkSEQoJcGFnZV9zaXplGAMgASgFEhIKCnBhZ2VfdG9rZW4YBCABKAkiYwoXU2VhcmNoQXVkaXRMb2dzUmVzcG9uc2USLwoKYXVkaXRfbG9ncxgBIAMoCzIVLmJ5dGViYXNlLnYxLkF1ZGl0TG9nQgTQ6jACEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSK7AQoWRXhwb3J0QXVkaXRMb2dzUmVxdWVzdBItCgZwYXJlbnQYBCABKAlCHeBBAvpBFxIVYnl0ZWJhc2UuY29tL0F1ZGl0TG9nEg4KBmZpbHRlchgBIAEoCRIQCghvcmRlcl9ieRgCIAEoCRIpCgZmb3JtYXQYAyABKA4yGS5ieXRlYmFzZS52MS5FeHBvcnRGb3JtYXQSEQoJcGFnZV9zaXplGAUgASgFEhIKCnBhZ2VfdG9rZW4YBiABKAkiSQoXRXhwb3J0QXVkaXRMb2dzUmVzcG9uc2USFQoHY29udGVudBgBIAEoDEIE0OowAhIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAki0wQKCEF1ZGl0TG9nEhEKBG5hbWUYASABKAlCA+BBAxI0CgtjcmVhdGVfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIMCgR1c2VyGAMgASgJEg4KBm1ldGhvZBgEIAEoCRIwCghzZXZlcml0eRgFIAEoDjIeLmJ5dGViYXNlLnYxLkF1ZGl0TG9nLlNldmVyaXR5EhAKCHJlc291cmNlGAYgASgJEg8KB3JlcXVlc3QYByABKAkSEAoIcmVzcG9uc2UYCCABKAkSIgoGc3RhdHVzGAkgASgLMhIuZ29vZ2xlLnJwYy5TdGF0dXMSKgoHbGF0ZW5jeRgKIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbhIwCgxzZXJ2aWNlX2RhdGEYCyABKAsyFC5nb29nbGUucHJvdG9idWYuQW55QgTQ6jACEjYKEHJlcXVlc3RfbWV0YWRhdGEYDCABKAsyHC5ieXRlYmFzZS52MS5SZXF1ZXN0TWV0YWRhdGESNwoObWNwX2RlbGVnYXRpb24YDSABKAsyGi5ieXRlYmFzZS52MS5NQ1BEZWxlZ2F0aW9uQgPgQQMihQEKCFNldmVyaXR5EhgKFFNFVkVSSVRZX1VOU1BFQ0lGSUVEEAASCQoFREVCVUcQARIICgRJTkZPEAISCgoGTk9USUNFEAMSCwoHV0FSTklORxAEEgkKBUVSUk9SEAUSDAoIQ1JJVElDQUwQBhIJCgVBTEVSVBAHEg0KCUVNRVJHRU5DWRAIIjsKCUF1ZGl0RGF0YRIuCgxwb2xpY3lfZGVsdGEYASABKAsyGC5ieXRlYmFzZS52MS5Qb2xpY3lEZWx0YSJICg9SZXF1ZXN0TWV0YWRhdGESEQoJY2FsbGVyX2lwGAEgASgJEiIKGmNhbGxlcl9zdXBwbGllZF91c2VyX2FnZW50GAIgASgJIlsKDU1DUERlbGVnYXRpb24SDQoFc2NvcGUYASABKAkSEAoIcmVzb3VyY2UYAiABKAkSEQoJY2xpZW50X2lkGAMgASgJEhYKDmNvcnJlbGF0aW9uX2lkGAQgASgJMr0DCg9BdWRpdExvZ1NlcnZpY2US0wEKD1NlYXJjaEF1ZGl0TG9ncxIjLmJ5dGViYXNlLnYxLlNlYXJjaEF1ZGl0TG9nc1JlcXVlc3QaJC5ieXRlYmFzZS52MS5TZWFyY2hBdWRpdExvZ3NSZXNwb25zZSJ1iuowE2JiLmF1ZGl0TG9ncy5zZWFyY2iQ6jABmOowAaDqMASo6jAJgtPkkwJIOgEqWhk6ASoiFC92MS9hdWRpdExvZ3M6c2VhcmNoIigvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9hdWRpdExvZ3M6c2VhcmNoEtMBCg9FeHBvcnRBdWRpdExvZ3MSIy5ieXRlYmFzZS52MS5FeHBvcnRBdWRpdExvZ3NSZXF1ZXN0GiQuYnl0ZWJhc2UudjEuRXhwb3J0QXVkaXRMb2dzUmVzcG9uc2UidYrqMBNiYi5hdWRpdExvZ3MuZXhwb3J0kOowAZjqMAGg6jAEqOowCYLT5JMCSDoBKloZOgEqIhQvdjEvYXVkaXRMb2dzOmV4cG9ydCIoL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vYXVkaXRMb2dzOmV4cG9ydEKqAQoPY29tLmJ5dGViYXNlLnYxQhRBdWRpdExvZ1NlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_any, file_google_protobuf_duration, file_google_protobuf_timestamp, file_google_rpc_status, file_v1_annotation, file_v1_common, file_v1_iam_policy]);
+ fileDesc("Chp2MS9hdWRpdF9sb2dfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEikAEKFlNlYXJjaEF1ZGl0TG9nc1JlcXVlc3QSLQoGcGFyZW50GAUgASgJQh3gQQL6QRcSFWJ5dGViYXNlLmNvbS9BdWRpdExvZxIOCgZmaWx0ZXIYASABKAkSEAoIb3JkZXJfYnkYAiABKAkSEQoJcGFnZV9zaXplGAMgASgFEhIKCnBhZ2VfdG9rZW4YBCABKAkiYwoXU2VhcmNoQXVkaXRMb2dzUmVzcG9uc2USLwoKYXVkaXRfbG9ncxgBIAMoCzIVLmJ5dGViYXNlLnYxLkF1ZGl0TG9nQgTQ6jACEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSK7AQoWRXhwb3J0QXVkaXRMb2dzUmVxdWVzdBItCgZwYXJlbnQYBCABKAlCHeBBAvpBFxIVYnl0ZWJhc2UuY29tL0F1ZGl0TG9nEg4KBmZpbHRlchgBIAEoCRIQCghvcmRlcl9ieRgCIAEoCRIpCgZmb3JtYXQYAyABKA4yGS5ieXRlYmFzZS52MS5FeHBvcnRGb3JtYXQSEQoJcGFnZV9zaXplGAUgASgFEhIKCnBhZ2VfdG9rZW4YBiABKAkiSQoXRXhwb3J0QXVkaXRMb2dzUmVzcG9uc2USFQoHY29udGVudBgBIAEoDEIE0OowAhIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAki1AQKCEF1ZGl0TG9nEhEKBG5hbWUYASABKAlCA+BBAxI0CgtjcmVhdGVfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxINCgVhY3RvchgDIAEoCRIOCgZtZXRob2QYBCABKAkSMAoIc2V2ZXJpdHkYBSABKA4yHi5ieXRlYmFzZS52MS5BdWRpdExvZy5TZXZlcml0eRIQCghyZXNvdXJjZRgGIAEoCRIPCgdyZXF1ZXN0GAcgASgJEhAKCHJlc3BvbnNlGAggASgJEiIKBnN0YXR1cxgJIAEoCzISLmdvb2dsZS5ycGMuU3RhdHVzEioKB2xhdGVuY3kYCiABKAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRpb24SMAoMc2VydmljZV9kYXRhGAsgASgLMhQuZ29vZ2xlLnByb3RvYnVmLkFueUIE0OowAhI2ChByZXF1ZXN0X21ldGFkYXRhGAwgASgLMhwuYnl0ZWJhc2UudjEuUmVxdWVzdE1ldGFkYXRhEjcKDm1jcF9kZWxlZ2F0aW9uGA0gASgLMhouYnl0ZWJhc2UudjEuTUNQRGVsZWdhdGlvbkID4EEDIoUBCghTZXZlcml0eRIYChRTRVZFUklUWV9VTlNQRUNJRklFRBAAEgkKBURFQlVHEAESCAoESU5GTxACEgoKBk5PVElDRRADEgsKB1dBUk5JTkcQBBIJCgVFUlJPUhAFEgwKCENSSVRJQ0FMEAYSCQoFQUxFUlQQBxINCglFTUVSR0VOQ1kQCCI7CglBdWRpdERhdGESLgoMcG9saWN5X2RlbHRhGAEgASgLMhguYnl0ZWJhc2UudjEuUG9saWN5RGVsdGEiSAoPUmVxdWVzdE1ldGFkYXRhEhEKCWNhbGxlcl9pcBgBIAEoCRIiChpjYWxsZXJfc3VwcGxpZWRfdXNlcl9hZ2VudBgCIAEoCSJbCg1NQ1BEZWxlZ2F0aW9uEg0KBXNjb3BlGAEgASgJEhAKCHJlc291cmNlGAIgASgJEhEKCWNsaWVudF9pZBgDIAEoCRIWCg5jb3JyZWxhdGlvbl9pZBgEIAEoCTK9AwoPQXVkaXRMb2dTZXJ2aWNlEtMBCg9TZWFyY2hBdWRpdExvZ3MSIy5ieXRlYmFzZS52MS5TZWFyY2hBdWRpdExvZ3NSZXF1ZXN0GiQuYnl0ZWJhc2UudjEuU2VhcmNoQXVkaXRMb2dzUmVzcG9uc2UidYrqMBNiYi5hdWRpdExvZ3Muc2VhcmNokOowAZjqMAGg6jAEqOowCYLT5JMCSDoBKloZOgEqIhQvdjEvYXVkaXRMb2dzOnNlYXJjaCIoL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vYXVkaXRMb2dzOnNlYXJjaBLTAQoPRXhwb3J0QXVkaXRMb2dzEiMuYnl0ZWJhc2UudjEuRXhwb3J0QXVkaXRMb2dzUmVxdWVzdBokLmJ5dGViYXNlLnYxLkV4cG9ydEF1ZGl0TG9nc1Jlc3BvbnNlInWK6jATYmIuYXVkaXRMb2dzLmV4cG9ydJDqMAGY6jABoOowBKjqMAmC0+STAkg6ASpaGToBKiIUL3YxL2F1ZGl0TG9nczpleHBvcnQiKC92MS97cGFyZW50PXByb2plY3RzLyp9L2F1ZGl0TG9nczpleHBvcnRCqgEKD2NvbS5ieXRlYmFzZS52MUIUQXVkaXRMb2dTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_any, file_google_protobuf_duration, file_google_protobuf_timestamp, file_google_rpc_status, file_v1_annotation, file_v1_common, file_v1_iam_policy]);
/**
* Describes the message bytebase.v1.SearchAuditLogsRequest.
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 59a9557c4f..b6edea6a56 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -5923,7 +5923,8 @@ paths:
- method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
- resource: the resource the entry is about, support "==" operator.
- severity: support "==" operator, check Severity enum in AuditLog message for values.
- - user: the actor, should in "users/{email}" format, support "==" operator.
+ - actor: the actor, in users/{email}, serviceAccounts/{email}, or
+ workloadIdentities/{email} format. Support "==" operator.
- create_time: support ">=" and "<=" operator.
- mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
- mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
@@ -5931,7 +5932,7 @@ paths:
For example:
- filter = "method == '/bytebase.v1.SQLService/Query'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
- - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
+ - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && actor == 'users/[email protected]'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
- filter = "mcp == true"
- filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
@@ -17525,12 +17526,12 @@ components:
title: create_time
description: The timestamp when the audit log was created.
readOnly: true
- user:
+ actor:
type: string
- title: user
+ title: actor
description: |-
- The user who performed the action.
- Format: users/{email}
+ The principal who performed the action.
+ Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}
method:
type: string
title: method
@@ -28052,7 +28053,8 @@ components:
- method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
- resource: the resource the entry is about, support "==" operator.
- severity: support "==" operator, check Severity enum in AuditLog message for values.
- - user: the actor, should in "users/{email}" format, support "==" operator.
+ - actor: the actor, in users/{email}, serviceAccounts/{email}, or
+ workloadIdentities/{email} format. Support "==" operator.
- create_time: support ">=" and "<=" operator.
- mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
- mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
@@ -28060,7 +28062,7 @@ components:
For example:
- filter = "method == '/bytebase.v1.SQLService/Query'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
- - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
+ - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && actor == 'users/[email protected]'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
- filter = "mcp == true"
- filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
@@ -32566,15 +32568,10 @@ components:
enum:
- NULL_VALUE
description: |-
- Represents a JSON `null`.
-
- `NullValue` is a sentinel, using an enum with only one value to represent
- the null value for the `Value` type union.
+ `NullValue` is a singleton enumeration to represent the null value for the
+ `Value` type union.
- A field of type `NullValue` with any value other than `0` is considered
- invalid. Most ProtoJSON serializers will emit a Value with a `null_value` set
- as a JSON `null` regardless of the integer value, and so will round trip to
- a `0` value.
+ The JSON representation for `NullValue` is JSON `null`.
google.protobuf.Struct:
type: object
additionalProperties:
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 8a247dac11..55d75f4a44 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -818,7 +818,7 @@ Status represents the approver&#39;s decision state.
| parent | [string](#string) | | The project or workspace the audit log belongs to. Formats: - projects/{project} - workspaces/{workspace} |
| method | [string](#string) | | Example: /bytebase.v1.SQLService/Query |
| resource | [string](#string) | | The resource name. Example: projects/{project} |
-| user | [string](#string) | | Format: users/{email}. |
+| user | [string](#string) | | The principal who performed the action. Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}. |
| severity | [AuditLog.Severity](#bytebase-store-AuditLog-Severity) | | |
| request | [string](#string) | | Marshalled request. |
| response | [string](#string) | | Marshalled response. Some fields are omitted because they are too large or contain sensitive information. |
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 60d6e0869d..60e647efdb 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -2799,7 +2799,8 @@ Example: projects/{project} </p></td>
<td>user</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>Format: users/{email}. </p></td>
+ <td><p>The principal who performed the action.
+Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}. </p></td>
</tr>
<tr>
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index d7d7daa248..01deef5396 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -5444,7 +5444,7 @@ Audit log entry recording system activity or API call.
| ----- | ---- | ----- | ----------- |
| name | [string](#string) | | The name of the log. Formats: - projects/{project}/auditLogs/{uid} - workspaces/{workspace}/auditLogs/{uid} |
| create_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The timestamp when the audit log was created. |
-| user | [string](#string) | | The user who performed the action. Format: users/{email} |
+| actor | [string](#string) | | The principal who performed the action. Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email} |
| method | [string](#string) | | The method or action being audited. For example: /bytebase.v1.SQLService/Query or bb.project.repository.push |
| severity | [AuditLog.Severity](#bytebase-v1-AuditLog-Severity) | | The severity level of this audit log entry. |
| resource | [string](#string) | | The resource associated with this audit log. |
@@ -5545,9 +5545,9 @@ Request message for searching audit logs.
| parent | [string](#string) | | |
| filter | [string](#string) | | The filter of the log. It should be a valid CEL expression. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
-Supported filter: - method: the API name, can be found in the docs. Usually &#34;/bytebase.v1.…&#34;, for example &#34;/bytebase.v1.UserService/CreateUser&#34;; entries written outside the v1 API carry their own prefix, such as &#34;/bytebase.mcp.Session/Authorize&#34; or &#34;/bytebase.cli.Recovery/ResetUserPassword&#34;. Support &#34;==&#34; operator. - resource: the resource the entry is about, support &#34;==&#34; operator. - severity: support &#34;==&#34; operator, check Severity enum in AuditLog message for values. - user: the actor, should in &#34;users/{email}&#34; format, support &#34;==&#34; operator. - create_time: support &#34;&gt;=&#34; and &#34;&lt;=&#34; operator. - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support &#34;==&#34; operator. - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry&#39;s mcp_delegation.correlation_id. Support &#34;==&#34; operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
+Supported filter: - method: the API name, can be found in the docs. Usually &#34;/bytebase.v1.…&#34;, for example &#34;/bytebase.v1.UserService/CreateUser&#34;; entries written outside the v1 API carry their own prefix, such as &#34;/bytebase.mcp.Session/Authorize&#34; or &#34;/bytebase.cli.Recovery/ResetUserPassword&#34;. Support &#34;==&#34; operator. - resource: the resource the entry is about, support &#34;==&#34; operator. - severity: support &#34;==&#34; operator, check Severity enum in AuditLog message for values. - actor: the actor, in users/{email}, serviceAccounts/{email}, or workloadIdentities/{email} format. Support &#34;==&#34; operator. - create_time: support &#34;&gt;=&#34; and &#34;&lt;=&#34; operator. - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support &#34;==&#34; operator. - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry&#39;s mcp_delegation.correlation_id. Support &#34;==&#34; operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
-For example: - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; user == &#39;users/[email protected]&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; create_time &lt;= &#39;2021-01-01T00:00:00Z&#39; &amp;&amp; create_time &gt;= &#39;2020-01-01T00:00:00Z&#39;&#34; - filter = &#34;mcp == true&#34; - filter = &#34;mcp_correlation_id == &#39;0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60&#39;&#34; |
+For example: - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; actor == &#39;users/[email protected]&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; create_time &lt;= &#39;2021-01-01T00:00:00Z&#39; &amp;&amp; create_time &gt;= &#39;2020-01-01T00:00:00Z&#39;&#34; - filter = &#34;mcp == true&#34; - filter = &#34;mcp_correlation_id == &#39;0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60&#39;&#34; |
| order_by | [string](#string) | | The order by of the log. Only support order by create_time. The default sorting order is ascending. For example: - order_by = &#34;create_time asc&#34; - order_by = &#34;create_time desc&#34; |
| page_size | [int32](#int32) | | The maximum number of logs to return. The service may return fewer than this value. If unspecified, at most 10 log entries will be returned. The maximum value is 5000; values above 5000 will be coerced to 5000. |
| page_token | [string](#string) | | A page token, received from a previous `SearchLogs` call. Provide this to retrieve the subsequent page. |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index c7496ae93b..7567803eb1 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -15645,11 +15645,11 @@ Formats:
</tr>
<tr>
- <td>user</td>
+ <td>actor</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>The user who performed the action.
-Format: users/{email} </p></td>
+ <td><p>The principal who performed the action.
+Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email} </p></td>
</tr>
<tr>
@@ -15945,7 +15945,8 @@ Supported filter:
- method: the API name, can be found in the docs. Usually &#34;/bytebase.v1.…&#34;, for example &#34;/bytebase.v1.UserService/CreateUser&#34;; entries written outside the v1 API carry their own prefix, such as &#34;/bytebase.mcp.Session/Authorize&#34; or &#34;/bytebase.cli.Recovery/ResetUserPassword&#34;. Support &#34;==&#34; operator.
- resource: the resource the entry is about, support &#34;==&#34; operator.
- severity: support &#34;==&#34; operator, check Severity enum in AuditLog message for values.
-- user: the actor, should in &#34;users/{email}&#34; format, support &#34;==&#34; operator.
+- actor: the actor, in users/{email}, serviceAccounts/{email}, or
+ workloadIdentities/{email} format. Support &#34;==&#34; operator.
- create_time: support &#34;&gt;=&#34; and &#34;&lt;=&#34; operator.
- mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support &#34;==&#34; operator.
- mcp_correlation_id: the MCP session an entry belongs to, taken from an entry&#39;s mcp_delegation.correlation_id. Support &#34;==&#34; operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
@@ -15953,7 +15954,7 @@ Supported filter:
For example:
- filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39;&#34;
- filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39;&#34;
- - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; user == &#39;users/[email protected]&#39;&#34;
+ - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; actor == &#39;users/[email protected]&#39;&#34;
- filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; create_time &lt;= &#39;2021-01-01T00:00:00Z&#39; &amp;&amp; create_time &gt;= &#39;2020-01-01T00:00:00Z&#39;&#34;
- filter = &#34;mcp == true&#34;
- filter = &#34;mcp_correlation_id == &#39;0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60&#39;&#34; </p></td>
diff --git a/proto/store/store/audit_log.proto b/proto/store/store/audit_log.proto
index 2a1da37311..6de104951c 100644
--- a/proto/store/store/audit_log.proto
+++ b/proto/store/store/audit_log.proto
@@ -22,7 +22,8 @@ message AuditLog {
// Example: projects/{project}
string resource = 3;
- // Format: users/{email}.
+ // The principal who performed the action.
+ // Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}.
string user = 4;
Severity severity = 5;
diff --git a/proto/v1/v1/audit_log_service.proto b/proto/v1/v1/audit_log_service.proto
index c8da2006c8..51f4eee2b6 100644
--- a/proto/v1/v1/audit_log_service.proto
+++ b/proto/v1/v1/audit_log_service.proto
@@ -68,7 +68,8 @@ message SearchAuditLogsRequest {
// - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
// - resource: the resource the entry is about, support "==" operator.
// - severity: support "==" operator, check Severity enum in AuditLog message for values.
- // - user: the actor, should in "users/{email}" format, support "==" operator.
+ // - actor: the actor, in users/{email}, serviceAccounts/{email}, or
+ // workloadIdentities/{email} format. Support "==" operator.
// - create_time: support ">=" and "<=" operator.
// - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
// - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
@@ -76,7 +77,7 @@ message SearchAuditLogsRequest {
// For example:
// - filter = "method == '/bytebase.v1.SQLService/Query'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
- // - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
+ // - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && actor == 'users/[email protected]'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
// - filter = "mcp == true"
// - filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
@@ -164,9 +165,9 @@ message AuditLog {
// The timestamp when the audit log was created.
google.protobuf.Timestamp create_time = 2 [(google.api.field_behavior) = OUTPUT_ONLY];
- // The user who performed the action.
- // Format: users/{email}
- string user = 3;
+ // The principal who performed the action.
+ // Formats: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}
+ string actor = 3;
// The method or action being audited.
// For example: /bytebase.v1.SQLService/Query or bb.project.repository.push