Skip to content

Commit

Permalink
Merge pull request from GHSA-9766-5277-j5hr
Browse files Browse the repository at this point in the history
* fix: Enable Redis authentication in the default installation

Signed-off-by: May Zhang <[email protected]>

* chore: fix git_test unit test

Signed-off-by: Leonardo Luz Almeida <[email protected]>

---------

Signed-off-by: May Zhang <[email protected]>
Signed-off-by: Leonardo Luz Almeida <[email protected]>
Co-authored-by: May Zhang <[email protected]>
  • Loading branch information
leoluz and mayzhang2000 authored May 21, 2024
1 parent c227d22 commit 35a7d6c
Show file tree
Hide file tree
Showing 26 changed files with 887 additions and 116 deletions.
1 change: 1 addition & 0 deletions cmd/argocd/commands/admin/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ func NewAdminCommand() *cobra.Command {
command.AddCommand(NewDashboardCommand())
command.AddCommand(NewNotificationsCommand())
command.AddCommand(NewInitialPasswordCommand())
command.AddCommand(NewRedisInitialPasswordCommand())

command.Flags().StringVar(&cmdutil.LogFormat, "logformat", "text", "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", "info", "Set the logging level. One of: debug|info|warn|error")
Expand Down
98 changes: 98 additions & 0 deletions cmd/argocd/commands/admin/redis_initial_password.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package admin

import (
"context"
"crypto/rand"
"fmt"
"math/big"

"github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/util/cli"
apierr "k8s.io/apimachinery/pkg/api/errors"

"github.com/argoproj/argo-cd/v2/util/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"

"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
)

const defaulRedisInitialPasswordSecretName = "argocd-redis"
const defaultResisInitialPasswordKey = "auth"

func generateRandomPassword() (string, error) {
const initialPasswordLength = 16
const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"
randBytes := make([]byte, initialPasswordLength)
for i := 0; i < initialPasswordLength; i++ {
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
if err != nil {
return "", err
}
randBytes[i] = letters[num.Int64()]
}
initialPassword := string(randBytes)
return initialPassword, nil
}

// NewRedisInitialPasswordCommand defines a new command to ensure Argo CD Redis password secret exists.
func NewRedisInitialPasswordCommand() *cobra.Command {
var (
clientConfig clientcmd.ClientConfig
)
var command = cobra.Command{
Use: "redis-initial-password",
Short: "Ensure the Redis password exists, creating a new one if necessary.",
Run: func(c *cobra.Command, args []string) {
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)

redisInitialPasswordSecretName := defaulRedisInitialPasswordSecretName
redisInitialPasswordKey := defaultResisInitialPasswordKey
fmt.Printf("Checking for initial Redis password in secret %s/%s at key %s. \n", namespace, redisInitialPasswordSecretName, redisInitialPasswordKey)

config, err := clientConfig.ClientConfig()
errors.CheckError(err)
errors.CheckError(v1alpha1.SetK8SConfigDefaults(config))

kubeClientset := kubernetes.NewForConfigOrDie(config)

randomPassword, err := generateRandomPassword()
errors.CheckError(err)

data := map[string][]byte{
redisInitialPasswordKey: []byte(randomPassword),
}
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: redisInitialPasswordSecretName,
Namespace: namespace,
},
Data: data,
Type: corev1.SecretTypeOpaque,
}
_, err = kubeClientset.CoreV1().Secrets(namespace).Create(context.Background(), secret, metav1.CreateOptions{})
if err != nil && !apierr.IsAlreadyExists(err) {
errors.CheckError(err)
}

fmt.Println("Argo CD Redis secret state confirmed: secret name argocd-redis.")
secret, err = kubeClientset.CoreV1().Secrets(namespace).Get(context.Background(), redisInitialPasswordSecretName, v1.GetOptions{})
errors.CheckError(err)

if _, ok := secret.Data[redisInitialPasswordKey]; ok {
fmt.Println("Password secret is configured properly.")
} else {
err := fmt.Errorf("key %s doesn't exist in secret %s. \n", redisInitialPasswordKey, redisInitialPasswordSecretName)
errors.CheckError(err)
}
},
}

clientConfig = cli.AddKubectlFlagsToCmd(&command)

return &command
}
42 changes: 42 additions & 0 deletions docs/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,3 +259,45 @@ The most common instance of this error is with `env:` fields for `containers`.

!!! note "Dynamic applications"
It's possible that your application is being generated by a tool in which case the duplication might not be evident within the scope of a single file. If you have trouble debugging this problem, consider filing a ticket to the owner of the generator tool asking them to improve its validation and error reporting.

