ceph: add vault kms support for osd encryption
When the Ceph cluster runs on PVC and the OSDs are encrypted we can store LUKS's Key Encryption Key inside a Key Management System. Today, Rook only supports HashiCorp Vault: https://www.vaultproject.io/ The CephCluster has now a new "security" field which will plug onto the KMS. Here is an example: security: kms: tokenSecretName: <name of the secret containing a Vault token, used to authenticate> connectionDetails: < a map of strings containing connection information> Refer to the ceph-cluster-crd documentation to lear more. Closes: https://github.com/rook/rook/issues/6105 Signed-off-by: Sébastien Han <seb@redhat.com>
This commit is contained in:
1 parent
1c562512e1
commit
ea1d71cbfb
51 files changed
+3318
-194
No files matched your search
@@ -1,8 +1,8 @@
|
||||
name: Canary integration test
|
||||
name: Canary integration tests
|
||||
on: [pull_request]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
canary:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
@@ -14,10 +14,16 @@ jobs:
|
||||
go-version: 1.15
|
||||
|
||||
- name: setup minikube
|
||||
uses: opsgang/ga-setup-minikube@v0.1.1
|
||||
uses: manusa/actions-setup-minikube@v2.0.1
|
||||
with:
|
||||
minikube-version: 1.13.0
|
||||
k8s-version: 1.19.2
|
||||
minikube version: 'v1.13.1'
|
||||
kubernetes version: 'v1.19.2'
|
||||
start args: --memory 6g --cpus=2
|
||||
|
||||
- name: check k8s cluster status
|
||||
run: |
|
||||
kubectl cluster-info
|
||||
kubectl get pods -n kube-system
|
||||
|
||||
- name: use local disk
|
||||
run: |
|
||||
@@ -27,20 +33,8 @@ jobs:
|
||||
sudo wipefs --all --force /dev/$(lsblk|awk '/14G/ {print $1}'| head -1)1
|
||||
sudo lsblk
|
||||
|
||||
- name: configure minikube
|
||||
run: |
|
||||
minikube config set vm-driver docker
|
||||
minikube config set kubernetes-version v1.19.2
|
||||
minikube start --memory 6g --cpus=2
|
||||
minikube update-context
|
||||
kubectl cluster-info
|
||||
kubectl get pods -n kube-system
|
||||
# minikube docker driver uses docker in docker and the minikube container does not have the lvm binary so let's copy it from the host inside the minikube container
|
||||
docker cp /sbin/lvm $(docker ps|awk '/minikube/ {print $1}'):/sbin/lvm
|
||||
|
||||
- name: build rook
|
||||
run: |
|
||||
eval $(minikube docker-env -p minikube --shell=$SHELL)
|
||||
# set VERSION to a dummy value since Jenkins normally sets it for us. Do this to make Helm happy and not fail with "Error: Invalid Semantic Version"
|
||||
GOPATH=$(go env GOPATH) make clean && make -j$nproc IMAGES='ceph' VERSION=0 build
|
||||
docker images
|
||||
@@ -61,11 +55,11 @@ jobs:
|
||||
|
||||
- name: wait for prepare pod
|
||||
run: |
|
||||
timeout 300 sh -c 'until kubectl -n rook-ceph logs -f job/rook-ceph-osd-prepare-minikube; do sleep 5; done'
|
||||
timeout 300 sh -c 'until kubectl -n rook-ceph logs -f $(kubectl -n rook-ceph get pod -l app=rook-ceph-osd-prepare -o jsonpath='{.items[*].metadata.name}'); do sleep 5; done'
|
||||
|
||||
- name: wait for ceph to be ready
|
||||
run: |
|
||||
hack/validate_cluster.sh
|
||||
tests/scripts/validate_cluster.sh
|
||||
kubectl -n rook-ceph get pods
|
||||
|
||||
- name: test external script create-external-cluster-resources.py
|
||||
@@ -76,3 +70,148 @@ jobs:
|
||||
# copy the test file
|
||||
# execute the test file
|
||||
|
||||
encryption-pvc:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: setup golang
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15
|
||||
|
||||
- name: setup minikube
|
||||
uses: manusa/actions-setup-minikube@v2.0.1
|
||||
with:
|
||||
minikube version: 'v1.13.1'
|
||||
kubernetes version: 'v1.19.2'
|
||||
start args: --memory 6g --cpus=2
|
||||
|
||||
- name: check k8s cluster status
|
||||
run: |
|
||||
kubectl cluster-info
|
||||
kubectl get pods -n kube-system
|
||||
|
||||
- name: install yq
|
||||
run: |
|
||||
sudo wget https://github.com/mikefarah/yq/releases/download/3.4.1/yq_linux_amd64 -O /usr/bin/yq
|
||||
sudo chmod +x /usr/bin/yq
|
||||
|
||||
- name: use local disk
|
||||
run: |
|
||||
sudo dmsetup version||true
|
||||
sudo swapoff --all --verbose
|
||||
sudo umount /mnt
|
||||
# search for the device since it keeps changing between sda and sdb
|
||||
sudo wipefs --all --force /dev/$(lsblk|awk '/14G/ {print $1}'| head -1)1
|
||||
sudo lsblk
|
||||
|
||||
- name: build rook
|
||||
run: |
|
||||
# set VERSION to a dummy value since Jenkins normally sets it for us. Do this to make Helm happy and not fail with "Error: Invalid Semantic Version"
|
||||
GOPATH=$(go env GOPATH) make clean && make -j$nproc IMAGES='ceph' VERSION=0 build
|
||||
docker images
|
||||
docker tag $(docker images|awk '/build-/ {print $1}') rook/ceph:master
|
||||
|
||||
- name: rook prerequisites
|
||||
run: |
|
||||
tests/scripts/localPathPV.sh $(lsblk --paths|awk '/14G/ {print $1}'| head -1)
|
||||
kubectl create -f cluster/examples/kubernetes/ceph/common.yaml
|
||||
|
||||
- name: deploy rook
|
||||
run: |
|
||||
kubectl create -f cluster/examples/kubernetes/ceph/operator.yaml
|
||||
kubectl create -f tests/manifests/test-cluster-on-pvc-encrypted.yaml
|
||||
kubectl create -f cluster/examples/kubernetes/ceph/toolbox.yaml
|
||||
|
||||
- name: wait for prepare pod
|
||||
run: |
|
||||
timeout 180 sh -c 'until kubectl -n rook-ceph logs -f $(kubectl -n rook-ceph get pod -l app=rook-ceph-osd-prepare -o jsonpath='{.items[*].metadata.name}'); do sleep 5; done'||true
|
||||
timeout 60 sh -c 'until kubectl -n rook-ceph logs $(kubectl -n rook-ceph get pod -l app=rook-ceph-osd,ceph_daemon_id=0 -o jsonpath='{.items[*].metadata.name}') --all-containers; do echo "waiting for osd container" && sleep 1; done'||true
|
||||
kubectl -n rook-ceph describe deploy/rook-ceph-osd-0||true
|
||||
|
||||
- name: wait for ceph to be ready
|
||||
run: |
|
||||
tests/scripts/validate_cluster.sh osd
|
||||
kubectl -n rook-ceph get pods
|
||||
kubectl -n rook-ceph get secrets
|
||||
sudo lsblk
|
||||
|
||||
encryption-pvc-kms-vault-token-auth:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: setup golang
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15
|
||||
|
||||
- name: setup minikube
|
||||
uses: manusa/actions-setup-minikube@v2.0.1
|
||||
with:
|
||||
minikube version: 'v1.13.1'
|
||||
kubernetes version: 'v1.19.2'
|
||||
start args: --memory 6g --cpus=2
|
||||
|
||||
- name: check k8s cluster status
|
||||
run: |
|
||||
kubectl cluster-info
|
||||
kubectl get pods -n kube-system
|
||||
|
||||
- name: install yq
|
||||
run: |
|
||||
sudo wget https://github.com/mikefarah/yq/releases/download/3.4.1/yq_linux_amd64 -O /usr/bin/yq
|
||||
sudo chmod +x /usr/bin/yq
|
||||
|
||||
- name: use local disk
|
||||
run: |
|
||||
sudo dmsetup version||true
|
||||
sudo swapoff --all --verbose
|
||||
sudo umount /mnt
|
||||
# search for the device since it keeps changing between sda and sdb
|
||||
sudo wipefs --all --force /dev/$(lsblk|awk '/14G/ {print $1}'| head -1)1
|
||||
sudo lsblk
|
||||
|
||||
- name: build rook
|
||||
run: |
|
||||
# set VERSION to a dummy value since Jenkins normally sets it for us. Do this to make Helm happy and not fail with "Error: Invalid Semantic Version"
|
||||
GOPATH=$(go env GOPATH) make clean && make -j$nproc IMAGES='ceph' VERSION=0 build
|
||||
docker images
|
||||
docker tag $(docker images|awk '/build-/ {print $1}') rook/ceph:master
|
||||
|
||||
- name: rook prereq
|
||||
run: |
|
||||
tests/scripts/localPathPV.sh $(lsblk --paths|awk '/14G/ {print $1}'| head -1)
|
||||
kubectl create -f cluster/examples/kubernetes/ceph/common.yaml
|
||||
|
||||
- name: deploy vault
|
||||
run: |
|
||||
tests/scripts/deploy-validate-vault.sh deploy
|
||||
|
||||
- name: deploy rook
|
||||
run: |
|
||||
kubectl create -f cluster/examples/kubernetes/ceph/operator.yaml
|
||||
cat tests/manifests/test-kms-vault.yaml >> tests/manifests/test-cluster-on-pvc-encrypted.yaml
|
||||
yq merge --inplace --arrays append tests/manifests/test-cluster-on-pvc-encrypted.yaml tests/manifests/test-kms-vault-spec.yaml
|
||||
kubectl create -f tests/manifests/test-cluster-on-pvc-encrypted.yaml
|
||||
kubectl create -f cluster/examples/kubernetes/ceph/toolbox.yaml
|
||||
|
||||
- name: wait for prepare pod
|
||||
run: |
|
||||
timeout 180 sh -c 'until kubectl -n rook-ceph logs -f $(kubectl -n rook-ceph get pod -l app=rook-ceph-osd-prepare -o jsonpath='{.items[*].metadata.name}'); do sleep 5; done'||true
|
||||
timeout 60 sh -c 'until kubectl -n rook-ceph logs $(kubectl -n rook-ceph get pod -l app=rook-ceph-osd,ceph_daemon_id=0 -o jsonpath='{.items[*].metadata.name}') --all-containers; do echo "waiting for osd container" && sleep 1; done'||true
|
||||
kubectl -n rook-ceph describe job/$(kubectl -n rook-ceph get pod -l app=rook-ceph-osd-prepare -o jsonpath='{.items[*].metadata.name}')||true
|
||||
kubectl -n rook-ceph describe deploy/rook-ceph-osd-0||true
|
||||
|
||||
- name: wait for ceph to be ready
|
||||
run: |
|
||||
tests/scripts/validate_cluster.sh osd
|
||||
kubectl -n rook-ceph get pods
|
||||
|
||||
- name: validate vault
|
||||
run: |
|
||||
tests/scripts/deploy-validate-vault.sh validate
|
||||
sudo lsblk
|
||||
@@ -16,5 +16,5 @@ jobs:
|
||||
run: GOPATH=$(go env GOPATH) make codegen
|
||||
|
||||
- name: validate codegen
|
||||
run: hack/validate_modified_files.sh codegen
|
||||
run: tests/scripts/validate_modified_files.sh codegen
|
||||
|
||||
@@ -16,5 +16,5 @@ jobs:
|
||||
run: GOPATH=$(go env GOPATH) make -j $(nproc) mod.check
|
||||
|
||||
- name: validate modcheck
|
||||
run: hack/validate_modified_files.sh modcheck
|
||||
run: tests/scripts/validate_modified_files.sh modcheck
|
||||
|
||||
@@ -156,6 +156,7 @@ For more details on the mons and when to choose a number other than `3`, see the
|
||||
* `machineDisruptionBudgetNamespace`: the namespace in which to watch the MachineDisruptionBudgets.
|
||||
* `removeOSDsIfOutAndSafeToRemove`: If `true` the operator will remove the OSDs that are down and whose data has been restored to other OSDs. In Ceph terms, the OSDs are `out` and `safe-to-destroy` when they are removed.
|
||||
* `cleanupPolicy`: [cleanup policy settings](#cleanup-policy)
|
||||
* `security`: [security settings](#security)
|
||||
|
||||
### Ceph container images
|
||||
|
||||
@@ -320,7 +321,7 @@ The following are the settings for Storage Class Device Sets which can be config
|
||||
However, if there are more OSDs than nodes, this anti-affinity will not be effective. Another placement scheme to consider is to add labels to the nodes in such a way that the OSDs can be grouped on those nodes, create multiple storageClassDeviceSets, and add node affinity to each of the device sets that will place the OSDs in those sets of nodes.
|
||||
|
||||
* `preparePlacement`: The placement criteria for the preparation of the OSD devices. Creating OSDs is a two-step process and the prepare job may require different placement than the OSD daemons. If the `preparePlacement` is not specified, the `placement` will instead be applied for consistent placement for the OSD prepare jobs and OSD deployments. The `preparePlacement` is only useful for `portable` OSDs in the device sets. OSDs that are not portable will be tied to the host where the OSD prepare job initially runs.
|
||||
* For example, provisioning may require topology spread constraints across zones, but the OSD daemons may require constraints across hosts within the zones.
|
||||
* For example, provisioning may require topology spread constraints across zones, but the OSD daemons may require constraints across hosts within the zones.
|
||||
* `portable`: If `true`, the OSDs will be allowed to move between nodes during failover. This requires a storage class that supports portability (e.g. `aws-ebs`, but not the local storage provisioner). If `false`, the OSDs will be assigned to a node permanently. Rook will configure Ceph's CRUSH map to support the portability.
|
||||
* `tuneDeviceClass`: For example, Ceph cannot detect AWS volumes as HDDs from the storage class "gp2", so you can improve Ceph performance by setting this to true.
|
||||
* `tuneFastDeviceClass`: For example, Ceph cannot detect Azure disks as SSDs from the storage class "managed-premium", so you can improve Ceph performance by setting this to true..
|
||||
@@ -367,7 +368,7 @@ application.
|
||||
|
||||
Ceph supports adding devices as OSDs by Ceph Drive Group definitions in later versions of Ceph
|
||||
Octopus (v15.2.5+).
|
||||
See Ceph Drive Group docs for more info: https://docs.ceph.com/docs/master/cephadm/drivegroups/.
|
||||
See Ceph Drive Group docs for more [info](https://docs.ceph.com/docs/master/cephadm/drivegroups/).
|
||||
Drive Groups cannot be used to provision OSDs on PVCs.
|
||||
|
||||
> **IMPORTANT:** When managing a Rook/Ceph cluster's OSD layouts with Drive Groups, the `storage`
|
||||
@@ -378,6 +379,7 @@ Drive Groups cannot be used to provision OSDs on PVCs.
|
||||
> OSDs with Drive Groups on new Rook-Ceph clusters.
|
||||
|
||||
A Drive Group is defined by a name, a Ceph Drive Group spec, and a Rook placement
|
||||
|
||||
* `name`: A name for the Drive Group.
|
||||
* `spec`: The Ceph Drive group spec. Some components of the spec are treated differently in the
|
||||
context of Rook as noted below:
|
||||
@@ -1139,7 +1141,7 @@ If the previous section has not been completed, the Rook Operator will still ack
|
||||
|
||||
> **WARNING**: If no cluster is managed by the current Rook Operator, you need to inject `common.yaml`, then modify `cluster-external.yaml` and specify `rook-ceph` as `namespace`.
|
||||
|
||||
If this is successfull you will see the CepCluster status as connected.
|
||||
If this is successful you will see the CepCluster status as connected.
|
||||
|
||||
```console
|
||||
kubectl get CephCluster -n rook-ceph-external
|
||||
@@ -1252,3 +1254,125 @@ Nothing will happen until the deletion of the CR is requested, so this can still
|
||||
However, all new configuration by the operator will be blocked with this cleanup policy enabled.
|
||||
|
||||
Rook waits for the deletion of PVs provisioned using the cephCluster before proceeding to delete the cephCluster. To force deletion of the cephCluster without waiting for the PVs to be deleted, you can set the allowUninstallWithVolumes to true under spec.CleanupPolicy.
|
||||
|
||||
### Security
|
||||
|
||||
Rook has the ability to encrypt OSDs of clusters running on PVC via the flag (`encrypted: true`) in your `storageClassDeviceSets` [template](#pvc-based-cluster).
|
||||
By default, the Key Encryption Keys (also known as Data Encryption Keys) are stored in a Kubernetes Secret.
|
||||
|
||||
However, if a Key Management System exists Rook is capable of using it. HashiCorp Vault is the only KMS currently supported by Rook.
|
||||
Please refer to the next section.
|
||||
|
||||
The `security` section contains settings related to encryption of the cluster.
|
||||
|
||||
* `security`:
|
||||
* `kms`: Key Management System settings
|
||||
* `connectionDetails`: the list of parameters representing kms connection details
|
||||
* `tokenSecretName`: the name of the Kubernetes Secret containing the kms authentication token
|
||||
|
||||
#### Vault KMS
|
||||
|
||||
In order for Rook to connect to Vault, you must configure the following in your `CephCluster` template:
|
||||
|
||||
```yaml
|
||||
security:
|
||||
kms:
|
||||
# name of the k8s config map containing all the kms connection details
|
||||
connectionDetails:
|
||||
KMS_PROVIDER: vault
|
||||
VAULT_ADDR: https://vault.default.svc.cluster.local:8200
|
||||
VAULT_BACKEND_PATH: rook
|
||||
# name of the k8s secret containing the kms authentication token
|
||||
tokenSecretName: rook-vault-token
|
||||
```
|
||||
|
||||
Note: Rook supports **all** the Vault [environment variables](https://www.vaultproject.io/docs/commands#environment-variables).
|
||||
|
||||
The Kubernetes Secret `rook-vault-token` should contain:
|
||||
|
||||
```yaml
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: rook-vault-token
|
||||
namespace: rook-ceph
|
||||
data:
|
||||
token: <TOKEN> # base64 of a token to connect to Vault, for example: cy5GWXpsbzAyY2duVGVoRjhkWG5Bb3EyWjkK
|
||||
```
|
||||
|
||||
As part of the token, here is an example of a policy that can be used:
|
||||
|
||||
```hcl
|
||||
path "rook/*" {
|
||||
capabilities = ["create", "read", "update", "delete", "list"]
|
||||
}
|
||||
path "sys/mounts" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
```
|
||||
|
||||
You can write the policy like so and then create a token:
|
||||
|
||||
```console
|
||||
vault policy write ocs /tmp/rook.hcl
|
||||
vault token create -policy=rook
|
||||
Key Value
|
||||
--- -----
|
||||
token s.FYzlo02cgnTehF8dXnAoq2Z9
|
||||
token_accessor oMo7sAXQKbYtxU4HtO8k3pko
|
||||
token_duration 768h
|
||||
token_renewable true
|
||||
token_policies ["default" "rook"]
|
||||
identity_policies []
|
||||
policies ["default" "rook"]
|
||||
```
|
||||
|
||||
In this example the backend path named `rook` is used it must be enabled in Vault with the following:
|
||||
|
||||
```console
|
||||
vault secrets enable -path=rook kv
|
||||
```
|
||||
|
||||
If a different path is used, the `VAULT_BACKEND_PATH` key in `connectionDetails` must be changed.
|
||||
|
||||
Currently the token-based authentication is the only supported method.
|
||||
Later Rook is planning on supporting the [Vault Kubernetes native authentication](https://www.vaultproject.io/docs/auth/kubernetes).
|
||||
|
||||
##### TLS configuration
|
||||
|
||||
This is an advanced but recommended configuration for production deployments, in this case the `vault-connection-details` will look like:
|
||||
|
||||
```yaml
|
||||
security:
|
||||
kms:
|
||||
# name of the k8s config map containing all the kms connection details
|
||||
connectionDetails:
|
||||
KMS_PROVIDER: vault
|
||||
VAULT_ADDR: https://vault.default.svc.cluster.local:8200
|
||||
VAULT_CACERT: <name of the k8s secret containing the PEM-encoded CA certificate>
|
||||
VAULT_CLIENT_CERT: <name of the k8s secret containing the PEM-encoded client certificate>
|
||||
VAULT_CLIENT_KEY: <name of the k8s secret containing the PEM-encoded private key>
|
||||
# name of the k8s secret containing the kms authentication token
|
||||
tokenSecretName: rook-vault-token
|
||||
```
|
||||
|
||||
Each secret keys are expected to be:
|
||||
|
||||
* VAULT_CACERT: `cert`
|
||||
* VAULT_CLIENT_CERT: `cert`
|
||||
* VAULT_CLIENT_KEY: `key`
|
||||
|
||||
For instance `VAULT_CACERT` Secret named `vault-tls-ca-certificate` will look like:
|
||||
|
||||
```yaml
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: vault-tls-ca-certificate
|
||||
namespace: rook-ceph
|
||||
data:
|
||||
cert: <PEM base64 encoded CA certificate>
|
||||
```
|
||||
|
||||
Note: if you are using self-signed certificates (not known/approved by a proper CA) you must pass `VAULT_SKIP_VERIFY: true`.
|
||||
Communications will remain encrypted but the validity of the certificate will not be verified.
|
||||
@@ -20,3 +20,4 @@ v1.5...
|
||||
* Ceph Block Pool: add mirroring support
|
||||
* Ceph Block Pool: add `replicasPerFailureDomain` to set the number of replica in a failure domain ([#5591](https://github.com/rook/rook/issues/5591))
|
||||
* Ceph Cluster: export the storage capacity of the ceph cluster ([#6475](https://github.com/rook/rook/pull/6475))
|
||||
* Ceph Cluster: add encryption support with Key Management Service
|
||||
@@ -1452,6 +1452,16 @@ spec:
|
||||
iteration:
|
||||
type: integer
|
||||
format: int32
|
||||
security:
|
||||
properties:
|
||||
kms:
|
||||
properties:
|
||||
connectionDetails:
|
||||
type: object
|
||||
nullable: true
|
||||
x-kubernetes-preserve-unknown-fields: true
|
||||
tokenSecretName:
|
||||
type: string
|
||||
additionalPrinterColumns:
|
||||
- name: DataDirHostPath
|
||||
type: string
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
# kubectl create -f operator.yaml
|
||||
# kubectl create -f cluster-on-pvc.yaml
|
||||
#################################################################################################################
|
||||
|
||||
apiVersion: ceph.rook.io/v1
|
||||
kind: CephCluster
|
||||
metadata:
|
||||
@@ -172,3 +171,26 @@ spec:
|
||||
osdMaintenanceTimeout: 30
|
||||
manageMachineDisruptionBudgets: false
|
||||
machineDisruptionBudgetNamespace: openshift-machine-api
|
||||
# security oriented settings
|
||||
# security:
|
||||
# To enable the KMS configuration properly don't forget to uncomment the Secret at the end of the file
|
||||
# kms:
|
||||
# # name of the config map containing all the kms connection details
|
||||
# connectionDetails:
|
||||
#KMS_PROVIDER: "vault"
|
||||
#VAULT_ADDR: VAULT_ADDR_CHANGE_ME # e,g: https://vault.my-domain.com:8200
|
||||
#VAULT_BACKEND_PATH: "rook"
|
||||
# # name of the secret containing the kms authentication token
|
||||
# tokenSecretName: rook-vault-token
|
||||
# UNCOMMENT THIS TO ENABLE A KMS CONNECTION
|
||||
# Also, do not forget to replace both:
|
||||
# * ROOK_TOKEN_CHANGE_ME: with a base64 encoded value of the token to use
|
||||
# * VAULT_ADDR_CHANGE_ME: with the Vault address
|
||||
# ---
|
||||
# apiVersion: v1
|
||||
# kind: Secret
|
||||
# metadata:
|
||||
# name: rook-vault-token
|
||||
# namespace: rook-ceph
|
||||
# data:
|
||||
# token: ROOK_TOKEN_CHANGE_ME
|
||||
@@ -300,6 +300,18 @@ spec:
|
||||
iteration:
|
||||
type: integer
|
||||
format: int32
|
||||
security:
|
||||
type: object
|
||||
properties:
|
||||
kms:
|
||||
type: object
|
||||
properties:
|
||||
connectionDetails:
|
||||
type: object
|
||||
nullable: true
|
||||
x-kubernetes-preserve-unknown-fields: true
|
||||
tokenSecretName:
|
||||
type: string
|
||||
annotations:
|
||||
type: object
|
||||
nullable: true
|
||||
|
||||
@@ -93,4 +93,227 @@ spec:
|
||||
secretNames:
|
||||
type: array
|
||||
subresources:
|
||||
status: {}
|
||||
status: {}
|
||||
---
|
||||
apiVersion: apiextensions.k8s.io/v1beta1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: cephclusters.ceph.rook.io
|
||||
spec:
|
||||
group: ceph.rook.io
|
||||
names:
|
||||
kind: CephCluster
|
||||
listKind: CephClusterList
|
||||
plural: cephclusters
|
||||
singular: cephcluster
|
||||
scope: Namespaced
|
||||
version: v1
|
||||
validation:
|
||||
openAPIV3Schema:
|
||||
properties:
|
||||
spec:
|
||||
properties:
|
||||
annotations: {}
|
||||
cephVersion:
|
||||
properties:
|
||||
allowUnsupported:
|
||||
type: boolean
|
||||
image:
|
||||
type: string
|
||||
dashboard:
|
||||
properties:
|
||||
enabled:
|
||||
type: boolean
|
||||
urlPrefix:
|
||||
type: string
|
||||
port:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 65535
|
||||
ssl:
|
||||
type: boolean
|
||||
dataDirHostPath:
|
||||
pattern: ^/(\S+)
|
||||
type: string
|
||||
disruptionManagement:
|
||||
properties:
|
||||
machineDisruptionBudgetNamespace:
|
||||
type: string
|
||||
managePodBudgets:
|
||||
type: boolean
|
||||
osdMaintenanceTimeout:
|
||||
type: integer
|
||||
manageMachineDisruptionBudgets:
|
||||
type: boolean
|
||||
skipUpgradeChecks:
|
||||
type: boolean
|
||||
continueUpgradeAfterChecksEvenIfNotHealthy:
|
||||
type: boolean
|
||||
mon:
|
||||
properties:
|
||||
allowMultiplePerNode:
|
||||
type: boolean
|
||||
count:
|
||||
maximum: 9
|
||||
minimum: 0
|
||||
type: integer
|
||||
volumeClaimTemplate: {}
|
||||
mgr:
|
||||
properties:
|
||||
modules:
|
||||
items:
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
enabled:
|
||||
type: boolean
|
||||
network:
|
||||
properties:
|
||||
hostNetwork:
|
||||
type: boolean
|
||||
provider:
|
||||
type: string
|
||||
selectors: {}
|
||||
storage:
|
||||
properties:
|
||||
disruptionManagement:
|
||||
properties:
|
||||
machineDisruptionBudgetNamespace:
|
||||
type: string
|
||||
managePodBudgets:
|
||||
type: boolean
|
||||
osdMaintenanceTimeout:
|
||||
type: integer
|
||||
manageMachineDisruptionBudgets:
|
||||
type: boolean
|
||||
useAllNodes:
|
||||
type: boolean
|
||||
nodes:
|
||||
items:
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
config:
|
||||
properties:
|
||||
metadataDevice:
|
||||
type: string
|
||||
storeType:
|
||||
type: string
|
||||
pattern: ^(bluestore)$
|
||||
databaseSizeMB:
|
||||
type: string
|
||||
walSizeMB:
|
||||
type: string
|
||||
journalSizeMB:
|
||||
type: string
|
||||
osdsPerDevice:
|
||||
type: string
|
||||
encryptedDevice:
|
||||
type: string
|
||||
pattern: ^(true|false)$
|
||||
useAllDevices:
|
||||
type: boolean
|
||||
deviceFilter:
|
||||
type: string
|
||||
devicePathFilter:
|
||||
type: string
|
||||
devices:
|
||||
type: array
|
||||
items:
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
config: {}
|
||||
resources: {}
|
||||
type: array
|
||||
useAllDevices:
|
||||
type: boolean
|
||||
deviceFilter:
|
||||
type: string
|
||||
devicePathFilter:
|
||||
type: string
|
||||
config: {}
|
||||
storageClassDeviceSets: {}
|
||||
driveGroups:
|
||||
type: array
|
||||
nullable: true
|
||||
items:
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
spec: {}
|
||||
placement: {}
|
||||
required:
|
||||
- name
|
||||
- spec
|
||||
monitoring:
|
||||
properties:
|
||||
enabled:
|
||||
type: boolean
|
||||
rulesNamespace:
|
||||
type: string
|
||||
externalMgrEndpoints:
|
||||
type: array
|
||||
items:
|
||||
properties:
|
||||
ip:
|
||||
type: string
|
||||
removeOSDsIfOutAndSafeToRemove:
|
||||
type: boolean
|
||||
external:
|
||||
properties:
|
||||
enable:
|
||||
type: boolean
|
||||
cleanupPolicy:
|
||||
properties:
|
||||
confirmation:
|
||||
type: string
|
||||
pattern: ^$|^yes-really-destroy-data$
|
||||
sanitizeDisks:
|
||||
properties:
|
||||
method:
|
||||
type: string
|
||||
pattern: ^(complete|quick)$
|
||||
dataSource:
|
||||
type: string
|
||||
pattern: ^(zero|random)$
|
||||
iteration:
|
||||
type: integer
|
||||
format: int32
|
||||
security:
|
||||
properties:
|
||||
kms:
|
||||
properties:
|
||||
connectionDetails:
|
||||
type: object
|
||||
tokenSecretName:
|
||||
type: string
|
||||
placement: {}
|
||||
resources: {}
|
||||
healthCheck: {}
|
||||
subresources:
|
||||
status: {}
|
||||
additionalPrinterColumns:
|
||||
- name: DataDirHostPath
|
||||
type: string
|
||||
description: Directory used on the K8s nodes
|
||||
JSONPath: .spec.dataDirHostPath
|
||||
- name: MonCount
|
||||
type: string
|
||||
description: Number of MONs
|
||||
JSONPath: .spec.mon.count
|
||||
- name: Age
|
||||
type: date
|
||||
JSONPath: .metadata.creationTimestamp
|
||||
- name: Phase
|
||||
type: string
|
||||
description: Phase
|
||||
JSONPath: .status.phase
|
||||
- name: Message
|
||||
type: string
|
||||
description: Message
|
||||
JSONPath: .status.message
|
||||
- name: Health
|
||||
type: string
|
||||
description: Ceph Health
|
||||
JSONPath: .status.ceph.health
|
||||
@@ -3,21 +3,23 @@ module github.com/rook/rook
|
||||
go 1.13
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go v1.16.26
|
||||
github.com/aws/aws-sdk-go v1.25.41
|
||||
github.com/banzaicloud/k8s-objectmatcher v1.1.0
|
||||
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f
|
||||
github.com/coreos/prometheus-operator v0.34.0
|
||||
github.com/corpix/uarand v0.1.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1
|
||||
github.com/ghodss/yaml v1.0.0
|
||||
github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32
|
||||
github.com/go-ini/ini v1.51.1
|
||||
github.com/go-sql-driver/mysql v1.4.1
|
||||
github.com/google/go-cmp v0.4.0
|
||||
github.com/google/go-cmp v0.5.0
|
||||
github.com/google/gofuzz v1.1.0 // indirect
|
||||
github.com/google/uuid v1.1.1
|
||||
github.com/hashicorp/vault/api v1.0.5-0.20200902155336-f9d5ce5a171a
|
||||
github.com/icrowley/fake v0.0.0-20180203215853-4178557ae428
|
||||
github.com/k8snetworkplumbingwg/network-attachment-definition-client v0.0.0-20200401090632-ee27f62faef8
|
||||
github.com/kube-object-storage/lib-bucket-provisioner v0.0.0-20200610144127-e2eec875d6d1
|
||||
github.com/libopenstorage/secrets v0.0.0-20201006135900-af310b01fe47
|
||||
github.com/openshift/cluster-api v0.0.0-20191129101638-b09907ac6668
|
||||
github.com/openshift/machine-api-operator v0.2.1-0.20190903202259-474e14e4965a
|
||||
github.com/pkg/errors v0.9.1
|
||||
@@ -27,11 +29,10 @@ require (
|
||||
github.com/spf13/pflag v1.0.5
|
||||
github.com/stretchr/testify v1.4.0
|
||||
github.com/yanniszark/go-nodetool v0.0.0-20191206125106-cd8f91fa16be
|
||||
golang.org/x/net v0.0.0-20200301022130-244492dfa37a // indirect
|
||||
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d // indirect
|
||||
golang.org/x/text v0.3.3 // indirect
|
||||
golang.org/x/tools v0.0.0-20200319210407-521f4a0cd458 // indirect
|
||||
google.golang.org/grpc v1.26.0 // indirect
|
||||
google.golang.org/protobuf v1.25.0 // indirect
|
||||
gopkg.in/ini.v1 v1.51.1
|
||||
k8s.io/api v0.17.2
|
||||
k8s.io/apiextensions-apiserver v0.17.2
|
||||
@@ -51,7 +52,9 @@ require (
|
||||
// This looks "horrible", but is due to the Rook including k8s.io/kubernetes directly which is not recommended,
|
||||
// ee https://github.com/kubernetes/kubernetes/issues/79384#issuecomment-505725449
|
||||
replace (
|
||||
go.etcd.io/etcd => go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738
|
||||
golang.org/x/text => golang.org/x/text v0.3.3
|
||||
google.golang.org/grpc => google.golang.org/grpc v1.26.0
|
||||
k8s.io/api => k8s.io/api v0.17.2
|
||||
k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.17.2
|
||||
k8s.io/apimachinery => k8s.io/apimachinery v0.17.2
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 v1
|
||||
|
||||
// IsEnabled return whether a KMS is configured
|
||||
func (kms *KeyManagementServiceSpec) IsEnabled() bool {
|
||||
return len(kms.ConnectionDetails) != 0
|
||||
}
|
||||
|
||||
// IsTokenAuthEnabled return whether KMS token auth is enabled
|
||||
func (kms *KeyManagementServiceSpec) IsTokenAuthEnabled() bool {
|
||||
return kms.TokenSecretName != ""
|
||||
}
|
||||
@@ -129,9 +129,23 @@ type ClusterSpec struct {
|
||||
|
||||
// Internal daemon healthchecks and liveness probe
|
||||
HealthCheck CephClusterHealthCheckSpec `json:"healthCheck"`
|
||||
|
||||
// Security represents security settings
|
||||
Security SecuritySpec `json:"security,omitempty"`
|
||||
}
|
||||
|
||||
// VersionSpec represents the settings for the Ceph version that Rook is orchestrating.
|
||||
// SecuritySpec is security spec to include various security items such as kms
|
||||
type SecuritySpec struct {
|
||||
KeyManagementService KeyManagementServiceSpec `json:"kms,omitempty"`
|
||||
}
|
||||
|
||||
// KeyManagementServiceSpec represent various details of the KMS server
|
||||
type KeyManagementServiceSpec struct {
|
||||
ConnectionDetails map[string]string `json:"connectionDetails,omitempty"`
|
||||
TokenSecretName string `json:"tokenSecretName,omitempty"`
|
||||
}
|
||||
|
||||
// CephVersionSpec represents the settings for the Ceph version that Rook is orchestrating.
|
||||
type CephVersionSpec struct {
|
||||
// Image is the container image used to launch the ceph daemons, such as ceph/ceph:v15.2.4
|
||||
Image string `json:"image,omitempty"`
|
||||
|
||||
@@ -1045,6 +1045,7 @@ func (in *ClusterSpec) DeepCopyInto(out *ClusterSpec) {
|
||||
in.Mgr.DeepCopyInto(&out.Mgr)
|
||||
out.CleanupPolicy = in.CleanupPolicy
|
||||
in.HealthCheck.DeepCopyInto(&out.HealthCheck)
|
||||
in.Security.DeepCopyInto(&out.Security)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1422,6 +1423,29 @@ func (in *HealthCheckSpec) DeepCopy() *HealthCheckSpec {
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *KeyManagementServiceSpec) DeepCopyInto(out *KeyManagementServiceSpec) {
|
||||
*out = *in
|
||||
if in.ConnectionDetails != nil {
|
||||
in, out := &in.ConnectionDetails, &out.ConnectionDetails
|
||||
*out = make(map[string]string, len(*in))
|
||||
for key, val := range *in {
|
||||
(*out)[key] = val
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KeyManagementServiceSpec.
|
||||
func (in *KeyManagementServiceSpec) DeepCopy() *KeyManagementServiceSpec {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(KeyManagementServiceSpec)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *MetadataServerSpec) DeepCopyInto(out *MetadataServerSpec) {
|
||||
*out = *in
|
||||
@@ -1905,6 +1929,23 @@ func (in *SanitizeDisksSpec) DeepCopy() *SanitizeDisksSpec {
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *SecuritySpec) DeepCopyInto(out *SecuritySpec) {
|
||||
*out = *in
|
||||
in.KeyManagementService.DeepCopyInto(&out.KeyManagementService)
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecuritySpec.
|
||||
func (in *SecuritySpec) DeepCopy() *SecuritySpec {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(SecuritySpec)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *Status) DeepCopyInto(out *Status) {
|
||||
*out = *in
|
||||
|
||||
@@ -147,3 +147,14 @@ func (s NodesByName) Swap(i, j int) {
|
||||
func (s NodesByName) Less(i, j int) bool {
|
||||
return s[i].Name < s[j].Name
|
||||
}
|
||||
|
||||
// IsOnPVCEncrypted returns whether a Ceph Cluster on PVC will be encrypted
|
||||
func (s *StorageScopeSpec) IsOnPVCEncrypted() bool {
|
||||
for _, storageClassDeviceSet := range s.StorageClassDeviceSets {
|
||||
if storageClassDeviceSet.Encrypted {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -245,3 +245,13 @@ func TestStorageScopeSpec_NodeWithNameExists(t *testing.T) {
|
||||
assert.True(t, spec.NodeWithNameExists("node1"))
|
||||
assert.True(t, spec.NodeWithNameExists("node2"))
|
||||
}
|
||||
|
||||
func TestIsOnPVCEncrypted(t *testing.T) {
|
||||
s := &StorageScopeSpec{}
|
||||
assert.False(t, s.IsOnPVCEncrypted())
|
||||
|
||||
s.StorageClassDeviceSets = []StorageClassDeviceSet{
|
||||
{Encrypted: true},
|
||||
}
|
||||
assert.True(t, s.IsOnPVCEncrypted())
|
||||
}
|
||||
@@ -196,7 +196,7 @@ func OkToContinue(context *clusterd.Context, clusterInfo *ClusterInfo, deploymen
|
||||
}
|
||||
|
||||
func okToStopDaemon(context *clusterd.Context, clusterInfo *ClusterInfo, deployment, daemonType, daemonName string) error {
|
||||
if !stringInSlice(daemonType, daemonNoCheck) {
|
||||
if !StringInSlice(daemonType, daemonNoCheck) {
|
||||
args := []string{daemonType, "ok-to-stop", daemonName}
|
||||
buf, err := NewCephCommand(context, clusterInfo, args).Run()
|
||||
if err != nil {
|
||||
@@ -242,7 +242,8 @@ func okToContinueMDSDaemon(context *clusterd.Context, clusterInfo *ClusterInfo,
|
||||
return nil
|
||||
}
|
||||
|
||||
func stringInSlice(a string, list []string) bool {
|
||||
// StringInSlice return whether an element is in a slice
|
||||
func StringInSlice(a string, list []string) bool {
|
||||
for _, b := range list {
|
||||
if b == a {
|
||||
return true
|
||||
|
||||
@@ -205,6 +205,18 @@ func Provision(context *clusterd.Context, agent *OsdAgent, crushLocation string)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "binary %q does not exist on the host, make sure lvm2 package is installed", lvmCommandToCheck)
|
||||
}
|
||||
// Init KMS store, retrieve the KEK and store it as an env var for ceph-volume
|
||||
} else {
|
||||
err := setKEKinEnv(context, agent.clusterInfo)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to set kek as an environment variable")
|
||||
}
|
||||
}
|
||||
|
||||
// Print dmsetup version
|
||||
err := dmsetupVersion(context)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to print device mapper version")
|
||||
}
|
||||
|
||||
// set the initial orchestration status
|
||||
@@ -217,7 +229,6 @@ func Provision(context *clusterd.Context, agent *OsdAgent, crushLocation string)
|
||||
|
||||
logger.Infof("discovering hardware")
|
||||
|
||||
var err error
|
||||
var rawDevices []*sys.LocalDisk
|
||||
if agent.pvcBacked {
|
||||
for i := range agent.devices {
|
||||
|
||||
@@ -17,12 +17,19 @@ limitations under the License.
|
||||
package osd
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
v1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
cephclient "github.com/rook/rook/pkg/daemon/ceph/client"
|
||||
"github.com/rook/rook/pkg/daemon/ceph/osd/kms"
|
||||
oposd "github.com/rook/rook/pkg/operator/ceph/cluster/osd"
|
||||
)
|
||||
|
||||
const (
|
||||
cryptsetupBinary = "cryptsetup"
|
||||
dmsetupBinary = "dmsetup"
|
||||
)
|
||||
|
||||
func closeEncryptedDevice(context *clusterd.Context, dmName string) error {
|
||||
@@ -32,6 +39,38 @@ func closeEncryptedDevice(context *clusterd.Context, dmName string) error {
|
||||
return errors.Wrapf(err, "failed to close encrypted device. %s", cryptsetupOut)
|
||||
}
|
||||
|
||||
logger.Info(cryptsetupOut)
|
||||
logger.Infof("dm version:\n%s", cryptsetupOut)
|
||||
return nil
|
||||
}
|
||||
|
||||
func dmsetupVersion(context *clusterd.Context) error {
|
||||
args := []string{"version"}
|
||||
dmsetupOut, err := context.Executor.ExecuteCommandWithCombinedOutput(dmsetupBinary, args...)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to find device mapper version. %s", dmsetupOut)
|
||||
}
|
||||
|
||||
logger.Info(dmsetupOut)
|
||||
return nil
|
||||
}
|
||||
|
||||
func setKEKinEnv(context *clusterd.Context, clusterInfo *cephclient.ClusterInfo) error {
|
||||
// KMS details are passed by the Operator as env variables in the pod
|
||||
// The token if any is mounted in the provisioner pod as an env variable so the secrets lib will pick it up
|
||||
kmsConfig := kms.NewConfig(context, &v1.ClusterSpec{Security: v1.SecuritySpec{KeyManagementService: v1.KeyManagementServiceSpec{ConnectionDetails: kms.ConfigEnvsToMapString()}}}, clusterInfo)
|
||||
if kmsConfig.IsVault() {
|
||||
// Fetch the KEK
|
||||
kek, err := kmsConfig.GetSecret(os.Getenv(oposd.PVCNameEnvVarName))
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to retrieve key encryption key from %q kms", kmsConfig.Provider)
|
||||
}
|
||||
|
||||
// Set the KEK as an env variable for ceph-volume
|
||||
err = os.Setenv(oposd.CephVolumeEncryptedKeyEnvVarName, kek)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to set key encryption key env variable for ceph-volume")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -40,3 +40,23 @@ func TestCloseEncryptedDevice(t *testing.T) {
|
||||
err := closeEncryptedDevice(context, "/dev/mapper/ceph-43e9efed-0676-4731-b75a-a4c42ece1bb1-xvdbr-block-dmcrypt")
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestDmsetupVersion(t *testing.T) {
|
||||
dmsetupOutput := `
|
||||
Library version: 1.02.154 (2018-12-07)
|
||||
Driver version: 4.40.0
|
||||
`
|
||||
executor := &exectest.MockExecutor{}
|
||||
executor.MockExecuteCommandWithCombinedOutput = func(command string, args ...string) (string, error) {
|
||||
logger.Infof("%s %v", command, args)
|
||||
if command == "dmsetup" && args[0] == "version" {
|
||||
return dmsetupOutput, nil
|
||||
}
|
||||
|
||||
return "", errors.Errorf("unknown command %s %s", command, args)
|
||||
}
|
||||
|
||||
context := &clusterd.Context{Executor: executor}
|
||||
err := dmsetupVersion(context)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/vault/api"
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
"github.com/rook/rook/pkg/daemon/ceph/client"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
)
|
||||
|
||||
var (
|
||||
knownKMSPrefix = []string{"VAULT_"}
|
||||
)
|
||||
|
||||
// VaultTokenEnvVarFromSecret returns the kms token secret value as an env var
|
||||
func vaultTokenEnvVarFromSecret(tokenSecretName string) v1.EnvVar {
|
||||
return v1.EnvVar{
|
||||
Name: api.EnvVaultToken,
|
||||
ValueFrom: &v1.EnvVarSource{
|
||||
SecretKeyRef: &v1.SecretKeySelector{
|
||||
LocalObjectReference: v1.LocalObjectReference{
|
||||
Name: tokenSecretName,
|
||||
},
|
||||
Key: KMSTokenSecretNameKey,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// vaultTLSEnvVarFromSecret translates TLS env var which are set to k8s secret name to their actual path on the fs once mounted as volume
|
||||
// See: TLSSecretVolumeAndMount() for more details
|
||||
func vaultTLSEnvVarFromSecret(kmsConfig map[string]string) []v1.EnvVar {
|
||||
vaultTLSEnvVar := []v1.EnvVar{}
|
||||
|
||||
for _, tlsOption := range vaultTLSConnectionDetails {
|
||||
tlsSecretName := GetParam(kmsConfig, tlsOption)
|
||||
if tlsSecretName != "" {
|
||||
vaultTLSEnvVar = append(vaultTLSEnvVar, v1.EnvVar{Name: tlsOption, Value: path.Join(EtcVaultDir, tlsSecretPath(tlsOption))})
|
||||
}
|
||||
}
|
||||
|
||||
return vaultTLSEnvVar
|
||||
}
|
||||
|
||||
// VaultConfigToEnvVar populates the kms config as env variables
|
||||
func VaultConfigToEnvVar(spec cephv1.ClusterSpec) []v1.EnvVar {
|
||||
envs := []v1.EnvVar{}
|
||||
for k, v := range spec.Security.KeyManagementService.ConnectionDetails {
|
||||
// Skip TLS and token env var to avoid env being set multiple times
|
||||
toSkip := append(vaultTLSConnectionDetails, api.EnvVaultToken)
|
||||
if client.StringInSlice(k, toSkip) {
|
||||
continue
|
||||
}
|
||||
envs = append(envs, v1.EnvVar{Name: k, Value: v})
|
||||
}
|
||||
|
||||
// Add the VAULT_TOKEN
|
||||
envs = append(envs, vaultTokenEnvVarFromSecret(spec.Security.KeyManagementService.TokenSecretName))
|
||||
|
||||
// Add TLS env if any
|
||||
envs = append(envs, vaultTLSEnvVarFromSecret(spec.Security.KeyManagementService.ConnectionDetails)...)
|
||||
|
||||
logger.Debugf("kms envs are %v", envs)
|
||||
|
||||
return envs
|
||||
}
|
||||
|
||||
// ConfigEnvsToMapString returns all the env variables in map from a known KMS
|
||||
func ConfigEnvsToMapString() map[string]string {
|
||||
envs := make(map[string]string)
|
||||
for _, e := range os.Environ() {
|
||||
pair := strings.SplitN(e, "=", 2)
|
||||
for _, knownKMS := range knownKMSPrefix {
|
||||
if strings.HasPrefix(pair[0], knownKMS) || pair[0] == Provider {
|
||||
envs[pair[0]] = os.Getenv(pair[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return envs
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
"github.com/stretchr/testify/assert"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
)
|
||||
|
||||
func TestVaultTLSEnvVarFromSecret(t *testing.T) {
|
||||
type args struct {
|
||||
kmsConfig map[string]string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want []v1.EnvVar
|
||||
}{
|
||||
{"no tls", args{kmsConfig: map[string]string{"foo": "bar"}}, []v1.EnvVar{}},
|
||||
{"ca cert tls", args{kmsConfig: map[string]string{"foo": "bar", "VAULT_CACERT": "vault-ca-cert-secret"}}, []v1.EnvVar{{Name: "VAULT_CACERT", Value: "/etc/vault/vault.ca"}}},
|
||||
{"ca cert tls and client ca/key", args{kmsConfig: map[string]string{
|
||||
"foo": "bar",
|
||||
"VAULT_CACERT": "vault-ca-cert-secret",
|
||||
"VAULT_CLIENT_CERT": "vault-client-cert-secret",
|
||||
"VAULT_CLIENT_KEY": "vault-key-cert-secret",
|
||||
}},
|
||||
[]v1.EnvVar{
|
||||
{Name: "VAULT_CACERT", Value: "/etc/vault/vault.ca"},
|
||||
{Name: "VAULT_CLIENT_CERT", Value: "/etc/vault/vault.crt"},
|
||||
{Name: "VAULT_CLIENT_KEY", Value: "/etc/vault/vault.key"},
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := vaultTLSEnvVarFromSecret(tt.args.kmsConfig); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("vaultTLSEnvVarFromSecret() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVaultConfigToEnvVar(t *testing.T) {
|
||||
type args struct {
|
||||
spec cephv1.ClusterSpec
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want []v1.EnvVar
|
||||
}{
|
||||
{"no tls", args{spec: cephv1.ClusterSpec{Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{TokenSecretName: "vault-token", ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault", "VAULT_ADDR": "http://1.1.1.1:8200"}}}}}, []v1.EnvVar{
|
||||
{Name: "KMS_PROVIDER", Value: "vault"},
|
||||
{Name: "VAULT_ADDR", Value: "http://1.1.1.1:8200"},
|
||||
{Name: "VAULT_TOKEN", ValueFrom: &v1.EnvVarSource{
|
||||
SecretKeyRef: &v1.SecretKeySelector{
|
||||
LocalObjectReference: v1.LocalObjectReference{
|
||||
Name: "vault-token",
|
||||
},
|
||||
Key: "token",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{" tls", args{spec: cephv1.ClusterSpec{Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{TokenSecretName: "vault-token", ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault", "VAULT_ADDR": "http://1.1.1.1:8200", "VAULT_CACERT": "vault-ca-cert-secret"}}}}}, []v1.EnvVar{
|
||||
{Name: "KMS_PROVIDER", Value: "vault"},
|
||||
{Name: "VAULT_ADDR", Value: "http://1.1.1.1:8200"},
|
||||
{Name: "VAULT_TOKEN", ValueFrom: &v1.EnvVarSource{
|
||||
SecretKeyRef: &v1.SecretKeySelector{
|
||||
LocalObjectReference: v1.LocalObjectReference{
|
||||
Name: "vault-token",
|
||||
},
|
||||
Key: "token",
|
||||
},
|
||||
},
|
||||
},
|
||||
{Name: "VAULT_CACERT", Value: "/etc/vault/vault.ca"},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := VaultConfigToEnvVar(tt.args.spec); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("VaultConfigToEnvVar() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigEnvsToMapString(t *testing.T) {
|
||||
// No VAULT envs
|
||||
envs := ConfigEnvsToMapString()
|
||||
assert.Equal(t, 0, len(envs))
|
||||
|
||||
// Single KMS value
|
||||
os.Setenv("KMS_PROVIDER", "vault")
|
||||
defer os.Unsetenv("KMS_PROVIDER")
|
||||
envs = ConfigEnvsToMapString()
|
||||
assert.Equal(t, 1, len(envs))
|
||||
|
||||
// Some more Vault KMS with one intruder
|
||||
os.Setenv("KMS_PROVIDER", "vault")
|
||||
defer os.Unsetenv("KMS_PROVIDER")
|
||||
os.Setenv("VAULT_ADDR", "1.1.1.1")
|
||||
defer os.Unsetenv("VAULT_ADDR")
|
||||
os.Setenv("VAULT_SKIP_VERIFY", "true")
|
||||
defer os.Unsetenv("VAULT_SKIP_VERIFY")
|
||||
os.Setenv("foo", "bar")
|
||||
defer os.Unsetenv("foo")
|
||||
envs = ConfigEnvsToMapString()
|
||||
assert.Equal(t, 3, len(envs))
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
cephclient "github.com/rook/rook/pkg/daemon/ceph/client"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
kerrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
// OsdEncryptionSecretNameKeyName is the key name of the Secret that contains the OSD encryption key
|
||||
// #nosec G101 since this is not leaking any hardcoded credentials, it's just the secret key name
|
||||
OsdEncryptionSecretNameKeyName = "dmcrypt-key"
|
||||
|
||||
// #nosec G101 since this is not leaking any hardcoded credentials, it's just the prefix of the secret name
|
||||
osdEncryptionSecretNamePrefix = "rook-ceph-osd-encryption-key"
|
||||
|
||||
// KMSTokenSecretNameKey is the key name of the Secret that contains the KMS authentication token
|
||||
KMSTokenSecretNameKey = "token"
|
||||
)
|
||||
|
||||
// storeSecretInKubernetes stores the dmcrypt key in a Kubernetes Secret
|
||||
func (c *Config) storeSecretInKubernetes(pvcName, key string) error {
|
||||
s := generateOSDEncryptedKeySecret(pvcName, key, c.clusterInfo)
|
||||
|
||||
// Create the Kubernetes Secret
|
||||
_, err := c.context.Clientset.CoreV1().Secrets(c.clusterInfo.Namespace).Create(s)
|
||||
if err != nil && !kerrors.IsAlreadyExists(err) {
|
||||
return errors.Wrapf(err, "failed to save ceph osd encryption key as a secret for pvc %q", pvcName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateOSDEncryptedKeySecret(pvcName, key string, clusterInfo *cephclient.ClusterInfo) *v1.Secret {
|
||||
s := &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: GenerateOSDEncryptionSecretName(pvcName),
|
||||
Namespace: clusterInfo.Namespace,
|
||||
Labels: map[string]string{
|
||||
"pvc_name": pvcName,
|
||||
},
|
||||
},
|
||||
StringData: map[string]string{
|
||||
OsdEncryptionSecretNameKeyName: key,
|
||||
},
|
||||
Type: k8sutil.RookType,
|
||||
}
|
||||
|
||||
// Set the ownerref to the Secret
|
||||
k8sutil.SetOwnerRef(&s.ObjectMeta, &clusterInfo.OwnerRef)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// GenerateOSDEncryptionSecretName generate the Kubernetes Secret name of the encrypted key
|
||||
func GenerateOSDEncryptionSecretName(pvcName string) string {
|
||||
return fmt.Sprintf("%s-%s", osdEncryptionSecretNamePrefix, pvcName)
|
||||
}
|
||||
|
||||
// IsK8s determines whether the configured KMS is Kubernetes
|
||||
func (c *Config) IsK8s() bool {
|
||||
return c.Provider == "kubernetes" || c.Provider == "k8s"
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGenerateOSDEncryptionSecretName(t *testing.T) {
|
||||
assert.Equal(t, "rook-ceph-osd-encryption-key-set1-data-0-7dwll", GenerateOSDEncryptionSecretName("set1-data-0-7dwll"))
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/coreos/pkg/capnslog"
|
||||
"github.com/hashicorp/vault/api"
|
||||
"github.com/libopenstorage/secrets"
|
||||
"github.com/pkg/errors"
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
cephclient "github.com/rook/rook/pkg/daemon/ceph/client"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
// Provider is the config name for the KMS provider type
|
||||
Provider = "KMS_PROVIDER"
|
||||
)
|
||||
|
||||
var (
|
||||
logger = capnslog.NewPackageLogger("github.com/rook/rook", "op-kms")
|
||||
kmsMandatoryConnectionDetails = []string{Provider}
|
||||
)
|
||||
|
||||
// Config is the generic configuration for the KMS
|
||||
type Config struct {
|
||||
Provider string
|
||||
context *clusterd.Context
|
||||
clusterSpec *cephv1.ClusterSpec
|
||||
clusterInfo *cephclient.ClusterInfo
|
||||
}
|
||||
|
||||
// NewConfig returns the selected KMS
|
||||
func NewConfig(context *clusterd.Context, clusterSpec *cephv1.ClusterSpec, clusterInfo *cephclient.ClusterInfo) *Config {
|
||||
config := &Config{
|
||||
context: context,
|
||||
clusterInfo: clusterInfo,
|
||||
clusterSpec: clusterSpec,
|
||||
}
|
||||
|
||||
Provider := clusterSpec.Security.KeyManagementService.ConnectionDetails[Provider]
|
||||
switch Provider {
|
||||
case "":
|
||||
config.Provider = secrets.TypeK8s
|
||||
case secrets.TypeVault:
|
||||
config.Provider = secrets.TypeVault
|
||||
default:
|
||||
logger.Errorf("unsupported kms type %q", Provider)
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
// PutSecret writes an encrypted key in a KMS
|
||||
func (c *Config) PutSecret(secretName, secretValue string) error {
|
||||
// If Kubernetes Secret KMS is selected (default)
|
||||
if c.IsK8s() {
|
||||
// Store the secret in Kubernetes Secrets
|
||||
err := c.storeSecretInKubernetes(secretName, secretValue)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to store secret in kubernetes secret")
|
||||
}
|
||||
}
|
||||
if c.IsVault() {
|
||||
// Store the secret in Vault
|
||||
v, err := InitVault(c.context, c.clusterInfo.Namespace, c.clusterSpec.Security.KeyManagementService.ConnectionDetails)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to init vault kms")
|
||||
}
|
||||
k := buildKeyContext(c.clusterSpec.Security.KeyManagementService.ConnectionDetails)
|
||||
err = put(v, GenerateOSDEncryptionSecretName(secretName), secretValue, k)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to put secret in vault")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSecret returns an encrypted key from a KMS
|
||||
func (c *Config) GetSecret(secretName string) (string, error) {
|
||||
var value string
|
||||
if c.IsVault() {
|
||||
// Store the secret in Vault
|
||||
v, err := InitVault(c.context, c.clusterInfo.Namespace, c.clusterSpec.Security.KeyManagementService.ConnectionDetails)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "failed to get secret in vault")
|
||||
}
|
||||
|
||||
k := buildKeyContext(c.clusterSpec.Security.KeyManagementService.ConnectionDetails)
|
||||
value, err = get(v, GenerateOSDEncryptionSecretName(secretName), k)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "failed to get secret in vault")
|
||||
}
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// DeleteSecret deletes an encrypted key from a KMS
|
||||
func (c *Config) DeleteSecret(secretName string) error {
|
||||
if c.IsVault() {
|
||||
// Store the secret in Vault
|
||||
v, err := InitVault(c.context, c.clusterInfo.Namespace, c.clusterSpec.Security.KeyManagementService.ConnectionDetails)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to delete secret in vault")
|
||||
}
|
||||
|
||||
k := buildKeyContext(c.clusterSpec.Security.KeyManagementService.ConnectionDetails)
|
||||
err = delete(v, GenerateOSDEncryptionSecretName(secretName), k)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to delete secret in vault")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetParam returns the value of the KMS config option
|
||||
func GetParam(kmsConfig map[string]string, param string) string {
|
||||
if val, ok := kmsConfig[param]; ok && val != "" {
|
||||
return strings.TrimSpace(val)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ValidateConnectionDetails validates mandatory KMS connection details
|
||||
func ValidateConnectionDetails(context *clusterd.Context, clusterSpec *cephv1.ClusterSpec, ns string) error {
|
||||
// A token must be specified
|
||||
if !clusterSpec.Security.KeyManagementService.IsTokenAuthEnabled() {
|
||||
return errors.New("failed to validate kms configuration (missing token in spec)")
|
||||
}
|
||||
|
||||
// Lookup mandatory connection details
|
||||
for _, config := range kmsMandatoryConnectionDetails {
|
||||
if GetParam(clusterSpec.Security.KeyManagementService.ConnectionDetails, config) == "" {
|
||||
return errors.Errorf("failed to validate kms config %q. cannot be empty", config)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate KMS provider connection details
|
||||
switch GetParam(clusterSpec.Security.KeyManagementService.ConnectionDetails, Provider) {
|
||||
case "vault":
|
||||
err := validateVaultConnectionDetails(context, ns, clusterSpec.Security.KeyManagementService.ConnectionDetails)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to validate vault connection details")
|
||||
}
|
||||
}
|
||||
|
||||
// Validate potential token Secret presence
|
||||
if clusterSpec.Security.KeyManagementService.IsTokenAuthEnabled() {
|
||||
kmsToken, err := context.Clientset.CoreV1().Secrets(ns).Get(clusterSpec.Security.KeyManagementService.TokenSecretName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to fetch kms token secret %q", clusterSpec.Security.KeyManagementService.TokenSecretName)
|
||||
}
|
||||
|
||||
// Check for empty token
|
||||
token, ok := kmsToken.Data[KMSTokenSecretNameKey]
|
||||
if !ok || len(token) == 0 {
|
||||
return errors.Errorf("failed to read k8s kms secret %q key %q (not found or empty)", KMSTokenSecretNameKey, clusterSpec.Security.KeyManagementService.TokenSecretName)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetTokenToEnvVar sets a KMS token as an env variable
|
||||
func SetTokenToEnvVar(context *clusterd.Context, tokenSecretName, provider, namespace string) error {
|
||||
// Get the secret containing the kms token
|
||||
kmsToken, err := context.Clientset.CoreV1().Secrets(namespace).Get(tokenSecretName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to fetch kms token secret %q", tokenSecretName)
|
||||
}
|
||||
|
||||
// We set the token as an env variable, the secrets lib will pick it up
|
||||
var key, value string
|
||||
switch provider {
|
||||
case secrets.TypeVault:
|
||||
key = api.EnvVaultToken
|
||||
value = string(kmsToken.Data[KMSTokenSecretNameKey])
|
||||
default:
|
||||
logger.Debugf("unknown provider %q return nil", provider)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Set the env variable
|
||||
err = os.Setenv(key, value)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to set kms token to an env var")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
func TestValidateConnectionDetails(t *testing.T) {
|
||||
// Placeholder
|
||||
context := &clusterd.Context{Clientset: test.New(t, 3)}
|
||||
clusterSpec := &cephv1.ClusterSpec{Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{}}}}
|
||||
ns := "rook-ceph"
|
||||
|
||||
// Error: no token in spec
|
||||
err := ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.Error(t, err, "")
|
||||
assert.EqualError(t, err, "failed to validate kms configuration (missing token in spec)")
|
||||
|
||||
clusterSpec.Security.KeyManagementService.TokenSecretName = "vault-token"
|
||||
|
||||
// Error: Data is present but no provider
|
||||
clusterSpec.Security.KeyManagementService.ConnectionDetails = map[string]string{"foo": "bar"}
|
||||
err = ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.Error(t, err, "")
|
||||
assert.EqualError(t, err, "failed to validate kms config \"KMS_PROVIDER\". cannot be empty")
|
||||
|
||||
// Error: Data has a KMS_PROVIDER but missing details
|
||||
clusterSpec.Security.KeyManagementService.ConnectionDetails["KMS_PROVIDER"] = "vault"
|
||||
err = ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.Error(t, err, "")
|
||||
assert.EqualError(t, err, "failed to validate vault connection details: failed to find connection details \"VAULT_ADDR\"")
|
||||
|
||||
// Error: connection details are correct but the token secret does not exist
|
||||
clusterSpec.Security.KeyManagementService.ConnectionDetails["VAULT_ADDR"] = "https://1.1.1.1:8200"
|
||||
err = ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.Error(t, err, "")
|
||||
assert.EqualError(t, err, "failed to fetch kms token secret \"vault-token\": secrets \"vault-token\" not found")
|
||||
|
||||
// Error: token secret present but empty content
|
||||
s := &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: clusterSpec.Security.KeyManagementService.TokenSecretName,
|
||||
Namespace: ns,
|
||||
},
|
||||
}
|
||||
_, err = context.Clientset.CoreV1().Secrets(ns).Create(s)
|
||||
assert.NoError(t, err)
|
||||
err = ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.Error(t, err, "")
|
||||
assert.EqualError(t, err, "failed to read k8s kms secret \"token\" key \"vault-token\" (not found or empty)")
|
||||
|
||||
// Error: token key does not exist
|
||||
s.Data = map[string][]byte{"foo": []byte("bar")}
|
||||
_, err = context.Clientset.CoreV1().Secrets(ns).Update(s)
|
||||
assert.NoError(t, err)
|
||||
err = ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.Error(t, err, "")
|
||||
assert.EqualError(t, err, "failed to read k8s kms secret \"token\" key \"vault-token\" (not found or empty)")
|
||||
|
||||
// Success: token content is ok
|
||||
s.Data["token"] = []byte("myt-otkenbenvqrev")
|
||||
_, err = context.Clientset.CoreV1().Secrets(ns).Update(s)
|
||||
assert.NoError(t, err)
|
||||
err = ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.NoError(t, err, "")
|
||||
|
||||
// Error: TLS is configured but secrets do not exist
|
||||
clusterSpec.Security.KeyManagementService.ConnectionDetails["VAULT_CACERT"] = "vault-ca-secret"
|
||||
err = ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.Error(t, err, "")
|
||||
assert.EqualError(t, err, "failed to validate vault connection details: failed to find TLS connection details k8s secret \"VAULT_CACERT\"")
|
||||
|
||||
// Error: TLS secret exists but empty key
|
||||
tlsSecret := &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "vault-ca-secret",
|
||||
Namespace: ns,
|
||||
},
|
||||
}
|
||||
_, err = context.Clientset.CoreV1().Secrets(ns).Create(tlsSecret)
|
||||
assert.NoError(t, err)
|
||||
err = ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.Error(t, err, "")
|
||||
assert.EqualError(t, err, "failed to validate vault connection details: failed to find TLS connection key \"cert\" for \"VAULT_CACERT\" in k8s secret \"vault-ca-secret\"")
|
||||
|
||||
// Success: TLS config is correct
|
||||
tlsSecret.Data = map[string][]byte{"cert": []byte("envnrevbnbvsbjkrtn")}
|
||||
_, err = context.Clientset.CoreV1().Secrets(ns).Update(tlsSecret)
|
||||
assert.NoError(t, err)
|
||||
err = ValidateConnectionDetails(context, clusterSpec, ns)
|
||||
assert.NoError(t, err, "")
|
||||
}
|
||||
|
||||
func TestSetTokenToEnvVar(t *testing.T) {
|
||||
context := &clusterd.Context{Clientset: test.New(t, 3)}
|
||||
secretName := "vault-secret"
|
||||
ns := "rook-ceph"
|
||||
s := &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: secretName,
|
||||
Namespace: ns,
|
||||
},
|
||||
Data: map[string][]byte{"token": []byte("toto")},
|
||||
}
|
||||
_, err := context.Clientset.CoreV1().Secrets(ns).Create(s)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = SetTokenToEnvVar(context, secretName, "vault", ns)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, os.Getenv("VAULT_TOKEN"), "toto")
|
||||
os.Unsetenv("VAULT_TOKEN")
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/vault/api"
|
||||
"github.com/libopenstorage/secrets"
|
||||
"github.com/libopenstorage/secrets/vault"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
// EtcVaultDir is vault config dir
|
||||
EtcVaultDir = "/etc/vault"
|
||||
)
|
||||
|
||||
var (
|
||||
vaultMandatoryConnectionDetails = []string{api.EnvVaultAddress}
|
||||
vaultTLSConnectionDetails = []string{api.EnvVaultCACert, api.EnvVaultClientCert, api.EnvVaultClientKey}
|
||||
)
|
||||
|
||||
/* VAULT API INTERNAL VALUES
|
||||
// Refer to https://pkg.golangclub.com/github.com/hashicorp/vault/api?tab=doc#pkg-constants
|
||||
const EnvVaultAddress = "VAULT_ADDR"
|
||||
const EnvVaultAgentAddr = "VAULT_AGENT_ADDR"
|
||||
const EnvVaultCACert = "VAULT_CACERT"
|
||||
const EnvVaultCAPath = "VAULT_CAPATH"
|
||||
const EnvVaultClientCert = "VAULT_CLIENT_CERT"
|
||||
const EnvVaultClientKey = "VAULT_CLIENT_KEY"
|
||||
const EnvVaultClientTimeout = "VAULT_CLIENT_TIMEOUT"
|
||||
const EnvVaultSRVLookup = "VAULT_SRV_LOOKUP"
|
||||
const EnvVaultSkipVerify = "VAULT_SKIP_VERIFY"
|
||||
const EnvVaultNamespace = "VAULT_NAMESPACE"
|
||||
const EnvVaultTLSServerName = "VAULT_TLS_SERVER_NAME"
|
||||
const EnvVaultWrapTTL = "VAULT_WRAP_TTL"
|
||||
const EnvVaultMaxRetries = "VAULT_MAX_RETRIES"
|
||||
const EnvVaultToken = "VAULT_TOKEN"
|
||||
const EnvVaultMFA = "VAULT_MFA"
|
||||
const EnvRateLimit = "VAULT_RATE_LIMIT"
|
||||
*/
|
||||
|
||||
// InitVault inits the secret store
|
||||
func InitVault(context *clusterd.Context, namespace string, config map[string]string) (secrets.Secrets, error) {
|
||||
c := make(map[string]interface{})
|
||||
|
||||
// So that we don't alter the content of c.config for later iterations
|
||||
// We just want to swap the name of the TLS config secret name --> file name for the kms lib
|
||||
oriConfig := make(map[string]string)
|
||||
for k, v := range config {
|
||||
oriConfig[k] = v
|
||||
}
|
||||
|
||||
// Populate TLS config
|
||||
newConfigWithTLS, err := configTLS(context, namespace, oriConfig)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to initialize vault tls configuration")
|
||||
}
|
||||
|
||||
// Populate TLS config
|
||||
for key, value := range newConfigWithTLS {
|
||||
c[key] = string(value)
|
||||
}
|
||||
|
||||
// Initialize Vault
|
||||
v, err := vault.New(c)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to initialize vault secret store")
|
||||
}
|
||||
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func configTLS(context *clusterd.Context, namespace string, config map[string]string) (map[string]string, error) {
|
||||
for _, tlsOption := range vaultTLSConnectionDetails {
|
||||
tlsSecretName := GetParam(config, tlsOption)
|
||||
if tlsSecretName == "" {
|
||||
continue
|
||||
}
|
||||
// If the string already has the correct path /etc/vault, we are in provisioner code and all the envs have been populated by the op already
|
||||
if !strings.Contains(tlsSecretName, EtcVaultDir) {
|
||||
secret, err := context.Clientset.CoreV1().Secrets(namespace).Get(tlsSecretName, v1.GetOptions{})
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "failed to fetch tls k8s secret %q", tlsSecretName)
|
||||
}
|
||||
|
||||
// Generate a temp file
|
||||
file, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "failed to generate temp file for k8s secret %q content", tlsSecretName)
|
||||
}
|
||||
|
||||
// Write into a file
|
||||
err = ioutil.WriteFile(file.Name(), secret.Data[tlsSecretKeyToCheck(tlsOption)], 0444)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "failed to write k8s secret %q content to a file", tlsSecretName)
|
||||
}
|
||||
|
||||
logger.Debugf("replacing %q current content %q with %q", tlsOption, config[tlsOption], file.Name())
|
||||
|
||||
// update the env var with the path
|
||||
config[tlsOption] = file.Name()
|
||||
} else {
|
||||
logger.Debugf("value of tlsOption %q tlsSecretName is already correct %q", tlsOption, tlsSecretName)
|
||||
}
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func put(v secrets.Secrets, secretName, secretValue string, keyContext map[string]string) error {
|
||||
// Build Secret
|
||||
data := make(map[string]interface{})
|
||||
data[secretName] = secretValue
|
||||
|
||||
// #nosec G104 Write the encryption key in Vault
|
||||
err := v.PutSecret(secretName, data, keyContext)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to put secret %q in vault", secretName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func get(v secrets.Secrets, secretName string, keyContext map[string]string) (string, error) {
|
||||
// #nosec G104 Write the encryption key in Vault
|
||||
s, err := v.GetSecret(secretName, keyContext)
|
||||
if err != nil {
|
||||
return "", errors.Wrapf(err, "failed to get secret %q in vault", secretName)
|
||||
}
|
||||
|
||||
return s[secretName].(string), nil
|
||||
}
|
||||
|
||||
func delete(v secrets.Secrets, secretName string, keyContext map[string]string) error {
|
||||
// #nosec G104 Write the encryption key in Vault
|
||||
err := v.DeleteSecret(secretName, keyContext)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to delete secret %q in vault", secretName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildKeyContext(config map[string]string) map[string]string {
|
||||
// Key context is just the Vault namespace, available in the enterprise version only
|
||||
keyContext := map[string]string{secrets.KeyVaultNamespace: config[api.EnvVaultNamespace]}
|
||||
vaultNamespace, ok := config[api.EnvVaultNamespace]
|
||||
if !ok || vaultNamespace == "" {
|
||||
keyContext = nil
|
||||
}
|
||||
|
||||
return keyContext
|
||||
}
|
||||
|
||||
// IsVault determines whether the configured KMS is Vault
|
||||
func (c *Config) IsVault() bool {
|
||||
return c.Provider == "vault"
|
||||
}
|
||||
|
||||
func validateVaultConnectionDetails(context *clusterd.Context, ns string, kmsConfig map[string]string) error {
|
||||
for _, option := range vaultMandatoryConnectionDetails {
|
||||
if GetParam(kmsConfig, option) == "" {
|
||||
return errors.Errorf("failed to find connection details %q", option)
|
||||
}
|
||||
}
|
||||
|
||||
// We do not support a directory with multiple CA since we fetch a k8s Secret and read its content
|
||||
// So we operate with a single CA only
|
||||
if GetParam(kmsConfig, api.EnvVaultCAPath) != "" {
|
||||
return errors.Errorf("failed to validate TLS connection details. %q is not supported. use %q instead", api.EnvVaultCAPath, api.EnvVaultCACert)
|
||||
}
|
||||
|
||||
// Validate potential TLS configuration
|
||||
for _, tlsOption := range vaultTLSConnectionDetails {
|
||||
tlsSecretName := GetParam(kmsConfig, tlsOption)
|
||||
if tlsSecretName != "" {
|
||||
// Fetch the secret
|
||||
s, err := context.Clientset.CoreV1().Secrets(ns).Get(tlsSecretName, v1.GetOptions{})
|
||||
if err != nil {
|
||||
return errors.Errorf("failed to find TLS connection details k8s secret %q", tlsOption)
|
||||
}
|
||||
|
||||
// Check the Secret key and its content
|
||||
keyToCheck := tlsSecretKeyToCheck(tlsOption)
|
||||
cert, ok := s.Data[keyToCheck]
|
||||
if !ok || len(cert) == 0 {
|
||||
return errors.Errorf("failed to find TLS connection key %q for %q in k8s secret %q", keyToCheck, tlsOption, tlsSecretName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func tlsSecretKeyToCheck(tlsOption string) string {
|
||||
if tlsOption == api.EnvVaultCACert || tlsOption == api.EnvVaultClientCert {
|
||||
return vaultCACertSecretKeyName
|
||||
} else if tlsOption == api.EnvVaultClientKey {
|
||||
return vaultKeySecretKeyName
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
func Test_tlsSecretKeyToCheck(t *testing.T) {
|
||||
type args struct {
|
||||
tlsOption string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want string
|
||||
}{
|
||||
{"certificate", args{tlsOption: "VAULT_CACERT"}, "cert"},
|
||||
{"client-certificate", args{tlsOption: "VAULT_CLIENT_CERT"}, "cert"},
|
||||
{"client-key", args{tlsOption: "VAULT_CLIENT_KEY"}, "key"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tlsSecretKeyToCheck(tt.args.tlsOption); got != tt.want {
|
||||
t.Errorf("tlsSecretKeyToCheck() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_configTLS(t *testing.T) {
|
||||
config := map[string]string{
|
||||
"foo": "bar",
|
||||
"KMS_PROVIDER": "vault",
|
||||
"VAULT_ADDR": "1.1.1.1",
|
||||
"VAULT_BACKEND_PATH": "vault",
|
||||
}
|
||||
ns := "rook-ceph"
|
||||
context := &clusterd.Context{Clientset: test.New(t, 3)}
|
||||
|
||||
// No tls config
|
||||
_, err := configTLS(context, ns, config)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// TLS config with correct values
|
||||
config = map[string]string{
|
||||
"foo": "bar",
|
||||
"KMS_PROVIDER": "vault",
|
||||
"VAULT_ADDR": "1.1.1.1",
|
||||
"VAULT_BACKEND_PATH": "vault",
|
||||
"VAULT_CACERT": "/etc/vault/cacert",
|
||||
"VAULT_SKIP_VERIFY": "false",
|
||||
}
|
||||
config, err = configTLS(context, ns, config)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "/etc/vault/cacert", config["VAULT_CACERT"])
|
||||
|
||||
// TLS config but no secret
|
||||
config = map[string]string{
|
||||
"foo": "bar",
|
||||
"KMS_PROVIDER": "vault",
|
||||
"VAULT_ADDR": "1.1.1.1",
|
||||
"VAULT_BACKEND_PATH": "vault",
|
||||
"VAULT_CACERT": "vault-ca-cert",
|
||||
"VAULT_SKIP_VERIFY": "false",
|
||||
}
|
||||
_, err = configTLS(context, ns, config)
|
||||
assert.Error(t, err)
|
||||
assert.EqualError(t, err, "failed to fetch tls k8s secret \"vault-ca-cert\": secrets \"vault-ca-cert\" not found")
|
||||
|
||||
// TLS config success!
|
||||
config = map[string]string{
|
||||
"foo": "bar",
|
||||
"KMS_PROVIDER": "vault",
|
||||
"VAULT_ADDR": "1.1.1.1",
|
||||
"VAULT_BACKEND_PATH": "vault",
|
||||
"VAULT_CACERT": "vault-ca-cert",
|
||||
"VAULT_SKIP_VERIFY": "false",
|
||||
}
|
||||
s := &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "vault-ca-cert",
|
||||
Namespace: ns,
|
||||
},
|
||||
Data: map[string][]byte{"cert": []byte("bar")},
|
||||
}
|
||||
_, err = context.Clientset.CoreV1().Secrets(ns).Create(s)
|
||||
assert.NoError(t, err)
|
||||
config, err = configTLS(context, ns, config)
|
||||
assert.NoError(t, err)
|
||||
assert.NotEqual(t, "vault-ca-cert", config["VAULT_CACERT"])
|
||||
err = context.Clientset.CoreV1().Secrets(ns).Delete(s.Name, &metav1.DeleteOptions{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
// All TLS success!
|
||||
config = map[string]string{
|
||||
"foo": "bar",
|
||||
"KMS_PROVIDER": "vault",
|
||||
"VAULT_ADDR": "1.1.1.1",
|
||||
"VAULT_BACKEND_PATH": "vault",
|
||||
"VAULT_CACERT": "vault-ca-cert",
|
||||
"VAULT_CLIENT_CERT": "vault-client-cert",
|
||||
"VAULT_CLIENT_KEY": "vault-client-key",
|
||||
}
|
||||
sCa := &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "vault-ca-cert",
|
||||
Namespace: ns,
|
||||
},
|
||||
Data: map[string][]byte{"cert": []byte("bar")},
|
||||
}
|
||||
sClCert := &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "vault-client-cert",
|
||||
Namespace: ns,
|
||||
},
|
||||
Data: map[string][]byte{"cert": []byte("bar")},
|
||||
}
|
||||
sClKey := &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "vault-client-key",
|
||||
Namespace: ns,
|
||||
},
|
||||
Data: map[string][]byte{"key": []byte("bar")},
|
||||
}
|
||||
_, err = context.Clientset.CoreV1().Secrets(ns).Create(sCa)
|
||||
assert.NoError(t, err)
|
||||
_, err = context.Clientset.CoreV1().Secrets(ns).Create(sClCert)
|
||||
assert.NoError(t, err)
|
||||
_, err = context.Clientset.CoreV1().Secrets(ns).Create(sClKey)
|
||||
assert.NoError(t, err)
|
||||
config, err = configTLS(context, ns, config)
|
||||
assert.NoError(t, err)
|
||||
assert.NotEqual(t, "vault-ca-cert", config["VAULT_CACERT"])
|
||||
assert.NotEqual(t, "vault-client-cert", config["VAULT_CLIENT_CERT"])
|
||||
assert.NotEqual(t, "vault-client-key", config["VAULT_CLIENT_KEY"])
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"github.com/hashicorp/vault/api"
|
||||
"github.com/libopenstorage/secrets"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
// Key name of the Secret containing the cert and client key
|
||||
vaultCACertSecretKeyName = "cert"
|
||||
vaultKeySecretKeyName = "key"
|
||||
|
||||
// File names of the Secret value when mapping on the filesystem
|
||||
vaultCAFileName = "vault.ca"
|
||||
vaultCertFileName = "vault.crt"
|
||||
vaultKeyFileName = "vault.key"
|
||||
)
|
||||
|
||||
// TLSSecretVolumeAndMount return the volume and matching volume mount for mounting the secrets into /etc/vault
|
||||
func TLSSecretVolumeAndMount(config map[string]string) []v1.VolumeProjection {
|
||||
// Projection list
|
||||
secretVolumeProjections := []v1.VolumeProjection{}
|
||||
|
||||
// File mode
|
||||
mode := int32(0400)
|
||||
|
||||
// Vault TLS Secrets
|
||||
for _, tlsOption := range vaultTLSConnectionDetails {
|
||||
tlsSecretName := GetParam(config, tlsOption)
|
||||
if tlsSecretName != "" {
|
||||
projectionSecret := &v1.SecretProjection{Items: []v1.KeyToPath{{Key: tlsSecretKeyToCheck(tlsOption), Path: tlsSecretPath(tlsOption), Mode: &mode}}}
|
||||
projectionSecret.Name = tlsSecretName
|
||||
secretProjection := v1.VolumeProjection{Secret: projectionSecret}
|
||||
secretVolumeProjections = append(secretVolumeProjections, secretProjection)
|
||||
}
|
||||
}
|
||||
|
||||
return secretVolumeProjections
|
||||
}
|
||||
|
||||
// VaultVolumeAndMount returns Vault volume and volume mount
|
||||
func VaultVolumeAndMount(config map[string]string) (v1.Volume, v1.VolumeMount) {
|
||||
v := v1.Volume{
|
||||
Name: secrets.TypeVault,
|
||||
VolumeSource: v1.VolumeSource{
|
||||
Projected: &v1.ProjectedVolumeSource{
|
||||
Sources: TLSSecretVolumeAndMount(config),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
m := v1.VolumeMount{
|
||||
Name: secrets.TypeVault,
|
||||
ReadOnly: true,
|
||||
MountPath: EtcVaultDir,
|
||||
}
|
||||
|
||||
return v, m
|
||||
}
|
||||
|
||||
func tlsSecretPath(tlsOption string) string {
|
||||
switch tlsOption {
|
||||
case api.EnvVaultCACert:
|
||||
return vaultCAFileName
|
||||
case api.EnvVaultClientCert:
|
||||
return vaultCertFileName
|
||||
case api.EnvVaultClientKey:
|
||||
return vaultKeyFileName
|
||||
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 kms
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
v1 "k8s.io/api/core/v1"
|
||||
)
|
||||
|
||||
func Test_tlsSecretPath(t *testing.T) {
|
||||
type args struct {
|
||||
tlsOption string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want string
|
||||
}{
|
||||
{"certificate", args{tlsOption: "VAULT_CACERT"}, "vault.ca"},
|
||||
{"client-certificate", args{tlsOption: "VAULT_CLIENT_CERT"}, "vault.crt"},
|
||||
{"client-key", args{tlsOption: "VAULT_CLIENT_KEY"}, "vault.key"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tlsSecretPath(tt.args.tlsOption); got != tt.want {
|
||||
t.Errorf("tlsSecretPath() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTLSSecretVolumeAndMount(t *testing.T) {
|
||||
m := int32(0400)
|
||||
type args struct {
|
||||
config map[string]string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want []v1.VolumeProjection
|
||||
}{
|
||||
{"empty", args{config: map[string]string{"foo": "bar"}}, []v1.VolumeProjection{}},
|
||||
{"single ca", args{config: map[string]string{"VAULT_CACERT": "vault-ca-secret"}}, []v1.VolumeProjection{
|
||||
{Secret: &v1.SecretProjection{LocalObjectReference: v1.LocalObjectReference{Name: "vault-ca-secret"}, Items: []v1.KeyToPath{{Key: "cert", Path: "vault.ca", Mode: &m}}, Optional: nil}}},
|
||||
},
|
||||
{"ca and client cert", args{config: map[string]string{"VAULT_CACERT": "vault-ca-secret", "VAULT_CLIENT_CERT": "vault-client-cert"}}, []v1.VolumeProjection{
|
||||
{Secret: &v1.SecretProjection{LocalObjectReference: v1.LocalObjectReference{Name: "vault-ca-secret"}, Items: []v1.KeyToPath{{Key: "cert", Path: "vault.ca", Mode: &m}}, Optional: nil}},
|
||||
{Secret: &v1.SecretProjection{LocalObjectReference: v1.LocalObjectReference{Name: "vault-client-cert"}, Items: []v1.KeyToPath{{Key: "cert", Path: "vault.crt", Mode: &m}}, Optional: nil}},
|
||||
}},
|
||||
{"ca and client cert/key", args{config: map[string]string{"VAULT_CACERT": "vault-ca-secret", "VAULT_CLIENT_CERT": "vault-client-cert", "VAULT_CLIENT_KEY": "vault-client-key"}}, []v1.VolumeProjection{
|
||||
{Secret: &v1.SecretProjection{LocalObjectReference: v1.LocalObjectReference{Name: "vault-ca-secret"}, Items: []v1.KeyToPath{{Key: "cert", Path: "vault.ca", Mode: &m}}, Optional: nil}},
|
||||
{Secret: &v1.SecretProjection{LocalObjectReference: v1.LocalObjectReference{Name: "vault-client-cert"}, Items: []v1.KeyToPath{{Key: "cert", Path: "vault.crt", Mode: &m}}, Optional: nil}},
|
||||
{Secret: &v1.SecretProjection{LocalObjectReference: v1.LocalObjectReference{Name: "vault-client-key"}, Items: []v1.KeyToPath{{Key: "key", Path: "vault.key", Mode: &m}}, Optional: nil}},
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := TLSSecretVolumeAndMount(tt.args.config); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("TLSSecretVolumeAndMount() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -331,7 +331,7 @@ func (a *OsdAgent) initializeBlockPVC(context *clusterd.Context, devices *Device
|
||||
}
|
||||
|
||||
// Return failure
|
||||
return "", "", "", errors.Wrapf(err, "failed to run ceph-volume. debug logs below:\n%s", cvLog)
|
||||
return "", "", "", errors.Wrapf(err, "failed to run ceph-volume. %s. debug logs below:\n%s", op, cvLog)
|
||||
}
|
||||
logger.Infof("%v", op)
|
||||
// if raw mode is used or PV on LV, let's return the path of the device
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/daemon/ceph/client"
|
||||
"github.com/rook/rook/pkg/daemon/ceph/osd/kms"
|
||||
"github.com/rook/rook/pkg/operator/ceph/cluster/crash"
|
||||
"github.com/rook/rook/pkg/operator/ceph/cluster/mgr"
|
||||
"github.com/rook/rook/pkg/operator/ceph/cluster/mon"
|
||||
@@ -371,6 +372,15 @@ func (c *ClusterController) preClusterStartValidation(cluster *cluster, clusterO
|
||||
}
|
||||
}
|
||||
|
||||
// Validate on-PVC cluster encryption KMS settings
|
||||
if cluster.Spec.Storage.IsOnPVCEncrypted() && cluster.Spec.Security.KeyManagementService.IsEnabled() {
|
||||
// Validate the KMS details
|
||||
err := kms.ValidateConnectionDetails(c.context, cluster.Spec, cluster.Namespace)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to validate kms connection details")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Debug("cluster spec successfully validated")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -28,6 +28,8 @@ import (
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/daemon/ceph/agent/flexvolume/attachment"
|
||||
cephclient "github.com/rook/rook/pkg/daemon/ceph/client"
|
||||
"github.com/rook/rook/pkg/daemon/ceph/osd/kms"
|
||||
"github.com/rook/rook/pkg/operator/ceph/cluster/osd"
|
||||
"github.com/rook/rook/pkg/operator/ceph/config"
|
||||
opcontroller "github.com/rook/rook/pkg/operator/ceph/controller"
|
||||
@@ -388,16 +390,26 @@ func (c *ClusterController) requestClusterDelete(cluster *cephv1.CephCluster) (r
|
||||
}
|
||||
}
|
||||
|
||||
if cluster, ok := c.clusterMap[cluster.Namespace]; ok {
|
||||
delete(c.clusterMap, cluster.Namespace)
|
||||
}
|
||||
|
||||
// Only valid when the cluster is not external
|
||||
if cluster.Spec.External.Enable {
|
||||
purgeExternalCluster(c.context.Clientset, cluster.Namespace)
|
||||
return reconcile.Result{}, true
|
||||
}
|
||||
|
||||
// If the StorageClass retain policy of an encrypted cluster with KMS is Delete we also delete the keys
|
||||
if cluster.Spec.Storage.IsOnPVCEncrypted() && cluster.Spec.Security.KeyManagementService.IsEnabled() {
|
||||
// Delete keys from KMS
|
||||
err := c.deleteOSDEncryptionKeyFromKMS(cluster)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to delete osd encryption keys from kms. %v", err)
|
||||
return reconcile.Result{}, true
|
||||
}
|
||||
}
|
||||
|
||||
if cluster, ok := c.clusterMap[cluster.Namespace]; ok {
|
||||
delete(c.clusterMap, cluster.Namespace)
|
||||
}
|
||||
|
||||
return reconcile.Result{}, true
|
||||
}
|
||||
|
||||
@@ -526,3 +538,39 @@ func removeFinalizer(client client.Client, name types.NamespacedName) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ClusterController) deleteOSDEncryptionKeyFromKMS(currentCluster *cephv1.CephCluster) error {
|
||||
// If the operator was stopped and we enter this code, the map is empty
|
||||
if _, ok := c.clusterMap[currentCluster.Namespace]; !ok {
|
||||
c.clusterMap[currentCluster.Namespace] = &cluster{ClusterInfo: &cephclient.ClusterInfo{Namespace: currentCluster.Namespace}}
|
||||
}
|
||||
|
||||
// Fetch PVCs
|
||||
osdPVCs, err := osd.GetExistingOSDPVCs(c.context, currentCluster.Namespace)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to list osd pvc")
|
||||
}
|
||||
|
||||
// Initialize the KMS code
|
||||
kmsConfig := kms.NewConfig(c.context, ¤tCluster.Spec, c.clusterMap[currentCluster.Namespace].ClusterInfo)
|
||||
|
||||
// If token auth is used by the KMS we set it as an env variable
|
||||
if currentCluster.Spec.Security.KeyManagementService.IsTokenAuthEnabled() {
|
||||
err := kms.SetTokenToEnvVar(c.context, currentCluster.Spec.Security.KeyManagementService.TokenSecretName, kmsConfig.Provider, currentCluster.Namespace)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to fetch kms token secret %q", currentCluster.Spec.Security.KeyManagementService.TokenSecretName)
|
||||
}
|
||||
}
|
||||
|
||||
// Delete each PV KEK
|
||||
for _, osdPVC := range osdPVCs {
|
||||
// Generate and store the encrypted key in whatever KMS is configured
|
||||
err = kmsConfig.DeleteSecret(osdPVC.Name)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to delete secret. %v", err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -19,6 +19,7 @@ package osd
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"path"
|
||||
"strconv"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
@@ -26,9 +27,7 @@ import (
|
||||
"github.com/rook/rook/pkg/operator/ceph/cluster/mgr"
|
||||
opconfig "github.com/rook/rook/pkg/operator/ceph/config"
|
||||
"github.com/rook/rook/pkg/operator/ceph/config/keyring"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -41,8 +40,6 @@ key = %s
|
||||
// #nosec G101 since this is not leaking any hardcoded credentials, it's just the secret key name
|
||||
OsdEncryptionSecretNameKeyName = "dmcrypt-key"
|
||||
dmCryptKeySize = 128
|
||||
// #nosec G101 since this is not leaking any hardcoded credentials, it's just the prefix of the secret name
|
||||
osdEncryptionSecretNamePrefix = "rook-ceph-osd-encryption-key"
|
||||
)
|
||||
|
||||
func (c *Cluster) generateKeyring(osdID int) (string, error) {
|
||||
@@ -84,7 +81,7 @@ func osdOnSDNFlag(network cephv1.NetworkSpec) []string {
|
||||
}
|
||||
|
||||
func encryptionKeyPath() string {
|
||||
return fmt.Sprintf("%s/%s", opconfig.EtcCephDir, encryptionKeyFileName)
|
||||
return path.Join(opconfig.EtcCephDir, encryptionKeyFileName)
|
||||
}
|
||||
|
||||
func encryptionDMName(pvcName, blockType string) string {
|
||||
@@ -92,7 +89,11 @@ func encryptionDMName(pvcName, blockType string) string {
|
||||
}
|
||||
|
||||
func encryptionDMPath(pvcName, blockType string) string {
|
||||
return fmt.Sprintf("/dev/mapper/%s", encryptionDMName(pvcName, blockType))
|
||||
return path.Join("/dev/mapper", encryptionDMName(pvcName, blockType))
|
||||
}
|
||||
|
||||
func encryptionBlockDestinationCopy(mountPath, blockType string) string {
|
||||
return path.Join(mountPath, blockType) + "-tmp"
|
||||
}
|
||||
|
||||
func generateDmCryptKey() (string, error) {
|
||||
@@ -104,26 +105,6 @@ func generateDmCryptKey() (string, error) {
|
||||
return base64.StdEncoding.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
func generateOSDEncryptedKeySecret(pvcName, namespace, key string) *v1.Secret {
|
||||
return &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: generateOSDEncryptionSecretName(pvcName),
|
||||
Namespace: namespace,
|
||||
Labels: map[string]string{
|
||||
"pvc_name": pvcName,
|
||||
},
|
||||
},
|
||||
StringData: map[string]string{
|
||||
OsdEncryptionSecretNameKeyName: key,
|
||||
},
|
||||
Type: k8sutil.RookType,
|
||||
}
|
||||
}
|
||||
|
||||
func generateOSDEncryptionSecretName(pvcName string) string {
|
||||
return fmt.Sprintf("%s-%s", osdEncryptionSecretNamePrefix, pvcName)
|
||||
}
|
||||
|
||||
func (c *Cluster) isCephVolumeRawModeSupported() bool {
|
||||
if c.clusterInfo.CephVersion.IsAtLeast(cephVolumeRawEncryptionModeMinNautilusCephVersion) && !c.clusterInfo.CephVersion.IsOctopus() {
|
||||
return true
|
||||
|
||||
@@ -43,8 +43,19 @@ func TestEncryptionKeyPath(t *testing.T) {
|
||||
assert.Equal(t, "/etc/ceph/luks_key", encryptionKeyPath())
|
||||
}
|
||||
|
||||
func TestGenerateOSDEncryptionSecretName(t *testing.T) {
|
||||
assert.Equal(t, "rook-ceph-osd-encryption-key-set1-data-0-7dwll", generateOSDEncryptionSecretName("set1-data-0-7dwll"))
|
||||
func TestEncryptionBlockDestinationCopy(t *testing.T) {
|
||||
m := "/var/lib/ceph/osd/ceph-0"
|
||||
assert.Equal(t, "/var/lib/ceph/osd/ceph-0/block-tmp", encryptionBlockDestinationCopy(m, bluestoreBlockName))
|
||||
assert.Equal(t, "/var/lib/ceph/osd/ceph-0/block.db-tmp", encryptionBlockDestinationCopy(m, bluestoreMetadataName))
|
||||
assert.Equal(t, "/var/lib/ceph/osd/ceph-0/block.wal-tmp", encryptionBlockDestinationCopy(m, bluestoreWalName))
|
||||
}
|
||||
|
||||
func TestEncryptionDMPath(t *testing.T) {
|
||||
assert.Equal(t, "/dev/mapper/set1-data-0-6rqdn-block-dmcrypt", encryptionDMPath("set1-data-0-6rqdn", DmcryptBlockType))
|
||||
}
|
||||
|
||||
func TestEncryptionDMName(t *testing.T) {
|
||||
assert.Equal(t, "set1-data-0-6rqdn-block-dmcrypt", encryptionDMName("set1-data-0-6rqdn", DmcryptBlockType))
|
||||
}
|
||||
|
||||
func TestClusterIsCephVolumeRAwModeSupported(t *testing.T) {
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
rookv1 "github.com/rook/rook/pkg/apis/rook.io/v1"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/ceph/controller"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
@@ -31,7 +32,7 @@ import (
|
||||
func (c *Cluster) prepareStorageClassDeviceSets(config *provisionConfig) []rookv1.VolumeSource {
|
||||
volumeSources := []rookv1.VolumeSource{}
|
||||
|
||||
existingPVCs, err := c.getExistingOSDPVCs()
|
||||
existingPVCs, err := GetExistingOSDPVCs(c.context, c.clusterInfo.Namespace)
|
||||
if err != nil {
|
||||
config.addError("failed to detect existing OSD PVCs. %v", err)
|
||||
return volumeSources
|
||||
@@ -177,9 +178,10 @@ func makeStorageClassDeviceSetPVC(storageClassDeviceSetName, pvcStorageClassDevi
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cluster) getExistingOSDPVCs() (map[string]*v1.PersistentVolumeClaim, error) {
|
||||
// GetExistingOSDPVCs fetches the list of OSD PVCs
|
||||
func GetExistingOSDPVCs(context *clusterd.Context, namespace string) (map[string]*v1.PersistentVolumeClaim, error) {
|
||||
selector := metav1.ListOptions{LabelSelector: CephDeviceSetPVCIDLabelKey}
|
||||
pvcs, err := c.context.Clientset.CoreV1().PersistentVolumeClaims(c.clusterInfo.Namespace).List(selector)
|
||||
pvcs, err := context.Clientset.CoreV1().PersistentVolumeClaims(namespace).List(selector)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to detect pvcs")
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rook/rook/pkg/daemon/ceph/client"
|
||||
kms "github.com/rook/rook/pkg/daemon/ceph/osd/kms"
|
||||
opmon "github.com/rook/rook/pkg/operator/ceph/cluster/mon"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"gopkg.in/ini.v1"
|
||||
@@ -33,6 +34,7 @@ const (
|
||||
osdsPerDeviceEnvVarName = "ROOK_OSDS_PER_DEVICE"
|
||||
// EncryptedDeviceEnvVarName is used in the pod spec to indicate whether the OSD is encrypted or not
|
||||
EncryptedDeviceEnvVarName = "ROOK_ENCRYPTED_DEVICE"
|
||||
PVCNameEnvVarName = "ROOK_PVC_NAME"
|
||||
// CephVolumeEncryptedKeyEnvVarName is the env variable used by ceph-volume to encrypt the OSD (raw mode)
|
||||
// Hardcoded in ceph-volume do NOT touch
|
||||
CephVolumeEncryptedKeyEnvVarName = "CEPH_VOLUME_DMCRYPT_SECRET"
|
||||
@@ -171,14 +173,20 @@ func crushDeviceClassEnvVar(crushDeviceClass string) v1.EnvVar {
|
||||
func encryptedDeviceEnvVar(encryptedDevice bool) v1.EnvVar {
|
||||
return v1.EnvVar{Name: EncryptedDeviceEnvVarName, Value: strconv.FormatBool(encryptedDevice)}
|
||||
}
|
||||
func pvcNameEnvVar(pvcName string) v1.EnvVar {
|
||||
return v1.EnvVar{Name: PVCNameEnvVarName, Value: pvcName}
|
||||
}
|
||||
|
||||
func cephVolumeRawEncryptedEnvVar(pvcName string) v1.EnvVar {
|
||||
func cephVolumeRawEncryptedEnvVarFromSecret(osdProps osdProperties) v1.EnvVar {
|
||||
return v1.EnvVar{
|
||||
Name: CephVolumeEncryptedKeyEnvVarName,
|
||||
ValueFrom: &v1.EnvVarSource{
|
||||
SecretKeyRef: &v1.SecretKeySelector{LocalObjectReference: v1.LocalObjectReference{
|
||||
Name: generateOSDEncryptionSecretName(pvcName)},
|
||||
Key: OsdEncryptionSecretNameKeyName},
|
||||
SecretKeyRef: &v1.SecretKeySelector{
|
||||
LocalObjectReference: v1.LocalObjectReference{
|
||||
Name: kms.GenerateOSDEncryptionSecretName(osdProps.pvc.ClaimName),
|
||||
},
|
||||
Key: kms.OsdEncryptionSecretNameKeyName,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ import (
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/daemon/ceph/client"
|
||||
cephclient "github.com/rook/rook/pkg/daemon/ceph/client"
|
||||
kms "github.com/rook/rook/pkg/daemon/ceph/osd/kms"
|
||||
"github.com/rook/rook/pkg/operator/ceph/cluster/mon"
|
||||
osdconfig "github.com/rook/rook/pkg/operator/ceph/cluster/osd/config"
|
||||
opconfig "github.com/rook/rook/pkg/operator/ceph/config"
|
||||
@@ -284,16 +285,24 @@ func (c *Cluster) startProvisioningOverPVCs(config *provisionConfig) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Store the kube secret here!
|
||||
s := generateOSDEncryptedKeySecret(osdProps.pvc.ClaimName, c.clusterInfo.Namespace, key)
|
||||
// Initialize the KMS code
|
||||
kmsConfig := kms.NewConfig(c.context, &c.spec, c.clusterInfo)
|
||||
|
||||
// Set the ownerref to the Secret
|
||||
k8sutil.SetOwnerRef(&s.ObjectMeta, &c.clusterInfo.OwnerRef)
|
||||
// We could set an env var in the Operator or a global var instead of the API call?
|
||||
// Hopefully, the API is cheap and we can always retrieve the token if it has changed...
|
||||
if c.spec.Security.KeyManagementService.IsTokenAuthEnabled() {
|
||||
err := kms.SetTokenToEnvVar(c.context, c.spec.Security.KeyManagementService.TokenSecretName, kmsConfig.Provider, c.clusterInfo.Namespace)
|
||||
if err != nil {
|
||||
errMsg := fmt.Sprintf("failed to fetch kms token secret %q", c.spec.Security.KeyManagementService.TokenSecretName)
|
||||
config.addError(errMsg)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Create the Kubernetes Secret
|
||||
_, err = c.context.Clientset.CoreV1().Secrets(c.clusterInfo.Namespace).Create(s)
|
||||
if err != nil && !kerrors.IsAlreadyExists(err) {
|
||||
errMsg := fmt.Sprintf("failed to save ceph osd encryption key as a secret for pvc %q. %v", osdProps.pvc.ClaimName, err)
|
||||
// Generate and store the encrypted key in whatever KMS is configured
|
||||
err = kmsConfig.PutSecret(osdProps.pvc.ClaimName, key)
|
||||
if err != nil {
|
||||
errMsg := fmt.Sprintf("failed to store secret. %v", err)
|
||||
config.addError(errMsg)
|
||||
continue
|
||||
}
|
||||
@@ -674,7 +683,6 @@ func (c *Cluster) resolveNode(nodeName string) *rookv1.Node {
|
||||
}
|
||||
|
||||
func (c *Cluster) getOSDPropsForPVC(pvcName string) (osdProperties, error) {
|
||||
|
||||
for _, volumeSource := range c.ValidStorage.VolumeSources {
|
||||
// The data PVC template is required.
|
||||
dataSource, dataOK := volumeSource.PVCSources[bluestorePVCData]
|
||||
|
||||
@@ -21,8 +21,10 @@ import (
|
||||
"fmt"
|
||||
"path"
|
||||
|
||||
"github.com/libopenstorage/secrets"
|
||||
"github.com/pkg/errors"
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
kms "github.com/rook/rook/pkg/daemon/ceph/osd/kms"
|
||||
"github.com/rook/rook/pkg/operator/ceph/cluster/osd/config"
|
||||
"github.com/rook/rook/pkg/operator/ceph/controller"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
@@ -113,6 +115,16 @@ func (c *Cluster) provisionPodTemplateSpec(osdProps osdProperties, restart v1.Re
|
||||
if osdProps.onPVC() {
|
||||
// Create volume config for PVCs
|
||||
volumes = append(volumes, getPVCOSDVolumes(&osdProps)...)
|
||||
if osdProps.encrypted {
|
||||
// If a KMS is configured we populate
|
||||
if c.spec.Security.KeyManagementService.IsEnabled() {
|
||||
kmsProvider := kms.GetParam(c.spec.Security.KeyManagementService.ConnectionDetails, kms.Provider)
|
||||
if kmsProvider == secrets.TypeVault {
|
||||
volumeTLS, _ := kms.VaultVolumeAndMount(c.spec.Security.KeyManagementService.ConnectionDetails)
|
||||
volumes = append(volumes, volumeTLS)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(volumes) == 0 {
|
||||
@@ -271,9 +283,20 @@ func (c *Cluster) provisionOSDContainer(osdProps osdProperties, copyBinariesMoun
|
||||
envVars = append(envVars, pvcBackedOSDEnvVar("true"))
|
||||
envVars = append(envVars, crushDeviceClassEnvVar(osdProps.crushDeviceClass))
|
||||
envVars = append(envVars, encryptedDeviceEnvVar(osdProps.encrypted))
|
||||
envVars = append(envVars, pvcNameEnvVar(osdProps.pvc.ClaimName))
|
||||
|
||||
if osdProps.encrypted {
|
||||
envVars = append(envVars, cephVolumeRawEncryptedEnvVar(osdProps.pvc.ClaimName))
|
||||
// If a KMS is configured we populate
|
||||
if c.spec.Security.KeyManagementService.IsEnabled() {
|
||||
kmsProvider := kms.GetParam(c.spec.Security.KeyManagementService.ConnectionDetails, kms.Provider)
|
||||
if kmsProvider == secrets.TypeVault {
|
||||
_, volumeMountsTLS := kms.VaultVolumeAndMount(c.spec.Security.KeyManagementService.ConnectionDetails)
|
||||
volumeMounts = append(volumeMounts, volumeMountsTLS)
|
||||
envVars = append(envVars, kms.VaultConfigToEnvVar(c.spec)...)
|
||||
}
|
||||
} else {
|
||||
envVars = append(envVars, cephVolumeRawEncryptedEnvVarFromSecret(osdProps))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,8 +22,10 @@ import (
|
||||
"path"
|
||||
"strconv"
|
||||
|
||||
"github.com/libopenstorage/secrets"
|
||||
"github.com/pkg/errors"
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
kms "github.com/rook/rook/pkg/daemon/ceph/osd/kms"
|
||||
opmon "github.com/rook/rook/pkg/operator/ceph/cluster/mon"
|
||||
"github.com/rook/rook/pkg/operator/ceph/cluster/osd/config"
|
||||
opconfig "github.com/rook/rook/pkg/operator/ceph/config"
|
||||
@@ -40,6 +42,7 @@ const (
|
||||
activateOSDVolumeName = "activate-osd"
|
||||
activateOSDMountPath = "/var/lib/ceph/osd/ceph-"
|
||||
blockPVCMapperInitContainer = "blkdevmapper"
|
||||
blockEncryptionKMSGetKEKInitContainer = "encryption-kms-get-kek"
|
||||
blockEncryptionOpenInitContainer = "encryption-open"
|
||||
blockEncryptionOpenMetadataInitContainer = "encryption-open-metadata"
|
||||
blockEncryptionOpenWalInitContainer = "encryption-open-wal"
|
||||
@@ -58,10 +61,10 @@ const (
|
||||
// DmcryptMetadataType is a portion of the device mapper name for the encrypted OSD on PVC block
|
||||
DmcryptMetadataType = "db-dmcrypt"
|
||||
// DmcryptWalType is a portion of the device mapper name for the encrypted OSD on PVC wal
|
||||
DmcryptWalType = "wal-dmcrypt"
|
||||
dmcryptBlockName = "block"
|
||||
dmcryptMetadataName = "block.db"
|
||||
dmcryptWalName = "block.wal"
|
||||
DmcryptWalType = "wal-dmcrypt"
|
||||
bluestoreBlockName = "block"
|
||||
bluestoreMetadataName = "block.db"
|
||||
bluestoreWalName = "block.wal"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -122,6 +125,9 @@ BLOCK_PATH=%s
|
||||
DM_NAME=%s
|
||||
DM_PATH=%s
|
||||
|
||||
# Helps debugging
|
||||
dmsetup version
|
||||
|
||||
function open_encrypted_block {
|
||||
echo "Opening encrypted device $BLOCK_PATH at $DM_PATH"
|
||||
cryptsetup luksOpen --verbose --disable-keyring --allow-discards --key-file "$KEY_FILE_PATH" "$BLOCK_PATH" "$DM_NAME"
|
||||
@@ -143,6 +149,49 @@ if [ -b "$DM_PATH" ]; then
|
||||
else
|
||||
open_encrypted_block
|
||||
fi
|
||||
`
|
||||
// #nosec G101 no leak just variable names
|
||||
getKEKFromVaultWithToken = `
|
||||
# DO NOT RUN WITH -x TO AVOID LEAKING VAULT_TOKEN
|
||||
set -e
|
||||
|
||||
KEK_NAME=%s
|
||||
KEY_PATH=%s
|
||||
VAULT_DEFAULT_BACKEND=v1
|
||||
CURL_PAYLOAD=$(mktemp)
|
||||
ARGS=(--request GET --header "X-Vault-Token: ${VAULT_TOKEN}")
|
||||
|
||||
# If a vault namespace is set
|
||||
if [ -n "$VAULT_NAMESPACE" ]; then
|
||||
ARGS+=(--header "X-Vault-Namespace: ${VAULT_NAMESPACE}")
|
||||
fi
|
||||
|
||||
# If SSL is configured but self-signed CA is used
|
||||
if [ -n "$VAULT_SKIP_VERIFY" ] && [[ "$VAULT_SKIP_VERIFY" == "true" ]]; then
|
||||
ARGS+=(--insecure)
|
||||
fi
|
||||
|
||||
# TLS args
|
||||
if [ -n "$VAULT_CACERT" ]; then
|
||||
ARGS+=(--cacert "${VAULT_CACERT}")
|
||||
fi
|
||||
if [ -n "$VAULT_CLIENT_CERT" ]; then
|
||||
ARGS+=(--cert "${VAULT_CLIENT_CERT}")
|
||||
fi
|
||||
if [ -n "$VAULT_CLIENT_KEY" ]; then
|
||||
ARGS+=(--key "${VAULT_CLIENT_KEY}")
|
||||
fi
|
||||
|
||||
# Check KV backend
|
||||
if [ -z "$VAULT_BACKEND" ]; then
|
||||
VAULT_BACKEND=$VAULT_DEFAULT_BACKEND
|
||||
fi
|
||||
|
||||
# Get the Key Encryption Key
|
||||
curl "${ARGS[@]}" "$VAULT_ADDR"/"$VAULT_BACKEND"/"$VAULT_BACKEND_PATH"/"$KEK_NAME" > "$CURL_PAYLOAD"
|
||||
|
||||
# Put the KEK in a file for cryptsetup to read
|
||||
python3 -c "import sys, json; print(json.load(sys.stdin)[\"data\"][\"$KEK_NAME\"], end='')" < "$CURL_PAYLOAD" > "$KEY_PATH"
|
||||
`
|
||||
)
|
||||
|
||||
@@ -170,6 +219,12 @@ var defaultTuneSlowSettings = map[string]string{
|
||||
"osd_delete_sleep": "2", // Time in seconds to sleep before next removal transaction
|
||||
}
|
||||
|
||||
var cpArgs = []string{
|
||||
"--archive", // Archive mode preserves the specified attributes
|
||||
"--dereference", // always follow symbolic links in SOURCE to avoid broken links when copying dm devs
|
||||
"--verbose",
|
||||
}
|
||||
|
||||
func (c *Cluster) makeDeployment(osdProps osdProperties, osd OSDInfo, provisionConfig *provisionConfig) (*apps.Deployment, error) {
|
||||
// If running on Octopus, we don't need to use the host PID namespace
|
||||
var hostPID = !c.clusterInfo.CephVersion.IsAtLeastOctopus()
|
||||
@@ -210,8 +265,12 @@ func (c *Cluster) makeDeployment(osdProps osdProperties, osd OSDInfo, provisionC
|
||||
volumes = append(volumes, getPVCOSDVolumes(&osdProps)...)
|
||||
// If encrypted let's add the secret key mount path
|
||||
if osdProps.encrypted && osd.CVMode == "raw" {
|
||||
encryptedVol, _ := getEncryptionVolume(osdProps.pvc.ClaimName)
|
||||
encryptedVol, _ := c.getEncryptionVolume(osdProps)
|
||||
volumes = append(volumes, encryptedVol)
|
||||
if c.spec.Security.KeyManagementService.IsEnabled() {
|
||||
encryptedVol, _ := kms.VaultVolumeAndMount(c.spec.Security.KeyManagementService.ConnectionDetails)
|
||||
volumes = append(volumes, encryptedVol)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,7 +433,7 @@ func (c *Cluster) makeDeployment(osdProps osdProperties, osd OSDInfo, provisionC
|
||||
}
|
||||
|
||||
// needed for luksOpen synchronization when devices are encrypted and the osd is prepared with LVM
|
||||
hostIPC := osdProps.storeConfig.EncryptedDevice
|
||||
hostIPC := osdProps.storeConfig.EncryptedDevice || osdProps.encrypted
|
||||
|
||||
initContainers := make([]v1.Container, 0, 4)
|
||||
if doConfigInit {
|
||||
@@ -396,23 +455,25 @@ func (c *Cluster) makeDeployment(osdProps osdProperties, osd OSDInfo, provisionC
|
||||
}
|
||||
|
||||
if osdProps.onPVC() && osd.CVMode == "raw" {
|
||||
// Copy main block device to an empty dir
|
||||
initContainers = append(initContainers, c.getPVCInitContainerActivate(osdDataDirPath, osdProps))
|
||||
// Copy main block.db device to an empty dir
|
||||
if osdProps.onPVCWithMetadata() {
|
||||
initContainers = append(initContainers, c.getPVCMetadataInitContainerActivate(osdDataDirPath, osdProps))
|
||||
}
|
||||
// Copy main block.wal device to an empty dir
|
||||
if osdProps.onPVCWithWal() {
|
||||
initContainers = append(initContainers, c.getPVCWalInitContainerActivate(osdDataDirPath, osdProps))
|
||||
}
|
||||
if osdProps.encrypted {
|
||||
// Open the encrypted disk
|
||||
initContainers = append(initContainers, c.getPVCEncryptionOpenInitContainerActivate(osdProps)...)
|
||||
initContainers = append(initContainers, c.getPVCEncryptionOpenInitContainerActivate(osdDataDirPath, osdProps)...)
|
||||
// Copy the encrypted block to the osd data location, e,g: /var/lib/ceph/osd/ceph-0/block
|
||||
initContainers = append(initContainers, c.getPVCEncryptionInitContainerActivate(osdDataDirPath, osdProps)...)
|
||||
// Print the encrypted block status
|
||||
initContainers = append(initContainers, c.getEncryptedStatusPVCInitContainer(osdDataDirPath, osdProps))
|
||||
// Resize the encrypted device if necessary, this must be done after the encrypted block is opened
|
||||
initContainers = append(initContainers, c.getExpandEncryptedPVCInitContainer(osdDataDirPath, osdProps))
|
||||
} else {
|
||||
initContainers = append(initContainers, c.getPVCInitContainerActivate(osdDataDirPath, osdProps))
|
||||
if osdProps.onPVCWithMetadata() {
|
||||
initContainers = append(initContainers, c.getPVCMetadataInitContainerActivate(osdDataDirPath, osdProps))
|
||||
}
|
||||
if osdProps.onPVCWithWal() {
|
||||
initContainers = append(initContainers, c.getPVCWalInitContainerActivate(osdDataDirPath, osdProps))
|
||||
}
|
||||
}
|
||||
initContainers = append(initContainers, c.getActivatePVCInitContainer(osdProps, osdID))
|
||||
initContainers = append(initContainers, c.getExpandPVCInitContainer(osdProps, osdID))
|
||||
@@ -638,25 +699,30 @@ func (c *Cluster) getPVCInitContainer(osdProps osdProperties) v1.Container {
|
||||
Command: []string{
|
||||
"cp",
|
||||
},
|
||||
Args: []string{"-a", fmt.Sprintf("/%s", osdProps.pvc.ClaimName), fmt.Sprintf("/mnt/%s", osdProps.pvc.ClaimName)},
|
||||
Args: append(cpArgs, fmt.Sprintf("/%s", osdProps.pvc.ClaimName), fmt.Sprintf("/mnt/%s", osdProps.pvc.ClaimName)),
|
||||
VolumeDevices: []v1.VolumeDevice{
|
||||
{
|
||||
Name: osdProps.pvc.ClaimName,
|
||||
DevicePath: fmt.Sprintf("/%s", osdProps.pvc.ClaimName),
|
||||
},
|
||||
},
|
||||
VolumeMounts: []v1.VolumeMount{
|
||||
{
|
||||
MountPath: "/mnt",
|
||||
Name: fmt.Sprintf("%s-bridge", osdProps.pvc.ClaimName),
|
||||
},
|
||||
},
|
||||
VolumeMounts: []v1.VolumeMount{getPvcOSDBridgeMount(osdProps.pvc.ClaimName)},
|
||||
SecurityContext: opmon.PodSecurityContext(),
|
||||
Resources: osdProps.resources,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cluster) getPVCInitContainerActivate(mountPath string, osdProps osdProperties) v1.Container {
|
||||
cpDestinationName := path.Join(mountPath, bluestoreBlockName)
|
||||
// Encrypted is a special
|
||||
// We have an initial "cp" to copy the pvc to an empty dir, typically we copy it in /var/lib/ceph/osd/ceph-0/block
|
||||
// BUT we encryption we need a second block copy, the copy of the opened encrypted block which ultimately will be at /var/lib/ceph/osd/ceph-0/block
|
||||
// So when encrypted we first copy to /var/lib/ceph/osd/ceph-0/block-tmp
|
||||
// Then open the encrypted block and finally copy it to /var/lib/ceph/osd/ceph-0/block
|
||||
// If we don't do this "cp" will fail to copy the special block file
|
||||
if osdProps.encrypted {
|
||||
cpDestinationName = encryptionBlockDestinationCopy(mountPath, bluestoreBlockName)
|
||||
}
|
||||
|
||||
return v1.Container{
|
||||
Name: blockPVCMapperInitContainer,
|
||||
@@ -664,7 +730,7 @@ func (c *Cluster) getPVCInitContainerActivate(mountPath string, osdProps osdProp
|
||||
Command: []string{
|
||||
"cp",
|
||||
},
|
||||
Args: []string{"-a", fmt.Sprintf("/%s", osdProps.pvc.ClaimName), path.Join(mountPath, dmcryptBlockName)},
|
||||
Args: append(cpArgs, fmt.Sprintf("/%s", osdProps.pvc.ClaimName), cpDestinationName),
|
||||
VolumeDevices: []v1.VolumeDevice{
|
||||
{
|
||||
Name: osdProps.pvc.ClaimName,
|
||||
@@ -677,7 +743,7 @@ func (c *Cluster) getPVCInitContainerActivate(mountPath string, osdProps osdProp
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cluster) generateEncryptionOpenBlockContainer(resources v1.ResourceRequirements, containerName, pvcName, blockType string) v1.Container {
|
||||
func (c *Cluster) generateEncryptionOpenBlockContainer(resources v1.ResourceRequirements, containerName, pvcName, volumeMountPVCName, cryptBlockType, blockType, mountPath string) v1.Container {
|
||||
return v1.Container{
|
||||
Name: containerName,
|
||||
Image: c.spec.CephVersion.Image,
|
||||
@@ -686,43 +752,73 @@ func (c *Cluster) generateEncryptionOpenBlockContainer(resources v1.ResourceRequ
|
||||
Command: []string{
|
||||
"/bin/bash",
|
||||
"-c",
|
||||
fmt.Sprintf(openEncryptedBlock, encryptionKeyPath(), fmt.Sprintf("/%s", pvcName), encryptionDMName(pvcName, blockType), encryptionDMPath(pvcName, blockType)),
|
||||
fmt.Sprintf(openEncryptedBlock, encryptionKeyPath(), encryptionBlockDestinationCopy(mountPath, blockType), encryptionDMName(pvcName, cryptBlockType), encryptionDMPath(pvcName, cryptBlockType)),
|
||||
},
|
||||
VolumeDevices: []v1.VolumeDevice{
|
||||
{
|
||||
Name: pvcName,
|
||||
DevicePath: fmt.Sprintf("/%s", pvcName),
|
||||
},
|
||||
},
|
||||
VolumeMounts: []v1.VolumeMount{getDeviceMapperMount()},
|
||||
SecurityContext: opmon.PodSecurityContext(),
|
||||
VolumeMounts: []v1.VolumeMount{getPvcOSDBridgeMountActivate(mountPath, volumeMountPVCName), getDeviceMapperMount()},
|
||||
SecurityContext: PrivilegedContext(),
|
||||
Resources: resources,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cluster) getPVCEncryptionOpenInitContainerActivate(osdProps osdProperties) []v1.Container {
|
||||
func (c *Cluster) generateVaultGetKEK(osdProps osdProperties) v1.Container {
|
||||
return v1.Container{
|
||||
Name: blockEncryptionKMSGetKEKInitContainer,
|
||||
Image: c.spec.CephVersion.Image,
|
||||
Command: []string{
|
||||
"/bin/bash",
|
||||
"-c",
|
||||
fmt.Sprintf(getKEKFromVaultWithToken, kms.GenerateOSDEncryptionSecretName(osdProps.pvc.ClaimName), encryptionKeyPath()),
|
||||
},
|
||||
Env: kms.VaultConfigToEnvVar(c.spec),
|
||||
Resources: osdProps.resources,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cluster) getPVCEncryptionOpenInitContainerActivate(mountPath string, osdProps osdProperties) []v1.Container {
|
||||
containers := []v1.Container{}
|
||||
|
||||
// If a KMS is enabled we need to add an init container to fetch the KEK
|
||||
if c.spec.Security.KeyManagementService.IsEnabled() {
|
||||
kmsProvider := kms.GetParam(c.spec.Security.KeyManagementService.ConnectionDetails, kms.Provider)
|
||||
// Get Vault KEK from KMS container
|
||||
if kmsProvider == secrets.TypeVault {
|
||||
if c.spec.Security.KeyManagementService.IsTokenAuthEnabled() {
|
||||
getKEKFromKMSContainer := c.generateVaultGetKEK(osdProps)
|
||||
|
||||
// Volume mount to store the encrypted key
|
||||
_, volMount := c.getEncryptionVolume(osdProps)
|
||||
getKEKFromKMSContainer.VolumeMounts = append(getKEKFromKMSContainer.VolumeMounts, volMount)
|
||||
|
||||
// Now let's see if there is a TLS config we need to mount as well
|
||||
_, vaultVolMount := kms.VaultVolumeAndMount(c.spec.Security.KeyManagementService.ConnectionDetails)
|
||||
getKEKFromKMSContainer.VolumeMounts = append(getKEKFromKMSContainer.VolumeMounts, vaultVolMount)
|
||||
|
||||
// Add the container to the list of containers
|
||||
containers = append(containers, getKEKFromKMSContainer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Main block container
|
||||
blockContainer := c.generateEncryptionOpenBlockContainer(osdProps.resources, blockEncryptionOpenInitContainer, osdProps.pvc.ClaimName, DmcryptBlockType)
|
||||
_, volMount := getEncryptionVolume(osdProps.pvc.ClaimName)
|
||||
blockContainer := c.generateEncryptionOpenBlockContainer(osdProps.resources, blockEncryptionOpenInitContainer, osdProps.pvc.ClaimName, osdProps.pvc.ClaimName, DmcryptBlockType, bluestoreBlockName, mountPath)
|
||||
_, volMount := c.getEncryptionVolume(osdProps)
|
||||
blockContainer.VolumeMounts = append(blockContainer.VolumeMounts, volMount)
|
||||
containers = append(containers, blockContainer)
|
||||
|
||||
// If there is a metadata PVC
|
||||
if osdProps.metadataPVC.ClaimName != "" {
|
||||
metadataContainer := c.generateEncryptionOpenBlockContainer(osdProps.resources, blockEncryptionOpenMetadataInitContainer, osdProps.metadataPVC.ClaimName, DmcryptMetadataType)
|
||||
if osdProps.onPVCWithMetadata() {
|
||||
metadataContainer := c.generateEncryptionOpenBlockContainer(osdProps.resources, blockEncryptionOpenMetadataInitContainer, osdProps.metadataPVC.ClaimName, osdProps.pvc.ClaimName, DmcryptMetadataType, bluestoreMetadataName, mountPath)
|
||||
// We use the same key for both block and block.db so we must use osdProps.pvc.ClaimName for the getEncryptionVolume()
|
||||
_, volMount := getEncryptionVolume(osdProps.pvc.ClaimName)
|
||||
_, volMount := c.getEncryptionVolume(osdProps)
|
||||
metadataContainer.VolumeMounts = append(metadataContainer.VolumeMounts, volMount)
|
||||
containers = append(containers, metadataContainer)
|
||||
}
|
||||
|
||||
// If there is a wal PVC
|
||||
if osdProps.walPVC.ClaimName != "" {
|
||||
metadataContainer := c.generateEncryptionOpenBlockContainer(osdProps.resources, blockEncryptionOpenWalInitContainer, osdProps.walPVC.ClaimName, DmcryptWalType)
|
||||
if osdProps.onPVCWithWal() {
|
||||
metadataContainer := c.generateEncryptionOpenBlockContainer(osdProps.resources, blockEncryptionOpenWalInitContainer, osdProps.walPVC.ClaimName, osdProps.pvc.ClaimName, DmcryptWalType, bluestoreWalName, mountPath)
|
||||
// We use the same key for both block and block.db so we must use osdProps.pvc.ClaimName for the getEncryptionVolume()
|
||||
_, volMount := getEncryptionVolume(osdProps.pvc.ClaimName)
|
||||
_, volMount := c.getEncryptionVolume(osdProps)
|
||||
metadataContainer.VolumeMounts = append(metadataContainer.VolumeMounts, volMount)
|
||||
containers = append(containers, metadataContainer)
|
||||
}
|
||||
@@ -737,10 +833,10 @@ func (c *Cluster) generateEncryptionCopyBlockContainer(resources v1.ResourceRequ
|
||||
Command: []string{
|
||||
"cp",
|
||||
},
|
||||
Args: []string{"-a", encryptionDMPath(pvcName, blockType), path.Join(mountPath, blockName)},
|
||||
Args: append(cpArgs, encryptionDMPath(pvcName, blockType), path.Join(mountPath, blockName)),
|
||||
// volumeMountPVCName is crucial, especially when the block we copy is the metadata block
|
||||
// its value must be the name of the block PV so that all init containers use the same bridge (the emptyDir shared by all the init containers)
|
||||
VolumeMounts: []v1.VolumeMount{getPvcOSDBridgeMountActivate(mountPath, volumeMountPVCName)},
|
||||
VolumeMounts: []v1.VolumeMount{getPvcOSDBridgeMountActivate(mountPath, volumeMountPVCName), getDeviceMapperMount()},
|
||||
SecurityContext: opmon.PodSecurityContext(),
|
||||
Resources: resources,
|
||||
}
|
||||
@@ -748,16 +844,16 @@ func (c *Cluster) generateEncryptionCopyBlockContainer(resources v1.ResourceRequ
|
||||
|
||||
func (c *Cluster) getPVCEncryptionInitContainerActivate(mountPath string, osdProps osdProperties) []v1.Container {
|
||||
containers := []v1.Container{}
|
||||
containers = append(containers, c.generateEncryptionCopyBlockContainer(osdProps.resources, blockPVCMapperEncryptionInitContainer, osdProps.pvc.ClaimName, mountPath, osdProps.pvc.ClaimName, dmcryptBlockName, DmcryptBlockType))
|
||||
containers = append(containers, c.generateEncryptionCopyBlockContainer(osdProps.resources, blockPVCMapperEncryptionInitContainer, osdProps.pvc.ClaimName, mountPath, osdProps.pvc.ClaimName, bluestoreBlockName, DmcryptBlockType))
|
||||
|
||||
// If there is a metadata PVC
|
||||
if osdProps.metadataPVC.ClaimName != "" {
|
||||
containers = append(containers, c.generateEncryptionCopyBlockContainer(osdProps.resources, blockPVCMapperEncryptionMetadataInitContainer, osdProps.metadataPVC.ClaimName, mountPath, osdProps.pvc.ClaimName, dmcryptMetadataName, DmcryptMetadataType))
|
||||
containers = append(containers, c.generateEncryptionCopyBlockContainer(osdProps.resources, blockPVCMapperEncryptionMetadataInitContainer, osdProps.metadataPVC.ClaimName, mountPath, osdProps.pvc.ClaimName, bluestoreMetadataName, DmcryptMetadataType))
|
||||
}
|
||||
|
||||
// If there is a wal PVC
|
||||
if osdProps.walPVC.ClaimName != "" {
|
||||
containers = append(containers, c.generateEncryptionCopyBlockContainer(osdProps.resources, blockPVCMapperEncryptionWalInitContainer, osdProps.walPVC.ClaimName, mountPath, osdProps.pvc.ClaimName, dmcryptWalName, DmcryptWalType))
|
||||
containers = append(containers, c.generateEncryptionCopyBlockContainer(osdProps.resources, blockPVCMapperEncryptionWalInitContainer, osdProps.walPVC.ClaimName, mountPath, osdProps.pvc.ClaimName, bluestoreWalName, DmcryptWalType))
|
||||
}
|
||||
|
||||
return containers
|
||||
@@ -774,7 +870,7 @@ func (c *Cluster) getPVCMetadataInitContainer(mountPath string, osdProps osdProp
|
||||
Command: []string{
|
||||
"cp",
|
||||
},
|
||||
Args: []string{"-a", fmt.Sprintf("/%s", osdProps.metadataPVC.ClaimName), fmt.Sprintf("/srv/%s", osdProps.metadataPVC.ClaimName)},
|
||||
Args: append(cpArgs, fmt.Sprintf("/%s", osdProps.metadataPVC.ClaimName), fmt.Sprintf("/srv/%s", osdProps.metadataPVC.ClaimName)),
|
||||
VolumeDevices: []v1.VolumeDevice{
|
||||
{
|
||||
Name: osdProps.metadataPVC.ClaimName,
|
||||
@@ -793,13 +889,24 @@ func (c *Cluster) getPVCMetadataInitContainer(mountPath string, osdProps osdProp
|
||||
}
|
||||
|
||||
func (c *Cluster) getPVCMetadataInitContainerActivate(mountPath string, osdProps osdProperties) v1.Container {
|
||||
cpDestinationName := path.Join(mountPath, bluestoreMetadataName)
|
||||
// Encrypted is a special
|
||||
// We have an initial "cp" to copy the pvc to an empty dir, typically we copy it in /var/lib/ceph/osd/ceph-0/block
|
||||
// BUT we encryption we need a second block copy, the copy of the opened encrypted block which ultimately will be at /var/lib/ceph/osd/ceph-0/block
|
||||
// So when encrypted we first copy to /var/lib/ceph/osd/ceph-0/block-tmp
|
||||
// Then open the encrypted block and finally copy it to /var/lib/ceph/osd/ceph-0/block
|
||||
// If we don't do this "cp" will fail to copy the special block file
|
||||
if osdProps.encrypted {
|
||||
cpDestinationName = encryptionBlockDestinationCopy(mountPath, bluestoreMetadataName)
|
||||
}
|
||||
|
||||
return v1.Container{
|
||||
Name: blockPVCMetadataMapperInitContainer,
|
||||
Image: c.spec.CephVersion.Image,
|
||||
Command: []string{
|
||||
"cp",
|
||||
},
|
||||
Args: []string{"-a", fmt.Sprintf("/%s", osdProps.metadataPVC.ClaimName), path.Join(mountPath, "block.db")},
|
||||
Args: append(cpArgs, fmt.Sprintf("/%s", osdProps.metadataPVC.ClaimName), cpDestinationName),
|
||||
VolumeDevices: []v1.VolumeDevice{
|
||||
{
|
||||
Name: osdProps.metadataPVC.ClaimName,
|
||||
@@ -821,7 +928,7 @@ func (c *Cluster) getPVCWalInitContainer(mountPath string, osdProps osdPropertie
|
||||
Command: []string{
|
||||
"cp",
|
||||
},
|
||||
Args: []string{"-a", fmt.Sprintf("/%s", osdProps.walPVC.ClaimName), fmt.Sprintf("/wal/%s", osdProps.walPVC.ClaimName)},
|
||||
Args: append(cpArgs, fmt.Sprintf("/%s", osdProps.walPVC.ClaimName), fmt.Sprintf("/wal/%s", osdProps.walPVC.ClaimName)),
|
||||
VolumeDevices: []v1.VolumeDevice{
|
||||
{
|
||||
Name: osdProps.walPVC.ClaimName,
|
||||
@@ -840,13 +947,24 @@ func (c *Cluster) getPVCWalInitContainer(mountPath string, osdProps osdPropertie
|
||||
}
|
||||
|
||||
func (c *Cluster) getPVCWalInitContainerActivate(mountPath string, osdProps osdProperties) v1.Container {
|
||||
cpDestinationName := path.Join(mountPath, bluestoreWalName)
|
||||
// Encrypted is a special
|
||||
// We have an initial "cp" to copy the pvc to an empty dir, typically we copy it in /var/lib/ceph/osd/ceph-0/block
|
||||
// BUT we encryption we need a second block copy, the copy of the opened encrypted block which ultimately will be at /var/lib/ceph/osd/ceph-0/block
|
||||
// So when encrypted we first copy to /var/lib/ceph/osd/ceph-0/block-tmp
|
||||
// Then open the encrypted block and finally copy it to /var/lib/ceph/osd/ceph-0/block
|
||||
// If we don't do this "cp" will fail to copy the special block file
|
||||
if osdProps.encrypted {
|
||||
cpDestinationName = encryptionBlockDestinationCopy(mountPath, bluestoreWalName)
|
||||
}
|
||||
|
||||
return v1.Container{
|
||||
Name: blockPVCWalMapperInitContainer,
|
||||
Image: c.spec.CephVersion.Image,
|
||||
Command: []string{
|
||||
"cp",
|
||||
},
|
||||
Args: []string{"-a", fmt.Sprintf("/%s", osdProps.walPVC.ClaimName), path.Join(mountPath, "block.wal")},
|
||||
Args: append(cpArgs, fmt.Sprintf("/%s", osdProps.walPVC.ClaimName), cpDestinationName),
|
||||
VolumeDevices: []v1.VolumeDevice{
|
||||
{
|
||||
Name: osdProps.walPVC.ClaimName,
|
||||
|
||||
@@ -217,18 +217,20 @@ func testPodDevices(t *testing.T, dataDir, deviceName string, allDevices bool) {
|
||||
deployment, err = c.makeDeployment(osdProp, osd, dataPathMap)
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, deployment)
|
||||
assert.Equal(t, 7, len(deployment.Spec.Template.Spec.InitContainers), deployment.Spec.Template.Spec.InitContainers[2].Name)
|
||||
assert.Equal(t, "encryption-open", deployment.Spec.Template.Spec.InitContainers[0].Name)
|
||||
assert.Equal(t, "blkdevmapper-encryption", deployment.Spec.Template.Spec.InitContainers[1].Name)
|
||||
assert.Equal(t, "encrypted-block-status", deployment.Spec.Template.Spec.InitContainers[2].Name)
|
||||
assert.Equal(t, "expand-encrypted-bluefs", deployment.Spec.Template.Spec.InitContainers[3].Name)
|
||||
assert.Equal(t, "activate", deployment.Spec.Template.Spec.InitContainers[4].Name)
|
||||
assert.Equal(t, "expand-bluefs", deployment.Spec.Template.Spec.InitContainers[5].Name)
|
||||
assert.Equal(t, "chown-container-data-dir", deployment.Spec.Template.Spec.InitContainers[6].Name)
|
||||
assert.Equal(t, 8, len(deployment.Spec.Template.Spec.InitContainers), deployment.Spec.Template.Spec.InitContainers[2].Name)
|
||||
assert.Equal(t, "blkdevmapper", deployment.Spec.Template.Spec.InitContainers[0].Name)
|
||||
assert.Equal(t, "encryption-open", deployment.Spec.Template.Spec.InitContainers[1].Name)
|
||||
assert.Equal(t, "blkdevmapper-encryption", deployment.Spec.Template.Spec.InitContainers[2].Name)
|
||||
assert.Equal(t, "encrypted-block-status", deployment.Spec.Template.Spec.InitContainers[3].Name)
|
||||
assert.Equal(t, "expand-encrypted-bluefs", deployment.Spec.Template.Spec.InitContainers[4].Name)
|
||||
assert.Equal(t, "activate", deployment.Spec.Template.Spec.InitContainers[5].Name)
|
||||
assert.Equal(t, "expand-bluefs", deployment.Spec.Template.Spec.InitContainers[6].Name)
|
||||
assert.Equal(t, "chown-container-data-dir", deployment.Spec.Template.Spec.InitContainers[7].Name)
|
||||
assert.Equal(t, 1, len(deployment.Spec.Template.Spec.Containers))
|
||||
cont = deployment.Spec.Template.Spec.Containers[0]
|
||||
assert.Equal(t, 7, len(cont.VolumeMounts), cont.VolumeMounts)
|
||||
osdProp.encrypted = false
|
||||
assert.Equal(t, 9, len(deployment.Spec.Template.Spec.Volumes), deployment.Spec.Template.Spec.Volumes)
|
||||
|
||||
// // Test OSD on PVC with RAW and metadata device
|
||||
osd = OSDInfo{
|
||||
@@ -252,6 +254,7 @@ func testPodDevices(t *testing.T, dataDir, deviceName string, allDevices bool) {
|
||||
assert.Equal(t, 1, len(blkInitCont.VolumeDevices))
|
||||
blkMetaInitCont := deployment.Spec.Template.Spec.InitContainers[2]
|
||||
assert.Equal(t, 1, len(blkMetaInitCont.VolumeDevices))
|
||||
assert.Equal(t, 9, len(deployment.Spec.Template.Spec.Volumes), deployment.Spec.Template.Spec.Volumes)
|
||||
|
||||
// // Test encrypted OSD on PVC with RAW and metadata device
|
||||
osd = OSDInfo{
|
||||
@@ -263,24 +266,27 @@ func testPodDevices(t *testing.T, dataDir, deviceName string, allDevices bool) {
|
||||
deployment, err = c.makeDeployment(osdProp, osd, dataPathMap)
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, deployment)
|
||||
assert.Equal(t, 9, len(deployment.Spec.Template.Spec.InitContainers))
|
||||
assert.Equal(t, "encryption-open", deployment.Spec.Template.Spec.InitContainers[0].Name)
|
||||
assert.Equal(t, "encryption-open-metadata", deployment.Spec.Template.Spec.InitContainers[1].Name)
|
||||
assert.Equal(t, "blkdevmapper-encryption", deployment.Spec.Template.Spec.InitContainers[2].Name)
|
||||
assert.Equal(t, "blkdevmapper-metadata-encryption", deployment.Spec.Template.Spec.InitContainers[3].Name)
|
||||
assert.Equal(t, "encrypted-block-status", deployment.Spec.Template.Spec.InitContainers[4].Name)
|
||||
assert.Equal(t, "expand-encrypted-bluefs", deployment.Spec.Template.Spec.InitContainers[5].Name)
|
||||
assert.Equal(t, "activate", deployment.Spec.Template.Spec.InitContainers[6].Name)
|
||||
assert.Equal(t, "expand-bluefs", deployment.Spec.Template.Spec.InitContainers[7].Name)
|
||||
assert.Equal(t, "chown-container-data-dir", deployment.Spec.Template.Spec.InitContainers[8].Name)
|
||||
assert.Equal(t, 11, len(deployment.Spec.Template.Spec.InitContainers))
|
||||
assert.Equal(t, "blkdevmapper", deployment.Spec.Template.Spec.InitContainers[0].Name)
|
||||
assert.Equal(t, "blkdevmapper-metadata", deployment.Spec.Template.Spec.InitContainers[1].Name)
|
||||
assert.Equal(t, "encryption-open", deployment.Spec.Template.Spec.InitContainers[2].Name)
|
||||
assert.Equal(t, "encryption-open-metadata", deployment.Spec.Template.Spec.InitContainers[3].Name)
|
||||
assert.Equal(t, "blkdevmapper-encryption", deployment.Spec.Template.Spec.InitContainers[4].Name)
|
||||
assert.Equal(t, "blkdevmapper-metadata-encryption", deployment.Spec.Template.Spec.InitContainers[5].Name)
|
||||
assert.Equal(t, "encrypted-block-status", deployment.Spec.Template.Spec.InitContainers[6].Name)
|
||||
assert.Equal(t, "expand-encrypted-bluefs", deployment.Spec.Template.Spec.InitContainers[7].Name)
|
||||
assert.Equal(t, "activate", deployment.Spec.Template.Spec.InitContainers[8].Name)
|
||||
assert.Equal(t, "expand-bluefs", deployment.Spec.Template.Spec.InitContainers[9].Name)
|
||||
assert.Equal(t, "chown-container-data-dir", deployment.Spec.Template.Spec.InitContainers[10].Name)
|
||||
assert.Equal(t, 1, len(deployment.Spec.Template.Spec.Containers))
|
||||
cont = deployment.Spec.Template.Spec.Containers[0]
|
||||
assert.Equal(t, 7, len(cont.VolumeMounts), cont.VolumeMounts)
|
||||
blkInitCont = deployment.Spec.Template.Spec.InitContainers[1]
|
||||
assert.Equal(t, 1, len(blkInitCont.VolumeDevices))
|
||||
blkMetaInitCont = deployment.Spec.Template.Spec.InitContainers[6]
|
||||
blkMetaInitCont = deployment.Spec.Template.Spec.InitContainers[8]
|
||||
assert.Equal(t, 1, len(blkMetaInitCont.VolumeDevices))
|
||||
osdProp.encrypted = false
|
||||
assert.Equal(t, 11, len(deployment.Spec.Template.Spec.Volumes), deployment.Spec.Template.Spec.Volumes)
|
||||
|
||||
// // Test OSD on PVC with RAW / metadata and wal device
|
||||
osd = OSDInfo{
|
||||
@@ -306,6 +312,7 @@ func testPodDevices(t *testing.T, dataDir, deviceName string, allDevices bool) {
|
||||
assert.Equal(t, 1, len(blkInitCont.VolumeDevices))
|
||||
blkMetaInitCont = deployment.Spec.Template.Spec.InitContainers[2]
|
||||
assert.Equal(t, 1, len(blkMetaInitCont.VolumeDevices))
|
||||
assert.Equal(t, 11, len(deployment.Spec.Template.Spec.Volumes), deployment.Spec.Template.Spec.Volumes)
|
||||
|
||||
// // Test encrypted OSD on PVC with RAW / metadata and wal device
|
||||
osd = OSDInfo{
|
||||
@@ -318,25 +325,67 @@ func testPodDevices(t *testing.T, dataDir, deviceName string, allDevices bool) {
|
||||
deployment, err = c.makeDeployment(osdProp, osd, dataPathMap)
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, deployment)
|
||||
assert.Equal(t, 11, len(deployment.Spec.Template.Spec.InitContainers))
|
||||
assert.Equal(t, "encryption-open", deployment.Spec.Template.Spec.InitContainers[0].Name)
|
||||
assert.Equal(t, "encryption-open-metadata", deployment.Spec.Template.Spec.InitContainers[1].Name)
|
||||
assert.Equal(t, "encryption-open-wal", deployment.Spec.Template.Spec.InitContainers[2].Name)
|
||||
assert.Equal(t, "blkdevmapper-encryption", deployment.Spec.Template.Spec.InitContainers[3].Name)
|
||||
assert.Equal(t, "blkdevmapper-metadata-encryption", deployment.Spec.Template.Spec.InitContainers[4].Name)
|
||||
assert.Equal(t, "blkdevmapper-wal-encryption", deployment.Spec.Template.Spec.InitContainers[5].Name)
|
||||
assert.Equal(t, "encrypted-block-status", deployment.Spec.Template.Spec.InitContainers[6].Name)
|
||||
assert.Equal(t, "expand-encrypted-bluefs", deployment.Spec.Template.Spec.InitContainers[7].Name)
|
||||
assert.Equal(t, "activate", deployment.Spec.Template.Spec.InitContainers[8].Name)
|
||||
assert.Equal(t, "expand-bluefs", deployment.Spec.Template.Spec.InitContainers[9].Name)
|
||||
assert.Equal(t, "chown-container-data-dir", deployment.Spec.Template.Spec.InitContainers[10].Name)
|
||||
assert.Equal(t, 14, len(deployment.Spec.Template.Spec.InitContainers))
|
||||
assert.Equal(t, "blkdevmapper", deployment.Spec.Template.Spec.InitContainers[0].Name)
|
||||
assert.Equal(t, "blkdevmapper-metadata", deployment.Spec.Template.Spec.InitContainers[1].Name)
|
||||
assert.Equal(t, "blkdevmapper-wal", deployment.Spec.Template.Spec.InitContainers[2].Name)
|
||||
assert.Equal(t, "encryption-open", deployment.Spec.Template.Spec.InitContainers[3].Name)
|
||||
assert.Equal(t, "encryption-open-metadata", deployment.Spec.Template.Spec.InitContainers[4].Name)
|
||||
assert.Equal(t, "encryption-open-wal", deployment.Spec.Template.Spec.InitContainers[5].Name)
|
||||
assert.Equal(t, "blkdevmapper-encryption", deployment.Spec.Template.Spec.InitContainers[6].Name)
|
||||
assert.Equal(t, "blkdevmapper-metadata-encryption", deployment.Spec.Template.Spec.InitContainers[7].Name)
|
||||
assert.Equal(t, "blkdevmapper-wal-encryption", deployment.Spec.Template.Spec.InitContainers[8].Name)
|
||||
assert.Equal(t, "encrypted-block-status", deployment.Spec.Template.Spec.InitContainers[9].Name)
|
||||
assert.Equal(t, "expand-encrypted-bluefs", deployment.Spec.Template.Spec.InitContainers[10].Name)
|
||||
assert.Equal(t, "activate", deployment.Spec.Template.Spec.InitContainers[11].Name)
|
||||
assert.Equal(t, "expand-bluefs", deployment.Spec.Template.Spec.InitContainers[12].Name)
|
||||
assert.Equal(t, "chown-container-data-dir", deployment.Spec.Template.Spec.InitContainers[13].Name)
|
||||
assert.Equal(t, 1, len(deployment.Spec.Template.Spec.Containers))
|
||||
cont = deployment.Spec.Template.Spec.Containers[0]
|
||||
assert.Equal(t, 7, len(cont.VolumeMounts), cont.VolumeMounts)
|
||||
blkInitCont = deployment.Spec.Template.Spec.InitContainers[1]
|
||||
assert.Equal(t, 1, len(blkInitCont.VolumeDevices))
|
||||
blkMetaInitCont = deployment.Spec.Template.Spec.InitContainers[8]
|
||||
blkMetaInitCont = deployment.Spec.Template.Spec.InitContainers[11]
|
||||
assert.Equal(t, 1, len(blkMetaInitCont.VolumeDevices))
|
||||
assert.Equal(t, 13, len(deployment.Spec.Template.Spec.Volumes), deployment.Spec.Template.Spec.Volumes)
|
||||
|
||||
// Test with encrypted OSD on PVC with RAW with KMS
|
||||
osdProp.encrypted = true
|
||||
osdProp.metadataPVC = v1.PersistentVolumeClaimVolumeSource{}
|
||||
osdProp.walPVC = v1.PersistentVolumeClaimVolumeSource{}
|
||||
c.spec.Security.KeyManagementService.ConnectionDetails = map[string]string{"KMS_PROVIDER": "vault"}
|
||||
c.spec.Security.KeyManagementService.TokenSecretName = "vault-token"
|
||||
deployment, err = c.makeDeployment(osdProp, osd, dataPathMap)
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, deployment)
|
||||
assert.Equal(t, 9, len(deployment.Spec.Template.Spec.InitContainers), deployment.Spec.Template.Spec.InitContainers)
|
||||
assert.Equal(t, "blkdevmapper", deployment.Spec.Template.Spec.InitContainers[0].Name)
|
||||
assert.Equal(t, "encryption-kms-get-kek", deployment.Spec.Template.Spec.InitContainers[1].Name)
|
||||
assert.Equal(t, "encryption-open", deployment.Spec.Template.Spec.InitContainers[2].Name)
|
||||
assert.Equal(t, "blkdevmapper-encryption", deployment.Spec.Template.Spec.InitContainers[3].Name)
|
||||
assert.Equal(t, "encrypted-block-status", deployment.Spec.Template.Spec.InitContainers[4].Name)
|
||||
assert.Equal(t, "expand-encrypted-bluefs", deployment.Spec.Template.Spec.InitContainers[5].Name)
|
||||
assert.Equal(t, "activate", deployment.Spec.Template.Spec.InitContainers[6].Name)
|
||||
assert.Equal(t, "expand-bluefs", deployment.Spec.Template.Spec.InitContainers[7].Name)
|
||||
assert.Equal(t, "chown-container-data-dir", deployment.Spec.Template.Spec.InitContainers[8].Name)
|
||||
assert.Equal(t, 1, len(deployment.Spec.Template.Spec.Containers))
|
||||
cont = deployment.Spec.Template.Spec.Containers[0]
|
||||
assert.Equal(t, 7, len(cont.VolumeMounts), cont.VolumeMounts)
|
||||
assert.Equal(t, 10, len(deployment.Spec.Template.Spec.Volumes), deployment.Spec.Template.Spec.Volumes) // One more than the encryption with k8s for the kek get init container
|
||||
assert.Equal(t, 0, len(deployment.Spec.Template.Spec.Volumes[7].VolumeSource.Projected.Sources), deployment.Spec.Template.Spec.Volumes[0]) // 0 since we have no tls secrets
|
||||
|
||||
// Test with encrypted OSD on PVC with RAW with KMS with TLS
|
||||
osdProp.encrypted = true
|
||||
osdProp.metadataPVC = v1.PersistentVolumeClaimVolumeSource{}
|
||||
osdProp.walPVC = v1.PersistentVolumeClaimVolumeSource{}
|
||||
c.spec.Security.KeyManagementService.ConnectionDetails = map[string]string{"KMS_PROVIDER": "vault", "VAULT_CACERT": "vault-ca-cert-secret", "VAULT_CLIENT_CERT": "vault-client-cert-secret", "VAULT_CLIENT_KEY": "vault-client-key-secret"}
|
||||
c.spec.Security.KeyManagementService.TokenSecretName = "vault-token"
|
||||
deployment, err = c.makeDeployment(osdProp, osd, dataPathMap)
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, deployment)
|
||||
assert.Equal(t, 10, len(deployment.Spec.Template.Spec.Volumes), deployment.Spec.Template.Spec.Volumes) // One more than the encryption with k8s for the kek get init container
|
||||
assert.Equal(t, 3, len(deployment.Spec.Template.Spec.Volumes[7].VolumeSource.Projected.Sources), deployment.Spec.Template.Spec.Volumes[0]) // 3 more since we have the tls secrets
|
||||
osdProp.encrypted = false
|
||||
|
||||
// Test tune Fast settings when OSD on PVC
|
||||
osdProp.tuneFastDeviceClass = true
|
||||
@@ -520,19 +569,20 @@ func TestClusterGetPVCEncryptionOpenInitContainerActivate(t *testing.T) {
|
||||
ClaimName: "pvc1",
|
||||
},
|
||||
}
|
||||
mountPath := "/var/lib/ceph/osd/ceph-0"
|
||||
|
||||
// No metadata PVC
|
||||
containers := c.getPVCEncryptionOpenInitContainerActivate(osdProperties)
|
||||
containers := c.getPVCEncryptionOpenInitContainerActivate(mountPath, osdProperties)
|
||||
assert.Equal(t, 1, len(containers))
|
||||
|
||||
// With metadata PVC
|
||||
osdProperties.metadataPVC.ClaimName = "pvcDB"
|
||||
containers = c.getPVCEncryptionOpenInitContainerActivate(osdProperties)
|
||||
containers = c.getPVCEncryptionOpenInitContainerActivate(mountPath, osdProperties)
|
||||
assert.Equal(t, 2, len(containers))
|
||||
|
||||
// With wal PVC
|
||||
osdProperties.walPVC.ClaimName = "pvcWal"
|
||||
containers = c.getPVCEncryptionOpenInitContainerActivate(osdProperties)
|
||||
containers = c.getPVCEncryptionOpenInitContainerActivate(mountPath, osdProperties)
|
||||
assert.Equal(t, 3, len(containers))
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ import (
|
||||
"fmt"
|
||||
"path"
|
||||
|
||||
"github.com/libopenstorage/secrets"
|
||||
kms "github.com/rook/rook/pkg/daemon/ceph/osd/kms"
|
||||
"github.com/rook/rook/pkg/operator/ceph/config"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
)
|
||||
@@ -176,16 +178,26 @@ func getUdevVolume() (v1.Volume, v1.VolumeMount) {
|
||||
return volume, volumeMounts
|
||||
}
|
||||
|
||||
func getEncryptionVolume(pvcName string) (v1.Volume, v1.VolumeMount) {
|
||||
func (c *Cluster) getEncryptionVolume(osdProps osdProperties) (v1.Volume, v1.VolumeMount) {
|
||||
// Determine whether we have a KMS configuration
|
||||
var isKMS bool
|
||||
if len(c.spec.Security.KeyManagementService.ConnectionDetails) != 0 {
|
||||
provider := kms.GetParam(c.spec.Security.KeyManagementService.ConnectionDetails, kms.Provider)
|
||||
if provider == secrets.TypeVault {
|
||||
isKMS = true
|
||||
}
|
||||
}
|
||||
|
||||
// Generate volume
|
||||
var m int32 = 0400
|
||||
volume := v1.Volume{
|
||||
Name: osdEncryptionVolName,
|
||||
VolumeSource: v1.VolumeSource{
|
||||
Secret: &v1.SecretVolumeSource{
|
||||
SecretName: generateOSDEncryptionSecretName(pvcName),
|
||||
SecretName: kms.GenerateOSDEncryptionSecretName(osdProps.pvc.ClaimName),
|
||||
Items: []v1.KeyToPath{
|
||||
{
|
||||
Key: OsdEncryptionSecretNameKeyName,
|
||||
Key: kms.OsdEncryptionSecretNameKeyName,
|
||||
Path: encryptionKeyFileName,
|
||||
},
|
||||
},
|
||||
@@ -194,6 +206,16 @@ func getEncryptionVolume(pvcName string) (v1.Volume, v1.VolumeMount) {
|
||||
},
|
||||
}
|
||||
|
||||
// On the KMS use case, we want the volume mount to be in memory since we pass write the KEK
|
||||
if isKMS {
|
||||
volume.VolumeSource.Secret = nil
|
||||
volume.VolumeSource = v1.VolumeSource{
|
||||
EmptyDir: &v1.EmptyDirVolumeSource{
|
||||
Medium: v1.StorageMediumMemory,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Mounts /etc/ceph/luks_key
|
||||
volumeMounts := v1.VolumeMount{
|
||||
Name: osdEncryptionVolName,
|
||||
@@ -201,5 +223,10 @@ func getEncryptionVolume(pvcName string) (v1.Volume, v1.VolumeMount) {
|
||||
MountPath: config.EtcCephDir,
|
||||
}
|
||||
|
||||
// With KMS we must be able to write inside the directory to write the KEK
|
||||
if isKMS {
|
||||
volumeMounts.ReadOnly = false
|
||||
}
|
||||
|
||||
return volume, volumeMounts
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
Copyright 2020 The Rook Authors. All rights reserved.
|
||||
|
||||
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 osd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
|
||||
"github.com/stretchr/testify/assert"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
)
|
||||
|
||||
func TestGetEncryptionVolume(t *testing.T) {
|
||||
var m int32 = 0400
|
||||
c := &Cluster{}
|
||||
|
||||
// No KMS
|
||||
osdProps := osdProperties{pvc: v1.PersistentVolumeClaimVolumeSource{ClaimName: "set1-data-1-bbgcw"}}
|
||||
v, vM := c.getEncryptionVolume(osdProps)
|
||||
assert.Equal(t, v1.Volume{Name: "osd-encryption-key", VolumeSource: v1.VolumeSource{Secret: &v1.SecretVolumeSource{SecretName: "rook-ceph-osd-encryption-key-set1-data-1-bbgcw", Items: []v1.KeyToPath{{Key: "dmcrypt-key", Path: "luks_key"}}, DefaultMode: &m}}}, v)
|
||||
assert.Equal(t, v1.VolumeMount{Name: "osd-encryption-key", ReadOnly: true, MountPath: "/etc/ceph"}, vM)
|
||||
|
||||
// With KMS
|
||||
c.spec.Security = cephv1.SecuritySpec{
|
||||
KeyManagementService: cephv1.KeyManagementServiceSpec{
|
||||
ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault"},
|
||||
},
|
||||
}
|
||||
v, vM = c.getEncryptionVolume(osdProps)
|
||||
assert.Equal(t, v1.Volume{Name: "osd-encryption-key", VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{Medium: "Memory"}}}, v)
|
||||
assert.Equal(t, v1.VolumeMount{Name: "osd-encryption-key", ReadOnly: false, MountPath: "/etc/ceph"}, vM)
|
||||
}
|
||||
@@ -95,7 +95,8 @@ func configOverrideConfigMapVolumeAndMount() (v1.Volume, v1.VolumeMount) {
|
||||
return v, m
|
||||
}
|
||||
|
||||
func confGeneratedInPodVolumeAndMount() (v1.Volume, v1.VolumeMount) {
|
||||
// ConfGeneratedInPodVolumeAndMount generate an empty dir of /etc/ceph
|
||||
func ConfGeneratedInPodVolumeAndMount() (v1.Volume, v1.VolumeMount) {
|
||||
name := "ceph-conf-emptydir"
|
||||
dir := config.EtcCephDir
|
||||
v := v1.Volume{Name: name, VolumeSource: v1.VolumeSource{
|
||||
@@ -118,7 +119,7 @@ func PodVolumes(dataPaths *config.DataPathMap, dataDirHostPath string, confGener
|
||||
}
|
||||
configVolume, _ := configOverrideConfigMapVolumeAndMount()
|
||||
if confGeneratedInPod {
|
||||
configVolume, _ = confGeneratedInPodVolumeAndMount()
|
||||
configVolume, _ = ConfGeneratedInPodVolumeAndMount()
|
||||
}
|
||||
|
||||
v := []v1.Volume{
|
||||
@@ -135,7 +136,7 @@ func PodVolumes(dataPaths *config.DataPathMap, dataDirHostPath string, confGener
|
||||
func CephVolumeMounts(dataPaths *config.DataPathMap, confGeneratedInPod bool) []v1.VolumeMount {
|
||||
_, configMount := configOverrideConfigMapVolumeAndMount()
|
||||
if confGeneratedInPod {
|
||||
_, configMount = confGeneratedInPodVolumeAndMount()
|
||||
_, configMount = ConfGeneratedInPodVolumeAndMount()
|
||||
}
|
||||
|
||||
v := []v1.VolumeMount{
|
||||
|
||||
@@ -1544,6 +1544,14 @@ spec:
|
||||
iteration:
|
||||
type: integer
|
||||
format: int32
|
||||
security:
|
||||
properties:
|
||||
kms:
|
||||
properties:
|
||||
connectionDetails:
|
||||
type: object
|
||||
tokenSecretName:
|
||||
type: string
|
||||
placement: {}
|
||||
resources: {}
|
||||
additionalPrinterColumns:
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
apiVersion: ceph.rook.io/v1
|
||||
kind: CephCluster
|
||||
metadata:
|
||||
name: rook-ceph
|
||||
namespace: rook-ceph
|
||||
spec:
|
||||
dataDirHostPath: /var/lib/rook
|
||||
mon:
|
||||
count: 1
|
||||
volumeClaimTemplate:
|
||||
spec:
|
||||
storageClassName: manual
|
||||
resources:
|
||||
requests:
|
||||
storage: 5Gi
|
||||
cephVersion:
|
||||
image: ceph/daemon-base:latest-nautilus-devel
|
||||
dashboard:
|
||||
enabled: false
|
||||
network:
|
||||
hostNetwork: false
|
||||
crashCollector:
|
||||
disable: true
|
||||
storage:
|
||||
storageClassDeviceSets:
|
||||
- name: set1
|
||||
count: 1
|
||||
portable: false
|
||||
tuneDeviceClass: false
|
||||
encrypted: true
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
name: data
|
||||
spec:
|
||||
resources:
|
||||
requests:
|
||||
storage: 10Gi
|
||||
storageClassName: manual
|
||||
volumeMode: Block
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
@@ -0,0 +1,9 @@
|
||||
spec:
|
||||
security:
|
||||
kms:
|
||||
connectionDetails:
|
||||
KMS_PROVIDER: vault
|
||||
VAULT_ADDR: https://vault.default.svc.cluster.local:8200
|
||||
VAULT_BACKEND_PATH: rook
|
||||
VAULT_SKIP_VERIFY: "true"
|
||||
tokenSecretName: rook-vault-token
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: rook-vault-token
|
||||
namespace: rook-ceph
|
||||
data:
|
||||
token: ROOK_TOKEN
|
||||
Executable
+195
@@ -0,0 +1,195 @@
|
||||
#!/bin/bash
|
||||
set -ex
|
||||
|
||||
: "${ACTION:=${1}}"
|
||||
|
||||
#############
|
||||
# VARIABLES #
|
||||
#############
|
||||
SERVICE=vault
|
||||
NAMESPACE=default
|
||||
ROOK_NAMESPACE=rook-ceph
|
||||
SECRET_NAME=vault-server-tls
|
||||
TMPDIR=$(mktemp -d)
|
||||
|
||||
#############
|
||||
# FUNCTIONS #
|
||||
#############
|
||||
|
||||
function install_helm {
|
||||
curl https://baltocdn.com/helm/signing.asc | sudo apt-key add -
|
||||
sudo apt-get install apt-transport-https --yes
|
||||
echo "deb https://baltocdn.com/helm/stable/debian/ all main" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list
|
||||
sudo apt-get update
|
||||
sudo apt-get install helm
|
||||
}
|
||||
|
||||
if [[ "$(uname)" == "Linux" ]]; then
|
||||
sudo apt-get install jq -y
|
||||
install_helm
|
||||
fi
|
||||
|
||||
function generate_vault_tls_config {
|
||||
openssl genrsa -out "${TMPDIR}"/vault.key 2048
|
||||
|
||||
cat <<EOF >"${TMPDIR}"/csr.conf
|
||||
[req]
|
||||
req_extensions = v3_req
|
||||
distinguished_name = req_distinguished_name
|
||||
[req_distinguished_name]
|
||||
[ v3_req ]
|
||||
basicConstraints = CA:FALSE
|
||||
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
|
||||
extendedKeyUsage = serverAuth
|
||||
subjectAltName = @alt_names
|
||||
[alt_names]
|
||||
DNS.1 = ${SERVICE}
|
||||
DNS.2 = ${SERVICE}.${NAMESPACE}
|
||||
DNS.3 = ${SERVICE}.${NAMESPACE}.svc
|
||||
DNS.4 = ${SERVICE}.${NAMESPACE}.svc.cluster.local
|
||||
IP.1 = 127.0.0.1
|
||||
EOF
|
||||
|
||||
openssl req -new -key "${TMPDIR}"/vault.key -subj "/CN=${SERVICE}.${NAMESPACE}.svc" -out "${TMPDIR}"/server.csr -config "${TMPDIR}"/csr.conf
|
||||
|
||||
export CSR_NAME=vault-csr
|
||||
|
||||
cat <<EOF >"${TMPDIR}"/csr.yaml
|
||||
apiVersion: certificates.k8s.io/v1beta1
|
||||
kind: CertificateSigningRequest
|
||||
metadata:
|
||||
name: ${CSR_NAME}
|
||||
spec:
|
||||
groups:
|
||||
- system:authenticated
|
||||
request: $(cat ${TMPDIR}/server.csr | base64 | tr -d '\n')
|
||||
usages:
|
||||
- digital signature
|
||||
- key encipherment
|
||||
- server auth
|
||||
EOF
|
||||
|
||||
kubectl create -f "${TMPDIR}/"csr.yaml
|
||||
|
||||
kubectl certificate approve ${CSR_NAME}
|
||||
|
||||
serverCert=$(kubectl get csr ${CSR_NAME} -o jsonpath='{.status.certificate}')
|
||||
echo "${serverCert}" | openssl base64 -d -A -out "${TMPDIR}"/vault.crt
|
||||
kubectl config view --raw --minify --flatten -o jsonpath='{.clusters[].cluster.certificate-authority-data}' | base64 -d > "${TMPDIR}"/vault.ca
|
||||
kubectl create secret generic ${SECRET_NAME} \
|
||||
--namespace ${NAMESPACE} \
|
||||
--from-file=vault.key="${TMPDIR}"/vault.key \
|
||||
--from-file=vault.crt="${TMPDIR}"/vault.crt \
|
||||
--from-file=vault.ca="${TMPDIR}"/vault.ca
|
||||
|
||||
# for rook
|
||||
kubectl create secret generic vault-ca-cert --namespace ${ROOK_NAMESPACE} --from-file=cert="${TMPDIR}"/vault.ca
|
||||
kubectl create secret generic vault-client-cert --namespace ${ROOK_NAMESPACE} --from-file=cert="${TMPDIR}"/vault.crt
|
||||
kubectl create secret generic vault-client-key --namespace ${ROOK_NAMESPACE} --from-file=key="${TMPDIR}"/vault.key
|
||||
}
|
||||
|
||||
function vault_helm_tls {
|
||||
|
||||
cat <<EOF >"${TMPDIR}/"custom-values.yaml
|
||||
global:
|
||||
enabled: true
|
||||
tlsDisable: false
|
||||
|
||||
server:
|
||||
extraEnvironmentVars:
|
||||
VAULT_CACERT: /vault/userconfig/vault-server-tls/vault.ca
|
||||
|
||||
extraVolumes:
|
||||
- type: secret
|
||||
name: vault-server-tls # Matches the ${SECRET_NAME} from above
|
||||
|
||||
standalone:
|
||||
enabled: true
|
||||
config: |
|
||||
listener "tcp" {
|
||||
address = "[::]:8200"
|
||||
cluster_address = "[::]:8201"
|
||||
tls_cert_file = "/vault/userconfig/vault-server-tls/vault.crt"
|
||||
tls_key_file = "/vault/userconfig/vault-server-tls/vault.key"
|
||||
tls_client_ca_file = "/vault/userconfig/vault-server-tls/vault.ca"
|
||||
}
|
||||
|
||||
storage "file" {
|
||||
path = "/vault/data"
|
||||
}
|
||||
EOF
|
||||
|
||||
}
|
||||
|
||||
function deploy_vault {
|
||||
# TLS config
|
||||
generate_vault_tls_config
|
||||
vault_helm_tls
|
||||
|
||||
# Install Vault with Helm
|
||||
helm repo add hashicorp https://helm.releases.hashicorp.com
|
||||
helm install vault hashicorp/vault --values "${TMPDIR}/"custom-values.yaml
|
||||
timeout 120 sh -c 'until kubectl get pods -l app.kubernetes.io/name=vault --field-selector=status.phase=Running|grep vault-0; do sleep 5; done'
|
||||
|
||||
# Unseal Vault
|
||||
VAULT_INIT_TEMP_DIR=$(mktemp)
|
||||
kubectl exec -ti vault-0 -- vault operator init -format "json" -ca-cert /vault/userconfig/vault-server-tls/vault.crt | tee -a "$VAULT_INIT_TEMP_DIR"
|
||||
for i in $(seq 0 2); do
|
||||
kubectl exec -ti vault-0 -- vault operator unseal -ca-cert /vault/userconfig/vault-server-tls/vault.crt "$(jq -r ".unseal_keys_b64[$i]" "$VAULT_INIT_TEMP_DIR")"
|
||||
done
|
||||
kubectl get pods -l app.kubernetes.io/name=vault
|
||||
|
||||
# Wait for vault to be ready once unsealed
|
||||
while [[ $(kubectl get pods -l app.kubernetes.io/name=vault -o 'jsonpath={..status.conditions[?(@.type=="Ready")].status}') != "True" ]]; do echo "waiting vault to be ready" && sleep 1; done
|
||||
|
||||
# Configure Vault
|
||||
ROOT_TOKEN=$(jq -r '.root_token' "$VAULT_INIT_TEMP_DIR")
|
||||
kubectl exec -it vault-0 -- vault login -ca-cert /vault/userconfig/vault-server-tls/vault.crt "$ROOT_TOKEN"
|
||||
kubectl exec -ti vault-0 -- vault secrets enable -ca-cert /vault/userconfig/vault-server-tls/vault.crt -path=rook kv
|
||||
kubectl exec -ti vault-0 -- vault kv list -ca-cert /vault/userconfig/vault-server-tls/vault.crt rook || true # failure is expected
|
||||
|
||||
# Configure Vault Policy for Rook
|
||||
echo '
|
||||
path "rook/*" {
|
||||
capabilities = ["create", "read", "update", "delete", "list"]
|
||||
}
|
||||
path "sys/mounts" {
|
||||
capabilities = ["read"]
|
||||
}'| kubectl exec -i vault-0 -- vault policy write -ca-cert /vault/userconfig/vault-server-tls/vault.crt rook -
|
||||
|
||||
# Create a token for Rook
|
||||
ROOK_TOKEN=$(kubectl exec vault-0 -- vault token create -policy=rook -format json -ca-cert /vault/userconfig/vault-server-tls/vault.crt|jq -r '.auth.client_token'|base64)
|
||||
|
||||
# Configure cluster
|
||||
sed -i "s|ROOK_TOKEN|$ROOK_TOKEN|" tests/manifests/test-kms-vault.yaml
|
||||
}
|
||||
|
||||
function validate_deployment {
|
||||
validate_pvc_secret
|
||||
}
|
||||
|
||||
function validate_pvc_secret {
|
||||
NB_OSD_PVC=$(kubectl -n rook-ceph get pvc|grep -c set1)
|
||||
NB_VAULT_SECRET=$(kubectl -n default exec -ti vault-0 -- vault kv list -ca-cert /vault/userconfig/vault-server-tls/vault.crt rook|grep -c set1)
|
||||
|
||||
if [ "$NB_OSD_PVC" -ne "$NB_VAULT_SECRET" ]; then
|
||||
echo "number of osd pvc is $NB_OSD_PVC and number of vault secret is $NB_VAULT_SECRET, mismatch"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
########
|
||||
# MAIN #
|
||||
########
|
||||
|
||||
case "$ACTION" in
|
||||
deploy)
|
||||
deploy_vault
|
||||
;;
|
||||
validate)
|
||||
validate_deployment
|
||||
;;
|
||||
*)
|
||||
echo "invalid action $ACTION" >&2
|
||||
exit 1
|
||||
esac
|
||||
@@ -1,6 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
set -xE
|
||||
|
||||
: "${DAEMON_TO_VALIDATE:=${1}}"
|
||||
if [ -z "$DAEMON_TO_VALIDATE" ]; then
|
||||
DAEMON_TO_VALIDATE=all
|
||||
fi
|
||||
|
||||
trap display_status ERR
|
||||
|
||||
#############
|
||||
@@ -90,10 +95,47 @@ function display_status {
|
||||
test_csi
|
||||
test_demo_mon
|
||||
test_demo_mgr
|
||||
test_demo_osd
|
||||
test_demo_rgw
|
||||
test_demo_mds
|
||||
test_demo_rbd_mirror
|
||||
|
||||
if [[ "$DAEMON_TO_VALIDATE" == "all" ]]; then
|
||||
daemons_list="osd mds rgw rbd_mirror"
|
||||
else
|
||||
# change commas to space
|
||||
comma_to_space=${DAEMON_TO_VALIDATE//,/ }
|
||||
|
||||
# transform to an array
|
||||
IFS=" " read -r -a array <<< "$comma_to_space"
|
||||
|
||||
# sort and remove potential duplicate
|
||||
daemons_list=$(echo "${array[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' ')
|
||||
fi
|
||||
|
||||
for daemon in $daemons_list; do
|
||||
case "$daemon" in
|
||||
mon)
|
||||
continue
|
||||
;;
|
||||
mgr)
|
||||
continue
|
||||
;;
|
||||
osd)
|
||||
test_demo_osd
|
||||
;;
|
||||
mds)
|
||||
test_demo_mds
|
||||
;;
|
||||
rgw)
|
||||
test_demo_rgw
|
||||
;;
|
||||
rbd_mirror)
|
||||
test_demo_rbd_mirror
|
||||
;;
|
||||
*)
|
||||
log "ERROR: unknown daemon to validate!"
|
||||
log "Available daemon are: mon mgr osd mds rgw rbd_mirror"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "Ceph is up and running, have a look!"
|
||||
$EXEC_COMMAND -s
|
||||
File renamed without changes.
Reference in new issue
Block a user