Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

Merge branch 'main' of github.com:Infisical/infisical into sid/k8s-operator

sidwebworksf9f989c8af6d
diff --cc k8-operator/config/samples/crd/infisicalsecret/infisicalSecretCrd.yaml
index b33662b543,b18f5df824..0e51f5bafb
--- a/k8-operator/config/samples/crd/infisicalsecret/infisicalSecretCrd.yaml
+++ b/k8-operator/config/samples/crd/infisicalsecret/infisicalSecretCrd.yaml
@@@ -7,9 -7,8 +7,9 @@@ metadata
annotations:
example.com/annotation-to-be-passed-to-managed-secret: "sample-value"
spec:
- hostAPI: https://app.infisical.com/api
+ hostAPI: http://localhost:8080/api
resyncInterval: 10
+ instantUpdates: true
# tls:
# caRef:
# secretName: custom-ca-certificate
diff --cc k8-operator/config/samples/universalAuthIdentitySecret.yaml
index 365598d7d4,88d60e6ab1..e940c42938
--- a/k8-operator/config/samples/universalAuthIdentitySecret.yaml
+++ b/k8-operator/config/samples/universalAuthIdentitySecret.yaml
@@@ -1,8 -1,8 +1,8 @@@
apiVersion: v1
kind: Secret
metadata:
- name: universal-auth-credentials
+ name: universal-auth-credentials
type: Opaque
stringData:
- clientId: da81e27e-1885-47d9-9ea3-ec7d4d807bb6
- clientSecret: 2772414d440fe04d8b975f5fe25acd0fbfe71b2a4a420409eb9ac6f5ae6c1e98
+ clientId: <your-client-id>
+ clientSecret: <your-client-secret>
diff --cc k8-operator/internal/controller/infisicalsecret_controller.go
index 075b25d371,d5d9c5d39b..9ebca1f076
--- a/k8-operator/internal/controller/infisicalsecret_controller.go
+++ b/k8-operator/internal/controller/infisicalsecret_controller.go
@@@ -12,28 -31,22 +31,25 @@@ import
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
+ "sigs.k8s.io/controller-runtime/pkg/source"
- defaultErrors "errors"
-
secretsv1alpha1 "github.com/Infisical/infisical/k8-operator/api/v1alpha1"
- "github.com/Infisical/infisical/k8-operator/packages/api"
- controllerhelpers "github.com/Infisical/infisical/k8-operator/packages/controllerhelpers"
- "github.com/Infisical/infisical/k8-operator/packages/util"
+ "github.com/Infisical/infisical/k8-operator/internal/controllerhelpers"
+ "github.com/Infisical/infisical/k8-operator/internal/util"
"github.com/go-logr/logr"
)
// InfisicalSecretReconciler reconciles a InfisicalSecret object
type InfisicalSecretReconciler struct {
client.Client
- BaseLogger logr.Logger
- Scheme *runtime.Scheme
+ BaseLogger logr.Logger
+ Scheme *runtime.Scheme
+
- SourceCh chan event.GenericEvent
++ SourceCh chan event.TypedGenericEvent[client.Object]
+ Namespace string
+ IsNamespaceScoped bool
}
- const FINALIZER_NAME = "secrets.finalizers.infisical.com"
-
var infisicalSecretResourceVariablesMap map[string]util.ResourceVariables = make(map[string]util.ResourceVariables)
func (r *InfisicalSecretReconciler) GetLogger(req ctrl.Request) logr.Logger {
@@@ -53,14 -66,17 +69,18 @@@
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
+ // TODO(user): Modify the Reconcile function to compare the state specified by
+ // the InfisicalSecret object against the actual cluster state, and then
+ // perform operations to make the cluster state reflect the state specified by
+ // the user.
+ //
// For more details, check Reconcile and its Result here:
- // - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
-
+ // - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
func (r *InfisicalSecretReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
-
logger := r.GetLogger(req)
+ logger.Info("Reconcile called")
+
var infisicalSecretCRD secretsv1alpha1.InfisicalSecret
requeueTime := time.Minute // seconds
@@@ -200,13 -204,7 +221,12 @@@
}
func (r *InfisicalSecretReconciler) SetupWithManager(mgr ctrl.Manager) error {
- r.SourceCh = make(chan event.GenericEvent)
++ r.SourceCh = make(chan event.TypedGenericEvent[client.Object])
+
return ctrl.NewControllerManagedBy(mgr).
- Watches(
- &source.Channel{Source: r.SourceCh},
- &util.EnqueueDelayedEventHandler{Delay: time.Second * 3},
++ WatchesRawSource(
++ source.Channel[client.Object](r.SourceCh, &util.EnqueueDelayedEventHandler{Delay: time.Second * 3}),
+ ).
For(&secretsv1alpha1.InfisicalSecret{}, builder.WithPredicates(predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
if e.ObjectOld.GetGeneration() == e.ObjectNew.GetGeneration() {
diff --cc k8-operator/internal/services/infisicalsecret/reconciler.go
index b8ab29e595,94596fb8c9..d93e010d44
--- a/k8-operator/internal/services/infisicalsecret/reconciler.go
+++ b/k8-operator/internal/services/infisicalsecret/reconciler.go
@@@ -11,77 -9,31 +11,35 @@@ import
tpl "text/template"
"github.com/Infisical/infisical/k8-operator/api/v1alpha1"
- secretsv1alpha1 "github.com/Infisical/infisical/k8-operator/api/v1alpha1"
- "github.com/Infisical/infisical/k8-operator/packages/api"
- "github.com/Infisical/infisical/k8-operator/packages/constants"
- "github.com/Infisical/infisical/k8-operator/packages/crypto"
- "github.com/Infisical/infisical/k8-operator/packages/model"
- "github.com/Infisical/infisical/k8-operator/packages/template"
- "github.com/Infisical/infisical/k8-operator/packages/util"
- "github.com/Infisical/infisical/k8-operator/packages/util/sse"
+ "github.com/Infisical/infisical/k8-operator/internal/api"
+ "github.com/Infisical/infisical/k8-operator/internal/constants"
+ "github.com/Infisical/infisical/k8-operator/internal/crypto"
+ "github.com/Infisical/infisical/k8-operator/internal/model"
+ "github.com/Infisical/infisical/k8-operator/internal/template"
+ "github.com/Infisical/infisical/k8-operator/internal/util"
++ "github.com/Infisical/infisical/k8-operator/internal/util/sse"
"github.com/go-logr/logr"
+ "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
+ "sigs.k8s.io/controller-runtime/pkg/client"
++ "sigs.k8s.io/controller-runtime/pkg/event"
infisicalSdk "github.com/infisical/go-sdk"
corev1 "k8s.io/api/core/v1"
k8Errors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
- "sigs.k8s.io/controller-runtime/pkg/client"
- "sigs.k8s.io/controller-runtime/pkg/event"
)
- func (r *InfisicalSecretReconciler) handleAuthentication(ctx context.Context, infisicalSecret v1alpha1.InfisicalSecret, infisicalClient infisicalSdk.InfisicalClientInterface) (util.AuthenticationDetails, error) {
-
- // ? Legacy support, service token auth
- infisicalToken, err := r.getInfisicalTokenFromKubeSecret(ctx, infisicalSecret)
- if err != nil {
- return util.AuthenticationDetails{}, fmt.Errorf("ReconcileInfisicalSecret: unable to get service token from kube secret [err=%s]", err)
- }
- if infisicalToken != "" {
- infisicalClient.Auth().SetAccessToken(infisicalToken)
- return util.AuthenticationDetails{AuthStrategy: util.AuthStrategy.SERVICE_TOKEN}, nil
- }
-
- // ? Legacy support, service account auth
- serviceAccountCreds, err := r.getInfisicalServiceAccountCredentialsFromKubeSecret(ctx, infisicalSecret)
- if err != nil {
- return util.AuthenticationDetails{}, fmt.Errorf("ReconcileInfisicalSecret: unable to get service account creds from kube secret [err=%s]", err)
- }
-
- if serviceAccountCreds.AccessKey != "" || serviceAccountCreds.PrivateKey != "" || serviceAccountCreds.PublicKey != "" {
- infisicalClient.Auth().SetAccessToken(serviceAccountCreds.AccessKey)
- return util.AuthenticationDetails{AuthStrategy: util.AuthStrategy.SERVICE_ACCOUNT}, nil
- }
-
- authStrategies := map[util.AuthStrategyType]func(ctx context.Context, reconcilerClient client.Client, secretCrd util.SecretAuthInput, infisicalClient infisicalSdk.InfisicalClientInterface) (util.AuthenticationDetails, error){
- util.AuthStrategy.UNIVERSAL_MACHINE_IDENTITY: util.HandleUniversalAuth,
- util.AuthStrategy.KUBERNETES_MACHINE_IDENTITY: util.HandleKubernetesAuth,
- util.AuthStrategy.AWS_IAM_MACHINE_IDENTITY: util.HandleAwsIamAuth,
- util.AuthStrategy.AZURE_MACHINE_IDENTITY: util.HandleAzureAuth,
- util.AuthStrategy.GCP_ID_TOKEN_MACHINE_IDENTITY: util.HandleGcpIdTokenAuth,
- util.AuthStrategy.GCP_IAM_MACHINE_IDENTITY: util.HandleGcpIamAuth,
- util.AuthStrategy.LDAP_MACHINE_IDENTITY: util.HandleLdapAuth,
- }
+ const FINALIZER_NAME = "secrets.finalizers.infisical.com"
- for authStrategy, authHandler := range authStrategies {
- authDetails, err := authHandler(ctx, r.Client, util.SecretAuthInput{
- Secret: infisicalSecret,
- Type: util.SecretCrd.INFISICAL_SECRET,
- }, infisicalClient)
-
- if err == nil {
- return authDetails, nil
- }
-
- if !errors.Is(err, util.ErrAuthNotApplicable) {
- return util.AuthenticationDetails{}, fmt.Errorf("authentication failed for strategy [%s] [err=%w]", authStrategy, err)
- }
- }
-
- return util.AuthenticationDetails{}, fmt.Errorf("no authentication method provided")
+ type InfisicalSecretReconciler struct {
+ client.Client
- Scheme *runtime.Scheme
++ Scheme *runtime.Scheme
+
++ SourceCh chan event.TypedGenericEvent[client.Object]
+ IsNamespaceScoped bool
}
func (r *InfisicalSecretReconciler) getInfisicalTokenFromKubeSecret(ctx context.Context, infisicalSecret v1alpha1.InfisicalSecret) (string, error) {
@@@ -466,27 -408,28 +414,28 @@@ func (r *InfisicalSecretReconciler) get
UserAgent: api.USER_AGENT_NAME,
})
- infisicalSecretResourceVariablesMap[string(infisicalSecret.UID)] = util.ResourceVariables{
+ resourceVariablesMap[string(infisicalSecret.UID)] = util.ResourceVariables{
- InfisicalClient: client,
- CancelCtx: cancel,
- AuthDetails: util.AuthenticationDetails{},
+ InfisicalClient: client,
+ CancelCtx: cancel,
+ AuthDetails: util.AuthenticationDetails{},
+ ServerSentEvents: sse.NewConnectionRegistry(ctx),
}
- resourceVariables = infisicalSecretResourceVariablesMap[string(infisicalSecret.UID)]
+ resourceVariables = resourceVariablesMap[string(infisicalSecret.UID)]
} else {
- resourceVariables = infisicalSecretResourceVariablesMap[string(infisicalSecret.UID)]
+ resourceVariables = resourceVariablesMap[string(infisicalSecret.UID)]
}
return resourceVariables
-
}
- func (r *InfisicalSecretReconciler) updateResourceVariables(infisicalSecret v1alpha1.InfisicalSecret, resourceVariables util.ResourceVariables) {
- infisicalSecretResourceVariablesMap[string(infisicalSecret.UID)] = resourceVariables
+ func (r *InfisicalSecretReconciler) updateResourceVariables(infisicalSecret v1alpha1.InfisicalSecret, resourceVariables util.ResourceVariables, resourceVariablesMap map[string]util.ResourceVariables) {
+ resourceVariablesMap[string(infisicalSecret.UID)] = resourceVariables
}
- func (r *InfisicalSecretReconciler) ReconcileInfisicalSecret(ctx context.Context, logger logr.Logger, infisicalSecret *v1alpha1.InfisicalSecret, managedKubeSecretReferences []v1alpha1.ManagedKubeSecretConfig, managedKubeConfigMapReferences []v1alpha1.ManagedKubeConfigMapConfig) (int, error) {
+ func (r *InfisicalSecretReconciler) ReconcileInfisicalSecret(ctx context.Context, logger logr.Logger, infisicalSecret *v1alpha1.InfisicalSecret, managedKubeSecretReferences []v1alpha1.ManagedKubeSecretConfig, managedKubeConfigMapReferences []v1alpha1.ManagedKubeConfigMapConfig, resourceVariablesMap map[string]util.ResourceVariables) (int, error) {
+
if infisicalSecret == nil {
return 0, fmt.Errorf("infisicalSecret is nil")
}
@@@ -507,11 -454,10 +460,11 @@@
}
r.updateResourceVariables(*infisicalSecret, util.ResourceVariables{
- InfisicalClient: infisicalClient,
- CancelCtx: cancelCtx,
- AuthDetails: authDetails,
+ InfisicalClient: infisicalClient,
+ CancelCtx: cancelCtx,
+ AuthDetails: authDetails,
+ ServerSentEvents: sse.NewConnectionRegistry(ctx),
- })
+ }, resourceVariablesMap)
}
plainTextSecretsFromApi, err := r.fetchSecretsFromAPI(ctx, logger, authDetails, infisicalClient, *infisicalSecret)
@@@ -573,124 -525,3 +532,112 @@@
return secretsCount, nil
}
+
- func (r *InfisicalSecretReconciler) EnsureEventStream(ctx context.Context, logger logr.Logger, secret *v1alpha1.InfisicalSecret) error {
- if secret == nil {
- return fmt.Errorf("infisicalSecret is nil")
- }
-
- variables := r.getResourceVariables(*secret)
-
++func (r *InfisicalSecretReconciler) EnsureEventStream(ctx context.Context, logger logr.Logger, secret *v1alpha1.InfisicalSecret, variables util.ResourceVariables) error {
+ if !variables.AuthDetails.IsMachineIdentityAuth {
+ return fmt.Errorf("only machine identity is supported for subscriptions")
+ }
+
+ projectSlug := variables.AuthDetails.MachineIdentityScope.ProjectSlug
+ secretsPath := variables.AuthDetails.MachineIdentityScope.SecretsPath
+ envSlug := variables.AuthDetails.MachineIdentityScope.EnvSlug
+
+ infiscalClient := variables.InfisicalClient
+ conn := variables.ServerSentEvents
+
+ token := infiscalClient.Auth().GetAccessToken()
+
+ project, err := util.GetProjectBySlug(token, projectSlug)
+
+ if err != nil {
+ return fmt.Errorf("failed to get project [err=%s]", err)
+ }
+
+ if variables.AuthDetails.MachineIdentityScope.Recursive {
+ secretsPath = fmt.Sprint(secretsPath, "**")
+ }
+
+ conditions := &api.SubProjectEventsRequestCondition{
+ SecretPath: secretsPath,
+ EnvironmentSlug: envSlug,
+ }
+
+ body, err := json.Marshal(api.SubProjectEventsRequest{
+ ProjectID: project.ID,
+ Register: []api.SubProjectEventsRequestRegister{
+ {
+ Event: "secret:create",
+ Conditions: conditions,
+ },
+ {
+ Event: "secret:update",
+ Conditions: conditions,
+ },
+ {
+ Event: "secret:delete",
+ Conditions: conditions,
+ },
+ },
+ })
+
+ if err != nil {
+ return fmt.Errorf("CallSubscribeProjectEvents: unable to marshal body [err=%s]", err)
+ }
+
+ events, errors, err := conn.Subscribe(func() (*http.Request, error) {
+ headers := map[string]string{
+ "User-Agent": api.USER_AGENT_NAME,
+ "Authorization": fmt.Sprint("Bearer ", token),
+ }
+
+ req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("%s/v1/events/subscribe/project-events", api.API_HOST_URL), strings.NewReader(string(body)))
+
+ if err != nil {
+ return nil, err
+ }
+
+ for k, v := range headers {
+ req.Header.Set(k, v)
+ }
+
+ return req, nil
+ })
+
+ if err != nil {
+ return fmt.Errorf("unable to connect to SSE server [err=%s]", err)
+ }
+
+ go func() {
+ outer:
+ for {
+ select {
+ case ev := <-events:
+ logger.Info("Received SSE Event", "event", ev)
- r.SourceCh <- event.GenericEvent{
++ r.SourceCh <- event.TypedGenericEvent[client.Object]{
+ Object: secret,
+ }
+ case err := <-errors:
+ logger.Error(err, "Error occurred")
+ break outer
+ case <-ctx.Done():
+ break outer
+ }
+ }
+ }()
+
+ return nil
+}
+
- func (r *InfisicalSecretReconciler) CloseEventStream(ctx context.Context, logger logr.Logger, secret *secretsv1alpha1.InfisicalSecret) error {
- if secret == nil {
- return fmt.Errorf("infisicalSecret is nil")
- }
-
- variables := r.getResourceVariables(*secret)
-
++func (r *InfisicalSecretReconciler) CloseEventStream(ctx context.Context, logger logr.Logger, variables util.ResourceVariables) error {
+ if !variables.AuthDetails.IsMachineIdentityAuth {
+ return fmt.Errorf("only machine identity is supported for subscriptions")
+ }
+
+ conn := variables.ServerSentEvents
+
+ if _, ok := conn.Get(); ok {
+ conn.Close()
+ }
+
+ return nil
+}
diff --cc k8-operator/internal/util/handler.go
index ca5e82dcc3,0000000000..d1cc86562a
mode 100644,000000..100644
--- a/k8-operator/internal/util/handler.go
+++ b/k8-operator/internal/util/handler.go
@@@ -1,57 -1,0 +1,59 @@@
+package util
+
+import (
++ "context"
+ "math/rand"
+ "time"
+
+ "k8s.io/apimachinery/pkg/types"
+ "k8s.io/client-go/util/workqueue"
++ "sigs.k8s.io/controller-runtime/pkg/client"
+ "sigs.k8s.io/controller-runtime/pkg/event"
+ "sigs.k8s.io/controller-runtime/pkg/reconcile"
+)
+
+// computeMaxJitterDuration returns a random duration between 0 and max.
+// This is useful for introducing jitter to event processing.
+func computeMaxJitterDuration(max time.Duration) (time.Duration, time.Duration) {
+ if max <= 0 {
+ return 0, 0
+ }
+ jitter := time.Duration(rand.Int63n(int64(max)))
+ return max, jitter
+}
+
+// EnqueueDelayedEventHandler enqueues reconcile requests with a random delay (jitter)
+// to spread the load and avoid thundering herd issues.
+type EnqueueDelayedEventHandler struct {
+ Delay time.Duration
+}
+
- func (e *EnqueueDelayedEventHandler) Create(_ event.CreateEvent, _ workqueue.RateLimitingInterface) {
++func (e *EnqueueDelayedEventHandler) Create(_ context.Context, _ event.TypedCreateEvent[client.Object], _ workqueue.TypedRateLimitingInterface[reconcile.Request]) {
+}
+
- func (e *EnqueueDelayedEventHandler) Update(_ event.UpdateEvent, _ workqueue.RateLimitingInterface) {
++func (e *EnqueueDelayedEventHandler) Update(_ context.Context, _ event.TypedUpdateEvent[client.Object], _ workqueue.TypedRateLimitingInterface[reconcile.Request]) {
+}
+
- func (e *EnqueueDelayedEventHandler) Delete(_ event.DeleteEvent, _ workqueue.RateLimitingInterface) {
++func (e *EnqueueDelayedEventHandler) Delete(_ context.Context, _ event.TypedDeleteEvent[client.Object], _ workqueue.TypedRateLimitingInterface[reconcile.Request]) {
+}
+
- func (e *EnqueueDelayedEventHandler) Generic(evt event.GenericEvent, q workqueue.RateLimitingInterface) {
++func (e *EnqueueDelayedEventHandler) Generic(_ context.Context, evt event.TypedGenericEvent[client.Object], q workqueue.TypedRateLimitingInterface[reconcile.Request]) {
+ if evt.Object == nil {
+ return
+ }
+
+ req := reconcile.Request{
+ NamespacedName: types.NamespacedName{
+ Namespace: evt.Object.GetNamespace(),
+ Name: evt.Object.GetName(),
+ },
+ }
+
+ _, delay := computeMaxJitterDuration(e.Delay)
+
+ if delay > 0 {
+ q.AddAfter(req, delay)
+ } else {
+ q.Add(req)
+ }
+}
diff --cc k8-operator/internal/util/sse/client.go
index f118611a62,0000000000..f118611a62
mode 100644,000000..100644
--- a/k8-operator/internal/util/sse/client.go
+++ b/k8-operator/internal/util/sse/client.go
diff --cc k8-operator/internal/util/sse/sse.go
index ec4a5dbce7,0000000000..ec4a5dbce7
mode 100644,000000..100644
--- a/k8-operator/internal/util/sse/sse.go
+++ b/k8-operator/internal/util/sse/sse.go