Files
threshold/internal/credential/vault/repository_credentials_test.go
T
Louis Ruch 9b39345c7f bug(credential): Fix panic in credential Issue
Vault KV backend returns a nil secret and no error if the secret does not
exist. This caused a panic in during Issue:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x1388279]

goroutine 2639 [running]:
github.com/hashicorp/boundary/internal/credential/vault.(*Repository).Issue(0xc001222200, {0x3b932d0, 0xc001203350}, {0xc000dc6e90, 0xc}, {0xc0010e5e40, 0x0, 0x0})
        /home/louis/boundary/internal/credential/vault/repository_credentials.go:67 +0x2d9
github.com/hashicorp/boundary/internal/servers/controller/handlers/targets.Service.AuthorizeSession({{}, 0xc000cd4a38, 0xc000cd4840, 0xc000cd48d0, 0xc000cd4a50, 0xc000cd4870, 0xc000cd4858, 0xc000cd48b8, 0xc0001a8880}, {0x3b932d0, ...}, ...)
        /home/louis/boundary/internal/servers/controller/handlers/targets/target_service.go:1059 +0x1525
github.com/hashicorp/boundary/internal/gen/controller/api/services._TargetService_AuthorizeSession_Handler.func1({0x3b932d0, 0xc001203350}, {0x1a0dd40, 0xc000dc8880})
        /home/louis/boundary/internal/gen/controller/api/services/target_service_grpc.pb.go:631 +0x78
github.com/hashicorp/boundary/internal/servers/controller.auditResponseInterceptor.func1({0x3b932d0, 0xc001203350}, {0x1a0dd40, 0xc000dc8880}, 0x461279, 0x40d234)
        /home/louis/boundary/internal/servers/controller/interceptor.go:262 +0x4e
github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1.1({0x3b932d0, 0xc001203350}, {0x1a0dd40, 0xc000dc8880})
        /home/louis/go/pkg/mod/github.com/grpc-ecosystem/go-grpc-middleware@v1.3.0/chain.go:25 +0x3a
github.com/hashicorp/boundary/internal/servers/controller.statusCodeInterceptor.func1({0x3b932d0, 0xc001203350}, {0x1a0dd40, 0xc000dc8880}, 0x203000, 0x203000)
        /home/louis/boundary/internal/servers/controller/interceptor.go:207 +0x34
github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1.1({0x3b932d0, 0xc001203350}, {0x1a0dd40, 0xc000dc8880})
        /home/louis/go/pkg/mod/github.com/grpc-ecosystem/go-grpc-middleware@v1.3.0/chain.go:25 +0x3a
github.com/hashicorp/boundary/internal/servers/controller.errorInterceptor.func1({0x3b932d0, 0xc001203350}, {0x1a0dd40, 0xc000dc8880}, 0x18e2b40, 0x0)
        /home/louis/boundary/internal/servers/controller/interceptor.go:156 +0x4e
github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1.1({0x3b932d0, 0xc001203350}, {0x1a0dd40, 0xc000dc8880})
        /home/louis/go/pkg/mod/github.com/grpc-ecosystem/go-grpc-middleware@v1.3.0/chain.go:25 +0x3a
github.com/hashicorp/boundary/internal/servers/controller.auditRequestInterceptor.func1({0x3b932d0, 0xc001203350}, {0x1a0dd40, 0xc000dc8880}, 0x1a1c860, 0xc0010e5280)
        /home/louis/boundary/internal/servers/controller/interceptor.go:248 +0x198
github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1.1({0x3b932d0, 0xc001203350}, {0x1a0dd40, 0xc000dc8880})
        /home/louis/go/pkg/mod/github.com/grpc-ecosystem/go-grpc-middleware@v1.3.0/chain.go:25 +0x3a
github.com/hashicorp/boundary/internal/servers/controller.requestCtxInterceptor.func1({0x3b932d0, 0xc001203260}, {0x1a0dd40, 0xc000dc8880}, 0x18, 0xc0010e52a0)
        /home/louis/boundary/internal/servers/controller/interceptor.go:140 +0x5de
github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1.1({0x3b932d0, 0xc001203260}, {0x1a0dd40, 0xc000dc8880})
        /home/louis/go/pkg/mod/github.com/grpc-ecosystem/go-grpc-middleware@v1.3.0/chain.go:25 +0x3a
