Skip to content

Commit a97c205

Browse files
alpebsdickhoven
authored andcommitted
fix(linkerd-cni): improve SA token rotation detection (linkerd#478)
* fix(linkerd-cni): improve SA token rotation detection This makes the logic introduced in linkerd#440 more robust, by watching over the proper file change to trigger the kubeconfig file re-creation. See linkerd/linkerd2#12573 (comment)
1 parent 5f984e0 commit a97c205

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

cni-plugin/deployment/scripts/install-cni.sh

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -289,21 +289,26 @@ monitor_cni_config() {
289289
done
290290
}
291291

292-
# Kubernetes rolls out serviceaccount tokens by creating new directories
293-
# containing a new token file and re-creating the
294-
# /var/run/secrets/kubernetes.io/serviceaccount/token symlink pointing to it.
295-
# This function listens to creation events under the serviceaccount directory,
296-
# only reacting to direct creation of a "token" file, or creation of
297-
# directories containing a "token" file.
292+
# This function detects whether the service account token was rotated by
293+
# listening to MOVED_TO events under the directory
294+
# /var/run/secrets/kubernetes.io/serviceaccount, detecting whether the ..data
295+
# directory was moved to, as recommended by k8s' atomic writer:
296+
# > Consumers of the target directory can monitor the ..data symlink using
297+
# > inotify or fanotify to receive events when the content in the volume is
298+
# > updated.
299+
# Indeed, as per atomic writer's Write function docs, in the final steps the
300+
# ..data_tmp symlink points to a new timestamped directory containing the new
301+
# files, which is then atomically renamed to ..data:
302+
# > 8. A symlink to the new timestamped directory ..data_tmp is created that will
303+
# > become the new data directory.
304+
# > 9. The new data directory symlink is renamed to the data directory; rename is atomic.
305+
# See https://github.com/kubernetes/kubernetes/blob/release-1.32/pkg/volume/util/atomic_writer.go
298306
monitor_service_account_token() {
299-
inotifywait -m "${SERVICEACCOUNT_PATH}" -e create |
300-
while read -r directory _ filename; do
301-
target=$(realpath "$directory/$filename")
302-
if [[ (-f "$target" && "${target##*/}" == "token") || (-d "$target" && -e "$target/token") ]]; then
303-
log "Detected creation of file in $directory: $filename; recreating kubeconfig file"
304-
create_kubeconfig
305-
else
306-
log "Detected creation of file in $directory: $filename; ignoring"
307+
inotifywait -m "${SERVICEACCOUNT_PATH}" -e moved_to |
308+
while read -r _ _ filename; do
309+
if [[ "$filename" == "..data" ]]; then
310+
log "Detected change in service account files; recreating kubeconfig file"
311+
create_kubeconfig
307312
fi
308313
done
309314
}

0 commit comments

Comments
 (0)