diff --git a/docs.json b/docs.json index 4a93aba9..f3cf3561 100644 --- a/docs.json +++ b/docs.json @@ -286,6 +286,28 @@ "pages": [ "introduction/manage", "info/projects", + "info/authentication", + { + "group": "Workload Identity Federation", + "pages": [ + "info/workload-identity/overview", + "info/workload-identity/service-accounts", + { + "group": "Providers", + "pages": [ + "info/workload-identity/github-actions", + "info/workload-identity/aws", + "info/workload-identity/google-cloud", + "info/workload-identity/microsoft-entra", + "info/workload-identity/kubernetes", + "info/workload-identity/custom-oidc" + ] + }, + "info/workload-identity/migrate-from-api-keys", + "info/workload-identity/reference", + "info/workload-identity/troubleshooting" + ] + }, "info/api-keys", "info/api-key-permissions", "info/audit-logs", diff --git a/info/api-key-permissions.mdx b/info/api-key-permissions.mdx index b35c2efe..6ef92716 100644 --- a/info/api-key-permissions.mdx +++ b/info/api-key-permissions.mdx @@ -1,9 +1,23 @@ --- -title: "API Key Permissions" -description: "Actions and resources you can grant in a scoped API key policy" +title: "Scoping Permissions" +description: "Actions and resources you can grant in a policy for an API key, a federation rule, or a service account API key" --- -This page lists everything you can grant in a scoped API key's `policy`. To create a scoped key, see [Scope a key to specific resources](/info/api-keys#scope-a-key-to-specific-resources). +A **policy** limits what a credential can do. It's a list of allow statements, each pairing one action with one resource, and everything it doesn't list is denied. This page lists everything you can grant in a policy. + +## Where policies apply + +Three kinds of credential carry a policy, and all three use the same format: + +| Credential | Policy | Boundary | +| --- | --- | --- | +| [Scoped API key](/info/api-keys#scope-a-key-to-specific-resources) | Optional. A key without a policy is unrestricted inside its organization or project. | The key's organization, or its project for a project-scoped key. | +| [Federation rule](/info/workload-identity/overview#federation-rules) | Required. | The rule's one project. | +| [Service account API key](/info/workload-identity/service-accounts#service-account-api-keys) | Required. | The key's one project. | + +Every resource in a policy must be inside its credential's boundary. A few operations stay closed to federation rules and service account API keys whatever their policy grants. See [what a service account can't do](/info/workload-identity/service-accounts#what-a-service-account-cant-do). + +For a CI job, cloud service, or Kubernetes pod, put the policy on a federation rule instead of a stored key. See [API authentication](/info/authentication) to choose. ## Resources @@ -13,7 +27,7 @@ This page lists everything you can grant in a scoped API key's `policy`. To crea | `projects/{project_id}/*` | Everything in the project. | | `projects/{project_id}/{kind}/{id}` | One object. `kind` is `browsers`, `profiles`, `vaults`, or `proxies`. | -Resources must be inside the new key's organization, or its project for a project-scoped key. Kernel checks that every object ID exists when you create the key. +Resources must be inside the credential's boundary: the organization, or the one project for a project-scoped key, a federation rule, or a service account API key. Kernel checks that every object ID exists when you create or update the key or rule. ## Conditions @@ -31,7 +45,7 @@ A statement can carry one condition that narrows it to matching requests: How conditions evaluate: -- A condition only narrows its own statement. To restrict a whole key, add the same condition to every statement. +- A condition only narrows its own statement. To restrict a whole credential, add the same condition to every statement. - Requests from outside every listed network get `403` with `insufficient_scope`, recorded in your [audit logs](/info/audit-logs) with the client IP. - A scoped key can't delegate a wider condition than it holds: a delegated key can narrow its parent's IP rules, never loosen them. - You can add or change IP rules on an existing key without rotating its credential. See [Limit a key to your IP ranges](/info/api-keys#limit-a-key-to-your-ip-ranges). @@ -88,11 +102,11 @@ How conditions evaluate: | Add or remove a card in a Kernel wallet (`add_payment_method`, `remove_payment_method`) | `vaults:use` and `vaults:write` on the vault. Without `vaults:write`, the wallet doesn't list either operation in `available_operations`, and invoking one returns `403` with `insufficient_scope`. Other wallet and purchase operations need only `vaults:use`. | | Run a proxy health check | `proxies:use` and `proxies:read`. | -List endpoints return only the objects the key can access, so a key without a matching grant gets an empty list. +List endpoints return only the objects the credential can access, so a credential without a matching grant gets an empty list. -## Not available to scoped keys +## Not available to credentials with a policy -Scoped keys get `403` with `insufficient_scope` on: +A credential with a policy gets `403` with `insufficient_scope` on: - API key management, including creating, listing, rotating, and deleting keys. - Browser pools. diff --git a/info/api-keys.mdx b/info/api-keys.mdx index 91006a80..bdb90016 100644 --- a/info/api-keys.mdx +++ b/info/api-keys.mdx @@ -7,6 +7,10 @@ An API key is the credential your server, script, or CI job uses to call Kernel Kernel only returns the plaintext key once, when you create it. Save the `key` value immediately. After that, Kernel only shows the masked value. + +**For anything that isn't a person at a keyboard, use [workload identity federation](/info/workload-identity/overview) instead of an API key.** An API key is a stored secret that works until someone revokes it. With federation, a CI job, cloud service, or Kubernetes pod exchanges a token from its own identity provider for a short-lived KERNEL access token, and there's no secret to store. API keys remain the right tool for local development and for environments with no identity provider. See [API authentication](/info/authentication) to choose. + + ## Before you start You need one existing Kernel credential to create another API key: @@ -261,6 +265,18 @@ If you need a credential whose lifetime you control (for CI, a persistent backen List keys to audit what exists. List and retrieve responses include `masked_key`, `project_id`, `project_name`, `created_by`, expiry metadata, and `policy` for scoped keys, but they don't include the plaintext key. +The list returns `active` keys by default: keys that are neither deleted nor expired. Pass `status` to see the others, and combine these filters to narrow the list: + +| Query parameter | Returns | +| --- | --- | +| `status` | `active` (the default), `expired`, `deleted`, or `all`. Expired keys aren't part of `active`. | +| `principal_type` | `user` for keys that act as a person, or `service_account` for keys that act as a [service account](/info/workload-identity/service-accounts). | +| `service_account_id` | Keys that belong to one service account. | +| `created_by` | Keys created by one user ID. | +| `project_id` | Keys scoped to one project. Use `org` for keys that aren't scoped to a project. | + +In the dashboard, filter the list by **Created by**, **Linked account**, and **Project**, and switch between **Active**, **Expired**, and **Deleted**. + ```typescript TypeScript for await (const apiKey of kernel.apiKeys.list({ limit: 20 })) { @@ -459,6 +475,14 @@ After you rotate a key: To cut over immediately instead of using a grace window, pass `expire_in_days: 0`. The old key stops working, its associated browsers are ended asynchronously, and unsaved profile changes in those browsers are discarded. With a grace period, existing browsers keep running after the old key expires. +## Service account API keys + +A key you create for yourself acts as you. For a workload that can't use [workload identity federation](/info/workload-identity/overview), an organization admin can link a key to a [service account](/info/workload-identity/service-accounts) instead, so the key belongs to the organization and keeps working when its creator leaves. + +A service account API key always has one project and an explicit policy, and it can't hold API key permissions. Create one from the dashboard: click **Create API Key**, choose **Continue with an API key**, and pick the service account under **Linked account**. See [Service account API keys](/info/workload-identity/service-accounts#service-account-api-keys). + +It's still a stored secret. Prefer federation wherever your workload has an identity provider, and [move existing workloads](/info/workload-identity/migrate-from-api-keys) when you can. + ## Troubleshooting | Error | What it means | What to do | diff --git a/info/authentication.mdx b/info/authentication.mdx new file mode 100644 index 00000000..01f06ca1 --- /dev/null +++ b/info/authentication.mdx @@ -0,0 +1,65 @@ +--- +title: "API Authentication" +description: "Choose how your code authenticates to KERNEL: workload identity federation for workloads, API keys for local development" +--- + +Every request to the KERNEL API carries a credential in the `Authorization: Bearer` header. + +**Use [workload identity federation](/info/workload-identity/overview) for anything that isn't a person at a keyboard.** A CI job, a cloud service, or a Kubernetes pod already has an identity from its platform. Federation exchanges that identity for a short-lived KERNEL access token, so there's no long-lived secret to store, rotate, or leak. Each access token lasts five minutes by default, and the SDK requests a new one before it expires, so a workload of any length stays authenticated. + +## Why federation instead of an API key + +By default, a static API key works from anywhere, for anyone who holds it, until someone revokes it. A federated credential doesn't have that failure mode. + +| | Static API key | Workload identity federation | +| --- | --- | --- | +| **What you store** | A secret, in a CI variable, a secret manager, or an environment file. | Nothing. The rule ID your workload sends isn't a secret. | +| **Lifetime** | Until it expires or you delete it. Expiry is optional and can be up to 3,650 days. | 300 seconds by default, 600 at most. The SDK exchanges a fresh token before it expires. | +| **If it leaks** | It works until you revoke it, from any machine, or only from the [IP ranges](/info/api-keys#limit-a-key-to-your-ip-ranges) you limited it to if you set them. | The token stops working within minutes, and nobody can get a new one without your workload's own identity. | +| **Who can use it** | Anyone who has the string. | Only the workload your federation rule names, such as one repository, workflow, and branch. | +| **Scope** | Your whole organization or one project. A policy is optional. | Always one project and an explicit policy. | +| **Rotation** | You rotate it and redeploy every consumer. | Nothing to rotate. | +| **Turning it off** | Delete the key. | Disable the rule, issuer, or service account. Issued tokens stop working within about 10 seconds. | +| **Attribution** | The person who created the key, or a service account. | A named service account, with a record of each token it was issued. | + +## Which one to use + +| Your code runs in | Use | +| --- | --- | +| A GitHub Actions workflow | [Federation with GitHub Actions](/info/workload-identity/github-actions) | +| AWS (ECS, Lambda, EC2) | [Federation with AWS](/info/workload-identity/aws) | +| Google Cloud (GKE, Cloud Run, Compute Engine) | [Federation with Google Cloud](/info/workload-identity/google-cloud) | +| Azure, with a managed identity or an app registration | [Federation with Microsoft Entra](/info/workload-identity/microsoft-entra) | +| A Kubernetes cluster | [Federation with Kubernetes](/info/workload-identity/kubernetes) | +| Any other platform that issues OIDC tokens | [Federation with a custom OIDC issuer](/info/workload-identity/custom-oidc) | +| A server or tool with no identity provider | A [service account API key](/info/workload-identity/service-accounts#service-account-api-keys), limited to one project and an explicit policy | +| Your laptop, while you develop | `kernel login` for the [CLI](/reference/cli/auth), or a personal [API key](/info/api-keys) with a short expiry for the SDKs | +| A KERNEL app deployment | The [deployment key](/info/api-keys#deployment-api-keys) KERNEL injects for you | +| An MCP client such as Claude or Cursor | [OAuth](/reference/mcp-server/authentication) | + +## When an API key is still the right tool + +For some jobs an API key is still a reasonable choice: + +- **Local development.** Your laptop has no workload identity. Sign in with `kernel login`, or create a personal key with a short expiry. +- **Environments with no identity provider.** A VM at a host that issues no OIDC tokens, or a third-party tool that only accepts a key, can't federate. Give it a [service account API key](/info/workload-identity/service-accounts#service-account-api-keys) so the key belongs to your organization, not to the person who created it. +- **Access across projects.** A federation rule covers one project. A task that needs every project in your organization at once needs an organization-scoped key. +- **Features closed to service accounts.** Acquiring a browser from a [pool](/browsers/pools), deploying or invoking [apps](/apps/deploy), and managing API keys aren't available to federated credentials. See [what a service account can't do](/info/workload-identity/service-accounts#what-a-service-account-cant-do). + +When you do use an API key, limit what a leak can reach: scope it to one project, give it a [policy](/info/api-keys#scope-a-key-to-specific-resources) and a short expiry, and [limit it to your IP ranges](/info/api-keys#limit-a-key-to-your-ip-ranges) if it's used from a fixed network. + +If you already run workloads on API keys, [move them to federation](/info/workload-identity/migrate-from-api-keys) one at a time. Both credentials work side by side while you switch. + +## Next steps + + + + How the exchange works, and how to connect your first workload. + + + Switch an existing workload without downtime. + + + Create, scope, rotate, and delete keys. + + diff --git a/info/projects.mdx b/info/projects.mdx index 12e0221a..cf0ecc37 100644 --- a/info/projects.mdx +++ b/info/projects.mdx @@ -112,6 +112,10 @@ API keys can be **org-wide** or **project-scoped**. OAuth tokens (used by the Kernel CLI and MCP server) are **always org-wide**. You cannot bind an OAuth session to a single project. To scope OAuth-authenticated requests, send the `X-Kernel-Project-Id` header with each request — or use the CLI's `--project` flag (see below). +### Workload identity federation + +A [federation rule](/info/workload-identity/overview#federation-rules) names exactly one project, and the tokens it issues work only in that project. So does a [service account API key](/info/workload-identity/service-accounts#service-account-api-keys). To give a workload access to two projects, such as `staging` and `production`, create one rule for each. + ## Using projects from the CLI The Kernel [CLI](/reference/cli/projects) has first-class project support: diff --git a/info/workload-identity/aws.mdx b/info/workload-identity/aws.mdx new file mode 100644 index 00000000..b057d1cb --- /dev/null +++ b/info/workload-identity/aws.mdx @@ -0,0 +1,260 @@ +--- +title: "AWS" +description: "Authenticate ECS tasks, Lambda functions, and EC2 instances to KERNEL with AWS STS web identity tokens" +--- + +A workload on AWS already has an IAM role. With AWS [outbound identity federation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_outbound.html), that role can ask the AWS Security Token Service (STS) for a signed token that names it. With [workload identity federation](/info/workload-identity/overview), your workload exchanges that token for a KERNEL access token, so you don't put a `KERNEL_API_KEY` in Secrets Manager, a task definition, or a Lambda environment. + + +Running on EKS? You can use this guide with the pod's IAM role, or use the cluster's own service account tokens with the [Kubernetes](/info/workload-identity/kubernetes) provider. + + +## Before you start + +- You're an organization admin in KERNEL. +- You can change IAM account settings and role policies in the AWS account. +- Your workload uses the TypeScript, Python, or Go SDK. + +## Configure AWS + + + +In the AWS console, open **IAM** > **Account settings** and enable outbound identity federation. Or run: + +```bash +aws iam enable-outbound-web-identity-federation +``` + +Note the account's token issuer URL. Each AWS account has its own, and it looks like `https://a1b2c3d4-0000-4111-8222-333344445555.tokens.sts.global.api.aws`. + + + +Attach a policy to the role your workload runs as. This one allows tokens for KERNEL only, and caps their lifetime at five minutes: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "sts:GetWebIdentityToken", + "Resource": "*", + "Condition": { + "ForAllValues:StringEquals": { + "sts:IdentityTokenAudience": "https://auth.onkernel.com" + }, + "Null": { + "sts:IdentityTokenAudience": "false" + }, + "NumericLessThanEquals": { + "sts:DurationSeconds": 300 + } + } + } + ] +} +``` + + + +## Configure KERNEL + + + +In the [dashboard](https://dashboard.onkernel.com), open **Keys** > **Workload identity**, click **Connect workload**, and select the **AWS** tile. + +- Paste the issuer URL into **STS token issuer URL**. +- Check **Outbound web identity federation is enabled for this AWS account.** +- Click **Apply and continue**. + +Register one issuer per AWS account. + + + +Under **Match conditions**, enter the **IAM role ARN** your workload runs as, such as `arn:aws:iam::123456789012:role/service/browser-worker`. + +The token's subject is the full role ARN, including its path. A role created with the path `/service/` has `role/service/browser-worker` in its ARN, and the rule must include it. + +Under **Authorization**, choose the **Project**, the **Permissions**, and the **Token lifetime**. + + + +Choose or create a service account, click **Create rule**, then turn on the issuer and the rule in the **Test** step. Copy the rule ID (`wifr_...`). + + + +## Configure your workload + +The AWS source needs the AWS SDK for your language, which each KERNEL SDK keeps optional: + + +```bash TypeScript +npm install @onkernel/sdk @aws-sdk/client-sts +``` + +```bash Python +pip install "kernel[aws]" +``` + +```bash Go +go get github.com/kernel/kernel-go-sdk +``` + + +Set two environment variables on the task, function, or instance: + +```bash +KERNEL_FEDERATION_RULE_ID=wifr_k3v8q1m6z2x9c4b7n0h5j2da +KERNEL_IDENTITY_TOKEN_SOURCE=aws_sts +``` + +Then construct the client with no arguments: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; + +const kernel = new Kernel(); + +const browser = await kernel.browsers.create(); +console.log(browser.session_id); +``` + +```python Python +from kernel import Kernel + +client = Kernel() + +browser = client.browsers.create() +print(browser.session_id) +``` + +```go Go +package main + +import ( + "context" + "fmt" + + "github.com/kernel/kernel-go-sdk" + // Registers the aws_sts identity token source. + _ "github.com/kernel/kernel-go-sdk/lib/credentials/awssts" +) + +func main() { + ctx := context.Background() + client := kernel.NewClient() + + browser, err := client.Browsers.New(ctx, kernel.BrowserNewParams{}) + if err != nil { + panic(err) + } + fmt.Println(browser.SessionID) +} +``` + + +In Go, the blank import is what turns the AWS source on. Programs that don't import it don't depend on the AWS SDK. + +| SDK | Requirement | Without it | +| --- | --- | --- | +| TypeScript | `@aws-sdk/client-sts` version 3.935.0 or later | The first request fails with an error that names the package. | +| Python | `boto3` 1.41.0 or later, installed by `kernel[aws]` | The first request raises an error that names the extra. | +| Go | The `awssts` import | Requests fail with an error that names the import. | + +## What the SDK does + +For every exchange, the SDK calls STS [`GetWebIdentityToken`](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) with your workload's own AWS credentials: + +- **Audience:** `https://auth.onkernel.com` +- **Signing algorithm:** `RS256` +- **Duration:** 300 seconds +- **Region:** `AWS_REGION`, then `AWS_DEFAULT_REGION`, then `us-east-1`. The call goes to that region's STS endpoint. + +It then exchanges the token at `https://auth.onkernel.com/token`. AWS tokens are always single-use in KERNEL, and the SDK requests a new one for each refresh. + +To configure the source in code, for example to set the region: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; +import { identityTokenFromAWSSTS, oidcFederationProvider } from '@onkernel/sdk/lib/credentials'; + +const kernel = new Kernel({ + credentials: oidcFederationProvider({ + federationRuleId: 'wifr_k3v8q1m6z2x9c4b7n0h5j2da', + identityTokenProvider: identityTokenFromAWSSTS({ region: 'us-west-2' }), + }), +}); +``` + +```python Python +from kernel import AWSSTSIdentityToken, Kernel, WorkloadIdentityCredentials + +client = Kernel( + credentials=WorkloadIdentityCredentials( + identity_token_provider=AWSSTSIdentityToken(region="us-west-2"), + federation_rule_id="wifr_k3v8q1m6z2x9c4b7n0h5j2da", + ) +) +``` + +```go Go +package main + +import ( + "github.com/aws/aws-sdk-go-v2/config" + "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/lib/credentials/awssts" + "github.com/kernel/kernel-go-sdk/option" +) + +func main() { + client := kernel.NewClient( + option.WithFederationTokenProvider( + awssts.IdentityToken("https://auth.onkernel.com", config.WithRegion("us-west-2")), + option.FederationOptions{FederationRuleID: "wifr_k3v8q1m6z2x9c4b7n0h5j2da"}, + ), + ) + _ = client +} +``` + + +## What the token looks like + +```json +{ + "iss": "https://a1b2c3d4-0000-4111-8222-333344445555.tokens.sts.global.api.aws", + "aud": "https://auth.onkernel.com", + "sub": "arn:aws:iam::123456789012:role/service/browser-worker", + "jti": "6f2b1d3e-7c4a-4d55-9d6a-0a1b2c3d4e5f", + "https://sts.amazonaws.com/": { + "aws_account": "123456789012", + "source_region": "us-east-1", + "principal_id": "arn:aws:iam::123456789012:role/service/browser-worker" + } +} +``` + +Two details to make note of: + +- **`sub` is the role ARN, not the assumed-role session ARN.** Match `arn:aws:iam:::role//`. +- **AWS's own claims are nested** under the key `https://sts.amazonaws.com/`. They aren't top-level claims. + +## Narrow the rule + +A rule that names one role ARN is already specific. To add a condition on a nested claim, open **Advanced matching** in the rule and add an **Additional claim condition**. Claim paths are [JSON Pointers](https://datatracker.ietf.org/doc/html/rfc6901), so each `/` inside the AWS key is written `~1`: + +| Claim | Expected value | Meaning | +| --- | --- | --- | +| `/https:~1~1sts.amazonaws.com~1/aws_account` | `123456789012` | The token came from this AWS account. | +| `/https:~1~1sts.amazonaws.com~1/source_region` | `us-east-1` | The token was requested in this region. | + +Conditions are exact matches, and every condition must hold. + +## Next steps + +- [Reference](/info/workload-identity/reference#aws-and-custom-oidc): AWS match fields +- [Troubleshooting](/info/workload-identity/troubleshooting): what a refused exchange means +- [Move a workload from an API key](/info/workload-identity/migrate-from-api-keys) diff --git a/info/workload-identity/custom-oidc.mdx b/info/workload-identity/custom-oidc.mdx new file mode 100644 index 00000000..8cad7ba5 --- /dev/null +++ b/info/workload-identity/custom-oidc.mdx @@ -0,0 +1,196 @@ +--- +title: "Custom OIDC" +description: "Federate any identity provider that signs OIDC tokens, including one you run yourself" +--- + +If your platform isn't GitHub Actions, AWS, Google Cloud, Microsoft Entra, or Kubernetes, it can still federate as long as it issues signed OIDC tokens. Register it as a custom issuer, tell KERNEL where its public keys are, and write rules against the token's subject and claims. + + +A custom issuer is trusted exactly as you configure it. KERNEL can't apply provider-specific checks to an issuer it doesn't know, so the rule you write is the whole boundary. Check the issuer URL and key source, and restrict every rule to specific subjects. + + +## What your tokens need + +KERNEL accepts a token from a custom issuer when it is: + +- A signed JWT, 16 KiB or smaller, using `RS256`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`, `ES256`, `ES384`, `ES512`, or `EdDSA`. +- Issued by exactly the registered issuer URL, in the `iss` claim. +- For exactly one audience, in the `aud` claim, equal to the rule's expected audience. +- About a non-empty subject, in the `sub` claim. +- Carrying both `iat` and `exp`, not expired, and with a lifetime no longer than the issuer's maximum. +- Carrying a `jti` claim, when the issuer is single-use. + +## Register the issuer + +In the [dashboard](https://dashboard.onkernel.com), open **Keys** > **Workload identity**, click **Connect workload**, and select the **Custom OIDC** tile. To register an issuer without creating a rule yet, use **Register issuer** on the **Issuers** tab; the fields are the same. + +| Field | What to enter | +| --- | --- | +| **Name** | A label, using letters, numbers, and hyphens. | +| **Issuer URL (iss claim)** | The exact `iss` value in your tokens. It must be an `https` URL with no query string. | +| **JWKS source** | How KERNEL gets the issuer's public signing keys. See the next table. | +| **CA certificate** | Optional. PEM-encoded public CA certificates to trust instead of the system roots when fetching discovery and keys. | +| **Enforce single-use tokens (JTI replay protection)** | On by default. Each token's `jti` can be exchanged once. Turn it off only if your workload must present the same token more than once. | +| **Maximum token lifetime (hours)** | Tokens whose `exp` minus `iat` exceeds this are refused. The default is 1 hour and the maximum is 24. | + +### JWKS source + +| Option | Use it when | What KERNEL does | +| --- | --- | --- | +| **OIDC discovery** | The issuer serves `/.well-known/openid-configuration`. This is the default. | Reads the discovery document and fetches the key set it names. If discovery lives somewhere other than the issuer URL, set **Discovery base URL**. | +| **JWKS URL** | The issuer publishes keys but no discovery document. | Fetches the key set from the **JWKS URL** you enter. | +| **Inline keys** | The issuer isn't reachable from the public internet. | Uses the JSON Web Key Set you paste into **Public keys**. Update it whenever the issuer rotates keys. | + +KERNEL fetches keys only over `https` from public internet addresses, and never follows a URL inside a token. A key set holds at most 16 public keys. RSA keys must be at least 2,048 bits. + +KERNEL caches an issuer's keys for five minutes. When a token names a key ID that isn't in the cache, KERNEL fetches the key set again, at most once a minute. A rotated key is usually picked up on the first token that uses it. + +## Write a rule + +Under **Match conditions**, a custom rule needs a subject, a claim condition, or both: + +| Field | What to enter | +| --- | --- | +| **Subject pattern** | An exact match on the `sub` claim, or a prefix match if the value ends with a single `*`. `spiffe://acme.internal/ci/*` matches every subject that starts with `spiffe://acme.internal/ci/`. | +| **Additional claim conditions** | Exact matches on other claims. Use a `/` path, such as `/resource_access/kernel/role`, for a nested claim. | +| **Expected audience** | The `aud` value the token must carry. Leave it blank for `https://auth.onkernel.com`. | + +Every condition must hold. Claim conditions compare a claim by its JSON text, so a boolean matches `true` or `false` and a number matches its digits. A condition never matches an object or an array; address an array element by its index, such as `/groups/0`. + +Prefer an exact subject. A prefix widens the rule to every subject your issuer can produce under it, including ones created later. + +Under **Authorization**, choose the **Project**, the **Permissions**, and the **Token lifetime**. Then pick a service account, create the rule, and enable the issuer and the rule in the **Test** step. + +## Supply the token from your workload + +The SDK needs a fresh token from your issuer for every exchange. Pick the way that fits how your platform delivers it. + +### From a file + +If an agent writes the token to a file and keeps it current, set: + +```bash +KERNEL_FEDERATION_RULE_ID=wifr_b4n7m1q8z5x2c9v3k6j0h7da +KERNEL_IDENTITY_TOKEN_FILE=/run/identity/kernel-token +``` + +The SDK reads the file again for every exchange. With a single-use issuer, whatever writes the file must replace the token before each refresh. Otherwise turn off single use on the issuer. + +### From a callback + +When your code fetches the token itself, pass a callback. It runs once per exchange and must return a newly issued token each time: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; +import { oidcFederationProvider } from '@onkernel/sdk/lib/credentials'; + +async function fetchIdentityToken(audience: string): Promise { + const response = await fetch('https://idp.acme.internal/token', { + method: 'POST', + body: new URLSearchParams({ audience }), + }); + if (!response.ok) throw new Error(`identity provider responded ${response.status}`); + return (await response.text()).trim(); +} + +const kernel = new Kernel({ + credentials: oidcFederationProvider({ + federationRuleId: 'wifr_b4n7m1q8z5x2c9v3k6j0h7da', + identityTokenProvider: ({ audience } = {}) => + fetchIdentityToken(audience ?? 'https://auth.onkernel.com'), + }), +}); +``` + +```python Python +import httpx +from kernel import Kernel, WorkloadIdentityCredentials + + +def fetch_identity_token() -> str: + response = httpx.post( + "https://idp.acme.internal/token", + data={"audience": "https://auth.onkernel.com"}, + ) + response.raise_for_status() + return response.text.strip() + + +client = Kernel( + credentials=WorkloadIdentityCredentials( + identity_token_provider=fetch_identity_token, + federation_rule_id="wifr_b4n7m1q8z5x2c9v3k6j0h7da", + ) +) +``` + +```go Go +package main + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/lib/credentials" + "github.com/kernel/kernel-go-sdk/option" +) + +func fetchIdentityToken(ctx context.Context) (string, error) { + audience, err := credentials.ResolveAudience(ctx, "") + if err != nil { + return "", err + } + form := url.Values{"audience": {audience}} + req, err := http.NewRequestWithContext(ctx, http.MethodPost, + "https://idp.acme.internal/token", strings.NewReader(form.Encode())) + if err != nil { + return "", err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := http.DefaultClient.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("identity provider responded %d", resp.StatusCode) + } + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + return strings.TrimSpace(string(body)), nil +} + +func main() { + client := kernel.NewClient( + option.WithFederationTokenProvider(fetchIdentityToken, option.FederationOptions{ + FederationRuleID: "wifr_b4n7m1q8z5x2c9v3k6j0h7da", + }), + ) + _ = client +} +``` + + +With `AsyncKernel` in Python, the callback can be an `async def` function. + +### From a single token + +For a short script, set `KERNEL_IDENTITY_TOKEN` to one token. It's good for exactly one exchange, so the client works until its first access token expires: 300 seconds by default. Use a file or a callback for anything longer. + +### Without an SDK + +Post the token to the token endpoint yourself. See [Exchange a token without an SDK](/info/workload-identity/overview#exchange-a-token-without-an-sdk). + +## Next steps + +- [Reference](/info/workload-identity/reference): every issuer and rule field +- [Troubleshooting](/info/workload-identity/troubleshooting): what a refused exchange means +- [Move a workload from an API key](/info/workload-identity/migrate-from-api-keys) diff --git a/info/workload-identity/github-actions.mdx b/info/workload-identity/github-actions.mdx new file mode 100644 index 00000000..e5405365 --- /dev/null +++ b/info/workload-identity/github-actions.mdx @@ -0,0 +1,264 @@ +--- +title: "GitHub Actions" +description: "Authenticate GitHub Actions workflows to KERNEL without storing a KERNEL_API_KEY secret" +--- + +Every GitHub Actions job can ask GitHub for a signed identity token that says which repository, workflow, and branch it's running. With [workload identity federation](/info/workload-identity/overview), your job exchanges that token for a KERNEL access token. You don't store a `KERNEL_API_KEY` secret in the repository, and a fork or another workflow can't use your access. + +## Before you start + +- You're an organization admin in KERNEL. +- You can edit workflow files in the repository. +- Your workflow uses the TypeScript, Python, or Go SDK. For anything else, see [Exchange the token yourself](#exchange-the-token-yourself). + +## Connect the workflow + + + +In the [dashboard](https://dashboard.onkernel.com), open **Keys** > **Workload identity**, click **Connect workload**, and select the **GitHub Actions** tile. GitHub has one fixed issuer, `https://token.actions.githubusercontent.com`, so there's nothing to enter except an optional **Name**. Click **Apply and continue**. + +Trusting GitHub's issuer accepts no workflow by itself. Each rule names the repository, workflow, and branch or environment it allows. If your organization already registered GitHub, select **Use a registered issuer** instead. + + + +Fill in the **Match conditions**: + +| Field | What to enter | +| --- | --- | +| **Repository** | `owner/name`, such as `acme/widgets`. Click **Look up IDs** to fill in the next two fields. | +| **Repository ID** and **Owner ID** | GitHub's numeric IDs. The rule matches these, not the name, so a renamed or recreated repository doesn't match. | +| **Workflow** | The workflow file's path, such as `.github/workflows/e2e.yml`. | +| **Branch** | The branch the job must run on, such as `main`. | +| **Environment** | The [deployment environment](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments) the job must use, such as `staging`. | +| **Allowed events** | The events that can trigger the job. `push` and `workflow_dispatch` are selected by default. | + +Set a branch, an environment, or both. A job must match every value you set. + +Under **Authorization**, choose the **Project**, the **Permissions**, and the **Token lifetime**. + + + +Choose or create a service account, click **Create rule**, then turn on the issuer and the rule in the **Test** step. Copy the rule ID (`wifr_...`). + + + +Give the job permission to request an identity token, and set the rule ID. The rule ID isn't a secret, so it can live in the workflow file: + +```yaml .github/workflows/e2e.yml +name: e2e +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + id-token: write # lets the job request a GitHub identity token + contents: read + +jobs: + browsers: + runs-on: ubuntu-latest + env: + KERNEL_FEDERATION_RULE_ID: wifr_tz4a98xxat96iws9zmbrgj3a + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: npm ci + - run: node scripts/run-browsers.mjs +``` + +Your script constructs the client with no arguments: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; + +const kernel = new Kernel(); + +const browser = await kernel.browsers.create(); +console.log(browser.session_id); +await kernel.browsers.deleteByID(browser.session_id); +``` + +```python Python +from kernel import Kernel + +client = Kernel() + +browser = client.browsers.create() +print(browser.session_id) +client.browsers.delete_by_id(browser.session_id) +``` + +```go Go +package main + +import ( + "context" + "fmt" + + "github.com/kernel/kernel-go-sdk" +) + +func main() { + ctx := context.Background() + client := kernel.NewClient() + + browser, err := client.Browsers.New(ctx, kernel.BrowserNewParams{}) + if err != nil { + panic(err) + } + fmt.Println(browser.SessionID) + + if err := client.Browsers.DeleteByID(ctx, browser.SessionID); err != nil { + panic(err) + } +} +``` + + + + +Push to the branch or run the workflow by hand. The exchange appears in the wizard and on the **Authentication events** tab. + +If the repository has a `KERNEL_API_KEY` secret, stop passing it to this job. The SDK uses the API key whenever it's set. Then delete the secret and the key. See [Move a workload from an API key](/info/workload-identity/migrate-from-api-keys). + + + +## What the SDK does + +When `KERNEL_FEDERATION_RULE_ID` is set and the runner exposes `ACTIONS_ID_TOKEN_REQUEST_URL`, the SDK: + +1. Asks the runner for an identity token with the audience `https://auth.onkernel.com`. +2. Exchanges it at `https://auth.onkernel.com/token`. +3. Sends the access token on each API request, and requests a new identity token for each refresh. + +A job of any length stays authenticated, because each refresh uses a new GitHub token. GitHub tokens are always single-use in KERNEL: one token, one exchange. + +If the job doesn't have `id-token: write`, the runner sets no token endpoint, so the SDK finds no identity token source and the client fails with a missing-credentials error. Add the permission to the workflow or the job. + +To select GitHub explicitly instead of relying on detection, set `KERNEL_IDENTITY_TOKEN_SOURCE=github_actions`, or configure it in code: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; +import { identityTokenFromGitHubActions, oidcFederationProvider } from '@onkernel/sdk/lib/credentials'; + +const kernel = new Kernel({ + credentials: oidcFederationProvider({ + federationRuleId: 'wifr_tz4a98xxat96iws9zmbrgj3a', + identityTokenProvider: identityTokenFromGitHubActions(), + }), +}); +``` + +```python Python +from kernel import GitHubActionsIdentityToken, Kernel, WorkloadIdentityCredentials + +client = Kernel( + credentials=WorkloadIdentityCredentials( + identity_token_provider=GitHubActionsIdentityToken(), + federation_rule_id="wifr_tz4a98xxat96iws9zmbrgj3a", + ) +) +``` + +```go Go +package main + +import ( + "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/lib/credentials" + "github.com/kernel/kernel-go-sdk/option" +) + +func main() { + client := kernel.NewClient( + option.WithFederationTokenProvider( + credentials.GitHubActions("https://auth.onkernel.com"), + option.FederationOptions{FederationRuleID: "wifr_tz4a98xxat96iws9zmbrgj3a"}, + ), + ) + _ = client +} +``` + + +## What the token looks like + +A GitHub identity token carries claims like these. Your rule is checked against them: + +```json +{ + "iss": "https://token.actions.githubusercontent.com", + "aud": "https://auth.onkernel.com", + "sub": "repo:acme@9182734/widgets@738291456:ref:refs/heads/main", + "repository": "acme/widgets", + "repository_id": "738291456", + "repository_owner_id": "9182734", + "ref": "refs/heads/main", + "workflow_ref": "acme/widgets/.github/workflows/e2e.yml@refs/heads/main", + "event_name": "push", + "jti": "f1e7a9c2-0b61-4f0e-9a3e-2f2f6f9f3c11" +} +``` + +Two details to make note of: + +- **`sub` now embeds numeric IDs.** GitHub's subject looks like `repo:owner@id/name@id:ref:...`. KERNEL rules match the `repository_id` and `repository_owner_id` claims, not `sub`, so you don't write subject patterns for GitHub. +- **`repository_id` and `repository_owner_id` are strings.** If you create rules through the API, send them as strings of digits. + +## How a rule matches + +A GitHub Actions rule accepts a token only when all of these hold: + +- `repository_id` and `repository_owner_id` equal the rule's IDs. +- `event_name` is one of the rule's allowed events. +- If the rule sets a branch, `ref` equals it. The dashboard stores `main` as `refs/heads/main`. +- If the rule sets an environment, `environment` equals it. +- If the rule sets a workflow path, `workflow_ref` equals `/@`. The workflow file must come from the same ref the job runs on. + +Every GitHub rule needs the repository and owner IDs, a workflow restriction, and a branch or an environment. KERNEL rejects a rule without them, so you can't create a rule that trusts a whole GitHub organization by accident. + + +Use an environment when the job must be approved. A rule that requires `environment: production` only matches jobs that GitHub let into that environment, so your environment's protection rules and required reviewers gate KERNEL access too. + + +### Find the repository IDs yourself + +The dashboard's **Look up IDs** button does this for you. From a terminal: + +```bash +gh api repos/acme/widgets --jq '{repository_id: .id, repository_owner_id: .owner.id}' +``` + +## Exchange the token yourself + +Without an SDK, request the token from the runner and post it to the token endpoint: + +```yaml +- name: Get a KERNEL access token + run: | + IDENTITY_TOKEN=$(curl -sS \ + -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \ + "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=https://auth.onkernel.com" | jq -r .value) + + ACCESS_TOKEN=$(curl -sS https://auth.onkernel.com/token \ + -d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \ + -d federation_rule_id=wifr_tz4a98xxat96iws9zmbrgj3a \ + -d resource=https://api.onkernel.com \ + --data-urlencode "assertion=$IDENTITY_TOKEN" | jq -r .access_token) + + echo "::add-mask::$ACCESS_TOKEN" + echo "KERNEL_ACCESS_TOKEN=$ACCESS_TOKEN" >> "$GITHUB_ENV" +``` + +The access token lasts for the rule's token lifetime, 300 seconds by default. For a longer job, repeat both requests: each exchange needs a new GitHub token. + +## Next steps + +- [Reference](/info/workload-identity/reference#github-actions): every GitHub Actions match field +- [Troubleshooting](/info/workload-identity/troubleshooting): what a refused exchange means +- [Move a workload from an API key](/info/workload-identity/migrate-from-api-keys) diff --git a/info/workload-identity/google-cloud.mdx b/info/workload-identity/google-cloud.mdx new file mode 100644 index 00000000..ad28ff0c --- /dev/null +++ b/info/workload-identity/google-cloud.mdx @@ -0,0 +1,200 @@ +--- +title: "Google Cloud" +description: "Authenticate GKE, Cloud Run, and Compute Engine workloads to KERNEL with Google-signed identity tokens" +--- + +A workload on Google Cloud runs as a service account, and the metadata server hands it a Google-signed identity token on request. With [workload identity federation](/info/workload-identity/overview), your workload exchanges that token for a KERNEL access token, so there's no `KERNEL_API_KEY` in Secret Manager or your service's environment. + +## Before you start + +- You're an organization admin in KERNEL. +- Your workload runs with a Google service account attached, on GKE, Cloud Run, Cloud Functions, or Compute Engine. +- Your workload uses the TypeScript, Python, or Go SDK. + +## Find the service account's unique ID + +Google's issuer, `https://accounts.google.com`, is shared by every Google Cloud customer. What tells your workload apart is the token's subject: the service account's numeric unique ID. Look it up: + +```bash +gcloud iam service-accounts describe browser-worker@acme-prod.iam.gserviceaccount.com \ + --format='value(uniqueId)' +``` + +The ID is a long number such as `104857600000000000000`. It's also on the service account's details page in the Google Cloud console. + +## Configure KERNEL + + + +In the [dashboard](https://dashboard.onkernel.com), open **Keys** > **Workload identity**, click **Connect workload**, and select the **Google Cloud** tile. Google has one fixed issuer, so there's nothing to enter except an optional **Name**. Click **Apply and continue**. + +Trusting Google's issuer accepts no workload by itself. Each rule names the service account it allows. + + + +Under **Match conditions**: + +| Field | What to enter | +| --- | --- | +| **Service account unique ID** | The numeric ID from the previous section. Required. | +| **Service account email** | Optional. Adds a check on the token's `email` claim. | + +Under **Authorization**, choose the **Project**, the **Permissions**, and the **Token lifetime**. + + + +Choose or create a KERNEL service account, click **Create rule**, then turn on the issuer and the rule in the **Test** step. Copy the rule ID (`wifr_...`). + + + +## Configure your workload + +Set two environment variables on the service, job, or instance: + +```bash +KERNEL_FEDERATION_RULE_ID=wifr_m8c2x5v9b1n4q7z0k3j6h2fa +KERNEL_IDENTITY_TOKEN_SOURCE=gcp_metadata +``` + +Then construct the client with no arguments: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; + +const kernel = new Kernel(); + +const browser = await kernel.browsers.create(); +console.log(browser.session_id); +``` + +```python Python +from kernel import Kernel + +client = Kernel() + +browser = client.browsers.create() +print(browser.session_id) +``` + +```go Go +package main + +import ( + "context" + "fmt" + + "github.com/kernel/kernel-go-sdk" +) + +func main() { + ctx := context.Background() + client := kernel.NewClient() + + browser, err := client.Browsers.New(ctx, kernel.BrowserNewParams{}) + if err != nil { + panic(err) + } + fmt.Println(browser.SessionID) +} +``` + + +## What the SDK does + +For every exchange, the SDK asks the metadata server for an identity token for the attached service account, with the audience `https://auth.onkernel.com` and `format=full`, then exchanges it at `https://auth.onkernel.com/token`. + +To configure the source in code: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; +import { identityTokenFromGCPMetadata, oidcFederationProvider } from '@onkernel/sdk/lib/credentials'; + +const kernel = new Kernel({ + credentials: oidcFederationProvider({ + federationRuleId: 'wifr_m8c2x5v9b1n4q7z0k3j6h2fa', + identityTokenProvider: identityTokenFromGCPMetadata(), + }), +}); +``` + +```python Python +from kernel import GCPMetadataIdentityToken, Kernel, WorkloadIdentityCredentials + +client = Kernel( + credentials=WorkloadIdentityCredentials( + identity_token_provider=GCPMetadataIdentityToken(), + federation_rule_id="wifr_m8c2x5v9b1n4q7z0k3j6h2fa", + ) +) +``` + +```go Go +package main + +import ( + "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/lib/credentials" + "github.com/kernel/kernel-go-sdk/option" +) + +func main() { + client := kernel.NewClient( + option.WithFederationTokenProvider( + credentials.GCPMetadata("https://auth.onkernel.com"), + option.FederationOptions{FederationRuleID: "wifr_m8c2x5v9b1n4q7z0k3j6h2fa"}, + ), + ) + _ = client +} +``` + + +## What the token looks like + +```json +{ + "iss": "https://accounts.google.com", + "aud": "https://auth.onkernel.com", + "azp": "104857600000000000000", + "sub": "104857600000000000000", + "email": "browser-worker@acme-prod.iam.gserviceaccount.com", + "email_verified": true, + "iat": 1780000000, + "exp": 1780003600 +} +``` + +Two details to make note of: + +- **A Google identity token lasts 3,600 seconds.** You can't request a shorter one. +- **It carries no token ID.** With no `jti` claim, KERNEL has nothing to mark as used, so a Google issuer always allows reuse: the same token can be exchanged again until it expires. + + +Because a Google identity token can be exchanged repeatedly for up to an hour, treat one like a credential for that hour. Don't log it or pass it between services. Each KERNEL access token it yields still expires after the rule's token lifetime, and disabling the rule stops new exchanges at once. + + +## Narrow the rule + +The numeric subject already pins one service account. To add more conditions, open **Advanced matching** in the rule and add an **Additional claim condition**. + +Claim conditions compare a claim by its JSON text, so a boolean matches the strings `true` and `false`: + +| Claim | Expected value | Meaning | +| --- | --- | --- | +| `email` | `browser-worker@acme-prod.iam.gserviceaccount.com` | The token names this service account email. | +| `email_verified` | `true` | Google verified the email. | +| `/google/compute_engine/project_id` | `acme-prod` | The token came from a Compute Engine instance in this project. This claim is present only on tokens requested with `format=full` from Compute Engine. | + +## Tokens from outside Google Cloud + +A workload that isn't on Google Cloud compute can still get a Google identity token by impersonating a service account. The `generateIdToken` method of the IAM Credentials API needs only the `roles/iam.serviceAccountOpenIdTokenCreator` role on that service account. `gcloud auth print-identity-token --impersonate-service-account` also needs `roles/iam.serviceAccountTokenCreator`. + +Pass the token to the SDK through a [file or a callback](/info/workload-identity/custom-oidc#supply-the-token-from-your-workload), requesting the audience `https://auth.onkernel.com`. + +## Next steps + +- [Reference](/info/workload-identity/reference#google-cloud): Google Cloud match fields +- [Troubleshooting](/info/workload-identity/troubleshooting): what a refused exchange means +- [Move a workload from an API key](/info/workload-identity/migrate-from-api-keys) diff --git a/info/workload-identity/kubernetes.mdx b/info/workload-identity/kubernetes.mdx new file mode 100644 index 00000000..fb456834 --- /dev/null +++ b/info/workload-identity/kubernetes.mdx @@ -0,0 +1,241 @@ +--- +title: "Kubernetes" +description: "Authenticate pods to KERNEL with projected service account tokens signed by your cluster" +--- + +Every Kubernetes cluster signs tokens for its service accounts. With [workload identity federation](/info/workload-identity/overview), a pod mounts one of those tokens, and the KERNEL SDK exchanges it for a KERNEL access token. You don't create a Kubernetes `Secret` holding a `KERNEL_API_KEY`. + +This guide works for any cluster whose OIDC discovery document and signing keys are reachable from the public internet. Managed services such as EKS publish them for you. For a private cluster, see [Private clusters](#private-clusters). + +## Before you start + +- You're an organization admin in KERNEL. +- You can deploy pods and create service accounts in the cluster. +- Your workload uses the TypeScript, Python, or Go SDK. + +## Find the cluster's issuer + +```bash +kubectl get --raw /.well-known/openid-configuration +``` + +The `issuer` field is the URL to register, such as `https://oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B716D3041E`. Each cluster has its own. + +## Configure KERNEL + + + +In the [dashboard](https://dashboard.onkernel.com), open **Keys** > **Workload identity**, click **Connect workload**, and select the **Kubernetes** tile. + +- Paste the issuer into **Cluster issuer URL**. +- Check the box confirming the cluster's discovery document and JWKS are reachable from the public internet. +- Click **Apply and continue**. + +Register one issuer per cluster. + + + +Under **Match conditions**, enter the **Namespace** and the Kubernetes **Service account** your pods run as, such as `ci` and `browser-runner`. The rule accepts tokens whose subject is exactly `system:serviceaccount:ci:browser-runner`. + +Under **Authorization**, choose the **Project**, the **Permissions**, and the **Token lifetime**. + + + +Choose or create a KERNEL service account, click **Create rule**, then turn on the issuer and the rule in the **Test** step. Copy the rule ID (`wifr_...`). + + + +## Configure your pod + +Mount a [projected service account token](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#serviceaccount-token-volume-projection) with the audience `https://auth.onkernel.com`, and point the SDK at it: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: browser-runner + namespace: ci +spec: + replicas: 1 + selector: + matchLabels: + app: browser-runner + template: + metadata: + labels: + app: browser-runner + spec: + serviceAccountName: browser-runner + containers: + - name: app + image: ghcr.io/acme/browser-runner:1.8.2 + env: + - name: KERNEL_FEDERATION_RULE_ID + value: wifr_x9c4v7b2n5m8q1z3k6j0h4ea + - name: KERNEL_IDENTITY_TOKEN_FILE + value: /var/run/secrets/kernel/token + volumeMounts: + - name: kernel-token + mountPath: /var/run/secrets/kernel + readOnly: true + volumes: + - name: kernel-token + projected: + sources: + - serviceAccountToken: + path: token + audience: https://auth.onkernel.com + expirationSeconds: 3600 +``` + + +Don't use the token Kubernetes mounts by default at `/var/run/secrets/kubernetes.io/serviceaccount/token`. Its audience is your cluster's API server, so KERNEL refuses it. The projected volume above issues a separate token for KERNEL only. + + +Your code constructs the client with no arguments: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; + +const kernel = new Kernel(); + +const browser = await kernel.browsers.create(); +console.log(browser.session_id); +``` + +```python Python +from kernel import Kernel + +client = Kernel() + +browser = client.browsers.create() +print(browser.session_id) +``` + +```go Go +package main + +import ( + "context" + "fmt" + + "github.com/kernel/kernel-go-sdk" +) + +func main() { + ctx := context.Background() + client := kernel.NewClient() + + browser, err := client.Browsers.New(ctx, kernel.BrowserNewParams{}) + if err != nil { + panic(err) + } + fmt.Println(browser.SessionID) +} +``` + + +## What the SDK does + +The SDK reads the token file again for every exchange, so it picks up the token the kubelet rotates. It then exchanges the token at `https://auth.onkernel.com/token`. An empty or missing file is an error that names the path. + +To configure the file in code instead of `KERNEL_IDENTITY_TOKEN_FILE`: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; +import { identityTokenFromFile, oidcFederationProvider } from '@onkernel/sdk/lib/credentials'; + +const kernel = new Kernel({ + credentials: oidcFederationProvider({ + federationRuleId: 'wifr_x9c4v7b2n5m8q1z3k6j0h4ea', + identityTokenProvider: identityTokenFromFile('/var/run/secrets/kernel/token'), + }), +}); +``` + +```python Python +from kernel import IdentityTokenFile, Kernel, WorkloadIdentityCredentials + +client = Kernel( + credentials=WorkloadIdentityCredentials( + identity_token_provider=IdentityTokenFile("/var/run/secrets/kernel/token"), + federation_rule_id="wifr_x9c4v7b2n5m8q1z3k6j0h4ea", + ) +) +``` + +```go Go +package main + +import ( + "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/option" +) + +func main() { + client := kernel.NewClient( + option.WithFederationTokenProvider( + option.IdentityTokenFile("/var/run/secrets/kernel/token"), + option.FederationOptions{FederationRuleID: "wifr_x9c4v7b2n5m8q1z3k6j0h4ea"}, + ), + ) + _ = client +} +``` + + +## What the token looks like + +```json +{ + "iss": "https://oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B716D3041E", + "aud": ["https://auth.onkernel.com"], + "sub": "system:serviceaccount:ci:browser-runner", + "jti": "0d9c8b7a-6f5e-4d3c-2b1a-0f9e8d7c6b5a", + "iat": 1780000000, + "exp": 1780003600, + "kubernetes.io": { + "namespace": "ci", + "serviceaccount": { "name": "browser-runner", "uid": "a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d" } + } +} +``` + +Three details to make note of: + +- **The audience must be exactly one value.** A token projected with more than one audience is refused. +- **A pod rereads the same token.** The kubelet replaces a projected token only as it nears expiry, so between rotations every exchange presents the same one. A Kubernetes issuer allows that reuse by default. +- **Token lifetime is capped at one hour by default.** KERNEL refuses a token whose lifetime, `exp` minus `iat`, is over the issuer's maximum of 3,600 seconds. Keep `expirationSeconds` at `3600` or less, or raise **Maximum token lifetime (hours)** on the issuer. + +### Require single use + +If every exchange fetches a new token, for example a job that runs `kubectl create token` each time, you can make the issuer single-use. On the **Issuers** tab, select **Edit** on the issuer and turn on **Enforce single-use tokens (JTI replay protection)**. + +Don't turn this on for pods that read a projected token file. The second exchange with the same file contents is refused. + +## Private clusters + +KERNEL fetches signing keys only from public internet addresses. If your cluster's discovery endpoint is private, upload its public keys instead: + +1. Export the keys: + + ```bash + kubectl get --raw /openid/v1/jwks + ``` + +2. On the **Issuers** tab, click **Register issuer**. +3. Enter the cluster's issuer URL in **Issuer URL (iss claim)**. +4. Set **JWKS source** to **Inline keys** and paste the key set into **Public keys**. +5. Turn off **Enforce single-use tokens (JTI replay protection)**, because pods reread their token. + +An issuer registered this way is a [custom OIDC](/info/workload-identity/custom-oidc) issuer. Its rules match on **Subject pattern**: enter `system:serviceaccount:ci:browser-runner`. + +Update the inline keys whenever the cluster rotates its signing keys. KERNEL can't fetch new ones for you. + +## Next steps + +- [Reference](/info/workload-identity/reference#kubernetes): Kubernetes match fields +- [Troubleshooting](/info/workload-identity/troubleshooting): what a refused exchange means +- [Move a workload from an API key](/info/workload-identity/migrate-from-api-keys) diff --git a/info/workload-identity/microsoft-entra.mdx b/info/workload-identity/microsoft-entra.mdx new file mode 100644 index 00000000..450dbff9 --- /dev/null +++ b/info/workload-identity/microsoft-entra.mdx @@ -0,0 +1,191 @@ +--- +title: "Microsoft Entra" +description: "Authenticate Azure workloads to KERNEL with tokens from a managed identity or an app registration in your Entra tenant" +--- + +A workload on Azure can get a token from Microsoft Entra ID through a managed identity or an app registration. With [workload identity federation](/info/workload-identity/overview), your workload exchanges that token for a KERNEL access token, so there's no `KERNEL_API_KEY` in Key Vault or your app settings. + +Entra differs from the other providers in one way: the token's audience is an app registration in **your** tenant, not `https://auth.onkernel.com`. You create that app registration once, and your workloads request tokens for it. + +## Before you start + +- You're an organization admin in KERNEL. +- You can create app registrations in your Entra tenant. +- Your workload has a managed identity, or a service principal with its own credentials. + +## Configure Entra + + + +In the Azure portal, create an app registration that stands for KERNEL in your tenant, and give it an Application ID URI of `api://`. Note its **Application (client) ID** and your **Directory (tenant) ID**. + + + +Entra issues v1.0 or v2.0 tokens, and the two have different issuers and audiences: + +| | v1.0 | v2.0 | +| --- | --- | --- | +| Issuer | `https://sts.windows.net//` | `https://login.microsoftonline.com//v2.0` | +| Audience | `api://` | The bare client ID | + +Tokens are v1.0 unless the app registration sets `requestedAccessTokenVersion` to `2`. Managed identity tokens default to v1.0. + + + +Note the **Object (principal) ID** of the managed identity or service principal your workload runs as. The rule pins this ID. + + + +## Configure KERNEL + + + +In the [dashboard](https://dashboard.onkernel.com), open **Keys** > **Workload identity**, click **Connect workload**, and select the **Microsoft Entra** tile. + +- Enter your **Directory (tenant) ID**. +- Under **Token issuer**, select **v1 (sts.windows.net)** or **v2.0 (login.microsoftonline.com)** to match your tokens. +- Click **Apply and continue**. + + + +Under **Match conditions**: + +| Field | What to enter | +| --- | --- | +| **Object (principal) ID** | The managed identity or service principal that requests the token. | +| **Application (client) ID** | The app registration the token is issued for. KERNEL derives the expected audience from it: `api://` for a v1 issuer, the bare client ID for a v2.0 issuer. | + +Under **Authorization**, choose the **Project**, the **Permissions**, and the **Token lifetime**. + + + +Choose or create a service account, click **Create rule**, then turn on the issuer and the rule in the **Test** step. Copy the rule ID (`wifr_...`). + + + +Entra tokens are single-use in KERNEL by default. The Azure Identity libraries and managed identity endpoints cache a token and return the same one until it nears expiry, so a second exchange with it is refused. + +If your workload gets its token that way, open the **Issuers** tab, select **Edit** on the issuer, and turn off **Enforce single-use tokens (JTI replay protection)**. The token can then be exchanged until it expires. + + + +## Configure your workload + +The SDKs have no built-in Entra source, because the audience is yours. Pass a callback that returns a token for your app registration. These examples use the Azure Identity library and a v1.0 audience: + + +```typescript TypeScript +import { DefaultAzureCredential } from '@azure/identity'; +import Kernel from '@onkernel/sdk'; +import { oidcFederationProvider } from '@onkernel/sdk/lib/credentials'; + +const azure = new DefaultAzureCredential(); + +const kernel = new Kernel({ + credentials: oidcFederationProvider({ + federationRuleId: 'wifr_q5z1x8c3v6b9n2m4k7j0h3ga', + identityTokenProvider: async () => + (await azure.getToken('api://4f6c1a52-9d0e-4b7a-8c3d-2e5f7a9b1c0d/.default')).token, + }), +}); + +const browser = await kernel.browsers.create(); +console.log(browser.session_id); +``` + +```python Python +from azure.identity import DefaultAzureCredential +from kernel import Kernel, WorkloadIdentityCredentials + +azure = DefaultAzureCredential() + + +def entra_token() -> str: + return azure.get_token("api://4f6c1a52-9d0e-4b7a-8c3d-2e5f7a9b1c0d/.default").token + + +client = Kernel( + credentials=WorkloadIdentityCredentials( + identity_token_provider=entra_token, + federation_rule_id="wifr_q5z1x8c3v6b9n2m4k7j0h3ga", + ) +) + +browser = client.browsers.create() +print(browser.session_id) +``` + +```go Go +package main + +import ( + "context" + "fmt" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/option" +) + +func main() { + ctx := context.Background() + + azure, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + panic(err) + } + entraToken := func(ctx context.Context) (string, error) { + token, err := azure.GetToken(ctx, policy.TokenRequestOptions{ + Scopes: []string{"api://4f6c1a52-9d0e-4b7a-8c3d-2e5f7a9b1c0d/.default"}, + }) + if err != nil { + return "", err + } + return token.Token, nil + } + + client := kernel.NewClient( + option.WithFederationTokenProvider(entraToken, option.FederationOptions{ + FederationRuleID: "wifr_q5z1x8c3v6b9n2m4k7j0h3ga", + }), + ) + + browser, err := client.Browsers.New(ctx, kernel.BrowserNewParams{}) + if err != nil { + panic(err) + } + fmt.Println(browser.SessionID) +} +``` + + +For a v2.0 audience, request the scope `/.default` instead. + +## What KERNEL accepts + +An Entra rule accepts only an application's own token: + +- **A token with delegated scopes is refused.** If the token carries an `scp` claim, it was issued to a signed-in user, and it never matches. +- **The tenant is pinned.** KERNEL adds the issuer's tenant ID to the rule's conditions, so a token from another tenant doesn't match. +- **Pin the object ID where you can.** A rule that names the object ID (`oid`) needs no extra Entra configuration. +- **A rule keyed only on a client ID needs `idtyp`.** If you create a rule through the API that names only `appid` or `azp`, KERNEL also requires the token's `idtyp` claim to be `app`. Entra doesn't emit `idtyp` unless you add it as an optional claim on the audience app registration: + + ```bash + az ad app update --id 4f6c1a52-9d0e-4b7a-8c3d-2e5f7a9b1c0d \ + --optional-claims '{"accessToken":[{"name":"idtyp"}]}' + ``` + + Until you do, that rule rejects every token. + +Two more details: + +- **Entra's token ID is `uti`.** KERNEL uses it, not `jti`, for single-use checks. +- **Switching between v1.0 and v2.0 changes both `iss` and `aud`.** If you change the app registration's token version, change the issuer and the rule's expected audience together. +- **Long-lived tokens need a higher limit.** By default, KERNEL accepts an Entra token only if its lifetime, `exp` minus `iat`, is 7,500 seconds or less. If your tokens live longer, raise **Maximum token lifetime (hours)** on the issuer, up to 24 hours. + +## Next steps + +- [Reference](/info/workload-identity/reference#microsoft-entra): Microsoft Entra match fields +- [Troubleshooting](/info/workload-identity/troubleshooting): what a refused exchange means +- [Move a workload from an API key](/info/workload-identity/migrate-from-api-keys) diff --git a/info/workload-identity/migrate-from-api-keys.mdx b/info/workload-identity/migrate-from-api-keys.mdx new file mode 100644 index 00000000..9d590a66 --- /dev/null +++ b/info/workload-identity/migrate-from-api-keys.mdx @@ -0,0 +1,147 @@ +--- +title: "Move a Workload from an API Key" +sidebarTitle: "Migrate from API Keys" +description: "Switch an existing workload from a stored KERNEL_API_KEY to workload identity federation without downtime" +--- + +You can move a workload from an API key to [workload identity federation](/info/workload-identity/overview) without a gap. Set up federation next to the key, switch the workload over, confirm it, and only then delete the key. + +Move one workload at a time. Each workload gets its own rule, so a mistake in one doesn't touch the others. + +## Before you start + +- You're an organization admin in KERNEL. +- The workload runs somewhere with an identity provider: GitHub Actions, AWS, Google Cloud, Microsoft Entra, Kubernetes, or another OIDC issuer. If it doesn't, see [If the workload can't federate](#if-the-workload-cant-federate). +- The workload uses a KERNEL SDK release with federation support. Upgrade `@onkernel/sdk`, the `kernel` Python package, or `github.com/kernel/kernel-go-sdk` to the latest version first. + +## Migrate + + + +Open **Keys** > **API keys** in the [dashboard](https://dashboard.onkernel.com) and find the key the workload uses. Note two things: + +- **Its project.** A federation rule covers one project. If the key is org-wide, work out which project the workload really uses. A workload that uses two projects needs two rules. +- **What it calls.** An unrestricted key can do anything, but your workload does a few things. List them, such as creating, using, and deleting browsers, so you can grant only those. Your [audit logs](/info/audit-logs) record every authenticated request, and you can filter them to API key authentication. + +Check that the workload doesn't depend on something [closed to service accounts](/info/workload-identity/service-accounts#what-a-service-account-cant-do): acquiring browsers from a pool, app deployments and invocations, or managing API keys. + + + +Click **Connect workload** and follow the guide for your provider: + +- [GitHub Actions](/info/workload-identity/github-actions) +- [AWS](/info/workload-identity/aws) +- [Google Cloud](/info/workload-identity/google-cloud) +- [Microsoft Entra](/info/workload-identity/microsoft-entra) +- [Kubernetes](/info/workload-identity/kubernetes) +- [Custom OIDC](/info/workload-identity/custom-oidc) + +Choose the project and permissions you noted. Enable the issuer and the rule. Leave the API key in place: nothing has changed for the workload yet. + + + +Set `KERNEL_FEDERATION_RULE_ID` and, where your provider needs it, the identity token source. Deploy the change. + +The workload still uses the API key. `KERNEL_API_KEY` wins over the federation variables, and the SDK logs one warning that both are set. That warning tells you the new settings reached the workload. + + + +Stop supplying `KERNEL_API_KEY` to this workload: delete it from the workflow's `env`, the task definition, the pod spec, or the service's settings. Don't set it to an empty string in a place where another layer could still fill it in. Deploy the change. + +If your code passes the key explicitly, remove that too: + + +```typescript TypeScript +// Before +const kernel = new Kernel({ apiKey: process.env.KERNEL_API_KEY }); + +// After +const kernel = new Kernel(); +``` + +```python Python +# Before +client = Kernel(api_key=os.environ["KERNEL_API_KEY"]) + +# After +client = Kernel() +``` + +```go Go +// Before +client := kernel.NewClient(option.WithAPIKey(os.Getenv("KERNEL_API_KEY"))) + +// After +client := kernel.NewClient() +``` + + + + +Check from both sides: + +- **In the dashboard.** The **Authentication events** tab shows a `success` event for your rule, and the rule's **Last exchange** time is current. +- **In the workload.** Ask the API who it sees: + + +```typescript TypeScript +const context = await kernel.auth.context.retrieve(); +console.log(context.principal.type); // 'service_account' +console.log(context.workload_identity?.federation_rule_id); +``` + +```python Python +context = client.auth.context.retrieve() +print(context.principal.type) # service_account +print(context.workload_identity.federation_rule_id if context.workload_identity else None) +``` + +```go Go +authContext, err := client.Auth.Context.Get(ctx) +if err != nil { + panic(err) +} +fmt.Println(authContext.Principal.Type) // service_account +fmt.Println(authContext.WorkloadIdentity.FederationRuleID) +``` + + +If a request fails with `403` and `insufficient_scope`, the rule's policy is missing a permission the workload uses. The message names the action and resource. Add it to the rule and try again. + + + +Once the workload has run on federation through a full cycle, delete the old key on the **API keys** page, and remove the stored copy from your CI secrets or secret manager. + +Check the key's **Last used** time first. If it's still moving, something else uses the key. Find that consumer before you delete it. + + +Deleting an API key ends the browsers associated with that key and discards their unsaved profile changes. Delete it when none of its browsers are doing work you need. + + + + +## Roll back + +Until you delete the key, rolling back is one change: supply `KERNEL_API_KEY` to the workload again. The SDK uses it ahead of federation. + +To stop the federated path without touching the workload, disable the rule on the **Rules** tab. + +## If the workload can't federate + +A workload with no identity provider still benefits from leaving a personal key behind. Replace it with a [service account API key](/info/workload-identity/service-accounts#service-account-api-keys): + +- It belongs to your organization, so it keeps working when the person who created it leaves. +- It's limited to one project and an explicit policy. +- Give it an expiry and rotate it on a schedule. + +Move that workload to federation when its platform gains an identity provider. + +## Common problems + +| Symptom | Cause | Fix | +| --- | --- | --- | +| The workload still authenticates with the API key. | `KERNEL_API_KEY` is still in its environment. | Remove it everywhere the workload gets its environment, including inherited CI variables and shared config. | +| The client fails with a missing-credentials error. | `KERNEL_FEDERATION_RULE_ID` is set but the SDK found no identity token source. | Set `KERNEL_IDENTITY_TOKEN_SOURCE` or `KERNEL_IDENTITY_TOKEN_FILE`. In GitHub Actions, add `id-token: write`. | +| The exchange fails with `invalid_grant`. | The token doesn't satisfy the rule, or the issuer or rule isn't enabled. | See [Troubleshooting](/info/workload-identity/troubleshooting). | +| Requests fail with `403` after the switch. | The rule grants less than the old key did. | Add the missing action to the rule's policy. | +| Requests to another project fail. | A rule covers one project. | Create a second rule for the other project. | diff --git a/info/workload-identity/overview.mdx b/info/workload-identity/overview.mdx new file mode 100644 index 00000000..99dbc235 --- /dev/null +++ b/info/workload-identity/overview.mdx @@ -0,0 +1,357 @@ +--- +title: "Workload Identity Federation" +sidebarTitle: "Overview" +description: "Authenticate CI jobs, cloud services, and Kubernetes pods to KERNEL with short-lived tokens from your own identity provider instead of stored API keys" +--- + +Workload identity federation lets a workload authenticate to KERNEL without an API key. The workload presents a short-lived OpenID Connect (OIDC) token from an identity provider it already has: GitHub Actions, AWS, Google Cloud, Microsoft Entra, Kubernetes, or any OIDC issuer. KERNEL checks the token against rules you configure and returns a KERNEL access token that expires in five minutes. + +Use it for every workload that isn't a person at a keyboard. A few operations, such as acquiring a browser from a pool and running app deployments, [stay closed to service accounts](/info/workload-identity/service-accounts#what-a-service-account-cant-do), so check them before you plan a migration. A stored API key works until someone revokes it, so one leaked CI variable is standing access to your browsers, profiles, and credentials. With federation: + +- **There's no secret to leak.** Nothing is stored in CI variables, config files, or secret managers. The federation rule ID your workload sends is an identifier, not a credential. +- **Tokens expire in minutes.** An access token lasts 300 seconds by default and 600 at most. The SDKs exchange a fresh one before it expires. +- **Access is tied to one workload.** A rule names exactly who can authenticate, such as one repository, workflow, and branch, or one IAM role. A token from anywhere else is refused. +- **Access is narrow by construction.** Every rule is limited to one project and an explicit list of permissions. + + +Federation is as strong as the identity provider that signs the tokens. Write rules as specific as your workload allows, and keep using the controls your provider gives you, such as protected branches and deployment environments. + + +API keys still have a place for local development and for environments with no identity provider. See [API authentication](/info/authentication) for how to choose. + +## Concepts + +An organization admin sets up three resources. Together they say: tokens signed by this **issuer**, that match this **rule**, can act as this **service account**. + +### Service accounts + +A **service account** (`svc_...`) is a named, non-human identity that your organization owns. It's what a workload acts as: browsers the workload creates are recorded as created by the service account, and it shows when it was last used. + +A service account has only a name and a description. It has no permissions of its own. Each federation rule that targets it sets the project and permissions for the tokens that rule issues. See [Service accounts](/info/workload-identity/service-accounts). + +### Issuers + +An **issuer** (`wii_...`) registers an identity provider with your organization. It tells KERNEL which `iss` claim to expect and where to get the provider's public signing keys. + +Each issuer has a provider type: `github_actions`, `aws`, `google_cloud`, `microsoft_entra`, `kubernetes`, or `custom_oidc`. The type decides which identity checks a rule on that issuer must make. Registering an issuer accepts no token by itself. Only a rule does that. + +### Federation rules + +A **federation rule** (`wifr_...`) decides which tokens from an issuer are accepted and what they can do. A rule has: + +- **Match conditions.** What the token must say about the workload. Each provider type has its own required conditions. A GitHub Actions rule, for example, names a repository by its numeric ID, a workflow, and a branch or environment. +- **Expected audience.** The `aud` claim the token must carry. The SDKs request `https://auth.onkernel.com`. +- **Target.** The service account the workload acts as. +- **Authorization.** One project, a permission policy inside that project, and the access token lifetime. + +A rule covers exactly one project. To give a workload access to two projects, such as staging and production, create two rules. An issuer can have as many rules as you need. + +Issuers and rules are created disabled. Nothing is trusted until you enable the issuer and then the rule. + +## How it works + +```mermaid +sequenceDiagram + participant W as Your workload + participant I as Identity provider + participant K as auth.onkernel.com + participant A as api.onkernel.com + W->>I: Request an identity token for audience https://auth.onkernel.com + I-->>W: Signed, short-lived token + W->>K: POST /token with the token and a federation rule ID + K->>K: Verify signature, issuer, audience, expiry, and replay + K->>K: Check the token against that rule + K-->>W: Access token (300 seconds by default) + W->>A: API requests with the access token + A->>A: Recheck that the issuer, rule, and service account are still active +``` + +1. **Your identity provider issues a token to the workload.** Most platforms hand it over without any setup in your code: the GitHub Actions runner, the AWS Security Token Service, the Google Cloud metadata server, or a file Kubernetes mounts into the pod. +2. **The SDK exchanges it for a KERNEL access token.** It sends the token and your federation rule ID to `POST https://auth.onkernel.com/token`. The request needs no KERNEL credential. The rule ID only selects which rule to check; the token must still satisfy it. +3. **The SDK calls the API with the access token** and exchanges a fresh identity token before the access token expires. There's no refresh token. + +## Set up federation in the dashboard + +You need to be an organization admin. Members can view service accounts, issuers, rules, and authentication events, but can't change them. + + + +In the [dashboard](https://dashboard.onkernel.com), open **Keys** in the sidebar, select **Workload identity**, and click **Connect workload**. + +You also get here from **API keys**: clicking **Create API Key** offers **Set up identity federation** before it issues a key. + + + +Select **Connect a new provider** and pick a tile: **GitHub Actions**, **AWS**, **Google Cloud**, **Microsoft Entra**, **Kubernetes**, or **Custom OIDC**. Fill in what the provider needs, such as your AWS issuer URL or your Entra tenant ID, then click **Apply and continue**. + +If your organization already trusts the provider, select **Use a registered issuer** and pick it from the list. + + + +Enter a **Rule name**, then fill in **Match conditions** for your provider. Under **Authorization**, choose the **Project**, the **Permissions** the workload needs in that project, and the **Token lifetime**. + +Grant only what the workload uses. A job that runs browsers needs `browsers:create`, `browsers:use`, and `browsers:delete`. See [Scoping permissions](/info/api-key-permissions) for every action. Federation rules use the same policy format as scoped API keys. + + + +Select **Use an existing account**, or **Create a service account** and give it a name such as `browser-ci`. Check the **Review** summary and click **Create rule**. The rule is created disabled. + + + +The last step walks you through four checks: + +1. **Check the issuer's signing keys.** Click **Check keys** to confirm KERNEL can fetch the provider's public keys. This grants no access. +2. **Enable.** Turn on the issuer, then the rule. +3. **Configure your workload.** Copy the rule ID (`wifr_...`) and set it as `KERNEL_FEDERATION_RULE_ID` where your workload runs. The provider guides below show the rest. +4. **Watch for the first exchange.** Run your workload. The wizard shows the exchange as soon as KERNEL issues a token. + +Click **Done**. If you close the wizard early, the issuer and rule stay saved and disabled. Enable them later from the **Issuers** and **Rules** tabs. + + + +## Authenticate from your workload + +With `KERNEL_FEDERATION_RULE_ID` set and no `KERNEL_API_KEY`, the SDKs find the identity token, exchange it, and refresh the access token for you. Your application code doesn't change: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; + +// Reads KERNEL_FEDERATION_RULE_ID and the identity token source from the environment. +const kernel = new Kernel(); + +const browser = await kernel.browsers.create(); +console.log(browser.session_id); +``` + +```python Python +from kernel import Kernel + +# Reads KERNEL_FEDERATION_RULE_ID and the identity token source from the environment. +client = Kernel() + +browser = client.browsers.create() +print(browser.session_id) +``` + +```go Go +package main + +import ( + "context" + "fmt" + + "github.com/kernel/kernel-go-sdk" +) + +func main() { + ctx := context.Background() + + // Reads KERNEL_FEDERATION_RULE_ID and the identity token source from the environment. + client := kernel.NewClient() + + browser, err := client.Browsers.New(ctx, kernel.BrowserNewParams{}) + if err != nil { + panic(err) + } + fmt.Println(browser.SessionID) +} +``` + + +The SDK needs to know where the identity token comes from. Set `KERNEL_IDENTITY_TOKEN_SOURCE`, or let the SDK detect it: + +| Where your workload runs | What to set | +| --- | --- | +| GitHub Actions | Nothing else. The SDK detects the runner when the job has `id-token: write`. | +| AWS | `KERNEL_IDENTITY_TOKEN_SOURCE=aws_sts` | +| Google Cloud | `KERNEL_IDENTITY_TOKEN_SOURCE=gcp_metadata` | +| Kubernetes, or anything that writes a token to a file | `KERNEL_IDENTITY_TOKEN_FILE=/var/run/secrets/kernel/token` | +| Azure, with Microsoft Entra | An identity token callback in code. See [Microsoft Entra](/info/workload-identity/microsoft-entra). | +| Anywhere else | An identity token callback in code. See [Custom OIDC](/info/workload-identity/custom-oidc). | + +### Configure it in code + +Every setting has a code equivalent. This client reads its identity token from a file and names its rule explicitly: + + +```typescript TypeScript +import Kernel from '@onkernel/sdk'; +import { identityTokenFromFile, oidcFederationProvider } from '@onkernel/sdk/lib/credentials'; + +const kernel = new Kernel({ + credentials: oidcFederationProvider({ + federationRuleId: 'wifr_tz4a98xxat96iws9zmbrgj3a', + identityTokenProvider: identityTokenFromFile('/var/run/secrets/kernel/token'), + }), +}); +``` + +```python Python +from kernel import IdentityTokenFile, Kernel, WorkloadIdentityCredentials + +client = Kernel( + credentials=WorkloadIdentityCredentials( + identity_token_provider=IdentityTokenFile("/var/run/secrets/kernel/token"), + federation_rule_id="wifr_tz4a98xxat96iws9zmbrgj3a", + ) +) +``` + +```go Go +package main + +import ( + "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/option" +) + +func main() { + client := kernel.NewClient( + option.WithFederationTokenProvider( + option.IdentityTokenFile("/var/run/secrets/kernel/token"), + option.FederationOptions{FederationRuleID: "wifr_tz4a98xxat96iws9zmbrgj3a"}, + ), + ) + _ = client +} +``` + + +### Exchange a token without an SDK + +In a language with no KERNEL SDK, make the exchange yourself. It's one unauthenticated form post: + +```bash +ACCESS_TOKEN=$(curl -sS https://auth.onkernel.com/token \ + -d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \ + -d federation_rule_id=wifr_tz4a98xxat96iws9zmbrgj3a \ + -d resource=https://api.onkernel.com \ + --data-urlencode "assertion=$IDENTITY_TOKEN" | jq -r .access_token) + +curl https://api.onkernel.com/browsers \ + -H "Authorization: Bearer $ACCESS_TOKEN" +``` + +Exchange a fresh identity token whenever you need a new access token. See [Token exchange](/info/workload-identity/reference#token-exchange) for every field. + +## Credential precedence + + +`KERNEL_API_KEY` wins over the federation variables. If both are set, the SDK uses the API key and logs one warning. When you move a workload to federation, remove `KERNEL_API_KEY` from everywhere that workload gets its environment. + + +The SDKs resolve a credential in this order: + +1. An API key or federation credentials passed in code. +2. `KERNEL_API_KEY`. +3. `KERNEL_FEDERATION_RULE_ID` with an identity token source. + +See [SDK configuration](/info/workload-identity/reference#sdk-configuration) for how each SDK behaves when both are passed in code. + +## Token lifetime and refresh + +An access token lasts for the rule's **Token lifetime**: 300 seconds by default, 600 at most. It never outlives the identity token it came from, so a provider token with two minutes left yields an access token of two minutes or less. + +The SDKs cache the access token and renew it on two thresholds: + +- **Background refresh** when less than 120 seconds, or 40% of the token's lifetime if that's shorter, remains. Requests keep using the cached token while the new exchange runs. +- **Blocking refresh** when less than 30 seconds, or 10% of the lifetime, remains. Requests wait for the new token, and fail if the exchange fails. + +If the API answers a request with `401`, the SDK drops the token, exchanges a fresh identity token, and retries the request once. + +Every exchange needs an identity token from your provider. Most providers' tokens can be exchanged only once: + +| Provider type | Can an identity token be exchanged more than once? | +| --- | --- | +| GitHub Actions | No. | +| AWS | No. | +| Google Cloud | Yes, until the token expires. Google identity tokens carry no token ID. | +| Kubernetes | Yes by default, because a pod reads the same projected token until the kubelet rotates it. You can require single use. | +| Microsoft Entra | No by default. You can allow reuse. | +| Custom OIDC | No by default. You can allow reuse. | + +The built-in SDK sources request a new identity token for every exchange, so you don't manage this yourself. It matters when you supply tokens through a file or a callback: the source must return a fresh token each time. + +## What a workload can do + +A federated credential can do what its rule's policy grants, inside the rule's one project. Three things stay closed to service accounts whatever the policy says: acquiring a browser from a pool, using app deployments and invocations, and managing API keys. See [what a service account can't do](/info/workload-identity/service-accounts#what-a-service-account-cant-do). + +A workload can inspect its own identity and permissions: + + +```typescript TypeScript +const context = await kernel.auth.context.retrieve(); + +console.log(context.principal); // { type: 'service_account', id: 'svc_p2m5k8w1q9z4c7x3v6b0n2ha' } +console.log(context.authorization.effective_policy); +``` + +```python Python +context = client.auth.context.retrieve() + +print(context.principal.type, context.principal.id) # service_account svc_p2m5k8w1q9z4c7x3v6b0n2ha +print(context.authorization.effective_policy) +``` + +```go Go +authContext, err := client.Auth.Context.Get(ctx) +if err != nil { + panic(err) +} +fmt.Println(authContext.RawJSON()) +``` + + +## Turn access off + +Disable or archive any link in the chain to stop a workload: the rule, the issuer, or the service account. New exchanges are refused at once, and tokens already issued stop working within about 10 seconds. + +- **Disable** when you may turn it back on. In the dashboard, open the row's menu on the **Issuers** or **Rules** tab and select **Disable**. +- **Archive** when the workload is gone for good. Archiving can't be undone. Registering the same name or issuer URL again creates a new resource with a new ID. + +Disabling a rule stops that rule only. Disabling an issuer stops every rule on it. + + +Stopping a workload doesn't delete the browsers it created. Delete those browsers yourself when you end the workload. + + +## See what happened + +- **Authentication events.** The **Authentication events** tab lists each token KERNEL issued, with its issuer, rule, service account, and project. It also lists exchanges refused after the token was verified, such as a replayed token. Events are kept for 30 days. +- **Last exchange.** Each rule shows when it last issued a token. +- **Last used.** Each service account shows when one of its rules last issued a token or one of its API keys last authenticated. + +An exchange that fails before KERNEL can tie it to your organization, such as a token with a bad signature or the wrong audience, isn't recorded. See [Troubleshooting](/info/workload-identity/troubleshooting). + +## Provider guides + +Each guide covers where the identity token comes from, what its claims look like, and what to enter in the dashboard. + + + + CI without a `KERNEL_API_KEY` repository secret. + + + ECS, Lambda, and EC2 with STS web identity tokens. + + + GKE, Cloud Run, and Compute Engine with identity tokens from the metadata server. + + + Managed identities and app registrations in your tenant. + + + Projected service account tokens from your cluster. + + + Any other issuer that signs OIDC tokens. + + + +## See also + +- [Service accounts](/info/workload-identity/service-accounts): what they are, what they can't do, and service account API keys +- [Move a workload from an API key](/info/workload-identity/migrate-from-api-keys): switch without downtime +- [Reference](/info/workload-identity/reference): the token exchange, SDK configuration, and every issuer and rule field +- [Troubleshooting](/info/workload-identity/troubleshooting): what a refused exchange means and how to fix it diff --git a/info/workload-identity/reference.mdx b/info/workload-identity/reference.mdx new file mode 100644 index 00000000..17d928e6 --- /dev/null +++ b/info/workload-identity/reference.mdx @@ -0,0 +1,520 @@ +--- +title: "Workload Identity Reference" +sidebarTitle: "Reference" +description: "The token exchange, SDK configuration, and every issuer, federation rule, and service account field" +--- + +This page is the reference for [workload identity federation](/info/workload-identity/overview). To set it up, start with the guide for your [provider](/info/workload-identity/overview#provider-guides). + +## Token exchange + +A workload gets a KERNEL access token by posting its identity token to the KERNEL authorization server. The SDKs make this request for you. + +### Request + +```bash +curl -sS https://auth.onkernel.com/token \ + -d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \ + -d federation_rule_id=wifr_tz4a98xxat96iws9zmbrgj3a \ + -d resource=https://api.onkernel.com \ + --data-urlencode "assertion=$IDENTITY_TOKEN" +``` + +`POST https://auth.onkernel.com/token` takes a form-encoded body and no credential. + +| Parameter | Required | Value | +| --- | --- | --- | +| `grant_type` | Yes | `urn:ietf:params:oauth:grant-type:jwt-bearer` | +| `assertion` | Yes | The identity token from your provider: a signed JWT of 16 KiB or less. | +| `federation_rule_id` | Yes | The rule to check the token against (`wifr_...`). It selects a rule and grants nothing by itself. | +| `resource` | No | The API the access token is for. It must equal the rule's token audience exactly: `https://api.onkernel.com`, with no trailing slash. | + +The endpoint is strict about what it accepts: + +- Any other parameter, including `client_id` and `client_secret`, is rejected. +- A parameter sent twice is rejected. +- A request with an `Authorization` header is rejected. The identity token is the only proof. + +### Response + +```json +{ + "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6...", + "token_type": "Bearer", + "expires_in": 298, + "scope": "browsers:create browsers:use browsers:delete", + "org_id": "org_8f3k9m2q", + "access_scope": "project", + "project_id": "proj_staging_9f3k", + "principal": { "type": "service_account", "id": "svc_p2m5k8w1q9z4c7x3v6b0n2ha" }, + "federation_rule_id": "wifr_tz4a98xxat96iws9zmbrgj3a" +} +``` + +| Field | Description | +| --- | --- | +| `access_token` | Send it as `Authorization: Bearer ` on API requests. | +| `token_type` | Always `Bearer`. | +| `expires_in` | Seconds until the access token expires. | +| `scope` | The actions the rule's policy grants, separated by spaces. | +| `org_id` | Your organization. | +| `access_scope` | `project`. A federated token is always bound to one project. | +| `project_id` | The rule's project. | +| `principal` | The service account the token acts as. | +| `federation_rule_id` | The rule that issued the token. | + +There's no refresh token. To get another access token, exchange a fresh identity token. + +### Access token lifetime + +The access token expires at the earliest of: + +- The rule's token lifetime (`max_token_ttl_seconds`): 300 seconds by default, 600 at most. +- The identity token's own expiry. + +### Errors + +Errors use the OAuth error format, with an `error` code and an `error_description`. + +| Status | `error` | `error_description` | Meaning | +| --- | --- | --- | --- | +| `400` | `invalid_request` | `Missing required parameter: assertion` or `federation_rule_id` | A required parameter is missing. | +| `400` | `invalid_request` | `Unsupported workload identity parameter` | The body has a parameter the endpoint doesn't accept. | +| `400` | `invalid_request` | `Repeated workload identity parameter` | A parameter appears more than once. | +| `400` | `invalid_request` | `Workload assertion exchange does not accept client authentication` | The request has an `Authorization` header. | +| `400` | `invalid_target` | `Invalid resource parameter` | `resource` isn't the rule's token audience. Check for a trailing slash. | +| `400` | `invalid_grant` | `Credential is invalid, expired, or revoked` | The token didn't verify, didn't match the rule, or the rule, issuer, or service account isn't active. | +| `400` | `invalid_grant` | `Credential was already used` | The identity token was already exchanged, and its issuer is single-use. | +| `503` | `temporarily_unavailable` | Varies | KERNEL couldn't complete the exchange, for example because it couldn't fetch the issuer's signing keys. Retry with a fresh identity token. | + +The endpoint doesn't say why a token was refused, so that a caller can't probe your configuration. See [Troubleshooting](/info/workload-identity/troubleshooting) to find the reason. + +### Discovery + +A client can find everything it needs from the API host: + +1. `GET https://api.onkernel.com/.well-known/oauth-protected-resource` returns `resource`, the exact value to send as the `resource` parameter, and `authorization_servers`, which names the authorization server. +2. `GET https://auth.onkernel.com/.well-known/oauth-authorization-server` returns the `token_endpoint`, and lists `urn:ietf:params:oauth:grant-type:jwt-bearer` under `grant_types_supported`. + +## SDK configuration + +Federation support is in `@onkernel/sdk` for TypeScript, the `kernel` package for Python, and `github.com/kernel/kernel-go-sdk` for Go. The Go SDK needs Go 1.23 or later. + +### Environment variables + +| Variable | Description | +| --- | --- | +| `KERNEL_FEDERATION_RULE_ID` | The federation rule ID (`wifr_...`). Setting it turns federation on. | +| `KERNEL_IDENTITY_TOKEN_SOURCE` | Where identity tokens come from: `github_actions`, `gcp_metadata`, `aws_sts`, `file`, or `env`. | +| `KERNEL_IDENTITY_TOKEN_FILE` | Path of a file holding the identity token. The SDK reads it again for every exchange. | +| `KERNEL_IDENTITY_TOKEN` | A literal identity token. It can be exchanged once. | +| `KERNEL_IDENTITY_TOKEN_AUDIENCE` | The audience the built-in sources request. Defaults to the auth base URL, `https://auth.onkernel.com`. The rule's expected audience must be the same value. | +| `KERNEL_AUTH_BASE_URL` | The KERNEL authorization server. Defaults to `https://auth.onkernel.com` when the API base URL is the default. | +| `KERNEL_API_KEY` | An API key. When set, it's used instead of federation. | + +When `KERNEL_IDENTITY_TOKEN_SOURCE` isn't set, the SDK uses the first of these that applies: + +1. `KERNEL_IDENTITY_TOKEN_FILE` +2. `KERNEL_IDENTITY_TOKEN` +3. GitHub Actions, when the runner exposes `ACTIONS_ID_TOKEN_REQUEST_URL` + +AWS and Google Cloud are never detected. Set `KERNEL_IDENTITY_TOKEN_SOURCE` to `aws_sts` or `gcp_metadata`. + +### Credential precedence + +| Order | Source | +| --- | --- | +| 1 | An API key or federation credentials passed in code | +| 2 | `KERNEL_API_KEY` | +| 3 | `KERNEL_FEDERATION_RULE_ID` and an identity token source | + +When `KERNEL_API_KEY` and `KERNEL_FEDERATION_RULE_ID` are both set, the SDK uses the API key and logs one warning. + +The SDKs differ in two edge cases: + +| Case | TypeScript | Python | Go | +| --- | --- | --- | --- | +| Both an API key and federation credentials are passed in code | Throws | Raises `ValueError` | The last option wins | +| `KERNEL_FEDERATION_RULE_ID` is set but no identity token source is found | The constructor throws the missing-key error | The constructor raises `WorkloadIdentityError` | Requests fail with `WorkloadIdentityError` | + +### Identity token sources + +| `KERNEL_IDENTITY_TOKEN_SOURCE` | TypeScript | Python | Go | +| --- | --- | --- | --- | +| `github_actions` | `identityTokenFromGitHubActions()` | `GitHubActionsIdentityToken()` | `credentials.GitHubActions(audience)` | +| `gcp_metadata` | `identityTokenFromGCPMetadata()` | `GCPMetadataIdentityToken()` | `credentials.GCPMetadata(audience)` | +| `aws_sts` | `identityTokenFromAWSSTS()` | `AWSSTSIdentityToken()` | `awssts.IdentityToken(audience)` | +| `file` | `identityTokenFromFile(path)` | `IdentityTokenFile(path)` | `option.IdentityTokenFile(path)` | +| `env` | `identityTokenFromValue(token)` | `StaticIdentityToken(token)` | `credentials.Static(token)` | +| None: your own callback | A function that returns the token | A function that returns the token | An `option.IdentityTokenFunc` | + +Import the TypeScript names from `@onkernel/sdk/lib/credentials`, the Python names from `kernel`, and the Go names from `github.com/kernel/kernel-go-sdk/lib/credentials`, its `awssts` subpackage, and `github.com/kernel/kernel-go-sdk/option`. + +The built-in sources request a token for this audience: the source's own `audience` setting, then `KERNEL_IDENTITY_TOKEN_AUDIENCE`, then the auth base URL. + +### Federation options + +Pass these with the identity token source: to `oidcFederationProvider` in TypeScript, `WorkloadIdentityCredentials` in Python, and `option.FederationOptions` in Go. + +| TypeScript | Python | Go | Description | +| --- | --- | --- | --- | +| `federationRuleId` | `federation_rule_id` | `FederationRuleID` | The rule to authenticate against. Required. | +| `identityTokenProvider` | `identity_token_provider` | First argument of `option.WithFederationTokenProvider` | Returns a fresh identity token for each exchange. Required. | +| `resource` | `resource` | `Resource` | The API the token is for. Defaults to the origin of the client's base URL. | +| `authBaseURL` | `auth_base_url` | `AuthBaseURL` | The authorization server. Defaults to `KERNEL_AUTH_BASE_URL`, then `https://auth.onkernel.com`. | + +If you point the client at a base URL other than `https://api.onkernel.com`, you must also set the auth base URL. The SDK refuses to pair a custom API with the default authorization server. + +### Exchange a token once + +To manage the access token yourself, call the exchange directly. It makes one request, caches nothing, and needs no KERNEL credential: + + +```typescript TypeScript +import { exchangeFederationAssertion } from '@onkernel/sdk/lib/credentials'; + +const { accessToken, expiresAt, principal, projectId, scope } = await exchangeFederationAssertion({ + assertion: identityToken, + federationRuleId: 'wifr_tz4a98xxat96iws9zmbrgj3a', +}); +``` + +```python Python +from kernel import exchange_federation_assertion + +token = exchange_federation_assertion( + assertion=identity_token, + federation_rule_id="wifr_tz4a98xxat96iws9zmbrgj3a", + resource="https://api.onkernel.com", +) +print(token.token, token.expires_at, token.principal, token.project_id, token.scope) +``` + +```go Go +token, err := credentials.ExchangeFederationAssertion(ctx, credentials.FederationExchangeParams{ + Assertion: identityToken, + FederationRuleID: "wifr_tz4a98xxat96iws9zmbrgj3a", + Resource: "https://api.onkernel.com", +}) +if err != nil { + panic(err) +} +fmt.Println(token.AccessToken, token.ExpiresAt, token.Principal.ID, token.ProjectID, token.Scope) +``` + + +`expiresAt` and `expires_at` are Unix seconds. In Go, `ExpiresAt` is a `time.Time`. Python also has `async_exchange_federation_assertion`. + +The call spends the identity token. Don't call it again with the same token, even after a timeout. + +### Refresh and retries + +- The SDK caches the access token and shares it between copies of a client that use the same base URL. +- It refreshes in the background when less than 120 seconds, or 40% of the token's lifetime if that's shorter, remains. +- It blocks requests on a refresh when less than 30 seconds, or 10% of the lifetime, remains. +- Concurrent requests share one exchange. The identity token source is never called twice at once. +- A `401` from the API drops the cached token and retries the request once with a token from a fresh exchange. A second `401` is returned to you. A request whose body can't be sent again isn't retried. In Python, a client with `max_retries=0` doesn't retry a `401` at all. + +### Errors + +A failed exchange or a misconfiguration surfaces as a `WorkloadIdentityError`. + +| | TypeScript | Python | Go | +| --- | --- | --- | --- | +| Type | `WorkloadIdentityError` | `WorkloadIdentityError` | `*credentials.WorkloadIdentityError` | +| HTTP status | `statusCode` | `status_code` | `StatusCode` | +| OAuth error code | `errorCode` | `error` | `Code` | +| OAuth error description | `errorDescription` | `error_description` | `Description` | +| Request ID | `requestId` | `request_id` | `RequestID` | + +For a token that was already exchanged, the message adds advice that depends on where the token came from: a file that wasn't rotated, a static value, or a callback that returned the same token. + +### Safeguards + +The SDKs protect the identity token in transit: + +- The token endpoint must be `https`. Plain `http` is allowed only for `localhost`, `127.0.0.1`, and `::1`. +- An identity token over 16 KiB is refused before it's sent. +- Token requests don't follow redirects. +- Errors and logs never include the identity token or the access token. + +## Issuers + +An issuer (`wii_...`) registers one identity provider. + +| Field | Description | +| --- | --- | +| `name` | 1 to 128 letters, numbers, and hyphens, starting with a letter or number. | +| `description` | Up to 4,096 characters. | +| `issuer_url` | The exact `iss` value expected in tokens. An `https` URL with no query string. Optional for `github_actions` and `google_cloud`, which each have one fixed issuer. | +| `preset_type` | The provider type. See the next table. Defaults to the type the issuer URL belongs to, or `custom_oidc`. | +| `jwks` | Where the public signing keys come from. See [Key sources](#key-sources). | +| `token_validation.max_lifetime_seconds` | The longest lifetime, `exp` minus `iat`, an incoming token can have. 1 to 86,400. Defaults to 3,600, or 7,500 for `microsoft_entra`. | +| `token_validation.replay_protection` | `single_use` or `allow_reuse`. See the next table. | +| `enabled` | Defaults to `false`. Enabling an issuer checks that its keys can be fetched. | + +### Provider types + +| `preset_type` | Issuer URL | Replay protection | Signing algorithms | +| --- | --- | --- | --- | +| `github_actions` | `https://token.actions.githubusercontent.com` | Always `single_use` | `RS256` | +| `aws` | Your account's STS token issuer URL | Always `single_use` | Any supported | +| `google_cloud` | `https://accounts.google.com` | Always `allow_reuse` | `RS256` | +| `microsoft_entra` | `https://sts.windows.net//` or `https://login.microsoftonline.com//v2.0` | `single_use` by default; `allow_reuse` can be set | `RS256` | +| `kubernetes` | Your cluster's issuer | `allow_reuse` by default; `single_use` can be set | Any supported | +| `custom_oidc` | Any other issuer | `single_use` by default; `allow_reuse` can be set | Any supported | + +The supported algorithms are `RS256`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`, `ES256`, `ES384`, `ES512`, and `EdDSA`. + +GitHub Actions, Google Cloud, and Microsoft Entra issuers are recognized by their issuer URL and must use their own type. You can't register `https://accounts.google.com` as `custom_oidc` to skip Google's identity checks. + +### Key sources + +| `jwks.type` | Fields | Behavior | +| --- | --- | --- | +| `discovery` | `discovery_base_url` (optional), `ca_cert_pem` (optional) | Reads `/.well-known/openid-configuration` at the issuer URL, or at `discovery_base_url`, and fetches the key set it names. The default. | +| `explicit_url` | `url`, `ca_cert_pem` (optional) | Fetches the key set from `url`. | +| `inline` | `keys` | Uses the 1 to 16 public keys you provide. Nothing is fetched. | + +- Keys are fetched over `https` from public internet addresses only. +- `ca_cert_pem` replaces the system root certificates for that fetch. It holds public CA certificates only. +- A key set holds at most 16 keys, all public. RSA keys must be at least 2,048 bits. +- Fetched keys are cached for five minutes. A token that names an unknown key ID triggers a new fetch, at most once a minute. +- GitHub Actions issuers always use discovery. + +### How a token is verified + +KERNEL accepts an identity token only when: + +- It's a signed JWT of 16 KiB or less, and its signature verifies against one of the issuer's keys. +- `iss` equals the issuer URL exactly. +- `aud` holds exactly one value, equal to the rule's `expected_audience`. +- `sub` is a non-empty string of 1,024 characters or less. +- `exp` and `iat` are both present, the token hasn't expired, and `exp` minus `iat` is within `max_lifetime_seconds`. KERNEL allows 30 seconds of clock difference. +- For a single-use issuer, the token has a token ID that hasn't been exchanged before. The token ID is `jti`, or `uti` for Microsoft Entra. +- The rule's match conditions all hold. + +A single-use token is spent only when an access token is issued. A token refused for another reason isn't spent. + +## Federation rules + +A federation rule (`wifr_...`) maps tokens from one issuer to one service account, one project, and one policy. + +| Field | Description | +| --- | --- | +| `name` | 1 to 128 letters, numbers, and hyphens, starting with a letter or number. | +| `description` | Up to 4,096 characters. | +| `issuer_id` | The issuer whose tokens this rule accepts. | +| `match` | The conditions a token must satisfy. See [Match fields](#match-fields). | +| `expected_audience` | The `aud` value the token must carry. | +| `target` | `{ "type": "service_account", "service_account_id": "svc_..." }` | +| `authorization.project_id` | The one project the rule's tokens are limited to. | +| `authorization.policy` | Allow statements in the shared [policy format](/info/api-key-permissions). Resources must be inside the rule's project, and API key actions aren't allowed. | +| `authorization.token_audience` | The API the access token is for: `https://api.onkernel.com`. | +| `authorization.max_token_ttl_seconds` | The access token lifetime. 1 to 600. Defaults to 300. | +| `enabled` | Defaults to `false`. A rule can't be enabled while its issuer is disabled. | +| `last_exchange_at` | Read-only. When the rule last issued a token. | + +```json +{ + "name": "browser-ci-staging", + "issuer_id": "wii_h7d3k9s2m4q8x1c5v0b6n3ja", + "match": { + "type": "github_actions", + "repository": "acme/widgets", + "repository_id": "738291456", + "repository_owner_id": "9182734", + "workflow": ".github/workflows/e2e.yml", + "ref": "refs/heads/main", + "event_names": ["push", "workflow_dispatch"] + }, + "expected_audience": "https://auth.onkernel.com", + "target": { + "type": "service_account", + "service_account_id": "svc_p2m5k8w1q9z4c7x3v6b0n2ha" + }, + "authorization": { + "project_id": "proj_staging_9f3k", + "policy": { + "statements": [ + { "action": "browsers:create", "resource": "projects/proj_staging_9f3k/*" }, + { "action": "browsers:use", "resource": "projects/proj_staging_9f3k/*" }, + { "action": "browsers:delete", "resource": "projects/proj_staging_9f3k/*" } + ] + }, + "token_audience": "https://api.onkernel.com", + "max_token_ttl_seconds": 300 + } +} +``` + +### Match fields + +`match.type` must equal the issuer's `preset_type`. Every condition a rule sets must hold. + +These fields are available for every type: + +| Field | Description | +| --- | --- | +| `subject` | Exact match on the `sub` claim. | +| `subject_prefix` | The `sub` claim must start with this value. | +| `claims` | Up to 32 exact string conditions, keyed by [JSON Pointer](https://datatracker.ietf.org/doc/html/rfc6901), such as `"/email": "browser-worker@acme-prod.iam.gserviceaccount.com"`. A boolean or number claim is compared by its JSON text. Objects and arrays never match. | + +#### GitHub Actions + +| Field | Required | Description | +| --- | --- | --- | +| `repository_id` | Yes | The repository's numeric ID, as a string. | +| `repository_owner_id` | Yes | The owner's numeric ID, as a string. | +| `repository` | No | `owner/name`, for display. The IDs define the repository. | +| `workflow` | One of these three | A workflow file path that starts with `.github/workflows/`. The token's `workflow_ref` must be that file at the ref the job runs on. | +| `workflow_ref` | One of these three | Exact match on the `workflow_ref` claim. | +| `job_workflow_ref` | One of these three | Exact match on the `job_workflow_ref` claim, for reusable workflows. | +| `ref` | `ref` or `environment` | Exact match on the `ref` claim, such as `refs/heads/main`. | +| `environment` | `ref` or `environment` | Exact match on the `environment` claim. | +| `event_names` | No | 1 to 20 allowed values of the `event_name` claim. Defaults to `push` and `workflow_dispatch`. | + +#### AWS and custom OIDC + +At least one of `subject`, `subject_prefix`, or `claims` is required. For AWS, `subject` is the IAM role ARN, including its path. + +#### Google Cloud + +| Field | Required | Description | +| --- | --- | --- | +| `subject` | Yes | The service account's numeric unique ID. | + +#### Microsoft Entra + +At least one of these is required: `subject`, or a `claims` condition on `/oid`, `/appid`, or `/azp`. + +- KERNEL adds a `/tid` condition for the issuer's tenant. A rule that names a different tenant is rejected. +- A rule with no `subject` and no `/oid` also requires `/idtyp` to be `app`. +- A token with an `scp` claim never matches. + +#### Kubernetes + +| Field | Required | Description | +| --- | --- | --- | +| `namespace` | Yes | The pod's namespace. | +| `service_account` | Yes | The Kubernetes service account name. | + +The token's subject must be exactly `system:serviceaccount::`. + +## Service accounts + +| Field | Description | +| --- | --- | +| `id` | `svc_...` | +| `name` | 1 to 128 letters, numbers, and hyphens, starting with a letter or number. | +| `description` | Up to 4,096 characters. | +| `last_used_at` | When one of the account's API keys last authenticated or one of its rules last issued a token. Recorded at most once every 15 minutes. `null` if never used. | +| `created_by_user_id` | The admin who created it. | +| `archived_at` | Set when the account is archived. | + +See [Service accounts](/info/workload-identity/service-accounts). + +## Authentication events + +Each event records one exchange outcome. Events never hold tokens or claims. + +| Field | Description | +| --- | --- | +| `outcome` | `success` or `failure`. | +| `reason` | See the next table. | +| `issuer_id`, `federation_rule_id`, `service_account_id`, `project_id` | What the exchange resolved to. | +| `credential_id` | The ID of the access token that was issued. `null` for a failure. | +| `correlation_id` | An ID that identifies this exchange. | +| `created_at` | When the exchange happened. | + +| `outcome` | `reason` | Meaning | +| --- | --- | --- | +| `success` | `issued` | KERNEL issued an access token. | +| `failure` | `assertion_replayed` | The identity token was already exchanged, and its issuer is single-use. | +| `failure` | `authority_inactive` | The issuer, rule, service account, or project stopped being active while the exchange was in progress. | +| `failure` | `policy_rejected` | The rule's policy couldn't be granted. | +| `failure` | `authority_unavailable` | KERNEL couldn't complete the exchange. Retry with a fresh identity token. | + +A failure is recorded only after the token has verified and matched an enabled rule. A token that fails signature, issuer, audience, expiry, or match checks leaves no event, because KERNEL can't yet tie it to your organization. Repeated failures for the same token and reason are recorded once. + +Events are kept for 30 days. Through the API, a query returns the last seven days by default and spans at most 30 days. You can filter by issuer, rule, service account, project, outcome, and time range. + +## Auth context + +`GET https://api.onkernel.com/auth/context` describes the credential that makes the request. For a federated token, it returns the service account, the project, the current policy, and which issuer and rule the token came from: + +```json +{ + "authentication": { "method": "jwt", "source": "oauth", "credential_id": null }, + "principal": { "type": "service_account", "id": "svc_p2m5k8w1q9z4c7x3v6b0n2ha" }, + "organization": { "id": "org_8f3k9m2q" }, + "authorization": { + "credential_scope": { "project_id": "proj_staging_9f3k" }, + "effective_scope": { "project_id": "proj_staging_9f3k" }, + "effective_policy": { + "statements": [ + { "action": "browsers:create", "resource": "projects/proj_staging_9f3k/*" }, + { "action": "browsers:use", "resource": "projects/proj_staging_9f3k/*" }, + { "action": "browsers:delete", "resource": "projects/proj_staging_9f3k/*" } + ] + } + }, + "workload_identity": { + "issuer_id": "wii_h7d3k9s2m4q8x1c5v0b6n3ja", + "federation_rule_id": "wifr_tz4a98xxat96iws9zmbrgj3a", + "external_subject_digest": "Zq1V0m4k7yQ2m3H8v5c1x9b6n4p7r2t0s8w3e6u1i5o" + } +} +``` + +`external_subject_digest` is a digest of the identity token's subject. The token and its claims are never returned. A service account API key gets the same response without `workload_identity`, and with `authentication.method` set to `api_key`. + +The call needs no permission in the policy. + +## Management API + +Manage service accounts, issuers, and rules in the dashboard. These are the endpoints behind it, listed for reference. They aren't currently accessible with an API key or a federated token: a call with either returns `403`, including through the SDK methods for these endpoints. + +| Endpoint | Operations | +| --- | --- | +| `/org/service_accounts` | Create, list | +| `/org/service_accounts/{id}` | Get, update, archive | +| `/org/workload_identity_issuers` | Create, list | +| `/org/workload_identity_issuers/{id}` | Get, update, archive | +| `/org/workload_identity_issuers/{id}/verify` | Check that the issuer's keys can be fetched. Returns the key IDs. Grants nothing. | +| `/org/workload_identity_federation_rules` | Create, list | +| `/org/workload_identity_federation_rules/{id}` | Get, update, archive | +| `/org/workload_identity_authentication_events` | List | + +### Who can manage them + +- **Any organization member can view** service accounts, issuers, rules, and authentication events. +- **Only an organization admin can change** them: create, update, archive, and verify. + +The same applies to service account API keys: only an organization admin can create, rotate, rename, change the permissions of, or delete one, and only from the dashboard. + +### Updates and versions + +Every resource has a `security_version` that increases when a change affects what it trusts or grants. An update (`PATCH`) must send the version it's based on as `expected_version`. If the resource changed in the meantime, the update returns `409 Conflict`. Read the resource again and retry. + +### Lists and archiving + +- Lists take `limit` (1 to 100, default 20) and `offset`, and return `X-Has-More` and `X-Next-Offset` headers. Service account, issuer, and rule lists also take `status`: `active` (the default), `archived`, or `all`. +- `DELETE` archives. History stays, and the archived resource stops granting access. Creating a resource with the same name or issuer URL later creates a new ID. +- A problem the admin can fix, such as a key endpoint that isn't public or a discovery document that names a different issuer, returns `400` with the reason. A `503` means a condition that may pass on retry, such as a timeout. + +## Limits + +| Limit | Value | +| --- | --- | +| Access token lifetime | 300 seconds by default; 1 to 600 | +| Identity token size | 16 KiB | +| Identity token lifetime (`exp` minus `iat`) | 3,600 seconds by default, 7,500 for Microsoft Entra; up to 86,400 | +| Clock difference allowed | 30 seconds | +| Projects per rule | 1 | +| Policy statements per rule | 1 to 256 | +| Claim conditions per rule | 32 | +| Inline public keys per issuer | 16 | +| Time for a disable or archive to stop issued tokens | About 10 seconds | +| Authentication event retention | 30 days | +| Service account `last_used_at` granularity | 15 minutes | diff --git a/info/workload-identity/service-accounts.mdx b/info/workload-identity/service-accounts.mdx new file mode 100644 index 00000000..cfd34a91 --- /dev/null +++ b/info/workload-identity/service-accounts.mdx @@ -0,0 +1,100 @@ +--- +title: "Service Accounts" +description: "Named, non-human identities for your workloads, and the service account API keys to use when a workload can't federate" +--- + +A **service account** (`svc_...`) is a named identity your organization owns, for software instead of people. Workloads act as a service account in two ways: + +- **Through a [federation rule](/info/workload-identity/overview#federation-rules)**, which issues short-lived tokens. Use this wherever your workload has an identity provider. +- **Through a [service account API key](#service-account-api-keys)**, for workloads that can't federate. + +Either way, the service account outlives the people who set it up. A personal API key acts as the person who created it. A service account credential acts as the service account, so it keeps its meaning when that person changes teams or leaves. + +## What a service account is + +A service account has a name and a description, and nothing else. It holds no permissions. Each rule or key that uses it carries its own project, policy, and expiry, so one service account can back a rule for staging and a rule for production with different permissions. + +Names use letters, numbers, and hyphens, up to 128 characters, and start with a letter or number. + +## Create a service account + +Only an organization admin can create, edit, or archive a service account. Any member can view them. + +1. In the [dashboard](https://dashboard.onkernel.com), open **Keys** in the sidebar and select **Service accounts**. +2. Click **Create service account**. +3. Enter a **Name**, such as `browser-ci`, and an optional **Description**. +4. Click **Create service account**. + +You can also create one inline in the **Target** step of **Connect workload**, or from the **Linked account** select when you create an API key. + +Open a service account to see its ID, when it was created and last used, the **API keys** linked to it, and the **Federation rules** that target it. + +## What a service account can do + +A service account credential can do what its rule's or key's policy grants, inside that rule's or key's one project. The policy uses the same actions and resources as a scoped API key. See [Scoping permissions](/info/api-key-permissions). + +- **Browsers** it creates are recorded as created by the service account. Creating a browser needs `browsers:create` and `browsers:use`, plus permission on any profile, vault, or proxy the browser attaches. +- **Other resources**, such as profiles and proxies, can be created when the policy grants it. They record no creator. + +### What a service account can't do + +Three things are closed to service accounts, whatever the policy says: + +| Closed | Why | +| --- | --- | +| Acquiring a browser from a [pool](/browsers/pools) | A pool lease records a user, not a service account. | +| [App](/apps/deploy) deployments and invocations, including attaching a browser to an invocation and listing or deleting an invocation's browsers | Deployments and invocations identify their caller as a user. | +| Managing API keys | A service account's policy can't include API key permissions. | + +If a workload needs one of these, use a personal [API key](/info/api-keys) for that part. + +## Last used + +A service account's **Last used** time updates when one of its rules issues a token or one of its API keys authenticates. It's recorded at most once every 15 minutes, so it can trail real use by a little more than that. Use it to find service accounts that nothing uses anymore. + +## Archive a service account + +Archiving stops everything that acts as the service account. New token exchanges are refused, and tokens already issued stop working within about 10 seconds. Archiving keeps the account's history and can't be undone. Creating a service account with the same name later gives you a new ID, and nothing that pointed at the old one moves to it. + +Archiving doesn't delete browsers the service account created. Delete those yourself. + +To archive, open the row's menu on the **Service accounts** page and select **Archive**. + +## Service account API keys + + +A service account API key is still a stored secret that works from anywhere until it expires or you delete it. If your workload runs on GitHub Actions, AWS, Google Cloud, Azure, or Kubernetes, use a [federation rule](/info/workload-identity/overview) instead. + + +Some workloads can't federate: a VM at a host with no identity provider, or a third-party tool that only accepts a key. For those, link an API key to a service account. The key acts as the service account, not as you, and it keeps working after you leave the organization. + +A service account API key always has: + +- **One project.** It can't be organization-wide. +- **An explicit policy.** There's no unrestricted service account key. The policy can't grant API key permissions. + +### Create a service account API key + +Only an organization admin can create one, from the dashboard. Creating one isn't currently possible with an API key or a federated token. + +1. Open **Keys** in the sidebar and select **API keys**. +2. Click **Create API Key**, then **Continue with an API key**. +3. Under **Linked account**, select the service account, or select **Create a service account**. +4. Choose a **Project**. +5. Set an **Expiration**. Pick the shortest one your workload can live with. +6. Under **Permissions**, grant the actions the workload needs. +7. Create the key and copy it. KERNEL shows the plaintext key once. + +You can start from the service account instead: open it and click **Create key** in the **API keys** section. The account is preselected. + +### Manage a service account API key + +An admin can rename, rotate, or delete a service account API key, and can replace its permissions in place without issuing a new secret. + +- **Rotating** keeps the service account, project, and policy. +- **Deleting** one key doesn't affect the service account or its federation rules. +- **The creator is for audit only.** The key shows who created it, but it doesn't act as that person and doesn't stop working when they leave. + +To find these keys, filter the **API keys** list by **Linked account**, or list them through the API with `principal_type=service_account` or `service_account_id`. See [List and inspect API keys](/info/api-keys#list-and-inspect-api-keys). + +When your workload gains an identity provider, [move it to federation](/info/workload-identity/migrate-from-api-keys) and delete the key. diff --git a/info/workload-identity/troubleshooting.mdx b/info/workload-identity/troubleshooting.mdx new file mode 100644 index 00000000..aca5fb88 --- /dev/null +++ b/info/workload-identity/troubleshooting.mdx @@ -0,0 +1,133 @@ +--- +title: "Troubleshooting Workload Identity" +sidebarTitle: "Troubleshooting" +description: "Find out why a token exchange was refused and fix it" +--- + +The token endpoint doesn't say why it refused a token. That's deliberate: a caller without valid proof learns nothing about your configuration. This page shows how to find the reason from your side. + +## Start here + + + +The SDK raises a `WorkloadIdentityError` with the HTTP status, the OAuth error code, and a description. Match it against the [table below](#exchange-errors). + + + +In the [dashboard](https://dashboard.onkernel.com), open **Keys** > **Workload identity** > **Authentication events** and filter by **Rule**. + +- **A `failure` event exists.** The token verified and matched the rule, and the reason says what went wrong next. +- **No event exists.** The token was refused before KERNEL could tie it to your organization: the signature, issuer, audience, expiry, or match conditions didn't hold, or the rule or issuer isn't enabled. + + + +Print the identity token's claims from inside the workload and compare them with the rule: + +```bash +echo "$IDENTITY_TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq . +``` + +Check `iss` against the issuer URL, `aud` against the rule's expected audience, and `sub` and the other claims against the rule's match conditions. Don't paste a live token into a website or a chat. + + + +## Exchange errors + +| Error | Likely cause | Fix | +| --- | --- | --- | +| `invalid_grant`: `Credential is invalid, expired, or revoked` | The issuer or the rule is disabled or archived. Both are created disabled. | Enable the issuer, then the rule. A rule can't be enabled while its issuer is disabled. | +| | The token's `aud` isn't the rule's expected audience. | Request the audience `https://auth.onkernel.com`, or set `KERNEL_IDENTITY_TOKEN_AUDIENCE` to the rule's expected audience. For Microsoft Entra, the audience is your app registration. | +| | The token's `iss` isn't the issuer URL, character for character. | Compare them, including a trailing slash. Entra v1.0 issuers end in `/`; v2.0 issuers end in `/v2.0`. | +| | The token doesn't satisfy the rule's match conditions. | Decode the token and compare each condition. See the provider notes below. | +| | The rule ID belongs to a rule on a different issuer. | Check `KERNEL_FEDERATION_RULE_ID`. | +| | The token expired, or its lifetime is over the issuer's maximum. | Request a fresh token. If your provider issues long-lived tokens, raise **Maximum token lifetime (hours)** on the issuer. | +| | The token has more than one audience. | Request a token for one audience. | +| | The service account is archived. | Point the rule at an active service account. | +| `invalid_grant`: `Credential was already used` | The identity token was exchanged before, and the issuer is single-use. | Give each exchange a fresh token. See [The same token was sent twice](#the-same-token-was-sent-twice). | +| `invalid_target`: `Invalid resource parameter` | `resource` isn't `https://api.onkernel.com`. | Remove a trailing slash or a path. With an SDK, don't override `resource`. | +| `invalid_request`: `Missing required parameter: federation_rule_id` | No rule ID was sent. | Set `KERNEL_FEDERATION_RULE_ID`. | +| `invalid_request`: `Unsupported workload identity parameter` | The request has a parameter such as `client_id`. | Send only `grant_type`, `assertion`, `federation_rule_id`, and `resource`. | +| `invalid_request`: `Workload assertion exchange does not accept client authentication` | The request has an `Authorization` header. | Remove it. A proxy or an HTTP client default may be adding one. | +| `temporarily_unavailable` (`503`) | KERNEL couldn't fetch or use the issuer's signing keys, or had a temporary problem. | Run **Check signing keys** on the issuer. If it reports a problem, fix the key source. Otherwise retry with a fresh token. | + +## The same token was sent twice + +GitHub Actions and AWS tokens can be exchanged once. Microsoft Entra and custom OIDC tokens can be exchanged once unless you allow reuse. When a token is presented a second time, the SDK's message says where it came from: + +| The token came from | What happened | Fix | +| --- | --- | --- | +| `KERNEL_IDENTITY_TOKEN_FILE` | The file held the same token as a previous exchange. | Make whatever writes the file replace the token before each refresh. For tokens that are reread by design, such as Kubernetes projected tokens, allow reuse on the issuer. | +| `KERNEL_IDENTITY_TOKEN` | A static token is good for one exchange. The SDK refuses to send it a second time. | Use a file, a built-in source, or a callback for anything that outlives one access token. | +| A callback | The callback returned a token it had returned before. | Return a newly issued token on every call. If your identity library caches tokens, as the Azure Identity libraries do, allow reuse on the issuer. | +| Your own retry loop | A failed request was retried with the same token. | After an ambiguous response such as a timeout, get a fresh token before you retry. | + +To allow reuse on a Microsoft Entra, Kubernetes, or custom OIDC issuer, select **Edit** on the issuer and turn off **Enforce single-use tokens (JTI replay protection)**. A reusable token can be exchanged until it expires, so allow reuse only when your token source needs it. + +## SDK configuration problems + +| Symptom | Cause | Fix | +| --- | --- | --- | +| The workload authenticates as a person, not a service account. | `KERNEL_API_KEY` is set and wins. The SDK logs a warning that both are set. | Remove `KERNEL_API_KEY` from the workload's environment. | +| The client reports missing credentials although `KERNEL_FEDERATION_RULE_ID` is set. | The SDK found no identity token source. | Set `KERNEL_IDENTITY_TOKEN_SOURCE`, `KERNEL_IDENTITY_TOKEN_FILE`, or `KERNEL_IDENTITY_TOKEN`. In GitHub Actions, add `permissions: id-token: write` to the workflow or the job. | +| With `KERNEL_IDENTITY_TOKEN_SOURCE=github_actions`, the SDK says `ACTIONS_ID_TOKEN_REQUEST_URL` isn't set. | The job can't request an identity token. | Add `permissions: id-token: write` to the workflow or the job. | +| The `aws_sts` source says a package or import is missing. | The AWS SDK is optional. | Install `@aws-sdk/client-sts` 3.935.0 or later, install `kernel[aws]`, or import `github.com/kernel/kernel-go-sdk/lib/credentials/awssts`. | +| AWS reports access denied on `GetWebIdentityToken`. | The role can't request tokens, or outbound identity federation is off for the account. | Enable it and grant `sts:GetWebIdentityToken`. See [AWS](/info/workload-identity/aws#configure-aws). | +| The SDK says it can't determine the auth base URL. | The client uses a custom API base URL. | Set `KERNEL_AUTH_BASE_URL` or the auth base URL option. | +| The identity token file is empty or missing. | The volume isn't mounted, or its projection is wrong. | Check the mount path and the projected token's `audience`. | +| The SDK says the identity token is too large. | The source points at something that isn't a token, such as a key or a certificate. | Point it at the token. Identity tokens are a few kilobytes. | + +## Requests fail after a successful exchange + +| Symptom | Cause | Fix | +| --- | --- | --- | +| `403` with `insufficient_scope` | The rule's policy doesn't grant the action on that resource. | The message names the missing action and resource. Add it to the rule. Operations such as creating a browser need [more than one action](/info/api-key-permissions#operations-that-need-more-than-one-action). | +| A pool acquire, a deployment, or an invocation is refused | These are [closed to service accounts](/info/workload-identity/service-accounts#what-a-service-account-cant-do). | Use a personal API key for that part of the workload. | +| A request that names another project fails | The token is bound to the rule's project. | Create a rule for the other project. | +| `401` shortly after it worked | The rule, issuer, or service account was disabled, archived, or changed. Issued tokens stop working within about 10 seconds. | Check the **Rules** and **Issuers** tabs. The SDK retries once with a fresh exchange, so a re-enabled rule recovers by itself. | +| Lists come back empty | List endpoints return only what the policy can access. | Grant the matching read or use action. | + +## Provider notes + +**GitHub Actions** + +- A rule needs a branch or an environment. A job on another branch, or without that environment, doesn't match. +- `pull_request`, `schedule`, and `release` events aren't allowed unless you add them to **Allowed events**. +- A rule with a **Workflow** path matches only when the workflow file comes from the same ref the job runs on. +- The rule pins numeric repository and owner IDs. A repository that was deleted and recreated under the same name has a new ID. + +**AWS** + +- The subject is the IAM role ARN with its path, such as `arn:aws:iam::123456789012:role/service/browser-worker`. +- `GetWebIdentityToken` isn't served by the global STS endpoint. The SDKs call the regional endpoint for `AWS_REGION`. + +**Google Cloud** + +- The subject is the service account's numeric unique ID, not its email. +- The metadata server returns a token for the service account attached to the workload. Check that it's the one your rule names. + +**Microsoft Entra** + +- A token with an `scp` claim was issued to a signed-in user and never matches. Use a managed identity or client credentials. +- v1.0 and v2.0 tokens have different issuers and audiences. Register the issuer version your tokens carry. +- A rule keyed only on a client ID needs the `idtyp` optional claim. See [Microsoft Entra](/info/workload-identity/microsoft-entra#what-kernel-accepts). + +**Kubernetes** + +- The default service account token has the wrong audience. Mount a projected token with the audience `https://auth.onkernel.com`. +- A projected token with `expirationSeconds` over 3,600 exceeds the issuer's default maximum lifetime. +- KERNEL must reach the cluster's discovery document and keys from the public internet. For a private cluster, [upload the keys](/info/workload-identity/kubernetes#private-clusters). + +## Issuer key problems + +**Check signing keys** on the **Issuers** tab fetches the issuer's keys and reports the result. When KERNEL can't use the keys for a reason you can fix, it tells you which: + +- The key endpoint's address isn't on the public internet. +- The endpoint returned the wrong status or didn't return JSON. +- The discovery document names a different issuer than the one you registered. +- The key set isn't valid or holds an unsupported key. + +A timeout or other temporary condition is reported as unavailable. Try again. + +## Still stuck + +Contact [support](/info/support) with the rule ID, the time of the attempt, and the request ID from the SDK error if there is one. Don't send the identity token or the access token. diff --git a/introduction/manage.mdx b/introduction/manage.mdx index ddfdb5de..f0ecafc6 100644 --- a/introduction/manage.mdx +++ b/introduction/manage.mdx @@ -11,8 +11,11 @@ Management settings apply across your organization rather than to a single brows Separate environments, teams, or customers, each with its own browsers, profiles, credentials, and limits. + + Let CI jobs and cloud services authenticate with short-lived tokens instead of stored API keys. + - Create, scope, rotate, and delete the keys your code and agents use. + Create, scope, rotate, and delete keys for local development and workloads that can't federate. Set a monthly spending guardrail for your organization, a project, or both. @@ -30,6 +33,6 @@ Management settings apply across your organization rather than to a single brows If you run KERNEL on behalf of your own customers, combine these pieces so each customer is isolated and capped: - **One [project](/info/projects) per customer.** Each project has its own browsers, profiles, credentials, proxies, and deployments. -- **A [project-scoped API key](/info/api-keys) per customer workload.** A project-scoped key can only reach resources in its project. +- **A [federation rule](/info/workload-identity/overview) or a [project-scoped API key](/info/api-keys) per customer workload.** Each one can only reach resources in its project. Prefer a federation rule where the workload has an identity provider, so there's no key to store. - **A [spending cap](/info/spending-caps) and a [concurrency limit](/info/projects#concurrency-limits) per project.** One customer's usage can't exhaust your budget or your organization's browser limit. - **One [profile](/browsers/profiles) per end user.** Each user's logins and browser state stay separate, inside their customer's project. diff --git a/reference/cli/api-keys.mdx b/reference/cli/api-keys.mdx index 98fc1a02..5d59254e 100644 --- a/reference/cli/api-keys.mdx +++ b/reference/cli/api-keys.mdx @@ -4,6 +4,10 @@ title: "API Keys" Manage [API keys](/info/api-keys) from the CLI. + +For CI jobs, cloud services, and Kubernetes pods, use [workload identity federation](/info/workload-identity/overview) instead of an API key. There's no secret to store, and the credential expires in minutes. Service accounts, issuers, and federation rules are managed from the dashboard. + + ## `kernel api-keys create` Create an API key. By default, the new key is org-wide. Pass `--project-id` to create a key whose own access is scoped to that project. @@ -29,7 +33,7 @@ kernel api-keys create \ ## `kernel api-keys list` -List API keys in the authenticated organization. API keys are masked. +List API keys in the authenticated organization. API keys are masked. The list shows active keys: keys that are neither deleted nor expired. ```bash kernel api-keys list --limit 20 diff --git a/reference/cli/auth.mdx b/reference/cli/auth.mdx index 23b27710..29e49c70 100644 --- a/reference/cli/auth.mdx +++ b/reference/cli/auth.mdx @@ -24,6 +24,10 @@ export KERNEL_API_KEY=sk_1234abcd Create and manage API keys from the Kernel dashboard or with [`kernel api-keys`](/reference/cli/api-keys). + +The CLI authenticates with `kernel login` or `KERNEL_API_KEY`. It doesn't exchange workload identity tokens. For a CI job or a cloud service that calls KERNEL through an SDK, use [workload identity federation](/info/workload-identity/overview) instead of storing an API key. + + ## Global flags The following flags are available on every CLI command: diff --git a/reference/mcp-server/authentication.mdx b/reference/mcp-server/authentication.mdx index d4066d1a..74c8ea69 100644 --- a/reference/mcp-server/authentication.mdx +++ b/reference/mcp-server/authentication.mdx @@ -35,3 +35,7 @@ API key authentication is useful for: - Environments where OAuth flows are not practical API keys bypass the OAuth flow but still require valid Kernel credentials. Keep your API key secure and don't expose it in client-side code. + + +If your automation calls the KERNEL API through an SDK instead of the MCP server, it doesn't need an API key. Use [workload identity federation](/info/workload-identity/overview): a CI job or cloud service authenticates with its own identity and gets a credential that expires in minutes. When an MCP client does need a key, scope the key to one project and give it a short expiry. + diff --git a/start/quickstart.mdx b/start/quickstart.mdx index 4528ccea..c86e1ae4 100644 --- a/start/quickstart.mdx +++ b/start/quickstart.mdx @@ -72,6 +72,10 @@ Create an API key in the [dashboard](https://dashboard.onkernel.com) and set it ```bash export KERNEL_API_KEY= ``` + + +An API key is the quickest way to try KERNEL from your own machine. When this code moves into CI or a cloud service, switch to [workload identity federation](/info/workload-identity/overview): the workload authenticates with its own identity, the credential expires in minutes, and there's no key to store or leak. +