Skip to content

Commit

Permalink
add --venafi-connection-namespace
Browse files Browse the repository at this point in the history
  • Loading branch information
maelvls committed Jul 19, 2024
1 parent 6718598 commit 9a35e7a
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 28 deletions.
16 changes: 14 additions & 2 deletions cmd/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,22 @@ func init() {
"Token used for authentication when API tokens are in use on the backend",
)
agentCmd.PersistentFlags().StringVar(
&agent.VenConn,
&agent.VenConnName,
"venafi-connection",
"",
"VenafiConnection to be used",
"Name of the VenafiConnection to be used. Using this flag will enable the VenafiConnection mode.",
)
agentCmd.PersistentFlags().StringVar(
&agent.VenConnNS,
"venafi-connection-namespace",
"",
"Namespace of the VenafiConnection to be used. It is only useful when the VenafiConnection isn't in the same namespace as the agent. The field `allowReferencesFrom` must be present on the cross-namespace VenafiConnection for the agent to use it.",
)
agentCmd.PersistentFlags().StringVar(
&agent.InstallNS,
"install-namespace",
"",
"Namespace in which the agent is running. Only needed when running the agent outside of Kubernetes.",
)
agentCmd.PersistentFlags().BoolVarP(
&agent.Profiling,
Expand Down
55 changes: 52 additions & 3 deletions pkg/agent/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,23 @@ var StrictMode bool
// APIToken is an authentication token used for the backend API as an alternative to oauth flows.
var APIToken string

var VenConn string
// VenConnName is the name of the VenafiConnection resource to use. Using this
// flag will enable Venafi Connection mode.
var VenConnName string

// VenConnNS is the namespace of the VenafiConnection resource to use. It is
// only useful when the VenafiConnection isn't in the same namespace as the
// agent.
//
// May be left empty to use the same namespace as the agent.
var VenConnNS string

// InstallNS is the namespace in which the agent is running in. Only needed when
// running the agent outside of Kubernetes.
//
// May be left empty when running in Kubernetes. In this case, the namespace is
// read from the file /var/run/secrets/kubernetes.io/serviceaccount/namespace.
var InstallNS string

// Profiling flag enabled pprof endpoints to run on the agent
var Profiling bool
Expand All @@ -81,6 +97,8 @@ var Prometheus bool
// raw resource data of unstructuredList
const schemaVersion string = "v2.0.0"

const inClusterNamespacePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"

// Run starts the agent process
func Run(cmd *cobra.Command, args []string) {
ctx, cancel := context.WithCancel(context.Background())
Expand Down Expand Up @@ -260,6 +278,18 @@ func getConfiguration() (Config, client.Client) {
}
}

venConnMode := VenConnName != ""

if venConnMode && InstallNS == "" {
InstallNS, err = getInClusterNamespace()
if err != nil {
log.Fatalf("could not guess which namespace the agent is running in: %s", err)
}
}
if venConnMode && VenConnNS == "" {
VenConnNS = InstallNS
}

agentMetadata := &api.AgentMetadata{
Version: version.PreflightVersion,
ClusterID: config.ClusterID,
Expand All @@ -272,9 +302,9 @@ func getConfiguration() (Config, client.Client) {
case APIToken != "":
log.Println("An API token was specified, using API token authentication.")
preflightClient, err = client.NewAPITokenClient(agentMetadata, APIToken, baseURL)
case VenConn != "":
case VenConnName != "":
log.Println("Venafi Connection mode was specified, using Venafi Connection authentication.")
preflightClient, err = client.NewVenConnClient(&http.Client{}, agentMetadata, baseURL, "", "venafi", VenConn)
preflightClient, err = client.NewVenConnClient(&http.Client{}, agentMetadata, baseURL, "", InstallNS, VenConnName, VenConnNS)
default:
log.Println("No credentials were specified, using with no authentication.")
preflightClient, err = client.NewUnauthenticatedClient(agentMetadata, baseURL)
Expand Down Expand Up @@ -473,3 +503,22 @@ func postData(config Config, preflightClient client.Client, readings []*api.Data

return nil
}

// Inspired from the controller-runtime project.
func getInClusterNamespace() (string, error) {
// Check whether the namespace file exists.
// If not, we are not running in cluster so can't guess the namespace.
_, err := os.Stat(inClusterNamespacePath)
if os.IsNotExist(err) {
return "", fmt.Errorf("not running in cluster, please use --install-namespace to specify the namespace in which the agent is running")
}
if err != nil {
return "", fmt.Errorf("error checking namespace file: %w", err)
}

namespace, err := os.ReadFile(inClusterNamespacePath)
if err != nil {
return "", fmt.Errorf("error reading namespace file: %w", err)
}
return string(namespace), nil
}
41 changes: 18 additions & 23 deletions pkg/client/client_venconn.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,38 +20,31 @@ import (
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
)

type VenConnClient struct {
baseURL string
agentMetadata *api.AgentMetadata
connHandler venafi_client.ConnectionHandler
installNamespace string // Namespace in which the agent is running in.
venConnName string // Name of the VenafiConnection resource to use.
client *http.Client // Used to make HTTP requests to Venafi Cloud.
baseURL string
agentMetadata *api.AgentMetadata
connHandler venafi_client.ConnectionHandler
installNS string // Namespace in which the agent is running in.
venConnName string // Name of the VenafiConnection resource to use.
venConnNS string // Namespace of the VenafiConnection resource to use.
client *http.Client // Used to make HTTP requests to Venafi Cloud.
}

// NewVenConnClient returns a new instance of the VenConnClient type that will perform HTTP requests using
// no authentication.
func NewVenConnClient(c *http.Client, agentMetadata *api.AgentMetadata, baseURL, kubeconfigPath, installNamespace, venConnName string) (*VenConnClient, error) {
func NewVenConnClient(c *http.Client, agentMetadata *api.AgentMetadata, baseURL, kubeconfigPath, installNS, venConnName, venConnNS string) (*VenConnClient, error) {
cfg, err := loadRESTConfig(kubeconfigPath)
if err != nil {
return nil, errors.WithStack(err)
}
cfg.Impersonate = rest.ImpersonationConfig{
UserName: fmt.Sprintf("system:serviceaccount:%s:venafi-connection", installNamespace),
UserName: fmt.Sprintf("system:serviceaccount:%s:venafi-connection", installNS),
}

clientset, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, errors.WithStack(err)
}
clientset.DiscoveryClient.RESTClient()

restMapper, err := apiutil.NewDynamicRESTMapper(cfg, &http.Client{})
if err != nil {
return nil, errors.WithStack(err)
Expand Down Expand Up @@ -84,12 +77,12 @@ func NewVenConnClient(c *http.Client, agentMetadata *api.AgentMetadata, baseURL,
}()

return &VenConnClient{
baseURL: baseURL,
agentMetadata: agentMetadata,
connHandler: handler,
installNamespace: installNamespace,
venConnName: venConnName,
client: c,
baseURL: baseURL,
agentMetadata: agentMetadata,
connHandler: handler,
installNS: installNS,
venConnName: venConnName,
client: c,
}, nil
}

Expand Down Expand Up @@ -131,7 +124,9 @@ func (c *VenConnClient) PostDataReadings(orgID, clusterID string, readings []*ap

// Post performs an HTTP POST request.
func (c *VenConnClient) Post(path string, body io.Reader) (*http.Response, error) {
_, token, err := c.connHandler.Get(context.Background(), c.installNamespace, auth.Scope{}, types.NamespacedName{Name: c.venConnName, Namespace: c.installNamespace})
// The VenafiConnection must be in the same namespace as the agent. It can't
// because `requestorNamespace` is set to the namespace of the agent.
_, token, err := c.connHandler.Get(context.Background(), c.installNS, auth.Scope{}, types.NamespacedName{Name: c.venConnName, Namespace: c.venConnNS})
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 9a35e7a

Please sign in to comment.