Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate database access credentials with tctl auth sign command #10785

Merged
merged 12 commits into from
Apr 4, 2022
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 50 additions & 4 deletions tool/tctl/common/auth_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ type AuthCommand struct {
leafCluster string
kubeCluster string
appName string
db string
dbName string
dbUser string
signOverwrite bool

rotateGracePeriod time.Duration
Expand Down Expand Up @@ -119,7 +122,10 @@ func (a *AuthCommand) Initialize(app *kingpin.Application, config *service.Confi
a.authSign.Flag("kube-cluster", `Leaf cluster to generate identity file for when --format is set to "kubernetes"`).Hidden().StringVar(&a.leafCluster)
a.authSign.Flag("leaf-cluster", `Leaf cluster to generate identity file for when --format is set to "kubernetes"`).StringVar(&a.leafCluster)
a.authSign.Flag("kube-cluster-name", `Kubernetes cluster to generate identity file for when --format is set to "kubernetes"`).StringVar(&a.kubeCluster)
a.authSign.Flag("app-name", `Application to generate identity file for`).StringVar(&a.appName)
a.authSign.Flag("app-name", `Application to generate identity file for. Mutually exclusive with "--db-name".`).StringVar(&a.appName)
a.authSign.Flag("db", `Database to generate identity file for. Mutually exclusive with "--app-name".`).StringVar(&a.db)
a.authSign.Flag("db-user", `Database user placed on the identity file. Only used when "--db" is set.`).StringVar(&a.dbUser)
a.authSign.Flag("db-name", `Database name placed on the identity file. Only used when "--db" is set.`).StringVar(&a.dbName)

a.authRotate = auth.Command("rotate", "Rotate certificate authorities in the cluster")
a.authRotate.Flag("grace-period", "Grace period keeps previous certificate authorities signatures valid, if set to 0 will force users to relogin and nodes to re-register.").
Expand Down Expand Up @@ -595,10 +601,19 @@ func (a *AuthCommand) generateUserKeys(ctx context.Context, clusterAPI auth.Clie
return trace.Wrap(err)
}

var routeToApp proto.RouteToApp
var certUsage proto.UserCertsRequest_CertUsage
var (
routeToApp proto.RouteToApp
routeToDatabase proto.RouteToDatabase
certUsage proto.UserCertsRequest_CertUsage
)

// `appName` and `db` are mutually exclusive.
if a.appName != "" && a.db != "" {
return trace.BadParameter("only --app-name or --db can be set, not both")
}

if a.appName != "" {
switch {
case a.appName != "":
server, err := getApplicationServer(ctx, clusterAPI, a.appName)
if err != nil {
return trace.Wrap(err)
Expand All @@ -620,6 +635,19 @@ func (a *AuthCommand) generateUserKeys(ctx context.Context, clusterAPI auth.Clie
SessionID: appSession.GetName(),
}
certUsage = proto.UserCertsRequest_App
case a.db != "":
server, err := getDatabaseServer(context.TODO(), clusterAPI, a.db)
if err != nil {
return trace.Wrap(err)
}

routeToDatabase = proto.RouteToDatabase{
ServiceName: a.db,
Protocol: server.GetDatabase().GetProtocol(),
Database: a.dbName,
Username: a.dbUser,
}
certUsage = proto.UserCertsRequest_Database
}

reqExpiry := time.Now().UTC().Add(a.genTTL)
Expand All @@ -633,6 +661,7 @@ func (a *AuthCommand) generateUserKeys(ctx context.Context, clusterAPI auth.Clie
KubernetesCluster: a.kubeCluster,
RouteToApp: routeToApp,
Usage: certUsage,
RouteToDatabase: routeToDatabase,
})
if err != nil {
return trace.Wrap(err)
Expand Down Expand Up @@ -833,3 +862,20 @@ func getApplicationServer(ctx context.Context, clusterAPI auth.ClientI, appName
}
return nil, trace.NotFound("app %q not found", appName)
}

// getDatabaseServer fetches a single `DatabaseServer` by name using the
// provided `auth.ClientI`.
func getDatabaseServer(ctx context.Context, clientAPI auth.ClientI, dbName string) (types.DatabaseServer, error) {
gabrielcorado marked this conversation as resolved.
Show resolved Hide resolved
servers, err := clientAPI.GetDatabaseServers(ctx, apidefaults.Namespace)
if err != nil {
return nil, trace.Wrap(err)
}

for _, server := range servers {
if server.GetName() == dbName {
return server, nil
}
}

return nil, trace.NotFound("database %q not found", dbName)
}
152 changes: 146 additions & 6 deletions tool/tctl/common/auth_command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"bytes"
"context"
"crypto/x509/pkix"
"io/ioutil"
"os"
"path/filepath"
"testing"
Expand All @@ -32,6 +31,7 @@ import (
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/client/identityfile"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/kube/kubeconfig"
"github.com/gravitational/teleport/lib/service"
"github.com/gravitational/teleport/lib/services"
Expand All @@ -42,7 +42,7 @@ import (
func TestAuthSignKubeconfig(t *testing.T) {
t.Parallel()

tmpDir, err := ioutil.TempDir("", "auth_command_test")
tmpDir, err := os.MkdirTemp("", "auth_command_test")
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -278,6 +278,7 @@ type mockClient struct {
remoteClusters []types.RemoteCluster
kubeServices []types.Server
appServices []types.AppServer
dbServices []types.DatabaseServer
appSession types.WebSession
}

Expand Down Expand Up @@ -313,6 +314,10 @@ func (c *mockClient) CreateAppSession(ctx context.Context, req types.CreateAppSe
return c.appSession, nil
}

func (c *mockClient) GetDatabaseServers(context.Context, string, ...services.MarshalOption) ([]types.DatabaseServer, error) {
return c.dbServices, nil
}

func TestCheckKubeCluster(t *testing.T) {
const teleportCluster = "local-teleport"
clusterName, err := services.NewClusterNameWithRandomID(types.ClusterNameSpecV2{
Expand Down Expand Up @@ -556,19 +561,19 @@ func TestGenerateDatabaseKeys(t *testing.T) {
require.Equal(t, test.outServerNames[0], authClient.dbCertsReq.ServerName)

if len(test.outKey) > 0 {
keyBytes, err := ioutil.ReadFile(filepath.Join(test.inOutDir, test.outKeyFile))
keyBytes, err := os.ReadFile(filepath.Join(test.inOutDir, test.outKeyFile))
require.NoError(t, err)
require.Equal(t, test.outKey, keyBytes, "keys match")
}

if len(test.outCert) > 0 {
certBytes, err := ioutil.ReadFile(filepath.Join(test.inOutDir, test.outCertFile))
certBytes, err := os.ReadFile(filepath.Join(test.inOutDir, test.outCertFile))
require.NoError(t, err)
require.Equal(t, test.outCert, certBytes, "certificates match")
}

if len(test.outCA) > 0 {
caBytes, err := ioutil.ReadFile(filepath.Join(test.inOutDir, test.outCAFile))
caBytes, err := os.ReadFile(filepath.Join(test.inOutDir, test.outCAFile))
require.NoError(t, err)
require.Equal(t, test.outCA, caBytes, "CA certificates match")
}
Expand Down Expand Up @@ -667,7 +672,142 @@ func TestGenerateAppCertificates(t *testing.T) {
require.Equal(t, proto.UserCertsRequest_App, authClient.userCertsReq.Usage)
require.Equal(t, expectedRouteToApp, authClient.userCertsReq.RouteToApp)

certBytes, err := ioutil.ReadFile(filepath.Join(tc.outDir, tc.outFileBase+".crt"))
certBytes, err := os.ReadFile(filepath.Join(tc.outDir, tc.outFileBase+".crt"))
require.NoError(t, err)
require.Equal(t, authClient.userCerts.TLS, certBytes, "certificates match")
})
}
}

func TestGenerateDatabaseUserCertificates(t *testing.T) {
ctx := context.Background()
tests := map[string]struct {
clusterName string
db string
dbName string
dbUser string
expectedDbProtocol string
dbServices []types.DatabaseServer
expectedErr error
}{
"DatabaseExists": {
clusterName: "example.com",
db: "db-1",
expectedDbProtocol: defaults.ProtocolPostgres,
dbServices: []types.DatabaseServer{
&types.DatabaseServerV3{
Metadata: types.Metadata{
Name: "db-1",
},
Spec: types.DatabaseServerSpecV3{
Hostname: "example.com",
Database: &types.DatabaseV3{
Spec: types.DatabaseSpecV3{
Protocol: defaults.ProtocolPostgres,
},
},
},
},
},
},
"DatabaseWithUserExists": {
clusterName: "example.com",
db: "db-user-1",
dbUser: "mongo-user",
expectedDbProtocol: defaults.ProtocolMongoDB,
dbServices: []types.DatabaseServer{
&types.DatabaseServerV3{
Metadata: types.Metadata{
Name: "db-user-1",
},
Spec: types.DatabaseServerSpecV3{
Hostname: "example.com",
Database: &types.DatabaseV3{
Spec: types.DatabaseSpecV3{
Protocol: defaults.ProtocolMongoDB,
},
},
},
},
},
},
"DatabaseWithDatabaseNameExists": {
clusterName: "example.com",
db: "db-user-1",
dbName: "root-database",
expectedDbProtocol: defaults.ProtocolMongoDB,
dbServices: []types.DatabaseServer{
&types.DatabaseServerV3{
Metadata: types.Metadata{
Name: "db-user-1",
},
Spec: types.DatabaseServerSpecV3{
Hostname: "example.com",
Database: &types.DatabaseV3{
Spec: types.DatabaseSpecV3{
Protocol: defaults.ProtocolMongoDB,
},
},
},
},
},
},
"DatabaseNotFound": {
clusterName: "example.com",
db: "db-2",
dbServices: []types.DatabaseServer{},
expectedErr: trace.NotFound(""),
},
}

for name, test := range tests {
t.Run(name, func(t *testing.T) {
clusterName, err := services.NewClusterNameWithRandomID(
types.ClusterNameSpecV2{
ClusterName: test.clusterName,
})
require.NoError(t, err)

authClient := &mockClient{
clusterName: clusterName,
userCerts: &proto.Certs{
SSH: []byte("SSH cert"),
TLS: []byte("TLS cert"),
},
dbServices: test.dbServices,
}

certsDir := t.TempDir()
output := filepath.Join(certsDir, test.db)
ac := AuthCommand{
output: output,
outputFormat: identityfile.FormatTLS,
signOverwrite: true,
genTTL: time.Hour,
db: test.db,
dbName: test.dbName,
dbUser: test.dbUser,
}

err = ac.generateUserKeys(ctx, authClient)
if test.expectedErr != nil {
require.Error(t, err)
gabrielcorado marked this conversation as resolved.
Show resolved Hide resolved
require.IsType(t, test.expectedErr, err)
return
}

require.NoError(t, err)

expectedRouteToDatabase := proto.RouteToDatabase{
ServiceName: test.db,
Protocol: test.expectedDbProtocol,
Database: test.dbName,
Username: test.dbUser,
}
require.Equal(t, proto.UserCertsRequest_Database, authClient.userCertsReq.Usage)
require.Equal(t, expectedRouteToDatabase, authClient.userCertsReq.RouteToDatabase)

certBytes, err := os.ReadFile(filepath.Join(certsDir, test.db+".crt"))
require.NoError(t, err)
require.Equal(t, authClient.userCerts.TLS, certBytes, "certificates match")
})
Expand Down