Skip to content

Commit 24fa4c1

Browse files
committed
temp
1 parent 8a0b57f commit 24fa4c1

File tree

3 files changed

+247
-60
lines changed

3 files changed

+247
-60
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/*
2+
* Teleport
3+
* Copyright (C) 2023 Gravitational, Inc.
4+
*
5+
* This program is free software: you can redistribute it and/or modify
6+
* it under the terms of the GNU Affero General Public License as published by
7+
* the Free Software Foundation, either version 3 of the License, or
8+
* (at your option) any later version.
9+
*
10+
* This program is distributed in the hope that it will be useful,
11+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13+
* GNU Affero General Public License for more details.
14+
*
15+
* You should have received a copy of the GNU Affero General Public License
16+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
17+
*/
18+
19+
package resources
20+
21+
import (
22+
"context"
23+
"net"
24+
"testing"
25+
"time"
26+
27+
"github.com/stretchr/testify/assert"
28+
"github.com/stretchr/testify/require"
29+
30+
"github.com/gravitational/teleport/api/types"
31+
"github.com/gravitational/teleport/integration/helpers"
32+
"github.com/gravitational/teleport/lib/auth"
33+
"github.com/gravitational/teleport/lib/defaults"
34+
"github.com/gravitational/teleport/lib/modules"
35+
"github.com/gravitational/teleport/lib/service/servicecfg"
36+
"github.com/gravitational/teleport/lib/services"
37+
"github.com/gravitational/teleport/lib/srv/db/common"
38+
"github.com/gravitational/teleport/lib/srv/db/postgres"
39+
)
40+
41+
func startPostgresTestServer(t *testing.T, authServer *auth.Server) *postgres.TestServer {
42+
postgresTestServer, err := postgres.NewTestServer(common.TestServerConfig{
43+
AuthClient: authServer,
44+
})
45+
require.NoError(t, err)
46+
47+
go func() {
48+
t.Logf("Postgres Fake server running at %s port", postgresTestServer.Port())
49+
assert.NoError(t, postgresTestServer.Serve())
50+
}()
51+
t.Cleanup(func() {
52+
postgresTestServer.Close()
53+
})
54+
55+
return postgresTestServer
56+
}
57+
58+
func TestDiagnoseConnectionForPostgresDatabases(t *testing.T) {
59+
modules.SetInsecureTestMode(true)
60+
61+
ctx := context.Background()
62+
63+
// Start Teleport Auth and Proxy services
64+
authProcess, proxyProcess, provisionToken := helpers.MakeTestServers(t)
65+
authServer := authProcess.GetAuthServer()
66+
proxyAddr, err := proxyProcess.ProxyWebAddr()
67+
require.NoError(t, err)
68+
69+
// Start Fake Postgres Database
70+
postgresTestServer := startPostgresTestServer(t, authServer)
71+
72+
// Start Teleport Database Service
73+
databaseResourceName := "mypsqldb"
74+
databaseDBName := "dbname"
75+
databaseDBUser := "dbuser"
76+
helpers.MakeTestDatabaseServer(t, *proxyAddr, provisionToken, nil /* resource matchers */, servicecfg.Database{
77+
Name: databaseResourceName,
78+
Protocol: defaults.ProtocolPostgres,
79+
URI: net.JoinHostPort("localhost", postgresTestServer.Port()),
80+
})
81+
// Wait for the Database Server to be registered
82+
waitForDatabases(t, func(ctx context.Context, name string) ([]types.DatabaseServer, error) {
83+
return authServer.GetDatabaseServers(ctx, name)
84+
}, databaseResourceName)
85+
86+
roleWithFullAccess, err := types.NewRole("fullaccess", types.RoleSpecV6{
87+
Allow: types.RoleConditions{
88+
Namespaces: []string{"default"},
89+
DatabaseLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
90+
Rules: []types.Rule{
91+
types.NewRule(types.KindConnectionDiagnostic, services.RW()),
92+
},
93+
DatabaseUsers: []string{databaseDBUser},
94+
DatabaseNames: []string{databaseDBName},
95+
},
96+
})
97+
require.NoError(t, err)
98+
roleWithFullAccess, err = authServer.UpsertRole(ctx, roleWithFullAccess)
99+
require.NoError(t, err)
100+
}
101+
102+
func waitForDatabases(t *testing.T, GetDatabaseServers func(ctx context.Context, name string) ([]types.DatabaseServer, error), dbNames ...string) {
103+
ctx := context.Background()
104+
105+
require.Eventually(t, func() bool {
106+
all, err := GetDatabaseServers(ctx, "default")
107+
assert.NoError(t, err)
108+
109+
if len(dbNames) > len(all) {
110+
return false
111+
}
112+
113+
registered := 0
114+
for _, db := range dbNames {
115+
for _, a := range all {
116+
if a.GetName() == db {
117+
registered++
118+
break
119+
}
120+
}
121+
}
122+
return registered == len(dbNames)
123+
}, 30*time.Second, 100*time.Millisecond)
124+
}

