GitLab Delegated Joining (#22705)

* Add type for GitLab ProvisionToken

* Add default behaviour for domain

* Add IDTokenClaims for GitLab

* Add gitlab token source and token validator

* Thread GitLab support through auth and tbot packages

* Adjust cluster name fetching in token validator

* Initialize GitLab token validator in auth

* Improve comment on `sub`

* Working GitLab CI delegated joining

* Add additional token rule fields

* Add checking for new configuration fields

* add additional test cases for validation of gitlab config struct

* Add TestAuth_RegisterUsingToken_GitLab

* Add tests for IDTokenSource

* Fix imports

* Add tests for GitLab Token Validator

* Fix some comments that were incomplete

* Add license headers
This commit is contained in:
Noah Stride
2023-03-16 16:19:11 +00:00
committed by GitHub
parent 81f319d3e3
commit acb255cd88
20 changed files with 3619 additions and 1578 deletions
+16
View File
@@ -74,6 +74,7 @@ import (
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/githubactions"
"github.com/gravitational/teleport/lib/gitlab"
"github.com/gravitational/teleport/lib/inventory"
kubeutils "github.com/gravitational/teleport/lib/kube/utils"
"github.com/gravitational/teleport/lib/kubernetestoken"
@@ -316,6 +317,17 @@ func NewServer(cfg *InitConfig, opts ...ServerOption) (*Server, error) {
},
)
}
if as.gitlabIDTokenValidator == nil {
as.gitlabIDTokenValidator, err = gitlab.NewIDTokenValidator(
gitlab.IDTokenValidatorConfig{
Clock: as.clock,
ClusterNameGetter: services,
},
)
if err != nil {
return nil, trace.Wrap(err)
}
}
if as.circleCITokenValidate == nil {
as.circleCITokenValidate = func(
ctx context.Context, organizationID, token string,
@@ -529,6 +541,10 @@ type Server struct {
// by the auth server. It can be overridden for the purpose of tests.
ghaIDTokenValidator ghaIDTokenValidator
// gitlabIDTokenValidator allows ID tokens from GitLab CI to be validated by
// the auth server. It can be overridden for the purpose of tests.
gitlabIDTokenValidator gitlabIDTokenValidator
// circleCITokenValidate allows ID tokens from CircleCI to be validated by
// the auth server. It can be overridden for the purpose of tests.
circleCITokenValidate func(ctx context.Context, organizationID, token string) (*circleci.IDTokenClaims, error)
+2
View File
@@ -278,6 +278,7 @@ func (s *Server) checkOrCreateBotToken(ctx context.Context, req *proto.CreateBot
case types.JoinMethodToken,
types.JoinMethodIAM,
types.JoinMethodGitHub,
types.JoinMethodGitLab,
types.JoinMethodCircleCI:
default:
return nil, trace.BadParameter(
@@ -286,6 +287,7 @@ func (s *Server) checkOrCreateBotToken(ctx context.Context, req *proto.CreateBot
types.JoinMethodToken,
types.JoinMethodIAM,
types.JoinMethodGitHub,
types.JoinMethodGitLab,
types.JoinMethodCircleCI,
})
}
+7
View File
@@ -125,6 +125,12 @@ func (a *Server) RegisterUsingToken(ctx context.Context, req *types.RegisterUsin
return nil, trace.Wrap(err)
}
joinAttributeSrc = claims
case types.JoinMethodGitLab:
claims, err := a.checkGitLabJoinRequest(ctx, req)
if err != nil {
return nil, trace.Wrap(err)
}
joinAttributeSrc = claims
case types.JoinMethodCircleCI:
claims, err := a.checkCircleCIJoinRequest(ctx, req)
if err != nil {
@@ -189,6 +195,7 @@ func (a *Server) generateCertsBot(
renewable = true
case types.JoinMethodIAM,
types.JoinMethodGitHub,
types.JoinMethodGitLab,
types.JoinMethodCircleCI,
types.JoinMethodKubernetes,
types.JoinMethodAzure:
+95
View File
@@ -0,0 +1,95 @@
/*
Copyright 2022 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package auth
import (
"context"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/gitlab"
)
type gitlabIDTokenValidator interface {
Validate(
ctx context.Context, domain string, token string,
) (*gitlab.IDTokenClaims, error)
}
func (a *Server) checkGitLabJoinRequest(ctx context.Context, req *types.RegisterUsingTokenRequest) (*gitlab.IDTokenClaims, error) {
if req.IDToken == "" {
return nil, trace.BadParameter("IDToken not provided for gitlab join request")
}
pt, err := a.GetToken(ctx, req.Token)
if err != nil {
return nil, trace.Wrap(err)
}
token, ok := pt.(*types.ProvisionTokenV2)
if !ok {
return nil, trace.BadParameter("gitlab join method only supports ProvisionTokenV2, '%T' was provided", pt)
}
claims, err := a.gitlabIDTokenValidator.Validate(
ctx, token.Spec.GitLab.Domain, req.IDToken,
)
if err != nil {
return nil, trace.Wrap(err)
}
log.WithFields(logrus.Fields{
"claims": claims,
"token": pt.GetName(),
}).Info("GitLab CI run trying to join cluster")
return claims, trace.Wrap(checkGitLabAllowRules(token, claims))
}
func checkGitLabAllowRules(token *types.ProvisionTokenV2, claims *gitlab.IDTokenClaims) error {
// If a single rule passes, accept the IDToken
for _, rule := range token.Spec.GitLab.Allow {
// Please consider keeping these field validators in the same order they
// are defined within the ProvisionTokenSpecV2GitLab proto spec.
if rule.Sub != "" && claims.Sub != rule.Sub {
continue
}
if rule.Ref != "" && claims.Ref != rule.Ref {
continue
}
if rule.RefType != "" && claims.RefType != rule.RefType {
continue
}
if rule.NamespacePath != "" && claims.NamespacePath != rule.NamespacePath {
continue
}
if rule.ProjectPath != "" && claims.ProjectPath != rule.ProjectPath {
continue
}
if rule.PipelineSource != "" && claims.PipelineSource != rule.PipelineSource {
continue
}
if rule.Environment != "" && claims.Environment != rule.Environment {
continue
}
// All provided rules met.
return nil
}
return trace.AccessDenied("id token claims did not match any allow rules")
}
+296
View File
@@ -0,0 +1,296 @@
/*
Copyright 2023 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package auth
import (
"context"
"testing"
"time"
"github.com/gravitational/trace"
"github.com/stretchr/testify/require"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/auth/testauthority"
"github.com/gravitational/teleport/lib/gitlab"
)
type mockGitLabTokenValidator struct {
tokens map[string]gitlab.IDTokenClaims
lastCalledDomain string
}
func (m *mockGitLabTokenValidator) Validate(
_ context.Context, domain string, token string,
) (*gitlab.IDTokenClaims, error) {
m.lastCalledDomain = domain
claims, ok := m.tokens[token]
if !ok {
return nil, errMockInvalidToken
}
return &claims, nil
}
func TestAuth_RegisterUsingToken_GitLab(t *testing.T) {
validIDToken := "test.fake.jwt"
idTokenValidator := &mockGitLabTokenValidator{
tokens: map[string]gitlab.IDTokenClaims{
validIDToken: {
Sub: "project_path:octo-org/octo-repo:ref_type:branch:ref:main",
ProjectPath: "octo-org/octo-repo",
NamespacePath: "octo-org",
PipelineSource: "web",
Environment: "prod",
UserLogin: "octocat",
Ref: "main",
RefType: "branch",
},
},
}
var withTokenValidator ServerOption = func(server *Server) error {
server.gitlabIDTokenValidator = idTokenValidator
return nil
}
ctx := context.Background()
p, err := newTestPack(ctx, t.TempDir(), withTokenValidator)
require.NoError(t, err)
auth := p.a
// helper for creating RegisterUsingTokenRequest
sshPrivateKey, sshPublicKey, err := testauthority.New().GenerateKeyPair()
require.NoError(t, err)
tlsPublicKey, err := PrivateKeyToPublicKeyTLS(sshPrivateKey)
require.NoError(t, err)
newRequest := func(idToken string) *types.RegisterUsingTokenRequest {
return &types.RegisterUsingTokenRequest{
HostID: "host-id",
Role: types.RoleNode,
IDToken: idToken,
PublicTLSKey: tlsPublicKey,
PublicSSHKey: sshPublicKey,
}
}
allowRule := func(modifier func(*types.ProvisionTokenSpecV2GitLab_Rule)) *types.ProvisionTokenSpecV2GitLab_Rule {
rule := &types.ProvisionTokenSpecV2GitLab_Rule{
Sub: "project_path:octo-org/octo-repo:ref_type:branch:ref:main",
ProjectPath: "octo-org/octo-repo",
NamespacePath: "octo-org",
PipelineSource: "web",
Environment: "prod",
Ref: "main",
RefType: "branch",
}
if modifier != nil {
modifier(rule)
}
return rule
}
allowRulesNotMatched := require.ErrorAssertionFunc(func(t require.TestingT, err error, i ...interface{}) {
require.ErrorContains(t, err, "id token claims did not match any allow rules")
require.True(t, trace.IsAccessDenied(err))
})
tests := []struct {
name string
request *types.RegisterUsingTokenRequest
tokenSpec types.ProvisionTokenSpecV2
assertError require.ErrorAssertionFunc
}{
{
name: "success",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(nil),
},
},
},
request: newRequest(validIDToken),
assertError: require.NoError,
},
{
name: "domain override",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Domain: "gitlab.example.com",
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(nil),
},
},
},
request: newRequest(validIDToken),
assertError: require.NoError,
},
{
name: "multiple allow rules",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(func(rule *types.ProvisionTokenSpecV2GitLab_Rule) {
rule.Sub = "not matching"
}),
allowRule(nil),
},
},
},
request: newRequest(validIDToken),
assertError: require.NoError,
},
{
name: "incorrect sub",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(func(rule *types.ProvisionTokenSpecV2GitLab_Rule) {
rule.Sub = "not matching"
}),
},
},
},
request: newRequest(validIDToken),
assertError: allowRulesNotMatched,
},
{
name: "incorrect project path",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(func(rule *types.ProvisionTokenSpecV2GitLab_Rule) {
rule.ProjectPath = "not matching"
}),
},
},
},
request: newRequest(validIDToken),
assertError: allowRulesNotMatched,
},
{
name: "incorrect namespace path",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(func(rule *types.ProvisionTokenSpecV2GitLab_Rule) {
rule.NamespacePath = "not matching"
}),
},
},
},
request: newRequest(validIDToken),
assertError: allowRulesNotMatched,
},
{
name: "incorrect pipeline source",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(func(rule *types.ProvisionTokenSpecV2GitLab_Rule) {
rule.PipelineSource = "not matching"
}),
},
},
},
request: newRequest(validIDToken),
assertError: allowRulesNotMatched,
},
{
name: "incorrect environment",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(func(rule *types.ProvisionTokenSpecV2GitLab_Rule) {
rule.Environment = "not matching"
}),
},
},
},
request: newRequest(validIDToken),
assertError: allowRulesNotMatched,
},
{
name: "incorrect ref",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(func(rule *types.ProvisionTokenSpecV2GitLab_Rule) {
rule.Ref = "not matching"
}),
},
},
},
request: newRequest(validIDToken),
assertError: allowRulesNotMatched,
},
{
name: "incorrect ref type",
tokenSpec: types.ProvisionTokenSpecV2{
JoinMethod: types.JoinMethodGitLab,
Roles: []types.SystemRole{types.RoleNode},
GitLab: &types.ProvisionTokenSpecV2GitLab{
Allow: []*types.ProvisionTokenSpecV2GitLab_Rule{
allowRule(func(rule *types.ProvisionTokenSpecV2GitLab_Rule) {
rule.RefType = "not matching"
}),
},
},
},
request: newRequest(validIDToken),
assertError: allowRulesNotMatched,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
token, err := types.NewProvisionTokenFromSpec(
tt.name, time.Now().Add(time.Minute), tt.tokenSpec,
)
require.NoError(t, err)
require.NoError(t, auth.CreateToken(ctx, token))
tt.request.Token = tt.name
_, err = auth.RegisterUsingToken(ctx, tt.request)
tt.assertError(t, err)
if tt.tokenSpec.GitLab.Domain != "" {
require.Equal(
t,
tt.tokenSpec.GitLab.Domain,
idTokenValidator.lastCalledDomain,
)
}
})
}
}
+6
View File
@@ -40,6 +40,7 @@ import (
"github.com/gravitational/teleport/lib/cloud/azure"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/githubactions"
"github.com/gravitational/teleport/lib/gitlab"
"github.com/gravitational/teleport/lib/kubernetestoken"
"github.com/gravitational/teleport/lib/srv/alpnproxy/common"
"github.com/gravitational/teleport/lib/tlsca"
@@ -214,6 +215,11 @@ func Register(params RegisterParams) (*proto.Certs, error) {
if err != nil {
return nil, trace.Wrap(err)
}
} else if params.JoinMethod == types.JoinMethodGitLab {
params.IDToken, err = gitlab.NewIDTokenSource(os.Getenv).GetIDToken()
if err != nil {
return nil, trace.Wrap(err)
}
} else if params.JoinMethod == types.JoinMethodCircleCI {
params.IDToken, err = circleci.GetIDToken(os.Getenv)
if err != nil {