Configure Fly.io Workload Identity
Authenticate Fly Machines to Keycard with the Machine's OIDC token.
A Fly Machine gets a short-lived OIDC token from the Machines API, with your Zone as its audience. It sends the token to Keycard along with the Client ID of the Application credential it authenticates as. Keycard checks the token’s signature with your organization’s public keys, then checks its audience, subject, and claims.
Prerequisites
Section titled “Prerequisites”- Familiarity with the concepts in Workload Identity, and with Fly.io’s OpenID Connect docs
- A Keycard Zone and an Application for the app
- Your Zone issuer URL, from Settings → Connection in Keycard Console
- The Keycard CLI, signed in with
keycard auth signin --org <org-id> - A Fly.io app, and your organization slug, as
fly launchprints it:Created app '<app-name>' in organization '<org-slug>'. It’s also in your dashboard URL,fly.io/dashboard/<org-slug>. For a personal organization,fly orgs listshowspersonal, which never appears in tokens.
Register your organization as a Provider
Section titled “Register your organization as a Provider”Each Fly.io organization has its own issuer. Create one Provider per organization:
keycard agent api /zones/<zone-id>/providers --org <org-id> -X POST -d '{ "name": "Fly.io <org-slug>", "identifier": "https://oidc.fly.io/<org-slug>", "protocols": { "oauth2": { "issuer": "https://oidc.fly.io/<org-slug>" } }}'Keycard discovers the organization’s signing keys from the issuer.
Create a token credential
Section titled “Create a token credential”-
Add the credential to the Application
Terminal window keycard agent api /zones/<zone-id>/application-credentials --org <org-id> -X POST -d '{"type": "token","version": 2,"application_id": "<application-id>","provider_id": "<fly-provider-id>","subject": "<org-slug>:<app-name>:*"}'Field Value subjectThe app’s Machines. The last segment is the Machine’s name, which differs per Machine, so end with *to trust every Machine in the app. To trust one named Machine, use<org-slug>:<app-name>:<machine-name>.allowed_audienceOmitted, so it defaults to your Zone issuer URL. The Machine requests its token with that audience. authentication_conditionOptional. The issuer already limits tokens to your organization. Fly.io tokens also carry
app_id,machine_id,image,image_digest, andregion. For an example token, see Fly.io’s OpenID Connect docs. -
Copy the credential’s Client ID
The response’s
identifieris the credential’s Client ID. The app sends it asclient_id. It is not a secret.
Configure the app
Section titled “Configure the app”-
Set environment variables
None of these values are secrets, so set them in
fly.toml:[env]KEYCARD_ISSUER = "<keycard-issuer-url>"KEYCARD_CLIENT_ID = "<client-id>"KEYCARD_RESOURCE_URL = "<resource-url>"fly deployappliesfly.toml. Machines you created withfly machine runaren’t part of a Fly Launch deploy, so neitherfly deploynor a plainfly secrets setreaches them. Stage the values on the app, then update each Machine:Terminal window fly secrets set --stage \KEYCARD_ISSUER="<keycard-issuer-url>" \KEYCARD_CLIENT_ID="<client-id>" \KEYCARD_RESOURCE_URL="<resource-url>"fly machine update <machine-id> --yesfly machine listshows each Machine’s ID. For a scheduled Machine, add--skip-startso the update doesn’t start an extra run; the Machine picks up the values at its next scheduled start. -
Request a Fly.io token and exchange it
Request a token from the Machines API at
/.fly/apiwith your Zone issuer URL as the audience. Then send it asclient_assertion, with the credential’s Client ID asclient_id, in aclient_credentialsgrant:Terminal window pip install keycardai-oauthimport asyncioimport osfrom keycardai.oauth import AsyncClient, GrantTypefrom keycardai.oauth.server import FlyTokenSourceasync def get_access_token() -> str:issuer = os.environ["KEYCARD_ISSUER"]fly_token = await FlyTokenSource(audience=issuer).identity_token()async with AsyncClient(issuer) as client:response = await client.client_credentials_grant(client_assertion=fly_token,client_assertion_type=GrantType.JWT_BEARER_CLIENT_ASSERTION,client_id=os.environ["KEYCARD_CLIENT_ID"],resource=os.environ["KEYCARD_RESOURCE_URL"],)return response.access_tokenaccess_token = asyncio.run(get_access_token())Terminal window npm install @keycardai/oauthimport { ClientCredentialsClient } from "@keycardai/oauth";import { FlyTokenSource } from "@keycardai/oauth/server";const issuer = process.env.KEYCARD_ISSUER!;const flyToken = await new FlyTokenSource({ audience: issuer }).identityToken();const client = new ClientCredentialsClient(issuer);const response = await client.requestToken({clientAssertion: flyToken,clientAssertionType: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",clientId: process.env.KEYCARD_CLIENT_ID!,resource: process.env.KEYCARD_RESOURCE_URL!,});const accessToken = response.accessToken;Terminal window go get github.com/keycardai/go-sdk/oauthissuer := os.Getenv("KEYCARD_ISSUER")flyToken, err := oauth.NewFlyTokenSource(oauth.WithFlyAudience(issuer)).IdentityToken(ctx)if err != nil {return err}client := oauth.NewClientCredentialsClient(issuer)response, err := client.RequestToken(ctx, oauth.ClientCredentialsRequest{ClientID: os.Getenv("KEYCARD_CLIENT_ID"),ClientAssertion: flyToken,ClientAssertionType: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",Resource: os.Getenv("KEYCARD_RESOURCE_URL"),})if err != nil {return err}accessToken := response.AccessTokenTerminal window bundle add keycardai-oauthrequire "keycardai/oauth"issuer = ENV.fetch("KEYCARD_ISSUER")fly_token = Keycardai::OAuth::FlyTokenSource.new(audience: issuer).identity_tokenclient = Keycardai::OAuth::ClientCredentialsClient.new(issuer: issuer)response = client.request_token(client_id: ENV.fetch("KEYCARD_CLIENT_ID"),client_assertion: fly_token,client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",resource: ENV.fetch("KEYCARD_RESOURCE_URL"))access_token = response.access_tokenTerminal window FLY_TOKEN=$(curl -sSf --unix-socket /.fly/api -X POST http://localhost/v1/tokens/oidc \-H "Content-Type: application/json" \-d "{\"aud\": \"$KEYCARD_ISSUER\"}")curl -sS "$KEYCARD_ISSUER/oauth/2/token" \-d grant_type=client_credentials \-d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \--data-urlencode "client_assertion=$FLY_TOKEN" \--data-urlencode "client_id=$KEYCARD_CLIENT_ID" \--data-urlencode "resource=$KEYCARD_RESOURCE_URL"Request a new token for each exchange. Fly.io tokens expire after 10 minutes.
Verify
Section titled “Verify”Deploy with fly deploy, or update a fly machine run Machine as in Configure the app, and run the app. The exchange returns an access token, and a credentials:issue event shows on the Application’s Activity tab in Keycard Console.
Troubleshooting
Section titled “Troubleshooting”Keycard returns invalid_client with Invalid client assertion when the issuer, audience, subject, or condition doesn’t match. The Audit Log records details on the failure. Request a token on a Machine and decode it to compare its claims against the Provider and credential. The image needs curl:
fly ssh console --machine <machine-id> -C "curl -sSf --unix-socket /.fly/api -X POST http://localhost/v1/tokens/oidc -H 'Content-Type: application/json' -d '{\"aud\": \"<keycard-issuer-url>\"}'" \ | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson | {iss, aud, sub}'issdoesn’t match the Provider: the Provider usespersonalor the organization’s display name. Use the slug iniss.subdoesn’t match: the app was renamed, or the subject names one Machine and the app runs others. End the subject with*.auddiffers from the Zone issuer URL: the token was requested withoutaud, so Fly.io set its default,https://fly.io/<org-slug>. Request it withaudset toKEYCARD_ISSUERexactly.- Wrong Client ID:
KEYCARD_CLIENT_IDisn’t the Client ID of a Workload Identity credential in this Zone, orKEYCARD_ISSUERnames another Zone. - Connection refused on
/.fly/api: the code isn’t running on a Fly Machine. The Machines API socket exists only inside one.