Initial migration to the Opaque API (#67279)

* Convert existing non-gogo codegen to the Hybrid API

Contributes to https://github.com/gravitational/teleport/issues/66776.

All existing protos explicitly set to API_OPEN have been change to
API_HBYRID. The new codegen was performed via make grpc. There are no
other functional changes to the code to start consuming the Hybrid API
those will come later. The intent is to get all Hybrid codegen in and
backported to ease the transition.

* Initial migration to the Opaque API

Contributes to https://github.com/gravitational/teleport/issues/66776.

All of the changes here are mechanical conversions generated from
`open2opaque rewrite -levels=green ./...`. There will be a follow up
to this in teleport.e which does the same. Once all changes have been
merged the process will be repeated with -levels=yellow followed by
-levels=red.


See https://protobuf.dev/reference/go/opaque-migration/ for more
details.
This commit is contained in:
rosstimothy
2026-06-05 14:52:58 +00:00
committed by GitHub
parent cc89378c3d
commit 4f17314a11
900 changed files with 21163 additions and 21591 deletions
@@ -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)
+1 -1
View File
@@ -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)
+5 -5
View File
@@ -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
}
}
+4 -4
View File
@@ -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) {
+16 -16
View File
@@ -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()
+35 -37
View File
@@ -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)
})
}
}
@@ -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
})
}
@@ -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,
+24 -24
View File
@@ -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
+8 -8
View File
@@ -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
+24 -24
View File
@@ -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
@@ -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
+8 -8
View File
@@ -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
@@ -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
@@ -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.
+24 -24
View File
@@ -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{}
+43 -43
View File
@@ -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)
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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)
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
@@ -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))
}
@@ -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))
}
@@ -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))
}
@@ -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)
}
@@ -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
}),
)...,
)
@@ -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)
}
@@ -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)
}
@@ -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
}
@@ -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)
}
@@ -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)
}
@@ -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))
}
@@ -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)
}
@@ -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))
}
@@ -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))
}
@@ -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))
}
@@ -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)
}
@@ -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
@@ -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)
}
@@ -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))
}
@@ -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)
}
@@ -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))
}
@@ -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()
}
+10 -10
View File
@@ -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,
+9 -9
View File
@@ -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.
+2 -2
View File
@@ -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)
+22 -22
View File
@@ -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)
+5 -5
View File
@@ -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) {
+52 -52
View File
@@ -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,
+11 -11
View File
@@ -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())
}
@@ -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
}
@@ -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,
@@ -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,
@@ -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.
@@ -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(),
)
}
@@ -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")
}
@@ -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())
})
+66 -72
View File
@@ -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, &notificationsv1.GlobalNotification{
Spec: &notificationsv1.GlobalNotificationSpec{
Matcher: &notificationsv1.GlobalNotificationSpec_ByPermissions{
ByPermissions: &notificationsv1.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: &notificationsv1.Notification{
Notification: notificationsv1.Notification_builder{
Spec: &notificationsv1.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 &notificationsv1.Notification{
Spec: &notificationsv1.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, &notificationsv1.GlobalNotification{
Spec: &notificationsv1.GlobalNotificationSpec{
Matcher: &notificationsv1.GlobalNotificationSpec_ByUsers{
ByUsers: &notificationsv1.ByUsers{
Users: owners,
},
},
Notification: &notificationsv1.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: &notificationsv1.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, &notificationsv1.GlobalNotification{
Spec: &notificationsv1.GlobalNotificationSpec{
Matcher: &notificationsv1.GlobalNotificationSpec_ByPermissions{
ByPermissions: &notificationsv1.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: &notificationsv1.Notification{
Notification: notificationsv1.Notification_builder{
Spec: &notificationsv1.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
}
+46 -46
View File
@@ -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)
+159 -159
View File
@@ -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, &notificationsv1.UserNotificationState{
Spec: &notificationsv1.UserNotificationStateSpec{
_, err := srv.Auth().UpsertUserNotificationState(ctx, notif.username, notificationsv1.UserNotificationState_builder{
Spec: notificationsv1.UserNotificationStateSpec_builder{
Username: notif.username,
NotificationId: notif.id,
},
Status: &notificationsv1.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, &notificationsv1.UserNotificationState{
Spec: &notificationsv1.UserNotificationStateSpec{
_, err := srv.Auth().UpsertUserNotificationState(ctx, username, notificationsv1.UserNotificationState_builder{
Spec: notificationsv1.UserNotificationStateSpec_builder{
Username: username,
NotificationId: notif.id,
},
Status: &notificationsv1.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, &notificationsv1.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, &notificationsv1.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: &notificationsv1.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 &notification
@@ -5479,21 +5481,19 @@ func newGlobalNotificationWithExpiry(t *testing.T, title string, expires *timest
t.Helper()
notification := notificationsv1.GlobalNotification{
Spec: &notificationsv1.GlobalNotificationSpec{
Matcher: &notificationsv1.GlobalNotificationSpec_All{
All: true,
},
Notification: &notificationsv1.Notification{
Spec: notificationsv1.GlobalNotificationSpec_builder{
All: proto.Bool(true),
Notification: notificationsv1.Notification_builder{
SubKind: "test-subkind",
Spec: &notificationsv1.NotificationSpec{},
Metadata: &headerv1.Metadata{
Metadata: headerv1.Metadata_builder{
Expires: expires,
Labels: map[string]string{
types.NotificationTitleLabel: title,
},
},
},
},
}.Build(),
}.Build(),
}.Build(),
}
return &notification
+25 -25
View File
@@ -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)
}
+164 -164
View File
@@ -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)
+12 -12
View File
@@ -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, &notificationsv1.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, &notificationsv1.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, &notificationsv1.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, &notificationsv1.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, &notificationsv1.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, &notificationsv1.DeleteUserNotificationRequest{
err := c.APIClient.DeleteUserNotification(ctx, notificationsv1.DeleteUserNotificationRequest_builder{
Username: username,
NotificationId: notificationId,
})
}.Build())
return trace.Wrap(err)
}
+8 -8
View File
@@ -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
}
+30 -30
View File
@@ -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.
+127 -127
View File
@@ -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.
+12 -12
View File
@@ -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)
@@ -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)
+7 -7
View File
@@ -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
}
+13 -13
View File
@@ -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())
}
},
},
+35 -35
View File
@@ -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 {
+145 -145
View File
@@ -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)
@@ -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)
}
@@ -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)
+9 -9
View File
@@ -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)
+15 -15
View File
@@ -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")
}
}
+74 -74
View File
@@ -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,
},
}
+18 -18
View File
@@ -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")
+10 -10
View File
@@ -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)
}
@@ -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)
}
@@ -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()
@@ -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()
}
@@ -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) {
@@ -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)
})
})
@@ -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
+4 -4
View File
@@ -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(),
})
})
}
@@ -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 {
@@ -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)
@@ -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)
}
@@ -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{

Some files were not shown because too many files have changed in this diff Show More