Tuesday, May 9, 2023

Decode JWTs in bash

Today, it is once again time for one of those "let's document it" blog posts. Lately, I looked into one of the IBM Cloud security features, trusted profiles based on compute resources. I described how to turn your container into a trusted identity. For developing code locally, I needed to copy over files from the Kubernetes pods to my local machine, then decode JWT access tokens, all using the command line. Here is what I did.

Decode JSON Web Tokens

A special service account / compute resource token is issued to the configured container environment. The service account token can then be converted into an IBM Cloud IAM (Identity and Access Management) access token. Both tokens are JSON Web Tokens (JWTs)

cat sa-token | tr "." "\n" | for run in {1..2} ; do read line ; echo $line | base64 -i -d | jq ; done

Decoded and pretty-printed JWT access token

In the screenshot above, you see the attributes "exp" (expires) and "iat" (issued at). Both are timestamps encoded as Unix time integers. They can be decoded with the date command:

date -d @1683550911

The command prints “Mon May 8 15:01:51 CEST 2023” on my machine. 

Copy files from Kubernetes

The command line tool kubectl is the utility of choice when working with Kubernetes. It features a copy command to move files between environments, e.g., from a running pod to your local machine. Its documentation also has examples for copying directory structure and more using a combination of the exec command and the tar utility.

kubectl exec tp-demo -- tar cf - "/var/run/secrets/tokens" | tar xf - --strip-components 4

I use the above command for my scenario. It bundles up the directory "/var/run/secrets/tokens" in the pod "tp-demo" and extracts it without the parents directories to my local machine. The option "--strip-components 4" makes sure that the four directory levels are stripped away.

That's it already. If you have feedback, suggestions, or questions about this post, please reach out to me on Twitter (@data_henrik), Mastodon (@data_henrik@mastodon.social), or LinkedIn.