integrations/operator/controllers/resources/testlib/env.go

+123-58
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,6 @@ import (
2929
"testing"
3030
"time"
3131

32-
"github.com/google/uuid"
33-
"github.com/sirupsen/logrus"
3432
"github.com/stretchr/testify/assert"
3533
"github.com/stretchr/testify/require"
3634
"go.uber.org/zap/zapcore"
@@ -50,17 +48,18 @@ import (
5048

5149
"github.com/gravitational/teleport/api/client"
5250
"github.com/gravitational/teleport/api/types"
53-
"github.com/gravitational/teleport/entitlements"
5451
"github.com/gravitational/teleport/integration/helpers"
5552
resourcesv1 "github.com/gravitational/teleport/integrations/operator/apis/resources/v1"
5653
resourcesv2 "github.com/gravitational/teleport/integrations/operator/apis/resources/v2"
5754
resourcesv3 "github.com/gravitational/teleport/integrations/operator/apis/resources/v3"
5855
resourcesv5 "github.com/gravitational/teleport/integrations/operator/apis/resources/v5"
5956
"github.com/gravitational/teleport/integrations/operator/controllers"
6057
"github.com/gravitational/teleport/integrations/operator/controllers/resources"
58+
"github.com/gravitational/teleport/lib/auth"
6159
"github.com/gravitational/teleport/lib/defaults"
6260
"github.com/gravitational/teleport/lib/modules"
6361
"github.com/gravitational/teleport/lib/service/servicecfg"
62+
"github.com/gravitational/teleport/lib/services"
6463
"github.com/gravitational/teleport/lib/srv/db/common"
6564
"github.com/gravitational/teleport/lib/srv/db/postgres"
6665
"github.com/gravitational/teleport/lib/utils"
@@ -103,73 +102,138 @@ func ValidRandomResourceName(prefix string) string {
103102
return prefix + string(b)
104103
}
105104

106-
func defaultTeleportServiceConfig(t *testing.T) (*helpers.TeleInstance, string) {
107-
modules.SetTestModules(t, &modules.TestModules{
108-
TestBuildType: modules.BuildEnterprise,
109-
TestFeatures: modules.Features{
110-
Entitlements: map[entitlements.EntitlementKind]modules.EntitlementInfo{
111-
entitlements.OIDC: {Enabled: true},
112-
entitlements.SAML: {Enabled: true},
113-
},
114-
},
105+
func startPostgresTestServer(t *testing.T, authServer *auth.Server) *postgres.TestServer {
106+
postgresTestServer, err := postgres.NewTestServer(common.TestServerConfig{
107+
AuthClient: authServer,
115108
})
109+
require.NoError(t, err)
116110

117-
teleportServer := helpers.NewInstance(t, helpers.InstanceConfig{
118-
ClusterName: "root.example.com",
119-
HostID: uuid.New().String(),
120-
NodeName: helpers.Loopback,
121-
Log: logrus.StandardLogger(),
111+
go func() {
112+
t.Logf("Postgres Fake server running at %s port", postgresTestServer.Port())
113+
assert.NoError(t, postgresTestServer.Serve())
114+
}()
115+
t.Cleanup(func() {
116+
postgresTestServer.Close()
122117
})
123118

124-
rcConf := servicecfg.MakeDefaultConfig()
125-
rcConf.DataDir = t.TempDir()
126-
rcConf.Auth.Enabled = true
127-
rcConf.Proxy.Enabled = true
128-
rcConf.Proxy.DisableWebInterface = true
129-
rcConf.SSH.Enabled = true
130-
rcConf.Version = "v2"
131-
132-
rcConf.Auth.StaticTokens, _ = types.NewStaticTokens(types.StaticTokensSpecV2{
133-
StaticTokens: []types.ProvisionTokenV1{{
134-
Roles: []types.SystemRole{types.RoleDatabase},
135-
Expires: time.Now().Add(time.Hour),
136-
Token: "token",
137-
}},
119+
return postgresTestServer
120+
}
121+
func doCopyPastedTest(t *testing.T) {
122+
modules.SetInsecureTestMode(true)
123+
124+
ctx := context.Background()
125+
126+
// Start Teleport Auth and Proxy services
127+
authProcess, proxyProcess, provisionToken := helpers.MakeTestServers(t)
128+
authServer := authProcess.GetAuthServer()
129+
proxyAddr, err := proxyProcess.ProxyWebAddr()
130+
require.NoError(t, err)
131+
132+
// Start Fake Postgres Database
133+
postgresTestServer := startPostgresTestServer(t, authServer)
134+
135+
// Start Teleport Database Service
136+
databaseResourceName := "mypsqldb"
137+
databaseDBName := "dbname"
138+
databaseDBUser := "dbuser"
139+
helpers.MakeTestDatabaseServer(t, *proxyAddr, provisionToken, nil /* resource matchers */, servicecfg.Database{
140+
Name: databaseResourceName,
141+
Protocol: defaults.ProtocolPostgres,
142+
URI: net.JoinHostPort("localhost", postgresTestServer.Port()),
138143
})
144+
// Wait for the Database Server to be registered
145+
waitForDatabases(t, func(ctx context.Context, name string) ([]types.DatabaseServer, error) {
146+
return authServer.GetDatabaseServers(ctx, name)
147+
}, databaseResourceName)
139148

140-
roleName := ValidRandomResourceName("role-")
141-
unrestricted := []string{"list", "create", "read", "update", "delete"}
142-
role, err := types.NewRole(roleName, types.RoleSpecV6{
149+
roleWithFullAccess, err := types.NewRole("fullaccess", types.RoleSpecV6{
143150
Allow: types.RoleConditions{
144-
// the operator has wildcard node labs to be able to see them
145-
// but has no login allowed, so it cannot SSH into them
146-
NodeLabels: types.Labels{"*": []string{"*"}},
151+
Namespaces: []string{"default"},
152+
DatabaseLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
147153
Rules: []types.Rule{
148-
types.NewRule(types.KindRole, unrestricted),
149-
types.NewRule(types.KindUser, unrestricted),
150-
types.NewRule(types.KindAuthConnector, unrestricted),
151-
types.NewRule(types.KindLoginRule, unrestricted),
152-
types.NewRule(types.KindToken, unrestricted),
153-
types.NewRule(types.KindOktaImportRule, unrestricted),
154-
types.NewRule(types.KindAccessList, unrestricted),
155-
types.NewRule(types.KindNode, unrestricted),
156-
types.NewRule(types.KindDatabase, unrestricted),
157-
},
158-
Impersonate: &types.ImpersonateConditions{
159-
Users: []string{"Db"},
160-
Roles: []string{"Db"},
154+
types.NewRule(types.KindConnectionDiagnostic, services.RW()),
161155
},
156+
DatabaseUsers: []string{databaseDBUser},
157+
DatabaseNames: []string{databaseDBName},
162158
},
163159
})
164160
require.NoError(t, err)
161+
roleWithFullAccess, err = authServer.UpsertRole(ctx, roleWithFullAccess)
162+
require.NoError(t, err)
163+
}
164+
165+
func defaultTeleportServiceConfig(t *testing.T) (*helpers.TeleInstance, string) {
166+
// modules.SetTestModules(t, &modules.TestModules{
167+
// TestBuildType: modules.BuildEnterprise,
168+
// TestFeatures: modules.Features{
169+
// Entitlements: map[entitlements.EntitlementKind]modules.EntitlementInfo{
170+
// entitlements.OIDC: {Enabled: true},
171+
// entitlements.SAML: {Enabled: true},
172+
// },
173+
// },
174+
// })
175+
176+
// teleportServer := helpers.NewInstance(t, helpers.InstanceConfig{
177+
// ClusterName: "root.example.com",
178+
// HostID: uuid.New().String(),
179+
// NodeName: helpers.Loopback,
180+
// Log: logrus.StandardLogger(),
181+
// })
182+
183+
// rcConf := servicecfg.MakeDefaultConfig()
184+
// rcConf.DataDir = t.TempDir()
185+
// rcConf.Auth.Enabled = true
186+
// rcConf.Proxy.Enabled = true
187+
// rcConf.Proxy.DisableWebInterface = true
188+
// rcConf.SSH.Enabled = true
189+
// rcConf.Version = "v2"
190+
191+
// rcConf.Auth.StaticTokens, _ = types.NewStaticTokens(types.StaticTokensSpecV2{
192+
// StaticTokens: []types.ProvisionTokenV1{{
193+
// Roles: []types.SystemRole{types.RoleDatabase},
194+
// Expires: time.Now().Add(time.Hour),
195+
// Token: "token",
196+
// }},
197+
// })
198+
199+
// roleName := ValidRandomResourceName("role-")
200+
// unrestricted := []string{"list", "create", "read", "update", "delete"}
201+
// role, err := types.NewRole(roleName, types.RoleSpecV6{
202+
// Allow: types.RoleConditions{
203+
// // the operator has wildcard node labs to be able to see them
204+
// // but has no login allowed, so it cannot SSH into them
205+
// NodeLabels: types.Labels{"*": []string{"*"}},
206+
// Rules: []types.Rule{
207+
// types.NewRule(types.KindRole, unrestricted),
208+
// types.NewRule(types.KindUser, unrestricted),
209+
// types.NewRule(types.KindAuthConnector, unrestricted),
210+
// types.NewRule(types.KindLoginRule, unrestricted),
211+
// types.NewRule(types.KindToken, unrestricted),
212+
// types.NewRule(types.KindOktaImportRule, unrestricted),
213+
// types.NewRule(types.KindAccessList, unrestricted),
214+
// types.NewRule(types.KindNode, unrestricted),
215+
// types.NewRule(types.KindDatabase, unrestricted),
216+
// },
217+
// Impersonate: &types.ImpersonateConditions{
218+
// Users: []string{"Db"},
219+
// Roles: []string{"Db"},
220+
// },
221+
// },
222+
// })
223+
// require.NoError(t, err)
165224

166-
operatorName := ValidRandomResourceName("operator-")
167-
_ = teleportServer.AddUserWithRole(operatorName, role)
225+
// operatorName := ValidRandomResourceName("operator-")
226+
// _ = teleportServer.AddUserWithRole(operatorName, role)
168227

169-
err = teleportServer.CreateEx(t, nil, rcConf)
228+
// err = teleportServer.CreateEx(t, nil, rcConf)
229+
// require.NoError(t, err)
230+
231+
authProcess, proxyProcess, provisionToken := helpers.MakeTestServers(t)
232+
authServer := authProcess.GetAuthServer()
233+
proxyAddr, err := proxyProcess.ProxyWebAddr()
170234
require.NoError(t, err)
171235

172-
return teleportServer, operatorName
236+
return teleportServer, ValidRandomResourceName("operator-")
173237
}
174238

175239
func FastEventually(t *testing.T, condition func() bool) {
@@ -280,7 +344,7 @@ func setupMockPostgresServer(t *testing.T, setup *TestSetup) {
280344
URI: net.JoinHostPort("localhost", postgresTestServer.Port()),
281345
})
282346

283-
waitForDatabases(t, setup, databaseResourceName)
347+
waitForDatabases(t, setup.TeleportClient.GetDatabaseServers, databaseResourceName)
284348

285349
// server, err := clickhouse.NewTestServer(common.TestServerConfig{
286350
// AuthClient: setup.TeleportClient,
@@ -296,11 +360,11 @@ func setupMockPostgresServer(t *testing.T, setup *TestSetup) {
296360
// }
297361
}
298362

299-
func waitForDatabases(t *testing.T, setup *TestSetup, dbNames ...string) {
363+
func waitForDatabases(t *testing.T, GetDatabaseServers func(ctx context.Context, name string) ([]types.DatabaseServer, error), dbNames ...string) {
300364
ctx := context.Background()
301365

302366
require.Eventually(t, func() bool {
303-
all, err := setup.TeleportClient.GetDatabaseServers(ctx, "default")
367+
all, err := GetDatabaseServers(ctx, "default")
304368
assert.NoError(t, err)
305369

306370
if len(dbNames) > len(all) {
@@ -311,7 +375,6 @@ func waitForDatabases(t *testing.T, setup *TestSetup, dbNames ...string) {
311375
for _, db := range dbNames {
312376
for _, a := range all {
313377
if a.GetName() == db {
314-
require.FailNow(t, "Got db: %#v", a)
315378
registered++
316379
break
317380
}
@@ -368,6 +431,8 @@ func StepByStep(setup *TestSetup) {
368431

369432
// SetupTestEnv creates a Kubernetes server, a teleport server and starts the operator
370433
func SetupTestEnv(t *testing.T, opts ...TestOption) *TestSetup {
434+
doCopyPastedTest(t)
435+
371436
// Hack to get the path of this file in order to find the crd path no matter
372437
// where this is called from.
373438
_, thisFileName, _, _ := runtime.Caller(0)

lib/client/conntest/database.go

-2
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,6 @@ func NewDatabaseConnectionTester(cfg DatabaseConnectionTesterConfig) (*DatabaseC
102102
// - the database is accessible and accepting connections from the database server
103103
// - the database has the database user and database name that was requested
104104
func (s *DatabaseConnectionTester) TestConnection(ctx context.Context, req TestConnectionRequest) (types.ConnectionDiagnostic, error) {
105-
fmt.Printf("HERE TESTCONNECTION *******************************")
106105
if req.ResourceKind != types.KindDatabase {
107106
return nil, trace.BadParameter("invalid value for ResourceKind, expected %q got %q", types.KindDatabase, req.ResourceKind)
108107
}
@@ -127,7 +126,6 @@ func (s *DatabaseConnectionTester) TestConnection(ctx context.Context, req TestC
127126
return nil, trace.Wrap(err)
128127
}
129128

130-
return s.handlePingSuccess(ctx, connectionDiagnosticID)
131129
databaseServers, err := s.getDatabaseServers(ctx, req.ResourceName)
132130
if err != nil {
133131
return nil, trace.Wrap(err)

0 commit comments

Comments
 (0)