diff --git a/README.md b/README.md index 76aa89b..a3622ba 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,16 @@ stringData: AKS cluster needs to have workload identity enabled. The managed identity needs to have the Federated Identity Credential created: https://azure.github.io/azure-workload-identity/docs/topics/federated-identity-credential.html. -##### Credentials secret: +##### Credentials secret (optional): +The workload identity webhook injects `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, +`AZURE_FEDERATED_TOKEN_FILE` and the projected token volume into every pod +that carries the `azure.workload.identity/use: "true"` label and runs with an +annotated service account, and the function reads those variables when the +corresponding key is absent. A credentials Secret is therefore only needed to +override them, for example to use a different client id than the one on the +service account. Both keys are optional: `clientId` defaults to +`AZURE_CLIENT_ID` and `tenantId` defaults to `AZURE_TENANT_ID`. + ```yaml apiVersion: v1 kind: Secret @@ -68,12 +77,13 @@ type: Opaque stringData: credentials: | { - "clientId": "your-client-id", # optional - "tenantId": "your-tenant-id", # optional - "federatedTokenFile": "/var/run/secrets/azure/tokens/azure-identity-token" + "clientId": "your-client-id", + "tenantId": "your-tenant-id" } ``` +Without a Secret, leave `credentials` out of the pipeline step. + ##### Function ```yaml apiVersion: pkg.crossplane.io/v1 @@ -89,39 +99,27 @@ spec: ``` ##### DeploymentRuntimeConfig +The label on the pod template and the annotation on the service account are +all the webhook needs; it adds the environment variables and the token volume +itself. + ```yaml apiVersion: pkg.crossplane.io/v1beta1 kind: DeploymentRuntimeConfig metadata: name: upbound-function-msgraph -spec: +spec: deploymentTemplate: spec: - selector: - matchLabels: - azure.workload.identity/use: "true" - pkg.crossplane.io/function: "upbound-function-msgraph" + selector: {} template: metadata: labels: azure.workload.identity/use: "true" - pkg.crossplane.io/function: "upbound-function-msgraph" spec: + serviceAccountName: "upbound-function-msgraph" containers: - name: package-runtime - volumeMounts: - - mountPath: /var/run/secrets/azure/tokens - name: azure-identity-token - readOnly: true - serviceAccountName: "upbound-function-msgraph" - volumes: - - name: azure-identity-token - projected: - sources: - - serviceAccountToken: - audience: api://AzureADTokenExchange - expirationSeconds: 3600 - path: azure-identity-token serviceAccountTemplate: metadata: annotations: diff --git a/example/identity-type-workload-identity.yaml b/example/identity-type-workload-identity.yaml index cb1e699..b6cedbb 100644 --- a/example/identity-type-workload-identity.yaml +++ b/example/identity-type-workload-identity.yaml @@ -27,9 +27,3 @@ spec: skipQueryWhenTargetHasData: true identity: type: AzureWorkloadIdentityCredentials - credentials: - - name: azure-creds - source: Secret - secretRef: - namespace: crossplane-system - name: azure-workload-identity-creds diff --git a/example/secrets/azure-workload-identity-creds.yaml b/example/secrets/azure-workload-identity-creds.yaml deleted file mode 100644 index 7a5ef11..0000000 --- a/example/secrets/azure-workload-identity-creds.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: v1 -stringData: - credentials: | - { - "federatedTokenFile": "/var/run/secrets/azure/tokens/azure-identity-token" - } -kind: Secret -metadata: - name: azure-workload-identity-creds - namespace: crossplane-system -type: Opaque diff --git a/fn.go b/fn.go index 1830c1f..8908348 100644 --- a/fn.go +++ b/fn.go @@ -359,7 +359,11 @@ func (f *Function) parseInputAndCredentials(req *fnv1.RunFunctionRequest, rsp *f return nil, nil, err } - azureCreds, err := getCreds(req) + // Workload identity can run on what the AKS webhook injects into the pod + // (AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE), so its + // credentials Secret is optional. + required := in.Identity == nil || in.Identity.Type != v1beta1.IdentityTypeAzureWorkloadIdentityCredentials + azureCreds, err := getCreds(req, required) if err != nil { response.Fatal(rsp, err) return nil, nil, err @@ -596,7 +600,7 @@ func (f *Function) processResults(req *fnv1.RunFunctionRequest, in *v1beta1.Inpu return nil } -func getCreds(req *fnv1.RunFunctionRequest) (map[string]string, error) { +func getCreds(req *fnv1.RunFunctionRequest, required bool) (map[string]string, error) { var azureCreds map[string]string rawCreds := req.GetCredentials() @@ -608,7 +612,7 @@ func getCreds(req *fnv1.RunFunctionRequest) (map[string]string, error) { return nil, errors.Wrap(err, "cannot parse json credentials") } } - } else { + } else if required { return nil, errors.New("failed to get azure-creds credentials") } diff --git a/fn_test.go b/fn_test.go index debf402..02fb08c 100644 --- a/fn_test.go +++ b/fn_test.go @@ -4212,6 +4212,85 @@ func TestIdentityType(t *testing.T) { }, }, }, + "AzureWorkloadIdentityCredentialsWithoutSecret": { + reason: "The Function should not fail on a missing azure-creds Secret for Workload Identity and should go on to the graph query", + args: args{ + ctx: context.Background(), + req: &fnv1.RunFunctionRequest{ + Meta: &fnv1.RequestMeta{Tag: testRequestTag}, + Input: resource.MustStructJSON(`{ + "apiVersion": "msgraph.fn.crossplane.io/v1alpha1", + "kind": "Input", + "queryType": "GroupObjectIDs", + "groupsRef": "status.groups", + "target": "status.groupObjectIDs", + "identity": { + "type": "AzureWorkloadIdentityCredentials" + } + }`), + Observed: &fnv1.State{ + Composite: &fnv1.Resource{ + Resource: resource.MustStructJSON(xr), + }, + }, + }, + }, + want: want{ + rsp: &fnv1.RunFunctionResponse{ + Meta: &fnv1.ResponseMeta{Tag: testRequestTag, Ttl: durationpb.New(response.DefaultTTL)}, + Results: []*fnv1.Result{ + { + Severity: fnv1.Severity_SEVERITY_FATAL, + Message: `failed to initialize workload identity provider: failed to obtain workloadidentity credentials`, + Target: fnv1.Target_TARGET_COMPOSITE.Enum(), + }, + }, + Desired: &fnv1.State{ + Composite: &fnv1.Resource{ + Resource: resource.MustStructJSON(xr), + }, + }, + }, + }, + }, + "AzureServicePrincipalCredentialsWithoutSecret": { + reason: "The Function should still require the azure-creds Secret for service principal credentials", + args: args{ + ctx: context.Background(), + req: &fnv1.RunFunctionRequest{ + Meta: &fnv1.RequestMeta{Tag: testRequestTag}, + Input: resource.MustStructJSON(`{ + "apiVersion": "msgraph.fn.crossplane.io/v1alpha1", + "kind": "Input", + "queryType": "GroupObjectIDs", + "groupsRef": "status.groups", + "target": "status.groupObjectIDs" + }`), + Observed: &fnv1.State{ + Composite: &fnv1.Resource{ + Resource: resource.MustStructJSON(xr), + }, + }, + }, + }, + want: want{ + rsp: &fnv1.RunFunctionResponse{ + Meta: &fnv1.ResponseMeta{Tag: testRequestTag, Ttl: durationpb.New(response.DefaultTTL)}, + Results: []*fnv1.Result{ + { + Severity: fnv1.Severity_SEVERITY_FATAL, + Message: `failed to get azure-creds credentials`, + Target: fnv1.Target_TARGET_COMPOSITE.Enum(), + }, + }, + Desired: &fnv1.State{ + Composite: &fnv1.Resource{ + Resource: resource.MustStructJSON(xr), + }, + }, + }, + }, + }, "AzureWorkloadIdentityCredentials": { reason: "The Function should use Workload Identity credentials if identity.type is AzureWorkloadIdentityCredentials", args: args{ @@ -4299,6 +4378,65 @@ func TestIdentityType(t *testing.T) { } } +func TestInitializeWorkloadIdentityProvider(t *testing.T) { + type want struct { + err bool + } + + cases := map[string]struct { + reason string + env map[string]string + creds map[string]string + want want + }{ + "NilCredsWithWebhookEnv": { + reason: "Without a credentials Secret the provider should fall back to the variables the workload identity webhook injects", + env: map[string]string{ + "AZURE_CLIENT_ID": "env-client-id", + "AZURE_TENANT_ID": "env-tenant-id", + "AZURE_FEDERATED_TOKEN_FILE": "/var/run/secrets/azure/tokens/azure-identity-token", + }, + creds: nil, + }, + "NilCredsWithoutWebhookEnv": { + reason: "Without a credentials Secret and without the webhook variables the provider should fail", + env: map[string]string{ + "AZURE_CLIENT_ID": "", + "AZURE_TENANT_ID": "", + "AZURE_FEDERATED_TOKEN_FILE": "", + }, + creds: nil, + want: want{err: true}, + }, + "CredsOverrideMissingEnv": { + reason: "Keys in the credentials Secret should be enough when the webhook variables are missing", + env: map[string]string{ + "AZURE_CLIENT_ID": "", + "AZURE_TENANT_ID": "", + "AZURE_FEDERATED_TOKEN_FILE": "", + }, + creds: map[string]string{ + ClientID: "secret-client-id", + TenantID: "secret-tenant-id", + WorkloadIdentityCredentialPath: "/tmp/azure-identity-token", + }, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + for k, v := range tc.env { + t.Setenv(k, v) + } + + _, err := (&GraphQuery{}).initializeWorkloadIdentityProvider(tc.creds) + if gotErr := err != nil; gotErr != tc.want.err { + t.Errorf("%s\ninitializeWorkloadIdentityProvider(...): want error %t, got %v", tc.reason, tc.want.err, err) + } + }) + } +} + // TestAdditionalFields verifies that AdditionalFields is propagated to the graph // query and that extra fields appear in the RunFunction response for every // supported queryType (UserValidation, GroupObjectIDs, ServicePrincipalDetails,