Skip to content

A VM can prove who it is to AWS or Google Cloud with a short-lived OIDC token. SlashInfra signs the token and names the VM in it, so the VM stores no cloud key.

si-identity prints a token for the audience you name, and writes no file. The token carries the VM’s organization, project, id, generation, labels and pool.

  1. Open SVMs and select api.
  2. Select Terminal.
  3. Run the command below. It mints a token and decodes the claims without printing the token.
Terminal window
TOKEN="$(si-identity --audience sts.amazonaws.com)" python3 - <<'PY'
import base64, json, os
payload = os.environ["TOKEN"].split(".")[1]
payload += "=" * (-len(payload) % 4)
print(json.dumps(json.loads(base64.urlsafe_b64decode(payload)), indent=2))
PY
Output
{
"org": "org_2fH7kLmN9pQrSt",
"project": "proj_0a1b2c3d4e",
"svm": "6f1c0f0e8a",
"generation": 1,
"labels": {},
"pool": "platform",
"iss": "https://api.slashinfra.com",
"sub": "svm:6f1c0f0e8a",
"aud": "sts.amazonaws.com",
"iat": 1795966345,
"nbf": 1795966345,
"exp": 1795966945,
"jti": "3f2a1c9e-7b4d-4e2a-9c1f-6d5e8a7b2c4d"
}

An empty audience prints identity: the audience is empty, and one longer than 256 bytes prints identity: the audience is empty or too long. A TTL outside 60 to 3600 seconds for a new token prints a message ending in invalid_ttl.

The token is an ES256 JWT. Its header names the signing key in kid. These are its claims:

Claim Value
iss https://api.slashinfra.com
sub svm: and the VM id
aud The audience you named
iat, nbf The signing instant, in seconds since the Unix epoch
exp iat plus the token life
jti A random UUID for this token
org The organization id
project The project id
svm The VM id
generation The VM generation
labels The VM’s user labels, without the reserved si. labels
pool The placement pool that holds the VM

Scroll horizontally to see all columns.

The token names one VM. A token for another VM has another sub, so a cloud role that trusts svm:6f1c0f0e8a refuses it.

You set this up once from your laptop with the AWS CLI, then the VM gets temporary AWS credentials whenever a program asks for them. The example role reads one S3 bucket, my-bucket; replace 123456789012 with your AWS account id.

