Skip to content

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

fix(api): refuse an access grant where just-in-time access is off (#21587)

Vincent Huang8b87d0c55e16
diff --git a/backend/api/v1/access_grant_service.go b/backend/api/v1/access_grant_service.go
index 871c1ae08a..905b4bae45 100644
--- a/backend/api/v1/access_grant_service.go
+++ b/backend/api/v1/access_grant_service.go
@@ -155,6 +155,9 @@ func (s *AccessGrantService) CreateAccessGrant(ctx context.Context, request *con
if err != nil {
return nil, err
}
+ if err := refuseAccessGrantWithoutJIT(project); err != nil {
+ return nil, err
+ }
if ok, err := isReadOnlyStatementForAccessGrant(ctx, instance.Metadata.GetEngine(), ag.Query); err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "invalid query"))
} else if !ok {
@@ -293,6 +296,17 @@ func refuseUnattendedMCPAccessGrant(ctx context.Context, approval *storepb.Issue
v1connect.AccessGrantServiceCreateAccessGrantProcedure))
}
+// refuseAccessGrantWithoutJIT refuses a request in a project that does not allow
+// just-in-time access: SQLService.preCheckAccess ignores every grant there.
+func refuseAccessGrantWithoutJIT(project *store.ProjectMessage) error {
+ if project.Setting.GetAllowJustInTimeAccess() {
+ return nil
+ }
+ return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf(
+ `just-in-time access is off for project %q, so an access grant there would not apply; `+
+ `a project owner can turn on "Allow access grants" in the project settings`, project.ResourceID))
+}
+
func (s *AccessGrantService) validateAccessGrantTargets(ctx context.Context, projectID string, targets []string) (*store.ProjectMessage, *store.InstanceMessage, error) {
workspaceID := common.GetWorkspaceIDFromContext(ctx)
project, err := s.store.GetProject(ctx, &store.FindProjectMessage{
diff --git a/backend/api/v1/access_grant_service_test.go b/backend/api/v1/access_grant_service_test.go
index 018aff2295..b79e5aa3b5 100644
--- a/backend/api/v1/access_grant_service_test.go
+++ b/backend/api/v1/access_grant_service_test.go
@@ -201,6 +201,18 @@ func TestConvertToAccessGrantNilPayloadIsSafe(t *testing.T) {
require.Empty(t, ag.Container)
}
+func TestRefuseAccessGrantWithoutJIT(t *testing.T) {
+ t.Parallel()
+ project := &store.ProjectMessage{ResourceID: "grant-project", Setting: &storepb.Project{}}
+ err := refuseAccessGrantWithoutJIT(project)
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ require.Contains(t, err.Error(), `just-in-time access is off for project "grant-project"`)
+ require.Contains(t, err.Error(), `turn on "Allow access grants" in the project settings`)
+
+ project.Setting.AllowJustInTimeAccess = true
+ require.NoError(t, refuseAccessGrantWithoutJIT(project))
+}
+
func TestRefuseUnattendedMCPAccessGrant(t *testing.T) {
t.Parallel()
mcpCtx := context.WithValue(context.Background(), common.AuthContextKey,
diff --git a/backend/tests/database.go b/backend/tests/database.go
index aa428f36e1..696e66d5e6 100644
--- a/backend/tests/database.go
+++ b/backend/tests/database.go
@@ -138,6 +138,19 @@ func (ctl *controller) allowLastPlanEditorApproval(ctx context.Context, project
return err
}
+// allowJustInTimeAccess opts the project into just-in-time access, which
+// CreateAccessGrant requires.
+func (ctl *controller) allowJustInTimeAccess(ctx context.Context, project *v1pb.Project) error {
+ _, err := ctl.projectServiceClient.UpdateProject(ctx, connect.NewRequest(&v1pb.UpdateProjectRequest{
+ Project: &v1pb.Project{
+ Name: project.Name,
+ AllowJustInTimeAccess: true,
+ },
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"allow_just_in_time_access"}},
+ }))
+ return err
+}
+
// instanceLocks serializes registerDatabase per instance: parallel subtests
// share instances, and a sync that reads the list before another subtest's
// update marks that subtest's database deleted.
diff --git a/backend/tests/maximum_request_expiration_test.go b/backend/tests/maximum_request_expiration_test.go
index 94b9705d24..41096ed860 100644
--- a/backend/tests/maximum_request_expiration_test.go
+++ b/backend/tests/maximum_request_expiration_test.go
@@ -194,6 +194,7 @@ func TestAccessGrantMaximumExpiration(t *testing.T) {
dbName := generateRandomString("db")
a.NoError(ctl.createDatabase(ctx, ctl.project, instanceResp.Msg, nil, dbName, ""))
target := fmt.Sprintf("%s/databases/%s", instanceResp.Msg.Name, dbName)
+ a.NoError(ctl.allowJustInTimeAccess(ctx, ctl.project))
// Cap role expiration to 7 days.
a.NoError(ctl.setMaximumRequestExpiration(ctx, durationpb.New(7*24*time.Hour)))
diff --git a/backend/tests/mcp_gate_test.go b/backend/tests/mcp_gate_test.go
index 44ccd4a45e..fe14b3f33a 100644
--- a/backend/tests/mcp_gate_test.go
+++ b/backend/tests/mcp_gate_test.go
@@ -3,6 +3,7 @@ package tests
import (
"context"
"encoding/base64"
+ "encoding/json"
"fmt"
"net/http"
"testing"
@@ -85,7 +86,8 @@ func TestMCPGateServesAndRefusesByClass(t *testing.T) {
}
// TestMCPGateRefusesGrantIssues covers, over one live MCP session, the grant
-// issues a session may not create and the access request it may file instead.
+// issues a session may not create and the access request it may file instead,
+// which needs a project that allows just-in-time access.
func TestMCPGateRefusesGrantIssues(t *testing.T) {
t.Parallel()
a := require.New(t)
@@ -210,10 +212,48 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {
"ttl": "3600s",
},
}
+ consoleCreate := func() (*connect.Response[v1pb.AccessGrant], error) {
+ return ctl.accessGrantServiceClient.CreateAccessGrant(ctx, connect.NewRequest(&v1pb.CreateAccessGrantRequest{
+ Parent: projectName,
+ AccessGrant: &v1pb.AccessGrant{
+ Targets: []string{target},
+ Query: "SELECT 1",
+ Reason: "a person asks the same",
+ Expiration: &v1pb.AccessGrant_Ttl{Ttl: durationpb.New(time.Hour)},
+ },
+ }))
+ }
+ rowCounts := func() (int, int) {
+ grants, err := ctl.accessGrantServiceClient.ListAccessGrants(ctx, connect.NewRequest(&v1pb.ListAccessGrantsRequest{Parent: projectName}))
+ a.NoError(err)
+ issues, err := ctl.issueServiceClient.ListIssues(ctx, connect.NewRequest(&v1pb.ListIssuesRequest{Parent: projectName}))
+ a.NoError(err)
+ return len(grants.Msg.AccessGrants), len(issues.Msg.Issues)
+ }
+
+ // The project does not allow just-in-time access yet.
+ grantsAtStart, issuesAtStart := rowCounts()
+ jitOff := callAPIOnSession(ctx, t, session, "AccessGrantService/CreateAccessGrant", requestAccess)
+ a.Equal(http.StatusBadRequest, jitOff.Status, jitOff.Error)
+ var jitOffBody struct {
+ Code string `json:"code"`
+ }
+ a.NoError(json.Unmarshal([]byte(jitOff.RawResponse), &jitOffBody))
+ a.Equal("failed_precondition", jitOffBody.Code)
+ a.Contains(jitOff.Error, `just-in-time access is off for project "mcp-grant-issue"`)
+ _, err = consoleCreate()
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err), "a console request is refused the same way: %v", err)
+ grantsRefused, issuesRefused := rowCounts()
+ a.Equal(grantsAtStart, grantsRefused, "a request refused for just-in-time access leaves no access grant")
+ a.Equal(issuesAtStart, issuesRefused, "a request refused for just-in-time access leaves no issue")
+ a.NoError(ctl.allowJustInTimeAccess(ctx, project.Msg))
// The seeded fallback rule sends the request to a project owner.
filed := callAPIOnSession(ctx, t, session, "AccessGrantService/CreateAccessGrant", requestAccess)
a.Equal(http.StatusOK, filed.Status, filed.Error)
+ grantsFiled, issuesFiled := rowCounts()
+ a.Equal(grantsAtStart+1, grantsFiled, "the row count sees a filed access grant")
+ a.Equal(issuesAtStart+1, issuesFiled, "the row count sees a filed issue")
var pending v1pb.AccessGrant
a.NoError(common.ProtojsonUnmarshaler.Unmarshal([]byte(filed.RawResponse), &pending))
a.Equal(v1pb.AccessGrant_PENDING, pending.Status)
@@ -232,15 +272,7 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {
a.Equal(v1pb.AccessGrant_PENDING, still.Msg.Status)
consoleRequest := func() *v1pb.AccessGrant {
- granted, err := ctl.accessGrantServiceClient.CreateAccessGrant(ctx, connect.NewRequest(&v1pb.CreateAccessGrantRequest{
- Parent: projectName,
- AccessGrant: &v1pb.AccessGrant{
- Targets: []string{target},
- Query: "SELECT 1",
- Reason: "a person asks the same",
- Expiration: &v1pb.AccessGrant_Ttl{Ttl: durationpb.New(time.Hour)},
- },
- }))
+ granted, err := consoleCreate()
a.NoError(err)
return granted.Msg
}
@@ -250,13 +282,6 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {
a.NoError(err)
a.Equal([]string{"roles/projectOwner"}, consoleIssue.Msg.GetApprovalTemplate().GetFlow().GetRoles())
- rowCounts := func() (int, int) {
- grants, err := ctl.accessGrantServiceClient.ListAccessGrants(ctx, connect.NewRequest(&v1pb.ListAccessGrantsRequest{Parent: projectName}))
- a.NoError(err)
- issues, err := ctl.issueServiceClient.ListIssues(ctx, connect.NewRequest(&v1pb.ListIssuesRequest{Parent: projectName}))
- a.NoError(err)
- return len(grants.Msg.AccessGrants), len(issues.Msg.Issues)
- }
for _, tc := range []struct {
name string
rules []*v1pb.WorkspaceApprovalSetting_Rule
diff --git a/backend/tests/mcp_masking_test.go b/backend/tests/mcp_masking_test.go
index 90875b68eb..324f367f44 100644
--- a/backend/tests/mcp_masking_test.go
+++ b/backend/tests/mcp_masking_test.go
@@ -27,7 +27,6 @@ import (
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/require"
"google.golang.org/genproto/googleapis/type/expr"
- "google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/timestamppb"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
@@ -254,14 +253,7 @@ func (f *mcpMaskingFixture) exemptFromMasking(t *testing.T, member string) strin
func (f *mcpMaskingFixture) grantUnmask(t *testing.T, export bool) {
t.Helper()
a := require.New(t)
-
- // preCheckAccess returns early unless the project allows JIT access, so
- // without this the grant would exist and never be consulted.
- _, err := f.ctl.projectServiceClient.UpdateProject(f.ctx, connect.NewRequest(&v1pb.UpdateProjectRequest{
- Project: &v1pb.Project{Name: f.ctl.project.Name, AllowJustInTimeAccess: true},
- UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"allow_just_in_time_access"}},
- }))
- a.NoError(err)
+ a.NoError(f.ctl.allowJustInTimeAccess(f.ctx, f.ctl.project))
created, err := f.ctl.accessGrantServiceClient.CreateAccessGrant(f.ctx, connect.NewRequest(&v1pb.CreateAccessGrantRequest{
Parent: f.ctl.project.Name,
diff --git a/backend/tests/project_instance_compat_extras_test.go b/backend/tests/project_instance_compat_extras_test.go
index 8b95429daf..2c8a810bf3 100644
--- a/backend/tests/project_instance_compat_extras_test.go
+++ b/backend/tests/project_instance_compat_extras_test.go
@@ -219,6 +219,7 @@ func TestProjectInstanceAccessGrant(t *testing.T) {
}
return resp.Msg, nil
}
+ a.NoError(ctl.allowJustInTimeAccess(ctx, ctl.project))
// A grant targeting the canonical project-scoped database works in the
// owning project and retains the target.
diff --git a/backend/tests/webhook_test.go b/backend/tests/webhook_test.go
index 936ab2ce46..5236dd6bc9 100644
--- a/backend/tests/webhook_test.go
+++ b/backend/tests/webhook_test.go
@@ -685,6 +685,7 @@ func TestWebhookIntegration(t *testing.T) {
collector.reset()
project := ctl.createTestProject(ctx, t, "access-grant-approval")
require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "access_grant_approval_db", ""))
+ require.NoError(t, ctl.allowJustInTimeAccess(ctx, project))
clearWorkspaceApprovalRules(ctx, t, ctl)
disableSelfApproval(ctx, t, ctl, project)