github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1({0x3b932d0, 0xc001203260}, {0x1a0dd40, 0xc000dc8880}, 0xc00331abb8, 0x18675e0)
        /home/louis/go/pkg/mod/github.com/grpc-ecosystem/go-grpc-middleware@v1.3.0/chain.go:34 +0xbf
github.com/hashicorp/boundary/internal/gen/controller/api/services._TargetService_AuthorizeSession_Handler({0x1ada420, 0xc00093a180}, {0x3b932d0, 0xc001203260}, 0xc001200840, 0xc000465260)
        /home/louis/boundary/internal/gen/controller/api/services/target_service_grpc.pb.go:633 +0x138
google.golang.org/grpc.(*Server).processUnaryRPC(0xc000cca540, {0x3bb4c58, 0xc0005a9c80}, 0xc001208480, 0xc0004a7440, 0x499e2b8, 0x0)
        /home/louis/go/pkg/mod/google.golang.org/grpc@v1.40.0/server.go:1297 +0xccf
google.golang.org/grpc.(*Server).handleStream(0xc000cca540, {0x3bb4c58, 0xc0005a9c80}, 0xc001208480, 0x0)
        /home/louis/go/pkg/mod/google.golang.org/grpc@v1.40.0/server.go:1626 +0xa2a
google.golang.org/grpc.(*Server).serveStreams.func1.2()
        /home/louis/go/pkg/mod/google.golang.org/grpc@v1.40.0/server.go:941 +0x98
created by google.golang.org/grpc.(*Server).serveStreams.func1
        /home/louis/go/pkg/mod/google.golang.org/grpc@v1.40.0/server.go:939 +0x294
2021-12-15 16:13:30 -08:00

517 lines
15 KiB
Go