AWS checks only the aud and sub claims of a token from a provider like SlashInfra; it cannot check org or project. Any SlashInfra VM can mint a token for sts.amazonaws.com, so the trust policy must name each VM id that may use the role. Never use a wildcard in sub.

  1. Create the OIDC provider. AWS reads the discovery document at https://api.slashinfra.com/.well-known/openid-configuration.

    Terminal window
    aws iam create-open-id-connect-provider \
    --url https://api.slashinfra.com \
    --client-id-list sts.amazonaws.com
  2. Save the trust policy as trust.json. It lets two VMs, by id, assume the role. Find a VM’s id with si ls.

    {
    "Version": "2012-10-17",
    "Statement": [
    {
    "Effect": "Allow",
    "Principal": {
    "Federated": "arn:aws:iam::123456789012:oidc-provider/api.slashinfra.com"
    },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
    "StringEquals": {
    "api.slashinfra.com:aud": "sts.amazonaws.com",
    "api.slashinfra.com:sub": ["svm:6f1c0f0e8a", "svm:7a2b3c4d5e"]
    }
    }
    }
    ]
    }
  3. Create the role with that trust policy.

    Terminal window
    aws iam create-role \
    --role-name slashinfra-reader \
    --assume-role-policy-document file://trust.json \
    --max-session-duration 3600
  4. Save what the role may do as s3-read.json. This policy lists my-bucket and reads its objects, and nothing else.

    {
    "Version": "2012-10-17",
    "Statement": [
    {
    "Effect": "Allow",
    "Action": "s3:ListBucket",
    "Resource": "arn:aws:s3:::my-bucket"
    },
    {
    "Effect": "Allow",
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-bucket/*"
    }
    ]
    }
  5. Attach it to the role.

    Terminal window
    aws iam put-role-policy \
    --role-name slashinfra-reader \
    --policy-name s3-read \
    --policy-document file://s3-read.json
  6. In the VM, save this program as /home/user/bin/aws-creds and run chmod +x /home/user/bin/aws-creds. It mints a token, exchanges it with AWS STS for a role session, and prints the credentials in the format of the AWS credential_process setting. It uses only Python’s standard library, so the VM needs no AWS tool.

    #!/usr/bin/env python3
    import json, subprocess, sys, urllib.error, urllib.parse, urllib.request
    import xml.etree.ElementTree as ET
    ROLE_ARN = "arn:aws:iam::123456789012:role/slashinfra-reader"
    token = subprocess.run(
    ["si-identity", "--audience", "sts.amazonaws.com"],
    check=True, capture_output=True, text=True,
    ).stdout.strip()
    body = urllib.parse.urlencode({
    "Action": "AssumeRoleWithWebIdentity",
    "Version": "2011-06-15",
    "RoleArn": ROLE_ARN,
    "RoleSessionName": "slashinfra-vm",
    "WebIdentityToken": token,
    }).encode()
    try:
    reply = urllib.request.urlopen(urllib.request.Request("https://sts.amazonaws.com/", data=body), timeout=10).read()
    except urllib.error.HTTPError as error:
    sys.exit(error.read().decode())
    ns = {"sts": "https://sts.amazonaws.com/doc/2011-06-15/"}
    credentials = ET.fromstring(reply).find("sts:AssumeRoleWithWebIdentityResult/sts:Credentials", ns)
    print(json.dumps({
    "Version": 1,
    "AccessKeyId": credentials.findtext("sts:AccessKeyId", namespaces=ns),
    "SecretAccessKey": credentials.findtext("sts:SecretAccessKey", namespaces=ns),
    "SessionToken": credentials.findtext("sts:SessionToken", namespaces=ns),
    "Expiration": credentials.findtext("sts:Expiration", namespaces=ns),
    }))
  7. In the VM, save this as /home/user/.aws/config. credential_process needs the full path, without ~.

    [default]
    region = eu-west-1
    credential_process = /home/user/bin/aws-creds
  8. Use any AWS SDK or the AWS CLI as usual. Each one runs aws-creds when it needs credentials and again before they expire, so no key is stored in the VM. With boto3 (pip install boto3):

    import boto3
    for item in boto3.client("s3").list_objects_v2(Bucket="my-bucket").get("Contents", []):
    print(item["Key"])

A VM’s id changes when you create a new VM, including one from a snapshot or a fork. Add the new id to trust.json and run aws iam update-assume-role-policy --role-name slashinfra-reader --policy-document file://trust.json.

You set this up once from your laptop with gcloud, then programs in the VM use Google Cloud client libraries with no key file. The example grants read access to one Cloud Storage bucket, my-bucket. Replace PROJECT_NUMBER with your Google Cloud project number (a number, not the project id), and ORG_ID with your SlashInfra organization id: the org line of si whoami.

Google Cloud can check any claim of the token. The provider below accepts only tokens of your organization, so a VM of another SlashInfra organization is refused even before any role applies.

  1. Create a workload identity pool.

    Terminal window
    gcloud iam workload-identity-pools create slashinfra \
    --location=global \
    --display-name="SlashInfra"
  2. Create the OIDC provider in it. The attribute mapping keeps the VM, organization and project of the token; the attribute condition refuses every token that is not from your organization.

    Terminal window
    gcloud iam workload-identity-pools providers create-oidc slashinfra \
    --location=global \
    --workload-identity-pool=slashinfra \
    --issuer-uri="https://api.slashinfra.com" \
    --allowed-audiences="slashinfra" \
    --attribute-mapping="google.subject=assertion.sub,attribute.org=assertion.org,attribute.project=assertion.project" \
    --attribute-condition="assertion.org == 'ORG_ID'"
  3. Grant the bucket role to one VM, by its subject:

    Terminal window
    gcloud storage buckets add-iam-policy-binding gs://my-bucket \
    --role=roles/storage.objectViewer \
    --member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/slashinfra/subject/svm:6f1c0f0e8a"

    Or grant it to every VM of one SlashInfra project, by the project attribute. The project id is the proj_ id in si org project ls.

    Terminal window
    gcloud storage buckets add-iam-policy-binding gs://my-bucket \
    --role=roles/storage.objectViewer \
    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/slashinfra/attribute.project/proj_6f1c0f0e8a"
  4. In the VM, save this program as /home/user/bin/gcp-token and run chmod +x /home/user/bin/gcp-token. It mints a token and prints it in Google Cloud’s format for executable-sourced credentials.

    #!/usr/bin/env python3
    import base64, json, subprocess
    token = subprocess.run(
    ["si-identity", "--audience", "slashinfra"],
    check=True, capture_output=True, text=True,
    ).stdout.strip()
    payload = token.split(".")[1]
    claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
    print(json.dumps({
    "version": 1,
    "success": True,
    "token_type": "urn:ietf:params:oauth:token-type:id_token",
    "id_token": token,
    "expiration_time": claims["exp"],
    }))
    Terminal window
    /home/user/bin/gcp-token
    Output
    {"version": 1, "success": true, "token_type": "urn:ietf:params:oauth:token-type:id_token", "id_token": "eyJ...", "expiration_time": 1795968147}
  5. On your laptop, write the credential configuration that points at that program, then copy it to the VM.

    Terminal window
    gcloud iam workload-identity-pools create-cred-config \
    projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/slashinfra/providers/slashinfra \
    --executable-command="/home/user/bin/gcp-token" \
    --executable-timeout-millis=5000 \
    --output-file=gcp-credentials.json
    si cp gcp-credentials.json my-vm:/home/user/gcp-credentials.json
  6. In the VM, point the client libraries at the file. Google’s libraries run a credential program only when you allow it with GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES.

    Terminal window
    export GOOGLE_APPLICATION_CREDENTIALS=/home/user/gcp-credentials.json
    export GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES=1
  7. Use a client library as usual. With google-cloud-storage (pip install google-cloud-storage):

    from google.cloud import storage
    for blob in storage.Client(project="my-project").list_blobs("my-bucket"):
    print(blob.name)

To set those variables on every new VM, put them in a profile, or in the env of the VM.

Field Type Default Allowed values What it changes
--audience string Required 1 to 256 bytes, a URL or a service name The aud claim, and the cloud provider that accepts the token.
--ttl integer 600 60 to 3600 seconds The life of a new token. A cached token for the same audience keeps its original life until its last minute.
-h, --help flag Prints the usage line.

Scroll horizontally to see all columns.

Operation Who can Key action
Open a shell in the VM Any member with a key that includes the VM’s project None
Get a token Anyone with a shell in the VM None
Use the token in AWS or Google Cloud The cloud principal you grant None on SlashInfra

Scroll horizontally to see all columns.

  • A token lasts 60 to 3600 seconds. The default is 600.
  • An audience has 1 to 256 bytes.
  • SlashInfra keeps one token per VM generation and audience and reuses it until 60 seconds before exp. A shorter --ttl does not shorten a token it already holds.
  • A token cannot be revoked before exp.
  • si-identity writes no file. A program that saves the output makes its own copy.
  • Tokens are signed with ES256, which AWS and Google Cloud accept.

The full list is in Limits.

  • Secrets: inject a key for one host when a cloud login does not apply.
  • VMs: the VM whose id the token names.
  • Isolation: what a VM can reach.