diff --git a/integration/autoupdate/tools/updater_tsh_test.go b/integration/autoupdate/tools/updater_tsh_test.go
index eafd687dd99..6bba808b4a1 100644
--- a/integration/autoupdate/tools/updater_tsh_test.go
+++ b/integration/autoupdate/tools/updater_tsh_test.go
@@ -372,17 +372,17 @@ func bootstrapTestServer(t *testing.T) (*service.TeleportProcess, string) {
func setupManagedUpdates(t *testing.T, server *auth.Server, muMode string, muVersion string) {
t.Helper()
ctx := context.Background()
- config, err := autoupdate.NewAutoUpdateConfig(&autoupdatev1pb.AutoUpdateConfigSpec{
- Tools: &autoupdatev1pb.AutoUpdateConfigSpecTools{
+ config, err := autoupdate.NewAutoUpdateConfig(autoupdatev1pb.AutoUpdateConfigSpec_builder{
+ Tools: autoupdatev1pb.AutoUpdateConfigSpecTools_builder{
Mode: muMode,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- version, err := autoupdate.NewAutoUpdateVersion(&autoupdatev1pb.AutoUpdateVersionSpec{
- Tools: &autoupdatev1pb.AutoUpdateVersionSpecTools{
+ version, err := autoupdate.NewAutoUpdateVersion(autoupdatev1pb.AutoUpdateVersionSpec_builder{
+ Tools: autoupdatev1pb.AutoUpdateVersionSpecTools_builder{
TargetVersion: muVersion,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
_, err = server.UpsertAutoUpdateConfig(ctx, config)
require.NoError(t, err)
diff --git a/integration/db/fixture.go b/integration/db/fixture.go
index 8b9065f7ba7..0ffce5371f9 100644
--- a/integration/db/fixture.go
+++ b/integration/db/fixture.go
@@ -349,7 +349,7 @@ func SetupDatabaseTest(t *testing.T, options ...TestOptionFunc) *DatabasePack {
// disable health checks to reduce log noise during tests
defaultHCC := services.VirtualDefaultHealthCheckConfigDB()
- defaultHCC.GetSpec().GetMatch().Disabled = true
+ defaultHCC.GetSpec().GetMatch().SetDisabled(true)
_, err = p.Root.Cluster.Process.GetAuthServer().UpsertHealthCheckConfig(ctx, defaultHCC)
require.NoError(t, err)
_, err = p.Leaf.Cluster.Process.GetAuthServer().UpsertHealthCheckConfig(ctx, defaultHCC)
diff --git a/integration/integration_test.go b/integration/integration_test.go
index 55ffd5876f7..60d95eba765 100644
--- a/integration/integration_test.go
+++ b/integration/integration_test.go
@@ -311,17 +311,17 @@ func testAuthLocalNodeControlStream(t *testing.T, suite *integrationTestSuite) {
var nodeID string
// verify node control stream registers, extracting the id.
require.Eventually(t, func() bool {
- status, err := clt.GetInventoryStatus(context.Background(), &proto.InventoryStatusRequest{
+ status, err := clt.GetInventoryStatus(context.Background(), proto.InventoryStatusRequest_builder{
Connected: true,
- })
+ }.Build())
require.NoError(t, err)
- for _, hello := range status.Connected {
- for _, s := range hello.Services {
+ for _, hello := range status.GetConnected() {
+ for _, s := range hello.GetServices() {
if s != string(types.RoleNode) {
continue
}
- nodeID = hello.ServerID
+ nodeID = hello.GetServerID()
return true
}
}
diff --git a/integration/proxy/proxy_helpers.go b/integration/proxy/proxy_helpers.go
index 3a69995b4d2..24d0c43ddf3 100644
--- a/integration/proxy/proxy_helpers.go
+++ b/integration/proxy/proxy_helpers.go
@@ -674,15 +674,15 @@ func mustFindKubePod(t *testing.T, tc *client.TeleportClient) {
serviceClient, err := tc.NewKubernetesServiceClient(context.Background(), tc.SiteName)
require.NoError(t, err)
- response, err := serviceClient.ListKubernetesResources(context.Background(), &kubeproto.ListKubernetesResourcesRequest{
+ response, err := serviceClient.ListKubernetesResources(context.Background(), kubeproto.ListKubernetesResourcesRequest_builder{
ResourceType: types.KindKubePod,
KubernetesCluster: kubeClusterName,
KubernetesNamespace: metav1.NamespaceDefault,
TeleportCluster: tc.SiteName,
- })
+ }.Build())
require.NoError(t, err)
- require.Len(t, response.Resources, 3)
- require.Equal(t, types.KindKubePod, response.Resources[0].Kind)
+ require.Len(t, response.GetResources(), 3)
+ require.Equal(t, types.KindKubePod, response.GetResources()[0].Kind)
}
func mustConnectDatabaseGateway(ctx context.Context, t *testing.T, _ *daemon.Service, gw gateway.Gateway) {
diff --git a/integration/tctl_token_kube_test.go b/integration/tctl_token_kube_test.go
index 3b1635cc159..5777c81dcf2 100644
--- a/integration/tctl_token_kube_test.go
+++ b/integration/tctl_token_kube_test.go
@@ -127,18 +127,18 @@ func TestTCTLTokenConfigureKubeCommand_OIDC(t *testing.T) {
pong, err := clt.Ping(ctx)
require.NoError(t, err)
- _, err = clt.BotServiceClient().CreateBot(ctx, &machineidv1.CreateBotRequest{
- Bot: &machineidv1.Bot{
+ _, err = clt.BotServiceClient().CreateBot(ctx, machineidv1.CreateBotRequest_builder{
+ Bot: machineidv1.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: testBotName,
- },
- Spec: &machineidv1.BotSpec{
+ }.Build(),
+ Spec: machineidv1.BotSpec_builder{
Roles: []string{testRoleName},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
addr, err := rc.Process.ProxyWebAddr()
@@ -244,18 +244,18 @@ func TestTCTLTokenConfigureKubeCommand_JWKS(t *testing.T) {
pong, err := clt.Ping(ctx)
require.NoError(t, err)
- _, err = clt.BotServiceClient().CreateBot(ctx, &machineidv1.CreateBotRequest{
- Bot: &machineidv1.Bot{
+ _, err = clt.BotServiceClient().CreateBot(ctx, machineidv1.CreateBotRequest_builder{
+ Bot: machineidv1.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: testBotName,
- },
- Spec: &machineidv1.BotSpec{
+ }.Build(),
+ Spec: machineidv1.BotSpec_builder{
Roles: []string{testRoleName},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
addr, err := rc.Process.ProxyWebAddr()
diff --git a/integration/teleterm_test.go b/integration/teleterm_test.go
index 38c65e99191..2802422c69b 100644
--- a/integration/teleterm_test.go
+++ b/integration/teleterm_test.go
@@ -332,8 +332,8 @@ func testListRootClustersReturnsLoggedInUser(t *testing.T, pack *dbhelpers.Datab
response, err := handler.ListRootClusters(context.Background(), &api.ListClustersRequest{})
require.NoError(t, err)
- require.Len(t, response.Clusters, 1)
- require.Equal(t, pack.Root.User.GetName(), response.Clusters[0].LoggedInUser.Name)
+ require.Len(t, response.GetClusters(), 1)
+ require.Equal(t, pack.Root.User.GetName(), response.GetClusters()[0].GetLoggedInUser().GetName())
}
func testGetClusterReturnsPropertiesFromAuthServer(t *testing.T, pack *dbhelpers.DatabasePack) {
@@ -418,20 +418,20 @@ func testGetClusterReturnsPropertiesFromAuthServer(t *testing.T, pack *dbhelpers
require.NoError(t, err)
clusterURI := uri.NewClusterURI(rootClusterName)
- response, err := handler.GetCluster(context.Background(), &api.GetClusterRequest{
+ response, err := handler.GetCluster(context.Background(), api.GetClusterRequest_builder{
ClusterUri: clusterURI.String(),
- })
+ }.Build())
require.NoError(t, err)
- require.Equal(t, userName, response.LoggedInUser.Name)
- require.ElementsMatch(t, []string{requestableRoleName}, response.LoggedInUser.RequestableRoles)
- require.ElementsMatch(t, []string{suggestedReviewer}, response.LoggedInUser.SuggestedReviewers)
+ require.Equal(t, userName, response.GetLoggedInUser().GetName())
+ require.ElementsMatch(t, []string{requestableRoleName}, response.GetLoggedInUser().GetRequestableRoles())
+ require.ElementsMatch(t, []string{suggestedReviewer}, response.GetLoggedInUser().GetSuggestedReviewers())
// Verify that cluster ID cache gets updated.
clusterIDFromCache, ok := clusterIDCache.Load(clusterURI)
require.True(t, ok, "ID for cluster %q was not found in the cache", clusterURI)
require.NotEmpty(t, clusterIDFromCache)
- require.Equal(t, response.AuthClusterId, clusterIDFromCache)
+ require.Equal(t, response.GetAuthClusterId(), clusterIDFromCache)
}
func testHeadlessWatcher(t *testing.T, pack *dbhelpers.DatabasePack, creds *helpers.UserCreds) {
@@ -560,10 +560,10 @@ func testClientCache(t *testing.T, pack *dbhelpers.DatabasePack, creds *helpers.
// Reissue user certs by assuming a role with a bogus ID in DropAccessRequests.
// This makes the cached client stale.
- accessRequest := &api.AssumeRoleRequest{
+ accessRequest := api.AssumeRoleRequest_builder{
RootClusterUri: cluster.URI.String(),
DropRequestIds: []string{"does-not-matter"},
- }
+ }.Build()
err = cluster.AssumeRole(ctx, secondCallForClient, accessRequest)
require.NoError(t, err)
@@ -616,10 +616,10 @@ func testClearingStaleCachedClients(t *testing.T, pack *dbhelpers.DatabasePack,
require.NoError(t, err)
require.Equal(t, firstCallForClient, secondCallForClient)
// Reissue user certs by assuming a role with a bogus ID in DropAccessRequests.
- accessRequest := &api.AssumeRoleRequest{
+ accessRequest := api.AssumeRoleRequest_builder{
RootClusterUri: cluster.URI.String(),
DropRequestIds: []string{"does-not-matter"},
- }
+ }.Build()
err = cluster.AssumeRole(ctx, firstCallForClient, accessRequest)
require.NoError(t, err)
// The cert has changed, so after clearing stale clients,
@@ -974,23 +974,21 @@ func testCreateConnectMyComputerRole(t *testing.T, pack *dbhelpers.DatabasePack)
// skips the actual login flow and saves valid certs to disk. We already had a regression that
// was not caught by this test because the test did not trigger certain code paths because it
// was using mustLogin as a shortcut.
- _, err = handler.AddCluster(ctx, &api.AddClusterRequest{Name: pack.Root.Cluster.Web})
+ _, err = handler.AddCluster(ctx, api.AddClusterRequest_builder{Name: pack.Root.Cluster.Web}.Build())
require.NoError(t, err)
- _, err = handler.Login(ctx, &api.LoginRequest{
+ _, err = handler.Login(ctx, api.LoginRequest_builder{
ClusterUri: rootClusterURI,
- Params: &api.LoginRequest_Local{
- Local: &api.LoginRequest_LocalParams{User: userName, Password: userPassword},
- },
- })
+ Local: api.LoginRequest_LocalParams_builder{User: userName, Password: userPassword}.Build(),
+ }.Build())
require.NoError(t, err)
// Call CreateConnectMyComputerRole.
- response, err := handler.CreateConnectMyComputerRole(ctx, &api.CreateConnectMyComputerRoleRequest{
+ response, err := handler.CreateConnectMyComputerRole(ctx, api.CreateConnectMyComputerRoleRequest_builder{
RootClusterUri: rootClusterURI,
- })
+ }.Build())
require.NoError(t, err)
- test.assertCertsReloaded(t, response.CertsReloaded, "CertsReloaded is the opposite of the expected value")
+ test.assertCertsReloaded(t, response.GetCertsReloaded(), "CertsReloaded is the opposite of the expected value")
// Verify that the role exists.
role, err := authServer.GetRole(ctx, roleName)
@@ -1007,11 +1005,11 @@ func testCreateConnectMyComputerRole(t *testing.T, pack *dbhelpers.DatabasePack)
//
// GetCluster reads data from the cert. If the certs were not reloaded properly, GetCluster
// will not return the role that's just been assigned to the user.
- clusterDetails, err := handler.GetCluster(ctx, &api.GetClusterRequest{
+ clusterDetails, err := handler.GetCluster(ctx, api.GetClusterRequest_builder{
ClusterUri: rootClusterURI,
- })
+ }.Build())
require.NoError(t, err)
- require.Contains(t, clusterDetails.LoggedInUser.Roles, roleName,
+ require.Contains(t, clusterDetails.GetLoggedInUser().GetRoles(), roleName,
"the user certs don't include the freshly added role; the certs might have not been reloaded properly")
})
}
@@ -1095,9 +1093,9 @@ func testCreateConnectMyComputerToken(t *testing.T, pack *dbhelpers.DatabasePack
require.NoError(t, err)
rootClusterURI := uri.NewClusterURI(rootClusterName).String()
requestCreatedAt := fakeClock.Now()
- createdTokenResponse, err := handler.CreateConnectMyComputerNodeToken(ctx, &api.CreateConnectMyComputerNodeTokenRequest{
+ createdTokenResponse, err := handler.CreateConnectMyComputerNodeToken(ctx, api.CreateConnectMyComputerNodeTokenRequest_builder{
RootClusterUri: rootClusterURI,
- })
+ }.Build())
require.NoError(t, err)
// Verify that token exists
@@ -1151,9 +1149,9 @@ func testWaitForConnectMyComputerNodeJoin(t *testing.T, pack *dbhelpers.Database
waitForNodeJoinErr := make(chan error)
go func() {
- _, err := handler.WaitForConnectMyComputerNodeJoin(ctx, &api.WaitForConnectMyComputerNodeJoinRequest{
+ _, err := handler.WaitForConnectMyComputerNodeJoin(ctx, api.WaitForConnectMyComputerNodeJoinRequest_builder{
RootClusterUri: uri.NewClusterURI(profileName).String(),
- })
+ }.Build())
waitForNodeJoinErr <- err
}()
@@ -1256,9 +1254,9 @@ func testDeleteConnectMyComputerNode(t *testing.T, pack *dbhelpers.DatabasePack)
require.NoError(t, err)
// test
- _, err = handler.DeleteConnectMyComputerNode(ctx, &api.DeleteConnectMyComputerNodeRequest{
+ _, err = handler.DeleteConnectMyComputerNode(ctx, api.DeleteConnectMyComputerNodeRequest_builder{
RootClusterUri: uri.NewClusterURI(profileName).String(),
- })
+ }.Build())
require.NoError(t, err)
// waits for the node to be deleted
@@ -1452,29 +1450,29 @@ func testListDatabaseUsersFromUnifiedResources(t *testing.T, pack *dbhelpers.Dat
require.NoError(t, err)
if accessRequestID != "" {
- _, err := handler.AssumeRole(ctx, &api.AssumeRoleRequest{
+ _, err := handler.AssumeRole(ctx, api.AssumeRoleRequest_builder{
RootClusterUri: test.dbURI.GetRootClusterURI().String(),
AccessRequestIds: []string{accessRequestID},
- })
+ }.Build())
require.NoError(t, err)
}
- res, err := handler.ListUnifiedResources(ctx, &api.ListUnifiedResourcesRequest{
+ res, err := handler.ListUnifiedResources(ctx, api.ListUnifiedResourcesRequest_builder{
ClusterUri: test.dbURI.GetClusterURI().String(),
Kinds: []string{types.KindDatabase},
- })
+ }.Build())
require.NoError(t, err)
var matchedDatabase *api.Database
- for _, resource := range res.Resources {
+ for _, resource := range res.GetResources() {
database := resource.GetDatabase()
- if database != nil && database.Uri == test.dbURI.String() {
+ if database != nil && database.GetUri() == test.dbURI.String() {
matchedDatabase = database
break
}
}
require.NotNil(t, matchedDatabase, "database %q not found in unified resources response", test.dbURI.String())
- require.Contains(t, matchedDatabase.DatabaseUsers, test.wantDBUser)
+ require.Contains(t, matchedDatabase.GetDatabaseUsers(), test.wantDBUser)
})
}
}
diff --git a/integrations/access/accessmonitoring/access_monitoring_rules.go b/integrations/access/accessmonitoring/access_monitoring_rules.go
index fc7cd79dada..b435f054713 100644
--- a/integrations/access/accessmonitoring/access_monitoring_rules.go
+++ b/integrations/access/accessmonitoring/access_monitoring_rules.go
@@ -102,9 +102,9 @@ func (amrh *RuleHandler) InitAccessMonitoringRulesCache(ctx context.Context) err
if !amrh.ruleApplies(amr) {
continue
}
- amrh.accessMonitoringRules.rules[amr.GetMetadata().Name] = amr
+ amrh.accessMonitoringRules.rules[amr.GetMetadata().GetName()] = amr
if amrh.onCacheUpdateCallback != nil {
- amrh.onCacheUpdateCallback(types.OpPut, amr.GetMetadata().Name, amr)
+ amrh.onCacheUpdateCallback(types.OpPut, amr.GetMetadata().GetName(), amr)
}
}
return nil
@@ -131,9 +131,9 @@ func (amrh *RuleHandler) HandleAccessMonitoringRule(ctx context.Context, event t
delete(amrh.accessMonitoringRules.rules, event.Resource.GetName())
return nil
}
- amrh.accessMonitoringRules.rules[req.Metadata.Name] = req
+ amrh.accessMonitoringRules.rules[req.GetMetadata().GetName()] = req
if amrh.onCacheUpdateCallback != nil {
- amrh.onCacheUpdateCallback(types.OpPut, req.GetMetadata().Name, req)
+ amrh.onCacheUpdateCallback(types.OpPut, req.GetMetadata().GetName(), req)
}
return nil
case types.OpDelete:
@@ -202,12 +202,12 @@ func (amrh *RuleHandler) getAllAccessMonitoringRules(ctx context.Context) ([]*ac
var resources []*accessmonitoringrulesv1.AccessMonitoringRule
var nextToken string
for {
- req := &accessmonitoringrulesv1.ListAccessMonitoringRulesWithFilterRequest{
+ req := accessmonitoringrulesv1.ListAccessMonitoringRulesWithFilterRequest_builder{
PageSize: defaultAccessMonitoringRulePageSize,
PageToken: nextToken,
Subjects: []string{types.KindAccessRequest},
NotificationName: amrh.pluginName,
- }
+ }.Build()
var page []*accessmonitoringrulesv1.AccessMonitoringRule
var err error
@@ -241,7 +241,7 @@ func (amrh *RuleHandler) ruleApplies(amr *accessmonitoringrulesv1.AccessMonitori
if amr.GetSpec().GetNotification().GetName() != amrh.pluginName {
return false
}
- return slices.ContainsFunc(amr.Spec.Subjects, func(subject string) bool {
+ return slices.ContainsFunc(amr.GetSpec().GetSubjects(), func(subject string) bool {
return subject == types.KindAccessRequest
})
}
diff --git a/integrations/access/accessmonitoring/access_monitoring_rules_test.go b/integrations/access/accessmonitoring/access_monitoring_rules_test.go
index 920a6316382..5973b2d2bc0 100644
--- a/integrations/access/accessmonitoring/access_monitoring_rules_test.go
+++ b/integrations/access/accessmonitoring/access_monitoring_rules_test.go
@@ -101,14 +101,14 @@ func TestRecipients(t *testing.T) {
},
})
- rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, &pb.AccessMonitoringRuleSpec{
+ rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, pb.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: `user.traits["team"].contains("example")`,
- Notification: &pb.Notification{
+ Notification: pb.Notification_builder{
Name: pluginName,
Recipients: []string{recipient},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
amrh.HandleAccessMonitoringRule(context.Background(), types.Event{
Type: types.OpPut,
@@ -181,14 +181,14 @@ func TestRecipientsWithResources(t *testing.T) {
},
})
- rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, &pb.AccessMonitoringRuleSpec{
+ rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, pb.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: `access_request.spec.resource_labels_intersection["env"].contains("dev")`,
- Notification: &pb.Notification{
+ Notification: pb.Notification_builder{
Name: pluginName,
Recipients: []string{recipient},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
err = amrh.HandleAccessMonitoringRule(context.Background(), types.Event{
Type: types.OpPut,
@@ -238,27 +238,27 @@ func TestRecipientsWithSchedules(t *testing.T) {
},
})
- rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, &pb.AccessMonitoringRuleSpec{
+ rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, pb.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Schedules: map[string]*pb.Schedule{
- "default": {
- Time: &pb.TimeSchedule{
+ "default": pb.Schedule_builder{
+ Time: pb.TimeSchedule_builder{
Shifts: []*pb.TimeSchedule_Shift{
- {
+ pb.TimeSchedule_Shift_builder{
Weekday: time.Monday.String(),
Start: "14:00",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
},
Condition: `true`,
- Notification: &pb.Notification{
+ Notification: pb.Notification_builder{
Name: pluginName,
Recipients: []string{recipient},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
err = amrh.HandleAccessMonitoringRule(context.Background(), types.Event{
Type: types.OpPut,
@@ -311,14 +311,14 @@ func TestHandleAccessMonitoringRule(t *testing.T) {
FetchRecipientCallback: mockFetchRecipient,
})
- rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, &pb.AccessMonitoringRuleSpec{
+ rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, pb.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "true",
- Notification: &pb.Notification{
+ Notification: pb.Notification_builder{
Name: "fakePluginName",
Recipients: []string{"a", "b"},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
amrh.HandleAccessMonitoringRule(context.Background(), types.Event{
Type: types.OpPut,
@@ -326,14 +326,14 @@ func TestHandleAccessMonitoringRule(t *testing.T) {
})
require.Len(t, amrh.getAccessMonitoringRules(), 1)
- rule2, err := services.NewAccessMonitoringRuleWithLabels("rule2", nil, &pb.AccessMonitoringRuleSpec{
+ rule2, err := services.NewAccessMonitoringRuleWithLabels("rule2", nil, pb.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "true",
- Notification: &pb.Notification{
+ Notification: pb.Notification_builder{
Name: "aDifferentFakePlugin",
Recipients: []string{"a", "b"},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
amrh.HandleAccessMonitoringRule(context.Background(), types.Event{
Type: types.OpPut,
@@ -354,14 +354,14 @@ func TestHandleAccessMonitoringRulePluginNameMisMatch(t *testing.T) {
FetchRecipientCallback: mockFetchRecipient,
})
- rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, &pb.AccessMonitoringRuleSpec{
+ rule1, err := services.NewAccessMonitoringRuleWithLabels("rule1", nil, pb.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "true",
- Notification: &pb.Notification{
+ Notification: pb.Notification_builder{
Name: "notTheFakePluginName",
Recipients: []string{"a", "b"},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
amrh.HandleAccessMonitoringRule(context.Background(), types.Event{
Type: types.OpPut,
@@ -369,14 +369,14 @@ func TestHandleAccessMonitoringRulePluginNameMisMatch(t *testing.T) {
})
require.Empty(t, amrh.getAccessMonitoringRules())
- rule2, err := services.NewAccessMonitoringRuleWithLabels("rule2", nil, &pb.AccessMonitoringRuleSpec{
+ rule2, err := services.NewAccessMonitoringRuleWithLabels("rule2", nil, pb.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "true",
- Notification: &pb.Notification{
+ Notification: pb.Notification_builder{
Name: "fakePluginName",
Recipients: []string{"c", "d"},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
amrh.HandleAccessMonitoringRule(context.Background(), types.Event{
Type: types.OpPut,
diff --git a/integrations/access/datadog/testlib/suite.go b/integrations/access/datadog/testlib/suite.go
index 9d3225954bd..e77f1a2ff23 100644
--- a/integrations/access/datadog/testlib/suite.go
+++ b/integrations/access/datadog/testlib/suite.go
@@ -257,23 +257,23 @@ func (s *DatadogSuiteOSS) TestRecipientsFromAccessMonitoringRule() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-datadog-amr",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "datadog",
Recipients: []string{
integration.Reviewer1UserName,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Test execution: create an access request
@@ -312,23 +312,23 @@ func (s *DatadogSuiteOSS) TestRecipientsFromAccessMonitoringRuleAfterUpdate() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-datadog-amr-2",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "datadog",
Recipients: []string{
integration.Reviewer1UserName,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
assert.NoError(t, err)
// Test execution: we create an access request
@@ -348,23 +348,23 @@ func (s *DatadogSuiteOSS) TestRecipientsFromAccessMonitoringRuleAfterUpdate() {
// Update the Access Monitoring Rule so it is no longer applied
_, err = s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- UpdateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ UpdateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-datadog-amr-2",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{"someOtherKind"},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "datadog",
Recipients: []string{
integration.Reviewer1UserName,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
assert.NoError(t, err)
// Test execution: we create an access request
diff --git a/integrations/access/discord/testlib/suite.go b/integrations/access/discord/testlib/suite.go
index 6975c5f2d01..d5bafd7f4a4 100644
--- a/integrations/access/discord/testlib/suite.go
+++ b/integrations/access/discord/testlib/suite.go
@@ -633,24 +633,24 @@ func (s *DiscordSuiteOSS) TestMessagePostingWithAMR() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &v1.Metadata{
+ Metadata: v1.Metadata_builder{
Name: "test-slack-amr-2",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "discord",
Recipients: []string{
"1001", // recipient 1
"1002", // recipient 2
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
assert.NoError(t, err)
userName := integration.RequesterOSSUserName
diff --git a/integrations/access/email/testlib/suite.go b/integrations/access/email/testlib/suite.go
index 0fc37177d52..bc63b86cf57 100644
--- a/integrations/access/email/testlib/suite.go
+++ b/integrations/access/email/testlib/suite.go
@@ -243,23 +243,23 @@ func (s *EmailSuiteOSS) TestRecipientsFromAccessMonitoringRule() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-email-amr",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "email",
Recipients: []string{
integration.Reviewer1UserName,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Test execution: create an access request
@@ -293,23 +293,23 @@ func (s *EmailSuiteOSS) TestRecipientsFromAccessMonitoringRuleAfterUpdate() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-email-amr-2",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "email",
Recipients: []string{
integration.Reviewer1UserName,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Test execution: create an access request
@@ -326,23 +326,23 @@ func (s *EmailSuiteOSS) TestRecipientsFromAccessMonitoringRuleAfterUpdate() {
// Update the Access Monitoring Rule so it is no longer applied
_, err = s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- UpdateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ UpdateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-email-amr-2",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{"someOtherKind"},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "email",
Recipients: []string{
integration.Reviewer1UserName,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Test execution: create an access request
diff --git a/integrations/access/mattermost/testlib/suite.go b/integrations/access/mattermost/testlib/suite.go
index b7a67da243a..abcd7dabec1 100644
--- a/integrations/access/mattermost/testlib/suite.go
+++ b/integrations/access/mattermost/testlib/suite.go
@@ -729,24 +729,24 @@ func (s *MattermostSuiteOSS) TestRecipientsFromAccessMonitoringRule() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &v1.Metadata{
+ Metadata: v1.Metadata_builder{
Name: "test-mattermost-amr",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "mattermost",
Recipients: []string{
"team-llama/channel-llama",
s.reviewer1MattermostUser.Email,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
assert.NoError(t, err)
userName := integration.RequesterOSSUserName
diff --git a/integrations/access/msteams/testlib/suite.go b/integrations/access/msteams/testlib/suite.go
index 1969b583e5a..f4a64d324dc 100644
--- a/integrations/access/msteams/testlib/suite.go
+++ b/integrations/access/msteams/testlib/suite.go
@@ -545,24 +545,24 @@ func (s *MsTeamsSuiteOSS) TestRecipientsFromAccessMonitoringRule() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &v1.Metadata{
+ Metadata: v1.Metadata_builder{
Name: "test-msteams-amr",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "msteams",
Recipients: []string{
s.reviewer1TeamsUser.ID,
s.reviewer2TeamsUser.Mail,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
assert.NoError(t, err)
// Test execution: create an access request
diff --git a/integrations/access/pagerduty/testlib/suite.go b/integrations/access/pagerduty/testlib/suite.go
index 8762380ede8..d9868da20c7 100644
--- a/integrations/access/pagerduty/testlib/suite.go
+++ b/integrations/access/pagerduty/testlib/suite.go
@@ -436,23 +436,23 @@ func (s *PagerdutySuiteOSS) TestRecipientsFromAccessMonitoringRule() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &v1.Metadata{
+ Metadata: v1.Metadata_builder{
Name: ruleName,
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "pagerduty",
Recipients: []string{
NotifyServiceName2,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Incident creation may happen before plugins Access Monitoring Rule cache
diff --git a/integrations/access/servicenow/testlib/suite.go b/integrations/access/servicenow/testlib/suite.go
index 026751d5fe8..739221aba96 100644
--- a/integrations/access/servicenow/testlib/suite.go
+++ b/integrations/access/servicenow/testlib/suite.go
@@ -151,23 +151,23 @@ func (s *ServiceNowSuiteOSS) TestMessagePostingWithAMR() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &v1.Metadata{
+ Metadata: v1.Metadata_builder{
Name: "test-servicenow-amr",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "servicenow",
Recipients: []string{
"someReviewer", // recipient 1
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
assert.NoError(t, err)
// Test execution: we create a new access request.
diff --git a/integrations/access/slack/testlib/suite.go b/integrations/access/slack/testlib/suite.go
index 0491daab131..dd83e46a110 100644
--- a/integrations/access/slack/testlib/suite.go
+++ b/integrations/access/slack/testlib/suite.go
@@ -261,24 +261,24 @@ func (s *SlackSuiteOSS) TestRecipientsFromAccessMonitoringRule() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &v1.Metadata{
+ Metadata: v1.Metadata_builder{
Name: "test-slack-amr",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "slack",
Recipients: []string{
s.reviewer1SlackUser.ID,
s.reviewer2SlackUser.Profile.Email,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
assert.NoError(t, err)
// Test execution: we create an access request
@@ -334,24 +334,24 @@ func (s *SlackSuiteOSS) TestRecipientsFromAccessMonitoringRuleAfterUpdate() {
_, err := s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- CreateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ CreateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &v1.Metadata{
+ Metadata: v1.Metadata_builder{
Name: "test-slack-amr-2",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "slack",
Recipients: []string{
s.reviewer1SlackUser.ID,
s.reviewer2SlackUser.Profile.Email,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
assert.NoError(t, err)
// Test execution: we create an access request
@@ -387,24 +387,24 @@ func (s *SlackSuiteOSS) TestRecipientsFromAccessMonitoringRuleAfterUpdate() {
_, err = s.ClientByName(integration.RulerUserName).
AccessMonitoringRulesClient().
- UpdateAccessMonitoringRule(ctx, &accessmonitoringrulesv1.AccessMonitoringRule{
+ UpdateAccessMonitoringRule(ctx, accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &v1.Metadata{
+ Metadata: v1.Metadata_builder{
Name: "test-slack-amr-2",
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{"someOtherKind"},
Condition: "!is_empty(access_request.spec.roles)",
- Notification: &accessmonitoringrulesv1.Notification{
+ Notification: accessmonitoringrulesv1.Notification_builder{
Name: "slack",
Recipients: []string{
s.reviewer1SlackUser.ID,
s.reviewer2SlackUser.Profile.Email,
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
assert.NoError(t, err)
messages = []slack.Message{}
diff --git a/integrations/lib/embeddedtbot/bot_test.go b/integrations/lib/embeddedtbot/bot_test.go
index eda0ab8f2bb..f0fc7ed2afe 100644
--- a/integrations/lib/embeddedtbot/bot_test.go
+++ b/integrations/lib/embeddedtbot/bot_test.go
@@ -290,70 +290,70 @@ func TestScopedBotJoinAuth(t *testing.T) {
)
// Role impersonated by the bot.
- botRole := &scopedaccessv1.ScopedRole{
+ botRole := scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: testBotRole,
- },
+ }.Build(),
Scope: testRootScope,
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{testRootScope},
Rules: []*scopedaccessv1.ScopedRule{
// The role can read scoped roles. We will use this to validate its permissions later.
- {
+ scopedaccessv1.ScopedRule_builder{
Resources: []string{scopedaccess.KindScopedRole},
Verbs: []string{types.VerbReadNoSecrets},
- },
+ }.Build(),
},
- },
- }
+ }.Build(),
+ }.Build()
require.NoError(t, scopedaccess.StrongValidateRole(botRole), "malformed role, this is a bug in the test fixture")
- _, err = adminClient.ScopedAccessServiceClient().CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
+ _, err = adminClient.ScopedAccessServiceClient().CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
Role: botRole,
- })
+ }.Build())
require.NoError(t, err)
// Create the bot.
- botResource := &machineidv1.Bot{
+ botResource := machineidv1.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: testBotName,
- },
+ }.Build(),
Spec: &machineidv1.BotSpec{},
Scope: testRootScope,
- }
- _, err = adminClient.BotServiceClient().CreateBot(ctx, &machineidv1.CreateBotRequest{
+ }.Build()
+ _, err = adminClient.BotServiceClient().CreateBot(ctx, machineidv1.CreateBotRequest_builder{
Bot: botResource,
- })
+ }.Build())
require.NoError(t, err)
// Assign role to bot
- roleAssignment := &scopedaccessv1.ScopedRoleAssignment{
+ roleAssignment := scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: testBotRole,
- },
+ }.Build(),
Scope: testRootScope,
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
Assignments: []*scopedaccessv1.Assignment{
- {
+ scopedaccessv1.Assignment_builder{
Role: testBotRole,
Scope: testRootScope,
- },
+ }.Build(),
},
BotName: testBotName,
BotScope: testRootScope,
- },
- }
+ }.Build(),
+ }.Build()
_, err = adminClient.ScopedAccessServiceClient().CreateScopedRoleAssignment(
ctx,
- &scopedaccessv1.CreateScopedRoleAssignmentRequest{
+ scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
Assignment: roleAssignment,
- })
+ }.Build())
require.NoError(t, err)
// Test setup: Wait for the role assignment to enter the auth server cache
@@ -361,14 +361,14 @@ func TestScopedBotJoinAuth(t *testing.T) {
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err := adminClient.ScopedAccessServiceClient().GetScopedRoleAssignment(
ctx,
- &scopedaccessv1.GetScopedRoleAssignmentRequest{
+ scopedaccessv1.GetScopedRoleAssignmentRequest_builder{
Name: testBotRole,
SubKind: scopedaccess.SubKindDynamic,
- },
+ }.Build(),
)
require.NoError(t, err)
require.NotNil(t, resp)
- require.NotNil(t, resp.Assignment)
+ require.NotNil(t, resp.GetAssignment())
}, 5*time.Second, 100*time.Millisecond, "expected role assignment to enter the auth cache")
// Test setup: Create a fake Kubernetes JWKS signer that will be used by the bot to join the cluster.
@@ -389,33 +389,33 @@ func TestScopedBotJoinAuth(t *testing.T) {
require.NoError(t, os.WriteFile(tokenPath, []byte(jwt), 0600))
// Test setup: Create the scoped token allowing the Bot to join with a JWT emitted by the Kube signer.
- token := &scopedjoiningv1.ScopedToken{
+ token := scopedjoiningv1.ScopedToken_builder{
Kind: scopedaccess.KindScopedToken,
Version: types.V1,
- Metadata: &headerv1.Metadata{Name: testTokenName},
+ Metadata: headerv1.Metadata_builder{Name: testTokenName}.Build(),
Scope: testRootScope,
- Spec: &scopedjoiningv1.ScopedTokenSpec{
+ Spec: scopedjoiningv1.ScopedTokenSpec_builder{
JoinMethod: string(types.JoinMethodKubernetes),
UsageMode: scopedjoining.TokenUsageModeBot,
- Kubernetes: &scopedjoiningv1.Kubernetes{
+ Kubernetes: scopedjoiningv1.Kubernetes_builder{
Allow: []*scopedjoiningv1.Kubernetes_Rule{
- {
+ scopedjoiningv1.Kubernetes_Rule_builder{
ServiceAccount: testNamespace + ":" + testServiceAccount,
- },
+ }.Build(),
},
Type: string(types.KubernetesJoinTypeStaticJWKS),
- StaticJwks: &scopedjoiningv1.Kubernetes_StaticJWKSConfig{Jwks: jwks},
- },
+ StaticJwks: scopedjoiningv1.Kubernetes_StaticJWKSConfig_builder{Jwks: jwks}.Build(),
+ }.Build(),
BotName: testBotName,
BotScope: testRootScope,
Roles: []string{string(types.RoleBot)},
- },
- }
+ }.Build(),
+ }.Build()
// Somehow the admin client interface doesn't expose CreateScopedToken ¯\_(ツ)_/¯
// We use the auth server directly to create the scoped token.
- _, err = teleportServer.Process.GetAuthServer().CreateScopedToken(ctx, &scopedjoiningv1.CreateScopedTokenRequest{
+ _, err = teleportServer.Process.GetAuthServer().CreateScopedToken(ctx, scopedjoiningv1.CreateScopedTokenRequest_builder{
Token: token,
- })
+ }.Build())
require.NoError(t, err)
// Test setup: Configure the bot to join the auth using the scoped join token and the JWT.
@@ -452,8 +452,8 @@ func TestScopedBotJoinAuth(t *testing.T) {
require.NoError(t, err)
require.Equal(t, clusterName, botPong.ClusterName)
- _, err = botClient.ScopedAccessServiceClient().GetScopedRole(ctx, &scopedaccessv1.GetScopedRoleRequest{
+ _, err = botClient.ScopedAccessServiceClient().GetScopedRole(ctx, scopedaccessv1.GetScopedRoleRequest_builder{
Name: testBotRole,
- })
+ }.Build())
require.NoError(t, err)
}
diff --git a/integrations/operator/apis/resources/v1/accessmonitoringrulev1_types.go b/integrations/operator/apis/resources/v1/accessmonitoringrulev1_types.go
index e4852e9afc1..8036defd1f6 100644
--- a/integrations/operator/apis/resources/v1/accessmonitoringrulev1_types.go
+++ b/integrations/operator/apis/resources/v1/accessmonitoringrulev1_types.go
@@ -59,16 +59,16 @@ type TeleportAccessMonitoringRuleV1List struct {
// ToTeleport returns an AccessMonitoringRule that can be sent to Teleport.
func (l *TeleportAccessMonitoringRuleV1) ToTeleport() *accessmonitoringrulesv1pb.AccessMonitoringRule {
- resource := &accessmonitoringrulesv1pb.AccessMonitoringRule{
+ resource := accessmonitoringrulesv1pb.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: l.Name,
Description: l.Annotations[teleportcr.DescriptionKey],
Labels: l.Labels,
- },
+ }.Build(),
Spec: (*accessmonitoringrulesv1pb.AccessMonitoringRuleSpec)(l.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/autoupdateconfigv1_types.go b/integrations/operator/apis/resources/v1/autoupdateconfigv1_types.go
index df0be6bfa98..7006fb28596 100644
--- a/integrations/operator/apis/resources/v1/autoupdateconfigv1_types.go
+++ b/integrations/operator/apis/resources/v1/autoupdateconfigv1_types.go
@@ -65,16 +65,16 @@ type TeleportAutoupdateConfigV1List struct {
// ToTeleport returns an AutoUpdateConfig that can be sent to Teleport.
func (l *TeleportAutoupdateConfigV1) ToTeleport() *autoupdatev1pb.AutoUpdateConfig {
- resource := &autoupdatev1pb.AutoUpdateConfig{
+ resource := autoupdatev1pb.AutoUpdateConfig_builder{
Kind: types.KindAutoUpdateConfig,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: l.Name,
Description: l.Annotations[teleportcr.DescriptionKey],
Labels: l.Labels,
- },
+ }.Build(),
Spec: (*autoupdatev1pb.AutoUpdateConfigSpec)(l.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/autoupdateversionv1_types.go b/integrations/operator/apis/resources/v1/autoupdateversionv1_types.go
index 3f127165397..217f6cca061 100644
--- a/integrations/operator/apis/resources/v1/autoupdateversionv1_types.go
+++ b/integrations/operator/apis/resources/v1/autoupdateversionv1_types.go
@@ -65,16 +65,16 @@ type TeleportAutoupdateVersionV1List struct {
// ToTeleport returns an AutoUpdateVersion that can be sent to Teleport.
func (l *TeleportAutoupdateVersionV1) ToTeleport() *autoupdatev1pb.AutoUpdateVersion {
- resource := &autoupdatev1pb.AutoUpdateVersion{
+ resource := autoupdatev1pb.AutoUpdateVersion_builder{
Kind: types.KindAutoUpdateVersion,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: l.Name,
Description: l.Annotations[teleportcr.DescriptionKey],
Labels: l.Labels,
- },
+ }.Build(),
Spec: (*autoupdatev1pb.AutoUpdateVersionSpec)(l.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/botv1_types.go b/integrations/operator/apis/resources/v1/botv1_types.go
index dd9f524cb49..266a708e96a 100644
--- a/integrations/operator/apis/resources/v1/botv1_types.go
+++ b/integrations/operator/apis/resources/v1/botv1_types.go
@@ -62,17 +62,17 @@ type TeleportBotV1List struct {
// [machineidv1.Bot] and implements the necessary interface methods used
// by the TeleportResourceReconciler.
func (l *TeleportBotV1) ToTeleport() *machineidv1.Bot {
- resource := &machineidv1.Bot{
+ resource := machineidv1.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: l.Name,
Description: l.Annotations[teleportcr.DescriptionKey],
Labels: l.Labels,
- },
+ }.Build(),
Spec: (*machineidv1.BotSpec)(l.Spec),
Scope: l.Scope,
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/inference_model_types.go b/integrations/operator/apis/resources/v1/inference_model_types.go
index f5e1423207a..f94e11b4208 100644
--- a/integrations/operator/apis/resources/v1/inference_model_types.go
+++ b/integrations/operator/apis/resources/v1/inference_model_types.go
@@ -60,16 +60,16 @@ type TeleportInferenceModelList struct {
// ToTeleport returns a Teleport representation of this Kubernetes resource.
func (m *TeleportInferenceModel) ToTeleport() *summarizerv1.InferenceModel {
- resource := &summarizerv1.InferenceModel{
+ resource := summarizerv1.InferenceModel_builder{
Kind: types.KindInferenceModel,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: m.Name,
Description: m.Annotations[teleportcr.DescriptionKey],
Labels: m.Labels,
- },
+ }.Build(),
Spec: (*summarizerv1.InferenceModelSpec)(m.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/inference_policy_types.go b/integrations/operator/apis/resources/v1/inference_policy_types.go
index 36a9b9d5c7d..d04af9ededf 100644
--- a/integrations/operator/apis/resources/v1/inference_policy_types.go
+++ b/integrations/operator/apis/resources/v1/inference_policy_types.go
@@ -60,16 +60,16 @@ type TeleportInferencePolicyList struct {
// ToTeleport returns a Teleport representation of this Kubernetes resource.
func (p *TeleportInferencePolicy) ToTeleport() *summarizerv1.InferencePolicy {
- resource := &summarizerv1.InferencePolicy{
+ resource := summarizerv1.InferencePolicy_builder{
Kind: types.KindInferencePolicy,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: p.Name,
Description: p.Annotations[teleportcr.DescriptionKey],
Labels: p.Labels,
- },
+ }.Build(),
Spec: (*summarizerv1.InferencePolicySpec)(p.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/inference_secret_types.go b/integrations/operator/apis/resources/v1/inference_secret_types.go
index 5e071cf88e3..824f9437153 100644
--- a/integrations/operator/apis/resources/v1/inference_secret_types.go
+++ b/integrations/operator/apis/resources/v1/inference_secret_types.go
@@ -60,16 +60,16 @@ type TeleportInferenceSecretList struct {
// ToTeleport returns a Teleport representation of this Kubernetes resource.
func (s *TeleportInferenceSecret) ToTeleport() *summarizerv1.InferenceSecret {
- resource := &summarizerv1.InferenceSecret{
+ resource := summarizerv1.InferenceSecret_builder{
Kind: types.KindInferenceSecret,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: s.Name,
Description: s.Annotations[teleportcr.DescriptionKey],
Labels: s.Labels,
- },
+ }.Build(),
Spec: (*summarizerv1.InferenceSecretSpec)(s.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/loginrule_types.go b/integrations/operator/apis/resources/v1/loginrule_types.go
index 4937e85f0a2..bdcb734c475 100644
--- a/integrations/operator/apis/resources/v1/loginrule_types.go
+++ b/integrations/operator/apis/resources/v1/loginrule_types.go
@@ -65,7 +65,7 @@ type TeleportLoginRuleList struct {
// by the TeleportResourceReconciler.
func (l TeleportLoginRule) ToTeleport() *LoginRuleResource {
resource := &LoginRuleResource{
- LoginRule: &loginrulepb.LoginRule{
+ LoginRule: loginrulepb.LoginRule_builder{
Metadata: &types.Metadata{
Name: l.Name,
Labels: l.Labels,
@@ -74,13 +74,13 @@ func (l TeleportLoginRule) ToTeleport() *LoginRuleResource {
Version: types.V1,
Priority: l.Spec.Priority,
TraitsExpression: l.Spec.TraitsExpression,
- },
+ }.Build(),
}
if len(l.Spec.TraitsMap) > 0 {
- resource.LoginRule.TraitsMap = make(map[string]*wrappers.StringValues, len(l.Spec.TraitsMap))
+ resource.LoginRule.SetTraitsMap(make(map[string]*wrappers.StringValues, len(l.Spec.TraitsMap)))
}
for traitKey, traitExpressions := range l.Spec.TraitsMap {
- resource.LoginRule.TraitsMap[traitKey] = &wrappers.StringValues{Values: traitExpressions}
+ resource.LoginRule.GetTraitsMap()[traitKey] = &wrappers.StringValues{Values: traitExpressions}
}
return resource
}
@@ -100,21 +100,21 @@ type LoginRuleResource struct {
}
func (l *LoginRuleResource) GetName() string {
- return l.LoginRule.Metadata.Name
+ return l.LoginRule.GetMetadata().Name
}
func (l *LoginRuleResource) SetOrigin(origin string) {
- l.LoginRule.Metadata.SetOrigin(origin)
+ l.LoginRule.GetMetadata().SetOrigin(origin)
}
func (l *LoginRuleResource) Origin() string {
- return l.LoginRule.Metadata.Origin()
+ return l.LoginRule.GetMetadata().Origin()
}
func (l *LoginRuleResource) GetRevision() string {
- return l.LoginRule.Metadata.GetRevision()
+ return l.LoginRule.GetMetadata().GetRevision()
}
func (l *LoginRuleResource) SetRevision(rev string) {
- l.LoginRule.Metadata.SetRevision(rev)
+ l.LoginRule.GetMetadata().SetRevision(rev)
}
diff --git a/integrations/operator/apis/resources/v1/retrieval_model_types.go b/integrations/operator/apis/resources/v1/retrieval_model_types.go
index 9742c79458f..1fa76116759 100644
--- a/integrations/operator/apis/resources/v1/retrieval_model_types.go
+++ b/integrations/operator/apis/resources/v1/retrieval_model_types.go
@@ -62,16 +62,16 @@ type TeleportRetrievalModelV1List struct {
// the Kubernetes CR name, because RetrievalModel is a singleton that can only
// exist under that fixed name.
func (l *TeleportRetrievalModelV1) ToTeleport() *summarizerv1.RetrievalModel {
- resource := &summarizerv1.RetrievalModel{
+ resource := summarizerv1.RetrievalModel_builder{
Kind: types.KindRetrievalModel,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: types.MetaNameRetrievalModel,
Description: l.Annotations[teleportcr.DescriptionKey],
Labels: l.Labels,
- },
+ }.Build(),
Spec: (*summarizerv1.RetrievalModelSpec)(l.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/scopedrole_types.go b/integrations/operator/apis/resources/v1/scopedrole_types.go
index 1c66550a16f..8b6b52fb3fb 100644
--- a/integrations/operator/apis/resources/v1/scopedrole_types.go
+++ b/integrations/operator/apis/resources/v1/scopedrole_types.go
@@ -60,17 +60,17 @@ type TeleportScopedRoleV1List struct {
// ToTeleport returns a Teleport representation of this Kubernetes resource.
func (m *TeleportScopedRoleV1) ToTeleport() *accessv1.ScopedRole {
- resource := &accessv1.ScopedRole{
+ resource := accessv1.ScopedRole_builder{
Kind: access.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: m.Name,
Description: m.Annotations[teleportcr.DescriptionKey],
Labels: m.Labels,
- },
+ }.Build(),
Scope: m.Scope,
Spec: (*accessv1.ScopedRoleSpec)(m.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/scopedroleassignment_types.go b/integrations/operator/apis/resources/v1/scopedroleassignment_types.go
index 9cd3786c2a8..1df03cee853 100644
--- a/integrations/operator/apis/resources/v1/scopedroleassignment_types.go
+++ b/integrations/operator/apis/resources/v1/scopedroleassignment_types.go
@@ -60,18 +60,18 @@ type TeleportScopedRoleAssignmentV1List struct {
// ToTeleport returns a Teleport representation of this Kubernetes resource.
func (m *TeleportScopedRoleAssignmentV1) ToTeleport() *accessv1.ScopedRoleAssignment {
- resource := &accessv1.ScopedRoleAssignment{
+ resource := accessv1.ScopedRoleAssignment_builder{
Kind: access.KindScopedRoleAssignment,
SubKind: access.SubKindDynamic,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: m.Name,
Description: m.Annotations[teleportcr.DescriptionKey],
Labels: m.Labels,
- },
+ }.Build(),
Scope: m.Scope,
Spec: (*accessv1.ScopedRoleAssignmentSpec)(m.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/scopedtoken_types.go b/integrations/operator/apis/resources/v1/scopedtoken_types.go
index 62ee5f3020c..2372730ac7b 100644
--- a/integrations/operator/apis/resources/v1/scopedtoken_types.go
+++ b/integrations/operator/apis/resources/v1/scopedtoken_types.go
@@ -59,17 +59,17 @@ type TeleportScopedTokenV1List struct {
// ToTeleport returns a Teleport representation of this Kubernetes resource.
func (m *TeleportScopedTokenV1) ToTeleport() *tokenv1.ScopedToken {
- resource := &tokenv1.ScopedToken{
+ resource := tokenv1.ScopedToken_builder{
Kind: types.KindScopedToken,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: m.Name,
Description: m.Annotations[teleportcr.DescriptionKey],
Labels: m.Labels,
- },
+ }.Build(),
Scope: m.Scope,
Spec: (*tokenv1.ScopedTokenSpec)(m.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/apis/resources/v1/workload_identityv1_types.go b/integrations/operator/apis/resources/v1/workload_identityv1_types.go
index 9ac642f8b88..74d89794802 100644
--- a/integrations/operator/apis/resources/v1/workload_identityv1_types.go
+++ b/integrations/operator/apis/resources/v1/workload_identityv1_types.go
@@ -62,16 +62,16 @@ type TeleportWorkloadIdentityV1List struct {
// [workloadidentityv1.WorkloadIdentity] and implements the necessary interface
// methods used by the TeleportResourceReconciler.
func (l *TeleportWorkloadIdentityV1) ToTeleport() *workloadidentityv1.WorkloadIdentity {
- resource := &workloadidentityv1.WorkloadIdentity{
+ resource := workloadidentityv1.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: l.Name,
Description: l.Annotations[teleportcr.DescriptionKey],
Labels: l.Labels,
- },
+ }.Build(),
Spec: (*workloadidentityv1.WorkloadIdentitySpec)(l.Spec),
- }
+ }.Build()
return resource
}
diff --git a/integrations/operator/controllers/reconcilers/resource153.go b/integrations/operator/controllers/reconcilers/resource153.go
index f6466172f52..d0d615a592a 100644
--- a/integrations/operator/controllers/reconcilers/resource153.go
+++ b/integrations/operator/controllers/reconcilers/resource153.go
@@ -57,12 +57,12 @@ func (a Resource153Adapter[T]) GetResourceOrigin(res T) string {
// SetResourceRevision implements the Adapter interface.
func (a Resource153Adapter[T]) SetResourceRevision(res T, revision string) {
- res.GetMetadata().Revision = revision
+ res.GetMetadata().SetRevision(revision)
}
// SetResourceLabels implements the Adapter interface.
func (a Resource153Adapter[T]) SetResourceLabels(res T, labels map[string]string) {
- res.GetMetadata().Labels = labels
+ res.GetMetadata().SetLabels(labels)
}
// NewTeleportResource153Reconciler instantiates a resourceReconciler for a
diff --git a/integrations/operator/controllers/resources/accessmonitoringrulev1_controller_test.go b/integrations/operator/controllers/resources/accessmonitoringrulev1_controller_test.go
index 7698717bbbb..f21733778eb 100644
--- a/integrations/operator/controllers/resources/accessmonitoringrulev1_controller_test.go
+++ b/integrations/operator/controllers/resources/accessmonitoringrulev1_controller_test.go
@@ -36,14 +36,14 @@ import (
"github.com/gravitational/teleport/integrations/operator/controllers/resources/testlib"
)
-var accessMonitoringRuleSpec = &accessmonitoringrulesv1pb.AccessMonitoringRuleSpec{
+var accessMonitoringRuleSpec = accessmonitoringrulesv1pb.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: "access_request.spec.roles.contains(\"your_role_name\")",
- Notification: &accessmonitoringrulesv1pb.Notification{
+ Notification: accessmonitoringrulesv1pb.Notification_builder{
Name: "slack",
Recipients: []string{"your-slack-channel"},
- },
-}
+ }.Build(),
+}.Build()
type accessMonitoringRuleTestingPrimitives struct {
setup *testSetup
@@ -59,17 +59,17 @@ func (g *accessMonitoringRuleTestingPrimitives) SetupTeleportFixtures(ctx contex
}
func (g *accessMonitoringRuleTestingPrimitives) CreateTeleportResource(ctx context.Context, name string) error {
- accessMonitoringRule := &accessmonitoringrulesv1pb.AccessMonitoringRule{
+ accessMonitoringRule := accessmonitoringrulesv1pb.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Spec: accessMonitoringRuleSpec,
- }
+ }.Build()
_, err := g.setup.TeleportClient.AccessMonitoringRulesClient().
CreateAccessMonitoringRule(ctx, accessMonitoringRule)
return trace.Wrap(err)
@@ -124,7 +124,7 @@ func (g *accessMonitoringRuleTestingPrimitives) ModifyKubernetesResource(ctx con
if err != nil {
return trace.Wrap(err)
}
- accessMonitoringRule.Spec.Notification.Recipients = []string{"your-slack-channel", "your-other-slack-channel"}
+ accessMonitoringRule.Spec.Notification.SetRecipients([]string{"your-slack-channel", "your-other-slack-channel"})
return trace.Wrap(g.setup.K8sClient.Update(ctx, accessMonitoringRule))
}
diff --git a/integrations/operator/controllers/resources/autoupdateconfig_controller_test.go b/integrations/operator/controllers/resources/autoupdateconfig_controller_test.go
index 680202706b2..452ff9657c5 100644
--- a/integrations/operator/controllers/resources/autoupdateconfig_controller_test.go
+++ b/integrations/operator/controllers/resources/autoupdateconfig_controller_test.go
@@ -38,35 +38,35 @@ import (
"github.com/gravitational/teleport/integrations/operator/controllers/resources/testlib"
)
-var autoUpdateConfigSpec = &autoupdatev1pb.AutoUpdateConfigSpec{
+var autoUpdateConfigSpec = autoupdatev1pb.AutoUpdateConfigSpec_builder{
Tools: nil,
- Agents: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ Agents: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "dev",
Days: []string{"*"},
StartHour: 12,
WaitHours: 0,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "stage",
Days: []string{"*"},
StartHour: 12,
WaitHours: 24,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "prod",
Days: []string{"Mon", "Tue", "Wed", "Thu"},
StartHour: 12,
WaitHours: 24,
- },
+ }.Build(),
},
- },
- },
-}
+ }.Build(),
+ }.Build(),
+}.Build()
type autoUpdateConfigTestingPrimitives struct {
setup *testSetup
@@ -82,17 +82,17 @@ func (g *autoUpdateConfigTestingPrimitives) SetupTeleportFixtures(ctx context.Co
}
func (g *autoUpdateConfigTestingPrimitives) CreateTeleportResource(ctx context.Context, name string) error {
- autoUpdateConfig := &autoupdatev1pb.AutoUpdateConfig{
+ autoUpdateConfig := autoupdatev1pb.AutoUpdateConfig_builder{
Kind: types.KindAutoUpdateConfig,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: types.MetaNameAutoUpdateConfig,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Spec: autoUpdateConfigSpec,
- }
+ }.Build()
_, err := g.setup.TeleportClient.
CreateAutoUpdateConfig(ctx, autoUpdateConfig)
return trace.Wrap(err)
@@ -147,10 +147,10 @@ func (g *autoUpdateConfigTestingPrimitives) ModifyKubernetesResource(ctx context
if err != nil {
return trace.Wrap(err)
}
- autoUpdateConfig.Spec.Agents.Mode = autoupdate.AgentsUpdateModeSuspended
- autoUpdateConfig.Spec.Tools = &autoupdatev1pb.AutoUpdateConfigSpecTools{
+ autoUpdateConfig.Spec.Agents.SetMode(autoupdate.AgentsUpdateModeSuspended)
+ autoUpdateConfig.Spec.Tools = autoupdatev1pb.AutoUpdateConfigSpecTools_builder{
Mode: autoupdate.ToolsUpdateModeEnabled,
- }
+ }.Build()
return trace.Wrap(g.setup.K8sClient.Update(ctx, autoUpdateConfig))
}
diff --git a/integrations/operator/controllers/resources/autoupdateversion_controller_test.go b/integrations/operator/controllers/resources/autoupdateversion_controller_test.go
index bbd0a8de6e5..db74091d6df 100644
--- a/integrations/operator/controllers/resources/autoupdateversion_controller_test.go
+++ b/integrations/operator/controllers/resources/autoupdateversion_controller_test.go
@@ -38,15 +38,15 @@ import (
"github.com/gravitational/teleport/integrations/operator/controllers/resources/testlib"
)
-var autoUpdateVersionSpec = &autoupdatev1pb.AutoUpdateVersionSpec{
+var autoUpdateVersionSpec = autoupdatev1pb.AutoUpdateVersionSpec_builder{
Tools: nil,
- Agents: &autoupdatev1pb.AutoUpdateVersionSpecAgents{
+ Agents: autoupdatev1pb.AutoUpdateVersionSpecAgents_builder{
StartVersion: "1.2.3",
TargetVersion: "1.2.4",
Schedule: autoupdate.AgentsScheduleRegular,
Mode: autoupdate.AgentsUpdateModeEnabled,
- },
-}
+ }.Build(),
+}.Build()
type autoUpdateVersionTestingPrimitives struct {
setup *testSetup
@@ -62,17 +62,17 @@ func (g *autoUpdateVersionTestingPrimitives) SetupTeleportFixtures(ctx context.C
}
func (g *autoUpdateVersionTestingPrimitives) CreateTeleportResource(ctx context.Context, name string) error {
- autoUpdateVersion := &autoupdatev1pb.AutoUpdateVersion{
+ autoUpdateVersion := autoupdatev1pb.AutoUpdateVersion_builder{
Kind: types.KindAutoUpdateVersion,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: types.MetaNameAutoUpdateVersion,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Spec: autoUpdateVersionSpec,
- }
+ }.Build()
_, err := g.setup.TeleportClient.
CreateAutoUpdateVersion(ctx, autoUpdateVersion)
return trace.Wrap(err)
@@ -127,10 +127,10 @@ func (g *autoUpdateVersionTestingPrimitives) ModifyKubernetesResource(ctx contex
if err != nil {
return trace.Wrap(err)
}
- autoUpdateVersion.Spec.Agents.Mode = autoupdate.AgentsUpdateModeSuspended
- autoUpdateVersion.Spec.Tools = &autoupdatev1pb.AutoUpdateVersionSpecTools{
+ autoUpdateVersion.Spec.Agents.SetMode(autoupdate.AgentsUpdateModeSuspended)
+ autoUpdateVersion.Spec.Tools = autoupdatev1pb.AutoUpdateVersionSpecTools_builder{
TargetVersion: "1.2.4",
- }
+ }.Build()
return trace.Wrap(g.setup.K8sClient.Update(ctx, autoUpdateVersion))
}
diff --git a/integrations/operator/controllers/resources/botv1_controller.go b/integrations/operator/controllers/resources/botv1_controller.go
index c7ddffd9844..7f280e77bbf 100644
--- a/integrations/operator/controllers/resources/botv1_controller.go
+++ b/integrations/operator/controllers/resources/botv1_controller.go
@@ -40,7 +40,7 @@ type botClient struct {
func (l botClient) Get(ctx context.Context, name string) (*machineidv1.Bot, error) {
resp, err := l.teleportClient.
BotServiceClient().
- GetBot(ctx, &machineidv1.GetBotRequest{BotName: name})
+ GetBot(ctx, machineidv1.GetBotRequest_builder{BotName: name}.Build())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -51,7 +51,7 @@ func (l botClient) Get(ctx context.Context, name string) (*machineidv1.Bot, erro
func (l botClient) Create(ctx context.Context, resource *machineidv1.Bot) error {
_, err := l.teleportClient.
BotServiceClient().
- CreateBot(ctx, &machineidv1.CreateBotRequest{Bot: resource})
+ CreateBot(ctx, machineidv1.CreateBotRequest_builder{Bot: resource}.Build())
return trace.Wrap(err)
}
@@ -59,7 +59,7 @@ func (l botClient) Create(ctx context.Context, resource *machineidv1.Bot) error
func (l botClient) Update(ctx context.Context, resource *machineidv1.Bot) error {
_, err := l.teleportClient.
BotServiceClient().
- UpsertBot(ctx, &machineidv1.UpsertBotRequest{Bot: resource})
+ UpsertBot(ctx, machineidv1.UpsertBotRequest_builder{Bot: resource}.Build())
return trace.Wrap(err)
}
@@ -67,7 +67,7 @@ func (l botClient) Update(ctx context.Context, resource *machineidv1.Bot) error
func (l botClient) Delete(ctx context.Context, name string) error {
_, err := l.teleportClient.
BotServiceClient().
- DeleteBot(ctx, &machineidv1.DeleteBotRequest{BotName: name})
+ DeleteBot(ctx, machineidv1.DeleteBotRequest_builder{BotName: name}.Build())
return trace.Wrap(err)
}
diff --git a/integrations/operator/controllers/resources/botv1_controller_test.go b/integrations/operator/controllers/resources/botv1_controller_test.go
index c0a8c0a726a..2673e13faae 100644
--- a/integrations/operator/controllers/resources/botv1_controller_test.go
+++ b/integrations/operator/controllers/resources/botv1_controller_test.go
@@ -40,22 +40,22 @@ import (
"github.com/gravitational/teleport/lib/defaults"
)
-var botSpec = &machineidv1.BotSpec{
+var botSpec = machineidv1.BotSpec_builder{
Roles: []string{"roleA", "roleB"},
Traits: []*machineidv1.Trait{
- {
+ machineidv1.Trait_builder{
Name: "traitA",
Values: []string{"valueA", "valueB"},
- },
- {
+ }.Build(),
+ machineidv1.Trait_builder{
Name: "traitB",
Values: []string{"valueC", "valueD"},
- },
+ }.Build(),
},
// Note: The server-side resource will have the default value filled in, so
// we need to explicitly set it to ensure comparisons succeed.
MaxSessionTtl: durationpb.New(defaults.DefaultBotMaxSessionTTL),
-}
+}.Build()
type botTestingPrimitives struct {
setup *testSetup
@@ -71,27 +71,27 @@ func (g *botTestingPrimitives) SetupTeleportFixtures(ctx context.Context) error
}
func (g *botTestingPrimitives) CreateTeleportResource(ctx context.Context, name string) error {
- bot := &machineidv1.Bot{
+ bot := machineidv1.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Spec: botSpec,
- }
+ }.Build()
_, err := g.setup.TeleportClient.
BotServiceClient().
- CreateBot(ctx, &machineidv1.CreateBotRequest{Bot: bot})
+ CreateBot(ctx, machineidv1.CreateBotRequest_builder{Bot: bot}.Build())
return trace.Wrap(err)
}
func (g *botTestingPrimitives) GetTeleportResource(ctx context.Context, name string) (*machineidv1.Bot, error) {
resp, err := g.setup.TeleportClient.
BotServiceClient().
- GetBot(ctx, &machineidv1.GetBotRequest{BotName: name})
+ GetBot(ctx, machineidv1.GetBotRequest_builder{BotName: name}.Build())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -101,7 +101,7 @@ func (g *botTestingPrimitives) GetTeleportResource(ctx context.Context, name str
func (g *botTestingPrimitives) DeleteTeleportResource(ctx context.Context, name string) error {
_, err := g.setup.TeleportClient.
BotServiceClient().
- DeleteBot(ctx, &machineidv1.DeleteBotRequest{BotName: name})
+ DeleteBot(ctx, machineidv1.DeleteBotRequest_builder{BotName: name}.Build())
if err != nil {
return trace.Wrap(err)
}
@@ -156,7 +156,7 @@ func (g *botTestingPrimitives) CompareTeleportAndKubernetesResource(
testlib.ProtoCompareOptions(
protocmp.IgnoreFields(&machineidv1.Bot{}, "status"),
protocmp.SortRepeated(func(a, b *machineidv1.Trait) bool {
- return strings.Compare(a.Name, b.Name) == -1
+ return strings.Compare(a.GetName(), b.GetName()) == -1
}),
)...,
)
diff --git a/integrations/operator/controllers/resources/inference_model_controller.go b/integrations/operator/controllers/resources/inference_model_controller.go
index 075cb852679..25c91a9a2b2 100644
--- a/integrations/operator/controllers/resources/inference_model_controller.go
+++ b/integrations/operator/controllers/resources/inference_model_controller.go
@@ -40,13 +40,13 @@ func (c inferenceModelClient) Get(
ctx context.Context, name string,
) (*summarizerv1.InferenceModel, error) {
resp, err := c.teleportClient.SummarizerServiceClient().GetInferenceModel(
- ctx, &summarizerv1.GetInferenceModelRequest{Name: name},
+ ctx, summarizerv1.GetInferenceModelRequest_builder{Name: name}.Build(),
)
if err != nil {
return nil, trace.Wrap(err)
}
- return resp.Model, nil
+ return resp.GetModel(), nil
}
// Create creates an inference model in Teleport.
@@ -54,7 +54,7 @@ func (c inferenceModelClient) Create(
ctx context.Context, model *summarizerv1.InferenceModel,
) error {
_, err := c.teleportClient.SummarizerServiceClient().CreateInferenceModel(
- ctx, &summarizerv1.CreateInferenceModelRequest{Model: model},
+ ctx, summarizerv1.CreateInferenceModelRequest_builder{Model: model}.Build(),
)
return trace.Wrap(err)
}
@@ -64,7 +64,7 @@ func (c inferenceModelClient) Update(
ctx context.Context, model *summarizerv1.InferenceModel,
) error {
_, err := c.teleportClient.SummarizerServiceClient().UpdateInferenceModel(
- ctx, &summarizerv1.UpdateInferenceModelRequest{Model: model},
+ ctx, summarizerv1.UpdateInferenceModelRequest_builder{Model: model}.Build(),
)
return trace.Wrap(err)
}
@@ -72,7 +72,7 @@ func (c inferenceModelClient) Update(
// Delete deletes an inference model with a given name from Teleport.
func (c inferenceModelClient) Delete(ctx context.Context, name string) error {
_, err := c.teleportClient.SummarizerServiceClient().DeleteInferenceModel(
- ctx, &summarizerv1.DeleteInferenceModelRequest{Name: name},
+ ctx, summarizerv1.DeleteInferenceModelRequest_builder{Name: name}.Build(),
)
return trace.Wrap(err)
}
diff --git a/integrations/operator/controllers/resources/inference_policy_controller.go b/integrations/operator/controllers/resources/inference_policy_controller.go
index b22188ce6c4..8f6d4fefb52 100644
--- a/integrations/operator/controllers/resources/inference_policy_controller.go
+++ b/integrations/operator/controllers/resources/inference_policy_controller.go
@@ -40,13 +40,13 @@ func (c inferencePolicyClient) Get(
ctx context.Context, name string,
) (*summarizerv1.InferencePolicy, error) {
resp, err := c.teleportClient.SummarizerServiceClient().GetInferencePolicy(
- ctx, &summarizerv1.GetInferencePolicyRequest{Name: name},
+ ctx, summarizerv1.GetInferencePolicyRequest_builder{Name: name}.Build(),
)
if err != nil {
return nil, trace.Wrap(err)
}
- return resp.Policy, nil
+ return resp.GetPolicy(), nil
}
// Create creates an inference policy in Teleport.
@@ -54,7 +54,7 @@ func (c inferencePolicyClient) Create(
ctx context.Context, policy *summarizerv1.InferencePolicy,
) error {
_, err := c.teleportClient.SummarizerServiceClient().CreateInferencePolicy(
- ctx, &summarizerv1.CreateInferencePolicyRequest{Policy: policy},
+ ctx, summarizerv1.CreateInferencePolicyRequest_builder{Policy: policy}.Build(),
)
return trace.Wrap(err)
}
@@ -64,7 +64,7 @@ func (c inferencePolicyClient) Update(
ctx context.Context, policy *summarizerv1.InferencePolicy,
) error {
_, err := c.teleportClient.SummarizerServiceClient().UpdateInferencePolicy(
- ctx, &summarizerv1.UpdateInferencePolicyRequest{Policy: policy},
+ ctx, summarizerv1.UpdateInferencePolicyRequest_builder{Policy: policy}.Build(),
)
return trace.Wrap(err)
}
@@ -72,7 +72,7 @@ func (c inferencePolicyClient) Update(
// Delete deletes an inference policy with a given name from Teleport.
func (c inferencePolicyClient) Delete(ctx context.Context, name string) error {
_, err := c.teleportClient.SummarizerServiceClient().DeleteInferencePolicy(
- ctx, &summarizerv1.DeleteInferencePolicyRequest{Name: name},
+ ctx, summarizerv1.DeleteInferencePolicyRequest_builder{Name: name}.Build(),
)
return trace.Wrap(err)
}
diff --git a/integrations/operator/controllers/resources/inference_secret_controller.go b/integrations/operator/controllers/resources/inference_secret_controller.go
index 8517320bbf1..25f5f9d3df9 100644
--- a/integrations/operator/controllers/resources/inference_secret_controller.go
+++ b/integrations/operator/controllers/resources/inference_secret_controller.go
@@ -40,19 +40,19 @@ type inferenceSecretClient struct {
// Get gets an inference secret with a given name from Teleport.
func (c inferenceSecretClient) Get(ctx context.Context, name string) (*summarizerv1.InferenceSecret, error) {
resp, err := c.teleportClient.SummarizerServiceClient().GetInferenceSecret(
- ctx, &summarizerv1.GetInferenceSecretRequest{Name: name},
+ ctx, summarizerv1.GetInferenceSecretRequest_builder{Name: name}.Build(),
)
if err != nil {
return nil, trace.Wrap(err)
}
- return resp.Secret, nil
+ return resp.GetSecret(), nil
}
// Create creates an inference secret in Teleport.
func (c inferenceSecretClient) Create(ctx context.Context, secret *summarizerv1.InferenceSecret) error {
_, err := c.teleportClient.SummarizerServiceClient().CreateInferenceSecret(
- ctx, &summarizerv1.CreateInferenceSecretRequest{Secret: secret},
+ ctx, summarizerv1.CreateInferenceSecretRequest_builder{Secret: secret}.Build(),
)
return trace.Wrap(err)
}
@@ -60,7 +60,7 @@ func (c inferenceSecretClient) Create(ctx context.Context, secret *summarizerv1.
// Update updates an existing inference secret in Teleport.
func (c inferenceSecretClient) Update(ctx context.Context, secret *summarizerv1.InferenceSecret) error {
_, err := c.teleportClient.SummarizerServiceClient().UpdateInferenceSecret(
- ctx, &summarizerv1.UpdateInferenceSecretRequest{Secret: secret},
+ ctx, summarizerv1.UpdateInferenceSecretRequest_builder{Secret: secret}.Build(),
)
return trace.Wrap(err)
}
@@ -68,7 +68,7 @@ func (c inferenceSecretClient) Update(ctx context.Context, secret *summarizerv1.
// Delete deletes an inference secret with a given name from Teleport.
func (c inferenceSecretClient) Delete(ctx context.Context, name string) error {
_, err := c.teleportClient.SummarizerServiceClient().DeleteInferenceSecret(
- ctx, &summarizerv1.DeleteInferenceSecretRequest{Name: name},
+ ctx, summarizerv1.DeleteInferenceSecretRequest_builder{Name: name}.Build(),
)
return trace.Wrap(err)
}
@@ -81,7 +81,7 @@ func (c inferenceSecretClient) Mutate(ctx context.Context, new, _ *summarizerv1.
if err != nil {
return trace.Wrap(err)
}
- new.Spec.Value = resolvedSecret
+ new.GetSpec().SetValue(resolvedSecret)
}
return nil
}
diff --git a/integrations/operator/controllers/resources/retrieval_model_controller.go b/integrations/operator/controllers/resources/retrieval_model_controller.go
index 5f537f4d08a..4bb00df60b9 100644
--- a/integrations/operator/controllers/resources/retrieval_model_controller.go
+++ b/integrations/operator/controllers/resources/retrieval_model_controller.go
@@ -44,20 +44,20 @@ func (r retrievalModelClient) Get(ctx context.Context, _ string) (*summarizerv1.
if err != nil {
return nil, trace.Wrap(err)
}
- return resp.Model, nil
+ return resp.GetModel(), nil
}
// Create creates the Teleport RetrievalModel singleton.
func (r retrievalModelClient) Create(ctx context.Context, resource *summarizerv1.RetrievalModel) error {
_, err := r.teleportClient.SummarizerServiceClient().
- CreateRetrievalModel(ctx, &summarizerv1.CreateRetrievalModelRequest{Model: resource})
+ CreateRetrievalModel(ctx, summarizerv1.CreateRetrievalModelRequest_builder{Model: resource}.Build())
return trace.Wrap(err)
}
// Update upserts the Teleport RetrievalModel singleton.
func (r retrievalModelClient) Update(ctx context.Context, resource *summarizerv1.RetrievalModel) error {
_, err := r.teleportClient.SummarizerServiceClient().
- UpsertRetrievalModel(ctx, &summarizerv1.UpsertRetrievalModelRequest{Model: resource})
+ UpsertRetrievalModel(ctx, summarizerv1.UpsertRetrievalModelRequest_builder{Model: resource}.Build())
return trace.Wrap(err)
}
diff --git a/integrations/operator/controllers/resources/scopedrole_controller.go b/integrations/operator/controllers/resources/scopedrole_controller.go
index 55d35fb1917..30da9425fdd 100644
--- a/integrations/operator/controllers/resources/scopedrole_controller.go
+++ b/integrations/operator/controllers/resources/scopedrole_controller.go
@@ -34,23 +34,23 @@ type scopedRoleClient struct {
}
func (s *scopedRoleClient) Create(ctx context.Context, role *accessv1.ScopedRole) error {
- _, err := s.teleportClient.ScopedAccessServiceClient().CreateScopedRole(ctx, &accessv1.CreateScopedRoleRequest{
+ _, err := s.teleportClient.ScopedAccessServiceClient().CreateScopedRole(ctx, accessv1.CreateScopedRoleRequest_builder{
Role: role,
- })
+ }.Build())
return trace.Wrap(err)
}
func (s *scopedRoleClient) Delete(ctx context.Context, name string) error {
- _, err := s.teleportClient.ScopedAccessServiceClient().DeleteScopedRole(ctx, &accessv1.DeleteScopedRoleRequest{
+ _, err := s.teleportClient.ScopedAccessServiceClient().DeleteScopedRole(ctx, accessv1.DeleteScopedRoleRequest_builder{
Name: name,
- })
+ }.Build())
return trace.Wrap(err)
}
func (s *scopedRoleClient) Get(ctx context.Context, name string) (*accessv1.ScopedRole, error) {
- resp, err := s.teleportClient.ScopedAccessServiceClient().GetScopedRole(ctx, &accessv1.GetScopedRoleRequest{
+ resp, err := s.teleportClient.ScopedAccessServiceClient().GetScopedRole(ctx, accessv1.GetScopedRoleRequest_builder{
Name: name,
- })
+ }.Build())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -58,9 +58,9 @@ func (s *scopedRoleClient) Get(ctx context.Context, name string) (*accessv1.Scop
}
func (s *scopedRoleClient) Update(ctx context.Context, role *accessv1.ScopedRole) error {
- _, err := s.teleportClient.ScopedAccessServiceClient().UpdateScopedRole(ctx, &accessv1.UpdateScopedRoleRequest{
+ _, err := s.teleportClient.ScopedAccessServiceClient().UpdateScopedRole(ctx, accessv1.UpdateScopedRoleRequest_builder{
Role: role,
- })
+ }.Build())
return trace.Wrap(err)
}
diff --git a/integrations/operator/controllers/resources/scopedrole_controller_test.go b/integrations/operator/controllers/resources/scopedrole_controller_test.go
index 0576b822670..14a1f613d2a 100644
--- a/integrations/operator/controllers/resources/scopedrole_controller_test.go
+++ b/integrations/operator/controllers/resources/scopedrole_controller_test.go
@@ -38,15 +38,15 @@ import (
"github.com/gravitational/teleport/lib/scopes/access"
)
-var scopedRoleSpec = &accessv1.ScopedRoleSpec{
+var scopedRoleSpec = accessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/staging"},
Rules: []*accessv1.ScopedRule{
- {
+ accessv1.ScopedRule_builder{
Resources: []string{"scoped_role"},
Verbs: []string{"readnosecrets", "list"},
- },
+ }.Build(),
},
-}
+}.Build()
type scopedRoleTestingPrimitives struct {
setup *testSetup
@@ -62,28 +62,28 @@ func (g *scopedRoleTestingPrimitives) SetupTeleportFixtures(ctx context.Context)
}
func (g *scopedRoleTestingPrimitives) CreateTeleportResource(ctx context.Context, name string) error {
- role := &accessv1.ScopedRole{
+ role := accessv1.ScopedRole_builder{
Kind: access.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Scope: "/staging",
Spec: scopedRoleSpec,
- }
- _, err := g.setup.TeleportClient.ScopedAccessServiceClient().CreateScopedRole(ctx, &accessv1.CreateScopedRoleRequest{
+ }.Build()
+ _, err := g.setup.TeleportClient.ScopedAccessServiceClient().CreateScopedRole(ctx, accessv1.CreateScopedRoleRequest_builder{
Role: role,
- })
+ }.Build())
return trace.Wrap(err)
}
func (g *scopedRoleTestingPrimitives) GetTeleportResource(ctx context.Context, name string) (*accessv1.ScopedRole, error) {
- resp, err := g.setup.TeleportClient.ScopedAccessServiceClient().GetScopedRole(ctx, &accessv1.GetScopedRoleRequest{
+ resp, err := g.setup.TeleportClient.ScopedAccessServiceClient().GetScopedRole(ctx, accessv1.GetScopedRoleRequest_builder{
Name: name,
- })
+ }.Build())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -91,9 +91,9 @@ func (g *scopedRoleTestingPrimitives) GetTeleportResource(ctx context.Context, n
}
func (g *scopedRoleTestingPrimitives) DeleteTeleportResource(ctx context.Context, name string) error {
- _, err := g.setup.TeleportClient.ScopedAccessServiceClient().DeleteScopedRole(ctx, &accessv1.DeleteScopedRoleRequest{
+ _, err := g.setup.TeleportClient.ScopedAccessServiceClient().DeleteScopedRole(ctx, accessv1.DeleteScopedRoleRequest_builder{
Name: name,
- })
+ }.Build())
return trace.Wrap(err)
}
@@ -135,9 +135,9 @@ func (g *scopedRoleTestingPrimitives) ModifyKubernetesResource(ctx context.Conte
return trace.Wrap(err)
}
role.Spec.AssignableScopes = []string{"/staging/aa", "/staging/bb"}
- role.Spec.Ssh = &accessv1.ScopedRoleSSH{
+ role.Spec.Ssh = accessv1.ScopedRoleSSH_builder{
HostSudoers: []string{"test"},
- }
+ }.Build()
return trace.Wrap(g.setup.K8sClient.Update(ctx, role))
}
diff --git a/integrations/operator/controllers/resources/scopedroleassignment_controller.go b/integrations/operator/controllers/resources/scopedroleassignment_controller.go
index f60e5712102..202c7584f09 100644
--- a/integrations/operator/controllers/resources/scopedroleassignment_controller.go
+++ b/integrations/operator/controllers/resources/scopedroleassignment_controller.go
@@ -35,25 +35,25 @@ type scopedRoleAssignmentClient struct {
}
func (s *scopedRoleAssignmentClient) Create(ctx context.Context, assignment *accessv1.ScopedRoleAssignment) error {
- _, err := s.teleportClient.ScopedAccessServiceClient().CreateScopedRoleAssignment(ctx, &accessv1.CreateScopedRoleAssignmentRequest{
+ _, err := s.teleportClient.ScopedAccessServiceClient().CreateScopedRoleAssignment(ctx, accessv1.CreateScopedRoleAssignmentRequest_builder{
Assignment: assignment,
- })
+ }.Build())
return trace.Wrap(err)
}
func (s *scopedRoleAssignmentClient) Delete(ctx context.Context, name string) error {
- _, err := s.teleportClient.ScopedAccessServiceClient().DeleteScopedRoleAssignment(ctx, &accessv1.DeleteScopedRoleAssignmentRequest{
+ _, err := s.teleportClient.ScopedAccessServiceClient().DeleteScopedRoleAssignment(ctx, accessv1.DeleteScopedRoleAssignmentRequest_builder{
Name: name,
SubKind: scopedaccess.SubKindDynamic,
- })
+ }.Build())
return trace.Wrap(err)
}
func (s *scopedRoleAssignmentClient) Get(ctx context.Context, name string) (*accessv1.ScopedRoleAssignment, error) {
- resp, err := s.teleportClient.ScopedAccessServiceClient().GetScopedRoleAssignment(ctx, &accessv1.GetScopedRoleAssignmentRequest{
+ resp, err := s.teleportClient.ScopedAccessServiceClient().GetScopedRoleAssignment(ctx, accessv1.GetScopedRoleAssignmentRequest_builder{
Name: name,
SubKind: scopedaccess.SubKindDynamic,
- })
+ }.Build())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -61,9 +61,9 @@ func (s *scopedRoleAssignmentClient) Get(ctx context.Context, name string) (*acc
}
func (s *scopedRoleAssignmentClient) Update(ctx context.Context, assignment *accessv1.ScopedRoleAssignment) error {
- _, err := s.teleportClient.ScopedAccessServiceClient().UpdateScopedRoleAssignment(ctx, &accessv1.UpdateScopedRoleAssignmentRequest{
+ _, err := s.teleportClient.ScopedAccessServiceClient().UpdateScopedRoleAssignment(ctx, accessv1.UpdateScopedRoleAssignmentRequest_builder{
Assignment: assignment,
- })
+ }.Build())
return trace.Wrap(err)
}
diff --git a/integrations/operator/controllers/resources/scopedroleassignment_controller_test.go b/integrations/operator/controllers/resources/scopedroleassignment_controller_test.go
index feab443af38..e365059cda3 100644
--- a/integrations/operator/controllers/resources/scopedroleassignment_controller_test.go
+++ b/integrations/operator/controllers/resources/scopedroleassignment_controller_test.go
@@ -39,15 +39,15 @@ import (
"github.com/gravitational/teleport/lib/scopes/access"
)
-var scopedRoleAssignmentSpec = &accessv1.ScopedRoleAssignmentSpec{
+var scopedRoleAssignmentSpec = accessv1.ScopedRoleAssignmentSpec_builder{
User: "test-user",
Assignments: []*accessv1.Assignment{
- {
+ accessv1.Assignment_builder{
Role: "test-role",
Scope: "/staging",
- },
+ }.Build(),
},
-}
+}.Build()
type scopedRoleAssignmentTestingPrimitives struct {
setup *testSetup
@@ -63,30 +63,30 @@ func (g *scopedRoleAssignmentTestingPrimitives) SetupTeleportFixtures(ctx contex
}
func (g *scopedRoleAssignmentTestingPrimitives) CreateTeleportResource(ctx context.Context, name string) error {
- assignment := &accessv1.ScopedRoleAssignment{
+ assignment := accessv1.ScopedRoleAssignment_builder{
Kind: access.KindScopedRoleAssignment,
Version: types.V1,
SubKind: access.SubKindDynamic,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Scope: "/staging",
Spec: scopedRoleAssignmentSpec,
- }
- _, err := g.setup.TeleportClient.ScopedAccessServiceClient().CreateScopedRoleAssignment(ctx, &accessv1.CreateScopedRoleAssignmentRequest{
+ }.Build()
+ _, err := g.setup.TeleportClient.ScopedAccessServiceClient().CreateScopedRoleAssignment(ctx, accessv1.CreateScopedRoleAssignmentRequest_builder{
Assignment: assignment,
- })
+ }.Build())
return trace.Wrap(err)
}
func (g *scopedRoleAssignmentTestingPrimitives) GetTeleportResource(ctx context.Context, name string) (*accessv1.ScopedRoleAssignment, error) {
- resp, err := g.setup.TeleportClient.ScopedAccessServiceClient().GetScopedRoleAssignment(ctx, &accessv1.GetScopedRoleAssignmentRequest{
+ resp, err := g.setup.TeleportClient.ScopedAccessServiceClient().GetScopedRoleAssignment(ctx, accessv1.GetScopedRoleAssignmentRequest_builder{
Name: name,
SubKind: access.SubKindDynamic,
- })
+ }.Build())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -94,10 +94,10 @@ func (g *scopedRoleAssignmentTestingPrimitives) GetTeleportResource(ctx context.
}
func (g *scopedRoleAssignmentTestingPrimitives) DeleteTeleportResource(ctx context.Context, name string) error {
- _, err := g.setup.TeleportClient.ScopedAccessServiceClient().DeleteScopedRoleAssignment(ctx, &accessv1.DeleteScopedRoleAssignmentRequest{
+ _, err := g.setup.TeleportClient.ScopedAccessServiceClient().DeleteScopedRoleAssignment(ctx, accessv1.DeleteScopedRoleAssignmentRequest_builder{
Name: name,
SubKind: access.SubKindDynamic,
- })
+ }.Build())
return trace.Wrap(err)
}
@@ -139,10 +139,10 @@ func (g *scopedRoleAssignmentTestingPrimitives) ModifyKubernetesResource(ctx con
return trace.Wrap(err)
}
assignment.Spec.Assignments = []*accessv1.Assignment{
- {
+ accessv1.Assignment_builder{
Role: "test-role",
Scope: "/staging/aa",
- },
+ }.Build(),
}
return trace.Wrap(g.setup.K8sClient.Update(ctx, assignment))
}
diff --git a/integrations/operator/controllers/resources/scopedtoken_controller_test.go b/integrations/operator/controllers/resources/scopedtoken_controller_test.go
index 1b7ccf7a859..1cc92a18c51 100644
--- a/integrations/operator/controllers/resources/scopedtoken_controller_test.go
+++ b/integrations/operator/controllers/resources/scopedtoken_controller_test.go
@@ -37,17 +37,17 @@ import (
"github.com/gravitational/teleport/integrations/operator/controllers/resources/testlib"
)
-var scopedTokenSpec = &tokenv1.ScopedTokenSpec{
+var scopedTokenSpec = tokenv1.ScopedTokenSpec_builder{
AssignedScope: "/staging/foo",
Roles: []string{types.RoleNode.String()},
JoinMethod: string(types.JoinMethodToken),
UsageMode: "unlimited",
- ImmutableLabels: &tokenv1.ImmutableLabels{
+ ImmutableLabels: tokenv1.ImmutableLabels_builder{
Ssh: map[string]string{
"env": "prod",
},
- },
-}
+ }.Build(),
+}.Build()
type scopedTokenTestingPrimitives struct {
setup *testSetup
@@ -63,18 +63,18 @@ func (g *scopedTokenTestingPrimitives) SetupTeleportFixtures(ctx context.Context
}
func (g *scopedTokenTestingPrimitives) CreateTeleportResource(ctx context.Context, name string) error {
- token := &tokenv1.ScopedToken{
+ token := tokenv1.ScopedToken_builder{
Kind: types.KindScopedToken,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Scope: "/staging",
Spec: scopedTokenSpec,
- }
+ }.Build()
_, err := g.setup.TeleportClient.CreateScopedToken(ctx, token)
return trace.Wrap(err)
}
@@ -124,9 +124,9 @@ func (g *scopedTokenTestingPrimitives) ModifyKubernetesResource(ctx context.Cont
if err != nil {
return trace.Wrap(err)
}
- token.Spec.ImmutableLabels.Ssh = map[string]string{
+ token.Spec.ImmutableLabels.SetSsh(map[string]string{
"env": "staging",
- }
+ })
return trace.Wrap(g.setup.K8sClient.Update(ctx, token))
}
diff --git a/integrations/operator/controllers/resources/testlib/inference_model_controller_tests.go b/integrations/operator/controllers/resources/testlib/inference_model_controller_tests.go
index 1fda7f7433a..ed62ce8f848 100644
--- a/integrations/operator/controllers/resources/testlib/inference_model_controller_tests.go
+++ b/integrations/operator/controllers/resources/testlib/inference_model_controller_tests.go
@@ -36,16 +36,14 @@ import (
"github.com/gravitational/teleport/integrations/operator/controllers/resources"
)
-var inferenceModelSpec = &summarizerv1.InferenceModelSpec{
- Provider: &summarizerv1.InferenceModelSpec_Bedrock{
- Bedrock: &summarizerv1.BedrockProvider{
- Region: "us-east-1",
- BedrockModelId: "anthropic.claude-3-haiku-20240307-v1:0",
- Integration: "some-integration",
- },
- },
+var inferenceModelSpec = summarizerv1.InferenceModelSpec_builder{
+ Bedrock: summarizerv1.BedrockProvider_builder{
+ Region: "us-east-1",
+ BedrockModelId: "anthropic.claude-3-haiku-20240307-v1:0",
+ Integration: "some-integration",
+ }.Build(),
MaxSessionLengthBytes: 1234567,
-}
+}.Build()
type inferenceModelTestingPrimitives struct {
setup *TestSetup
@@ -63,20 +61,20 @@ func (p *inferenceModelTestingPrimitives) SetupTeleportFixtures(ctx context.Cont
func (p *inferenceModelTestingPrimitives) CreateTeleportResource(
ctx context.Context, name string,
) error {
- model := &summarizerv1.InferenceModel{
+ model := summarizerv1.InferenceModel_builder{
Kind: types.KindInferenceModel,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Spec: inferenceModelSpec,
- }
+ }.Build()
_, err := p.setup.TeleportClient.
SummarizerServiceClient().
- CreateInferenceModel(ctx, &summarizerv1.CreateInferenceModelRequest{Model: model})
+ CreateInferenceModel(ctx, summarizerv1.CreateInferenceModelRequest_builder{Model: model}.Build())
return trace.Wrap(err)
}
@@ -85,11 +83,11 @@ func (p *inferenceModelTestingPrimitives) GetTeleportResource(
) (*summarizerv1.InferenceModel, error) {
resp, err := p.setup.TeleportClient.
SummarizerServiceClient().
- GetInferenceModel(ctx, &summarizerv1.GetInferenceModelRequest{Name: name})
+ GetInferenceModel(ctx, summarizerv1.GetInferenceModelRequest_builder{Name: name}.Build())
if err != nil {
return nil, trace.Wrap(err)
}
- return resp.Model, nil
+ return resp.GetModel(), nil
}
func (p *inferenceModelTestingPrimitives) DeleteTeleportResource(
@@ -97,7 +95,7 @@ func (p *inferenceModelTestingPrimitives) DeleteTeleportResource(
) error {
_, err := p.setup.TeleportClient.
SummarizerServiceClient().
- DeleteInferenceModel(ctx, &summarizerv1.DeleteInferenceModelRequest{Name: name})
+ DeleteInferenceModel(ctx, summarizerv1.DeleteInferenceModelRequest_builder{Name: name}.Build())
return trace.Wrap(err)
}
@@ -146,8 +144,8 @@ func (p *inferenceModelTestingPrimitives) ModifyKubernetesResource(
return trace.Wrap(err)
}
model.Spec.MaxSessionLengthBytes = 7654321
- (*summarizerv1.InferenceModelSpec)(model.Spec).GetBedrock().BedrockModelId =
- "anthropic.claude-3-5-sonnet-20240620-v1:0"
+ (*summarizerv1.InferenceModelSpec)(model.Spec).GetBedrock().SetBedrockModelId(
+ "anthropic.claude-3-5-sonnet-20240620-v1:0")
return trace.Wrap(p.setup.K8sClient.Update(ctx, model))
}
diff --git a/integrations/operator/controllers/resources/testlib/inference_policy_controller_tests.go b/integrations/operator/controllers/resources/testlib/inference_policy_controller_tests.go
index f08e758d45f..18c1a47f9cf 100644
--- a/integrations/operator/controllers/resources/testlib/inference_policy_controller_tests.go
+++ b/integrations/operator/controllers/resources/testlib/inference_policy_controller_tests.go
@@ -34,11 +34,11 @@ import (
"github.com/gravitational/teleport/integrations/operator/controllers/resources"
)
-var inferencePolicySpec = &summarizerv1.InferencePolicySpec{
+var inferencePolicySpec = summarizerv1.InferencePolicySpec_builder{
Kinds: []string{"ssh", "k8s"},
Model: "test-model",
Filter: "resource.metadata.labels[\"env\"] == \"production\"",
-}
+}.Build()
type inferencePolicyTestingPrimitives struct {
setup *TestSetup
@@ -56,20 +56,20 @@ func (p *inferencePolicyTestingPrimitives) SetupTeleportFixtures(ctx context.Con
func (p *inferencePolicyTestingPrimitives) CreateTeleportResource(
ctx context.Context, name string,
) error {
- policy := &summarizerv1.InferencePolicy{
+ policy := summarizerv1.InferencePolicy_builder{
Kind: types.KindInferencePolicy,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Spec: inferencePolicySpec,
- }
+ }.Build()
_, err := p.setup.TeleportClient.
SummarizerServiceClient().
- CreateInferencePolicy(ctx, &summarizerv1.CreateInferencePolicyRequest{Policy: policy})
+ CreateInferencePolicy(ctx, summarizerv1.CreateInferencePolicyRequest_builder{Policy: policy}.Build())
return trace.Wrap(err)
}
@@ -78,11 +78,11 @@ func (p *inferencePolicyTestingPrimitives) GetTeleportResource(
) (*summarizerv1.InferencePolicy, error) {
resp, err := p.setup.TeleportClient.
SummarizerServiceClient().
- GetInferencePolicy(ctx, &summarizerv1.GetInferencePolicyRequest{Name: name})
+ GetInferencePolicy(ctx, summarizerv1.GetInferencePolicyRequest_builder{Name: name}.Build())
if err != nil {
return nil, trace.Wrap(err)
}
- return resp.Policy, nil
+ return resp.GetPolicy(), nil
}
func (p *inferencePolicyTestingPrimitives) DeleteTeleportResource(
@@ -90,7 +90,7 @@ func (p *inferencePolicyTestingPrimitives) DeleteTeleportResource(
) error {
_, err := p.setup.TeleportClient.
SummarizerServiceClient().
- DeleteInferencePolicy(ctx, &summarizerv1.DeleteInferencePolicyRequest{Name: name})
+ DeleteInferencePolicy(ctx, summarizerv1.DeleteInferencePolicyRequest_builder{Name: name}.Build())
return trace.Wrap(err)
}
diff --git a/integrations/operator/controllers/resources/testlib/inference_secret_controller_tests.go b/integrations/operator/controllers/resources/testlib/inference_secret_controller_tests.go
index c3e2480b8f3..ed49ffc4ba1 100644
--- a/integrations/operator/controllers/resources/testlib/inference_secret_controller_tests.go
+++ b/integrations/operator/controllers/resources/testlib/inference_secret_controller_tests.go
@@ -36,9 +36,9 @@ import (
"github.com/gravitational/teleport/integrations/operator/controllers/resources"
)
-var inferenceSecretSpec = &summarizerv1.InferenceSecretSpec{
+var inferenceSecretSpec = summarizerv1.InferenceSecretSpec_builder{
Value: "my-secret-value-123",
-}
+}.Build()
type inferenceSecretTestingPrimitives struct {
setup *TestSetup
@@ -56,20 +56,20 @@ func (p *inferenceSecretTestingPrimitives) SetupTeleportFixtures(ctx context.Con
func (p *inferenceSecretTestingPrimitives) CreateTeleportResource(
ctx context.Context, name string,
) error {
- secret := &summarizerv1.InferenceSecret{
+ secret := summarizerv1.InferenceSecret_builder{
Kind: types.KindInferenceSecret,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Spec: inferenceSecretSpec,
- }
+ }.Build()
_, err := p.setup.TeleportClient.
SummarizerServiceClient().
- CreateInferenceSecret(ctx, &summarizerv1.CreateInferenceSecretRequest{Secret: secret})
+ CreateInferenceSecret(ctx, summarizerv1.CreateInferenceSecretRequest_builder{Secret: secret}.Build())
return trace.Wrap(err)
}
@@ -78,11 +78,11 @@ func (p *inferenceSecretTestingPrimitives) GetTeleportResource(
) (*summarizerv1.InferenceSecret, error) {
resp, err := p.setup.TeleportClient.
SummarizerServiceClient().
- GetInferenceSecret(ctx, &summarizerv1.GetInferenceSecretRequest{Name: name})
+ GetInferenceSecret(ctx, summarizerv1.GetInferenceSecretRequest_builder{Name: name}.Build())
if err != nil {
return nil, trace.Wrap(err)
}
- return resp.Secret, nil
+ return resp.GetSecret(), nil
}
func (p *inferenceSecretTestingPrimitives) DeleteTeleportResource(
@@ -90,7 +90,7 @@ func (p *inferenceSecretTestingPrimitives) DeleteTeleportResource(
) error {
_, err := p.setup.TeleportClient.
SummarizerServiceClient().
- DeleteInferenceSecret(ctx, &summarizerv1.DeleteInferenceSecretRequest{Name: name})
+ DeleteInferenceSecret(ctx, summarizerv1.DeleteInferenceSecretRequest_builder{Name: name}.Build())
return trace.Wrap(err)
}
@@ -149,8 +149,8 @@ func (p *inferenceSecretTestingPrimitives) CompareTeleportAndKubernetesResource(
// InferenceSecret spec is write-only, so Teleport will return spec=nil. We
// therefore only compare the metadata.
diff := cmp.Diff(
- tResource.Metadata,
- kubeResource.ToTeleport().Metadata,
+ tResource.GetMetadata(),
+ kubeResource.ToTeleport().GetMetadata(),
ProtoCompareOptions()...,
)
return diff == "", diff
diff --git a/integrations/operator/controllers/resources/testlib/login_rule_controller_tests.go b/integrations/operator/controllers/resources/testlib/login_rule_controller_tests.go
index 990057c7190..92b05601789 100644
--- a/integrations/operator/controllers/resources/testlib/login_rule_controller_tests.go
+++ b/integrations/operator/controllers/resources/testlib/login_rule_controller_tests.go
@@ -67,26 +67,26 @@ func (l *loginRuleTestingPrimitives) CreateTeleportResource(ctx context.Context,
},
},
}
- rule.Metadata.SetOrigin(types.OriginKubernetes)
- _, err := l.setup.TeleportClient.LoginRuleClient().CreateLoginRule(ctx, &loginrulepb.CreateLoginRuleRequest{
+ rule.GetMetadata().SetOrigin(types.OriginKubernetes)
+ _, err := l.setup.TeleportClient.LoginRuleClient().CreateLoginRule(ctx, loginrulepb.CreateLoginRuleRequest_builder{
LoginRule: &rule,
- })
+ }.Build())
return trace.Wrap(err)
}
func (l *loginRuleTestingPrimitives) GetTeleportResource(ctx context.Context, name string) (*resourcesv1.LoginRuleResource, error) {
lrClient := l.setup.TeleportClient.LoginRuleClient()
- loginRule, err := lrClient.GetLoginRule(ctx, &loginrulepb.GetLoginRuleRequest{
+ loginRule, err := lrClient.GetLoginRule(ctx, loginrulepb.GetLoginRuleRequest_builder{
Name: name,
- })
+ }.Build())
return &resourcesv1.LoginRuleResource{LoginRule: loginRule}, trail.FromGRPC(err)
}
func (l *loginRuleTestingPrimitives) DeleteTeleportResource(ctx context.Context, name string) error {
lrClient := l.setup.TeleportClient.LoginRuleClient()
- _, err := lrClient.DeleteLoginRule(ctx, &loginrulepb.DeleteLoginRuleRequest{
+ _, err := lrClient.DeleteLoginRule(ctx, loginrulepb.DeleteLoginRuleRequest_builder{
Name: name,
- })
+ }.Build())
return trace.Wrap(err)
}
diff --git a/integrations/operator/controllers/resources/testlib/retrieval_model_controller_tests.go b/integrations/operator/controllers/resources/testlib/retrieval_model_controller_tests.go
index ec7198706ba..f3f3f123d31 100644
--- a/integrations/operator/controllers/resources/testlib/retrieval_model_controller_tests.go
+++ b/integrations/operator/controllers/resources/testlib/retrieval_model_controller_tests.go
@@ -42,15 +42,13 @@ import (
"github.com/gravitational/teleport/integrations/operator/controllers/resources"
)
-var retrievalModelSpec = &summarizerv1.RetrievalModelSpec{
- EmbeddingsProvider: &summarizerv1.RetrievalModelSpec_Bedrock{
- Bedrock: &summarizerv1.BedrockProvider{
- Region: "us-west-2",
- BedrockModelId: "amazon.titan-embed-text-v2:0",
- },
- },
+var retrievalModelSpec = summarizerv1.RetrievalModelSpec_builder{
+ Bedrock: summarizerv1.BedrockProvider_builder{
+ Region: "us-west-2",
+ BedrockModelId: "amazon.titan-embed-text-v2:0",
+ }.Build(),
InferenceModelName: "test-inference-model",
-}
+}.Build()
type retrievalModelTestingPrimitives struct {
setup *TestSetup
@@ -62,32 +60,32 @@ func (p *retrievalModelTestingPrimitives) Init(setup *TestSetup) {
}
func (p *retrievalModelTestingPrimitives) SetupTeleportFixtures(ctx context.Context) error {
- model := &summarizerv1.InferenceModel{
+ model := summarizerv1.InferenceModel_builder{
Kind: types.KindInferenceModel,
Version: types.V1,
- Metadata: &headerv1.Metadata{
- Name: retrievalModelSpec.InferenceModelName,
- },
+ Metadata: headerv1.Metadata_builder{
+ Name: retrievalModelSpec.GetInferenceModelName(),
+ }.Build(),
Spec: inferenceModelSpec,
- }
+ }.Build()
_, err := p.setup.TeleportClient.SummarizerClient().UpsertInferenceModel(ctx, model)
return trace.Wrap(err)
}
func (p *retrievalModelTestingPrimitives) CreateTeleportResource(ctx context.Context, _ string) error {
- model := &summarizerv1.RetrievalModel{
+ model := summarizerv1.RetrievalModel_builder{
Kind: types.KindRetrievalModel,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: types.MetaNameRetrievalModel,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Spec: retrievalModelSpec,
- }
+ }.Build()
_, err := p.setup.TeleportClient.SummarizerServiceClient().
- CreateRetrievalModel(ctx, &summarizerv1.CreateRetrievalModelRequest{Model: model})
+ CreateRetrievalModel(ctx, summarizerv1.CreateRetrievalModelRequest_builder{Model: model}.Build())
return trace.Wrap(err)
}
@@ -99,7 +97,7 @@ func (p *retrievalModelTestingPrimitives) GetTeleportResource(
if err != nil {
return nil, trace.Wrap(err)
}
- return resp.Model, nil
+ return resp.GetModel(), nil
}
func (p *retrievalModelTestingPrimitives) DeleteTeleportResource(ctx context.Context, _ string) error {
@@ -147,10 +145,10 @@ func (p *retrievalModelTestingPrimitives) ModifyKubernetesResource(ctx context.C
return trace.Wrap(err)
}
model.Spec.EmbeddingsProvider = &summarizerv1.RetrievalModelSpec_Bedrock{
- Bedrock: &summarizerv1.BedrockProvider{
+ Bedrock: summarizerv1.BedrockProvider_builder{
Region: "us-west-1",
BedrockModelId: "amazon.titan-embed-text-v2:0",
- },
+ }.Build(),
}
return trace.Wrap(p.setup.K8sClient.Update(ctx, model))
}
diff --git a/integrations/operator/controllers/resources/workload_identityv1_controller.go b/integrations/operator/controllers/resources/workload_identityv1_controller.go
index b9d5e4e19f3..1f77e45f5df 100644
--- a/integrations/operator/controllers/resources/workload_identityv1_controller.go
+++ b/integrations/operator/controllers/resources/workload_identityv1_controller.go
@@ -44,7 +44,7 @@ func (l workloadIdentityClient) Get(
resp, err := l.teleportClient.
WorkloadIdentityResourceServiceClient().
GetWorkloadIdentity(
- ctx, &workloadidentityv1.GetWorkloadIdentityRequest{Name: name},
+ ctx, workloadidentityv1.GetWorkloadIdentityRequest_builder{Name: name}.Build(),
)
if err != nil {
return nil, trace.Wrap(err)
@@ -60,9 +60,9 @@ func (l workloadIdentityClient) Create(
WorkloadIdentityResourceServiceClient().
CreateWorkloadIdentity(
ctx,
- &workloadidentityv1.CreateWorkloadIdentityRequest{
+ workloadidentityv1.CreateWorkloadIdentityRequest_builder{
WorkloadIdentity: resource,
- },
+ }.Build(),
)
return trace.Wrap(err)
}
@@ -75,9 +75,9 @@ func (l workloadIdentityClient) Update(
WorkloadIdentityResourceServiceClient().
UpsertWorkloadIdentity(
ctx,
- &workloadidentityv1.UpsertWorkloadIdentityRequest{
+ workloadidentityv1.UpsertWorkloadIdentityRequest_builder{
WorkloadIdentity: resource,
- },
+ }.Build(),
)
return trace.Wrap(err)
}
@@ -87,7 +87,7 @@ func (l workloadIdentityClient) Delete(ctx context.Context, name string) error {
_, err := l.teleportClient.
WorkloadIdentityResourceServiceClient().
DeleteWorkloadIdentity(
- ctx, &workloadidentityv1.DeleteWorkloadIdentityRequest{Name: name},
+ ctx, workloadidentityv1.DeleteWorkloadIdentityRequest_builder{Name: name}.Build(),
)
return trace.Wrap(err)
}
diff --git a/integrations/operator/controllers/resources/workload_identityv1_controller_test.go b/integrations/operator/controllers/resources/workload_identityv1_controller_test.go
index 746f897df12..1fb3d049263 100644
--- a/integrations/operator/controllers/resources/workload_identityv1_controller_test.go
+++ b/integrations/operator/controllers/resources/workload_identityv1_controller_test.go
@@ -36,27 +36,25 @@ import (
"github.com/gravitational/teleport/integrations/operator/controllers/resources/testlib"
)
-var workloadIdentitySpec = &workloadidentityv1.WorkloadIdentitySpec{
- Rules: &workloadidentityv1.WorkloadIdentityRules{
+var workloadIdentitySpec = workloadidentityv1.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1.WorkloadIdentityRule{
- {
+ workloadidentityv1.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1.WorkloadIdentityCondition{
- {
+ workloadidentityv1.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1.WorkloadIdentityCondition_Eq{
- Eq: &workloadidentityv1.WorkloadIdentityConditionEq{
- Value: "userA",
- },
- },
- },
+ Eq: workloadidentityv1.WorkloadIdentityConditionEq_builder{
+ Value: "userA",
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- Spiffe: &workloadidentityv1.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spiffe: workloadidentityv1.WorkloadIdentitySPIFFE_builder{
Id: "/test",
- },
-}
+ }.Build(),
+}.Build()
type workloadIdentityTestingPrimitives struct {
setup *testSetup
@@ -76,24 +74,24 @@ func (g *workloadIdentityTestingPrimitives) SetupTeleportFixtures(
func (g *workloadIdentityTestingPrimitives) CreateTeleportResource(
ctx context.Context, name string,
) error {
- resource := &workloadidentityv1.WorkloadIdentity{
+ resource := workloadidentityv1.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Labels: map[string]string{
types.OriginLabel: types.OriginKubernetes,
},
- },
+ }.Build(),
Spec: workloadIdentitySpec,
- }
+ }.Build()
_, err := g.setup.TeleportClient.
WorkloadIdentityResourceServiceClient().
CreateWorkloadIdentity(
ctx,
- &workloadidentityv1.CreateWorkloadIdentityRequest{
+ workloadidentityv1.CreateWorkloadIdentityRequest_builder{
WorkloadIdentity: resource,
- },
+ }.Build(),
)
return trace.Wrap(err)
}
@@ -104,7 +102,7 @@ func (g *workloadIdentityTestingPrimitives) GetTeleportResource(
resp, err := g.setup.TeleportClient.
WorkloadIdentityResourceServiceClient().
GetWorkloadIdentity(
- ctx, &workloadidentityv1.GetWorkloadIdentityRequest{Name: name},
+ ctx, workloadidentityv1.GetWorkloadIdentityRequest_builder{Name: name}.Build(),
)
if err != nil {
return nil, trace.Wrap(err)
@@ -118,7 +116,7 @@ func (g *workloadIdentityTestingPrimitives) DeleteTeleportResource(
_, err := g.setup.TeleportClient.
WorkloadIdentityResourceServiceClient().
DeleteWorkloadIdentity(
- ctx, &workloadidentityv1.DeleteWorkloadIdentityRequest{Name: name},
+ ctx, workloadidentityv1.DeleteWorkloadIdentityRequest_builder{Name: name}.Build(),
)
if err != nil {
return trace.Wrap(err)
@@ -170,7 +168,7 @@ func (g *workloadIdentityTestingPrimitives) ModifyKubernetesResource(
if err != nil {
return trace.Wrap(err)
}
- resource.Spec.Spiffe.Id = "/changed"
+ resource.Spec.Spiffe.SetId("/changed")
return trace.Wrap(g.setup.K8sClient.Update(ctx, resource))
}
diff --git a/lib/accessmonitoring/access_monitoring_rule_test.go b/lib/accessmonitoring/access_monitoring_rule_test.go
index 24ba82b1c1e..1da631e7b9a 100644
--- a/lib/accessmonitoring/access_monitoring_rule_test.go
+++ b/lib/accessmonitoring/access_monitoring_rule_test.go
@@ -92,7 +92,7 @@ func TestEvaluateRules(t *testing.T) {
rules := EvaluateRules(ctx, logtest.NewLogger(), test.env, test.rules)
require.Len(t, rules, len(test.expected))
for _, rule := range rules {
- require.Contains(t, test.expected, rule.Metadata.GetName())
+ require.Contains(t, test.expected, rule.GetMetadata().GetName())
}
})
}
@@ -103,26 +103,26 @@ func makeRule(
weekday time.Weekday,
start, end string,
) *accessmonitoringrulesv1.AccessMonitoringRule {
- return &accessmonitoringrulesv1.AccessMonitoringRule{
+ return accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: condition,
Schedules: map[string]*accessmonitoringrulesv1.Schedule{
- "default": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
- Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{{
+ "default": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
+ Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: weekday.String(),
Start: start,
End: end,
- }},
- },
- },
+ }.Build()},
+ }.Build(),
+ }.Build(),
},
- },
- }
+ }.Build(),
+ }.Build()
}
diff --git a/lib/accessmonitoring/cache_test.go b/lib/accessmonitoring/cache_test.go
index eee751fde5d..2334d6c2e9d 100644
--- a/lib/accessmonitoring/cache_test.go
+++ b/lib/accessmonitoring/cache_test.go
@@ -33,8 +33,8 @@ func TestCache(t *testing.T) {
// Ensure rules are cached
rules := []*accessmonitoringrulesv1.AccessMonitoringRule{
- {Metadata: &headerv1.Metadata{Name: "test-rule-1"}},
- {Metadata: &headerv1.Metadata{Name: "test-rule-2"}},
+ accessmonitoringrulesv1.AccessMonitoringRule_builder{Metadata: headerv1.Metadata_builder{Name: "test-rule-1"}.Build()}.Build(),
+ accessmonitoringrulesv1.AccessMonitoringRule_builder{Metadata: headerv1.Metadata_builder{Name: "test-rule-2"}.Build()}.Build(),
}
cache.Put(rules)
require.Len(t, cache.Get(), 2)
@@ -42,14 +42,14 @@ func TestCache(t *testing.T) {
// Ensure rules are updated
updatedRules := []*accessmonitoringrulesv1.AccessMonitoringRule{
- {Metadata: &headerv1.Metadata{
+ accessmonitoringrulesv1.AccessMonitoringRule_builder{Metadata: headerv1.Metadata_builder{
Name: "test-rule-1",
Description: "updated-rule-1",
- }},
- {Metadata: &headerv1.Metadata{
+ }.Build()}.Build(),
+ accessmonitoringrulesv1.AccessMonitoringRule_builder{Metadata: headerv1.Metadata_builder{
Name: "test-rule-2",
Description: "updated-rule-2",
- }},
+ }.Build()}.Build(),
}
cache.Put(updatedRules)
require.Len(t, cache.Get(), 2)
@@ -66,12 +66,12 @@ func TestInitializeCache(t *testing.T) {
cache := NewCache()
rulesPageOne := []*accessmonitoringrulesv1.AccessMonitoringRule{
- {Metadata: &headerv1.Metadata{Name: "test-rule-1"}},
- {Metadata: &headerv1.Metadata{Name: "test-rule-2"}},
+ accessmonitoringrulesv1.AccessMonitoringRule_builder{Metadata: headerv1.Metadata_builder{Name: "test-rule-1"}.Build()}.Build(),
+ accessmonitoringrulesv1.AccessMonitoringRule_builder{Metadata: headerv1.Metadata_builder{Name: "test-rule-2"}.Build()}.Build(),
}
rulesPageTwo := []*accessmonitoringrulesv1.AccessMonitoringRule{
- {Metadata: &headerv1.Metadata{Name: "test-rule-3"}},
- {Metadata: &headerv1.Metadata{Name: "test-rule-4"}},
+ accessmonitoringrulesv1.AccessMonitoringRule_builder{Metadata: headerv1.Metadata_builder{Name: "test-rule-3"}.Build()}.Build(),
+ accessmonitoringrulesv1.AccessMonitoringRule_builder{Metadata: headerv1.Metadata_builder{Name: "test-rule-4"}.Build()}.Build(),
}
mockFetchPages := func(ctx context.Context, pageSize int64, pageToken string) (
[]*accessmonitoringrulesv1.AccessMonitoringRule,
diff --git a/lib/accessmonitoring/monitor_test.go b/lib/accessmonitoring/monitor_test.go
index d1b589162bd..bf1acc7478c 100644
--- a/lib/accessmonitoring/monitor_test.go
+++ b/lib/accessmonitoring/monitor_test.go
@@ -81,7 +81,7 @@ func TestAccessMonitoringRule(t *testing.T) {
"handle create access monitoring rule event")
// Test update access monitoring rule event.
- rule.Spec.Condition = "new-condition"
+ rule.GetSpec().SetCondition("new-condition")
updateEvent := types.Event{
Type: types.OpPut,
Resource: types.Resource153ToLegacy(rule),
@@ -269,22 +269,22 @@ func (w mockWatcher) Error() error {
func newApprovalRule(name, condition string) *accessmonitoringrulesv1.AccessMonitoringRule {
const integrationName = "test"
- return &accessmonitoringrulesv1.AccessMonitoringRule{
+ return accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: condition,
DesiredState: types.AccessMonitoringRuleStateReviewed,
- AutomaticReview: &accessmonitoringrulesv1.AutomaticReview{
+ AutomaticReview: accessmonitoringrulesv1.AutomaticReview_builder{
Integration: integrationName,
Decision: types.RequestState_APPROVED.String(),
- },
- },
- }
+ }.Build(),
+ }.Build(),
+ }.Build()
}
// mockEventHandler is a mock implementation of the EventHandler.
diff --git a/lib/accessmonitoring/review/review.go b/lib/accessmonitoring/review/review.go
index 5192caaf247..4ad3cb87c59 100644
--- a/lib/accessmonitoring/review/review.go
+++ b/lib/accessmonitoring/review/review.go
@@ -102,12 +102,12 @@ func (handler *Handler) initialize(ctx context.Context) error {
string,
error,
) {
- req := &accessmonitoringrulesv1.ListAccessMonitoringRulesWithFilterRequest{
+ req := accessmonitoringrulesv1.ListAccessMonitoringRulesWithFilterRequest_builder{
PageSize: pageSize,
PageToken: pageToken,
Subjects: []string{types.KindAccessRequest},
AutomaticReviewName: handler.HandlerName,
- }
+ }.Build()
page, next, err := handler.Client.ListAccessMonitoringRulesWithFilter(ctx, req)
if err != nil {
return nil, "", trace.Wrap(err)
diff --git a/lib/accessmonitoring/review/review_test.go b/lib/accessmonitoring/review/review_test.go
index 3a46a082df6..1d7e3464ebe 100644
--- a/lib/accessmonitoring/review/review_test.go
+++ b/lib/accessmonitoring/review/review_test.go
@@ -57,10 +57,10 @@ func TestInitializeCache(t *testing.T) {
})
require.NoError(t, err)
- mockReq := &accessmonitoringrulesv1.ListAccessMonitoringRulesWithFilterRequest{
+ mockReq := accessmonitoringrulesv1.ListAccessMonitoringRulesWithFilterRequest_builder{
Subjects: []string{types.KindAccessRequest},
AutomaticReviewName: handler.HandlerName,
- }
+ }.Build()
mockResp := []*accessmonitoringrulesv1.AccessMonitoringRule{
newApprovedRule("test-rule", "condition"),
@@ -119,7 +119,7 @@ func TestHandleAccessMonitoringRule(t *testing.T) {
// Test rule does not apply with invalid automatic approval name.
rule = newApprovedRule("test-rule", `condition`)
- rule.Spec.AutomaticReview.Integration = "invalid"
+ rule.GetSpec().GetAutomaticReview().SetIntegration("invalid")
require.NoError(t, handler.HandleAccessMonitoringRule(ctx, types.Event{
Type: types.OpPut,
Resource: types.Resource153ToResourceWithLabels(rule),
@@ -128,7 +128,7 @@ func TestHandleAccessMonitoringRule(t *testing.T) {
// Test rule does not apply with invalid state.
rule = newApprovedRule("test-rule", `condition`)
- rule.Spec.DesiredState = "invalid"
+ rule.GetSpec().SetDesiredState("invalid")
require.NoError(t, handler.HandleAccessMonitoringRule(ctx, types.Event{
Type: types.OpPut,
Resource: types.Resource153ToResourceWithLabels(rule),
@@ -137,7 +137,7 @@ func TestHandleAccessMonitoringRule(t *testing.T) {
// Test rule does not apply with invalid subject.
rule = newApprovedRule("test-rule", `condition`)
- rule.Spec.Subjects = []string{"invalid"}
+ rule.GetSpec().SetSubjects([]string{"invalid"})
require.NoError(t, handler.HandleAccessMonitoringRule(ctx, types.Event{
Type: types.OpPut,
Resource: types.Resource153ToResourceWithLabels(rule),
@@ -221,19 +221,19 @@ func TestScheduleRequest(t *testing.T) {
testRuleName,
`true`)
- testRule.Spec.Schedules = map[string]*accessmonitoringrulesv1.Schedule{
- "test-schedule": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ testRule.GetSpec().SetSchedules(map[string]*accessmonitoringrulesv1.Schedule{
+ "test-schedule": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{
- {
+ accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: time.Monday.String(),
Start: "14:00",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
- }
+ }.Build(),
+ }.Build(),
+ })
cache := accessmonitoring.NewCache()
cache.Put([]*accessmonitoringrulesv1.AccessMonitoringRule{testRule})
@@ -604,21 +604,21 @@ func newDeniedRule(name, condition string) *accessmonitoringrulesv1.AccessMonito
}
func newReviewRule(name, condition, decision string) *accessmonitoringrulesv1.AccessMonitoringRule {
- return &accessmonitoringrulesv1.AccessMonitoringRule{
+ return accessmonitoringrulesv1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
- },
- Spec: &accessmonitoringrulesv1.AccessMonitoringRuleSpec{
+ }.Build(),
+ Spec: accessmonitoringrulesv1.AccessMonitoringRuleSpec_builder{
Subjects: []string{types.KindAccessRequest},
Condition: condition,
DesiredState: types.AccessMonitoringRuleStateReviewed,
- AutomaticReview: &accessmonitoringrulesv1.AutomaticReview{
+ AutomaticReview: accessmonitoringrulesv1.AutomaticReview_builder{
Integration: handlerName,
Decision: decision,
- },
- },
- }
+ }.Build(),
+ }.Build(),
+ }.Build()
}
// mockClient is a mock implementation of the Teleport API client.
@@ -641,7 +641,7 @@ func (m *mockClient) ListAccessMonitoringRulesWithFilter(ctx context.Context, re
error,
) {
// Expect zero value page size for testing.
- req.PageSize = 0
+ req.SetPageSize(0)
args := m.Called(ctx, req)
rules, ok := args.Get(0).([]*accessmonitoringrulesv1.AccessMonitoringRule)
diff --git a/lib/accessmonitoring/schedule.go b/lib/accessmonitoring/schedule.go
index 69510a721fa..4ddb31844df 100644
--- a/lib/accessmonitoring/schedule.go
+++ b/lib/accessmonitoring/schedule.go
@@ -56,18 +56,18 @@ func inSchedule(schedule *accessmonitoringrulesv1.Schedule, timestamp time.Time)
weekday := timestamp.Weekday().String()
for _, shift := range schedule.GetTime().GetShifts() {
- if weekday != shift.Weekday {
+ if weekday != shift.GetWeekday() {
continue
}
- startTime, err := ClockTime(timestamp, shift.Start)
+ startTime, err := ClockTime(timestamp, shift.GetStart())
if err != nil {
- return false, trace.Wrap(err, "invalid start time: %q", shift.Start)
+ return false, trace.Wrap(err, "invalid start time: %q", shift.GetStart())
}
- endTime, err := ClockTime(timestamp, shift.End)
+ endTime, err := ClockTime(timestamp, shift.GetEnd())
if err != nil {
- return false, trace.Wrap(err, "invalid end time: %q", shift.End)
+ return false, trace.Wrap(err, "invalid end time: %q", shift.GetEnd())
}
if !timestamp.Before(startTime) && !timestamp.After(endTime) {
diff --git a/lib/accessmonitoring/schedule_test.go b/lib/accessmonitoring/schedule_test.go
index 08316b84fcf..5b17091bac1 100644
--- a/lib/accessmonitoring/schedule_test.go
+++ b/lib/accessmonitoring/schedule_test.go
@@ -95,17 +95,17 @@ func TestInSchedule(t *testing.T) {
{
description: "in schedule",
schedules: map[string]*accessmonitoringrulesv1.Schedule{
- "default": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ "default": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{
- {
+ accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: time.Monday.String(),
Start: "14:00",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
},
assertErr: require.NoError,
assertInSchedule: require.True,
@@ -113,11 +113,11 @@ func TestInSchedule(t *testing.T) {
{
description: "schedule does not contain any shifts",
schedules: map[string]*accessmonitoringrulesv1.Schedule{
- "default": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ "default": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{},
- },
- },
+ }.Build(),
+ }.Build(),
},
assertErr: require.NoError,
assertInSchedule: require.False,
@@ -125,18 +125,18 @@ func TestInSchedule(t *testing.T) {
{
description: "invalid timezone",
schedules: map[string]*accessmonitoringrulesv1.Schedule{
- "default": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ "default": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Timezone: "invalid",
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{
- {
+ accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: time.Monday.String(),
Start: "14:00",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
},
assertErr: func(t require.TestingT, err error, _ ...any) {
require.ErrorContains(t, err, "unknown time zone")
@@ -146,18 +146,18 @@ func TestInSchedule(t *testing.T) {
{
description: "different timezone",
schedules: map[string]*accessmonitoringrulesv1.Schedule{
- "default": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ "default": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Timezone: "America/Los_Angeles",
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{
- {
+ accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: time.Monday.String(),
Start: "14:00",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
},
assertErr: require.NoError,
assertInSchedule: require.False,
@@ -165,17 +165,17 @@ func TestInSchedule(t *testing.T) {
{
description: "different weekday",
schedules: map[string]*accessmonitoringrulesv1.Schedule{
- "default": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ "default": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{
- {
+ accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: time.Tuesday.String(),
Start: "14:00",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
},
assertErr: require.NoError,
assertInSchedule: require.False,
@@ -183,17 +183,17 @@ func TestInSchedule(t *testing.T) {
{
description: "before schedule",
schedules: map[string]*accessmonitoringrulesv1.Schedule{
- "default": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ "default": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{
- {
+ accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: time.Monday.String(),
Start: "14:31",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
},
assertErr: require.NoError,
assertInSchedule: require.False,
@@ -201,17 +201,17 @@ func TestInSchedule(t *testing.T) {
{
description: "exact start time",
schedules: map[string]*accessmonitoringrulesv1.Schedule{
- "default": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ "default": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{
- {
+ accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: time.Monday.String(),
Start: "14:30",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
},
assertErr: require.NoError,
assertInSchedule: require.True,
@@ -219,28 +219,28 @@ func TestInSchedule(t *testing.T) {
{
description: "multiple schedules",
schedules: map[string]*accessmonitoringrulesv1.Schedule{
- "schedule1": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ "schedule1": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{
- {
+ accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: time.Monday.String(),
Start: "14:30",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
- "schedule2": {
- Time: &accessmonitoringrulesv1.TimeSchedule{
+ }.Build(),
+ }.Build(),
+ "schedule2": accessmonitoringrulesv1.Schedule_builder{
+ Time: accessmonitoringrulesv1.TimeSchedule_builder{
Shifts: []*accessmonitoringrulesv1.TimeSchedule_Shift{
- {
+ accessmonitoringrulesv1.TimeSchedule_Shift_builder{
Weekday: time.Tuesday.String(),
Start: "14:30",
End: "15:00",
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
},
assertErr: require.NoError,
assertInSchedule: require.True,
diff --git a/lib/auth/access_request_test.go b/lib/auth/access_request_test.go
index bbdb5771961..d49abe8ce83 100644
--- a/lib/auth/access_request_test.go
+++ b/lib/auth/access_request_test.go
@@ -1054,30 +1054,30 @@ func testBotAccessRequestReview(t *testing.T, testPack *accessRequestTestPack) {
adminClient, err := testPack.tlsServer.NewClient(authtest.TestAdmin())
require.NoError(t, err)
defer adminClient.Close()
- bot, err := adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ bot, err := adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "request-approver",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{
// Grants the ability to approve requests
"admins",
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Use the bot user to generate some certs using role impersonation.
// This mimics what the bot actually does.
- botClient, err := testPack.tlsServer.NewClient(authtest.TestUser(bot.Status.UserName))
+ botClient, err := testPack.tlsServer.NewClient(authtest.TestUser(bot.GetStatus().GetUserName()))
require.NoError(t, err)
defer botClient.Close()
certRes, err := botClient.GenerateUserCerts(ctx, proto.UserCertsRequest{
- Username: bot.Status.UserName,
+ Username: bot.GetStatus().GetUserName(),
TLSPublicKey: testPack.tlsPubKey,
Expires: time.Now().Add(time.Hour),
@@ -1110,7 +1110,7 @@ func testBotAccessRequestReview(t *testing.T, testPack *accessRequestTestPack) {
require.NoError(t, err)
// Check the final state of the request
- require.Equal(t, bot.Status.UserName, accessRequest.GetReviews()[0].Author)
+ require.Equal(t, bot.GetStatus().GetUserName(), accessRequest.GetReviews()[0].Author)
require.Equal(t, types.RequestState_APPROVED, accessRequest.GetState())
}
diff --git a/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service.go b/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service.go
index e3e7e566656..6b008f13e75 100644
--- a/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service.go
+++ b/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service.go
@@ -79,7 +79,7 @@ func (s *Service) CreateAccessMonitoringRule(ctx context.Context, req *accessmon
if err := authCtx.CheckAccessToKind(types.KindAccessMonitoringRule, types.VerbCreate); err != nil {
return nil, trace.Wrap(err)
}
- created, err := s.backend.CreateAccessMonitoringRule(ctx, req.Rule)
+ created, err := s.backend.CreateAccessMonitoringRule(ctx, req.GetRule())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -96,7 +96,7 @@ func (s *Service) UpdateAccessMonitoringRule(ctx context.Context, req *accessmon
return nil, trace.Wrap(err)
}
- created, err := s.backend.UpdateAccessMonitoringRule(ctx, req.Rule)
+ created, err := s.backend.UpdateAccessMonitoringRule(ctx, req.GetRule())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -112,7 +112,7 @@ func (s *Service) GetAccessMonitoringRule(ctx context.Context, req *accessmonito
if err := authCtx.CheckAccessToKind(types.KindAccessMonitoringRule, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
- got, err := s.backend.GetAccessMonitoringRule(ctx, req.Name)
+ got, err := s.backend.GetAccessMonitoringRule(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -128,7 +128,7 @@ func (s *Service) DeleteAccessMonitoringRule(ctx context.Context, req *accessmon
if err := authCtx.CheckAccessToKind(types.KindAccessMonitoringRule, types.VerbDelete); err != nil {
return nil, trace.Wrap(err)
}
- if err := s.backend.DeleteAccessMonitoringRule(ctx, req.Name); err != nil {
+ if err := s.backend.DeleteAccessMonitoringRule(ctx, req.GetName()); err != nil {
return nil, trace.Wrap(err)
}
return &emptypb.Empty{}, nil
@@ -144,7 +144,7 @@ func (s *Service) UpsertAccessMonitoringRule(ctx context.Context, req *accessmon
return nil, trace.Wrap(err)
}
- created, err := s.backend.UpsertAccessMonitoringRule(ctx, req.Rule)
+ created, err := s.backend.UpsertAccessMonitoringRule(ctx, req.GetRule())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -160,14 +160,14 @@ func (s *Service) ListAccessMonitoringRules(ctx context.Context, req *accessmoni
if err := authCtx.CheckAccessToKind(types.KindAccessMonitoringRule, types.VerbRead, types.VerbList); err != nil {
return nil, trace.Wrap(err)
}
- results, nextToken, err := s.cache.ListAccessMonitoringRules(ctx, int(req.PageSize), req.PageToken)
+ results, nextToken, err := s.cache.ListAccessMonitoringRules(ctx, int(req.GetPageSize()), req.GetPageToken())
if err != nil {
return nil, trace.Wrap(err)
}
- return &accessmonitoringrulesv1.ListAccessMonitoringRulesResponse{
+ return accessmonitoringrulesv1.ListAccessMonitoringRulesResponse_builder{
Rules: results,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// ListAccessMonitoringRulesWithFilter lists current access monitoring rules.
@@ -183,8 +183,8 @@ func (s *Service) ListAccessMonitoringRulesWithFilter(ctx context.Context, req *
if err != nil {
return nil, trace.Wrap(err)
}
- return &accessmonitoringrulesv1.ListAccessMonitoringRulesWithFilterResponse{
+ return accessmonitoringrulesv1.ListAccessMonitoringRulesWithFilterResponse_builder{
Rules: results,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
diff --git a/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service_test.go b/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service_test.go
index 8594f6d054c..662be02cbfe 100644
--- a/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service_test.go
+++ b/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service_test.go
@@ -49,15 +49,15 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
ctx, localClient, resourceSvc := initSvc(t, clusterName)
sampleAccessMonitoringRuleFn := func(name string) *accessmonitoringrulev1.AccessMonitoringRule {
- return &accessmonitoringrulev1.AccessMonitoringRule{
+ return accessmonitoringrulev1.AccessMonitoringRule_builder{
Kind: types.KindAccessMonitoringRule,
Version: types.V1,
- Metadata: &v1.Metadata{Name: name},
- Spec: &accessmonitoringrulev1.AccessMonitoringRuleSpec{
+ Metadata: v1.Metadata_builder{Name: name}.Build(),
+ Spec: accessmonitoringrulev1.AccessMonitoringRuleSpec_builder{
Subjects: []string{"someSubject"},
Condition: "someCondition",
- },
- }
+ }.Build(),
+ }.Build()
}
tt := []struct {
@@ -81,9 +81,9 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
- _, err := resourceSvc.GetAccessMonitoringRule(ctx, &accessmonitoringrulev1.GetAccessMonitoringRuleRequest{
+ _, err := resourceSvc.GetAccessMonitoringRule(ctx, accessmonitoringrulev1.GetAccessMonitoringRuleRequest_builder{
Name: amrName,
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -92,9 +92,9 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
Name: "no access to read AccessMonitoringRules",
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
- _, err := resourceSvc.GetAccessMonitoringRule(ctx, &accessmonitoringrulev1.GetAccessMonitoringRuleRequest{
+ _, err := resourceSvc.GetAccessMonitoringRule(ctx, accessmonitoringrulev1.GetAccessMonitoringRuleRequest_builder{
Name: amrName,
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -108,9 +108,9 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
}}},
},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
- _, err := resourceSvc.GetAccessMonitoringRule(ctx, &accessmonitoringrulev1.GetAccessMonitoringRuleRequest{
+ _, err := resourceSvc.GetAccessMonitoringRule(ctx, accessmonitoringrulev1.GetAccessMonitoringRuleRequest_builder{
Name: amrName,
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -132,10 +132,10 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
}
},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
- _, err := resourceSvc.ListAccessMonitoringRules(ctx, &accessmonitoringrulev1.ListAccessMonitoringRulesRequest{
+ _, err := resourceSvc.ListAccessMonitoringRules(ctx, accessmonitoringrulev1.ListAccessMonitoringRulesRequest_builder{
PageSize: 0,
PageToken: "",
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -149,10 +149,10 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
}}},
},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
- _, err := resourceSvc.ListAccessMonitoringRules(ctx, &accessmonitoringrulev1.ListAccessMonitoringRulesRequest{
+ _, err := resourceSvc.ListAccessMonitoringRules(ctx, accessmonitoringrulev1.ListAccessMonitoringRulesRequest_builder{
PageSize: 0,
PageToken: "",
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -164,9 +164,9 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
amr := sampleAccessMonitoringRuleFn(amrName)
- _, err := resourceSvc.CreateAccessMonitoringRule(ctx, &accessmonitoringrulev1.CreateAccessMonitoringRuleRequest{
+ _, err := resourceSvc.CreateAccessMonitoringRule(ctx, accessmonitoringrulev1.CreateAccessMonitoringRuleRequest_builder{
Rule: amr,
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -181,9 +181,9 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
amr := sampleAccessMonitoringRuleFn(amrName)
- _, err := resourceSvc.CreateAccessMonitoringRule(ctx, &accessmonitoringrulev1.CreateAccessMonitoringRuleRequest{
+ _, err := resourceSvc.CreateAccessMonitoringRule(ctx, accessmonitoringrulev1.CreateAccessMonitoringRuleRequest_builder{
Rule: amr,
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -195,9 +195,9 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
amr := sampleAccessMonitoringRuleFn(amrName)
- _, err := resourceSvc.UpdateAccessMonitoringRule(ctx, &accessmonitoringrulev1.UpdateAccessMonitoringRuleRequest{
+ _, err := resourceSvc.UpdateAccessMonitoringRule(ctx, accessmonitoringrulev1.UpdateAccessMonitoringRuleRequest_builder{
Rule: amr,
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -216,9 +216,9 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
amr := sampleAccessMonitoringRuleFn(amrName)
- _, err := resourceSvc.UpdateAccessMonitoringRule(ctx, &accessmonitoringrulev1.UpdateAccessMonitoringRuleRequest{
+ _, err := resourceSvc.UpdateAccessMonitoringRule(ctx, accessmonitoringrulev1.UpdateAccessMonitoringRuleRequest_builder{
Rule: amr,
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -235,9 +235,9 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
amr := sampleAccessMonitoringRuleFn(amrName)
- _, err := resourceSvc.UpsertAccessMonitoringRule(ctx, &accessmonitoringrulev1.UpsertAccessMonitoringRuleRequest{
+ _, err := resourceSvc.UpsertAccessMonitoringRule(ctx, accessmonitoringrulev1.UpsertAccessMonitoringRuleRequest_builder{
Rule: amr,
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -253,9 +253,9 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
Setup: func(t *testing.T, amrName string) {},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
amr := sampleAccessMonitoringRuleFn(amrName)
- _, err := resourceSvc.UpsertAccessMonitoringRule(ctx, &accessmonitoringrulev1.UpsertAccessMonitoringRuleRequest{
+ _, err := resourceSvc.UpsertAccessMonitoringRule(ctx, accessmonitoringrulev1.UpsertAccessMonitoringRuleRequest_builder{
Rule: amr,
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -266,7 +266,7 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
Name: "no access to delete AccessMonitoringRule",
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
- _, err := resourceSvc.DeleteAccessMonitoringRule(ctx, &accessmonitoringrulev1.DeleteAccessMonitoringRuleRequest{Name: "x"})
+ _, err := resourceSvc.DeleteAccessMonitoringRule(ctx, accessmonitoringrulev1.DeleteAccessMonitoringRuleRequest_builder{Name: "x"}.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -284,7 +284,7 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, amrName string) error {
- _, err := resourceSvc.DeleteAccessMonitoringRule(ctx, &accessmonitoringrulev1.DeleteAccessMonitoringRuleRequest{Name: amrName})
+ _, err := resourceSvc.DeleteAccessMonitoringRule(ctx, accessmonitoringrulev1.DeleteAccessMonitoringRuleRequest_builder{Name: amrName}.Build())
return err
},
ErrAssertion: require.NoError,
diff --git a/lib/auth/appauthconfig/appauthconfigv1/events.go b/lib/auth/appauthconfig/appauthconfigv1/events.go
index ee47f9f685f..5582a038451 100644
--- a/lib/auth/appauthconfig/appauthconfigv1/events.go
+++ b/lib/auth/appauthconfig/appauthconfigv1/events.go
@@ -73,12 +73,12 @@ func newVerifyJWTAuditEvent(ctx context.Context, req *appauthconfigv1.CreateAppS
Code: events.AppAuthConfigVerifySuccessCode,
Type: events.AppAuthConfigVerifySuccessEvent,
},
- AppAuthConfig: req.ConfigName,
+ AppAuthConfig: req.GetConfigName(),
UserMetadata: authz.ClientUserMetadata(ctx),
SessionMetadata: apievents.SessionMetadata{SessionID: sid},
AppMetadata: apievents.AppMetadata{
- AppName: req.App.AppName,
- AppURI: req.App.Uri,
+ AppName: req.GetApp().GetAppName(),
+ AppURI: req.GetApp().GetUri(),
},
Status: apievents.Status{
Success: true,
diff --git a/lib/auth/appauthconfig/appauthconfigv1/service.go b/lib/auth/appauthconfig/appauthconfigv1/service.go
index 624e6ab874e..700d4ac1f1c 100644
--- a/lib/auth/appauthconfig/appauthconfigv1/service.go
+++ b/lib/auth/appauthconfig/appauthconfigv1/service.go
@@ -130,10 +130,10 @@ func (s *Service) ListAppAuthConfigs(ctx context.Context, req *appauthconfigv1.L
if err != nil {
return nil, trace.Wrap(err)
}
- return &appauthconfigv1.ListAppAuthConfigsResponse{
+ return appauthconfigv1.ListAppAuthConfigsResponse_builder{
Configs: page,
NextPageToken: token,
- }, nil
+ }.Build(), nil
}
// UpdateAppAuthConfig implements appauthconfigv1.AppAuthConfigServiceServer.
diff --git a/lib/auth/appauthconfig/appauthconfigv1/service_test.go b/lib/auth/appauthconfig/appauthconfigv1/service_test.go
index 6e8be234d1b..ebe953e6d80 100644
--- a/lib/auth/appauthconfig/appauthconfigv1/service_test.go
+++ b/lib/auth/appauthconfig/appauthconfigv1/service_test.go
@@ -26,6 +26,7 @@ import (
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
appauthconfigv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/appauthconfig/v1"
labelv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/label/v1"
@@ -65,9 +66,9 @@ func TestAppAuthConfigCRUD(t *testing.T) {
{
name: "CreateAppAuthConfig",
actionFn: func(t *testing.T, ctx context.Context, clt testClient) error {
- _, err := clt.ServiceUnderTest.CreateAppAuthConfig(ctx, &appauthconfigv1.CreateAppAuthConfigRequest{
+ _, err := clt.ServiceUnderTest.CreateAppAuthConfig(ctx, appauthconfigv1.CreateAppAuthConfigRequest_builder{
Config: newAppAuthConfigJWT(),
- })
+ }.Build())
return err
},
requiredAccessRules: []types.Rule{appAuthConfigRule(types.VerbCreate)},
@@ -80,9 +81,9 @@ func TestAppAuthConfigCRUD(t *testing.T) {
cfg1 := newAppAuthConfigJWT()
_, err := clt.CreateAppAuthConfig(ctx, cfg1)
require.NoError(t, err)
- _, err = clt.ServiceUnderTest.GetAppAuthConfig(ctx, &appauthconfigv1.GetAppAuthConfigRequest{
- Name: cfg1.Metadata.GetName(),
- })
+ _, err = clt.ServiceUnderTest.GetAppAuthConfig(ctx, appauthconfigv1.GetAppAuthConfigRequest_builder{
+ Name: cfg1.GetMetadata().GetName(),
+ }.Build())
return err
},
requiredAccessRules: []types.Rule{appAuthConfigRule(types.VerbRead)},
@@ -97,7 +98,7 @@ func TestAppAuthConfigCRUD(t *testing.T) {
resp, err := clt.ServiceUnderTest.ListAppAuthConfigs(ctx, &appauthconfigv1.ListAppAuthConfigsRequest{})
if err == nil {
require.NotNil(t, resp)
- require.Len(t, resp.Configs, 2, "expected 2 inserted")
+ require.Len(t, resp.GetConfigs(), 2, "expected 2 inserted")
}
return err
},
@@ -109,13 +110,13 @@ func TestAppAuthConfigCRUD(t *testing.T) {
actionFn: func(t *testing.T, ctx context.Context, clt testClient) error {
cfg, err := clt.CreateAppAuthConfig(ctx, newAppAuthConfigJWT())
require.NoError(t, err)
- firstRev := cfg.Metadata.Revision
- cfg, err = clt.ServiceUnderTest.UpdateAppAuthConfig(ctx, &appauthconfigv1.UpdateAppAuthConfigRequest{
+ firstRev := cfg.GetMetadata().GetRevision()
+ cfg, err = clt.ServiceUnderTest.UpdateAppAuthConfig(ctx, appauthconfigv1.UpdateAppAuthConfigRequest_builder{
Config: cfg,
- })
+ }.Build())
if err == nil {
require.NotNil(t, cfg, "the updated resource should be returned")
- require.NotEqual(t, firstRev, cfg.Metadata.Revision, "the resource should have been updated")
+ require.NotEqual(t, firstRev, cfg.GetMetadata().GetRevision(), "the resource should have been updated")
}
return err
},
@@ -126,9 +127,9 @@ func TestAppAuthConfigCRUD(t *testing.T) {
name: "UpsertAppAuthConfig",
actionFn: func(t *testing.T, ctx context.Context, clt testClient) error {
cfg := newAppAuthConfigJWT()
- _, err := clt.ServiceUnderTest.UpsertAppAuthConfig(ctx, &appauthconfigv1.UpsertAppAuthConfigRequest{
+ _, err := clt.ServiceUnderTest.UpsertAppAuthConfig(ctx, appauthconfigv1.UpsertAppAuthConfigRequest_builder{
Config: cfg,
- })
+ }.Build())
return err
},
requiredAccessRules: []types.Rule{appAuthConfigRule(types.VerbCreate, types.VerbUpdate)},
@@ -140,9 +141,9 @@ func TestAppAuthConfigCRUD(t *testing.T) {
actionFn: func(t *testing.T, ctx context.Context, clt testClient) error {
cfg, err := clt.CreateAppAuthConfig(ctx, newAppAuthConfigJWT())
require.NoError(t, err)
- _, err = clt.ServiceUnderTest.DeleteAppAuthConfig(ctx, &appauthconfigv1.DeleteAppAuthConfigRequest{
- Name: cfg.Metadata.GetName(),
- })
+ _, err = clt.ServiceUnderTest.DeleteAppAuthConfig(ctx, appauthconfigv1.DeleteAppAuthConfigRequest_builder{
+ Name: cfg.GetMetadata().GetName(),
+ }.Build())
return err
},
requiredAccessRules: []types.Rule{appAuthConfigRule(types.VerbDelete)},
@@ -216,14 +217,12 @@ func (c *accessTest) run(t *testing.T) {
func newAppAuthConfigJWT() *appauthconfigv1.AppAuthConfig {
return appauthconfig.NewAppAuthConfigJWT(
uuid.NewString(),
- []*labelv1.Label{{Name: "*", Values: []string{"*"}}},
- &appauthconfigv1.AppAuthConfigJWTSpec{
+ []*labelv1.Label{labelv1.Label_builder{Name: "*", Values: []string{"*"}}.Build()},
+ appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: "https://issuer-url",
Audience: "teleport",
- KeysSource: &appauthconfigv1.AppAuthConfigJWTSpec_JwksUrl{
- JwksUrl: "https://issuer-url/.well-known/jwks.json",
- },
- },
+ JwksUrl: proto.String("https://issuer-url/.well-known/jwks.json"),
+ }.Build(),
)
}
diff --git a/lib/auth/appauthconfig/appauthconfigv1/sessions_service.go b/lib/auth/appauthconfig/appauthconfigv1/sessions_service.go
index 32fe6b920ad..b0756cdc7d6 100644
--- a/lib/auth/appauthconfig/appauthconfigv1/sessions_service.go
+++ b/lib/auth/appauthconfig/appauthconfigv1/sessions_service.go
@@ -159,17 +159,17 @@ func (s *SessionsService) CreateAppSessionWithJWT(ctx context.Context, req *appa
return nil, trace.AccessDenied("this request can be only executed by a proxy")
}
- sid := services.GenerateAppSessionIDFromJWT(req.Jwt)
+ sid := services.GenerateAppSessionIDFromJWT(req.GetJwt())
if err := validateCreateAppSessionWithJWTRequest(req); err != nil {
return nil, trace.Wrap(err)
}
- config, err := s.cache.GetAppAuthConfig(ctx, req.ConfigName)
+ config, err := s.cache.GetAppAuthConfig(ctx, req.GetConfigName())
if err != nil {
return nil, trace.Wrap(err)
}
- jwtConfig := config.Spec.GetJwt()
+ jwtConfig := config.GetSpec().GetJwt()
if jwtConfig == nil {
return nil, trace.BadParameter("app auth config jwt session can only start with jwt configs")
}
@@ -179,7 +179,7 @@ func (s *SessionsService) CreateAppSessionWithJWT(ctx context.Context, req *appa
return nil, trace.Wrap(err)
}
- username, tokenTTL, err := verifyAppAuthJWTToken(req.Jwt, jwks, sigs, jwtConfig)
+ username, tokenTTL, err := verifyAppAuthJWTToken(req.GetJwt(), jwks, sigs, jwtConfig)
if err != nil {
return nil, trace.Wrap(err)
}
@@ -191,11 +191,11 @@ func (s *SessionsService) CreateAppSessionWithJWT(ctx context.Context, req *appa
ws, err := s.sessions.CreateAppSessionForAppAuth(ctx, &CreateAppSessionForAppAuthRequest{
Username: username,
- ClusterName: req.App.ClusterName,
- AppName: req.App.AppName,
- AppURI: req.App.Uri,
- AppPublicAddr: req.App.PublicAddr,
- LoginIP: req.RemoteAddr,
+ ClusterName: req.GetApp().GetClusterName(),
+ AppName: req.GetApp().GetAppName(),
+ AppURI: req.GetApp().GetUri(),
+ AppPublicAddr: req.GetApp().GetPublicAddr(),
+ LoginIP: req.GetRemoteAddr(),
Roles: user.GetRoles(),
Traits: user.GetTraits(),
TTL: time.Until(tokenTTL),
@@ -206,16 +206,16 @@ func (s *SessionsService) CreateAppSessionWithJWT(ctx context.Context, req *appa
return nil, trace.Wrap(err)
}
- return &appauthconfigv1.CreateAppSessionWithJWTResponse{Session: ws.(*types.WebSessionV2)}, nil
+ return appauthconfigv1.CreateAppSessionWithJWTResponse_builder{Session: ws.(*types.WebSessionV2)}.Build(), nil
}
// retrieveJWKSAppAuthConfig retrieves JWKS contents given a app auth JWT
// config.
func retrieveJWKSAppAuthConfig(jwtConfig *appauthconfigv1.AppAuthConfigJWTSpec, httpClient *http.Client) (*jose.JSONWebKeySet, []jose.SignatureAlgorithm, error) {
var rawJwks []byte
- switch jwksSource := jwtConfig.KeysSource.(type) {
- case *appauthconfigv1.AppAuthConfigJWTSpec_JwksUrl:
- req, err := http.NewRequest(http.MethodGet, jwksSource.JwksUrl, nil)
+ switch jwtConfig.WhichKeysSource() {
+ case appauthconfigv1.AppAuthConfigJWTSpec_JwksUrl_case:
+ req, err := http.NewRequest(http.MethodGet, jwtConfig.GetJwksUrl(), nil)
if err != nil {
return nil, nil, trace.Wrap(err)
}
@@ -230,8 +230,8 @@ func retrieveJWKSAppAuthConfig(jwtConfig *appauthconfigv1.AppAuthConfigJWTSpec,
if err != nil {
return nil, nil, trace.Wrap(err)
}
- case *appauthconfigv1.AppAuthConfigJWTSpec_StaticJwks:
- rawJwks = []byte(jwksSource.StaticJwks)
+ case appauthconfigv1.AppAuthConfigJWTSpec_StaticJwks_case:
+ rawJwks = []byte(jwtConfig.GetStaticJwks())
}
var jwks jose.JSONWebKeySet
@@ -268,8 +268,8 @@ func verifyAppAuthJWTToken(jwtToken string, jwks *jose.JSONWebKeySet, sigs []jos
}
expected := jwt.Expected{
- Issuer: jwtConfig.Issuer,
- AnyAudience: jwt.Audience{jwtConfig.Audience},
+ Issuer: jwtConfig.GetIssuer(),
+ AnyAudience: jwt.Audience{jwtConfig.GetAudience()},
Time: time.Now(),
}
if err := claims.Validate(expected); err != nil {
@@ -289,7 +289,7 @@ func verifyAppAuthJWTToken(jwtToken string, jwks *jose.JSONWebKeySet, sigs []jos
return "", time.Time{}, trace.BadParameter("token must be issued recently to be used")
}
- usernameClaimName := cmp.Or(jwtConfig.UsernameClaim, defaultUsernameClaim)
+ usernameClaimName := cmp.Or(jwtConfig.GetUsernameClaim(), defaultUsernameClaim)
usernameClaim, ok := remainingClaims[usernameClaimName]
if !ok {
return "", time.Time{}, trace.BadParameter("token must have %q claim", usernameClaimName)
@@ -305,17 +305,17 @@ func verifyAppAuthJWTToken(jwtToken string, jwks *jose.JSONWebKeySet, sigs []jos
func validateCreateAppSessionWithJWTRequest(req *appauthconfigv1.CreateAppSessionWithJWTRequest) error {
switch {
- case req.ConfigName == "":
+ case req.GetConfigName() == "":
return trace.BadParameter("create app session request requires an app auth config name")
- case req.App == nil:
+ case !req.HasApp():
return trace.BadParameter("create app session request requires app information")
- case req.App.AppName == "":
+ case req.GetApp().GetAppName() == "":
return trace.BadParameter("create app session request requires app name")
- case req.App.ClusterName == "":
+ case req.GetApp().GetClusterName() == "":
return trace.BadParameter("create app session request requires app cluster name")
- case req.App.PublicAddr == "":
+ case req.GetApp().GetPublicAddr() == "":
return trace.BadParameter("create app session request requires app public address")
- case req.App.Uri == "":
+ case req.GetApp().GetUri() == "":
return trace.BadParameter("create app session request requires app uri")
}
diff --git a/lib/auth/appauthconfig/appauthconfigv1/sessions_service_test.go b/lib/auth/appauthconfig/appauthconfigv1/sessions_service_test.go
index d3a621d8d18..b57ee5fea33 100644
--- a/lib/auth/appauthconfig/appauthconfigv1/sessions_service_test.go
+++ b/lib/auth/appauthconfig/appauthconfigv1/sessions_service_test.go
@@ -32,6 +32,7 @@ import (
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
appauthconfigv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/appauthconfig/v1"
labelv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/label/v1"
@@ -70,11 +71,9 @@ func TestRetrieveJWKS(t *testing.T) {
t.Run("static", func(t *testing.T) {
t.Run("valid", func(t *testing.T) {
jwksRes, sigsRes, err := retrieveJWKSAppAuthConfig(
- &appauthconfigv1.AppAuthConfigJWTSpec{
- KeysSource: &appauthconfigv1.AppAuthConfigJWTSpec_StaticJwks{
- StaticJwks: string(encodedJwks),
- },
- },
+ appauthconfigv1.AppAuthConfigJWTSpec_builder{
+ StaticJwks: proto.String(string(encodedJwks)),
+ }.Build(),
nil, /* httpClient */
)
require.NoError(t, err)
@@ -84,11 +83,9 @@ func TestRetrieveJWKS(t *testing.T) {
t.Run("empty", func(t *testing.T) {
_, _, err := retrieveJWKSAppAuthConfig(
- &appauthconfigv1.AppAuthConfigJWTSpec{
- KeysSource: &appauthconfigv1.AppAuthConfigJWTSpec_StaticJwks{
- StaticJwks: "{}",
- },
- },
+ appauthconfigv1.AppAuthConfigJWTSpec_builder{
+ StaticJwks: proto.String("{}"),
+ }.Build(),
nil, /* httpClient */
)
require.Error(t, err)
@@ -136,11 +133,9 @@ func TestRetrieveJWKS(t *testing.T) {
t.Cleanup(func() { httpSrv.Close() })
jwks, sigs, err := retrieveJWKSAppAuthConfig(
- &appauthconfigv1.AppAuthConfigJWTSpec{
- KeysSource: &appauthconfigv1.AppAuthConfigJWTSpec_JwksUrl{
- JwksUrl: httpSrv.URL,
- },
- },
+ appauthconfigv1.AppAuthConfigJWTSpec_builder{
+ JwksUrl: proto.String(httpSrv.URL),
+ }.Build(),
httpSrv.Client(),
)
tc.assertError(t, err)
@@ -162,11 +157,11 @@ func TestVerifyJWTToken(t *testing.T) {
assertUsername require.ValueAssertionFunc
}{
"valid token": {
- config: &appauthconfigv1.AppAuthConfigJWTSpec{
+ config: appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: "https://issuer-url/",
Audience: "teleport",
UsernameClaim: "username",
- },
+ }.Build(),
claims: jwt.Claims{
Issuer: "https://issuer-url/",
Audience: []string{"teleport"},
@@ -182,10 +177,10 @@ func TestVerifyJWTToken(t *testing.T) {
},
},
"default username claim": {
- config: &appauthconfigv1.AppAuthConfigJWTSpec{
+ config: appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: "https://issuer-url/",
Audience: "teleport",
- },
+ }.Build(),
claims: jwt.Claims{
Issuer: "https://issuer-url/",
Audience: []string{"teleport"},
@@ -201,10 +196,10 @@ func TestVerifyJWTToken(t *testing.T) {
},
},
"wrong audience": {
- config: &appauthconfigv1.AppAuthConfigJWTSpec{
+ config: appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: "https://issuer-url/",
Audience: "teleport",
- },
+ }.Build(),
claims: jwt.Claims{
Issuer: "https://issuer-url/",
Audience: []string{"random-app"},
@@ -218,10 +213,10 @@ func TestVerifyJWTToken(t *testing.T) {
assertUsername: require.Empty,
},
"wrong issuer": {
- config: &appauthconfigv1.AppAuthConfigJWTSpec{
+ config: appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: "https://issuer-url/",
Audience: "teleport",
- },
+ }.Build(),
claims: jwt.Claims{
Issuer: "https://random-issuer/",
Audience: []string{"teleport"},
@@ -235,10 +230,10 @@ func TestVerifyJWTToken(t *testing.T) {
assertUsername: require.Empty,
},
"missing username claim": {
- config: &appauthconfigv1.AppAuthConfigJWTSpec{
+ config: appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: "https://issuer-url/",
Audience: "teleport",
- },
+ }.Build(),
claims: jwt.Claims{
Issuer: "https://issuer-url/",
Audience: []string{"teleport"},
@@ -250,10 +245,10 @@ func TestVerifyJWTToken(t *testing.T) {
assertUsername: require.Empty,
},
"missing issued at claim": {
- config: &appauthconfigv1.AppAuthConfigJWTSpec{
+ config: appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: "https://issuer-url/",
Audience: "teleport",
- },
+ }.Build(),
claims: jwt.Claims{
Issuer: "https://issuer-url/",
Audience: []string{"teleport"},
@@ -266,10 +261,10 @@ func TestVerifyJWTToken(t *testing.T) {
assertUsername: require.Empty,
},
"missing exp claim": {
- config: &appauthconfigv1.AppAuthConfigJWTSpec{
+ config: appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: "https://issuer-url/",
Audience: "teleport",
- },
+ }.Build(),
claims: jwt.Claims{
Issuer: "https://issuer-url/",
Audience: []string{"teleport"},
@@ -293,14 +288,14 @@ func TestVerifyJWTToken(t *testing.T) {
}
t.Run("token freshness", func(t *testing.T) {
- config := &appauthconfigv1.AppAuthConfigJWTSpec{
+ config := appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: "https://issuer-url/",
Audience: "teleport",
UsernameClaim: "email",
- }
+ }.Build()
baseClaims := jwt.Claims{
- Issuer: config.Issuer,
- Audience: []string{config.Audience},
+ Issuer: config.GetIssuer(),
+ Audience: []string{config.GetAudience()},
}
usernameClaim := struct {
Email string `json:"email"`
@@ -352,14 +347,12 @@ func TestCreateAppSessionWithJWT(t *testing.T) {
user, err := types.NewUser("user")
require.NoError(t, err)
- config := appauthconfig.NewAppAuthConfigJWT("test-config", []*labelv1.Label{{Name: "*", Values: []string{"*"}}}, &appauthconfigv1.AppAuthConfigJWTSpec{
+ config := appauthconfig.NewAppAuthConfigJWT("test-config", []*labelv1.Label{labelv1.Label_builder{Name: "*", Values: []string{"*"}}.Build()}, appauthconfigv1.AppAuthConfigJWTSpec_builder{
Issuer: issuer,
Audience: audience,
UsernameClaim: usernameClaim,
- KeysSource: &appauthconfigv1.AppAuthConfigJWTSpec_StaticJwks{
- StaticJwks: string(encodedJwks),
- },
- })
+ StaticJwks: proto.String(string(encodedJwks)),
+ }.Build())
assertAuditEventFailure := func(tt require.TestingT, i1 any, i2 ...any) {
require.IsType(t, &apievents.AppAuthConfigVerify{}, i1, i2...)
@@ -468,16 +461,16 @@ func TestCreateAppSessionWithJWT(t *testing.T) {
})
require.NoError(t, err)
- _, err = svc.CreateAppSessionWithJWT(t.Context(), &appauthconfigv1.CreateAppSessionWithJWTRequest{
+ _, err = svc.CreateAppSessionWithJWT(t.Context(), appauthconfigv1.CreateAppSessionWithJWTRequest_builder{
ConfigName: "app-config-example",
Jwt: tc.token,
- App: &appauthconfigv1.App{
+ App: appauthconfigv1.App_builder{
AppName: "mcp-app",
PublicAddr: "https://proxy/mcp-app",
Uri: "mcp+https://localhost/mcp",
ClusterName: "example",
- },
- })
+ }.Build(),
+ }.Build())
tc.assertError(t, err)
tc.assertAuditEvent(t, emitter.LastEvent())
})
diff --git a/lib/auth/auth.go b/lib/auth/auth.go
index bda5ce2236d..c84f757dd6a 100644
--- a/lib/auth/auth.go
+++ b/lib/auth/auth.go
@@ -2370,7 +2370,7 @@ func (a *Server) doReleaseAlertSync(ctx context.Context, current vc.Target, visi
// server is up to date, but instances not connected to this auth need update.
var instanceVisitor vc.Visitor
a.inventory.UniqueHandles(func(handle inventory.UpstreamHandle) {
- v := vc.Normalize(handle.Hello().Version)
+ v := vc.Normalize(handle.Hello().GetVersion())
instanceVisitor.Visit(vc.NewTarget(v))
})
@@ -5557,14 +5557,14 @@ func (a *Server) GenerateHostCerts(ctx context.Context, params HostCertsParams)
var agentScopePin *scopesv1.Pin
if useAgentPin {
- agentScopePin = &scopesv1.Pin{
+ agentScopePin = scopesv1.Pin_builder{
Kind: scopesv1.PinKind_PIN_KIND_AGENT,
Scope: params.AgentScope,
- SystemRoles: &scopesv1.SystemRoles{
+ SystemRoles: scopesv1.SystemRoles_builder{
Primary: req.Role.String(),
Additional: systemRoles,
- },
- }
+ }.Build(),
+ }.Build()
}
// Agent scope pins encode role and scope solely via ScopePin; setting the
@@ -5682,10 +5682,10 @@ func (a *Server) RegisterInventoryControlStream(ics client.UpstreamInventoryCont
// in order to simplify creation of in-memory streams when dealing with local auth (note: in theory we could
// send hellos simultaneously to slightly improve perf, but there is a potential benefit to having the
// downstream hello serve double-duty as an indicator of having successfully transitioned the rbac layer).
- downstreamHello := &proto.DownstreamInventoryHello{
+ downstreamHello := proto.DownstreamInventoryHello_builder{
Version: teleport.Version,
ServerID: a.ServerID,
- Capabilities: &proto.DownstreamInventoryHello_SupportedCapabilities{
+ Capabilities: proto.DownstreamInventoryHello_SupportedCapabilities_builder{
NodeHeartbeats: true,
AppHeartbeats: true,
AppCleanup: true,
@@ -5695,8 +5695,8 @@ func (a *Server) RegisterInventoryControlStream(ics client.UpstreamInventoryCont
KubernetesHeartbeats: true,
KubernetesCleanup: true,
RelayServerHeartbeatsCleanup: true,
- },
- }
+ }.Build(),
+ }.Build()
if err := ics.Send(a.CloseContext(), downstreamHello); err != nil {
return trace.Wrap(err)
}
@@ -5730,35 +5730,35 @@ func (a *Server) MakeLocalInventoryControlStream(opts ...client.ICSPipeOption) c
func (a *Server) GetInventoryStatus(ctx context.Context, req *proto.InventoryStatusRequest) (*proto.InventoryStatusSummary, error) {
rsp := new(proto.InventoryStatusSummary)
- if req.Connected {
+ if req.GetConnected() {
a.inventory.UniqueHandles(func(handle inventory.UpstreamHandle) {
- rsp.Connected = append(rsp.Connected, handle.Hello())
+ rsp.SetConnected(append(rsp.GetConnected(), handle.Hello()))
})
// connected instance list is a special case, don't bother aggregating heartbeats
return rsp, nil
}
- rsp.VersionCounts = make(map[string]uint32)
- rsp.UpgraderCounts = make(map[string]uint32)
- rsp.ServiceCounts = make(map[string]uint32)
+ rsp.SetVersionCounts(make(map[string]uint32))
+ rsp.SetUpgraderCounts(make(map[string]uint32))
+ rsp.SetServiceCounts(make(map[string]uint32))
ins := a.GetInstances(ctx, types.InstanceFilter{})
for ins.Next() {
- rsp.InstanceCount++
+ rsp.SetInstanceCount(rsp.GetInstanceCount() + 1)
- rsp.VersionCounts[vc.Normalize(ins.Item().GetTeleportVersion())]++
+ rsp.GetVersionCounts()[vc.Normalize(ins.Item().GetTeleportVersion())]++
upgrader := ins.Item().GetExternalUpgrader()
if upgrader == "" {
upgrader = "none"
}
- rsp.UpgraderCounts[upgrader]++
+ rsp.GetUpgraderCounts()[upgrader]++
for _, service := range ins.Item().GetServices() {
- rsp.ServiceCounts[string(service)]++
+ rsp.GetServiceCounts()[string(service)]++
}
}
@@ -6160,31 +6160,29 @@ func (a *Server) CreateAccessRequestV2(ctx context.Context, req types.AccessRequ
}
}
- _, err = a.Services.CreateGlobalNotification(ctx, ¬ificationsv1.GlobalNotification{
- Spec: ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByPermissions{
- ByPermissions: ¬ificationsv1.ByPermissions{
- RoleConditions: []*types.RoleConditions{
- {
- ReviewRequests: &types.AccessReviewConditions{
- Roles: req.GetOriginalRoles(),
- },
+ _, err = a.Services.CreateGlobalNotification(ctx, notificationsv1.GlobalNotification_builder{
+ Spec: notificationsv1.GlobalNotificationSpec_builder{
+ ByPermissions: notificationsv1.ByPermissions_builder{
+ RoleConditions: []*types.RoleConditions{
+ {
+ ReviewRequests: &types.AccessReviewConditions{
+ Roles: req.GetOriginalRoles(),
},
},
},
- },
+ }.Build(),
// Prevent the requester from seeing the notification for their own access request.
ExcludeUsers: []string{req.GetUser()},
- Notification: ¬ificationsv1.Notification{
+ Notification: notificationsv1.Notification_builder{
Spec: ¬ificationsv1.NotificationSpec{},
SubKind: types.NotificationAccessRequestPendingSubKind,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Labels: map[string]string{types.NotificationTitleLabel: notificationText, "request-id": req.GetName()},
Expires: timestamppb.New(req.Expiry()),
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
if err != nil {
a.logger.WarnContext(ctx, "Failed to create access request notification", "error", err)
}
@@ -6566,12 +6564,12 @@ func generateAccessRequestReviewedNotification(req types.AccessRequest, params t
assumableTime = req.GetAssumeStartTime().Format("2006-01-02T15:04:05.000Z0700")
}
- return ¬ificationsv1.Notification{
- Spec: ¬ificationsv1.NotificationSpec{
+ return notificationsv1.Notification_builder{
+ Spec: notificationsv1.NotificationSpec_builder{
Username: req.GetUser(),
- },
+ }.Build(),
SubKind: subKind,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Labels: map[string]string{
types.NotificationTitleLabel: notificationText,
"request-id": params.RequestID,
@@ -6579,8 +6577,8 @@ func generateAccessRequestReviewedNotification(req types.AccessRequest, params t
"assumable-time": assumableTime,
},
Expires: timestamppb.New(req.Expiry()),
- },
- }
+ }.Build(),
+ }.Build()
}
func (a *Server) GetAccessCapabilities(ctx context.Context, req types.AccessCapabilitiesRequest) (*types.AccessCapabilities, error) {
@@ -7323,7 +7321,7 @@ func (a *Server) CreateAccessListReminderNotifications(ctx context.Context, opts
accessListIDs := set.New[string]()
for _, id := range identifiers {
// id.Spec.UniqueIdentifier is the access list ID
- accessListIDs.Add(id.Spec.UniqueIdentifier)
+ accessListIDs.Add(id.GetSpec().GetUniqueIdentifier())
}
// owners is the combined list of owners for relevant access lists we are creating the notification for.
@@ -7380,54 +7378,50 @@ func (a *Server) CreateAccessListReminderNotifications(ctx context.Context, opts
// createAccessListReminderNotification is a helper function to create a notification for an access list reminder.
func (a *Server) createAccessListReminderNotification(ctx context.Context, owners []string, subkind string, title string) error {
- _, err := a.Services.CreateGlobalNotification(ctx, ¬ificationsv1.GlobalNotification{
- Spec: ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByUsers{
- ByUsers: ¬ificationsv1.ByUsers{
- Users: owners,
- },
- },
- Notification: ¬ificationsv1.Notification{
+ _, err := a.Services.CreateGlobalNotification(ctx, notificationsv1.GlobalNotification_builder{
+ Spec: notificationsv1.GlobalNotificationSpec_builder{
+ ByUsers: notificationsv1.ByUsers_builder{
+ Users: owners,
+ }.Build(),
+ Notification: notificationsv1.Notification_builder{
Spec: ¬ificationsv1.NotificationSpec{},
SubKind: subkind,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Labels: map[string]string{types.NotificationTitleLabel: title},
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
if err != nil {
return err
}
// Also create a notification for users who have CRUD permissions for access lists. This is because they can also review access lists.
- _, err = a.Services.CreateGlobalNotification(ctx, ¬ificationsv1.GlobalNotification{
- Spec: ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByPermissions{
- ByPermissions: ¬ificationsv1.ByPermissions{
- RoleConditions: []*types.RoleConditions{
- {
- Rules: []types.Rule{
- {
- Resources: []string{types.KindAccessList},
- Verbs: services.RW(),
- },
+ _, err = a.Services.CreateGlobalNotification(ctx, notificationsv1.GlobalNotification_builder{
+ Spec: notificationsv1.GlobalNotificationSpec_builder{
+ ByPermissions: notificationsv1.ByPermissions_builder{
+ RoleConditions: []*types.RoleConditions{
+ {
+ Rules: []types.Rule{
+ {
+ Resources: []string{types.KindAccessList},
+ Verbs: services.RW(),
},
},
},
},
- },
+ }.Build(),
// Exclude the list of owners so that they don't get a duplicate notification, since we already created a notification for them.
ExcludeUsers: owners,
- Notification: ¬ificationsv1.Notification{
+ Notification: notificationsv1.Notification_builder{
Spec: ¬ificationsv1.NotificationSpec{},
SubKind: subkind,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Labels: map[string]string{types.NotificationTitleLabel: title},
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
if err != nil {
return err
}
diff --git a/lib/auth/auth_login_test.go b/lib/auth/auth_login_test.go
index 2dc334924cf..80a8adbb8a0 100644
--- a/lib/auth/auth_login_test.go
+++ b/lib/auth/auth_login_test.go
@@ -975,69 +975,69 @@ func TestBasicSSHScopedLogin(t *testing.T) {
// set up some scoped roles
scopedRoles := []*scopedaccessv1.ScopedRole{
- {
+ scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "role-a",
- },
+ }.Build(),
Scope: "/aa",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/aa"},
- Ssh: &scopedaccessv1.ScopedRoleSSH{
+ Ssh: scopedaccessv1.ScopedRoleSSH_builder{
Logins: []string{"login-a"},
- },
- },
+ }.Build(),
+ }.Build(),
Version: types.V1,
- },
- {
+ }.Build(),
+ scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "role-b",
- },
+ }.Build(),
Scope: "/aa/bb",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/aa/bb"},
- Ssh: &scopedaccessv1.ScopedRoleSSH{
+ Ssh: scopedaccessv1.ScopedRoleSSH_builder{
Logins: []string{"login-b"},
- },
- },
+ }.Build(),
+ }.Build(),
Version: types.V1,
- },
- {
+ }.Build(),
+ scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "role-c",
- },
+ }.Build(),
Scope: "/aa/bb/cc",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/aa/bb/cc"},
- Ssh: &scopedaccessv1.ScopedRoleSSH{
+ Ssh: scopedaccessv1.ScopedRoleSSH_builder{
Logins: []string{"login-c"},
- },
- },
+ }.Build(),
+ }.Build(),
Version: types.V1,
- },
- {
+ }.Build(),
+ scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "role-x",
- },
+ }.Build(),
Scope: "/xx",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/xx"},
- Ssh: &scopedaccessv1.ScopedRoleSSH{
+ Ssh: scopedaccessv1.ScopedRoleSSH_builder{
Logins: []string{"login-x"},
- },
- },
+ }.Build(),
+ }.Build(),
Version: types.V1,
- },
+ }.Build(),
}
// Create the roles.
for _, role := range scopedRoles {
- _, err := adminClient.ScopedAccessServiceClient().CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
+ _, err := adminClient.ScopedAccessServiceClient().CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
Role: role,
- })
+ }.Build())
require.NoError(t, err)
}
@@ -1045,26 +1045,26 @@ func TestBasicSSHScopedLogin(t *testing.T) {
for _, role := range scopedRoles {
assignmentID := uuid.NewString()
assignmentIDs = append(assignmentIDs, assignmentID)
- _, err = adminClient.ScopedAccessServiceClient().CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ _, err = adminClient.ScopedAccessServiceClient().CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: assignmentID,
- },
+ }.Build(),
Scope: role.GetScope(),
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: "alice",
Assignments: []*scopedaccessv1.Assignment{
- {
+ scopedaccessv1.Assignment_builder{
Role: role.GetMetadata().GetName(),
Scope: role.GetScope(),
- },
+ }.Build(),
},
- },
+ }.Build(),
Version: types.V1,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
}
@@ -1095,7 +1095,7 @@ func TestBasicSSHScopedLogin(t *testing.T) {
require.NoError(t, err)
// verify that the expected scope pin is applied to ssh and tls certificates
- expectedPin := &scopesv1.Pin{
+ expectedPin := scopesv1.Pin_builder{
Kind: scopesv1.PinKind_PIN_KIND_USER,
Scope: "/aa/bb",
AssignmentTree: pinning.AssignmentTreeFromMap(map[string]map[string][]string{
@@ -1103,7 +1103,7 @@ func TestBasicSSHScopedLogin(t *testing.T) {
"/aa/bb": {"/aa/bb": {"role-b"}},
"/aa/bb/cc": {"/aa/bb/cc": {"role-c"}},
}),
- }
+ }.Build()
// parse and examine the ssh cert
sshCert, err := sshutils.ParseCertificate(authrsp.Cert)
diff --git a/lib/auth/auth_test.go b/lib/auth/auth_test.go
index 649c7ca4001..2d18055fe2d 100644
--- a/lib/auth/auth_test.go
+++ b/lib/auth/auth_test.go
@@ -46,10 +46,11 @@ import (
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
"google.golang.org/grpc/metadata"
+ "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/gravitational/teleport"
- "github.com/gravitational/teleport/api/client/proto"
+ clientproto "github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/constants"
apidefaults "github.com/gravitational/teleport/api/defaults"
devicepb "github.com/gravitational/teleport/api/gen/proto/go/teleport/devicetrust/v1"
@@ -407,20 +408,20 @@ func TestAuthenticateWebUser_deviceWebToken(t *testing.T) {
switch {
case dwt == nil:
return nil, errors.New("dtw parameter is nil")
- case dwt.WebSessionId == "":
+ case dwt.GetWebSessionId() == "":
return nil, errors.New("dwt.WebSessionId is empty")
- case dwt.BrowserUserAgent == "":
+ case dwt.GetBrowserUserAgent() == "":
return nil, errors.New("dwt.BrowserUserAgent is empty")
- case dwt.BrowserIp != remoteIP:
+ case dwt.GetBrowserIp() != remoteIP:
return nil, errors.New("dwt.BrowserUserAgent is empty")
- case dwt.User != user:
+ case dwt.GetUser() != user:
return nil, errors.New("dwt.User mismatch")
}
- return &devicepb.DeviceWebToken{
+ return devicepb.DeviceWebToken_builder{
Id: "this is an opaque ID",
Token: "this is an opaque token",
- }, nil
+ }.Build(), nil
}
makeTokenError := func(context.Context, *devicepb.DeviceWebToken) (*devicepb.DeviceWebToken, error) {
@@ -438,9 +439,9 @@ func TestAuthenticateWebUser_deviceWebToken(t *testing.T) {
if dwt == nil {
return nil, errors.New("dwt required")
}
- uaToSessionID.Store(dwt.BrowserUserAgent, dwt.GetWebSessionId())
+ uaToSessionID.Store(dwt.GetBrowserUserAgent(), dwt.GetWebSessionId())
- if strings.HasPrefix(dwt.BrowserUserAgent, "fail") {
+ if strings.HasPrefix(dwt.GetBrowserUserAgent(), "fail") {
return makeTokenError(ctx, dwt)
}
@@ -983,9 +984,9 @@ func TestAuthenticateUser_mfaDeviceLocked(t *testing.T) {
require.NoError(t, err, "NewClient")
// OTP devices would work for this test too.
- dev1, err := authtest.RegisterTestDevice(ctx, userClient, "dev1", proto.DeviceType_DEVICE_TYPE_WEBAUTHN, nil /* authenticator */)
+ dev1, err := authtest.RegisterTestDevice(ctx, userClient, "dev1", clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN, nil /* authenticator */)
require.NoError(t, err, "RegisterTestDevice")
- dev2, err := authtest.RegisterTestDevice(ctx, userClient, "dev2", proto.DeviceType_DEVICE_TYPE_WEBAUTHN, dev1 /* authenticator */)
+ dev2, err := authtest.RegisterTestDevice(ctx, userClient, "dev2", clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN, dev1 /* authenticator */)
require.NoError(t, err, "RegisterTestDevice")
// Users initially authenticate via Proxy, as there isn't a userClient before
@@ -994,9 +995,9 @@ func TestAuthenticateUser_mfaDeviceLocked(t *testing.T) {
require.NoError(t, err, "NewClient")
authenticateSSH := func(dev *authtest.Device) (*authclient.CLILoginResponse, error) {
- chal, err := proxyClient.CreateAuthenticateChallenge(ctx, &proto.CreateAuthenticateChallengeRequest{
- Request: &proto.CreateAuthenticateChallengeRequest_UserCredentials{
- UserCredentials: &proto.UserCredentials{
+ chal, err := proxyClient.CreateAuthenticateChallenge(ctx, &clientproto.CreateAuthenticateChallengeRequest{
+ Request: &clientproto.CreateAuthenticateChallengeRequest_UserCredentials{
+ UserCredentials: &clientproto.UserCredentials{
Username: user,
Password: []byte(pass),
},
@@ -1049,9 +1050,9 @@ func TestAuthenticateUser_mfaDeviceLocked(t *testing.T) {
})
t.Run("locked device password change", func(t *testing.T) {
- chal, err := userClient.CreateAuthenticateChallenge(ctx, &proto.CreateAuthenticateChallengeRequest{
- Request: &proto.CreateAuthenticateChallengeRequest_ContextUser{
- ContextUser: &proto.ContextUser{},
+ chal, err := userClient.CreateAuthenticateChallenge(ctx, &clientproto.CreateAuthenticateChallengeRequest{
+ Request: &clientproto.CreateAuthenticateChallengeRequest_ContextUser{
+ ContextUser: &clientproto.ContextUser{},
},
ChallengeExtensions: &mfav1.ChallengeExtensions{
Scope: mfav1.ChallengeScope_CHALLENGE_SCOPE_CHANGE_PASSWORD,
@@ -1064,7 +1065,7 @@ func TestAuthenticateUser_mfaDeviceLocked(t *testing.T) {
require.NoError(t, err, "SolveAuthn")
assert.ErrorContains(t,
- userClient.ChangePassword(ctx, &proto.ChangePasswordRequest{
+ userClient.ChangePassword(ctx, &clientproto.ChangePasswordRequest{
User: user,
OldPassword: []byte(pass),
NewPassword: []byte("evenmoresecret!!1!ONE"),
@@ -1223,14 +1224,14 @@ func TestLocalControlStream(t *testing.T) {
stream := s.a.MakeLocalInventoryControlStream()
defer stream.Close()
- err := stream.Send(ctx, &proto.UpstreamInventoryHello{
+ err := stream.Send(ctx, clientproto.UpstreamInventoryHello_builder{
ServerID: serverID,
- })
+ }.Build())
require.NoError(t, err)
select {
case msg := <-stream.Recv():
- _, ok := msg.(*proto.DownstreamInventoryHello)
+ _, ok := msg.(*clientproto.DownstreamInventoryHello)
require.True(t, ok)
case <-stream.Done():
t.Fatalf("stream closed unexpectedly: %v", stream.Error())
@@ -1246,13 +1247,14 @@ func TestLocalControlStream(t *testing.T) {
}, time.Second*5, time.Millisecond*200)
// try performing a normal operation against the control stream to double-check that it is healthy
- go s.a.PingInventory(ctx, proto.InventoryPingRequest{
+ go s.a.PingInventory(ctx, clientproto.InventoryPingRequest{
ServerID: serverID,
})
select {
case msg := <-stream.Recv():
- require.IsType(t, *new(*proto.DownstreamInventoryPing), msg)
+ var want *clientproto.DownstreamInventoryPing
+ require.IsType(t, want, msg)
case <-stream.Done():
t.Fatalf("stream closed unexpectedly: %v", stream.Error())
case <-time.After(time.Second * 10):
@@ -2927,11 +2929,11 @@ func TestGenerateOpenSSHCert(t *testing.T) {
priv, err := cryptosuites.GeneratePrivateKeyWithAlgorithm(cryptosuites.Ed25519)
require.NoError(t, err)
- reply, err := p.a.GenerateOpenSSHCert(ctx, &proto.OpenSSHCertRequest{
+ reply, err := p.a.GenerateOpenSSHCert(ctx, &clientproto.OpenSSHCertRequest{
User: user,
Roles: []*types.RoleV6{role},
PublicKey: priv.MarshalSSHPublicKey(),
- TTL: proto.Duration(time.Hour),
+ TTL: clientproto.Duration(time.Hour),
Cluster: p.clusterName.GetClusterName(),
})
require.NoError(t, err)
@@ -2982,11 +2984,11 @@ func TestGenerateOpenSSHCert(t *testing.T) {
priv, err := cryptosuites.GeneratePrivateKeyWithAlgorithm(cryptosuites.Ed25519)
require.NoError(t, err)
- reply, err := p.a.GenerateOpenSSHCert(ctx, &proto.OpenSSHCertRequest{
+ reply, err := p.a.GenerateOpenSSHCert(ctx, &clientproto.OpenSSHCertRequest{
User: user,
Roles: []*types.RoleV6{role},
PublicKey: priv.MarshalSSHPublicKey(),
- TTL: proto.Duration(time.Hour),
+ TTL: clientproto.Duration(time.Hour),
Cluster: p.clusterName.GetClusterName(),
})
require.NoError(t, err)
@@ -3023,49 +3025,49 @@ func TestGenerateOpenSSHCertScoped(t *testing.T) {
// Create a scoped role at /staging that grants "scoped-login".
scopedService := local.NewScopedAccessService(p.bk)
- _, err = scopedService.CreateScopedRole(ctx, &scopedaccessv1pb.CreateScopedRoleRequest{
- Role: &scopedaccessv1pb.ScopedRole{
+ _, err = scopedService.CreateScopedRole(ctx, scopedaccessv1pb.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1pb.ScopedRole_builder{
Kind: "scoped_role",
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "staging-ssh",
- },
+ }.Build(),
Scope: "/staging",
- Spec: &scopedaccessv1pb.ScopedRoleSpec{
+ Spec: scopedaccessv1pb.ScopedRoleSpec_builder{
AssignableScopes: []string{"/staging"},
- Ssh: &scopedaccessv1pb.ScopedRoleSSH{
+ Ssh: scopedaccessv1pb.ScopedRoleSSH_builder{
Logins: []string{"scoped-login"},
Labels: []*labelv1.Label{
- {Name: "*", Values: []string{"*"}},
+ labelv1.Label_builder{Name: "*", Values: []string{"*"}}.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
Version: types.V1,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- _, err = scopedService.CreateScopedRoleAssignment(ctx, &scopedaccessv1pb.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1pb.ScopedRoleAssignment{
+ _, err = scopedService.CreateScopedRoleAssignment(ctx, scopedaccessv1pb.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1pb.ScopedRoleAssignment_builder{
Kind: "scoped_role_assignment",
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
Scope: "/staging",
SubKind: "dynamic",
- Spec: &scopedaccessv1pb.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1pb.ScopedRoleAssignmentSpec_builder{
User: "scoped-user",
Assignments: []*scopedaccessv1pb.Assignment{
- {
+ scopedaccessv1pb.Assignment_builder{
Role: "staging-ssh",
Scope: "/staging",
- },
+ }.Build(),
},
- },
+ }.Build(),
Version: types.V1,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- pin := &scopesv1pb.Pin{Kind: scopesv1pb.PinKind_PIN_KIND_USER, Scope: "/staging"}
+ pin := scopesv1pb.Pin_builder{Kind: scopesv1pb.PinKind_PIN_KIND_USER, Scope: "/staging"}.Build()
// Wait for scoped access cache to see the assignment.
require.EventuallyWithT(t, func(ct *assert.CollectT) {
@@ -3075,11 +3077,11 @@ func TestGenerateOpenSSHCertScoped(t *testing.T) {
}, 15*time.Second, 100*time.Millisecond)
t.Run("valid login in principals", func(t *testing.T) {
- reply, err := p.a.GenerateOpenSSHCert(ctx, &proto.OpenSSHCertRequest{
+ reply, err := p.a.GenerateOpenSSHCert(ctx, &clientproto.OpenSSHCertRequest{
User: user,
Roles: []*types.RoleV6{role},
PublicKey: priv.MarshalSSHPublicKey(),
- TTL: proto.Duration(time.Hour),
+ TTL: clientproto.Duration(time.Hour),
Cluster: p.clusterName.GetClusterName(),
ScopePin: pin,
Login: "scoped-login",
@@ -3092,11 +3094,11 @@ func TestGenerateOpenSSHCertScoped(t *testing.T) {
})
t.Run("errors when login is not provided", func(t *testing.T) {
- _, err := p.a.GenerateOpenSSHCert(ctx, &proto.OpenSSHCertRequest{
+ _, err := p.a.GenerateOpenSSHCert(ctx, &clientproto.OpenSSHCertRequest{
User: user,
Roles: []*types.RoleV6{role},
PublicKey: priv.MarshalSSHPublicKey(),
- TTL: proto.Duration(time.Hour),
+ TTL: clientproto.Duration(time.Hour),
Cluster: p.clusterName.GetClusterName(),
ScopePin: pin,
Login: "",
@@ -3639,42 +3641,42 @@ func TestDeleteMFADeviceSync(t *testing.T) {
require.NoError(t, err)
// webDev1 is used as the authenticator for various checks.
- webDev1, err := authtest.RegisterTestDevice(ctx, userClient, "web1", proto.DeviceType_DEVICE_TYPE_WEBAUTHN, nil /* authenticator */)
+ webDev1, err := authtest.RegisterTestDevice(ctx, userClient, "web1", clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN, nil /* authenticator */)
require.NoError(t, err, "RegisterTestDevice(web1)")
// Insert devices for deletion.
deviceOpts := []authtest.TestDeviceOpt{authtest.WithTestDeviceClock(testServer.Clock())}
- registerDevice := func(t *testing.T, deviceName string, deviceType proto.DeviceType) *authtest.Device {
+ registerDevice := func(t *testing.T, deviceName string, deviceType clientproto.DeviceType) *authtest.Device {
t.Helper()
testDev, err := authtest.RegisterTestDevice(
ctx, userClient, deviceName, deviceType, webDev1 /* authenticator */, deviceOpts...)
require.NoError(t, err, "RegisterTestDevice(%v)", deviceName)
return testDev
}
- deleteWeb1 := registerDevice(t, "delete-web1", proto.DeviceType_DEVICE_TYPE_WEBAUTHN)
- deleteWeb2 := registerDevice(t, "delete-web2", proto.DeviceType_DEVICE_TYPE_WEBAUTHN)
- deleteTOTP1 := registerDevice(t, "delete-totp1", proto.DeviceType_DEVICE_TYPE_TOTP)
- deleteTOTP2 := registerDevice(t, "delete-totp2", proto.DeviceType_DEVICE_TYPE_TOTP)
+ deleteWeb1 := registerDevice(t, "delete-web1", clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN)
+ deleteWeb2 := registerDevice(t, "delete-web2", clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN)
+ deleteTOTP1 := registerDevice(t, "delete-totp1", clientproto.DeviceType_DEVICE_TYPE_TOTP)
+ deleteTOTP2 := registerDevice(t, "delete-totp2", clientproto.DeviceType_DEVICE_TYPE_TOTP)
- deleteReqUsingToken := func(tokenReq authclient.CreateUserTokenRequest) func(t *testing.T) *proto.DeleteMFADeviceSyncRequest {
- return func(t *testing.T) *proto.DeleteMFADeviceSyncRequest {
+ deleteReqUsingToken := func(tokenReq authclient.CreateUserTokenRequest) func(t *testing.T) *clientproto.DeleteMFADeviceSyncRequest {
+ return func(t *testing.T) *clientproto.DeleteMFADeviceSyncRequest {
token, err := authServer.NewUserToken(ctx, tokenReq)
require.NoError(t, err, "newUserToken")
_, err = authServer.CreateUserToken(ctx, token)
require.NoError(t, err, "CreateUserToken")
- return &proto.DeleteMFADeviceSyncRequest{
+ return &clientproto.DeleteMFADeviceSyncRequest{
TokenID: token.GetName(),
}
}
}
- deleteReqUsingChallenge := func(authenticator *authtest.Device) func(t *testing.T) *proto.DeleteMFADeviceSyncRequest {
- return func(t *testing.T) *proto.DeleteMFADeviceSyncRequest {
- authnChal, err := userClient.CreateAuthenticateChallenge(ctx, &proto.CreateAuthenticateChallengeRequest{
- Request: &proto.CreateAuthenticateChallengeRequest_ContextUser{
- ContextUser: &proto.ContextUser{},
+ deleteReqUsingChallenge := func(authenticator *authtest.Device) func(t *testing.T) *clientproto.DeleteMFADeviceSyncRequest {
+ return func(t *testing.T) *clientproto.DeleteMFADeviceSyncRequest {
+ authnChal, err := userClient.CreateAuthenticateChallenge(ctx, &clientproto.CreateAuthenticateChallengeRequest{
+ Request: &clientproto.CreateAuthenticateChallengeRequest_ContextUser{
+ ContextUser: &clientproto.ContextUser{},
},
ChallengeExtensions: &mfav1.ChallengeExtensions{
Scope: mfav1.ChallengeScope_CHALLENGE_SCOPE_MANAGE_DEVICES,
@@ -3685,7 +3687,7 @@ func TestDeleteMFADeviceSync(t *testing.T) {
authnSolved, err := authenticator.SolveAuthn(authnChal)
require.NoError(t, err, "SolveAuthn")
- return &proto.DeleteMFADeviceSyncRequest{
+ return &clientproto.DeleteMFADeviceSyncRequest{
ExistingMFAResponse: authnSolved,
}
}
@@ -3693,7 +3695,7 @@ func TestDeleteMFADeviceSync(t *testing.T) {
tests := []struct {
name string
- createDeleteReq func(t *testing.T) *proto.DeleteMFADeviceSyncRequest
+ createDeleteReq func(t *testing.T) *clientproto.DeleteMFADeviceSyncRequest
deviceToDelete string
}{
{
@@ -3787,11 +3789,11 @@ func TestDeleteMFADeviceSync_WithErrors(t *testing.T) {
// Insert a device.
const devName = "otp"
_, err = authtest.RegisterTestDevice(
- ctx, userClient, devName, proto.DeviceType_DEVICE_TYPE_TOTP, nil /* authenticator */, authtest.WithTestDeviceClock(clock))
+ ctx, userClient, devName, clientproto.DeviceType_DEVICE_TYPE_TOTP, nil /* authenticator */, authtest.WithTestDeviceClock(clock))
require.NoError(t, err)
- createReq := func(name string) *proto.DeleteMFADeviceSyncRequest {
- return &proto.DeleteMFADeviceSyncRequest{
+ createReq := func(name string) *clientproto.DeleteMFADeviceSyncRequest {
+ return &clientproto.DeleteMFADeviceSyncRequest{
DeviceName: name,
}
}
@@ -3799,13 +3801,13 @@ func TestDeleteMFADeviceSync_WithErrors(t *testing.T) {
tests := []struct {
name string
tokenRequest *authclient.CreateUserTokenRequest
- deleteReq *proto.DeleteMFADeviceSyncRequest
+ deleteReq *clientproto.DeleteMFADeviceSyncRequest
wantErr string
assertErr func(error) bool
}{
{
name: "token not found",
- deleteReq: &proto.DeleteMFADeviceSyncRequest{
+ deleteReq: &clientproto.DeleteMFADeviceSyncRequest{
TokenID: "unknown-token-id",
DeviceName: devName,
},
@@ -3830,7 +3832,7 @@ func TestDeleteMFADeviceSync_WithErrors(t *testing.T) {
TTL: 5 * time.Minute,
Type: authclient.UserTokenTypeRecoveryApproved,
},
- deleteReq: &proto.DeleteMFADeviceSyncRequest{
+ deleteReq: &clientproto.DeleteMFADeviceSyncRequest{
DeviceName: "does-not-exist",
},
wantErr: "does not exist",
@@ -3844,11 +3846,11 @@ func TestDeleteMFADeviceSync_WithErrors(t *testing.T) {
},
{
name: "invalid challenge",
- deleteReq: &proto.DeleteMFADeviceSyncRequest{
+ deleteReq: &clientproto.DeleteMFADeviceSyncRequest{
DeviceName: devName,
- ExistingMFAResponse: &proto.MFAAuthenticateResponse{
- Response: &proto.MFAAuthenticateResponse_TOTP{
- TOTP: &proto.TOTPResponse{
+ ExistingMFAResponse: &clientproto.MFAAuthenticateResponse{
+ Response: &clientproto.MFAAuthenticateResponse_TOTP{
+ TOTP: &clientproto.TOTPResponse{
Code: "not an OTP code",
},
},
@@ -3917,9 +3919,9 @@ func TestDeleteMFADeviceSync_lastDevice(t *testing.T) {
deleteDevice := func(userClient *authclient.Client, testDev *authtest.Device) error {
// Issue and solve authn challenge.
- authnChal, err := userClient.CreateAuthenticateChallenge(ctx, &proto.CreateAuthenticateChallengeRequest{
- Request: &proto.CreateAuthenticateChallengeRequest_ContextUser{
- ContextUser: &proto.ContextUser{},
+ authnChal, err := userClient.CreateAuthenticateChallenge(ctx, &clientproto.CreateAuthenticateChallengeRequest{
+ Request: &clientproto.CreateAuthenticateChallengeRequest_ContextUser{
+ ContextUser: &clientproto.ContextUser{},
},
ChallengeExtensions: &mfav1.ChallengeExtensions{
Scope: mfav1.ChallengeScope_CHALLENGE_SCOPE_MANAGE_DEVICES,
@@ -3933,7 +3935,7 @@ func TestDeleteMFADeviceSync_lastDevice(t *testing.T) {
return err
}
- return userClient.DeleteMFADeviceSync(ctx, &proto.DeleteMFADeviceSyncRequest{
+ return userClient.DeleteMFADeviceSync(ctx, &clientproto.DeleteMFADeviceSyncRequest{
DeviceName: testDev.MFA.GetName(),
ExistingMFAResponse: authnSolved,
})
@@ -3951,7 +3953,7 @@ func TestDeleteMFADeviceSync_lastDevice(t *testing.T) {
deleteDevice(userClient, deviceToDelete),
wantErr)
- devicesResp, err := userClient.GetMFADevices(ctx, &proto.GetMFADevicesRequest{})
+ devicesResp, err := userClient.GetMFADevices(ctx, &clientproto.GetMFADevicesRequest{})
require.NoError(t, err, "GetMFADevices")
devName := deviceToDelete.MFA.GetName()
for _, dev := range devicesResp.Devices {
@@ -3978,7 +3980,7 @@ func TestDeleteMFADeviceSync_lastDevice(t *testing.T) {
t.Run("second factor on, otp device", makeTest(constants.SecondFactorOn, totpDev))
// Same as above, but now delete the last Webauthn device.
- webDev, err = authtest.RegisterTestDevice(ctx, userClient, "web1", proto.DeviceType_DEVICE_TYPE_WEBAUTHN, totpDev /* authenticator */)
+ webDev, err = authtest.RegisterTestDevice(ctx, userClient, "web1", clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN, totpDev /* authenticator */)
require.NoError(t, err, "RegisterTestDevice")
require.NoError(t,
deleteDevice(userClient, totpDev),
@@ -4017,14 +4019,14 @@ func TestAddMFADeviceSync(t *testing.T) {
solveChallengeWithToken := func(
t *testing.T,
tokenType string,
- deviceType proto.DeviceType,
- deviceUsage proto.DeviceUsage,
- ) (token string, testDev *authtest.Device, registerSolved *proto.MFARegisterResponse) {
+ deviceType clientproto.DeviceType,
+ deviceUsage clientproto.DeviceUsage,
+ ) (token string, testDev *authtest.Device, registerSolved *clientproto.MFARegisterResponse) {
privilegeToken, err := auth.CreatePrivilegeToken(ctx, authServer, u.username, tokenType)
require.NoError(t, err, "createPrivilegeToken")
token = privilegeToken.GetName()
- registerChal, err := authServer.CreateRegisterChallenge(ctx, &proto.CreateRegisterChallengeRequest{
+ registerChal, err := authServer.CreateRegisterChallenge(ctx, &clientproto.CreateRegisterChallengeRequest{
TokenID: token,
DeviceType: deviceType,
DeviceUsage: deviceUsage,
@@ -4038,13 +4040,13 @@ func TestAddMFADeviceSync(t *testing.T) {
solveChallengeWithUser := func(
t *testing.T,
- deviceType proto.DeviceType,
- deviceUsage proto.DeviceUsage,
- ) (*authtest.Device, *proto.MFARegisterResponse) {
+ deviceType clientproto.DeviceType,
+ deviceUsage clientproto.DeviceUsage,
+ ) (*authtest.Device, *clientproto.MFARegisterResponse) {
// Create and solve a registration challenge.
- authChal, err := userClient.CreateAuthenticateChallenge(ctx, &proto.CreateAuthenticateChallengeRequest{
- Request: &proto.CreateAuthenticateChallengeRequest_ContextUser{
- ContextUser: &proto.ContextUser{},
+ authChal, err := userClient.CreateAuthenticateChallenge(ctx, &clientproto.CreateAuthenticateChallengeRequest{
+ Request: &clientproto.CreateAuthenticateChallengeRequest_ContextUser{
+ ContextUser: &clientproto.ContextUser{},
},
ChallengeExtensions: &mfav1.ChallengeExtensions{
Scope: mfav1.ChallengeScope_CHALLENGE_SCOPE_MANAGE_DEVICES,
@@ -4055,7 +4057,7 @@ func TestAddMFADeviceSync(t *testing.T) {
authSolved, err := u.webDev.SolveAuthn(authChal)
require.NoError(t, err, "SolveAuthn")
- registerChal, err := userClient.CreateRegisterChallenge(ctx, &proto.CreateRegisterChallengeRequest{
+ registerChal, err := userClient.CreateRegisterChallenge(ctx, &clientproto.CreateRegisterChallengeRequest{
ExistingMFAResponse: authSolved,
DeviceType: deviceType,
DeviceUsage: deviceUsage,
@@ -4074,12 +4076,12 @@ func TestAddMFADeviceSync(t *testing.T) {
name string
deviceName string
wantErr bool
- getReq func(t *testing.T, deviceName string) *proto.AddMFADeviceSyncRequest
+ getReq func(t *testing.T, deviceName string) *clientproto.AddMFADeviceSyncRequest
}{
{
name: "invalid token type",
wantErr: true,
- getReq: func(t *testing.T, deviceName string) *proto.AddMFADeviceSyncRequest {
+ getReq: func(t *testing.T, deviceName string) *clientproto.AddMFADeviceSyncRequest {
// Obtain a non privilege token.
token, err := authServer.NewUserToken(ctx, authclient.CreateUserTokenRequest{
Name: u.username,
@@ -4090,7 +4092,7 @@ func TestAddMFADeviceSync(t *testing.T) {
_, err = authServer.CreateUserToken(ctx, token)
require.NoError(t, err)
- return &proto.AddMFADeviceSyncRequest{
+ return &clientproto.AddMFADeviceSyncRequest{
TokenID: token.GetName(),
NewDeviceName: deviceName,
}
@@ -4099,11 +4101,11 @@ func TestAddMFADeviceSync(t *testing.T) {
{
name: "TOTP device with privilege token",
deviceName: "new-totp",
- getReq: func(t *testing.T, deviceName string) *proto.AddMFADeviceSyncRequest {
+ getReq: func(t *testing.T, deviceName string) *clientproto.AddMFADeviceSyncRequest {
token, _, registerSolved := solveChallengeWithToken(
- t, authclient.UserTokenTypePrivilege, proto.DeviceType_DEVICE_TYPE_TOTP, proto.DeviceUsage_DEVICE_USAGE_MFA)
+ t, authclient.UserTokenTypePrivilege, clientproto.DeviceType_DEVICE_TYPE_TOTP, clientproto.DeviceUsage_DEVICE_USAGE_MFA)
- return &proto.AddMFADeviceSyncRequest{
+ return &clientproto.AddMFADeviceSyncRequest{
TokenID: token,
NewDeviceName: deviceName,
NewMFAResponse: registerSolved,
@@ -4113,11 +4115,11 @@ func TestAddMFADeviceSync(t *testing.T) {
{
name: "Webauthn device with privilege exception token",
deviceName: "new-webauthn",
- getReq: func(t *testing.T, deviceName string) *proto.AddMFADeviceSyncRequest {
+ getReq: func(t *testing.T, deviceName string) *clientproto.AddMFADeviceSyncRequest {
token, _, registerSolved := solveChallengeWithToken(
- t, authclient.UserTokenTypePrivilegeException, proto.DeviceType_DEVICE_TYPE_WEBAUTHN, proto.DeviceUsage_DEVICE_USAGE_MFA)
+ t, authclient.UserTokenTypePrivilegeException, clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN, clientproto.DeviceUsage_DEVICE_USAGE_MFA)
- return &proto.AddMFADeviceSyncRequest{
+ return &clientproto.AddMFADeviceSyncRequest{
TokenID: token,
NewDeviceName: deviceName,
NewMFAResponse: registerSolved,
@@ -4128,11 +4130,11 @@ func TestAddMFADeviceSync(t *testing.T) {
name: "invalid device name length",
deviceName: strings.Repeat("A", auth.MFADeviceNameMaxLen+1),
wantErr: true,
- getReq: func(t *testing.T, deviceName string) *proto.AddMFADeviceSyncRequest {
+ getReq: func(t *testing.T, deviceName string) *clientproto.AddMFADeviceSyncRequest {
token, _, registerSolved := solveChallengeWithToken(
- t, authclient.UserTokenTypePrivilegeException, proto.DeviceType_DEVICE_TYPE_WEBAUTHN, proto.DeviceUsage_DEVICE_USAGE_MFA)
+ t, authclient.UserTokenTypePrivilegeException, clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN, clientproto.DeviceUsage_DEVICE_USAGE_MFA)
- return &proto.AddMFADeviceSyncRequest{
+ return &clientproto.AddMFADeviceSyncRequest{
TokenID: token,
NewDeviceName: deviceName,
NewMFAResponse: registerSolved,
@@ -4142,34 +4144,34 @@ func TestAddMFADeviceSync(t *testing.T) {
{
name: "WebAuthn with context user",
deviceName: "context-webauthn1",
- getReq: func(t *testing.T, deviceName string) *proto.AddMFADeviceSyncRequest {
+ getReq: func(t *testing.T, deviceName string) *clientproto.AddMFADeviceSyncRequest {
_, registerSolved := solveChallengeWithUser(
t,
- proto.DeviceType_DEVICE_TYPE_WEBAUTHN,
- proto.DeviceUsage_DEVICE_USAGE_MFA)
+ clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN,
+ clientproto.DeviceUsage_DEVICE_USAGE_MFA)
- return &proto.AddMFADeviceSyncRequest{
- ContextUser: &proto.ContextUser{},
+ return &clientproto.AddMFADeviceSyncRequest{
+ ContextUser: &clientproto.ContextUser{},
NewDeviceName: deviceName,
NewMFAResponse: registerSolved,
- DeviceUsage: proto.DeviceUsage_DEVICE_USAGE_MFA,
+ DeviceUsage: clientproto.DeviceUsage_DEVICE_USAGE_MFA,
}
},
},
{
name: "TOTP with context user",
deviceName: "context-totp1",
- getReq: func(t *testing.T, deviceName string) *proto.AddMFADeviceSyncRequest {
+ getReq: func(t *testing.T, deviceName string) *clientproto.AddMFADeviceSyncRequest {
_, registerSolved := solveChallengeWithUser(
t,
- proto.DeviceType_DEVICE_TYPE_TOTP,
- proto.DeviceUsage_DEVICE_USAGE_MFA)
+ clientproto.DeviceType_DEVICE_TYPE_TOTP,
+ clientproto.DeviceUsage_DEVICE_USAGE_MFA)
- return &proto.AddMFADeviceSyncRequest{
- ContextUser: &proto.ContextUser{},
+ return &clientproto.AddMFADeviceSyncRequest{
+ ContextUser: &clientproto.ContextUser{},
NewDeviceName: deviceName,
NewMFAResponse: registerSolved,
- DeviceUsage: proto.DeviceUsage_DEVICE_USAGE_MFA,
+ DeviceUsage: clientproto.DeviceUsage_DEVICE_USAGE_MFA,
}
},
},
@@ -4194,7 +4196,7 @@ func TestAddMFADeviceSync(t *testing.T) {
assert.Contains(t, addEvt.ConnectionMetadata.RemoteAddr, "127.0.0.1", "client remote addr must be localhost")
// Check it's been added.
- res, err := userClient.GetMFADevices(ctx, &proto.GetMFADevicesRequest{})
+ res, err := userClient.GetMFADevices(ctx, &clientproto.GetMFADevicesRequest{})
require.NoError(t, err)
found := false
@@ -4232,9 +4234,9 @@ func TestGetMFADevices_WithToken(t *testing.T) {
clt, err := srv.NewClient(authtest.TestUser(username))
require.NoError(t, err)
- webDev, err := authtest.RegisterTestDevice(ctx, clt, "web", proto.DeviceType_DEVICE_TYPE_WEBAUTHN, nil /* authenticator */)
+ webDev, err := authtest.RegisterTestDevice(ctx, clt, "web", clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN, nil /* authenticator */)
require.NoError(t, err)
- totpDev, err := authtest.RegisterTestDevice(ctx, clt, "otp", proto.DeviceType_DEVICE_TYPE_TOTP, webDev, authtest.WithTestDeviceClock(srv.Clock()))
+ totpDev, err := authtest.RegisterTestDevice(ctx, clt, "otp", clientproto.DeviceType_DEVICE_TYPE_TOTP, webDev, authtest.WithTestDeviceClock(srv.Clock()))
require.NoError(t, err)
tests := []struct {
@@ -4278,7 +4280,7 @@ func TestGetMFADevices_WithToken(t *testing.T) {
tokenID = token.GetName()
}
- res, err := srv.Auth().GetMFADevices(ctx, &proto.GetMFADevicesRequest{
+ res, err := srv.Auth().GetMFADevices(ctx, &clientproto.GetMFADevicesRequest{
TokenID: tokenID,
})
@@ -4315,12 +4317,12 @@ func TestGetMFADevices_WithAuth(t *testing.T) {
clt, err := srv.NewClient(authtest.TestUser(username))
require.NoError(t, err)
- webDev, err := authtest.RegisterTestDevice(ctx, clt, "web", proto.DeviceType_DEVICE_TYPE_WEBAUTHN, nil /* authenticator */)
+ webDev, err := authtest.RegisterTestDevice(ctx, clt, "web", clientproto.DeviceType_DEVICE_TYPE_WEBAUTHN, nil /* authenticator */)
require.NoError(t, err)
- totpDev, err := authtest.RegisterTestDevice(ctx, clt, "otp", proto.DeviceType_DEVICE_TYPE_TOTP, webDev, authtest.WithTestDeviceClock(srv.Clock()))
+ totpDev, err := authtest.RegisterTestDevice(ctx, clt, "otp", clientproto.DeviceType_DEVICE_TYPE_TOTP, webDev, authtest.WithTestDeviceClock(srv.Clock()))
require.NoError(t, err)
- res, err := clt.GetMFADevices(ctx, &proto.GetMFADevicesRequest{})
+ res, err := clt.GetMFADevices(ctx, &clientproto.GetMFADevicesRequest{})
require.NoError(t, err)
compareDevices(t, true /* ignoreUpdateAndCounter */, res.GetDevices(), webDev.MFA, totpDev.MFA)
}
@@ -4390,7 +4392,7 @@ type mockCache struct {
resourcesError error
}
-func (m mockCache) ListResources(ctx context.Context, req proto.ListResourcesRequest) (*types.ListResourcesResponse, error) {
+func (m mockCache) ListResources(ctx context.Context, req clientproto.ListResourcesRequest) (*types.ListResourcesResponse, error) {
if m.resourcesError != nil {
return nil, m.resourcesError
}
@@ -4467,7 +4469,7 @@ func TestFilterResources(t *testing.T) {
srv := &auth.Server{Cache: tt.cache}
- err := srv.IterateResources(ctx, proto.ListResourcesRequest{
+ err := srv.IterateResources(ctx, clientproto.ListResourcesRequest{
ResourceType: types.KindNode,
Namespace: apidefaults.Namespace,
Limit: tt.limit,
@@ -5044,28 +5046,28 @@ func TestCleanupNotifications(t *testing.T) {
// Create notification states for all notifications
for _, notif := range createdNotifications {
if !notif.isGlobal {
- _, err := srv.Auth().UpsertUserNotificationState(ctx, notif.username, ¬ificationsv1.UserNotificationState{
- Spec: ¬ificationsv1.UserNotificationStateSpec{
+ _, err := srv.Auth().UpsertUserNotificationState(ctx, notif.username, notificationsv1.UserNotificationState_builder{
+ Spec: notificationsv1.UserNotificationStateSpec_builder{
Username: notif.username,
NotificationId: notif.id,
- },
- Status: ¬ificationsv1.UserNotificationStateStatus{
+ }.Build(),
+ Status: notificationsv1.UserNotificationStateStatus_builder{
NotificationState: notificationsv1.NotificationState_NOTIFICATION_STATE_CLICKED,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
} else {
// For global notifications, create a state for both users
for _, username := range users {
- _, err := srv.Auth().UpsertUserNotificationState(ctx, username, ¬ificationsv1.UserNotificationState{
- Spec: ¬ificationsv1.UserNotificationStateSpec{
+ _, err := srv.Auth().UpsertUserNotificationState(ctx, username, notificationsv1.UserNotificationState_builder{
+ Spec: notificationsv1.UserNotificationStateSpec_builder{
Username: username,
NotificationId: notif.id,
- },
- Status: ¬ificationsv1.UserNotificationStateStatus{
+ }.Build(),
+ Status: notificationsv1.UserNotificationStateStatus_builder{
NotificationState: notificationsv1.NotificationState_NOTIFICATION_STATE_CLICKED,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
}
}
@@ -5200,7 +5202,7 @@ func testCreateAccessListReminderNotifications(t *testing.T) {
synctest.Wait()
resp, err := client.ListNotifications(ctx, ¬ificationsv1.ListNotificationsRequest{})
require.NoError(t, err)
- assert.ElementsMatch(t, expectedSubKinds, slices.Map(resp.Notifications, reminderNotificationSubKind))
+ assert.ElementsMatch(t, expectedSubKinds, slices.Map(resp.GetNotifications(), reminderNotificationSubKind))
// Run CreateAccessListReminderNotifications() again to verify no duplicates are created
authServer.CreateAccessListReminderNotifications(ctx, auth.WithCreateNotificationInterval(time.Nanosecond))
@@ -5209,7 +5211,7 @@ func testCreateAccessListReminderNotifications(t *testing.T) {
synctest.Wait()
resp, err = client.ListNotifications(ctx, ¬ificationsv1.ListNotificationsRequest{})
require.NoError(t, err)
- assert.ElementsMatch(t, expectedSubKinds, slices.Map(resp.Notifications, reminderNotificationSubKind),
+ assert.ElementsMatch(t, expectedSubKinds, slices.Map(resp.GetNotifications(), reminderNotificationSubKind),
"notifications should not have changed after second reconciliation")
}
@@ -5218,17 +5220,17 @@ func TestPing(t *testing.T) {
type fixture struct {
name string
scopesFeatures scopes.Features
- scopesStatus proto.ScopesStatus
+ scopesStatus clientproto.ScopesStatus
}
fixtures := []fixture{
{
name: "scopes disabled",
- scopesStatus: proto.ScopesStatus_SCOPES_STATUS_DISABLED,
+ scopesStatus: clientproto.ScopesStatus_SCOPES_STATUS_DISABLED,
},
{
name: "scopes enabled",
scopesFeatures: scopes.Features{Enabled: true},
- scopesStatus: proto.ScopesStatus_SCOPES_STATUS_ENABLED,
+ scopesStatus: clientproto.ScopesStatus_SCOPES_STATUS_ENABLED,
},
}
@@ -5461,15 +5463,15 @@ func newUserNotificationWithExpiry(t *testing.T, username string, title string,
notification := notificationsv1.Notification{
SubKind: "test-subkind",
- Spec: ¬ificationsv1.NotificationSpec{
+ Spec: notificationsv1.NotificationSpec_builder{
Username: username,
- },
- Metadata: &headerv1.Metadata{
+ }.Build(),
+ Metadata: headerv1.Metadata_builder{
Expires: expires,
Labels: map[string]string{
types.NotificationTitleLabel: title,
},
- },
+ }.Build(),
}
return ¬ification
@@ -5479,21 +5481,19 @@ func newGlobalNotificationWithExpiry(t *testing.T, title string, expires *timest
t.Helper()
notification := notificationsv1.GlobalNotification{
- Spec: ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_All{
- All: true,
- },
- Notification: ¬ificationsv1.Notification{
+ Spec: notificationsv1.GlobalNotificationSpec_builder{
+ All: proto.Bool(true),
+ Notification: notificationsv1.Notification_builder{
SubKind: "test-subkind",
Spec: ¬ificationsv1.NotificationSpec{},
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Expires: expires,
Labels: map[string]string{
types.NotificationTitleLabel: title,
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
}
return ¬ification
diff --git a/lib/auth/auth_with_roles.go b/lib/auth/auth_with_roles.go
index 8b73c94c9a0..211aa0db7f2 100644
--- a/lib/auth/auth_with_roles.go
+++ b/lib/auth/auth_with_roles.go
@@ -835,16 +835,16 @@ func (a *ServerWithRoles) RegisterInventoryControlStream(ics client.UpstreamInve
filteredServices = append(filteredServices, service)
}
- hello.Services = filteredServices
+ hello.SetServices(filteredServices)
// If the hello message's scope is non-empty, we can verify that it matches the authenticated
// scope in the identity. Otherwise, in order to support agents unaware of scopes, we fall back
// to the authenticated identity's scope.
agentScope := a.context.Identity.GetIdentity().GetAgentScope()
- if hello.Scope != "" && hello.Scope != agentScope {
- return nil, trace.AccessDenied("provided scope %q does not match agent identity %q", hello.Scope, agentScope)
+ if hello.GetScope() != "" && hello.GetScope() != agentScope {
+ return nil, trace.AccessDenied("provided scope %q does not match agent identity %q", hello.GetScope(), agentScope)
}
- hello.Scope = agentScope
+ hello.SetScope(agentScope)
labelHash := a.context.Identity.GetIdentity().ImmutableLabelHash
if labels := hello.GetImmutableLabels(); labels != nil || labelHash != "" {
if !joining.VerifyImmutableLabelsHash(labels, labelHash) {
@@ -859,7 +859,7 @@ func (a *ServerWithRoles) GetInventoryStatus(ctx context.Context, req *proto.Inv
return nil, trace.Wrap(err)
}
- if req.Connected {
+ if req.GetConnected() {
if !a.hasBuiltinRole(types.RoleAdmin) {
return nil, trace.AccessDenied("requires local tctl, try using 'tctl inventory ls' instead")
}
@@ -1572,10 +1572,10 @@ func (a *ServerWithRoles) ListUnifiedResources(ctx context.Context, req *proto.L
if err != nil {
return nil, trace.Wrap(err, "getting user preferences")
}
- if len(prefs.ClusterPreferences.PinnedResources.ResourceIds) == 0 {
+ if len(prefs.GetClusterPreferences().GetPinnedResources().GetResourceIds()) == 0 {
return &proto.ListUnifiedResourcesResponse{}, nil
}
- unifiedResources, err = a.authServer.UnifiedResourceCache.GetUnifiedResourcesByIDs(ctx, prefs.ClusterPreferences.PinnedResources.GetResourceIds(), func(resource types.ResourceWithLabels) (bool, error) {
+ unifiedResources, err = a.authServer.UnifiedResourceCache.GetUnifiedResourcesByIDs(ctx, prefs.GetClusterPreferences().GetPinnedResources().GetResourceIds(), func(resource types.ResourceWithLabels) (bool, error) {
match, err := resourceLister.canList(resource, userFilter)
return match, trace.Wrap(err)
})
@@ -1780,23 +1780,23 @@ func (a *ServerWithRoles) filterICPermissionSets(r *proto.PaginatedResource, app
}
assignment := services.IdentityCenterAccountAssignment{
- AccountAssignment: &identitycenterv1.AccountAssignment{
+ AccountAssignment: identitycenterv1.AccountAssignment_builder{
Kind: types.KindIdentityCenterAccountAssignment,
Version: types.V1,
Metadata: &headerv1.Metadata{},
- Spec: &identitycenterv1.AccountAssignmentSpec{
+ Spec: identitycenterv1.AccountAssignmentSpec_builder{
AccountId: appV3.GetName(),
PermissionSet: &identitycenterv1.PermissionSetInfo{},
- },
- },
+ }.Build(),
+ }.Build(),
}
- permissionSetQuery := assignment.Spec.PermissionSet
+ permissionSetQuery := assignment.Spec.GetPermissionSet()
checkable := types.Resource153ToResourceWithLabels(assignment)
var output []*types.IdentityCenterPermissionSet
for _, ps := range pss {
- assignment.Metadata.Name = ps.AssignmentID
- permissionSetQuery.Arn = ps.ARN
+ assignment.Metadata.SetName(ps.AssignmentID)
+ permissionSetQuery.SetArn(ps.ARN)
hasAccess, err := checker.canList(checkable, services.MatchResourceFilter{
ResourceKind: types.KindIdentityCenterAccountAssignment,
@@ -5144,8 +5144,8 @@ func (a *ServerWithRoles) ListRoles(ctx context.Context, req *proto.ListRolesReq
// This does not use the resource verbs for RBAC, and all users are allowed to call this endpoint. The requestable roles returned here are only the ones that the user
// has been granted permission to request. If a user has not been granted permission to request any roles, this will return an empty list.
func (a *ServerWithRoles) ListRequestableRoles(ctx context.Context, req *proto.ListRequestableRolesRequest) (*proto.ListRequestableRolesResponse, error) {
- if req.PageSize == 0 || req.PageSize > apidefaults.DefaultChunkSize {
- req.PageSize = apidefaults.DefaultChunkSize
+ if req.GetPageSize() == 0 || req.GetPageSize() > apidefaults.DefaultChunkSize {
+ req.SetPageSize(apidefaults.DefaultChunkSize)
}
requestValidator, err := services.NewRequestValidator(ctx, a.authServer.clock, a.authServer, a.context.GetUserMetadata().User)
@@ -5155,14 +5155,14 @@ func (a *ServerWithRoles) ListRequestableRoles(ctx context.Context, req *proto.L
// Convert ListRequestableRolesRequest to ListRolesRequest for compatibility with `IterateRoles`
listReq := &proto.ListRolesRequest{
- Limit: req.PageSize,
- StartKey: req.PageToken,
+ Limit: req.GetPageSize(),
+ StartKey: req.GetPageToken(),
}
var roleFilter *types.RoleFilter
- if req.Filter != nil {
+ if req.HasFilter() {
roleFilter = &types.RoleFilter{
- SearchKeywords: req.Filter.SearchKeywords,
+ SearchKeywords: req.GetFilter().GetSearchKeywords(),
SkipSystemRoles: true,
}
}
@@ -5176,7 +5176,7 @@ func (a *ServerWithRoles) ListRequestableRoles(ctx context.Context, req *proto.L
}
// Apply any RoleFilters if defined.
- if req.Filter != nil && !roleFilter.Match(role) {
+ if req.HasFilter() && !roleFilter.Match(role) {
return false, nil
}
@@ -5192,20 +5192,20 @@ func (a *ServerWithRoles) ListRequestableRoles(ctx context.Context, req *proto.L
return nil, trace.Wrap(err)
}
- return &proto.ListRequestableRolesResponse{
+ return proto.ListRequestableRolesResponse_builder{
Roles: convertRolesToRequestableRoles(out),
NextPageToken: nextKey,
- }, nil
+ }.Build(), nil
}
// convertRolesToRequestableRoles turns a slice of Roles into RequestableRoles, stripping all data except the name and description.
func convertRolesToRequestableRoles(roles []*types.RoleV6) []*proto.ListRequestableRolesResponse_RequestableRole {
items := make([]*proto.ListRequestableRolesResponse_RequestableRole, 0, len(roles))
for _, role := range roles {
- item := &proto.ListRequestableRolesResponse_RequestableRole{
+ item := proto.ListRequestableRolesResponse_RequestableRole_builder{
Name: role.GetName(),
Description: role.GetMetadata().Description,
- }
+ }.Build()
items = append(items, item)
}
diff --git a/lib/auth/auth_with_roles_test.go b/lib/auth/auth_with_roles_test.go
index 4646280c8be..daceca76d26 100644
--- a/lib/auth/auth_with_roles_test.go
+++ b/lib/auth/auth_with_roles_test.go
@@ -1163,49 +1163,49 @@ func TestGenerateUserCertsForHeadlessKube(t *testing.T) {
}
scope := "/test"
- roleResp, err := srv.Auth().ScopedAccess().CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ roleResp, err := srv.Auth().ScopedAccess().CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: getScopeAsName(scope) + "-role",
- },
+ }.Build(),
Scope: scope,
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{scope},
- Kube: &scopedaccessv1.ScopedRoleKube{
+ Kube: scopedaccessv1.ScopedRoleKube_builder{
Users: []string{"scoped_kube_user"},
Groups: []string{"scoped_kube_group"},
Labels: []*labelv1.Label{
- {
+ labelv1.Label_builder{
Name: types.Wildcard,
Values: []string{types.Wildcard},
- },
+ }.Build(),
},
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
role := roleResp.GetRole()
- sra, err := srv.Auth().ScopedAccess().CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sra, err := srv.Auth().ScopedAccess().CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
Scope: scope,
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: user1.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: role.GetMetadata().GetName(), Scope: scope},
+ scopedaccessv1.Assignment_builder{Role: role.GetMetadata().GetName(), Scope: scope}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sra)
@@ -1272,7 +1272,7 @@ func TestGenerateUserCertsForHeadlessKube(t *testing.T) {
identity, err := tlsca.FromSubject(tlsCert.Subject, tlsCert.NotAfter)
require.NoError(t, err)
if tt.scope != "" {
- require.Equal(t, tt.scope, identity.ScopePin.Scope)
+ require.Equal(t, tt.scope, identity.ScopePin.GetScope())
} else {
require.Nil(t, identity.ScopePin)
}
@@ -3390,11 +3390,11 @@ func TestKubeCRUDFromKubeService(t *testing.T) {
_, err = adminClient.UpsertKubernetesServer(ctx, kubeServer)
require.NoError(t, err)
- waitingContainer, err := unscopedKubeClient.CreateKubernetesWaitingContainer(ctx, &kubewaitingcontainerv1.KubernetesWaitingContainer{
- Metadata: &headerv1.Metadata{
+ waitingContainer, err := unscopedKubeClient.CreateKubernetesWaitingContainer(ctx, kubewaitingcontainerv1.KubernetesWaitingContainer_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "waiting-container",
- },
- Spec: &kubewaitingcontainerv1.KubernetesWaitingContainerSpec{
+ }.Build(),
+ Spec: kubewaitingcontainerv1.KubernetesWaitingContainerSpec_builder{
Username: "user",
Cluster: clusterName,
Namespace: "namespace",
@@ -3402,8 +3402,8 @@ func TestKubeCRUDFromKubeService(t *testing.T) {
ContainerName: "waiting-container",
Patch: []byte("patch"),
PatchType: kubewaitingcontainer.ApplyPatchType,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
t.Run("CreateKubernetesCluster", func(t *testing.T) {
@@ -3543,11 +3543,11 @@ func TestKubeCRUDFromKubeService(t *testing.T) {
t.Run("CreateKubernetesWaitingContainer", func(t *testing.T) {
const wcName = "create-waiting-container"
- wc := &kubewaitingcontainerv1.KubernetesWaitingContainer{
- Metadata: &headerv1.Metadata{
+ wc := kubewaitingcontainerv1.KubernetesWaitingContainer_builder{
+ Metadata: headerv1.Metadata_builder{
Name: wcName,
- },
- Spec: &kubewaitingcontainerv1.KubernetesWaitingContainerSpec{
+ }.Build(),
+ Spec: kubewaitingcontainerv1.KubernetesWaitingContainerSpec_builder{
Username: waitingContainer.GetSpec().GetUsername(),
Cluster: waitingContainer.GetSpec().GetCluster(),
Namespace: waitingContainer.GetSpec().GetNamespace(),
@@ -3555,21 +3555,21 @@ func TestKubeCRUDFromKubeService(t *testing.T) {
ContainerName: wcName,
Patch: waitingContainer.GetSpec().GetPatch(),
PatchType: waitingContainer.GetSpec().GetPatchType(),
- },
- }
+ }.Build(),
+ }.Build()
// unscoped kube service clients SHOULD be able to create a kube waiting container
wc, err := unscopedKubeClient.CreateKubernetesWaitingContainer(ctx, wc)
require.NoError(t, err)
// cleanup waiting container
- err = unscopedKubeClient.DeleteKubernetesWaitingContainer(ctx, &kubewaitingcontainerv1.DeleteKubernetesWaitingContainerRequest{
+ err = unscopedKubeClient.DeleteKubernetesWaitingContainer(ctx, kubewaitingcontainerv1.DeleteKubernetesWaitingContainerRequest_builder{
Username: wc.GetSpec().GetUsername(),
Cluster: wc.GetSpec().GetCluster(),
Namespace: wc.GetSpec().GetNamespace(),
PodName: wc.GetSpec().GetPodName(),
ContainerName: wc.GetSpec().GetContainerName(),
- })
+ }.Build())
require.NoError(t, err)
// scoped kube service clients SHOULD NOT be able to create a kube waiting container
@@ -3580,11 +3580,11 @@ func TestKubeCRUDFromKubeService(t *testing.T) {
t.Run("DeleteKubernetesWaitingContainer", func(t *testing.T) {
const wcName = "delete-waiting-container"
- wc := &kubewaitingcontainerv1.KubernetesWaitingContainer{
- Metadata: &headerv1.Metadata{
+ wc := kubewaitingcontainerv1.KubernetesWaitingContainer_builder{
+ Metadata: headerv1.Metadata_builder{
Name: wcName,
- },
- Spec: &kubewaitingcontainerv1.KubernetesWaitingContainerSpec{
+ }.Build(),
+ Spec: kubewaitingcontainerv1.KubernetesWaitingContainerSpec_builder{
Username: waitingContainer.GetSpec().GetUsername(),
Cluster: waitingContainer.GetSpec().GetCluster(),
Namespace: waitingContainer.GetSpec().GetNamespace(),
@@ -3592,20 +3592,20 @@ func TestKubeCRUDFromKubeService(t *testing.T) {
ContainerName: wcName,
Patch: waitingContainer.GetSpec().GetPatch(),
PatchType: waitingContainer.GetSpec().GetPatchType(),
- },
- }
+ }.Build(),
+ }.Build()
// unscoped kube service clients SHOULD be able to create a kube waiting container
wc, err := unscopedKubeClient.CreateKubernetesWaitingContainer(ctx, wc)
require.NoError(t, err)
- deleteReq := &kubewaitingcontainerv1.DeleteKubernetesWaitingContainerRequest{
+ deleteReq := kubewaitingcontainerv1.DeleteKubernetesWaitingContainerRequest_builder{
Username: wc.GetSpec().GetUsername(),
Cluster: wc.GetSpec().GetCluster(),
Namespace: wc.GetSpec().GetNamespace(),
PodName: wc.GetSpec().GetPodName(),
ContainerName: wc.GetSpec().GetContainerName(),
- }
+ }.Build()
// cleanup waiting container
err = unscopedKubeClient.DeleteKubernetesWaitingContainer(ctx, deleteReq)
require.NoError(t, err)
@@ -3617,13 +3617,13 @@ func TestKubeCRUDFromKubeService(t *testing.T) {
})
t.Run("GetKubernetesWaitingContainer", func(t *testing.T) {
- req := &kubewaitingcontainerv1.GetKubernetesWaitingContainerRequest{
+ req := kubewaitingcontainerv1.GetKubernetesWaitingContainerRequest_builder{
Username: waitingContainer.GetSpec().GetUsername(),
Cluster: waitingContainer.GetSpec().GetCluster(),
Namespace: waitingContainer.GetSpec().GetNamespace(),
PodName: waitingContainer.GetSpec().GetPodName(),
ContainerName: waitingContainer.GetSpec().GetContainerName(),
- }
+ }.Build()
// unscoped kube clients SHOULD be able to fetch a kube waiting containers
_, err := unscopedKubeClient.GetKubernetesWaitingContainer(ctx, req)
require.NoError(t, err)
@@ -5482,52 +5482,52 @@ func TestListResources_KindKubernetesCluster(t *testing.T) {
}
// create scoped roles, users, and assignments
for _, scope := range scopes {
- roleResp, err := scopedAccess.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ roleResp, err := scopedAccess.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: getScopeAsName(scope) + "-role",
- },
+ }.Build(),
Scope: scope,
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{scope},
- Kube: &scopedaccessv1.ScopedRoleKube{
+ Kube: scopedaccessv1.ScopedRoleKube_builder{
Users: []string{"kube_user"},
Groups: []string{"kube_group"},
Labels: []*labelv1.Label{
- {
+ labelv1.Label_builder{
Name: types.Wildcard,
Values: []string{types.Wildcard},
- },
+ }.Build(),
},
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
user, err := authtest.CreateUser(ctx, srv.Auth(), getScopeAsName(scope)+"-reader")
require.NoError(t, err)
role := roleResp.GetRole()
- sra, err := scopedAccess.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sra, err := scopedAccess.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
Scope: scope,
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: user.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: role.GetMetadata().GetName(), Scope: scope},
+ scopedaccessv1.Assignment_builder{Role: role.GetMetadata().GetName(), Scope: scope}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sra)
@@ -5706,10 +5706,10 @@ func waitForSRACache(t *testing.T, srv *authtest.TLSServer, resps ...*scopedacce
ctx := t.Context()
require.EventuallyWithT(t, func(t *assert.CollectT) {
for _, resp := range resps {
- _, err := srv.Auth().ScopedAccessCache.GetScopedRoleAssignment(ctx, &scopedaccessv1.GetScopedRoleAssignmentRequest{
+ _, err := srv.Auth().ScopedAccessCache.GetScopedRoleAssignment(ctx, scopedaccessv1.GetScopedRoleAssignmentRequest_builder{
Name: resp.GetAssignment().GetMetadata().GetName(),
SubKind: resp.GetAssignment().GetSubKind(),
- })
+ }.Build())
require.NoError(t, err)
}
}, 10*time.Second, 100*time.Millisecond)
@@ -7593,19 +7593,19 @@ func TestListUnifiedResources_WithPinnedResources(t *testing.T) {
identity := authtest.TestUser(user.GetName())
// pin a resource
- pinned := &userpreferencesv1.PinnedResourcesUserPreferences{
+ pinned := userpreferencesv1.PinnedResourcesUserPreferences_builder{
ResourceIds: []string{"tifa/tifa/node"},
- }
- clusterPrefs := &userpreferencesv1.ClusterUserPreferences{
+ }.Build()
+ clusterPrefs := userpreferencesv1.ClusterUserPreferences_builder{
PinnedResources: pinned,
- }
+ }.Build()
- req := &userpreferencesv1.UpsertUserPreferencesRequest{
- Preferences: &userpreferencesv1.UserPreferences{
+ req := userpreferencesv1.UpsertUserPreferencesRequest_builder{
+ Preferences: userpreferencesv1.UserPreferences_builder{
ClusterPreferences: clusterPrefs,
- },
- }
- err = srv.Auth().UpsertUserPreferences(ctx, username, req.Preferences)
+ }.Build(),
+ }.Build()
+ err = srv.Auth().UpsertUserPreferences(ctx, username, req.GetPreferences())
require.NoError(t, err)
clt, err := srv.NewClient(identity)
@@ -7956,21 +7956,21 @@ func TestUnifiedResources_IdentityCenter(t *testing.T) {
withMatchingAccountAssignment := withAccountAssignment(types.Allow,
validAccountID, validPermissionSetARN)
- acct, err := srv.Auth().CreateIdentityCenterAccount(ctx, &identitycenterv1.Account{
+ acct, err := srv.Auth().CreateIdentityCenterAccount(ctx, identitycenterv1.Account_builder{
Kind: types.KindIdentityCenterAccount,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-account",
Labels: map[string]string{
types.OriginLabel: apicommon.OriginAWSIdentityCenter,
},
- },
- Spec: &identitycenterv1.AccountSpec{
+ }.Build(),
+ Spec: identitycenterv1.AccountSpec_builder{
Id: validAccountID,
Arn: "some:account:arn",
Name: "Test Account",
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
t.Cleanup(func() {
srv.Auth().DeleteIdentityCenterAccount(ctx,
@@ -8678,7 +8678,7 @@ func TestGenerateHostCert(t *testing.T) {
require.NoError(t, err)
// Try by calling new gRPC endpoint directly
- _, err = client.TrustClient().GenerateHostCert(ctx, &trustpb.GenerateHostCertRequest{
+ _, err = client.TrustClient().GenerateHostCert(ctx, trustpb.GenerateHostCertRequest_builder{
Key: pub,
HostId: "",
NodeName: "",
@@ -8686,7 +8686,7 @@ func TestGenerateHostCert(t *testing.T) {
ClusterName: clusterName,
Role: string(types.RoleNode),
Ttl: durationpb.New(0),
- })
+ }.Build())
require.True(t, test.expect(err))
})
}
@@ -11763,33 +11763,33 @@ func TestScopedRoleEvents(t *testing.T) {
require.Equal(t, types.OpInit, event.Type)
// Create a ScopedRole and verify create event is well-formed.
- role := &scopedaccessv1.ScopedRole{
+ role := scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-role",
- },
+ }.Build(),
Scope: "/",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/foo", "/bar"},
- },
+ }.Build(),
Version: types.V1,
- }
+ }.Build()
- crsp, err := service.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
+ crsp, err := service.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
Role: role,
- })
+ }.Build())
require.NoError(t, err)
event = getNextEvent()
require.Equal(t, types.OpPut, event.Type)
resource := (event.Resource).(types.Resource153UnwrapperT[*scopedaccessv1.ScopedRole]).UnwrapT()
- require.Empty(t, cmp.Diff(crsp.Role, resource, protocmp.Transform() /* deliberately not ignoring revision */))
+ require.Empty(t, cmp.Diff(crsp.GetRole(), resource, protocmp.Transform() /* deliberately not ignoring revision */))
// delete the role and verify delete event is well-formed.
- _, err = service.DeleteScopedRole(ctx, &scopedaccessv1.DeleteScopedRoleRequest{
- Name: role.Metadata.Name,
- })
+ _, err = service.DeleteScopedRole(ctx, scopedaccessv1.DeleteScopedRoleRequest_builder{
+ Name: role.GetMetadata().GetName(),
+ }.Build())
require.NoError(t, err)
event = getNextEvent()
@@ -11798,52 +11798,52 @@ func TestScopedRoleEvents(t *testing.T) {
require.Empty(t, cmp.Diff(&types.ResourceHeader{
Kind: scopedaccess.KindScopedRole,
Metadata: types.Metadata{
- Name: role.Metadata.Name,
+ Name: role.GetMetadata().GetName(),
},
}, event.Resource.(*types.ResourceHeader), protocmp.Transform()))
// recreate scoped role so that we can use it for testing assignment events
- _, err = service.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
+ _, err = service.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
Role: role,
- })
+ }.Build())
require.NoError(t, err)
_ = getNextEvent() // drain the role create event
- assignment := &scopedaccessv1.ScopedRoleAssignment{
+ assignment := scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.New().String(),
- },
+ }.Build(),
Scope: "/",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: "alice",
Assignments: []*scopedaccessv1.Assignment{
- {
- Role: role.Metadata.Name,
+ scopedaccessv1.Assignment_builder{
+ Role: role.GetMetadata().GetName(),
Scope: "/foo",
- },
+ }.Build(),
},
- },
+ }.Build(),
Version: types.V1,
- }
+ }.Build()
- acrsp, err := service.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
+ acrsp, err := service.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
Assignment: assignment,
- })
+ }.Build())
require.NoError(t, err)
event = getNextEvent()
require.Equal(t, types.OpPut, event.Type)
assignmentResource := (event.Resource).(types.Resource153UnwrapperT[*scopedaccessv1.ScopedRoleAssignment]).UnwrapT()
- require.Empty(t, cmp.Diff(acrsp.Assignment, assignmentResource, protocmp.Transform() /* deliberately not ignoring revision */))
+ require.Empty(t, cmp.Diff(acrsp.GetAssignment(), assignmentResource, protocmp.Transform() /* deliberately not ignoring revision */))
// delete the assignment and verify delete event is well-formed.
- _, err = service.DeleteScopedRoleAssignment(ctx, &scopedaccessv1.DeleteScopedRoleAssignmentRequest{
- Name: assignment.Metadata.Name,
- SubKind: assignment.SubKind,
- })
+ _, err = service.DeleteScopedRoleAssignment(ctx, scopedaccessv1.DeleteScopedRoleAssignmentRequest_builder{
+ Name: assignment.GetMetadata().GetName(),
+ SubKind: assignment.GetSubKind(),
+ }.Build())
require.NoError(t, err)
event = getNextEvent()
@@ -11853,7 +11853,7 @@ func TestScopedRoleEvents(t *testing.T) {
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
Metadata: types.Metadata{
- Name: assignment.Metadata.Name,
+ Name: assignment.GetMetadata().GetName(),
},
}, event.Resource.(*types.ResourceHeader), protocmp.Transform()))
}
@@ -12353,40 +12353,40 @@ func TestFilterIdentityCenterPermissionSets(t *testing.T) {
// GIVEN an Identity Center Account with some associated Permission Set
// resources
permissionSets := []*identitycenterv1.PermissionSetInfo{
- {
+ identitycenterv1.PermissionSetInfo_builder{
Name: "PS One",
Arn: permissionSetArnPrefix + "one",
AssignmentId: accountID + "-" + "ps_one",
- },
- {
+ }.Build(),
+ identitycenterv1.PermissionSetInfo_builder{
Name: "PS Two",
Arn: permissionSetArnPrefix + "two",
AssignmentId: accountID + "-" + "ps_two",
- },
- {
+ }.Build(),
+ identitycenterv1.PermissionSetInfo_builder{
Name: "PS Three",
Arn: permissionSetArnPrefix + "ps_three",
AssignmentId: accountID + "-" + "ps_three",
- },
+ }.Build(),
}
- _, err := srv.AuthServer.AuthServer.CreateIdentityCenterAccount(ctx, &identitycenterv1.Account{
+ _, err := srv.AuthServer.AuthServer.CreateIdentityCenterAccount(ctx, identitycenterv1.Account_builder{
Kind: types.KindIdentityCenterAccount,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: accountID,
Labels: map[string]string{
types.OriginLabel: apicommon.OriginAWSIdentityCenter,
},
- },
- Spec: &identitycenterv1.AccountSpec{
+ }.Build(),
+ Spec: identitycenterv1.AccountSpec_builder{
Id: accountID,
Arn: "aws:arn:test:account",
Name: "Test Account",
Description: "An account for testing",
PermissionSetInfo: permissionSets,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// GIVEN a role that allows access to all permission sets on the target
@@ -12432,8 +12432,8 @@ func TestFilterIdentityCenterPermissionSets(t *testing.T) {
{
name: "basic access",
roleModifiers: []authtest.CreateUserAndRoleOption{
- withAccountAssignment(types.Allow, accountID, permissionSets[0].Arn),
- withAccountAssignment(types.Allow, accountID, permissionSets[1].Arn),
+ withAccountAssignment(types.Allow, accountID, permissionSets[0].GetArn()),
+ withAccountAssignment(types.Allow, accountID, permissionSets[1].GetArn()),
},
expectedPSs: []*types.IdentityCenterPermissionSet{
paginatedAppPermissionSet(permissionSets[0]),
@@ -12444,7 +12444,7 @@ func TestFilterIdentityCenterPermissionSets(t *testing.T) {
{
name: "ignore search as roles when disabled",
roleModifiers: []authtest.CreateUserAndRoleOption{
- withAccountAssignment(types.Allow, accountID, permissionSets[1].Arn),
+ withAccountAssignment(types.Allow, accountID, permissionSets[1].GetArn()),
withRequesterRole,
},
includeRequestable: false,
@@ -12456,7 +12456,7 @@ func TestFilterIdentityCenterPermissionSets(t *testing.T) {
{
name: "requestable access",
roleModifiers: []authtest.CreateUserAndRoleOption{
- withAccountAssignment(types.Allow, accountID, permissionSets[1].Arn),
+ withAccountAssignment(types.Allow, accountID, permissionSets[1].GetArn()),
withRequesterRole,
},
includeRequestable: true,
@@ -12527,9 +12527,9 @@ func TestFilterIdentityCenterPermissionSets(t *testing.T) {
func paginatedAppPermissionSet(src *identitycenterv1.PermissionSetInfo) *types.IdentityCenterPermissionSet {
return &types.IdentityCenterPermissionSet{
- ARN: src.Arn,
- Name: src.Name,
- AssignmentID: src.AssignmentId,
+ ARN: src.GetArn(),
+ Name: src.GetName(),
+ AssignmentID: src.GetAssignmentId(),
}
}
@@ -12878,10 +12878,10 @@ func TestRegisterInventoryControlStreamScopes(t *testing.T) {
resultCh <- registerResult{hello: hello, err: err}
}()
- err := h.downstream.Send(ctx, &proto.UpstreamInventoryHello{
+ err := h.downstream.Send(ctx, proto.UpstreamInventoryHello_builder{
ServerID: serverID,
Scope: c.helloScope,
- })
+ }.Build())
require.NoError(t, err)
if c.expectErr != nil {
@@ -12907,12 +12907,12 @@ func TestRegisterInventoryControlStreamImmutableLabels(t *testing.T) {
ctx := t.Context()
const serverID = "test-server"
- helloLabels := &joiningv1.ImmutableLabels{
+ helloLabels := joiningv1.ImmutableLabels_builder{
Ssh: map[string]string{
"test": "label",
"test2": "label2",
},
- }
+ }.Build()
helloHash := joining.HashImmutableLabels(helloLabels)
as, err := authtest.NewAuthServer(authtest.AuthServerConfig{Dir: t.TempDir()})
@@ -12969,10 +12969,10 @@ func TestRegisterInventoryControlStreamImmutableLabels(t *testing.T) {
resultCh <- registerResult{hello: hello, err: err}
}()
- err := h.downstream.Send(ctx, &proto.UpstreamInventoryHello{
+ err := h.downstream.Send(ctx, proto.UpstreamInventoryHello_builder{
ServerID: serverID,
ImmutableLabels: c.helloLabels,
- })
+ }.Build())
require.NoError(t, err)
if c.expectErr != nil {
@@ -13010,52 +13010,52 @@ func TestScopedUserCertGeneration(t *testing.T) {
username := "scoped-user"
scope := "/test"
scopedAccess := srv.Auth().ScopedAccess()
- roleResp, err := scopedAccess.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ roleResp, err := scopedAccess.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: username,
- },
+ }.Build(),
Scope: scope,
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{scope},
- Kube: &scopedaccessv1.ScopedRoleKube{
+ Kube: scopedaccessv1.ScopedRoleKube_builder{
Users: []string{"kube_user"},
Groups: []string{"kube_group"},
Labels: []*labelv1.Label{
- {
+ labelv1.Label_builder{
Name: types.Wildcard,
Values: []string{types.Wildcard},
- },
+ }.Build(),
},
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
user, role, err := authtest.CreateUserAndRole(srv.Auth(), username, []string{username}, nil)
require.NoError(t, err)
scopedRole := roleResp.GetRole()
- sra, err := scopedAccess.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sra, err := scopedAccess.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
Scope: scope,
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: user.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.GetMetadata().GetName(), Scope: scope},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetMetadata().GetName(), Scope: scope}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sra)
diff --git a/lib/auth/authclient/clt.go b/lib/auth/authclient/clt.go
index 1f36297130d..75cd3acddbf 100644
--- a/lib/auth/authclient/clt.go
+++ b/lib/auth/authclient/clt.go
@@ -706,50 +706,50 @@ func (c *Client) ScopedRoleReader() services.ScopedRoleReader {
// UpsertUserNotificationState creates or updates a user notification state which records whether the user has clicked on or dismissed a notification.
func (c *Client) UpsertUserNotificationState(ctx context.Context, username string, uns *notificationsv1.UserNotificationState) (*notificationsv1.UserNotificationState, error) {
- return c.APIClient.UpsertUserNotificationState(ctx, ¬ificationsv1.UpsertUserNotificationStateRequest{
+ return c.APIClient.UpsertUserNotificationState(ctx, notificationsv1.UpsertUserNotificationStateRequest_builder{
Username: username,
UserNotificationState: uns,
- })
+ }.Build())
}
// UpsertUserLastSeenNotification creates or updates a user's last seen notification item.
func (c *Client) UpsertUserLastSeenNotification(ctx context.Context, username string, ulsn *notificationsv1.UserLastSeenNotification) (*notificationsv1.UserLastSeenNotification, error) {
- return c.APIClient.UpsertUserLastSeenNotification(ctx, ¬ificationsv1.UpsertUserLastSeenNotificationRequest{
+ return c.APIClient.UpsertUserLastSeenNotification(ctx, notificationsv1.UpsertUserLastSeenNotificationRequest_builder{
Username: username,
UserLastSeenNotification: ulsn,
- })
+ }.Build())
}
// CreateGlobalNotification creates a global notification.
func (c *Client) CreateGlobalNotification(ctx context.Context, gn *notificationsv1.GlobalNotification) (*notificationsv1.GlobalNotification, error) {
- rsp, err := c.APIClient.CreateGlobalNotification(ctx, ¬ificationsv1.CreateGlobalNotificationRequest{
+ rsp, err := c.APIClient.CreateGlobalNotification(ctx, notificationsv1.CreateGlobalNotificationRequest_builder{
GlobalNotification: gn,
- })
+ }.Build())
return rsp, trace.Wrap(err)
}
// CreateUserNotification creates a user-specific notification.
func (c *Client) CreateUserNotification(ctx context.Context, notification *notificationsv1.Notification) (*notificationsv1.Notification, error) {
- rsp, err := c.APIClient.CreateUserNotification(ctx, ¬ificationsv1.CreateUserNotificationRequest{
+ rsp, err := c.APIClient.CreateUserNotification(ctx, notificationsv1.CreateUserNotificationRequest_builder{
Notification: notification,
- })
+ }.Build())
return rsp, trace.Wrap(err)
}
// DeleteGlobalNotification deletes a global notification.
func (c *Client) DeleteGlobalNotification(ctx context.Context, notificationId string) error {
- err := c.APIClient.DeleteGlobalNotification(ctx, ¬ificationsv1.DeleteGlobalNotificationRequest{
+ err := c.APIClient.DeleteGlobalNotification(ctx, notificationsv1.DeleteGlobalNotificationRequest_builder{
NotificationId: notificationId,
- })
+ }.Build())
return trace.Wrap(err)
}
// DeleteUserNotification not implemented: can only be called locally.
func (c *Client) DeleteUserNotification(ctx context.Context, username string, notificationId string) error {
- err := c.APIClient.DeleteUserNotification(ctx, ¬ificationsv1.DeleteUserNotificationRequest{
+ err := c.APIClient.DeleteUserNotification(ctx, notificationsv1.DeleteUserNotificationRequest_builder{
Username: username,
NotificationId: notificationId,
- })
+ }.Build())
return trace.Wrap(err)
}
diff --git a/lib/auth/authclient/httpfallback.go b/lib/auth/authclient/httpfallback.go
index 052c40d200f..35fddea1849 100644
--- a/lib/auth/authclient/httpfallback.go
+++ b/lib/auth/authclient/httpfallback.go
@@ -85,9 +85,9 @@ func (c *Client) UpsertTunnelConnection(ctx context.Context, conn types.TunnelCo
if !ok {
return trace.BadParameter("unsupported tunnel connection type %T", conn)
}
- _, err := c.TrustClient().UpsertTunnelConnection(ctx, &trustpb.UpsertTunnelConnectionRequest{
+ _, err := c.TrustClient().UpsertTunnelConnection(ctx, trustpb.UpsertTunnelConnectionRequest_builder{
TunnelConnection: connV2,
- })
+ }.Build())
if err != nil {
if trace.IsNotImplemented(err) {
return trace.Wrap(c.HTTPClient.upsertTunnelConnection(ctx, conn))
@@ -116,10 +116,10 @@ func (c *HTTPClient) upsertTunnelConnection(ctx context.Context, conn types.Tunn
//
// TODO(strideynet): DELETE IN v20.0.0
func (c *Client) DeleteTunnelConnection(ctx context.Context, clusterName, connName string) error {
- _, err := c.TrustClient().DeleteTunnelConnection(ctx, &trustpb.DeleteTunnelConnectionRequest{
+ _, err := c.TrustClient().DeleteTunnelConnection(ctx, trustpb.DeleteTunnelConnectionRequest_builder{
ClusterName: clusterName,
ConnectionName: connName,
- })
+ }.Build())
if err != nil {
if trace.IsNotImplemented(err) {
return trace.Wrap(c.HTTPClient.deleteTunnelConnection(ctx, clusterName, connName))
@@ -179,9 +179,9 @@ func (c *Client) UpsertProxyServerWithoutReturn(ctx context.Context, s types.Ser
if !ok {
return trace.BadParameter("unsupported proxy server type %T", s)
}
- _, err := c.APIClient.PresenceServiceClient().UpsertProxyServer(ctx, &presencev1.UpsertProxyServerRequest{
+ _, err := c.APIClient.PresenceServiceClient().UpsertProxyServer(ctx, presencev1.UpsertProxyServerRequest_builder{
Server: serverV2,
- })
+ }.Build())
if err == nil {
return nil
}
@@ -213,9 +213,9 @@ func (c *HTTPClient) upsertProxyServerLegacy(ctx context.Context, s types.Server
//
// TODO(noah): DELETE IN v20.0.0
func (c *Client) DeleteProxyServer(ctx context.Context, name string) error {
- _, err := c.APIClient.PresenceServiceClient().DeleteProxyServer(ctx, &presencev1.DeleteProxyServerRequest{
+ _, err := c.APIClient.PresenceServiceClient().DeleteProxyServer(ctx, presencev1.DeleteProxyServerRequest_builder{
Name: name,
- })
+ }.Build())
if err == nil {
return nil
}
diff --git a/lib/auth/autoupdate/autoupdatev1/service.go b/lib/auth/autoupdate/autoupdatev1/service.go
index 9aaa6dc7302..f12d3ad68aa 100644
--- a/lib/auth/autoupdate/autoupdatev1/service.go
+++ b/lib/auth/autoupdate/autoupdatev1/service.go
@@ -148,11 +148,11 @@ func (s *Service) CreateAutoUpdateConfig(ctx context.Context, req *autoupdate.Cr
return nil, trace.Wrap(err)
}
- if err := validateServerSideAgentConfig(req.Config, s.modules.Features()); err != nil {
+ if err := validateServerSideAgentConfig(req.GetConfig(), s.modules.Features()); err != nil {
return nil, trace.Wrap(err)
}
- config, err := s.backend.CreateAutoUpdateConfig(ctx, req.Config)
+ config, err := s.backend.CreateAutoUpdateConfig(ctx, req.GetConfig())
var errMsg string
if err != nil {
errMsg = err.Error()
@@ -192,11 +192,11 @@ func (s *Service) UpdateAutoUpdateConfig(ctx context.Context, req *autoupdate.Up
return nil, trace.Wrap(err)
}
- if err := validateServerSideAgentConfig(req.Config, s.modules.Features()); err != nil {
+ if err := validateServerSideAgentConfig(req.GetConfig(), s.modules.Features()); err != nil {
return nil, trace.Wrap(err)
}
- config, err := s.backend.UpdateAutoUpdateConfig(ctx, req.Config)
+ config, err := s.backend.UpdateAutoUpdateConfig(ctx, req.GetConfig())
var errMsg string
if err != nil {
errMsg = err.Error()
@@ -236,11 +236,11 @@ func (s *Service) UpsertAutoUpdateConfig(ctx context.Context, req *autoupdate.Up
return nil, trace.Wrap(err)
}
- if err := validateServerSideAgentConfig(req.Config, s.modules.Features()); err != nil {
+ if err := validateServerSideAgentConfig(req.GetConfig(), s.modules.Features()); err != nil {
return nil, trace.Wrap(err)
}
- config, err := s.backend.UpsertAutoUpdateConfig(ctx, req.Config)
+ config, err := s.backend.UpsertAutoUpdateConfig(ctx, req.GetConfig())
var errMsg string
if err != nil {
errMsg = err.Error()
@@ -359,7 +359,7 @@ func (s *Service) CreateAutoUpdateVersion(ctx context.Context, req *autoupdate.C
return nil, trace.Wrap(err)
}
- autoUpdateVersion, err := s.backend.CreateAutoUpdateVersion(ctx, req.Version)
+ autoUpdateVersion, err := s.backend.CreateAutoUpdateVersion(ctx, req.GetVersion())
var errMsg string
if err != nil {
errMsg = err.Error()
@@ -404,7 +404,7 @@ func (s *Service) UpdateAutoUpdateVersion(ctx context.Context, req *autoupdate.U
return nil, trace.Wrap(err)
}
- autoUpdateVersion, err := s.backend.UpdateAutoUpdateVersion(ctx, req.Version)
+ autoUpdateVersion, err := s.backend.UpdateAutoUpdateVersion(ctx, req.GetVersion())
var errMsg string
if err != nil {
errMsg = err.Error()
@@ -449,7 +449,7 @@ func (s *Service) UpsertAutoUpdateVersion(ctx context.Context, req *autoupdate.U
return nil, trace.Wrap(err)
}
- autoUpdateVersion, err := s.backend.UpsertAutoUpdateVersion(ctx, req.Version)
+ autoUpdateVersion, err := s.backend.UpsertAutoUpdateVersion(ctx, req.GetVersion())
var errMsg string
if err != nil {
errMsg = err.Error()
@@ -575,7 +575,7 @@ func (s *Service) CreateAutoUpdateAgentRollout(ctx context.Context, req *autoupd
return nil, trace.Wrap(err)
}
- autoUpdateAgentRollout, err := s.backend.CreateAutoUpdateAgentRollout(ctx, req.Rollout)
+ autoUpdateAgentRollout, err := s.backend.CreateAutoUpdateAgentRollout(ctx, req.GetRollout())
return autoUpdateAgentRollout, trace.Wrap(err)
}
@@ -604,7 +604,7 @@ func (s *Service) UpdateAutoUpdateAgentRollout(ctx context.Context, req *autoupd
return nil, trace.Wrap(err)
}
- autoUpdateAgentRollout, err := s.backend.UpdateAutoUpdateAgentRollout(ctx, req.Rollout)
+ autoUpdateAgentRollout, err := s.backend.UpdateAutoUpdateAgentRollout(ctx, req.GetRollout())
return autoUpdateAgentRollout, trace.Wrap(err)
}
@@ -633,7 +633,7 @@ func (s *Service) UpsertAutoUpdateAgentRollout(ctx context.Context, req *autoupd
return nil, trace.Wrap(err)
}
- autoUpdateAgentRollout, err := s.backend.UpsertAutoUpdateAgentRollout(ctx, req.Rollout)
+ autoUpdateAgentRollout, err := s.backend.UpsertAutoUpdateAgentRollout(ctx, req.GetRollout())
return autoUpdateAgentRollout, trace.Wrap(err)
}
@@ -715,7 +715,7 @@ func (s *Service) TriggerAutoUpdateAgentGroup(ctx context.Context, req *autoupda
Code: events.AutoUpdateAgentRolloutTriggerCode,
},
UserMetadata: userMetadata,
- Groups: req.Groups,
+ Groups: req.GetGroups(),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
Status: apievents.Status{
Success: err == nil,
@@ -737,7 +737,7 @@ func (s *Service) TriggerAutoUpdateAgentGroup(ctx context.Context, req *autoupda
return nil, trace.Wrap(err, "getting reports")
}
- err = rollout.TriggerGroups(existingRollout, reports, rollout.GroupListToGroupSet(req.Groups), req.DesiredState, time.Now())
+ err = rollout.TriggerGroups(existingRollout, reports, rollout.GroupListToGroupSet(req.GetGroups()), req.GetDesiredState(), time.Now())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -781,7 +781,7 @@ func (s *Service) ForceAutoUpdateAgentGroup(ctx context.Context, req *autoupdate
Code: events.AutoUpdateAgentRolloutForceDoneCode,
},
UserMetadata: userMetadata,
- Groups: req.Groups,
+ Groups: req.GetGroups(),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
Status: apievents.Status{
Success: err == nil,
@@ -799,7 +799,7 @@ func (s *Service) ForceAutoUpdateAgentGroup(ctx context.Context, req *autoupdate
return nil, trace.Wrap(err)
}
- err = rollout.ForceGroupsDone(existingRollout, rollout.GroupListToGroupSet(req.Groups), time.Now())
+ err = rollout.ForceGroupsDone(existingRollout, rollout.GroupListToGroupSet(req.GetGroups()), time.Now())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -831,7 +831,7 @@ func (s *Service) RollbackAutoUpdateAgentGroup(ctx context.Context, req *autoupd
return nil, trace.Wrap(err)
}
- if len(req.Groups) == 0 && !req.AllStartedGroups {
+ if len(req.GetGroups()) == 0 && !req.GetAllStartedGroups() {
return nil, trace.BadParameter("at least one group must be specified or the all_started_groups flag set")
}
@@ -852,7 +852,7 @@ func (s *Service) RollbackAutoUpdateAgentGroup(ctx context.Context, req *autoupd
Success: err == nil,
Error: errMsg,
},
- Groups: req.Groups,
+ Groups: req.GetGroups(),
})
}()
@@ -865,8 +865,8 @@ func (s *Service) RollbackAutoUpdateAgentGroup(ctx context.Context, req *autoupd
return nil, trace.Wrap(err)
}
- groups := rollout.GroupListToGroupSet(req.Groups)
- if req.AllStartedGroups {
+ groups := rollout.GroupListToGroupSet(req.GetGroups())
+ if req.GetAllStartedGroups() {
startedGroups := rollout.GetStartedGroups(existingRollout)
for group := range startedGroups {
groups[group] = struct{}{}
@@ -909,10 +909,10 @@ func (s *Service) ListAutoUpdateAgentReports(ctx context.Context, req *autoupdat
return nil, trace.Wrap(err)
}
- return &autoupdate.ListAutoUpdateAgentReportsResponse{
+ return autoupdate.ListAutoUpdateAgentReportsResponse_builder{
AutoupdateAgentReports: reports,
NextKey: nextKey,
- }, nil
+ }.Build(), nil
}
@@ -1191,7 +1191,7 @@ func validateServerSideAgentConfig(config *autoupdate.AutoUpdateConfig, features
}
for i, group := range agentsSpec.GetSchedules().GetRegular() {
- weekdays, err := types.ParseWeekdays(group.Days)
+ weekdays, err := types.ParseWeekdays(group.GetDays())
if err != nil {
return trace.Wrap(err, "parsing weekdays from group %d", i)
}
@@ -1214,7 +1214,7 @@ func computeMinRolloutTime(groups []*autoupdate.AgentAutoUpdateGroup) int {
}
// We start the rollout at the first group hour, and we wait for the group to update (1 hour).
- hours := groups[0].StartHour + 1
+ hours := groups[0].GetStartHour() + 1
for _, group := range groups[1:] {
previousStartHour := (hours - 1) % 24
@@ -1222,16 +1222,16 @@ func computeMinRolloutTime(groups []*autoupdate.AgentAutoUpdateGroup) int {
// compute the difference between the current hour and the group start hour
// we then check if it's less than the WaitHours, in this case we wait a day
- diff := hourDifference(previousStartHour, group.StartHour)
- if diff < group.WaitHours%24 {
- hours += 24 + hourDifference(previousEndHour, group.StartHour)
+ diff := hourDifference(previousStartHour, group.GetStartHour())
+ if diff < group.GetWaitHours()%24 {
+ hours += 24 + hourDifference(previousEndHour, group.GetStartHour())
} else {
- hours += hourDifference(previousEndHour, group.StartHour)
+ hours += hourDifference(previousEndHour, group.GetStartHour())
}
// Handle the case where WaitHours is > 24
// This is an integer division
- waitDays := group.WaitHours / 24
+ waitDays := group.GetWaitHours() / 24
// There's a special case where the difference modulo 24 is zero, the
// wait hours are non-null, but we already waited 23 hours.
// To avoid double counting we reduce the number of wait days by 1 if
@@ -1246,7 +1246,7 @@ func computeMinRolloutTime(groups []*autoupdate.AgentAutoUpdateGroup) int {
}
// We remove the group start hour we added initially
- return int(hours - groups[0].StartHour)
+ return int(hours - groups[0].GetStartHour())
}
// hourDifference computed the difference between two hours.
diff --git a/lib/auth/autoupdate/autoupdatev1/service_test.go b/lib/auth/autoupdate/autoupdatev1/service_test.go
index 5afc8f2657a..32b650d253c 100644
--- a/lib/auth/autoupdate/autoupdatev1/service_test.go
+++ b/lib/auth/autoupdate/autoupdatev1/service_test.go
@@ -471,14 +471,14 @@ func TestAutoUpdateConfigEvents(t *testing.T) {
service := newService(t, authz.AdminActionAuthMFAVerified, checker, mockEmitter)
ctx := context.Background()
- config, err := autoupdate.NewAutoUpdateConfig(&autoupdatev1pb.AutoUpdateConfigSpec{
- Tools: &autoupdatev1pb.AutoUpdateConfigSpecTools{
+ config, err := autoupdate.NewAutoUpdateConfig(autoupdatev1pb.AutoUpdateConfigSpec_builder{
+ Tools: autoupdatev1pb.AutoUpdateConfigSpecTools_builder{
Mode: autoupdate.ToolsUpdateModeEnabled,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- _, err = service.CreateAutoUpdateConfig(ctx, &autoupdatev1pb.CreateAutoUpdateConfigRequest{Config: config})
+ _, err = service.CreateAutoUpdateConfig(ctx, autoupdatev1pb.CreateAutoUpdateConfigRequest_builder{Config: config}.Build())
require.NoError(t, err)
require.Len(t, mockEmitter.Events(), 1)
require.Equal(t, libevents.AutoUpdateConfigCreateEvent, mockEmitter.LastEvent().GetType())
@@ -486,7 +486,7 @@ func TestAutoUpdateConfigEvents(t *testing.T) {
require.Equal(t, types.MetaNameAutoUpdateConfig, mockEmitter.LastEvent().(*apievents.AutoUpdateConfigCreate).Name)
mockEmitter.Reset()
- _, err = service.UpdateAutoUpdateConfig(ctx, &autoupdatev1pb.UpdateAutoUpdateConfigRequest{Config: config})
+ _, err = service.UpdateAutoUpdateConfig(ctx, autoupdatev1pb.UpdateAutoUpdateConfigRequest_builder{Config: config}.Build())
require.NoError(t, err)
require.Len(t, mockEmitter.Events(), 1)
require.Equal(t, libevents.AutoUpdateConfigUpdateEvent, mockEmitter.LastEvent().GetType())
@@ -494,7 +494,7 @@ func TestAutoUpdateConfigEvents(t *testing.T) {
require.Equal(t, types.MetaNameAutoUpdateConfig, mockEmitter.LastEvent().(*apievents.AutoUpdateConfigUpdate).Name)
mockEmitter.Reset()
- _, err = service.UpsertAutoUpdateConfig(ctx, &autoupdatev1pb.UpsertAutoUpdateConfigRequest{Config: config})
+ _, err = service.UpsertAutoUpdateConfig(ctx, autoupdatev1pb.UpsertAutoUpdateConfigRequest_builder{Config: config}.Build())
require.NoError(t, err)
require.Len(t, mockEmitter.Events(), 1)
require.Equal(t, libevents.AutoUpdateConfigUpdateEvent, mockEmitter.LastEvent().GetType())
@@ -518,14 +518,14 @@ func TestAutoUpdateVersionEvents(t *testing.T) {
service := newService(t, authz.AdminActionAuthMFAVerified, checker, mockEmitter)
ctx := context.Background()
- config, err := autoupdate.NewAutoUpdateVersion(&autoupdatev1pb.AutoUpdateVersionSpec{
- Tools: &autoupdatev1pb.AutoUpdateVersionSpecTools{
+ config, err := autoupdate.NewAutoUpdateVersion(autoupdatev1pb.AutoUpdateVersionSpec_builder{
+ Tools: autoupdatev1pb.AutoUpdateVersionSpecTools_builder{
TargetVersion: "1.2.3",
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- _, err = service.CreateAutoUpdateVersion(ctx, &autoupdatev1pb.CreateAutoUpdateVersionRequest{Version: config})
+ _, err = service.CreateAutoUpdateVersion(ctx, autoupdatev1pb.CreateAutoUpdateVersionRequest_builder{Version: config}.Build())
require.NoError(t, err)
require.Len(t, mockEmitter.Events(), 1)
require.Equal(t, libevents.AutoUpdateVersionCreateEvent, mockEmitter.LastEvent().GetType())
@@ -533,7 +533,7 @@ func TestAutoUpdateVersionEvents(t *testing.T) {
require.Equal(t, types.MetaNameAutoUpdateVersion, mockEmitter.LastEvent().(*apievents.AutoUpdateVersionCreate).Name)
mockEmitter.Reset()
- _, err = service.UpdateAutoUpdateVersion(ctx, &autoupdatev1pb.UpdateAutoUpdateVersionRequest{Version: config})
+ _, err = service.UpdateAutoUpdateVersion(ctx, autoupdatev1pb.UpdateAutoUpdateVersionRequest_builder{Version: config}.Build())
require.NoError(t, err)
require.Len(t, mockEmitter.Events(), 1)
require.Equal(t, libevents.AutoUpdateVersionUpdateEvent, mockEmitter.LastEvent().GetType())
@@ -541,7 +541,7 @@ func TestAutoUpdateVersionEvents(t *testing.T) {
require.Equal(t, types.MetaNameAutoUpdateVersion, mockEmitter.LastEvent().(*apievents.AutoUpdateVersionUpdate).Name)
mockEmitter.Reset()
- _, err = service.UpsertAutoUpdateVersion(ctx, &autoupdatev1pb.UpsertAutoUpdateVersionRequest{Version: config})
+ _, err = service.UpsertAutoUpdateVersion(ctx, autoupdatev1pb.UpsertAutoUpdateVersionRequest_builder{Version: config}.Build())
require.NoError(t, err)
require.Len(t, mockEmitter.Events(), 1)
require.Equal(t, libevents.AutoUpdateVersionUpdateEvent, mockEmitter.LastEvent().GetType())
@@ -571,51 +571,51 @@ func TestAutoUpdateAgentRolloutEvents(t *testing.T) {
mockEmitter)
ctx := context.Background()
- rollout, err := autoupdate.NewAutoUpdateAgentRollout(&autoupdatev1pb.AutoUpdateAgentRolloutSpec{
+ rollout, err := autoupdate.NewAutoUpdateAgentRollout(autoupdatev1pb.AutoUpdateAgentRolloutSpec_builder{
StartVersion: "1.2.3",
TargetVersion: "1.2.4",
Schedule: autoupdate.AgentsScheduleRegular,
AutoupdateMode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- })
+ }.Build())
require.NoError(t, err)
- rollout.Status = &autoupdatev1pb.AutoUpdateAgentRolloutStatus{
+ rollout.SetStatus(autoupdatev1pb.AutoUpdateAgentRolloutStatus_builder{
Groups: []*autoupdatev1pb.AutoUpdateAgentRolloutStatusGroup{
- {
+ autoupdatev1pb.AutoUpdateAgentRolloutStatusGroup_builder{
Name: "blue",
State: autoupdatev1pb.AutoUpdateAgentGroupState_AUTO_UPDATE_AGENT_GROUP_STATE_ROLLEDBACK,
ConfigDays: cloudGroupUpdateDays,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AutoUpdateAgentRolloutStatusGroup_builder{
Name: "dev",
State: autoupdatev1pb.AutoUpdateAgentGroupState_AUTO_UPDATE_AGENT_GROUP_STATE_DONE,
ConfigDays: cloudGroupUpdateDays,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AutoUpdateAgentRolloutStatusGroup_builder{
Name: "stage",
State: autoupdatev1pb.AutoUpdateAgentGroupState_AUTO_UPDATE_AGENT_GROUP_STATE_ACTIVE,
ConfigDays: cloudGroupUpdateDays,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AutoUpdateAgentRolloutStatusGroup_builder{
Name: "prod",
State: autoupdatev1pb.AutoUpdateAgentGroupState_AUTO_UPDATE_AGENT_GROUP_STATE_UNSTARTED,
ConfigDays: cloudGroupUpdateDays,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AutoUpdateAgentRolloutStatusGroup_builder{
Name: "backup",
State: autoupdatev1pb.AutoUpdateAgentGroupState_AUTO_UPDATE_AGENT_GROUP_STATE_UNSPECIFIED,
ConfigDays: cloudGroupUpdateDays,
- },
+ }.Build(),
},
- }
+ }.Build())
- _, err = service.CreateAutoUpdateAgentRollout(ctx, &autoupdatev1pb.CreateAutoUpdateAgentRolloutRequest{Rollout: rollout})
+ _, err = service.CreateAutoUpdateAgentRollout(ctx, autoupdatev1pb.CreateAutoUpdateAgentRolloutRequest_builder{Rollout: rollout}.Build())
require.NoError(t, err)
groups := []string{"prod"}
- _, err = service.TriggerAutoUpdateAgentGroup(ctx, &autoupdatev1pb.TriggerAutoUpdateAgentGroupRequest{
+ _, err = service.TriggerAutoUpdateAgentGroup(ctx, autoupdatev1pb.TriggerAutoUpdateAgentGroupRequest_builder{
Groups: groups,
- })
+ }.Build())
require.NoError(t, err)
require.Len(t, mockEmitter.Events(), 1)
@@ -624,9 +624,9 @@ func TestAutoUpdateAgentRolloutEvents(t *testing.T) {
require.Equal(t, groups, mockEmitter.LastEvent().(*apievents.AutoUpdateAgentRolloutTrigger).Groups)
mockEmitter.Reset()
- _, err = service.ForceAutoUpdateAgentGroup(ctx, &autoupdatev1pb.ForceAutoUpdateAgentGroupRequest{
+ _, err = service.ForceAutoUpdateAgentGroup(ctx, autoupdatev1pb.ForceAutoUpdateAgentGroupRequest_builder{
Groups: []string{"prod"},
- })
+ }.Build())
require.NoError(t, err)
require.Len(t, mockEmitter.Events(), 1)
@@ -635,9 +635,9 @@ func TestAutoUpdateAgentRolloutEvents(t *testing.T) {
require.Equal(t, groups, mockEmitter.LastEvent().(*apievents.AutoUpdateAgentRolloutForceDone).Groups)
mockEmitter.Reset()
- _, err = service.RollbackAutoUpdateAgentGroup(ctx, &autoupdatev1pb.RollbackAutoUpdateAgentGroupRequest{
+ _, err = service.RollbackAutoUpdateAgentGroup(ctx, autoupdatev1pb.RollbackAutoUpdateAgentGroupRequest_builder{
Groups: []string{"prod"},
- })
+ }.Build())
require.NoError(t, err)
require.Len(t, mockEmitter.Events(), 1)
@@ -740,23 +740,23 @@ func TestComputeMinRolloutTime(t *testing.T) {
{
name: "single group",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
- },
+ }.Build(),
},
expectedHours: 1,
},
{
name: "two groups, same day, different start hour, no wait time",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
StartHour: 2,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g2",
StartHour: 4,
- },
+ }.Build(),
},
// g1 updates from 2:00 to 3:00, g2 updates from 4:00 to 5:00, rollout updates from 2:00 to 5:00.
expectedHours: 3,
@@ -764,14 +764,14 @@ func TestComputeMinRolloutTime(t *testing.T) {
{
name: "two groups, same day, same start hour, no wait time",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
StartHour: 2,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g2",
StartHour: 2,
- },
+ }.Build(),
},
// g1 and g2 can't update at the same time, the g1 updates from 2:00 to 3:00 days one,
// and g2 updates from 2:00 to 3:00 the next day. Total update spans from 2:00 day 1, to 3:00 day 2
@@ -780,15 +780,15 @@ func TestComputeMinRolloutTime(t *testing.T) {
{
name: "two groups, cannot happen on the same day because of wait_hours",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
StartHour: 2,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g2",
StartHour: 4,
WaitHours: 6,
- },
+ }.Build(),
},
// g1 updates from 2:00 to 3:00. At 4:00 g2 can't update yet, so we wait the next day.
// On day 2, g2 updates from 4:00 to 5:00. Rollout spans from 2:00 day on to 7:00 day 2.
@@ -797,15 +797,15 @@ func TestComputeMinRolloutTime(t *testing.T) {
{
name: "two groups, wait hours is several days",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
StartHour: 2,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g2",
StartHour: 4,
WaitHours: 48,
- },
+ }.Build(),
},
// g1 updates from 2:00 to 3:00. At 4:00 g2 can't update yet, so we wait 2 days.
// On day 3, g2 updates from 4:00 to 5:00. Rollout spans from 2:00 day on to 7:00 day 3.
@@ -814,83 +814,83 @@ func TestComputeMinRolloutTime(t *testing.T) {
{
name: "two groups, one wait hour",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
StartHour: 2,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g2",
StartHour: 3,
WaitHours: 1,
- },
+ }.Build(),
},
expectedHours: 2,
},
{
name: "two groups different days",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
StartHour: 23,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g2",
StartHour: 1,
- },
+ }.Build(),
},
expectedHours: 3,
},
{
name: "two groups different days, hour diff == wait hours == 1 day",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
StartHour: 12,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g2",
StartHour: 12,
WaitHours: 24,
- },
+ }.Build(),
},
expectedHours: 25,
},
{
name: "two groups different days, hour diff == wait hours",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
StartHour: 12,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g2",
StartHour: 11,
WaitHours: 23,
- },
+ }.Build(),
},
expectedHours: 24,
},
{
name: "everything at once",
groups: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g1",
StartHour: 23,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g2",
StartHour: 1,
WaitHours: 4,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g3",
StartHour: 1,
- },
- {
+ }.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: "g4",
StartHour: 10,
WaitHours: 6,
- },
+ }.Build(),
},
expectedHours: 60,
},
@@ -905,11 +905,11 @@ func TestComputeMinRolloutTime(t *testing.T) {
func generateGroups(n int, days []string) []*autoupdatev1pb.AgentAutoUpdateGroup {
groups := make([]*autoupdatev1pb.AgentAutoUpdateGroup, n)
for i := range groups {
- groups[i] = &autoupdatev1pb.AgentAutoUpdateGroup{
+ groups[i] = autoupdatev1pb.AgentAutoUpdateGroup_builder{
Name: strconv.Itoa(i),
Days: days,
StartHour: int32(i % 24),
- }
+ }.Build()
}
return groups
}
@@ -949,131 +949,131 @@ func TestValidateServerSideAgentConfig(t *testing.T) {
{
name: "over max groups time-based",
modules: selfHostedModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyTimeBased,
MaintenanceWindowDuration: durationpb.New(time.Hour),
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: generateGroups(maxGroupsTimeBasedStrategy+1, cloudGroupUpdateDays),
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.Error,
},
{
name: "over max groups halt-on-error",
modules: selfHostedModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: generateGroups(maxGroupsHaltOnErrorStrategy+1, cloudGroupUpdateDays),
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.Error,
},
{
name: "over max groups halt-on-error cloud unlimited",
modules: cloudUnlimitedModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: generateGroups(maxGroupsHaltOnErrorStrategy+1, cloudGroupUpdateDays),
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.Error,
},
{
name: "over max groups halt-on-error cloud",
modules: cloudModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: generateGroups(maxGroupsHaltOnErrorStrategyCloud+1, cloudGroupUpdateDays),
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.Error,
},
{
name: "cloud should reject custom weekdays",
modules: cloudModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: generateGroups(maxGroupsHaltOnErrorStrategyCloud, []string{"Mon"}),
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.Error,
},
{
name: "cloud unlimited should allow custom weekdays",
modules: cloudUnlimitedModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: generateGroups(maxGroupsHaltOnErrorStrategyCloud, []string{"Mon"}),
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.NoError,
},
{
name: "self-hosted should allow custom weekdays",
modules: selfHostedModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: generateGroups(maxGroupsHaltOnErrorStrategyCloud, []string{"Mon"}),
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.NoError,
},
{
name: "cloud should reject long rollouts",
modules: cloudModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {Name: "g1", Days: cloudGroupUpdateDays},
- {Name: "g2", Days: cloudGroupUpdateDays, WaitHours: maxRolloutDurationCloudHours},
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{Name: "g1", Days: cloudGroupUpdateDays}.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{Name: "g2", Days: cloudGroupUpdateDays, WaitHours: maxRolloutDurationCloudHours}.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.Error,
},
{
name: "cloud should allow long rollouts with entitlement",
modules: cloudUnlimitedModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {Name: "g1", Days: cloudGroupUpdateDays},
- {Name: "g2", Days: cloudGroupUpdateDays, WaitHours: maxRolloutDurationCloudHours},
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{Name: "g1", Days: cloudGroupUpdateDays}.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{Name: "g2", Days: cloudGroupUpdateDays, WaitHours: maxRolloutDurationCloudHours}.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.NoError,
},
{
name: "self-hosted should allow long rollouts",
modules: selfHostedModules,
- config: &autoupdatev1pb.AutoUpdateConfigSpecAgents{
+ config: autoupdatev1pb.AutoUpdateConfigSpecAgents_builder{
Mode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
- Schedules: &autoupdatev1pb.AgentAutoUpdateSchedules{
+ Schedules: autoupdatev1pb.AgentAutoUpdateSchedules_builder{
Regular: []*autoupdatev1pb.AgentAutoUpdateGroup{
- {Name: "g1", Days: cloudGroupUpdateDays},
- {Name: "g2", Days: cloudGroupUpdateDays, WaitHours: maxRolloutDurationCloudHours},
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{Name: "g1", Days: cloudGroupUpdateDays}.Build(),
+ autoupdatev1pb.AgentAutoUpdateGroup_builder{Name: "g2", Days: cloudGroupUpdateDays, WaitHours: maxRolloutDurationCloudHours}.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
expectErr: require.NoError,
},
}
@@ -1081,10 +1081,10 @@ func TestValidateServerSideAgentConfig(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
// Test setup: crafing a config and setting modules
config, err := autoupdate.NewAutoUpdateConfig(
- &autoupdatev1pb.AutoUpdateConfigSpec{
+ autoupdatev1pb.AutoUpdateConfigSpec_builder{
Tools: nil,
Agents: tt.config,
- })
+ }.Build())
require.NoError(t, err)
// Test execution.
diff --git a/lib/auth/autoupdate_agent_version_report.go b/lib/auth/autoupdate_agent_version_report.go
index 1991ea85138..85313752511 100644
--- a/lib/auth/autoupdate_agent_version_report.go
+++ b/lib/auth/autoupdate_agent_version_report.go
@@ -112,7 +112,7 @@ func filterHandler(handle inventory.UpstreamHandle, now time.Time) autoUpdateFil
hello := handle.Hello()
// If the machine has no updater, we skip it
- switch hello.ExternalUpgrader {
+ switch hello.GetExternalUpgrader() {
case "":
return autoUpdateFilterResultNoUpdater
case types.UpgraderKindSystemdUnit:
@@ -160,7 +160,7 @@ func (ir instanceReport) collectInstance(handle inventory.UpstreamHandle) {
// No need to check for UpdaterInfo being nil, it would have been filtered
// out by filterHandler().
- updateGroup := handle.Hello().UpdaterInfo.UpdateGroup
+ updateGroup := handle.Hello().GetUpdaterInfo().UpdateGroup
if _, ok := ir.data[updateGroup]; !ok {
ir.data[updateGroup] = instanceGroupReport{}
@@ -174,14 +174,14 @@ type instanceGroupReport map[string]instanceGroupVersionReport
func (ir instanceGroupReport) collectInstance(handle inventory.UpstreamHandle) {
hello := handle.Hello()
- stats, ok := ir[hello.Version]
+ stats, ok := ir[hello.GetVersion()]
if !ok {
stats = instanceGroupVersionReport{}
}
stats.count += 1
- ir[hello.Version] = stats
+ ir[hello.GetVersion()] = stats
}
type instanceGroupVersionReport struct {
@@ -201,11 +201,11 @@ func (a *Server) generateAgentVersionReport(ctx context.Context) (*autoupdatev1p
a.inventory.AllHandles(rawreport.collectInstance)
a.logger.DebugContext(ctx, "Building the agent version report")
- spec := &autoupdatev1pb.AutoUpdateAgentReportSpec{
+ spec := autoupdatev1pb.AutoUpdateAgentReportSpec_builder{
Timestamp: timestamppb.New(a.clock.Now()),
Groups: make(map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroup, len(rawreport.data)),
Omitted: make([]*autoupdatev1pb.AutoUpdateAgentReportSpecOmitted, 0, len(rawreport.omissions)),
- }
+ }.Build()
// TODO(hugoShaka): gracefully handle too many groups or versions (sort and report only the largest ones).
// Currently the agent version report will just fail validation if there are too many groups.
@@ -213,20 +213,20 @@ func (a *Server) generateAgentVersionReport(ctx context.Context) (*autoupdatev1p
for groupName, groupData := range rawreport.data {
versions := make(map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion, len(groupData))
for versionName, groupVersionData := range groupData {
- versions[versionName] = &autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion{
+ versions[versionName] = autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{
Count: int32(groupVersionData.count),
- }
+ }.Build()
}
- spec.Groups[groupName] = &autoupdatev1pb.AutoUpdateAgentReportSpecGroup{
+ spec.GetGroups()[groupName] = autoupdatev1pb.AutoUpdateAgentReportSpecGroup_builder{
Versions: versions,
- }
+ }.Build()
}
for reason, count := range rawreport.omissions {
- spec.Omitted = append(spec.Omitted, &autoupdatev1pb.AutoUpdateAgentReportSpecOmitted{
+ spec.SetOmitted(append(spec.GetOmitted(), autoupdatev1pb.AutoUpdateAgentReportSpecOmitted_builder{
Reason: reason,
Count: int64(count),
- })
+ }.Build()))
}
report, err := autoupdate.NewAutoUpdateAgentReport(spec, a.ServerID)
diff --git a/lib/auth/autoupdate_agent_version_report_test.go b/lib/auth/autoupdate_agent_version_report_test.go
index 5f9896c5590..0c272bd808b 100644
--- a/lib/auth/autoupdate_agent_version_report_test.go
+++ b/lib/auth/autoupdate_agent_version_report_test.go
@@ -107,9 +107,9 @@ func TestServer_generateAgentVersionReport(t *testing.T) {
}{
{
name: "no servers",
- expected: &autoupdatev1pb.AutoUpdateAgentReportSpec{
+ expected: autoupdatev1pb.AutoUpdateAgentReportSpec_builder{
Timestamp: timestamppb.New(now),
- },
+ }.Build(),
},
{
name: "no group, same version",
@@ -119,16 +119,16 @@ func TestServer_generateAgentVersionReport(t *testing.T) {
{version: "1.2.3", roles: agentRoles, updateGroup: "default"},
{version: "1.2.3", roles: agentRoles, updateGroup: "default"},
},
- expected: &autoupdatev1pb.AutoUpdateAgentReportSpec{
+ expected: autoupdatev1pb.AutoUpdateAgentReportSpec_builder{
Timestamp: timestamppb.New(now),
Groups: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroup{
- "default": {
+ "default": autoupdatev1pb.AutoUpdateAgentReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion{
- "1.2.3": {Count: 4},
+ "1.2.3": autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{Count: 4}.Build(),
},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
{
name: "control plane servers are ignored",
@@ -137,16 +137,16 @@ func TestServer_generateAgentVersionReport(t *testing.T) {
{version: "1.2.3", roles: types.SystemRoles{types.RoleApp, types.RoleProxy}, updateGroup: "default"},
{version: "1.2.3", roles: types.SystemRoles{types.RoleApp, types.RoleKube}, updateGroup: "default"},
},
- expected: &autoupdatev1pb.AutoUpdateAgentReportSpec{
+ expected: autoupdatev1pb.AutoUpdateAgentReportSpec_builder{
Timestamp: timestamppb.New(now),
Groups: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroup{
- "default": {
+ "default": autoupdatev1pb.AutoUpdateAgentReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion{
- "1.2.3": {Count: 1},
+ "1.2.3": autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
{
name: "disabled or pinned updaters are ignored",
@@ -155,38 +155,38 @@ func TestServer_generateAgentVersionReport(t *testing.T) {
{version: "1.2.3", roles: agentRoles, updaterStatus: types.UpdaterStatus_UPDATER_STATUS_PINNED, updateGroup: "default"},
{version: "1.2.3", roles: agentRoles, updaterStatus: types.UpdaterStatus_UPDATER_STATUS_DISABLED, updateGroup: "default"},
},
- expected: &autoupdatev1pb.AutoUpdateAgentReportSpec{
+ expected: autoupdatev1pb.AutoUpdateAgentReportSpec_builder{
Timestamp: timestamppb.New(now),
Groups: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroup{
- "default": {
+ "default": autoupdatev1pb.AutoUpdateAgentReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion{
- "1.2.3": {Count: 1},
+ "1.2.3": autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
+ }.Build(),
},
Omitted: []*autoupdatev1pb.AutoUpdateAgentReportSpecOmitted{
- {Reason: omissionReasonUpdaterPinned, Count: 1},
- {Reason: omissionReasonUpdaterDisabled, Count: 1},
+ autoupdatev1pb.AutoUpdateAgentReportSpecOmitted_builder{Reason: omissionReasonUpdaterPinned, Count: 1}.Build(),
+ autoupdatev1pb.AutoUpdateAgentReportSpecOmitted_builder{Reason: omissionReasonUpdaterDisabled, Count: 1}.Build(),
},
- },
+ }.Build(),
},
{
name: "reloaded and terminating instances are ignored",
fixtures: []fakeServer{
{version: "1.2.3", roles: agentRoles, updaterStatus: updaterOK, updateGroup: "default"},
- {version: "1.2.3", roles: agentRoles, updaterStatus: updaterOK, updateGroup: "default", goodbye: &proto.UpstreamInventoryGoodbye{SoftReload: true}},
- {version: "1.2.3", roles: agentRoles, updaterStatus: updaterOK, updateGroup: "default", goodbye: &proto.UpstreamInventoryGoodbye{DeleteResources: true}},
+ {version: "1.2.3", roles: agentRoles, updaterStatus: updaterOK, updateGroup: "default", goodbye: proto.UpstreamInventoryGoodbye_builder{SoftReload: true}.Build()},
+ {version: "1.2.3", roles: agentRoles, updaterStatus: updaterOK, updateGroup: "default", goodbye: proto.UpstreamInventoryGoodbye_builder{DeleteResources: true}.Build()},
},
- expected: &autoupdatev1pb.AutoUpdateAgentReportSpec{
+ expected: autoupdatev1pb.AutoUpdateAgentReportSpec_builder{
Timestamp: timestamppb.New(now),
Groups: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroup{
- "default": {
+ "default": autoupdatev1pb.AutoUpdateAgentReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion{
- "1.2.3": {Count: 1},
+ "1.2.3": autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
{
name: "too recent servers are ignored",
@@ -196,16 +196,16 @@ func TestServer_generateAgentVersionReport(t *testing.T) {
{version: "1.2.3", roles: agentRoles, updaterStatus: updaterOK, updateGroup: "default"},
{version: "1.2.3", roles: agentRoles, updaterStatus: updaterOK, updateGroup: "default"},
},
- expected: &autoupdatev1pb.AutoUpdateAgentReportSpec{
+ expected: autoupdatev1pb.AutoUpdateAgentReportSpec_builder{
Timestamp: timestamppb.New(now),
Groups: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroup{
- "default": {
+ "default": autoupdatev1pb.AutoUpdateAgentReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion{
- "1.2.3": {Count: 1},
+ "1.2.3": autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
{
name: "multiple versions and groups",
@@ -216,27 +216,27 @@ func TestServer_generateAgentVersionReport(t *testing.T) {
{version: "1.2.5", updateGroup: "prod", roles: agentRoles, updaterStatus: updaterOK},
{version: "1.2.5", updateGroup: "dev", roles: agentRoles, updaterStatus: updaterOK},
},
- expected: &autoupdatev1pb.AutoUpdateAgentReportSpec{
+ expected: autoupdatev1pb.AutoUpdateAgentReportSpec_builder{
Timestamp: timestamppb.New(now),
Groups: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroup{
- "default": {
+ "default": autoupdatev1pb.AutoUpdateAgentReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion{
- "1.2.3": {Count: 1},
- "1.2.4": {Count: 1},
+ "1.2.3": autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{Count: 1}.Build(),
+ "1.2.4": autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
- "dev": {
+ }.Build(),
+ "dev": autoupdatev1pb.AutoUpdateAgentReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion{
- "1.2.5": {Count: 1},
+ "1.2.5": autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
- "prod": {
+ }.Build(),
+ "prod": autoupdatev1pb.AutoUpdateAgentReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion{
- "1.2.5": {Count: 2},
+ "1.2.5": autoupdatev1pb.AutoUpdateAgentReportSpecGroupVersion_builder{Count: 2}.Build(),
},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
}
for _, tt := range tests {
@@ -265,13 +265,13 @@ func TestServer_generateAgentVersionReport(t *testing.T) {
if status == types.UpdaterStatus_UPDATER_STATUS_UNSPECIFIED {
status = types.UpdaterStatus_UPDATER_STATUS_OK
}
- controller.RegisterControlStream(stream, &proto.UpstreamInventoryHello{
+ controller.RegisterControlStream(stream, proto.UpstreamInventoryHello_builder{
Services: fixture.roles.StringSlice(),
ServerID: uuid.New().String(),
Version: fixture.version,
ExternalUpgrader: types.UpgraderKindTeleportUpdate,
UpdaterInfo: &types.UpdaterV2Info{UpdaterStatus: status, UpdateGroup: fixture.updateGroup},
- })
+ }.Build())
if fixture.goodbye != nil {
// Sending the message twice is a little hack to make sure that the auth received the goodbye at
// least once. Else, the auth might still be in the small frame when it received the message
@@ -335,7 +335,7 @@ func TestServer_reportAgentVersions(t *testing.T) {
for range testNodeCount {
stream := newFakeControlStream()
- controller.RegisterControlStream(stream, &proto.UpstreamInventoryHello{
+ controller.RegisterControlStream(stream, proto.UpstreamInventoryHello_builder{
Services: types.SystemRoles{types.RoleNode}.StringSlice(),
Version: "1.2.3",
ServerID: uuid.NewString(),
@@ -344,18 +344,18 @@ func TestServer_reportAgentVersions(t *testing.T) {
UpdaterStatus: types.UpdaterStatus_UPDATER_STATUS_OK,
UpdateGroup: "default",
},
- })
+ }.Build())
t.Cleanup(stream.close)
}
ctx := context.Background()
- rollout, err := autoupdate.NewAutoUpdateAgentRollout(&autoupdatev1pb.AutoUpdateAgentRolloutSpec{
+ rollout, err := autoupdate.NewAutoUpdateAgentRollout(autoupdatev1pb.AutoUpdateAgentRolloutSpec_builder{
StartVersion: "1.2.3",
TargetVersion: "1.2.4",
Schedule: autoupdate.AgentsScheduleRegular,
AutoupdateMode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyHaltOnError,
MaintenanceWindowDuration: nil,
- })
+ }.Build())
require.NoError(t, err)
_, err = svc.CreateAutoUpdateAgentRollout(ctx, rollout)
require.NoError(t, err)
diff --git a/lib/auth/autoupdate_rollout.go b/lib/auth/autoupdate_rollout.go
index c3371c80f9a..e0f9468e88f 100644
--- a/lib/auth/autoupdate_rollout.go
+++ b/lib/auth/autoupdate_rollout.go
@@ -55,7 +55,7 @@ func (a *Server) SampleAgentsFromAutoUpdateGroup(ctx context.Context, groupName
}
// If the agent group matches, we keep it.
- if handle.Hello().UpdaterInfo.UpdateGroup == groupName {
+ if handle.Hello().GetUpdaterInfo().UpdateGroup == groupName {
// No need to check for UpdaterInfo being nil, it would have been filtered
// out by filterHandler().
return true
@@ -67,7 +67,7 @@ func (a *Server) SampleAgentsFromAutoUpdateGroup(ctx context.Context, groupName
}
// This is the catch-call group, it matches agents from every group not in groups.
- _, ok := groupSet[handle.Hello().UpdaterInfo.UpdateGroup]
+ _, ok := groupSet[handle.Hello().GetUpdaterInfo().UpdateGroup]
// If the agent group is not in the group list, it falls into the catch-all.
return !ok
}
@@ -80,16 +80,16 @@ func (a *Server) SampleAgentsFromAutoUpdateGroup(ctx context.Context, groupName
canaries := make([]*autoupdatev1pb.Canary, 0, len(sampled))
for _, h := range sampled {
hello := h.Hello()
- updaterID, err := uuid.FromBytes(hello.UpdaterInfo.UpdateUUID)
+ updaterID, err := uuid.FromBytes(hello.GetUpdaterInfo().UpdateUUID)
if err != nil {
return nil, trace.Wrap(err)
}
- canaries = append(canaries, &autoupdatev1pb.Canary{
+ canaries = append(canaries, autoupdatev1pb.Canary_builder{
UpdaterId: updaterID.String(),
- HostId: hello.ServerID,
- Hostname: hello.Hostname,
+ HostId: hello.GetServerID(),
+ Hostname: hello.GetHostname(),
Success: false,
- })
+ }.Build())
}
return canaries, nil
}
diff --git a/lib/auth/autoupdate_rollout_test.go b/lib/auth/autoupdate_rollout_test.go
index 65fded882c8..f0752175c94 100644
--- a/lib/auth/autoupdate_rollout_test.go
+++ b/lib/auth/autoupdate_rollout_test.go
@@ -75,7 +75,7 @@ func TestSampleAgentsFromGroup(t *testing.T) {
for range testNodeCount {
updaterID := uuid.New()
stream := newFakeControlStream()
- controller.RegisterControlStream(stream, &proto.UpstreamInventoryHello{
+ controller.RegisterControlStream(stream, proto.UpstreamInventoryHello_builder{
Services: types.SystemRoles{types.RoleNode}.StringSlice(),
Version: "1.2.3",
ServerID: uuid.NewString(),
@@ -85,7 +85,7 @@ func TestSampleAgentsFromGroup(t *testing.T) {
UpdaterStatus: types.UpdaterStatus_UPDATER_STATUS_OK,
UpdateGroup: testGroupName,
},
- })
+ }.Build())
t.Cleanup(stream.close)
}
@@ -101,7 +101,7 @@ func TestSampleAgentsFromGroup(t *testing.T) {
// Test execution: check that there were no duplicates in the samples
canarySet := make(map[string]*autoupdatev1pb.Canary)
for _, canary := range canaries {
- canarySet[canary.UpdaterId] = canary
+ canarySet[canary.GetUpdaterId()] = canary
}
require.Len(t, canarySet, sampleSize, "some canary got duplicated")
@@ -110,14 +110,14 @@ func TestSampleAgentsFromGroup(t *testing.T) {
require.Len(t, canaries2, sampleSize)
canarySet = make(map[string]*autoupdatev1pb.Canary)
for _, canary := range canaries2 {
- canarySet[canary.UpdaterId] = canary
+ canarySet[canary.GetUpdaterId()] = canary
}
require.Len(t, canarySet, sampleSize, "some canary got duplicated")
// Text execution: check that the random looks sane
var conflicts int
for i := range sampleSize {
- if canaries[i].UpdaterId == canaries2[i].UpdaterId {
+ if canaries[i].GetUpdaterId() == canaries2[i].GetUpdaterId() {
conflicts++
}
}
@@ -131,7 +131,7 @@ func TestSampleAgentsFromGroup(t *testing.T) {
require.Len(t, canariesCatchAll, sampleSize)
canarySet = make(map[string]*autoupdatev1pb.Canary)
for _, canary := range canariesCatchAll {
- canarySet[canary.UpdaterId] = canary
+ canarySet[canary.GetUpdaterId()] = canary
}
require.Len(t, canarySet, sampleSize, "some canary got duplicated")
@@ -141,7 +141,7 @@ func TestSampleAgentsFromGroup(t *testing.T) {
require.Len(t, canariesCatchAll, sampleSize)
canarySet = make(map[string]*autoupdatev1pb.Canary)
for _, canary := range canariesCatchAll {
- canarySet[canary.UpdaterId] = canary
+ canarySet[canary.GetUpdaterId()] = canary
}
require.Len(t, canarySet, sampleSize, "some canary got duplicated")
}
@@ -181,7 +181,7 @@ func TestLookupAgentInInventory(t *testing.T) {
updaterID := uuid.New()
hellos := make([]*proto.UpstreamInventoryHello, i+1)
for j := range i + 1 {
- hello := &proto.UpstreamInventoryHello{
+ hello := proto.UpstreamInventoryHello_builder{
Services: types.SystemRoles{types.RoleNode}.StringSlice(),
Version: fmt.Sprintf("1.2.%d", j),
ServerID: hostID,
@@ -191,7 +191,7 @@ func TestLookupAgentInInventory(t *testing.T) {
UpdaterStatus: types.UpdaterStatus_UPDATER_STATUS_OK,
UpdateGroup: testGroupName,
},
- }
+ }.Build()
hellos[j] = hello
stream := newFakeControlStream()
@@ -207,7 +207,7 @@ func TestLookupAgentInInventory(t *testing.T) {
// and content matches.
opts := cmp.Options{
- cmpopts.SortSlices(func(a, b *proto.UpstreamInventoryHello) bool { return a.Version > b.Version }),
+ cmpopts.SortSlices(func(a, b *proto.UpstreamInventoryHello) bool { return a.GetVersion() > b.GetVersion() }),
protocmp.Transform(),
}
for hostID, handles := range hosts {
@@ -223,9 +223,9 @@ type fakeHandle struct {
}
func (f *fakeHandle) Hello() *proto.UpstreamInventoryHello {
- return &proto.UpstreamInventoryHello{
+ return proto.UpstreamInventoryHello_builder{
Hostname: fmt.Sprintf("hostname-%d", f.id),
- }
+ }.Build()
}
func TestHandlerSampler(t *testing.T) {
@@ -290,7 +290,7 @@ func TestHandlerSampler(t *testing.T) {
require.Len(t, reservoir, 5)
for i, h := range reservoir {
expectedHostname := fmt.Sprintf("hostname-%d", i)
- require.Equal(t, expectedHostname, h.Hello().Hostname)
+ require.Equal(t, expectedHostname, h.Hello().GetHostname())
}
},
},
diff --git a/lib/auth/bot.go b/lib/auth/bot.go
index e55c22d095d..4f7b01d573c 100644
--- a/lib/auth/bot.go
+++ b/lib/auth/bot.go
@@ -337,10 +337,10 @@ func (a *Server) updateBotInstance(
return trace.Wrap(err)
} else {
// We have an existing instance, so fetch its generation.
- auths := existingInstance.Status.LatestAuthentications
+ auths := existingInstance.GetStatus().GetLatestAuthentications()
if len(auths) > 0 {
latest := auths[len(auths)-1]
- instanceGeneration = latest.Generation
+ instanceGeneration = latest.GetGeneration()
}
}
}
@@ -357,19 +357,19 @@ func (a *Server) updateBotInstance(
}
}
- authRecord := &machineidv1pb.BotInstanceStatusAuthentication{
+ authRecord := machineidv1pb.BotInstanceStatusAuthentication_builder{
AuthenticatedAt: timestamppb.New(a.GetClock().Now()),
PublicKey: publicKeyPEM,
// Note: This is presumed to be a token join. If not, a
// `templateAuthRecord` should be provided to override this value.
JoinMethod: string(types.JoinMethodToken),
- }
+ }.Build()
if templateAuthRecord != nil {
- authRecord.JoinToken = templateAuthRecord.JoinToken
- authRecord.JoinMethod = templateAuthRecord.JoinMethod
- authRecord.JoinAttrs = templateAuthRecord.JoinAttrs
+ authRecord.SetJoinToken(templateAuthRecord.GetJoinToken())
+ authRecord.SetJoinMethod(templateAuthRecord.GetJoinMethod())
+ authRecord.SetJoinAttrs(templateAuthRecord.GetJoinAttrs())
}
// An empty bot instance most likely means a bot is rejoining after an
@@ -403,11 +403,11 @@ func (a *Server) updateBotInstance(
}
// Copy the value from the request into the auth record.
- authRecord.Generation = int32(req.Generation)
+ authRecord.SetGeneration(int32(req.Generation))
} else {
// Otherwise, just set it to 1.
req.Generation = 1
- authRecord.Generation = 1
+ authRecord.SetGeneration(1)
}
a.logger.InfoContext(ctx, "bot has no valid instance ID, a new instance will be generated",
@@ -418,11 +418,11 @@ func (a *Server) updateBotInstance(
expires := a.GetClock().Now().Add(req.TTL + machineidv1.ExpiryMargin)
- bi := newBotInstance(&machineidv1pb.BotInstanceSpec{
+ bi := newBotInstance(machineidv1pb.BotInstanceSpec_builder{
BotName: botName,
InstanceId: instanceID.String(),
- }, authRecord, expires)
- bi.Scope = scope
+ }.Build(), authRecord, expires)
+ bi.SetScope(scope)
if _, err := a.BotInstance.CreateBotInstance(ctx, bi); err != nil {
return trace.Wrap(err)
@@ -447,7 +447,7 @@ func (a *Server) updateBotInstance(
} else if currentIdentityGeneration > 0 && currentIdentityGeneration != instanceGeneration {
// Generation counter enforcement depends on the type of cert and join
// method (if any - token renewals technically have no join method.)
- if shouldEnforceGenerationCounter(req.Renewable, authRecord.JoinMethod) {
+ if shouldEnforceGenerationCounter(req.Renewable, authRecord.GetJoinMethod()) {
if err := a.tryLockBotDueToGenerationMismatch(ctx, botName, botInstanceID, req.JoinToken, req.Renewable); err != nil {
log.WarnContext(ctx, "Failed to lock bot when a generation mismatch was detected", "error", err)
}
@@ -466,7 +466,7 @@ func (a *Server) updateBotInstance(
log.WarnContext(ctx, msg,
"bot_instance_generation", instanceGeneration,
"bot_identity_generation", currentIdentityGeneration,
- "bot_join_method", authRecord.JoinMethod,
+ "bot_join_method", authRecord.GetJoinMethod(),
)
}
}
@@ -474,7 +474,7 @@ func (a *Server) updateBotInstance(
// Increment the generation counter the cert and bot instance. The counter
// should be incremented and stored even if it is not validated above.
newGeneration := instanceGeneration + 1
- authRecord.Generation = newGeneration
+ authRecord.SetGeneration(newGeneration)
req.Generation = uint64(newGeneration)
// Commit the generation counter to the bot user for downgrade
@@ -490,29 +490,29 @@ func (a *Server) updateBotInstance(
}
_, err := a.BotInstance.PatchBotInstance(ctx, botName, botInstanceID, func(bi *machineidv1pb.BotInstance) (*machineidv1pb.BotInstance, error) {
- if bi.Status == nil {
- bi.Status = &machineidv1pb.BotInstanceStatus{}
+ if !bi.HasStatus() {
+ bi.SetStatus(&machineidv1pb.BotInstanceStatus{})
}
// Update the record's expiration timestamp based on the request TTL
// plus an expiry margin.
- bi.Metadata.Expires = timestamppb.New(a.GetClock().Now().Add(req.TTL + machineidv1.ExpiryMargin))
+ bi.GetMetadata().SetExpires(timestamppb.New(a.GetClock().Now().Add(req.TTL + machineidv1.ExpiryMargin)))
// If we're at or above the limit, remove enough of the front elements
// to make room for the new one at the end.
- if len(bi.Status.LatestAuthentications) >= machineidv1.AuthenticationHistoryLimit {
- toRemove := len(bi.Status.LatestAuthentications) - machineidv1.AuthenticationHistoryLimit + 1
- bi.Status.LatestAuthentications = bi.Status.LatestAuthentications[toRemove:]
+ if len(bi.GetStatus().GetLatestAuthentications()) >= machineidv1.AuthenticationHistoryLimit {
+ toRemove := len(bi.GetStatus().GetLatestAuthentications()) - machineidv1.AuthenticationHistoryLimit + 1
+ bi.GetStatus().SetLatestAuthentications(bi.GetStatus().GetLatestAuthentications()[toRemove:])
}
// An initial auth record should have been added during initial join,
// but if not, add it now.
- if bi.Status.InitialAuthentication == nil {
+ if !bi.GetStatus().HasInitialAuthentication() {
log.WarnContext(ctx, "bot instance is missing its initial authentication record, a new one will be added")
- bi.Status.InitialAuthentication = authRecord
+ bi.GetStatus().SetInitialAuthentication(authRecord)
}
- bi.Status.LatestAuthentications = append(bi.Status.LatestAuthentications, authRecord)
+ bi.GetStatus().SetLatestAuthentications(append(bi.GetStatus().GetLatestAuthentications(), authRecord))
return bi, nil
})
@@ -526,18 +526,18 @@ func newBotInstance(
initialAuth *machineidv1pb.BotInstanceStatusAuthentication,
expires time.Time,
) *machineidv1pb.BotInstance {
- return &machineidv1pb.BotInstance{
+ return machineidv1pb.BotInstance_builder{
Kind: types.KindBotInstance,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Expires: timestamppb.New(expires),
- },
+ }.Build(),
Spec: spec,
- Status: &machineidv1pb.BotInstanceStatus{
+ Status: machineidv1pb.BotInstanceStatus_builder{
InitialAuthentication: initialAuth,
LatestAuthentications: []*machineidv1pb.BotInstanceStatusAuthentication{initialAuth},
- },
- }
+ }.Build(),
+ }.Build()
}
// generateInitialBotCerts is used to generate bot certs and overlaps
@@ -620,7 +620,7 @@ func (a *Server) generateInitialBotCerts(
// token-joined bots and it's a secret value, so we don't bother setting it.
// (The renewable flag implies token joining.)
if !renewable {
- certReq.JoinToken = initialAuth.JoinToken
+ certReq.JoinToken = initialAuth.GetJoinToken()
}
if existingInstanceID == "" {
@@ -630,14 +630,14 @@ func (a *Server) generateInitialBotCerts(
return nil, "", trace.Wrap(err)
}
- initialAuth.Generation = 1
+ initialAuth.SetGeneration(1)
- bi := newBotInstance(&machineidv1pb.BotInstanceSpec{
+ bi := newBotInstance(machineidv1pb.BotInstanceSpec_builder{
BotName: botName,
InstanceId: uuid.String(),
PreviousInstanceId: previousInstanceID,
- }, initialAuth, expires.Add(machineidv1.ExpiryMargin))
- bi.Scope = botScope
+ }.Build(), initialAuth, expires.Add(machineidv1.ExpiryMargin))
+ bi.SetScope(botScope)
_, err = a.BotInstance.CreateBotInstance(ctx, bi)
if err != nil {
diff --git a/lib/auth/bot_test.go b/lib/auth/bot_test.go
index e3d5ab01077..be3c359f839 100644
--- a/lib/auth/bot_test.go
+++ b/lib/auth/bot_test.go
@@ -138,23 +138,23 @@ func TestRegisterBotCertificateGenerationCheck(t *testing.T) {
// Create a new bot.
client, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- bot, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ bot, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
token, err := types.NewProvisionTokenFromSpec("testxyzzy", time.Time{}, types.ProvisionTokenSpecV2{
Roles: types.SystemRoles{types.RoleBot},
- BotName: bot.Metadata.Name,
+ BotName: bot.GetMetadata().GetName(),
})
require.NoError(t, err)
require.NoError(t, client.CreateToken(ctx, token))
@@ -188,18 +188,18 @@ func TestRegisterBotCertificateGenerationCheck(t *testing.T) {
// There should always be at least 1 entry as the initial join is
// duplicated in the list.
- require.Len(t, bi.Status.LatestAuthentications, min(i+1, machineidv1.AuthenticationHistoryLimit))
+ require.Len(t, bi.GetStatus().GetLatestAuthentications(), min(i+1, machineidv1.AuthenticationHistoryLimit))
// Generation starts at 1 for initial certs.
- latest := bi.Status.LatestAuthentications[len(bi.Status.LatestAuthentications)-1]
- require.Equal(t, int32(i+1), latest.Generation)
+ latest := bi.GetStatus().GetLatestAuthentications()[len(bi.GetStatus().GetLatestAuthentications())-1]
+ require.Equal(t, int32(i+1), latest.GetGeneration())
- lastExpires := bi.Metadata.Expires.AsTime()
+ lastExpires := bi.GetMetadata().GetExpires().AsTime()
// Advance the clock a bit.
fakeClock.Advance(time.Minute)
- _, certs, err = renewBotCerts(ctx, srv, certs.TLS, bot.Status.UserName, result.PrivateKey)
+ _, certs, err = renewBotCerts(ctx, srv, certs.TLS, bot.GetStatus().GetUserName(), result.PrivateKey)
require.NoError(t, err)
// Parse the Identity
@@ -222,12 +222,12 @@ func TestRegisterBotCertificateGenerationCheck(t *testing.T) {
bi, err = srv.Auth().BotInstance.GetBotInstance(ctx, initialIdent.BotName, initialIdent.BotInstanceID)
require.NoError(t, err)
- require.Len(t, bi.Status.LatestAuthentications, min(i+2, machineidv1.AuthenticationHistoryLimit))
+ require.Len(t, bi.GetStatus().GetLatestAuthentications(), min(i+2, machineidv1.AuthenticationHistoryLimit))
- latest = bi.Status.LatestAuthentications[len(bi.Status.LatestAuthentications)-1]
- require.Equal(t, int32(i+2), latest.Generation)
+ latest = bi.GetStatus().GetLatestAuthentications()[len(bi.GetStatus().GetLatestAuthentications())-1]
+ require.Equal(t, int32(i+2), latest.GetGeneration())
- require.True(t, bi.Metadata.Expires.AsTime().After(lastExpires), "Metadata.Expires must be extended")
+ require.True(t, bi.GetMetadata().GetExpires().AsTime().After(lastExpires), "Metadata.Expires must be extended")
}
}
@@ -250,18 +250,18 @@ func TestBotJoinAttrs_Kubernetes(t *testing.T) {
// Create a new bot.
client, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- bot, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ bot, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
k8s, err := fakeissuer.NewKubernetesSigner(srv.Clock())
@@ -282,7 +282,7 @@ func TestBotJoinAttrs_Kubernetes(t *testing.T) {
types.ProvisionTokenSpecV2{
Roles: types.SystemRoles{types.RoleBot},
JoinMethod: types.JoinMethodKubernetes,
- BotName: bot.Metadata.Name,
+ BotName: bot.GetMetadata().GetName(),
Kubernetes: &types.ProvisionTokenSpecV2Kubernetes{
Type: types.KubernetesJoinTypeStaticJWKS,
StaticJWKS: &types.ProvisionTokenSpecV2Kubernetes_StaticJWKSConfig{
@@ -317,22 +317,22 @@ func TestBotJoinAttrs_Kubernetes(t *testing.T) {
require.NoError(t, err)
ident, err := tlsca.FromSubject(cert.Subject, cert.NotAfter)
require.NoError(t, err)
- wantAttrs := &workloadidentityv1pb.JoinAttrs{
- Meta: &workloadidentityv1pb.JoinAttrsMeta{
+ wantAttrs := workloadidentityv1pb.JoinAttrs_builder{
+ Meta: workloadidentityv1pb.JoinAttrsMeta_builder{
JoinTokenName: tok.GetName(),
JoinMethod: string(types.JoinMethodKubernetes),
- },
- Kubernetes: &workloadidentityv1pb.JoinAttrsKubernetes{
- ServiceAccount: &workloadidentityv1pb.JoinAttrsKubernetesServiceAccount{
+ }.Build(),
+ Kubernetes: workloadidentityv1pb.JoinAttrsKubernetes_builder{
+ ServiceAccount: workloadidentityv1pb.JoinAttrsKubernetesServiceAccount_builder{
Namespace: "my-namespace",
Name: "my-service-account",
- },
- Pod: &workloadidentityv1pb.JoinAttrsKubernetesPod{
+ }.Build(),
+ Pod: workloadidentityv1pb.JoinAttrsKubernetesPod_builder{
Name: "my-pod",
- },
+ }.Build(),
Subject: "system:serviceaccount:my-namespace:my-service-account",
- },
- }
+ }.Build(),
+ }.Build()
require.Empty(t, cmp.Diff(
ident.JoinAttributes,
wantAttrs,
@@ -354,7 +354,7 @@ func TestBotJoinAttrs_Kubernetes(t *testing.T) {
roleCerts, err := botClient.GenerateUserCerts(ctx, proto.UserCertsRequest{
SSHPublicKey: ssh.MarshalAuthorizedKey(sshPub),
TLSPublicKey: tlsPub,
- Username: bot.Status.UserName,
+ Username: bot.GetStatus().GetUserName(),
RoleRequests: []string{
role.GetName(),
},
@@ -390,23 +390,23 @@ func TestRegisterBotInstance(t *testing.T) {
// Create a new bot.
client, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- bot, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ bot, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
token, err := types.NewProvisionTokenFromSpec("testxyzzy", time.Time{}, types.ProvisionTokenSpecV2{
Roles: types.SystemRoles{types.RoleBot},
- BotName: bot.Metadata.Name,
+ BotName: bot.GetMetadata().GetName(),
})
require.NoError(t, err)
require.NoError(t, client.CreateToken(ctx, token))
@@ -433,19 +433,19 @@ func TestRegisterBotInstance(t *testing.T) {
botInstance, err := srv.Auth().BotInstance.GetBotInstance(ctx, ident.BotName, ident.BotInstanceID)
require.NoError(t, err)
- require.Equal(t, ident.BotName, botInstance.GetSpec().BotName)
- require.Equal(t, ident.BotInstanceID, botInstance.GetSpec().InstanceId)
+ require.Equal(t, ident.BotName, botInstance.GetSpec().GetBotName())
+ require.Equal(t, ident.BotInstanceID, botInstance.GetSpec().GetInstanceId())
// The initial authentication record should be sane
- ia := botInstance.GetStatus().InitialAuthentication
+ ia := botInstance.GetStatus().GetInitialAuthentication()
require.NotNil(t, ia)
- require.Equal(t, int32(1), ia.Generation)
- require.Equal(t, string(types.JoinMethodToken), ia.JoinMethod)
- require.Equal(t, token.GetSafeName(), ia.JoinToken)
+ require.Equal(t, int32(1), ia.GetGeneration())
+ require.Equal(t, string(types.JoinMethodToken), ia.GetJoinMethod())
+ require.Equal(t, token.GetSafeName(), ia.GetJoinToken())
// The latest authentications field should contain the same record (and
// only that record.)
- require.Len(t, botInstance.GetStatus().LatestAuthentications, 1)
- require.EqualExportedValues(t, ia, botInstance.GetStatus().LatestAuthentications[0])
+ require.Len(t, botInstance.GetStatus().GetLatestAuthentications(), 1)
+ require.EqualExportedValues(t, ia, botInstance.GetStatus().GetLatestAuthentications()[0])
// Validate that expected audit events were emitted...
auditEvents := mockEmitter.Events()
@@ -537,23 +537,23 @@ func TestRegisterBotCertificateGenerationStolen(t *testing.T) {
// Create a new bot.
client, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- bot, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ bot, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
token, err := types.NewProvisionTokenFromSpec("testxyzzy", time.Time{}, types.ProvisionTokenSpecV2{
Roles: types.SystemRoles{types.RoleBot},
- BotName: bot.Metadata.Name,
+ BotName: bot.GetMetadata().GetName(),
})
require.NoError(t, err)
require.NoError(t, client.CreateToken(ctx, token))
@@ -568,7 +568,7 @@ func TestRegisterBotCertificateGenerationStolen(t *testing.T) {
require.NoError(t, err)
// Renew the certs once (e.g. this is the actual bot process)
- renewedClient, certsReal, err := renewBotCerts(ctx, srv, result.Certs.TLS, bot.Status.UserName, result.PrivateKey)
+ renewedClient, certsReal, err := renewBotCerts(ctx, srv, result.Certs.TLS, bot.GetStatus().GetUserName(), result.PrivateKey)
require.NoError(t, err)
// This client should be able to ping.
@@ -583,7 +583,7 @@ func TestRegisterBotCertificateGenerationStolen(t *testing.T) {
require.Equal(t, uint64(2), impersonatedIdent.Generation)
// Meanwhile, the initial set of certs was stolen. Let's try to renew those.
- _, _, err = renewBotCerts(ctx, srv, result.Certs.TLS, bot.Status.UserName, result.PrivateKey)
+ _, _, err = renewBotCerts(ctx, srv, result.Certs.TLS, bot.GetStatus().GetUserName(), result.PrivateKey)
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
@@ -613,23 +613,23 @@ func TestRegisterBotCertificateExtensions(t *testing.T) {
// Create a new bot.
client, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- bot, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ bot, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
token, err := types.NewProvisionTokenFromSpec("testxyzzy", time.Time{}, types.ProvisionTokenSpecV2{
Roles: types.SystemRoles{types.RoleBot},
- BotName: bot.Metadata.Name,
+ BotName: bot.GetMetadata().GetName(),
})
require.NoError(t, err)
require.NoError(t, client.CreateToken(ctx, token))
@@ -644,7 +644,7 @@ func TestRegisterBotCertificateExtensions(t *testing.T) {
require.NoError(t, err)
checkCertLoginIP(t, result.Certs.TLS, "127.0.0.1")
- _, certs, err := renewBotCerts(ctx, srv, result.Certs.TLS, bot.Status.UserName, result.PrivateKey)
+ _, certs, err := renewBotCerts(ctx, srv, result.Certs.TLS, bot.GetStatus().GetUserName(), result.PrivateKey)
require.NoError(t, err)
// Parse the Identity
@@ -677,16 +677,16 @@ func TestRegisterBot_RemoteAddr(t *testing.T) {
require.NoError(t, err)
botName := "botty"
- _, err = machineidv1.UpsertBot(ctx, a, &machineidv1pb.Bot{
+ _, err = machineidv1.UpsertBot(ctx, a, machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: botName,
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{roleName},
- },
- }, a.GetClock().Now(), "", scopes.Features{})
+ }.Build(),
+ }.Build(), a.GetClock().Now(), "", scopes.Features{})
require.NoError(t, err)
remoteAddr := "42.42.42.42:42"
@@ -935,16 +935,16 @@ func TestRegisterBot_BotInstanceRejoin(t *testing.T) {
require.NoError(t, err)
botName := "bot"
- _, err = machineidv1.UpsertBot(ctx, a, &machineidv1pb.Bot{
+ _, err = machineidv1.UpsertBot(ctx, a, machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: botName,
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{roleName},
- },
- }, a.GetClock().Now(), "", scopes.Features{})
+ }.Build(),
+ }.Build(), a.GetClock().Now(), "", scopes.Features{})
require.NoError(t, err)
// Create k8s and IAM join tokens
@@ -1091,16 +1091,16 @@ func TestRegisterBotWithInvalidInstanceID(t *testing.T) {
_, err = authtest.CreateRole(ctx, a, roleName, types.RoleSpecV6{})
require.NoError(t, err)
- _, err = machineidv1.UpsertBot(ctx, a, &machineidv1pb.Bot{
+ _, err = machineidv1.UpsertBot(ctx, a, machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: botName,
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{roleName},
- },
- }, a.GetClock().Now(), "", scopes.Features{})
+ }.Build(),
+ }.Build(), a.GetClock().Now(), "", scopes.Features{})
require.NoError(t, err)
client, err := srv.NewClient(authtest.TestAdmin())
@@ -1169,30 +1169,30 @@ func TestRegisterBotMultipleTokens(t *testing.T) {
// Initial setup, create a bot and join token.
client, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- bot, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ bot, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tokenA, err := types.NewProvisionTokenFromSpec("a", time.Time{}, types.ProvisionTokenSpecV2{
Roles: types.SystemRoles{types.RoleBot},
- BotName: bot.Metadata.Name,
+ BotName: bot.GetMetadata().GetName(),
})
require.NoError(t, err)
require.NoError(t, client.CreateToken(ctx, tokenA))
tokenB, err := types.NewProvisionTokenFromSpec("b", time.Time{}, types.ProvisionTokenSpecV2{
Roles: types.SystemRoles{types.RoleBot},
- BotName: bot.Metadata.Name,
+ BotName: bot.GetMetadata().GetName(),
})
require.NoError(t, err)
require.NoError(t, client.CreateToken(ctx, tokenB))
@@ -1226,7 +1226,7 @@ func TestRegisterBotMultipleTokens(t *testing.T) {
require.NotEqual(t, initialInstanceA, initialInstanceB)
for i := range 6 {
- _, certsA, err = renewBotCerts(ctx, srv, certsA.TLS, bot.Status.UserName, resultA.PrivateKey)
+ _, certsA, err = renewBotCerts(ctx, srv, certsA.TLS, bot.GetStatus().GetUserName(), resultA.PrivateKey)
require.NoError(t, err)
instanceA, generationA := instanceIDFromCerts(t, certsA)
@@ -1235,7 +1235,7 @@ func TestRegisterBotMultipleTokens(t *testing.T) {
// Only renew bot B 3x.
if i < 3 {
- _, certsB, err = renewBotCerts(ctx, srv, certsB.TLS, bot.Status.UserName, resultB.PrivateKey)
+ _, certsB, err = renewBotCerts(ctx, srv, certsB.TLS, bot.GetStatus().GetUserName(), resultB.PrivateKey)
require.NoError(t, err)
instanceB, generationB := instanceIDFromCerts(t, certsB)
@@ -1247,14 +1247,14 @@ func TestRegisterBotMultipleTokens(t *testing.T) {
// Renew B again. This will be the final renewal, but the legacy generation
// counter on the user will be greater as it should have been incremented by
// bot A.
- _, certsB, err = renewBotCerts(ctx, srv, certsB.TLS, bot.Status.UserName, resultB.PrivateKey)
+ _, certsB, err = renewBotCerts(ctx, srv, certsB.TLS, bot.GetStatus().GetUserName(), resultB.PrivateKey)
require.NoError(t, err)
instanceB, generationB := instanceIDFromCerts(t, certsB)
require.Equal(t, initialInstanceB, instanceB)
require.Equal(t, uint64(5), generationB)
- botUser, err := client.GetUser(ctx, bot.Status.UserName, false)
+ botUser, err := client.GetUser(ctx, bot.GetStatus().GetUserName(), false)
require.NoError(t, err)
genStr := botUser.BotGenerationLabel()
require.Equal(t, "7", genStr)
@@ -1266,62 +1266,62 @@ func createScopedBot(t *testing.T, srv *authtest.TLSServer, adminClient *authcli
// Create a scoped role for the bot.
scopedSvc := adminClient.ScopedAccessServiceClient()
- _, err := scopedSvc.CreateScopedRole(t.Context(), &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ _, err := scopedSvc.CreateScopedRole(t.Context(), scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-example",
- },
+ }.Build(),
Scope: "/test",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/test"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Create the scoped bot.
- _, err = adminClient.BotServiceClient().CreateBot(t.Context(), &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ _, err = adminClient.BotServiceClient().CreateBot(t.Context(), machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
Scope: "/test",
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-scoped",
- },
+ }.Build(),
Spec: &machineidv1pb.BotSpec{},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Create a scoped role assignment for the bot.
- resp, err := srv.Auth().ScopedAccess().CreateScopedRoleAssignment(t.Context(), &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ resp, err := srv.Auth().ScopedAccess().CreateScopedRoleAssignment(t.Context(), scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/test",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
BotName: "test-scoped",
BotScope: "/test",
Assignments: []*scopedaccessv1.Assignment{
- {Role: "scoped-example", Scope: "/test"},
+ scopedaccessv1.Assignment_builder{Role: "scoped-example", Scope: "/test"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
ctx := t.Context()
require.EventuallyWithT(t, func(t *assert.CollectT) {
- _, err := srv.Auth().ScopedAccessCache.GetScopedRoleAssignment(ctx, &scopedaccessv1.GetScopedRoleAssignmentRequest{
+ _, err := srv.Auth().ScopedAccessCache.GetScopedRoleAssignment(ctx, scopedaccessv1.GetScopedRoleAssignmentRequest_builder{
Name: resp.GetAssignment().GetMetadata().GetName(),
SubKind: resp.GetAssignment().GetSubKind(),
- })
+ }.Build())
require.NoError(t, err)
}, time.Second*10, 100*time.Millisecond)
}
@@ -1351,32 +1351,32 @@ func TestRegisterBotWithScopedKubernetesToken(t *testing.T) {
)
require.NoError(t, err)
- scopedToken := &joiningv1.ScopedToken{
+ scopedToken := joiningv1.ScopedToken_builder{
Kind: types.KindScopedToken,
Version: types.V1,
Scope: "/test",
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "example-token",
- },
- Spec: &joiningv1.ScopedTokenSpec{
+ }.Build(),
+ Spec: joiningv1.ScopedTokenSpec_builder{
JoinMethod: string(types.JoinMethodKubernetes),
Roles: []string{string(types.RoleBot)},
UsageMode: joining.TokenUsageModeBot,
BotName: "test-scoped",
BotScope: "/test",
- Kubernetes: &joiningv1.Kubernetes{
+ Kubernetes: joiningv1.Kubernetes_builder{
Type: string(types.KubernetesJoinTypeStaticJWKS),
- StaticJwks: &joiningv1.Kubernetes_StaticJWKSConfig{
+ StaticJwks: joiningv1.Kubernetes_StaticJWKSConfig_builder{
Jwks: jwks,
- },
+ }.Build(),
Allow: []*joiningv1.Kubernetes_Rule{
- {
+ joiningv1.Kubernetes_Rule_builder{
ServiceAccount: "my-namespace:my-service-account",
- },
+ }.Build(),
},
- },
- },
- }
+ }.Build(),
+ }.Build(),
+ }.Build()
_, err = client.CreateScopedToken(ctx, scopedToken)
require.NoError(t, err)
diff --git a/lib/auth/clusterconfig/clusterconfigv1/service.go b/lib/auth/clusterconfig/clusterconfigv1/service.go
index 97c7c4b549b..bb14e71f612 100644
--- a/lib/auth/clusterconfig/clusterconfigv1/service.go
+++ b/lib/auth/clusterconfig/clusterconfigv1/service.go
@@ -214,26 +214,26 @@ func (s *Service) UpdateAuthPreference(ctx context.Context, req *clusterconfigpb
}
// check that the given RequireMFAType is supported in this build.
- if req.AuthPreference.GetPrivateKeyPolicy().IsHardwareKeyPolicy() && s.modules.BuildType() != modules.BuildEnterprise {
+ if req.GetAuthPreference().GetPrivateKeyPolicy().IsHardwareKeyPolicy() && s.modules.BuildType() != modules.BuildEnterprise {
return nil, trace.AccessDenied("Hardware Key support is only available with an enterprise license")
}
- if err := dtconfig.ValidateConfigAgainstModules(req.AuthPreference.GetDeviceTrust(), s.modules); err != nil {
+ if err := dtconfig.ValidateConfigAgainstModules(req.GetAuthPreference().GetDeviceTrust(), s.modules); err != nil {
return nil, trace.Wrap(err)
}
- if err := req.AuthPreference.CheckSignatureAlgorithmSuite(s.signatureAlgorithmSuiteParams); err != nil {
+ if err := req.GetAuthPreference().CheckSignatureAlgorithmSuite(s.signatureAlgorithmSuiteParams); err != nil {
return nil, trace.Wrap(err)
}
- req.AuthPreference.SetOrigin(types.OriginDynamic)
+ req.GetAuthPreference().SetOrigin(types.OriginDynamic)
original, err := s.cache.GetAuthPreference(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
- updated, err := s.backend.UpdateAuthPreference(ctx, req.AuthPreference)
+ updated, err := s.backend.UpdateAuthPreference(ctx, req.GetAuthPreference())
if auditErr := s.emitter.EmitAuditEvent(ctx, &apievents.AuthPreferenceUpdate{
Metadata: apievents.Metadata{
@@ -243,7 +243,7 @@ func (s *Service) UpdateAuthPreference(ctx context.Context, req *clusterconfigpb
UserMetadata: authzCtx.GetUserMetadata(),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
Status: eventStatus(err),
- AdminActionsMFA: GetAdminActionsMFAStatus(original, req.AuthPreference),
+ AdminActionsMFA: GetAdminActionsMFAStatus(original, req.GetAuthPreference()),
}); auditErr != nil {
slog.WarnContext(ctx, "Failed to emit auth preference update event.", "error", auditErr)
}
@@ -282,26 +282,26 @@ func (s *Service) UpsertAuthPreference(ctx context.Context, req *clusterconfigpb
}
// check that the given RequireMFAType is supported in this build.
- if req.AuthPreference.GetPrivateKeyPolicy().IsHardwareKeyPolicy() && s.modules.BuildType() != modules.BuildEnterprise {
+ if req.GetAuthPreference().GetPrivateKeyPolicy().IsHardwareKeyPolicy() && s.modules.BuildType() != modules.BuildEnterprise {
return nil, trace.AccessDenied("Hardware Key support is only available with an enterprise license")
}
- if err := dtconfig.ValidateConfigAgainstModules(req.AuthPreference.GetDeviceTrust(), s.modules); err != nil {
+ if err := dtconfig.ValidateConfigAgainstModules(req.GetAuthPreference().GetDeviceTrust(), s.modules); err != nil {
return nil, trace.Wrap(err)
}
- if err := req.AuthPreference.CheckSignatureAlgorithmSuite(s.signatureAlgorithmSuiteParams); err != nil {
+ if err := req.GetAuthPreference().CheckSignatureAlgorithmSuite(s.signatureAlgorithmSuiteParams); err != nil {
return nil, trace.Wrap(err)
}
- req.AuthPreference.SetOrigin(types.OriginDynamic)
+ req.GetAuthPreference().SetOrigin(types.OriginDynamic)
original, err := s.cache.GetAuthPreference(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
- updated, err := s.backend.UpsertAuthPreference(ctx, req.AuthPreference)
+ updated, err := s.backend.UpsertAuthPreference(ctx, req.GetAuthPreference())
if auditErr := s.emitter.EmitAuditEvent(ctx, &apievents.AuthPreferenceUpdate{
Metadata: apievents.Metadata{
@@ -311,7 +311,7 @@ func (s *Service) UpsertAuthPreference(ctx context.Context, req *clusterconfigpb
UserMetadata: authzCtx.GetUserMetadata(),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
Status: eventStatus(err),
- AdminActionsMFA: GetAdminActionsMFAStatus(original, req.AuthPreference),
+ AdminActionsMFA: GetAdminActionsMFAStatus(original, req.GetAuthPreference()),
}); auditErr != nil {
slog.WarnContext(ctx, "Failed to emit auth preference update event.", "error", auditErr)
}
@@ -485,7 +485,7 @@ func (s *Service) UpdateClusterNetworkingConfig(ctx context.Context, req *cluste
return nil, trace.Wrap(err)
}
- tst, err := req.ClusterNetworkConfig.GetTunnelStrategyType()
+ tst, err := req.GetClusterNetworkConfig().GetTunnelStrategyType()
if err != nil {
return nil, trace.Wrap(err)
}
@@ -493,7 +493,7 @@ func (s *Service) UpdateClusterNetworkingConfig(ctx context.Context, req *cluste
return nil, trace.AccessDenied("proxy peering is an enterprise-only feature")
}
- req.ClusterNetworkConfig.SetOrigin(types.OriginDynamic)
+ req.GetClusterNetworkConfig().SetOrigin(types.OriginDynamic)
oldCfg, err := s.cache.GetClusterNetworkingConfig(ctx)
if err != nil {
@@ -506,7 +506,7 @@ func (s *Service) UpdateClusterNetworkingConfig(ctx context.Context, req *cluste
return nil, trace.Wrap(err)
}
- updated, err := s.backend.UpdateClusterNetworkingConfig(ctx, req.ClusterNetworkConfig)
+ updated, err := s.backend.UpdateClusterNetworkingConfig(ctx, req.GetClusterNetworkConfig())
if err := s.emitter.EmitAuditEvent(ctx, &apievents.ClusterNetworkingConfigUpdate{
Metadata: apievents.Metadata{
@@ -550,7 +550,7 @@ func (s *Service) UpsertClusterNetworkingConfig(ctx context.Context, req *cluste
return nil, trace.Wrap(err)
}
- tst, err := req.ClusterNetworkConfig.GetTunnelStrategyType()
+ tst, err := req.GetClusterNetworkConfig().GetTunnelStrategyType()
if err != nil {
return nil, trace.Wrap(err)
}
@@ -558,7 +558,7 @@ func (s *Service) UpsertClusterNetworkingConfig(ctx context.Context, req *cluste
return nil, trace.AccessDenied("proxy peering is an enterprise-only feature")
}
- req.ClusterNetworkConfig.SetOrigin(types.OriginDynamic)
+ req.GetClusterNetworkConfig().SetOrigin(types.OriginDynamic)
oldCfg, err := s.cache.GetClusterNetworkingConfig(ctx)
if err != nil {
@@ -787,13 +787,13 @@ func (s *Service) UpdateSessionRecordingConfig(ctx context.Context, req *cluster
return nil, trace.Wrap(err)
}
- req.SessionRecordingConfig.SetOrigin(types.OriginDynamic)
+ req.GetSessionRecordingConfig().SetOrigin(types.OriginDynamic)
- if err := services.ValidateSessionRecordingConfig(req.SessionRecordingConfig, s.signatureAlgorithmSuiteParams.FIPS, s.signatureAlgorithmSuiteParams.Cloud); err != nil {
+ if err := services.ValidateSessionRecordingConfig(req.GetSessionRecordingConfig(), s.signatureAlgorithmSuiteParams.FIPS, s.signatureAlgorithmSuiteParams.Cloud); err != nil {
return nil, trace.Wrap(err)
}
- updated, err := s.backend.UpdateSessionRecordingConfig(ctx, req.SessionRecordingConfig)
+ updated, err := s.backend.UpdateSessionRecordingConfig(ctx, req.GetSessionRecordingConfig())
if err := s.emitter.EmitAuditEvent(ctx, &apievents.SessionRecordingConfigUpdate{
Metadata: apievents.Metadata{
@@ -837,13 +837,13 @@ func (s *Service) UpsertSessionRecordingConfig(ctx context.Context, req *cluster
return nil, trace.Wrap(err)
}
- req.SessionRecordingConfig.SetOrigin(types.OriginDynamic)
+ req.GetSessionRecordingConfig().SetOrigin(types.OriginDynamic)
- if err := services.ValidateSessionRecordingConfig(req.SessionRecordingConfig, s.signatureAlgorithmSuiteParams.FIPS, s.signatureAlgorithmSuiteParams.Cloud); err != nil {
+ if err := services.ValidateSessionRecordingConfig(req.GetSessionRecordingConfig(), s.signatureAlgorithmSuiteParams.FIPS, s.signatureAlgorithmSuiteParams.Cloud); err != nil {
return nil, trace.Wrap(err)
}
- upserted, err := s.backend.UpsertSessionRecordingConfig(ctx, req.SessionRecordingConfig)
+ upserted, err := s.backend.UpsertSessionRecordingConfig(ctx, req.GetSessionRecordingConfig())
if err := s.emitter.EmitAuditEvent(ctx, &apievents.SessionRecordingConfigUpdate{
Metadata: apievents.Metadata{
@@ -945,11 +945,11 @@ func (s *Service) GetClusterAccessGraphConfig(ctx context.Context, _ *clustercon
// If the policy feature is disabled in the license, return a disabled response. if cloud, return the response to allow demo mode enabling
if !s.modules.Features().GetEntitlement(entitlements.Policy).Enabled && !s.modules.Features().AccessGraph && !s.modules.Features().Cloud {
- return &clusterconfigpb.GetClusterAccessGraphConfigResponse{
- AccessGraph: &clusterconfigpb.AccessGraphConfig{
+ return clusterconfigpb.GetClusterAccessGraphConfigResponse_builder{
+ AccessGraph: clusterconfigpb.AccessGraphConfig_builder{
Enabled: false,
- },
- }, nil
+ }.Build(),
+ }.Build(), nil
}
var sshScanEnabled bool
@@ -960,17 +960,17 @@ func (s *Service) GetClusterAccessGraphConfig(ctx context.Context, _ *clustercon
sshScanEnabled = obj.SecretsScanConfig() == clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED
}
- return &clusterconfigpb.GetClusterAccessGraphConfigResponse{
- AccessGraph: &clusterconfigpb.AccessGraphConfig{
+ return clusterconfigpb.GetClusterAccessGraphConfigResponse_builder{
+ AccessGraph: clusterconfigpb.AccessGraphConfig_builder{
Enabled: s.accessGraph.Enabled,
Address: s.accessGraph.Address,
Ca: s.accessGraph.CA,
Insecure: s.accessGraph.Insecure,
- SecretsScanConfig: &clusterconfigpb.AccessGraphSecretsScanConfiguration{
+ SecretsScanConfig: clusterconfigpb.AccessGraphSecretsScanConfiguration_builder{
SshScanEnabled: sshScanEnabled,
- },
- },
- }, nil
+ }.Build(),
+ }.Build(),
+ }.Build(), nil
}
func (s *Service) GetAccessGraphSettings(ctx context.Context, _ *clusterconfigpb.GetAccessGraphSettingsRequest) (*clusterconfigpb.AccessGraphSettings, error) {
@@ -1137,9 +1137,9 @@ func (s *Service) ResetAccessGraphSettings(ctx context.Context, _ *clusterconfig
return nil, trace.AccessDenied("access graph is feature isn't enabled")
}
- obj, err := clusterconfig.NewAccessGraphSettings(&clusterconfigpb.AccessGraphSettingsSpec{
+ obj, err := clusterconfig.NewAccessGraphSettings(clusterconfigpb.AccessGraphSettingsSpec_builder{
SecretsScanConfig: clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_DISABLED,
- })
+ }.Build())
if err != nil {
return nil, trace.Wrap(err)
}
diff --git a/lib/auth/clusterconfig/clusterconfigv1/service_test.go b/lib/auth/clusterconfig/clusterconfigv1/service_test.go
index 3e1a092487f..17df57ea708 100644
--- a/lib/auth/clusterconfig/clusterconfigv1/service_test.go
+++ b/lib/auth/clusterconfig/clusterconfigv1/service_test.go
@@ -195,7 +195,7 @@ func TestUpdateAuthPreference(t *testing.T) {
test.preference(pref)
}
- updated, err := env.UpdateAuthPreference(context.Background(), &clusterconfigpb.UpdateAuthPreferenceRequest{AuthPreference: pref.(*types.AuthPreferenceV2)})
+ updated, err := env.UpdateAuthPreference(context.Background(), clusterconfigpb.UpdateAuthPreferenceRequest_builder{AuthPreference: pref.(*types.AuthPreferenceV2)}.Build())
test.assertion(t, updated, err)
})
}
@@ -318,7 +318,7 @@ func TestUpsertAuthPreference(t *testing.T) {
test.preference(pref)
}
- updated, err := env.UpsertAuthPreference(context.Background(), &clusterconfigpb.UpsertAuthPreferenceRequest{AuthPreference: pref.(*types.AuthPreferenceV2)})
+ updated, err := env.UpsertAuthPreference(context.Background(), clusterconfigpb.UpsertAuthPreferenceRequest_builder{AuthPreference: pref.(*types.AuthPreferenceV2)}.Build())
test.assertion(t, updated, err)
})
}
@@ -757,7 +757,7 @@ func TestUpdateClusterNetworkingConfig(t *testing.T) {
test.config(cfg)
}
- updated, err := env.UpdateClusterNetworkingConfig(context.Background(), &clusterconfigpb.UpdateClusterNetworkingConfigRequest{ClusterNetworkConfig: cfg.(*types.ClusterNetworkingConfigV2)})
+ updated, err := env.UpdateClusterNetworkingConfig(context.Background(), clusterconfigpb.UpdateClusterNetworkingConfigRequest_builder{ClusterNetworkConfig: cfg.(*types.ClusterNetworkingConfigV2)}.Build())
test.assertion(t, updated, err)
})
}
@@ -867,7 +867,7 @@ func TestUpsertClusterNetworkingConfig(t *testing.T) {
test.config(cfg)
}
- updated, err := env.UpsertClusterNetworkingConfig(context.Background(), &clusterconfigpb.UpsertClusterNetworkingConfigRequest{ClusterNetworkConfig: cfg.(*types.ClusterNetworkingConfigV2)})
+ updated, err := env.UpsertClusterNetworkingConfig(context.Background(), clusterconfigpb.UpsertClusterNetworkingConfigRequest_builder{ClusterNetworkConfig: cfg.(*types.ClusterNetworkingConfigV2)}.Build())
test.assertion(t, updated, err)
})
}
@@ -1134,7 +1134,7 @@ func TestUpdateSessionRecordingConfig(t *testing.T) {
test.config(cfg)
}
- updated, err := env.UpdateSessionRecordingConfig(context.Background(), &clusterconfigpb.UpdateSessionRecordingConfigRequest{SessionRecordingConfig: cfg.(*types.SessionRecordingConfigV2)})
+ updated, err := env.UpdateSessionRecordingConfig(context.Background(), clusterconfigpb.UpdateSessionRecordingConfigRequest_builder{SessionRecordingConfig: cfg.(*types.SessionRecordingConfigV2)}.Build())
test.assertion(t, updated, err)
})
}
@@ -1223,7 +1223,7 @@ func TestUpsertSessionRecordingConfig(t *testing.T) {
test.config(cfg)
}
- updated, err := env.UpsertSessionRecordingConfig(context.Background(), &clusterconfigpb.UpsertSessionRecordingConfigRequest{SessionRecordingConfig: cfg.(*types.SessionRecordingConfigV2)})
+ updated, err := env.UpsertSessionRecordingConfig(context.Background(), clusterconfigpb.UpsertSessionRecordingConfigRequest_builder{SessionRecordingConfig: cfg.(*types.SessionRecordingConfigV2)}.Build())
test.assertion(t, updated, err)
})
}
@@ -1419,13 +1419,13 @@ func TestAuditEventsEmitted(t *testing.T) {
p.SetLockingMode(constants.LockingModeStrict)
- p, err = env.UpdateAuthPreference(ctx, &clusterconfigpb.UpdateAuthPreferenceRequest{AuthPreference: p})
+ p, err = env.UpdateAuthPreference(ctx, clusterconfigpb.UpdateAuthPreferenceRequest_builder{AuthPreference: p}.Build())
require.NoError(t, err)
evt = <-env.emitter.C()
require.Empty(t, cmp.Diff(&mfaUnchangedEvent, evt))
- _, err = env.UpsertAuthPreference(ctx, &clusterconfigpb.UpsertAuthPreferenceRequest{AuthPreference: p})
+ _, err = env.UpsertAuthPreference(ctx, clusterconfigpb.UpsertAuthPreferenceRequest_builder{AuthPreference: p}.Build())
require.NoError(t, err)
evt = <-env.emitter.C()
@@ -1436,7 +1436,7 @@ func TestAuditEventsEmitted(t *testing.T) {
RPID: "example.com",
}
- p, err = env.UpdateAuthPreference(ctx, &clusterconfigpb.UpdateAuthPreferenceRequest{AuthPreference: p})
+ p, err = env.UpdateAuthPreference(ctx, clusterconfigpb.UpdateAuthPreferenceRequest_builder{AuthPreference: p}.Build())
require.NoError(t, err)
evt = <-env.emitter.C()
@@ -1447,7 +1447,7 @@ func TestAuditEventsEmitted(t *testing.T) {
// from the previous authPref setup
p.Spec.AllowCLIAuthViaBrowser = nil
- _, err = env.UpsertAuthPreference(ctx, &clusterconfigpb.UpsertAuthPreferenceRequest{AuthPreference: p})
+ _, err = env.UpsertAuthPreference(ctx, clusterconfigpb.UpsertAuthPreferenceRequest_builder{AuthPreference: p}.Build())
require.NoError(t, err)
evt = <-env.emitter.C()
@@ -1477,13 +1477,13 @@ func TestAuditEventsEmitted(t *testing.T) {
cfg.SetRoutingStrategy(types.RoutingStrategy_MOST_RECENT)
- cfg, err = env.UpdateClusterNetworkingConfig(ctx, &clusterconfigpb.UpdateClusterNetworkingConfigRequest{ClusterNetworkConfig: cfg})
+ cfg, err = env.UpdateClusterNetworkingConfig(ctx, clusterconfigpb.UpdateClusterNetworkingConfigRequest_builder{ClusterNetworkConfig: cfg}.Build())
require.NoError(t, err)
evt = <-env.emitter.C()
require.Empty(t, cmp.Diff(expectedEvent, evt))
- _, err = env.UpsertClusterNetworkingConfig(ctx, &clusterconfigpb.UpsertClusterNetworkingConfigRequest{ClusterNetworkConfig: cfg})
+ _, err = env.UpsertClusterNetworkingConfig(ctx, clusterconfigpb.UpsertClusterNetworkingConfigRequest_builder{ClusterNetworkConfig: cfg}.Build())
require.NoError(t, err)
evt = <-env.emitter.C()
@@ -1513,13 +1513,13 @@ func TestAuditEventsEmitted(t *testing.T) {
cfg.SetMode(types.RecordAtProxy)
- cfg, err = env.UpdateSessionRecordingConfig(ctx, &clusterconfigpb.UpdateSessionRecordingConfigRequest{SessionRecordingConfig: cfg})
+ cfg, err = env.UpdateSessionRecordingConfig(ctx, clusterconfigpb.UpdateSessionRecordingConfigRequest_builder{SessionRecordingConfig: cfg}.Build())
require.NoError(t, err)
evt = <-env.emitter.C()
require.Empty(t, cmp.Diff(expectedEvent, evt))
- _, err = env.UpsertSessionRecordingConfig(ctx, &clusterconfigpb.UpsertSessionRecordingConfigRequest{SessionRecordingConfig: cfg})
+ _, err = env.UpsertSessionRecordingConfig(ctx, clusterconfigpb.UpsertSessionRecordingConfigRequest_builder{SessionRecordingConfig: cfg}.Build())
require.NoError(t, err)
evt = <-env.emitter.C()
@@ -1573,13 +1573,13 @@ func TestAuditEventsEmitted(t *testing.T) {
evt := <-env.emitter.C()
require.Empty(t, cmp.Diff(expectedEvent, evt))
- _, err = env.UpdateAuthPreference(ctx, &clusterconfigpb.UpdateAuthPreferenceRequest{AuthPreference: types.DefaultAuthPreference().(*types.AuthPreferenceV2)})
+ _, err = env.UpdateAuthPreference(ctx, clusterconfigpb.UpdateAuthPreferenceRequest_builder{AuthPreference: types.DefaultAuthPreference().(*types.AuthPreferenceV2)}.Build())
require.Error(t, err)
evt = <-env.emitter.C()
require.Empty(t, cmp.Diff(expectedEvent, evt))
- _, err = env.UpsertAuthPreference(ctx, &clusterconfigpb.UpsertAuthPreferenceRequest{AuthPreference: types.DefaultAuthPreference().(*types.AuthPreferenceV2)})
+ _, err = env.UpsertAuthPreference(ctx, clusterconfigpb.UpsertAuthPreferenceRequest_builder{AuthPreference: types.DefaultAuthPreference().(*types.AuthPreferenceV2)}.Build())
require.Error(t, err)
evt = <-env.emitter.C()
@@ -1609,13 +1609,13 @@ func TestAuditEventsEmitted(t *testing.T) {
evt := <-env.emitter.C()
require.Empty(t, cmp.Diff(expectedEvent, evt))
- _, err = env.UpdateClusterNetworkingConfig(ctx, &clusterconfigpb.UpdateClusterNetworkingConfigRequest{ClusterNetworkConfig: types.DefaultClusterNetworkingConfig().(*types.ClusterNetworkingConfigV2)})
+ _, err = env.UpdateClusterNetworkingConfig(ctx, clusterconfigpb.UpdateClusterNetworkingConfigRequest_builder{ClusterNetworkConfig: types.DefaultClusterNetworkingConfig().(*types.ClusterNetworkingConfigV2)}.Build())
require.Error(t, err)
evt = <-env.emitter.C()
require.Empty(t, cmp.Diff(expectedEvent, evt))
- _, err = env.UpsertClusterNetworkingConfig(ctx, &clusterconfigpb.UpsertClusterNetworkingConfigRequest{ClusterNetworkConfig: types.DefaultClusterNetworkingConfig().(*types.ClusterNetworkingConfigV2)})
+ _, err = env.UpsertClusterNetworkingConfig(ctx, clusterconfigpb.UpsertClusterNetworkingConfigRequest_builder{ClusterNetworkConfig: types.DefaultClusterNetworkingConfig().(*types.ClusterNetworkingConfigV2)}.Build())
require.Error(t, err)
evt = <-env.emitter.C()
@@ -1645,13 +1645,13 @@ func TestAuditEventsEmitted(t *testing.T) {
evt := <-env.emitter.C()
require.Empty(t, cmp.Diff(expectedEvent, evt))
- _, err = env.UpdateSessionRecordingConfig(ctx, &clusterconfigpb.UpdateSessionRecordingConfigRequest{SessionRecordingConfig: types.DefaultSessionRecordingConfig().(*types.SessionRecordingConfigV2)})
+ _, err = env.UpdateSessionRecordingConfig(ctx, clusterconfigpb.UpdateSessionRecordingConfigRequest_builder{SessionRecordingConfig: types.DefaultSessionRecordingConfig().(*types.SessionRecordingConfigV2)}.Build())
require.Error(t, err)
evt = <-env.emitter.C()
require.Empty(t, cmp.Diff(expectedEvent, evt))
- _, err = env.UpsertSessionRecordingConfig(ctx, &clusterconfigpb.UpsertSessionRecordingConfigRequest{SessionRecordingConfig: types.DefaultSessionRecordingConfig().(*types.SessionRecordingConfigV2)})
+ _, err = env.UpsertSessionRecordingConfig(ctx, clusterconfigpb.UpsertSessionRecordingConfigRequest_builder{SessionRecordingConfig: types.DefaultSessionRecordingConfig().(*types.SessionRecordingConfigV2)}.Build())
require.Error(t, err)
evt = <-env.emitter.C()
@@ -1870,9 +1870,9 @@ func newTestEnv(opts ...serviceOpt) (*env, error) {
func TestGetAccessGraphConfig(t *testing.T) {
settings, err := clusterconfig.NewAccessGraphSettings(
- &clusterconfigpb.AccessGraphSettingsSpec{
+ clusterconfigpb.AccessGraphSettingsSpec_builder{
SecretsScanConfig: clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED,
- },
+ }.Build(),
)
require.NoError(t, err)
@@ -1896,11 +1896,11 @@ func TestGetAccessGraphConfig(t *testing.T) {
role: types.RoleProxy,
accessGraphConfig: cfgEnabled,
errorAssertion: require.NoError,
- responseAssertion: &clusterconfigpb.GetClusterAccessGraphConfigResponse{
- AccessGraph: &clusterconfigpb.AccessGraphConfig{
+ responseAssertion: clusterconfigpb.GetClusterAccessGraphConfigResponse_builder{
+ AccessGraph: clusterconfigpb.AccessGraphConfig_builder{
Enabled: false,
- },
- },
+ }.Build(),
+ }.Build(),
},
{
name: "authorized proxy with non empty access graph config; Policy module is enabled",
@@ -1914,15 +1914,15 @@ func TestGetAccessGraphConfig(t *testing.T) {
},
accessGraphConfig: cfgEnabled,
errorAssertion: require.NoError,
- responseAssertion: &clusterconfigpb.GetClusterAccessGraphConfigResponse{
- AccessGraph: &clusterconfigpb.AccessGraphConfig{
+ responseAssertion: clusterconfigpb.GetClusterAccessGraphConfigResponse_builder{
+ AccessGraph: clusterconfigpb.AccessGraphConfig_builder{
Enabled: true,
Insecure: true,
Address: "address",
Ca: []byte("ca"),
SecretsScanConfig: &clusterconfigpb.AccessGraphSecretsScanConfiguration{},
- },
- },
+ }.Build(),
+ }.Build(),
},
{
name: "authorized discovery with non empty access graph config; Policy module is enabled",
@@ -1936,15 +1936,15 @@ func TestGetAccessGraphConfig(t *testing.T) {
},
accessGraphConfig: cfgEnabled,
errorAssertion: require.NoError,
- responseAssertion: &clusterconfigpb.GetClusterAccessGraphConfigResponse{
- AccessGraph: &clusterconfigpb.AccessGraphConfig{
+ responseAssertion: clusterconfigpb.GetClusterAccessGraphConfigResponse_builder{
+ AccessGraph: clusterconfigpb.AccessGraphConfig_builder{
Enabled: true,
Insecure: true,
Address: "address",
Ca: []byte("ca"),
SecretsScanConfig: &clusterconfigpb.AccessGraphSecretsScanConfiguration{},
- },
- },
+ }.Build(),
+ }.Build(),
},
{
name: "Policy module is enabled with secrets scan option",
@@ -1959,17 +1959,17 @@ func TestGetAccessGraphConfig(t *testing.T) {
accessGraphConfig: cfgEnabled,
accessGraphSettings: settings,
errorAssertion: require.NoError,
- responseAssertion: &clusterconfigpb.GetClusterAccessGraphConfigResponse{
- AccessGraph: &clusterconfigpb.AccessGraphConfig{
+ responseAssertion: clusterconfigpb.GetClusterAccessGraphConfigResponse_builder{
+ AccessGraph: clusterconfigpb.AccessGraphConfig_builder{
Enabled: true,
Insecure: true,
Address: "address",
Ca: []byte("ca"),
- SecretsScanConfig: &clusterconfigpb.AccessGraphSecretsScanConfiguration{
+ SecretsScanConfig: clusterconfigpb.AccessGraphSecretsScanConfiguration_builder{
SshScanEnabled: true,
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
},
}
@@ -2034,9 +2034,9 @@ func TestGetAccessGraphSettings(t *testing.T) {
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
settings, err := clusterconfig.NewAccessGraphSettings(
- &clusterconfigpb.AccessGraphSettingsSpec{
+ clusterconfigpb.AccessGraphSettingsSpec_builder{
SecretsScanConfig: clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_DISABLED,
- },
+ }.Build(),
)
require.NoError(t, err)
env, err := newTestEnv(withAuthorizer(test.authorizer), withAccessGraphSettings(settings))
@@ -2099,7 +2099,7 @@ func TestUpdateAccessGraphSettings(t *testing.T) {
}, nil
}),
mutator: func(p *clusterconfigpb.AccessGraphSettings) {
- p.Spec.SecretsScanConfig = clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED
+ p.GetSpec().SetSecretsScanConfig(clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED)
},
assertion: func(t *testing.T, updated *clusterconfigpb.AccessGraphSettings, err error) {
require.Error(t, err)
@@ -2127,7 +2127,7 @@ func TestUpdateAccessGraphSettings(t *testing.T) {
}, nil
}),
mutator: func(p *clusterconfigpb.AccessGraphSettings) {
- p.Spec.SecretsScanConfig = clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED
+ p.GetSpec().SetSecretsScanConfig(clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED)
},
assertion: func(t *testing.T, updated *clusterconfigpb.AccessGraphSettings, err error) {
require.NoError(t, err)
@@ -2139,9 +2139,9 @@ func TestUpdateAccessGraphSettings(t *testing.T) {
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
settings, err := clusterconfig.NewAccessGraphSettings(
- &clusterconfigpb.AccessGraphSettingsSpec{
+ clusterconfigpb.AccessGraphSettingsSpec_builder{
SecretsScanConfig: clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED,
- },
+ }.Build(),
)
require.NoError(t, err)
env, err := newTestEnv(
@@ -2157,7 +2157,7 @@ func TestUpdateAccessGraphSettings(t *testing.T) {
test.mutator(pref)
}
- updated, err := env.UpdateAccessGraphSettings(context.Background(), &clusterconfigpb.UpdateAccessGraphSettingsRequest{AccessGraphSettings: pref})
+ updated, err := env.UpdateAccessGraphSettings(context.Background(), clusterconfigpb.UpdateAccessGraphSettingsRequest_builder{AccessGraphSettings: pref}.Build())
test.assertion(t, updated, err)
})
}
@@ -2250,11 +2250,11 @@ func TestUpsertAccessGraphSettings(t *testing.T) {
}, nil
}),
mutator: func(p *clusterconfigpb.AccessGraphSettings) {
- p.Spec.SecretsScanConfig = clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED
+ p.GetSpec().SetSecretsScanConfig(clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED)
},
assertion: func(t *testing.T, updated *clusterconfigpb.AccessGraphSettings, err error) {
require.NoError(t, err)
- require.Equal(t, clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED, updated.Spec.SecretsScanConfig)
+ require.Equal(t, clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_ENABLED, updated.GetSpec().GetSecretsScanConfig())
},
},
}
@@ -2262,9 +2262,9 @@ func TestUpsertAccessGraphSettings(t *testing.T) {
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
settings, err := clusterconfig.NewAccessGraphSettings(
- &clusterconfigpb.AccessGraphSettingsSpec{
+ clusterconfigpb.AccessGraphSettingsSpec_builder{
SecretsScanConfig: clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_DISABLED,
- })
+ }.Build())
require.NoError(t, err)
@@ -2281,7 +2281,7 @@ func TestUpsertAccessGraphSettings(t *testing.T) {
test.mutator(pref)
}
- updated, err := env.UpsertAccessGraphSettings(context.Background(), &clusterconfigpb.UpsertAccessGraphSettingsRequest{AccessGraphSettings: pref})
+ updated, err := env.UpsertAccessGraphSettings(context.Background(), clusterconfigpb.UpsertAccessGraphSettingsRequest_builder{AccessGraphSettings: pref}.Build())
test.assertion(t, updated, err)
})
}
@@ -2351,9 +2351,9 @@ func TestResetAccessGraphSettings(t *testing.T) {
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
settings, err := clusterconfig.NewAccessGraphSettings(
- &clusterconfigpb.AccessGraphSettingsSpec{
+ clusterconfigpb.AccessGraphSettingsSpec_builder{
SecretsScanConfig: clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_DISABLED,
- })
+ }.Build())
require.NoError(t, err)
diff --git a/lib/auth/crownjewel/crownjewelv1/service.go b/lib/auth/crownjewel/crownjewelv1/service.go
index 109fad79708..c3c462f4f40 100644
--- a/lib/auth/crownjewel/crownjewelv1/service.go
+++ b/lib/auth/crownjewel/crownjewelv1/service.go
@@ -115,11 +115,11 @@ func (s *Service) CreateCrownJewel(ctx context.Context, req *crownjewelv1.Create
return nil, trace.Wrap(err)
}
- if err := crownjewel.ValidateCrownJewel(req.CrownJewel); err != nil {
+ if err := crownjewel.ValidateCrownJewel(req.GetCrownJewel()); err != nil {
return nil, trace.Wrap(err)
}
- rsp, err := s.backend.CreateCrownJewel(ctx, req.CrownJewel)
+ rsp, err := s.backend.CreateCrownJewel(ctx, req.GetCrownJewel())
s.emitCreateAuditEvent(ctx, rsp, authCtx, err)
@@ -157,15 +157,15 @@ func (s *Service) ListCrownJewels(ctx context.Context, req *crownjewelv1.ListCro
return nil, trace.Wrap(err)
}
- rsp, nextToken, err := s.reader.ListCrownJewels(ctx, req.PageSize, req.PageToken)
+ rsp, nextToken, err := s.reader.ListCrownJewels(ctx, req.GetPageSize(), req.GetPageToken())
if err != nil {
return nil, trace.Wrap(err)
}
- return &crownjewelv1.ListCrownJewelsResponse{
+ return crownjewelv1.ListCrownJewelsResponse_builder{
CrownJewels: rsp,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// GetCrownJewel returns crown jewel resource.
@@ -202,7 +202,7 @@ func (s *Service) UpdateCrownJewel(ctx context.Context, req *crownjewelv1.Update
return nil, trace.Wrap(err)
}
- if err := crownjewel.ValidateCrownJewel(req.CrownJewel); err != nil {
+ if err := crownjewel.ValidateCrownJewel(req.GetCrownJewel()); err != nil {
return nil, trace.Wrap(err)
}
@@ -211,7 +211,7 @@ func (s *Service) UpdateCrownJewel(ctx context.Context, req *crownjewelv1.Update
return nil, trace.Wrap(err)
}
- rsp, err := s.backend.UpdateCrownJewel(ctx, req.CrownJewel)
+ rsp, err := s.backend.UpdateCrownJewel(ctx, req.GetCrownJewel())
s.emitUpdateAuditEvent(ctx, oldCrownJewel, req.GetCrownJewel(), authCtx, err)
@@ -254,7 +254,7 @@ func (s *Service) UpsertCrownJewel(ctx context.Context, req *crownjewelv1.Upsert
return nil, trace.Wrap(err)
}
- if err := crownjewel.ValidateCrownJewel(req.CrownJewel); err != nil {
+ if err := crownjewel.ValidateCrownJewel(req.GetCrownJewel()); err != nil {
return nil, trace.Wrap(err)
}
@@ -263,7 +263,7 @@ func (s *Service) UpsertCrownJewel(ctx context.Context, req *crownjewelv1.Upsert
return nil, trace.Wrap(err)
}
- rsp, err := s.backend.UpsertCrownJewel(ctx, req.CrownJewel)
+ rsp, err := s.backend.UpsertCrownJewel(ctx, req.GetCrownJewel())
s.emitUpsertAuditEvent(ctx, oldCrownJewel, req.GetCrownJewel(), authCtx, err)
diff --git a/lib/auth/crownjewel/object.go b/lib/auth/crownjewel/object.go
index 2d7b4f5d553..8a53264a820 100644
--- a/lib/auth/crownjewel/object.go
+++ b/lib/auth/crownjewel/object.go
@@ -29,14 +29,14 @@ import (
// NewCrownJewel creates a new CrownJewel object.
// It validates the object before returning it.
func NewCrownJewel(name string, spec *crownjewelv1.CrownJewelSpec) (*crownjewelv1.CrownJewel, error) {
- cj := &crownjewelv1.CrownJewel{
+ cj := crownjewelv1.CrownJewel_builder{
Kind: types.KindCrownJewel,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
- },
+ }.Build(),
Spec: spec,
- }
+ }.Build()
if err := ValidateCrownJewel(cj); err != nil {
return nil, trace.Wrap(err)
@@ -54,18 +54,18 @@ func ValidateCrownJewel(jewel *crownjewelv1.CrownJewel) error {
switch {
case jewel == nil:
return trace.BadParameter("crown jewel is nil")
- case jewel.Metadata == nil:
+ case !jewel.HasMetadata():
return trace.BadParameter("crown jewel metadata is nil")
- case jewel.Metadata.Name == "":
+ case jewel.GetMetadata().GetName() == "":
return trace.BadParameter("crown jewel name is empty")
- case jewel.Spec == nil:
+ case !jewel.HasSpec():
return trace.BadParameter("crown jewel spec is nil")
- case len(jewel.Spec.TeleportMatchers) == 0 && len(jewel.Spec.AwsMatchers) == 0 && jewel.Spec.Query == "":
+ case len(jewel.GetSpec().GetTeleportMatchers()) == 0 && len(jewel.GetSpec().GetAwsMatchers()) == 0 && jewel.GetSpec().GetQuery() == "":
return trace.BadParameter("crown jewel must have at least one matcher")
}
- if len(jewel.Spec.TeleportMatchers) > 0 {
- for _, matcher := range jewel.Spec.TeleportMatchers {
+ if len(jewel.GetSpec().GetTeleportMatchers()) > 0 {
+ for _, matcher := range jewel.GetSpec().GetTeleportMatchers() {
if len(matcher.GetKinds()) == 0 {
return trace.BadParameter("teleport matcher kinds must be set")
}
@@ -74,20 +74,20 @@ func ValidateCrownJewel(jewel *crownjewelv1.CrownJewel) error {
return trace.Wrap(err)
}
- if len(matcher.Names) == 0 && len(matcher.GetLabels()) == 0 {
+ if len(matcher.GetNames()) == 0 && len(matcher.GetLabels()) == 0 {
return trace.BadParameter("teleport matcher names or labels must be set")
}
for _, label := range matcher.GetLabels() {
- if label.Name == "" || len(label.Values) == 0 {
+ if label.GetName() == "" || len(label.GetValues()) == 0 {
return trace.BadParameter("teleport matcher label name or value is empty")
}
}
}
}
- if len(jewel.Spec.AwsMatchers) > 0 {
- for _, matcher := range jewel.Spec.AwsMatchers {
+ if len(jewel.GetSpec().GetAwsMatchers()) > 0 {
+ for _, matcher := range jewel.GetSpec().GetAwsMatchers() {
if len(matcher.GetTypes()) == 0 {
return trace.BadParameter("aws matcher type must be set")
}
@@ -97,7 +97,7 @@ func ValidateCrownJewel(jewel *crownjewelv1.CrownJewel) error {
}
for _, label := range matcher.GetTags() {
- if label.Key == "" || len(label.Values) == 0 {
+ if label.GetKey() == "" || len(label.GetValues()) == 0 {
return trace.BadParameter("aws matcher tag key or value is empty")
}
}
diff --git a/lib/auth/crownjewel/object_test.go b/lib/auth/crownjewel/object_test.go
index db1c23bbb26..8f8c894d904 100644
--- a/lib/auth/crownjewel/object_test.go
+++ b/lib/auth/crownjewel/object_test.go
@@ -45,184 +45,184 @@ func TestValidateCrownJewel(t *testing.T) {
},
{
name: "ValidCrownJewel",
- jewel: &crownjewelv1.CrownJewel{
- Metadata: &headerv1.Metadata{
+ jewel: crownjewelv1.CrownJewel_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &crownjewelv1.CrownJewelSpec{
+ }.Build(),
+ Spec: crownjewelv1.CrownJewelSpec_builder{
TeleportMatchers: []*crownjewelv1.TeleportMatcher{
- {
+ crownjewelv1.TeleportMatcher_builder{
Kinds: []string{"db"},
Names: []string{"name1"},
Labels: []*labelv1.Label{
- {
+ labelv1.Label_builder{
Name: "label1",
Values: []string{"value1"},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
AwsMatchers: []*crownjewelv1.AWSMatcher{
- {
+ crownjewelv1.AWSMatcher_builder{
Types: []string{"type1"},
Arns: []string{"arn1"},
Tags: []*crownjewelv1.AWSTag{
- {
+ crownjewelv1.AWSTag_builder{
Key: "key1",
Values: []*wrapperspb.StringValue{wrapperspb.String("value1")},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
wantErr: require.NoError,
},
{
name: "ValidCrownJewelWithQuery",
- jewel: &crownjewelv1.CrownJewel{
- Metadata: &headerv1.Metadata{
+ jewel: crownjewelv1.CrownJewel_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &crownjewelv1.CrownJewelSpec{
+ }.Build(),
+ Spec: crownjewelv1.CrownJewelSpec_builder{
Query: "SELECT * FROM nodes",
- },
- },
+ }.Build(),
+ }.Build(),
wantErr: require.NoError,
},
{
name: "MissingMatchers",
- jewel: &crownjewelv1.CrownJewel{
- Metadata: &headerv1.Metadata{
+ jewel: crownjewelv1.CrownJewel_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
+ }.Build(),
Spec: &crownjewelv1.CrownJewelSpec{},
- },
+ }.Build(),
wantErr: require.Error,
},
{
name: "MissingMetadata",
- jewel: &crownjewelv1.CrownJewel{
- Spec: &crownjewelv1.CrownJewelSpec{
+ jewel: crownjewelv1.CrownJewel_builder{
+ Spec: crownjewelv1.CrownJewelSpec_builder{
TeleportMatchers: []*crownjewelv1.TeleportMatcher{
- {
+ crownjewelv1.TeleportMatcher_builder{
Kinds: []string{"kind1"},
Names: []string{"name1"},
Labels: []*labelv1.Label{
- {
+ labelv1.Label_builder{
Name: "label1",
Values: []string{"value1"},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
wantErr: require.Error,
},
{
name: "EmptyName",
- jewel: &crownjewelv1.CrownJewel{
- Metadata: &headerv1.Metadata{
+ jewel: crownjewelv1.CrownJewel_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "",
- },
- Spec: &crownjewelv1.CrownJewelSpec{
+ }.Build(),
+ Spec: crownjewelv1.CrownJewelSpec_builder{
TeleportMatchers: []*crownjewelv1.TeleportMatcher{
- {
+ crownjewelv1.TeleportMatcher_builder{
Kinds: []string{"kind1"},
Names: []string{"name1"},
Labels: []*labelv1.Label{
- {
+ labelv1.Label_builder{
Name: "label1",
Values: []string{"value1"},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
AwsMatchers: []*crownjewelv1.AWSMatcher{
- {
+ crownjewelv1.AWSMatcher_builder{
Types: []string{"type1"},
Arns: []string{"arn1"},
Tags: []*crownjewelv1.AWSTag{
- {
+ crownjewelv1.AWSTag_builder{
Key: "key1",
Values: []*wrapperspb.StringValue{wrapperspb.String("value1")},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
wantErr: require.Error,
},
{
name: "EmptyTeleportMatcherKinds",
- jewel: &crownjewelv1.CrownJewel{
- Metadata: &headerv1.Metadata{
+ jewel: crownjewelv1.CrownJewel_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &crownjewelv1.CrownJewelSpec{
+ }.Build(),
+ Spec: crownjewelv1.CrownJewelSpec_builder{
TeleportMatchers: []*crownjewelv1.TeleportMatcher{
- {
+ crownjewelv1.TeleportMatcher_builder{
Kinds: []string{},
Names: []string{"name1"},
Labels: []*labelv1.Label{
- {
+ labelv1.Label_builder{
Name: "label1",
Values: []string{"value1"},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
AwsMatchers: []*crownjewelv1.AWSMatcher{
- {
+ crownjewelv1.AWSMatcher_builder{
Types: []string{"type1"},
Arns: []string{"arn1"},
Tags: []*crownjewelv1.AWSTag{
- {
+ crownjewelv1.AWSTag_builder{
Key: "key1",
Values: []*wrapperspb.StringValue{wrapperspb.String("value1")},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
wantErr: require.Error,
},
{
name: "EmptyAWSMatcherKinds",
- jewel: &crownjewelv1.CrownJewel{
- Metadata: &headerv1.Metadata{
+ jewel: crownjewelv1.CrownJewel_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &crownjewelv1.CrownJewelSpec{
+ }.Build(),
+ Spec: crownjewelv1.CrownJewelSpec_builder{
TeleportMatchers: []*crownjewelv1.TeleportMatcher{
- {
+ crownjewelv1.TeleportMatcher_builder{
Kinds: []string{"type2"},
Names: []string{"name1"},
Labels: []*labelv1.Label{
- {
+ labelv1.Label_builder{
Name: "label1",
Values: []string{"value1"},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
AwsMatchers: []*crownjewelv1.AWSMatcher{
- {
+ crownjewelv1.AWSMatcher_builder{
Types: []string{},
Arns: []string{"arn1"},
Tags: []*crownjewelv1.AWSTag{
- {
+ crownjewelv1.AWSTag_builder{
Key: "key1",
Values: []*wrapperspb.StringValue{wrapperspb.String("value1")},
- },
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
wantErr: require.Error,
},
}
diff --git a/lib/auth/db_test.go b/lib/auth/db_test.go
index 75e1bd1565a..bda00fa0990 100644
--- a/lib/auth/db_test.go
+++ b/lib/auth/db_test.go
@@ -202,32 +202,32 @@ func TestDBCertSigning(t *testing.T) {
oldCert, err := tlsutils.ParseCertificatePEM(oldCertPEM)
require.NoError(t, err)
- dbClientCAOverride = &subcav1.CertAuthorityOverride{
+ dbClientCAOverride = subcav1.CertAuthorityOverride_builder{
Kind: types.KindCertAuthorityOverride,
SubKind: string(types.DatabaseClientCA),
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: clusterName,
- },
- Spec: &subcav1.CertAuthorityOverrideSpec{
+ }.Build(),
+ Spec: subcav1.CertAuthorityOverrideSpec_builder{
CertificateOverrides: []*subcav1.CertificateOverride{
subCAEnv.NewDisabledCertificateOverride(t, parsedActiveDBClientCert, nil),
subCAEnv.NewDisabledCertificateOverride(t, parsedNewDBClientCert, nil),
subCAEnv.NewDisabledCertificateOverride(t, oldCert, nil),
},
- },
- }
+ }.Build(),
+ }.Build()
// Include external root in the first override's chain.
- dbClientCAOverride.Spec.CertificateOverrides[0].Chain = []string{string(externalRoot.CertPEM)}
+ dbClientCAOverride.GetSpec().GetCertificateOverrides()[0].SetChain([]string{string(externalRoot.CertPEM)})
// Active the old override.
- dbClientCAOverride.Spec.CertificateOverrides[2].Disabled = false
+ dbClientCAOverride.GetSpec().GetCertificateOverrides()[2].SetDisabled(false)
}
// Map self-signed certificates to their overrides.
// Certificates absent from the map don't need to change.
caOverrideCertificateMap := map[string]*subcav1.CertificateOverride{
- string(activeDBClientCACert): dbClientCAOverride.Spec.CertificateOverrides[0],
- string(newDBClientCACert): dbClientCAOverride.Spec.CertificateOverrides[1],
+ string(activeDBClientCACert): dbClientCAOverride.GetSpec().GetCertificateOverrides()[0],
+ string(newDBClientCACert): dbClientCAOverride.GetSpec().GetCertificateOverrides()[1],
}
getOverrideAwareCertificates := func(
selfSignedCert []byte,
@@ -239,21 +239,21 @@ func TestDBCertSigning(t *testing.T) {
}
if includeChain {
- chain = make([][]byte, 0, len(co.Chain)+1)
- chain = append(chain, []byte(co.Certificate))
- for _, pem := range co.Chain {
+ chain = make([][]byte, 0, len(co.GetChain())+1)
+ chain = append(chain, []byte(co.GetCertificate()))
+ for _, pem := range co.GetChain() {
chain = append(chain, []byte(pem))
}
}
- return []byte(co.Certificate), co.PublicKey, chain
+ return []byte(co.GetCertificate()), co.GetPublicKey(), chain
}
mustDeleteCAOverrides := func(t *testing.T) {
t.Helper()
err := authServer.DeleteCertAuthorityOverride(t.Context(), types.CertAuthorityOverrideID{
- ClusterName: dbClientCAOverride.Metadata.Name,
- CAType: dbClientCAOverride.SubKind,
+ ClusterName: dbClientCAOverride.GetMetadata().GetName(),
+ CAType: dbClientCAOverride.GetSubKind(),
})
require.NoError(t, err, "DeleteCertAuthorityOverride errored")
}
@@ -360,8 +360,8 @@ func TestDBCertSigning(t *testing.T) {
t.Run("active_ca_overrides", func(t *testing.T) {
// Take a copy, then enable all overrides.
caOverride := proto.Clone(dbClientCAOverride).(*subcav1.CertAuthorityOverride)
- for _, co := range caOverride.Spec.CertificateOverrides {
- co.Disabled = false
+ for _, co := range caOverride.GetSpec().GetCertificateOverrides() {
+ co.SetDisabled(false)
}
_, err := authServer.CreateCertAuthorityOverride(t.Context(), caOverride)
require.NoError(t, err, "CreateCertAuthorityOverride errored")
diff --git a/lib/auth/dbobject/dbobjectv1/service.go b/lib/auth/dbobject/dbobjectv1/service.go
index 43ecd7a6a8d..c657f5c3553 100644
--- a/lib/auth/dbobject/dbobjectv1/service.go
+++ b/lib/auth/dbobject/dbobjectv1/service.go
@@ -103,11 +103,11 @@ func (rs *DatabaseObjectService) GetDatabaseObject(ctx context.Context, req *pb.
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be non-empty")
}
- out, err := rs.backend.GetDatabaseObject(ctx, req.Name)
+ out, err := rs.backend.GetDatabaseObject(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -123,14 +123,14 @@ func (rs *DatabaseObjectService) ListDatabaseObjects(
return nil, trace.Wrap(err)
}
- out, next, err := rs.backend.ListDatabaseObjects(ctx, int(req.PageSize), req.PageToken)
+ out, next, err := rs.backend.ListDatabaseObjects(ctx, int(req.GetPageSize()), req.GetPageToken())
if err != nil {
return nil, trace.Wrap(err)
}
- return &pb.ListDatabaseObjectsResponse{
+ return pb.ListDatabaseObjectsResponse_builder{
Objects: out,
NextPageToken: next,
- }, nil
+ }.Build(), nil
}
// CreateDatabaseObject creates a new DatabaseObject. It will return an error if the DatabaseObject already
@@ -143,12 +143,12 @@ func (rs *DatabaseObjectService) CreateDatabaseObject(
return nil, trace.Wrap(err)
}
- err = databaseobject.ValidateDatabaseObject(req.Object)
+ err = databaseobject.ValidateDatabaseObject(req.GetObject())
if err != nil {
return nil, trace.Wrap(err, "validating object")
}
- out, err := rs.backend.CreateDatabaseObject(ctx, req.Object)
+ out, err := rs.backend.CreateDatabaseObject(ctx, req.GetObject())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -180,12 +180,12 @@ func (rs *DatabaseObjectService) UpdateDatabaseObject(
return nil, trace.Wrap(err)
}
- err = databaseobject.ValidateDatabaseObject(req.Object)
+ err = databaseobject.ValidateDatabaseObject(req.GetObject())
if err != nil {
return nil, trace.Wrap(err, "validating object")
}
- object, err := rs.backend.UpdateDatabaseObject(ctx, req.Object)
+ object, err := rs.backend.UpdateDatabaseObject(ctx, req.GetObject())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -215,7 +215,7 @@ func (rs *DatabaseObjectService) DeleteDatabaseObject(
return nil, trace.Wrap(err)
}
- err = rs.backend.DeleteDatabaseObject(ctx, req.Name)
+ err = rs.backend.DeleteDatabaseObject(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
diff --git a/lib/auth/dbobjectimportrule/dbobjectimportrulev1/service.go b/lib/auth/dbobjectimportrule/dbobjectimportrulev1/service.go
index a10b1fc7a55..fd1fb64323d 100644
--- a/lib/auth/dbobjectimportrule/dbobjectimportrulev1/service.go
+++ b/lib/auth/dbobjectimportrule/dbobjectimportrulev1/service.go
@@ -103,11 +103,11 @@ func (rs *DatabaseObjectImportRuleService) GetDatabaseObjectImportRule(ctx conte
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be non-empty")
}
- out, err := rs.backend.GetDatabaseObjectImportRule(ctx, req.Name)
+ out, err := rs.backend.GetDatabaseObjectImportRule(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -123,14 +123,14 @@ func (rs *DatabaseObjectImportRuleService) ListDatabaseObjectImportRules(
return nil, trace.Wrap(err)
}
- out, next, err := rs.backend.ListDatabaseObjectImportRules(ctx, int(req.PageSize), req.PageToken)
+ out, next, err := rs.backend.ListDatabaseObjectImportRules(ctx, int(req.GetPageSize()), req.GetPageToken())
if err != nil {
return nil, trace.Wrap(err)
}
- return &pb.ListDatabaseObjectImportRulesResponse{
+ return pb.ListDatabaseObjectImportRulesResponse_builder{
Rules: out,
NextPageToken: next,
- }, nil
+ }.Build(), nil
}
// CreateDatabaseObjectImportRule creates a new DatabaseObjectImportRule. It will return an error if the DatabaseObjectImportRule already
@@ -143,12 +143,12 @@ func (rs *DatabaseObjectImportRuleService) CreateDatabaseObjectImportRule(
return nil, trace.Wrap(err)
}
- err = databaseobjectimportrule.ValidateDatabaseObjectImportRule(req.Rule)
+ err = databaseobjectimportrule.ValidateDatabaseObjectImportRule(req.GetRule())
if err != nil {
return nil, trace.Wrap(err, "validating rule")
}
- out, err := rs.backend.CreateDatabaseObjectImportRule(ctx, req.Rule)
+ out, err := rs.backend.CreateDatabaseObjectImportRule(ctx, req.GetRule())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -180,12 +180,12 @@ func (rs *DatabaseObjectImportRuleService) UpdateDatabaseObjectImportRule(
return nil, trace.Wrap(err)
}
- err = databaseobjectimportrule.ValidateDatabaseObjectImportRule(req.Rule)
+ err = databaseobjectimportrule.ValidateDatabaseObjectImportRule(req.GetRule())
if err != nil {
return nil, trace.Wrap(err, "validating rule")
}
- rule, err := rs.backend.UpdateDatabaseObjectImportRule(ctx, req.Rule)
+ rule, err := rs.backend.UpdateDatabaseObjectImportRule(ctx, req.GetRule())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -215,7 +215,7 @@ func (rs *DatabaseObjectImportRuleService) DeleteDatabaseObjectImportRule(
return nil, trace.Wrap(err)
}
- err = rs.backend.DeleteDatabaseObjectImportRule(ctx, req.Name)
+ err = rs.backend.DeleteDatabaseObjectImportRule(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
diff --git a/lib/auth/delegation/delegationv1/create_delegation_session.go b/lib/auth/delegation/delegationv1/create_delegation_session.go
index cae089aedf5..de3c6feb7c2 100644
--- a/lib/auth/delegation/delegationv1/create_delegation_session.go
+++ b/lib/auth/delegation/delegationv1/create_delegation_session.go
@@ -77,15 +77,15 @@ func (s *SessionService) CreateDelegationSession(
return nil, trace.BadParameter("ttl: cannot be more than %d hours", sessionMaxTTL/time.Hour)
}
- session := &delegationv1.DelegationSession{
+ session := delegationv1.DelegationSession_builder{
Kind: types.KindDelegationSession,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
Expires: timestamppb.New(time.Now().Add(ttl)),
- },
+ }.Build(),
Spec: req.GetSpec(),
- }
+ }.Build()
spec := session.GetSpec()
resources := spec.GetResources()
diff --git a/lib/auth/delegation/delegationv1/create_delegation_session_test.go b/lib/auth/delegation/delegationv1/create_delegation_session_test.go
index 5bc5ad00b23..2eaa59c4500 100644
--- a/lib/auth/delegation/delegationv1/create_delegation_session_test.go
+++ b/lib/auth/delegation/delegationv1/create_delegation_session_test.go
@@ -27,6 +27,7 @@ import (
"github.com/gravitational/trace"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/durationpb"
@@ -58,10 +59,10 @@ func TestSessionService_CreateSession(t *testing.T) {
expectedExpires := time.Now().Add(5 * time.Minute)
expectedSpec := newDelegationSessionSpec("bob")
- session, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ session, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: expectedSpec,
Ttl: durationpb.New(5 * time.Minute),
- })
+ }.Build())
require.NoError(t, err)
assert.Equal(t, types.KindDelegationSession, session.GetKind())
@@ -91,16 +92,16 @@ func TestSessionService_CreateSession(t *testing.T) {
types.RoleSpecV6{},
)
- session, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ session, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: newDelegationSessionSpec(
"bob",
- &delegationv1pb.DelegationResourceSpec{
+ delegationv1pb.DelegationResourceSpec_builder{
Kind: types.Wildcard,
Name: types.Wildcard,
- },
+ }.Build(),
),
Ttl: durationpb.New(5 * time.Minute),
- })
+ }.Build())
require.NoError(t, err)
assert.Equal(t, types.Wildcard, session.GetSpec().GetResources()[0].GetKind())
assert.Equal(t, types.Wildcard, session.GetSpec().GetResources()[0].GetName())
@@ -115,10 +116,10 @@ func TestSessionService_CreateSession(t *testing.T) {
types.RoleSpecV6{},
)
- _, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ _, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: newDelegationSessionSpec("bob"),
Ttl: durationpb.New(5 * time.Minute),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
require.ErrorContains(t, err, "user does not have permission to delegate access to all of the required resources")
@@ -139,16 +140,16 @@ func TestSessionService_CreateSession(t *testing.T) {
},
)
- _, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ _, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: newDelegationSessionSpec(
"bob",
- &delegationv1pb.DelegationResourceSpec{
+ delegationv1pb.DelegationResourceSpec_builder{
Kind: types.KindApp,
Name: "unknown-app",
- },
+ }.Build(),
),
Ttl: durationpb.New(5 * time.Minute),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
require.ErrorContains(t, err, "missing resources: [app/unknown-app]")
@@ -169,10 +170,10 @@ func TestSessionService_CreateSession(t *testing.T) {
},
)
- _, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ _, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: newDelegationSessionSpec("alice"),
Ttl: durationpb.New(5 * time.Minute),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
require.ErrorContains(t, err, "cannot create a delegation session for a different user")
@@ -193,10 +194,10 @@ func TestSessionService_CreateSession(t *testing.T) {
},
)
- _, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ _, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: newDelegationSessionSpec("bob"),
Ttl: durationpb.New(5 * time.Minute),
- })
+ }.Build())
require.Error(t, err)
require.ErrorIs(t, err, &mfa.ErrAdminActionMFARequired)
})
@@ -218,10 +219,10 @@ func TestSessionService_CreateSession(t *testing.T) {
},
)
- _, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ _, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: newDelegationSessionSpec("bob"),
Ttl: durationpb.New(5 * time.Minute),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
require.ErrorContains(t, err, "cannot create a delegation session from within a delegation session")
@@ -243,10 +244,10 @@ func TestSessionService_CreateSession(t *testing.T) {
},
)
- _, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ _, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: newDelegationSessionSpec("bob"),
Ttl: durationpb.New(5 * time.Minute),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
require.ErrorContains(t, err, "cannot create a delegation session because certificate reissuance is prohibited")
@@ -267,9 +268,9 @@ func TestSessionService_CreateSession(t *testing.T) {
},
)
- _, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ _, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: newDelegationSessionSpec("bob"),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "ttl: is required")
@@ -290,10 +291,10 @@ func TestSessionService_CreateSession(t *testing.T) {
},
)
- _, err := service.CreateDelegationSession(t.Context(), &delegationv1pb.CreateDelegationSessionRequest{
+ _, err := service.CreateDelegationSession(t.Context(), delegationv1pb.CreateDelegationSessionRequest_builder{
Spec: newDelegationSessionSpec("bob"),
Ttl: durationpb.New(14 * 24 * time.Hour),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "ttl: cannot be more than 168 hours")
@@ -306,23 +307,21 @@ func newDelegationSessionSpec(
) *delegationv1pb.DelegationSessionSpec {
if len(resources) == 0 {
resources = []*delegationv1pb.DelegationResourceSpec{
- {
+ delegationv1pb.DelegationResourceSpec_builder{
Kind: types.KindApp,
Name: "hr-system",
- },
+ }.Build(),
}
}
- return &delegationv1pb.DelegationSessionSpec{
+ return delegationv1pb.DelegationSessionSpec_builder{
User: user,
Resources: resources,
AuthorizedUsers: []*delegationv1pb.DelegationUserSpec{
- {
- Kind: types.KindBot,
- Matcher: &delegationv1pb.DelegationUserSpec_BotName{
- BotName: "payroll-agent",
- },
- },
+ delegationv1pb.DelegationUserSpec_builder{
+ Kind: types.KindBot,
+ BotName: proto.String("payroll-agent"),
+ }.Build(),
},
- }
+ }.Build()
}
diff --git a/lib/auth/delegation/delegationv1/generate_certs.go b/lib/auth/delegation/delegationv1/generate_certs.go
index dd8e55c9f5a..c7f9b2f1196 100644
--- a/lib/auth/delegation/delegationv1/generate_certs.go
+++ b/lib/auth/delegation/delegationv1/generate_certs.go
@@ -251,11 +251,11 @@ func (s *SessionService) generateCertificates(
}
// Add the protocol-specific routing hints to the certificate.
- switch routing := req.Routing.(type) {
- case *delegationv1.GenerateCertsRequest_RouteToKubernetes:
- certReq.KubernetesCluster = routing.RouteToKubernetes.GetClusterName()
- case *delegationv1.GenerateCertsRequest_RouteToApp:
- route := routing.RouteToApp
+ switch req.WhichRouting() {
+ case delegationv1.GenerateCertsRequest_RouteToKubernetes_case:
+ certReq.KubernetesCluster = req.GetRouteToKubernetes().GetClusterName()
+ case delegationv1.GenerateCertsRequest_RouteToApp_case:
+ route := req.GetRouteToApp()
certReq.AppPublicAddr = route.GetPublicAddr()
certReq.AppClusterName = route.GetClusterName()
@@ -296,8 +296,8 @@ func (s *SessionService) generateCertificates(
return nil, trace.Wrap(err)
}
certReq.AppSessionID = appSession.GetName()
- case *delegationv1.GenerateCertsRequest_RouteToDatabase:
- route := routing.RouteToDatabase
+ case delegationv1.GenerateCertsRequest_RouteToDatabase_case:
+ route := req.GetRouteToDatabase()
certReq.DBService = route.GetServiceName()
certReq.DBProtocol = route.GetProtocol()
@@ -310,10 +310,10 @@ func (s *SessionService) generateCertificates(
if err != nil {
return nil, trace.Wrap(err)
}
- return &delegationv1.GenerateCertsResponse{
+ return delegationv1.GenerateCertsResponse_builder{
Ssh: certs.SSH,
Tls: certs.TLS,
- }, nil
+ }.Build(), nil
}
func (s *SessionService) getRoleSet(ctx context.Context, user services.UserState) (services.RoleSet, error) {
diff --git a/lib/auth/delegation/delegationv1/generate_certs_test.go b/lib/auth/delegation/delegationv1/generate_certs_test.go
index ec46eef54d0..c5d6ebd5045 100644
--- a/lib/auth/delegation/delegationv1/generate_certs_test.go
+++ b/lib/auth/delegation/delegationv1/generate_certs_test.go
@@ -27,9 +27,10 @@ import (
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
- "github.com/gravitational/teleport/api/client/proto"
+ clientproto "github.com/gravitational/teleport/api/client/proto"
delegationv1pb "github.com/gravitational/teleport/api/gen/proto/go/teleport/delegation/v1"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/auth/delegation/delegationv1"
@@ -59,23 +60,21 @@ func TestSessionService_GenerateCerts(t *testing.T) {
},
})
- session := pack.createSession(t, &delegationv1pb.DelegationSessionSpec{
+ session := pack.createSession(t, delegationv1pb.DelegationSessionSpec_builder{
User: "bob",
Resources: []*delegationv1pb.DelegationResourceSpec{
- {
+ delegationv1pb.DelegationResourceSpec_builder{
Kind: types.KindApp,
Name: "hr-system",
- },
+ }.Build(),
},
AuthorizedUsers: []*delegationv1pb.DelegationUserSpec{
- {
- Kind: types.KindBot,
- Matcher: &delegationv1pb.DelegationUserSpec_BotName{
- BotName: "payroll-agent",
- },
- },
+ delegationv1pb.DelegationUserSpec_builder{
+ Kind: types.KindBot,
+ BotName: proto.String("payroll-agent"),
+ }.Build(),
},
- })
+ }.Build())
appSession, err := types.NewWebSession(
uuid.NewString(),
@@ -104,7 +103,7 @@ func TestSessionService_GenerateCerts(t *testing.T) {
return appSession, nil
}
- pack.onGenerateCert = func(_ context.Context, req cert.Request) (*proto.Certs, error) {
+ pack.onGenerateCert = func(_ context.Context, req cert.Request) (*clientproto.Certs, error) {
require.Equal(t, "bob", req.User.GetName())
require.Equal(t, sshPublicKey, req.SSHPublicKey)
require.Equal(t, tlsPublicKey, req.TLSPublicKey)
@@ -132,34 +131,32 @@ func TestSessionService_GenerateCerts(t *testing.T) {
require.Equal(t, appSession.GetName(), req.AppSessionID)
require.Equal(t, "payroll-agent", req.BotName)
- return &proto.Certs{
+ return &clientproto.Certs{
TLS: tlsCertificate,
SSH: sshCertificate,
}, nil
}
pack.authenticateBot("payroll-agent")
- rsp, err := service.GenerateCerts(t.Context(), &delegationv1pb.GenerateCertsRequest{
+ rsp, err := service.GenerateCerts(t.Context(), delegationv1pb.GenerateCertsRequest_builder{
DelegationSessionId: session.GetMetadata().GetName(),
SshPublicKey: sshPublicKey,
TlsPublicKey: tlsPublicKey,
Ttl: durationpb.New(5 * time.Minute),
- Routing: &delegationv1pb.GenerateCertsRequest_RouteToApp{
- RouteToApp: &delegationv1pb.RouteToApp{
- Name: "hr-system",
- PublicAddr: "hr-system.test.teleport.sh",
- ClusterName: "test.teleport.sh",
- Uri: "http://localhost:9000",
- TargetPort: 9000,
- },
- },
- })
+ RouteToApp: delegationv1pb.RouteToApp_builder{
+ Name: "hr-system",
+ PublicAddr: "hr-system.test.teleport.sh",
+ ClusterName: "test.teleport.sh",
+ Uri: "http://localhost:9000",
+ TargetPort: 9000,
+ }.Build(),
+ }.Build())
require.NoError(t, err)
require.Equal(t,
- &delegationv1pb.GenerateCertsResponse{
+ delegationv1pb.GenerateCertsResponse_builder{
Ssh: sshCertificate,
Tls: tlsCertificate,
- },
+ }.Build(),
rsp,
)
})
@@ -176,20 +173,18 @@ func TestSessionService_GenerateCerts(t *testing.T) {
},
})
- session := pack.createSession(t, &delegationv1pb.DelegationSessionSpec{
+ session := pack.createSession(t, delegationv1pb.DelegationSessionSpec_builder{
User: "bob",
Resources: []*delegationv1pb.DelegationResourceSpec{
- {Kind: types.Wildcard, Name: types.Wildcard},
+ delegationv1pb.DelegationResourceSpec_builder{Kind: types.Wildcard, Name: types.Wildcard}.Build(),
},
AuthorizedUsers: []*delegationv1pb.DelegationUserSpec{
- {
- Kind: types.KindBot,
- Matcher: &delegationv1pb.DelegationUserSpec_BotName{
- BotName: "payroll-agent",
- },
- },
+ delegationv1pb.DelegationUserSpec_builder{
+ Kind: types.KindBot,
+ BotName: proto.String("payroll-agent"),
+ }.Build(),
},
- })
+ }.Build())
appSession, err := types.NewWebSession(
uuid.NewString(),
@@ -206,39 +201,37 @@ func TestSessionService_GenerateCerts(t *testing.T) {
return appSession, nil
}
- pack.onGenerateCert = func(_ context.Context, req cert.Request) (*proto.Certs, error) {
+ pack.onGenerateCert = func(_ context.Context, req cert.Request) (*clientproto.Certs, error) {
params := req.CheckerContext.CertParams().UnscopedCertParams()
require.NotNil(t, params)
require.Empty(t, params.GetAllowedResourceAccessIDs())
- return &proto.Certs{
+ return &clientproto.Certs{
TLS: tlsCertificate,
SSH: sshCertificate,
}, nil
}
pack.authenticateBot("payroll-agent")
- rsp, err := service.GenerateCerts(t.Context(), &delegationv1pb.GenerateCertsRequest{
+ rsp, err := service.GenerateCerts(t.Context(), delegationv1pb.GenerateCertsRequest_builder{
DelegationSessionId: session.GetMetadata().GetName(),
SshPublicKey: sshPublicKey,
TlsPublicKey: tlsPublicKey,
Ttl: durationpb.New(5 * time.Minute),
- Routing: &delegationv1pb.GenerateCertsRequest_RouteToApp{
- RouteToApp: &delegationv1pb.RouteToApp{
- Name: "hr-system",
- PublicAddr: "hr-system.test.teleport.sh",
- ClusterName: "test.teleport.sh",
- Uri: "http://localhost:9000",
- TargetPort: 9000,
- },
- },
- })
+ RouteToApp: delegationv1pb.RouteToApp_builder{
+ Name: "hr-system",
+ PublicAddr: "hr-system.test.teleport.sh",
+ ClusterName: "test.teleport.sh",
+ Uri: "http://localhost:9000",
+ TargetPort: 9000,
+ }.Build(),
+ }.Build())
require.NoError(t, err)
require.Equal(t,
- &delegationv1pb.GenerateCertsResponse{
+ delegationv1pb.GenerateCertsResponse_builder{
Ssh: sshCertificate,
Tls: tlsCertificate,
- },
+ }.Build(),
rsp,
)
})
@@ -248,12 +241,12 @@ func TestSessionService_GenerateCerts(t *testing.T) {
service, pack := sessionServiceTestPack(t)
pack.authenticateBot("payroll-agent")
- _, err := service.GenerateCerts(t.Context(), &delegationv1pb.GenerateCertsRequest{
+ _, err := service.GenerateCerts(t.Context(), delegationv1pb.GenerateCertsRequest_builder{
DelegationSessionId: uuid.NewString(),
SshPublicKey: sshPublicKey,
TlsPublicKey: tlsPublicKey,
Ttl: durationpb.New(1 * time.Hour),
- })
+ }.Build())
require.ErrorIs(t, err, delegationv1.ErrDelegationUnauthorized)
})
@@ -268,30 +261,28 @@ func TestSessionService_GenerateCerts(t *testing.T) {
})
pack.authenticateBot("evil-bot")
- session := pack.createSession(t, &delegationv1pb.DelegationSessionSpec{
+ session := pack.createSession(t, delegationv1pb.DelegationSessionSpec_builder{
User: "bob",
Resources: []*delegationv1pb.DelegationResourceSpec{
- {
+ delegationv1pb.DelegationResourceSpec_builder{
Kind: types.KindApp,
Name: "hr-system",
- },
+ }.Build(),
},
AuthorizedUsers: []*delegationv1pb.DelegationUserSpec{
- {
- Kind: types.KindBot,
- Matcher: &delegationv1pb.DelegationUserSpec_BotName{
- BotName: "payroll-agent",
- },
- },
+ delegationv1pb.DelegationUserSpec_builder{
+ Kind: types.KindBot,
+ BotName: proto.String("payroll-agent"),
+ }.Build(),
},
- })
+ }.Build())
- _, err := service.GenerateCerts(t.Context(), &delegationv1pb.GenerateCertsRequest{
+ _, err := service.GenerateCerts(t.Context(), delegationv1pb.GenerateCertsRequest_builder{
DelegationSessionId: session.GetMetadata().GetName(),
SshPublicKey: sshPublicKey,
TlsPublicKey: tlsPublicKey,
Ttl: durationpb.New(1 * time.Hour),
- })
+ }.Build())
require.ErrorIs(t, err, delegationv1.ErrDelegationUnauthorized)
})
@@ -306,30 +297,28 @@ func TestSessionService_GenerateCerts(t *testing.T) {
})
pack.authenticateBotInDelegationSession("payroll-agent", "source-delegation-session")
- session := pack.createSession(t, &delegationv1pb.DelegationSessionSpec{
+ session := pack.createSession(t, delegationv1pb.DelegationSessionSpec_builder{
User: "bob",
Resources: []*delegationv1pb.DelegationResourceSpec{
- {
+ delegationv1pb.DelegationResourceSpec_builder{
Kind: types.KindApp,
Name: "hr-system",
- },
+ }.Build(),
},
AuthorizedUsers: []*delegationv1pb.DelegationUserSpec{
- {
- Kind: types.KindBot,
- Matcher: &delegationv1pb.DelegationUserSpec_BotName{
- BotName: "payroll-agent",
- },
- },
+ delegationv1pb.DelegationUserSpec_builder{
+ Kind: types.KindBot,
+ BotName: proto.String("payroll-agent"),
+ }.Build(),
},
- })
+ }.Build())
- _, err := service.GenerateCerts(t.Context(), &delegationv1pb.GenerateCertsRequest{
+ _, err := service.GenerateCerts(t.Context(), delegationv1pb.GenerateCertsRequest_builder{
DelegationSessionId: session.GetMetadata().GetName(),
SshPublicKey: sshPublicKey,
TlsPublicKey: tlsPublicKey,
Ttl: durationpb.New(1 * time.Hour),
- })
+ }.Build())
require.ErrorIs(t, err, delegationv1.ErrDelegationUnauthorized)
})
@@ -345,33 +334,31 @@ func TestSessionService_GenerateCerts(t *testing.T) {
})
pack.authenticateBot("payroll-agent")
- session := pack.createSession(t, &delegationv1pb.DelegationSessionSpec{
+ session := pack.createSession(t, delegationv1pb.DelegationSessionSpec_builder{
User: "bob",
Resources: []*delegationv1pb.DelegationResourceSpec{
- {
+ delegationv1pb.DelegationResourceSpec_builder{
Kind: types.KindApp,
Name: "hr-system",
- },
+ }.Build(),
},
AuthorizedUsers: []*delegationv1pb.DelegationUserSpec{
- {
- Kind: types.KindBot,
- Matcher: &delegationv1pb.DelegationUserSpec_BotName{
- BotName: "payroll-agent",
- },
- },
+ delegationv1pb.DelegationUserSpec_builder{
+ Kind: types.KindBot,
+ BotName: proto.String("payroll-agent"),
+ }.Build(),
},
- })
+ }.Build())
// This won't actually sleep, thanks to synctest!
time.Sleep(time.Until(session.GetMetadata().GetExpires().AsTime().Add(delegationv1.ClockSkewAllowance)))
- _, err := service.GenerateCerts(t.Context(), &delegationv1pb.GenerateCertsRequest{
+ _, err := service.GenerateCerts(t.Context(), delegationv1pb.GenerateCertsRequest_builder{
DelegationSessionId: session.GetMetadata().GetName(),
SshPublicKey: sshPublicKey,
TlsPublicKey: tlsPublicKey,
Ttl: durationpb.New(1 * time.Hour),
- })
+ }.Build())
require.ErrorIs(t, err, delegationv1.ErrDelegationUnauthorized)
})
})
@@ -381,30 +368,28 @@ func TestSessionService_GenerateCerts(t *testing.T) {
pack.createUser(t, "bob", types.RoleSpecV6{})
pack.authenticateBot("payroll-agent")
- session := pack.createSession(t, &delegationv1pb.DelegationSessionSpec{
+ session := pack.createSession(t, delegationv1pb.DelegationSessionSpec_builder{
User: "bob",
Resources: []*delegationv1pb.DelegationResourceSpec{
- {
+ delegationv1pb.DelegationResourceSpec_builder{
Kind: types.KindApp,
Name: "hr-system",
- },
+ }.Build(),
},
AuthorizedUsers: []*delegationv1pb.DelegationUserSpec{
- {
- Kind: types.KindBot,
- Matcher: &delegationv1pb.DelegationUserSpec_BotName{
- BotName: "payroll-agent",
- },
- },
+ delegationv1pb.DelegationUserSpec_builder{
+ Kind: types.KindBot,
+ BotName: proto.String("payroll-agent"),
+ }.Build(),
},
- })
+ }.Build())
- _, err := service.GenerateCerts(t.Context(), &delegationv1pb.GenerateCertsRequest{
+ _, err := service.GenerateCerts(t.Context(), delegationv1pb.GenerateCertsRequest_builder{
DelegationSessionId: session.GetMetadata().GetName(),
SshPublicKey: sshPublicKey,
TlsPublicKey: tlsPublicKey,
Ttl: durationpb.New(1 * time.Hour),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
require.ErrorContains(t, err, "user does not have permission to delegate access to all of the required resources")
@@ -434,49 +419,45 @@ func TestSessionService_GenerateCerts(t *testing.T) {
return appSession, nil
}
- pack.onGenerateCert = func(_ context.Context, req cert.Request) (*proto.Certs, error) {
+ pack.onGenerateCert = func(_ context.Context, req cert.Request) (*clientproto.Certs, error) {
require.Equal(t, 1*time.Hour, req.TTL) // This is the session expiry, not the requested TTL.
- return &proto.Certs{
+ return &clientproto.Certs{
TLS: tlsCertificate,
SSH: sshCertificate,
}, nil
}
pack.authenticateBot("payroll-agent")
- session := pack.createSession(t, &delegationv1pb.DelegationSessionSpec{
+ session := pack.createSession(t, delegationv1pb.DelegationSessionSpec_builder{
User: "bob",
Resources: []*delegationv1pb.DelegationResourceSpec{
- {
+ delegationv1pb.DelegationResourceSpec_builder{
Kind: types.KindApp,
Name: "hr-system",
- },
+ }.Build(),
},
AuthorizedUsers: []*delegationv1pb.DelegationUserSpec{
- {
- Kind: types.KindBot,
- Matcher: &delegationv1pb.DelegationUserSpec_BotName{
- BotName: "payroll-agent",
- },
- },
+ delegationv1pb.DelegationUserSpec_builder{
+ Kind: types.KindBot,
+ BotName: proto.String("payroll-agent"),
+ }.Build(),
},
- })
+ }.Build())
- _, err = service.GenerateCerts(t.Context(), &delegationv1pb.GenerateCertsRequest{
+ _, err = service.GenerateCerts(t.Context(), delegationv1pb.GenerateCertsRequest_builder{
DelegationSessionId: session.GetMetadata().GetName(),
SshPublicKey: sshPublicKey,
TlsPublicKey: tlsPublicKey,
Ttl: durationpb.New(365 * 24 * 1 * time.Hour),
- Routing: &delegationv1pb.GenerateCertsRequest_RouteToApp{
- RouteToApp: &delegationv1pb.RouteToApp{
- Name: "hr-system",
- PublicAddr: "hr-system.test.teleport.sh",
- ClusterName: "test.teleport.sh",
- Uri: "http://localhost:9000",
- TargetPort: 9000,
- },
- },
- })
+ RouteToApp: delegationv1pb.RouteToApp_builder{
+ Name: "hr-system",
+ PublicAddr: "hr-system.test.teleport.sh",
+ ClusterName: "test.teleport.sh",
+ Uri: "http://localhost:9000",
+ TargetPort: 9000,
+ }.Build(),
+ }.Build())
require.NoError(t, err)
})
})
diff --git a/lib/auth/delegation/delegationv1/session_service_test.go b/lib/auth/delegation/delegationv1/session_service_test.go
index 4c33eb89177..7b2a8d5a87f 100644
--- a/lib/auth/delegation/delegationv1/session_service_test.go
+++ b/lib/auth/delegation/delegationv1/session_service_test.go
@@ -250,15 +250,15 @@ func (p *sessionTestPack) authenticateBotInDelegationSession(botName, delegation
func (p *sessionTestPack) createSession(t *testing.T, spec *delegationv1pb.DelegationSessionSpec) *delegationv1pb.DelegationSession {
t.Helper()
- session, err := p.sessions.CreateDelegationSession(t.Context(), &delegationv1pb.DelegationSession{
+ session, err := p.sessions.CreateDelegationSession(t.Context(), delegationv1pb.DelegationSession_builder{
Kind: types.KindDelegationSession,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
Expires: timestamppb.New(time.Now().Add(time.Hour)),
- },
+ }.Build(),
Spec: spec,
- })
+ }.Build())
require.NoError(t, err)
return session
diff --git a/lib/auth/desktop_test.go b/lib/auth/desktop_test.go
index 872d4b590ac..d2e827a749c 100644
--- a/lib/auth/desktop_test.go
+++ b/lib/auth/desktop_test.go
@@ -117,16 +117,16 @@ func TestDesktopAccessCAOverrides(t *testing.T) {
ExternalRoot: externalCA,
}
caOverride := env.NewOverrideForCA(t, ca, nil)
- override := caOverride.Spec.CertificateOverrides[0]
- override.Disabled = false // enable
+ override := caOverride.GetSpec().GetCertificateOverrides()[0]
+ override.SetDisabled(false) // enable
_, err = authServer.CreateCertAuthorityOverride(t.Context(), caOverride)
require.NoError(t, err, "CreateCertAuthorityOverride errored")
- overrideCert, err := tlsutils.ParseCertificatePEM([]byte(override.Certificate))
+ overrideCert, err := tlsutils.ParseCertificatePEM([]byte(override.GetCertificate()))
require.NoError(t, err)
t.Run("generate with override", func(t *testing.T) {
runTest(t, overrideCert, &proto.CAOverrideCertificateDetails{
- PublicKeyHash: override.PublicKey,
+ PublicKeyHash: override.GetPublicKey(),
})
})
}
diff --git a/lib/auth/discoveryconfig/discoveryconfigv1/service.go b/lib/auth/discoveryconfig/discoveryconfigv1/service.go
index 2265e77cc73..e7e944a3af9 100644
--- a/lib/auth/discoveryconfig/discoveryconfigv1/service.go
+++ b/lib/auth/discoveryconfig/discoveryconfigv1/service.go
@@ -149,10 +149,10 @@ func (s *Service) ListDiscoveryConfigs(ctx context.Context, req *discoveryconfig
dcs[i] = conv.ToProto(downgraded)
}
- return &discoveryconfigv1.ListDiscoveryConfigsResponse{
+ return discoveryconfigv1.ListDiscoveryConfigsResponse_builder{
DiscoveryConfigs: dcs,
NextKey: nextKey,
- }, nil
+ }.Build(), nil
}
// GetDiscoveryConfig returns the specified DiscoveryConfig resource.
@@ -166,7 +166,7 @@ func (s *Service) GetDiscoveryConfig(ctx context.Context, req *discoveryconfigv1
return nil, trace.Wrap(err)
}
- dc, err := s.backend.GetDiscoveryConfig(ctx, req.Name)
+ dc, err := s.backend.GetDiscoveryConfig(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -347,7 +347,7 @@ func (s *Service) DeleteDiscoveryConfig(ctx context.Context, req *discoveryconfi
},
UserMetadata: authCtx.GetUserMetadata(),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.Name,
+ Name: req.GetName(),
},
ConnectionMetadata: authz.ConnectionMetadata(ctx),
}); err != nil {
diff --git a/lib/auth/discoveryconfig/discoveryconfigv1/service_test.go b/lib/auth/discoveryconfig/discoveryconfigv1/service_test.go
index ec739a265a9..b979c8586b7 100644
--- a/lib/auth/discoveryconfig/discoveryconfigv1/service_test.go
+++ b/lib/auth/discoveryconfig/discoveryconfigv1/service_test.go
@@ -87,9 +87,9 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
- _, err := resourceSvc.GetDiscoveryConfig(ctx, &discoveryconfigpb.GetDiscoveryConfigRequest{
+ _, err := resourceSvc.GetDiscoveryConfig(ctx, discoveryconfigpb.GetDiscoveryConfigRequest_builder{
Name: dcName,
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -98,9 +98,9 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
Name: "no access to read discovery configs",
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
- _, err := resourceSvc.GetDiscoveryConfig(ctx, &discoveryconfigpb.GetDiscoveryConfigRequest{
+ _, err := resourceSvc.GetDiscoveryConfig(ctx, discoveryconfigpb.GetDiscoveryConfigRequest_builder{
Name: dcName,
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -114,9 +114,9 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
}}},
},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
- _, err := resourceSvc.GetDiscoveryConfig(ctx, &discoveryconfigpb.GetDiscoveryConfigRequest{
+ _, err := resourceSvc.GetDiscoveryConfig(ctx, discoveryconfigpb.GetDiscoveryConfigRequest_builder{
Name: dcName,
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -138,10 +138,10 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
}
},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
- _, err := resourceSvc.ListDiscoveryConfigs(ctx, &discoveryconfigpb.ListDiscoveryConfigsRequest{
+ _, err := resourceSvc.ListDiscoveryConfigs(ctx, discoveryconfigpb.ListDiscoveryConfigsRequest_builder{
PageSize: 0,
NextToken: "",
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -155,10 +155,10 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
}}},
},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
- _, err := resourceSvc.ListDiscoveryConfigs(ctx, &discoveryconfigpb.ListDiscoveryConfigsRequest{
+ _, err := resourceSvc.ListDiscoveryConfigs(ctx, discoveryconfigpb.ListDiscoveryConfigsRequest_builder{
PageSize: 0,
NextToken: "",
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -170,9 +170,9 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
dc := sampleDiscoveryConfigFn(t, dcName)
- _, err := resourceSvc.CreateDiscoveryConfig(ctx, &discoveryconfigpb.CreateDiscoveryConfigRequest{
+ _, err := resourceSvc.CreateDiscoveryConfig(ctx, discoveryconfigpb.CreateDiscoveryConfigRequest_builder{
DiscoveryConfig: convert.ToProto(dc),
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -187,9 +187,9 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
dc := sampleDiscoveryConfigFn(t, dcName)
- _, err := resourceSvc.CreateDiscoveryConfig(ctx, &discoveryconfigpb.CreateDiscoveryConfigRequest{
+ _, err := resourceSvc.CreateDiscoveryConfig(ctx, discoveryconfigpb.CreateDiscoveryConfigRequest_builder{
DiscoveryConfig: convert.ToProto(dc),
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -201,9 +201,9 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
dc := sampleDiscoveryConfigFn(t, dcName)
- _, err := resourceSvc.UpdateDiscoveryConfig(ctx, &discoveryconfigpb.UpdateDiscoveryConfigRequest{
+ _, err := resourceSvc.UpdateDiscoveryConfig(ctx, discoveryconfigpb.UpdateDiscoveryConfigRequest_builder{
DiscoveryConfig: convert.ToProto(dc),
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -222,9 +222,9 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
dc := sampleDiscoveryConfigFn(t, dcName)
- _, err := resourceSvc.UpdateDiscoveryConfig(ctx, &discoveryconfigpb.UpdateDiscoveryConfigRequest{
+ _, err := resourceSvc.UpdateDiscoveryConfig(ctx, discoveryconfigpb.UpdateDiscoveryConfigRequest_builder{
DiscoveryConfig: convert.ToProto(dc),
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -241,9 +241,9 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
dc := sampleDiscoveryConfigFn(t, dcName)
- _, err := resourceSvc.UpsertDiscoveryConfig(ctx, &discoveryconfigpb.UpsertDiscoveryConfigRequest{
+ _, err := resourceSvc.UpsertDiscoveryConfig(ctx, discoveryconfigpb.UpsertDiscoveryConfigRequest_builder{
DiscoveryConfig: convert.ToProto(dc),
- })
+ }.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -259,9 +259,9 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
Setup: func(t *testing.T, dcName string) {},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
dc := sampleDiscoveryConfigFn(t, dcName)
- _, err := resourceSvc.UpsertDiscoveryConfig(ctx, &discoveryconfigpb.UpsertDiscoveryConfigRequest{
+ _, err := resourceSvc.UpsertDiscoveryConfig(ctx, discoveryconfigpb.UpsertDiscoveryConfigRequest_builder{
DiscoveryConfig: convert.ToProto(dc),
- })
+ }.Build())
return err
},
ErrAssertion: require.NoError,
@@ -272,7 +272,7 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
Name: "no access to delete discovery config",
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
- _, err := resourceSvc.DeleteDiscoveryConfig(ctx, &discoveryconfigpb.DeleteDiscoveryConfigRequest{Name: "x"})
+ _, err := resourceSvc.DeleteDiscoveryConfig(ctx, discoveryconfigpb.DeleteDiscoveryConfigRequest_builder{Name: "x"}.Build())
return err
},
ErrAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -290,7 +290,7 @@ func TestDiscoveryConfigCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, dcName string) error {
- _, err := resourceSvc.DeleteDiscoveryConfig(ctx, &discoveryconfigpb.DeleteDiscoveryConfigRequest{Name: dcName})
+ _, err := resourceSvc.DeleteDiscoveryConfig(ctx, discoveryconfigpb.DeleteDiscoveryConfigRequest_builder{Name: dcName}.Build())
return err
},
ErrAssertion: require.NoError,
@@ -376,9 +376,9 @@ func TestUpdateDiscoveryConfigStatus(t *testing.T) {
name: "no access to update discovery config status",
systemRole: types.RoleNode,
test: func(t *testing.T, ctx context.Context, resourceSvc *Service, dcName string) error {
- _, err := resourceSvc.UpdateDiscoveryConfigStatus(ctx, &discoveryconfigpb.UpdateDiscoveryConfigStatusRequest{
+ _, err := resourceSvc.UpdateDiscoveryConfigStatus(ctx, discoveryconfigpb.UpdateDiscoveryConfigStatusRequest_builder{
Name: dcName,
- })
+ }.Build())
return err
},
errAssertion: requireTraceErrorFn(trace.IsAccessDenied),
@@ -387,9 +387,9 @@ func TestUpdateDiscoveryConfigStatus(t *testing.T) {
name: "discovery config doesn't exist",
systemRole: types.RoleDiscovery,
test: func(t *testing.T, ctx context.Context, resourceSvc *Service, dcName string) error {
- _, err := resourceSvc.UpdateDiscoveryConfigStatus(ctx, &discoveryconfigpb.UpdateDiscoveryConfigStatusRequest{
+ _, err := resourceSvc.UpdateDiscoveryConfigStatus(ctx, discoveryconfigpb.UpdateDiscoveryConfigStatusRequest_builder{
Name: dcName,
- })
+ }.Build())
return err
},
errAssertion: requireTraceErrorFn(trace.IsNotFound),
@@ -404,17 +404,17 @@ func TestUpdateDiscoveryConfigStatus(t *testing.T) {
test: func(t *testing.T, ctx context.Context, resourceSvc *Service, dcName string) error {
now := time.Now()
msg := "error message"
- status := &discoveryconfigpb.DiscoveryConfigStatus{
+ status := discoveryconfigpb.DiscoveryConfigStatus_builder{
State: discoveryconfigpb.DiscoveryConfigState_DISCOVERY_CONFIG_STATE_RUNNING,
ErrorMessage: &msg,
DiscoveredResources: 42,
LastSyncTime: timestamppb.New(now),
- }
+ }.Build()
- out, err := resourceSvc.UpdateDiscoveryConfigStatus(ctx, &discoveryconfigpb.UpdateDiscoveryConfigStatusRequest{
+ out, err := resourceSvc.UpdateDiscoveryConfigStatus(ctx, discoveryconfigpb.UpdateDiscoveryConfigStatusRequest_builder{
Name: dcName,
Status: status,
- })
+ }.Build())
require.NoError(t, err)
dc := sampleDiscoveryConfigFn(t, dcName)
dc.Status = convert.StatusFromProto(status)
diff --git a/lib/auth/dynamicwindows/dynamicwindowsv1/service.go b/lib/auth/dynamicwindows/dynamicwindowsv1/service.go
index dac5b72ca33..ee46ab83be1 100644
--- a/lib/auth/dynamicwindows/dynamicwindowsv1/service.go
+++ b/lib/auth/dynamicwindows/dynamicwindowsv1/service.go
@@ -131,14 +131,14 @@ func (s *Service) ListDynamicWindowsDesktops(ctx context.Context, request *dynam
return nil, trace.Wrap(err)
}
- desktops, next, err := s.cache.ListDynamicWindowsDesktops(ctx, int(request.PageSize), request.PageToken)
+ desktops, next, err := s.cache.ListDynamicWindowsDesktops(ctx, int(request.GetPageSize()), request.GetPageToken())
if err != nil {
return nil, trace.Wrap(err)
}
- response := &dynamicwindowspb.ListDynamicWindowsDesktopsResponse{
+ response := dynamicwindowspb.ListDynamicWindowsDesktopsResponse_builder{
NextPageToken: next,
- }
+ }.Build()
for _, d := range desktops {
if err := checkAccess(auth, d); err != nil {
continue
@@ -147,7 +147,7 @@ func (s *Service) ListDynamicWindowsDesktops(ctx context.Context, request *dynam
if !ok {
return nil, trace.BadParameter("unexpected type %T", d)
}
- response.Desktops = append(response.Desktops, desktop)
+ response.SetDesktops(append(response.GetDesktops(), desktop))
}
return response, nil
@@ -168,7 +168,7 @@ func (s *Service) CreateDynamicWindowsDesktop(ctx context.Context, req *dynamicw
if err := checkAccess(auth, req.GetDesktop()); err != nil {
return nil, trace.Wrap(err)
}
- d, err := s.backend.CreateDynamicWindowsDesktop(ctx, types.DynamicWindowsDesktop(req.Desktop))
+ d, err := s.backend.CreateDynamicWindowsDesktop(ctx, types.DynamicWindowsDesktop(req.GetDesktop()))
if err != nil {
return nil, trace.Wrap(err)
}
@@ -207,7 +207,7 @@ func (s *Service) UpdateDynamicWindowsDesktop(ctx context.Context, req *dynamicw
if err := checkAccess(auth, req.GetDesktop()); err != nil {
return nil, trace.Wrap(err)
}
- d, err = s.backend.UpdateDynamicWindowsDesktop(ctx, req.Desktop)
+ d, err = s.backend.UpdateDynamicWindowsDesktop(ctx, req.GetDesktop())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -244,7 +244,7 @@ func (s *Service) UpsertDynamicWindowsDesktop(ctx context.Context, req *dynamicw
if err := checkAccess(auth, req.GetDesktop()); err != nil {
return nil, trace.Wrap(err)
}
- d, err = s.backend.UpsertDynamicWindowsDesktop(ctx, req.Desktop)
+ d, err = s.backend.UpsertDynamicWindowsDesktop(ctx, req.GetDesktop())
if err != nil {
return nil, trace.Wrap(err)
}
diff --git a/lib/auth/dynamicwindows/dynamicwindowsv1/service_test.go b/lib/auth/dynamicwindows/dynamicwindowsv1/service_test.go
index efc0f9a1fb1..15f308319dd 100644
--- a/lib/auth/dynamicwindows/dynamicwindowsv1/service_test.go
+++ b/lib/auth/dynamicwindows/dynamicwindowsv1/service_test.go
@@ -70,7 +70,7 @@ func TestFailedAccessCheck(t *testing.T) {
}
resp, err := s.ListDynamicWindowsDesktops(context.Background(), &req)
require.NoError(t, err)
- require.Empty(t, resp.Desktops)
+ require.Empty(t, resp.GetDesktops())
})
}
@@ -211,7 +211,7 @@ func callMethod(service *Service, method string) error {
_, err := desc.Handler(service, context.Background(), func(arg any) error {
switch arg := arg.(type) {
case *dynamicwindowsv1.GetDynamicWindowsDesktopRequest:
- arg.Name = "test2"
+ arg.SetName("test2")
case *dynamicwindowsv1.CreateDynamicWindowsDesktopRequest:
arg.Desktop, _ = types.NewDynamicWindowsDesktopV1("test", nil, types.DynamicWindowsDesktopSpecV1{
diff --git a/lib/auth/gitserver/gitserverv1/github.go b/lib/auth/gitserver/gitserverv1/github.go
index 66463b764da..a0c5b8aec17 100644
--- a/lib/auth/gitserver/gitserverv1/github.go
+++ b/lib/auth/gitserver/gitserverv1/github.go
@@ -33,20 +33,20 @@ import (
)
func (s *Service) CreateGitHubAuthRequest(ctx context.Context, in *pb.CreateGitHubAuthRequestRequest) (*types.GithubAuthRequest, error) {
- if in.Request == nil {
+ if !in.HasRequest() {
return nil, trace.BadParameter("missing github auth request")
}
- if err := types.ValidateGitHubOrganizationName(in.Organization); err != nil {
+ if err := types.ValidateGitHubOrganizationName(in.GetOrganization()); err != nil {
return nil, trace.Wrap(err)
}
- if in.Request.SSOTestFlow {
+ if in.GetRequest().SSOTestFlow {
return nil, trace.BadParameter("sso test flow is not supported when creating GitHub auth request for authenticated user")
}
- if in.Request.CreateWebSession {
+ if in.GetRequest().CreateWebSession {
return nil, trace.BadParameter("CreateWebSession is not supported when creating GitHub auth request for authenticated user")
}
- authCtx, gitServer, err := s.authAndFindServerByOrg(ctx, in.Organization)
+ authCtx, gitServer, err := s.authAndFindServerByOrg(ctx, in.GetOrganization())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -64,15 +64,15 @@ func (s *Service) CreateGitHubAuthRequest(ctx context.Context, in *pb.CreateGitH
return nil, trace.Wrap(err)
}
- in.Request.ConnectorID = uuid
- in.Request.ConnectorSpec = spec
- in.Request.AuthenticatedUser = authCtx.User.GetName()
- in.Request.CertTTL = authCtx.Identity.GetIdentity().Expires.Sub(s.cfg.clock.Now())
- in.Request.ClientLoginIP = authCtx.Identity.GetIdentity().LoginIP
+ in.GetRequest().ConnectorID = uuid
+ in.GetRequest().ConnectorSpec = spec
+ in.GetRequest().AuthenticatedUser = authCtx.User.GetName()
+ in.GetRequest().CertTTL = authCtx.Identity.GetIdentity().Expires.Sub(s.cfg.clock.Now())
+ in.GetRequest().ClientLoginIP = authCtx.Identity.GetIdentity().LoginIP
// More params of in.Request will get updated and checked by
// s.cfg.GitHubAuthRequestCreator.
- request, err := s.cfg.GitHubAuthRequestCreator(ctx, *in.Request)
+ request, err := s.cfg.GitHubAuthRequestCreator(ctx, *in.GetRequest())
return request, trace.Wrap(err)
}
diff --git a/lib/auth/gitserver/gitserverv1/github_test.go b/lib/auth/gitserver/gitserverv1/github_test.go
index c3d80455c38..aa9c86d24b5 100644
--- a/lib/auth/gitserver/gitserverv1/github_test.go
+++ b/lib/auth/gitserver/gitserverv1/github_test.go
@@ -44,10 +44,10 @@ func TestCreateGitHubAuthRequest(t *testing.T) {
}
service := newService(t, checker, org1)
- createdRequest, err := service.CreateGitHubAuthRequest(ctx, &pb.CreateGitHubAuthRequestRequest{
+ createdRequest, err := service.CreateGitHubAuthRequest(ctx, pb.CreateGitHubAuthRequestRequest_builder{
Request: &types.GithubAuthRequest{},
Organization: org1.GetGitHub().Organization,
- })
+ }.Build())
require.NoError(t, err)
require.NotNil(t, createdRequest)
diff --git a/lib/auth/gitserver/gitserverv1/service.go b/lib/auth/gitserver/gitserverv1/service.go
index 795841dcb23..d99af40b92b 100644
--- a/lib/auth/gitserver/gitserverv1/service.go
+++ b/lib/auth/gitserver/gitserverv1/service.go
@@ -109,7 +109,7 @@ func (s *Service) CreateGitServer(ctx context.Context, req *pb.CreateGitServerRe
if _, err := s.authorize(ctx, types.VerbCreate); err != nil {
return nil, trace.Wrap(err)
}
- server, err := s.cfg.Backend.CreateGitServer(ctx, req.Server)
+ server, err := s.cfg.Backend.CreateGitServer(ctx, req.GetServer())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -121,13 +121,13 @@ func (s *Service) GetGitServer(ctx context.Context, req *pb.GetGitServerRequest)
if err != nil {
return nil, trace.Wrap(err)
}
- server, err := s.cfg.Backend.GetGitServer(ctx, req.Name)
+ server, err := s.cfg.Backend.GetGitServer(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
if err := s.checkAccess(authCtx, server); err != nil {
if trace.IsAccessDenied(err) {
- return nil, trace.NotFound("git server %q not found", req.Name)
+ return nil, trace.NotFound("git server %q not found", req.GetName())
}
return nil, trace.Wrap(err)
}
@@ -139,14 +139,14 @@ func (s *Service) ListGitServers(ctx context.Context, req *pb.ListGitServersRequ
if err != nil {
return nil, trace.Wrap(err)
}
- servers, next, err := s.cfg.Backend.ListGitServers(ctx, int(req.PageSize), req.PageToken)
+ servers, next, err := s.cfg.Backend.ListGitServers(ctx, int(req.GetPageSize()), req.GetPageToken())
if err != nil {
return nil, trace.Wrap(err)
}
- resp := &pb.ListGitServersResponse{
+ resp := pb.ListGitServersResponse_builder{
NextPageToken: next,
- }
+ }.Build()
for _, server := range servers {
err := s.checkAccess(authCtx, server)
if trace.IsAccessDenied(err) {
@@ -158,7 +158,7 @@ func (s *Service) ListGitServers(ctx context.Context, req *pb.ListGitServersRequ
if serverV2, err := toServerV2(server); err != nil {
return nil, trace.Wrap(err)
} else {
- resp.Servers = append(resp.Servers, serverV2)
+ resp.SetServers(append(resp.GetServers(), serverV2))
}
}
return resp, nil
@@ -168,7 +168,7 @@ func (s *Service) UpdateGitServer(ctx context.Context, req *pb.UpdateGitServerRe
if _, err := s.authorize(ctx, types.VerbUpdate); err != nil {
return nil, trace.Wrap(err)
}
- server, err := s.cfg.Backend.UpdateGitServer(ctx, req.Server)
+ server, err := s.cfg.Backend.UpdateGitServer(ctx, req.GetServer())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -179,7 +179,7 @@ func (s *Service) UpsertGitServer(ctx context.Context, req *pb.UpsertGitServerRe
if _, err := s.authorize(ctx, types.VerbCreate, types.VerbUpdate); err != nil {
return nil, trace.Wrap(err)
}
- server, err := s.cfg.Backend.UpsertGitServer(ctx, req.Server)
+ server, err := s.cfg.Backend.UpsertGitServer(ctx, req.GetServer())
if err != nil {
return nil, trace.Wrap(err)
}
diff --git a/lib/auth/gitserver/gitserverv1/service_test.go b/lib/auth/gitserver/gitserverv1/service_test.go
index e0ba093ecbb..8fcdefd4484 100644
--- a/lib/auth/gitserver/gitserverv1/service_test.go
+++ b/lib/auth/gitserver/gitserverv1/service_test.go
@@ -66,7 +66,7 @@ func TestServiceAccess(t *testing.T) {
name: "create verb not allowed",
checker: &fakeAccessChecker{ /*nothing allowed*/ },
run: func(t *testing.T, service *Service) {
- _, err := service.CreateGitServer(ctx, &pb.CreateGitServerRequest{Server: org3})
+ _, err := service.CreateGitServer(ctx, pb.CreateGitServerRequest_builder{Server: org3}.Build())
require.True(t, trace.IsAccessDenied(err))
},
},
@@ -76,7 +76,7 @@ func TestServiceAccess(t *testing.T) {
allowVerbs: []string{types.VerbCreate},
},
run: func(t *testing.T, service *Service) {
- _, err := service.CreateGitServer(ctx, &pb.CreateGitServerRequest{Server: org3})
+ _, err := service.CreateGitServer(ctx, pb.CreateGitServerRequest_builder{Server: org3}.Build())
require.NoError(t, err)
},
},
@@ -84,7 +84,7 @@ func TestServiceAccess(t *testing.T) {
name: "get verb not allowed",
checker: &fakeAccessChecker{ /*nothing allowed*/ },
run: func(t *testing.T, service *Service) {
- _, err := service.GetGitServer(ctx, &pb.GetGitServerRequest{Name: org1.GetName()})
+ _, err := service.GetGitServer(ctx, pb.GetGitServerRequest_builder{Name: org1.GetName()}.Build())
require.True(t, trace.IsAccessDenied(err))
},
},
@@ -94,7 +94,7 @@ func TestServiceAccess(t *testing.T) {
allowVerbs: []string{types.VerbRead},
},
run: func(t *testing.T, service *Service) {
- _, err := service.GetGitServer(ctx, &pb.GetGitServerRequest{Name: org1.GetName()})
+ _, err := service.GetGitServer(ctx, pb.GetGitServerRequest_builder{Name: org1.GetName()}.Build())
require.True(t, trace.IsNotFound(err))
},
},
@@ -105,7 +105,7 @@ func TestServiceAccess(t *testing.T) {
allowResource: true,
},
run: func(t *testing.T, service *Service) {
- server, err := service.GetGitServer(ctx, &pb.GetGitServerRequest{Name: org1.GetName()})
+ server, err := service.GetGitServer(ctx, pb.GetGitServerRequest_builder{Name: org1.GetName()}.Build())
require.NoError(t, err)
require.Equal(t, "org1", server.GetGitHub().Organization)
},
@@ -129,7 +129,7 @@ func TestServiceAccess(t *testing.T) {
run: func(t *testing.T, service *Service) {
resp, err := service.ListGitServers(ctx, &pb.ListGitServersRequest{})
require.NoError(t, err)
- require.Empty(t, resp.Servers)
+ require.Empty(t, resp.GetServers())
},
},
{
@@ -141,14 +141,14 @@ func TestServiceAccess(t *testing.T) {
run: func(t *testing.T, service *Service) {
resp, err := service.ListGitServers(ctx, &pb.ListGitServersRequest{})
require.NoError(t, err)
- require.Len(t, resp.Servers, 2)
+ require.Len(t, resp.GetServers(), 2)
},
},
{
name: "update verb not allowed",
checker: &fakeAccessChecker{ /*nothing allowed*/ },
run: func(t *testing.T, service *Service) {
- _, err := service.UpdateGitServer(ctx, &pb.UpdateGitServerRequest{Server: org1})
+ _, err := service.UpdateGitServer(ctx, pb.UpdateGitServerRequest_builder{Server: org1}.Build())
require.True(t, trace.IsAccessDenied(err))
},
},
@@ -160,7 +160,7 @@ func TestServiceAccess(t *testing.T) {
run: func(t *testing.T, service *Service) {
org1WithRevision, err := service.cfg.Backend.GetGitServer(ctx, org1.GetName())
require.NoError(t, err)
- _, err = service.UpdateGitServer(ctx, &pb.UpdateGitServerRequest{Server: org1WithRevision.(*types.ServerV2)})
+ _, err = service.UpdateGitServer(ctx, pb.UpdateGitServerRequest_builder{Server: org1WithRevision.(*types.ServerV2)}.Build())
require.NoError(t, err)
},
},
@@ -168,7 +168,7 @@ func TestServiceAccess(t *testing.T) {
name: "upsert verb not allowed",
checker: &fakeAccessChecker{ /*nothing allowed*/ },
run: func(t *testing.T, service *Service) {
- _, err := service.UpsertGitServer(ctx, &pb.UpsertGitServerRequest{Server: org3})
+ _, err := service.UpsertGitServer(ctx, pb.UpsertGitServerRequest_builder{Server: org3}.Build())
require.True(t, trace.IsAccessDenied(err))
},
},
@@ -178,7 +178,7 @@ func TestServiceAccess(t *testing.T) {
allowVerbs: []string{types.VerbCreate, types.VerbUpdate},
},
run: func(t *testing.T, service *Service) {
- _, err := service.UpsertGitServer(ctx, &pb.UpsertGitServerRequest{Server: org3})
+ _, err := service.UpsertGitServer(ctx, pb.UpsertGitServerRequest_builder{Server: org3}.Build())
require.NoError(t, err)
},
},
@@ -186,7 +186,7 @@ func TestServiceAccess(t *testing.T) {
name: "delete verb not allowed",
checker: &fakeAccessChecker{ /*nothing allowed*/ },
run: func(t *testing.T, service *Service) {
- _, err := service.DeleteGitServer(ctx, &pb.DeleteGitServerRequest{Name: org1.GetName()})
+ _, err := service.DeleteGitServer(ctx, pb.DeleteGitServerRequest_builder{Name: org1.GetName()}.Build())
require.True(t, trace.IsAccessDenied(err))
},
},
@@ -196,7 +196,7 @@ func TestServiceAccess(t *testing.T) {
allowVerbs: []string{types.VerbDelete},
},
run: func(t *testing.T, service *Service) {
- _, err := service.DeleteGitServer(ctx, &pb.DeleteGitServerRequest{Name: org1.GetName()})
+ _, err := service.DeleteGitServer(ctx, pb.DeleteGitServerRequest_builder{Name: org1.GetName()}.Build())
require.NoError(t, err)
},
},
@@ -207,10 +207,10 @@ func TestServiceAccess(t *testing.T) {
allowResource: true,
},
run: func(t *testing.T, service *Service) {
- _, err := service.CreateGitHubAuthRequest(ctx, &pb.CreateGitHubAuthRequestRequest{
+ _, err := service.CreateGitHubAuthRequest(ctx, pb.CreateGitHubAuthRequestRequest_builder{
Request: &types.GithubAuthRequest{},
Organization: org1.GetGitHub().Organization,
- })
+ }.Build())
require.NoError(t, err)
},
},
@@ -220,10 +220,10 @@ func TestServiceAccess(t *testing.T) {
allowVerbs: []string{types.VerbRead, types.VerbList},
},
run: func(t *testing.T, service *Service) {
- _, err := service.CreateGitHubAuthRequest(ctx, &pb.CreateGitHubAuthRequestRequest{
+ _, err := service.CreateGitHubAuthRequest(ctx, pb.CreateGitHubAuthRequestRequest_builder{
Request: &types.GithubAuthRequest{},
Organization: org1.GetGitHub().Organization,
- })
+ }.Build())
// Getting NotFound instead of AccessDenied.
require.True(t, trace.IsNotFound(err))
},
diff --git a/lib/auth/grpcclientconfig/grpcclientconfigv1/service.go b/lib/auth/grpcclientconfig/grpcclientconfigv1/service.go
index 3444e293b16..1408c3d5173 100644
--- a/lib/auth/grpcclientconfig/grpcclientconfigv1/service.go
+++ b/lib/auth/grpcclientconfig/grpcclientconfigv1/service.go
@@ -61,7 +61,7 @@ type Service struct {
// GetServiceConfig handles requests for fetching the service config configured
// on this server.
func (s *Service) GetServiceConfig(ctx context.Context, req *grpcv1.GetServiceConfigRequest) (*grpcv1.GetServiceConfigResponse, error) {
- return &grpcv1.GetServiceConfigResponse{
+ return grpcv1.GetServiceConfigResponse_builder{
Config: s.config,
- }, nil
+ }.Build(), nil
}
diff --git a/lib/auth/grpcclientconfig/grpcclientconfigv1/service_test.go b/lib/auth/grpcclientconfig/grpcclientconfigv1/service_test.go
index dd715b26842..e1b593357b3 100644
--- a/lib/auth/grpcclientconfig/grpcclientconfigv1/service_test.go
+++ b/lib/auth/grpcclientconfig/grpcclientconfigv1/service_test.go
@@ -45,18 +45,16 @@ func TestGetServiceConfigEnvVar(t *testing.T) {
{
name: "custom service config envvar",
env: ptr(`{"loadBalancingConfig": [{"teleport_pick_healthy": {"mode": "MODE_RECONNECT"}}], "healthCheckConfig":{"serviceName": "test"}}`),
- expected: &grpcv1.ServiceConfig{
- LoadBalancingConfig: []*grpcv1.LoadBalancerConfig{{
- Config: &grpcv1.LoadBalancerConfig_TeleportPickHealthy{
- TeleportPickHealthy: &grpcv1.TeleportPickHealthyConfig{
- Mode: grpcv1.Mode_MODE_RECONNECT,
- },
- },
- }},
- HealthCheckConfig: &grpcv1.HealthCheckConfig{
+ expected: grpcv1.ServiceConfig_builder{
+ LoadBalancingConfig: []*grpcv1.LoadBalancerConfig{grpcv1.LoadBalancerConfig_builder{
+ TeleportPickHealthy: grpcv1.TeleportPickHealthyConfig_builder{
+ Mode: grpcv1.Mode_MODE_RECONNECT,
+ }.Build(),
+ }.Build()},
+ HealthCheckConfig: grpcv1.HealthCheckConfig_builder{
ServiceName: ptr("test"),
- },
- },
+ }.Build(),
+ }.Build(),
},
} {
t.Run(tt.name, func(t *testing.T) {
diff --git a/lib/auth/grpcserver.go b/lib/auth/grpcserver.go
index 83cf07a5a08..9e2c18414d4 100644
--- a/lib/auth/grpcserver.go
+++ b/lib/auth/grpcserver.go
@@ -922,7 +922,7 @@ func (g *GRPCServer) InventoryControlStream(stream authpb.AuthService_InventoryC
// services that currently use ics for heartbeats are registered in the icsServiceToMetricName
// mapping for translation.
var metricServices []string
- for _, service := range hello.Services {
+ for _, service := range hello.GetServices() {
if name, ok := icsServiceToMetricName[types.SystemRole(service)]; ok {
metricServices = append(metricServices, name)
}
@@ -3814,7 +3814,7 @@ func (g *GRPCServer) ListAuthServers(ctx context.Context, req *presencev1pb.List
return nil, trace.Wrap(err)
}
- servers, next, err := auth.ListAuthServers(ctx, int(req.PageSize), req.PageToken)
+ servers, next, err := auth.ListAuthServers(ctx, int(req.GetPageSize()), req.GetPageToken())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -3828,10 +3828,10 @@ func (g *GRPCServer) ListAuthServers(ctx context.Context, req *presencev1pb.List
serverV2s = append(serverV2s, srv)
}
- return &presencev1pb.ListAuthServersResponse{
+ return presencev1pb.ListAuthServersResponse_builder{
Servers: serverV2s,
NextPageToken: next,
- }, nil
+ }.Build(), nil
}
// ListProxyServers returns a paginated list of proxy servers.
@@ -3841,7 +3841,7 @@ func (g *GRPCServer) ListProxyServers(ctx context.Context, req *presencev1pb.Lis
return nil, trace.Wrap(err)
}
- servers, next, err := auth.ListProxyServers(ctx, int(req.PageSize), req.PageToken)
+ servers, next, err := auth.ListProxyServers(ctx, int(req.GetPageSize()), req.GetPageToken())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -3855,10 +3855,10 @@ func (g *GRPCServer) ListProxyServers(ctx context.Context, req *presencev1pb.Lis
serverV2s = append(serverV2s, srv)
}
- return &presencev1pb.ListProxyServersResponse{
+ return presencev1pb.ListProxyServersResponse_builder{
Servers: serverV2s,
NextPageToken: next,
- }, nil
+ }.Build(), nil
}
// GetNode retrieves a node by name and namespace.
@@ -6874,22 +6874,22 @@ func (g *GRPCServer) GetUnstructuredEvents(ctx context.Context, req *auditlogpb.
rawEvents, lastkey, err := auth.ServerWithRoles.SearchUnstructuredEvents(
ctx,
events.SearchEventsRequest{
- From: req.StartDate.AsTime(),
- To: req.EndDate.AsTime(),
- EventTypes: req.EventTypes,
- Limit: int(req.Limit),
- Order: types.EventOrder(req.Order),
- StartKey: req.StartKey,
+ From: req.GetStartDate().AsTime(),
+ To: req.GetEndDate().AsTime(),
+ EventTypes: req.GetEventTypes(),
+ Limit: int(req.GetLimit()),
+ Order: types.EventOrder(req.GetOrder()),
+ StartKey: req.GetStartKey(),
},
)
if err != nil {
return nil, trace.Wrap(err)
}
- return &auditlogpb.EventsUnstructured{
+ return auditlogpb.EventsUnstructured_builder{
Items: rawEvents,
LastKey: lastkey,
- }, nil
+ }.Build(), nil
}
// ExportUnstructuredEvents exports events from a given event chunk returned by GetEventExportChunks. This API prioritizes
@@ -6939,7 +6939,7 @@ func (g *GRPCServer) StreamUnstructuredSessionEvents(req *auditlogpb.StreamUnstr
return trace.Wrap(err)
}
- c, e := auth.ServerWithRoles.StreamSessionEvents(stream.Context(), session.ID(req.SessionId), int64(req.StartIndex))
+ c, e := auth.ServerWithRoles.StreamSessionEvents(stream.Context(), session.ID(req.GetSessionId()), int64(req.GetStartIndex()))
for {
select {
diff --git a/lib/auth/grpcserver_test.go b/lib/auth/grpcserver_test.go
index 88846434ea1..923131e1fa8 100644
--- a/lib/auth/grpcserver_test.go
+++ b/lib/auth/grpcserver_test.go
@@ -3260,11 +3260,11 @@ func TestInstanceCertAndControlStream(t *testing.T) {
require.NoError(t, err)
defer stream.Close()
- err = stream.Send(ctx, &proto.UpstreamInventoryHello{
+ err = stream.Send(ctx, proto.UpstreamInventoryHello_builder{
ServerID: serverID,
Version: teleport.Version,
Services: types.SystemRoles(roles).StringSlice(),
- })
+ }.Build())
require.NoError(t, err)
select {
@@ -3298,9 +3298,9 @@ func TestInstanceCertAndControlStream(t *testing.T) {
case msg := <-stream.Recv():
ping, ok := msg.(*proto.DownstreamInventoryPing)
require.True(t, ok)
- err = stream.Send(ctx, &proto.UpstreamInventoryPong{
- ID: ping.ID,
- })
+ err = stream.Send(ctx, proto.UpstreamInventoryPong_builder{
+ ID: ping.GetID(),
+ }.Build())
require.NoError(t, err)
case <-time.After(time.Second * 5):
t.Fatalf("timeout waiting for downstream ping")
@@ -5417,14 +5417,14 @@ func TestGRPCServer_GetInstallers(t *testing.T) {
if tc.hasAgentRollout {
rollout, err := autoupdate.NewAutoUpdateAgentRollout(
- &autoupdatev1pb.AutoUpdateAgentRolloutSpec{
+ autoupdatev1pb.AutoUpdateAgentRolloutSpec_builder{
StartVersion: "1.2.3",
TargetVersion: "1.2.4",
Schedule: autoupdate.AgentsScheduleImmediate,
AutoupdateMode: autoupdate.AgentsUpdateModeEnabled,
Strategy: autoupdate.AgentsStrategyTimeBased,
MaintenanceWindowDuration: durationpb.New(1 * time.Hour),
- })
+ }.Build())
require.NoError(t, err)
_, err = grpc.AuthServer.CreateAutoUpdateAgentRollout(ctx, rollout)
require.NoError(t, err)
@@ -5949,12 +5949,12 @@ func TestGetAccessGraphConfig(t *testing.T) {
)
user, _, err := authtest.CreateUserAndRole(server.Auth(), "test", []string{"role"}, nil)
require.NoError(t, err)
- positiveResponse := &clusterconfigpb.AccessGraphConfig{
+ positiveResponse := clusterconfigpb.AccessGraphConfig_builder{
Enabled: true,
Ca: []byte("ca"),
Address: "addr",
SecretsScanConfig: &clusterconfigpb.AccessGraphSecretsScanConfiguration{},
- }
+ }.Build()
tests := []struct {
desc string
@@ -6009,10 +6009,10 @@ func TestGetVnetConfig(t *testing.T) {
require.NoError(t, err)
// Create newConfig.
- newConfig, err := vnet.NewVnetConfig(&vnetv1pb.VnetConfigSpec{
+ newConfig, err := vnet.NewVnetConfig(vnetv1pb.VnetConfigSpec_builder{
Ipv4CidrRange: vnet.DefaultIPv4CIDRRange,
- CustomDnsZones: []*vnetv1pb.CustomDNSZone{{Suffix: "example.com"}},
- })
+ CustomDnsZones: []*vnetv1pb.CustomDNSZone{vnetv1pb.CustomDNSZone_builder{Suffix: "example.com"}.Build()},
+ }.Build())
require.NoError(t, err)
createdConfig, err := server.Auth().CreateVnetConfig(t.Context(), newConfig)
require.NoError(t, err)
@@ -7074,55 +7074,55 @@ func TestGenerateUserCertsScopedBot(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
ctx := t.Context()
- bot, err := adminClient.BotServiceClient().CreateBot(ctx, &machineidv1.CreateBotRequest{
- Bot: &machineidv1.Bot{
+ bot, err := adminClient.BotServiceClient().CreateBot(ctx, machineidv1.CreateBotRequest_builder{
+ Bot: machineidv1.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: c.botName,
- },
+ }.Build(),
Scope: c.scope,
Spec: &machineidv1.BotSpec{},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
ident := authtest.TestBot(c.botName, c.internal)
if c.scope != "" {
scopedSvc := adminClient.ScopedAccessServiceClient()
- roleResp, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ roleResp, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: c.botName + "-role",
- },
+ }.Build(),
Scope: c.scope,
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{c.scope},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- sra, err := testServer.Auth().ScopedAccess().CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sra, err := testServer.Auth().ScopedAccess().CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
Scope: c.scope,
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
BotName: bot.GetMetadata().GetName(),
BotScope: c.scope,
Assignments: []*scopedaccessv1.Assignment{
- {Role: roleResp.GetRole().GetMetadata().GetName(), Scope: c.scope},
+ scopedaccessv1.Assignment_builder{Role: roleResp.GetRole().GetMetadata().GetName(), Scope: c.scope}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, testServer, sra)
diff --git a/lib/auth/healthcheckconfig/healthcheckconfigv1/service.go b/lib/auth/healthcheckconfig/healthcheckconfigv1/service.go
index be6bd5485bb..b15bc88a9da 100644
--- a/lib/auth/healthcheckconfig/healthcheckconfigv1/service.go
+++ b/lib/auth/healthcheckconfig/healthcheckconfigv1/service.go
@@ -117,10 +117,10 @@ func (s *Service) ListHealthCheckConfigs(ctx context.Context, req *healthcheckco
if err != nil {
return nil, trace.Wrap(err)
}
- return &healthcheckconfigv1.ListHealthCheckConfigsResponse{
+ return healthcheckconfigv1.ListHealthCheckConfigsResponse_builder{
Configs: page,
NextPageToken: token,
- }, nil
+ }.Build(), nil
}
// UpdateHealthCheckConfig updates an existing HealthCheckConfig.
diff --git a/lib/auth/healthcheckconfig/healthcheckconfigv1/service_test.go b/lib/auth/healthcheckconfig/healthcheckconfigv1/service_test.go
index 381da2a9fa0..69f9c379744 100644
--- a/lib/auth/healthcheckconfig/healthcheckconfigv1/service_test.go
+++ b/lib/auth/healthcheckconfig/healthcheckconfigv1/service_test.go
@@ -67,9 +67,9 @@ func TestHealthCheckConfigCRUD(t *testing.T) {
{
name: "CreateHealthCheckConfig",
actionFn: func(t *testing.T, ctx context.Context, clt testClient) error {
- _, err := clt.ServiceUnderTest.CreateHealthCheckConfig(ctx, &healthcheckconfigv1.CreateHealthCheckConfigRequest{
+ _, err := clt.ServiceUnderTest.CreateHealthCheckConfig(ctx, healthcheckconfigv1.CreateHealthCheckConfigRequest_builder{
Config: newResource(t),
- })
+ }.Build())
return err
},
requiredAccessRules: []types.Rule{healthCheckConfigRule(types.VerbCreate)},
@@ -82,9 +82,9 @@ func TestHealthCheckConfigCRUD(t *testing.T) {
cfg1 := newResource(t)
_, err := clt.CreateHealthCheckConfig(ctx, cfg1)
require.NoError(t, err)
- _, err = clt.ServiceUnderTest.GetHealthCheckConfig(ctx, &healthcheckconfigv1.GetHealthCheckConfigRequest{
- Name: cfg1.Metadata.GetName(),
- })
+ _, err = clt.ServiceUnderTest.GetHealthCheckConfig(ctx, healthcheckconfigv1.GetHealthCheckConfigRequest_builder{
+ Name: cfg1.GetMetadata().GetName(),
+ }.Build())
return err
},
requiredAccessRules: []types.Rule{healthCheckConfigRule(types.VerbRead)},
@@ -99,7 +99,7 @@ func TestHealthCheckConfigCRUD(t *testing.T) {
resp, err := clt.ServiceUnderTest.ListHealthCheckConfigs(ctx, &healthcheckconfigv1.ListHealthCheckConfigsRequest{})
if err == nil {
require.NotNil(t, resp)
- require.Len(t, resp.Configs, 2+teleport.VirtualDefaultHealthCheckConfigCount,
+ require.Len(t, resp.GetConfigs(), 2+teleport.VirtualDefaultHealthCheckConfigCount,
"expected 2 inserted and virtual defaults")
}
return err
@@ -112,13 +112,13 @@ func TestHealthCheckConfigCRUD(t *testing.T) {
actionFn: func(t *testing.T, ctx context.Context, clt testClient) error {
cfg, err := clt.CreateHealthCheckConfig(ctx, newResource(t))
require.NoError(t, err)
- cfg.Spec.HealthyThreshold = 3
- cfg, err = clt.ServiceUnderTest.UpdateHealthCheckConfig(ctx, &healthcheckconfigv1.UpdateHealthCheckConfigRequest{
+ cfg.GetSpec().SetHealthyThreshold(3)
+ cfg, err = clt.ServiceUnderTest.UpdateHealthCheckConfig(ctx, healthcheckconfigv1.UpdateHealthCheckConfigRequest_builder{
Config: cfg,
- })
+ }.Build())
if err == nil {
require.NotNil(t, cfg, "the updated resource should be returned")
- require.Equal(t, 3, int(cfg.Spec.HealthyThreshold), "the resource should have been updated")
+ require.Equal(t, 3, int(cfg.GetSpec().GetHealthyThreshold()), "the resource should have been updated")
}
return err
},
@@ -129,9 +129,9 @@ func TestHealthCheckConfigCRUD(t *testing.T) {
name: "UpsertHealthCheckConfig",
actionFn: func(t *testing.T, ctx context.Context, clt testClient) error {
cfg := newResource(t)
- _, err := clt.ServiceUnderTest.UpsertHealthCheckConfig(ctx, &healthcheckconfigv1.UpsertHealthCheckConfigRequest{
+ _, err := clt.ServiceUnderTest.UpsertHealthCheckConfig(ctx, healthcheckconfigv1.UpsertHealthCheckConfigRequest_builder{
Config: cfg,
- })
+ }.Build())
return err
},
requiredAccessRules: []types.Rule{healthCheckConfigRule(types.VerbCreate, types.VerbUpdate)},
@@ -143,9 +143,9 @@ func TestHealthCheckConfigCRUD(t *testing.T) {
actionFn: func(t *testing.T, ctx context.Context, clt testClient) error {
cfg, err := clt.CreateHealthCheckConfig(ctx, newResource(t))
require.NoError(t, err)
- _, err = clt.ServiceUnderTest.DeleteHealthCheckConfig(ctx, &healthcheckconfigv1.DeleteHealthCheckConfigRequest{
- Name: cfg.Metadata.GetName(),
- })
+ _, err = clt.ServiceUnderTest.DeleteHealthCheckConfig(ctx, healthcheckconfigv1.DeleteHealthCheckConfigRequest_builder{
+ Name: cfg.GetMetadata().GetName(),
+ }.Build())
return err
},
requiredAccessRules: []types.Rule{healthCheckConfigRule(types.VerbDelete)},
@@ -219,14 +219,14 @@ func (c *accessTest) run(t *testing.T) {
func newResource(t *testing.T) *healthcheckconfigv1.HealthCheckConfig {
t.Helper()
r, err := healthcheckconfig.NewHealthCheckConfig(uuid.NewString(),
- &healthcheckconfigv1.HealthCheckConfigSpec{
- Match: &healthcheckconfigv1.Matcher{
- DbLabels: []*labelv1.Label{{
+ healthcheckconfigv1.HealthCheckConfigSpec_builder{
+ Match: healthcheckconfigv1.Matcher_builder{
+ DbLabels: []*labelv1.Label{labelv1.Label_builder{
Name: "*",
Values: []string{"*"},
- }},
- },
- },
+ }.Build()},
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
return r
diff --git a/lib/auth/init.go b/lib/auth/init.go
index 12ebcacd62d..92f7a5a31a5 100644
--- a/lib/auth/init.go
+++ b/lib/auth/init.go
@@ -1313,9 +1313,9 @@ func initializeAccessGraphSettings(ctx context.Context, asrv *Server) error {
return nil
}
- stored, err = clusterconfig.NewAccessGraphSettings(&clusterconfigpb.AccessGraphSettingsSpec{
+ stored, err = clusterconfig.NewAccessGraphSettings(clusterconfigpb.AccessGraphSettingsSpec_builder{
SecretsScanConfig: clusterconfigpb.AccessGraphSecretsScanConfig_ACCESS_GRAPH_SECRETS_SCAN_CONFIG_DISABLED,
- })
+ }.Build())
if err != nil {
return trace.Wrap(err)
}
diff --git a/lib/auth/init_test.go b/lib/auth/init_test.go
index 1579be3c130..62a2f7861d6 100644
--- a/lib/auth/init_test.go
+++ b/lib/auth/init_test.go
@@ -1758,7 +1758,7 @@ func TestInit_bootstrap(t *testing.T) {
cfg.BootstrapResources = append(
cfg.BootstrapResources,
newHealthCheckConfig(t, func(hcc *healthcheckconfigv1.HealthCheckConfig) {
- hcc.Spec.HealthyThreshold = 9000
+ hcc.GetSpec().SetHealthyThreshold(9000)
}),
)
},
@@ -2478,9 +2478,9 @@ func TestTeleportProcessAuthVersionUpgradeCheck(t *testing.T) {
if test.initialVersion != "" {
ver, err := semver.NewVersion(test.initialVersion)
require.NoError(t, err)
- backendInfo, err := backendinfo.NewBackendInfo(&backendinfov1.BackendInfoSpec{
+ backendInfo, err := backendinfo.NewBackendInfo(backendinfov1.BackendInfoSpec_builder{
TeleportVersion: ver.String(),
- })
+ }.Build())
require.NoError(t, err)
_, err = service.CreateBackendInfo(ctx, backendInfo)
require.NoError(t, err)
@@ -2533,21 +2533,21 @@ func Test_createPresetDatabaseObjectImportRule(t *testing.T) {
presetRule := databaseobjectimportrule.NewPresetImportAllObjectsRule()
require.NotNil(t, presetRule)
- customRule, err := databaseobjectimportrule.NewDatabaseObjectImportRule("dev_rule", &dbobjectimportrulev1.DatabaseObjectImportRuleSpec{
+ customRule, err := databaseobjectimportrule.NewDatabaseObjectImportRule("dev_rule", dbobjectimportrulev1.DatabaseObjectImportRuleSpec_builder{
Priority: 100,
DatabaseLabels: label.FromMap(map[string][]string{"env": {"dev"}}),
- Mappings: []*dbobjectimportrulev1.DatabaseObjectImportRuleMapping{{
- Match: &dbobjectimportrulev1.DatabaseObjectImportMatch{
+ Mappings: []*dbobjectimportrulev1.DatabaseObjectImportRuleMapping{dbobjectimportrulev1.DatabaseObjectImportRuleMapping_builder{
+ Match: dbobjectimportrulev1.DatabaseObjectImportMatch_builder{
TableNames: []string{"*"},
- },
+ }.Build(),
AddLabels: map[string]string{
"env": "dev",
},
- Scope: &dbobjectimportrulev1.DatabaseObjectImportScope{
+ Scope: dbobjectimportrulev1.DatabaseObjectImportScope_builder{
SchemaNames: []string{"public"},
- },
- }},
- })
+ }.Build(),
+ }.Build()},
+ }.Build())
require.NoError(t, err)
tests := []struct {
diff --git a/lib/auth/integration/integrationv1/awsoidc.go b/lib/auth/integration/integrationv1/awsoidc.go
index 09a1b4ebf33..648fad6adbd 100644
--- a/lib/auth/integration/integrationv1/awsoidc.go
+++ b/lib/auth/integration/integrationv1/awsoidc.go
@@ -49,7 +49,7 @@ func (s *Service) GenerateAWSOIDCToken(ctx context.Context, req *integrationpb.G
for _, allowedRole := range []types.SystemRole{types.RoleDiscovery, types.RoleAuth, types.RoleProxy} {
if authz.HasBuiltinRole(*authCtx, string(allowedRole)) {
- return s.generateAWSOIDCTokenWithoutAuthZ(ctx, req.Integration)
+ return s.generateAWSOIDCTokenWithoutAuthZ(ctx, req.GetIntegration())
}
}
@@ -74,9 +74,9 @@ func (s *Service) generateAWSOIDCTokenWithoutAuthZ(ctx context.Context, integrat
return nil, trace.Wrap(err)
}
- return &integrationpb.GenerateAWSOIDCTokenResponse{
+ return integrationpb.GenerateAWSOIDCTokenResponse_builder{
Token: token,
- }, nil
+ }.Build(), nil
}
// AWSOIDCServiceConfig holds configuration options for the AWSOIDC Integration gRPC service.
@@ -272,9 +272,9 @@ func NewAWSOIDCService(cfg *AWSOIDCServiceConfig) (*AWSOIDCService, error) {
var _ integrationpb.AWSOIDCServiceServer = (*AWSOIDCService)(nil)
func (s *AWSOIDCService) roleARNForIntegration(ctx context.Context, integrationName string) (string, error) {
- integration, err := s.integrationService.GetIntegration(ctx, &integrationpb.GetIntegrationRequest{
+ integration, err := s.integrationService.GetIntegration(ctx, integrationpb.GetIntegrationRequest_builder{
Name: integrationName,
- })
+ }.Build())
if err != nil {
return "", trace.Wrap(err)
}
@@ -297,7 +297,7 @@ func (s *AWSOIDCService) awsClientReqWithARN(ctx context.Context, integrationNam
}
return &awsoidc.AWSClientRequest{
- Token: token.Token,
+ Token: token.GetToken(),
RoleARN: arn,
Region: region,
}, nil
@@ -326,7 +326,7 @@ func (s *AWSOIDCService) ListEICE(ctx context.Context, req *integrationpb.ListEI
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -337,9 +337,9 @@ func (s *AWSOIDCService) ListEICE(ctx context.Context, req *integrationpb.ListEI
}
listResp, err := awsoidc.ListEC2ICE(ctx, listClient, awsoidc.ListEC2ICERequest{
- Region: req.Region,
- VPCIDs: req.VpcIds,
- NextToken: req.NextToken,
+ Region: req.GetRegion(),
+ VPCIDs: req.GetVpcIds(),
+ NextToken: req.GetNextToken(),
})
if err != nil {
return nil, trace.Wrap(err)
@@ -347,21 +347,21 @@ func (s *AWSOIDCService) ListEICE(ctx context.Context, req *integrationpb.ListEI
eiceList := make([]*integrationpb.EC2InstanceConnectEndpoint, 0, len(listResp.EC2ICEs))
for _, e := range listResp.EC2ICEs {
- eiceList = append(eiceList, &integrationpb.EC2InstanceConnectEndpoint{
+ eiceList = append(eiceList, integrationpb.EC2InstanceConnectEndpoint_builder{
Name: e.Name,
State: e.State,
StateMessage: e.StateMessage,
DashboardLink: e.DashboardLink,
SubnetId: e.SubnetID,
VpcId: e.VPCID,
- })
+ }.Build())
}
- return &integrationpb.ListEICEResponse{
+ return integrationpb.ListEICEResponse_builder{
NextToken: listResp.NextToken,
Ec2Ices: eiceList,
DashboardLink: listResp.DashboardLink,
- }, nil
+ }.Build(), nil
}
// CreateEICE creates multiple EC2 Instance Connect Endpoint using the provided Subnets and Security Group IDs.
@@ -377,7 +377,7 @@ func (s *AWSOIDCService) CreateEICE(ctx context.Context, req *integrationpb.Crea
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -392,18 +392,18 @@ func (s *AWSOIDCService) CreateEICE(ctx context.Context, req *integrationpb.Crea
return nil, trace.Wrap(err)
}
- endpoints := make([]awsoidc.EC2ICEEndpoint, 0, len(req.Endpoints))
- for _, endpoint := range req.Endpoints {
+ endpoints := make([]awsoidc.EC2ICEEndpoint, 0, len(req.GetEndpoints()))
+ for _, endpoint := range req.GetEndpoints() {
endpoints = append(endpoints, awsoidc.EC2ICEEndpoint{
- Name: endpoint.Name,
- SubnetID: endpoint.SubnetId,
- SecurityGroupIDs: endpoint.SecurityGroupIds,
+ Name: endpoint.GetName(),
+ SubnetID: endpoint.GetSubnetId(),
+ SecurityGroupIDs: endpoint.GetSecurityGroupIds(),
})
}
createResp, err := awsoidc.CreateEC2ICE(ctx, createClient, awsoidc.CreateEC2ICERequest{
Cluster: clusterName.GetClusterName(),
- IntegrationName: req.Integration,
+ IntegrationName: req.GetIntegration(),
Endpoints: endpoints,
})
if err != nil {
@@ -412,17 +412,17 @@ func (s *AWSOIDCService) CreateEICE(ctx context.Context, req *integrationpb.Crea
eiceList := make([]*integrationpb.EC2ICEndpoint, 0, len(createResp.CreatedEndpoints))
for _, e := range createResp.CreatedEndpoints {
- eiceList = append(eiceList, &integrationpb.EC2ICEndpoint{
+ eiceList = append(eiceList, integrationpb.EC2ICEndpoint_builder{
Name: e.Name,
SubnetId: e.SubnetID,
SecurityGroupIds: e.SecurityGroupIDs,
- })
+ }.Build())
}
- return &integrationpb.CreateEICEResponse{
+ return integrationpb.CreateEICEResponse_builder{
Name: createResp.Name,
CreatedEndpoints: eiceList,
- }, nil
+ }.Build(), nil
}
// ListDatabases returns a paginated list of Databases.
@@ -436,7 +436,7 @@ func (s *AWSOIDCService) ListDatabases(ctx context.Context, req *integrationpb.L
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -447,11 +447,11 @@ func (s *AWSOIDCService) ListDatabases(ctx context.Context, req *integrationpb.L
}
listDBsResp, err := awsoidc.ListDatabases(ctx, listDBsClient, s.logger, awsoidc.ListDatabasesRequest{
- Region: req.Region,
- RDSType: req.RdsType,
- Engines: req.Engines,
- NextToken: req.NextToken,
- VpcId: req.VpcId,
+ Region: req.GetRegion(),
+ RDSType: req.GetRdsType(),
+ Engines: req.GetEngines(),
+ NextToken: req.GetNextToken(),
+ VpcId: req.GetVpcId(),
})
if err != nil {
return nil, trace.Wrap(err)
@@ -471,10 +471,10 @@ func (s *AWSOIDCService) ListDatabases(ctx context.Context, req *integrationpb.L
dbList = append(dbList, dbV3)
}
- return &integrationpb.ListDatabasesResponse{
+ return integrationpb.ListDatabasesResponse_builder{
Databases: dbList,
NextToken: listDBsResp.NextToken,
- }, nil
+ }.Build(), nil
}
// ListSecurityGroups returns a paginated list of SecurityGroups.
@@ -488,7 +488,7 @@ func (s *AWSOIDCService) ListSecurityGroups(ctx context.Context, req *integratio
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -499,8 +499,8 @@ func (s *AWSOIDCService) ListSecurityGroups(ctx context.Context, req *integratio
}
listSGsResp, err := awsoidc.ListSecurityGroups(ctx, listSGsClient, awsoidc.ListSecurityGroupsRequest{
- VPCID: req.VpcId,
- NextToken: req.NextToken,
+ VPCID: req.GetVpcId(),
+ NextToken: req.GetNextToken(),
})
if err != nil {
return nil, trace.Wrap(err)
@@ -508,19 +508,19 @@ func (s *AWSOIDCService) ListSecurityGroups(ctx context.Context, req *integratio
sgList := make([]*integrationpb.SecurityGroup, 0, len(listSGsResp.SecurityGroups))
for _, sg := range listSGsResp.SecurityGroups {
- sgList = append(sgList, &integrationpb.SecurityGroup{
+ sgList = append(sgList, integrationpb.SecurityGroup_builder{
Name: sg.Name,
Id: sg.ID,
Description: sg.Description,
InboundRules: convertSecurityGroupRulesToProto(sg.InboundRules),
OutboundRules: convertSecurityGroupRulesToProto(sg.OutboundRules),
- })
+ }.Build())
}
- return &integrationpb.ListSecurityGroupsResponse{
+ return integrationpb.ListSecurityGroupsResponse_builder{
SecurityGroups: sgList,
NextToken: listSGsResp.NextToken,
- }, nil
+ }.Build(), nil
}
func convertSecurityGroupRulesToProto(inRules []awsoidc.SecurityGroupRule) []*integrationpb.SecurityGroupRule {
@@ -531,10 +531,10 @@ func convertSecurityGroupRulesToProto(inRules []awsoidc.SecurityGroupRule) []*in
cidrs = make([]*integrationpb.SecurityGroupRuleCIDR, 0, len(r.CIDRs))
}
for _, cidr := range r.CIDRs {
- cidrs = append(cidrs, &integrationpb.SecurityGroupRuleCIDR{
+ cidrs = append(cidrs, integrationpb.SecurityGroupRuleCIDR_builder{
Cidr: cidr.CIDR,
Description: cidr.Description,
- })
+ }.Build())
}
var groupIDs []*integrationpb.SecurityGroupRuleGroupID
@@ -542,18 +542,18 @@ func convertSecurityGroupRulesToProto(inRules []awsoidc.SecurityGroupRule) []*in
groupIDs = make([]*integrationpb.SecurityGroupRuleGroupID, 0, len(r.Groups))
}
for _, group := range r.Groups {
- groupIDs = append(groupIDs, &integrationpb.SecurityGroupRuleGroupID{
+ groupIDs = append(groupIDs, integrationpb.SecurityGroupRuleGroupID_builder{
GroupId: group.GroupId,
Description: group.Description,
- })
+ }.Build())
}
- out = append(out, &integrationpb.SecurityGroupRule{
+ out = append(out, integrationpb.SecurityGroupRule_builder{
IpProtocol: r.IPProtocol,
FromPort: int32(r.FromPort),
ToPort: int32(r.ToPort),
Cidrs: cidrs,
GroupIds: groupIDs,
- })
+ }.Build())
}
return out
}
@@ -574,7 +574,7 @@ func (s *AWSOIDCService) DeployDatabaseService(ctx context.Context, req *integra
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -584,34 +584,34 @@ func (s *AWSOIDCService) DeployDatabaseService(ctx context.Context, req *integra
return nil, trace.Wrap(err)
}
- deployments := make([]awsoidc.DeployDatabaseServiceRequestDeployment, 0, len(req.Deployments))
- for _, d := range req.Deployments {
+ deployments := make([]awsoidc.DeployDatabaseServiceRequestDeployment, 0, len(req.GetDeployments()))
+ for _, d := range req.GetDeployments() {
deployments = append(deployments, awsoidc.DeployDatabaseServiceRequestDeployment{
- VPCID: d.VpcId,
- SubnetIDs: d.SubnetIds,
- SecurityGroupIDs: d.SecurityGroups,
- DeployServiceConfig: d.TeleportConfigString,
+ VPCID: d.GetVpcId(),
+ SubnetIDs: d.GetSubnetIds(),
+ SecurityGroupIDs: d.GetSecurityGroups(),
+ DeployServiceConfig: d.GetTeleportConfigString(),
})
}
deployDBResp, err := awsoidc.DeployDatabaseService(ctx, deployServiceClient, awsoidc.DeployDatabaseServiceRequest{
- Region: req.Region,
- TaskRoleARN: req.TaskRoleArn,
- TeleportVersionTag: req.TeleportVersion,
- DeploymentJoinTokenName: req.DeploymentJoinTokenName,
+ Region: req.GetRegion(),
+ TaskRoleARN: req.GetTaskRoleArn(),
+ TeleportVersionTag: req.GetTeleportVersion(),
+ DeploymentJoinTokenName: req.GetDeploymentJoinTokenName(),
Deployments: deployments,
TeleportClusterName: clusterName.GetClusterName(),
- IntegrationName: req.Integration,
+ IntegrationName: req.GetIntegration(),
TeleportBuildType: s.modules.BuildType(),
})
if err != nil {
return nil, trace.Wrap(err)
}
- return &integrationpb.DeployDatabaseServiceResponse{
+ return integrationpb.DeployDatabaseServiceResponse_builder{
ClusterArn: deployDBResp.ClusterARN,
ClusterDashboardUrl: deployDBResp.ClusterDashboardURL,
- }, nil
+ }.Build(), nil
}
// ListDeployedDatabaseServices lists Database Services deployed into Amazon ECS.
@@ -630,7 +630,7 @@ func (s *AWSOIDCService) ListDeployedDatabaseServices(ctx context.Context, req *
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -641,10 +641,10 @@ func (s *AWSOIDCService) ListDeployedDatabaseServices(ctx context.Context, req *
}
listDatabaseServicesResponse, err := awsoidc.ListDeployedDatabaseServices(ctx, listDatabaseServicesClient, awsoidc.ListDeployedDatabaseServicesRequest{
- Integration: req.Integration,
+ Integration: req.GetIntegration(),
TeleportClusterName: clusterName.GetClusterName(),
- Region: req.Region,
- NextToken: req.NextToken,
+ Region: req.GetRegion(),
+ NextToken: req.GetNextToken(),
})
if err != nil {
return nil, trace.Wrap(err)
@@ -652,18 +652,18 @@ func (s *AWSOIDCService) ListDeployedDatabaseServices(ctx context.Context, req *
deployedDatabaseServices := make([]*integrationpb.DeployedDatabaseService, 0, len(listDatabaseServicesResponse.DeployedDatabaseServices))
for _, deployedService := range listDatabaseServicesResponse.DeployedDatabaseServices {
- deployedDatabaseServices = append(deployedDatabaseServices, &integrationpb.DeployedDatabaseService{
+ deployedDatabaseServices = append(deployedDatabaseServices, integrationpb.DeployedDatabaseService_builder{
Name: deployedService.Name,
ServiceDashboardUrl: deployedService.ServiceDashboardURL,
ContainerEntryPoint: deployedService.ContainerEntryPoint,
ContainerCommand: deployedService.ContainerCommand,
- })
+ }.Build())
}
- return &integrationpb.ListDeployedDatabaseServicesResponse{
+ return integrationpb.ListDeployedDatabaseServicesResponse_builder{
DeployedDatabaseServices: deployedDatabaseServices,
NextToken: listDatabaseServicesResponse.NextToken,
- }, nil
+ }.Build(), nil
}
// EnrollEKSClusters enrolls EKS clusters into Teleport by installing teleport-kube-agent chart on the clusters.
@@ -682,7 +682,7 @@ func (s *AWSOIDCService) EnrollEKSClusters(ctx context.Context, req *integration
return nil, trace.BadParameter("could not get public proxy address.")
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -699,15 +699,15 @@ func (s *AWSOIDCService) EnrollEKSClusters(ctx context.Context, req *integration
features := s.modules.Features()
enrollmentResponse, err := awsoidc.EnrollEKSClusters(ctx, s.logger, s.clock, publicProxyAddr, enrollEKSClient, awsoidc.EnrollEKSClustersRequest{
- Region: req.Region,
+ Region: req.GetRegion(),
ClusterNames: req.GetEksClusterNames(),
- EnableAppDiscovery: req.EnableAppDiscovery,
+ EnableAppDiscovery: req.GetEnableAppDiscovery(),
EnableAutoUpgrades: features.AutomaticUpgrades,
IsCloud: features.Cloud,
- AgentVersion: req.AgentVersion,
+ AgentVersion: req.GetAgentVersion(),
TeleportClusterName: clusterName.GetClusterName(),
- IntegrationName: req.Integration,
- ExtraLabels: req.ExtraLabels,
+ IntegrationName: req.GetIntegration(),
+ ExtraLabels: req.GetExtraLabels(),
})
if err != nil {
return nil, trace.Wrap(err)
@@ -715,17 +715,17 @@ func (s *AWSOIDCService) EnrollEKSClusters(ctx context.Context, req *integration
results := make([]*integrationpb.EnrollEKSClusterResult, 0, len(enrollmentResponse.Results))
for _, r := range enrollmentResponse.Results {
- results = append(results, &integrationpb.EnrollEKSClusterResult{
+ results = append(results, integrationpb.EnrollEKSClusterResult_builder{
EksClusterName: r.ClusterName,
ResourceId: r.ResourceId,
Error: trace.UserMessage(r.Error),
IssueType: r.IssueType,
- })
+ }.Build())
}
- return &integrationpb.EnrollEKSClustersResponse{
+ return integrationpb.EnrollEKSClustersResponse_builder{
Results: results,
- }, nil
+ }.Build(), nil
}
// DeployService deploys Services into Amazon ECS.
@@ -744,7 +744,7 @@ func (s *AWSOIDCService) DeployService(ctx context.Context, req *integrationpb.D
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -755,28 +755,28 @@ func (s *AWSOIDCService) DeployService(ctx context.Context, req *integrationpb.D
}
deployServiceResp, err := awsoidc.DeployService(ctx, deployServiceClient, awsoidc.DeployServiceRequest{
- DeploymentJoinTokenName: req.DeploymentJoinTokenName,
- DeploymentMode: req.DeploymentMode,
- TeleportConfigString: req.TeleportConfigString,
- IntegrationName: req.Integration,
- Region: req.Region,
- SecurityGroups: req.SecurityGroups,
- SubnetIDs: req.SubnetIds,
- TaskRoleARN: req.TaskRoleArn,
+ DeploymentJoinTokenName: req.GetDeploymentJoinTokenName(),
+ DeploymentMode: req.GetDeploymentMode(),
+ TeleportConfigString: req.GetTeleportConfigString(),
+ IntegrationName: req.GetIntegration(),
+ Region: req.GetRegion(),
+ SecurityGroups: req.GetSecurityGroups(),
+ SubnetIDs: req.GetSubnetIds(),
+ TaskRoleARN: req.GetTaskRoleArn(),
TeleportClusterName: clusterName.GetClusterName(),
- TeleportVersionTag: req.TeleportVersion,
+ TeleportVersionTag: req.GetTeleportVersion(),
TeleportBuildType: s.modules.BuildType(),
})
if err != nil {
return nil, trace.Wrap(err)
}
- return &integrationpb.DeployServiceResponse{
+ return integrationpb.DeployServiceResponse_builder{
ClusterArn: deployServiceResp.ClusterARN,
ServiceArn: deployServiceResp.ServiceARN,
TaskDefinitionArn: deployServiceResp.TaskDefinitionARN,
ServiceDashboardUrl: deployServiceResp.ServiceDashboardURL,
- }, nil
+ }.Build(), nil
}
// ListEC2 returns a paginated list of AWS EC2 instances.
@@ -792,7 +792,7 @@ func (s *AWSOIDCService) ListEC2(ctx context.Context, req *integrationpb.ListEC2
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -803,9 +803,9 @@ func (s *AWSOIDCService) ListEC2(ctx context.Context, req *integrationpb.ListEC2
}
listEC2Resp, err := awsoidc.ListEC2(ctx, listEC2Client, awsoidc.ListEC2Request{
- Region: req.Region,
- Integration: req.Integration,
- NextToken: req.NextToken,
+ Region: req.GetRegion(),
+ Integration: req.GetIntegration(),
+ NextToken: req.GetNextToken(),
})
if err != nil {
return nil, trace.Wrap(err)
@@ -825,10 +825,10 @@ func (s *AWSOIDCService) ListEC2(ctx context.Context, req *integrationpb.ListEC2
serverList = append(serverList, serverV2)
}
- return &integrationpb.ListEC2Response{
+ return integrationpb.ListEC2Response_builder{
Servers: serverList,
NextToken: listEC2Resp.NextToken,
- }, nil
+ }.Build(), nil
}
// ListEKSCluster returns a paginated list of AWS EKS Clusters.
@@ -842,7 +842,7 @@ func (s *AWSOIDCService) ListEKSClusters(ctx context.Context, req *integrationpb
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -853,8 +853,8 @@ func (s *AWSOIDCService) ListEKSClusters(ctx context.Context, req *integrationpb
}
listEKSClustersResp, err := awsoidc.ListEKSClusters(ctx, listEKSClustersClient, awsoidc.ListEKSClustersRequest{
- Region: req.Region,
- NextToken: req.NextToken,
+ Region: req.GetRegion(),
+ NextToken: req.GetNextToken(),
})
if err != nil {
return nil, trace.Wrap(err)
@@ -865,14 +865,14 @@ func (s *AWSOIDCService) ListEKSClusters(ctx context.Context, req *integrationpb
clustersList = append(clustersList, convertEKSCluster(cluster))
}
- return &integrationpb.ListEKSClustersResponse{
+ return integrationpb.ListEKSClustersResponse_builder{
Clusters: clustersList,
NextToken: listEKSClustersResp.NextToken,
- }, nil
+ }.Build(), nil
}
func convertEKSCluster(clusterService awsoidc.EKSCluster) *integrationpb.EKSCluster {
- return &integrationpb.EKSCluster{
+ return integrationpb.EKSCluster_builder{
Name: clusterService.Name,
Region: clusterService.Region,
Arn: clusterService.Arn,
@@ -881,7 +881,7 @@ func convertEKSCluster(clusterService awsoidc.EKSCluster) *integrationpb.EKSClus
Status: clusterService.Status,
EndpointPublicAccess: clusterService.EndpointPublicAccess,
AuthenticationMode: clusterService.AuthenticationMode,
- }
+ }.Build()
}
// ListSubnets returns a list of AWS VPC subnets.
@@ -895,7 +895,7 @@ func (s *AWSOIDCService) ListSubnets(ctx context.Context, req *integrationpb.Lis
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -906,8 +906,8 @@ func (s *AWSOIDCService) ListSubnets(ctx context.Context, req *integrationpb.Lis
}
resp, err := awsoidc.ListSubnets(ctx, awsClient, awsoidc.ListSubnetsRequest{
- VPCID: req.VpcId,
- NextToken: req.NextToken,
+ VPCID: req.GetVpcId(),
+ NextToken: req.GetNextToken(),
})
if err != nil {
return nil, trace.Wrap(err)
@@ -915,17 +915,17 @@ func (s *AWSOIDCService) ListSubnets(ctx context.Context, req *integrationpb.Lis
subnets := make([]*integrationpb.Subnet, 0, len(resp.Subnets))
for _, s := range resp.Subnets {
- subnets = append(subnets, &integrationpb.Subnet{
+ subnets = append(subnets, integrationpb.Subnet_builder{
Name: s.Name,
Id: s.ID,
AvailabilityZone: s.AvailabilityZone,
- })
+ }.Build())
}
- return &integrationpb.ListSubnetsResponse{
+ return integrationpb.ListSubnetsResponse_builder{
Subnets: subnets,
NextToken: resp.NextToken,
- }, nil
+ }.Build(), nil
}
// ListVPCs returns a list of AWS VPCs.
@@ -939,7 +939,7 @@ func (s *AWSOIDCService) ListVPCs(ctx context.Context, req *integrationpb.ListVP
return nil, trace.Wrap(err)
}
- awsClientReq, err := s.awsClientReq(ctx, req.Integration, req.Region)
+ awsClientReq, err := s.awsClientReq(ctx, req.GetIntegration(), req.GetRegion())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -950,7 +950,7 @@ func (s *AWSOIDCService) ListVPCs(ctx context.Context, req *integrationpb.ListVP
}
resp, err := awsoidc.ListVPCs(ctx, awsClient, awsoidc.ListVPCsRequest{
- NextToken: req.NextToken,
+ NextToken: req.GetNextToken(),
})
if err != nil {
return nil, trace.Wrap(err)
@@ -958,16 +958,16 @@ func (s *AWSOIDCService) ListVPCs(ctx context.Context, req *integrationpb.ListVP
vpcs := make([]*integrationpb.VPC, 0, len(resp.VPCs))
for _, s := range resp.VPCs {
- vpcs = append(vpcs, &integrationpb.VPC{
+ vpcs = append(vpcs, integrationpb.VPC_builder{
Name: s.Name,
Id: s.ID,
- })
+ }.Build())
}
- return &integrationpb.ListVPCsResponse{
+ return integrationpb.ListVPCsResponse_builder{
Vpcs: vpcs,
NextToken: resp.NextToken,
- }, nil
+ }.Build(), nil
}
// Ping does a health check for an integration.
@@ -984,7 +984,7 @@ func (s *AWSOIDCService) Ping(ctx context.Context, req *integrationpb.PingReques
var awsClientReq *awsoidc.AWSClientRequest
switch {
case req.GetRoleArn() != "":
- awsClientReq, err = s.awsClientReqWithARN(ctx, req.Integration, awsutils.AWSGlobalRegion, req.GetRoleArn())
+ awsClientReq, err = s.awsClientReqWithARN(ctx, req.GetIntegration(), awsutils.AWSGlobalRegion, req.GetRoleArn())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -1007,9 +1007,9 @@ func (s *AWSOIDCService) Ping(ctx context.Context, req *integrationpb.PingReques
return nil, trace.Wrap(err)
}
- return &integrationpb.PingResponse{
+ return integrationpb.PingResponse_builder{
AccountId: resp.AccountID,
Arn: resp.ARN,
UserId: resp.UserID,
- }, nil
+ }.Build(), nil
}
diff --git a/lib/auth/integration/integrationv1/awsoidc_test.go b/lib/auth/integration/integrationv1/awsoidc_test.go
index 2ead25f9f94..403ad145233 100644
--- a/lib/auth/integration/integrationv1/awsoidc_test.go
+++ b/lib/auth/integration/integrationv1/awsoidc_test.go
@@ -82,7 +82,7 @@ func TestGenerateAWSOIDCToken(t *testing.T) {
}},
}, localClient)
- _, err := resourceSvc.GenerateAWSOIDCToken(ctx, &integrationv1.GenerateAWSOIDCTokenRequest{Integration: integrationNameWithoutIssuer})
+ _, err := resourceSvc.GenerateAWSOIDCToken(ctx, integrationv1.GenerateAWSOIDCTokenRequest_builder{Integration: integrationNameWithoutIssuer}.Build())
require.True(t, trace.IsAccessDenied(err), "expected AccessDenied error, got %T", err)
})
@@ -97,7 +97,7 @@ func TestGenerateAWSOIDCToken(t *testing.T) {
},
})
- _, err := resourceSvc.GenerateAWSOIDCToken(ctx, &integrationv1.GenerateAWSOIDCTokenRequest{Integration: integrationNameWithoutIssuer})
+ _, err := resourceSvc.GenerateAWSOIDCToken(ctx, integrationv1.GenerateAWSOIDCTokenRequest_builder{Integration: integrationNameWithoutIssuer}.Build())
require.NoError(t, err)
}
})
@@ -127,9 +127,9 @@ func TestGenerateAWSOIDCToken(t *testing.T) {
require.NoError(t, err)
t.Run("with integration in rpc call but no issuer defined", func(t *testing.T) {
- resp, err := resourceSvc.GenerateAWSOIDCToken(ctx, &integrationv1.GenerateAWSOIDCTokenRequest{
+ resp, err := resourceSvc.GenerateAWSOIDCToken(ctx, integrationv1.GenerateAWSOIDCTokenRequest_builder{
Integration: integrationNameWithoutIssuer,
- })
+ }.Build())
require.NoError(t, err)
_, err = key.VerifyAWSOIDC(jwt.AWSOIDCVerifyParams{
@@ -145,9 +145,9 @@ func TestGenerateAWSOIDCToken(t *testing.T) {
require.Error(t, err)
})
t.Run("with integration in rpc call and issuer defined", func(t *testing.T) {
- resp, err := resourceSvc.GenerateAWSOIDCToken(ctx, &integrationv1.GenerateAWSOIDCTokenRequest{
+ resp, err := resourceSvc.GenerateAWSOIDCToken(ctx, integrationv1.GenerateAWSOIDCTokenRequest_builder{
Integration: integrationNameWithIssuer,
- })
+ }.Build())
require.NoError(t, err)
_, err = key.VerifyAWSOIDC(jwt.AWSOIDCVerifyParams{
@@ -181,15 +181,15 @@ func TestConvertSecurityGroupRulesToProto(t *testing.T) {
Description: "cidr x",
}},
}},
- expected: []*integrationv1.SecurityGroupRule{{
+ expected: []*integrationv1.SecurityGroupRule{integrationv1.SecurityGroupRule_builder{
IpProtocol: "tcp",
FromPort: 8080,
ToPort: 8081,
- Cidrs: []*integrationv1.SecurityGroupRuleCIDR{{
+ Cidrs: []*integrationv1.SecurityGroupRuleCIDR{integrationv1.SecurityGroupRuleCIDR_builder{
Cidr: "10.10.10.0/24",
Description: "cidr x",
- }},
- }},
+ }.Build()},
+ }.Build()},
},
} {
t.Run(tt.name, func(t *testing.T) {
@@ -248,76 +248,76 @@ func TestRBAC(t *testing.T) {
{
name: "ListDatabases",
fn: func() error {
- _, err := awsoidService.ListDatabases(userCtx, &integrationv1.ListDatabasesRequest{
+ _, err := awsoidService.ListDatabases(userCtx, integrationv1.ListDatabasesRequest_builder{
Integration: integrationName,
Region: "",
RdsType: "",
Engines: []string{},
NextToken: "",
VpcId: "vpc-123",
- })
+ }.Build())
return err
},
},
{
name: "EnrollEKSClusters",
fn: func() error {
- _, err := awsoidService.EnrollEKSClusters(userCtx, &integrationv1.EnrollEKSClustersRequest{
+ _, err := awsoidService.EnrollEKSClusters(userCtx, integrationv1.EnrollEKSClustersRequest_builder{
Integration: integrationName,
Region: "my-region",
EksClusterNames: []string{"EKS1"},
AgentVersion: "10.0.0",
- })
+ }.Build())
return err
},
},
{
name: "DeployService",
fn: func() error {
- _, err = awsoidService.DeployService(userCtx, &integrationv1.DeployServiceRequest{
+ _, err = awsoidService.DeployService(userCtx, integrationv1.DeployServiceRequest_builder{
Integration: integrationName,
Region: "my-region",
- })
+ }.Build())
return err
},
},
{
name: "ListSubnets",
fn: func() error {
- _, err := awsoidService.ListSubnets(userCtx, &integrationv1.ListSubnetsRequest{
+ _, err := awsoidService.ListSubnets(userCtx, integrationv1.ListSubnetsRequest_builder{
Integration: integrationName,
Region: "my-region",
VpcId: "vpc-1",
- })
+ }.Build())
return err
},
},
{
name: "ListVPCs",
fn: func() error {
- _, err := awsoidService.ListVPCs(userCtx, &integrationv1.ListVPCsRequest{
+ _, err := awsoidService.ListVPCs(userCtx, integrationv1.ListVPCsRequest_builder{
Integration: integrationName,
Region: "my-region",
- })
+ }.Build())
return err
},
},
{
name: "Ping",
fn: func() error {
- _, err := awsoidService.Ping(userCtx, &integrationv1.PingRequest{
+ _, err := awsoidService.Ping(userCtx, integrationv1.PingRequest_builder{
Integration: integrationName,
- })
+ }.Build())
return err
},
},
{
name: "Ping with arn",
fn: func() error {
- _, err := awsoidService.Ping(userCtx, &integrationv1.PingRequest{
+ _, err := awsoidService.Ping(userCtx, integrationv1.PingRequest_builder{
Integration: integrationName,
RoleArn: "some-arn",
- })
+ }.Build())
return err
},
},
@@ -343,57 +343,57 @@ func TestRBAC(t *testing.T) {
{
name: "ListDatabases",
fn: func() error {
- _, err := awsoidService.ListDatabases(userCtx, &integrationv1.ListDatabasesRequest{
+ _, err := awsoidService.ListDatabases(userCtx, integrationv1.ListDatabasesRequest_builder{
Integration: integrationName,
Region: "",
RdsType: "",
Engines: []string{},
NextToken: "",
VpcId: "vpc-123",
- })
+ }.Build())
return err
},
},
{
name: "EnrollEKSClusters",
fn: func() error {
- _, err := awsoidService.EnrollEKSClusters(userCtx, &integrationv1.EnrollEKSClustersRequest{
+ _, err := awsoidService.EnrollEKSClusters(userCtx, integrationv1.EnrollEKSClustersRequest_builder{
Integration: integrationName,
Region: "my-region",
EksClusterNames: []string{"EKS1"},
AgentVersion: "10.0.0",
- })
+ }.Build())
return err
},
},
{
name: "DeployService",
fn: func() error {
- _, err = awsoidService.DeployService(userCtx, &integrationv1.DeployServiceRequest{
+ _, err = awsoidService.DeployService(userCtx, integrationv1.DeployServiceRequest_builder{
Integration: integrationName,
Region: "my-region",
- })
+ }.Build())
return err
},
},
{
name: "ListSubnets",
fn: func() error {
- _, err := awsoidService.ListSubnets(userCtx, &integrationv1.ListSubnetsRequest{
+ _, err := awsoidService.ListSubnets(userCtx, integrationv1.ListSubnetsRequest_builder{
Integration: integrationName,
Region: "my-region",
VpcId: "vpc-1",
- })
+ }.Build())
return err
},
},
{
name: "ListVPCs",
fn: func() error {
- _, err := awsoidService.ListVPCs(userCtx, &integrationv1.ListVPCsRequest{
+ _, err := awsoidService.ListVPCs(userCtx, integrationv1.ListVPCsRequest_builder{
Integration: integrationName,
Region: "my-region",
- })
+ }.Build())
return err
},
},
@@ -407,10 +407,10 @@ func TestRBAC(t *testing.T) {
{
name: "ListDeployedDatabaseServices",
fn: func() error {
- _, err := awsoidService.ListDeployedDatabaseServices(userCtx, &integrationv1.ListDeployedDatabaseServicesRequest{
+ _, err := awsoidService.ListDeployedDatabaseServices(userCtx, integrationv1.ListDeployedDatabaseServicesRequest_builder{
Integration: integrationName,
Region: "my-region",
- })
+ }.Build())
return err
},
},
@@ -441,7 +441,7 @@ func TestConvertEKSCluster(t *testing.T) {
AuthenticationMode: "API",
EndpointPublicAccess: true,
},
- expected: &integrationv1.EKSCluster{
+ expected: integrationv1.EKSCluster_builder{
Name: "my-cluster",
Region: "us-east-1",
Arn: "my-arn",
@@ -450,7 +450,7 @@ func TestConvertEKSCluster(t *testing.T) {
Status: "ACTIVE",
AuthenticationMode: "API",
EndpointPublicAccess: true,
- },
+ }.Build(),
},
} {
t.Run(tt.name, func(t *testing.T) {
diff --git a/lib/auth/integration/integrationv1/awsra.go b/lib/auth/integration/integrationv1/awsra.go
index ff12884ea66..bf15a63a836 100644
--- a/lib/auth/integration/integrationv1/awsra.go
+++ b/lib/auth/integration/integrationv1/awsra.go
@@ -85,12 +85,12 @@ func (s *Service) generateAWSRACredentialsWithoutAuthZ(ctx context.Context, req
return nil, trace.Wrap(err)
}
- return &integrationpb.GenerateAWSRACredentialsResponse{
+ return integrationpb.GenerateAWSRACredentialsResponse_builder{
AccessKeyId: awsCredentials.AccessKeyID,
SecretAccessKey: awsCredentials.SecretAccessKey,
SessionToken: awsCredentials.SessionToken,
Expiration: timestamppb.New(awsCredentials.Expiration),
- }, nil
+ }.Build(), nil
}
func (s *Service) getAWSRolesAnywhereIntegrationSpec(ctx context.Context, integrationName string) (*types.AWSRAIntegrationSpecV1, error) {
@@ -199,12 +199,12 @@ func (s *AWSRolesAnywhereService) ListRolesAnywhereProfiles(ctx context.Context,
}
trustAnchor := spec.TrustAnchorARN
- credentials, err := s.integrationService.generateAWSRACredentialsWithoutAuthZ(ctx, &integrationpb.GenerateAWSRACredentialsRequest{
+ credentials, err := s.integrationService.generateAWSRACredentialsWithoutAuthZ(ctx, integrationpb.GenerateAWSRACredentialsRequest_builder{
ProfileArn: spec.ProfileSyncConfig.ProfileARN,
RoleArn: spec.ProfileSyncConfig.RoleARN,
ProfileAcceptsRoleSessionName: spec.ProfileSyncConfig.ProfileAcceptsRoleSessionName,
SubjectName: authCtx.Identity.GetIdentity().Username,
- }, trustAnchor)
+ }.Build(), trustAnchor)
if err != nil {
return nil, trace.Wrap(err)
}
@@ -217,10 +217,10 @@ func (s *AWSRolesAnywhereService) ListRolesAnywhereProfiles(ctx context.Context,
listRolesAnywhereClient, err := awsra.NewListRolesAnywhereProfilesClient(ctx, &awsra.AWSClientConfig{
Credentials: awsra.Credentials{
- AccessKeyID: credentials.AccessKeyId,
- SecretAccessKey: credentials.SecretAccessKey,
- SessionToken: credentials.SessionToken,
- Expiration: credentials.Expiration.AsTime(),
+ AccessKeyID: credentials.GetAccessKeyId(),
+ SecretAccessKey: credentials.GetSecretAccessKey(),
+ SessionToken: credentials.GetSessionToken(),
+ Expiration: credentials.GetExpiration().AsTime(),
Version: 1,
},
Region: trustAnchorRegion,
@@ -239,10 +239,10 @@ func (s *AWSRolesAnywhereService) ListRolesAnywhereProfiles(ctx context.Context,
return nil, trace.Wrap(err)
}
- return &integrationpb.ListRolesAnywhereProfilesResponse{
+ return integrationpb.ListRolesAnywhereProfilesResponse_builder{
Profiles: profileList.Profiles,
NextPageToken: profileList.NextToken,
- }, nil
+ }.Build(), nil
}
// AWSRolesAnywherePing performs a health check for the AWS Roles Anywhere integration.
@@ -264,8 +264,8 @@ func (s *AWSRolesAnywhereService) AWSRolesAnywherePing(ctx context.Context, req
var trustAnchorARN, profileARN, roleARN string
- switch req.Mode.(type) {
- case *integrationpb.AWSRolesAnywherePingRequest_Integration:
+ switch req.WhichMode() {
+ case integrationpb.AWSRolesAnywherePingRequest_Integration_case:
spec, err := s.integrationService.getAWSRolesAnywhereIntegrationSpec(ctx, req.GetIntegration())
if err != nil {
return nil, trace.Wrap(err)
@@ -275,7 +275,7 @@ func (s *AWSRolesAnywhereService) AWSRolesAnywherePing(ctx context.Context, req
profileARN = spec.ProfileSyncConfig.ProfileARN
roleARN = spec.ProfileSyncConfig.RoleARN
- case *integrationpb.AWSRolesAnywherePingRequest_Custom:
+ case integrationpb.AWSRolesAnywherePingRequest_Custom_case:
trustAnchorARN = req.GetCustom().GetTrustAnchorArn()
profileARN = req.GetCustom().GetProfileArn()
roleARN = req.GetCustom().GetRoleArn()
@@ -291,11 +291,11 @@ func (s *AWSRolesAnywhereService) AWSRolesAnywherePing(ctx context.Context, req
"role_arn", roleARN,
)
- credentialsRequest := &integrationpb.GenerateAWSRACredentialsRequest{
+ credentialsRequest := integrationpb.GenerateAWSRACredentialsRequest_builder{
ProfileArn: profileARN,
RoleArn: roleARN,
SubjectName: authCtx.Identity.GetIdentity().Username,
- }
+ }.Build()
trustAnchorARNParsed, err := arn.Parse(trustAnchorARN)
if err != nil {
@@ -310,10 +310,10 @@ func (s *AWSRolesAnywhereService) AWSRolesAnywherePing(ctx context.Context, req
pingClient, err := s.newPingClient(ctx, &awsra.AWSClientConfig{
Credentials: awsra.Credentials{
- AccessKeyID: credentials.AccessKeyId,
- SecretAccessKey: credentials.SecretAccessKey,
- SessionToken: credentials.SessionToken,
- Expiration: credentials.Expiration.AsTime(),
+ AccessKeyID: credentials.GetAccessKeyId(),
+ SecretAccessKey: credentials.GetSecretAccessKey(),
+ SessionToken: credentials.GetSessionToken(),
+ Expiration: credentials.GetExpiration().AsTime(),
Version: 1,
},
Region: trustAnchorRegion,
@@ -329,10 +329,10 @@ func (s *AWSRolesAnywhereService) AWSRolesAnywherePing(ctx context.Context, req
return nil, trace.Wrap(err)
}
- return &integrationpb.AWSRolesAnywherePingResponse{
+ return integrationpb.AWSRolesAnywherePingResponse_builder{
ProfileCount: int32(pingResp.EnabledProfileCounter),
AccountId: pingResp.AccountID,
Arn: pingResp.ARN,
UserId: pingResp.UserID,
- }, nil
+ }.Build(), nil
}
diff --git a/lib/auth/integration/integrationv1/awsra_test.go b/lib/auth/integration/integrationv1/awsra_test.go
index f244f0d0e31..63830eb7651 100644
--- a/lib/auth/integration/integrationv1/awsra_test.go
+++ b/lib/auth/integration/integrationv1/awsra_test.go
@@ -28,6 +28,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/gravitational/trace"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
integrationv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/integration/v1"
"github.com/gravitational/teleport/api/types"
@@ -68,12 +69,12 @@ func TestGenerateAWSRACredentials(t *testing.T) {
}},
}, localClient)
- _, err := resourceSvc.GenerateAWSRACredentials(ctx, &integrationv1.GenerateAWSRACredentialsRequest{
+ _, err := resourceSvc.GenerateAWSRACredentials(ctx, integrationv1.GenerateAWSRACredentialsRequest_builder{
Integration: integrationName,
RoleArn: "arn:aws:iam::123456789012:role/OpsTeam",
ProfileArn: "arn:aws:rolesanywhere:eu-west-2:123456789012:profile/12345678-1234-1234-1234-123456789012",
SubjectName: "test",
- })
+ }.Build())
require.True(t, trace.IsAccessDenied(err), "expected AccessDenied error, got %T", err)
})
@@ -88,13 +89,13 @@ func TestGenerateAWSRACredentials(t *testing.T) {
},
})
- _, err := resourceSvc.GenerateAWSRACredentials(ctx, &integrationv1.GenerateAWSRACredentialsRequest{
+ _, err := resourceSvc.GenerateAWSRACredentials(ctx, integrationv1.GenerateAWSRACredentialsRequest_builder{
Integration: integrationName,
RoleArn: "arn:aws:iam::123456789012:role/OpsTeam",
ProfileArn: "arn:aws:rolesanywhere:eu-west-2:123456789012:profile/12345678-1234-1234-1234-123456789012",
ProfileAcceptsRoleSessionName: true,
SubjectName: "test",
- })
+ }.Build())
require.NoError(t, err)
}
})
@@ -133,33 +134,33 @@ func TestAWSRolesAnywhereProfileSyncFilters(t *testing.T) {
t.Run("valid without filters", func(t *testing.T) {
ig := integrationWithFilters(t, "integration1", []string{})
- _, err := resourceSvc.CreateIntegration(ctx, &integrationv1.CreateIntegrationRequest{
+ _, err := resourceSvc.CreateIntegration(ctx, integrationv1.CreateIntegrationRequest_builder{
Integration: ig,
- })
+ }.Build())
require.NoError(t, err)
})
t.Run("valid with glob filter", func(t *testing.T) {
ig := integrationWithFilters(t, "integration2", []string{"MyTeam-*"})
- _, err := resourceSvc.CreateIntegration(ctx, &integrationv1.CreateIntegrationRequest{
+ _, err := resourceSvc.CreateIntegration(ctx, integrationv1.CreateIntegrationRequest_builder{
Integration: ig,
- })
+ }.Build())
require.NoError(t, err)
})
t.Run("valid with regex filter", func(t *testing.T) {
ig := integrationWithFilters(t, "integration3", []string{"^MyTeam-.*$"})
- _, err := resourceSvc.CreateIntegration(ctx, &integrationv1.CreateIntegrationRequest{
+ _, err := resourceSvc.CreateIntegration(ctx, integrationv1.CreateIntegrationRequest_builder{
Integration: ig,
- })
+ }.Build())
require.NoError(t, err)
})
t.Run("invalid with invalid regex", func(t *testing.T) {
ig := integrationWithFilters(t, "integration5", []string{`^[invalid-regex{$`})
- _, err := resourceSvc.CreateIntegration(ctx, &integrationv1.CreateIntegrationRequest{
+ _, err := resourceSvc.CreateIntegration(ctx, integrationv1.CreateIntegrationRequest_builder{
Integration: ig,
- })
+ }.Build())
require.Error(t, err)
})
}
@@ -222,31 +223,27 @@ func TestAWSRolesAnywherePing(t *testing.T) {
require.NoError(t, err)
t.Run("test connection using an integration", func(t *testing.T) {
- pingResp, err := awsRolesAnywhereService.AWSRolesAnywherePing(ctx, &integrationv1.AWSRolesAnywherePingRequest{
- Mode: &integrationv1.AWSRolesAnywherePingRequest_Integration{
- Integration: integrationName,
- },
- })
+ pingResp, err := awsRolesAnywhereService.AWSRolesAnywherePing(ctx, integrationv1.AWSRolesAnywherePingRequest_builder{
+ Integration: proto.String(integrationName),
+ }.Build())
require.NoError(t, err)
require.NotNil(t, pingResp)
- require.Equal(t, "123456789012", pingResp.AccountId)
- require.Equal(t, int32(1), pingResp.ProfileCount)
+ require.Equal(t, "123456789012", pingResp.GetAccountId())
+ require.Equal(t, int32(1), pingResp.GetProfileCount())
})
t.Run("test connection using provided trust anchor", func(t *testing.T) {
- pingResp, err := awsRolesAnywhereService.AWSRolesAnywherePing(ctx, &integrationv1.AWSRolesAnywherePingRequest{
- Mode: &integrationv1.AWSRolesAnywherePingRequest_Custom{
- Custom: &integrationv1.AWSRolesAnywherePingRequestWithoutIntegration{
- TrustAnchorArn: "arn:aws:rolesanywhere:eu-west-2:123456789012:trust-anchor/12345678-1234-1234-1234-123456789012",
- RoleArn: "arn:aws:iam::123456789012:role/SyncRole",
- ProfileArn: "arn:aws:rolesanywhere:eu-west-2:123456789012:profile/12345678-1234-1234-1234-123456789012",
- },
- },
- })
+ pingResp, err := awsRolesAnywhereService.AWSRolesAnywherePing(ctx, integrationv1.AWSRolesAnywherePingRequest_builder{
+ Custom: integrationv1.AWSRolesAnywherePingRequestWithoutIntegration_builder{
+ TrustAnchorArn: "arn:aws:rolesanywhere:eu-west-2:123456789012:trust-anchor/12345678-1234-1234-1234-123456789012",
+ RoleArn: "arn:aws:iam::123456789012:role/SyncRole",
+ ProfileArn: "arn:aws:rolesanywhere:eu-west-2:123456789012:profile/12345678-1234-1234-1234-123456789012",
+ }.Build(),
+ }.Build())
require.NoError(t, err)
require.NotNil(t, pingResp)
- require.Equal(t, "123456789012", pingResp.AccountId)
- require.Equal(t, int32(1), pingResp.ProfileCount)
+ require.Equal(t, "123456789012", pingResp.GetAccountId())
+ require.Equal(t, int32(1), pingResp.GetProfileCount())
})
}
diff --git a/lib/auth/integration/integrationv1/azureoidc.go b/lib/auth/integration/integrationv1/azureoidc.go
index 0db1fd50e59..fd56fd512d6 100644
--- a/lib/auth/integration/integrationv1/azureoidc.go
+++ b/lib/auth/integration/integrationv1/azureoidc.go
@@ -35,7 +35,7 @@ func (s *Service) GenerateAzureOIDCToken(ctx context.Context, req *integrationpb
if err != nil {
return nil, trace.Wrap(err)
}
- _, err = s.cache.GetIntegration(ctx, req.Integration)
+ _, err = s.cache.GetIntegration(ctx, req.GetIntegration())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -45,7 +45,7 @@ func (s *Service) GenerateAzureOIDCToken(ctx context.Context, req *integrationpb
if err != nil {
return nil, trace.Wrap(err)
}
- return &integrationpb.GenerateAzureOIDCTokenResponse{Token: token}, nil
+ return integrationpb.GenerateAzureOIDCTokenResponse_builder{Token: token}.Build(), nil
}
}
return nil, trace.AccessDenied("token generation is only available to auth, proxy or discovery services")
diff --git a/lib/auth/integration/integrationv1/azureoidc_test.go b/lib/auth/integration/integrationv1/azureoidc_test.go
index f235d51538d..e6dab71e142 100644
--- a/lib/auth/integration/integrationv1/azureoidc_test.go
+++ b/lib/auth/integration/integrationv1/azureoidc_test.go
@@ -61,7 +61,7 @@ func TestGenerateAzureOIDCToken(t *testing.T) {
{Resources: []string{types.KindIntegration}, Verbs: []string{types.VerbUse}},
}},
}, localClient)
- _, err = resourceSvc.GenerateAzureOIDCToken(ctx, &integrationv1.GenerateAzureOIDCTokenRequest{Integration: integrationName})
+ _, err = resourceSvc.GenerateAzureOIDCToken(ctx, integrationv1.GenerateAzureOIDCTokenRequest_builder{Integration: integrationName}.Build())
require.True(t, trace.IsAccessDenied(err), "expected AccessDenied error, got %T", err)
// Auth, Discovery, and Proxy roles should be able to generate Azure OIDC tokens
@@ -75,7 +75,7 @@ func TestGenerateAzureOIDCToken(t *testing.T) {
},
})
- _, err := resourceSvc.GenerateAzureOIDCToken(ctx, &integrationv1.GenerateAzureOIDCTokenRequest{Integration: integrationName})
+ _, err := resourceSvc.GenerateAzureOIDCToken(ctx, integrationv1.GenerateAzureOIDCTokenRequest_builder{Integration: integrationName}.Build())
require.NoError(t, err)
}
})
@@ -89,9 +89,9 @@ func TestGenerateAzureOIDCToken(t *testing.T) {
Username: string(types.RoleDiscovery),
},
})
- resp, err := resourceSvc.GenerateAzureOIDCToken(ctx, &integrationv1.GenerateAzureOIDCTokenRequest{
+ resp, err := resourceSvc.GenerateAzureOIDCToken(ctx, integrationv1.GenerateAzureOIDCTokenRequest_builder{
Integration: integrationName,
- })
+ }.Build())
require.NoError(t, err)
// Validate JWT against public key
@@ -107,7 +107,7 @@ func TestGenerateAzureOIDCToken(t *testing.T) {
require.NoError(t, err)
// Verify the Azure token using the JWT
- _, err = key.VerifyAzureToken(resp.Token)
+ _, err = key.VerifyAzureToken(resp.GetToken())
require.NoError(t, err)
})
}
diff --git a/lib/auth/integration/integrationv1/credentials.go b/lib/auth/integration/integrationv1/credentials.go
index 9d63b7b7dce..f611b2f18cd 100644
--- a/lib/auth/integration/integrationv1/credentials.go
+++ b/lib/auth/integration/integrationv1/credentials.go
@@ -39,7 +39,7 @@ func (s *Service) ExportIntegrationCertAuthorities(ctx context.Context, in *inte
if err := authCtx.CheckAccessToKind(types.KindIntegration, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
- ig, err := s.cache.GetIntegration(ctx, in.Integration)
+ ig, err := s.cache.GetIntegration(ctx, in.GetIntegration())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -51,9 +51,9 @@ func (s *Service) ExportIntegrationCertAuthorities(ctx context.Context, in *inte
// Currently only public keys are exported.
caKeySetWithoutSecrets := caKeySet.WithoutSecrets()
- return &integrationpb.ExportIntegrationCertAuthoritiesResponse{
+ return integrationpb.ExportIntegrationCertAuthoritiesResponse_builder{
CertAuthorities: &caKeySetWithoutSecrets,
- }, nil
+ }.Build(), nil
}
func buildGitHubOAuthCredentials(idSecret *types.PluginIdSecretCredential) (*types.PluginStaticCredentialsV1, error) {
diff --git a/lib/auth/integration/integrationv1/credentials_test.go b/lib/auth/integration/integrationv1/credentials_test.go
index bab9e544311..4e59e272ac6 100644
--- a/lib/auth/integration/integrationv1/credentials_test.go
+++ b/lib/auth/integration/integrationv1/credentials_test.go
@@ -52,9 +52,9 @@ func TestExportIntegrationCertAuthorities(t *testing.T) {
Username: string(types.RoleAdmin),
})
- _, err = resourceSvc.CreateIntegration(adminCtx, &integrationpb.CreateIntegrationRequest{Integration: githubIntegration})
+ _, err = resourceSvc.CreateIntegration(adminCtx, integrationpb.CreateIntegrationRequest_builder{Integration: githubIntegration}.Build())
require.NoError(t, err)
- _, err = resourceSvc.CreateIntegration(adminCtx, &integrationpb.CreateIntegrationRequest{Integration: oidcIntegration})
+ _, err = resourceSvc.CreateIntegration(adminCtx, integrationpb.CreateIntegrationRequest_builder{Integration: oidcIntegration}.Build())
require.NoError(t, err)
tests := []struct {
@@ -71,11 +71,11 @@ func TestExportIntegrationCertAuthorities(t *testing.T) {
t.Helper()
require.NoError(t, err)
require.NotNil(t, resp)
- require.NotNil(t, resp.CertAuthorities)
- require.Len(t, resp.CertAuthorities.SSH, 1)
- require.NotNil(t, resp.CertAuthorities.SSH[0])
- assert.NotEmpty(t, resp.CertAuthorities.SSH[0].PublicKey)
- assert.Empty(t, resp.CertAuthorities.SSH[0].PrivateKey)
+ require.NotNil(t, resp.GetCertAuthorities())
+ require.Len(t, resp.GetCertAuthorities().SSH, 1)
+ require.NotNil(t, resp.GetCertAuthorities().SSH[0])
+ assert.NotEmpty(t, resp.GetCertAuthorities().SSH[0].PublicKey)
+ assert.Empty(t, resp.GetCertAuthorities().SSH[0].PrivateKey)
},
},
{
@@ -115,9 +115,9 @@ func TestExportIntegrationCertAuthorities(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
- resp, err := resourceSvc.ExportIntegrationCertAuthorities(test.identity, &integrationpb.ExportIntegrationCertAuthoritiesRequest{
+ resp, err := resourceSvc.ExportIntegrationCertAuthorities(test.identity, integrationpb.ExportIntegrationCertAuthoritiesRequest_builder{
Integration: test.integration,
- })
+ }.Build())
test.check(t, resp, err)
})
}
diff --git a/lib/auth/integration/integrationv1/github.go b/lib/auth/integration/integrationv1/github.go
index e9fcbd1b3b0..a1757e4fb06 100644
--- a/lib/auth/integration/integrationv1/github.go
+++ b/lib/auth/integration/integrationv1/github.go
@@ -46,26 +46,26 @@ func (s *Service) GenerateGitHubUserCert(ctx context.Context, in *integrationpb.
if err != nil {
return nil, trace.Wrap(err)
}
- caSigner, err := s.getGitHubSigner(ctx, in.Integration)
+ caSigner, err := s.getGitHubSigner(ctx, in.GetIntegration())
if err != nil {
return nil, trace.Wrap(err)
}
if err := cert.SignCert(rand.Reader, caSigner); err != nil {
return nil, trace.Wrap(err)
}
- return &integrationpb.GenerateGitHubUserCertResponse{
+ return integrationpb.GenerateGitHubUserCertResponse_builder{
AuthorizedKey: ssh.MarshalAuthorizedKey(cert),
- }, nil
+ }.Build(), nil
}
func (s *Service) prepareGitHubCert(in *integrationpb.GenerateGitHubUserCertRequest) (*ssh.Certificate, error) {
- if in.UserId == "" {
+ if in.GetUserId() == "" {
return nil, trace.BadParameter("missing UserId for GenerateGitHubUserCert")
}
- if in.KeyId == "" {
+ if in.GetKeyId() == "" {
return nil, trace.BadParameter("missing KeyId for GenerateGitHubUserCert")
}
- key, _, _, _, err := ssh.ParseAuthorizedKey(in.PublicKey)
+ key, _, _, _, err := ssh.ParseAuthorizedKey(in.GetPublicKey())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -75,12 +75,12 @@ func (s *Service) prepareGitHubCert(in *integrationpb.GenerateGitHubUserCertRequ
cert := &ssh.Certificate{
Key: key,
CertType: ssh.UserCert,
- KeyId: in.KeyId,
+ KeyId: in.GetKeyId(),
ValidAfter: uint64(now.Add(-time.Minute).Unix()),
- ValidBefore: uint64(now.Add(in.Ttl.AsDuration()).Unix()),
+ ValidBefore: uint64(now.Add(in.GetTtl().AsDuration()).Unix()),
Permissions: ssh.Permissions{
Extensions: map[string]string{
- "id@github.com": in.UserId,
+ "id@github.com": in.GetUserId(),
},
},
}
diff --git a/lib/auth/integration/integrationv1/github_test.go b/lib/auth/integration/integrationv1/github_test.go
index bc576e1e8f6..d10b01d337e 100644
--- a/lib/auth/integration/integrationv1/github_test.go
+++ b/lib/auth/integration/integrationv1/github_test.go
@@ -46,19 +46,19 @@ func TestGenerateGitHubUserCert(t *testing.T) {
Role: types.RoleAdmin,
Username: string(types.RoleAdmin),
})
- _, err = resourceSvc.CreateIntegration(adminCtx, &integrationpb.CreateIntegrationRequest{Integration: githubIntegration})
+ _, err = resourceSvc.CreateIntegration(adminCtx, integrationpb.CreateIntegrationRequest_builder{Integration: githubIntegration}.Build())
require.NoError(t, err)
key, err := cryptosuites.GeneratePrivateKeyWithAlgorithm(cryptosuites.Ed25519)
require.NoError(t, err)
- req := &integrationpb.GenerateGitHubUserCertRequest{
+ req := integrationpb.GenerateGitHubUserCertRequest_builder{
Integration: "github-my-org",
PublicKey: key.MarshalSSHPublicKey(),
UserId: "1122334455",
KeyId: "alice",
Ttl: durationpb.New(time.Minute),
- }
+ }.Build()
// Admin users cannot generate certs.
_, err = resourceSvc.GenerateGitHubUserCert(adminCtx, req)
@@ -71,7 +71,7 @@ func TestGenerateGitHubUserCert(t *testing.T) {
})
resp, err := resourceSvc.GenerateGitHubUserCert(proxyCtx, req)
require.NoError(t, err)
- authorizedKey, _, _, _, err := ssh.ParseAuthorizedKey(resp.AuthorizedKey)
+ authorizedKey, _, _, _, err := ssh.ParseAuthorizedKey(resp.GetAuthorizedKey())
require.NoError(t, err)
sshCert, ok := authorizedKey.(*ssh.Certificate)
require.True(t, ok)
diff --git a/lib/auth/integration/integrationv1/service.go b/lib/auth/integration/integrationv1/service.go
index 009a45aff53..db563dbf95b 100644
--- a/lib/auth/integration/integrationv1/service.go
+++ b/lib/auth/integration/integrationv1/service.go
@@ -218,10 +218,10 @@ func (s *Service) ListIntegrations(ctx context.Context, req *integrationpb.ListI
igs[i] = v1
}
- return &integrationpb.ListIntegrationsResponse{
+ return integrationpb.ListIntegrationsResponse_builder{
Integrations: igs,
NextKey: nextKey,
- }, nil
+ }.Build(), nil
}
// GetIntegration returns the specified Integration resource.
@@ -260,25 +260,25 @@ func (s *Service) CreateIntegration(ctx context.Context, req *integrationpb.Crea
return nil, trace.Wrap(err)
}
- switch req.Integration.GetSubKind() {
+ switch req.GetIntegration().GetSubKind() {
case types.IntegrationSubKindGitHub:
if s.modules.BuildType() != modules.BuildEnterprise {
return nil, trace.AccessDenied("GitHub integration requires a Teleport Enterprise license")
}
- if err := s.createGitHubCredentials(ctx, req.Integration); err != nil {
+ if err := s.createGitHubCredentials(ctx, req.GetIntegration()); err != nil {
return nil, trace.Wrap(err)
}
case types.IntegrationSubKindAWSOIDC, types.IntegrationSubKindAWSRolesAnywhere:
- if err := awscommon.ValidIntegrationName(req.Integration.GetName()); err != nil {
+ if err := awscommon.ValidIntegrationName(req.GetIntegration().GetName()); err != nil {
return nil, trace.Wrap(err)
}
- if err := validateAWSRolesAnywhereProfileFilters(req.Integration); err != nil {
+ if err := validateAWSRolesAnywhereProfileFilters(req.GetIntegration()); err != nil {
return nil, trace.Wrap(err)
}
}
- ig, err := s.backend.CreateIntegration(ctx, req.Integration)
+ ig, err := s.backend.CreateIntegration(ctx, req.GetIntegration())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -324,15 +324,15 @@ func (s *Service) UpdateIntegration(ctx context.Context, req *integrationpb.Upda
return nil, trace.Wrap(err)
}
- if err := validateAWSRolesAnywhereProfileFilters(req.Integration); err != nil {
+ if err := validateAWSRolesAnywhereProfileFilters(req.GetIntegration()); err != nil {
return nil, trace.Wrap(err)
}
- if err := s.maybeUpdateStaticCredentials(ctx, req.Integration); err != nil {
+ if err := s.maybeUpdateStaticCredentials(ctx, req.GetIntegration()); err != nil {
return nil, trace.Wrap(err)
}
- ig, err := s.backend.UpdateIntegration(ctx, req.Integration)
+ ig, err := s.backend.UpdateIntegration(ctx, req.GetIntegration())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -411,7 +411,7 @@ func (s *Service) DeleteIntegration(ctx context.Context, req *integrationpb.Dele
return nil, trace.Wrap(err)
}
- if req.DeleteAssociatedResources {
+ if req.GetDeleteAssociatedResources() {
if err := s.deleteAssociatedResources(ctx, authCtx, ig); err != nil {
return nil, trace.Wrap(err)
}
diff --git a/lib/auth/integration/integrationv1/service_test.go b/lib/auth/integration/integrationv1/service_test.go
index 25ac381f42e..f9c72f13c90 100644
--- a/lib/auth/integration/integrationv1/service_test.go
+++ b/lib/auth/integration/integrationv1/service_test.go
@@ -104,9 +104,9 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.GetIntegration(ctx, &integrationpb.GetIntegrationRequest{
+ _, err := resourceSvc.GetIntegration(ctx, integrationpb.GetIntegrationRequest_builder{
Name: igName,
- })
+ }.Build())
return err
},
ErrAssertion: noError,
@@ -115,9 +115,9 @@ func TestIntegrationCRUD(t *testing.T) {
Name: "no access to read integrations",
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.GetIntegration(ctx, &integrationpb.GetIntegrationRequest{
+ _, err := resourceSvc.GetIntegration(ctx, integrationpb.GetIntegrationRequest_builder{
Name: igName,
- })
+ }.Build())
return err
},
ErrAssertion: trace.IsAccessDenied,
@@ -131,9 +131,9 @@ func TestIntegrationCRUD(t *testing.T) {
}}},
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.GetIntegration(ctx, &integrationpb.GetIntegrationRequest{
+ _, err := resourceSvc.GetIntegration(ctx, integrationpb.GetIntegrationRequest_builder{
Name: igName,
- })
+ }.Build())
return err
},
ErrAssertion: trace.IsAccessDenied,
@@ -155,10 +155,10 @@ func TestIntegrationCRUD(t *testing.T) {
}
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.ListIntegrations(ctx, &integrationpb.ListIntegrationsRequest{
+ _, err := resourceSvc.ListIntegrations(ctx, integrationpb.ListIntegrationsRequest_builder{
Limit: 0,
NextKey: "",
- })
+ }.Build())
return err
},
ErrAssertion: noError,
@@ -172,10 +172,10 @@ func TestIntegrationCRUD(t *testing.T) {
}}},
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.ListIntegrations(ctx, &integrationpb.ListIntegrationsRequest{
+ _, err := resourceSvc.ListIntegrations(ctx, integrationpb.ListIntegrationsRequest_builder{
Limit: 0,
NextKey: "",
- })
+ }.Build())
return err
},
ErrAssertion: trace.IsAccessDenied,
@@ -187,7 +187,7 @@ func TestIntegrationCRUD(t *testing.T) {
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
ig := sampleIntegrationFn(t, igName)
- _, err := resourceSvc.CreateIntegration(ctx, &integrationpb.CreateIntegrationRequest{Integration: ig.(*types.IntegrationV1)})
+ _, err := resourceSvc.CreateIntegration(ctx, integrationpb.CreateIntegrationRequest_builder{Integration: ig.(*types.IntegrationV1)}.Build())
return err
},
ErrAssertion: trace.IsAccessDenied,
@@ -203,7 +203,7 @@ func TestIntegrationCRUD(t *testing.T) {
IntegrationName: "integration-allow-create-access",
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
ig := sampleIntegrationFn(t, igName)
- _, err := resourceSvc.CreateIntegration(ctx, &integrationpb.CreateIntegrationRequest{Integration: ig.(*types.IntegrationV1)})
+ _, err := resourceSvc.CreateIntegration(ctx, integrationpb.CreateIntegrationRequest_builder{Integration: ig.(*types.IntegrationV1)}.Build())
return err
},
ErrAssertion: noError,
@@ -219,7 +219,7 @@ func TestIntegrationCRUD(t *testing.T) {
IntegrationName: "integration-awsoidc-invalid.name",
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
ig := sampleIntegrationFn(t, igName)
- _, err := resourceSvc.CreateIntegration(ctx, &integrationpb.CreateIntegrationRequest{Integration: ig.(*types.IntegrationV1)})
+ _, err := resourceSvc.CreateIntegration(ctx, integrationpb.CreateIntegrationRequest_builder{Integration: ig.(*types.IntegrationV1)}.Build())
return err
},
ErrAssertion: trace.IsBadParameter,
@@ -238,7 +238,7 @@ func TestIntegrationCRUD(t *testing.T) {
return trace.Wrap(err)
}
- _, err = resourceSvc.CreateIntegration(ctx, &integrationpb.CreateIntegrationRequest{Integration: ig})
+ _, err = resourceSvc.CreateIntegration(ctx, integrationpb.CreateIntegrationRequest_builder{Integration: ig}.Build())
return trace.Wrap(err)
},
Validate: func(t *testing.T, igName string) {
@@ -253,7 +253,7 @@ func TestIntegrationCRUD(t *testing.T) {
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
ig := sampleIntegrationFn(t, igName)
- _, err := resourceSvc.UpdateIntegration(ctx, &integrationpb.UpdateIntegrationRequest{Integration: ig.(*types.IntegrationV1)})
+ _, err := resourceSvc.UpdateIntegration(ctx, integrationpb.UpdateIntegrationRequest_builder{Integration: ig.(*types.IntegrationV1)}.Build())
return err
},
ErrAssertion: trace.IsAccessDenied,
@@ -272,7 +272,7 @@ func TestIntegrationCRUD(t *testing.T) {
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
ig := sampleIntegrationFn(t, igName)
- _, err := resourceSvc.UpdateIntegration(ctx, &integrationpb.UpdateIntegrationRequest{Integration: ig.(*types.IntegrationV1)})
+ _, err := resourceSvc.UpdateIntegration(ctx, integrationpb.UpdateIntegrationRequest_builder{Integration: ig.(*types.IntegrationV1)}.Build())
return err
},
ErrAssertion: noError,
@@ -290,7 +290,7 @@ func TestIntegrationCRUD(t *testing.T) {
if err != nil {
return trace.Wrap(err)
}
- _, err = resourceSvc.CreateIntegration(ctx, &integrationpb.CreateIntegrationRequest{Integration: oldIg})
+ _, err = resourceSvc.CreateIntegration(ctx, integrationpb.CreateIntegrationRequest_builder{Integration: oldIg}.Build())
if err != nil {
return trace.Wrap(err)
}
@@ -299,7 +299,7 @@ func TestIntegrationCRUD(t *testing.T) {
if err != nil {
return trace.Wrap(err)
}
- _, err = resourceSvc.UpdateIntegration(ctx, &integrationpb.UpdateIntegrationRequest{Integration: newIg})
+ _, err = resourceSvc.UpdateIntegration(ctx, integrationpb.UpdateIntegrationRequest_builder{Integration: newIg}.Build())
return err
},
Validate: func(t *testing.T, igName string) {
@@ -320,7 +320,7 @@ func TestIntegrationCRUD(t *testing.T) {
if err != nil {
return trace.Wrap(err)
}
- _, err = resourceSvc.CreateIntegration(ctx, &integrationpb.CreateIntegrationRequest{Integration: oldIg})
+ _, err = resourceSvc.CreateIntegration(ctx, integrationpb.CreateIntegrationRequest_builder{Integration: oldIg}.Build())
if err != nil {
return trace.Wrap(err)
}
@@ -329,7 +329,7 @@ func TestIntegrationCRUD(t *testing.T) {
if err != nil {
return trace.Wrap(err)
}
- _, err = resourceSvc.UpdateIntegration(ctx, &integrationpb.UpdateIntegrationRequest{Integration: newIg})
+ _, err = resourceSvc.UpdateIntegration(ctx, integrationpb.UpdateIntegrationRequest_builder{Integration: newIg}.Build())
return err
},
Validate: func(t *testing.T, igName string) {
@@ -350,7 +350,7 @@ func TestIntegrationCRUD(t *testing.T) {
if err != nil {
return trace.Wrap(err)
}
- _, err = resourceSvc.CreateIntegration(ctx, &integrationpb.CreateIntegrationRequest{Integration: oldIg})
+ _, err = resourceSvc.CreateIntegration(ctx, integrationpb.CreateIntegrationRequest_builder{Integration: oldIg}.Build())
if err != nil {
return trace.Wrap(err)
}
@@ -359,7 +359,7 @@ func TestIntegrationCRUD(t *testing.T) {
if err != nil {
return trace.Wrap(err)
}
- _, err = resourceSvc.UpdateIntegration(ctx, &integrationpb.UpdateIntegrationRequest{Integration: newIg})
+ _, err = resourceSvc.UpdateIntegration(ctx, integrationpb.UpdateIntegrationRequest_builder{Integration: newIg}.Build())
return err
},
Validate: func(t *testing.T, igName string) {
@@ -380,7 +380,7 @@ func TestIntegrationCRUD(t *testing.T) {
if err != nil {
return trace.Wrap(err)
}
- _, err = resourceSvc.CreateIntegration(ctx, &integrationpb.CreateIntegrationRequest{Integration: oldIg})
+ _, err = resourceSvc.CreateIntegration(ctx, integrationpb.CreateIntegrationRequest_builder{Integration: oldIg}.Build())
if err != nil {
return trace.Wrap(err)
}
@@ -389,7 +389,7 @@ func TestIntegrationCRUD(t *testing.T) {
if err != nil {
return trace.Wrap(err)
}
- _, err = resourceSvc.UpdateIntegration(ctx, &integrationpb.UpdateIntegrationRequest{Integration: newIg})
+ _, err = resourceSvc.UpdateIntegration(ctx, integrationpb.UpdateIntegrationRequest_builder{Integration: newIg}.Build())
return err
},
ErrAssertion: trace.IsBadParameter,
@@ -400,7 +400,7 @@ func TestIntegrationCRUD(t *testing.T) {
Name: "no access to delete integration",
Role: types.RoleSpecV6{},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{Name: "x"})
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{Name: "x"}.Build())
return err
},
ErrAssertion: trace.IsAccessDenied,
@@ -420,7 +420,7 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{Name: igName})
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{Name: igName}.Build())
return err
},
@@ -447,7 +447,7 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{Name: igName})
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{Name: igName}.Build())
return err
},
Cleanup: func(t *testing.T, igName string) {
@@ -474,10 +474,10 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, localClient.CreatePlugin(ctx, NewIdentityCenterPlugin(igName, igName)))
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{Name: "another-plugin"})
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{Name: "another-plugin"}.Build())
require.NoError(t, err)
require.NoError(t, localClient.DeletePlugin(ctx, types.PluginTypeMattermost))
- _, err = resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{Name: igName})
+ _, err = resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{Name: igName}.Build())
return err
},
Cleanup: func(t *testing.T, igName string) {
@@ -498,7 +498,7 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{Name: igName})
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{Name: igName}.Build())
return err
},
ErrAssertion: noError,
@@ -554,7 +554,7 @@ func TestIntegrationCRUD(t *testing.T) {
require.NotNil(t, staticCreds)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{Name: igName})
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{Name: igName}.Build())
return err
},
Validate: func(t *testing.T, igName string) {
@@ -584,9 +584,9 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{
Name: igName,
- })
+ }.Build())
return err
},
ErrAssertion: trace.IsBadParameter,
@@ -610,10 +610,10 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{
Name: igName,
DeleteAssociatedResources: true,
- })
+ }.Build())
return err
},
ErrAssertion: trace.IsAccessDenied,
@@ -650,10 +650,10 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{
Name: igName,
DeleteAssociatedResources: true,
- })
+ }.Build())
return err
},
Validate: func(t *testing.T, igName string) {
@@ -690,10 +690,10 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{
Name: igName,
DeleteAssociatedResources: true,
- })
+ }.Build())
return err
},
Validate: func(t *testing.T, igName string) {
@@ -737,10 +737,10 @@ func TestIntegrationCRUD(t *testing.T) {
require.NoError(t, err)
},
Test: func(ctx context.Context, resourceSvc *Service, igName string) error {
- _, err := resourceSvc.DeleteIntegration(ctx, &integrationpb.DeleteIntegrationRequest{
+ _, err := resourceSvc.DeleteIntegration(ctx, integrationpb.DeleteIntegrationRequest_builder{
Name: igName,
DeleteAssociatedResources: true,
- })
+ }.Build())
return err
},
Validate: func(t *testing.T, igName string) {
diff --git a/lib/auth/issuance/v1/service.go b/lib/auth/issuance/v1/service.go
index 50bef9ff522..b233755fe27 100644
--- a/lib/auth/issuance/v1/service.go
+++ b/lib/auth/issuance/v1/service.go
@@ -122,12 +122,12 @@ func (s *Service) IssueScopedBotCerts(
)
}
// Ensure at least one key is provided
- if len(req.TlsPublicKey) == 0 && len(req.SshPublicKey) == 0 {
+ if len(req.GetTlsPublicKey()) == 0 && len(req.GetSshPublicKey()) == 0 {
return nil, trace.BadParameter("at least one of ssh_public_key or tls_public_key is required")
}
- switch req.GetUsage().(type) {
- case *issuancev1pb.IssueScopedBotCertsRequest_Identity:
+ switch req.WhichUsage() {
+ case issuancev1pb.IssueScopedBotCertsRequest_Identity_case:
// no special handling.
default:
return nil, trace.BadParameter(
@@ -149,7 +149,7 @@ func (s *Service) IssueScopedBotCerts(
)
case currentIdentity.DisallowReissue:
return nil, trace.AccessDenied("reissuance is prohibited")
- case currentIdentity.ScopePin == nil || currentIdentity.ScopePin.Scope == "":
+ case currentIdentity.ScopePin == nil || currentIdentity.ScopePin.GetScope() == "":
return nil, trace.AccessDenied(
"scope pin missing, rpc can only be invoked by scoped identities",
)
@@ -178,7 +178,7 @@ func (s *Service) IssueScopedBotCerts(
// resource itself. In the future, we will allow "sub-pinning" where the
// resulting certs may be a descendant scope of the current scope and
// bot scope.
- requestedScope := currentIdentity.ScopePin.Scope
+ requestedScope := currentIdentity.ScopePin.GetScope()
// Sanity check that the requested scope is still descendant or equiv to
// botScope - in case bot scope has changed.
if !scopes.ScopeOfOrigin(botScope).IsAssignableToScopeOfEffect(requestedScope) {
@@ -199,8 +199,8 @@ func (s *Service) IssueScopedBotCerts(
User: user,
CheckerContext: checker,
TTL: ttl,
- SSHPublicKey: req.SshPublicKey,
- TLSPublicKey: req.TlsPublicKey,
+ SSHPublicKey: req.GetSshPublicKey(),
+ TLSPublicKey: req.GetTlsPublicKey(),
// Explicitly set BotInternal to false as these certs are intended for
// outputs/services and not use by the bot internally. This prevents
@@ -233,10 +233,10 @@ func (s *Service) IssueScopedBotCerts(
// We do not return any CAs. The Bot already has an internal identity and
// the ability to fetch/watch CAs. Returning CAs here would create confusion
// around where to correctly source CAs.
- return &issuancev1pb.IssueScopedBotCertsResponse{
- Certs: &issuancev1pb.Certs{
+ return issuancev1pb.IssueScopedBotCertsResponse_builder{
+ Certs: issuancev1pb.Certs_builder{
Tls: certs.TLS,
Ssh: certs.SSH,
- },
- }, nil
+ }.Build(),
+ }.Build(), nil
}
diff --git a/lib/auth/issuance/v1/service_test.go b/lib/auth/issuance/v1/service_test.go
index d3c06e5a4f8..6c3ab28eb3d 100644
--- a/lib/auth/issuance/v1/service_test.go
+++ b/lib/auth/issuance/v1/service_test.go
@@ -94,60 +94,60 @@ func TestIssueScopedBotCerts(t *testing.T) {
// Create a scoped role.
scopedSvc := adminClient.ScopedAccessServiceClient()
- _, err = scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ _, err = scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "bot-role",
- },
+ }.Build(),
Scope: botScope,
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{botScope},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Create a scoped bot.
- bot, err := adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ bot, err := adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-bot",
- },
+ }.Build(),
Scope: botScope,
Spec: &machineidv1pb.BotSpec{},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Create a scoped role assignment for the bot.
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
Scope: botScope,
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
- BotName: bot.Metadata.Name,
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
+ BotName: bot.GetMetadata().GetName(),
BotScope: botScope,
Assignments: []*scopedaccessv1.Assignment{
- {Role: "bot-role", Scope: botScope},
+ scopedaccessv1.Assignment_builder{Role: "bot-role", Scope: botScope}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp)
// Create a client with a scoped bot internal identity.
botClient, err := srv.NewClient(
- authtest.TestScopedBot(bot.Metadata.Name, botScope, true),
+ authtest.TestScopedBot(bot.GetMetadata().GetName(), botScope, true),
)
require.NoError(t, err)
t.Cleanup(func() { _ = botClient.Close() })
@@ -173,12 +173,12 @@ func TestIssueScopedBotCerts(t *testing.T) {
Usage: &issuancev1pb.IssueScopedBotCertsRequest_Identity{},
})
require.NoError(t, err)
- require.NotNil(t, resp.Certs)
- require.NotEmpty(t, resp.Certs.Ssh)
- require.NotEmpty(t, resp.Certs.Tls)
+ require.NotNil(t, resp.GetCerts())
+ require.NotEmpty(t, resp.GetCerts().GetSsh())
+ require.NotEmpty(t, resp.GetCerts().GetTls())
// Parse the returned TLS cert and verify identity properties.
- tlsCert, err := tlsca.ParseCertificatePEM(resp.Certs.Tls)
+ tlsCert, err := tlsca.ParseCertificatePEM(resp.GetCerts().GetTls())
require.NoError(t, err)
identity, err := tlsca.FromSubject(tlsCert.Subject, tlsCert.NotAfter)
require.NoError(t, err)
@@ -191,7 +191,7 @@ func TestIssueScopedBotCerts(t *testing.T) {
require.WithinDuration(t, now.Add(requestedTTL), tlsCert.NotAfter, time.Minute)
// Verify the SSH cert is valid.
- sshParsedKey, _, _, _, err := ssh.ParseAuthorizedKey(resp.Certs.Ssh)
+ sshParsedKey, _, _, _, err := ssh.ParseAuthorizedKey(resp.GetCerts().GetSsh())
require.NoError(t, err)
sshCert, ok := sshParsedKey.(*ssh.Certificate)
require.True(t, ok, "parsed SSH key should be a certificate")
@@ -213,11 +213,11 @@ func TestIssueScopedBotCerts(t *testing.T) {
})
t.Run("missing usage rejected", func(t *testing.T) {
- _, err := issuanceClient.IssueScopedBotCerts(ctx, &issuancev1pb.IssueScopedBotCertsRequest{
+ _, err := issuanceClient.IssueScopedBotCerts(ctx, issuancev1pb.IssueScopedBotCertsRequest_builder{
SshPublicKey: sshPubKeyBytes,
TlsPublicKey: tlsPubKeyPEM,
Ttl: durationpb.New(time.Hour),
- })
+ }.Build())
require.ErrorContains(t, err, "unsupported or unspecified usage variant")
})
@@ -228,9 +228,9 @@ func TestIssueScopedBotCerts(t *testing.T) {
Usage: &issuancev1pb.IssueScopedBotCertsRequest_Identity{},
})
require.NoError(t, err)
- require.NotNil(t, resp.Certs)
- require.NotEmpty(t, resp.Certs.Ssh)
- require.Empty(t, resp.Certs.Tls)
+ require.NotNil(t, resp.GetCerts())
+ require.NotEmpty(t, resp.GetCerts().GetSsh())
+ require.Empty(t, resp.GetCerts().GetTls())
})
t.Run("tls only", func(t *testing.T) {
@@ -240,9 +240,9 @@ func TestIssueScopedBotCerts(t *testing.T) {
Usage: &issuancev1pb.IssueScopedBotCertsRequest_Identity{},
})
require.NoError(t, err)
- require.NotNil(t, resp.Certs)
- require.Empty(t, resp.Certs.Ssh)
- require.NotEmpty(t, resp.Certs.Tls)
+ require.NotNil(t, resp.GetCerts())
+ require.Empty(t, resp.GetCerts().GetSsh())
+ require.NotEmpty(t, resp.GetCerts().GetTls())
})
t.Run("missing keys rejected", func(t *testing.T) {
@@ -318,19 +318,19 @@ func TestIssueScopedBotCerts_Unauthorized(t *testing.T) {
// Create a scoped role (needed for scoped identity generation).
scopedSvc := adminClient.ScopedAccessServiceClient()
- _, err = scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ _, err = scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-role",
- },
+ }.Build(),
Scope: testScope,
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{testScope},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Generate a key pair shared across subtests.
@@ -342,37 +342,37 @@ func TestIssueScopedBotCerts_Unauthorized(t *testing.T) {
require.NoError(t, err)
sshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey)
- scopedBot, err := adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ scopedBot, err := adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot",
- },
+ }.Build(),
Scope: testScope,
Spec: &machineidv1pb.BotSpec{},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
SubKind: scopedaccess.SubKindDynamic,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
Scope: testScope,
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
- BotName: scopedBot.Metadata.Name,
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
+ BotName: scopedBot.GetMetadata().GetName(),
BotScope: testScope,
Assignments: []*scopedaccessv1.Assignment{
- {Role: "test-role", Scope: testScope},
+ scopedaccessv1.Assignment_builder{Role: "test-role", Scope: testScope}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp)
@@ -397,23 +397,23 @@ func TestIssueScopedBotCerts_Unauthorized(t *testing.T) {
user, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user")
require.NoError(t, err)
- userSRAResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ userSRAResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
SubKind: scopedaccess.SubKindDynamic,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
Scope: testScope,
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: user.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: "test-role", Scope: testScope},
+ scopedaccessv1.Assignment_builder{Role: "test-role", Scope: testScope}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, userSRAResp)
@@ -433,20 +433,20 @@ func TestIssueScopedBotCerts_Unauthorized(t *testing.T) {
t.Run("unscoped bot", func(t *testing.T) {
// Create an unscoped bot.
- unscopedBot, err := adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ unscopedBot, err := adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "unscoped-bot",
- },
+ }.Build(),
Spec: &machineidv1pb.BotSpec{},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
botClient, err := srv.NewClient(
- authtest.TestBot(unscopedBot.Metadata.Name, true),
+ authtest.TestBot(unscopedBot.GetMetadata().GetName(), true),
)
require.NoError(t, err)
t.Cleanup(func() { _ = botClient.Close() })
@@ -461,7 +461,7 @@ func TestIssueScopedBotCerts_Unauthorized(t *testing.T) {
t.Run("scoped bot without BotInternal", func(t *testing.T) {
botClient, err := srv.NewClient(
- authtest.TestScopedBot(scopedBot.Metadata.Name, testScope, false),
+ authtest.TestScopedBot(scopedBot.GetMetadata().GetName(), testScope, false),
)
require.NoError(t, err)
t.Cleanup(func() { _ = botClient.Close() })
@@ -475,7 +475,7 @@ func TestIssueScopedBotCerts_Unauthorized(t *testing.T) {
})
t.Run("scoped bot with DisallowReissue", func(t *testing.T) {
- ident := authtest.TestScopedBot(scopedBot.Metadata.Name, testScope, true)
+ ident := authtest.TestScopedBot(scopedBot.GetMetadata().GetName(), testScope, true)
lu := ident.I.(authz.LocalUser)
lu.Identity.DisallowReissue = true
ident.I = lu
@@ -498,10 +498,10 @@ func waitForSRACache(t *testing.T, srv *authtest.TLSServer, resps ...*scopedacce
ctx := t.Context()
require.EventuallyWithT(t, func(t *assert.CollectT) {
for _, resp := range resps {
- _, err := srv.Auth().ScopedAccessCache.GetScopedRoleAssignment(ctx, &scopedaccessv1.GetScopedRoleAssignmentRequest{
+ _, err := srv.Auth().ScopedAccessCache.GetScopedRoleAssignment(ctx, scopedaccessv1.GetScopedRoleAssignmentRequest_builder{
Name: resp.GetAssignment().GetMetadata().GetName(),
SubKind: resp.GetAssignment().GetSubKind(),
- })
+ }.Build())
require.NoError(t, err)
}
}, 10*time.Second, 100*time.Millisecond)
diff --git a/lib/auth/join.go b/lib/auth/join.go
index 893e98f4984..d10320882cf 100644
--- a/lib/auth/join.go
+++ b/lib/auth/join.go
@@ -229,7 +229,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
claims, err := a.checkGitHubJoinRequest(ctx, req, provisionToken)
if claims != nil {
rawClaims = claims
- attrs.Github = claims.JoinAttrs()
+ attrs.SetGithub(claims.JoinAttrs())
}
if err != nil {
return nil, trace.Wrap(err)
@@ -238,7 +238,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
claims, err := a.checkGitLabJoinRequest(ctx, req, provisionToken)
if claims != nil {
rawClaims = claims
- attrs.Gitlab = claims.JoinAttrs()
+ attrs.SetGitlab(claims.JoinAttrs())
}
if err != nil {
return nil, trace.Wrap(err)
@@ -247,7 +247,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
claims, err := a.checkCircleCIJoinRequest(ctx, req, provisionToken)
if claims != nil {
rawClaims = claims
- attrs.Circleci = claims.JoinAttrs()
+ attrs.SetCircleci(claims.JoinAttrs())
}
if err != nil {
return nil, trace.Wrap(err)
@@ -256,7 +256,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
claims, err := a.checkKubernetesJoinRequest(ctx, req, provisionToken)
if claims != nil {
rawClaims = claims
- attrs.Kubernetes = claims.JoinAttrs()
+ attrs.SetKubernetes(claims.JoinAttrs())
}
if err != nil {
return nil, trace.Wrap(err)
@@ -265,7 +265,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
claims, err := a.checkGCPJoinRequest(ctx, req, provisionToken)
if claims != nil {
rawClaims = claims
- attrs.Gcp = claims.JoinAttrs()
+ attrs.SetGcp(claims.JoinAttrs())
}
if err != nil {
return nil, trace.Wrap(err)
@@ -274,7 +274,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
claims, err := a.checkSpaceliftJoinRequest(ctx, req, provisionToken)
if claims != nil {
rawClaims = claims
- attrs.Spacelift = claims.JoinAttrs()
+ attrs.SetSpacelift(claims.JoinAttrs())
}
if err != nil {
return nil, trace.Wrap(err)
@@ -283,7 +283,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
claims, err := a.checkTerraformCloudJoinRequest(ctx, req, provisionToken)
if claims != nil {
rawClaims = claims
- attrs.TerraformCloud = claims.JoinAttrs()
+ attrs.SetTerraformCloud(claims.JoinAttrs())
}
if err != nil {
return nil, trace.Wrap(err)
@@ -292,7 +292,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
claims, err := a.checkBitbucketJoinRequest(ctx, req, provisionToken)
if claims != nil {
rawClaims = claims
- attrs.Bitbucket = claims.JoinAttrs()
+ attrs.SetBitbucket(claims.JoinAttrs())
}
if err != nil {
return nil, trace.Wrap(err)
@@ -301,7 +301,7 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
claims, err := a.checkAzureDevopsJoinRequest(ctx, req, provisionToken)
if claims != nil {
rawClaims = claims.ForAudit()
- attrs.AzureDevops = claims.JoinAttrs()
+ attrs.SetAzureDevops(claims.JoinAttrs())
}
if err != nil {
return nil, trace.Wrap(err)
@@ -420,14 +420,14 @@ func (a *Server) GenerateBotCertsForJoin(
if params.Attrs == nil {
params.Attrs = &workloadidentityv1pb.JoinAttrs{}
}
- params.Attrs.Meta = &workloadidentityv1pb.JoinAttrsMeta{
+ params.Attrs.SetMeta(workloadidentityv1pb.JoinAttrsMeta_builder{
JoinMethod: string(joinMethod),
- }
+ }.Build())
if joinMethod != types.JoinMethodToken {
- params.Attrs.Meta.JoinTokenName = token.GetName()
+ params.Attrs.GetMeta().SetJoinTokenName(token.GetName())
}
- auth := &machineidv1pb.BotInstanceStatusAuthentication{
+ auth := machineidv1pb.BotInstanceStatusAuthentication_builder{
AuthenticatedAt: timestamppb.New(a.GetClock().Now()),
// TODO: GetSafeName may not return an appropriate value for later
// comparison / locking purposes, and this also shouldn't contain
@@ -436,7 +436,7 @@ func (a *Server) GenerateBotCertsForJoin(
JoinMethod: string(token.GetJoinMethod()),
PublicKey: params.PublicTLSKey,
JoinAttrs: params.Attrs,
- }
+ }.Build()
// TODO(noah): In v19, we can drop writing to the deprecated Metadata field.
auth.Metadata, err = rawJoinAttrsToGoogleStruct(params.RawJoinClaims)
diff --git a/lib/auth/join/join_test.go b/lib/auth/join/join_test.go
index 709c8dbdcb2..12124c3f190 100644
--- a/lib/auth/join/join_test.go
+++ b/lib/auth/join/join_test.go
@@ -163,25 +163,25 @@ func TestRegister_Bot(t *testing.T) {
srv := newTestTLSServer(t)
- bot, err := machineidv1.UpsertBot(ctx, srv.Auth(), &machineidv1pb.Bot{
+ bot, err := machineidv1.UpsertBot(ctx, srv.Auth(), machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{},
- },
- }, srv.Clock().Now(), "", scopes.Features{})
+ }.Build(),
+ }.Build(), srv.Clock().Now(), "", scopes.Features{})
require.NoError(t, err)
later := srv.Clock().Now().Add(4 * time.Hour)
- goodToken := newBotToken(t, "good-token", bot.Metadata.Name, types.RoleBot, later)
- expiredToken := newBotToken(t, "expired", bot.Metadata.Name, types.RoleBot, srv.Clock().Now().Add(-1*time.Hour))
+ goodToken := newBotToken(t, "good-token", bot.GetMetadata().GetName(), types.RoleBot, later)
+ expiredToken := newBotToken(t, "expired", bot.GetMetadata().GetName(), types.RoleBot, srv.Clock().Now().Add(-1*time.Hour))
wrongKind := newBotToken(t, "wrong-kind", "", types.RoleNode, later)
wrongUser := newBotToken(t, "wrong-user", "llama", types.RoleBot, later)
- invalidToken := newBotToken(t, "this-token-does-not-exist", bot.Metadata.Name, types.RoleBot, later)
+ invalidToken := newBotToken(t, "this-token-does-not-exist", bot.GetMetadata().GetName(), types.RoleBot, later)
err = srv.Auth().UpsertToken(ctx, goodToken)
require.NoError(t, err)
@@ -307,17 +307,17 @@ func TestRegister_Bot_Expiry(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
botName := uuid.NewString()
- _, err := machineidv1.UpsertBot(ctx, srv.Auth(), &machineidv1pb.Bot{
+ _, err := machineidv1.UpsertBot(ctx, srv.Auth(), machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: botName,
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{},
Traits: []*machineidv1pb.Trait{},
- },
- }, srv.Clock().Now(), "", scopes.Features{})
+ }.Build(),
+ }.Build(), srv.Clock().Now(), "", scopes.Features{})
require.NoError(t, err)
tok := newBotToken(t, uuid.NewString(), botName, types.RoleBot, srv.Clock().Now().Add(time.Hour))
require.NoError(t, srv.Auth().UpsertToken(ctx, tok))
diff --git a/lib/auth/join_azure_legacy.go b/lib/auth/join_azure_legacy.go
index 9032f084e6a..90dccd46b7e 100644
--- a/lib/auth/join_azure_legacy.go
+++ b/lib/auth/join_azure_legacy.go
@@ -97,9 +97,9 @@ func (a *Server) RegisterUsingAzureMethod(
}
if req.RegisterUsingTokenRequest.Role == types.RoleBot {
- params := makeBotCertsParams(req.RegisterUsingTokenRequest, nil /*rawClaims*/, &workloadidentityv1pb.JoinAttrs{
+ params := makeBotCertsParams(req.RegisterUsingTokenRequest, nil /*rawClaims*/, workloadidentityv1pb.JoinAttrs_builder{
Azure: joinAttrs,
- })
+ }.Build())
certs, _, err := a.GenerateBotCertsForJoin(ctx, provisionToken, params)
return certs, trace.Wrap(err)
}
diff --git a/lib/auth/join_bound_keypair_test.go b/lib/auth/join_bound_keypair_test.go
index 4d0358a568c..9309e85e8eb 100644
--- a/lib/auth/join_bound_keypair_test.go
+++ b/lib/auth/join_bound_keypair_test.go
@@ -129,18 +129,18 @@ func TestServer_RegisterUsingBoundKeypairMethod(t *testing.T) {
adminClient, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- _, err = adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ _, err = adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
sshPrivateKey, sshPublicKey, err := testauthority.GenerateKeyPair()
@@ -979,18 +979,18 @@ func TestServer_RegisterUsingBoundKeypairMethod_GenerationCounter(t *testing.T)
adminClient, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- _, err = adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ _, err = adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
token, err := types.NewProvisionTokenFromSpecAndStatus(
@@ -1188,18 +1188,18 @@ func TestServer_RegisterUsingBoundKeypairMethod_JoinStateFailure(t *testing.T) {
adminClient, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- _, err = adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ _, err = adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
token, err := types.NewProvisionTokenFromSpecAndStatus(
@@ -1346,18 +1346,18 @@ func TestServer_RegisterUsingBoundKeypairMethod_JoinStateFailureDuringRenewal(t
adminClient, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- _, err = adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ _, err = adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"example"},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
token, err := types.NewProvisionTokenFromSpecAndStatus(
diff --git a/lib/auth/join_iam.go b/lib/auth/join_iam.go
index 6249e6903c0..987ffbf188b 100644
--- a/lib/auth/join_iam.go
+++ b/lib/auth/join_iam.go
@@ -117,9 +117,9 @@ func (a *Server) RegisterUsingIAMMethod(
}
if req.RegisterUsingTokenRequest.Role == types.RoleBot {
- params := makeBotCertsParams(req.RegisterUsingTokenRequest, verifiedIdentity, &workloadidentityv1pb.JoinAttrs{
+ params := makeBotCertsParams(req.RegisterUsingTokenRequest, verifiedIdentity, workloadidentityv1pb.JoinAttrs_builder{
Iam: verifiedIdentity.JoinAttrs(),
- })
+ }.Build())
certs, _, err := a.GenerateBotCertsForJoin(ctx, provisionToken, params)
return certs, trace.Wrap(err, "generating bot certs")
}
diff --git a/lib/auth/join_oracle.go b/lib/auth/join_oracle.go
index a37bd912e3e..ac43a22e8bd 100644
--- a/lib/auth/join_oracle.go
+++ b/lib/auth/join_oracle.go
@@ -92,9 +92,9 @@ func (a *Server) registerUsingOracleMethod(
}
if tokenReq.Role == types.RoleBot {
- params := makeBotCertsParams(tokenReq, claims, &workloadidentityv1pb.JoinAttrs{
+ params := makeBotCertsParams(tokenReq, claims, workloadidentityv1pb.JoinAttrs_builder{
Oracle: claims.JoinAttrs(),
- })
+ }.Build())
certs, _, err := a.GenerateBotCertsForJoin(ctx, provisionToken, params)
return certs, trace.Wrap(err, "generating bot certs")
}
diff --git a/lib/auth/join_test.go b/lib/auth/join_test.go
index 2bfab455638..125ff5bd686 100644
--- a/lib/auth/join_test.go
+++ b/lib/auth/join_test.go
@@ -308,25 +308,25 @@ func TestJoin_Bot(t *testing.T) {
srv := newTestTLSServer(t)
- bot, err := machineidv1.UpsertBot(ctx, srv.Auth(), &machineidv1pb.Bot{
+ bot, err := machineidv1.UpsertBot(ctx, srv.Auth(), machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{},
- },
- }, srv.Clock().Now(), "", scopes.Features{})
+ }.Build(),
+ }.Build(), srv.Clock().Now(), "", scopes.Features{})
require.NoError(t, err)
later := srv.Clock().Now().Add(4 * time.Hour)
- goodToken := newBotToken(t, "good-token", bot.Metadata.Name, types.RoleBot, later)
- expiredToken := newBotToken(t, "expired", bot.Metadata.Name, types.RoleBot, srv.Clock().Now().Add(-1*time.Hour))
+ goodToken := newBotToken(t, "good-token", bot.GetMetadata().GetName(), types.RoleBot, later)
+ expiredToken := newBotToken(t, "expired", bot.GetMetadata().GetName(), types.RoleBot, srv.Clock().Now().Add(-1*time.Hour))
wrongKind := newBotToken(t, "wrong-kind", "", types.RoleNode, later)
wrongUser := newBotToken(t, "wrong-user", "llama", types.RoleBot, later)
- invalidToken := newBotToken(t, "this-token-does-not-exist", bot.Metadata.Name, types.RoleBot, later)
+ invalidToken := newBotToken(t, "this-token-does-not-exist", bot.GetMetadata().GetName(), types.RoleBot, later)
err = srv.Auth().UpsertToken(ctx, goodToken)
require.NoError(t, err)
@@ -451,17 +451,17 @@ func TestJoin_Bot_Expiry(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
botName := uuid.NewString()
- _, err := machineidv1.UpsertBot(ctx, srv.Auth(), &machineidv1pb.Bot{
+ _, err := machineidv1.UpsertBot(ctx, srv.Auth(), machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: botName,
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{},
Traits: []*machineidv1pb.Trait{},
- },
- }, srv.Clock().Now(), "", scopes.Features{})
+ }.Build(),
+ }.Build(), srv.Clock().Now(), "", scopes.Features{})
require.NoError(t, err)
tok := newBotToken(t, uuid.NewString(), botName, types.RoleBot, srv.Clock().Now().Add(time.Hour))
require.NoError(t, srv.Auth().UpsertToken(ctx, tok))
diff --git a/lib/auth/join_tpm.go b/lib/auth/join_tpm.go
index 365d0fb4a15..49076435511 100644
--- a/lib/auth/join_tpm.go
+++ b/lib/auth/join_tpm.go
@@ -93,9 +93,9 @@ func (a *Server) RegisterUsingTPMMethod(
}
if initReq.JoinRequest.Role == types.RoleBot {
- params := makeBotCertsParams(initReq.JoinRequest, validatedEK, &workloadidentityv1pb.JoinAttrs{
+ params := makeBotCertsParams(initReq.JoinRequest, validatedEK, workloadidentityv1pb.JoinAttrs_builder{
Tpm: validatedEK.JoinAttrs(),
- })
+ }.Build())
certs, _, err := a.GenerateBotCertsForJoin(ctx, ptv2, params)
return certs, trace.Wrap(err, "generating certs for bot")
}
diff --git a/lib/auth/kubewaitingcontainer/kubewaitingcontainerv1/service.go b/lib/auth/kubewaitingcontainer/kubewaitingcontainerv1/service.go
index 4c20e89ef53..4a81e71d535 100644
--- a/lib/auth/kubewaitingcontainer/kubewaitingcontainerv1/service.go
+++ b/lib/auth/kubewaitingcontainer/kubewaitingcontainerv1/service.go
@@ -92,34 +92,34 @@ func (s *Service) ListKubernetesWaitingContainers(ctx context.Context, req *kube
return nil, trace.AccessDenied("unauthorized to list Kubernetes waiting container resources")
}
- conts, nextToken, err := s.cache.ListKubernetesWaitingContainers(ctx, int(req.PageSize), req.PageToken)
+ conts, nextToken, err := s.cache.ListKubernetesWaitingContainers(ctx, int(req.GetPageSize()), req.GetPageToken())
if err != nil {
return nil, trace.Wrap(err)
}
- return &kubewaitingcontainerpb.ListKubernetesWaitingContainersResponse{
+ return kubewaitingcontainerpb.ListKubernetesWaitingContainersResponse_builder{
WaitingContainers: conts,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// GetKubernetesWaitingContainer returns a Kubernetes ephemeral
// container that are waiting to be created until moderated
// session conditions are met.
func (s *Service) GetKubernetesWaitingContainer(ctx context.Context, req *kubewaitingcontainerpb.GetKubernetesWaitingContainerRequest) (*kubewaitingcontainerpb.KubernetesWaitingContainer, error) {
- if req.Username == "" {
+ if req.GetUsername() == "" {
return nil, trace.BadParameter("missing username")
}
- if req.Cluster == "" {
+ if req.GetCluster() == "" {
return nil, trace.BadParameter("missing cluster")
}
- if req.Namespace == "" {
+ if req.GetNamespace() == "" {
return nil, trace.BadParameter("missing namespace")
}
- if req.PodName == "" {
+ if req.GetPodName() == "" {
return nil, trace.BadParameter("missing pod name")
}
- if req.ContainerName == "" {
+ if req.GetContainerName() == "" {
return nil, trace.BadParameter("missing container name")
}
@@ -134,13 +134,13 @@ func (s *Service) GetKubernetesWaitingContainer(ctx context.Context, req *kubewa
return nil, trace.AccessDenied("unauthorized to read Kubernetes waiting container resources")
}
- out, err := s.cache.GetKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.GetKubernetesWaitingContainerRequest{
- Username: req.Username,
- Cluster: req.Cluster,
- Namespace: req.Namespace,
- PodName: req.PodName,
- ContainerName: req.ContainerName,
- })
+ out, err := s.cache.GetKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.GetKubernetesWaitingContainerRequest_builder{
+ Username: req.GetUsername(),
+ Cluster: req.GetCluster(),
+ Namespace: req.GetNamespace(),
+ PodName: req.GetPodName(),
+ ContainerName: req.GetContainerName(),
+ }.Build())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -163,7 +163,7 @@ func (s *Service) CreateKubernetesWaitingContainer(ctx context.Context, req *kub
return nil, trace.AccessDenied("unauthorized to create Kubernetes waiting container resources")
}
- out, err := s.backend.CreateKubernetesWaitingContainer(ctx, req.WaitingContainer)
+ out, err := s.backend.CreateKubernetesWaitingContainer(ctx, req.GetWaitingContainer())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -175,19 +175,19 @@ func (s *Service) CreateKubernetesWaitingContainer(ctx context.Context, req *kub
// container that are waiting to be created until moderated
// session conditions are met.
func (s *Service) DeleteKubernetesWaitingContainer(ctx context.Context, req *kubewaitingcontainerpb.DeleteKubernetesWaitingContainerRequest) (*emptypb.Empty, error) {
- if req.Username == "" {
+ if req.GetUsername() == "" {
return nil, trace.BadParameter("missing username")
}
- if req.Cluster == "" {
+ if req.GetCluster() == "" {
return nil, trace.BadParameter("missing cluster")
}
- if req.Namespace == "" {
+ if req.GetNamespace() == "" {
return nil, trace.BadParameter("missing namespace")
}
- if req.PodName == "" {
+ if req.GetPodName() == "" {
return nil, trace.BadParameter("missing pod name")
}
- if req.ContainerName == "" {
+ if req.GetContainerName() == "" {
return nil, trace.BadParameter("missing container name")
}
@@ -202,13 +202,13 @@ func (s *Service) DeleteKubernetesWaitingContainer(ctx context.Context, req *kub
return nil, trace.AccessDenied("unauthorized to delete Kubernetes waiting container resources")
}
- return &emptypb.Empty{}, trace.Wrap(s.backend.DeleteKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.DeleteKubernetesWaitingContainerRequest{
- Username: req.Username,
- Cluster: req.Cluster,
- Namespace: req.Namespace,
- PodName: req.PodName,
- ContainerName: req.ContainerName,
- }))
+ return &emptypb.Empty{}, trace.Wrap(s.backend.DeleteKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.DeleteKubernetesWaitingContainerRequest_builder{
+ Username: req.GetUsername(),
+ Cluster: req.GetCluster(),
+ Namespace: req.GetNamespace(),
+ PodName: req.GetPodName(),
+ ContainerName: req.GetContainerName(),
+ }.Build()))
}
// isKubeSvcOrProxy returns true if the given context has the builtin role
diff --git a/lib/auth/kubewaitingcontainer/kubewaitingcontainerv1/service_test.go b/lib/auth/kubewaitingcontainer/kubewaitingcontainerv1/service_test.go
index abdf600ee1a..bcc0109bfb9 100644
--- a/lib/auth/kubewaitingcontainer/kubewaitingcontainerv1/service_test.go
+++ b/lib/auth/kubewaitingcontainer/kubewaitingcontainerv1/service_test.go
@@ -47,7 +47,7 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
sampleKubeWaitingContFn := func(t *testing.T, name string) *kubewaitingcontainerpb.KubernetesWaitingContainer {
wc, err := kubewaitingcontainer.NewKubeWaitingContainer(
name,
- &kubewaitingcontainerpb.KubernetesWaitingContainerSpec{
+ kubewaitingcontainerpb.KubernetesWaitingContainerSpec_builder{
Username: username,
Cluster: cluster,
Namespace: namespace,
@@ -55,7 +55,7 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
ContainerName: name,
Patch: []byte("patch"),
PatchType: patchType,
- },
+ }.Build(),
)
require.NoError(t, err)
return wc
@@ -84,9 +84,9 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
},
Setup: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
for range 10 {
- _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest_builder{
WaitingContainer: sampleKubeWaitingContFn(t, uuid.NewString()),
- })
+ }.Build())
require.NoError(t, err)
}
},
@@ -116,27 +116,27 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
return kubeAuthFn
},
Setup: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest_builder{
WaitingContainer: sampleKubeWaitingContFn(t, wcName),
- })
+ }.Build())
require.NoError(t, err)
},
Test: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- out, err := resourceSvc.GetKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.GetKubernetesWaitingContainerRequest{
+ out, err := resourceSvc.GetKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.GetKubernetesWaitingContainerRequest_builder{
Username: username,
Cluster: cluster,
Namespace: namespace,
PodName: podName,
ContainerName: wcName,
- })
+ }.Build())
require.NoError(t, err)
- require.Equal(t, wcName, out.Metadata.Name)
- require.Equal(t, username, out.Spec.Username)
- require.Equal(t, cluster, out.Spec.Cluster)
- require.Equal(t, namespace, out.Spec.Namespace)
- require.Equal(t, podName, out.Spec.PodName)
- require.Equal(t, wcName, out.Spec.ContainerName)
- require.Equal(t, patchType, out.Spec.PatchType)
+ require.Equal(t, wcName, out.GetMetadata().GetName())
+ require.Equal(t, username, out.GetSpec().GetUsername())
+ require.Equal(t, cluster, out.GetSpec().GetCluster())
+ require.Equal(t, namespace, out.GetSpec().GetNamespace())
+ require.Equal(t, podName, out.GetSpec().GetPodName())
+ require.Equal(t, wcName, out.GetSpec().GetContainerName())
+ require.Equal(t, patchType, out.GetSpec().GetPatchType())
},
},
{
@@ -147,13 +147,13 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
})
},
Test: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.GetKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.GetKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.GetKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.GetKubernetesWaitingContainerRequest_builder{
Username: username,
Cluster: cluster,
Namespace: namespace,
PodName: podName,
ContainerName: wcName,
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
},
@@ -164,13 +164,13 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
return kubeAuthFn
},
Test: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.GetKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.GetKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.GetKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.GetKubernetesWaitingContainerRequest_builder{
Username: username,
Cluster: cluster,
Namespace: namespace,
PodName: podName,
ContainerName: wcName,
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsNotFound(err))
},
@@ -183,17 +183,17 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
return kubeAuthFn
},
Test: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- out, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest{
+ out, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest_builder{
WaitingContainer: sampleKubeWaitingContFn(t, wcName),
- })
+ }.Build())
require.NoError(t, err)
- require.Equal(t, wcName, out.Metadata.Name)
- require.Equal(t, username, out.Spec.Username)
- require.Equal(t, cluster, out.Spec.Cluster)
- require.Equal(t, namespace, out.Spec.Namespace)
- require.Equal(t, podName, out.Spec.PodName)
- require.Equal(t, wcName, out.Spec.ContainerName)
- require.Equal(t, patchType, out.Spec.PatchType)
+ require.Equal(t, wcName, out.GetMetadata().GetName())
+ require.Equal(t, username, out.GetSpec().GetUsername())
+ require.Equal(t, cluster, out.GetSpec().GetCluster())
+ require.Equal(t, namespace, out.GetSpec().GetNamespace())
+ require.Equal(t, podName, out.GetSpec().GetPodName())
+ require.Equal(t, wcName, out.GetSpec().GetContainerName())
+ require.Equal(t, patchType, out.GetSpec().GetPatchType())
},
},
{
@@ -204,9 +204,9 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
})
},
Test: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest_builder{
WaitingContainer: sampleKubeWaitingContFn(t, wcName),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
},
@@ -217,15 +217,15 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
return kubeAuthFn
},
Setup: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest_builder{
WaitingContainer: sampleKubeWaitingContFn(t, wcName),
- })
+ }.Build())
require.NoError(t, err)
},
Test: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest_builder{
WaitingContainer: sampleKubeWaitingContFn(t, wcName),
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAlreadyExists(err))
},
@@ -238,19 +238,19 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
return kubeAuthFn
},
Setup: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.CreateKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.CreateKubernetesWaitingContainerRequest_builder{
WaitingContainer: sampleKubeWaitingContFn(t, wcName),
- })
+ }.Build())
require.NoError(t, err)
},
Test: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.DeleteKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.DeleteKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.DeleteKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.DeleteKubernetesWaitingContainerRequest_builder{
Username: username,
Cluster: cluster,
Namespace: namespace,
PodName: podName,
ContainerName: wcName,
- })
+ }.Build())
require.NoError(t, err)
},
},
@@ -262,13 +262,13 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
})
},
Test: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.DeleteKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.DeleteKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.DeleteKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.DeleteKubernetesWaitingContainerRequest_builder{
Username: username,
Cluster: cluster,
Namespace: namespace,
PodName: podName,
ContainerName: wcName,
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
},
@@ -279,13 +279,13 @@ func TestKubeWaitingContainerServiceCRUD(t *testing.T) {
return kubeAuthFn
},
Test: func(t *testing.T, ctx context.Context, resourceSvc *Service, wcName string) {
- _, err := resourceSvc.DeleteKubernetesWaitingContainer(ctx, &kubewaitingcontainerpb.DeleteKubernetesWaitingContainerRequest{
+ _, err := resourceSvc.DeleteKubernetesWaitingContainer(ctx, kubewaitingcontainerpb.DeleteKubernetesWaitingContainerRequest_builder{
Username: username,
Cluster: cluster,
Namespace: namespace,
PodName: podName,
ContainerName: wcName,
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsNotFound(err))
},
diff --git a/lib/auth/linuxdesktop/linuxdesktopv1/desktop.go b/lib/auth/linuxdesktop/linuxdesktopv1/desktop.go
index cbb990eb9c6..766f9ee82b4 100644
--- a/lib/auth/linuxdesktop/linuxdesktopv1/desktop.go
+++ b/lib/auth/linuxdesktop/linuxdesktopv1/desktop.go
@@ -25,15 +25,15 @@ import (
)
func NewLinuxDesktop(name string, spec *linuxdesktopv1pb.LinuxDesktopSpec) (*linuxdesktopv1pb.LinuxDesktop, error) {
- return &linuxdesktopv1pb.LinuxDesktop{
+ return linuxdesktopv1pb.LinuxDesktop_builder{
Kind: types.KindLinuxDesktop,
SubKind: "",
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
- },
+ }.Build(),
Spec: spec,
- }, nil
+ }.Build(), nil
}
func ValidateLinuxDesktop(desktop *linuxdesktopv1pb.LinuxDesktop) error {
diff --git a/lib/auth/linuxdesktop/linuxdesktopv1/desktop_test.go b/lib/auth/linuxdesktop/linuxdesktopv1/desktop_test.go
index 80913c5ca38..9c8229e454c 100644
--- a/lib/auth/linuxdesktop/linuxdesktopv1/desktop_test.go
+++ b/lib/auth/linuxdesktop/linuxdesktopv1/desktop_test.go
@@ -32,10 +32,10 @@ import (
func TestNewLinuxDesktop(t *testing.T) {
t.Parallel()
- spec := &linuxdesktopv1pb.LinuxDesktopSpec{
+ spec := linuxdesktopv1pb.LinuxDesktopSpec_builder{
Addr: "127.0.0.1:22",
Hostname: "desktop-1",
- }
+ }.Build()
desktop, err := NewLinuxDesktop("desktop-1", spec)
require.NoError(t, err)
require.Equal(t, types.KindLinuxDesktop, desktop.GetKind())
@@ -47,17 +47,17 @@ func TestNewLinuxDesktop(t *testing.T) {
func TestValidateLinuxDesktop(t *testing.T) {
t.Parallel()
- valid := &linuxdesktopv1pb.LinuxDesktop{
+ valid := linuxdesktopv1pb.LinuxDesktop_builder{
Kind: types.KindLinuxDesktop,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "desktop-1",
- },
- Spec: &linuxdesktopv1pb.LinuxDesktopSpec{
+ }.Build(),
+ Spec: linuxdesktopv1pb.LinuxDesktopSpec_builder{
Addr: "127.0.0.1:22",
Hostname: "host",
- },
- }
+ }.Build(),
+ }.Build()
tests := []struct {
name string
@@ -75,44 +75,44 @@ func TestValidateLinuxDesktop(t *testing.T) {
},
{
name: "missing metadata",
- desktop: &linuxdesktopv1pb.LinuxDesktop{
- Spec: valid.Spec,
- },
+ desktop: linuxdesktopv1pb.LinuxDesktop_builder{
+ Spec: valid.GetSpec(),
+ }.Build(),
wantErr: true,
},
{
name: "missing name",
- desktop: &linuxdesktopv1pb.LinuxDesktop{
+ desktop: linuxdesktopv1pb.LinuxDesktop_builder{
Metadata: &headerv1.Metadata{},
- Spec: valid.Spec,
- },
+ Spec: valid.GetSpec(),
+ }.Build(),
wantErr: true,
},
{
name: "missing spec",
- desktop: &linuxdesktopv1pb.LinuxDesktop{
- Metadata: valid.Metadata,
- },
+ desktop: linuxdesktopv1pb.LinuxDesktop_builder{
+ Metadata: valid.GetMetadata(),
+ }.Build(),
wantErr: true,
},
{
name: "missing addr",
- desktop: &linuxdesktopv1pb.LinuxDesktop{
- Metadata: valid.Metadata,
- Spec: &linuxdesktopv1pb.LinuxDesktopSpec{
+ desktop: linuxdesktopv1pb.LinuxDesktop_builder{
+ Metadata: valid.GetMetadata(),
+ Spec: linuxdesktopv1pb.LinuxDesktopSpec_builder{
Hostname: "host",
- },
- },
+ }.Build(),
+ }.Build(),
wantErr: true,
},
{
name: "missing hostname",
- desktop: &linuxdesktopv1pb.LinuxDesktop{
- Metadata: valid.Metadata,
- Spec: &linuxdesktopv1pb.LinuxDesktopSpec{
+ desktop: linuxdesktopv1pb.LinuxDesktop_builder{
+ Metadata: valid.GetMetadata(),
+ Spec: linuxdesktopv1pb.LinuxDesktopSpec_builder{
Addr: "127.0.0.1:22",
- },
- },
+ }.Build(),
+ }.Build(),
wantErr: true,
},
}
diff --git a/lib/auth/linuxdesktop/linuxdesktopv1/service.go b/lib/auth/linuxdesktop/linuxdesktopv1/service.go
index 9e683ee69b8..4954f2e0e30 100644
--- a/lib/auth/linuxdesktop/linuxdesktopv1/service.go
+++ b/lib/auth/linuxdesktop/linuxdesktopv1/service.go
@@ -136,7 +136,7 @@ func (s *Service) ListLinuxDesktops(ctx context.Context, req *linuxdesktopv1.Lis
return nil, false
}),
- int(req.PageSize),
+ int(req.GetPageSize()),
func(t *linuxdesktopv1.LinuxDesktop) string {
return t.GetMetadata().GetName()
})
@@ -145,10 +145,10 @@ func (s *Service) ListLinuxDesktops(ctx context.Context, req *linuxdesktopv1.Lis
return nil, trace.Wrap(err)
}
- return &linuxdesktopv1.ListLinuxDesktopsResponse{
+ return linuxdesktopv1.ListLinuxDesktopsResponse_builder{
LinuxDesktops: rsp,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// GetLinuxDesktop returns Linux desktop resource.
diff --git a/lib/auth/linuxdesktop/linuxdesktopv1/service_test.go b/lib/auth/linuxdesktop/linuxdesktopv1/service_test.go
index 7cc32bf2b16..c8e188e9e9c 100644
--- a/lib/auth/linuxdesktop/linuxdesktopv1/service_test.go
+++ b/lib/auth/linuxdesktop/linuxdesktopv1/service_test.go
@@ -186,10 +186,10 @@ func allowChecks(checks ...check) map[check]bool {
func newTestDesktop(t *testing.T, name string) *linuxdesktopv1pb.LinuxDesktop {
t.Helper()
- desktop, err := NewLinuxDesktop(name, &linuxdesktopv1pb.LinuxDesktopSpec{
+ desktop, err := NewLinuxDesktop(name, linuxdesktopv1pb.LinuxDesktopSpec_builder{
Addr: "127.0.0.1:22",
Hostname: "desktop-host",
- })
+ }.Build())
require.NoError(t, err)
return desktop
}
@@ -213,10 +213,10 @@ func TestServiceListLinuxDesktops(t *testing.T) {
}
service := newTestService(t, checker, authz.AdminActionAuthNotRequired, backend, reader)
- resp, err := service.ListLinuxDesktops(ctx, &linuxdesktopv1pb.ListLinuxDesktopsRequest{
+ resp, err := service.ListLinuxDesktops(ctx, linuxdesktopv1pb.ListLinuxDesktopsRequest_builder{
PageSize: 10,
PageToken: "next-token",
- })
+ }.Build())
require.NoError(t, err)
require.Equal(t, []*linuxdesktopv1pb.LinuxDesktop{desktop}, resp.GetLinuxDesktops())
require.Empty(t, resp.GetNextPageToken())
@@ -246,9 +246,9 @@ func TestServiceGetLinuxDesktop(t *testing.T) {
}
service := newTestService(t, checker, authz.AdminActionAuthNotRequired, backend, reader)
- resp, err := service.GetLinuxDesktop(ctx, &linuxdesktopv1pb.GetLinuxDesktopRequest{
+ resp, err := service.GetLinuxDesktop(ctx, linuxdesktopv1pb.GetLinuxDesktopRequest_builder{
Name: "desktop-1",
- })
+ }.Build())
require.NoError(t, err)
require.Equal(t, desktop, resp)
require.True(t, reader.getCalled)
@@ -273,9 +273,9 @@ func TestServiceCreateLinuxDesktop(t *testing.T) {
}
service := newTestService(t, checker, authz.AdminActionAuthNotRequired, backend, reader)
- resp, err := service.CreateLinuxDesktop(ctx, &linuxdesktopv1pb.CreateLinuxDesktopRequest{
+ resp, err := service.CreateLinuxDesktop(ctx, linuxdesktopv1pb.CreateLinuxDesktopRequest_builder{
LinuxDesktop: desktop,
- })
+ }.Build())
require.NoError(t, err)
require.Equal(t, desktop, resp)
require.True(t, backend.createCalled)
@@ -319,9 +319,9 @@ func TestServiceUpdateLinuxDesktop(t *testing.T) {
}
service := newTestService(t, checker, authz.AdminActionAuthNotRequired, backend, reader)
- resp, err := service.UpdateLinuxDesktop(ctx, &linuxdesktopv1pb.UpdateLinuxDesktopRequest{
+ resp, err := service.UpdateLinuxDesktop(ctx, linuxdesktopv1pb.UpdateLinuxDesktopRequest_builder{
LinuxDesktop: desktop,
- })
+ }.Build())
require.NoError(t, err)
require.Equal(t, desktop, resp)
require.True(t, backend.updateCalled)
@@ -366,9 +366,9 @@ func TestServiceUpsertLinuxDesktop(t *testing.T) {
}
service := newTestService(t, checker, authz.AdminActionAuthNotRequired, backend, reader)
- resp, err := service.UpsertLinuxDesktop(ctx, &linuxdesktopv1pb.UpsertLinuxDesktopRequest{
+ resp, err := service.UpsertLinuxDesktop(ctx, linuxdesktopv1pb.UpsertLinuxDesktopRequest_builder{
LinuxDesktop: desktop,
- })
+ }.Build())
require.NoError(t, err)
require.Equal(t, desktop, resp)
require.True(t, backend.upsertCalled)
@@ -413,9 +413,9 @@ func TestServiceDeleteLinuxDesktop(t *testing.T) {
}
service := newTestService(t, checker, authz.AdminActionAuthNotRequired, backend, reader)
- _, err := service.DeleteLinuxDesktop(ctx, &linuxdesktopv1pb.DeleteLinuxDesktopRequest{
+ _, err := service.DeleteLinuxDesktop(ctx, linuxdesktopv1pb.DeleteLinuxDesktopRequest_builder{
Name: "desktop-1",
- })
+ }.Build())
require.NoError(t, err)
require.True(t, backend.deleteCalled)
require.Equal(t, "desktop-1", backend.deleteName)
@@ -439,9 +439,9 @@ func TestServiceAdminActionRequired(t *testing.T) {
{
name: "create",
call: func(ctx context.Context, svc *Service) error {
- _, err := svc.CreateLinuxDesktop(ctx, &linuxdesktopv1pb.CreateLinuxDesktopRequest{
+ _, err := svc.CreateLinuxDesktop(ctx, linuxdesktopv1pb.CreateLinuxDesktopRequest_builder{
LinuxDesktop: desktop,
- })
+ }.Build())
return err
},
backendCheck: func(t *testing.T, backend *fakeBackend) {
@@ -452,9 +452,9 @@ func TestServiceAdminActionRequired(t *testing.T) {
{
name: "update",
call: func(ctx context.Context, svc *Service) error {
- _, err := svc.UpdateLinuxDesktop(ctx, &linuxdesktopv1pb.UpdateLinuxDesktopRequest{
+ _, err := svc.UpdateLinuxDesktop(ctx, linuxdesktopv1pb.UpdateLinuxDesktopRequest_builder{
LinuxDesktop: desktop,
- })
+ }.Build())
return err
},
backendCheck: func(t *testing.T, backend *fakeBackend) {
@@ -465,9 +465,9 @@ func TestServiceAdminActionRequired(t *testing.T) {
{
name: "upsert",
call: func(ctx context.Context, svc *Service) error {
- _, err := svc.UpsertLinuxDesktop(ctx, &linuxdesktopv1pb.UpsertLinuxDesktopRequest{
+ _, err := svc.UpsertLinuxDesktop(ctx, linuxdesktopv1pb.UpsertLinuxDesktopRequest_builder{
LinuxDesktop: desktop,
- })
+ }.Build())
return err
},
backendCheck: func(t *testing.T, backend *fakeBackend) {
@@ -481,9 +481,9 @@ func TestServiceAdminActionRequired(t *testing.T) {
{
name: "delete",
call: func(ctx context.Context, svc *Service) error {
- _, err := svc.DeleteLinuxDesktop(ctx, &linuxdesktopv1pb.DeleteLinuxDesktopRequest{
+ _, err := svc.DeleteLinuxDesktop(ctx, linuxdesktopv1pb.DeleteLinuxDesktopRequest_builder{
Name: "desktop-1",
- })
+ }.Build())
return err
},
backendCheck: func(t *testing.T, backend *fakeBackend) {
diff --git a/lib/auth/machineid/machineidv1/auto_update_version_reporter.go b/lib/auth/machineid/machineidv1/auto_update_version_reporter.go
index 756620b3494..6bf77ab48dc 100644
--- a/lib/auth/machineid/machineidv1/auto_update_version_reporter.go
+++ b/lib/auth/machineid/machineidv1/auto_update_version_reporter.go
@@ -267,24 +267,24 @@ func (r *AutoUpdateVersionReporter) generateReport(ctx context.Context) error {
// If the bot did not send an ExternalUpdater, it does not properly
// support managed updates - so we put it in the no-group ("") group.
var groupName string
- if ui := latest.GetUpdaterInfo(); latest.ExternalUpdater != "" && ui != nil {
+ if ui := latest.GetUpdaterInfo(); latest.GetExternalUpdater() != "" && ui != nil {
groupName = ui.UpdateGroup
}
group, ok := groups[groupName]
if !ok {
- group = &autoupdate.AutoUpdateBotInstanceReportSpecGroup{
+ group = autoupdate.AutoUpdateBotInstanceReportSpecGroup_builder{
Versions: make(map[string]*autoupdate.AutoUpdateBotInstanceReportSpecGroupVersion),
- }
+ }.Build()
groups[groupName] = group
}
- version, ok := group.Versions[latest.GetVersion()]
+ version, ok := group.GetVersions()[latest.GetVersion()]
if !ok {
version = &autoupdate.AutoUpdateBotInstanceReportSpecGroupVersion{}
- group.Versions[latest.GetVersion()] = version
+ group.GetVersions()[latest.GetVersion()] = version
}
- version.Count++
+ version.SetCount(version.GetCount() + 1)
}
if nextToken == "" || len(instances) == 0 {
@@ -292,10 +292,10 @@ func (r *AutoUpdateVersionReporter) generateReport(ctx context.Context) error {
}
}
- report, err := update.NewAutoUpdateBotInstanceReport(&autoupdate.AutoUpdateBotInstanceReportSpec{
+ report, err := update.NewAutoUpdateBotInstanceReport(autoupdate.AutoUpdateBotInstanceReportSpec_builder{
Timestamp: timestamppb.New(r.clock.Now()),
Groups: groups,
- })
+ }.Build())
if err != nil {
return trace.Wrap(err, "creating report")
}
@@ -338,13 +338,13 @@ func EmitInstancesMetric(report *autoupdate.AutoUpdateBotInstanceReport, gauge *
gauge.With(prometheus.Labels{
teleport.TagVersion: version,
teleport.TagAutomaticUpdates: "false",
- }).Set(float64(versionMetrics.Count))
+ }).Set(float64(versionMetrics.GetCount()))
}
continue
}
for version, metrics := range groupMetrics.GetVersions() {
- byVersion[version] += metrics.Count
+ byVersion[version] += metrics.GetCount()
}
}
diff --git a/lib/auth/machineid/machineidv1/auto_update_version_reporter_test.go b/lib/auth/machineid/machineidv1/auto_update_version_reporter_test.go
index c87314315c4..da38fb76582 100644
--- a/lib/auth/machineid/machineidv1/auto_update_version_reporter_test.go
+++ b/lib/auth/machineid/machineidv1/auto_update_version_reporter_test.go
@@ -69,25 +69,25 @@ func TestAutoUpdateVersionReporter(t *testing.T) {
createBotInstance := func(t *testing.T, group string, versions []string) {
t.Helper()
- _, err = botInstanceService.CreateBotInstance(ctx, &machineidv1pb.BotInstance{
- Metadata: &headerv1.Metadata{
+ _, err = botInstanceService.CreateBotInstance(ctx, machineidv1pb.BotInstance_builder{
+ Metadata: headerv1.Metadata_builder{
Expires: timestamppb.New(clock.Now().Add(1 * time.Hour)),
- },
- Spec: &machineidv1pb.BotInstanceSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotInstanceSpec_builder{
InstanceId: uuid.NewString(),
BotName: "bot-1234",
- },
- Status: &machineidv1pb.BotInstanceStatus{
+ }.Build(),
+ Status: machineidv1pb.BotInstanceStatus_builder{
LatestHeartbeats: slices.Map(versions, func(v string) *machineidv1pb.BotInstanceStatusHeartbeat {
- heartbeat := &machineidv1pb.BotInstanceStatusHeartbeat{Version: v}
+ heartbeat := machineidv1pb.BotInstanceStatusHeartbeat_builder{Version: v}.Build()
if group != "" {
- heartbeat.ExternalUpdater = "kube"
- heartbeat.UpdaterInfo = &types.UpdaterV2Info{UpdateGroup: group}
+ heartbeat.SetExternalUpdater("kube")
+ heartbeat.SetUpdaterInfo(&types.UpdaterV2Info{UpdateGroup: group})
}
return heartbeat
}),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
}
createBotInstance(t, "", []string{"17.0.0", "18.0.0"})
@@ -124,29 +124,29 @@ func TestAutoUpdateVersionReporter(t *testing.T) {
require.NoError(t, err)
diff := cmp.Diff(
- &autoupdatev1pb.AutoUpdateBotInstanceReportSpec{
+ autoupdatev1pb.AutoUpdateBotInstanceReportSpec_builder{
Timestamp: timestamppb.New(clock.Now()),
Groups: map[string]*autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroup{
- "prod": {
+ "prod": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion{
- "18.1.0": {Count: 1},
+ "18.1.0": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
- "stage": {
+ }.Build(),
+ "stage": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion{
- "19.0.0-dev": {Count: 1},
+ "19.0.0-dev": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
+ }.Build(),
// Unmanaged (no-group) group.
- "": {
+ "": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion{
- "18.0.0": {Count: 1},
- "18.1.0": {Count: 2},
+ "18.0.0": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 1}.Build(),
+ "18.1.0": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 2}.Build(),
},
- },
+ }.Build(),
},
- },
+ }.Build(),
report.GetSpec(),
protocmp.Transform(),
)
@@ -171,30 +171,30 @@ func TestEmitInstancesMetric(t *testing.T) {
)
machineidv1.EmitInstancesMetric(
- &autoupdatev1pb.AutoUpdateBotInstanceReport{
- Spec: &autoupdatev1pb.AutoUpdateBotInstanceReportSpec{
+ autoupdatev1pb.AutoUpdateBotInstanceReport_builder{
+ Spec: autoupdatev1pb.AutoUpdateBotInstanceReportSpec_builder{
Groups: map[string]*autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroup{
- "prod": {
+ "prod": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion{
- "18.0.0": {Count: 1},
- "19.0.0": {Count: 1},
+ "18.0.0": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 1}.Build(),
+ "19.0.0": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
- "stage": {
+ }.Build(),
+ "stage": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion{
- "18.0.0": {Count: 1},
- "19.0.0": {Count: 1},
+ "18.0.0": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 1}.Build(),
+ "19.0.0": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 1}.Build(),
},
- },
- "": {
+ }.Build(),
+ "": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroup_builder{
Versions: map[string]*autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion{
- "19.0.0": {Count: 123},
- "20.0.0": {Count: 321},
+ "19.0.0": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 123}.Build(),
+ "20.0.0": autoupdatev1pb.AutoUpdateBotInstanceReportSpecGroupVersion_builder{Count: 321}.Build(),
},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
gauge,
)
diff --git a/lib/auth/machineid/machineidv1/bot_instance_service.go b/lib/auth/machineid/machineidv1/bot_instance_service.go
index 7bbfe3b2ea1..585d696f2d7 100644
--- a/lib/auth/machineid/machineidv1/bot_instance_service.go
+++ b/lib/auth/machineid/machineidv1/bot_instance_service.go
@@ -129,7 +129,7 @@ func (b *BotInstanceService) DeleteBotInstance(ctx context.Context, req *pb.Dele
return nil, trace.Wrap(err)
}
- instance, err := b.backend.GetBotInstance(ctx, req.BotName, req.InstanceId)
+ instance, err := b.backend.GetBotInstance(ctx, req.GetBotName(), req.GetInstanceId())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -137,7 +137,7 @@ func (b *BotInstanceService) DeleteBotInstance(ctx context.Context, req *pb.Dele
ruleCtx.Resource153 = instance
if err := authCtx.CheckerContext.Decision(
ctx,
- instance.Scope,
+ instance.GetScope(),
func(checker *services.ScopedAccessChecker) error {
return checker.CheckAccessToRules(
&ruleCtx,
@@ -158,7 +158,7 @@ func (b *BotInstanceService) DeleteBotInstance(ctx context.Context, req *pb.Dele
}
if err := b.backend.DeleteBotInstance(
- ctx, instance.Spec.BotName, instance.Spec.InstanceId,
+ ctx, instance.GetSpec().GetBotName(), instance.GetSpec().GetInstanceId(),
); err != nil {
return nil, trace.Wrap(err)
}
@@ -182,7 +182,7 @@ func (b *BotInstanceService) GetBotInstance(ctx context.Context, req *pb.GetBotI
return nil, trace.Wrap(err)
}
- res, err := b.cache.GetBotInstance(ctx, req.BotName, req.InstanceId)
+ res, err := b.cache.GetBotInstance(ctx, req.GetBotName(), req.GetInstanceId())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -190,7 +190,7 @@ func (b *BotInstanceService) GetBotInstance(ctx context.Context, req *pb.GetBotI
ruleCtx.Resource153 = res
if err := authCtx.CheckerContext.Decision(
ctx,
- res.Scope,
+ res.GetScope(),
func(checker *services.ScopedAccessChecker) error {
return checker.CheckAccessToRules(
&ruleCtx,
@@ -213,16 +213,16 @@ func (b *BotInstanceService) ListBotInstances(ctx context.Context, req *pb.ListB
sortField = req.GetSort().Field
sortDesc = req.GetSort().IsDesc
}
- return b.ListBotInstancesV2(ctx, &pb.ListBotInstancesV2Request{
+ return b.ListBotInstancesV2(ctx, pb.ListBotInstancesV2Request_builder{
PageSize: req.GetPageSize(),
PageToken: req.GetPageToken(),
SortField: sortField,
SortDesc: sortDesc,
- Filter: &pb.ListBotInstancesV2Request_Filters{
+ Filter: pb.ListBotInstancesV2Request_Filters_builder{
BotName: req.GetFilterBotName(),
SearchTerm: req.GetFilterSearchTerm(),
- },
- })
+ }.Build(),
+ }.Build())
}
// ListBotInstancesV2 returns a list of bot instances matching the criteria in the request
@@ -243,8 +243,8 @@ func (b *BotInstanceService) ListBotInstancesV2(ctx context.Context, req *pb.Lis
botInstances, nextToken, err := b.cache.ListBotInstances(
ctx,
- int(req.PageSize),
- req.PageToken,
+ int(req.GetPageSize()),
+ req.GetPageToken(),
&services.ListBotInstancesRequestOptions{
SortField: req.GetSortField(),
SortDesc: req.GetSortDesc(),
@@ -256,7 +256,7 @@ func (b *BotInstanceService) ListBotInstancesV2(ctx context.Context, req *pb.Lis
ruleCtx.Resource153 = botInstance
err := authCtx.CheckerContext.Decision(
ctx,
- botInstance.Scope,
+ botInstance.GetScope(),
func(checker *services.ScopedAccessChecker) error {
return checker.CheckAccessToRules(
&ruleCtx,
@@ -274,10 +274,10 @@ func (b *BotInstanceService) ListBotInstancesV2(ctx context.Context, req *pb.Lis
return nil, trace.Wrap(err)
}
- return &pb.ListBotInstancesResponse{
+ return pb.ListBotInstancesResponse_builder{
BotInstances: botInstances,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// SubmitHeartbeat records heartbeat information for a bot
@@ -286,7 +286,7 @@ func (b *BotInstanceService) SubmitHeartbeat(ctx context.Context, req *pb.Submit
if err != nil {
return nil, trace.Wrap(err)
}
- if req.Heartbeat == nil {
+ if !req.HasHeartbeat() {
return nil, trace.BadParameter("heartbeat: must be non-nil")
}
@@ -316,7 +316,7 @@ func (b *BotInstanceService) SubmitHeartbeat(ctx context.Context, req *pb.Submit
// flag set - however - once sufficient time has passed and we're sure all
// existing bots will have the BotInternal flag set in their certs, we can
// make this check always applied.
- if ident.ScopePin != nil && ident.ScopePin.Scope != "" {
+ if ident.ScopePin != nil && ident.ScopePin.GetScope() != "" {
if !ident.BotInternal {
return nil, trace.AccessDenied("identity not marked BotInternal")
}
@@ -327,28 +327,28 @@ func (b *BotInstanceService) SubmitHeartbeat(ctx context.Context, req *pb.Submit
"Received bot instance heartbeat",
"bot_name", botName,
"bot_instance", botInstanceID,
- "heartbeat", logutils.StringerAttr(req.Heartbeat),
+ "heartbeat", logutils.StringerAttr(req.GetHeartbeat()),
)
_, err = b.backend.PatchBotInstance(ctx, botName, botInstanceID, func(instance *pb.BotInstance) (*pb.BotInstance, error) {
- if instance.Status == nil {
- instance.Status = &pb.BotInstanceStatus{}
+ if !instance.HasStatus() {
+ instance.SetStatus(&pb.BotInstanceStatus{})
}
// Set initial heartbeat if not set.
- if instance.Status.InitialHeartbeat == nil {
- instance.Status.InitialHeartbeat = req.Heartbeat
+ if !instance.GetStatus().HasInitialHeartbeat() {
+ instance.GetStatus().SetInitialHeartbeat(req.GetHeartbeat())
}
// If we're at or above the limit, remove enough of the front
// elements to make room for the new one at the end.
- if len(instance.Status.LatestHeartbeats) >= heartbeatHistoryLimit {
- toRemove := len(instance.Status.LatestHeartbeats) - heartbeatHistoryLimit + 1
- instance.Status.LatestHeartbeats = instance.Status.LatestHeartbeats[toRemove:]
+ if len(instance.GetStatus().GetLatestHeartbeats()) >= heartbeatHistoryLimit {
+ toRemove := len(instance.GetStatus().GetLatestHeartbeats()) - heartbeatHistoryLimit + 1
+ instance.GetStatus().SetLatestHeartbeats(instance.GetStatus().GetLatestHeartbeats()[toRemove:])
}
// Append the new heartbeat to the end.
- instance.Status.LatestHeartbeats = append(instance.Status.LatestHeartbeats, req.Heartbeat)
+ instance.GetStatus().SetLatestHeartbeats(append(instance.GetStatus().GetLatestHeartbeats(), req.GetHeartbeat()))
if storeHeartbeatExtras() {
// Overwrite the service health.
- instance.Status.ServiceHealth = req.ServiceHealth
+ instance.GetStatus().SetServiceHealth(req.GetServiceHealth())
}
return instance, nil
diff --git a/lib/auth/machineid/machineidv1/bot_instance_service_test.go b/lib/auth/machineid/machineidv1/bot_instance_service_test.go
index c6e13c41236..61b5da56529 100644
--- a/lib/auth/machineid/machineidv1/bot_instance_service_test.go
+++ b/lib/auth/machineid/machineidv1/bot_instance_service_test.go
@@ -53,7 +53,7 @@ const (
func insertTestBotInstance(t *testing.T, backend *local.BotInstanceService) {
t.Helper()
bi := newBotInstance(testBotName)
- bi.Spec.InstanceId = testInstanceID
+ bi.GetSpec().SetInstanceId(testInstanceID)
_, err := backend.CreateBotInstance(t.Context(), bi)
require.NoError(t, err)
}
@@ -195,61 +195,61 @@ func TestBotInstanceServiceReadDelete(t *testing.T) {
// Make sure we can get all foo instances
for id := range idsFoo {
- ins, err := service.GetBotInstance(ctx, &machineidv1.GetBotInstanceRequest{
+ ins, err := service.GetBotInstance(ctx, machineidv1.GetBotInstanceRequest_builder{
BotName: "foo",
InstanceId: id,
- })
+ }.Build())
require.NoError(t, err)
- require.Equal(t, "foo", ins.Spec.BotName)
- require.Equal(t, id, ins.Spec.InstanceId)
+ require.Equal(t, "foo", ins.GetSpec().GetBotName())
+ require.Equal(t, id, ins.GetSpec().GetInstanceId())
}
// Make sure we can get all bar instances
for id := range idsBar {
- ins, err := service.GetBotInstance(ctx, &machineidv1.GetBotInstanceRequest{
+ ins, err := service.GetBotInstance(ctx, machineidv1.GetBotInstanceRequest_builder{
BotName: "bar",
InstanceId: id,
- })
+ }.Build())
require.NoError(t, err)
- require.Equal(t, "bar", ins.Spec.BotName)
- require.Equal(t, id, ins.Spec.InstanceId)
+ require.Equal(t, "bar", ins.GetSpec().GetBotName())
+ require.Equal(t, id, ins.GetSpec().GetInstanceId())
}
// List should work
fooInstances := listInstances(t, ctx, service, "foo")
require.Len(t, fooInstances, 3)
for _, bi := range fooInstances {
- require.Contains(t, idsFoo, bi.Spec.InstanceId)
+ require.Contains(t, idsFoo, bi.GetSpec().GetInstanceId())
}
barInstances := listInstances(t, ctx, service, "bar")
require.Len(t, barInstances, 3)
for _, bi := range barInstances {
- require.Contains(t, idsBar, bi.Spec.InstanceId)
+ require.Contains(t, idsBar, bi.GetSpec().GetInstanceId())
}
allInstances := listInstances(t, ctx, service, "")
require.Len(t, allInstances, 6)
for _, bi := range allInstances {
- require.Contains(t, idsAll, bi.Spec.InstanceId)
+ require.Contains(t, idsAll, bi.GetSpec().GetInstanceId())
}
// Attempt to delete everything
for id := range idsFoo {
- _, err := service.DeleteBotInstance(ctx, &machineidv1.DeleteBotInstanceRequest{
+ _, err := service.DeleteBotInstance(ctx, machineidv1.DeleteBotInstanceRequest_builder{
BotName: "foo",
InstanceId: id,
- })
+ }.Build())
require.NoError(t, err)
}
for id := range idsBar {
- _, err := service.DeleteBotInstance(ctx, &machineidv1.DeleteBotInstanceRequest{
+ _, err := service.DeleteBotInstance(ctx, machineidv1.DeleteBotInstanceRequest_builder{
BotName: "bar",
InstanceId: id,
- })
+ }.Build())
require.NoError(t, err)
}
@@ -287,43 +287,43 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
{
name: "success",
createBotInstance: true,
- req: &machineidv1.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1.BotInstanceStatusHeartbeat{
+ req: machineidv1.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{
Hostname: "llama",
- },
+ }.Build(),
ServiceHealth: []*machineidv1.BotInstanceServiceHealth{
- {
- Service: &machineidv1.BotInstanceServiceIdentifier{
+ machineidv1.BotInstanceServiceHealth_builder{
+ Service: machineidv1.BotInstanceServiceIdentifier_builder{
Type: "application-tunnel",
Name: "my-application-tunnel",
- },
+ }.Build(),
Status: machineidv1.BotInstanceHealthStatus_BOT_INSTANCE_HEALTH_STATUS_UNHEALTHY,
Reason: ptr("application is broken"),
- },
+ }.Build(),
},
- },
+ }.Build(),
identity: goodIdentity,
assertErr: assert.NoError,
wantHeartbeat: true,
wantServiceHealth: []*machineidv1.BotInstanceServiceHealth{
- {
- Service: &machineidv1.BotInstanceServiceIdentifier{
+ machineidv1.BotInstanceServiceHealth_builder{
+ Service: machineidv1.BotInstanceServiceIdentifier_builder{
Type: "application-tunnel",
Name: "my-application-tunnel",
- },
+ }.Build(),
Status: machineidv1.BotInstanceHealthStatus_BOT_INSTANCE_HEALTH_STATUS_UNHEALTHY,
Reason: ptr("application is broken"),
- },
+ }.Build(),
},
},
{
name: "missing bot name",
createBotInstance: true,
- req: &machineidv1.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1.BotInstanceStatusHeartbeat{
+ req: machineidv1.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{
Hostname: "llama",
- },
- },
+ }.Build(),
+ }.Build(),
identity: tlsca.Identity{
BotInstanceID: botInstanceID,
},
@@ -335,11 +335,11 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
{
name: "missing instance id",
createBotInstance: true,
- req: &machineidv1.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1.BotInstanceStatusHeartbeat{
+ req: machineidv1.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{
Hostname: "llama",
- },
- },
+ }.Build(),
+ }.Build(),
identity: tlsca.Identity{
BotName: botName,
},
@@ -351,11 +351,11 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
{
name: "bot instance does not exist",
createBotInstance: false,
- req: &machineidv1.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1.BotInstanceStatusHeartbeat{
+ req: machineidv1.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{
Hostname: "llama",
- },
- },
+ }.Build(),
+ }.Build(),
identity: goodIdentity,
assertErr: func(t assert.TestingT, err error, i ...any) bool {
return assert.True(t, trace.IsNotFound(err))
@@ -364,9 +364,9 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
{
name: "missing heartbeat",
createBotInstance: true,
- req: &machineidv1.SubmitHeartbeatRequest{
+ req: machineidv1.SubmitHeartbeatRequest_builder{
Heartbeat: nil,
- },
+ }.Build(),
identity: goodIdentity,
assertErr: func(t assert.TestingT, err error, i ...any) bool {
return assert.True(t, trace.IsBadParameter(err)) && assert.Contains(t, err.Error(), "heartbeat: must be non-nil")
@@ -376,21 +376,21 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
{
name: "service name too long",
createBotInstance: true,
- req: &machineidv1.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1.BotInstanceStatusHeartbeat{
+ req: machineidv1.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{
Hostname: "llama",
- },
+ }.Build(),
ServiceHealth: []*machineidv1.BotInstanceServiceHealth{
- {
- Service: &machineidv1.BotInstanceServiceIdentifier{
+ machineidv1.BotInstanceServiceHealth_builder{
+ Service: machineidv1.BotInstanceServiceIdentifier_builder{
Type: "application-tunnel",
Name: strings.Repeat("a", 100),
- },
+ }.Build(),
Status: machineidv1.BotInstanceHealthStatus_BOT_INSTANCE_HEALTH_STATUS_UNHEALTHY,
Reason: ptr("application is broken"),
- },
+ }.Build(),
},
- },
+ }.Build(),
identity: goodIdentity,
assertErr: func(t assert.TestingT, err error, i ...any) bool {
return assert.True(t, trace.IsBadParameter(err)) && assert.Contains(t, err.Error(), "is longer than 64 bytes")
@@ -400,21 +400,21 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
{
name: "status reason too long",
createBotInstance: true,
- req: &machineidv1.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1.BotInstanceStatusHeartbeat{
+ req: machineidv1.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{
Hostname: "llama",
- },
+ }.Build(),
ServiceHealth: []*machineidv1.BotInstanceServiceHealth{
- {
- Service: &machineidv1.BotInstanceServiceIdentifier{
+ machineidv1.BotInstanceServiceHealth_builder{
+ Service: machineidv1.BotInstanceServiceIdentifier_builder{
Type: "application-tunnel",
Name: "my-application-tunnel",
- },
+ }.Build(),
Status: machineidv1.BotInstanceHealthStatus_BOT_INSTANCE_HEALTH_STATUS_UNHEALTHY,
Reason: ptr(strings.Repeat("a", 300)),
- },
+ }.Build(),
},
- },
+ }.Build(),
identity: goodIdentity,
assertErr: func(t assert.TestingT, err error, i ...any) bool {
return assert.True(t, trace.IsBadParameter(err)) && assert.Contains(t, err.Error(), "status reason longer than 256 bytes")
@@ -424,13 +424,13 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
{
name: "scoped identity without BotInternal",
createBotInstance: true,
- req: &machineidv1.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1.BotInstanceStatusHeartbeat{Hostname: "llama"},
- },
+ req: machineidv1.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{Hostname: "llama"}.Build(),
+ }.Build(),
identity: tlsca.Identity{
BotName: botName,
BotInstanceID: botInstanceID,
- ScopePin: &scopesv1.Pin{Kind: scopesv1.PinKind_PIN_KIND_USER, Scope: "/scopes/test"},
+ ScopePin: scopesv1.Pin_builder{Kind: scopesv1.PinKind_PIN_KIND_USER, Scope: "/scopes/test"}.Build(),
BotInternal: false,
},
assertErr: func(t assert.TestingT, err error, i ...any) bool {
@@ -442,13 +442,13 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
{
name: "scoped identity with BotInternal",
createBotInstance: true,
- req: &machineidv1.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1.BotInstanceStatusHeartbeat{Hostname: "llama"},
- },
+ req: machineidv1.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{Hostname: "llama"}.Build(),
+ }.Build(),
identity: tlsca.Identity{
BotName: botName,
BotInstanceID: botInstanceID,
- ScopePin: &scopesv1.Pin{Kind: scopesv1.PinKind_PIN_KIND_USER, Scope: "/scopes/test"},
+ ScopePin: scopesv1.Pin_builder{Kind: scopesv1.PinKind_PIN_KIND_USER, Scope: "/scopes/test"}.Build(),
BotInternal: true,
},
assertErr: assert.NoError,
@@ -475,7 +475,7 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
if tt.createBotInstance {
bi := newBotInstance(botName)
- bi.Spec.InstanceId = botInstanceID
+ bi.GetSpec().SetInstanceId(botInstanceID)
_, err := backend.CreateBotInstance(ctx, bi)
require.NoError(t, err)
}
@@ -489,25 +489,25 @@ func TestBotInstanceServiceSubmitHeartbeat(t *testing.T) {
assert.Empty(
t,
cmp.Diff(
- bi.Status.InitialHeartbeat,
- tt.req.Heartbeat,
+ bi.GetStatus().GetInitialHeartbeat(),
+ tt.req.GetHeartbeat(),
protocmp.Transform()),
)
- assert.Len(t, bi.Status.LatestHeartbeats, 1)
+ assert.Len(t, bi.GetStatus().GetLatestHeartbeats(), 1)
assert.Empty(
t,
cmp.Diff(
- bi.Status.LatestHeartbeats[0],
- tt.req.Heartbeat,
+ bi.GetStatus().GetLatestHeartbeats()[0],
+ tt.req.GetHeartbeat(),
protocmp.Transform()),
)
} else {
- assert.Nil(t, bi.Status.InitialHeartbeat)
- assert.Empty(t, bi.Status.LatestHeartbeats)
+ assert.Nil(t, bi.GetStatus().GetInitialHeartbeat())
+ assert.Empty(t, bi.GetStatus().GetLatestHeartbeats())
}
assert.Empty(t,
cmp.Diff(
- bi.Status.ServiceHealth,
+ bi.GetStatus().GetServiceHealth(),
tt.wantServiceHealth,
protocmp.Transform(),
),
@@ -543,28 +543,28 @@ func TestBotInstanceServiceSubmitHeartbeat_HeartbeatLimit(t *testing.T) {
require.NoError(t, err)
bi := newBotInstance(botName)
- bi.Spec.InstanceId = botInstanceID
+ bi.GetSpec().SetInstanceId(botInstanceID)
_, err = backend.CreateBotInstance(ctx, bi)
require.NoError(t, err)
extraHeartbeats := 5
for i := range heartbeatHistoryLimit + extraHeartbeats {
- _, err = service.SubmitHeartbeat(ctx, &machineidv1.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1.BotInstanceStatusHeartbeat{
+ _, err = service.SubmitHeartbeat(ctx, machineidv1.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{
Hostname: strconv.Itoa(i),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
}
bi, err = backend.GetBotInstance(ctx, botName, botInstanceID)
require.NoError(t, err)
- assert.Len(t, bi.Status.LatestHeartbeats, heartbeatHistoryLimit)
- assert.Equal(t, "0", bi.Status.InitialHeartbeat.Hostname)
+ assert.Len(t, bi.GetStatus().GetLatestHeartbeats(), heartbeatHistoryLimit)
+ assert.Equal(t, "0", bi.GetStatus().GetInitialHeartbeat().GetHostname())
// Ensure we have the last 10 heartbeats
for i := range heartbeatHistoryLimit {
wantHostname := strconv.Itoa(i + extraHeartbeats)
- assert.Equal(t, wantHostname, bi.Status.LatestHeartbeats[i].Hostname)
+ assert.Equal(t, wantHostname, bi.GetStatus().GetLatestHeartbeats()[i].GetHostname())
}
}
@@ -635,11 +635,11 @@ func callMethod(t *testing.T, service *BotInstanceService, method string) error
_, err := desc.Handler(service, context.Background(), func(req any) error {
switch r := req.(type) {
case *machineidv1.GetBotInstanceRequest:
- r.BotName = testBotName
- r.InstanceId = testInstanceID
+ r.SetBotName(testBotName)
+ r.SetInstanceId(testInstanceID)
case *machineidv1.DeleteBotInstanceRequest:
- r.BotName = testBotName
- r.InstanceId = testInstanceID
+ r.SetBotName(testBotName)
+ r.SetInstanceId(testInstanceID)
}
return nil
}, nil)
@@ -654,15 +654,15 @@ func callMethod(t *testing.T, service *BotInstanceService, method string) error
func newBotInstance(botName string) *machineidv1.BotInstance {
id := uuid.New()
- bi := &machineidv1.BotInstance{
+ bi := machineidv1.BotInstance_builder{
Kind: types.KindBotInstance,
Version: types.V1,
- Spec: &machineidv1.BotInstanceSpec{
+ Spec: machineidv1.BotInstanceSpec_builder{
BotName: botName,
InstanceId: id.String(),
- },
+ }.Build(),
Status: &machineidv1.BotInstanceStatus{},
- }
+ }.Build()
return bi
}
@@ -678,7 +678,7 @@ func createInstances(t *testing.T, ctx context.Context, backend *local.BotInstan
_, err := backend.CreateBotInstance(ctx, bi)
require.NoError(t, err)
- ids[bi.Spec.InstanceId] = struct{}{}
+ ids[bi.GetSpec().GetInstanceId()] = struct{}{}
}
return ids
@@ -692,16 +692,16 @@ func listInstances(t *testing.T, ctx context.Context, service *BotInstanceServic
var nextKey string
for {
- res, err := service.ListBotInstances(ctx, &machineidv1.ListBotInstancesRequest{
+ res, err := service.ListBotInstances(ctx, machineidv1.ListBotInstancesRequest_builder{
FilterBotName: botName,
PageSize: 0,
PageToken: nextKey,
- })
+ }.Build())
require.NoError(t, err)
- resources = append(resources, res.BotInstances...)
+ resources = append(resources, res.GetBotInstances()...)
- nextKey = res.NextPageToken
+ nextKey = res.GetNextPageToken()
if nextKey == "" {
break
}
diff --git a/lib/auth/machineid/machineidv1/bot_service.go b/lib/auth/machineid/machineidv1/bot_service.go
index aa2cab4a03c..fff480da6ae 100644
--- a/lib/auth/machineid/machineidv1/bot_service.go
+++ b/lib/auth/machineid/machineidv1/bot_service.go
@@ -189,24 +189,24 @@ func (bs *BotService) GetBot(ctx context.Context, req *pb.GetBotRequest) (*pb.Bo
return nil, trace.Wrap(err)
}
- if req.BotName == "" {
+ if req.GetBotName() == "" {
return nil, trace.BadParameter("bot_name: must be non-empty")
}
- bot, err := bs.getBot(ctx, req.BotName)
+ bot, err := bs.getBot(ctx, req.GetBotName())
if err != nil {
return nil, trace.Wrap(err, "fetching bot")
}
ruleCtx.Resource153 = bot
if err := authCtx.CheckerContext.Decision(
- ctx, bot.Scope, func(checker *services.ScopedAccessChecker) error {
+ ctx, bot.GetScope(), func(checker *services.ScopedAccessChecker) error {
return checker.CheckAccessToRules(&ruleCtx, types.KindBot, types.VerbReadNoSecrets)
},
); err != nil {
// Return NotFound rather than Forbidden to avoid leaking existence of
// bot.
- return nil, trace.NotFound("bot %q not found", req.BotName)
+ return nil, trace.NotFound("bot %q not found", req.GetBotName())
}
return bot, nil
@@ -262,14 +262,14 @@ func (bs *BotService) ListBots(
// needing to iterate over all users here. This is currently a fairly
// expensive implementation.
bots := []*pb.Bot{}
- rsp, err := bs.cache.ListUsers(ctx, &userspb.ListUsersRequest{
- PageSize: req.PageSize,
- PageToken: req.PageToken,
- })
+ rsp, err := bs.cache.ListUsers(ctx, userspb.ListUsersRequest_builder{
+ PageSize: req.GetPageSize(),
+ PageToken: req.GetPageToken(),
+ }.Build())
if err != nil {
return nil, trace.Wrap(err, "listing users")
}
- for _, u := range rsp.Users {
+ for _, u := range rsp.GetUsers() {
botName, isBot := u.GetLabel(types.BotLabel)
if !isBot {
continue
@@ -316,7 +316,7 @@ func (bs *BotService) ListBots(
// Check if user can access this specific Bot.
ruleCtx := authCtx.RuleContext()
ruleCtx.Resource153 = bot
- if err := authCtx.CheckerContext.Decision(ctx, bot.Scope, func(checker *services.ScopedAccessChecker) error {
+ if err := authCtx.CheckerContext.Decision(ctx, bot.GetScope(), func(checker *services.ScopedAccessChecker) error {
return checker.CheckAccessToRules(&ruleCtx, types.KindBot, types.VerbList)
}); err != nil {
// Ignore resources the user cannot access.
@@ -326,10 +326,10 @@ func (bs *BotService) ListBots(
bots = append(bots, bot)
}
- return &pb.ListBotsResponse{
+ return pb.ListBotsResponse_builder{
Bots: bots,
- NextPageToken: rsp.NextPageToken,
- }, nil
+ NextPageToken: rsp.GetNextPageToken(),
+ }.Build(), nil
}
// CreateBot creates a new bot. It will throw an error if the bot already
@@ -337,7 +337,7 @@ func (bs *BotService) ListBots(
func (bs *BotService) CreateBot(
ctx context.Context, req *pb.CreateBotRequest,
) (*pb.Bot, error) {
- if err := setKindAndVersion(req.Bot); err != nil {
+ if err := setKindAndVersion(req.GetBot()); err != nil {
return nil, trace.Wrap(err, "setting kind and version")
}
authCtx, err := bs.scopedAuthorizer.AuthorizeScoped(ctx)
@@ -345,15 +345,15 @@ func (bs *BotService) CreateBot(
return nil, trace.Wrap(err)
}
- if err := StrongValidateBot(req.Bot); err != nil {
+ if err := StrongValidateBot(req.GetBot()); err != nil {
return nil, trace.Wrap(err, "validating bot")
}
// Validation comes before authz checks so we know that scope etc is
// well-formed.
ruleCtx := authCtx.RuleContext()
- ruleCtx.Resource153 = req.Bot
- if err := authCtx.CheckerContext.Decision(ctx, req.Bot.Scope, func(checker *services.ScopedAccessChecker) error {
+ ruleCtx.Resource153 = req.GetBot()
+ if err := authCtx.CheckerContext.Decision(ctx, req.GetBot().GetScope(), func(checker *services.ScopedAccessChecker) error {
return checker.CheckAccessToRules(&ruleCtx, types.KindBot, types.VerbCreate)
}); err != nil {
return nil, trace.Wrap(err)
@@ -367,13 +367,13 @@ func (bs *BotService) CreateBot(
}
var bot *pb.Bot
- if req.Bot.Scope != "" {
- bot, err = bs.createScopedBot(ctx, authCtx, req.Bot)
+ if req.GetBot().GetScope() != "" {
+ bot, err = bs.createScopedBot(ctx, authCtx, req.GetBot())
if err != nil {
return nil, trace.Wrap(err)
}
} else {
- bot, err = bs.createUnscopedBot(ctx, authCtx, req.Bot)
+ bot, err = bs.createUnscopedBot(ctx, authCtx, req.GetBot())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -381,10 +381,10 @@ func (bs *BotService) CreateBot(
bs.reporter.AnonymizeAndSubmit(&usagereporter.BotCreateEvent{
UserName: authz.ClientUsername(ctx),
- BotUserName: BotResourceName(bot.Metadata.Name),
- RoleName: BotResourceName(bot.Metadata.Name),
- BotName: bot.Metadata.Name,
- RoleCount: int64(len(bot.Spec.Roles)),
+ BotUserName: BotResourceName(bot.GetMetadata().GetName()),
+ RoleName: BotResourceName(bot.GetMetadata().GetName()),
+ BotName: bot.GetMetadata().GetName(),
+ RoleCount: int64(len(bot.GetSpec().GetRoles())),
})
if err := bs.emitter.EmitAuditEvent(ctx, &apievents.BotCreate{
Metadata: apievents.Metadata{
@@ -393,7 +393,7 @@ func (bs *BotService) CreateBot(
},
UserMetadata: authz.ClientUserMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: bot.Metadata.Name,
+ Name: bot.GetMetadata().GetName(),
},
}); err != nil {
bs.logger.WarnContext(
@@ -475,7 +475,7 @@ func UpsertBot(
createdBy string,
scopesFeatures scopes.Features,
) (*pb.Bot, error) {
- if bot.Scope != "" {
+ if bot.GetScope() != "" {
if err := scopesFeatures.AssertEnabled(); err != nil {
return nil, trace.Wrap(err)
}
@@ -487,7 +487,7 @@ func UpsertBot(
// Fetch pre-existing user, we'll use this to preserve generation and
// check for scope transitions.
existingUser, err := backend.GetUser(
- ctx, BotResourceName(bot.Metadata.Name), false,
+ ctx, BotResourceName(bot.GetMetadata().GetName()), false,
)
if err != nil && !trace.IsNotFound(err) {
// We'll happily ignore a not-found error, in this case, we have an
@@ -502,7 +502,7 @@ func UpsertBot(
// This restriction may be loosened in future if we evaluate pre-upsert
// and post-upsert scope authz.
existingScope, _ := existingUser.GetLabel(types.BotScopeLabel)
- if existingScope != bot.Scope {
+ if existingScope != bot.GetScope() {
return nil, trace.BadParameter(
"upserts cannot cause the scope of a bot to change, delete and recreate the bot to change its scope",
)
@@ -512,7 +512,7 @@ func UpsertBot(
// Create User (and maybe Role if unscoped) from the Bot.
var user types.User
var role types.Role
- if bot.Scope != "" {
+ if bot.GetScope() != "" {
user, err = scopedBotToUser(bot, now, createdBy)
if err != nil {
return nil, trace.Wrap(err, "converting scoped bot to user resource")
@@ -563,7 +563,7 @@ func UpsertBot(
// UpsertBot creates a new bot or forcefully updates an existing bot.
func (bs *BotService) UpsertBot(ctx context.Context, req *pb.UpsertBotRequest) (*pb.Bot, error) {
- if err := setKindAndVersion(req.Bot); err != nil {
+ if err := setKindAndVersion(req.GetBot()); err != nil {
return nil, trace.Wrap(err, "setting kind and version")
}
@@ -572,17 +572,17 @@ func (bs *BotService) UpsertBot(ctx context.Context, req *pb.UpsertBotRequest) (
return nil, trace.Wrap(err)
}
- if err := StrongValidateBot(req.Bot); err != nil {
+ if err := StrongValidateBot(req.GetBot()); err != nil {
return nil, trace.Wrap(err, "validating bot")
}
// Validation comes before authz checks so that we know scope (if present)
// is well-formed.
ruleCtx := authCtx.RuleContext()
- ruleCtx.Resource153 = req.Bot
+ ruleCtx.Resource153 = req.GetBot()
if err := authCtx.CheckerContext.Decision(
ctx,
- req.Bot.Scope,
+ req.GetBot().GetScope(),
func(checker *services.ScopedAccessChecker) error {
return checker.CheckAccessToRules(
&ruleCtx, types.KindBot, types.VerbCreate, types.VerbUpdate,
@@ -601,7 +601,7 @@ func (bs *BotService) UpsertBot(ctx context.Context, req *pb.UpsertBotRequest) (
}
bot, err := UpsertBot(
- ctx, bs.backend, req.Bot, bs.clock.Now(), authCtx.User.GetName(), bs.scopesFeatures,
+ ctx, bs.backend, req.GetBot(), bs.clock.Now(), authCtx.User.GetName(), bs.scopesFeatures,
)
if err != nil {
return nil, trace.Wrap(err)
@@ -609,10 +609,10 @@ func (bs *BotService) UpsertBot(ctx context.Context, req *pb.UpsertBotRequest) (
bs.reporter.AnonymizeAndSubmit(&usagereporter.BotCreateEvent{
UserName: authz.ClientUsername(ctx),
- BotUserName: BotResourceName(bot.Metadata.Name),
- RoleName: BotResourceName(bot.Metadata.Name),
- BotName: bot.Metadata.Name,
- RoleCount: int64(len(bot.Spec.Roles)),
+ BotUserName: BotResourceName(bot.GetMetadata().GetName()),
+ RoleName: BotResourceName(bot.GetMetadata().GetName()),
+ BotName: bot.GetMetadata().GetName(),
+ RoleCount: int64(len(bot.GetSpec().GetRoles())),
})
if err := bs.emitter.EmitAuditEvent(ctx, &apievents.BotCreate{
Metadata: apievents.Metadata{
@@ -621,7 +621,7 @@ func (bs *BotService) UpsertBot(ctx context.Context, req *pb.UpsertBotRequest) (
},
UserMetadata: authz.ClientUserMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: bot.Metadata.Name,
+ Name: bot.GetMetadata().GetName(),
},
}); err != nil {
bs.logger.WarnContext(
@@ -638,7 +638,7 @@ func (bs *BotService) UpsertBot(ctx context.Context, req *pb.UpsertBotRequest) (
func (bs *BotService) UpdateBot(
ctx context.Context, req *pb.UpdateBotRequest,
) (*pb.Bot, error) {
- if err := setKindAndVersion(req.Bot); err != nil {
+ if err := setKindAndVersion(req.GetBot()); err != nil {
return nil, trace.Wrap(err, "setting kind and version")
}
@@ -656,7 +656,7 @@ func (bs *BotService) UpdateBot(
}
if err := authCtx.CheckAccessToResource153(
- req.Bot,
+ req.GetBot(),
types.VerbUpdate,
); err != nil {
return nil, trace.Wrap(err)
@@ -666,62 +666,62 @@ func (bs *BotService) UpdateBot(
}
switch {
- case req.Bot == nil:
+ case !req.HasBot():
return nil, trace.BadParameter("bot: must be non-nil")
- case req.Bot.Metadata == nil:
+ case !req.GetBot().HasMetadata():
return nil, trace.BadParameter("bot.metadata: must be non-nil")
- case req.Bot.Metadata.Name == "":
+ case req.GetBot().GetMetadata().GetName() == "":
return nil, trace.BadParameter("bot.metadata.name: must be non-empty")
- case req.Bot.Spec == nil:
+ case !req.GetBot().HasSpec():
return nil, trace.BadParameter("bot.spec: must be non-nil")
- case req.UpdateMask == nil:
+ case !req.HasUpdateMask():
return nil, trace.BadParameter("update_mask: must be non-nil")
- case len(req.UpdateMask.Paths) == 0:
+ case len(req.GetUpdateMask().Paths) == 0:
return nil, trace.BadParameter("update_mask.paths: must be non-empty")
}
- user, err := bs.backend.GetUser(ctx, BotResourceName(req.Bot.Metadata.Name), false)
+ user, err := bs.backend.GetUser(ctx, BotResourceName(req.GetBot().GetMetadata().GetName()), false)
if err != nil {
return nil, trace.Wrap(err, "getting bot user")
}
if scope := user.GetMetadata().Labels[types.BotScopeLabel]; scope != "" {
return nil, trace.BadParameter("cannot update scoped bot")
}
- role, err := bs.backend.GetRole(ctx, BotResourceName(req.Bot.Metadata.Name))
+ role, err := bs.backend.GetRole(ctx, BotResourceName(req.GetBot().GetMetadata().GetName()))
if err != nil {
return nil, trace.Wrap(err, "getting bot role")
}
- for _, path := range req.UpdateMask.Paths {
+ for _, path := range req.GetUpdateMask().Paths {
switch path {
case "spec.roles":
- if slices.Contains(req.Bot.Spec.Roles, "") {
+ if slices.Contains(req.GetBot().GetSpec().GetRoles(), "") {
return nil, trace.BadParameter(
"spec.roles: must not contain empty strings",
)
}
role.SetImpersonateConditions(types.Allow, types.ImpersonateConditions{
- Roles: req.Bot.Spec.Roles,
+ Roles: req.GetBot().GetSpec().GetRoles(),
})
case "spec.traits":
traits := map[string][]string{}
- for _, t := range req.Bot.Spec.Traits {
- if len(t.Values) == 0 {
+ for _, t := range req.GetBot().GetSpec().GetTraits() {
+ if len(t.GetValues()) == 0 {
continue
}
- if traits[t.Name] == nil {
- traits[t.Name] = []string{}
+ if traits[t.GetName()] == nil {
+ traits[t.GetName()] = []string{}
}
- traits[t.Name] = append(traits[t.Name], t.Values...)
+ traits[t.GetName()] = append(traits[t.GetName()], t.GetValues()...)
}
user.SetTraits(traits)
case "spec.max_session_ttl":
opts := role.GetOptions()
- opts.MaxSessionTTL = types.Duration(req.Bot.Spec.MaxSessionTtl.AsDuration())
+ opts.MaxSessionTTL = types.Duration(req.GetBot().GetSpec().GetMaxSessionTtl().AsDuration())
role.SetOptions(opts)
case "metadata.description":
meta := user.GetMetadata()
- meta.Description = req.Bot.Metadata.Description
+ meta.Description = req.GetBot().GetMetadata().GetDescription()
user.SetMetadata(meta)
default:
return nil, trace.BadParameter("update_mask: unsupported path %q", path)
@@ -744,7 +744,7 @@ func (bs *BotService) UpdateBot(
},
UserMetadata: authz.ClientUserMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.Bot.Metadata.Name,
+ Name: req.GetBot().GetMetadata().GetName(),
},
}); err != nil {
bs.logger.WarnContext(
@@ -789,13 +789,13 @@ func (bs *BotService) deleteBotRole(ctx context.Context, botName string) error {
// dummyBotWithName returns a dummy bot with the given name. This is used
// for evaluating RBAC for the Delete RPC
func dummyBotWithName(name string) *pb.Bot {
- return &pb.Bot{
+ return pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
- },
- }
+ }.Build(),
+ }.Build()
}
// DeleteBot deletes an existing bot. It will throw an error if the bot does
@@ -812,7 +812,7 @@ func (bs *BotService) DeleteBot(
if err != nil {
return nil, trace.Wrap(err)
}
- if req.BotName == "" {
+ if req.GetBotName() == "" {
return nil, trace.BadParameter("bot_name: must be non-empty")
}
@@ -826,14 +826,14 @@ func (bs *BotService) DeleteBot(
// Fetch user to determine if bot is scoped or unscoped.
user, err := bs.backend.GetUser(
- ctx, BotResourceName(req.BotName), false,
+ ctx, BotResourceName(req.GetBotName()), false,
)
if err != nil {
return nil, trace.Wrap(err)
}
scope := user.GetMetadata().Labels[types.BotScopeLabel]
- ruleCtx.Resource153 = dummyBotWithName(req.BotName)
+ ruleCtx.Resource153 = dummyBotWithName(req.GetBotName())
if err := authCtx.CheckerContext.Decision(ctx, scope, func(checker *services.ScopedAccessChecker) error {
return checker.CheckAccessToRules(&ruleCtx, types.KindBot, types.VerbDelete)
}); err != nil {
@@ -847,11 +847,11 @@ func (bs *BotService) DeleteBot(
}
}
- userErr := bs.deleteBotUser(ctx, req.BotName, user)
+ userErr := bs.deleteBotUser(ctx, req.GetBotName(), user)
var roleErr error
if scope == "" {
// Only unscoped bots have a Bot role for us to delete.
- roleErr = bs.deleteBotRole(ctx, req.BotName)
+ roleErr = bs.deleteBotRole(ctx, req.GetBotName())
}
err = trace.NewAggregate(
trace.Wrap(userErr, "deleting bot user"),
@@ -868,7 +868,7 @@ func (bs *BotService) DeleteBot(
},
UserMetadata: authz.ClientUserMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.BotName,
+ Name: req.GetBotName(),
},
}); err != nil {
bs.logger.WarnContext(
@@ -892,11 +892,11 @@ func setKindAndVersion(b *pb.Bot) error {
if b == nil {
return trace.BadParameter("bot: must be non-nil")
}
- if b.Kind == "" {
- b.Kind = types.KindBot
+ if b.GetKind() == "" {
+ b.SetKind(types.KindBot)
}
- if b.Version == "" {
- b.Version = types.V1
+ if b.GetVersion() == "" {
+ b.SetVersion(types.V1)
}
return nil
}
@@ -908,34 +908,34 @@ func StrongValidateBot(b *pb.Bot) error {
if b == nil {
return trace.BadParameter("must be non-nil")
}
- if b.Metadata == nil {
+ if !b.HasMetadata() {
return trace.BadParameter("metadata: must be non-nil")
}
- if b.Metadata.Name == "" {
+ if b.GetMetadata().GetName() == "" {
return trace.BadParameter("metadata.name: must be non-empty")
}
- if b.Spec == nil {
+ if !b.HasSpec() {
return trace.BadParameter("spec: must be non-nil")
}
- if slices.Contains(b.Spec.Roles, "") {
+ if slices.Contains(b.GetSpec().GetRoles(), "") {
return trace.BadParameter("spec.roles: must not contain empty strings")
}
// Scoped bot only validation
- if b.Scope != "" {
+ if b.GetScope() != "" {
// Validate scope-specific fields
- if err := scopes.StrongValidate(b.Scope); err != nil {
+ if err := scopes.StrongValidate(b.GetScope()); err != nil {
return trace.Wrap(err, "scope:")
}
// Validate unsupported fields aren't set.
- if len(b.Spec.Roles) > 0 {
+ if len(b.GetSpec().GetRoles()) > 0 {
return trace.BadParameter("spec.roles: cannot be set on scoped bot")
}
- if b.Spec.MaxSessionTtl.AsDuration() != 0 {
+ if b.GetSpec().GetMaxSessionTtl().AsDuration() != 0 {
return trace.BadParameter("spec.max_session_ttl: cannot be set on scoped bot")
}
- if len(b.Spec.Traits) > 0 {
+ if len(b.GetSpec().GetTraits()) > 0 {
return trace.BadParameter("spec.traits: cannot be set on scoped bot")
}
}
@@ -970,33 +970,33 @@ func botFromUserAndRole(user types.User, role types.Role) (*pb.Bot, error) {
return nil, trace.BadParameter("botFromUserAndRole called on user with scope label")
}
- b := &pb.Bot{
+ b := pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: botName,
Expires: botExpiryFromUser(user),
Description: user.GetMetadata().Description,
- },
- Status: &pb.BotStatus{
+ }.Build(),
+ Status: pb.BotStatus_builder{
UserName: user.GetName(),
RoleName: role.GetName(),
- },
- Spec: &pb.BotSpec{
+ }.Build(),
+ Spec: pb.BotSpec_builder{
Roles: role.GetImpersonateConditions(types.Allow).Roles,
MaxSessionTtl: durationpb.New(role.GetOptions().MaxSessionTTL.Duration()),
- },
- }
+ }.Build(),
+ }.Build()
// Copy in labels from the user
- b.Metadata.Labels = map[string]string{}
+ b.GetMetadata().SetLabels(map[string]string{})
for k, v := range user.GetMetadata().Labels {
// We exclude the labels that are implicitly added to the user by the
// bot service.
if nonPropagatedLabels.Contains(k) {
continue
}
- b.Metadata.Labels[k] = v
+ b.GetMetadata().GetLabels()[k] = v
}
// Copy in traits
@@ -1004,10 +1004,10 @@ func botFromUserAndRole(user types.User, role types.Role) (*pb.Bot, error) {
if len(v) == 0 {
continue
}
- b.Spec.Traits = append(b.Spec.Traits, &pb.Trait{
+ b.GetSpec().SetTraits(append(b.GetSpec().GetTraits(), pb.Trait_builder{
Name: k,
Values: v,
- })
+ }.Build()))
}
return b, nil
@@ -1024,48 +1024,48 @@ func scopedBotFromUser(user types.User) (*pb.Bot, error) {
return nil, trace.BadParameter("scopedBotFromUser called on user without scope label")
}
- b := &pb.Bot{
+ b := pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
Scope: scope,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: botName,
Expires: botExpiryFromUser(user),
Description: user.GetMetadata().Description,
- },
- Status: &pb.BotStatus{
+ }.Build(),
+ Status: pb.BotStatus_builder{
UserName: user.GetName(),
- },
+ }.Build(),
Spec: &pb.BotSpec{},
- }
+ }.Build()
// Copy in labels from the user
- b.Metadata.Labels = map[string]string{}
+ b.GetMetadata().SetLabels(map[string]string{})
for k, v := range user.GetMetadata().Labels {
// We exclude the labels that are implicitly added to the user by the
// bot service.
if nonPropagatedLabels.Contains(k) {
continue
}
- b.Metadata.Labels[k] = v
+ b.GetMetadata().GetLabels()[k] = v
}
return b, nil
}
func botToUserAndRole(bot *pb.Bot, now time.Time, createdBy string) (types.User, types.Role, error) {
- if bot.Scope != "" {
+ if bot.GetScope() != "" {
return nil, nil, trace.BadParameter("botToUserAndRole called on scoped bot")
}
// Setup role
- resourceName := BotResourceName(bot.Metadata.Name)
+ resourceName := BotResourceName(bot.GetMetadata().GetName())
// Continue to use the legacy max session TTL (12 hours) as the default, but
// allow overrides via the optional bot spec field.
maxSessionTTL := defaults.DefaultBotMaxSessionTTL
- if bot.Spec.MaxSessionTtl != nil {
- maxSessionTTL = bot.Spec.MaxSessionTtl.AsDuration()
+ if bot.GetSpec().HasMaxSessionTtl() {
+ maxSessionTTL = bot.GetSpec().GetMaxSessionTtl().AsDuration()
}
role, err := types.NewRole(resourceName, types.RoleSpecV6{
@@ -1078,7 +1078,7 @@ func botToUserAndRole(bot *pb.Bot, now time.Time, createdBy string) (types.User,
types.NewRule(types.KindCertAuthority, []string{types.VerbReadNoSecrets}),
},
Impersonate: &types.ImpersonateConditions{
- Roles: bot.Spec.Roles,
+ Roles: bot.GetSpec().GetRoles(),
},
},
})
@@ -1087,10 +1087,10 @@ func botToUserAndRole(bot *pb.Bot, now time.Time, createdBy string) (types.User,
}
roleMeta := role.GetMetadata()
roleMeta.Description = fmt.Sprintf(
- "Automatically generated role for bot %s", bot.Metadata.Name,
+ "Automatically generated role for bot %s", bot.GetMetadata().GetName(),
)
roleMeta.Labels = map[string]string{
- types.BotLabel: bot.Metadata.Name,
+ types.BotLabel: bot.GetMetadata().GetName(),
}
roleMeta.Expires = userAndRoleExpiryFromBot(bot)
role.SetMetadata(roleMeta)
@@ -1105,10 +1105,10 @@ func botToUserAndRole(bot *pb.Bot, now time.Time, createdBy string) (types.User,
// First copy in the labels from the Bot resource
userMeta.Labels = map[string]string{}
- maps.Copy(userMeta.Labels, bot.Metadata.Labels)
+ maps.Copy(userMeta.Labels, bot.GetMetadata().GetLabels())
// Then set these labels over the top - we exclude these when converting
// back.
- userMeta.Labels[types.BotLabel] = bot.Metadata.Name
+ userMeta.Labels[types.BotLabel] = bot.GetMetadata().GetName()
// We always set this to zero here - but in Upsert, we copy from the
// previous user before writing if necessary
userMeta.Labels[types.BotGenerationLabel] = "0"
@@ -1117,18 +1117,18 @@ func botToUserAndRole(bot *pb.Bot, now time.Time, createdBy string) (types.User,
userMeta.Expires = userAndRoleExpiryFromBot(bot)
// We track the Bot description within the User description field because
// the Role description already has a message.
- userMeta.Description = bot.Metadata.Description
+ userMeta.Description = bot.GetMetadata().GetDescription()
user.SetMetadata(userMeta)
traits := map[string][]string{}
- for _, t := range bot.Spec.Traits {
- if len(t.Values) == 0 {
+ for _, t := range bot.GetSpec().GetTraits() {
+ if len(t.GetValues()) == 0 {
continue
}
- if traits[t.Name] == nil {
- traits[t.Name] = []string{}
+ if traits[t.GetName()] == nil {
+ traits[t.GetName()] = []string{}
}
- traits[t.Name] = append(traits[t.Name], t.Values...)
+ traits[t.GetName()] = append(traits[t.GetName()], t.GetValues()...)
}
user.SetTraits(traits)
user.SetCreatedBy(types.CreatedBy{
@@ -1140,12 +1140,12 @@ func botToUserAndRole(bot *pb.Bot, now time.Time, createdBy string) (types.User,
}
func scopedBotToUser(bot *pb.Bot, now time.Time, createdBy string) (types.User, error) {
- if bot.Scope == "" {
+ if bot.GetScope() == "" {
return nil, trace.BadParameter("scopedBotToUser called on unscoped bot")
}
// Setup user
- user, err := types.NewUser(BotResourceName(bot.Metadata.Name))
+ user, err := types.NewUser(BotResourceName(bot.GetMetadata().GetName()))
if err != nil {
return nil, trace.Wrap(err, "new user")
}
@@ -1153,18 +1153,18 @@ func scopedBotToUser(bot *pb.Bot, now time.Time, createdBy string) (types.User,
// First copy in the labels from the Bot resource
userMeta.Labels = map[string]string{}
- maps.Copy(userMeta.Labels, bot.Metadata.Labels)
+ maps.Copy(userMeta.Labels, bot.GetMetadata().GetLabels())
// Then set these labels over the top - we exclude these when converting
// back.
- userMeta.Labels[types.BotLabel] = bot.Metadata.Name
+ userMeta.Labels[types.BotLabel] = bot.GetMetadata().GetName()
// We always set this to zero here - but in Upsert, we copy from the
// previous user before writing if necessary
userMeta.Labels[types.BotGenerationLabel] = "0"
- userMeta.Labels[types.BotScopeLabel] = bot.Scope
+ userMeta.Labels[types.BotScopeLabel] = bot.GetScope()
userMeta.Expires = userAndRoleExpiryFromBot(bot)
// We track the Bot description within the User description field because
// the Role description already has a message.
- userMeta.Description = bot.Metadata.Description
+ userMeta.Description = bot.GetMetadata().GetDescription()
user.SetMetadata(userMeta)
user.SetCreatedBy(types.CreatedBy{
@@ -1176,11 +1176,11 @@ func scopedBotToUser(bot *pb.Bot, now time.Time, createdBy string) (types.User,
}
func userAndRoleExpiryFromBot(bot *pb.Bot) *time.Time {
- if bot.Metadata.GetExpires() == nil {
+ if bot.GetMetadata().GetExpires() == nil {
return nil
}
- expiry := bot.Metadata.GetExpires().AsTime()
+ expiry := bot.GetMetadata().GetExpires().AsTime()
if expiry.IsZero() || expiry.Unix() == 0 {
return nil
}
diff --git a/lib/auth/machineid/machineidv1/expression/expression_test.go b/lib/auth/machineid/machineidv1/expression/expression_test.go
index 44a64da4075..53831726184 100644
--- a/lib/auth/machineid/machineidv1/expression/expression_test.go
+++ b/lib/auth/machineid/machineidv1/expression/expression_test.go
@@ -32,24 +32,24 @@ func TestBotInstanceExpressionParser(t *testing.T) {
makeBaseEnv := func() Environment {
return Environment{
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-bot-1/76efb07a-3077-471c-988a-54d0fa49fc71",
- },
- Spec: &machineidv1.BotInstanceSpec{
+ }.Build(),
+ Spec: machineidv1.BotInstanceSpec_builder{
BotName: "test-bot-1",
InstanceId: "76efb07a-3077-471c-988a-54d0fa49fc71",
- },
- LatestAuthentication: &machineidv1.BotInstanceStatusAuthentication{
+ }.Build(),
+ LatestAuthentication: machineidv1.BotInstanceStatusAuthentication_builder{
JoinMethod: "kubernetes",
- },
- LatestHeartbeat: &machineidv1.BotInstanceStatusHeartbeat{
+ }.Build(),
+ LatestHeartbeat: machineidv1.BotInstanceStatusHeartbeat_builder{
IsStartup: false,
Version: "19.0.1",
OneShot: false,
Architecture: "arm64",
Os: "linux",
Hostname: "test-hostname-1",
- },
+ }.Build(),
}
}
@@ -100,9 +100,9 @@ func TestBotInstanceExpressionParser(t *testing.T) {
expFalse: `!status.latest_heartbeat.one_shot`,
envFns: []func(*Environment){
func(e *Environment) {
- e.LatestHeartbeat = &machineidv1.BotInstanceStatusHeartbeat{
+ e.LatestHeartbeat = machineidv1.BotInstanceStatusHeartbeat_builder{
OneShot: true,
- }
+ }.Build()
},
},
},
diff --git a/lib/auth/machineid/machineidv1/machineidv1_test.go b/lib/auth/machineid/machineidv1/machineidv1_test.go
index 8d34100f8d6..6fda0923c5b 100644
--- a/lib/auth/machineid/machineidv1/machineidv1_test.go
+++ b/lib/auth/machineid/machineidv1/machineidv1_test.go
@@ -120,65 +120,65 @@ func TestCreateBot(t *testing.T) {
require.NoError(t, err)
preExistingBot, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
expiry := time.Now().Add(time.Hour)
scopedSvc := client.ScopedAccessServiceClient()
- scopedRole, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ scopedRole, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-creator",
- },
+ }.Build(),
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/scopes/granted", "/scopes/ungranted"},
Rules: []*scopedaccessv1.ScopedRule{
- {
+ scopedaccessv1.ScopedRule_builder{
Verbs: []string{types.VerbCreate},
Resources: []string{types.KindBot},
- },
+ }.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
scopedUser, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user")
require.NoError(t, err)
// Create scoped role assignments linking users to scoped roles.
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/granted"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/granted"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp)
@@ -195,11 +195,11 @@ func TestCreateBot(t *testing.T) {
{
name: "success",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "success",
Labels: map[string]string{
"my-label": "my-value",
@@ -209,52 +209,52 @@ func TestCreateBot(t *testing.T) {
types.BotScopeLabel: "/please-unset-me",
},
Description: "Property of US Robotics and Mechanical Men.",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
- {
+ }.Build(),
+ machineidv1pb.Trait_builder{
Name: constants.TraitKubeUsers,
Values: []string{},
- },
+ }.Build(),
},
// Note: Deliberately omitting MaxSessionTtl here to verify
// the default value.
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "success",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
Description: "Property of US Robotics and Mechanical Men.",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
+ }.Build(),
},
MaxSessionTtl: durationpb.New(libdefaults.DefaultBotMaxSessionTTL),
- },
- Status: &machineidv1pb.BotStatus{
+ }.Build(),
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-success",
RoleName: "bot-success",
- },
- },
+ }.Build(),
+ }.Build(),
wantUser: &types.UserV2{
Kind: types.KindUser,
Version: types.V2,
@@ -314,63 +314,63 @@ func TestCreateBot(t *testing.T) {
{
name: "success with expiry",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "success-with-expiry",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
Expires: timestamppb.New(expiry),
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
- {
+ }.Build(),
+ machineidv1pb.Trait_builder{
Name: constants.TraitKubeUsers,
Values: []string{},
- },
+ }.Build(),
},
// Note: Deliberately omitting MaxSessionTtl here to
// validate the default value.
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "success-with-expiry",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
Expires: timestamppb.New(expiry),
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
+ }.Build(),
},
MaxSessionTtl: durationpb.New(libdefaults.DefaultBotMaxSessionTTL),
- },
- Status: &machineidv1pb.BotStatus{
+ }.Build(),
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-success-with-expiry",
RoleName: "bot-success-with-expiry",
- },
- },
+ }.Build(),
+ }.Build(),
wantUser: &types.UserV2{
Kind: types.KindUser,
Version: types.V2,
@@ -431,59 +431,59 @@ func TestCreateBot(t *testing.T) {
{
name: "success with max ttl",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "success-with-max-ttl",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
Expires: timestamppb.New(expiry),
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
- {
+ }.Build(),
+ machineidv1pb.Trait_builder{
Name: constants.TraitKubeUsers,
Values: []string{},
- },
+ }.Build(),
},
MaxSessionTtl: durationpb.New(libdefaults.MaxRenewableCertTTL),
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "success-with-max-ttl",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
Expires: timestamppb.New(expiry),
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
+ }.Build(),
},
MaxSessionTtl: durationpb.New(libdefaults.MaxRenewableCertTTL),
- },
- Status: &machineidv1pb.BotStatus{
+ }.Build(),
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-success-with-max-ttl",
RoleName: "bot-success-with-max-ttl",
- },
- },
+ }.Build(),
+ }.Build(),
wantRole: &types.RoleV6{
Kind: types.KindRole,
Version: types.V8,
@@ -517,43 +517,43 @@ func TestCreateBot(t *testing.T) {
{
name: "success with where on name",
identity: authtest.TestUser(botCreatorWhere.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "foo-xyzzy",
Labels: map[string]string{},
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
},
{
name: "failure with where on name",
identity: authtest.TestUser(botCreatorWhere.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "bar-xyzzy",
Labels: map[string]string{},
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: require.Error,
},
{
name: "bot already exists",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
+ req: machineidv1pb.CreateBotRequest_builder{
Bot: preExistingBot,
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAlreadyExists(err), "error should be already exists")
@@ -562,9 +562,9 @@ func TestCreateBot(t *testing.T) {
{
name: "no permissions",
identity: authtest.TestUser(unprivilegedUser.GetName()),
- req: &machineidv1pb.CreateBotRequest{
+ req: machineidv1pb.CreateBotRequest_builder{
Bot: preExistingBot,
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
@@ -573,9 +573,9 @@ func TestCreateBot(t *testing.T) {
{
name: "validation - nil bot",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
+ req: machineidv1pb.CreateBotRequest_builder{
Bot: nil,
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "must be non-nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -584,16 +584,16 @@ func TestCreateBot(t *testing.T) {
{
name: "validation - nil metadata",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
Metadata: nil,
- Spec: &machineidv1pb.BotSpec{
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "must be non-nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -602,16 +602,16 @@ func TestCreateBot(t *testing.T) {
{
name: "validation - no name",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
Metadata: &headerv1.Metadata{},
- Spec: &machineidv1pb.BotSpec{
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "must be non-empty")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -620,16 +620,16 @@ func TestCreateBot(t *testing.T) {
{
name: "validation - nil spec",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "terminator",
- },
+ }.Build(),
Spec: nil,
- },
- },
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "spec: must be non-nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -638,19 +638,19 @@ func TestCreateBot(t *testing.T) {
{
name: "validation - empty role",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "empty-string-role",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"foo", "", "bar"},
Traits: []*machineidv1pb.Trait{},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "spec.roles: must not contain empty strings")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -659,67 +659,67 @@ func TestCreateBot(t *testing.T) {
{
name: "scoped identity creates scoped bot",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-success",
- },
+ }.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- },
- },
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-success",
- },
+ }.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- Status: &machineidv1pb.BotStatus{
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-scoped-bot-success",
- },
- },
+ }.Build(),
+ }.Build(),
},
{
name: "unscoped identity creates scoped bot",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-from-unscoped",
- },
+ }.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- },
- },
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-from-unscoped",
- },
+ }.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- Status: &machineidv1pb.BotStatus{
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-scoped-bot-from-unscoped",
- },
- },
+ }.Build(),
+ }.Build(),
},
{
name: "scoped identity wrong scope",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-denied",
- },
+ }.Build(),
Scope: "/scopes/ungranted",
Spec: &machineidv1pb.BotSpec{},
- },
- },
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "expected access denied, got: %v", err)
},
@@ -727,16 +727,16 @@ func TestCreateBot(t *testing.T) {
{
name: "scoped identity cannot create unscoped bot",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "unscoped-from-scoped",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "expected access denied, got: %v", err)
},
@@ -804,31 +804,31 @@ func TestUpdateBot(t *testing.T) {
// Create a pre-existing bot so we can check you can update an existing bot.
client, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- preExistingBot, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ preExistingBot, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing",
Description: "before",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{beforeRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"before"},
- },
+ }.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// We find the user associated with the Bot and set the generation label. This allows us to ensure that the
// generation label is preserved when UpsertBot is called.
{
- preExistingBotUser, err := srv.Auth().GetUser(ctx, preExistingBot.Status.UserName, false)
+ preExistingBotUser, err := srv.Auth().GetUser(ctx, preExistingBot.GetStatus().GetUserName(), false)
require.NoError(t, err)
meta := preExistingBotUser.GetMetadata()
meta.Labels[types.BotGenerationLabel] = "1337"
@@ -850,79 +850,79 @@ func TestUpdateBot(t *testing.T) {
{
name: "success",
user: botUpdaterUser.GetName(),
- req: &machineidv1pb.UpdateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpdateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
- Name: preExistingBot.Metadata.Name,
+ Metadata: headerv1.Metadata_builder{
+ Name: preExistingBot.GetMetadata().GetName(),
Description: "after",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{afterRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"after"},
- },
- {
+ }.Build(),
+ machineidv1pb.Trait_builder{
Name: constants.TraitKubeUsers,
Values: []string{
"after",
},
- },
+ }.Build(),
},
MaxSessionTtl: durationpb.New(libdefaults.MaxRenewableCertTTL),
- },
- },
+ }.Build(),
+ }.Build(),
UpdateMask: &fieldmaskpb.FieldMask{
Paths: []string{"spec.roles", "spec.traits", "spec.max_session_ttl", "metadata.description"},
},
- },
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
- Name: preExistingBot.Metadata.Name,
+ Metadata: headerv1.Metadata_builder{
+ Name: preExistingBot.GetMetadata().GetName(),
Description: "after",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{afterRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"after"},
- },
- {
+ }.Build(),
+ machineidv1pb.Trait_builder{
Name: constants.TraitKubeUsers,
Values: []string{
"after",
},
- },
+ }.Build(),
},
MaxSessionTtl: durationpb.New(libdefaults.MaxRenewableCertTTL),
- },
- Status: &machineidv1pb.BotStatus{
- UserName: preExistingBot.Status.UserName,
- RoleName: preExistingBot.Status.RoleName,
- },
- },
+ }.Build(),
+ Status: machineidv1pb.BotStatus_builder{
+ UserName: preExistingBot.GetStatus().GetUserName(),
+ RoleName: preExistingBot.GetStatus().GetRoleName(),
+ }.Build(),
+ }.Build(),
wantUser: &types.UserV2{
Kind: types.KindUser,
Version: types.V2,
Metadata: types.Metadata{
- Name: preExistingBot.Status.UserName,
+ Name: preExistingBot.GetStatus().GetUserName(),
Description: "after",
Namespace: defaults.Namespace,
Labels: map[string]string{
- types.BotLabel: preExistingBot.Metadata.Name,
+ types.BotLabel: preExistingBot.GetMetadata().GetName(),
types.BotGenerationLabel: "1337",
},
},
Spec: types.UserSpecV2{
- Roles: []string{preExistingBot.Status.RoleName},
+ Roles: []string{preExistingBot.GetStatus().GetRoleName()},
Traits: map[string][]string{
constants.TraitLogins: {"after"},
constants.TraitKubeUsers: {"after"},
@@ -941,10 +941,10 @@ func TestUpdateBot(t *testing.T) {
Kind: types.KindRole,
Version: types.V8,
Metadata: types.Metadata{
- Name: preExistingBot.Status.RoleName,
+ Name: preExistingBot.GetStatus().GetRoleName(),
Namespace: defaults.Namespace,
Labels: map[string]string{
- types.BotLabel: preExistingBot.Metadata.Name,
+ types.BotLabel: preExistingBot.GetMetadata().GetName(),
},
Description: "Automatically generated role for bot pre-existing",
},
@@ -966,19 +966,19 @@ func TestUpdateBot(t *testing.T) {
{
name: "no permissions",
user: unprivilegedUser.GetName(),
- req: &machineidv1pb.UpdateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpdateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "valid-bot",
- Description: preExistingBot.Metadata.Description,
- },
- Spec: &machineidv1pb.BotSpec{
+ Description: preExistingBot.GetMetadata().GetDescription(),
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{beforeRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -986,12 +986,12 @@ func TestUpdateBot(t *testing.T) {
{
name: "validation - nil bot",
user: botUpdaterUser.GetName(),
- req: &machineidv1pb.UpdateBotRequest{
+ req: machineidv1pb.UpdateBotRequest_builder{
Bot: nil,
UpdateMask: &fieldmaskpb.FieldMask{
Paths: []string{"spec.roles"},
},
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "bot: must be non-nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1000,20 +1000,20 @@ func TestUpdateBot(t *testing.T) {
{
name: "validation - nil bot spec",
user: botUpdaterUser.GetName(),
- req: &machineidv1pb.UpdateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpdateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "bernard-lowe",
Description: "before",
- },
+ }.Build(),
Spec: nil,
- },
+ }.Build(),
UpdateMask: &fieldmaskpb.FieldMask{
Paths: []string{"spec.roles"},
},
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "bot.spec: must be non-nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1022,18 +1022,18 @@ func TestUpdateBot(t *testing.T) {
{
name: "validation - nil metadata",
user: botUpdaterUser.GetName(),
- req: &machineidv1pb.UpdateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpdateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Spec: &machineidv1pb.BotSpec{
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{beforeRole.GetName()},
- },
- },
+ }.Build(),
+ }.Build(),
UpdateMask: &fieldmaskpb.FieldMask{
Paths: []string{"spec.roles"},
},
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "bot.metadata: must be non-nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1042,22 +1042,22 @@ func TestUpdateBot(t *testing.T) {
{
name: "validation - no name",
user: botUpdaterUser.GetName(),
- req: &machineidv1pb.UpdateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpdateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "",
- Description: preExistingBot.Metadata.Description,
- },
- Spec: &machineidv1pb.BotSpec{
+ Description: preExistingBot.GetMetadata().GetDescription(),
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{beforeRole.GetName()},
- },
- },
+ }.Build(),
+ }.Build(),
UpdateMask: &fieldmaskpb.FieldMask{
Paths: []string{"spec.roles"},
},
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "bot.metadata.name: must be non-empty")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1066,20 +1066,20 @@ func TestUpdateBot(t *testing.T) {
{
name: "validation - no update mask",
user: botUpdaterUser.GetName(),
- req: &machineidv1pb.UpdateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpdateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "foo",
Description: "before",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{beforeRole.GetName()},
- },
- },
+ }.Build(),
+ }.Build(),
UpdateMask: nil,
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "update_mask: must be non-nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1088,22 +1088,22 @@ func TestUpdateBot(t *testing.T) {
{
name: "validation - no update mask paths",
user: botUpdaterUser.GetName(),
- req: &machineidv1pb.UpdateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpdateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "foo",
- Description: preExistingBot.Metadata.Description,
- },
- Spec: &machineidv1pb.BotSpec{
+ Description: preExistingBot.GetMetadata().GetDescription(),
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{beforeRole.GetName()},
- },
- },
+ }.Build(),
+ }.Build(),
UpdateMask: &fieldmaskpb.FieldMask{
Paths: []string{},
},
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "update_mask.paths: must be non-empty")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1112,23 +1112,23 @@ func TestUpdateBot(t *testing.T) {
{
name: "validation - empty string role",
user: botUpdaterUser.GetName(),
- req: &machineidv1pb.UpdateBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpdateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
- Name: preExistingBot.Metadata.Name,
- Description: preExistingBot.Metadata.Description,
- },
- Spec: &machineidv1pb.BotSpec{
+ Metadata: headerv1.Metadata_builder{
+ Name: preExistingBot.GetMetadata().GetName(),
+ Description: preExistingBot.GetMetadata().GetDescription(),
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"foo", "", "bar"},
Traits: []*machineidv1pb.Trait{},
- },
- },
+ }.Build(),
+ }.Build(),
UpdateMask: &fieldmaskpb.FieldMask{
Paths: []string{"spec.roles"},
},
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "spec.roles: must not contain empty strings")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1213,29 +1213,29 @@ func TestUpsertBot(t *testing.T) {
// Create a pre-existing bot so we can check you can upsert over an existing bot.
client, err := srv.NewClient(authtest.TestAdmin())
require.NoError(t, err)
- preExistingBot, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ preExistingBot, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
expiry := time.Now().Add(time.Hour)
// We find the user associated with the Bot and set the generation label. This allows us to ensure that the
// generation label is preserved when UpsertBot is called.
{
- preExistingBotUser, err := srv.Auth().GetUser(ctx, preExistingBot.Status.UserName, false)
+ preExistingBotUser, err := srv.Auth().GetUser(ctx, preExistingBot.GetStatus().GetUserName(), false)
require.NoError(t, err)
meta := preExistingBotUser.GetMetadata()
meta.Labels[types.BotGenerationLabel] = "1337"
@@ -1246,58 +1246,58 @@ func TestUpsertBot(t *testing.T) {
// Scoped identity setup.
scopedSvc := client.ScopedAccessServiceClient()
- scopedRole, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ scopedRole, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-upserter",
- },
+ }.Build(),
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/scopes/granted", "/scopes/ungranted"},
Rules: []*scopedaccessv1.ScopedRule{
- {
+ scopedaccessv1.ScopedRule_builder{
Verbs: []string{types.VerbCreate, types.VerbUpdate},
Resources: []string{types.KindBot},
- },
+ }.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
scopedUser, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user")
require.NoError(t, err)
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/granted"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/granted"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp)
// Pre-existing scoped bot for scope-transition tests.
- _, err = client.BotServiceClient().UpsertBot(ctx, &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{Name: "scope-change-test"},
+ _, err = client.BotServiceClient().UpsertBot(ctx, machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{Name: "scope-change-test"}.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -1313,55 +1313,55 @@ func TestUpsertBot(t *testing.T) {
{
name: "new",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "new",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "new",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
+ }.Build(),
},
MaxSessionTtl: durationpb.New(libdefaults.DefaultBotMaxSessionTTL),
- },
- Status: &machineidv1pb.BotStatus{
+ }.Build(),
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-new",
RoleName: "bot-new",
- },
- },
+ }.Build(),
+ }.Build(),
wantUser: &types.UserV2{
Kind: types.KindUser,
Version: types.V2,
@@ -1414,57 +1414,57 @@ func TestUpsertBot(t *testing.T) {
{
name: "new with expiry",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "new-with-expiry",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
Expires: timestamppb.New(expiry),
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "new-with-expiry",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
Expires: timestamppb.New(expiry),
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
Traits: []*machineidv1pb.Trait{
- {
+ machineidv1pb.Trait_builder{
Name: constants.TraitLogins,
Values: []string{"root"},
- },
+ }.Build(),
},
MaxSessionTtl: durationpb.New(libdefaults.DefaultBotMaxSessionTTL),
- },
- Status: &machineidv1pb.BotStatus{
+ }.Build(),
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-new-with-expiry",
RoleName: "bot-new-with-expiry",
- },
- },
+ }.Build(),
+ }.Build(),
wantUser: &types.UserV2{
Kind: types.KindUser,
Version: types.V2,
@@ -1519,9 +1519,9 @@ func TestUpsertBot(t *testing.T) {
{
name: "already exists",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
+ req: machineidv1pb.UpsertBotRequest_builder{
Bot: preExistingBot,
- },
+ }.Build(),
assertError: require.NoError,
want: preExistingBot,
@@ -1578,42 +1578,42 @@ func TestUpsertBot(t *testing.T) {
{
name: "already exists with max session ttl",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
MaxSessionTtl: durationpb.New(libdefaults.MaxRenewableCertTTL),
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
MaxSessionTtl: durationpb.New(libdefaults.MaxRenewableCertTTL),
- },
- Status: &machineidv1pb.BotStatus{
+ }.Build(),
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-pre-existing",
RoleName: "bot-pre-existing",
- },
- },
+ }.Build(),
+ }.Build(),
wantUser: &types.UserV2{
Kind: types.KindUser,
Version: types.V2,
@@ -1667,35 +1667,35 @@ func TestUpsertBot(t *testing.T) {
{
name: "new with where",
identity: authtest.TestUser(botWhereCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "foo-new",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
},
{
name: "failed new with where",
identity: authtest.TestUser(botWhereCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "not-foo-new",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -1703,18 +1703,18 @@ func TestUpsertBot(t *testing.T) {
{
name: "no permissions",
identity: authtest.TestUser(unprivilegedUser.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "not-foo-new",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
@@ -1723,9 +1723,9 @@ func TestUpsertBot(t *testing.T) {
{
name: "validation - nil bot",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
+ req: machineidv1pb.UpsertBotRequest_builder{
Bot: nil,
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "must be non-nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1734,16 +1734,16 @@ func TestUpsertBot(t *testing.T) {
{
name: "validation - nil metadata",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
Metadata: nil,
- Spec: &machineidv1pb.BotSpec{
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "must be non-nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1752,16 +1752,16 @@ func TestUpsertBot(t *testing.T) {
{
name: "validation - no name",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
Metadata: &headerv1.Metadata{},
- Spec: &machineidv1pb.BotSpec{
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "must be non-empty")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1770,19 +1770,19 @@ func TestUpsertBot(t *testing.T) {
{
name: "validation - empty role",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "empty-string-role",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"foo", "", "bar"},
Traits: []*machineidv1pb.Trait{},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "spec.roles: must not contain empty strings")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -1791,67 +1791,67 @@ func TestUpsertBot(t *testing.T) {
{
name: "scoped identity upserts scoped bot",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-upsert-success",
- },
+ }.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- },
- },
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-upsert-success",
- },
+ }.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- Status: &machineidv1pb.BotStatus{
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-scoped-upsert-success",
- },
- },
+ }.Build(),
+ }.Build(),
},
{
name: "unscoped identity upserts scoped bot",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-upsert-from-unscoped",
- },
+ }.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- },
- },
+ }.Build(),
+ }.Build(),
assertError: require.NoError,
- want: &machineidv1pb.Bot{
+ want: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-upsert-from-unscoped",
- },
+ }.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- Status: &machineidv1pb.BotStatus{
+ Status: machineidv1pb.BotStatus_builder{
UserName: "bot-scoped-upsert-from-unscoped",
- },
- },
+ }.Build(),
+ }.Build(),
},
{
name: "scoped identity wrong scope",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-upsert-denied",
- },
+ }.Build(),
Scope: "/scopes/ungranted",
Spec: &machineidv1pb.BotSpec{},
- },
- },
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "expected access denied, got: %v", err)
},
@@ -1859,16 +1859,16 @@ func TestUpsertBot(t *testing.T) {
{
name: "scoped identity cannot upsert unscoped bot",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{
Name: "unscoped-from-scoped",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "expected access denied, got: %v", err)
},
@@ -1876,12 +1876,12 @@ func TestUpsertBot(t *testing.T) {
{
name: "cannot change scope: scoped to unscoped",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{Name: "scope-change-test"},
- Spec: &machineidv1pb.BotSpec{Roles: []string{testRole.GetName()}},
- },
- },
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{Name: "scope-change-test"}.Build(),
+ Spec: machineidv1pb.BotSpec_builder{Roles: []string{testRole.GetName()}}.Build(),
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err), "expected bad parameter, got: %v", err)
},
@@ -1889,13 +1889,13 @@ func TestUpsertBot(t *testing.T) {
{
name: "cannot change scope: unscoped to scoped",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{Name: "pre-existing"},
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{Name: "pre-existing"}.Build(),
Scope: "/scopes/granted",
Spec: &machineidv1pb.BotSpec{},
- },
- },
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err), "expected bad parameter, got: %v", err)
},
@@ -1903,13 +1903,13 @@ func TestUpsertBot(t *testing.T) {
{
name: "cannot change scope: scoped to different scope",
identity: authtest.TestUser(botCreator.GetName()),
- req: &machineidv1pb.UpsertBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{Name: "scope-change-test"},
+ req: machineidv1pb.UpsertBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{Name: "scope-change-test"}.Build(),
Scope: "/scopes/ungranted",
Spec: &machineidv1pb.BotSpec{},
- },
- },
+ }.Build(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err), "expected bad parameter, got: %v", err)
},
@@ -1995,111 +1995,111 @@ func TestGetBot(t *testing.T) {
require.NoError(t, err)
preExistingBot, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
Description: "The maze wasn't meant for you",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
preExistingBot2, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "foo-pre-existing",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
// Scoped identity setup.
scopedSvc := client.ScopedAccessServiceClient()
- scopedRole, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ scopedRole, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-getter",
- },
+ }.Build(),
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/scopes/granted", "/scopes/ungranted"},
Rules: []*scopedaccessv1.ScopedRule{
- {
+ scopedaccessv1.ScopedRule_builder{
Verbs: []string{types.VerbReadNoSecrets},
Resources: []string{types.KindBot},
- },
+ }.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
scopedUser, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user")
require.NoError(t, err)
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/granted"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/granted"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp)
- scopedPreExisting, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ scopedPreExisting, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-pre-existing",
- },
+ }.Build(),
Spec: &machineidv1pb.BotSpec{},
Scope: "/scopes/granted",
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- _, err = client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ _, err = client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-pre-existing-wrong-scope",
- },
+ }.Build(),
Spec: &machineidv1pb.BotSpec{},
Scope: "/scopes/ungranted",
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -2112,9 +2112,9 @@ func TestGetBot(t *testing.T) {
{
name: "success",
identity: authtest.TestUser(botGetterUser.GetName()),
- req: &machineidv1pb.GetBotRequest{
- BotName: preExistingBot.Metadata.Name,
- },
+ req: machineidv1pb.GetBotRequest_builder{
+ BotName: preExistingBot.GetMetadata().GetName(),
+ }.Build(),
assertError: require.NoError,
want: preExistingBot,
@@ -2122,9 +2122,9 @@ func TestGetBot(t *testing.T) {
{
name: "success with where",
identity: authtest.TestUser(botGetterWhereUser.GetName()),
- req: &machineidv1pb.GetBotRequest{
- BotName: preExistingBot2.Metadata.Name,
- },
+ req: machineidv1pb.GetBotRequest_builder{
+ BotName: preExistingBot2.GetMetadata().GetName(),
+ }.Build(),
assertError: require.NoError,
want: preExistingBot2,
@@ -2132,9 +2132,9 @@ func TestGetBot(t *testing.T) {
{
name: "no permissions with where",
identity: authtest.TestUser(botGetterWhereUser.GetName()),
- req: &machineidv1pb.GetBotRequest{
- BotName: preExistingBot.Metadata.Name,
- },
+ req: machineidv1pb.GetBotRequest_builder{
+ BotName: preExistingBot.GetMetadata().GetName(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err), "error should be not found")
},
@@ -2142,9 +2142,9 @@ func TestGetBot(t *testing.T) {
{
name: "no permissions",
identity: authtest.TestUser(unprivilegedUser.GetName()),
- req: &machineidv1pb.GetBotRequest{
- BotName: preExistingBot.Metadata.Name,
- },
+ req: machineidv1pb.GetBotRequest_builder{
+ BotName: preExistingBot.GetMetadata().GetName(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -2152,9 +2152,9 @@ func TestGetBot(t *testing.T) {
{
name: "validation - no bot name",
identity: authtest.TestUser(botGetterUser.GetName()),
- req: &machineidv1pb.GetBotRequest{
+ req: machineidv1pb.GetBotRequest_builder{
BotName: "",
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "must be non-empty")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -2163,9 +2163,9 @@ func TestGetBot(t *testing.T) {
{
name: "bot doesnt exist",
identity: authtest.TestUser(botGetterUser.GetName()),
- req: &machineidv1pb.GetBotRequest{
+ req: machineidv1pb.GetBotRequest_builder{
BotName: "non-existent",
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err), "error should be bad parameter")
},
@@ -2173,27 +2173,27 @@ func TestGetBot(t *testing.T) {
{
name: "scoped identity gets scoped bot",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.GetBotRequest{
- BotName: scopedPreExisting.Metadata.Name,
- },
+ req: machineidv1pb.GetBotRequest_builder{
+ BotName: scopedPreExisting.GetMetadata().GetName(),
+ }.Build(),
assertError: require.NoError,
want: scopedPreExisting,
},
{
name: "unscoped identity gets scoped bot",
identity: authtest.TestUser(botGetterUser.GetName()),
- req: &machineidv1pb.GetBotRequest{
- BotName: scopedPreExisting.Metadata.Name,
- },
+ req: machineidv1pb.GetBotRequest_builder{
+ BotName: scopedPreExisting.GetMetadata().GetName(),
+ }.Build(),
assertError: require.NoError,
want: scopedPreExisting,
},
{
name: "scoped identity wrong scope",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.GetBotRequest{
+ req: machineidv1pb.GetBotRequest_builder{
BotName: "scoped-pre-existing-wrong-scope",
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
// GetBot returns NotFound rather than AccessDenied to avoid leaking existence.
require.True(t, trace.IsNotFound(err), "expected not found, got: %v", err)
@@ -2202,9 +2202,9 @@ func TestGetBot(t *testing.T) {
{
name: "scoped identity cannot get unscoped bot",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.GetBotRequest{
- BotName: preExistingBot.Metadata.Name,
- },
+ req: machineidv1pb.GetBotRequest_builder{
+ BotName: preExistingBot.GetMetadata().GetName(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
// GetBot returns NotFound rather than AccessDenied to avoid leaking existence.
require.True(t, trace.IsNotFound(err), "expected not found, got: %v", err)
@@ -2268,136 +2268,136 @@ func TestListBots(t *testing.T) {
require.NoError(t, err)
preExistingBot, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing",
Labels: map[string]string{
"my-label": "my-value",
"my-other-label": "my-other-value",
},
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
preExistingBot2, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing-2",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
preExistingBot3, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "foo-pre-existing-2",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
// Scoped identity setup.
scopedSvc := client.ScopedAccessServiceClient()
- scopedRole, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ scopedRole, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-lister",
- },
+ }.Build(),
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/scopes/granted", "/scopes/ungranted"},
Rules: []*scopedaccessv1.ScopedRule{
- {
+ scopedaccessv1.ScopedRule_builder{
Verbs: []string{types.VerbList},
Resources: []string{types.KindBot},
- },
+ }.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
scopedUser, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user")
require.NoError(t, err)
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
Scope: "/scopes",
SubKind: scopedaccess.SubKindDynamic,
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/granted"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/granted"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Create a 2nd scoped user with assignment at /scopes/ungranted (where no bots exist).
scopedUser2, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user-2")
require.NoError(t, err)
- sraResp2, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp2, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser2.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/ungranted"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/ungranted"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp, sraResp2)
- scopedPreExisting, err := client.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ scopedPreExisting, err := client.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-pre-existing",
- },
+ }.Build(),
Spec: &machineidv1pb.BotSpec{},
Scope: "/scopes/granted",
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -2412,25 +2412,25 @@ func TestListBots(t *testing.T) {
identity: authtest.TestUser(botListerUser.GetName()),
req: &machineidv1pb.ListBotsRequest{},
assertError: require.NoError,
- want: &machineidv1pb.ListBotsResponse{
+ want: machineidv1pb.ListBotsResponse_builder{
Bots: []*machineidv1pb.Bot{
preExistingBot,
preExistingBot2,
preExistingBot3,
scopedPreExisting,
},
- },
+ }.Build(),
},
{
name: "success with where",
identity: authtest.TestUser(botListWhereUser.GetName()),
req: &machineidv1pb.ListBotsRequest{},
assertError: require.NoError,
- want: &machineidv1pb.ListBotsResponse{
+ want: machineidv1pb.ListBotsResponse_builder{
Bots: []*machineidv1pb.Bot{
preExistingBot3,
},
- },
+ }.Build(),
},
{
name: "no permissions",
@@ -2445,11 +2445,11 @@ func TestListBots(t *testing.T) {
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
req: &machineidv1pb.ListBotsRequest{},
assertError: require.NoError,
- want: &machineidv1pb.ListBotsResponse{
+ want: machineidv1pb.ListBotsResponse_builder{
Bots: []*machineidv1pb.Bot{
scopedPreExisting,
},
- },
+ }.Build(),
},
{
// Scoped user at /scopes/ungranted where no bots exist: returns empty list.
@@ -2457,9 +2457,9 @@ func TestListBots(t *testing.T) {
identity: authtest.TestScopedUser(scopedUser2.GetName(), "/scopes/ungranted"),
req: &machineidv1pb.ListBotsRequest{},
assertError: require.NoError,
- want: &machineidv1pb.ListBotsResponse{
+ want: machineidv1pb.ListBotsResponse_builder{
Bots: []*machineidv1pb.Bot{},
- },
+ }.Build(),
},
}
for _, tt := range tests {
@@ -2537,113 +2537,113 @@ func TestDeleteBot(t *testing.T) {
require.NoError(t, err)
preExistingBot, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
preExistingBot3, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "pre-existing-3",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
preExistingBot4, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "foo-pre-existing",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
preExistingBot5, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "not-foo-pre-existing",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{testRole.GetName()},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
// Scoped identity setup: create a scoped role, user, and assignment.
scopedSvc := client.ScopedAccessServiceClient()
- scopedRole, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ scopedRole, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-deleter",
- },
+ }.Build(),
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/scopes/granted", "/scopes/ungranted"},
Rules: []*scopedaccessv1.ScopedRule{
- {
+ scopedaccessv1.ScopedRule_builder{
Verbs: []string{types.VerbDelete},
Resources: []string{types.KindBot},
- },
+ }.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
scopedUser, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user")
require.NoError(t, err)
// Create scoped role assignment linking user to scoped role.
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/granted"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/granted"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp)
@@ -2651,47 +2651,47 @@ func TestDeleteBot(t *testing.T) {
// Note: scoped bots cannot have roles set.
scopedPreExisting, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-pre-existing",
- },
+ }.Build(),
Spec: &machineidv1pb.BotSpec{},
Scope: "/scopes/granted",
- },
- },
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
scopedPreExistingUnscoped, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-pre-existing-unscoped",
- },
+ }.Build(),
Spec: &machineidv1pb.BotSpec{},
Scope: "/scopes/granted",
- },
- },
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
scopedPreExistingWrongScope, err := client.BotServiceClient().CreateBot(
ctx,
- &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
+ machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-pre-existing-wrong-scope",
- },
+ }.Build(),
Spec: &machineidv1pb.BotSpec{},
Scope: "/scopes/ungranted",
- },
- },
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
@@ -2706,27 +2706,27 @@ func TestDeleteBot(t *testing.T) {
{
name: "success",
identity: authtest.TestUser(botDeleterUser.GetName()),
- req: &machineidv1pb.DeleteBotRequest{
- BotName: preExistingBot.Metadata.Name,
- },
+ req: machineidv1pb.DeleteBotRequest_builder{
+ BotName: preExistingBot.GetMetadata().GetName(),
+ }.Build(),
assertError: require.NoError,
checkResourcesDeleted: true,
},
{
name: "success with where",
identity: authtest.TestUser(botWhereDeleterUser.GetName()),
- req: &machineidv1pb.DeleteBotRequest{
- BotName: preExistingBot4.Metadata.Name,
- },
+ req: machineidv1pb.DeleteBotRequest_builder{
+ BotName: preExistingBot4.GetMetadata().GetName(),
+ }.Build(),
assertError: require.NoError,
checkResourcesDeleted: true,
},
{
name: "no permissions with where",
identity: authtest.TestUser(botWhereDeleterUser.GetName()),
- req: &machineidv1pb.DeleteBotRequest{
- BotName: preExistingBot5.Metadata.Name,
- },
+ req: machineidv1pb.DeleteBotRequest_builder{
+ BotName: preExistingBot5.GetMetadata().GetName(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -2734,9 +2734,9 @@ func TestDeleteBot(t *testing.T) {
{
name: "no permissions",
identity: authtest.TestUser(unprivilegedUser.GetName()),
- req: &machineidv1pb.DeleteBotRequest{
- BotName: preExistingBot3.Metadata.Name,
- },
+ req: machineidv1pb.DeleteBotRequest_builder{
+ BotName: preExistingBot3.GetMetadata().GetName(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -2744,9 +2744,9 @@ func TestDeleteBot(t *testing.T) {
{
name: "non existent",
identity: authtest.TestUser(botDeleterUser.GetName()),
- req: &machineidv1pb.DeleteBotRequest{
+ req: machineidv1pb.DeleteBotRequest_builder{
BotName: "does-not-exist",
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err), "error should be not found")
},
@@ -2754,9 +2754,9 @@ func TestDeleteBot(t *testing.T) {
{
name: "non-bot role",
identity: authtest.TestUser(botDeleterUser.GetName()),
- req: &machineidv1pb.DeleteBotRequest{
+ req: machineidv1pb.DeleteBotRequest_builder{
BotName: "not-bot",
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "missing bot label matching bot name")
},
@@ -2764,9 +2764,9 @@ func TestDeleteBot(t *testing.T) {
{
name: "validation - no bot name",
identity: authtest.TestUser(botDeleterUser.GetName()),
- req: &machineidv1pb.DeleteBotRequest{
+ req: machineidv1pb.DeleteBotRequest_builder{
BotName: "",
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "bot_name: must be non-empty")
require.True(t, trace.IsBadParameter(err), "error should be access denied")
@@ -2775,9 +2775,9 @@ func TestDeleteBot(t *testing.T) {
{
name: "scoped identity deletes scoped bot",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.DeleteBotRequest{
- BotName: scopedPreExisting.Metadata.Name,
- },
+ req: machineidv1pb.DeleteBotRequest_builder{
+ BotName: scopedPreExisting.GetMetadata().GetName(),
+ }.Build(),
assertError: require.NoError,
checkResourcesDeleted: true,
scoped: true,
@@ -2785,9 +2785,9 @@ func TestDeleteBot(t *testing.T) {
{
name: "unscoped identity deletes scoped bot",
identity: authtest.TestUser(botDeleterUser.GetName()),
- req: &machineidv1pb.DeleteBotRequest{
- BotName: scopedPreExistingUnscoped.Metadata.Name,
- },
+ req: machineidv1pb.DeleteBotRequest_builder{
+ BotName: scopedPreExistingUnscoped.GetMetadata().GetName(),
+ }.Build(),
assertError: require.NoError,
checkResourcesDeleted: true,
scoped: true,
@@ -2795,9 +2795,9 @@ func TestDeleteBot(t *testing.T) {
{
name: "scoped identity wrong scope",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.DeleteBotRequest{
- BotName: scopedPreExistingWrongScope.Metadata.Name,
- },
+ req: machineidv1pb.DeleteBotRequest_builder{
+ BotName: scopedPreExistingWrongScope.GetMetadata().GetName(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "expected access denied, got: %v", err)
},
@@ -2805,9 +2805,9 @@ func TestDeleteBot(t *testing.T) {
{
name: "scoped identity cannot delete unscoped bot",
identity: authtest.TestScopedUser(scopedUser.GetName(), "/scopes/granted"),
- req: &machineidv1pb.DeleteBotRequest{
- BotName: preExistingBot3.Metadata.Name,
- },
+ req: machineidv1pb.DeleteBotRequest_builder{
+ BotName: preExistingBot3.GetMetadata().GetName(),
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "expected access denied, got: %v", err)
},
@@ -2821,10 +2821,10 @@ func TestDeleteBot(t *testing.T) {
_, err = client.BotServiceClient().DeleteBot(ctx, tt.req)
tt.assertError(t, err)
if tt.checkResourcesDeleted {
- _, err := srv.Auth().GetUser(ctx, machineidv1.BotResourceName(tt.req.BotName), false)
+ _, err := srv.Auth().GetUser(ctx, machineidv1.BotResourceName(tt.req.GetBotName()), false)
require.True(t, trace.IsNotFound(err), "bot user should be deleted")
if !tt.scoped {
- _, err = srv.Auth().GetRole(ctx, machineidv1.BotResourceName(tt.req.BotName))
+ _, err = srv.Auth().GetRole(ctx, machineidv1.BotResourceName(tt.req.GetBotName()))
require.True(t, trace.IsNotFound(err), "bot role should be deleted")
}
}
@@ -2834,31 +2834,31 @@ func TestDeleteBot(t *testing.T) {
func TestStrongValidateBot(t *testing.T) {
newBot := func(mutate func(bot *machineidv1pb.Bot)) *machineidv1pb.Bot {
- bot := &machineidv1pb.Bot{
+ bot := machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-bot",
- },
- Spec: &machineidv1pb.BotSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotSpec_builder{
Roles: []string{"test-role"},
- },
- }
+ }.Build(),
+ }.Build()
if mutate != nil {
mutate(bot)
}
return bot
}
newScopedBot := func(mutate func(bot *machineidv1pb.Bot)) *machineidv1pb.Bot {
- bot := &machineidv1pb.Bot{
+ bot := machineidv1pb.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-bot",
- },
+ }.Build(),
Scope: "/test/scope",
Spec: &machineidv1pb.BotSpec{},
- }
+ }.Build()
if mutate != nil {
mutate(bot)
}
@@ -2881,23 +2881,23 @@ func TestStrongValidateBot(t *testing.T) {
},
{
name: "nil metadata",
- bot: newBot(func(b *machineidv1pb.Bot) { b.Metadata = nil }),
+ bot: newBot(func(b *machineidv1pb.Bot) { b.ClearMetadata() }),
assertError: isBadParam,
},
{
name: "empty name",
- bot: newBot(func(b *machineidv1pb.Bot) { b.Metadata.Name = "" }),
+ bot: newBot(func(b *machineidv1pb.Bot) { b.GetMetadata().SetName("") }),
assertError: isBadParam,
},
{
name: "nil spec",
- bot: newBot(func(b *machineidv1pb.Bot) { b.Spec = nil }),
+ bot: newBot(func(b *machineidv1pb.Bot) { b.ClearSpec() }),
assertError: isBadParam,
},
{
name: "roles contains empty string",
bot: newBot(func(b *machineidv1pb.Bot) {
- b.Spec.Roles = []string{"valid-role", ""}
+ b.GetSpec().SetRoles([]string{"valid-role", ""})
}),
assertError: isBadParam,
},
@@ -2909,41 +2909,41 @@ func TestStrongValidateBot(t *testing.T) {
{
name: "valid unscoped bot with no roles",
bot: newBot(func(b *machineidv1pb.Bot) {
- b.Spec.Roles = nil
+ b.GetSpec().SetRoles(nil)
}),
assertError: require.NoError,
},
{
name: "valid unscoped bot with traits and max_session_ttl",
bot: newBot(func(b *machineidv1pb.Bot) {
- b.Spec.Traits = []*machineidv1pb.Trait{{Name: "foo", Values: []string{"bar"}}}
- b.Spec.MaxSessionTtl = durationpb.New(time.Hour)
+ b.GetSpec().SetTraits([]*machineidv1pb.Trait{machineidv1pb.Trait_builder{Name: "foo", Values: []string{"bar"}}.Build()})
+ b.GetSpec().SetMaxSessionTtl(durationpb.New(time.Hour))
}),
assertError: require.NoError,
},
{
name: "scoped bot with invalid scope",
- bot: newScopedBot(func(b *machineidv1pb.Bot) { b.Scope = "no-leading-slash" }),
+ bot: newScopedBot(func(b *machineidv1pb.Bot) { b.SetScope("no-leading-slash") }),
assertError: isBadParam,
},
{
name: "scoped bot with roles set",
bot: newScopedBot(func(b *machineidv1pb.Bot) {
- b.Spec.Roles = []string{"some-role"}
+ b.GetSpec().SetRoles([]string{"some-role"})
}),
assertError: isBadParam,
},
{
name: "scoped bot with traits set",
bot: newScopedBot(func(b *machineidv1pb.Bot) {
- b.Spec.Traits = []*machineidv1pb.Trait{{Name: "foo", Values: []string{"bar"}}}
+ b.GetSpec().SetTraits([]*machineidv1pb.Trait{machineidv1pb.Trait_builder{Name: "foo", Values: []string{"bar"}}.Build()})
}),
assertError: isBadParam,
},
{
name: "scoped bot with max_session_ttl set",
bot: newScopedBot(func(b *machineidv1pb.Bot) {
- b.Spec.MaxSessionTtl = durationpb.New(time.Hour)
+ b.GetSpec().SetMaxSessionTtl(durationpb.New(time.Hour))
}),
assertError: isBadParam,
},
@@ -2954,7 +2954,7 @@ func TestStrongValidateBot(t *testing.T) {
},
{
name: "valid scoped bot at root scope",
- bot: newScopedBot(func(b *machineidv1pb.Bot) { b.Scope = "/" }),
+ bot: newScopedBot(func(b *machineidv1pb.Bot) { b.SetScope("/") }),
assertError: require.NoError,
},
}
@@ -2986,11 +2986,11 @@ func TestStrongValidateBotScopedFuzz(t *testing.T) {
spec := &machineidv1pb.BotSpec{}
protoSetNonZeroField(spec.ProtoReflect(), fd)
- bot := &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{Name: "test-bot"},
+ bot := machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{Name: "test-bot"}.Build(),
Scope: "/test/scope",
Spec: spec,
- }
+ }.Build()
err := machineidv1.StrongValidateBot(bot)
if allowedScopedSpecFields[fd.Name()] {
@@ -3080,10 +3080,10 @@ func waitForSRACache(t *testing.T, srv *authtest.TLSServer, resps ...*scopedacce
ctx := t.Context()
require.EventuallyWithT(t, func(t *assert.CollectT) {
for _, resp := range resps {
- _, err := srv.Auth().ScopedAccessCache.GetScopedRoleAssignment(ctx, &scopedaccessv1.GetScopedRoleAssignmentRequest{
+ _, err := srv.Auth().ScopedAccessCache.GetScopedRoleAssignment(ctx, scopedaccessv1.GetScopedRoleAssignmentRequest_builder{
Name: resp.GetAssignment().GetMetadata().GetName(),
SubKind: resp.GetAssignment().GetSubKind(),
- })
+ }.Build())
require.NoError(t, err)
}
}, 10*time.Second, 100*time.Millisecond)
@@ -3098,19 +3098,19 @@ func createBotInstance(
if instanceID == "" {
instanceID = uuid.NewString()
}
- bi := &machineidv1pb.BotInstance{
+ bi := machineidv1pb.BotInstance_builder{
Kind: types.KindBotInstance,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &machineidv1pb.BotInstanceSpec{
+ }.Build(),
+ Spec: machineidv1pb.BotInstanceSpec_builder{
BotName: botName,
InstanceId: instanceID,
- },
+ }.Build(),
Status: &machineidv1pb.BotInstanceStatus{},
Scope: scope,
- }
+ }.Build()
created, err := srv.Auth().BotInstance.CreateBotInstance(t.Context(), bi)
require.NoError(t, err)
return created
@@ -3137,47 +3137,47 @@ func TestBotInstanceService_DeleteBotInstance(t *testing.T) {
require.NoError(t, err)
scopedSvc := adminClient.ScopedAccessServiceClient()
- scopedRole, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ scopedRole, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-instance-deleter",
- },
+ }.Build(),
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/scopes/granted", "/scopes/ungranted"},
Rules: []*scopedaccessv1.ScopedRule{
- {
+ scopedaccessv1.ScopedRule_builder{
Verbs: []string{types.VerbDelete},
Resources: []string{types.KindBotInstance},
- },
+ }.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
scopedUser, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user")
require.NoError(t, err)
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/granted"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/granted"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp)
@@ -3234,10 +3234,10 @@ func TestBotInstanceService_DeleteBotInstance(t *testing.T) {
client, err := srv.NewClient(tt.identity)
require.NoError(t, err)
- _, err = client.BotInstanceServiceClient().DeleteBotInstance(ctx, &machineidv1pb.DeleteBotInstanceRequest{
- BotName: tt.instance.Spec.BotName,
- InstanceId: tt.instance.Spec.InstanceId,
- })
+ _, err = client.BotInstanceServiceClient().DeleteBotInstance(ctx, machineidv1pb.DeleteBotInstanceRequest_builder{
+ BotName: tt.instance.GetSpec().GetBotName(),
+ InstanceId: tt.instance.GetSpec().GetInstanceId(),
+ }.Build())
tt.assertError(t, err)
})
}
@@ -3264,47 +3264,47 @@ func TestBotInstanceService_GetBotInstance(t *testing.T) {
require.NoError(t, err)
scopedSvc := adminClient.ScopedAccessServiceClient()
- scopedRole, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ scopedRole, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-instance-reader",
- },
+ }.Build(),
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/scopes/granted", "/scopes/ungranted"},
Rules: []*scopedaccessv1.ScopedRule{
- {
+ scopedaccessv1.ScopedRule_builder{
Verbs: []string{types.VerbReadNoSecrets},
Resources: []string{types.KindBotInstance},
- },
+ }.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
scopedUser, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user")
require.NoError(t, err)
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/granted"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/granted"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp)
@@ -3358,13 +3358,13 @@ func TestBotInstanceService_GetBotInstance(t *testing.T) {
client, err := srv.NewClient(tt.identity)
require.NoError(t, err)
- got, err := client.BotInstanceServiceClient().GetBotInstance(ctx, &machineidv1pb.GetBotInstanceRequest{
- BotName: tt.instance.Spec.BotName,
- InstanceId: tt.instance.Spec.InstanceId,
- })
+ got, err := client.BotInstanceServiceClient().GetBotInstance(ctx, machineidv1pb.GetBotInstanceRequest_builder{
+ BotName: tt.instance.GetSpec().GetBotName(),
+ InstanceId: tt.instance.GetSpec().GetInstanceId(),
+ }.Build())
tt.assertError(t, err)
if err == nil {
- require.Equal(t, tt.instance.Spec.InstanceId, got.Spec.InstanceId)
+ require.Equal(t, tt.instance.GetSpec().GetInstanceId(), got.GetSpec().GetInstanceId())
}
})
}
@@ -3391,65 +3391,65 @@ func TestBotInstanceService_ListBotInstancesV2(t *testing.T) {
require.NoError(t, err)
scopedSvc := adminClient.ScopedAccessServiceClient()
- scopedRole, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ scopedRole, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-bot-instance-lister",
- },
+ }.Build(),
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/scopes/granted", "/scopes/ungranted", "/scopes/other"},
Rules: []*scopedaccessv1.ScopedRule{
- {
+ scopedaccessv1.ScopedRule_builder{
Verbs: []string{types.VerbReadNoSecrets, types.VerbList},
Resources: []string{types.KindBotInstance},
- },
+ }.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
scopedUser, err := authtest.CreateUser(ctx, srv.Auth(), "scoped-user")
require.NoError(t, err)
- sra1Resp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sra1Resp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/granted"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/granted"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- sra2Resp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sra2Resp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
User: scopedUser.GetName(),
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/other"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/other"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sra1Resp, sra2Resp)
@@ -3473,11 +3473,11 @@ func TestBotInstanceService_ListBotInstancesV2(t *testing.T) {
allIDs := make(map[string]struct{})
for _, bi := range allInstances {
- allIDs[bi.Spec.InstanceId] = struct{}{}
+ allIDs[bi.GetSpec().GetInstanceId()] = struct{}{}
}
grantedIDs := make(map[string]struct{})
for _, bi := range grantedInstances {
- grantedIDs[bi.Spec.InstanceId] = struct{}{}
+ grantedIDs[bi.GetSpec().GetInstanceId()] = struct{}{}
}
listAll := func(t *testing.T, client machineidv1pb.BotInstanceServiceClient) []*machineidv1pb.BotInstance {
@@ -3487,11 +3487,11 @@ func TestBotInstanceService_ListBotInstancesV2(t *testing.T) {
func(
ctx context.Context, limit int, nextToken string,
) ([]*machineidv1pb.BotInstance, string, error) {
- res, err := client.ListBotInstancesV2(ctx, &machineidv1pb.ListBotInstancesV2Request{
+ res, err := client.ListBotInstancesV2(ctx, machineidv1pb.ListBotInstancesV2Request_builder{
PageToken: nextToken,
PageSize: int32(limit),
- })
- return res.BotInstances, res.NextPageToken, err
+ }.Build())
+ return res.GetBotInstances(), res.GetNextPageToken(), err
}),
)
require.NoError(t, err)
@@ -3505,7 +3505,7 @@ func TestBotInstanceService_ListBotInstancesV2(t *testing.T) {
got := listAll(t, client.BotInstanceServiceClient())
require.Len(t, got, len(allInstances))
for _, bi := range got {
- require.Contains(t, allIDs, bi.Spec.InstanceId)
+ require.Contains(t, allIDs, bi.GetSpec().GetInstanceId())
}
})
@@ -3516,7 +3516,7 @@ func TestBotInstanceService_ListBotInstancesV2(t *testing.T) {
got := listAll(t, client.BotInstanceServiceClient())
require.Len(t, got, len(grantedInstances))
for _, bi := range got {
- require.Contains(t, grantedIDs, bi.Spec.InstanceId)
+ require.Contains(t, grantedIDs, bi.GetSpec().GetInstanceId())
}
})
@@ -3561,96 +3561,96 @@ func TestBotInstanceService_SubmitHeartbeat(t *testing.T) {
t.Run("unscoped bot", func(t *testing.T) {
const botName = "heartbeat-unscoped"
- _, err := adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{Name: botName},
- Spec: &machineidv1pb.BotSpec{Roles: []string{testRole.GetName()}},
- },
- })
+ _, err := adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{Name: botName}.Build(),
+ Spec: machineidv1pb.BotSpec_builder{Roles: []string{testRole.GetName()}}.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
botClient, instanceID := newBotClient(t, authtest.TestBot(botName, false))
createBotInstance(t, srv, botName, "", instanceID)
- _, err = botClient.BotInstanceServiceClient().SubmitHeartbeat(ctx, &machineidv1pb.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1pb.BotInstanceStatusHeartbeat{Hostname: "unscoped-host"},
- })
+ _, err = botClient.BotInstanceServiceClient().SubmitHeartbeat(ctx, machineidv1pb.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1pb.BotInstanceStatusHeartbeat_builder{Hostname: "unscoped-host"}.Build(),
+ }.Build())
require.NoError(t, err)
- got, err := adminClient.BotInstanceServiceClient().GetBotInstance(ctx, &machineidv1pb.GetBotInstanceRequest{
+ got, err := adminClient.BotInstanceServiceClient().GetBotInstance(ctx, machineidv1pb.GetBotInstanceRequest_builder{
BotName: botName,
InstanceId: instanceID,
- })
+ }.Build())
require.NoError(t, err)
- require.NotNil(t, got.Status.InitialHeartbeat)
- require.Equal(t, "unscoped-host", got.Status.InitialHeartbeat.Hostname)
+ require.NotNil(t, got.GetStatus().GetInitialHeartbeat())
+ require.Equal(t, "unscoped-host", got.GetStatus().GetInitialHeartbeat().GetHostname())
})
t.Run("scoped bot", func(t *testing.T) {
const botName = "heartbeat-scoped"
- _, err := adminClient.BotServiceClient().CreateBot(ctx, &machineidv1pb.CreateBotRequest{
- Bot: &machineidv1pb.Bot{
- Metadata: &headerv1.Metadata{Name: botName},
+ _, err := adminClient.BotServiceClient().CreateBot(ctx, machineidv1pb.CreateBotRequest_builder{
+ Bot: machineidv1pb.Bot_builder{
+ Metadata: headerv1.Metadata_builder{Name: botName}.Build(),
Scope: "/scopes/test",
Spec: &machineidv1pb.BotSpec{},
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// We need to assign our bot a scoped role otherwise we won't be able
// to generate certificates for it.
scopedSvc := adminClient.ScopedAccessServiceClient()
- scopedRole, err := scopedSvc.CreateScopedRole(ctx, &scopedaccessv1.CreateScopedRoleRequest{
- Role: &scopedaccessv1.ScopedRole{
+ scopedRole, err := scopedSvc.CreateScopedRole(ctx, scopedaccessv1.CreateScopedRoleRequest_builder{
+ Role: scopedaccessv1.ScopedRole_builder{
Kind: scopedaccess.KindScopedRole,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "scoped-heartbeat-role",
- },
+ }.Build(),
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleSpec{
+ Spec: scopedaccessv1.ScopedRoleSpec_builder{
AssignableScopes: []string{"/scopes/test"},
Rules: []*scopedaccessv1.ScopedRule{},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, &scopedaccessv1.CreateScopedRoleAssignmentRequest{
- Assignment: &scopedaccessv1.ScopedRoleAssignment{
+ sraResp, err := scopedSvc.CreateScopedRoleAssignment(ctx, scopedaccessv1.CreateScopedRoleAssignmentRequest_builder{
+ Assignment: scopedaccessv1.ScopedRoleAssignment_builder{
Kind: scopedaccess.KindScopedRoleAssignment,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: uuid.NewString(),
- },
+ }.Build(),
SubKind: scopedaccess.SubKindDynamic,
Scope: "/scopes",
- Spec: &scopedaccessv1.ScopedRoleAssignmentSpec{
+ Spec: scopedaccessv1.ScopedRoleAssignmentSpec_builder{
BotName: botName,
BotScope: "/scopes/test",
Assignments: []*scopedaccessv1.Assignment{
- {Role: scopedRole.Role.Metadata.Name, Scope: "/scopes/test"},
+ scopedaccessv1.Assignment_builder{Role: scopedRole.GetRole().GetMetadata().GetName(), Scope: "/scopes/test"}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
waitForSRACache(t, srv, sraResp)
botClient, instanceID := newBotClient(t, authtest.TestScopedBot(botName, "/scopes/test", true))
createBotInstance(t, srv, botName, "/scopes/test", instanceID)
- _, err = botClient.BotInstanceServiceClient().SubmitHeartbeat(ctx, &machineidv1pb.SubmitHeartbeatRequest{
- Heartbeat: &machineidv1pb.BotInstanceStatusHeartbeat{Hostname: "scoped-host"},
- })
+ _, err = botClient.BotInstanceServiceClient().SubmitHeartbeat(ctx, machineidv1pb.SubmitHeartbeatRequest_builder{
+ Heartbeat: machineidv1pb.BotInstanceStatusHeartbeat_builder{Hostname: "scoped-host"}.Build(),
+ }.Build())
require.NoError(t, err)
- got, err := adminClient.BotInstanceServiceClient().GetBotInstance(ctx, &machineidv1pb.GetBotInstanceRequest{
+ got, err := adminClient.BotInstanceServiceClient().GetBotInstance(ctx, machineidv1pb.GetBotInstanceRequest_builder{
BotName: botName,
InstanceId: instanceID,
- })
+ }.Build())
require.NoError(t, err)
- require.NotNil(t, got.Status.InitialHeartbeat)
- require.Equal(t, "scoped-host", got.Status.InitialHeartbeat.Hostname)
+ require.NotNil(t, got.GetStatus().GetInitialHeartbeat())
+ require.Equal(t, "scoped-host", got.GetStatus().GetInitialHeartbeat().GetHostname())
})
}
diff --git a/lib/auth/machineid/machineidv1/spiffe_federation_service.go b/lib/auth/machineid/machineidv1/spiffe_federation_service.go
index 62d4290c922..d068296b409 100644
--- a/lib/auth/machineid/machineidv1/spiffe_federation_service.go
+++ b/lib/auth/machineid/machineidv1/spiffe_federation_service.go
@@ -119,11 +119,11 @@ func (s *SPIFFEFederationService) GetSPIFFEFederation(
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be non-empty")
}
- federation, err := s.cache.GetSPIFFEFederation(ctx, req.Name)
+ federation, err := s.cache.GetSPIFFEFederation(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -147,17 +147,17 @@ func (s *SPIFFEFederationService) ListSPIFFEFederations(
federations, nextToken, err := s.cache.ListSPIFFEFederations(
ctx,
- int(req.PageSize),
- req.PageToken,
+ int(req.GetPageSize()),
+ req.GetPageToken(),
)
if err != nil {
return nil, trace.Wrap(err)
}
- return &machineidv1.ListSPIFFEFederationsResponse{
+ return machineidv1.ListSPIFFEFederationsResponse_builder{
SpiffeFederations: federations,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// DeleteSPIFFEFederation deletes a SPIFFE Federation by name.
@@ -176,11 +176,11 @@ func (s *SPIFFEFederationService) DeleteSPIFFEFederation(
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be non-empty")
}
- if err := s.backend.DeleteSPIFFEFederation(ctx, req.Name); err != nil {
+ if err := s.backend.DeleteSPIFFEFederation(ctx, req.GetName()); err != nil {
return nil, trace.Wrap(err)
}
@@ -192,7 +192,7 @@ func (s *SPIFFEFederationService) DeleteSPIFFEFederation(
UserMetadata: authz.ClientUserMetadata(ctx),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.Name,
+ Name: req.GetName(),
},
}); err != nil {
s.logger.ErrorContext(
@@ -226,7 +226,7 @@ func (s *SPIFFEFederationService) CreateSPIFFEFederation(
}
}
- created, err := s.backend.CreateSPIFFEFederation(ctx, req.SpiffeFederation)
+ created, err := s.backend.CreateSPIFFEFederation(ctx, req.GetSpiffeFederation())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -239,7 +239,7 @@ func (s *SPIFFEFederationService) CreateSPIFFEFederation(
UserMetadata: authz.ClientUserMetadata(ctx),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.SpiffeFederation.Metadata.Name,
+ Name: req.GetSpiffeFederation().GetMetadata().GetName(),
},
}); err != nil {
s.logger.ErrorContext(
diff --git a/lib/auth/machineid/machineidv1/spiffe_federation_service_test.go b/lib/auth/machineid/machineidv1/spiffe_federation_service_test.go
index fc56ea9753d..24360145be4 100644
--- a/lib/auth/machineid/machineidv1/spiffe_federation_service_test.go
+++ b/lib/auth/machineid/machineidv1/spiffe_federation_service_test.go
@@ -78,20 +78,20 @@ func TestSPIFFEFederationService_CreateSPIFFEFederation(t *testing.T) {
)
require.NoError(t, err)
- good := &machineidv1pb.SPIFFEFederation{
+ good := machineidv1pb.SPIFFEFederation_builder{
Kind: types.KindSPIFFEFederation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "example.com",
- },
- Spec: &machineidv1pb.SPIFFEFederationSpec{
- BundleSource: &machineidv1pb.SPIFFEFederationBundleSource{
- HttpsWeb: &machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb{
+ }.Build(),
+ Spec: machineidv1pb.SPIFFEFederationSpec_builder{
+ BundleSource: machineidv1pb.SPIFFEFederationBundleSource_builder{
+ HttpsWeb: machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb_builder{
BundleEndpointUrl: "https://example.com/bundle.json",
- },
- },
- },
- }
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build()
tests := []struct {
name string
@@ -104,9 +104,9 @@ func TestSPIFFEFederationService_CreateSPIFFEFederation(t *testing.T) {
{
name: "success",
user: authorizedUser.GetName(),
- req: &machineidv1pb.CreateSPIFFEFederationRequest{
+ req: machineidv1pb.CreateSPIFFEFederationRequest_builder{
SpiffeFederation: good,
- },
+ }.Build(),
requireError: require.NoError,
requireSuccess: true,
requireEvent: &events.SPIFFEFederationCreate{
@@ -128,15 +128,15 @@ func TestSPIFFEFederationService_CreateSPIFFEFederation(t *testing.T) {
{
name: "unable to set status",
user: authorizedUser.GetName(),
- req: &machineidv1pb.CreateSPIFFEFederationRequest{
+ req: machineidv1pb.CreateSPIFFEFederationRequest_builder{
SpiffeFederation: func() *machineidv1pb.SPIFFEFederation {
fed := proto.Clone(good).(*machineidv1pb.SPIFFEFederation)
- fed.Status = &machineidv1pb.SPIFFEFederationStatus{
+ fed.SetStatus(machineidv1pb.SPIFFEFederationStatus_builder{
CurrentBundleSyncedAt: timestamppb.Now(),
- }
+ }.Build())
return fed
}(),
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.Error(t, err)
require.True(t, trace.IsBadParameter(err))
@@ -146,13 +146,13 @@ func TestSPIFFEFederationService_CreateSPIFFEFederation(t *testing.T) {
{
name: "validation is run",
user: authorizedUser.GetName(),
- req: &machineidv1pb.CreateSPIFFEFederationRequest{
+ req: machineidv1pb.CreateSPIFFEFederationRequest_builder{
SpiffeFederation: func() *machineidv1pb.SPIFFEFederation {
fed := proto.Clone(good).(*machineidv1pb.SPIFFEFederation)
- fed.Metadata.Name = "spiffe://im----invalid"
+ fed.GetMetadata().SetName("spiffe://im----invalid")
return fed
}(),
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.Error(t, err)
require.True(t, trace.IsBadParameter(err))
@@ -162,9 +162,9 @@ func TestSPIFFEFederationService_CreateSPIFFEFederation(t *testing.T) {
{
name: "unauthorized",
user: unauthorizedUser.GetName(),
- req: &machineidv1pb.CreateSPIFFEFederationRequest{
+ req: machineidv1pb.CreateSPIFFEFederationRequest_builder{
SpiffeFederation: good,
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
@@ -185,7 +185,7 @@ func TestSPIFFEFederationService_CreateSPIFFEFederation(t *testing.T) {
require.Empty(
t,
cmp.Diff(
- tt.req.SpiffeFederation,
+ tt.req.GetSpiffeFederation(),
got,
protocmp.Transform(),
protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"),
@@ -194,13 +194,13 @@ func TestSPIFFEFederationService_CreateSPIFFEFederation(t *testing.T) {
// Then check the response is actually stored in the backend
got, err := srv.Auth().Services.SPIFFEFederations.GetSPIFFEFederation(
- ctx, got.Metadata.GetName(),
+ ctx, got.GetMetadata().GetName(),
)
require.NoError(t, err)
require.Empty(
t,
cmp.Diff(
- tt.req.SpiffeFederation,
+ tt.req.GetSpiffeFederation(),
got,
protocmp.Transform(),
protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"),
@@ -318,20 +318,20 @@ func TestSPIFFEFederationService_DeleteSPIFFEFederation(t *testing.T) {
client, err := srv.NewClient(authtest.TestUser(tt.user))
require.NoError(t, err)
- resource := &machineidv1pb.SPIFFEFederation{
+ resource := machineidv1pb.SPIFFEFederation_builder{
Kind: types.KindSPIFFEFederation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
- },
- Spec: &machineidv1pb.SPIFFEFederationSpec{
- BundleSource: &machineidv1pb.SPIFFEFederationBundleSource{
- HttpsWeb: &machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb{
+ }.Build(),
+ Spec: machineidv1pb.SPIFFEFederationSpec_builder{
+ BundleSource: machineidv1pb.SPIFFEFederationBundleSource_builder{
+ HttpsWeb: machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb_builder{
BundleEndpointUrl: "https://example.com/bundle.json",
- },
- },
- },
- }
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build()
if tt.create {
_, err := srv.Auth().Services.SPIFFEFederations.CreateSPIFFEFederation(
@@ -341,14 +341,14 @@ func TestSPIFFEFederationService_DeleteSPIFFEFederation(t *testing.T) {
}
mockEmitter.Reset()
- _, err = client.SPIFFEFederationServiceClient().DeleteSPIFFEFederation(ctx, &machineidv1pb.DeleteSPIFFEFederationRequest{
- Name: resource.Metadata.GetName(),
- })
+ _, err = client.SPIFFEFederationServiceClient().DeleteSPIFFEFederation(ctx, machineidv1pb.DeleteSPIFFEFederationRequest_builder{
+ Name: resource.GetMetadata().GetName(),
+ }.Build())
tt.requireError(t, err)
if tt.requireSuccess {
// Check that it is no longer in the backend
_, err := srv.Auth().Services.SPIFFEFederations.GetSPIFFEFederation(
- ctx, resource.Metadata.GetName(),
+ ctx, resource.GetMetadata().GetName(),
)
require.True(t, trace.IsNotFound(err))
}
@@ -397,20 +397,20 @@ func TestSPIFFEFederationService_GetSPIFFEFederation(t *testing.T) {
name := "example.com"
resource, err := srv.Auth().Services.SPIFFEFederations.CreateSPIFFEFederation(
- ctx, &machineidv1pb.SPIFFEFederation{
+ ctx, machineidv1pb.SPIFFEFederation_builder{
Kind: types.KindSPIFFEFederation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
- },
- Spec: &machineidv1pb.SPIFFEFederationSpec{
- BundleSource: &machineidv1pb.SPIFFEFederationBundleSource{
- HttpsWeb: &machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb{
+ }.Build(),
+ Spec: machineidv1pb.SPIFFEFederationSpec_builder{
+ BundleSource: machineidv1pb.SPIFFEFederationBundleSource_builder{
+ HttpsWeb: machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb_builder{
BundleEndpointUrl: "https://example.com/bundle.json",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
@@ -444,9 +444,9 @@ func TestSPIFFEFederationService_GetSPIFFEFederation(t *testing.T) {
client, err := srv.NewClient(authtest.TestUser(tt.user))
require.NoError(t, err)
- got, err := client.SPIFFEFederationServiceClient().GetSPIFFEFederation(ctx, &machineidv1pb.GetSPIFFEFederationRequest{
+ got, err := client.SPIFFEFederationServiceClient().GetSPIFFEFederation(ctx, machineidv1pb.GetSPIFFEFederationRequest_builder{
Name: tt.getName,
- })
+ }.Build())
tt.requireError(t, err)
if tt.requireSuccess {
require.Empty(
@@ -495,20 +495,20 @@ func TestSPIFFEFederationService_ListSPIFFEFederations(t *testing.T) {
for i := range 49 {
created, err := srv.AuthServer.AuthServer.Services.SPIFFEFederations.CreateSPIFFEFederation(
ctx,
- &machineidv1pb.SPIFFEFederation{
+ machineidv1pb.SPIFFEFederation_builder{
Kind: types.KindSPIFFEFederation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: fmt.Sprintf("%d.example.com", i),
- },
- Spec: &machineidv1pb.SPIFFEFederationSpec{
- BundleSource: &machineidv1pb.SPIFFEFederationBundleSource{
- HttpsWeb: &machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb{
+ }.Build(),
+ Spec: machineidv1pb.SPIFFEFederationSpec_builder{
+ BundleSource: machineidv1pb.SPIFFEFederationBundleSource_builder{
+ HttpsWeb: machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb_builder{
BundleEndpointUrl: "https://example.com/bundle.json",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
createdObjects = append(createdObjects, created)
@@ -549,19 +549,19 @@ func TestSPIFFEFederationService_ListSPIFFEFederations(t *testing.T) {
iterations := 0
for {
iterations++
- resp, err := client.SPIFFEFederationServiceClient().ListSPIFFEFederations(ctx, &machineidv1pb.ListSPIFFEFederationsRequest{
+ resp, err := client.SPIFFEFederationServiceClient().ListSPIFFEFederations(ctx, machineidv1pb.ListSPIFFEFederationsRequest_builder{
PageSize: int32(tt.pageSize),
PageToken: token,
- })
+ }.Build())
tt.requireError(t, err)
if err != nil {
return
}
- fetched = append(fetched, resp.SpiffeFederations...)
- if resp.NextPageToken == "" {
+ fetched = append(fetched, resp.GetSpiffeFederations()...)
+ if resp.GetNextPageToken() == "" {
break
}
- token = resp.NextPageToken
+ token = resp.GetNextPageToken()
}
if tt.assertResponse {
require.Equal(t, tt.wantIterations, iterations)
diff --git a/lib/auth/machineid/machineidv1/spiffe_federation_syncer.go b/lib/auth/machineid/machineidv1/spiffe_federation_syncer.go
index 127ee4516a0..b018a13936c 100644
--- a/lib/auth/machineid/machineidv1/spiffe_federation_syncer.go
+++ b/lib/auth/machineid/machineidv1/spiffe_federation_syncer.go
@@ -484,20 +484,20 @@ func (s *SPIFFEFederationSyncer) shouldSyncTrustDomain(
log *slog.Logger,
in *machineidv1.SPIFFEFederation,
) string {
- if in.Status == nil {
+ if !in.HasStatus() {
log.DebugContext(ctx, "No status, will sync")
return "no_status"
}
- if in.Status.CurrentBundle == "" {
+ if in.GetStatus().GetCurrentBundle() == "" {
log.DebugContext(ctx, "No status.current_bundle, will sync")
return "no_current_bundle"
}
- if in.Status.CurrentBundleSyncedAt.AsTime().IsZero() {
+ if in.GetStatus().GetCurrentBundleSyncedAt().AsTime().IsZero() {
log.DebugContext(ctx, "No status.current_bundle_synced_at, will sync")
return "no_current_bundle_synced_at"
}
// Check if we've passed the next sync time.
- nextSyncAt := in.Status.NextSyncAt.AsTime()
+ nextSyncAt := in.GetStatus().GetNextSyncAt().AsTime()
now := s.cfg.Clock.Now()
if !nextSyncAt.IsZero() && now.After(nextSyncAt) {
log.DebugContext(
@@ -509,8 +509,8 @@ func (s *SPIFFEFederationSyncer) shouldSyncTrustDomain(
return "next_sync_at_passed"
}
// Check to see if the configured bundle source has changed
- if in.Status.CurrentBundleSyncedFrom != nil {
- if !proto.Equal(in.Spec.BundleSource, in.Status.CurrentBundleSyncedFrom) {
+ if in.GetStatus().HasCurrentBundleSyncedFrom() {
+ if !proto.Equal(in.GetSpec().GetBundleSource(), in.GetStatus().GetCurrentBundleSyncedFrom()) {
log.DebugContext(ctx, "status.current_bundle_synced_from has changed, will sync")
return "bundle_source_changed"
}
@@ -554,15 +554,15 @@ func (s *SPIFFEFederationSyncer) syncTrustDomain(
out = proto.Clone(current).(*machineidv1.SPIFFEFederation)
// Refresh...
- if out.Status == nil {
- out.Status = &machineidv1.SPIFFEFederationStatus{}
+ if !out.HasStatus() {
+ out.SetStatus(&machineidv1.SPIFFEFederationStatus{})
}
var bundle *spiffebundle.Bundle
var nextSyncIn time.Duration
switch {
case current.GetSpec().GetBundleSource().GetHttpsWeb() != nil:
- url := current.Spec.BundleSource.HttpsWeb.BundleEndpointUrl
+ url := current.GetSpec().GetBundleSource().GetHttpsWeb().GetBundleEndpointUrl()
log.DebugContext(
ctx,
"Fetching bundle using https_web profile",
@@ -602,7 +602,7 @@ func (s *SPIFFEFederationSyncer) syncTrustDomain(
ctx, "Fetching bundle using spec.bundle_source.static.bundle",
)
bundle, err = spiffebundle.Parse(
- td, []byte(current.Spec.BundleSource.Static.Bundle),
+ td, []byte(current.GetSpec().GetBundleSource().GetStatic().GetBundle()),
)
if err != nil {
return nil, trace.Wrap(
@@ -619,14 +619,14 @@ func (s *SPIFFEFederationSyncer) syncTrustDomain(
if err != nil {
return nil, trace.Wrap(err, "marshaling bundle")
}
- out.Status.CurrentBundle = string(bundleBytes)
- out.Status.CurrentBundleSyncedFrom = current.Spec.BundleSource
+ out.GetStatus().SetCurrentBundle(string(bundleBytes))
+ out.GetStatus().SetCurrentBundleSyncedFrom(current.GetSpec().GetBundleSource())
syncedAt := s.cfg.Clock.Now().UTC()
- out.Status.CurrentBundleSyncedAt = timestamppb.New(syncedAt)
+ out.GetStatus().SetCurrentBundleSyncedAt(timestamppb.New(syncedAt))
// For certain sources, we need to set a next sync time.
if nextSyncIn > 0 {
- out.Status.NextSyncAt = timestamppb.New(syncedAt.Add(nextSyncIn))
+ out.GetStatus().SetNextSyncAt(timestamppb.New(syncedAt.Add(nextSyncIn)))
}
out, err = s.cfg.Store.UpdateSPIFFEFederation(ctx, out)
@@ -638,7 +638,7 @@ func (s *SPIFFEFederationSyncer) syncTrustDomain(
log.InfoContext(
ctx,
"Sync succeeded, new SPIFFEFederation persisted",
- "new_revision", out.Metadata.Revision,
+ "new_revision", out.GetMetadata().GetRevision(),
)
return out, nil
diff --git a/lib/auth/machineid/machineidv1/spiffe_federation_syncer_test.go b/lib/auth/machineid/machineidv1/spiffe_federation_syncer_test.go
index 9d3cb138238..66744d8dcb4 100644
--- a/lib/auth/machineid/machineidv1/spiffe_federation_syncer_test.go
+++ b/lib/auth/machineid/machineidv1/spiffe_federation_syncer_test.go
@@ -104,20 +104,20 @@ func TestSPIFFEFederationSyncer(t *testing.T) {
caPool.AddCert(testSrv2.Certificate())
// Create one trust domain prior to startng the syncer
- created1, err := store.CreateSPIFFEFederation(ctx, &machineidv1pb.SPIFFEFederation{
+ created1, err := store.CreateSPIFFEFederation(ctx, machineidv1pb.SPIFFEFederation_builder{
Kind: types.KindSPIFFEFederation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "1.example.com",
- },
- Spec: &machineidv1pb.SPIFFEFederationSpec{
- BundleSource: &machineidv1pb.SPIFFEFederationBundleSource{
- HttpsWeb: &machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb{
+ }.Build(),
+ Spec: machineidv1pb.SPIFFEFederationSpec_builder{
+ BundleSource: machineidv1pb.SPIFFEFederationBundleSource_builder{
+ HttpsWeb: machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb_builder{
BundleEndpointUrl: testSrv1.URL,
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
syncer, err := NewSPIFFEFederationSyncer(SPIFFEFederationSyncerConfig{
@@ -141,41 +141,41 @@ func TestSPIFFEFederationSyncer(t *testing.T) {
// Wait for the initially created SPIFFEFederation to be synced
require.EventuallyWithT(t, func(t *assert.CollectT) {
- got, err := store.GetSPIFFEFederation(ctx, created1.Metadata.Name)
+ got, err := store.GetSPIFFEFederation(ctx, created1.GetMetadata().GetName())
require.NoError(t, err)
// Check that some update as occurred (as indicated by the revision)
- require.NotEqual(t, got.Metadata.Revision, created1.Metadata.Revision)
+ require.NotEqual(t, got.GetMetadata().GetRevision(), created1.GetMetadata().GetRevision())
// Check that the expected status fields have been set...
- require.NotNil(t, got.Status)
- require.Equal(t, string(marshaledBundle1), got.Status.CurrentBundle)
+ require.NotNil(t, got.GetStatus())
+ require.Equal(t, string(marshaledBundle1), got.GetStatus().GetCurrentBundle())
}, time.Second*10, time.Millisecond*200)
// Create a second SPIFFEFederation and wait for it to be synced
- created2, err := store.CreateSPIFFEFederation(ctx, &machineidv1pb.SPIFFEFederation{
+ created2, err := store.CreateSPIFFEFederation(ctx, machineidv1pb.SPIFFEFederation_builder{
Kind: types.KindSPIFFEFederation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "2.example.com",
- },
- Spec: &machineidv1pb.SPIFFEFederationSpec{
- BundleSource: &machineidv1pb.SPIFFEFederationBundleSource{
- HttpsWeb: &machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb{
+ }.Build(),
+ Spec: machineidv1pb.SPIFFEFederationSpec_builder{
+ BundleSource: machineidv1pb.SPIFFEFederationBundleSource_builder{
+ HttpsWeb: machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb_builder{
BundleEndpointUrl: testSrv2.URL,
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
require.EventuallyWithT(t, func(t *assert.CollectT) {
- got, err := store.GetSPIFFEFederation(ctx, created2.Metadata.Name)
+ got, err := store.GetSPIFFEFederation(ctx, created2.GetMetadata().GetName())
require.NoError(t, err)
// Check that some update as occurred (as indicated by the revision)
- require.NotEqual(t, got.Metadata.Revision, created2.Metadata.Revision)
+ require.NotEqual(t, got.GetMetadata().GetRevision(), created2.GetMetadata().GetRevision())
// Check that the expected status fields have been set...
- require.NotNil(t, got.Status)
- require.Equal(t, string(marshaledBundle2), got.Status.CurrentBundle)
+ require.NotNil(t, got.GetStatus())
+ require.Equal(t, string(marshaledBundle2), got.GetStatus().GetCurrentBundle())
}, time.Second*10, time.Millisecond*200)
cancel()
@@ -231,20 +231,20 @@ func TestSPIFFEFederationSyncer_syncFederation(t *testing.T) {
require.NoError(t, err)
t.Run("https-web", func(t *testing.T) {
- in := &machineidv1pb.SPIFFEFederation{
+ in := machineidv1pb.SPIFFEFederation_builder{
Kind: types.KindSPIFFEFederation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "example.com",
- },
- Spec: &machineidv1pb.SPIFFEFederationSpec{
- BundleSource: &machineidv1pb.SPIFFEFederationBundleSource{
- HttpsWeb: &machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb{
+ }.Build(),
+ Spec: machineidv1pb.SPIFFEFederationSpec_builder{
+ BundleSource: machineidv1pb.SPIFFEFederationBundleSource_builder{
+ HttpsWeb: machineidv1pb.SPIFFEFederationBundleSourceHTTPSWeb_builder{
BundleEndpointUrl: testSrv.URL,
- },
- },
- },
- }
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build()
created, err := store.CreateSPIFFEFederation(ctx, in)
require.NoError(t, err)
@@ -255,16 +255,16 @@ func TestSPIFFEFederationSyncer_syncFederation(t *testing.T) {
// Require that the persisted resource equals the resource output by syncTrustDomain
require.Empty(t, cmp.Diff(got, firstSync, protocmp.Transform()))
// Check that some update as occurred (as indicated by the revision)
- require.NotEqual(t, created.Metadata.Revision, firstSync.Metadata.Revision)
+ require.NotEqual(t, created.GetMetadata().GetRevision(), firstSync.GetMetadata().GetRevision())
// Check that the expected status fields have been set...
- require.NotNil(t, firstSync.Status)
- wantStatus := &machineidv1pb.SPIFFEFederationStatus{
+ require.NotNil(t, firstSync.GetStatus())
+ wantStatus := machineidv1pb.SPIFFEFederationStatus_builder{
CurrentBundleSyncedAt: timestamppb.New(clock.Now().UTC()),
- CurrentBundleSyncedFrom: proto.Clone(created).(*machineidv1pb.SPIFFEFederation).Spec.BundleSource,
+ CurrentBundleSyncedFrom: proto.Clone(created).(*machineidv1pb.SPIFFEFederation).GetSpec().GetBundleSource(),
NextSyncAt: timestamppb.New(clock.Now().UTC().Add(time.Minute * 12)),
CurrentBundle: string(marshaledBundle),
- }
- require.Empty(t, cmp.Diff(firstSync.Status, wantStatus, protocmp.Transform()))
+ }.Build()
+ require.Empty(t, cmp.Diff(firstSync.GetStatus(), wantStatus, protocmp.Transform()))
// Check that syncing again does nothing.
secondSync, err := syncer.syncTrustDomain(ctx, "example.com")
@@ -275,14 +275,14 @@ func TestSPIFFEFederationSyncer_syncFederation(t *testing.T) {
clock.Advance(time.Minute * 15)
thirdSync, err := syncer.syncTrustDomain(ctx, "example.com")
require.NoError(t, err)
- require.NotEqual(t, firstSync.Metadata.Revision, thirdSync.Metadata.Revision)
- wantStatus = &machineidv1pb.SPIFFEFederationStatus{
+ require.NotEqual(t, firstSync.GetMetadata().GetRevision(), thirdSync.GetMetadata().GetRevision())
+ wantStatus = machineidv1pb.SPIFFEFederationStatus_builder{
CurrentBundleSyncedAt: timestamppb.New(clock.Now().UTC()),
- CurrentBundleSyncedFrom: proto.Clone(created).(*machineidv1pb.SPIFFEFederation).Spec.BundleSource,
+ CurrentBundleSyncedFrom: proto.Clone(created).(*machineidv1pb.SPIFFEFederation).GetSpec().GetBundleSource(),
NextSyncAt: timestamppb.New(clock.Now().UTC().Add(time.Minute * 12)),
CurrentBundle: string(marshaledBundle),
- }
- require.Empty(t, cmp.Diff(thirdSync.Status, wantStatus, protocmp.Transform()))
+ }.Build()
+ require.Empty(t, cmp.Diff(thirdSync.GetStatus(), wantStatus, protocmp.Transform()))
// Check that syncing again does nothing.
fourthSync, err := syncer.syncTrustDomain(ctx, "example.com")
@@ -290,18 +290,18 @@ func TestSPIFFEFederationSyncer_syncFederation(t *testing.T) {
require.Empty(t, cmp.Diff(fourthSync, thirdSync, protocmp.Transform()))
// Check that modifying the bundle source triggers a sync.
- fourthSync.Spec.BundleSource.HttpsWeb.BundleEndpointUrl = fmt.Sprintf("%s/modified", testSrv.URL)
+ fourthSync.GetSpec().GetBundleSource().GetHttpsWeb().SetBundleEndpointUrl(fmt.Sprintf("%s/modified", testSrv.URL))
updated, err := store.UpdateSPIFFEFederation(ctx, fourthSync)
require.NoError(t, err)
fifthSync, err := syncer.syncTrustDomain(ctx, "example.com")
require.NoError(t, err)
- require.NotEqual(t, updated.Metadata.Revision, fifthSync.Metadata.Revision)
- wantStatus = &machineidv1pb.SPIFFEFederationStatus{
+ require.NotEqual(t, updated.GetMetadata().GetRevision(), fifthSync.GetMetadata().GetRevision())
+ wantStatus = machineidv1pb.SPIFFEFederationStatus_builder{
CurrentBundleSyncedAt: timestamppb.New(clock.Now().UTC()),
- CurrentBundleSyncedFrom: proto.Clone(updated).(*machineidv1pb.SPIFFEFederation).Spec.BundleSource,
+ CurrentBundleSyncedFrom: proto.Clone(updated).(*machineidv1pb.SPIFFEFederation).GetSpec().GetBundleSource(),
NextSyncAt: timestamppb.New(clock.Now().UTC().Add(time.Minute * 12)),
CurrentBundle: string(marshaledBundle),
- }
- require.Empty(t, cmp.Diff(fifthSync.Status, wantStatus, protocmp.Transform()))
+ }.Build()
+ require.Empty(t, cmp.Diff(fifthSync.GetStatus(), wantStatus, protocmp.Transform()))
})
}
diff --git a/lib/auth/machineid/machineidv1/workload_identity_service.go b/lib/auth/machineid/machineidv1/workload_identity_service.go
index a761f7553c3..65694839420 100644
--- a/lib/auth/machineid/machineidv1/workload_identity_service.go
+++ b/lib/auth/machineid/machineidv1/workload_identity_service.go
@@ -242,10 +242,10 @@ func (wis *WorkloadIdentityService) signX509SVID(
},
UserMetadata: authz.ClientUserMetadata(ctx),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
- Hint: req.Hint,
+ Hint: req.GetHint(),
SVIDType: "x509",
- DNSSANs: req.DnsSans,
- IPSANs: req.IpSans,
+ DNSSANs: req.GetDnsSans(),
+ IPSANs: req.GetIpSans(),
}
if err != nil {
evt.Code = events.SPIFFESVIDIssuedFailureCode
@@ -265,25 +265,25 @@ func (wis *WorkloadIdentityService) signX509SVID(
// Parse and validate parameters
switch {
- case req.SpiffeIdPath == "":
+ case req.GetSpiffeIdPath() == "":
return nil, trace.BadParameter("spiffeIdPath: must be non-empty")
- case !strings.HasPrefix(req.SpiffeIdPath, "/"):
+ case !strings.HasPrefix(req.GetSpiffeIdPath(), "/"):
return nil, trace.BadParameter("spiffeIdPath: must start with '/'")
- case len(req.PublicKey) == 0:
+ case len(req.GetPublicKey()) == 0:
return nil, trace.BadParameter("publicKey: must be non-empty")
}
spiffeID, err = spiffeid.FromURI(&url.URL{
Scheme: spiffeScheme,
Host: clusterName,
- Path: req.SpiffeIdPath,
+ Path: req.GetSpiffeIdPath(),
})
if err != nil {
return nil, trace.Wrap(err, "creating SPIFFE ID")
}
ipSans := []net.IP{}
- for i, stringIP := range req.IpSans {
+ for i, stringIP := range req.GetIpSans() {
ip := net.ParseIP(stringIP)
if ip == nil {
return nil, trace.BadParameter(
@@ -296,7 +296,7 @@ func (wis *WorkloadIdentityService) signX509SVID(
// Default TTL is 1 hour - maximum is 24 hours. If TTL is greater than max,
// we will use the max.
ttl := defaultX509SVIDTTL
- if reqTTL := req.Ttl.AsDuration(); reqTTL > 0 {
+ if reqTTL := req.GetTtl().AsDuration(); reqTTL > 0 {
ttl = reqTTL
}
if ttl > maxSVIDTTL {
@@ -310,8 +310,8 @@ func (wis *WorkloadIdentityService) signX509SVID(
// Perform authz checks. They must be allowed to issue the SPIFFE ID and
// any listed SANs.
if err := authCtx.Checker.CheckSPIFFESVID(
- req.SpiffeIdPath,
- req.DnsSans,
+ req.GetSpiffeIdPath(),
+ req.GetDnsSans(),
ipSans,
); err != nil {
return nil, trace.Wrap(err)
@@ -319,21 +319,21 @@ func (wis *WorkloadIdentityService) signX509SVID(
var pemBytes []byte
pemBytes, serialNumber, err = signx509SVID(
- notBefore, notAfter, ca, req.PublicKey, spiffeID.URL(), req.DnsSans, ipSans,
+ notBefore, notAfter, ca, req.GetPublicKey(), spiffeID.URL(), req.GetDnsSans(), ipSans,
)
if err != nil {
return nil, trace.Wrap(err)
}
- return &pb.SVIDResponse{
+ return pb.SVIDResponse_builder{
SpiffeId: spiffeID.String(),
- Hint: req.Hint,
+ Hint: req.GetHint(),
Certificate: pemBytes,
- }, nil
+ }.Build(), nil
}
func (wis *WorkloadIdentityService) SignX509SVIDs(ctx context.Context, req *pb.SignX509SVIDsRequest) (*pb.SignX509SVIDsResponse, error) {
- if len(req.Svids) == 0 {
+ if len(req.GetSvids()) == 0 {
return nil, trace.BadParameter("svids: must be non-empty")
}
@@ -364,14 +364,14 @@ func (wis *WorkloadIdentityService) SignX509SVIDs(ctx context.Context, req *pb.S
}
res := &pb.SignX509SVIDsResponse{}
- for i, svidReq := range req.Svids {
+ for i, svidReq := range req.GetSvids() {
svidRes, err := wis.signX509SVID(
ctx, authCtx, svidReq, clusterName.GetClusterName(), tlsCA,
)
if err != nil {
return nil, trace.Wrap(err, "signing svid %d", i)
}
- res.Svids = append(res.Svids, svidRes)
+ res.SetSvids(append(res.GetSvids(), svidRes))
}
wis.logger.WarnContext(
@@ -400,9 +400,9 @@ func (wis *WorkloadIdentityService) signJWTSVID(
},
UserMetadata: authz.ClientUserMetadata(ctx),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
- Hint: req.Hint,
+ Hint: req.GetHint(),
SVIDType: "jwt",
- Audiences: req.Audiences,
+ Audiences: req.GetAudiences(),
}
if err != nil {
evt.Code = events.SPIFFESVIDIssuedFailureCode
@@ -423,18 +423,18 @@ func (wis *WorkloadIdentityService) signJWTSVID(
}()
switch {
- case req.SpiffeIdPath == "":
+ case req.GetSpiffeIdPath() == "":
return nil, trace.BadParameter("spiffe_id_path: must be non-empty")
- case !strings.HasPrefix(req.SpiffeIdPath, "/"):
+ case !strings.HasPrefix(req.GetSpiffeIdPath(), "/"):
return nil, trace.BadParameter("spiffe_id_path: must start with '/'")
- case len(req.Audiences) == 0:
+ case len(req.GetAudiences()) == 0:
return nil, trace.BadParameter("audiences: must be non-empty")
}
// Perform authz checks. They must be allowed to issue the SPIFFE ID. Since
// this is a JWT SVID, there are no SANs to check.
if err := authCtx.Checker.CheckSPIFFESVID(
- req.SpiffeIdPath,
+ req.GetSpiffeIdPath(),
[]string{},
[]net.IP{},
); err != nil {
@@ -450,14 +450,14 @@ func (wis *WorkloadIdentityService) signJWTSVID(
spiffeID, err = spiffeid.FromURI(&url.URL{
Scheme: spiffeScheme,
Host: clusterName,
- Path: req.SpiffeIdPath,
+ Path: req.GetSpiffeIdPath(),
})
if err != nil {
return nil, trace.Wrap(err, "creating SPIFFE ID")
}
ttl := defaultJWTSVIDTTL
- if reqTTL := req.Ttl.AsDuration(); reqTTL > 0 {
+ if reqTTL := req.GetTtl().AsDuration(); reqTTL > 0 {
ttl = reqTTL
}
if ttl > maxSVIDTTL {
@@ -465,7 +465,7 @@ func (wis *WorkloadIdentityService) signJWTSVID(
}
signed, err := key.SignJWTSVID(jwt.SignParamsJWTSVID{
- Audiences: req.Audiences,
+ Audiences: req.GetAudiences(),
SPIFFEID: spiffeID,
TTL: ttl,
JTI: jti,
@@ -475,20 +475,20 @@ func (wis *WorkloadIdentityService) signJWTSVID(
return nil, trace.Wrap(err, "signing jwt")
}
- return &pb.JWTSVIDResponse{
- Audiences: req.Audiences,
+ return pb.JWTSVIDResponse_builder{
+ Audiences: req.GetAudiences(),
Jwt: signed,
SpiffeId: spiffeID.String(),
Jti: jti,
- Hint: req.Hint,
- }, nil
+ Hint: req.GetHint(),
+ }.Build(), nil
}
// SignJWTSVIDs signs and returns the requested JWT SVIDs.
func (wis *WorkloadIdentityService) SignJWTSVIDs(
ctx context.Context, req *pb.SignJWTSVIDsRequest,
) (*pb.SignJWTSVIDsResponse, error) {
- if len(req.Svids) == 0 {
+ if len(req.GetSvids()) == 0 {
return nil, trace.BadParameter("svids: must be non-empty")
}
@@ -528,14 +528,14 @@ func (wis *WorkloadIdentityService) SignJWTSVIDs(
}
res := &pb.SignJWTSVIDsResponse{}
- for i, svidReq := range req.Svids {
+ for i, svidReq := range req.GetSvids() {
svidRes, err := wis.signJWTSVID(
ctx, authCtx, clusterName.GetClusterName(), issuer, jwtKey, svidReq,
)
if err != nil {
return nil, trace.Wrap(err, "signing svid %d", i)
}
- res.Svids = append(res.Svids, svidRes)
+ res.SetSvids(append(res.GetSvids(), svidRes))
}
wis.logger.WarnContext(
diff --git a/lib/auth/machineid/machineidv1/workload_identity_service_test.go b/lib/auth/machineid/machineidv1/workload_identity_service_test.go
index 0563b08281a..e6bd8707f1a 100644
--- a/lib/auth/machineid/machineidv1/workload_identity_service_test.go
+++ b/lib/auth/machineid/machineidv1/workload_identity_service_test.go
@@ -108,9 +108,9 @@ func TestWorkloadIdentityService_SignX509SVIDs(t *testing.T) {
{
name: "success",
user: authorizedUser.GetName(),
- req: &machineidv1pb.SignX509SVIDsRequest{
+ req: machineidv1pb.SignX509SVIDsRequest_builder{
Svids: []*machineidv1pb.SVIDRequest{
- {
+ machineidv1pb.SVIDRequest_builder{
SpiffeIdPath: "/alpha/foo",
PublicKey: pubBytes,
Hint: "llamas",
@@ -120,19 +120,19 @@ func TestWorkloadIdentityService_SignX509SVIDs(t *testing.T) {
"bar.alpha.example.com",
},
IpSans: []string{"10.42.42.42"},
- },
+ }.Build(),
},
- },
+ }.Build(),
requireError: require.NoError,
assertResponse: func(t *testing.T, resp *machineidv1pb.SignX509SVIDsResponse) {
wantSPIFFEID := "spiffe://localhost/alpha/foo"
// Parse response
- require.Len(t, resp.Svids, 1)
- svid := resp.Svids[0]
- require.Equal(t, "llamas", svid.Hint)
- require.Equal(t, wantSPIFFEID, svid.SpiffeId)
- cert, err := x509.ParseCertificate(svid.Certificate)
+ require.Len(t, resp.GetSvids(), 1)
+ svid := resp.GetSvids()[0]
+ require.Equal(t, "llamas", svid.GetHint())
+ require.Equal(t, wantSPIFFEID, svid.GetSpiffeId())
+ cert, err := x509.ParseCertificate(svid.GetCertificate())
require.NoError(t, err)
// Check TTL
@@ -174,20 +174,20 @@ func TestWorkloadIdentityService_SignX509SVIDs(t *testing.T) {
{
name: "forbidden svid",
user: authorizedUser.GetName(),
- req: &machineidv1pb.SignX509SVIDsRequest{
+ req: machineidv1pb.SignX509SVIDsRequest_builder{
Svids: []*machineidv1pb.SVIDRequest{
// Include an ok SVID first to ensure we check perms for all
// SVIDs.
- {
+ machineidv1pb.SVIDRequest_builder{
SpiffeIdPath: "/alpha/foo",
PublicKey: pubBytes,
- },
- {
+ }.Build(),
+ machineidv1pb.SVIDRequest_builder{
SpiffeIdPath: "/alpha/forbidden",
PublicKey: pubBytes,
- },
+ }.Build(),
},
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -204,14 +204,14 @@ func TestWorkloadIdentityService_SignX509SVIDs(t *testing.T) {
{
name: "no permissions",
user: unauthorizedUser.GetName(),
- req: &machineidv1pb.SignX509SVIDsRequest{
+ req: machineidv1pb.SignX509SVIDsRequest_builder{
Svids: []*machineidv1pb.SVIDRequest{
- {
+ machineidv1pb.SVIDRequest_builder{
SpiffeIdPath: "/alpha/foo",
PublicKey: pubBytes,
- },
+ }.Build(),
},
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -309,29 +309,29 @@ func TestWorkloadIdentityService_SignJWTSVIDs(t *testing.T) {
{
name: "success",
user: authorizedUser.GetName(),
- req: &machineidv1pb.SignJWTSVIDsRequest{
+ req: machineidv1pb.SignJWTSVIDsRequest_builder{
Svids: []*machineidv1pb.JWTSVIDRequest{
- {
+ machineidv1pb.JWTSVIDRequest_builder{
SpiffeIdPath: "/alpha/foo",
Hint: "llamas",
Ttl: durationpb.New(30 * time.Minute),
Audiences: []string{"example.com"},
- },
+ }.Build(),
},
- },
+ }.Build(),
requireError: require.NoError,
assertResponse: func(t *testing.T, resp *machineidv1pb.SignJWTSVIDsResponse) {
- require.Len(t, resp.Svids, 1)
+ require.Len(t, resp.GetSvids(), 1)
- svid := resp.Svids[0]
+ svid := resp.GetSvids()[0]
wantSPIFFEID := "spiffe://localhost/alpha/foo"
- require.Equal(t, wantSPIFFEID, svid.SpiffeId)
- require.Equal(t, "llamas", svid.Hint)
- require.Equal(t, []string{"example.com"}, svid.Audiences)
- require.NotEmpty(t, svid.Jti)
- require.NotEmpty(t, svid.Jwt)
+ require.Equal(t, wantSPIFFEID, svid.GetSpiffeId())
+ require.Equal(t, "llamas", svid.GetHint())
+ require.Equal(t, []string{"example.com"}, svid.GetAudiences())
+ require.NotEmpty(t, svid.GetJti())
+ require.NotEmpty(t, svid.GetJwt())
- parsed, err := jwt.ParseSigned(svid.Jwt)
+ parsed, err := jwt.ParseSigned(svid.GetJwt())
require.NoError(t, err)
claims := jwt.Claims{}
@@ -344,7 +344,7 @@ func TestWorkloadIdentityService_SignJWTSVIDs(t *testing.T) {
// Check claims
require.Equal(t, wantSPIFFEID, claims.Subject)
- require.Equal(t, svid.Jti, claims.ID)
+ require.Equal(t, svid.GetJti(), claims.ID)
require.Equal(t, "example.com", claims.Audience[0])
require.Equal(t, wantIssuer, claims.Issuer)
require.WithinDuration(t, srv.Clock().Now().Add(30*time.Minute), claims.Expiry.Time(), 5*time.Second)
@@ -354,20 +354,20 @@ func TestWorkloadIdentityService_SignJWTSVIDs(t *testing.T) {
{
name: "forbidden svid",
user: authorizedUser.GetName(),
- req: &machineidv1pb.SignJWTSVIDsRequest{
+ req: machineidv1pb.SignJWTSVIDsRequest_builder{
Svids: []*machineidv1pb.JWTSVIDRequest{
// Include an ok SVID first to ensure we check perms for all
// SVIDs.
- {
+ machineidv1pb.JWTSVIDRequest_builder{
SpiffeIdPath: "/alpha/foo",
Audiences: []string{"example.com"},
- },
- {
+ }.Build(),
+ machineidv1pb.JWTSVIDRequest_builder{
SpiffeIdPath: "/alpha/forbidden",
Audiences: []string{"example.com"},
- },
+ }.Build(),
},
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -375,14 +375,14 @@ func TestWorkloadIdentityService_SignJWTSVIDs(t *testing.T) {
{
name: "no permissions",
user: unauthorizedUser.GetName(),
- req: &machineidv1pb.SignJWTSVIDsRequest{
+ req: machineidv1pb.SignJWTSVIDsRequest_builder{
Svids: []*machineidv1pb.JWTSVIDRequest{
- {
+ machineidv1pb.JWTSVIDRequest_builder{
SpiffeIdPath: "/alpha/foo",
Audiences: []string{"example.com"},
- },
+ }.Build(),
},
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
diff --git a/lib/auth/machineid/workloadidentityv1/decision.go b/lib/auth/machineid/workloadidentityv1/decision.go
index 47545ff1b4c..dd00127c68d 100644
--- a/lib/auth/machineid/workloadidentityv1/decision.go
+++ b/lib/auth/machineid/workloadidentityv1/decision.go
@@ -75,14 +75,14 @@ func decide(
d.reason = trace.Wrap(err, "templating spec.spiffe.id")
return d
}
- d.templatedWorkloadIdentity.Spec.Spiffe.Id = templated
+ d.templatedWorkloadIdentity.GetSpec().GetSpiffe().SetId(templated)
templated, err = expression.RenderTemplate(wi.GetSpec().GetSpiffe().GetHint(), &expression.Environment{Attrs: attrs})
if err != nil {
d.reason = trace.Wrap(err, "templating spec.spiffe.hint")
return d
}
- d.templatedWorkloadIdentity.Spec.Spiffe.Hint = templated
+ d.templatedWorkloadIdentity.GetSpec().GetSpiffe().SetHint(templated)
for i, san := range wi.GetSpec().GetSpiffe().GetX509().GetDnsSans() {
templated, err = expression.RenderTemplate(san, &expression.Environment{Attrs: attrs})
@@ -98,14 +98,14 @@ func decide(
)
return d
}
- d.templatedWorkloadIdentity.Spec.Spiffe.X509.DnsSans[i] = templated
+ d.templatedWorkloadIdentity.GetSpec().GetSpiffe().GetX509().GetDnsSans()[i] = templated
}
st := wi.GetSpec().GetSpiffe().GetX509().GetSubjectTemplate()
if st != nil {
- dst := d.templatedWorkloadIdentity.Spec.Spiffe.X509.SubjectTemplate
+ dst := d.templatedWorkloadIdentity.GetSpec().GetSpiffe().GetX509().GetSubjectTemplate()
- templated, err = expression.RenderTemplate(st.CommonName, &expression.Environment{Attrs: attrs})
+ templated, err = expression.RenderTemplate(st.GetCommonName(), &expression.Environment{Attrs: attrs})
if err != nil {
d.reason = trace.Wrap(
err,
@@ -113,9 +113,9 @@ func decide(
)
return d
}
- dst.CommonName = templated
+ dst.SetCommonName(templated)
- templated, err = expression.RenderTemplate(st.Organization, &expression.Environment{Attrs: attrs})
+ templated, err = expression.RenderTemplate(st.GetOrganization(), &expression.Environment{Attrs: attrs})
if err != nil {
d.reason = trace.Wrap(
err,
@@ -123,9 +123,9 @@ func decide(
)
return d
}
- dst.Organization = templated
+ dst.SetOrganization(templated)
- templated, err = expression.RenderTemplate(st.OrganizationalUnit, &expression.Environment{Attrs: attrs})
+ templated, err = expression.RenderTemplate(st.GetOrganizationalUnit(), &expression.Environment{Attrs: attrs})
if err != nil {
d.reason = trace.Wrap(
err,
@@ -133,7 +133,7 @@ func decide(
)
return d
}
- dst.OrganizationalUnit = templated
+ dst.SetOrganizationalUnit(templated)
}
if ec := wi.GetSpec().GetSpiffe().GetJwt().GetExtraClaims(); ec != nil {
@@ -145,7 +145,7 @@ func decide(
)
return d
}
- d.templatedWorkloadIdentity.Spec.Spiffe.Jwt.ExtraClaims = templated
+ d.templatedWorkloadIdentity.GetSpec().GetSpiffe().GetJwt().SetExtraClaims(templated)
}
// Yay - made it to the end!
@@ -251,29 +251,29 @@ ruleLoop:
}
for _, condition := range rule.GetConditions() {
- val, err := getFieldStringValue(attrs, condition.Attribute)
+ val, err := getFieldStringValue(attrs, condition.GetAttribute())
if err != nil {
return trace.Wrap(err)
}
- switch c := condition.Operator.(type) {
- case *workloadidentityv1pb.WorkloadIdentityCondition_Eq:
- if val != c.Eq.Value {
+ switch c := condition.WhichOperator(); c {
+ case workloadidentityv1pb.WorkloadIdentityCondition_Eq_case:
+ if val != condition.GetEq().GetValue() {
continue ruleLoop
}
- case *workloadidentityv1pb.WorkloadIdentityCondition_NotEq:
- if val == c.NotEq.Value {
+ case workloadidentityv1pb.WorkloadIdentityCondition_NotEq_case:
+ if val == condition.GetNotEq().GetValue() {
continue ruleLoop
}
- case *workloadidentityv1pb.WorkloadIdentityCondition_In:
- if !slices.Contains(c.In.Values, val) {
+ case workloadidentityv1pb.WorkloadIdentityCondition_In_case:
+ if !slices.Contains(condition.GetIn().GetValues(), val) {
continue ruleLoop
}
- case *workloadidentityv1pb.WorkloadIdentityCondition_NotIn:
- if slices.Contains(c.NotIn.Values, val) {
+ case workloadidentityv1pb.WorkloadIdentityCondition_NotIn_case:
+ if slices.Contains(condition.GetNotIn().GetValues(), val) {
continue ruleLoop
}
default:
- return trace.BadParameter("unsupported operator %T", c)
+ return trace.BadParameter("unsupported operator %v", c)
}
}
return nil
diff --git a/lib/auth/machineid/workloadidentityv1/decision_test.go b/lib/auth/machineid/workloadidentityv1/decision_test.go
index a532eb35900..92415dc3e1c 100644
--- a/lib/auth/machineid/workloadidentityv1/decision_test.go
+++ b/lib/auth/machineid/workloadidentityv1/decision_test.go
@@ -34,17 +34,17 @@ import (
)
func Test_decide(t *testing.T) {
- standardAttrs := &workloadidentityv1pb.Attrs{
- User: &workloadidentityv1pb.UserAttrs{
+ standardAttrs := workloadidentityv1pb.Attrs_builder{
+ User: workloadidentityv1pb.UserAttrs_builder{
Name: "jeff",
- },
- Workload: &workloadidentityv1pb.WorkloadAttrs{
- Kubernetes: &workloadidentityv1pb.WorkloadAttrsKubernetes{
+ }.Build(),
+ Workload: workloadidentityv1pb.WorkloadAttrs_builder{
+ Kubernetes: workloadidentityv1pb.WorkloadAttrsKubernetes_builder{
PodName: "pod1",
Namespace: "default",
- },
- },
- }
+ }.Build(),
+ }.Build(),
+ }.Build()
tests := []struct {
name string
wid *workloadidentityv1pb.WorkloadIdentity
@@ -54,18 +54,18 @@ func Test_decide(t *testing.T) {
}{
{
name: "invalid dns name",
- wid: &workloadidentityv1pb.WorkloadIdentity{
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/valid",
- X509: &workloadidentityv1pb.WorkloadIdentitySPIFFEX509{
+ X509: workloadidentityv1pb.WorkloadIdentitySPIFFEX509_builder{
DnsSans: []string{
"//imvalid;;",
},
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: standardAttrs,
wantIssue: false,
assertReason: func(t require.TestingT, err error, i ...any) {
@@ -83,17 +83,17 @@ func Test_decide(t *testing.T) {
}
func Test_evaluateRules(t *testing.T) {
- attrs := &workloadidentityv1pb.Attrs{
- User: &workloadidentityv1pb.UserAttrs{
+ attrs := workloadidentityv1pb.Attrs_builder{
+ User: workloadidentityv1pb.UserAttrs_builder{
Name: "foo",
- },
- Workload: &workloadidentityv1pb.WorkloadAttrs{
- Kubernetes: &workloadidentityv1pb.WorkloadAttrsKubernetes{
+ }.Build(),
+ Workload: workloadidentityv1pb.WorkloadAttrs_builder{
+ Kubernetes: workloadidentityv1pb.WorkloadAttrsKubernetes_builder{
PodName: "pod1",
Namespace: "default",
- },
- },
- }
+ }.Build(),
+ }.Build(),
+ }.Build()
var noMatchRule require.ErrorAssertionFunc = func(t require.TestingT, err error, i ...any) {
require.Error(t, err)
@@ -108,294 +108,278 @@ func Test_evaluateRules(t *testing.T) {
}{
{
name: "no rules: pass",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
Rules: &workloadidentityv1pb.WorkloadIdentityRules{},
- },
- },
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: require.NoError,
},
{
name: "eq: pass",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_Eq{
- Eq: &workloadidentityv1pb.WorkloadIdentityConditionEq{
- Value: "foo",
- },
- },
- },
+ Eq: workloadidentityv1pb.WorkloadIdentityConditionEq_builder{
+ Value: "foo",
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: require.NoError,
},
{
name: "eq: fail",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_Eq{
- Eq: &workloadidentityv1pb.WorkloadIdentityConditionEq{
- Value: "not-foo",
- },
- },
- },
+ Eq: workloadidentityv1pb.WorkloadIdentityConditionEq_builder{
+ Value: "not-foo",
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: noMatchRule,
},
{
name: "not_eq: pass",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_NotEq{
- NotEq: &workloadidentityv1pb.WorkloadIdentityConditionNotEq{
- Value: "bar",
- },
- },
- },
+ NotEq: workloadidentityv1pb.WorkloadIdentityConditionNotEq_builder{
+ Value: "bar",
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: require.NoError,
},
{
name: "not_eq: fail",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_NotEq{
- NotEq: &workloadidentityv1pb.WorkloadIdentityConditionNotEq{
- Value: "foo",
- },
- },
- },
+ NotEq: workloadidentityv1pb.WorkloadIdentityConditionNotEq_builder{
+ Value: "foo",
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: noMatchRule,
},
{
name: "in: pass",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_In{
- In: &workloadidentityv1pb.WorkloadIdentityConditionIn{
- Values: []string{"bar", "foo"},
- },
- },
- },
+ In: workloadidentityv1pb.WorkloadIdentityConditionIn_builder{
+ Values: []string{"bar", "foo"},
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: require.NoError,
},
{
name: "in: fail",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_In{
- In: &workloadidentityv1pb.WorkloadIdentityConditionIn{
- Values: []string{"bar", "fizz"},
- },
- },
- },
+ In: workloadidentityv1pb.WorkloadIdentityConditionIn_builder{
+ Values: []string{"bar", "fizz"},
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: noMatchRule,
},
{
name: "not_in: pass",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_NotIn{
- NotIn: &workloadidentityv1pb.WorkloadIdentityConditionNotIn{
- Values: []string{"bar", "fizz"},
- },
- },
- },
+ NotIn: workloadidentityv1pb.WorkloadIdentityConditionNotIn_builder{
+ Values: []string{"bar", "fizz"},
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: require.NoError,
},
{
name: "in: fail",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_NotIn{
- NotIn: &workloadidentityv1pb.WorkloadIdentityConditionNotIn{
- Values: []string{"bar", "foo"},
- },
- },
- },
+ NotIn: workloadidentityv1pb.WorkloadIdentityConditionNotIn_builder{
+ Values: []string{"bar", "foo"},
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: noMatchRule,
},
{
name: "expression: pass",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {Expression: `user.name == "foo"`},
+ workloadidentityv1pb.WorkloadIdentityRule_builder{Expression: `user.name == "foo"`}.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: require.NoError,
},
{
name: "expression: fail",
- wid: &workloadidentityv1pb.WorkloadIdentity{
+ wid: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {Expression: `user.name == "not-foo"`},
+ workloadidentityv1pb.WorkloadIdentityRule_builder{Expression: `user.name == "not-foo"`}.Build(),
},
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
attrs: attrs,
requireErr: noMatchRule,
},
@@ -410,16 +394,16 @@ func Test_evaluateRules(t *testing.T) {
}
func Test_decision_sigstore(t *testing.T) {
- identity := &workloadidentityv1pb.WorkloadIdentity{
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ identity := workloadidentityv1pb.WorkloadIdentity_builder{
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {Expression: `sigstore.policy_satisfied("foo") && sigstore.policy_satisfied("bar")`},
+ workloadidentityv1pb.WorkloadIdentityRule_builder{Expression: `sigstore.policy_satisfied("foo") && sigstore.policy_satisfied("bar")`}.Build(),
},
- },
+ }.Build(),
Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{},
- },
- }
+ }.Build(),
+ }.Build()
attrs := &workloadidentityv1pb.Attrs{}
t.Run("success", func(t *testing.T) {
@@ -530,19 +514,19 @@ func TestTemplateExtraClaims_Success(t *testing.T) {
err = json.Unmarshal([]byte(expectedOutputJSON), &expectedOutput)
require.NoError(t, err)
- output, err := templateExtraClaims(input, &workloadidentityv1pb.Attrs{
- User: &workloadidentityv1pb.UserAttrs{
+ output, err := templateExtraClaims(input, workloadidentityv1pb.Attrs_builder{
+ User: workloadidentityv1pb.UserAttrs_builder{
Name: "Bobby",
- },
- Workload: &workloadidentityv1pb.WorkloadAttrs{
- Podman: &workloadidentityv1pb.WorkloadAttrsPodman{
- Pod: &workloadidentityv1pb.WorkloadAttrsPodmanPod{
+ }.Build(),
+ Workload: workloadidentityv1pb.WorkloadAttrs_builder{
+ Podman: workloadidentityv1pb.WorkloadAttrsPodman_builder{
+ Pod: workloadidentityv1pb.WorkloadAttrsPodmanPod_builder{
Name: "webserver",
Labels: map[string]string{"a": "a", "b": "b"},
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
require.Empty(t, cmp.Diff(expectedOutput, output, protocmp.Transform()))
}
diff --git a/lib/auth/machineid/workloadidentityv1/expression/evaluate_test.go b/lib/auth/machineid/workloadidentityv1/expression/evaluate_test.go
index 3331c39cd97..3d9b72707f9 100644
--- a/lib/auth/machineid/workloadidentityv1/expression/evaluate_test.go
+++ b/lib/auth/machineid/workloadidentityv1/expression/evaluate_test.go
@@ -35,16 +35,16 @@ func TestEvaluate(t *testing.T) {
result, err := expression.Evaluate(
`workload.podman.attested && workload.podman.container.image == "ubuntu"`,
&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
- Workload: &workloadidentityv1.WorkloadAttrs{
- Podman: &workloadidentityv1.WorkloadAttrsPodman{
+ Attrs: workloadidentityv1.Attrs_builder{
+ Workload: workloadidentityv1.WorkloadAttrs_builder{
+ Podman: workloadidentityv1.WorkloadAttrsPodman_builder{
Attested: true,
- Container: &workloadidentityv1.WorkloadAttrsPodmanContainer{
+ Container: workloadidentityv1.WorkloadAttrsPodmanContainer_builder{
Image: "ubuntu",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
},
)
require.NoError(t, err)
@@ -54,11 +54,11 @@ func TestEvaluate(t *testing.T) {
result, err = expression.Evaluate(
`user.name != user.name`,
&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
- User: &workloadidentityv1.UserAttrs{
+ Attrs: workloadidentityv1.Attrs_builder{
+ User: workloadidentityv1.UserAttrs_builder{
Name: "Bobby",
- },
- },
+ }.Build(),
+ }.Build(),
},
)
require.NoError(t, err)
@@ -68,11 +68,11 @@ func TestEvaluate(t *testing.T) {
result, err = expression.Evaluate(
`user.name == ""`,
&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
- User: &workloadidentityv1.UserAttrs{
+ Attrs: workloadidentityv1.Attrs_builder{
+ User: workloadidentityv1.UserAttrs_builder{
Name: "",
- },
- },
+ }.Build(),
+ }.Build(),
},
)
require.NoError(t, err)
@@ -87,26 +87,26 @@ func TestEvaluate_Errors(t *testing.T) {
}{
"unset sub-message": {
expr: `workload.podman.pod.labels["foo"] == "bar"`,
- attrs: &workloadidentityv1.Attrs{
- Workload: &workloadidentityv1.WorkloadAttrs{
- Podman: &workloadidentityv1.WorkloadAttrsPodman{
+ attrs: workloadidentityv1.Attrs_builder{
+ Workload: workloadidentityv1.WorkloadAttrs_builder{
+ Podman: workloadidentityv1.WorkloadAttrsPodman_builder{
Pod: nil,
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
err: "workload.podman.pod is unset",
},
"unset map key": {
expr: `workload.podman.pod.labels["foo"] == "bar"`,
- attrs: &workloadidentityv1.Attrs{
- Workload: &workloadidentityv1.WorkloadAttrs{
- Podman: &workloadidentityv1.WorkloadAttrsPodman{
- Pod: &workloadidentityv1.WorkloadAttrsPodmanPod{
+ attrs: workloadidentityv1.Attrs_builder{
+ Workload: workloadidentityv1.WorkloadAttrs_builder{
+ Podman: workloadidentityv1.WorkloadAttrsPodman_builder{
+ Pod: workloadidentityv1.WorkloadAttrsPodmanPod_builder{
Labels: map[string]string{"bar": "baz"},
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
err: `no value for key: "foo"`,
},
"non-boolean expression": {
@@ -127,16 +127,16 @@ func TestEvaluate_Traits(t *testing.T) {
result, err := expression.Evaluate(
`user.traits.logins.contains("root")`,
&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
- User: &workloadidentityv1.UserAttrs{
+ Attrs: workloadidentityv1.Attrs_builder{
+ User: workloadidentityv1.UserAttrs_builder{
Traits: []*traitv1.Trait{
- {
+ traitv1.Trait_builder{
Key: "logins",
Values: []string{"root", "alice", "bob"},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
},
)
require.NoError(t, err)
@@ -146,11 +146,11 @@ func TestEvaluate_Traits(t *testing.T) {
result, err = expression.Evaluate(
`is_empty(user.traits.logins)`,
&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
- User: &workloadidentityv1.UserAttrs{
+ Attrs: workloadidentityv1.Attrs_builder{
+ User: workloadidentityv1.UserAttrs_builder{
Traits: []*traitv1.Trait{},
- },
- },
+ }.Build(),
+ }.Build(),
},
)
require.NoError(t, err)
diff --git a/lib/auth/machineid/workloadidentityv1/expression/expression.go b/lib/auth/machineid/workloadidentityv1/expression/expression.go
index 89821e88059..1b088298ff7 100644
--- a/lib/auth/machineid/workloadidentityv1/expression/expression.go
+++ b/lib/auth/machineid/workloadidentityv1/expression/expression.go
@@ -53,7 +53,7 @@ var (
vars["user.traits"] = typical.DynamicMapFunction(func(env *Environment, key string) (expression.Set, error) {
traits := make(map[string][]string)
for _, v := range env.Attrs.GetUser().GetTraits() {
- traits[v.GetKey()] = append(traits[v.GetKey()], v.Values...)
+ traits[v.GetKey()] = append(traits[v.GetKey()], v.GetValues()...)
}
return expression.NewSet(traits[key]...), nil
})
@@ -80,7 +80,7 @@ var (
vars["user.traits"] = typical.DynamicMapFunction(func(env *Environment, key string) (string, error) {
traits := make(map[string][]string)
for _, v := range env.Attrs.GetUser().GetTraits() {
- traits[v.GetKey()] = append(traits[v.GetKey()], v.Values...)
+ traits[v.GetKey()] = append(traits[v.GetKey()], v.GetValues()...)
}
vals := traits[key]
diff --git a/lib/auth/machineid/workloadidentityv1/expression/template_test.go b/lib/auth/machineid/workloadidentityv1/expression/template_test.go
index 74063c8ca01..41663a2d0df 100644
--- a/lib/auth/machineid/workloadidentityv1/expression/template_test.go
+++ b/lib/auth/machineid/workloadidentityv1/expression/template_test.go
@@ -41,36 +41,36 @@ func TestTemplate_Success(t *testing.T) {
},
"simple interpolation": {
tmpl: "{{user.name}}",
- attrs: &workloadidentityv1.Attrs{
- User: &workloadidentityv1.UserAttrs{
+ attrs: workloadidentityv1.Attrs_builder{
+ User: workloadidentityv1.UserAttrs_builder{
Name: "Larry",
- },
- },
+ }.Build(),
+ }.Build(),
output: "Larry",
},
"multiple interpolations": {
tmpl: "{{user.name}} {{user.bot_name}}",
- attrs: &workloadidentityv1.Attrs{
- User: &workloadidentityv1.UserAttrs{
+ attrs: workloadidentityv1.Attrs_builder{
+ User: workloadidentityv1.UserAttrs_builder{
Name: "Larry",
BotName: "LarryBot",
- },
- },
+ }.Build(),
+ }.Build(),
output: "Larry LarryBot",
},
"map access": {
tmpl: `/region/{{workload.podman.pod.labels["com.mycloud/region"]}}/service`,
- attrs: &workloadidentityv1.Attrs{
- Workload: &workloadidentityv1.WorkloadAttrs{
- Podman: &workloadidentityv1.WorkloadAttrsPodman{
- Pod: &workloadidentityv1.WorkloadAttrsPodmanPod{
+ attrs: workloadidentityv1.Attrs_builder{
+ Workload: workloadidentityv1.WorkloadAttrs_builder{
+ Podman: workloadidentityv1.WorkloadAttrsPodman_builder{
+ Pod: workloadidentityv1.WorkloadAttrsPodmanPod_builder{
Labels: map[string]string{
"com.mycloud/region": "eu",
},
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
output: "/region/eu/service",
},
"function calling": {
@@ -100,38 +100,38 @@ func TestTemplate_Success(t *testing.T) {
},
"int interpolation": {
tmpl: `{{ workload.unix.pid }}`,
- attrs: &workloadidentityv1.Attrs{
- Workload: &workloadidentityv1.WorkloadAttrs{
- Unix: &workloadidentityv1.WorkloadAttrsUnix{
+ attrs: workloadidentityv1.Attrs_builder{
+ Workload: workloadidentityv1.WorkloadAttrs_builder{
+ Unix: workloadidentityv1.WorkloadAttrsUnix_builder{
Pid: 1337,
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
output: "1337",
},
"uint interpolation": {
tmpl: `{{ workload.unix.uid }}`,
- attrs: &workloadidentityv1.Attrs{
- Workload: &workloadidentityv1.WorkloadAttrs{
- Unix: &workloadidentityv1.WorkloadAttrsUnix{
+ attrs: workloadidentityv1.Attrs_builder{
+ Workload: workloadidentityv1.WorkloadAttrs_builder{
+ Unix: workloadidentityv1.WorkloadAttrsUnix_builder{
Uid: 1337,
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
output: "1337",
},
"user traits": {
tmpl: `{{user.traits.skill}}`,
- attrs: &workloadidentityv1.Attrs{
- User: &workloadidentityv1.UserAttrs{
+ attrs: workloadidentityv1.Attrs_builder{
+ User: workloadidentityv1.UserAttrs_builder{
Traits: []*traitv1.Trait{
- {
+ traitv1.Trait_builder{
Key: "skill",
Values: []string{"coffee-drinker"},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
output: "coffee-drinker",
},
}
@@ -170,16 +170,16 @@ func TestTemplate_MultipleTraitValues(t *testing.T) {
require.NoError(t, err)
_, err = tmpl.Render(&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
- User: &workloadidentityv1.UserAttrs{
+ Attrs: workloadidentityv1.Attrs_builder{
+ User: workloadidentityv1.UserAttrs_builder{
Traits: []*traitv1.Trait{
- {
+ traitv1.Trait_builder{
Key: "skills",
Values: []string{"sword-fighting", "sonnet-writing"},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
})
require.ErrorContains(t, err, "multiple values")
}
@@ -189,9 +189,9 @@ func TestTemplate_MissingSubmessage(t *testing.T) {
require.NoError(t, err)
_, err = tmpl.Render(&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
+ Attrs: workloadidentityv1.Attrs_builder{
Workload: &workloadidentityv1.WorkloadAttrs{},
- },
+ }.Build(),
})
require.ErrorContains(t, err, "workload.podman is unset")
}
@@ -201,15 +201,15 @@ func TestTemplate_MissingMapValue(t *testing.T) {
require.NoError(t, err)
_, err = tmpl.Render(&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
- Workload: &workloadidentityv1.WorkloadAttrs{
- Podman: &workloadidentityv1.WorkloadAttrsPodman{
- Container: &workloadidentityv1.WorkloadAttrsPodmanContainer{
+ Attrs: workloadidentityv1.Attrs_builder{
+ Workload: workloadidentityv1.WorkloadAttrs_builder{
+ Podman: workloadidentityv1.WorkloadAttrsPodman_builder{
+ Container: workloadidentityv1.WorkloadAttrsPodmanContainer_builder{
Labels: map[string]string{"bar": "baz"},
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
})
require.ErrorContains(t, err, `no value for key: "foo"`)
}
@@ -219,16 +219,16 @@ func TestTemplate_MissingTrait(t *testing.T) {
require.NoError(t, err)
_, err = tmpl.Render(&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
- User: &workloadidentityv1.UserAttrs{
+ Attrs: workloadidentityv1.Attrs_builder{
+ User: workloadidentityv1.UserAttrs_builder{
Traits: []*traitv1.Trait{
- {
+ traitv1.Trait_builder{
Key: "bar",
Values: []string{"baz"},
- },
+ }.Build(),
},
- },
- },
+ }.Build(),
+ }.Build(),
})
require.ErrorContains(t, err, `no value for trait: "foo"`)
}
@@ -238,15 +238,15 @@ func TestTemplate_UnsetValue(t *testing.T) {
require.NoError(t, err)
_, err = tmpl.Render(&expression.Environment{
- Attrs: &workloadidentityv1.Attrs{
- Workload: &workloadidentityv1.WorkloadAttrs{
- Podman: &workloadidentityv1.WorkloadAttrsPodman{
- Container: &workloadidentityv1.WorkloadAttrsPodmanContainer{
+ Attrs: workloadidentityv1.Attrs_builder{
+ Workload: workloadidentityv1.WorkloadAttrs_builder{
+ Podman: workloadidentityv1.WorkloadAttrsPodman_builder{
+ Container: workloadidentityv1.WorkloadAttrsPodmanContainer_builder{
Name: "",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
})
require.ErrorContains(t, err, "workload.podman.container.name is unset")
}
diff --git a/lib/auth/machineid/workloadidentityv1/issuer_service.go b/lib/auth/machineid/workloadidentityv1/issuer_service.go
index 08499ee6dbd..00581c3e850 100644
--- a/lib/auth/machineid/workloadidentityv1/issuer_service.go
+++ b/lib/auth/machineid/workloadidentityv1/issuer_service.go
@@ -170,22 +170,22 @@ func (s *IssuanceService) deriveAttrs(
authzCtx *authz.Context,
workloadAttrs *workloadidentityv1pb.WorkloadAttrs,
) (*workloadidentityv1pb.Attrs, error) {
- attrs := &workloadidentityv1pb.Attrs{
+ attrs := workloadidentityv1pb.Attrs_builder{
Workload: workloadAttrs,
- User: &workloadidentityv1pb.UserAttrs{
+ User: workloadidentityv1pb.UserAttrs_builder{
Name: authzCtx.Identity.GetIdentity().Username,
IsBot: authzCtx.Identity.GetIdentity().BotName != "",
BotName: authzCtx.Identity.GetIdentity().BotName,
Labels: authzCtx.User.GetAllLabels(),
- },
+ }.Build(),
Join: authzCtx.Identity.GetIdentity().JoinAttributes,
- }
+ }.Build()
for key, values := range authzCtx.Identity.GetIdentity().Traits {
- attrs.User.Traits = append(attrs.User.Traits, &traitv1.Trait{
+ attrs.GetUser().SetTraits(append(attrs.GetUser().GetTraits(), traitv1.Trait_builder{
Key: key,
Values: values,
- })
+ }.Build()))
}
return attrs, nil
@@ -242,9 +242,9 @@ func (s *IssuanceService) IssueWorkloadIdentity(
}
var cred *workloadidentityv1pb.Credential
- switch v := req.GetCredential().(type) {
- case *workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams:
- ca, chain, err := s.getX509CA(ctx, types.SPIFFECA, v.X509SvidParams.GetUseIssuerOverrides())
+ switch req.WhichCredential() {
+ case workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams_case:
+ ca, chain, err := s.getX509CA(ctx, types.SPIFFECA, req.GetX509SvidParams().GetUseIssuerOverrides())
if err != nil {
return nil, trace.Wrap(err, "fetching X509 SPIFFE CA")
}
@@ -254,8 +254,8 @@ func (s *IssuanceService) IssueWorkloadIdentity(
ca: ca,
chain: chain,
workloadIdentity: decision.templatedWorkloadIdentity,
- x509Params: v.X509SvidParams,
- requestedTTL: req.RequestedTtl.AsDuration(),
+ x509Params: req.GetX509SvidParams(),
+ requestedTTL: req.GetRequestedTtl().AsDuration(),
attrs: attrs,
sigstorePolicyResults: decision.sigstorePolicyResults,
nameSelector: req.GetName(),
@@ -264,7 +264,7 @@ func (s *IssuanceService) IssueWorkloadIdentity(
if err != nil {
return nil, trace.Wrap(err, "issuing X509 SVID")
}
- case *workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams:
+ case workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams_case:
key, issuer, err := s.getJWTIssuerKey(ctx)
if err != nil {
return nil, trace.Wrap(err, "getting JWT issuer key")
@@ -275,8 +275,8 @@ func (s *IssuanceService) IssueWorkloadIdentity(
issuerKey: key,
issuerURI: issuer,
workloadIdentity: decision.templatedWorkloadIdentity,
- jwtParams: v.JwtSvidParams,
- requestedTTL: req.RequestedTtl.AsDuration(),
+ jwtParams: req.GetJwtSvidParams(),
+ requestedTTL: req.GetRequestedTtl().AsDuration(),
attrs: attrs,
sigstorePolicyResults: decision.sigstorePolicyResults,
nameSelector: req.GetName(),
@@ -286,12 +286,12 @@ func (s *IssuanceService) IssueWorkloadIdentity(
return nil, trace.Wrap(err, "issuing JWT SVID")
}
default:
- return nil, trace.BadParameter("credential: unknown type %T", req.GetCredential())
+ return nil, trace.BadParameter("credential: unknown type %v", req.WhichCredential())
}
- return &workloadidentityv1pb.IssueWorkloadIdentityResponse{
+ return workloadidentityv1pb.IssueWorkloadIdentityResponse_builder{
Credential: cred,
- }, nil
+ }.Build(), nil
}
// maxWorkloadIdentitiesIssued is the maximum number of workload identities that
@@ -305,7 +305,7 @@ func (s *IssuanceService) IssueWorkloadIdentities(
req *workloadidentityv1pb.IssueWorkloadIdentitiesRequest,
) (*workloadidentityv1pb.IssueWorkloadIdentitiesResponse, error) {
switch {
- case len(req.LabelSelectors) == 0:
+ case len(req.GetLabelSelectors()) == 0:
return nil, trace.BadParameter("label_selectors: at least one label selector must be specified")
case req.GetCredential() == nil:
return nil, trace.BadParameter("at least one credential type must be requested")
@@ -328,7 +328,7 @@ func (s *IssuanceService) IssueWorkloadIdentities(
workloadIdentities, err := s.matchingAndAuthorizedWorkloadIdentities(
ctx,
authCtx,
- convertLabels(req.LabelSelectors),
+ convertLabels(req.GetLabelSelectors()),
)
if err != nil {
return nil, trace.Wrap(err)
@@ -352,9 +352,9 @@ func (s *IssuanceService) IssueWorkloadIdentities(
}
creds := make([]*workloadidentityv1pb.Credential, 0, len(shouldIssue))
- switch v := req.GetCredential().(type) {
- case *workloadidentityv1pb.IssueWorkloadIdentitiesRequest_X509SvidParams:
- ca, chain, err := s.getX509CA(ctx, types.SPIFFECA, v.X509SvidParams.GetUseIssuerOverrides())
+ switch req.WhichCredential() {
+ case workloadidentityv1pb.IssueWorkloadIdentitiesRequest_X509SvidParams_case:
+ ca, chain, err := s.getX509CA(ctx, types.SPIFFECA, req.GetX509SvidParams().GetUseIssuerOverrides())
if err != nil {
return nil, trace.Wrap(err, "fetching CA to sign X509 SVID")
}
@@ -365,10 +365,10 @@ func (s *IssuanceService) IssueWorkloadIdentities(
ca: ca,
chain: chain,
workloadIdentity: wi,
- x509Params: v.X509SvidParams,
- requestedTTL: req.RequestedTtl.AsDuration(),
+ x509Params: req.GetX509SvidParams(),
+ requestedTTL: req.GetRequestedTtl().AsDuration(),
attrs: attrs,
- labelSelectors: req.LabelSelectors,
+ labelSelectors: req.GetLabelSelectors(),
},
)
if err != nil {
@@ -380,7 +380,7 @@ func (s *IssuanceService) IssueWorkloadIdentities(
}
creds = append(creds, cred)
}
- case *workloadidentityv1pb.IssueWorkloadIdentitiesRequest_JwtSvidParams:
+ case workloadidentityv1pb.IssueWorkloadIdentitiesRequest_JwtSvidParams_case:
key, issuer, err := s.getJWTIssuerKey(ctx)
if err != nil {
return nil, trace.Wrap(err, "getting JWT issuer key")
@@ -392,10 +392,10 @@ func (s *IssuanceService) IssueWorkloadIdentities(
issuerKey: key,
issuerURI: issuer,
workloadIdentity: wi,
- jwtParams: v.JwtSvidParams,
- requestedTTL: req.RequestedTtl.AsDuration(),
+ jwtParams: req.GetJwtSvidParams(),
+ requestedTTL: req.GetRequestedTtl().AsDuration(),
attrs: attrs,
- labelSelectors: req.LabelSelectors,
+ labelSelectors: req.GetLabelSelectors(),
},
)
if err != nil {
@@ -408,12 +408,12 @@ func (s *IssuanceService) IssueWorkloadIdentities(
creds = append(creds, cred)
}
default:
- return nil, trace.BadParameter("credential: unknown type %T", req.GetCredential())
+ return nil, trace.BadParameter("credential: unknown type %v", req.WhichCredential())
}
- return &workloadidentityv1pb.IssueWorkloadIdentitiesResponse{
+ return workloadidentityv1pb.IssueWorkloadIdentitiesResponse_builder{
Credentials: creds,
- }, nil
+ }.Build(), nil
}
// IssueTeleportWorkloadIdentity issues a workload identity credential for the
@@ -442,14 +442,14 @@ func (s *IssuanceService) IssueTeleportWorkloadIdentity(
return nil, trace.AccessDenied("only Teleport services can execute this request")
}
- switch usage := req.Usage.(type) {
- case *workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_AppAccess:
+ switch req.WhichUsage() {
+ case workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_AppAccess_case:
if !authz.HasBuiltinRole(*authCtx, string(types.RoleApp)) {
return nil, trace.AccessDenied("only app services can issue workload identity for app access")
}
switch credParams := req.Credential.(type) {
case *workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_X509SvidParams:
- return s.issueAppAccessX509Identity(ctx, builtin.GetServerID(), req, usage.AppAccess, credParams)
+ return s.issueAppAccessX509Identity(ctx, builtin.GetServerID(), req, req.GetAppAccess(), credParams)
default:
return nil, trace.BadParameter("app access usage only supports issuing x509 credentials")
}
@@ -482,7 +482,7 @@ func (s *IssuanceService) issueAppAccessX509Identity(
return nil, trace.Wrap(err, "unable to locate app")
}
- pubKey, err := x509.ParsePKIXPublicKey(credParams.X509SvidParams.PublicKey)
+ pubKey, err := x509.ParsePKIXPublicKey(credParams.X509SvidParams.GetPublicKey())
if err != nil {
return nil, trace.Wrap(err, "parsing public key")
}
@@ -497,7 +497,7 @@ func (s *IssuanceService) issueAppAccessX509Identity(
ctx,
s.logger,
s.clock,
- req.RequestedTtl.AsDuration(),
+ req.GetRequestedTtl().AsDuration(),
// Cap the cert TTL at the session expiry, plus an alloweance for clock
// drift that mirrors [veirfyCertValidityWithSkew]. Without the
// allowance session that are within the skew window would yield app
@@ -534,9 +534,9 @@ func (s *IssuanceService) issueAppAccessX509Identity(
notAfter,
spiffeID,
nil, /* dnsSANs */
- &workloadidentityv1pb.X509DistinguishedNameTemplate{
+ workloadidentityv1pb.X509DistinguishedNameTemplate_builder{
CommonName: userIdentity.Username,
- },
+ }.Build(),
),
ca.Cert,
pubKey,
@@ -546,22 +546,20 @@ func (s *IssuanceService) issueAppAccessX509Identity(
return nil, trace.Wrap(err)
}
- return &workloadidentityv1pb.IssueTeleportWorkloadIdentityResponse{
- Credential: &workloadidentityv1pb.Credential{
+ return workloadidentityv1pb.IssueTeleportWorkloadIdentityResponse_builder{
+ Credential: workloadidentityv1pb.Credential_builder{
SpiffeId: spiffeID.String(),
ExpiresAt: timestamppb.New(notAfter),
Ttl: durationpb.New(ttl),
- Credential: &workloadidentityv1pb.Credential_X509Svid{
- X509Svid: &workloadidentityv1pb.X509SVIDCredential{
- Cert: certBytes,
- SerialNumber: serialString(certSerial),
- Chain: chain,
- },
- },
- },
- }, nil
+ X509Svid: workloadidentityv1pb.X509SVIDCredential_builder{
+ Cert: certBytes,
+ SerialNumber: serialString(certSerial),
+ Chain: chain,
+ }.Build(),
+ }.Build(),
+ }.Build(), nil
}
// routeToAppFromCert validates the certificate and extracts the RouteToApp info.
@@ -734,14 +732,14 @@ func x509Template(
DNSNames: dnsSANs,
}
if subjectTemplate != nil {
- c.Subject.CommonName = subjectTemplate.CommonName
- if subjectTemplate.Organization != "" {
+ c.Subject.CommonName = subjectTemplate.GetCommonName()
+ if subjectTemplate.GetOrganization() != "" {
c.Subject.Organization = []string{
- subjectTemplate.Organization,
+ subjectTemplate.GetOrganization(),
}
}
- if subjectTemplate.OrganizationalUnit != "" {
- c.Subject.OrganizationalUnit = []string{subjectTemplate.OrganizationalUnit}
+ if subjectTemplate.GetOrganizationalUnit() != "" {
+ c.Subject.OrganizationalUnit = []string{subjectTemplate.GetOrganizationalUnit()}
}
}
@@ -868,8 +866,8 @@ func labelSelectorsToAudit(
out := make([]*apievents.LabelSelector, 0, len(in))
for _, ls := range in {
out = append(out, &apievents.LabelSelector{
- Key: ls.Key,
- Values: ls.Values,
+ Key: ls.GetKey(),
+ Values: ls.GetValues(),
})
}
return out
@@ -919,7 +917,7 @@ func (s *IssuanceService) issueX509SVID(ctx context.Context, params issueX509SVI
switch {
case params.x509Params == nil:
return nil, trace.BadParameter("x509_svid_params: is required")
- case len(params.x509Params.PublicKey) == 0:
+ case len(params.x509Params.GetPublicKey()) == 0:
return nil, trace.BadParameter("x509_svid_params.public_key: is required")
}
@@ -939,7 +937,7 @@ func (s *IssuanceService) issueX509SVID(ctx context.Context, params issueX509SVI
params.workloadIdentity.GetSpec().GetSpiffe().GetX509().GetMaximumTtl().AsDuration(),
)
- pubKey, err := x509.ParsePKIXPublicKey(params.x509Params.PublicKey)
+ pubKey, err := x509.ParsePKIXPublicKey(params.x509Params.GetPublicKey())
if err != nil {
return nil, trace.Wrap(err, "parsing public key")
}
@@ -992,7 +990,7 @@ func (s *IssuanceService) issueX509SVID(ctx context.Context, params issueX509SVI
)
}
- return &workloadidentityv1pb.Credential{
+ return workloadidentityv1pb.Credential_builder{
WorkloadIdentityName: params.workloadIdentity.GetMetadata().GetName(),
WorkloadIdentityRevision: params.workloadIdentity.GetMetadata().GetRevision(),
@@ -1002,14 +1000,12 @@ func (s *IssuanceService) issueX509SVID(ctx context.Context, params issueX509SVI
ExpiresAt: timestamppb.New(notAfter),
Ttl: durationpb.New(ttl),
- Credential: &workloadidentityv1pb.Credential_X509Svid{
- X509Svid: &workloadidentityv1pb.X509SVIDCredential{
- Cert: certBytes,
- SerialNumber: serialString,
- Chain: params.chain,
- },
- },
- }, nil
+ X509Svid: workloadidentityv1pb.X509SVIDCredential_builder{
+ Cert: certBytes,
+ SerialNumber: serialString,
+ Chain: params.chain,
+ }.Build(),
+ }.Build(), nil
}
const jtiLength = 16
@@ -1069,7 +1065,7 @@ func (s *IssuanceService) issueJWTSVID(ctx context.Context, params issueJWTSVIDP
switch {
case params.jwtParams == nil:
return nil, trace.BadParameter("jwt_svid_params: is required")
- case len(params.jwtParams.Audiences) == 0:
+ case len(params.jwtParams.GetAudiences()) == 0:
return nil, trace.BadParameter("jwt_svid_params.audiences: at least one audience should be specified")
}
@@ -1095,7 +1091,7 @@ func (s *IssuanceService) issueJWTSVID(ctx context.Context, params issueJWTSVIDP
}
signed, err := params.issuerKey.SignJWTSVID(jwt.SignParamsJWTSVID{
- Audiences: params.jwtParams.Audiences,
+ Audiences: params.jwtParams.GetAudiences(),
SPIFFEID: spiffeID,
JTI: jti,
Issuer: params.issuerURI,
@@ -1132,7 +1128,7 @@ func (s *IssuanceService) issueJWTSVID(ctx context.Context, params issueJWTSVIDP
)
}
- return &workloadidentityv1pb.Credential{
+ return workloadidentityv1pb.Credential_builder{
WorkloadIdentityName: params.workloadIdentity.GetMetadata().GetName(),
WorkloadIdentityRevision: params.workloadIdentity.GetMetadata().GetRevision(),
@@ -1142,13 +1138,11 @@ func (s *IssuanceService) issueJWTSVID(ctx context.Context, params issueJWTSVIDP
ExpiresAt: timestamppb.New(notAfter),
Ttl: durationpb.New(ttl),
- Credential: &workloadidentityv1pb.Credential_JwtSvid{
- JwtSvid: &workloadidentityv1pb.JWTSVIDCredential{
- Jwt: signed,
- Jti: jti,
- },
- },
- }, nil
+ JwtSvid: workloadidentityv1pb.JWTSVIDCredential_builder{
+ Jwt: signed,
+ Jti: jti,
+ }.Build(),
+ }.Build(), nil
}
func (s *IssuanceService) getAllWorkloadIdentities(
@@ -1213,7 +1207,7 @@ func (s *IssuanceService) matchingAndAuthorizedWorkloadIdentities(
func convertLabels(selectors []*workloadidentityv1pb.LabelSelector) types.Labels {
labels := types.Labels{}
for _, selector := range selectors {
- labels[selector.Key] = selector.Values
+ labels[selector.GetKey()] = selector.GetValues()
}
return labels
}
diff --git a/lib/auth/machineid/workloadidentityv1/resource_service.go b/lib/auth/machineid/workloadidentityv1/resource_service.go
index 9d074256722..74ab20836d9 100644
--- a/lib/auth/machineid/workloadidentityv1/resource_service.go
+++ b/lib/auth/machineid/workloadidentityv1/resource_service.go
@@ -113,11 +113,11 @@ func (s *ResourceService) GetWorkloadIdentity(
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be non-empty")
}
- resource, err := s.cache.GetWorkloadIdentity(ctx, req.Name)
+ resource, err := s.cache.GetWorkloadIdentity(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -131,10 +131,10 @@ func (s *ResourceService) GetWorkloadIdentity(
func (s *ResourceService) ListWorkloadIdentities(
ctx context.Context, req *workloadidentityv1pb.ListWorkloadIdentitiesRequest,
) (*workloadidentityv1pb.ListWorkloadIdentitiesResponse, error) {
- return s.ListWorkloadIdentitiesV2(ctx, &workloadidentityv1pb.ListWorkloadIdentitiesV2Request{
+ return s.ListWorkloadIdentitiesV2(ctx, workloadidentityv1pb.ListWorkloadIdentitiesV2Request_builder{
PageSize: req.GetPageSize(),
PageToken: req.GetPageToken(),
- })
+ }.Build())
}
// ListWorkloadIdentitiesV2 returns a list of WorkloadIdentity resources. It
@@ -154,8 +154,8 @@ func (s *ResourceService) ListWorkloadIdentitiesV2(
resources, nextToken, err := s.cache.ListWorkloadIdentities(
ctx,
- int(req.PageSize),
- req.PageToken,
+ int(req.GetPageSize()),
+ req.GetPageToken(),
&services.ListWorkloadIdentitiesRequestOptions{
SortField: req.GetSortField(),
SortDesc: req.GetSortDesc(),
@@ -166,10 +166,10 @@ func (s *ResourceService) ListWorkloadIdentitiesV2(
return nil, trace.Wrap(err)
}
- return &workloadidentityv1pb.ListWorkloadIdentitiesResponse{
+ return workloadidentityv1pb.ListWorkloadIdentitiesResponse_builder{
WorkloadIdentities: resources,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// DeleteWorkloadIdentity deletes a WorkloadIdentity by name.
@@ -188,11 +188,11 @@ func (s *ResourceService) DeleteWorkloadIdentity(
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be non-empty")
}
- if err := s.backend.DeleteWorkloadIdentity(ctx, req.Name); err != nil {
+ if err := s.backend.DeleteWorkloadIdentity(ctx, req.GetName()); err != nil {
return nil, trace.Wrap(err)
}
@@ -204,7 +204,7 @@ func (s *ResourceService) DeleteWorkloadIdentity(
UserMetadata: authz.ClientUserMetadata(ctx),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.Name,
+ Name: req.GetName(),
},
}); err != nil {
s.logger.ErrorContext(
@@ -232,7 +232,7 @@ func (s *ResourceService) CreateWorkloadIdentity(
return nil, trace.Wrap(err)
}
- created, err := s.backend.CreateWorkloadIdentity(ctx, req.WorkloadIdentity)
+ created, err := s.backend.CreateWorkloadIdentity(ctx, req.GetWorkloadIdentity())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -245,7 +245,7 @@ func (s *ResourceService) CreateWorkloadIdentity(
UserMetadata: authz.ClientUserMetadata(ctx),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.WorkloadIdentity.Metadata.Name,
+ Name: req.GetWorkloadIdentity().GetMetadata().GetName(),
},
}
evt.WorkloadIdentityData, err = resourceToStruct(created)
@@ -282,7 +282,7 @@ func (s *ResourceService) UpdateWorkloadIdentity(
return nil, trace.Wrap(err)
}
- created, err := s.backend.UpdateWorkloadIdentity(ctx, req.WorkloadIdentity)
+ created, err := s.backend.UpdateWorkloadIdentity(ctx, req.GetWorkloadIdentity())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -295,7 +295,7 @@ func (s *ResourceService) UpdateWorkloadIdentity(
UserMetadata: authz.ClientUserMetadata(ctx),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.WorkloadIdentity.Metadata.Name,
+ Name: req.GetWorkloadIdentity().GetMetadata().GetName(),
},
}
evt.WorkloadIdentityData, err = resourceToStruct(created)
@@ -334,7 +334,7 @@ func (s *ResourceService) UpsertWorkloadIdentity(
return nil, trace.Wrap(err)
}
- created, err := s.backend.UpsertWorkloadIdentity(ctx, req.WorkloadIdentity)
+ created, err := s.backend.UpsertWorkloadIdentity(ctx, req.GetWorkloadIdentity())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -347,7 +347,7 @@ func (s *ResourceService) UpsertWorkloadIdentity(
UserMetadata: authz.ClientUserMetadata(ctx),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.WorkloadIdentity.Metadata.Name,
+ Name: req.GetWorkloadIdentity().GetMetadata().GetName(),
},
}
evt.WorkloadIdentityData, err = resourceToStruct(created)
diff --git a/lib/auth/machineid/workloadidentityv1/revocation_service.go b/lib/auth/machineid/workloadidentityv1/revocation_service.go
index f2397fd073a..018207ca1ce 100644
--- a/lib/auth/machineid/workloadidentityv1/revocation_service.go
+++ b/lib/auth/machineid/workloadidentityv1/revocation_service.go
@@ -167,11 +167,11 @@ func (s *RevocationService) GetWorkloadIdentityX509Revocation(
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be non-empty")
}
- resource, err := s.store.GetWorkloadIdentityX509Revocation(ctx, req.Name)
+ resource, err := s.store.GetWorkloadIdentityX509Revocation(ctx, req.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -196,17 +196,17 @@ func (s *RevocationService) ListWorkloadIdentityX509Revocations(
resources, nextToken, err := s.store.ListWorkloadIdentityX509Revocations(
ctx,
- int(req.PageSize),
- req.PageToken,
+ int(req.GetPageSize()),
+ req.GetPageToken(),
)
if err != nil {
return nil, trace.Wrap(err)
}
- return &workloadidentityv1pb.ListWorkloadIdentityX509RevocationsResponse{
+ return workloadidentityv1pb.ListWorkloadIdentityX509RevocationsResponse_builder{
WorkloadIdentityX509Revocations: resources,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// DeleteWorkloadIdentityX509Revocation deletes a WorkloadIdentityX509Revocation
@@ -226,11 +226,11 @@ func (s *RevocationService) DeleteWorkloadIdentityX509Revocation(
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be non-empty")
}
- if err := s.store.DeleteWorkloadIdentityX509Revocation(ctx, req.Name); err != nil {
+ if err := s.store.DeleteWorkloadIdentityX509Revocation(ctx, req.GetName()); err != nil {
return nil, trace.Wrap(err)
}
@@ -242,7 +242,7 @@ func (s *RevocationService) DeleteWorkloadIdentityX509Revocation(
UserMetadata: authz.ClientUserMetadata(ctx),
ConnectionMetadata: authz.ConnectionMetadata(ctx),
ResourceMetadata: apievents.ResourceMetadata{
- Name: req.Name,
+ Name: req.GetName(),
},
}
if err := s.emitter.EmitAuditEvent(ctx, evt); err != nil {
@@ -271,7 +271,7 @@ func (s *RevocationService) CreateWorkloadIdentityX509Revocation(
return nil, trace.Wrap(err)
}
- created, err := s.store.CreateWorkloadIdentityX509Revocation(ctx, req.WorkloadIdentityX509Revocation)
+ created, err := s.store.CreateWorkloadIdentityX509Revocation(ctx, req.GetWorkloadIdentityX509Revocation())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -315,7 +315,7 @@ func (s *RevocationService) UpdateWorkloadIdentityX509Revocation(
return nil, trace.Wrap(err)
}
- created, err := s.store.UpdateWorkloadIdentityX509Revocation(ctx, req.WorkloadIdentityX509Revocation)
+ created, err := s.store.UpdateWorkloadIdentityX509Revocation(ctx, req.GetWorkloadIdentityX509Revocation())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -361,7 +361,7 @@ func (s *RevocationService) UpsertWorkloadIdentityX509Revocation(
return nil, trace.Wrap(err)
}
- created, err := s.store.UpsertWorkloadIdentityX509Revocation(ctx, req.WorkloadIdentityX509Revocation)
+ created, err := s.store.UpsertWorkloadIdentityX509Revocation(ctx, req.GetWorkloadIdentityX509Revocation())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -402,9 +402,9 @@ func (s *RevocationService) StreamSignedCRL(
// The CRL may not yet have been signed, so, skip straight to waiting
// for an update.
if len(crl) != 0 {
- if err := srv.Send(&workloadidentityv1pb.StreamSignedCRLResponse{
+ if err := srv.Send(workloadidentityv1pb.StreamSignedCRLResponse_builder{
Crl: crl,
- }); err != nil {
+ }.Build()); err != nil {
return trace.Wrap(err)
}
}
@@ -484,7 +484,7 @@ func (s *RevocationService) watchAndSign(ctx context.Context) error {
}
revocationsMap := make(map[string]*workloadidentityv1pb.WorkloadIdentityX509Revocation, len(revocationsSlice))
for _, revocation := range revocationsSlice {
- revocationsMap[revocation.Metadata.Name] = revocation
+ revocationsMap[revocation.GetMetadata().GetName()] = revocation
}
handleEvent := func(e types.Event) (bool, error) {
@@ -498,7 +498,7 @@ func (s *RevocationService) watchAndSign(ctx context.Context) error {
)
}
revocation := unwrapper.UnwrapT()
- revocationsMap[revocation.Metadata.Name] = revocation
+ revocationsMap[revocation.GetMetadata().GetName()] = revocation
return true, nil
case types.OpDelete:
delete(revocationsMap, e.Resource.GetName())
@@ -565,7 +565,7 @@ func (s *RevocationService) watchAndSign(ctx context.Context) error {
}
newRevocationsMap := make(map[string]*workloadidentityv1pb.WorkloadIdentityX509Revocation, len(revocationsSlice))
for _, revocation := range revocationsSlice {
- newRevocationsMap[revocation.Metadata.Name] = revocation
+ newRevocationsMap[revocation.GetMetadata().GetName()] = revocation
}
revocationsMap = newRevocationsMap
crl, err := s.signCRL(ctx, revocationsMap)
@@ -637,19 +637,19 @@ func (s *RevocationService) signCRL(
for _, revocation := range revocations {
serial := new(big.Int)
- _, ok := serial.SetString(revocation.Metadata.Name, 16)
+ _, ok := serial.SetString(revocation.GetMetadata().GetName(), 16)
if !ok {
s.logger.WarnContext(
ctx,
"Encountered WorkloadIdentityX509Revocation with unparsable serial number, it will be omitted from the CRL",
- "workload_identity_revocation_name", revocation.Metadata.Name,
+ "workload_identity_revocation_name", revocation.GetMetadata().GetName(),
)
continue
}
tmpl.RevokedCertificateEntries = append(tmpl.RevokedCertificateEntries, x509.RevocationListEntry{
SerialNumber: serial,
- RevocationTime: revocation.Spec.RevokedAt.AsTime(),
+ RevocationTime: revocation.GetSpec().GetRevokedAt().AsTime(),
})
}
diff --git a/lib/auth/machineid/workloadidentityv1/workloadidentityv1_test.go b/lib/auth/machineid/workloadidentityv1/workloadidentityv1_test.go
index 3f88b35b5bb..dbedf6cd31c 100644
--- a/lib/auth/machineid/workloadidentityv1/workloadidentityv1_test.go
+++ b/lib/auth/machineid/workloadidentityv1/workloadidentityv1_test.go
@@ -230,57 +230,55 @@ func TestIssueWorkloadIdentityE2E(t *testing.T) {
})
require.NoError(t, err)
- wid, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ wid, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "my-wid",
Labels: map[string]string{
"my-label": "my-value",
},
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "join.kubernetes.service_account.namespace",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_Eq{
- Eq: &workloadidentityv1pb.WorkloadIdentityConditionEq{
- Value: "my-namespace",
- },
- },
- },
+ Eq: workloadidentityv1pb.WorkloadIdentityConditionEq_builder{
+ Value: "my-namespace",
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: `/example/{{ user.name }}/{{ user.traits["organizational-unit"] }}/{{ join.kubernetes.service_account.namespace }}/{{ join.kubernetes.pod.name }}/{{ workload.unix.pid }}`,
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- bot := &machineidv1.Bot{
+ bot := machineidv1.Bot_builder{
Kind: types.KindBot,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "my-bot",
- },
- Spec: &machineidv1.BotSpec{
+ }.Build(),
+ Spec: machineidv1.BotSpec_builder{
Roles: []string{
role.GetName(),
},
Traits: []*machineidv1.Trait{
- {
+ machineidv1.Trait_builder{
Name: "organizational-unit",
Values: []string{"finance-department"},
- },
+ }.Build(),
},
- },
- }
+ }.Build(),
+ }.Build()
k8s, err := fakeissuer.NewKubernetesSigner(tp.clock)
require.NoError(t, err)
@@ -300,7 +298,7 @@ func TestIssueWorkloadIdentityE2E(t *testing.T) {
types.ProvisionTokenSpecV2{
Roles: types.SystemRoles{types.RoleBot},
JoinMethod: types.JoinMethodKubernetes,
- BotName: bot.Metadata.Name,
+ BotName: bot.GetMetadata().GetName(),
Kubernetes: &types.ProvisionTokenSpecV2Kubernetes{
Type: types.KubernetesJoinTypeStaticJWKS,
StaticJWKS: &types.ProvisionTokenSpecV2Kubernetes_StaticJWKSConfig{
@@ -320,9 +318,9 @@ func TestIssueWorkloadIdentityE2E(t *testing.T) {
require.NoError(t, err)
_, err = adminClient.CreateRole(ctx, role)
require.NoError(t, err)
- _, err = adminClient.BotServiceClient().CreateBot(ctx, &machineidv1.CreateBotRequest{
+ _, err = adminClient.BotServiceClient().CreateBot(ctx, machineidv1.CreateBotRequest_builder{
Bot: bot,
- })
+ }.Build())
require.NoError(t, err)
err = adminClient.CreateToken(ctx, token)
require.NoError(t, err)
@@ -378,19 +376,17 @@ func TestIssueWorkloadIdentityE2E(t *testing.T) {
c := workloadidentityv1pb.NewWorkloadIdentityIssuanceServiceClient(
roleClient.GetConnection(),
)
- res, err := c.IssueWorkloadIdentity(ctx, &workloadidentityv1pb.IssueWorkloadIdentityRequest{
- Name: wid.Metadata.Name,
- WorkloadAttrs: &workloadidentityv1pb.WorkloadAttrs{
- Unix: &workloadidentityv1pb.WorkloadAttrsUnix{
+ res, err := c.IssueWorkloadIdentity(ctx, workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
+ Name: wid.GetMetadata().GetName(),
+ WorkloadAttrs: workloadidentityv1pb.WorkloadAttrs_builder{
+ Unix: workloadidentityv1pb.WorkloadAttrsUnix_builder{
Pid: 123,
- },
- },
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Perform a minimal validation of the returned credential - enough to prove
@@ -486,70 +482,66 @@ func TestIssueWorkloadIdentity(t *testing.T) {
require.NoError(t, err)
// Create some WorkloadIdentity resources
- full, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ full, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "full",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "user.name",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_Eq{
- Eq: &workloadidentityv1pb.WorkloadIdentityConditionEq{
- Value: "dog",
- },
- },
- },
- {
+ Eq: workloadidentityv1pb.WorkloadIdentityConditionEq_builder{
+ Value: "dog",
+ }.Build(),
+ }.Build(),
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "workload.kubernetes.namespace",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_Eq{
- Eq: &workloadidentityv1pb.WorkloadIdentityConditionEq{
- Value: "default",
- },
- },
- },
+ Eq: workloadidentityv1pb.WorkloadIdentityConditionEq_builder{
+ Value: "default",
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example/{{user.name}}/{{ workload.kubernetes.namespace }}/{{ workload.kubernetes.service_account }}",
Hint: "Wow - what a lovely hint, {{user.name}}!",
- X509: &workloadidentityv1pb.WorkloadIdentitySPIFFEX509{
+ X509: workloadidentityv1pb.WorkloadIdentitySPIFFEX509_builder{
DnsSans: []string{
"*.example.com",
"{{user.name}}.example.com",
},
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- subjectTemplate, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ subjectTemplate, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "subject-template",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/foo",
- X509: &workloadidentityv1pb.WorkloadIdentitySPIFFEX509{
- SubjectTemplate: &workloadidentityv1pb.X509DistinguishedNameTemplate{
+ X509: workloadidentityv1pb.WorkloadIdentitySPIFFEX509_builder{
+ SubjectTemplate: workloadidentityv1pb.X509DistinguishedNameTemplate_builder{
CommonName: "{{user.name}}",
Organization: "{{user.name}} Inc",
OrganizationalUnit: "Team {{user.name}}",
- },
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
extraClaimTemplates, err := structpb.NewStruct(map[string]any{
@@ -560,77 +552,77 @@ func TestIssueWorkloadIdentity(t *testing.T) {
})
require.NoError(t, err)
- extraClaims, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ extraClaims, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "extra-claims",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/foo",
- Jwt: &workloadidentityv1pb.WorkloadIdentitySPIFFEJWT{
+ Jwt: workloadidentityv1pb.WorkloadIdentitySPIFFEJWT_builder{
ExtraClaims: extraClaimTemplates,
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- modifiedMaxTTL, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ modifiedMaxTTL, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "max-ttl-modified",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/foo",
- X509: &workloadidentityv1pb.WorkloadIdentitySPIFFEX509{
+ X509: workloadidentityv1pb.WorkloadIdentitySPIFFEX509_builder{
MaximumTtl: durationpb.New(time.Hour * 30),
- },
- Jwt: &workloadidentityv1pb.WorkloadIdentitySPIFFEJWT{
+ }.Build(),
+ Jwt: workloadidentityv1pb.WorkloadIdentitySPIFFEJWT_builder{
MaximumTtl: durationpb.New(time.Minute * 15),
- },
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- sigstorePolicyRequired, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ sigstorePolicyRequired, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "sigstore-policy-required",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/foo",
- },
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {Expression: `sigstore.policy_satisfied("foo") || sigstore.policy_satisfied("bar")`},
+ workloadidentityv1pb.WorkloadIdentityRule_builder{Expression: `sigstore.policy_satisfied("foo") || sigstore.policy_satisfied("bar")`}.Build(),
},
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- traitsRequired, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ traitsRequired, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "traits-required",
Labels: map[string]string{
"trait-label": "trait-value-b",
},
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/foo",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
for policy, result := range map[string]error{
@@ -642,14 +634,14 @@ func TestIssueWorkloadIdentity(t *testing.T) {
}
workloadAttrs := func(f func(attrs *workloadidentityv1pb.WorkloadAttrs)) *workloadidentityv1pb.WorkloadAttrs {
- attrs := &workloadidentityv1pb.WorkloadAttrs{
- Kubernetes: &workloadidentityv1pb.WorkloadAttrsKubernetes{
+ attrs := workloadidentityv1pb.WorkloadAttrs_builder{
+ Kubernetes: workloadidentityv1pb.WorkloadAttrsKubernetes_builder{
Attested: true,
Namespace: "default",
PodName: "test",
ServiceAccount: "bar",
- },
- }
+ }.Build(),
+ }.Build()
if f != nil {
f(attrs)
}
@@ -665,32 +657,30 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "jwt svid",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: full.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
- },
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
RequestedTtl: durationpb.New(time.Minute * 14),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- cred := res.Credential
- require.NotNil(t, res.Credential)
+ cred := res.GetCredential()
+ require.NotNil(t, res.GetCredential())
wantTTL := time.Minute * 14
wantSPIFFEID := "spiffe://localhost/example/dog/default/bar"
require.Empty(t, cmp.Diff(
cred,
- &workloadidentityv1pb.Credential{
+ workloadidentityv1pb.Credential_builder{
Ttl: durationpb.New(wantTTL),
SpiffeId: wantSPIFFEID,
Hint: "Wow - what a lovely hint, dog!",
WorkloadIdentityName: full.GetMetadata().GetName(),
WorkloadIdentityRevision: full.GetMetadata().GetRevision(),
- },
+ }.Build(),
protocmp.Transform(),
protocmp.IgnoreFields(
&workloadidentityv1pb.Credential{},
@@ -760,15 +750,13 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "jwt svid - extra claims",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: extraClaims.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com"},
- },
- },
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com"},
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
// Checks for a bug where unix epoch timestamps (e.g. the `exp`
@@ -816,32 +804,30 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "x509 svid",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: full.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
RequestedTtl: durationpb.New(time.Hour * 2),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- cred := res.Credential
- require.NotNil(t, res.Credential)
+ cred := res.GetCredential()
+ require.NotNil(t, res.GetCredential())
wantSPIFFEID := "spiffe://localhost/example/dog/default/bar"
wantTTL := time.Hour * 2
require.Empty(t, cmp.Diff(
cred,
- &workloadidentityv1pb.Credential{
+ workloadidentityv1pb.Credential_builder{
Ttl: durationpb.New(wantTTL),
SpiffeId: wantSPIFFEID,
Hint: "Wow - what a lovely hint, dog!",
WorkloadIdentityName: full.GetMetadata().GetName(),
WorkloadIdentityRevision: full.GetMetadata().GetRevision(),
- },
+ }.Build(),
protocmp.Transform(),
protocmp.IgnoreFields(
&workloadidentityv1pb.Credential{},
@@ -936,30 +922,28 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "x509 svid - subject templating",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: subjectTemplate.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- cred := res.Credential
- require.NotNil(t, res.Credential)
+ cred := res.GetCredential()
+ require.NotNil(t, res.GetCredential())
wantSPIFFEID := "spiffe://localhost/foo"
wantTTL := time.Hour
require.Empty(t, cmp.Diff(
cred,
- &workloadidentityv1pb.Credential{
+ workloadidentityv1pb.Credential_builder{
Ttl: durationpb.New(wantTTL),
SpiffeId: wantSPIFFEID,
WorkloadIdentityName: subjectTemplate.GetMetadata().GetName(),
WorkloadIdentityRevision: subjectTemplate.GetMetadata().GetRevision(),
- },
+ }.Build(),
protocmp.Transform(),
protocmp.IgnoreFields(
&workloadidentityv1pb.Credential{},
@@ -1053,20 +1037,18 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "x509 svid - ttl limited by default max",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: subjectTemplate.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
RequestedTtl: durationpb.New(time.Hour * 32),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- cred := res.Credential
- require.NotNil(t, res.Credential)
+ cred := res.GetCredential()
+ require.NotNil(t, res.GetCredential())
wantTTL := time.Hour * 24
// Check expiry makes sense
require.WithinDuration(t, tp.clock.Now().Add(wantTTL), cred.GetExpiresAt().AsTime(), time.Second)
@@ -1084,36 +1066,32 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "x509 svid - access via traits in labels",
client: traitAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: traitsRequired.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- require.NotNil(t, res.Credential)
+ require.NotNil(t, res.GetCredential())
},
},
{
name: "x509 svid - unspecified ttl",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: subjectTemplate.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- cred := res.Credential
- require.NotNil(t, res.Credential)
+ cred := res.GetCredential()
+ require.NotNil(t, res.GetCredential())
wantTTL := time.Hour
// Check expiry makes sense
require.WithinDuration(t, tp.clock.Now().Add(wantTTL), cred.GetExpiresAt().AsTime(), time.Second)
@@ -1131,20 +1109,18 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "x509 svid - ttl limited by configured limit",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: modifiedMaxTTL.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
RequestedTtl: durationpb.New(time.Hour * 32),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- cred := res.Credential
- require.NotNil(t, res.Credential)
+ cred := res.GetCredential()
+ require.NotNil(t, res.GetCredential())
wantTTL := time.Hour * 30
// Check expiry makes sense
require.WithinDuration(t, tp.clock.Now().Add(wantTTL), cred.GetExpiresAt().AsTime(), time.Second)
@@ -1162,20 +1138,18 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "x509 svid - ok ttl between default and configured limit",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: modifiedMaxTTL.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
RequestedTtl: durationpb.New(time.Hour * 28),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- cred := res.Credential
- require.NotNil(t, res.Credential)
+ cred := res.GetCredential()
+ require.NotNil(t, res.GetCredential())
wantTTL := time.Hour * 28
// Check expiry makes sense
require.WithinDuration(t, tp.clock.Now().Add(wantTTL), cred.GetExpiresAt().AsTime(), time.Second)
@@ -1193,20 +1167,18 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "jwt svid ttl exceeds max default",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: full.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
- },
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
RequestedTtl: durationpb.New(time.Hour * 30),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- cred := res.Credential
- require.NotNil(t, res.Credential)
+ cred := res.GetCredential()
+ require.NotNil(t, res.GetCredential())
wantTTL := time.Hour * 24
// Check expiry makes sense
@@ -1223,20 +1195,18 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "jwt svid ttl exceeds configured default",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: modifiedMaxTTL.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
- },
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
RequestedTtl: durationpb.New(time.Hour * 14),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- cred := res.Credential
- require.NotNil(t, res.Credential)
+ cred := res.GetCredential()
+ require.NotNil(t, res.GetCredential())
wantTTL := time.Minute * 15
// Check expiry makes sense
@@ -1253,26 +1223,24 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "sigstore policy required",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: sigstorePolicyRequired.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
- },
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
WorkloadAttrs: func() *workloadidentityv1pb.WorkloadAttrs {
attrs := workloadAttrs(nil)
- attrs.Sigstore = &workloadidentityv1pb.WorkloadAttrsSigstore{
+ attrs.SetSigstore(workloadidentityv1pb.WorkloadAttrsSigstore_builder{
Payloads: []*workloadidentityv1pb.SigstoreVerificationPayload{
- {Bundle: []byte(`bundle`)},
+ workloadidentityv1pb.SigstoreVerificationPayload_builder{Bundle: []byte(`bundle`)}.Build(),
},
- }
+ }.Build())
return attrs
}(),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentityResponse) {
- require.NotNil(t, res.Credential)
+ require.NotNil(t, res.GetCredential())
evt, ok := tp.eventRecorder.LastEvent().(*events.SPIFFESVIDIssued)
require.True(t, ok)
@@ -1296,17 +1264,15 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "unauthorized by rules",
client: wilcardAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: full.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
- },
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
WorkloadAttrs: workloadAttrs(func(attrs *workloadidentityv1pb.WorkloadAttrs) {
- attrs.Kubernetes.Namespace = "not-default"
+ attrs.GetKubernetes().SetNamespace("not-default")
}),
- },
+ }.Build(),
requireErr: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -1314,15 +1280,13 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "unauthorized by labels",
client: specificAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: full.GetMetadata().GetName(),
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
- },
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -1330,15 +1294,13 @@ func TestIssueWorkloadIdentity(t *testing.T) {
{
name: "does not exist",
client: specificAccessClient,
- req: &workloadidentityv1pb.IssueWorkloadIdentityRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentityRequest_builder{
Name: "does-not-exist",
- Credential: &workloadidentityv1pb.IssueWorkloadIdentityRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
- },
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err))
},
@@ -1392,125 +1354,121 @@ func TestIssueWorkloadIdentities(t *testing.T) {
require.NoError(t, err)
// Create some WorkloadIdentity resources
- _, err = tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ _, err = tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "bar-labeled",
Labels: map[string]string{
"foo": "bar",
"access": "yes",
},
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "workload.kubernetes.namespace",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_Eq{
- Eq: &workloadidentityv1pb.WorkloadIdentityConditionEq{
- Value: "default",
- },
- },
- },
+ Eq: workloadidentityv1pb.WorkloadIdentityConditionEq_builder{
+ Value: "default",
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example/{{user.name}}/{{ workload.kubernetes.namespace }}/{{ workload.kubernetes.service_account }}",
Hint: "Wow - what a lovely hint, {{user.name}}!",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- _, err = tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ _, err = tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "buzz-labeled",
Labels: map[string]string{
"foo": "buzz",
"access": "yes",
},
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Rules: &workloadidentityv1pb.WorkloadIdentityRules{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Rules: workloadidentityv1pb.WorkloadIdentityRules_builder{
Allow: []*workloadidentityv1pb.WorkloadIdentityRule{
- {
+ workloadidentityv1pb.WorkloadIdentityRule_builder{
Conditions: []*workloadidentityv1pb.WorkloadIdentityCondition{
- {
+ workloadidentityv1pb.WorkloadIdentityCondition_builder{
Attribute: "workload.kubernetes.namespace",
- Operator: &workloadidentityv1pb.WorkloadIdentityCondition_Eq{
- Eq: &workloadidentityv1pb.WorkloadIdentityConditionEq{
- Value: "default",
- },
- },
- },
+ Eq: workloadidentityv1pb.WorkloadIdentityConditionEq_builder{
+ Value: "default",
+ }.Build(),
+ }.Build(),
},
- },
+ }.Build(),
},
- },
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example/{{user.name}}/{{ workload.kubernetes.namespace }}/{{ workload.kubernetes.service_account }}",
Hint: "Wow - what a lovely hint, {{user.name}}!",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- _, err = tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ _, err = tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "inaccessible",
Labels: map[string]string{
"foo": "bar",
"access": "no",
},
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
Rules: &workloadidentityv1pb.WorkloadIdentityRules{},
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Make enough to trip the "too many" error
for i := range 12 {
- _, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, &workloadidentityv1pb.WorkloadIdentity{
+ _, err := tp.srv.Auth().CreateWorkloadIdentity(ctx, workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: fmt.Sprintf("%d", i),
Labels: map[string]string{
"error": "too-many",
"access": "yes",
},
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
Rules: &workloadidentityv1pb.WorkloadIdentityRules{},
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/exampled",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
}
workloadAttrs := func(f func(attrs *workloadidentityv1pb.WorkloadAttrs)) *workloadidentityv1pb.WorkloadAttrs {
- attrs := &workloadidentityv1pb.WorkloadAttrs{
- Kubernetes: &workloadidentityv1pb.WorkloadAttrsKubernetes{
+ attrs := workloadidentityv1pb.WorkloadAttrs_builder{
+ Kubernetes: workloadidentityv1pb.WorkloadAttrsKubernetes_builder{
Attested: true,
Namespace: "default",
PodName: "test",
ServiceAccount: "bar",
- },
- }
+ }.Build(),
+ }.Build()
if f != nil {
f(attrs)
}
@@ -1526,25 +1484,23 @@ func TestIssueWorkloadIdentities(t *testing.T) {
{
name: "jwt svid",
client: client,
- req: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentitiesRequest_builder{
LabelSelectors: []*workloadidentityv1pb.LabelSelector{
- {
+ workloadidentityv1pb.LabelSelector_builder{
Key: "foo",
Values: []string{"bar", "buzz"},
- },
- },
- Credential: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
+ }.Build(),
},
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentitiesResponse) {
workloadIdentitiesIssued := []string{}
- for _, cred := range res.Credentials {
- workloadIdentitiesIssued = append(workloadIdentitiesIssued, cred.WorkloadIdentityName)
+ for _, cred := range res.GetCredentials() {
+ workloadIdentitiesIssued = append(workloadIdentitiesIssued, cred.GetWorkloadIdentityName())
// Check a credential was actually included and is valid.
parsed, err := jwt.ParseSigned(cred.GetJwtSvid().GetJwt())
@@ -1559,25 +1515,23 @@ func TestIssueWorkloadIdentities(t *testing.T) {
{
name: "x509 svid",
client: client,
- req: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentitiesRequest_builder{
LabelSelectors: []*workloadidentityv1pb.LabelSelector{
- {
+ workloadidentityv1pb.LabelSelector_builder{
Key: "foo",
Values: []string{"bar", "buzz"},
- },
- },
- Credential: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
+ }.Build(),
},
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentitiesResponse) {
workloadIdentitiesIssued := []string{}
- for _, cred := range res.Credentials {
- workloadIdentitiesIssued = append(workloadIdentitiesIssued, cred.WorkloadIdentityName)
+ for _, cred := range res.GetCredentials() {
+ workloadIdentitiesIssued = append(workloadIdentitiesIssued, cred.GetWorkloadIdentityName())
// Check X509 cert actually included and signed.
cert, err := x509.ParseCertificate(cred.GetX509Svid().GetCert())
require.NoError(t, err)
@@ -1595,66 +1549,60 @@ func TestIssueWorkloadIdentities(t *testing.T) {
{
name: "rules prevent issuing",
client: client,
- req: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentitiesRequest_builder{
LabelSelectors: []*workloadidentityv1pb.LabelSelector{
- {
+ workloadidentityv1pb.LabelSelector_builder{
Key: "foo",
Values: []string{"bar", "buzz"},
- },
- },
- Credential: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
+ }.Build(),
},
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
WorkloadAttrs: workloadAttrs(func(attrs *workloadidentityv1pb.WorkloadAttrs) {
- attrs.Kubernetes.Namespace = "not-default"
+ attrs.GetKubernetes().SetNamespace("not-default")
}),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentitiesResponse) {
- require.Empty(t, res.Credentials)
+ require.Empty(t, res.GetCredentials())
},
},
{
name: "no matching labels",
client: client,
- req: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentitiesRequest_builder{
LabelSelectors: []*workloadidentityv1pb.LabelSelector{
- {
+ workloadidentityv1pb.LabelSelector_builder{
Key: "foo",
Values: []string{"muahah"},
- },
- },
- Credential: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
+ }.Build(),
},
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: require.NoError,
assert: func(t *testing.T, res *workloadidentityv1pb.IssueWorkloadIdentitiesResponse) {
- require.Empty(t, res.Credentials)
+ require.Empty(t, res.GetCredentials())
},
},
{
name: "too many to issue",
client: client,
- req: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest{
+ req: workloadidentityv1pb.IssueWorkloadIdentitiesRequest_builder{
LabelSelectors: []*workloadidentityv1pb.LabelSelector{
- {
+ workloadidentityv1pb.LabelSelector_builder{
Key: "error",
Values: []string{"too-many"},
- },
- },
- Credential: &workloadidentityv1pb.IssueWorkloadIdentitiesRequest_JwtSvidParams{
- JwtSvidParams: &workloadidentityv1pb.JWTSVIDParams{
- Audiences: []string{"example.com", "test.example.com"},
- },
+ }.Build(),
},
+ JwtSvidParams: workloadidentityv1pb.JWTSVIDParams_builder{
+ Audiences: []string{"example.com", "test.example.com"},
+ }.Build(),
WorkloadAttrs: workloadAttrs(nil),
- },
+ }.Build(),
requireErr: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "number of identities that would be issued exceeds maximum permitted (max = 10), use more specific labels")
},
@@ -1754,23 +1702,19 @@ func TestIssueTeleportWorkloadIdentity(t *testing.T) {
}{
"app service generates workload identity for a session": {
clt: appServiceClt,
- req: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest{
- Credential: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
- Usage: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_AppAccess{
- AppAccess: &workloadidentityv1pb.AppAccessUsage{
- UserCertificate: aliceSessionCertBytes,
- },
- },
- },
+ req: workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_builder{
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
+ AppAccess: workloadidentityv1pb.AppAccessUsage_builder{
+ UserCertificate: aliceSessionCertBytes,
+ }.Build(),
+ }.Build(),
expectErr: require.NoError,
expectResp: func(tt require.TestingT, i1 any, i2 ...any) {
resp, _ := i1.(*workloadidentityv1pb.IssueTeleportWorkloadIdentityResponse)
// Check X509 cert actually included and signed.
- cert, err := x509.ParseCertificate(resp.Credential.GetX509Svid().GetCert())
+ cert, err := x509.ParseCertificate(resp.GetCredential().GetX509Svid().GetCert())
require.NoError(tt, err)
// Check included public key matches
require.Equal(tt, workloadKey.Public(), cert.PublicKey)
@@ -1794,18 +1738,14 @@ func TestIssueTeleportWorkloadIdentity(t *testing.T) {
},
"other service cannot generate workload identity for app access": {
clt: otherServiceClt,
- req: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest{
- Credential: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
- Usage: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_AppAccess{
- AppAccess: &workloadidentityv1pb.AppAccessUsage{
- UserCertificate: aliceSessionCertBytes,
- },
- },
- },
+ req: workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_builder{
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
+ AppAccess: workloadidentityv1pb.AppAccessUsage_builder{
+ UserCertificate: aliceSessionCertBytes,
+ }.Build(),
+ }.Build(),
expectErr: func(tt require.TestingT, err error, i ...any) {
require.ErrorContains(tt, err, "only app services can issue workload identity for app access", i...)
},
@@ -1813,18 +1753,14 @@ func TestIssueTeleportWorkloadIdentity(t *testing.T) {
},
"app service not serving app cannot generate workload identity for requested session": {
clt: nonServingAppServiceClt,
- req: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest{
- Credential: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
- Usage: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_AppAccess{
- AppAccess: &workloadidentityv1pb.AppAccessUsage{
- UserCertificate: aliceSessionCertBytes,
- },
- },
- },
+ req: workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_builder{
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
+ AppAccess: workloadidentityv1pb.AppAccessUsage_builder{
+ UserCertificate: aliceSessionCertBytes,
+ }.Build(),
+ }.Build(),
expectErr: func(tt require.TestingT, err error, i ...any) {
require.ErrorContains(tt, err, "unable to locate app", i...)
},
@@ -1832,18 +1768,14 @@ func TestIssueTeleportWorkloadIdentity(t *testing.T) {
},
"app service generates workload identity for an expired session": {
clt: appServiceClt,
- req: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest{
- Credential: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
- Usage: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_AppAccess{
- AppAccess: &workloadidentityv1pb.AppAccessUsage{
- UserCertificate: aliceExpiredSessionCertBytes,
- },
- },
- },
+ req: workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_builder{
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
+ AppAccess: workloadidentityv1pb.AppAccessUsage_builder{
+ UserCertificate: aliceExpiredSessionCertBytes,
+ }.Build(),
+ }.Build(),
expectErr: func(tt require.TestingT, err error, i ...any) {
require.ErrorContains(tt, err, "certificate has expired", i...)
},
@@ -1851,18 +1783,14 @@ func TestIssueTeleportWorkloadIdentity(t *testing.T) {
},
"users cannot request the RPC": {
clt: userClt,
- req: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest{
- Credential: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
- Usage: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_AppAccess{
- AppAccess: &workloadidentityv1pb.AppAccessUsage{
- UserCertificate: aliceSessionCertBytes,
- },
- },
- },
+ req: workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_builder{
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
+ AppAccess: workloadidentityv1pb.AppAccessUsage_builder{
+ UserCertificate: aliceSessionCertBytes,
+ }.Build(),
+ }.Build(),
expectErr: func(tt require.TestingT, err error, i ...any) {
require.ErrorContains(tt, err, "only app services can issue workload identity for app access", i...)
},
@@ -1945,18 +1873,14 @@ func TestIssueTeleportWorkloadIdentityRejectsExpiredUserCA(t *testing.T) {
c := workloadidentityv1pb.NewWorkloadIdentityIssuanceServiceClient(appServiceClt.GetConnection())
// Here we ensure the certificate is OK and returns without errors.
- res, err := c.IssueTeleportWorkloadIdentity(ctx, &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest{
- Credential: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
- Usage: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_AppAccess{
- AppAccess: &workloadidentityv1pb.AppAccessUsage{
- UserCertificate: aliceSessionCertBytes,
- },
- },
- })
+ res, err := c.IssueTeleportWorkloadIdentity(ctx, workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_builder{
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
+ AppAccess: workloadidentityv1pb.AppAccessUsage_builder{
+ UserCertificate: aliceSessionCertBytes,
+ }.Build(),
+ }.Build())
require.NoError(t, err)
require.NotNil(t, res)
@@ -1999,18 +1923,14 @@ func TestIssueTeleportWorkloadIdentityRejectsExpiredUserCA(t *testing.T) {
// This time, the UserCA is expected to be expired, meaning it should fail
// the certificate verification.
- res, err = c.IssueTeleportWorkloadIdentity(ctx, &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest{
- Credential: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_X509SvidParams{
- X509SvidParams: &workloadidentityv1pb.X509SVIDParams{
- PublicKey: workloadKeyPubBytes,
- },
- },
- Usage: &workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_AppAccess{
- AppAccess: &workloadidentityv1pb.AppAccessUsage{
- UserCertificate: aliceSessionCertBytes,
- },
- },
- })
+ res, err = c.IssueTeleportWorkloadIdentity(ctx, workloadidentityv1pb.IssueTeleportWorkloadIdentityRequest_builder{
+ X509SvidParams: workloadidentityv1pb.X509SVIDParams_builder{
+ PublicKey: workloadKeyPubBytes,
+ }.Build(),
+ AppAccess: workloadidentityv1pb.AppAccessUsage_builder{
+ UserCertificate: aliceSessionCertBytes,
+ }.Build(),
+ }.Build())
require.ErrorContains(t, err, "requestor provided an invalid certificate")
require.ErrorContains(t, err, "certificate has expired")
@@ -2048,18 +1968,18 @@ func TestResourceService_CreateWorkloadIdentity(t *testing.T) {
// Create a pre-existing workload identity
preExisting, err := srv.Auth().CreateWorkloadIdentity(
ctx,
- &workloadidentityv1pb.WorkloadIdentity{
+ workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "preexisting",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -2073,20 +1993,20 @@ func TestResourceService_CreateWorkloadIdentity(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.CreateWorkloadIdentityRequest{
- WorkloadIdentity: &workloadidentityv1pb.WorkloadIdentity{
+ req: workloadidentityv1pb.CreateWorkloadIdentityRequest_builder{
+ WorkloadIdentity: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "new",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: require.NoError,
checkResultReturned: true,
requireEvent: &events.WorkloadIdentityCreate{
@@ -2108,20 +2028,20 @@ func TestResourceService_CreateWorkloadIdentity(t *testing.T) {
{
name: "pre-existing",
client: authorizedClient,
- req: &workloadidentityv1pb.CreateWorkloadIdentityRequest{
- WorkloadIdentity: &workloadidentityv1pb.WorkloadIdentity{
+ req: workloadidentityv1pb.CreateWorkloadIdentityRequest_builder{
+ WorkloadIdentity: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: preExisting.GetMetadata().GetName(),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAlreadyExists(err))
},
@@ -2129,20 +2049,20 @@ func TestResourceService_CreateWorkloadIdentity(t *testing.T) {
{
name: "validation fail",
client: authorizedClient,
- req: &workloadidentityv1pb.CreateWorkloadIdentityRequest{
- WorkloadIdentity: &workloadidentityv1pb.WorkloadIdentity{
+ req: workloadidentityv1pb.CreateWorkloadIdentityRequest_builder{
+ WorkloadIdentity: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "new",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "spec.spiffe.id: is required")
@@ -2151,20 +2071,20 @@ func TestResourceService_CreateWorkloadIdentity(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.CreateWorkloadIdentityRequest{
- WorkloadIdentity: &workloadidentityv1pb.WorkloadIdentity{
+ req: workloadidentityv1pb.CreateWorkloadIdentityRequest_builder{
+ WorkloadIdentity: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "unauthorized",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -2181,21 +2101,21 @@ func TestResourceService_CreateWorkloadIdentity(t *testing.T) {
tt.requireError(t, err)
if tt.checkResultReturned {
- require.NotEmpty(t, res.Metadata.Revision)
+ require.NotEmpty(t, res.GetMetadata().GetRevision())
// Expect returned result to match request, but also have a
// revision
require.Empty(
t,
cmp.Diff(
res,
- tt.req.WorkloadIdentity,
+ tt.req.GetWorkloadIdentity(),
protocmp.Transform(),
protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"),
),
)
// Expect the value fetched from the store to match returned
// item.
- fetched, err := srv.Auth().GetWorkloadIdentity(ctx, res.Metadata.Name)
+ fetched, err := srv.Auth().GetWorkloadIdentity(ctx, res.GetMetadata().GetName())
require.NoError(t, err)
require.Empty(
t,
@@ -2251,18 +2171,18 @@ func TestResourceService_DeleteWorkloadIdentity(t *testing.T) {
// Create a pre-existing workload identity
preExisting, err := srv.Auth().CreateWorkloadIdentity(
ctx,
- &workloadidentityv1pb.WorkloadIdentity{
+ workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "preexisting",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -2276,9 +2196,9 @@ func TestResourceService_DeleteWorkloadIdentity(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.DeleteWorkloadIdentityRequest{
+ req: workloadidentityv1pb.DeleteWorkloadIdentityRequest_builder{
Name: preExisting.GetMetadata().GetName(),
- },
+ }.Build(),
requireError: require.NoError,
checkNonExisting: true,
requireEvent: &events.WorkloadIdentityDelete{
@@ -2300,9 +2220,9 @@ func TestResourceService_DeleteWorkloadIdentity(t *testing.T) {
{
name: "non-existing",
client: authorizedClient,
- req: &workloadidentityv1pb.DeleteWorkloadIdentityRequest{
+ req: workloadidentityv1pb.DeleteWorkloadIdentityRequest_builder{
Name: "i-do-not-exist",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err))
},
@@ -2310,9 +2230,9 @@ func TestResourceService_DeleteWorkloadIdentity(t *testing.T) {
{
name: "validation fail",
client: authorizedClient,
- req: &workloadidentityv1pb.DeleteWorkloadIdentityRequest{
+ req: workloadidentityv1pb.DeleteWorkloadIdentityRequest_builder{
Name: "",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "name: must be non-empty")
@@ -2321,9 +2241,9 @@ func TestResourceService_DeleteWorkloadIdentity(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.DeleteWorkloadIdentityRequest{
+ req: workloadidentityv1pb.DeleteWorkloadIdentityRequest_builder{
Name: "unauthorized",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -2340,7 +2260,7 @@ func TestResourceService_DeleteWorkloadIdentity(t *testing.T) {
tt.requireError(t, err)
if tt.checkNonExisting {
- _, err := srv.Auth().GetWorkloadIdentity(ctx, tt.req.Name)
+ _, err := srv.Auth().GetWorkloadIdentity(ctx, tt.req.GetName())
require.True(t, trace.IsNotFound(err))
}
if tt.requireEvent != nil {
@@ -2388,18 +2308,18 @@ func TestResourceService_GetWorkloadIdentity(t *testing.T) {
// Create a pre-existing workload identity
preExisting, err := srv.Auth().CreateWorkloadIdentity(
ctx,
- &workloadidentityv1pb.WorkloadIdentity{
+ workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "preexisting",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -2412,18 +2332,18 @@ func TestResourceService_GetWorkloadIdentity(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.GetWorkloadIdentityRequest{
+ req: workloadidentityv1pb.GetWorkloadIdentityRequest_builder{
Name: preExisting.GetMetadata().GetName(),
- },
+ }.Build(),
wantRes: preExisting,
requireError: require.NoError,
},
{
name: "non-existing",
client: authorizedClient,
- req: &workloadidentityv1pb.GetWorkloadIdentityRequest{
+ req: workloadidentityv1pb.GetWorkloadIdentityRequest_builder{
Name: "i-do-not-exist",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err))
},
@@ -2431,9 +2351,9 @@ func TestResourceService_GetWorkloadIdentity(t *testing.T) {
{
name: "validation fail",
client: authorizedClient,
- req: &workloadidentityv1pb.GetWorkloadIdentityRequest{
+ req: workloadidentityv1pb.GetWorkloadIdentityRequest_builder{
Name: "",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "name: must be non-empty")
@@ -2442,9 +2362,9 @@ func TestResourceService_GetWorkloadIdentity(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.GetWorkloadIdentityRequest{
+ req: workloadidentityv1pb.GetWorkloadIdentityRequest_builder{
Name: "unauthorized",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -2507,18 +2427,18 @@ func TestResourceService_ListWorkloadIdentities(t *testing.T) {
for i := range 29 {
r, err := srv.Auth().CreateWorkloadIdentity(
ctx,
- &workloadidentityv1pb.WorkloadIdentity{
+ workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: fmt.Sprintf("preexisting-%d", i),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
created = append(created, r)
}
@@ -2540,10 +2460,10 @@ func TestResourceService_ListWorkloadIdentities(t *testing.T) {
// For the default page size, we expect to get all results in one page
res, err := client.ListWorkloadIdentities(ctx, &workloadidentityv1pb.ListWorkloadIdentitiesRequest{})
require.NoError(t, err)
- require.Len(t, res.WorkloadIdentities, 29)
- require.Empty(t, res.NextPageToken)
+ require.Len(t, res.GetWorkloadIdentities(), 29)
+ require.Empty(t, res.GetNextPageToken())
for _, created := range created {
- require.True(t, slices.ContainsFunc(res.WorkloadIdentities, func(resource *workloadidentityv1pb.WorkloadIdentity) bool {
+ require.True(t, slices.ContainsFunc(res.GetWorkloadIdentities(), func(resource *workloadidentityv1pb.WorkloadIdentity) bool {
return proto.Equal(created, resource)
}))
}
@@ -2559,16 +2479,16 @@ func TestResourceService_ListWorkloadIdentities(t *testing.T) {
iterations := 0
for {
iterations++
- res, err := client.ListWorkloadIdentities(ctx, &workloadidentityv1pb.ListWorkloadIdentitiesRequest{
+ res, err := client.ListWorkloadIdentities(ctx, workloadidentityv1pb.ListWorkloadIdentitiesRequest_builder{
PageSize: 10,
PageToken: token,
- })
+ }.Build())
require.NoError(t, err)
- fetched = append(fetched, res.WorkloadIdentities...)
- if res.NextPageToken == "" {
+ fetched = append(fetched, res.GetWorkloadIdentities()...)
+ if res.GetNextPageToken() == "" {
break
}
- token = res.NextPageToken
+ token = res.GetNextPageToken()
}
require.Len(t, fetched, 29)
@@ -2612,33 +2532,33 @@ func TestResourceService_UpdateWorkloadIdentity(t *testing.T) {
// Create a pre-existing workload identity
preExisting, err := srv.Auth().CreateWorkloadIdentity(
ctx,
- &workloadidentityv1pb.WorkloadIdentity{
+ workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "preexisting",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
preExisting2, err := srv.Auth().CreateWorkloadIdentity(
ctx,
- &workloadidentityv1pb.WorkloadIdentity{
+ workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "preexisting-2",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- })
+ }.Build(),
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -2652,9 +2572,9 @@ func TestResourceService_UpdateWorkloadIdentity(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.UpdateWorkloadIdentityRequest{
+ req: workloadidentityv1pb.UpdateWorkloadIdentityRequest_builder{
WorkloadIdentity: preExisting,
- },
+ }.Build(),
requireError: require.NoError,
checkResultReturned: true,
requireEvent: &events.WorkloadIdentityUpdate{
@@ -2677,10 +2597,10 @@ func TestResourceService_UpdateWorkloadIdentity(t *testing.T) {
name: "incorrect revision",
client: authorizedClient,
req: (func() *workloadidentityv1pb.UpdateWorkloadIdentityRequest {
- preExisting2.Metadata.Revision = "incorrect"
- return &workloadidentityv1pb.UpdateWorkloadIdentityRequest{
+ preExisting2.GetMetadata().SetRevision("incorrect")
+ return workloadidentityv1pb.UpdateWorkloadIdentityRequest_builder{
WorkloadIdentity: preExisting2,
- }
+ }.Build()
})(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsCompareFailed(err))
@@ -2689,20 +2609,20 @@ func TestResourceService_UpdateWorkloadIdentity(t *testing.T) {
{
name: "not existing",
client: authorizedClient,
- req: &workloadidentityv1pb.UpdateWorkloadIdentityRequest{
- WorkloadIdentity: &workloadidentityv1pb.WorkloadIdentity{
+ req: workloadidentityv1pb.UpdateWorkloadIdentityRequest_builder{
+ WorkloadIdentity: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "new",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/test",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.Error(t, err)
},
@@ -2710,9 +2630,9 @@ func TestResourceService_UpdateWorkloadIdentity(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.UpdateWorkloadIdentityRequest{
+ req: workloadidentityv1pb.UpdateWorkloadIdentityRequest_builder{
WorkloadIdentity: preExisting,
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -2729,22 +2649,22 @@ func TestResourceService_UpdateWorkloadIdentity(t *testing.T) {
tt.requireError(t, err)
if tt.checkResultReturned {
- require.NotEmpty(t, res.Metadata.Revision)
- require.NotEqual(t, tt.req.WorkloadIdentity.GetMetadata().GetRevision(), res.Metadata.Revision)
+ require.NotEmpty(t, res.GetMetadata().GetRevision())
+ require.NotEqual(t, tt.req.GetWorkloadIdentity().GetMetadata().GetRevision(), res.GetMetadata().GetRevision())
// Expect returned result to match request, but also have a
// revision
require.Empty(
t,
cmp.Diff(
res,
- tt.req.WorkloadIdentity,
+ tt.req.GetWorkloadIdentity(),
protocmp.Transform(),
protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"),
),
)
// Expect the value fetched from the store to match returned
// item.
- fetched, err := srv.Auth().GetWorkloadIdentity(ctx, res.Metadata.Name)
+ fetched, err := srv.Auth().GetWorkloadIdentity(ctx, res.GetMetadata().GetName())
require.NoError(t, err)
require.Empty(
t,
@@ -2808,20 +2728,20 @@ func TestResourceService_UpsertWorkloadIdentity(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.UpsertWorkloadIdentityRequest{
- WorkloadIdentity: &workloadidentityv1pb.WorkloadIdentity{
+ req: workloadidentityv1pb.UpsertWorkloadIdentityRequest_builder{
+ WorkloadIdentity: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "new",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: require.NoError,
checkResultReturned: true,
requireEvent: &events.WorkloadIdentityCreate{
@@ -2843,20 +2763,20 @@ func TestResourceService_UpsertWorkloadIdentity(t *testing.T) {
{
name: "validation fail",
client: authorizedClient,
- req: &workloadidentityv1pb.UpsertWorkloadIdentityRequest{
- WorkloadIdentity: &workloadidentityv1pb.WorkloadIdentity{
+ req: workloadidentityv1pb.UpsertWorkloadIdentityRequest_builder{
+ WorkloadIdentity: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "new",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "spec.spiffe.id: is required")
@@ -2865,20 +2785,20 @@ func TestResourceService_UpsertWorkloadIdentity(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.UpsertWorkloadIdentityRequest{
- WorkloadIdentity: &workloadidentityv1pb.WorkloadIdentity{
+ req: workloadidentityv1pb.UpsertWorkloadIdentityRequest_builder{
+ WorkloadIdentity: workloadidentityv1pb.WorkloadIdentity_builder{
Kind: types.KindWorkloadIdentity,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "unauthorized",
- },
- Spec: &workloadidentityv1pb.WorkloadIdentitySpec{
- Spiffe: &workloadidentityv1pb.WorkloadIdentitySPIFFE{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentitySpec_builder{
+ Spiffe: workloadidentityv1pb.WorkloadIdentitySPIFFE_builder{
Id: "/example",
- },
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -2895,21 +2815,21 @@ func TestResourceService_UpsertWorkloadIdentity(t *testing.T) {
tt.requireError(t, err)
if tt.checkResultReturned {
- require.NotEmpty(t, res.Metadata.Revision)
+ require.NotEmpty(t, res.GetMetadata().GetRevision())
// Expect returned result to match request, but also have a
// revision
require.Empty(
t,
cmp.Diff(
res,
- tt.req.WorkloadIdentity,
+ tt.req.GetWorkloadIdentity(),
protocmp.Transform(),
protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"),
),
)
// Expect the value fetched from the store to match returned
// item.
- fetched, err := srv.Auth().GetWorkloadIdentity(ctx, res.Metadata.Name)
+ fetched, err := srv.Auth().GetWorkloadIdentity(ctx, res.GetMetadata().GetName())
require.NoError(t, err)
require.Empty(
t,
@@ -2965,18 +2885,18 @@ func TestRevocationService_CreateWorkloadIdentityX509Revocation(t *testing.T) {
// Create a pre-existing workload identity revocation
preExisting, err := srv.Auth().CreateWorkloadIdentityX509Revocation(
ctx,
- &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aabbccdd",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -2990,20 +2910,20 @@ func TestRevocationService_CreateWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.CreateWorkloadIdentityX509RevocationRequest{
- WorkloadIdentityX509Revocation: &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ req: workloadidentityv1pb.CreateWorkloadIdentityX509RevocationRequest_builder{
+ WorkloadIdentityX509Revocation: workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aa",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: require.NoError,
checkResultReturned: true,
requireEvent: &events.WorkloadIdentityX509RevocationCreate{
@@ -3026,9 +2946,9 @@ func TestRevocationService_CreateWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "pre-existing",
client: authorizedClient,
- req: &workloadidentityv1pb.CreateWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.CreateWorkloadIdentityX509RevocationRequest_builder{
WorkloadIdentityX509Revocation: preExisting,
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAlreadyExists(err))
},
@@ -3036,20 +2956,20 @@ func TestRevocationService_CreateWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "validation fail",
client: authorizedClient,
- req: &workloadidentityv1pb.CreateWorkloadIdentityX509RevocationRequest{
- WorkloadIdentityX509Revocation: &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ req: workloadidentityv1pb.CreateWorkloadIdentityX509RevocationRequest_builder{
+ WorkloadIdentityX509Revocation: workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "bb",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "spec.reason: is required")
@@ -3058,20 +2978,20 @@ func TestRevocationService_CreateWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.CreateWorkloadIdentityX509RevocationRequest{
- WorkloadIdentityX509Revocation: &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ req: workloadidentityv1pb.CreateWorkloadIdentityX509RevocationRequest_builder{
+ WorkloadIdentityX509Revocation: workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "cc",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -3088,21 +3008,21 @@ func TestRevocationService_CreateWorkloadIdentityX509Revocation(t *testing.T) {
tt.requireError(t, err)
if tt.checkResultReturned {
- require.NotEmpty(t, res.Metadata.Revision)
+ require.NotEmpty(t, res.GetMetadata().GetRevision())
// Expect returned result to match request, but also have a
// revision
require.Empty(
t,
cmp.Diff(
res,
- tt.req.WorkloadIdentityX509Revocation,
+ tt.req.GetWorkloadIdentityX509Revocation(),
protocmp.Transform(),
protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"),
),
)
// Expect the value fetched from the store to match returned
// item.
- fetched, err := srv.Auth().GetWorkloadIdentityX509Revocation(ctx, res.Metadata.Name)
+ fetched, err := srv.Auth().GetWorkloadIdentityX509Revocation(ctx, res.GetMetadata().GetName())
require.NoError(t, err)
require.Empty(
t,
@@ -3158,18 +3078,18 @@ func TestRevocationService_DeleteWorkloadIdentityX509Revocation(t *testing.T) {
// Create a pre-existing workload identity revocation
preExisting, err := srv.Auth().CreateWorkloadIdentityX509Revocation(
ctx,
- &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aabbccdd",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -3183,9 +3103,9 @@ func TestRevocationService_DeleteWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.DeleteWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.DeleteWorkloadIdentityX509RevocationRequest_builder{
Name: preExisting.GetMetadata().GetName(),
- },
+ }.Build(),
requireError: require.NoError,
checkNonExisting: true,
requireEvent: &events.WorkloadIdentityX509RevocationDelete{
@@ -3207,9 +3127,9 @@ func TestRevocationService_DeleteWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "non-existing",
client: authorizedClient,
- req: &workloadidentityv1pb.DeleteWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.DeleteWorkloadIdentityX509RevocationRequest_builder{
Name: "i-do-not-exist",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err))
},
@@ -3217,9 +3137,9 @@ func TestRevocationService_DeleteWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "validation fail",
client: authorizedClient,
- req: &workloadidentityv1pb.DeleteWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.DeleteWorkloadIdentityX509RevocationRequest_builder{
Name: "",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "name: must be non-empty")
@@ -3228,9 +3148,9 @@ func TestRevocationService_DeleteWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.DeleteWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.DeleteWorkloadIdentityX509RevocationRequest_builder{
Name: "unauthorized",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -3247,7 +3167,7 @@ func TestRevocationService_DeleteWorkloadIdentityX509Revocation(t *testing.T) {
tt.requireError(t, err)
if tt.checkNonExisting {
- _, err := srv.Auth().GetWorkloadIdentityX509Revocation(ctx, tt.req.Name)
+ _, err := srv.Auth().GetWorkloadIdentityX509Revocation(ctx, tt.req.GetName())
require.True(t, trace.IsNotFound(err))
}
if tt.requireEvent != nil {
@@ -3295,18 +3215,18 @@ func TestRevocationService_GetWorkloadIdentityX509Revocation(t *testing.T) {
// Create a pre-existing workload identity revocation
preExisting, err := srv.Auth().CreateWorkloadIdentityX509Revocation(
ctx,
- &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aabbccdd",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -3319,18 +3239,18 @@ func TestRevocationService_GetWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.GetWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.GetWorkloadIdentityX509RevocationRequest_builder{
Name: preExisting.GetMetadata().GetName(),
- },
+ }.Build(),
wantRes: preExisting,
requireError: require.NoError,
},
{
name: "non-existing",
client: authorizedClient,
- req: &workloadidentityv1pb.GetWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.GetWorkloadIdentityX509RevocationRequest_builder{
Name: "i-do-not-exist",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err))
},
@@ -3338,9 +3258,9 @@ func TestRevocationService_GetWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "validation fail",
client: authorizedClient,
- req: &workloadidentityv1pb.GetWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.GetWorkloadIdentityX509RevocationRequest_builder{
Name: "",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "name: must be non-empty")
@@ -3349,9 +3269,9 @@ func TestRevocationService_GetWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.GetWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.GetWorkloadIdentityX509RevocationRequest_builder{
Name: "unauthorized",
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -3414,18 +3334,18 @@ func TestRevocationService_ListWorkloadIdentityX509Revocations(t *testing.T) {
for i := range 29 {
r, err := srv.Auth().CreateWorkloadIdentityX509Revocation(
ctx,
- &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: fmt.Sprintf("%d%d", i, i),
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
created = append(created, r)
}
@@ -3450,10 +3370,10 @@ func TestRevocationService_ListWorkloadIdentityX509Revocations(t *testing.T) {
// For the default page size, we expect to get all results in one page
res, err := client.ListWorkloadIdentityX509Revocations(ctx, &workloadidentityv1pb.ListWorkloadIdentityX509RevocationsRequest{})
require.NoError(t, err)
- require.Len(t, res.WorkloadIdentityX509Revocations, 29)
- require.Empty(t, res.NextPageToken)
+ require.Len(t, res.GetWorkloadIdentityX509Revocations(), 29)
+ require.Empty(t, res.GetNextPageToken())
for _, created := range created {
- require.True(t, slices.ContainsFunc(res.WorkloadIdentityX509Revocations, func(resource *workloadidentityv1pb.WorkloadIdentityX509Revocation) bool {
+ require.True(t, slices.ContainsFunc(res.GetWorkloadIdentityX509Revocations(), func(resource *workloadidentityv1pb.WorkloadIdentityX509Revocation) bool {
return proto.Equal(created, resource)
}))
}
@@ -3469,16 +3389,16 @@ func TestRevocationService_ListWorkloadIdentityX509Revocations(t *testing.T) {
iterations := 0
for {
iterations++
- res, err := client.ListWorkloadIdentityX509Revocations(ctx, &workloadidentityv1pb.ListWorkloadIdentityX509RevocationsRequest{
+ res, err := client.ListWorkloadIdentityX509Revocations(ctx, workloadidentityv1pb.ListWorkloadIdentityX509RevocationsRequest_builder{
PageSize: 10,
PageToken: token,
- })
+ }.Build())
require.NoError(t, err)
- fetched = append(fetched, res.WorkloadIdentityX509Revocations...)
- if res.NextPageToken == "" {
+ fetched = append(fetched, res.GetWorkloadIdentityX509Revocations()...)
+ if res.GetNextPageToken() == "" {
break
}
- token = res.NextPageToken
+ token = res.GetNextPageToken()
}
require.Len(t, fetched, 29)
@@ -3522,34 +3442,34 @@ func TestRevocationService_UpdateWorkloadIdentityX509Revocation(t *testing.T) {
// Create a pre-existing workload identity revocation
preExisting, err := srv.Auth().CreateWorkloadIdentityX509Revocation(
ctx,
- &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aabbccdd",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Create a pre-existing workload identity revocation
preExisting2, err := srv.Auth().CreateWorkloadIdentityX509Revocation(
ctx,
- &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aabbccee",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
tests := []struct {
@@ -3563,9 +3483,9 @@ func TestRevocationService_UpdateWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.UpdateWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.UpdateWorkloadIdentityX509RevocationRequest_builder{
WorkloadIdentityX509Revocation: preExisting,
- },
+ }.Build(),
requireError: require.NoError,
checkResultReturned: true,
requireEvent: &events.WorkloadIdentityX509RevocationUpdate{
@@ -3589,10 +3509,10 @@ func TestRevocationService_UpdateWorkloadIdentityX509Revocation(t *testing.T) {
name: "incorrect revision",
client: authorizedClient,
req: (func() *workloadidentityv1pb.UpdateWorkloadIdentityX509RevocationRequest {
- preExisting2.Metadata.Revision = "incorrect"
- return &workloadidentityv1pb.UpdateWorkloadIdentityX509RevocationRequest{
+ preExisting2.GetMetadata().SetRevision("incorrect")
+ return workloadidentityv1pb.UpdateWorkloadIdentityX509RevocationRequest_builder{
WorkloadIdentityX509Revocation: preExisting2,
- }
+ }.Build()
})(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsCompareFailed(err))
@@ -3601,20 +3521,20 @@ func TestRevocationService_UpdateWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "not existing",
client: authorizedClient,
- req: &workloadidentityv1pb.UpdateWorkloadIdentityX509RevocationRequest{
- WorkloadIdentityX509Revocation: &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ req: workloadidentityv1pb.UpdateWorkloadIdentityX509RevocationRequest_builder{
+ WorkloadIdentityX509Revocation: workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aabbccdd404",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.Error(t, err)
},
@@ -3622,9 +3542,9 @@ func TestRevocationService_UpdateWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.UpdateWorkloadIdentityX509RevocationRequest{
+ req: workloadidentityv1pb.UpdateWorkloadIdentityX509RevocationRequest_builder{
WorkloadIdentityX509Revocation: preExisting,
- },
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -3641,22 +3561,22 @@ func TestRevocationService_UpdateWorkloadIdentityX509Revocation(t *testing.T) {
tt.requireError(t, err)
if tt.checkResultReturned {
- require.NotEmpty(t, res.Metadata.Revision)
- require.NotEqual(t, tt.req.WorkloadIdentityX509Revocation.GetMetadata().GetRevision(), res.Metadata.Revision)
+ require.NotEmpty(t, res.GetMetadata().GetRevision())
+ require.NotEqual(t, tt.req.GetWorkloadIdentityX509Revocation().GetMetadata().GetRevision(), res.GetMetadata().GetRevision())
// Expect returned result to match request, but also have a
// revision
require.Empty(
t,
cmp.Diff(
res,
- tt.req.WorkloadIdentityX509Revocation,
+ tt.req.GetWorkloadIdentityX509Revocation(),
protocmp.Transform(),
protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"),
),
)
// Expect the value fetched from the store to match returned
// item.
- fetched, err := srv.Auth().GetWorkloadIdentityX509Revocation(ctx, res.Metadata.Name)
+ fetched, err := srv.Auth().GetWorkloadIdentityX509Revocation(ctx, res.GetMetadata().GetName())
require.NoError(t, err)
require.Empty(
t,
@@ -3720,20 +3640,20 @@ func TestRevocationService_UpsertWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "success",
client: authorizedClient,
- req: &workloadidentityv1pb.UpsertWorkloadIdentityX509RevocationRequest{
- WorkloadIdentityX509Revocation: &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ req: workloadidentityv1pb.UpsertWorkloadIdentityX509RevocationRequest_builder{
+ WorkloadIdentityX509Revocation: workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aabbccdd",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: require.NoError,
checkResultReturned: true,
requireEvent: &events.WorkloadIdentityX509RevocationCreate{
@@ -3756,19 +3676,19 @@ func TestRevocationService_UpsertWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "validation fail",
client: authorizedClient,
- req: &workloadidentityv1pb.UpsertWorkloadIdentityX509RevocationRequest{
- WorkloadIdentityX509Revocation: &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ req: workloadidentityv1pb.UpsertWorkloadIdentityX509RevocationRequest_builder{
+ WorkloadIdentityX509Revocation: workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aabbccdd",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err))
require.ErrorContains(t, err, "spec.reason: is required")
@@ -3777,20 +3697,20 @@ func TestRevocationService_UpsertWorkloadIdentityX509Revocation(t *testing.T) {
{
name: "unauthorized",
client: unauthorizedClient,
- req: &workloadidentityv1pb.UpsertWorkloadIdentityX509RevocationRequest{
- WorkloadIdentityX509Revocation: &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ req: workloadidentityv1pb.UpsertWorkloadIdentityX509RevocationRequest_builder{
+ WorkloadIdentityX509Revocation: workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "aabbccdd",
Expires: timestamppb.New(srv.Clock().Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(srv.Clock().Now()),
- },
- },
- },
+ }.Build(),
+ }.Build(),
+ }.Build(),
requireError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err))
},
@@ -3807,21 +3727,21 @@ func TestRevocationService_UpsertWorkloadIdentityX509Revocation(t *testing.T) {
tt.requireError(t, err)
if tt.checkResultReturned {
- require.NotEmpty(t, res.Metadata.Revision)
+ require.NotEmpty(t, res.GetMetadata().GetRevision())
// Expect returned result to match request, but also have a
// revision
require.Empty(
t,
cmp.Diff(
res,
- tt.req.WorkloadIdentityX509Revocation,
+ tt.req.GetWorkloadIdentityX509Revocation(),
protocmp.Transform(),
protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"),
),
)
// Expect the value fetched from the store to match returned
// item.
- fetched, err := srv.Auth().GetWorkloadIdentityX509Revocation(ctx, res.Metadata.Name)
+ fetched, err := srv.Auth().GetWorkloadIdentityX509Revocation(ctx, res.GetMetadata().GetName())
require.NoError(t, err)
require.Empty(
t,
@@ -3962,18 +3882,18 @@ func TestRevocationService_CRL(t *testing.T) {
_, err := store.CreateWorkloadIdentityX509Revocation(
t.Context(),
- &workloadidentityv1pb.WorkloadIdentityX509Revocation{
+ workloadidentityv1pb.WorkloadIdentityX509Revocation_builder{
Kind: types.KindWorkloadIdentityX509Revocation,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: name,
Expires: timestamppb.New(time.Now().Add(time.Hour)),
- },
- Spec: &workloadidentityv1pb.WorkloadIdentityX509RevocationSpec{
+ }.Build(),
+ Spec: workloadidentityv1pb.WorkloadIdentityX509RevocationSpec_builder{
Reason: "compromised",
RevokedAt: timestamppb.New(revokedAt),
- },
- },
+ }.Build(),
+ }.Build(),
)
require.NoError(t, err)
@@ -4007,7 +3927,7 @@ func TestRevocationService_CRL(t *testing.T) {
// Fetch the initial, empty, CRL
res, err := stream.Recv()
require.NoError(t, err)
- checkCRL(t, res.Crl, nil)
+ checkCRL(t, res.GetCrl(), nil)
// Create new revocations
createRevocation(t, "ff")
@@ -4019,7 +3939,7 @@ func TestRevocationService_CRL(t *testing.T) {
// The client should now receive a new CRL
res, err = stream.Recv()
require.NoError(t, err)
- checkCRL(t, res.Crl, []x509.RevocationListEntry{
+ checkCRL(t, res.GetCrl(), []x509.RevocationListEntry{
{
SerialNumber: big.NewInt(170),
RevocationTime: revokedAt,
@@ -4040,7 +3960,7 @@ func TestRevocationService_CRL(t *testing.T) {
// The client should now receive a new CRL
res, err = stream.Recv()
require.NoError(t, err)
- checkCRL(t, res.Crl, []x509.RevocationListEntry{
+ checkCRL(t, res.GetCrl(), []x509.RevocationListEntry{
{
SerialNumber: big.NewInt(255),
RevocationTime: revokedAt,
@@ -4061,7 +3981,7 @@ func TestRevocationService_CRL(t *testing.T) {
// The client should now receive a new CRL
res, err = stream.Recv()
require.NoError(t, err)
- checkCRL(t, res.Crl, nil)
+ checkCRL(t, res.GetCrl(), nil)
// Wait ten minutes to see if the periodic CRL is sent.
t.Log("Advancing fake clock to pass the periodic timer")
@@ -4069,7 +3989,7 @@ func TestRevocationService_CRL(t *testing.T) {
res, err = stream.Recv()
require.NoError(t, err)
- checkCRL(t, res.Crl, nil)
+ checkCRL(t, res.GetCrl(), nil)
// Cancel the RPC context and check it didn't return an error.
cancel()
diff --git a/lib/auth/machineid/workloadidentityv1/x509_overrides_service.go b/lib/auth/machineid/workloadidentityv1/x509_overrides_service.go
index 8c61388d319..ae69646d055 100644
--- a/lib/auth/machineid/workloadidentityv1/x509_overrides_service.go
+++ b/lib/auth/machineid/workloadidentityv1/x509_overrides_service.go
@@ -134,10 +134,10 @@ func (s *X509OverridesService) ListX509IssuerOverrides(ctx context.Context, req
return nil, trace.Wrap(err)
}
- return &workloadidentityv1pb.ListX509IssuerOverridesResponse{
+ return workloadidentityv1pb.ListX509IssuerOverridesResponse_builder{
X509IssuerOverrides: overrides,
NextPageToken: nextPageToken,
- }, nil
+ }.Build(), nil
}
// CreateX509IssuerOverride implements [workloadidentityv1pb.X509OverridesServiceServer].
diff --git a/lib/auth/methods.go b/lib/auth/methods.go
index e22909fa63e..6652270e714 100644
--- a/lib/auth/methods.go
+++ b/lib/auth/methods.go
@@ -89,10 +89,10 @@ func (a *Server) AccessCheckerForScope(ctx context.Context, scope string, userSt
}
// set up scope pin (invalid until populated)
- scopePin := &scopesv1.Pin{
+ scopePin := scopesv1.Pin_builder{
Kind: scopesv1.PinKind_PIN_KIND_USER,
Scope: scope,
- }
+ }.Build()
if userState.IsBot() {
botScope, _ := userState.GetLabel(types.BotScopeLabel)
diff --git a/lib/auth/mfa/mfav2/service.go b/lib/auth/mfa/mfav2/service.go
index 75508721900..61ce2e8094d 100644
--- a/lib/auth/mfa/mfav2/service.go
+++ b/lib/auth/mfa/mfav2/service.go
@@ -393,9 +393,9 @@ func (s *Service) ValidateSessionChallenge(
mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: mfaResp.GetName(),
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: mfav2.SessionIdentifyingPayload_builder{
SshSessionId: details.Payload.SSHSessionID,
@@ -494,9 +494,9 @@ func (s *Service) ReplicateValidatedMFAChallenge(
chal := mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: req.GetName(),
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: req.GetPayload(),
SourceCluster: req.GetSourceCluster(),
diff --git a/lib/auth/mfa/mfav2/service_test.go b/lib/auth/mfa/mfav2/service_test.go
index 00b09c3ba44..8078e747647 100644
--- a/lib/auth/mfa/mfav2/service_test.go
+++ b/lib/auth/mfa/mfav2/service_test.go
@@ -135,9 +135,9 @@ func TestCreateValidateSessionChallenge_Webauthn(t *testing.T) {
wantedChallenge := mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: challengeResp.GetMfaChallenge().GetName(),
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
@@ -244,9 +244,9 @@ func TestCreateValidateSessionChallenge_SSO(t *testing.T) {
wantedChallenge := mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: challengeResp.GetMfaChallenge().GetName(),
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
@@ -666,9 +666,9 @@ func TestListValidatedMFAChallenges_Success(t *testing.T) {
mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-challenge-1",
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
@@ -679,9 +679,9 @@ func TestListValidatedMFAChallenges_Success(t *testing.T) {
mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-challenge-2",
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
@@ -692,9 +692,9 @@ func TestListValidatedMFAChallenges_Success(t *testing.T) {
mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "test-challenge-3",
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
@@ -802,9 +802,9 @@ func TestListValidatedMFAChallenges_FilterByTargetCluster(t *testing.T) {
mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: "challenge-for-target-cluster",
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
@@ -867,9 +867,9 @@ func TestReplicateValidatedMFAChallenge_Success(t *testing.T) {
ReplicatedChallenge: mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: chalName,
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
@@ -1118,9 +1118,9 @@ func TestVerifyValidatedMFAChallenge_Success(t *testing.T) {
chal := mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: chalName,
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
@@ -1166,9 +1166,9 @@ func TestVerifyValidatedMFAChallenge_PayloadMismatch(t *testing.T) {
chal := mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: chalName,
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
@@ -1203,9 +1203,9 @@ func TestVerifyValidatedMFAChallenge_SourceClusterMismatch(t *testing.T) {
chal := mfav2.ValidatedMFAChallenge_builder{
Kind: types.KindValidatedMFAChallenge,
Version: types.V1,
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Name: chalName,
- },
+ }.Build(),
Spec: mfav2.ValidatedMFAChallengeSpec_builder{
Payload: payload,
SourceCluster: sourceCluster,
diff --git a/lib/auth/notification_test.go b/lib/auth/notification_test.go
index 30fe7620bc4..00868271e8c 100644
--- a/lib/auth/notification_test.go
+++ b/lib/auth/notification_test.go
@@ -27,6 +27,7 @@ import (
"github.com/gravitational/trace"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
headerv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/header/v1"
notificationsv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/notifications/v1"
@@ -110,130 +111,116 @@ func TestNotificationMatchers(t *testing.T) {
// A notification targeted at a specific role (managers)
{
- globalNotification: newGlobalNotification("alice-2", ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByRoles{
- ByRoles: ¬ificationsv1.ByRoles{
- Roles: []string{"managers"},
- },
- },
- }),
+ globalNotification: newGlobalNotification("alice-2", notificationsv1.GlobalNotificationSpec_builder{
+ ByRoles: notificationsv1.ByRoles_builder{
+ Roles: []string{"managers"},
+ }.Build(),
+ }.Build()),
},
// A notification for everyone
{
- globalNotification: newGlobalNotification("bob-2,alice-3,carol-1", ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_All{All: true},
- }),
+ globalNotification: newGlobalNotification("bob-2,alice-3,carol-1", notificationsv1.GlobalNotificationSpec_builder{
+ All: proto.Bool(true),
+ }.Build()),
},
// A notification targeted to users with specific permissions (create tokens)
{
- globalNotification: newGlobalNotification("carol-2", ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByPermissions{
- ByPermissions: ¬ificationsv1.ByPermissions{
- RoleConditions: []*types.RoleConditions{
- {
- Rules: []types.Rule{
- {
- Resources: []string{types.KindToken},
- Verbs: []string{types.VerbCreate},
- },
+ globalNotification: newGlobalNotification("carol-2", notificationsv1.GlobalNotificationSpec_builder{
+ ByPermissions: notificationsv1.ByPermissions_builder{
+ RoleConditions: []*types.RoleConditions{
+ {
+ Rules: []types.Rule{
+ {
+ Resources: []string{types.KindToken},
+ Verbs: []string{types.VerbCreate},
},
},
},
},
- },
- }),
+ }.Build(),
+ }.Build()),
},
// A notification targeted to users who can review certain access requests
{
- globalNotification: newGlobalNotification("alice-4", ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByPermissions{
- ByPermissions: ¬ificationsv1.ByPermissions{
- RoleConditions: []*types.RoleConditions{
- {
- ReviewRequests: &types.AccessReviewConditions{
- Roles: []string{"intern"},
- },
+ globalNotification: newGlobalNotification("alice-4", notificationsv1.GlobalNotificationSpec_builder{
+ ByPermissions: notificationsv1.ByPermissions_builder{
+ RoleConditions: []*types.RoleConditions{
+ {
+ ReviewRequests: &types.AccessReviewConditions{
+ Roles: []string{"intern"},
},
},
},
- },
- }),
+ }.Build(),
+ }.Build()),
},
// A notification for multiple users (by username)
{
- globalNotification: newGlobalNotification("alice-5,bob-3", ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByUsers{
- ByUsers: ¬ificationsv1.ByUsers{
- Users: []string{"alice", "bob"},
- },
- },
- }),
+ globalNotification: newGlobalNotification("alice-5,bob-3", notificationsv1.GlobalNotificationSpec_builder{
+ ByUsers: notificationsv1.ByUsers_builder{
+ Users: []string{"alice", "bob"},
+ }.Build(),
+ }.Build()),
},
// Multiple matchers - logical OR
{
- globalNotification: newGlobalNotification("alice-6,carol-3", ¬ificationsv1.GlobalNotificationSpec{
+ globalNotification: newGlobalNotification("alice-6,carol-3", notificationsv1.GlobalNotificationSpec_builder{
MatchAllConditions: false, // logical OR
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByPermissions{
- ByPermissions: ¬ificationsv1.ByPermissions{
- RoleConditions: []*types.RoleConditions{
- {
- Logins: []string{"user"},
- },
- {
- Rules: []types.Rule{types.NewRule(types.KindToken, []string{types.VerbUpdate})},
- },
+ ByPermissions: notificationsv1.ByPermissions_builder{
+ RoleConditions: []*types.RoleConditions{
+ {
+ Logins: []string{"user"},
+ },
+ {
+ Rules: []types.Rule{types.NewRule(types.KindToken, []string{types.VerbUpdate})},
},
},
- },
- }),
+ }.Build(),
+ }.Build()),
},
// Multiple matchers - logical AND
{
- globalNotification: newGlobalNotification("nomatches", ¬ificationsv1.GlobalNotificationSpec{
+ globalNotification: newGlobalNotification("nomatches", notificationsv1.GlobalNotificationSpec_builder{
MatchAllConditions: true, // logical AND
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByPermissions{
- ByPermissions: ¬ificationsv1.ByPermissions{
- RoleConditions: []*types.RoleConditions{
- {
- Logins: []string{"user"},
- },
- {
- Rules: []types.Rule{types.NewRule(types.KindToken, []string{types.VerbUpdate})},
- },
+ ByPermissions: notificationsv1.ByPermissions_builder{
+ RoleConditions: []*types.RoleConditions{
+ {
+ Logins: []string{"user"},
+ },
+ {
+ Rules: []types.Rule{types.NewRule(types.KindToken, []string{types.VerbUpdate})},
},
},
- },
- }),
+ }.Build(),
+ }.Build()),
},
// A notification for everyone but alice.
{
- globalNotification: newGlobalNotification("bob-4,carol-4", ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_All{All: true},
+ globalNotification: newGlobalNotification("bob-4,carol-4", notificationsv1.GlobalNotificationSpec_builder{
+ All: proto.Bool(true),
ExcludeUsers: []string{"alice"},
- }),
+ }.Build()),
},
// Multiple logins in a single rule. The notification goes to all users who
// have at least one of the logins mentioned here.
{
- globalNotification: newGlobalNotification("alice-7", ¬ificationsv1.GlobalNotificationSpec{
- Matcher: ¬ificationsv1.GlobalNotificationSpec_ByPermissions{
- ByPermissions: ¬ificationsv1.ByPermissions{
- RoleConditions: []*types.RoleConditions{
- {
- Logins: []string{"user", "fakeuser1", "fakeuser2"},
- },
+ globalNotification: newGlobalNotification("alice-7", notificationsv1.GlobalNotificationSpec_builder{
+ ByPermissions: notificationsv1.ByPermissions_builder{
+ RoleConditions: []*types.RoleConditions{
+ {
+ Logins: []string{"user", "fakeuser1", "fakeuser2"},
},
},
- },
- }),
+ }.Build(),
+ }.Build()),
},
}
@@ -267,10 +254,10 @@ func TestNotificationMatchers(t *testing.T) {
require.NoError(t, err)
t.Cleanup(func() { client.Close() })
- resp, err := client.ListNotifications(t.Context(), ¬ificationsv1.ListNotificationsRequest{PageSize: 100})
+ resp, err := client.ListNotifications(t.Context(), notificationsv1.ListNotificationsRequest_builder{PageSize: 100}.Build())
require.NoError(t, err)
- titles := notificationTitles(resp.Notifications)
+ titles := notificationTitles(resp.GetNotifications())
assert.Len(t, titles, test.count)
for _, title := range titles {
@@ -307,53 +294,53 @@ func TestNotificationStates(t *testing.T) {
t.Cleanup(func() { client.Close() })
// Update bob's last seen timestamp, which should make the bob-0 notification go away.
- _, err = client.UpsertUserLastSeenNotification(t.Context(), "bob", ¬ificationsv1.UserLastSeenNotification{
- Status: ¬ificationsv1.UserLastSeenNotificationStatus{
+ _, err = client.UpsertUserLastSeenNotification(t.Context(), "bob", notificationsv1.UserLastSeenNotification_builder{
+ Status: notificationsv1.UserLastSeenNotificationStatus_builder{
LastSeenTime: created[0].GetSpec().GetCreated(),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// RBAC check - bob should not be able to set last seen time for other users.
- _, err = client.UpsertUserLastSeenNotification(t.Context(), "alice", ¬ificationsv1.UserLastSeenNotification{
- Status: ¬ificationsv1.UserLastSeenNotificationStatus{
+ _, err = client.UpsertUserLastSeenNotification(t.Context(), "alice", notificationsv1.UserLastSeenNotification_builder{
+ Status: notificationsv1.UserLastSeenNotificationStatus_builder{
LastSeenTime: created[0].GetSpec().GetCreated(),
- },
- })
+ }.Build(),
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
// Mark notification-1 as dismissed, so it stops showing up.
- _, err = client.UpsertUserNotificationState(t.Context(), "bob", ¬ificationsv1.UserNotificationState{
- Spec: ¬ificationsv1.UserNotificationStateSpec{
+ _, err = client.UpsertUserNotificationState(t.Context(), "bob", notificationsv1.UserNotificationState_builder{
+ Spec: notificationsv1.UserNotificationStateSpec_builder{
NotificationId: created[1].GetMetadata().GetName(),
- },
- Status: ¬ificationsv1.UserNotificationStateStatus{
+ }.Build(),
+ Status: notificationsv1.UserNotificationStateStatus_builder{
NotificationState: notificationsv1.NotificationState_NOTIFICATION_STATE_DISMISSED,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// Mark notification-2 as clicked. It will still show up.
- _, err = client.UpsertUserNotificationState(t.Context(), "bob", ¬ificationsv1.UserNotificationState{
- Spec: ¬ificationsv1.UserNotificationStateSpec{
+ _, err = client.UpsertUserNotificationState(t.Context(), "bob", notificationsv1.UserNotificationState_builder{
+ Spec: notificationsv1.UserNotificationStateSpec_builder{
NotificationId: created[2].GetMetadata().GetName(),
- },
- Status: ¬ificationsv1.UserNotificationStateStatus{
+ }.Build(),
+ Status: notificationsv1.UserNotificationStateStatus_builder{
NotificationState: notificationsv1.NotificationState_NOTIFICATION_STATE_CLICKED,
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
- resp, err := client.ListNotifications(t.Context(), ¬ificationsv1.ListNotificationsRequest{PageSize: 10})
+ resp, err := client.ListNotifications(t.Context(), notificationsv1.ListNotificationsRequest_builder{PageSize: 10}.Build())
require.NoError(t, err)
- require.Len(t, resp.Notifications, 3)
- require.Equal(t, []string{"notification-3", "notification-2", "notification-0"}, notificationTitles(resp.Notifications))
+ require.Len(t, resp.GetNotifications(), 3)
+ require.Equal(t, []string{"notification-3", "notification-2", "notification-0"}, notificationTitles(resp.GetNotifications()))
- require.Empty(t, resp.Notifications[0].GetMetadata().GetLabels()[types.NotificationClickedLabel])
- require.Equal(t, "true", resp.Notifications[1].GetMetadata().GetLabels()[types.NotificationClickedLabel])
- require.Empty(t, resp.Notifications[2].GetMetadata().GetLabels()[types.NotificationClickedLabel])
+ require.Empty(t, resp.GetNotifications()[0].GetMetadata().GetLabels()[types.NotificationClickedLabel])
+ require.Equal(t, "true", resp.GetNotifications()[1].GetMetadata().GetLabels()[types.NotificationClickedLabel])
+ require.Empty(t, resp.GetNotifications()[2].GetMetadata().GetLabels()[types.NotificationClickedLabel])
}
func TestNotificationPagination(t *testing.T) {
@@ -383,28 +370,28 @@ func TestNotificationPagination(t *testing.T) {
var all []*notificationsv1.Notification
var token string
- resp, err := client.ListNotifications(t.Context(), ¬ificationsv1.ListNotificationsRequest{PageSize: 3, PageToken: token})
+ resp, err := client.ListNotifications(t.Context(), notificationsv1.ListNotificationsRequest_builder{PageSize: 3, PageToken: token}.Build())
require.NoError(t, err)
- require.Len(t, resp.Notifications, 3)
- all = append(all, resp.Notifications...)
- token = resp.NextPageToken
+ require.Len(t, resp.GetNotifications(), 3)
+ all = append(all, resp.GetNotifications()...)
+ token = resp.GetNextPageToken()
- resp, err = client.ListNotifications(t.Context(), ¬ificationsv1.ListNotificationsRequest{PageSize: 4, PageToken: token})
+ resp, err = client.ListNotifications(t.Context(), notificationsv1.ListNotificationsRequest_builder{PageSize: 4, PageToken: token}.Build())
require.NoError(t, err)
- require.Len(t, resp.Notifications, 4)
- all = append(all, resp.Notifications...)
- token = resp.NextPageToken
+ require.Len(t, resp.GetNotifications(), 4)
+ all = append(all, resp.GetNotifications()...)
+ token = resp.GetNextPageToken()
- resp, err = client.ListNotifications(t.Context(), ¬ificationsv1.ListNotificationsRequest{PageSize: 1, PageToken: token})
+ resp, err = client.ListNotifications(t.Context(), notificationsv1.ListNotificationsRequest_builder{PageSize: 1, PageToken: token}.Build())
require.NoError(t, err)
- require.Len(t, resp.Notifications, 1)
- all = append(all, resp.Notifications...)
- token = resp.NextPageToken
+ require.Len(t, resp.GetNotifications(), 1)
+ all = append(all, resp.GetNotifications()...)
+ token = resp.GetNextPageToken()
- resp, err = client.ListNotifications(t.Context(), ¬ificationsv1.ListNotificationsRequest{PageSize: 10, PageToken: token})
+ resp, err = client.ListNotifications(t.Context(), notificationsv1.ListNotificationsRequest_builder{PageSize: 10, PageToken: token}.Build())
require.NoError(t, err)
- require.Len(t, resp.Notifications, 2) // only 2 remaining
- all = append(all, resp.Notifications...)
+ require.Len(t, resp.GetNotifications(), 2) // only 2 remaining
+ all = append(all, resp.GetNotifications()...)
require.Len(t, all, 10)
@@ -424,31 +411,31 @@ func TestNotificationPagination(t *testing.T) {
}
func newUserNotification(username string, title string) *notificationsv1.Notification {
- return ¬ificationsv1.Notification{
+ return notificationsv1.Notification_builder{
SubKind: "test-subkind",
- Spec: ¬ificationsv1.NotificationSpec{
+ Spec: notificationsv1.NotificationSpec_builder{
Username: username,
- },
- Metadata: &headerv1.Metadata{
+ }.Build(),
+ Metadata: headerv1.Metadata_builder{
Labels: map[string]string{
types.NotificationTitleLabel: title,
},
- },
- }
+ }.Build(),
+ }.Build()
}
func newGlobalNotification(title string, spec *notificationsv1.GlobalNotificationSpec) *notificationsv1.GlobalNotification {
- spec.Notification = ¬ificationsv1.Notification{
+ spec.SetNotification(notificationsv1.Notification_builder{
SubKind: "test-subkind",
Spec: ¬ificationsv1.NotificationSpec{},
- Metadata: &headerv1.Metadata{
+ Metadata: headerv1.Metadata_builder{
Labels: map[string]string{
types.NotificationTitleLabel: title,
},
- },
- }
+ }.Build(),
+ }.Build())
- return ¬ificationsv1.GlobalNotification{Spec: spec}
+ return notificationsv1.GlobalNotification_builder{Spec: spec}.Build()
}
func mockAuth(t *testing.T) *authtest.TLSServer {
diff --git a/lib/auth/notifications/notificationsv1/service.go b/lib/auth/notifications/notificationsv1/service.go
index de0ddbcd7c4..4460a5706ba 100644
--- a/lib/auth/notifications/notificationsv1/service.go
+++ b/lib/auth/notifications/notificationsv1/service.go
@@ -108,11 +108,11 @@ func NewService(cfg ServiceConfig) (*Service, error) {
// ListNotifications returns a paginated list of notifications which match the user.
func (s *Service) ListNotifications(ctx context.Context, req *notificationsv1.ListNotificationsRequest) (*notificationsv1.ListNotificationsResponse, error) {
labelsMatch := func(resourceLabels map[string]string) bool {
- if req.Filters == nil || len(req.Filters.Labels) == 0 {
+ if !req.HasFilters() || len(req.GetFilters().GetLabels()) == 0 {
// no labels to match against
return true
}
- for k, v := range req.Filters.Labels {
+ for k, v := range req.GetFilters().GetLabels() {
if resourceLabels[k] != v {
return false
}
@@ -120,11 +120,11 @@ func (s *Service) ListNotifications(ctx context.Context, req *notificationsv1.Li
return true
}
- if req.Filters != nil {
- if req.Filters.GlobalOnly {
+ if req.HasFilters() {
+ if req.GetFilters().GetGlobalOnly() {
return s.listGlobalNotifications(ctx, req)
}
- if req.Filters.Username != "" {
+ if req.GetFilters().GetUsername() != "" {
return s.listUserSpecificNotificationsForUser(ctx, req)
}
@@ -146,8 +146,8 @@ func (s *Service) ListNotifications(ctx context.Context, req *notificationsv1.Li
return nil, trace.Wrap(err)
}
for _, notificationState := range notificationStates {
- if notificationState.Spec != nil && notificationState.Status != nil {
- notificationStatesMap[notificationState.Spec.NotificationId] = notificationState.Status.GetNotificationState()
+ if notificationState.HasSpec() && notificationState.HasStatus() {
+ notificationStatesMap[notificationState.GetSpec().GetNotificationId()] = notificationState.GetStatus().GetNotificationState()
}
}
if nextKey == "" {
@@ -166,8 +166,8 @@ func (s *Service) ListNotifications(ctx context.Context, req *notificationsv1.Li
// Return true if the user hasn't dismissed this notification
return notificationStatesMap[n.GetMetadata().GetName()] != notificationsv1.NotificationState_NOTIFICATION_STATE_DISMISSED
}
- userKey, globalKey, found := strings.Cut(req.PageToken, ",")
- if !found && req.PageToken != "" {
+ userKey, globalKey, found := strings.Cut(req.GetPageToken(), ",")
+ if !found && req.GetPageToken() != "" {
return nil, trace.BadParameter("invalid page token provided")
}
@@ -222,7 +222,7 @@ func (s *Service) ListNotifications(ctx context.Context, req *notificationsv1.Li
},
func(globalNotification *notificationsv1.GlobalNotification) *notificationsv1.Notification {
notification := globalNotification.GetSpec().GetNotification()
- notification.Metadata.Name = globalNotification.GetMetadata().GetName()
+ notification.GetMetadata().SetName(globalNotification.GetMetadata().GetName())
return notification
},
)
@@ -234,7 +234,7 @@ func (s *Service) ListNotifications(ctx context.Context, req *notificationsv1.Li
if item != nil {
notifications = append(notifications, item)
}
- if len(notifications) == int(req.PageSize) {
+ if len(notifications) == int(req.GetPageSize()) {
// The nextKeys should represent the next unconsumed items in their respective lists.
// If the last item in this page (ie. the current item in the stream) was a user-specific notification,
// then the userNotificationsNextKey should be the next item in the userNotifsStream, and
@@ -280,18 +280,18 @@ func (s *Service) ListNotifications(ctx context.Context, req *notificationsv1.Li
// Add label to indicate notifications that the user has clicked.
for _, notification := range notifications {
if (notificationStatesMap[notification.GetMetadata().GetName()]) == notificationsv1.NotificationState_NOTIFICATION_STATE_CLICKED {
- notification.GetMetadata().Labels[types.NotificationClickedLabel] = "true"
+ notification.GetMetadata().GetLabels()[types.NotificationClickedLabel] = "true"
}
}
var nextPageToken string
if nextUserKey != "" || nextGlobalKey != "" {
nextPageToken = fmt.Sprintf("%s,%s", nextUserKey, nextGlobalKey)
}
- response := ¬ificationsv1.ListNotificationsResponse{
+ response := notificationsv1.ListNotificationsResponse_builder{
Notifications: notifications,
NextPageToken: nextPageToken,
UserLastSeenNotificationTimestamp: userLastSeenNotification.GetStatus().GetLastSeenTime(),
- }
+ }.Build()
return response, nil
}
@@ -302,25 +302,25 @@ func (s *Service) matchGlobalNotification(ctx context.Context, authCtx *authz.Co
}
// If the user is explicitly excluded by the notification, return false early.
- if gn.Spec.ExcludeUsers != nil && slices.Contains(gn.Spec.ExcludeUsers, authCtx.User.GetName()) {
+ if gn.GetSpec().GetExcludeUsers() != nil && slices.Contains(gn.GetSpec().GetExcludeUsers(), authCtx.User.GetName()) {
return false
}
- switch matcher := gn.Spec.Matcher.(type) {
- case *notificationsv1.GlobalNotificationSpec_All:
+ switch gn.GetSpec().WhichMatcher() {
+ case notificationsv1.GlobalNotificationSpec_All_case:
// Always return true if the matcher is "all."
return true
- case *notificationsv1.GlobalNotificationSpec_ByUsers:
- userList := matcher.ByUsers.GetUsers()
+ case notificationsv1.GlobalNotificationSpec_ByUsers_case:
+ userList := gn.GetSpec().GetByUsers().GetUsers()
return slices.Contains(userList, authCtx.User.GetName())
- case *notificationsv1.GlobalNotificationSpec_ByRoles:
- matcherRoles := matcher.ByRoles.GetRoles()
+ case notificationsv1.GlobalNotificationSpec_ByRoles_case:
+ matcherRoles := gn.GetSpec().GetByRoles().GetRoles()
userRoles := authCtx.User.GetRoles()
// If MatchAllConditions is true, then userRoles must contain every role in matcherRoles.
- if gn.Spec.MatchAllConditions {
+ if gn.GetSpec().GetMatchAllConditions() {
for _, matcherRole := range matcherRoles {
// Return false if there is any role missing.
if !slices.Contains(userRoles, matcherRole) {
@@ -339,8 +339,8 @@ func (s *Service) matchGlobalNotification(ctx context.Context, authCtx *authz.Co
return false
- case *notificationsv1.GlobalNotificationSpec_ByPermissions:
- roleConditionsList := matcher.ByPermissions.GetRoleConditions()
+ case notificationsv1.GlobalNotificationSpec_ByPermissions_case:
+ roleConditionsList := gn.GetSpec().GetByPermissions().GetRoleConditions()
var results []bool
for _, roleConditions := range roleConditionsList {
@@ -351,12 +351,12 @@ func (s *Service) matchGlobalNotification(ctx context.Context, authCtx *authz.Co
}
// If MatchAllConditions is false, we can exit at the first match.
- if !gn.Spec.MatchAllConditions && match {
+ if !gn.GetSpec().GetMatchAllConditions() && match {
return true
}
// If MatchAllConditions is true, we exit at the first non-match.
- if gn.Spec.MatchAllConditions && !match {
+ if gn.GetSpec().GetMatchAllConditions() && !match {
return false
}
@@ -364,7 +364,7 @@ func (s *Service) matchGlobalNotification(ctx context.Context, authCtx *authz.Co
}
// Return false if any of the roleConditions didn't match.
- if gn.Spec.MatchAllConditions {
+ if gn.GetSpec().GetMatchAllConditions() {
return !slices.Contains(results, false)
}
@@ -477,10 +477,10 @@ func isMoreRecent(userNotification *notificationsv1.Notification, globalNotifica
// UpsertUserNotificationState creates or updates a user notification state which records whether the user has clicked on or dismissed a notification.
func (s *Service) UpsertUserNotificationState(ctx context.Context, req *notificationsv1.UpsertUserNotificationStateRequest) (*notificationsv1.UserNotificationState, error) {
- if req.Username == "" {
+ if req.GetUsername() == "" {
return nil, trace.BadParameter("missing username")
}
- if req.UserNotificationState == nil {
+ if !req.HasUserNotificationState() {
return nil, trace.BadParameter("missing notification state")
}
@@ -489,11 +489,11 @@ func (s *Service) UpsertUserNotificationState(ctx context.Context, req *notifica
return nil, trace.Wrap(err)
}
username := authCtx.User.GetName()
- if username != req.Username {
+ if username != req.GetUsername() {
return nil, trace.AccessDenied("a user may only update their own notification state")
}
- out, err := s.backend.UpsertUserNotificationState(ctx, req.Username, req.UserNotificationState)
+ out, err := s.backend.UpsertUserNotificationState(ctx, req.GetUsername(), req.GetUserNotificationState())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -503,10 +503,10 @@ func (s *Service) UpsertUserNotificationState(ctx context.Context, req *notifica
// UpsertUserLastSeenNotification creates or updates a user's last seen notification timestamp.
func (s *Service) UpsertUserLastSeenNotification(ctx context.Context, req *notificationsv1.UpsertUserLastSeenNotificationRequest) (*notificationsv1.UserLastSeenNotification, error) {
- if req.Username == "" {
+ if req.GetUsername() == "" {
return nil, trace.BadParameter("missing username")
}
- if req.UserLastSeenNotification == nil {
+ if !req.HasUserLastSeenNotification() {
return nil, trace.BadParameter("missing user last seen notification")
}
@@ -516,11 +516,11 @@ func (s *Service) UpsertUserLastSeenNotification(ctx context.Context, req *notif
}
username := authCtx.User.GetName()
- if username != req.Username {
+ if username != req.GetUsername() {
return nil, trace.AccessDenied("a user may only update their own last seen notification timestamp")
}
- out, err := s.backend.UpsertUserLastSeenNotification(ctx, req.Username, req.UserLastSeenNotification)
+ out, err := s.backend.UpsertUserLastSeenNotification(ctx, req.GetUsername(), req.GetUserLastSeenNotification())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -543,7 +543,7 @@ func (s *Service) CreateGlobalNotification(ctx context.Context, req *notificatio
return nil, trace.Wrap(err)
}
- out, err := s.backend.CreateGlobalNotification(ctx, req.GlobalNotification)
+ out, err := s.backend.CreateGlobalNotification(ctx, req.GetGlobalNotification())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -553,7 +553,7 @@ func (s *Service) CreateGlobalNotification(ctx context.Context, req *notificatio
// CreateUserNotification creates a user-specific notification.
func (s *Service) CreateUserNotification(ctx context.Context, req *notificationsv1.CreateUserNotificationRequest) (*notificationsv1.Notification, error) {
- if req.Username == "" {
+ if req.GetUsername() == "" {
return nil, trace.BadParameter("missing username")
}
@@ -570,7 +570,7 @@ func (s *Service) CreateUserNotification(ctx context.Context, req *notifications
return nil, trace.Wrap(err)
}
- out, err := s.backend.CreateUserNotification(ctx, req.Notification)
+ out, err := s.backend.CreateUserNotification(ctx, req.GetNotification())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -593,7 +593,7 @@ func (s *Service) DeleteGlobalNotification(ctx context.Context, req *notificatio
return nil, trace.Wrap(err)
}
- err = s.backend.DeleteGlobalNotification(ctx, req.NotificationId)
+ err = s.backend.DeleteGlobalNotification(ctx, req.GetNotificationId())
return nil, trace.Wrap(err)
}
@@ -612,7 +612,7 @@ func (s *Service) DeleteUserNotification(ctx context.Context, req *notifications
return nil, trace.Wrap(err)
}
- err = s.backend.DeleteUserNotification(ctx, req.Username, req.NotificationId)
+ err = s.backend.DeleteUserNotification(ctx, req.GetUsername(), req.GetNotificationId())
return nil, trace.Wrap(err)
}
@@ -625,7 +625,7 @@ func (s *Service) listUserSpecificNotificationsForUser(ctx context.Context, req
// If no username is provided, fetch notifications for the current user.
if req.GetFilters().GetUsername() == "" {
- req.Filters.Username = authCtx.User.GetName()
+ req.GetFilters().SetUsername(authCtx.User.GetName())
}
// If the user is trying to fetch notifications for a different user, they need `list` permissions for `Notifications`.
@@ -668,10 +668,10 @@ func (s *Service) listUserSpecificNotificationsForUser(ctx context.Context, req
}
}
- return ¬ificationsv1.ListNotificationsResponse{
+ return notificationsv1.ListNotificationsResponse_builder{
Notifications: notifications,
NextPageToken: nextKey,
- }, nil
+ }.Build(), nil
}
// listGlobalNotifications returns a paginated list of all global notifications. This is a privileged operation requiring `list` access for `Notifications` and should only be used by cluster admins.
@@ -714,7 +714,7 @@ func (s *Service) listGlobalNotifications(ctx context.Context, req *notification
item := stream.Item()
if item != nil {
notification := item.GetSpec().GetNotification()
- notification.Metadata.Name = item.GetMetadata().GetName()
+ notification.GetMetadata().SetName(item.GetMetadata().GetName())
notifications = append(notifications, notification)
@@ -725,8 +725,8 @@ func (s *Service) listGlobalNotifications(ctx context.Context, req *notification
}
}
- return ¬ificationsv1.ListNotificationsResponse{
+ return notificationsv1.ListNotificationsResponse_builder{
Notifications: notifications,
NextPageToken: nextKey,
- }, nil
+ }.Build(), nil
}
diff --git a/lib/auth/periodic_test.go b/lib/auth/periodic_test.go
index 7e58ba4e6d8..924f0897c37 100644
--- a/lib/auth/periodic_test.go
+++ b/lib/auth/periodic_test.go
@@ -34,10 +34,10 @@ func TestTotalInstances(t *testing.T) {
t.Parallel()
instances := []*proto.UpstreamInventoryHello{
{},
- {Version: "15.0.0"},
- {ServerID: "id"},
- {ExternalUpgrader: "kube"},
- {ExternalUpgraderVersion: "14.0.0"},
+ proto.UpstreamInventoryHello_builder{Version: "15.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{ServerID: "id"}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "kube"}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgraderVersion: "14.0.0"}.Build(),
}
periodic := newInstanceMetricsPeriodic()
@@ -58,11 +58,11 @@ func TestTotalEnrolledInUpgrades(t *testing.T) {
{
desc: "mixed",
instances: []*proto.UpstreamInventoryHello{
- {ExternalUpgrader: "kube", ExternalUpgraderVersion: "13.0.0"},
- {ExternalUpgrader: "kube", ExternalUpgraderVersion: "14.0.0"},
- {ExternalUpgrader: "unit", ExternalUpgraderVersion: "13.0.0"},
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "kube", ExternalUpgraderVersion: "13.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "kube", ExternalUpgraderVersion: "14.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "unit", ExternalUpgraderVersion: "13.0.0"}.Build(),
{},
- {ExternalUpgrader: "unit", ExternalUpgraderVersion: "14.0.0"},
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "unit", ExternalUpgraderVersion: "14.0.0"}.Build(),
{},
},
expected: 4,
@@ -70,8 +70,8 @@ func TestTotalEnrolledInUpgrades(t *testing.T) {
{
desc: "version omitted",
instances: []*proto.UpstreamInventoryHello{
- {ExternalUpgrader: "kube"},
- {ExternalUpgrader: "unit"},
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "kube"}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "unit"}.Build(),
},
expected: 2,
},
@@ -110,19 +110,19 @@ func TestUpgraderCounts(t *testing.T) {
{
desc: "mixed",
instances: []*proto.UpstreamInventoryHello{
- {ExternalUpgrader: "kube", ExternalUpgraderVersion: "13.0.0", UpdaterInfo: &types.UpdaterV2Info{
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "kube", ExternalUpgraderVersion: "13.0.0", UpdaterInfo: &types.UpdaterV2Info{
UpdaterStatus: types.UpdaterStatus_UPDATER_STATUS_OK,
- }},
- {ExternalUpgrader: "kube", ExternalUpgraderVersion: "14.0.0", UpdaterInfo: &types.UpdaterV2Info{
+ }}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "kube", ExternalUpgraderVersion: "14.0.0", UpdaterInfo: &types.UpdaterV2Info{
UpdaterStatus: types.UpdaterStatus_UPDATER_STATUS_OK,
- }},
- {ExternalUpgrader: "unit", ExternalUpgraderVersion: "13.0.0", UpdaterInfo: &types.UpdaterV2Info{
+ }}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "unit", ExternalUpgraderVersion: "13.0.0", UpdaterInfo: &types.UpdaterV2Info{
UpdaterStatus: types.UpdaterStatus_UPDATER_STATUS_OK,
- }},
+ }}.Build(),
{},
- {ExternalUpgrader: "unit", ExternalUpgraderVersion: "14.0.0", UpdaterInfo: &types.UpdaterV2Info{
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "unit", ExternalUpgraderVersion: "14.0.0", UpdaterInfo: &types.UpdaterV2Info{
UpdaterStatus: types.UpdaterStatus_UPDATER_STATUS_PINNED,
- }},
+ }}.Build(),
{},
},
expected: map[upgrader]int{
@@ -143,10 +143,10 @@ func TestUpgraderCounts(t *testing.T) {
{
desc: "all-enrolled",
instances: []*proto.UpstreamInventoryHello{
- {ExternalUpgrader: "kube", ExternalUpgraderVersion: "13.0.0"},
- {ExternalUpgrader: "kube", ExternalUpgraderVersion: "13.0.0"},
- {ExternalUpgrader: "unit", ExternalUpgraderVersion: "13.0.0"},
- {ExternalUpgrader: "unit", ExternalUpgraderVersion: "13.0.0"},
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "kube", ExternalUpgraderVersion: "13.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "kube", ExternalUpgraderVersion: "13.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "unit", ExternalUpgraderVersion: "13.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "unit", ExternalUpgraderVersion: "13.0.0"}.Build(),
},
expected: map[upgrader]int{
{"kube", "13.0.0", ""}: 2,
@@ -156,8 +156,8 @@ func TestUpgraderCounts(t *testing.T) {
{
desc: "nil version",
instances: []*proto.UpstreamInventoryHello{
- {ExternalUpgrader: "kube"},
- {ExternalUpgrader: "unit"},
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "kube"}.Build(),
+ proto.UpstreamInventoryHello_builder{ExternalUpgrader: "unit"}.Build(),
},
expected: map[upgrader]int{
{"kube", "", ""}: 1,
@@ -206,10 +206,10 @@ func TestInstallMethodCounts(t *testing.T) {
{
desc: "various install methods",
metadata: []*proto.UpstreamInventoryAgentMetadata{
- {InstallMethods: []string{"systemctl"}},
- {InstallMethods: []string{"systemctl"}},
- {InstallMethods: []string{"helm_kube_agent"}},
- {InstallMethods: []string{"dockerfile"}},
+ proto.UpstreamInventoryAgentMetadata_builder{InstallMethods: []string{"systemctl"}}.Build(),
+ proto.UpstreamInventoryAgentMetadata_builder{InstallMethods: []string{"systemctl"}}.Build(),
+ proto.UpstreamInventoryAgentMetadata_builder{InstallMethods: []string{"helm_kube_agent"}}.Build(),
+ proto.UpstreamInventoryAgentMetadata_builder{InstallMethods: []string{"dockerfile"}}.Build(),
},
expected: map[string]int{
"systemctl": 2,
@@ -220,8 +220,8 @@ func TestInstallMethodCounts(t *testing.T) {
{
desc: "multiple install methods",
metadata: []*proto.UpstreamInventoryAgentMetadata{
- {InstallMethods: []string{"dockerfile", "helm_kube_agent"}},
- {InstallMethods: []string{"helm_kube_agent", "dockerfile"}},
+ proto.UpstreamInventoryAgentMetadata_builder{InstallMethods: []string{"dockerfile", "helm_kube_agent"}}.Build(),
+ proto.UpstreamInventoryAgentMetadata_builder{InstallMethods: []string{"helm_kube_agent", "dockerfile"}}.Build(),
},
expected: map[string]int{
"dockerfile,helm_kube_agent": 2,
@@ -255,9 +255,9 @@ func TestRegisteredAgentsCounts(t *testing.T) {
{
desc: "automatic updates disabled",
instance: []*proto.UpstreamInventoryHello{
- {Version: "13.0.0"},
- {Version: "14.0.0"},
- {Version: "15.0.0"},
+ proto.UpstreamInventoryHello_builder{Version: "13.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "14.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "15.0.0"}.Build(),
},
expected: map[registeredAgent]int{
{runtime.GOOS, "13.0.0", "false"}: 1,
@@ -268,15 +268,15 @@ func TestRegisteredAgentsCounts(t *testing.T) {
{
desc: "automatic updates enabled",
instance: []*proto.UpstreamInventoryHello{
- {Version: "13.0.0", ExternalUpgrader: "unit"},
- {Version: "13.0.0", ExternalUpgrader: "kube"},
- {Version: "13.0.0"},
- {Version: "14.0.0", ExternalUpgrader: "unit"},
- {Version: "14.0.0", ExternalUpgrader: "kube"},
- {Version: "14.0.0"},
- {Version: "15.0.0", ExternalUpgrader: "unit"},
- {Version: "15.0.0", ExternalUpgrader: "kube"},
- {Version: "15.0.0"},
+ proto.UpstreamInventoryHello_builder{Version: "13.0.0", ExternalUpgrader: "unit"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "13.0.0", ExternalUpgrader: "kube"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "13.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "14.0.0", ExternalUpgrader: "unit"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "14.0.0", ExternalUpgrader: "kube"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "14.0.0"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "15.0.0", ExternalUpgrader: "unit"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "15.0.0", ExternalUpgrader: "kube"}.Build(),
+ proto.UpstreamInventoryHello_builder{Version: "15.0.0"}.Build(),
},
expected: map[registeredAgent]int{
{runtime.GOOS, "13.0.0", "true"}: 2,
@@ -293,9 +293,9 @@ func TestRegisteredAgentsCounts(t *testing.T) {
periodic := newInstanceMetricsPeriodic()
for _, instance := range tt.instance {
- periodic.VisitInstance(instance, &proto.UpstreamInventoryAgentMetadata{
+ periodic.VisitInstance(instance, proto.UpstreamInventoryAgentMetadata_builder{
OS: runtime.GOOS,
- })
+ }.Build())
}
require.Equal(t, tt.expected, periodic.RegisteredAgentsCount(), "tt=%q", tt.desc)
})
diff --git a/lib/auth/presence/presencev1/service.go b/lib/auth/presence/presencev1/service.go
index e4a559f40a0..24a4fbd4878 100644
--- a/lib/auth/presence/presencev1/service.go
+++ b/lib/auth/presence/presencev1/service.go
@@ -137,7 +137,7 @@ func NewService(cfg ServiceConfig) (*Service, error) {
func (s *Service) GetRemoteCluster(
ctx context.Context, req *presencepb.GetRemoteClusterRequest,
) (*types.RemoteClusterV3, error) {
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be specified")
}
@@ -149,7 +149,7 @@ func (s *Service) GetRemoteCluster(
return nil, trace.Wrap(err)
}
- rc, err := s.backend.GetRemoteCluster(ctx, req.Name)
+ rc, err := s.backend.GetRemoteCluster(ctx, req.GetName())
if err != nil {
return nil, utils.OpaqueAccessDenied(err)
}
@@ -184,7 +184,7 @@ func (s *Service) ListRemoteClusters(
}
page, nextToken, err := s.backend.ListRemoteClusters(
- ctx, int(req.PageSize), req.PageToken,
+ ctx, int(req.GetPageSize()), req.GetPageToken(),
)
if err != nil {
return nil, trace.Wrap(err)
@@ -217,10 +217,10 @@ func (s *Service) ListRemoteClusters(
filteredPage = append(filteredPage, rc)
}
- return &presencepb.ListRemoteClustersResponse{
+ return presencepb.ListRemoteClustersResponse_builder{
RemoteClusters: filteredPage,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// UpdateRemoteCluster updates a remote cluster.
@@ -228,9 +228,9 @@ func (s *Service) UpdateRemoteCluster(
ctx context.Context, req *presencepb.UpdateRemoteClusterRequest,
) (*types.RemoteClusterV3, error) {
switch {
- case req.RemoteCluster == nil:
+ case !req.HasRemoteCluster():
return nil, trace.BadParameter("remote_cluster: must not be nil")
- case req.RemoteCluster.GetName() == "":
+ case req.GetRemoteCluster().GetName() == "":
return nil, trace.BadParameter("remote_cluster.Metadata.Name: must be non-empty")
}
@@ -247,7 +247,7 @@ func (s *Service) UpdateRemoteCluster(
// If the update mask is empty, update the entire remote cluster.
if len(req.GetUpdateMask().GetPaths()) == 0 {
- rc, err := s.backend.UpdateRemoteCluster(ctx, req.RemoteCluster)
+ rc, err := s.backend.UpdateRemoteCluster(ctx, req.GetRemoteCluster())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -266,23 +266,23 @@ func (s *Service) UpdateRemoteCluster(
// Otherwise, we apply the update mask to the current remote cluster using
// a patch operation.
req.GetUpdateMask().Normalize()
- rc, err := s.backend.PatchRemoteCluster(ctx, req.RemoteCluster.GetName(), func(rc types.RemoteCluster) (types.RemoteCluster, error) {
+ rc, err := s.backend.PatchRemoteCluster(ctx, req.GetRemoteCluster().GetName(), func(rc types.RemoteCluster) (types.RemoteCluster, error) {
for _, path := range req.GetUpdateMask().GetPaths() {
switch path {
case "Metadata.Labels":
md := rc.GetMetadata()
- md.Labels = req.RemoteCluster.GetMetadata().Labels
+ md.Labels = req.GetRemoteCluster().GetMetadata().Labels
rc.SetMetadata(md)
case "Metadata.Description":
md := rc.GetMetadata()
- md.Description = req.RemoteCluster.GetMetadata().Description
+ md.Description = req.GetRemoteCluster().GetMetadata().Description
rc.SetMetadata(md)
case "Metadata.Expires":
- rc.SetExpiry(req.RemoteCluster.Expiry())
+ rc.SetExpiry(req.GetRemoteCluster().Expiry())
case "Status.Connection":
- rc.SetConnectionStatus(req.RemoteCluster.GetConnectionStatus())
+ rc.SetConnectionStatus(req.GetRemoteCluster().GetConnectionStatus())
case "Status.LastHeartbeat":
- rc.SetLastHeartbeat(req.RemoteCluster.GetLastHeartbeat())
+ rc.SetLastHeartbeat(req.GetRemoteCluster().GetLastHeartbeat())
default:
return nil, trace.BadParameter("unsupported field: %q", path)
}
@@ -309,7 +309,7 @@ func (s *Service) UpdateRemoteCluster(
func (s *Service) DeleteRemoteCluster(
ctx context.Context, req *presencepb.DeleteRemoteClusterRequest,
) (*emptypb.Empty, error) {
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be specified")
}
@@ -326,7 +326,7 @@ func (s *Service) DeleteRemoteCluster(
return nil, trace.Wrap(err)
}
- if err := s.authServer.DeleteRemoteCluster(ctx, req.Name); err != nil {
+ if err := s.authServer.DeleteRemoteCluster(ctx, req.GetName()); err != nil {
return nil, trace.Wrap(err)
}
@@ -346,7 +346,7 @@ func (s *Service) ListReverseTunnels(
}
page, nextToken, err := s.cache.ListReverseTunnels(
- ctx, int(req.PageSize), req.PageToken,
+ ctx, int(req.GetPageSize()), req.GetPageToken(),
)
if err != nil {
return nil, trace.Wrap(err)
@@ -367,10 +367,10 @@ func (s *Service) ListReverseTunnels(
concretePage = append(concretePage, v3)
}
- return &presencepb.ListReverseTunnelsResponse{
+ return presencepb.ListReverseTunnelsResponse_builder{
ReverseTunnels: concretePage,
NextPageToken: nextToken,
- }, nil
+ }.Build(), nil
}
// UpsertReverseTunnel upserts a reverse tunnel.
@@ -385,15 +385,15 @@ func (s *Service) UpsertReverseTunnel(
return nil, trace.Wrap(err)
}
- if req.ReverseTunnel == nil {
+ if !req.HasReverseTunnel() {
return nil, trace.BadParameter("reverse_tunnel: must not be nil")
}
- if err := services.ValidateReverseTunnel(req.ReverseTunnel); err != nil {
+ if err := services.ValidateReverseTunnel(req.GetReverseTunnel()); err != nil {
return nil, trace.Wrap(err)
}
- res, err := s.backend.UpsertReverseTunnel(ctx, req.ReverseTunnel)
+ res, err := s.backend.UpsertReverseTunnel(ctx, req.GetReverseTunnel())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -417,11 +417,11 @@ func (s *Service) DeleteReverseTunnel(
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be specified")
}
- return nil, trace.Wrap(s.backend.DeleteReverseTunnel(ctx, req.Name))
+ return nil, trace.Wrap(s.backend.DeleteReverseTunnel(ctx, req.GetName()))
}
// GetRelayServer implements [presencepb.PresenceServiceServer].
@@ -439,9 +439,9 @@ func (s *Service) GetRelayServer(ctx context.Context, req *presencepb.GetRelaySe
return nil, trace.Wrap(err)
}
- return &presencepb.GetRelayServerResponse{
+ return presencepb.GetRelayServerResponse_builder{
RelayServer: relayServer,
- }, nil
+ }.Build(), nil
}
// ListRelayServers implements [presencepb.PresenceServiceServer].
@@ -459,10 +459,10 @@ func (s *Service) ListRelayServers(ctx context.Context, req *presencepb.ListRela
return nil, trace.Wrap(err)
}
- return &presencepb.ListRelayServersResponse{
+ return presencepb.ListRelayServersResponse_builder{
Relays: relayServers,
NextPageToken: nextPageToken,
- }, nil
+ }.Build(), nil
}
// DeleteRelayServer implements [presencepb.PresenceServiceServer].
@@ -523,9 +523,9 @@ func (s *Service) UpsertProxyServer(
if !ok {
return nil, trace.BadParameter("unsupported proxy server type %T", upserted)
}
- return &presencepb.UpsertProxyServerResponse{
+ return presencepb.UpsertProxyServerResponse_builder{
Server: upsertedV2,
- }, nil
+ }.Build(), nil
}
// DeleteProxyServer deletes a proxy server heartbeat by name.
@@ -540,7 +540,7 @@ func (s *Service) DeleteProxyServer(
return nil, trace.Wrap(err)
}
- if req.Name == "" {
+ if req.GetName() == "" {
return nil, trace.BadParameter("name: must be specified")
}
diff --git a/lib/auth/presence/presencev1/service_test.go b/lib/auth/presence/presencev1/service_test.go
index f6cba809d38..c2f1f3ac3e0 100644
--- a/lib/auth/presence/presencev1/service_test.go
+++ b/lib/auth/presence/presencev1/service_test.go
@@ -142,18 +142,18 @@ func TestGetRemoteCluster(t *testing.T) {
{
name: "success",
user: user.GetName(),
- req: &presencev1pb.GetRemoteClusterRequest{
+ req: presencev1pb.GetRemoteClusterRequest_builder{
Name: matchingRC.GetName(),
- },
+ }.Build(),
assertError: require.NoError,
want: matchingRC.(*types.RemoteClusterV3),
},
{
name: "no permissions",
user: unprivilegedUser.GetName(),
- req: &presencev1pb.GetRemoteClusterRequest{
+ req: presencev1pb.GetRemoteClusterRequest_builder{
Name: matchingRC.GetName(),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -161,9 +161,9 @@ func TestGetRemoteCluster(t *testing.T) {
{
name: "no permissions - unmatching rc",
user: user.GetName(),
- req: &presencev1pb.GetRemoteClusterRequest{
+ req: presencev1pb.GetRemoteClusterRequest_builder{
Name: notMatchingRC.GetName(),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
// Opaque no permission presents as not found
require.True(t, trace.IsNotFound(err), "error should be not found")
@@ -172,9 +172,9 @@ func TestGetRemoteCluster(t *testing.T) {
{
name: "validation - no name",
user: user.GetName(),
- req: &presencev1pb.GetRemoteClusterRequest{
+ req: presencev1pb.GetRemoteClusterRequest_builder{
Name: "",
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "must be specified")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -183,9 +183,9 @@ func TestGetRemoteCluster(t *testing.T) {
{
name: "doesnt exist",
user: user.GetName(),
- req: &presencev1pb.GetRemoteClusterRequest{
+ req: presencev1pb.GetRemoteClusterRequest_builder{
Name: "non-existent",
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err), "error should be not found")
},
@@ -209,13 +209,13 @@ func TestGetRemoteCluster(t *testing.T) {
client, err := srv.NewClient(authtest.TestUser(user.GetName()))
require.NoError(t, err)
- _, doesntExistError := client.PresenceServiceClient().GetRemoteCluster(ctx, &presencev1pb.GetRemoteClusterRequest{
+ _, doesntExistError := client.PresenceServiceClient().GetRemoteCluster(ctx, presencev1pb.GetRemoteClusterRequest_builder{
Name: "non-existent",
- })
+ }.Build())
require.Error(t, doesntExistError)
- _, noPermissionsError := client.PresenceServiceClient().GetRemoteCluster(ctx, &presencev1pb.GetRemoteClusterRequest{
+ _, noPermissionsError := client.PresenceServiceClient().GetRemoteCluster(ctx, presencev1pb.GetRemoteClusterRequest_builder{
Name: notMatchingRC.GetName(),
- })
+ }.Build())
require.Error(t, noPermissionsError)
require.Equal(t, doesntExistError.Error(), noPermissionsError.Error(),
@@ -304,12 +304,12 @@ func TestListRemoteClusters(t *testing.T) {
user: user.GetName(),
req: &presencev1pb.ListRemoteClustersRequest{},
assertError: require.NoError,
- want: &presencev1pb.ListRemoteClustersResponse{
+ want: presencev1pb.ListRemoteClustersResponse_builder{
RemoteClusters: []*types.RemoteClusterV3{
matchingRC.(*types.RemoteClusterV3),
matchingRC2.(*types.RemoteClusterV3),
},
- },
+ }.Build(),
},
{
name: "no permissions",
@@ -383,18 +383,18 @@ func TestDeleteRemoteCluster(t *testing.T) {
{
name: "success",
user: user.GetName(),
- req: &presencev1pb.DeleteRemoteClusterRequest{
+ req: presencev1pb.DeleteRemoteClusterRequest_builder{
Name: rc.GetName(),
- },
+ }.Build(),
assertError: require.NoError,
checkResourcesDeleted: true,
},
{
name: "no permissions",
user: unprivilegedUser.GetName(),
- req: &presencev1pb.DeleteRemoteClusterRequest{
+ req: presencev1pb.DeleteRemoteClusterRequest_builder{
Name: rc.GetName(),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -402,9 +402,9 @@ func TestDeleteRemoteCluster(t *testing.T) {
{
name: "non existent",
user: user.GetName(),
- req: &presencev1pb.DeleteRemoteClusterRequest{
+ req: presencev1pb.DeleteRemoteClusterRequest_builder{
Name: rc.GetName(),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err), "error should be not found")
},
@@ -418,7 +418,7 @@ func TestDeleteRemoteCluster(t *testing.T) {
_, err = client.PresenceServiceClient().DeleteRemoteCluster(ctx, tt.req)
tt.assertError(t, err)
if tt.checkResourcesDeleted {
- _, err := srv.Auth().GetRemoteCluster(ctx, tt.req.Name)
+ _, err := srv.Auth().GetRemoteCluster(ctx, tt.req.GetName())
require.True(t, trace.IsNotFound(err), "rc should be deleted")
}
})
@@ -483,7 +483,7 @@ func TestUpdateRemoteCluster(t *testing.T) {
{
name: "success",
user: user.GetName(),
- req: &presencev1pb.UpdateRemoteClusterRequest{
+ req: presencev1pb.UpdateRemoteClusterRequest_builder{
RemoteCluster: &types.RemoteClusterV3{
Kind: types.KindRemoteCluster,
Version: types.V3,
@@ -499,7 +499,7 @@ func TestUpdateRemoteCluster(t *testing.T) {
},
},
UpdateMask: nil,
- },
+ }.Build(),
assertError: require.NoError,
want: &types.RemoteClusterV3{
@@ -520,7 +520,7 @@ func TestUpdateRemoteCluster(t *testing.T) {
{
name: "patch success",
user: user.GetName(),
- req: &presencev1pb.UpdateRemoteClusterRequest{
+ req: presencev1pb.UpdateRemoteClusterRequest_builder{
RemoteCluster: &types.RemoteClusterV3{
Kind: types.KindRemoteCluster,
Version: types.V3,
@@ -546,7 +546,7 @@ func TestUpdateRemoteCluster(t *testing.T) {
"Status.LastHeartbeat",
},
},
- },
+ }.Build(),
assertError: require.NoError,
want: &types.RemoteClusterV3{
@@ -570,7 +570,7 @@ func TestUpdateRemoteCluster(t *testing.T) {
{
name: "partial patch success",
user: user.GetName(),
- req: &presencev1pb.UpdateRemoteClusterRequest{
+ req: presencev1pb.UpdateRemoteClusterRequest_builder{
RemoteCluster: &types.RemoteClusterV3{
Kind: types.KindRemoteCluster,
Version: types.V3,
@@ -592,7 +592,7 @@ func TestUpdateRemoteCluster(t *testing.T) {
"Status.LastHeartbeat",
},
},
- },
+ }.Build(),
assertError: require.NoError,
want: &types.RemoteClusterV3{
@@ -611,13 +611,13 @@ func TestUpdateRemoteCluster(t *testing.T) {
{
name: "no permissions",
user: unprivilegedUser.GetName(),
- req: &presencev1pb.UpdateRemoteClusterRequest{
+ req: presencev1pb.UpdateRemoteClusterRequest_builder{
RemoteCluster: &types.RemoteClusterV3{
Metadata: types.Metadata{
Name: rc.GetName(),
},
},
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -625,10 +625,10 @@ func TestUpdateRemoteCluster(t *testing.T) {
{
name: "validation - nil rc",
user: user.GetName(),
- req: &presencev1pb.UpdateRemoteClusterRequest{
+ req: presencev1pb.UpdateRemoteClusterRequest_builder{
RemoteCluster: nil,
UpdateMask: nil,
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "remote_cluster: must not be nil")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -637,14 +637,14 @@ func TestUpdateRemoteCluster(t *testing.T) {
{
name: "validation - no name",
user: user.GetName(),
- req: &presencev1pb.UpdateRemoteClusterRequest{
+ req: presencev1pb.UpdateRemoteClusterRequest_builder{
RemoteCluster: &types.RemoteClusterV3{
Metadata: types.Metadata{
Name: "",
},
},
UpdateMask: nil,
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "remote_cluster.Metadata.Name: must be non-empty")
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
@@ -732,9 +732,9 @@ func TestListReverseTunnels(t *testing.T) {
user: user.GetName(),
req: &presencev1pb.ListReverseTunnelsRequest{},
assertError: require.NoError,
- want: &presencev1pb.ListReverseTunnelsResponse{
+ want: presencev1pb.ListReverseTunnelsResponse_builder{
ReverseTunnels: created,
- },
+ }.Build(),
},
{
name: "no permissions",
@@ -838,18 +838,18 @@ func TestDeleteReverseTunnel(t *testing.T) {
{
name: "success",
user: user.GetName(),
- req: &presencev1pb.DeleteReverseTunnelRequest{
+ req: presencev1pb.DeleteReverseTunnelRequest_builder{
Name: rt.GetName(),
- },
+ }.Build(),
assertError: require.NoError,
checkResourcesDeleted: true,
},
{
name: "no permissions",
user: unprivilegedUser.GetName(),
- req: &presencev1pb.DeleteReverseTunnelRequest{
+ req: presencev1pb.DeleteReverseTunnelRequest_builder{
Name: rt.GetName(),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -857,9 +857,9 @@ func TestDeleteReverseTunnel(t *testing.T) {
{
name: "non existent",
user: user.GetName(),
- req: &presencev1pb.DeleteReverseTunnelRequest{
+ req: presencev1pb.DeleteReverseTunnelRequest_builder{
Name: rt.GetName(),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err), "error should be not found")
},
@@ -873,7 +873,7 @@ func TestDeleteReverseTunnel(t *testing.T) {
_, err = client.PresenceServiceClient().DeleteReverseTunnel(ctx, tt.req)
tt.assertError(t, err)
if tt.checkResourcesDeleted {
- _, err := srv.Auth().GetReverseTunnel(ctx, tt.req.Name)
+ _, err := srv.Auth().GetReverseTunnel(ctx, tt.req.GetName())
require.True(t, trace.IsNotFound(err), "rt should be deleted")
}
})
@@ -920,18 +920,18 @@ func TestDeleteProxyServer(t *testing.T) {
{
name: "success",
user: user.GetName(),
- req: &presencev1pb.DeleteProxyServerRequest{
+ req: presencev1pb.DeleteProxyServerRequest_builder{
Name: proxy.GetName(),
- },
+ }.Build(),
assertError: require.NoError,
checkResourcesDeleted: true,
},
{
name: "no permissions",
user: unprivilegedUser.GetName(),
- req: &presencev1pb.DeleteProxyServerRequest{
+ req: presencev1pb.DeleteProxyServerRequest_builder{
Name: proxy.GetName(),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -939,9 +939,9 @@ func TestDeleteProxyServer(t *testing.T) {
{
name: "non existent",
user: user.GetName(),
- req: &presencev1pb.DeleteProxyServerRequest{
+ req: presencev1pb.DeleteProxyServerRequest_builder{
Name: proxy.GetName(),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsNotFound(err), "error should be not found")
},
@@ -966,7 +966,7 @@ func TestDeleteProxyServer(t *testing.T) {
proxies, err := stream.Collect(clientutils.Resources(ctx, srv.Auth().ListProxyServers))
require.NoError(t, err)
for _, p := range proxies {
- require.NotEqual(t, tt.req.Name, p.GetName(), "proxy should be deleted")
+ require.NotEqual(t, tt.req.GetName(), p.GetName(), "proxy should be deleted")
}
}
})
@@ -1014,18 +1014,18 @@ func TestUpsertProxyServer(t *testing.T) {
{
name: "success",
user: user.GetName(),
- req: &presencev1pb.UpsertProxyServerRequest{
+ req: presencev1pb.UpsertProxyServerRequest_builder{
Server: proxy.(*types.ServerV2),
- },
+ }.Build(),
assertError: require.NoError,
checkResourceUpserted: true,
},
{
name: "no permissions",
user: unprivilegedUser.GetName(),
- req: &presencev1pb.UpsertProxyServerRequest{
+ req: presencev1pb.UpsertProxyServerRequest_builder{
Server: proxy.(*types.ServerV2),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -1041,7 +1041,7 @@ func TestUpsertProxyServer(t *testing.T) {
{
name: "validation failure - blank name",
user: user.GetName(),
- req: &presencev1pb.UpsertProxyServerRequest{
+ req: presencev1pb.UpsertProxyServerRequest_builder{
Server: &types.ServerV2{
Kind: types.KindProxy,
Version: types.V2,
@@ -1049,7 +1049,7 @@ func TestUpsertProxyServer(t *testing.T) {
Name: "",
},
},
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
},
@@ -1067,7 +1067,7 @@ func TestUpsertProxyServer(t *testing.T) {
require.NoError(t, err)
var found bool
for _, p := range proxies {
- if p.GetName() == tt.req.Server.GetName() {
+ if p.GetName() == tt.req.GetServer().GetName() {
found = true
break
}
@@ -1118,18 +1118,18 @@ func TestUpsertReverseTunnel(t *testing.T) {
{
name: "success",
user: user.GetName(),
- req: &presencev1pb.UpsertReverseTunnelRequest{
+ req: presencev1pb.UpsertReverseTunnelRequest_builder{
ReverseTunnel: rt.(*types.ReverseTunnelV2),
- },
+ }.Build(),
assertError: require.NoError,
want: rt.(*types.ReverseTunnelV2),
},
{
name: "no permissions",
user: unprivilegedUser.GetName(),
- req: &presencev1pb.UpsertReverseTunnelRequest{
+ req: presencev1pb.UpsertReverseTunnelRequest_builder{
ReverseTunnel: rt.(*types.ReverseTunnelV2),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsAccessDenied(err), "error should be access denied")
},
@@ -1137,9 +1137,9 @@ func TestUpsertReverseTunnel(t *testing.T) {
{
name: "no value",
user: user.GetName(),
- req: &presencev1pb.UpsertReverseTunnelRequest{
+ req: presencev1pb.UpsertReverseTunnelRequest_builder{
ReverseTunnel: nil,
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.True(t, trace.IsBadParameter(err), "error should be bad parameter")
},
@@ -1147,9 +1147,9 @@ func TestUpsertReverseTunnel(t *testing.T) {
{
name: "validation - invalid",
user: user.GetName(),
- req: &presencev1pb.UpsertReverseTunnelRequest{
+ req: presencev1pb.UpsertReverseTunnelRequest_builder{
ReverseTunnel: invalid.(*types.ReverseTunnelV2),
- },
+ }.Build(),
assertError: func(t require.TestingT, err error, i ...any) {
require.ErrorContains(t, err, "failed to parse")
},
diff --git a/lib/auth/recordingencryption/manager.go b/lib/auth/recordingencryption/manager.go
index 81213048687..49f78cb6659 100644
--- a/lib/auth/recordingencryption/manager.go
+++ b/lib/auth/recordingencryption/manager.go
@@ -223,17 +223,17 @@ func (m *Manager) ensureManualEncryptionKeys(ctx context.Context, manualKeyCfg t
return nil, trace.Wrap(err)
}
- encryptionKeys = append(encryptionKeys, &recordingencryptionv1.KeyPair{
+ encryptionKeys = append(encryptionKeys, recordingencryptionv1.KeyPair_builder{
KeyPair: &types.EncryptionKeyPair{
PublicKey: pubKey,
},
- })
+ }.Build())
}
- return &recordingencryptionv1.RecordingEncryption{
- Spec: &recordingencryptionv1.RecordingEncryptionSpec{
+ return recordingencryptionv1.RecordingEncryption_builder{
+ Spec: recordingencryptionv1.RecordingEncryptionSpec_builder{
ActiveKeyPairs: encryptionKeys,
- },
- }, nil
+ }.Build(),
+ }.Build(), nil
}
// ensureActiveKeyPair checks that there is at least one accessible key in the list of active pairs given.
@@ -243,14 +243,14 @@ func (m *Manager) ensureActiveKeyPair(ctx context.Context, activePairs []*record
var foundActiveKey bool
if len(activePairs) > 0 {
for _, pair := range activePairs {
- if pair.State != recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE {
+ if pair.GetState() != recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE {
continue
}
foundActiveKey = true
// fetch the decrypter to ensure we have access to it
- if _, err := m.keyStore.GetDecrypter(ctx, pair.KeyPair); err != nil {
- fp, _ := fingerprintPEM(pair.KeyPair.PublicKey)
+ if _, err := m.keyStore.GetDecrypter(ctx, pair.GetKeyPair()); err != nil {
+ fp, _ := fingerprintPEM(pair.GetKeyPair().PublicKey)
m.logger.DebugContext(ctx, "key not accessible", "fingerprint", fp)
continue
}
@@ -273,10 +273,10 @@ func (m *Manager) ensureActiveKeyPair(ctx context.Context, activePairs []*record
fp, _ := fingerprintPEM(encryptionPair.PublicKey)
m.logger.InfoContext(ctx, "no active encryption keys, generated new pair", "public_fingerprint", fp)
- return append(activePairs, &recordingencryptionv1.KeyPair{
+ return append(activePairs, recordingencryptionv1.KeyPair_builder{
KeyPair: encryptionPair,
State: recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE,
- }), true, nil
+ }.Build()), true, nil
}
// resolveRecordingEncryption returns the configured [RecordingEncryption] resource if it exists with an
@@ -310,9 +310,9 @@ func (m *Manager) resolveRecordingEncryption(ctx context.Context, sessionRecordi
if !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
- encryption = &recordingencryptionv1.RecordingEncryption{
+ encryption = recordingencryptionv1.RecordingEncryption_builder{
Spec: &recordingencryptionv1.RecordingEncryptionSpec{},
- }
+ }.Build()
persistFn = m.RecordingEncryption.CreateRecordingEncryption
}
}
@@ -326,7 +326,7 @@ func (m *Manager) resolveRecordingEncryption(ctx context.Context, sessionRecordi
return encryption, nil
}
- encryption.Spec.ActiveKeyPairs = activePairs
+ encryption.GetSpec().SetActiveKeyPairs(activePairs)
encryption, err = persistFn(ctx, encryption)
if err != nil {
return nil, trace.Wrap(err)
@@ -355,7 +355,7 @@ func (m *Manager) findDecrypter(ctx context.Context, fingerprint string) (crypto
continue
}
- activeFP, err := fingerprintPEM(key.KeyPair.PublicKey)
+ activeFP, err := fingerprintPEM(key.GetKeyPair().PublicKey)
if err != nil {
m.logger.ErrorContext(ctx, "failed to fingerprint active public key", "error", err)
continue
@@ -365,7 +365,7 @@ func (m *Manager) findDecrypter(ctx context.Context, fingerprint string) (crypto
continue
}
- decrypter, err := m.keyStore.GetDecrypter(ctx, key.KeyPair)
+ decrypter, err := m.keyStore.GetDecrypter(ctx, key.GetKeyPair())
if err != nil {
continue
}
@@ -457,7 +457,7 @@ func (m *Manager) RotateKey(ctx context.Context) error {
return trace.NotFound("no active key present to rotate")
}
- activePair.State = recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ROTATING
+ activePair.SetState(recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ROTATING)
if _, err := m.modifyRecordingEncryption(ctx, encryption); err != nil {
return trace.Wrap(err)
}
@@ -501,7 +501,7 @@ func (m *Manager) CompleteRotation(ctx context.Context) error {
}
}
- encryption.Spec.ActiveKeyPairs = remainingPairs
+ encryption.GetSpec().SetActiveKeyPairs(remainingPairs)
if _, err := m.modifyRecordingEncryption(ctx, encryption); err != nil {
return trace.Wrap(err)
}
@@ -530,7 +530,7 @@ func (m *Manager) RollbackRotation(ctx context.Context) error {
var rollbackPairs []*recordingencryptionv1.KeyPair
for _, pair := range activePairs {
if pair.GetState() == recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ROTATING {
- pair.State = recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE
+ pair.SetState(recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE)
rollbackPairs = append(rollbackPairs, pair)
}
}
@@ -539,7 +539,7 @@ func (m *Manager) RollbackRotation(ctx context.Context) error {
return trace.BadParameter("skipping rollback that would remove all encryption keys")
}
- encryption.Spec.ActiveKeyPairs = rollbackPairs
+ encryption.GetSpec().SetActiveKeyPairs(rollbackPairs)
if _, err := m.modifyRecordingEncryption(ctx, encryption); err != nil {
return trace.Wrap(err)
}
@@ -575,10 +575,10 @@ func (m *Manager) GetRotationState(ctx context.Context) ([]*recordingencryptionv
return nil, trace.Wrap(err)
}
- states = append(states, &recordingencryptionv1.FingerprintWithState{
+ states = append(states, recordingencryptionv1.FingerprintWithState_builder{
Fingerprint: fingerprint,
State: pair.GetState(),
- })
+ }.Build())
}
return states, nil
@@ -746,12 +746,12 @@ func (m *Manager) resolveRecordingEncryptionState(ctx context.Context, shouldRet
func getAgeEncryptionKeys(keys []*recordingencryptionv1.KeyPair) iter.Seq[*types.AgeEncryptionKey] {
return func(yield func(*types.AgeEncryptionKey) bool) {
for _, key := range keys {
- if key.KeyPair == nil {
+ if !key.HasKeyPair() {
continue
}
if !yield(&types.AgeEncryptionKey{
- PublicKey: key.KeyPair.PublicKey,
+ PublicKey: key.GetKeyPair().PublicKey,
}) {
return
}
diff --git a/lib/auth/recordingencryption/manager_test.go b/lib/auth/recordingencryption/manager_test.go
index 98f1a3ee8fc..f7875ba85f0 100644
--- a/lib/auth/recordingencryption/manager_test.go
+++ b/lib/auth/recordingencryption/manager_test.go
@@ -283,9 +283,9 @@ func TestCreateUpdateSessionRecordingConfig(t *testing.T) {
require.NoError(t, err)
activePairs := encryption.GetSpec().GetActiveKeyPairs()
require.Len(t, activePairs, 1)
- require.NotNil(t, activePairs[0].KeyPair)
- require.NotEmpty(t, activePairs[0].KeyPair.PrivateKey)
- require.NotEmpty(t, activePairs[0].KeyPair.PublicKey)
+ require.NotNil(t, activePairs[0].GetKeyPair())
+ require.NotEmpty(t, activePairs[0].GetKeyPair().PrivateKey)
+ require.NotEmpty(t, activePairs[0].GetKeyPair().PublicKey)
// update should change nothing
src, err = manager.UpdateSessionRecordingConfig(ctx, src)
@@ -331,16 +331,16 @@ func TestResolveRecordingEncryption(t *testing.T) {
require.Len(t, initialKeys, 1)
require.Len(t, src.GetEncryptionKeys(), 1)
key := initialKeys[0]
- require.Equal(t, key.KeyPair.PublicKey, src.GetEncryptionKeys()[0].PublicKey)
- require.NotNil(t, key.KeyPair)
+ require.Equal(t, key.GetKeyPair().PublicKey, src.GetEncryptionKeys()[0].PublicKey)
+ require.NotNil(t, key.GetKeyPair())
// CASE: service B should have access to the same key
encryption, src, err = resolve(ctx, service, managerB)
require.NoError(t, err)
- activePairs := encryption.GetSpec().ActiveKeyPairs
+ activePairs := encryption.GetSpec().GetActiveKeyPairs()
require.Len(t, src.GetEncryptionKeys(), 1)
- require.Equal(t, key.KeyPair.PublicKey, src.GetEncryptionKeys()[0].PublicKey)
+ require.Equal(t, key.GetKeyPair().PublicKey, src.GetEncryptionKeys()[0].PublicKey)
require.ElementsMatch(t, initialKeys, activePairs)
// service C should error without access to the current key
@@ -382,13 +382,13 @@ func TestResolveRecordingEncryptionConcurrent(t *testing.T) {
encryption, err := service.GetRecordingEncryption(ctx)
require.NoError(t, err)
- activePairs := encryption.GetSpec().ActiveKeyPairs
+ activePairs := encryption.GetSpec().GetActiveKeyPairs()
// each service should share a single active key
require.Len(t, activePairs, 1)
- require.NotNil(t, activePairs[0].KeyPair)
- require.NotEmpty(t, activePairs[0].KeyPair.PrivateKey)
- require.NotEmpty(t, activePairs[0].KeyPair.PublicKey)
- require.Equal(t, types.PrivateKeyType_RAW, activePairs[0].KeyPair.PrivateKeyType)
+ require.NotNil(t, activePairs[0].GetKeyPair())
+ require.NotEmpty(t, activePairs[0].GetKeyPair().PrivateKey)
+ require.NotEmpty(t, activePairs[0].GetKeyPair().PublicKey)
+ require.Equal(t, types.PrivateKeyType_RAW, activePairs[0].GetKeyPair().PrivateKeyType)
}
func TestUnwrapKey(t *testing.T) {
@@ -464,10 +464,10 @@ func TestRotateKey(t *testing.T) {
activePairs := encryption.GetSpec().GetActiveKeyPairs()
require.Len(t, activePairs, 1)
initialKey := activePairs[0]
- require.NotNil(t, initialKey.KeyPair)
- require.NotEmpty(t, initialKey.KeyPair.PrivateKey)
- require.NotEmpty(t, initialKey.KeyPair.PublicKey)
- require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, initialKey.State)
+ require.NotNil(t, initialKey.GetKeyPair())
+ require.NotEmpty(t, initialKey.GetKeyPair().PrivateKey)
+ require.NotEmpty(t, initialKey.GetKeyPair().PublicKey)
+ require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, initialKey.GetState())
// rotate key
err = manager.RotateKey(ctx)
@@ -481,12 +481,12 @@ func TestRotateKey(t *testing.T) {
var foundInitialPair bool
var newPair *recordingencryptionv1.KeyPair
for _, pair := range activePairs {
- if slices.Equal(initialKey.KeyPair.PublicKey, pair.KeyPair.PublicKey) {
- require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ROTATING, pair.State)
+ if slices.Equal(initialKey.GetKeyPair().PublicKey, pair.GetKeyPair().PublicKey) {
+ require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ROTATING, pair.GetState())
foundInitialPair = true
} else {
newPair = pair
- require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, pair.State)
+ require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, pair.GetState())
}
}
@@ -501,11 +501,11 @@ func TestRotateKey(t *testing.T) {
activePairs = encryption.GetSpec().GetActiveKeyPairs()
require.Len(t, activePairs, 1)
- require.Equal(t, newPair.KeyPair.PublicKey, activePairs[0].KeyPair.PublicKey)
- require.Equal(t, newPair.KeyPair.PrivateKey, activePairs[0].KeyPair.PrivateKey)
- require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, activePairs[0].State)
+ require.Equal(t, newPair.GetKeyPair().PublicKey, activePairs[0].GetKeyPair().PublicKey)
+ require.Equal(t, newPair.GetKeyPair().PrivateKey, activePairs[0].GetKeyPair().PrivateKey)
+ require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, activePairs[0].GetState())
- pubKey, err := x509.ParsePKIXPublicKey(initialKey.KeyPair.PublicKey)
+ pubKey, err := x509.ParsePKIXPublicKey(initialKey.GetKeyPair().PublicKey)
require.NoError(t, err)
fingerprint, err := recordingencryption.Fingerprint(pubKey)
@@ -514,8 +514,8 @@ func TestRotateKey(t *testing.T) {
rotatedKey, err := config.Backend.GetRotatedKey(ctx, fingerprint)
require.NoError(t, err)
- require.Equal(t, initialKey.KeyPair.PublicKey, rotatedKey.Spec.EncryptionKeyPair.PublicKey)
- require.Equal(t, initialKey.KeyPair.PrivateKey, rotatedKey.Spec.EncryptionKeyPair.PrivateKey)
+ require.Equal(t, initialKey.GetKeyPair().PublicKey, rotatedKey.GetSpec().GetEncryptionKeyPair().PublicKey)
+ require.Equal(t, initialKey.GetKeyPair().PrivateKey, rotatedKey.GetSpec().GetEncryptionKeyPair().PrivateKey)
}
func TestRotateRollback(t *testing.T) {
@@ -542,10 +542,10 @@ func TestRotateRollback(t *testing.T) {
activePairs := encryption.GetSpec().GetActiveKeyPairs()
require.Len(t, activePairs, 1)
initialKey := proto.CloneOf(activePairs[0])
- require.NotNil(t, initialKey.KeyPair)
- require.NotEmpty(t, initialKey.KeyPair.PrivateKey)
- require.NotEmpty(t, initialKey.KeyPair.PublicKey)
- require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, initialKey.State)
+ require.NotNil(t, initialKey.GetKeyPair())
+ require.NotEmpty(t, initialKey.GetKeyPair().PrivateKey)
+ require.NotEmpty(t, initialKey.GetKeyPair().PublicKey)
+ require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, initialKey.GetState())
// rotate key
err = manager.RotateKey(ctx)
@@ -559,12 +559,12 @@ func TestRotateRollback(t *testing.T) {
var foundInitialPair bool
var newPair *recordingencryptionv1.KeyPair
for _, pair := range activePairs {
- if slices.Equal(initialKey.KeyPair.PublicKey, pair.KeyPair.PublicKey) {
- require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ROTATING, pair.State)
+ if slices.Equal(initialKey.GetKeyPair().PublicKey, pair.GetKeyPair().PublicKey) {
+ require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ROTATING, pair.GetState())
foundInitialPair = true
} else {
newPair = pair
- require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, pair.State)
+ require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, pair.GetState())
}
}
@@ -579,11 +579,11 @@ func TestRotateRollback(t *testing.T) {
activePairs = encryption.GetSpec().GetActiveKeyPairs()
require.Len(t, activePairs, 1)
- require.Equal(t, initialKey.KeyPair.PublicKey, activePairs[0].KeyPair.PublicKey)
- require.Equal(t, initialKey.KeyPair.PrivateKey, activePairs[0].KeyPair.PrivateKey)
- require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, activePairs[0].State)
+ require.Equal(t, initialKey.GetKeyPair().PublicKey, activePairs[0].GetKeyPair().PublicKey)
+ require.Equal(t, initialKey.GetKeyPair().PrivateKey, activePairs[0].GetKeyPair().PrivateKey)
+ require.Equal(t, recordingencryptionv1.KeyPairState_KEY_PAIR_STATE_ACTIVE, activePairs[0].GetState())
- pubKey, err := x509.ParsePKIXPublicKey(initialKey.KeyPair.PublicKey)
+ pubKey, err := x509.ParsePKIXPublicKey(initialKey.GetKeyPair().PublicKey)
require.NoError(t, err)
fingerprint, err := recordingencryption.Fingerprint(pubKey)
diff --git a/lib/auth/recordingencryption/recordingencryptionv1/service.go b/lib/auth/recordingencryption/recordingencryptionv1/service.go
index f2c8598283a..3c145941860 100644
--- a/lib/auth/recordingencryption/recordingencryptionv1/service.go
+++ b/lib/auth/recordingencryption/recordingencryptionv1/service.go
@@ -114,30 +114,30 @@ type Service struct {
}
func streamUploadAsProto(upload events.StreamUpload) *recordingencryptionv1.Upload {
- return &recordingencryptionv1.Upload{
+ return recordingencryptionv1.Upload_builder{
UploadId: upload.ID,
SessionId: upload.SessionID.String(),
InitiatedAt: timestamppb.New(upload.Initiated),
- }
+ }.Build()
}
func protoAsStreamUpload(upload *recordingencryptionv1.Upload) (events.StreamUpload, error) {
- sessionID, err := session.ParseID(upload.SessionId)
+ sessionID, err := session.ParseID(upload.GetSessionId())
if err != nil {
return events.StreamUpload{}, trace.Wrap(err)
}
return events.StreamUpload{
- ID: upload.UploadId,
+ ID: upload.GetUploadId(),
SessionID: *sessionID,
- Initiated: upload.InitiatedAt.AsTime(),
+ Initiated: upload.GetInitiatedAt().AsTime(),
}, nil
}
func protoAsStreamPart(part *recordingencryptionv1.Part) events.StreamPart {
return events.StreamPart{
- Number: part.PartNumber,
- ETag: part.Etag,
+ Number: part.GetPartNumber(),
+ ETag: part.GetEtag(),
LastModified: time.Now(),
}
}
@@ -148,8 +148,8 @@ func (s *Service) CreateUpload(ctx context.Context, req *recordingencryptionv1.C
return nil, trace.AccessDenied("access denied")
}
- s.logger.DebugContext(ctx, "creating encrypted session upload", "session_id", req.SessionId)
- sessionID, err := session.ParseID(req.SessionId)
+ s.logger.DebugContext(ctx, "creating encrypted session upload", "session_id", req.GetSessionId())
+ sessionID, err := session.ParseID(req.GetSessionId())
if err != nil {
return nil, trace.Wrap(err)
}
@@ -159,14 +159,14 @@ func (s *Service) CreateUpload(ctx context.Context, req *recordingencryptionv1.C
return nil, trace.Wrap(err, "creating encrypted recording upload")
}
- return &recordingencryptionv1.CreateUploadResponse{
+ return recordingencryptionv1.CreateUploadResponse_builder{
Upload: streamUploadAsProto(*upload),
- }, nil
+ }.Build(), nil
}
// UploadPart uploads an encrypted session recording part to the given upload ID.
func (s *Service) UploadPart(ctx context.Context, req *recordingencryptionv1.UploadPartRequest) (*recordingencryptionv1.UploadPartResponse, error) {
- if err := validateUpload(req.Upload); err != nil {
+ if err := validateUpload(req.GetUpload()); err != nil {
return nil, trace.Wrap(err)
}
@@ -174,39 +174,39 @@ func (s *Service) UploadPart(ctx context.Context, req *recordingencryptionv1.Upl
return nil, trace.AccessDenied("access denied")
}
- s.logger.DebugContext(ctx, "uploading encrypted session part", "upload_id", req.Upload.UploadId, "session_id", req.Upload.SessionId, "part_number", req.PartNumber)
- upload, err := protoAsStreamUpload(req.Upload)
+ s.logger.DebugContext(ctx, "uploading encrypted session part", "upload_id", req.GetUpload().GetUploadId(), "session_id", req.GetUpload().GetSessionId(), "part_number", req.GetPartNumber())
+ upload, err := protoAsStreamUpload(req.GetUpload())
if err != nil {
return nil, trace.Wrap(err)
}
- if err := s.uploader.ReserveUploadPart(ctx, upload, req.PartNumber); err != nil {
+ if err := s.uploader.ReserveUploadPart(ctx, upload, req.GetPartNumber()); err != nil {
return nil, trace.Wrap(err)
}
// If upload part is not at least the minimum upload part size, append an empty part
// to pad up to the minimum upload size.
- part := req.Part
- if !req.IsLast && len(part) < events.MinUploadPartSizeBytes {
+ part := req.GetPart()
+ if !req.GetIsLast() && len(part) < events.MinUploadPartSizeBytes {
part = events.PadUploadPart(part, events.MinUploadPartSizeBytes)
}
- streamPart, err := s.uploader.UploadPart(ctx, upload, req.PartNumber, bytes.NewReader(part))
+ streamPart, err := s.uploader.UploadPart(ctx, upload, req.GetPartNumber(), bytes.NewReader(part))
if err != nil {
return nil, trace.Wrap(err, "uploading encrypted recording part")
}
- return &recordingencryptionv1.UploadPartResponse{
- Part: &recordingencryptionv1.Part{
+ return recordingencryptionv1.UploadPartResponse_builder{
+ Part: recordingencryptionv1.Part_builder{
PartNumber: streamPart.Number,
Etag: streamPart.ETag,
- },
- }, nil
+ }.Build(),
+ }.Build(), nil
}
// CompleteUpload marks a given encrypted session upload as complete.
func (s *Service) CompleteUpload(ctx context.Context, req *recordingencryptionv1.CompleteUploadRequest) (*recordingencryptionv1.CompleteUploadResponse, error) {
- if err := validateUpload(req.Upload); err != nil {
+ if err := validateUpload(req.GetUpload()); err != nil {
return nil, trace.Wrap(err)
}
@@ -214,14 +214,14 @@ func (s *Service) CompleteUpload(ctx context.Context, req *recordingencryptionv1
return nil, trace.AccessDenied("access denied")
}
- s.logger.DebugContext(ctx, "completing encrypted session upload", "upload_id", req.Upload.UploadId, "session_id", req.Upload.SessionId, "parts", len(req.Parts))
- upload, err := protoAsStreamUpload(req.Upload)
+ s.logger.DebugContext(ctx, "completing encrypted session upload", "upload_id", req.GetUpload().GetUploadId(), "session_id", req.GetUpload().GetSessionId(), "parts", len(req.GetParts()))
+ upload, err := protoAsStreamUpload(req.GetUpload())
if err != nil {
return nil, trace.Wrap(err)
}
- parts := make([]events.StreamPart, len(req.Parts))
- for idx, part := range req.Parts {
+ parts := make([]events.StreamPart, len(req.GetParts()))
+ for idx, part := range req.GetParts() {
parts[idx] = protoAsStreamPart(part)
}
@@ -319,18 +319,18 @@ func (s *Service) GetRotationState(ctx context.Context, req *recordingencryption
return nil, trace.Wrap(err)
}
- return &recordingencryptionv1.GetRotationStateResponse{
+ return recordingencryptionv1.GetRotationStateResponse_builder{
KeyPairStates: states,
- }, nil
+ }.Build(), nil
}
func validateUpload(upload *recordingencryptionv1.Upload) error {
switch {
case upload == nil:
return trace.BadParameter("upload is required")
- case upload.UploadId == "":
+ case upload.GetUploadId() == "":
return trace.BadParameter("upload.upload_id is required")
- case upload.SessionId == "":
+ case upload.GetSessionId() == "":
return trace.BadParameter("upload.session_id is required")
}
return nil
diff --git a/lib/auth/recordingencryption/recordingencryptionv1/service_test.go b/lib/auth/recordingencryption/recordingencryptionv1/service_test.go
index 2012bb96541..d171b7e87aa 100644
--- a/lib/auth/recordingencryption/recordingencryptionv1/service_test.go
+++ b/lib/auth/recordingencryption/recordingencryptionv1/service_test.go
@@ -178,7 +178,7 @@ func TestGetRotationState(t *testing.T) {
res, err := service.GetRotationState(withAuthCtx(t.Context(), c.ctx), nil)
c.assertErr(t, err)
if err == nil {
- require.Len(t, res.KeyPairStates, 1)
+ require.Len(t, res.GetKeyPairStates(), 1)
} else {
require.Nil(t, res)
}
@@ -245,10 +245,10 @@ type fakeKeyRotater struct {
func newFakeKeyRotater() *fakeKeyRotater {
return &fakeKeyRotater{
keys: []*recordingencryptionv1pb.FingerprintWithState{
- {
+ recordingencryptionv1pb.FingerprintWithState_builder{
Fingerprint: uuid.New().String(),
State: recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ACTIVE,
- },
+ }.Build(),
},
}
}
@@ -258,15 +258,15 @@ func (f *fakeKeyRotater) RotateKey(ctx context.Context) error {
return errors.New("rotation in progress")
}
- if f.keys[0].State != recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ACTIVE {
- return fmt.Errorf("keys in unexpected state: %v", f.keys[0].State)
+ if f.keys[0].GetState() != recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ACTIVE {
+ return fmt.Errorf("keys in unexpected state: %v", f.keys[0].GetState())
}
- f.keys[0].State = recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ROTATING
- f.keys = append(f.keys, &recordingencryptionv1pb.FingerprintWithState{
+ f.keys[0].SetState(recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ROTATING)
+ f.keys = append(f.keys, recordingencryptionv1pb.FingerprintWithState_builder{
Fingerprint: uuid.New().String(),
State: recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ACTIVE,
- })
+ }.Build())
return nil
}
@@ -274,7 +274,7 @@ func (f *fakeKeyRotater) RotateKey(ctx context.Context) error {
func (f *fakeKeyRotater) CompleteRotation(ctx context.Context) error {
var keys []*recordingencryptionv1pb.FingerprintWithState
for _, key := range f.keys {
- if key.State == recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ACTIVE {
+ if key.GetState() == recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ACTIVE {
keys = append(keys, key)
}
}
@@ -286,7 +286,7 @@ func (f *fakeKeyRotater) CompleteRotation(ctx context.Context) error {
func (f *fakeKeyRotater) RollbackRotation(ctx context.Context) error {
var keys []*recordingencryptionv1pb.FingerprintWithState
for _, key := range f.keys {
- if key.State == recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ROTATING {
+ if key.GetState() == recordingencryptionv1pb.KeyPairState_KEY_PAIR_STATE_ROTATING {
keys = append(keys, key)
}
}
@@ -335,13 +335,13 @@ func TestSessionCompleter(t *testing.T) {
require.NoError(t, err)
ctx := withAuthCtx(t.Context(), newServiceAuthCtx(t))
- _, err = service.CompleteUpload(ctx, &recordingencryptionv1pb.CompleteUploadRequest{
- Upload: &recordingencryptionv1pb.Upload{
+ _, err = service.CompleteUpload(ctx, recordingencryptionv1pb.CompleteUploadRequest_builder{
+ Upload: recordingencryptionv1pb.Upload_builder{
SessionId: string(sessionID),
InitiatedAt: timestamppb.Now(),
UploadId: uuid.NewString(),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
recorderMetadata.AssertExpectations(t)
@@ -427,13 +427,13 @@ func TestCompleteUploadRecoversMissingSessionEnd(t *testing.T) {
require.NoError(t, err)
ctx := withAuthCtx(t.Context(), newServiceAuthCtx(t))
- _, err = service.CompleteUpload(ctx, &recordingencryptionv1pb.CompleteUploadRequest{
- Upload: &recordingencryptionv1pb.Upload{
+ _, err = service.CompleteUpload(ctx, recordingencryptionv1pb.CompleteUploadRequest_builder{
+ Upload: recordingencryptionv1pb.Upload_builder{
SessionId: string(sessionID),
InitiatedAt: timestamppb.Now(),
UploadId: uuid.NewString(),
- },
- })
+ }.Build(),
+ }.Build())
require.NoError(t, err)
// The recovered session end event must have been emitted to the audit log.
@@ -486,21 +486,21 @@ func TestUploadValidation(t *testing.T) {
},
{
name: "missing upload_id",
- uploadPartReq: &recordingencryptionv1pb.UploadPartRequest{
- Upload: &recordingencryptionv1pb.Upload{SessionId: uuid.NewString()},
- },
- completeReq: &recordingencryptionv1pb.CompleteUploadRequest{
- Upload: &recordingencryptionv1pb.Upload{SessionId: uuid.NewString()},
- },
+ uploadPartReq: recordingencryptionv1pb.UploadPartRequest_builder{
+ Upload: recordingencryptionv1pb.Upload_builder{SessionId: uuid.NewString()}.Build(),
+ }.Build(),
+ completeReq: recordingencryptionv1pb.CompleteUploadRequest_builder{
+ Upload: recordingencryptionv1pb.Upload_builder{SessionId: uuid.NewString()}.Build(),
+ }.Build(),
},
{
name: "missing session_id",
- uploadPartReq: &recordingencryptionv1pb.UploadPartRequest{
- Upload: &recordingencryptionv1pb.Upload{UploadId: uuid.NewString()},
- },
- completeReq: &recordingencryptionv1pb.CompleteUploadRequest{
- Upload: &recordingencryptionv1pb.Upload{UploadId: uuid.NewString()},
- },
+ uploadPartReq: recordingencryptionv1pb.UploadPartRequest_builder{
+ Upload: recordingencryptionv1pb.Upload_builder{UploadId: uuid.NewString()}.Build(),
+ }.Build(),
+ completeReq: recordingencryptionv1pb.CompleteUploadRequest_builder{
+ Upload: recordingencryptionv1pb.Upload_builder{UploadId: uuid.NewString()}.Build(),
+ }.Build(),
},
}
@@ -521,14 +521,14 @@ func TestUploadValidation(t *testing.T) {
func TestAuthorizeUpload(t *testing.T) {
newUpload := func() *recordingencryptionv1pb.Upload {
- return &recordingencryptionv1pb.Upload{
+ return recordingencryptionv1pb.Upload_builder{
SessionId: uuid.NewString(),
UploadId: uuid.NewString(),
InitiatedAt: timestamppb.Now(),
- }
+ }.Build()
}
newUploadReq := func() *recordingencryptionv1pb.CreateUploadRequest {
- return &recordingencryptionv1pb.CreateUploadRequest{SessionId: uuid.NewString()}
+ return recordingencryptionv1pb.CreateUploadRequest_builder{SessionId: uuid.NewString()}.Build()
}
accessDeniedAssert := func(t require.TestingT, err error, i ...any) {
@@ -593,10 +593,10 @@ func TestAuthorizeUpload(t *testing.T) {
_, err := svc.CreateUpload(ctx, newUploadReq())
c.errAssertFunc(t, err)
- _, err = svc.UploadPart(ctx, &recordingencryptionv1pb.UploadPartRequest{Upload: newUpload(), IsLast: true})
+ _, err = svc.UploadPart(ctx, recordingencryptionv1pb.UploadPartRequest_builder{Upload: newUpload(), IsLast: true}.Build())
c.errAssertFunc(t, err)
- _, err = svc.CompleteUpload(ctx, &recordingencryptionv1pb.CompleteUploadRequest{Upload: newUpload()})
+ _, err = svc.CompleteUpload(ctx, recordingencryptionv1pb.CompleteUploadRequest_builder{Upload: newUpload()}.Build())
c.errAssertFunc(t, err)
})
}
@@ -692,29 +692,29 @@ func TestRecordingEncryptionService(t *testing.T) {
cli := authClient.RecordingEncryptionServiceClient()
- upload := &recordingencryptionv1pb.Upload{
+ upload := recordingencryptionv1pb.Upload_builder{
UploadId: uuid.NewString(),
SessionId: uuid.NewString(),
InitiatedAt: timestamppb.Now(),
- }
+ }.Build()
- createResp, err := cli.CreateUpload(t.Context(), &recordingencryptionv1pb.CreateUploadRequest{
+ createResp, err := cli.CreateUpload(t.Context(), recordingencryptionv1pb.CreateUploadRequest_builder{
SessionId: uuid.NewString(),
- })
+ }.Build())
c.assertErr(t, err)
if err == nil {
- upload = createResp.Upload
+ upload = createResp.GetUpload()
}
- _, err = cli.UploadPart(t.Context(), &recordingencryptionv1pb.UploadPartRequest{
+ _, err = cli.UploadPart(t.Context(), recordingencryptionv1pb.UploadPartRequest_builder{
Upload: upload,
IsLast: true,
- })
+ }.Build())
c.assertErr(t, err)
- _, err = cli.CompleteUpload(t.Context(), &recordingencryptionv1pb.CompleteUploadRequest{
+ _, err = cli.CompleteUpload(t.Context(), recordingencryptionv1pb.CompleteUploadRequest_builder{
Upload: upload,
- })
+ }.Build())
c.assertErr(t, err)
})
}
diff --git a/lib/auth/recordingmetadata/recordingmetadatav1/desktopprocessor.go b/lib/auth/recordingmetadata/recordingmetadatav1/desktopprocessor.go
index 6cc3e617d64..5b4110a3617 100644
--- a/lib/auth/recordingmetadata/recordingmetadatav1/desktopprocessor.go
+++ b/lib/auth/recordingmetadata/recordingmetadatav1/desktopprocessor.go
@@ -63,10 +63,10 @@ func (d *desktopProcessor) handleEvent(evt apievents.AuditEvent) error {
func (d *desktopProcessor) handleWindowsDesktopSessionStart(evt *apievents.WindowsDesktopSessionStart) error {
d.startTime = evt.GetTime()
- d.metadata.ClusterName = evt.ClusterName
- d.metadata.User = evt.User
- d.metadata.ResourceName = evt.DesktopName
- d.metadata.Type = pb.SessionRecordingType_SESSION_RECORDING_TYPE_WINDOWS_DESKTOP
+ d.metadata.SetClusterName(evt.ClusterName)
+ d.metadata.SetUser(evt.User)
+ d.metadata.SetResourceName(evt.DesktopName)
+ d.metadata.SetType(pb.SessionRecordingType_SESSION_RECORDING_TYPE_WINDOWS_DESKTOP)
return nil
}
@@ -82,11 +82,11 @@ func (d *desktopProcessor) handleDesktopRecording(evt *apievents.DesktopRecordin
}
func (d *desktopProcessor) handleWindowsDesktopSessionEnd(evt *apievents.WindowsDesktopSessionEnd) error {
- if d.metadata.Type == pb.SessionRecordingType_SESSION_RECORDING_TYPE_UNSPECIFIED {
- d.metadata.ClusterName = evt.ClusterName
- d.metadata.User = evt.User
- d.metadata.ResourceName = evt.DesktopName
- d.metadata.Type = pb.SessionRecordingType_SESSION_RECORDING_TYPE_WINDOWS_DESKTOP
+ if d.metadata.GetType() == pb.SessionRecordingType_SESSION_RECORDING_TYPE_UNSPECIFIED {
+ d.metadata.SetClusterName(evt.ClusterName)
+ d.metadata.SetUser(evt.User)
+ d.metadata.SetResourceName(evt.DesktopName)
+ d.metadata.SetType(pb.SessionRecordingType_SESSION_RECORDING_TYPE_WINDOWS_DESKTOP)
}
d.captureThumbnailIfNeeded(evt.GetTime(), d.thumbnailInterval)
@@ -99,9 +99,9 @@ func (d *desktopProcessor) collect() (*pb.SessionRecordingMetadata, *pb.SessionR
return nil, nil
}
- d.metadata.Duration = durationpb.New(d.lastEvent.GetTime().Sub(d.startTime))
- d.metadata.StartTime = timestamppb.New(d.startTime)
- d.metadata.EndTime = timestamppb.New(d.lastEvent.GetTime())
+ d.metadata.SetDuration(durationpb.New(d.lastEvent.GetTime().Sub(d.startTime)))
+ d.metadata.SetStartTime(timestamppb.New(d.startTime))
+ d.metadata.SetEndTime(timestamppb.New(d.lastEvent.GetTime()))
return d.metadata, d.thumbnail
}
diff --git a/lib/auth/recordingmetadata/recordingmetadatav1/desktopthumbnail.go b/lib/auth/recordingmetadata/recordingmetadatav1/desktopthumbnail.go
index 6a2d15e3997..0c093d8216a 100644
--- a/lib/auth/recordingmetadata/recordingmetadatav1/desktopthumbnail.go
+++ b/lib/auth/recordingmetadata/recordingmetadatav1/desktopthumbnail.go
@@ -138,14 +138,14 @@ func (d *desktopThumbnailGenerator) produceThumbnail(maxDim int) (*pb.SessionRec
return nil, trace.Wrap(err, "encoding thumbnail PNG")
}
- return &pb.SessionRecordingThumbnail{
+ return pb.SessionRecordingThumbnail_builder{
CursorX: int32(cursor.X),
CursorY: int32(cursor.Y),
CursorVisible: cursor.Visible,
ScreenWidth: int32(screenWidth),
ScreenHeight: int32(screenHeight),
Png: bytes.Clone(d.buf.Bytes()),
- }, nil
+ }.Build(), nil
}
func (d *desktopThumbnailGenerator) release() {
diff --git a/lib/auth/recordingmetadata/recordingmetadatav1/processor.go b/lib/auth/recordingmetadata/recordingmetadatav1/processor.go
index 9360da32e9c..61642cec39b 100644
--- a/lib/auth/recordingmetadata/recordingmetadatav1/processor.go
+++ b/lib/auth/recordingmetadata/recordingmetadatav1/processor.go
@@ -106,8 +106,8 @@ func (b *baseRecordingProcessor) captureThumbnailIfNeeded(eventTime time.Time, i
startOffset := durationpb.New(eventTime.Sub(b.startTime))
endOffset := durationpb.New(eventTime.Add(interval).Add(-1 * time.Millisecond).Sub(b.startTime))
- frame.StartOffset = startOffset
- frame.EndOffset = endOffset
+ frame.SetStartOffset(startOffset)
+ frame.SetEndOffset(endOffset)
if _, err := protodelim.MarshalTo(b.writer, frame); err != nil {
// log the error but continue processing other thumbnails and the session metadata (metadata is more important)
@@ -117,7 +117,7 @@ func (b *baseRecordingProcessor) captureThumbnailIfNeeded(eventTime time.Time, i
// Decide whether this frame should become the representative thumbnail. We only re-encode at
// the higher resolution when the frame is actually being kept, to avoid wasted work.
if b.thumbnail != nil {
- previousDiff := math.Abs(float64(b.thumbnailTime - b.thumbnail.StartOffset.AsDuration()))
+ previousDiff := math.Abs(float64(b.thumbnailTime - b.thumbnail.GetStartOffset().AsDuration()))
diff := math.Abs(float64(b.thumbnailTime - eventTime.Sub(b.startTime)))
if diff >= previousDiff {
return
@@ -133,8 +133,8 @@ func (b *baseRecordingProcessor) captureThumbnailIfNeeded(eventTime time.Time, i
if representative == nil {
return
}
- representative.StartOffset = startOffset
- representative.EndOffset = endOffset
+ representative.SetStartOffset(startOffset)
+ representative.SetEndOffset(endOffset)
b.thumbnail = representative
}
diff --git a/lib/auth/recordingmetadata/recordingmetadatav1/service.go b/lib/auth/recordingmetadata/recordingmetadatav1/service.go
index b014b68c167..01bd2710eed 100644
--- a/lib/auth/recordingmetadata/recordingmetadatav1/service.go
+++ b/lib/auth/recordingmetadata/recordingmetadatav1/service.go
@@ -97,11 +97,11 @@ func NewService(cfg ServiceConfig) (*Service, error) {
// GetThumbnail retrieves the thumbnail for a session recording.
func (r *Service) GetThumbnail(ctx context.Context, req *pb.GetThumbnailRequest) (*pb.GetThumbnailResponse, error) {
// Authorize will have checked the session end event to ensure the user has access to the session recording.
- if err := r.authorizer.Authorize(ctx, req.SessionId); err != nil {
+ if err := r.authorizer.Authorize(ctx, req.GetSessionId()); err != nil {
return nil, trace.Wrap(err)
}
- rc, err := r.downloadHandler.StreamSessionThumbnail(ctx, session.ID(req.SessionId))
+ rc, err := r.downloadHandler.StreamSessionThumbnail(ctx, session.ID(req.GetSessionId()))
if err != nil {
return nil, trace.Wrap(err)
}
@@ -118,18 +118,18 @@ func (r *Service) GetThumbnail(ctx context.Context, req *pb.GetThumbnailRequest)
return nil, trace.Wrap(err)
}
- return &pb.GetThumbnailResponse{Thumbnail: thumbnail}, nil
+ return pb.GetThumbnailResponse_builder{Thumbnail: thumbnail}.Build(), nil
}
// GetMetadata retrieves the metadata for a session recording, streaming it back in chunks (one for metadata and one
// for each frame).
func (r *Service) GetMetadata(req *pb.GetMetadataRequest, stream grpc.ServerStreamingServer[pb.GetMetadataResponseChunk]) error {
// Authorize will have checked the session end event to ensure the user has access to the session recording.
- if err := r.authorizer.Authorize(stream.Context(), req.SessionId); err != nil {
+ if err := r.authorizer.Authorize(stream.Context(), req.GetSessionId()); err != nil {
return trace.Wrap(err)
}
- rc, err := r.downloadHandler.StreamSessionMetadata(stream.Context(), session.ID(req.SessionId))
+ rc, err := r.downloadHandler.StreamSessionMetadata(stream.Context(), session.ID(req.GetSessionId()))
if err != nil {
return trace.Wrap(err)
}
@@ -148,7 +148,7 @@ func (r *Service) GetMetadata(req *pb.GetMetadataRequest, stream grpc.ServerStre
break
}
r.logger.ErrorContext(stream.Context(), "Failed to read delimited message",
- "session_id", req.SessionId, "error", err)
+ "session_id", req.GetSessionId(), "error", err)
return trace.Wrap(err)
}
@@ -164,7 +164,7 @@ func (r *Service) GetMetadata(req *pb.GetMetadataRequest, stream grpc.ServerStre
if err := stream.Send(metadataChunk); err != nil {
if !errors.Is(err, io.EOF) {
r.logger.ErrorContext(stream.Context(), "Failed to send session recording metadata",
- "session_id", req.SessionId, "error", err)
+ "session_id", req.GetSessionId(), "error", err)
}
return trace.Wrap(err)
}
@@ -184,7 +184,7 @@ func (r *Service) GetMetadata(req *pb.GetMetadataRequest, stream grpc.ServerStre
if err := stream.Send(frameChunk); err != nil {
if !errors.Is(err, io.EOF) {
r.logger.ErrorContext(stream.Context(), "Failed to send session recording thumbnail",
- "session_id", req.SessionId, "error", err)
+ "session_id", req.GetSessionId(), "error", err)
}
return trace.Wrap(err)
}
@@ -193,7 +193,7 @@ func (r *Service) GetMetadata(req *pb.GetMetadataRequest, stream grpc.ServerStre
}
r.logger.ErrorContext(stream.Context(), "Failed to parse message as metadata or thumbnail",
- "session_id", req.SessionId)
+ "session_id", req.GetSessionId())
return trace.Errorf("unable to parse message as metadata or thumbnail")
}
diff --git a/lib/auth/recordingmetadata/recordingmetadatav1/service_test.go b/lib/auth/recordingmetadata/recordingmetadatav1/service_test.go
index 4f0051cbc99..30e14c3b780 100644
--- a/lib/auth/recordingmetadata/recordingmetadatav1/service_test.go
+++ b/lib/auth/recordingmetadata/recordingmetadatav1/service_test.go
@@ -50,7 +50,7 @@ func TestService_GetThumbnail(t *testing.T) {
thumbnail := newThumbnail()
- thumbnail.Svg = []byte("")
+ thumbnail.SetSvg([]byte(""))
err := uploadThumbnail(ctx, uploader, session.ID("test-session"), thumbnail)
require.NoError(t, err, "failed to upload thumbnail")
@@ -60,13 +60,13 @@ func TestService_GetThumbnail(t *testing.T) {
downloadHandler: uploader,
}
- resp, err := service.GetThumbnail(ctx, &recordingmetadatav1pb.GetThumbnailRequest{
+ resp, err := service.GetThumbnail(ctx, recordingmetadatav1pb.GetThumbnailRequest_builder{
SessionId: "test-session",
- })
+ }.Build())
require.NoError(t, err, "failed to get thumbnail")
require.NotNil(t, resp, "expected non-nil response")
- require.Equal(t, thumbnail.Svg, resp.Thumbnail.Svg, "thumbnail SVG does not match expected value")
+ require.Equal(t, thumbnail.GetSvg(), resp.GetThumbnail().GetSvg(), "thumbnail SVG does not match expected value")
}
func TestService_GetThumbnailNotFound(t *testing.T) {
@@ -80,9 +80,9 @@ func TestService_GetThumbnailNotFound(t *testing.T) {
downloadHandler: uploader,
}
- _, err := service.GetThumbnail(ctx, &recordingmetadatav1pb.GetThumbnailRequest{
+ _, err := service.GetThumbnail(ctx, recordingmetadatav1pb.GetThumbnailRequest_builder{
SessionId: "test-session",
- })
+ }.Build())
require.Error(t, err, "expected error for test session")
require.True(t, trace.IsNotFound(err), "expected NotFound error, got %v", err)
}
@@ -145,9 +145,9 @@ func TestService_GetThumbnailAuthorized(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
- _, err := service.GetThumbnail(ctx, &recordingmetadatav1pb.GetThumbnailRequest{
+ _, err := service.GetThumbnail(ctx, recordingmetadatav1pb.GetThumbnailRequest_builder{
SessionId: tc.sessionID,
- })
+ }.Build())
if tc.wantError {
require.Error(t, err)
@@ -174,7 +174,7 @@ func TestService_GetMetadata(t *testing.T) {
newThumbnail(),
}
- metadata.ClusterName = "test-cluster"
+ metadata.SetClusterName("test-cluster")
err := uploadMetadata(ctx, uploader, session.ID("test-session"), metadata, frames)
require.NoError(t, err, "failed to upload metadata")
@@ -185,9 +185,9 @@ func TestService_GetMetadata(t *testing.T) {
}
stream := &fakeServerStream{ctx: ctx}
- err = service.GetMetadata(&recordingmetadatav1pb.GetMetadataRequest{
+ err = service.GetMetadata(recordingmetadatav1pb.GetMetadataRequest_builder{
SessionId: "test-session",
- }, stream)
+ }.Build(), stream)
require.NoError(t, err, "failed to get metadata")
require.NotNil(t, stream, "expected non-nil stream")
@@ -200,7 +200,7 @@ func TestService_GetMetadata(t *testing.T) {
require.NotNil(t, chunk, "expected non-nil chunk")
require.NotNil(t, chunk.GetMetadata(), "expected metadata in chunk")
- require.Equal(t, metadata.ClusterName, chunk.GetMetadata().ClusterName, "metadata cluster name does not match expected value")
+ require.Equal(t, metadata.GetClusterName(), chunk.GetMetadata().GetClusterName(), "metadata cluster name does not match expected value")
}
{
@@ -211,7 +211,7 @@ func TestService_GetMetadata(t *testing.T) {
require.NotNil(t, chunk, "expected non-nil chunk")
require.NotNil(t, chunk.GetFrame(), "expected frame in chunk")
- require.Equal(t, frames[0].Svg, chunk.GetFrame().Svg,
+ require.Equal(t, frames[0].GetSvg(), chunk.GetFrame().GetSvg(),
"first frame SVG does not match expected value")
}
@@ -223,7 +223,7 @@ func TestService_GetMetadata(t *testing.T) {
require.NotNil(t, chunk, "expected non-nil chunk")
require.NotNil(t, chunk.GetFrame(), "expected frame in chunk")
- require.Equal(t, frames[1].Svg, chunk.GetFrame().Svg,
+ require.Equal(t, frames[1].GetSvg(), chunk.GetFrame().GetSvg(),
"second frame SVG does not match expected value")
}
}
@@ -240,9 +240,9 @@ func TestService_GetMetadataNotFound(t *testing.T) {
}
stream := &fakeServerStream{ctx: ctx}
- err := service.GetMetadata(&recordingmetadatav1pb.GetMetadataRequest{
+ err := service.GetMetadata(recordingmetadatav1pb.GetMetadataRequest_builder{
SessionId: "test-session",
- }, stream)
+ }.Build(), stream)
require.Error(t, err, "expected error for test session")
require.True(t, trace.IsNotFound(err), "expected NotFound error, got %v", err)
@@ -306,9 +306,9 @@ func TestService_GetMetadataAuthorized(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
stream := &fakeServerStream{ctx: context.Background()}
- err := service.GetMetadata(&recordingmetadatav1pb.GetMetadataRequest{
+ err := service.GetMetadata(recordingmetadatav1pb.GetMetadataRequest_builder{
SessionId: tc.sessionID,
- }, stream)
+ }.Build(), stream)
if tc.wantError {
require.Error(t, err)
@@ -334,22 +334,22 @@ func TestService_AuthorizerError(t *testing.T) {
authorizer: authorizer,
}
- _, err := service.GetThumbnail(ctx, &recordingmetadatav1pb.GetThumbnailRequest{
+ _, err := service.GetThumbnail(ctx, recordingmetadatav1pb.GetThumbnailRequest_builder{
SessionId: "any-session",
- })
+ }.Build())
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
stream := &fakeServerStream{ctx: ctx}
- err = service.GetMetadata(&recordingmetadatav1pb.GetMetadataRequest{
+ err = service.GetMetadata(recordingmetadatav1pb.GetMetadataRequest_builder{
SessionId: "any-session",
- }, stream)
+ }.Build(), stream)
require.Error(t, err)
require.True(t, trace.IsAccessDenied(err))
}
func newThumbnail() *recordingmetadatav1pb.SessionRecordingThumbnail {
- return &recordingmetadatav1pb.SessionRecordingThumbnail{
+ return recordingmetadatav1pb.SessionRecordingThumbnail_builder{
Svg: []byte(""),
Cols: 80,
Rows: 24,
@@ -357,18 +357,18 @@ func newThumbnail() *recordingmetadatav1pb.SessionRecordingThumbnail {
CursorY: 0,
StartOffset: durationpb.New(0),
EndOffset: durationpb.New(60),
- }
+ }.Build()
}
func newMetadata() *recordingmetadatav1pb.SessionRecordingMetadata {
- return &recordingmetadatav1pb.SessionRecordingMetadata{
+ return recordingmetadatav1pb.SessionRecordingMetadata_builder{
Duration: durationpb.New(60),
StartCols: 80,
StartRows: 24,
StartTime: timestamppb.New(time.Now().Add(-time.Minute)),
EndTime: timestamppb.New(time.Now()),
ClusterName: "test-cluster",
- }
+ }.Build()
}
func uploadThumbnail(ctx context.Context, uploader events.UploadHandler, sessionID session.ID, thumbnail *recordingmetadatav1pb.SessionRecordingThumbnail) error {
diff --git a/lib/auth/recordingmetadata/recordingmetadatav1/ttyprocessor.go b/lib/auth/recordingmetadata/recordingmetadatav1/ttyprocessor.go
index ab6f95f5791..b604a09120d 100644
--- a/lib/auth/recordingmetadata/recordingmetadatav1/ttyprocessor.go
+++ b/lib/auth/recordingmetadata/recordingmetadatav1/ttyprocessor.go
@@ -86,20 +86,20 @@ func (t *ttyRecordingProcessor) handleSessionStart(evt *apievents.SessionStart)
}
// store the initial terminal size, this is typically 80:24 and is resized immediately
- t.metadata.StartCols = int32(size.W)
- t.metadata.StartRows = int32(size.H)
+ t.metadata.SetStartCols(int32(size.W))
+ t.metadata.SetStartRows(int32(size.H))
- t.metadata.ClusterName = evt.ClusterName
- t.metadata.User = evt.User
+ t.metadata.SetClusterName(evt.ClusterName)
+ t.metadata.SetUser(evt.User)
switch evt.Protocol {
case events.EventProtocolSSH:
- t.metadata.ResourceName = evt.ServerHostname
- t.metadata.Type = pb.SessionRecordingType_SESSION_RECORDING_TYPE_SSH
+ t.metadata.SetResourceName(evt.ServerHostname)
+ t.metadata.SetType(pb.SessionRecordingType_SESSION_RECORDING_TYPE_SSH)
case events.EventProtocolKube:
- t.metadata.ResourceName = evt.KubernetesCluster
- t.metadata.Type = pb.SessionRecordingType_SESSION_RECORDING_TYPE_KUBERNETES
+ t.metadata.SetResourceName(evt.KubernetesCluster)
+ t.metadata.SetType(pb.SessionRecordingType_SESSION_RECORDING_TYPE_KUBERNETES)
}
return t.thumbnailGenerator.handleEvent(evt)
@@ -115,19 +115,17 @@ func (t *ttyRecordingProcessor) handleResize(evt *apievents.Resize) error {
// this handles cases where the initial terminal size is not 80x24 and is resized immediately
// before any output is printed
if !t.hasSeenPrintEvent {
- t.metadata.StartCols = int32(size.W)
- t.metadata.StartRows = int32(size.H)
+ t.metadata.SetStartCols(int32(size.W))
+ t.metadata.SetStartRows(int32(size.H))
}
- t.metadata.Events = append(t.metadata.Events, &pb.SessionRecordingEvent{
+ t.metadata.SetEvents(append(t.metadata.GetEvents(), pb.SessionRecordingEvent_builder{
StartOffset: durationpb.New(evt.Time.Sub(t.startTime)),
- Event: &pb.SessionRecordingEvent_Resize{
- Resize: &pb.SessionRecordingResizeEvent{
- Cols: int32(size.W),
- Rows: int32(size.H),
- },
- },
- })
+ Resize: pb.SessionRecordingResizeEvent_builder{
+ Cols: int32(size.W),
+ Rows: int32(size.H),
+ }.Build(),
+ }.Build()))
return t.thumbnailGenerator.handleEvent(evt)
}
@@ -161,15 +159,13 @@ func (t *ttyRecordingProcessor) handleSessionJoin(evt *apievents.SessionJoin) er
func (t *ttyRecordingProcessor) handleSessionLeave(evt *apievents.SessionLeave) error {
if joinTime, ok := t.activeUsers[evt.User]; ok {
- t.metadata.Events = append(t.metadata.Events, &pb.SessionRecordingEvent{
+ t.metadata.SetEvents(append(t.metadata.GetEvents(), pb.SessionRecordingEvent_builder{
StartOffset: durationpb.New(joinTime),
EndOffset: durationpb.New(evt.Time.Sub(t.startTime)),
- Event: &pb.SessionRecordingEvent_Join{
- Join: &pb.SessionRecordingJoinEvent{
- User: evt.User,
- },
- },
- })
+ Join: pb.SessionRecordingJoinEvent_builder{
+ User: evt.User,
+ }.Build(),
+ }.Build()))
delete(t.activeUsers, evt.User)
}
@@ -191,13 +187,11 @@ func (t *ttyRecordingProcessor) addInactivityEvent(start, end time.Time) {
inactivityStart := durationpb.New(start.Sub(t.startTime))
inactivityEnd := durationpb.New(end.Sub(t.startTime))
- t.metadata.Events = append(t.metadata.Events, &pb.SessionRecordingEvent{
+ t.metadata.SetEvents(append(t.metadata.GetEvents(), pb.SessionRecordingEvent_builder{
StartOffset: inactivityStart,
EndOffset: inactivityEnd,
- Event: &pb.SessionRecordingEvent_Inactivity{
- Inactivity: &pb.SessionRecordingInactivityEvent{},
- },
- })
+ Inactivity: &pb.SessionRecordingInactivityEvent{},
+ }.Build()))
}
func (t *ttyRecordingProcessor) collect() (*pb.SessionRecordingMetadata, *pb.SessionRecordingThumbnail) {
@@ -207,20 +201,18 @@ func (t *ttyRecordingProcessor) collect() (*pb.SessionRecordingMetadata, *pb.Ses
// Finish off any remaining activity events
for user, userStartOffset := range t.activeUsers {
- t.metadata.Events = append(t.metadata.Events, &pb.SessionRecordingEvent{
+ t.metadata.SetEvents(append(t.metadata.GetEvents(), pb.SessionRecordingEvent_builder{
StartOffset: durationpb.New(userStartOffset),
EndOffset: durationpb.New(t.lastEvent.GetTime().Sub(t.startTime)),
- Event: &pb.SessionRecordingEvent_Join{
- Join: &pb.SessionRecordingJoinEvent{
- User: user,
- },
- },
- })
+ Join: pb.SessionRecordingJoinEvent_builder{
+ User: user,
+ }.Build(),
+ }.Build()))
}
- t.metadata.Duration = durationpb.New(t.lastEvent.GetTime().Sub(t.startTime))
- t.metadata.StartTime = timestamppb.New(t.startTime)
- t.metadata.EndTime = timestamppb.New(t.lastEvent.GetTime())
+ t.metadata.SetDuration(durationpb.New(t.lastEvent.GetTime().Sub(t.startTime)))
+ t.metadata.SetStartTime(timestamppb.New(t.startTime))
+ t.metadata.SetEndTime(timestamppb.New(t.lastEvent.GetTime()))
return t.metadata, t.thumbnail
}
diff --git a/lib/auth/recordingmetadata/recordingmetadatav1/ttyprocessor_test.go b/lib/auth/recordingmetadata/recordingmetadatav1/ttyprocessor_test.go
index 7c93ae4acc5..1f084cdf29c 100644
--- a/lib/auth/recordingmetadata/recordingmetadatav1/ttyprocessor_test.go
+++ b/lib/auth/recordingmetadata/recordingmetadatav1/ttyprocessor_test.go
@@ -49,13 +49,13 @@ func TestTTYRecordingProcessor(t *testing.T) {
events: generateBasicSession(startTime),
expectedMetadata: func(t *testing.T, metadata *pb.SessionRecordingMetadata) {
require.NotNil(t, metadata)
- require.NotNil(t, metadata.Duration)
- require.Equal(t, int32(80), metadata.StartCols)
- require.Equal(t, int32(24), metadata.StartRows)
+ require.NotNil(t, metadata.GetDuration())
+ require.Equal(t, int32(80), metadata.GetStartCols())
+ require.Equal(t, int32(24), metadata.GetStartRows())
},
expectedThumbnail: func(t *testing.T, thumbnail *pb.SessionRecordingThumbnail) {
require.NotNil(t, thumbnail)
- require.NotEmpty(t, thumbnail.Svg)
+ require.NotEmpty(t, thumbnail.GetSvg())
},
},
{
@@ -63,13 +63,13 @@ func TestTTYRecordingProcessor(t *testing.T) {
events: generateBasicSessionWithImmediateResize(startTime),
expectedMetadata: func(t *testing.T, metadata *pb.SessionRecordingMetadata) {
require.NotNil(t, metadata)
- require.NotNil(t, metadata.Duration)
- require.Equal(t, int32(100), metadata.StartCols)
- require.Equal(t, int32(30), metadata.StartRows)
+ require.NotNil(t, metadata.GetDuration())
+ require.Equal(t, int32(100), metadata.GetStartCols())
+ require.Equal(t, int32(30), metadata.GetStartRows())
},
expectedThumbnail: func(t *testing.T, thumbnail *pb.SessionRecordingThumbnail) {
require.NotNil(t, thumbnail)
- require.NotEmpty(t, thumbnail.Svg)
+ require.NotEmpty(t, thumbnail.GetSvg())
},
},
{
@@ -79,11 +79,11 @@ func TestTTYRecordingProcessor(t *testing.T) {
require.NotNil(t, metadata)
var hasResize bool
- for _, event := range metadata.Events {
+ for _, event := range metadata.GetEvents() {
if resize := event.GetResize(); resize != nil {
hasResize = true
- require.Equal(t, int32(120), resize.Cols)
- require.Equal(t, int32(40), resize.Rows)
+ require.Equal(t, int32(120), resize.GetCols())
+ require.Equal(t, int32(40), resize.GetRows())
}
}
require.True(t, hasResize, "expected resize event")
@@ -96,12 +96,12 @@ func TestTTYRecordingProcessor(t *testing.T) {
require.NotNil(t, metadata)
var inactivityCount int
- for _, event := range metadata.Events {
+ for _, event := range metadata.GetEvents() {
if event.GetInactivity() != nil {
inactivityCount++
- require.Equal(t, 1*time.Second, event.StartOffset.AsDuration(), "inactivity should start at last activity time")
- require.Equal(t, 21*time.Second, event.EndOffset.AsDuration(), "inactivity should end when activity resumes")
+ require.Equal(t, 1*time.Second, event.GetStartOffset().AsDuration(), "inactivity should start at last activity time")
+ require.Equal(t, 21*time.Second, event.GetEndOffset().AsDuration(), "inactivity should end when activity resumes")
}
}
require.Equal(t, 1, inactivityCount, "expected exactly one inactivity event")
@@ -114,19 +114,19 @@ func TestTTYRecordingProcessor(t *testing.T) {
require.NotNil(t, metadata)
joins := make(map[string]*pb.SessionRecordingEvent)
- for _, event := range metadata.Events {
+ for _, event := range metadata.GetEvents() {
if join := event.GetJoin(); join != nil {
- joins[join.User] = event
+ joins[join.GetUser()] = event
}
}
require.Len(t, joins, 2, "expected join events for alice and bob")
- require.Equal(t, 2*time.Second, joins["alice"].StartOffset.AsDuration())
- require.Equal(t, 6*time.Second, joins["alice"].EndOffset.AsDuration())
+ require.Equal(t, 2*time.Second, joins["alice"].GetStartOffset().AsDuration())
+ require.Equal(t, 6*time.Second, joins["alice"].GetEndOffset().AsDuration())
- require.Equal(t, 4*time.Second, joins["bob"].StartOffset.AsDuration())
- require.Equal(t, 10*time.Second, joins["bob"].EndOffset.AsDuration())
+ require.Equal(t, 4*time.Second, joins["bob"].GetStartOffset().AsDuration())
+ require.Equal(t, 10*time.Second, joins["bob"].GetEndOffset().AsDuration())
},
},
}
diff --git a/lib/auth/recordingmetadata/recordingmetadatav1/ttythumbnail.go b/lib/auth/recordingmetadata/recordingmetadatav1/ttythumbnail.go
index 6d232ab890c..d1bc24f2aab 100644
--- a/lib/auth/recordingmetadata/recordingmetadatav1/ttythumbnail.go
+++ b/lib/auth/recordingmetadata/recordingmetadatav1/ttythumbnail.go
@@ -88,14 +88,14 @@ func (t *ttyThumbnailGenerator) produceThumbnail(_ int) (*pb.SessionRecordingThu
cols, rows := t.vt.Size()
cursor := t.vt.Cursor()
- return &pb.SessionRecordingThumbnail{
+ return pb.SessionRecordingThumbnail_builder{
Svg: terminal.VtToSvg(t.vt),
Cols: int32(cols),
Rows: int32(rows),
CursorX: int32(cursor.X),
CursorY: int32(cursor.Y),
CursorVisible: t.vt.CursorVisible(),
- }, nil
+ }.Build(), nil
}
func (t *ttyThumbnailGenerator) release() {
diff --git a/lib/auth/recordingmetadata/recordingmetadatav1/ttythumbnail_test.go b/lib/auth/recordingmetadata/recordingmetadatav1/ttythumbnail_test.go
index 756f67c4ab0..11e04c128c4 100644
--- a/lib/auth/recordingmetadata/recordingmetadatav1/ttythumbnail_test.go
+++ b/lib/auth/recordingmetadata/recordingmetadatav1/ttythumbnail_test.go
@@ -38,8 +38,8 @@ func TestTtyThumbnailGenerator_HandleEvent(t *testing.T) {
thumb, err := gen.produceThumbnail(thumbnailMaxDimensions)
require.NoError(t, err)
- require.Equal(t, int32(100), thumb.Cols)
- require.Equal(t, int32(50), thumb.Rows)
+ require.Equal(t, int32(100), thumb.GetCols())
+ require.Equal(t, int32(50), thumb.GetRows())
})
t.Run("resize updates terminal size", func(t *testing.T) {
@@ -51,8 +51,8 @@ func TestTtyThumbnailGenerator_HandleEvent(t *testing.T) {
thumb, err := gen.produceThumbnail(thumbnailMaxDimensions)
require.NoError(t, err)
- require.Equal(t, int32(120), thumb.Cols)
- require.Equal(t, int32(40), thumb.Rows)
+ require.Equal(t, int32(120), thumb.GetCols())
+ require.Equal(t, int32(40), thumb.GetRows())
})
t.Run("session print writes data to terminal", func(t *testing.T) {
@@ -64,9 +64,9 @@ func TestTtyThumbnailGenerator_HandleEvent(t *testing.T) {
thumb, err := gen.produceThumbnail(thumbnailMaxDimensions)
require.NoError(t, err)
- require.NotEmpty(t, thumb.Svg)
- require.Contains(t, string(thumb.Svg), "Hello")
- require.Contains(t, string(thumb.Svg), "World")
+ require.NotEmpty(t, thumb.GetSvg())
+ require.Contains(t, string(thumb.GetSvg()), "Hello")
+ require.Contains(t, string(thumb.GetSvg()), "World")
})
t.Run("unhandled event types are ignored", func(t *testing.T) {
@@ -110,11 +110,11 @@ func TestTtyThumbnailGenerator_ProduceThumbnail(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, thumb)
- require.Equal(t, int32(80), thumb.Cols)
- require.Equal(t, int32(24), thumb.Rows)
- require.NotEmpty(t, thumb.Svg)
- require.Contains(t, string(thumb.Svg), "