Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 21 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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:
Expand Down
6 changes: 0 additions & 6 deletions example/identity-type-workload-identity.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
11 changes: 0 additions & 11 deletions example/secrets/azure-workload-identity-creds.yaml

This file was deleted.

10 changes: 7 additions & 3 deletions fn.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand All @@ -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")
}

Expand Down
138 changes: 138 additions & 0 deletions fn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4212,6 +4212,85 @@ func TestIdentityType(t *testing.T) {
},
},
},
"AzureWorkloadIdentityCredentialsWithoutSecret": {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This case doesn't reach the identity provider: MockGraphQuery ignores the creds and returns that error text itself, so the nil-creds AZURE_* fallback in initializeWorkloadIdentityProvider is untested.
Could you add a direct test: t.Setenv AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE, call (&GraphQuery{}).initializeWorkloadIdentityProvider(nil) and expect no error?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, that case only showed the missing Secret no longer fails early. I added TestInitializeWorkloadIdentityProvider, which calls (&GraphQuery{}).initializeWorkloadIdentityProvider(nil) directly with t.Setenv. With the three AZURE_* variables set it returns no error, and with them empty it returns one, so the fallback is really what makes the first case pass. A third case covers the Secret keys working on their own. I also reworded the old case so it only claims what it checks.

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{
Expand Down Expand Up @@ -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,
Expand Down