package vault_test
import (
"context"
"path"
"testing"
"github.com/hashicorp/boundary/internal/authtoken"
"github.com/hashicorp/boundary/internal/credential"
"github.com/hashicorp/boundary/internal/credential/vault"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/host/static"
"github.com/hashicorp/boundary/internal/iam"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/scheduler"
"github.com/hashicorp/boundary/internal/session"
"github.com/hashicorp/boundary/internal/target"
"github.com/hashicorp/boundary/internal/target/tcp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRepository_IssueCredentials(t *testing.T) {
t.Parallel()
ctx := context.Background()
v := vault.NewTestVaultServer(t, vault.WithDockerNetwork(true), vault.WithTestVaultTLS(vault.TestClientTLS))
v.MountDatabase(t)
v.MountPKI(t)
v.AddKVPolicy(t)
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
kms := kms.TestKms(t, conn, wrapper)
assert, require := assert.New(t), require.New(t)
sche := scheduler.TestScheduler(t, conn, wrapper)
repo, err := vault.NewRepository(rw, rw, kms, sche)
require.NoError(err)
require.NotNil(repo)
err = vault.RegisterJobs(ctx, sche, rw, rw, kms)
require.NoError(err)
_, token := v.CreateToken(t, vault.WithPolicies([]string{"default", "boundary-controller", "database", "pki", "secret"}))
// Create valid KV secret
v.CreateKVSecret(t, "my-secret", []byte(`{"data":{"username":"user","password":"pass"}}`))
var opts []vault.Option
opts = append(opts, vault.WithCACert(v.CaCert))
clientCert, err := vault.NewClientCertificate(v.ClientCert, v.ClientKey)
require.NoError(err)
opts = append(opts, vault.WithClientCert(clientCert))
credStoreIn, err := vault.NewCredentialStore(prj.GetPublicId(), v.Addr, []byte(token), opts...)
assert.NoError(err)
require.NotNil(credStoreIn)
origStore, err := repo.CreateCredentialStore(ctx, credStoreIn)
assert.NoError(err)
require.NotNil(origStore)
type libT int
const (
libDB libT = iota
libPKI
libErrPKI
libKV
libErrKV
)
libs := make(map[libT]string)
{
libPath := path.Join("database", "creds", "opened")
libIn, err := vault.NewCredentialLibrary(origStore.GetPublicId(), libPath)
assert.NoError(err)
require.NotNil(libIn)
lib, err := repo.CreateCredentialLibrary(ctx, prj.GetPublicId(), libIn)
assert.NoError(err)
require.NotNil(lib)
libs[libDB] = lib.GetPublicId()
}
{
libPath := path.Join("pki", "issue", "boundary")
libIn, err := vault.NewCredentialLibrary(origStore.GetPublicId(), libPath, vault.WithMethod(vault.MethodPost), vault.WithRequestBody([]byte(`{"common_name":"boundary.com"}`)))
assert.NoError(err)
require.NotNil(libIn)
lib, err := repo.CreateCredentialLibrary(ctx, prj.GetPublicId(), libIn)
assert.NoError(err)
require.NotNil(lib)
libs[libPKI] = lib.GetPublicId()
}
{
libPath := path.Join("pki", "issue", "boundary")
libIn, err := vault.NewCredentialLibrary(origStore.GetPublicId(), libPath, vault.WithMethod(vault.MethodPost))
assert.NoError(err)
require.NotNil(libIn)
lib, err := repo.CreateCredentialLibrary(ctx, prj.GetPublicId(), libIn)
assert.NoError(err)
require.NotNil(lib)
libs[libErrPKI] = lib.GetPublicId()
}
{
libPath := path.Join("secret", "data", "my-secret")
libIn, err := vault.NewCredentialLibrary(origStore.GetPublicId(), libPath, opts...)
assert.NoError(err)
require.NotNil(libIn)
lib, err := repo.CreateCredentialLibrary(ctx, prj.GetPublicId(), libIn)
assert.NoError(err)
require.NotNil(lib)
libs[libKV] = lib.GetPublicId()
}
{
libPath := path.Join("secret", "data", "fake-secret")
libIn, err := vault.NewCredentialLibrary(origStore.GetPublicId(), libPath, opts...)
assert.NoError(err)
require.NotNil(libIn)
lib, err := repo.CreateCredentialLibrary(ctx, prj.GetPublicId(), libIn)
assert.NoError(err)
require.NotNil(lib)
libs[libErrKV] = lib.GetPublicId()
}
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
uId := at.GetIamUserId()
hc := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
h := static.TestHosts(t, conn, hc.GetPublicId(), 1)[0]
static.TestSetMembers(t, conn, hs.GetPublicId(), []*static.Host{h})
tar := tcp.TestTarget(context.Background(), t, conn, prj.GetPublicId(), "test", target.WithHostSources([]string{hs.GetPublicId()}))
rc2dc := func(rcs []credential.Request) []*session.DynamicCredential {
var dcs []*session.DynamicCredential
for _, rc := range rcs {
dc := &session.DynamicCredential{
LibraryId: rc.SourceId,
CredentialPurpose: string(rc.Purpose),
}
dcs = append(dcs, dc)
}
return dcs
}
rc2nil := func(rcs []credential.Request) []*session.DynamicCredential { return nil }
tests := []struct {
name string
convertFn func(rcs []credential.Request) []*session.DynamicCredential
requests []credential.Request
wantErr errors.Code
}{
{
name: "one-library-valid",
convertFn: rc2dc,
requests: []credential.Request{
{
SourceId: libs[libDB],
Purpose: credential.ApplicationPurpose,
},
},
},
{
name: "multiple-valid-libraries",
convertFn: rc2dc,
requests: []credential.Request{
{
SourceId: libs[libDB],
Purpose: credential.ApplicationPurpose,
},
{
SourceId: libs[libPKI],
Purpose: credential.IngressPurpose,
},
},
},
{
name: "one-library-that-errors",
convertFn: rc2dc,
requests: []credential.Request{
{
SourceId: libs[libErrPKI],
Purpose: credential.IngressPurpose,
},
},
wantErr: errors.VaultCredentialRequest,
},
{
name: "no-session-dynamic-credentials",
convertFn: rc2nil,
requests: []credential.Request{
{
SourceId: libs[libDB],
Purpose: credential.ApplicationPurpose,
},
{
SourceId: libs[libPKI],
Purpose: credential.IngressPurpose,
},
},
wantErr: errors.InvalidDynamicCredential,
},
{
name: "valid-kv-secret",
convertFn: rc2dc,
requests: []credential.Request{
{
SourceId: libs[libKV],
Purpose: credential.IngressPurpose,
},
},
},
{
name: "invalid-kv-does-not-exist",
convertFn: rc2dc,
requests: []credential.Request{
{
SourceId: libs[libErrKV],
Purpose: credential.ApplicationPurpose,
},
},
wantErr: errors.VaultEmptySecret,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
sess := session.TestSession(t, conn, wrapper, session.ComposedOf{
UserId: uId,
HostId: h.GetPublicId(),
TargetId: tar.GetPublicId(),
HostSetId: hs.GetPublicId(),
AuthTokenId: at.GetPublicId(),
ScopeId: prj.GetPublicId(),
Endpoint: "tcp://127.0.0.1:22",
DynamicCredentials: tt.convertFn(tt.requests),
})
got, err := repo.Issue(ctx, sess.GetPublicId(), tt.requests)
if tt.wantErr != 0 {
assert.Truef(errors.Match(errors.T(tt.wantErr), err), "want err: %q got: %q", tt.wantErr, err)
assert.Nil(got)
return
}
assert.Len(got, len(tt.requests))
assert.NoError(err)
})
}
}
func TestRepository_Revoke(t *testing.T) {
t.Parallel()
assert, require := assert.New(t), require.New(t)
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
require.NotNil(prj)
assert.NotEmpty(prj.GetPublicId())
cs := vault.TestCredentialStores(t, conn, wrapper, prj.GetPublicId(), 1)[0]
cl := vault.TestCredentialLibraries(t, conn, wrapper, cs.GetPublicId(), 1)[0]
hc := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
h := static.TestHosts(t, conn, hc.GetPublicId(), 1)[0]
static.TestSetMembers(t, conn, hs.GetPublicId(), []*static.Host{h})
tar := tcp.TestTarget(context.Background(), t, conn, prj.GetPublicId(), "test", target.WithHostSources([]string{hs.GetPublicId()}))
target.TestCredentialLibrary(t, conn, tar.GetPublicId(), cl.GetPublicId())
const (
sessionCount = 4
credentialCount = 4
)
sessionIds := make([]string, sessionCount)
sessions := make(map[string][]*vault.Credential, sessionCount)
for i := 0; i < sessionCount; i++ {
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
uId := at.GetIamUserId()
sess := session.TestSession(t, conn, wrapper, session.ComposedOf{
UserId: uId,
HostId: h.GetPublicId(),
TargetId: tar.GetPublicId(),
HostSetId: hs.GetPublicId(),
AuthTokenId: at.GetPublicId(),
ScopeId: prj.GetPublicId(),
Endpoint: "tcp://127.0.0.1:22",
})
sessionIds[i] = sess.GetPublicId()
credentials := vault.TestCredentials(t, conn, wrapper, cl.GetPublicId(), sess.GetPublicId(), credentialCount)
assert.Len(credentials, credentialCount)
for _, credential := range credentials {
assert.NotEmpty(credential.GetPublicId())
}
sessions[sess.GetPublicId()] = credentials
}
sche := scheduler.TestScheduler(t, conn, wrapper)
repo, err := vault.NewRepository(rw, rw, kms, sche)
require.NoError(err)
require.NotNil(repo)
ctx := context.Background()
assert.Error(repo.Revoke(ctx, ""))
type credCount struct {
active, revoke int
revoked, expired, unknown int
}
assertCreds := func(want map[string]*credCount) {
const query = `
select session_id, status, count(public_id)
from credential_vault_credential
group by session_id, status;
`
got := make(map[string]*credCount, len(want))
for id := range want {
got[id] = new(credCount)
}
var (
id string
status string
count int
)
rows, err := rw.Query(ctx, query, nil)
require.NoError(err)
defer rows.Close()
for rows.Next() {
require.NoError(rows.Scan(&id, &status, &count))
switch status {
case "active":
got[id].active = count
case "revoke":
got[id].revoke = count
case "revoked":
got[id].revoked = count
case "expired":
got[id].expired = count
case "unknown":
got[id].unknown = count
default:
assert.Failf("Unexpected status: %s", status)
}
}
require.NoError(rows.Err())
assert.Equal(want, got)
}
cc := make(map[string]*credCount, sessionCount)
for _, id := range sessionIds {
cc[id] = new(credCount)
cc[id].active = credentialCount
}
for _, id := range sessionIds {
assert.NoError(repo.Revoke(ctx, id))
cc[id].revoke = cc[id].active
cc[id].active = 0
assertCreds(cc)
}
}
func Test_TerminateSession(t *testing.T) {
t.Parallel()
assert, require := assert.New(t), require.New(t)
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
require.NotNil(prj)
assert.NotEmpty(prj.GetPublicId())
cs := vault.TestCredentialStores(t, conn, wrapper, prj.GetPublicId(), 1)[0]
cl := vault.TestCredentialLibraries(t, conn, wrapper, cs.GetPublicId(), 1)[0]
hc := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
h := static.TestHosts(t, conn, hc.GetPublicId(), 1)[0]
static.TestSetMembers(t, conn, hs.GetPublicId(), []*static.Host{h})
tar := tcp.TestTarget(context.Background(), t, conn, prj.GetPublicId(), "test", target.WithHostSources([]string{hs.GetPublicId()}))
target.TestCredentialLibrary(t, conn, tar.GetPublicId(), cl.GetPublicId())
const (
sessionCount = 4
credentialCount = 4
)
sessionIds := make([]string, sessionCount)
sessions := make(map[string][]*vault.Credential, sessionCount)
for i := 0; i < sessionCount; i++ {
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
uId := at.GetIamUserId()
sess := session.TestSession(t, conn, wrapper, session.ComposedOf{
UserId: uId,
HostId: h.GetPublicId(),
TargetId: tar.GetPublicId(),
HostSetId: hs.GetPublicId(),
AuthTokenId: at.GetPublicId(),
ScopeId: prj.GetPublicId(),
Endpoint: "tcp://127.0.0.1:22",
})
sessionIds[i] = sess.GetPublicId()
credentials := vault.TestCredentials(t, conn, wrapper, cl.GetPublicId(), sess.GetPublicId(), credentialCount)
assert.Len(credentials, credentialCount)
for _, credential := range credentials {
assert.NotEmpty(credential.GetPublicId())
}
sessions[sess.GetPublicId()] = credentials
}
sche := scheduler.TestScheduler(t, conn, wrapper)
repo, err := vault.NewRepository(rw, rw, kms, sche)
require.NoError(err)
require.NotNil(repo)
ctx := context.Background()
assert.Error(repo.Revoke(ctx, ""))
type credCount struct {
active, revoke int
revoked, expired, unknown int
}
assertCreds := func(want map[string]*credCount) {
const query = `
select session_id, status, count(public_id)
from credential_vault_credential
group by session_id, status;
`
got := make(map[string]*credCount, len(want))
for id := range want {
got[id] = new(credCount)
}
var (
id string
status string
count int
)
rows, err := rw.Query(ctx, query, nil)
require.NoError(err)
defer rows.Close()
for rows.Next() {
require.NoError(rows.Scan(&id, &status, &count))
switch status {
case "active":
got[id].active = count
case "revoke":
got[id].revoke = count
case "revoked":
got[id].revoked = count
case "expired":
got[id].expired = count
case "unknown":
got[id].unknown = count
default:
assert.Failf("Unexpected status: %s", status)
}
}
require.NoError(rows.Err())
assert.Equal(want, got)
}
cc := make(map[string]*credCount, sessionCount)
for _, id := range sessionIds {
cc[id] = new(credCount)
cc[id].active = credentialCount
}
sessionRepo, err := session.NewRepository(rw, rw, kms)
require.NoError(err)
count, err := sessionRepo.TerminateCompletedSessions(ctx)
assert.NoError(err)
assert.Zero(count)
assertCreds(cc)
// call CancelSession
id := sessionIds[0]
_, err = sessionRepo.CancelSession(ctx, id, 1)
assert.NoError(err)
cc[id].revoke = cc[id].active
cc[id].active = 0
assertCreds(cc)
count, err = sessionRepo.TerminateCompletedSessions(ctx)
assert.NoError(err)
assert.Equal(1, count)
assertCreds(cc)
// call TerminateSession
id = sessionIds[1]
_, err = sessionRepo.TerminateSession(ctx, id, 1, session.ClosedByUser)
assert.NoError(err)
cc[id].revoke = cc[id].active
cc[id].active = 0
assertCreds(cc)
count, err = sessionRepo.TerminateCompletedSessions(ctx)
assert.NoError(err)
assert.Zero(count)
assertCreds(cc)
}