## How to rotate Redis secret?
* Delete `argocd-redis` secret in the namespace where Argo CD is installed.
```bash
kubectl delete secret argocd-redis -n <argocd namesapce>
```
* If you are running Redis in HA mode, restart Redis in HA.
```bash
kubectl rollout restart deployment argocd-redis-ha-haproxy
kubectl rollout restart statefulset argocd-redis-ha-server
```
* If you are running Redis in non-HA mode, restart Redis.
```bash
kubectl rollout restart deployment argocd-redis
```
* Restart other components.
```bash
kubectl rollout restart deployment argocd-server argocd-repo-server
kubectl rollout restart statefulset argocd-application-controller
```

## How to turn off Redis auth if users really want to?

Argo CD default installation is now configured automatically enable Redis authentication.
If for some reason authenticated Redis does not work for you and you want to use non-authenticated Redis, here are the steps:

* You need to have your own Redis installation.
* Configure Argo CD to use your own Redis instance. See this [doc](https://argo-cd.readthedocs.io/en/stable/operator-manual/argocd-cmd-params-cm-yaml/) for the Argo CD configuration.
* If you already installed Redis shipped with Argo CD, you also need to clean up the existing components:
* When HA Redis is used:
* kubectl delete deployment argocd-redis-ha-haproxy
* kubectl delete statefulset argocd-redis-ha-server
* When non-HA Redis is used:
* kubectl delete deployment argocd-redis
* Remove environment variable `REDIS_PASSWORD` from the following manifests
* Deployment: argocd-repo-server:
* Deployment: argocd-server
* StatefulSet: argocd-application-controller

## How do I provide my own Redis credentials?
The Redis password is stored in Kubernetes secret `argocd-redis` with key `auth` in the namespace where Argo CD is installed.
You can config your secret provider to generate Kubernetes secret accordingly.
3 changes: 3 additions & 0 deletions docs/getting_started.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ Do one of:

Use `argocd login --core` to [configure](./user-guide/commands/argocd_login.md) CLI access and skip steps 3-5.

!!! note
This default installation for Redis is using password authentication. The Redis password is stored in Kubernetes secret `argocd-redis` with key `auth` in the namespace where Argo CD is installed.

## 2. Download Argo CD CLI

Download the latest Argo CD version from [https://github.com/argoproj/argo-cd/releases/latest](https://github.com/argoproj/argo-cd/releases/latest). More detailed installation instructions can be found via the [CLI installation documentation](cli_installation.md).
Expand Down
1 change: 1 addition & 0 deletions docs/user-guide/commands/argocd_admin.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ argocd admin [flags]
* [argocd admin initial-password](argocd_admin_initial-password.md) - Prints initial password to log in to Argo CD for the first time
* [argocd admin notifications](argocd_admin_notifications.md) - Set of CLI commands that helps manage notifications settings
* [argocd admin proj](argocd_admin_proj.md) - Manage projects configuration
* [argocd admin redis-initial-password](argocd_admin_redis-initial-password.md) - Ensure the Redis password exists, creating a new one if necessary.
* [argocd admin repo](argocd_admin_repo.md) - Manage repositories configuration
* [argocd admin settings](argocd_admin_settings.md) - Provides set of commands for settings validation and troubleshooting

67 changes: 67 additions & 0 deletions docs/user-guide/commands/argocd_admin_redis-initial-password.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# `argocd admin redis-initial-password` Command Reference

## argocd admin redis-initial-password

Ensure the Redis password exists, creating a new one if necessary.

```
argocd admin redis-initial-password [flags]
```

### Options

```
--as string Username to impersonate for the operation
--as-group stringArray Group to impersonate for the operation, this flag can be repeated to specify multiple groups.
--as-uid string UID to impersonate for the operation
--certificate-authority string Path to a cert file for the certificate authority
--client-certificate string Path to a client certificate file for TLS
--client-key string Path to a client key file for TLS
--cluster string The name of the kubeconfig cluster to use
--context string The name of the kubeconfig context to use
--disable-compression If true, opt-out of response compression for all requests to the server
-h, --help help for redis-initial-password
--insecure-skip-tls-verify If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure
--kubeconfig string Path to a kube config. Only required if out-of-cluster
-n, --namespace string If present, the namespace scope for this CLI request
--password string Password for basic authentication to the API server
--proxy-url string If provided, this URL will be used to connect via proxy
--request-timeout string The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests. (default "0")
--server string The address and port of the Kubernetes API server
--tls-server-name string If provided, this name will be used to validate server certificate. If this is not provided, hostname used to contact the server is used.
--token string Bearer token for authentication to the API server
--user string The name of the kubeconfig user to use
--username string Username for basic authentication to the API server
```

### Options inherited from parent commands

```
--auth-token string Authentication token
--client-crt string Client certificate file
--client-crt-key string Client certificate key file
--config string Path to Argo CD config (default "/home/user/.config/argocd/config")
--controller-name string Name of the Argo CD Application controller; set this or the ARGOCD_APPLICATION_CONTROLLER_NAME environment variable when the controller's name label differs from the default, for example when installing via the Helm chart (default "argocd-application-controller")
--core If set to true then CLI talks directly to Kubernetes instead of talking to Argo CD API server
--grpc-web Enables gRPC-web protocol. Useful if Argo CD server is behind proxy which does not support HTTP2.
--grpc-web-root-path string Enables gRPC-web protocol. Useful if Argo CD server is behind proxy which does not support HTTP2. Set web root.
-H, --header strings Sets additional header to all requests made by Argo CD CLI. (Can be repeated multiple times to add multiple headers, also supports comma separated headers)
--http-retry-max int Maximum number of retries to establish http connection to Argo CD server
--insecure Skip server certificate and domain verification
--kube-context string Directs the command to the given kube-context
--logformat string Set the logging format. One of: text|json (default "text")
--loglevel string Set the logging level. One of: debug|info|warn|error (default "info")
--plaintext Disable TLS
--port-forward Connect to a random argocd-server port using port forwarding
--port-forward-namespace string Namespace name which should be used for port forwarding
--redis-haproxy-name string Name of the Redis HA Proxy; set this or the ARGOCD_REDIS_HAPROXY_NAME environment variable when the HA Proxy's name label differs from the default, for example when installing via the Helm chart (default "argocd-redis-ha-haproxy")
--redis-name string Name of the Redis deployment; set this or the ARGOCD_REDIS_NAME environment variable when the Redis's name label differs from the default, for example when installing via the Helm chart (default "argocd-redis")
--repo-server-name string Name of the Argo CD Repo server; set this or the ARGOCD_REPO_SERVER_NAME environment variable when the server's name label differs from the default, for example when installing via the Helm chart (default "argocd-repo-server")
--server-crt string Server certificate file
--server-name string Name of the Argo CD API server; set this or the ARGOCD_SERVER_NAME environment variable when the server's name label differs from the default, for example when installing via the Helm chart (default "argocd-server")
```

### SEE ALSO

* [argocd admin](argocd_admin.md) - Contains a set of commands useful for Argo CD administrators and requires direct Kubernetes access

Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ spec:
- args:
- /usr/local/bin/argocd-application-controller
env:
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
key: auth
name: argocd-redis
- name: ARGOCD_CONTROLLER_REPLICAS
value: "1"
- name: ARGOCD_RECONCILIATION_TIMEOUT
Expand Down
24 changes: 24 additions & 0 deletions manifests/base/redis/argocd-redis-deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,23 @@ spec:
labels:
app.kubernetes.io/name: argocd-redis
spec:
initContainers:
- command:
- argocd
- admin
- redis-initial-password
image: quay.io/argoproj/argocd:latest
imagePullPolicy: IfNotPresent
name: secret-init
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
readOnlyRootFilesystem: true
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
securityContext:
runAsNonRoot: true
runAsUser: 999
Expand All @@ -30,6 +47,13 @@ spec:
- ""
- "--appendonly"
- "no"
- --requirepass $(REDIS_PASSWORD)
env:
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
key: auth
name: argocd-redis
ports:
- containerPort: 6379
securityContext:
Expand Down
23 changes: 23 additions & 0 deletions manifests/base/redis/argocd-redis-role.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
labels:
app.kubernetes.io/component: redis
app.kubernetes.io/name: argocd-redis
app.kubernetes.io/part-of: argocd
name: argocd-redis
rules:
- apiGroups:
- ""
resources:
- secrets
resourceNames:
- argocd-redis
verbs:
- get
- apiGroups:
- ""
resources:
- secrets
verbs:
- create
15 changes: 15 additions & 0 deletions manifests/base/redis/argocd-redis-rolebinding.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
labels:
app.kubernetes.io/component: redis
app.kubernetes.io/name: argocd-redis
app.kubernetes.io/part-of: argocd
name: argocd-redis
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: argocd-redis
subjects:
- kind: ServiceAccount
name: argocd-redis
2 changes: 2 additions & 0 deletions manifests/base/redis/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ resources:
- argocd-redis-sa.yaml
- argocd-redis-service.yaml
- argocd-redis-network-policy.yaml
- argocd-redis-role.yaml
- argocd-redis-rolebinding.yaml
5 changes: 5 additions & 0 deletions manifests/base/repo-server/argocd-repo-server-deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ spec:
args:
- /usr/local/bin/argocd-repo-server
env:
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
key: auth
name: argocd-redis
- name: ARGOCD_RECONCILIATION_TIMEOUT
valueFrom:
configMapKeyRef:
Expand Down
5 changes: 5 additions & 0 deletions manifests/base/server/argocd-server-deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ spec:
args:
- /usr/local/bin/argocd-server
env:
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
key: auth
name: argocd-redis
- name: ARGOCD_SERVER_INSECURE
valueFrom:
configMapKeyRef:
Expand Down
Loading

0 comments on commit 35a7d6c

Please sign in to comment.