diff --git a/AGENTS.md b/AGENTS.md index db26c3d..38f8430 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,13 @@ Go 1.26.8 or later; the toolchain line in `go.work` and `engine/go.mod` selects These are requirements, not suggestions. A change that misses one is not done. 1. **Document it in the same commit.** + - **User guide first.** Anything a user can see or do (install, configure, secure, run, connect, upgrade, + troubleshoot) updates `docs/user-guide/` with complete, working instructions: every step, command, key and + default a user needs, tried on a real build, not described from the code. Add a page when a task has none, + and update `docs/user-guide/reference/runtime-toml.md` for every configuration key. + - **Check the whole guide, not only your page.** Before opening the PR, read every page the change touches and + the pages that link to them, and make commands, key names, defaults, ports and file paths agree with the code + and with each other. A PR that leaves another page wrong is not done. - A new or changed feature updates its page in `docs/features/` (create it from `docs/features/TEMPLATE.md`). - A design change updates `docs/guides/ARCHITECTURE.md` or adds a decision record in `docs/decisions/`. - A new or changed command, flag, configuration key or port updates the README, `docs/guides/DEVELOPING.md` @@ -117,6 +124,11 @@ These are requirements, not suggestions. A change that misses one is not done. ## Documentation +- `docs/user-guide/` is for the people who install and run the runtime. It is the source of the Workflow Runtime + section of the WSO2 Integrator documentation (planned under `manage/workflow-runtime/` in wso2/docs-integrator, + shaped like its ICP section), so write it that way: front matter (`title`, `description`, `keywords`), + task-oriented pages, numbered steps, `:::info`/`:::tip`/`:::caution` admonitions, plain Markdown (no MDX + imports), links relative to the page. No internal plans, issue numbers or code internals. - `docs/guides/` explains the system: `ARCHITECTURE.md` (components and how they connect), `DEVELOPING.md` (build, run, debug), `TESTING.md` (test layers and how to add tests). - `docs/features/` has one page per feature, from `TEMPLATE.md`: what it does, configuration, behavior, limits, diff --git a/README.md b/README.md index f4bf9d8..6e83376 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,8 @@ Status: early development. The engine builds and runs; the launcher, Manager and Documentation: [architecture](docs/guides/ARCHITECTURE.md), [developing](docs/guides/DEVELOPING.md), [testing](docs/guides/TESTING.md), [features](docs/features/README.md), [decisions](docs/decisions/). + +Installing and running the runtime: the [user guide](docs/user-guide/README.md). Contributors and coding agents: read [AGENTS.md](AGENTS.md) first. ## Build diff --git a/distribution/conf/runtime.toml b/distribution/conf/runtime.toml index 8b39e63..f4f9989 100644 --- a/distribution/conf/runtime.toml +++ b/distribution/conf/runtime.toml @@ -1,7 +1,7 @@ -# The runtime's configuration. [engine] and [database] are read by workflow-engine (docs/features/runtime-config.md); -# the other tables are illustrative until their components arrive. +# The runtime's configuration. [runtime] profiles, [engine] and [database] are read by workflow-engine +# (docs/features/runtime-config.md); the other tables are illustrative until their components arrive. [runtime] -profiles = ["all"] # or e.g. ["history"], ["manager"] +profiles = ["all"] # or e.g. ["frontend"], ["history", "matching"], ["worker"] [engine] # Listen on every interface and tell other nodes and clients which address reaches this one. @@ -10,6 +10,24 @@ profiles = ["all"] # or e.g. ["history"], ["manager"] # historyShards = 512 # fixed after the first start logLevel = "info" +# TLS on port 7233 and tokens from your identity provider (docs/features/engine-security.md). +# [engine.tls] +# certFile = "conf/certs/engine.crt" +# keyFile = "conf/certs/engine.key" +# +# [engine.auth] +# type = "jwt" +# issuer = "https://idp.example.com/oauth2/token" # its key set is discovered; or set jwksUrls +# rolesClaim = "groups" +# +# [[engine.auth.rules]] +# value = "workflow-admins" +# namespace = "*" +# role = "admin" + +# [engine.metrics] +# prometheusAddress = "0.0.0.0:9464" + [database] type = "postgresql" # postgresql | mysql | sqlite host = "db.example.com" diff --git a/docs/features/README.md b/docs/features/README.md index ca158d2..221f6da 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -8,3 +8,4 @@ in the same commit ([AGENTS.md](../../AGENTS.md#rules-for-every-change)). Start |---|---| | [Engine](engine.md) | Available | | [Runtime configuration](runtime-config.md) | Available | +| [Engine security](engine-security.md) | Available | diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md new file mode 100644 index 0000000..cde0ec0 --- /dev/null +++ b/docs/features/engine-security.md @@ -0,0 +1,117 @@ +# Engine security + +Status: available · since 0.1.0 (in development) + +## What it does + +Secures the engine's frontend (port 7233), the endpoint integrations connect to, without the Manager: TLS on the +connection, and tokens from the customer's own identity provider mapped to Temporal's namespace roles. + +## Configuration + +### `[engine.tls]` + +| Key | Default | Meaning | +|---|---|---| +| `certFile`, `keyFile` | off | The frontend's certificate and key (PEM). Clients connect with TLS and trust its CA | +| `clientCaFile` | off | Require client certificates signed by this CA (mutual TLS) | +| `[engine.tls.internode]` `enabled` | `false` | TLS between the engine's services and nodes | +| `[engine.tls.internode]` `certFile`, `keyFile` | the frontend's | Certificate the services present to each other | +| `[engine.tls.internode]` `caFile` | required when enabled | CA that signs the internode certificates | +| `[engine.tls.internode]` `serverName` | the internode certificate's DNS name, when it has exactly one | Name every node verifies in the others' certificates. Temporal reaches the internal frontend through its membership resolver, which has no host name, so a name is always needed. Required when the certificate has no DNS name or several; an explicit name must be in the certificate (a DNS name, a wildcard match or an IP address) | + +### `[engine.auth]` + +| Key | Default | Meaning | +|---|---|---| +| `type` | `none` | `jwt` checks a bearer token on every call; `none` needs `--allow-no-auth` | +| `jwksUrls` | discovered from `issuer` | The identity provider's key set (JWKS) URLs, when it has no OpenID Connect discovery document; https, or http to a loopback host | +| `keyRefreshInterval` | `1m` | How often the key set is fetched again | +| `issuer` | | Required value of `iss`, and where the key set is discovered at start (`/.well-known/openid-configuration`); `issuer` or `jwksUrls` is required | +| `audience` | not checked | Required value in `aud` | +| `subjectClaim` | `sub` | Claim naming the caller | +| `rolesClaim` | `permissions` | Claim holding the caller's groups, roles or scopes: a list, or a space- or comma-separated string; a dotted path reads a nested claim (`realm_access.roles`) | +| `valueRegex` | | Without rules: a regular expression with the named groups `namespace` and `role` | +| `leewaySeconds` | 0 | Clock skew allowed on `exp`, `nbf` and `iat` | +| `[[engine.auth.rules]]` `value`, `namespace`, `role` | | Grant `role` (`read`, `write`, `admin`) in `namespace` (or `*` for all) to callers whose roles claim holds `value` | + +```toml +[engine.tls] +certFile = "conf/certs/engine.crt" +keyFile = "conf/certs/engine.key" + +[engine.auth] +type = "jwt" +jwksUrls = ["https://cognito-idp.us-east-1.amazonaws.com//.well-known/jwks.json"] +issuer = "https://cognito-idp.us-east-1.amazonaws.com/" +rolesClaim = "cognito:groups" + +[[engine.auth.rules]] +value = "workflow-admins" +namespace = "*" +role = "admin" + +[[engine.auth.rules]] +value = "orders-integration" +namespace = "default" +role = "write" +``` + +## Behavior + +- **Three ways to read roles**, so any identity provider fits: + - Rules map the provider's group, role or scope names to namespace roles. Use them when the provider knows + nothing about namespaces, which is the usual case. + - Without rules, each value is Temporal's own `:` (for example `default:write`). + - `valueRegex` parses values in any other shape that carries both, such as `wf-default-write`. +- A role in namespace `*` (or Temporal's `temporal-system`) applies to every namespace and to cluster operations. +- Roles add up across values. `read` lets a caller list and describe; `write` adds starting and signalling + workflows and lets an integration's workers poll and complete tasks; `admin` adds namespace management. There is no + worker role: Temporal's default authorizer needs write to poll, so a `worker` rule is refused. +- `type = "jwt"` needs `[engine.tls]`, and, unless `bindAddress` is a loopback address, `[engine.tls.internode]`: + the internal frontend gives Temporal's own services system access without a token, so it and the other services' + ports accept only internode certificates. +- Internode TLS also turns on Temporal's `system.enableRingpopTLS` (passed as dynamic configuration at start), so the + membership ports, which list every node's address, take only internode certificates too. +- A `--service` list without `internal-frontend` on an engine with an authorizer logs a warning: another node must + run it. +- With neither `issuer` nor `audience`, those two claims are not checked; the start logs a warning. A token still + needs a valid signature from the key set, an expiry, a subject and a mapped role. +- With `issuer` and no `jwksUrls`, the start command reads the provider's OpenID Connect discovery document and uses + its `jwks_uri`; the document must name exactly the same issuer, and the engine does not start if it cannot read it. +- Key sets and discovery documents are fetched only over https (plain http only to a loopback host): a key set + replaced on the way would let anyone sign tokens the engine trusts. The same rule applies to every redirect, at start + and on each refresh, so the engine reads key sets itself (`jwtclaims.KeySet`); Temporal's key provider follows any + redirect. +- Each discovery document and key set read is limited to 1 MiB, and a redirect never goes from https to http. Only + RS256 and ES256 keys are kept, and only when their `use`, `key_ops` and `alg`, if published, allow verifying that + algorithm's signatures; an invalid entry never replaces a valid key with the same `kid`. A response without a `keys` member (an error page served with status 200) is refused, and the previous keys stay. +- Every token is checked for its signature, an expiry, the issuer and audience when set, and a subject; one issued in + the future (`iat` beyond `leewaySeconds`) is refused. A call without a token, or with a token that maps to no role, + is refused, except Temporal's health checks. +- Refusals return Temporal's generic "Request unauthorized"; the reason goes to the engine log. +- Temporal's own services reach the frontend through the internal frontend, which is not exposed to clients. +- Integrations connect with `mode = "SELF_HOSTED"`, the token in `authApiKey` and the CA in `authCaCert` + (`ballerina/workflow`). + +## Limits + +- Tokens must be signed with RS256 or ES256, as with Temporal's key provider. +- Clients present the token themselves; refreshing an expiring token is the client's job. +- Client certificates authenticate the connection only; roles still come from the token. + +## Not covered yet + +Roles from client certificate subjects, tokens issued by the Manager, and task-queue-scoped tokens. + +## Tests + +| Test | Covers | +|---|---| +| `engine/plugins/jwtclaims/discovery_test.go` | Discovery: the key set URL, another issuer or a trailing slash, no key set, a plain-http issuer or key set, invalid documents, unreachable providers; which URLs `CheckURL` accepts | +| `engine/plugins/jwtclaims/keyset_test.go` | Reading RS256 and ES256 keys, keeping them when a refresh fails, refreshing on the interval; a redirect to plain http refused for key sets and discovery, from https to loopback http refused, one to https followed; keys for encryption or another algorithm dropped, a bad entry not replacing a good key with the same ID; oversized key sets and sets without `keys` refused | +| `engine/plugins/jwtclaims/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, tokens issued in the future, forged and malformed tokens | +| `engine/internal/runtimeconfig/security_test.go` | TLS, auth and metrics mapping and every validation rule | +| `engine/internal/cli/cli_test.go` | A start with identity-provider auth; which claim mapper is built; the services the profiles and `--service` pass to the server, including `--service` with an `api`-only profile | +| `tools/internal/enginetest/cluster_test.go` | Two secured nodes on one SQLite file, one with frontend, matching and worker and one with frontend and history, form one engine: a workflow started through the first runs on the second's history, over TLS membership and internode TLS | +| `tools/internal/enginetest/security_test.go` | A real engine with TLS, internode mutual TLS and an OpenID Connect provider: an integration token starts and lists in its namespace; another namespace, a reader writing, no token, expired, forged, other-issuer and unmatched tokens, and plaintext are refused; the internal frontend refuses callers without an internode certificate and answers one with it; adding a search attribute works, which goes through the internal frontend with the derived server name; history, matching, worker and every membership port take TLS with a node certificate and refuse callers without one | diff --git a/docs/features/engine.md b/docs/features/engine.md index 1287992..233222d 100644 --- a/docs/features/engine.md +++ b/docs/features/engine.md @@ -15,7 +15,7 @@ the configuration defines one) in one binary built from the pinned Temporal serv | `workflow-engine start --runtime-config ` | one of the two | Generate Temporal's configuration from `conf/runtime.toml` ([runtime configuration](runtime-config.md)) | | `workflow-engine start --config-file ` | one of the two | Use a Temporal server configuration (YAML) as is | | `workflow-engine render-config --runtime-config ` | | Print the configuration generated from `runtime.toml`, password hidden | -| `--service ` (repeatable) | `frontend`, `history`, `matching`, `worker`, plus `internal-frontend` when `services.internal-frontend` is configured | `frontend`, `internal-frontend`, `history`, `matching`, `worker` | +| `--service ` (repeatable) | From `runtime.toml`'s `[runtime] profiles`; with `--config-file`, `frontend`, `history`, `matching`, `worker`, plus `internal-frontend` when configured | `frontend`, `internal-frontend`, `history`, `matching`, `worker`; overrides the profiles | | `--allow-no-auth` | off | Start without an authorizer; development and tests only | ## Behavior @@ -39,7 +39,9 @@ the configuration defines one) in one binary built from the pinned Temporal serv ## Not covered yet -The engine endpoint, our authorizer, TLS and token configuration, and the launcher's profiles. +The engine endpoint, Manager-issued tokens, and the launcher's supervision and restart. TLS, identity-provider +tokens and profiles are covered by [engine security](engine-security.md) and +[runtime configuration](runtime-config.md). ## Tests diff --git a/docs/features/runtime-config.md b/docs/features/runtime-config.md index f85d8ca..cc7bada 100644 --- a/docs/features/runtime-config.md +++ b/docs/features/runtime-config.md @@ -34,6 +34,15 @@ other, not both. | `[database.tls]` `enabled`, `caFile`, `certFile` and `keyFile` (both or neither), `serverName` (MySQL only) | off | TLS to the database (PostgreSQL and MySQL; refused for SQLite) | | `[database.tls]` `enableHostVerification` | `true` | Verify the server's certificate and host name; `false` turns verification off, which lets anyone between the engine and the database impersonate it | +### `[runtime]` + +| Key | Default | Meaning | +|---|---|---| +| `profiles` | `["all"]` | What this node runs: `all` or `engine` (every engine service), `frontend` (with the internal frontend), `history`, `matching`, `worker`, and `api` (the API server; the engine starts nothing for it). Profiles combine | + +Nodes find each other through the shared database, so a distributed deployment is the same `runtime.toml` on every +node with a different `profiles` and its own `broadcastAddress`. + ### `[engine]` | Key | Default | Meaning | @@ -43,8 +52,10 @@ other, not both. | `historyShards` | 512 (1 for SQLite) | Temporal history shards. **Cannot be changed after the first start** | | `logLevel` | `info` | `debug`, `info`, `warn` or `error` | | `[engine.ports]` `frontend`, `frontendHttp`, `internalFrontend`, `history`, `matching`, `worker` | 7233, 7243, 7236, 7234, 7235, 7239 | Service ports; each gRPC service's membership port is its port minus 300 (6933, 6936, …) | +| `[engine.tls]`, `[engine.auth]` | off | TLS and identity-provider tokens; see [engine security](engine-security.md) | +| `[engine.metrics]` `prometheusAddress` | off | `host:port` serving Prometheus metrics at `/metrics` | -Other tables (`[runtime]`, `[users]`, the portals) belong to other components and are ignored here. +Other tables (`[users]`, the portals) and other `[runtime]` keys belong to other components and are ignored here. ## Behavior @@ -75,8 +86,7 @@ Other tables (`[runtime]`, `[users]`, the portals) belong to other components an ## Not covered yet -Authorization and TLS for the engine's own endpoints, profiles (which services a node runs), schema creation and -upgrade on first start, Cassandra, and secure-vault secrets. +Schema creation and upgrade on first start, Cassandra, and secure-vault secrets. ## Tests @@ -86,5 +96,6 @@ upgrade on first start, Cassandra, and secure-vault secrets. | `tools/internal/enginetest/sqlite_test.go` | A real engine on a new SQLite file creates the schema, keeps a namespace and a waiting workflow across a restart, and closes the workflow after it | | `engine/internal/runtimeconfig/runtimeconfig_test.go` | What a redacted rendering cannot show: resolved environment passwords, redaction without changing the configuration, reading the file | | `engine/internal/runtimeconfig/postgresqltls_test.go` | Temporal's PostgreSQL session verifies the certificate against the host, not `serverName`; it fails once Temporal passes the name through, so the rule can go | -| `engine/internal/cli/cli_test.go` | `start --runtime-config`, the authorizer check, one configuration only, `render-config` | +| `engine/internal/runtimeconfig/security_test.go` | Profiles, TLS, auth and metrics | +| `engine/internal/cli/cli_test.go` | `start --runtime-config`, the authorizer check, one configuration only, `render-config`, profiles and the claim mapper | | `tests/ballerina/smoke` and `full`, with `--database sqlite\|postgresql\|mysql` | A real engine started from `runtime.toml` runs workflows on each database | diff --git a/docs/guides/ARCHITECTURE.md b/docs/guides/ARCHITECTURE.md index d485847..0c640f3 100644 --- a/docs/guides/ARCHITECTURE.md +++ b/docs/guides/ARCHITECTURE.md @@ -50,14 +50,14 @@ housekeeping; integration workers never connect to it. ## Profiles -One distribution; each node runs the profiles it is given (launcher, planned). +One distribution; each node runs the profiles in its `runtime.toml` (`[runtime] profiles`). | Profile | Starts | |---|---| -| `all` (default) | Everything on one machine | -| `engine` | The four Temporal services and the engine endpoint | -| `frontend`, `history`, `matching`, `worker` | One Temporal service (`frontend` includes the engine endpoint) | -| `manager` | The Manager, with the portals it serves | +| `all` (default), `engine` | Every engine service | +| `frontend` | The frontend and the internal frontend (and the engine endpoint, when it exists) | +| `history`, `matching`, `worker` | One Temporal service | +| `api` | The API server, the Manager's planned name (the engine starts nothing for it) | ## Data diff --git a/docs/guides/DEVELOPING.md b/docs/guides/DEVELOPING.md index 947e7fa..31e8419 100644 --- a/docs/guides/DEVELOPING.md +++ b/docs/guides/DEVELOPING.md @@ -85,3 +85,4 @@ Integrator. | The Dependency validation check fails on a new `go.mod` line | The module is not in WSO2's dependency registry for the `integrator` scope | Open a PR on [wso2/engineering-governance](https://github.com/wso2/engineering-governance) adding it, or drop the dependency | | The Dependency validation comment lists a `go.temporal.io` module as PENDING | Every `go.temporal.io` module goes to the registry in one request, not yet sent; until then they are reported but do not fail the check (`PENDING_MODULES` in `dependency-validation.yml`) | Nothing; remove the exception once the registry has them | | The engine exits about a minute after start with auth on and an explicit `--service` list | No process runs the internal frontend | Add `--service internal-frontend`, or run it in another process; without `--service` the engine starts it | +| Every node of a cluster with auth on exits about a minute after start | No node's `[runtime] profiles` include `frontend` (or `all`/`engine`), so nothing runs the internal frontend | Give at least one node the `frontend` profile; a node without it logs no warning, since history-only nodes are normal | diff --git a/docs/user-guide/README.md b/docs/user-guide/README.md new file mode 100644 index 0000000..dc5538d --- /dev/null +++ b/docs/user-guide/README.md @@ -0,0 +1,15 @@ +# Workflow Runtime user guide + +Pages for the people who install, configure and run the WSO2 Integration Workflow Runtime. They are the source of +the Workflow Runtime section of the WSO2 Integrator documentation and move there unchanged. + +| Page | Covers | +|---|---| +| [Workflow Runtime](workflow-runtime.md) | What the runtime is, its parts, and how integrations use it | +| [Configure the runtime](configure.md) | `conf/runtime.toml`: the database, the engine, starting and checking the configuration | +| [Secure the engine](secure-the-engine.md) | TLS, tokens from your identity provider, and the permission model | +| [Connect an integration](connect-an-integration.md) | Pointing a `ballerina/workflow` integration at the runtime | +| [Run across several nodes](scale-across-nodes.md) | Profiles, addresses, ports and load balancing | +| [Monitor the runtime](monitor.md) | Metrics, logs, and workflow visibility | +| [Troubleshoot](troubleshoot.md) | Common errors and what to do about them | +| [runtime.toml reference](reference/runtime-toml.md) | Every configuration key | diff --git a/docs/user-guide/configure.md b/docs/user-guide/configure.md new file mode 100644 index 0000000..b6a3e9e --- /dev/null +++ b/docs/user-guide/configure.md @@ -0,0 +1,86 @@ +--- +title: Configure the runtime +description: Configure the Workflow Runtime's database and engine in conf/runtime.toml, and start it. +keywords: [wso2 integrator, workflow runtime, configuration, runtime.toml, postgresql, mysql] +--- + +# Configure the runtime + +All settings live in one file, `conf/runtime.toml`. The engine reads it at start and builds the Temporal server +configuration in memory, so passwords never reach the disk. Every key is listed in the +[runtime.toml reference](reference/runtime-toml.md). + +## Choose a database + +| Database | Use | +|---|---| +| PostgreSQL 12 or later | Production | +| MySQL 8.0.17 or later | Production | +| SQLite (a file, or memory) | Trying out and development only: one connection, one node | + +The runtime uses two databases on the same server: `temporal` (workflow state) and `temporal_visibility` +(search). Create them and their schemas once with the schema tool shipped next to the engine: + +```bash +export SQL_PASSWORD='' # read by the tool, so the password stays out of the command line +sql() { bin/workflow-engine-sql --plugin postgres12 --ep db.example.com -p 5432 -u workflow "$@"; } +sql --db temporal create-database +sql --db temporal_visibility create-database +sql --db temporal setup-schema -v 0.0 +sql --db temporal update-schema --schema-name postgresql/v12/temporal +sql --db temporal_visibility setup-schema -v 0.0 +sql --db temporal_visibility update-schema --schema-name postgresql/v12/visibility +``` + +For MySQL use `--plugin mysql8`, port 3306 and the schema names `mysql/v8/temporal` and `mysql/v8/visibility`. + +## Write the configuration + +1. Set the `[database]` table: + + ```toml + [database] + type = "postgresql" + host = "db.example.com" + user = "workflow" + password = "$env{WORKFLOW_DB_PASSWORD}" + ``` + + `$env{NAME}` reads the password from an environment variable at start. Use `[database.tls]` when the server + requires TLS. + +2. Leave `[engine]` at its defaults on a single machine. To accept connections from other machines, listen on + every interface and name the address clients use: + + ```toml + [engine] + bindAddress = "0.0.0.0" + broadcastAddress = "10.0.0.5" + ``` + +3. For production, add `[engine.tls]` and `[engine.auth]` ([Secure the engine](secure-the-engine.md)). + +:::caution +`historyShards` (default 512; 1 for SQLite) cannot change after the first start. Decide it before the first start. +::: + +## Check the configuration + +Print the configuration the engine generates, with the password hidden: + +```bash +WORKFLOW_DB_PASSWORD= bin/workflow-engine render-config --runtime-config conf/runtime.toml +``` + +The engine checks every key before it starts. Unknown keys (usually typos), invalid ports, missing files and unset +`$env{}` variables stop it with a message naming the key. + +## Start the engine + +```bash +export WORKFLOW_DB_PASSWORD= +bin/workflow-engine start --runtime-config conf/runtime.toml +``` + +Without `[engine.auth]` the engine refuses to start. Add `--allow-no-auth` only for development on your own +machine; never expose such an engine on a network. diff --git a/docs/user-guide/connect-an-integration.md b/docs/user-guide/connect-an-integration.md new file mode 100644 index 0000000..a686242 --- /dev/null +++ b/docs/user-guide/connect-an-integration.md @@ -0,0 +1,48 @@ +--- +title: Connect an integration +description: Point a ballerina/workflow integration at the Workflow Runtime. +keywords: [wso2 integrator, workflow runtime, ballerina workflow, connect, config.toml] +--- + +# Connect an integration + +An integration that uses the `ballerina/workflow` module connects to the runtime with a few lines in its +`Config.toml`. + +## Before you start + +- The namespace exists, with the `WorkflowKind` search attribute `ballerina/workflow` uses. Create both once with + the Temporal CLI (an `admin` token is needed when auth is on): + + ```bash + OPTS="--address engine.example.com:7233 --tls-ca-path ca.pem --api-key $ADMIN_TOKEN" + temporal operator namespace create --namespace orders --retention 720h $OPTS + temporal operator search-attribute create --namespace orders --name WorkflowKind --type Keyword $OPTS + ``` + + The integration registers `WorkflowKind` itself when it is missing, but its first workflow can then be refused for + a few seconds until the engine sees the new attribute. + +- The integration has a token with `write` in that namespace + ([Secure the engine](secure-the-engine.md)), and the CA certificate that signed the engine's certificate. + +## Configure the integration + +```toml +[ballerina.workflow] +mode = "SELF_HOSTED" +url = "engine.example.com:7233" +namespace = "orders" +authApiKey = "" +authCaCert = "certs/engine-ca.pem" +``` + +Start the integration. Its workers connect at start; a wrong address, an untrusted certificate or a token without +the needed roles stops them with an error naming the cause. + +:::tip +For an engine started with `--allow-no-auth` on your own machine, leave out `authApiKey` and `authCaCert`. +::: + +Tokens expire. Give the integration a token whose lifetime covers its run, or a way to refresh it, per your +identity provider's guidance for client-credentials tokens. diff --git a/docs/user-guide/monitor.md b/docs/user-guide/monitor.md new file mode 100644 index 0000000..b247b3d --- /dev/null +++ b/docs/user-guide/monitor.md @@ -0,0 +1,34 @@ +--- +title: Monitor the runtime +description: Metrics, logs and workflow visibility for the Workflow Runtime. +keywords: [wso2 integrator, workflow runtime, monitoring, prometheus, metrics, logs, icp] +--- + +# Monitor the runtime + +## Metrics + +Serve Prometheus metrics from each node: + +```toml +[engine.metrics] +prometheusAddress = "0.0.0.0:9464" +``` + +Scrape `http://:9464/metrics`. The metrics are Temporal's server metrics (requests, latencies, task queue +backlogs, persistence calls). + +## Logs + +The engine logs JSON to standard output at `logLevel` (`info` by default; `debug`, `warn` or `error`). Collect it +with your platform's log collector. Refused calls are logged with the reason, which the caller does not see. + +## Workflows + +Use the Integration Control Plane (ICP) to see integrations' workflows, their status and history. The Temporal CLI +works too, with a token that has `read` in the namespace: + +```bash +temporal workflow list --namespace orders --address engine.example.com:7233 \ + --tls-ca-path ca.pem --api-key "$TOKEN" +``` diff --git a/docs/user-guide/reference/runtime-toml.md b/docs/user-guide/reference/runtime-toml.md new file mode 100644 index 0000000..fd70e15 --- /dev/null +++ b/docs/user-guide/reference/runtime-toml.md @@ -0,0 +1,108 @@ +--- +title: runtime.toml reference +description: Every key of the Workflow Runtime's conf/runtime.toml. +keywords: [wso2 integrator, workflow runtime, runtime.toml, configuration, reference] +--- + +# runtime.toml reference + +Unknown keys in `[engine]` and `[database]` stop the engine at start. Tables not listed here belong to other +components and are ignored by the engine. + +## `[runtime]` + +| Key | Default | Description | +|---|---|---| +| `profiles` | `["all"]` | Services this node runs: `all`, `engine`, `frontend`, `history`, `matching`, `worker`; `api` is reserved for the API server. Profiles combine. See [Run across several nodes](../scale-across-nodes.md) | + +## `[engine]` + +| Key | Default | Description | +|---|---|---| +| `bindAddress` | `127.0.0.1` | IP address every service listens on | +| `broadcastAddress` | `bindAddress` | IP address other nodes and clients use; required when `bindAddress` is `0.0.0.0` | +| `historyShards` | `512` (`1` for SQLite) | History shards; cannot change after the first start | +| `logLevel` | `info` | `debug`, `info`, `warn` or `error` | + +### `[engine.ports]` + +| Key | Default | Description | +|---|---|---| +| `frontend` | `7233` | gRPC port integrations connect to | +| `frontendHttp` | `7243` | HTTP API port of the frontend | +| `internalFrontend` | `7236` | Frontend for the engine's own services | +| `history` | `7234` | History service | +| `matching` | `7235` | Matching service | +| `worker` | `7239` | Worker service | + +Each gRPC service also uses a membership port 300 below its port (6933, 6936, 6934, 6935, 6939). + +### `[engine.tls]` + +| Key | Default | Description | +|---|---|---| +| `certFile`, `keyFile` | off | Frontend certificate and key (PEM); both or neither | +| `clientCaFile` | off | Require client certificates signed by this CA | + +### `[engine.tls.internode]` + +| Key | Default | Description | +|---|---|---| +| `enabled` | `false` | TLS between the engine's services and nodes | +| `certFile`, `keyFile` | the frontend's | Certificate the services present to each other | +| `caFile` | required when enabled | CA that signs the internode certificates | +| `serverName` | the certificate's DNS name, when it has exactly one | Name the nodes verify in each other's certificates; required when the certificate has no DNS name or several, and must be a name the certificate carries | + +### `[engine.auth]` + +`type = "jwt"` needs `[engine.tls]`, and `[engine.tls.internode]` when `bindAddress` is not a loopback address. + +| Key | Default | Description | +|---|---|---| +| `type` | `none` | `jwt` to require tokens; `none` needs `--allow-no-auth` | +| `jwksUrls` | discovered from `issuer` | Your identity provider's key set URLs (https; plain http only to a loopback host); set them when the provider has no OpenID Connect discovery document | +| `keyRefreshInterval` | `1m` | How often the key set is fetched again (a duration, at least `1s`) | +| `issuer` | | Required `iss`, exactly as tokens carry it; also where the key set is discovered over https (`/.well-known/openid-configuration`). `issuer` or `jwksUrls` is required for `jwt` | +| `audience` | not checked | Required value in `aud` | +| `subjectClaim` | `sub` | Claim naming the caller | +| `rolesClaim` | `permissions` | Claim holding groups, roles or scopes; a dotted path reads a nested claim | +| `valueRegex` | | Without rules: a regex with the named groups `namespace` and `role` | +| `leewaySeconds` | `0` | Clock skew allowed on `exp`, `nbf` and `iat` | + +### `[[engine.auth.rules]]` + +| Key | Description | +|---|---| +| `value` | A value of the roles claim, such as a group name | +| `namespace` | A namespace, or `*` for every namespace | +| `role` | `read`, `write` or `admin` (an integration needs `write`) | + +### `[engine.metrics]` + +| Key | Default | Description | +|---|---|---| +| `prometheusAddress` | off | `host:port` serving Prometheus metrics at `/metrics` | + +## `[database]` + +| Key | Default | Description | +|---|---|---| +| `type` | required | `postgresql`, `mysql` or `sqlite` | +| `host` | required for PostgreSQL and MySQL | Database server host | +| `port` | `5432` / `3306` | Database server port | +| `user`, `password` | empty | Credentials; `password` is a literal or `$env{NAME}` | +| `name` | `temporal` | Workflow database | +| `visibilityName` | `temporal_visibility` | Visibility (search) database; must differ from `name` | +| `path` | | SQLite only: the database file | +| `inMemory` | `false` | SQLite only: keep everything in memory | +| `maxConns` | `20` (`1` for SQLite) | Connections per database; must be `1` for an in-memory SQLite database | + +### `[database.tls]` + +| Key | Default | Description | +|---|---|---| +| `enabled` | `false` | TLS to the database server (PostgreSQL and MySQL; refused for SQLite) | +| `caFile` | system roots | CA that signs the server's certificate (for Amazon RDS, its certificate bundle) | +| `certFile`, `keyFile` | | Client certificate, when the server requires one | +| `serverName` | the host | MySQL only: name to verify in the server's certificate. PostgreSQL always verifies `host`, so set `host` to the name on the certificate | +| `enableHostVerification` | `true` | Verify the server's certificate and host name; `false` turns verification off | diff --git a/docs/user-guide/scale-across-nodes.md b/docs/user-guide/scale-across-nodes.md new file mode 100644 index 0000000..bd98072 --- /dev/null +++ b/docs/user-guide/scale-across-nodes.md @@ -0,0 +1,49 @@ +--- +title: Run across several nodes +description: Split the Workflow Runtime's services across machines with profiles. +keywords: [wso2 integrator, workflow runtime, profiles, high availability, scaling, cluster] +--- + +# Run across several nodes + +The same distribution runs on one machine or many. Each node runs the profiles you give it, and nodes find each +other through the shared database: there is no list of peers to maintain. + +## Profiles + +| Profile | Runs | +|---|---| +| `all` (default), `engine` | Every engine service | +| `frontend` | The frontend integrations connect to, and the internal frontend the engine's own services use | +| `history` | Workflow state and timers; the busiest tier | +| `matching` | Task queues | +| `worker` | The engine's housekeeping | + +## Set up the nodes + +1. Use the same `conf/runtime.toml` on every node (same `[database]`, same `historyShards`, same `[engine.auth]`). +2. On each node, set its profiles and its own address: + + ```toml + [runtime] + profiles = ["history", "matching"] + + [engine] + bindAddress = "0.0.0.0" + broadcastAddress = "10.0.1.21" # this node's IP address + ``` + +3. Open the ports between nodes: the service ports (7233 to 7239 by default) and their membership ports (6933 to + 6939). Integrations need only 7233. With `[engine.auth]`, turn on `[engine.tls.internode]` on every node: the + engine refuses to start without it, because the internal ports accept calls without a token + ([Secure the engine](secure-the-engine.md#turn-on-tls)). +4. Put a load balancer in front of the frontend nodes. Integrations keep long-lived gRPC connections, so use a + TCP (layer 4) load balancer, such as an AWS Network Load Balancer. + +A starting point: two frontend nodes, three history nodes, two matching nodes and one worker node. Grow history +with workflow throughput and frontend with the number of connected workers. + +:::info +`--service frontend --service history` on the command line overrides the profiles for one start, including on a +node whose profiles name only `api`. +::: diff --git a/docs/user-guide/secure-the-engine.md b/docs/user-guide/secure-the-engine.md new file mode 100644 index 0000000..f156730 --- /dev/null +++ b/docs/user-guide/secure-the-engine.md @@ -0,0 +1,149 @@ +--- +title: Secure the engine +description: Turn on TLS and your identity provider's tokens, and map groups to namespace roles. +keywords: [wso2 integrator, workflow runtime, security, tls, jwt, identity provider, permissions] +--- + +# Secure the engine + +A production engine needs two things: TLS on its frontend (port 7233), and tokens from your identity provider on +every call. Without `[engine.auth]` the engine refuses to start; `--allow-no-auth` exists for development on your +own machine only. + +## The permission model + +The runtime stores no users, groups or roles. Your identity provider owns them and puts them in the tokens it +issues; `conf/runtime.toml` says which group, role or scope gives which permission in which namespace. + +| Role | Allows | +|---|---| +| `read` | List and describe workflows and namespaces | +| `write` | `read`, plus start, signal, cancel and terminate workflows, and poll task queues and complete tasks: what an integration (its workers and the code that starts workflows) needs | +| `admin` | Everything, including creating and changing namespaces | + +There is no separate worker role: Temporal's authorizer needs `write` for a worker to poll and complete tasks, so a +rule asking for `worker` is refused at start. + +A role in namespace `*` applies to every namespace. Roles add up: a caller in two groups gets both roles. + +| Caller | Typical grant | +|---|---| +| An integration (its workers and the code that starts workflows) | `write` in its namespace, through a client-credentials token | +| An operator or a CI pipeline | `admin` in `*`, or in one namespace | +| Auditors and dashboards | `read` | + +## Turn on TLS + +1. Get a certificate and key for the address clients use (its DNS name or IP must be in the certificate). +2. Add them: + + ```toml + [engine.tls] + certFile = "conf/certs/engine.crt" + keyFile = "conf/certs/engine.key" + ``` + +3. To also require client certificates (mutual TLS), add `clientCaFile = "conf/certs/clients-ca.pem"`. Client + certificates authenticate the connection; permissions still come from the token. +4. When the engine listens beyond this machine (`bindAddress` is not `127.0.0.1`), turn on mutual TLS between + its services and nodes. It is required with `[engine.auth]`: + + ```toml + [engine.tls.internode] + enabled = true + certFile = "conf/certs/node.crt" # the frontend's certificate when left out + keyFile = "conf/certs/node.key" + caFile = "conf/certs/internode-ca.pem" + ``` + + Issue the internode certificates with a DNS name every node shares, such as `workflow-nodes.internal`. The nodes + verify that name in each other's certificates. When the certificate has that one DNS name, the engine uses it; when + it also carries the node's own name, set `serverName = "workflow-nodes.internal"`. The engine checks that the + certificate carries the name you set. A certificate with only IP addresses needs reissuing with the shared name: + each node's IP differs, so no one address is in every node's certificate. + + :::caution + Only port 7233 is for integrations. The internal frontend (7236 by default) gives the engine's own services + system access without a token, and the other service ports (7234, 7235, 7239) and membership ports (6933 to + 6939) are for the engine's nodes. Internode mutual TLS, membership included, lets only holders of a certificate + from the internode CA reach them; also allow them only between the engine's nodes in your firewall or security + groups. + ::: + +## Turn on your identity provider's tokens + +Any OpenID Connect provider works: WSO2 Identity Server, Asgardeo, Amazon Cognito, Microsoft Entra ID, Okta, +Keycloak, Auth0 and others. + +1. Find your provider's issuer (the `iss` of its tokens) and the claim that carries groups, roles or scopes. +2. Add `[engine.auth]` and one rule per group. With the issuer alone, the engine reads the provider's OpenID + Connect discovery document (`/.well-known/openid-configuration`) at start to find its key set: + + ```toml + [engine.auth] + type = "jwt" + issuer = "https://idp.example.com/oauth2/token" + audience = "workflow-engine" # optional + rolesClaim = "groups" + + [[engine.auth.rules]] + value = "workflow-admins" + namespace = "*" + role = "admin" + + [[engine.auth.rules]] + value = "orders-integration" + namespace = "orders" + role = "write" + ``` + + `[engine.auth]` needs `[engine.tls]`: the engine refuses to accept tokens in plain text. + + :::caution + `issuer` alone does not limit tokens to this engine: any unexpired token the provider issued, including tokens + for its other applications, passes, and its groups grant the roles your rules map. Set `audience` to the value + your provider puts in tokens for the engine (an API or resource identifier), or map rules only from groups that + no other application's tokens carry. With neither `issuer` nor `audience`, the engine logs a warning at start. + ::: + + The key set is fetched over https, and so is the discovery document; the engine refuses a plain `http` issuer, + `jwksUrls` entry or discovered `jwks_uri` unless it points at the same machine, because keys sent in plain text + could be replaced on the way. A redirect to plain `http` is refused too, at start and on every key refresh. The + issuer must match the discovery document's `issuer` exactly, trailing slash + included. + +3. Restart the engine. + +| Provider | `rolesClaim` | Notes | +|---|---|---| +| WSO2 Identity Server | `roles` or `groups` | Issuer `https://:9443/oauth2/token`. Use JWT access tokens and add the roles or groups claim to the application's access token attributes | +| Asgardeo | `roles` or `groups` | Issuer `https://api.asgardeo.io/t//oauth2/token`. Use JWT access tokens and add the claim to the application's access token attributes | +| Amazon Cognito | `cognito:groups` | Issuer `https://cognito-idp..amazonaws.com/` | +| Microsoft Entra ID | `roles` (app roles) or `groups` | Issuer `https://login.microsoftonline.com//v2.0` | +| Okta | `groups` (add a groups claim to the authorization server) | | +| Keycloak | `realm_access.roles` | A dotted path reads a nested claim | +| Scopes from any provider | `scope` or `scp` | Space- or comma-separated strings work | +| Any other OpenID Connect provider | The claim it puts groups or roles in | Set `issuer`; the key set is discovered | + +If the provider has no discovery document, or the engine cannot reach it at start, set the key set URL yourself +with `jwksUrls = ["https://idp.example.com/oauth2/jwks"]`; discovery is then skipped. + +If your provider already issues values that name the namespace, skip the rules: `default:write` works as is, and +`valueRegex` (with the named groups `namespace` and `role`) parses other shapes such as `wf-default-write`. + +:::info +Tokens must be signed with RS256 or ES256, and must carry an expiry (`exp`) and a subject (`sub`, or the claim +named by `subjectClaim`). +::: + +## Check it + +With the Temporal CLI and a token from your provider: + +```bash +temporal operator namespace list --address engine.example.com:7233 \ + --tls-ca-path ca.pem --api-key "$TOKEN" +``` + +A token that maps to no role gets `Request unauthorized`; the engine log says why (expired, wrong issuer, unknown +key, no matching group). diff --git a/docs/user-guide/troubleshoot.md b/docs/user-guide/troubleshoot.md new file mode 100644 index 0000000..654cb6d --- /dev/null +++ b/docs/user-guide/troubleshoot.md @@ -0,0 +1,31 @@ +--- +title: Troubleshoot +description: Common Workflow Runtime errors and how to fix them. +keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] +--- + +# Troubleshoot + +| Message | Cause | Fix | +|---|---|---| +| `no authorizer configured; set one or pass --allow-no-auth for development` | No `[engine.auth]` | Configure your identity provider ([Secure the engine](secure-the-engine.md)), or use `--allow-no-auth` on your own machine only | +| `unknown runtime configuration keys: engine.logLvl` | A typo in `runtime.toml` | Correct the key; see the [reference](reference/runtime-toml.md) | +| `database.password refers to environment variable WORKFLOW_DB_PASSWORD, which is not set` | The variable is missing in the engine's environment | Export it, or set it in the service's environment file | +| `engine.broadcastAddress is required when engine.bindAddress is 0.0.0.0` | Listening on every interface without saying which address others use | Set `broadcastAddress` to this node's IP | +| `database.tls is not supported for a sqlite database` | `[database.tls]` with `type = "sqlite"` | Remove `[database.tls]`; SQLite is a local file | +| `database.tls.serverName is not supported for a postgresql database` | `serverName` with `type = "postgresql"`, which cannot use it | Remove `serverName` and set `host` to the DNS name on the database certificate | +| `engine.tls.certFile: ... no such file or directory` | A wrong path | Paths are relative to the directory the engine starts in | +| `unable to create the claim mapper: unable to discover the identity provider's key set: ...` | The engine cannot read `/.well-known/openid-configuration`, or it names another issuer (a trailing slash counts) | Check `issuer` (it must equal the tokens' `iss` exactly) and the network, or set `jwksUrls` | +| `engine.auth.jwksUrls: "http://..." must use https` (or the issuer, or a discovered `jwks_uri`) | A key set or discovery document over plain http to another host | Use the provider's https URL | +| `refused a redirect: "http://..." must use https` (at start, or logged as `unable to refresh the token keys`) | The provider's https URL redirects to plain http | Configure the URL the redirect ends at, if it is https, or fix the provider's redirect | +| `runtime.profiles names no engine service; this node runs only other components` | `profiles = ["api"]` and no `--service` | Add an engine profile, or name the services with `--service` | +| `engine.metrics.prometheusAddress "..." has an invalid port` | A port that is not a number from 0 to 65535 | Correct the port | +| `engine.auth.type = "jwt" needs engine.tls` | Tokens without TLS | Add `[engine.tls]` ([Secure the engine](secure-the-engine.md)) | +| `engine.tls.internode.serverName is required: ... has no DNS name` (or `several DNS names`) | The engine cannot tell which name every node's certificate shares | Set `serverName` to the shared name, or reissue the certificates with one DNS name every node shares | +| `engine.tls.internode.serverName "..." is not a name in ...` | A typo, or a certificate issued without that name | Correct `serverName`, or reissue the certificate with it | +| With `[engine.auth]` on, every node exits about a minute after start | No node runs the `frontend` profile, which brings the internal frontend Temporal's own services use | Give at least one node `frontend`, `engine` or `all` in `[runtime] profiles` ([Run across several nodes](scale-across-nodes.md)) | +| `engine.auth needs engine.tls.internode when engine.bindAddress is ...` | Auth on an engine reachable from other machines without mutual TLS between its nodes | Add `[engine.tls.internode]` ([Secure the engine](secure-the-engine.md#turn-on-tls)) | +| `rule for "...": grant write, not worker` | A rule with `role = "worker"` | Use `write`; it lets an integration's workers poll | +| Client: `Request unauthorized` | The token maps to no role, or failed a check | Read the engine log: it names the reason (expired, issuer, unknown key, no matching group); check `rolesClaim` and the rules | +| Client: `x509: certificate is not trusted` or `certificate is valid for ..., not ...` | The client does not trust the CA, or the certificate lacks the address the client uses | Give the client the CA (`authCaCert`, `--tls-ca-path`); reissue the certificate with the right DNS name or IP | +| `unable to read DB schema version` or `database "temporal" does not exist` | The databases or schemas are missing | Create them ([Configure the runtime](configure.md#choose-a-database)) | diff --git a/docs/user-guide/workflow-runtime.md b/docs/user-guide/workflow-runtime.md new file mode 100644 index 0000000..b1cce4f --- /dev/null +++ b/docs/user-guide/workflow-runtime.md @@ -0,0 +1,37 @@ +--- +title: Workflow Runtime +description: What the WSO2 Integration Workflow Runtime is and how integrations use it. +keywords: [wso2 integrator, workflow runtime, durable workflows, temporal] +--- + +# Workflow Runtime + +The Workflow Runtime runs the durable workflows of WSO2 Integrator. Integrations that use the `ballerina/workflow` +module connect to it, start workflows, and run their workflow and activity code; the runtime keeps every +workflow's state, timers, retries and history, so a workflow survives restarts and can wait for days. + +The runtime's engine is built from the open-source Temporal server and is supported by WSO2. You configure it with +one file, `conf/runtime.toml`. + +## Parts + +| Part | What it does | +|---|---| +| Engine (`workflow-engine`) | Temporal's services: the frontend integrations connect to (port 7233), history, matching, and a worker for the engine's own housekeeping | +| Database | Workflow state and history (the workflow database) and workflow search (the visibility database): PostgreSQL or MySQL in production, SQLite for trying out | +| Your identity provider | Issues the tokens integrations and operators present; the runtime keeps no users or roles of its own | + +## How integrations use it + +1. An integration's `Config.toml` names the runtime's address, a namespace, and its token + ([Connect an integration](connect-an-integration.md)). +2. At start, the integration's workers connect to the engine and wait for work on their task queues. +3. The integration starts workflows; the engine schedules each step on a worker and records the result. + +Namespaces separate teams or environments. Each has a retention period after which closed workflows are deleted. + +## Where to go next + +- [Configure the runtime](configure.md) +- [Secure the engine](secure-the-engine.md) +- [Run across several nodes](scale-across-nodes.md) diff --git a/engine/go.mod b/engine/go.mod index 44f1545..97712d1 100644 --- a/engine/go.mod +++ b/engine/go.mod @@ -6,6 +6,7 @@ toolchain go1.26.10 require ( github.com/go-viper/mapstructure/v2 v2.5.0 + github.com/golang-jwt/jwt/v5 v5.3.1 github.com/jackc/pgx/v5 v5.10.0 github.com/jmoiron/sqlx v1.4.0 github.com/knadh/koanf/parsers/toml/v2 v2.2.2 diff --git a/engine/go.sum b/engine/go.sum index aaba569..4ba87fa 100644 --- a/engine/go.sum +++ b/engine/go.sum @@ -212,6 +212,8 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI= github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= diff --git a/engine/internal/cli/cli.go b/engine/internal/cli/cli.go index 3c301ab..dfe7e30 100644 --- a/engine/internal/cli/cli.go +++ b/engine/internal/cli/cli.go @@ -21,12 +21,15 @@ package cli import ( + "context" "errors" "flag" "fmt" "io" "os" + "slices" "strings" + "time" "go.temporal.io/server/common/authorization" "go.temporal.io/server/common/config" @@ -39,13 +42,19 @@ import ( "go.temporal.io/server/temporal" "github.com/wso2/integration-workflow-runtime/engine/internal/runtimeconfig" + "github.com/wso2/integration-workflow-runtime/engine/plugins/jwtclaims" ) const usageText = `usage: workflow-engine version workflow-engine start (--runtime-config | --config-file ) [--service ]... [--allow-no-auth] workflow-engine render-config --runtime-config ` -type serverFactory func(opts ...temporal.ServerOption) (temporal.Server, error) +// serverFactory builds the server for the services this node runs; tests record the services. +type serverFactory func(services []string, opts ...temporal.ServerOption) (temporal.Server, error) + +func newTemporalServer(services []string, opts ...temporal.ServerOption) (temporal.Server, error) { + return temporal.NewServer(append(opts, temporal.ForServices(services))...) +} type command struct { version string @@ -56,7 +65,7 @@ type command struct { // Main runs the command with the given arguments and returns the process exit code. func Main(version string, args []string) int { - c := command{version: version, stdout: os.Stdout, stderr: os.Stderr, newServer: temporal.NewServer} + c := command{version: version, stdout: os.Stdout, stderr: os.Stderr, newServer: newTemporalServer} return c.run(args) } @@ -110,13 +119,21 @@ func (c command) start(args []string) error { } return err } - cfg, err := loadConfig(*runtimeConfig, *configFile) + cfg, rt, err := loadConfig(*runtimeConfig, *configFile) if err != nil { return err } - if len(services) == 0 { + explicit := len(services) > 0 + switch { + case explicit: + case rt != nil: + services = rt.Services + default: services = defaultServices(cfg) } + if len(services) == 0 { + return runtimeconfig.ErrNoServices + } logger := log.NewZapLogger(log.BuildZapLogger(cfg.Log)) authorizer, err := authorization.GetAuthorizerFromConfig(&cfg.Global.Authorization) @@ -136,7 +153,7 @@ func (c command) start(args []string) error { if !authorization.IsNoopAuthorizer(authorizer) && !hasInternalFrontend(cfg) { return errors.New("an authorizer needs the internal frontend; add services.internal-frontend to the configuration") } - claimMapper, err := authorization.GetClaimMapperFromConfig(&cfg.Global.Authorization, logger) + claimMapper, err := newClaimMapper(cfg, rt, logger) if err != nil { return fmt.Errorf("unable to create the claim mapper: %w", err) } @@ -145,15 +162,24 @@ func (c command) start(args []string) error { return fmt.Errorf("unable to create the audience mapper: %w", err) } - server, err := c.newServer( - temporal.ForServices(services), + // Profiles keep the internal frontend with the frontend; a --service list can drop it, which another node may cover. + if explicit && !authorization.IsNoopAuthorizer(authorizer) && + !slices.Contains(services, string(primitives.InternalFrontendService)) { + logger.Warn("--service leaves out internal-frontend; with an authorizer on, another node must run it, or " + + "Temporal's services cannot reach the frontend and the engine stops about a minute after start") + } + opts := []temporal.ServerOption{ temporal.WithConfig(cfg), temporal.WithLogger(logger), temporal.InterruptOn(temporal.InterruptCh()), temporal.WithAuthorizer(authorizer), temporal.WithClaimMapper(func(*config.Config) authorization.ClaimMapper { return claimMapper }), temporal.WithAudienceGetter(func(*config.Config) authorization.JWTAudienceMapper { return audienceMapper }), - ) + } + if rt != nil && rt.DynamicConfig != nil { + opts = append(opts, temporal.WithDynamicConfigClient(rt.DynamicConfig)) + } + server, err := c.newServer(services, opts...) if err != nil { return fmt.Errorf("unable to create the server: %w", err) } @@ -170,11 +196,11 @@ func (c command) renderConfig(args []string) error { if *runtimeConfig == "" { return errors.New("--runtime-config is required") } - cfg, err := runtimeconfig.Load(*runtimeConfig) + rt, err := runtimeconfig.Load(*runtimeConfig) if err != nil { return err } - rendered, err := runtimeconfig.Render(cfg) + rendered, err := runtimeconfig.Render(&rt.Temporal) if err != nil { return fmt.Errorf("unable to render the configuration: %w", err) } @@ -182,22 +208,56 @@ func (c command) renderConfig(args []string) error { return err } -// loadConfig returns the Temporal configuration from exactly one of a runtime.toml and a Temporal YAML file. -func loadConfig(runtimeConfig, configFile string) (*config.Config, error) { +// loadConfig returns the Temporal configuration from exactly one of a runtime.toml and a Temporal YAML file; the +// runtime settings are nil for a Temporal YAML file, which is used as is. +func loadConfig(runtimeConfig, configFile string) (*config.Config, *runtimeconfig.Runtime, error) { switch { case runtimeConfig != "" && configFile != "": - return nil, errors.New("pass either --runtime-config or --config-file, not both") + return nil, nil, errors.New("pass either --runtime-config or --config-file, not both") case runtimeConfig != "": - return runtimeconfig.Load(runtimeConfig) + rt, err := runtimeconfig.Load(runtimeConfig) + if err != nil { + return nil, nil, err + } + return &rt.Temporal, rt, nil case configFile != "": cfg, err := config.Load(config.WithConfigFile(configFile)) if err != nil { - return nil, fmt.Errorf("unable to load configuration: %w", err) + return nil, nil, fmt.Errorf("unable to load configuration: %w", err) } - return cfg, nil + return cfg, nil, nil default: - return nil, errors.New("--runtime-config or --config-file is required") + return nil, nil, errors.New("--runtime-config or --config-file is required") + } +} + +// keyFetchTimeout bounds each discovery or key set request. +const keyFetchTimeout = 15 * time.Second + +// newClaimMapper builds the identity-provider mapper that runtime.toml's [engine.auth] asks for, or Temporal's own. +func newClaimMapper(cfg *config.Config, rt *runtimeconfig.Runtime, logger log.Logger) (authorization.ClaimMapper, error) { + if cfg.Global.Authorization.ClaimMapper != runtimeconfig.ClaimMapperName { + return authorization.GetClaimMapperFromConfig(&cfg.Global.Authorization, logger) + } + if rt == nil || rt.Auth == nil { + return nil, fmt.Errorf("claim mapper %q is configured only through runtime.toml [engine.auth]", + runtimeconfig.ClaimMapperName) + } + client := jwtclaims.Client(keyFetchTimeout) + if len(cfg.Global.Authorization.JWTKeyProvider.KeySourceURIs) == 0 { + jwks, err := jwtclaims.Discover(context.Background(), client, rt.Auth.Issuer) + if err != nil { + return nil, fmt.Errorf("unable to discover the identity provider's key set: %w", err) + } + cfg.Global.Authorization.JWTKeyProvider.KeySourceURIs = []string{jwks} + } + if rt.Auth.Issuer == "" && rt.Auth.Audience == "" { + logger.Warn("engine.auth checks neither issuer nor audience: every unexpired token the key set signs is " + + "accepted, including tokens issued for other applications; set issuer or audience") } + kp := cfg.Global.Authorization.JWTKeyProvider + keys := jwtclaims.NewKeySet(kp.KeySourceURIs, kp.RefreshInterval, client, logger) + return jwtclaims.New(keys, *rt.Auth) } // defaultServices is Temporal's default set plus the internal frontend when the configuration defines one. diff --git a/engine/internal/cli/cli_test.go b/engine/internal/cli/cli_test.go index 596063f..adf528b 100644 --- a/engine/internal/cli/cli_test.go +++ b/engine/internal/cli/cli_test.go @@ -19,13 +19,21 @@ package cli import ( "bytes" "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" "path/filepath" "slices" "strings" "testing" "go.temporal.io/server/common/config" + "go.temporal.io/server/common/log" "go.temporal.io/server/temporal" + + "github.com/wso2/integration-workflow-runtime/engine/internal/runtimeconfig" + "github.com/wso2/integration-workflow-runtime/engine/plugins/jwtclaims" ) const minimalConfig = "testdata/minimal.yaml" @@ -48,7 +56,7 @@ func newTestCommand(server temporal.Server, factoryErr error) (command, *bytes.B version: "9.9.9-test", stdout: stdout, stderr: stderr, - newServer: func(...temporal.ServerOption) (temporal.Server, error) { + newServer: func([]string, ...temporal.ServerOption) (temporal.Server, error) { return server, factoryErr }, } @@ -287,3 +295,116 @@ func TestRenderConfigErrors(t *testing.T) { t.Fatal("render-config accepted an unknown flag") } } + +func TestStartWithIdentityProviderAuth(t *testing.T) { + server := &fakeServer{} + c, _, stderr := newTestCommand(server, nil) + if code := c.run([]string{"start", "--runtime-config", "testdata/runtime-auth.toml"}); code != 0 || !server.started { + t.Fatalf("exit code = %d, started = %v, stderr = %s", code, server.started, stderr.String()) + } +} + +func TestNewClaimMapper(t *testing.T) { + logger := log.NewNoopLogger() + rt, err := runtimeconfig.Load("testdata/runtime-auth.toml") + if err != nil { + t.Fatal(err) + } + if !slices.Equal(rt.Services, []string{"frontend", "internal-frontend", "history"}) { + t.Fatalf("services = %v", rt.Services) + } + m, err := newClaimMapper(&rt.Temporal, rt, logger) + if err != nil { + t.Fatal(err) + } + if _, ok := m.(*jwtclaims.Mapper); !ok { + t.Fatalf("mapper = %T, want *jwtclaims.Mapper", m) + } + if _, err := newClaimMapper(&rt.Temporal, nil, logger); err == nil || !strings.Contains(err.Error(), "only through runtime.toml") { + t.Fatalf("mapper without runtime settings: %v", err) + } + plain := &config.Config{Global: config.Global{Authorization: config.Authorization{ClaimMapper: "default"}}} + if m, err := newClaimMapper(plain, nil, logger); err != nil || m == nil { + t.Fatalf("Temporal's default mapper: %v, %v", m, err) + } +} + +func TestNewClaimMapperDiscoversTheKeySet(t *testing.T) { + var base string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = fmt.Fprintf(w, `{"issuer":%q,"jwks_uri":%q}`, base+"/oauth2/token", base+"/oauth2/jwks") + })) + defer srv.Close() + base = srv.URL + write := func(issuer string) string { + p := filepath.Join(t.TempDir(), "runtime.toml") + cert, _ := filepath.Abs("testdata/certs/engine.crt") + key, _ := filepath.Abs("testdata/certs/engine.key") + toml := "[engine.tls]\ncertFile = \"" + cert + "\"\nkeyFile = \"" + key + "\"\n" + + "[engine.auth]\ntype = \"jwt\"\nissuer = \"" + issuer + "\"\n[database]\ntype = \"sqlite\"\ninMemory = true\n" + if err := os.WriteFile(p, []byte(toml), 0o600); err != nil { + t.Fatal(err) + } + return p + } + rt, err := runtimeconfig.Load(write(base + "/oauth2/token")) + if err != nil { + t.Fatal(err) + } + if _, err := newClaimMapper(&rt.Temporal, rt, log.NewNoopLogger()); err != nil { + t.Fatal(err) + } + if got := rt.Temporal.Global.Authorization.JWTKeyProvider.KeySourceURIs; !slices.Equal(got, []string{base + "/oauth2/jwks"}) { + t.Fatalf("key set = %v", got) + } + rt, err = runtimeconfig.Load(write("http://127.0.0.1:1/oauth2/token")) + if err != nil { + t.Fatal(err) + } + if _, err := newClaimMapper(&rt.Temporal, rt, log.NewNoopLogger()); err == nil || + !strings.Contains(err.Error(), "unable to discover the identity provider's key set") { + t.Fatalf("unreachable provider: %v", err) + } +} + +func TestServicesReachTheServerFactory(t *testing.T) { + for name, tt := range map[string]struct { + args []string + want []string + }{ + "profiles": {[]string{"--runtime-config", "testdata/runtime-auth.toml"}, []string{"frontend", "internal-frontend", "history"}}, + "service override": {[]string{"--runtime-config", "testdata/runtime-auth.toml", "--service", "worker"}, []string{"worker"}}, + "default profile": {[]string{"--runtime-config", "testdata/runtime-sqlite.toml", "--allow-no-auth"}, []string{"frontend", "internal-frontend", "history", "matching", "worker"}}, + "api profile with a service": {[]string{"--runtime-config", "testdata/runtime-api.toml", "--allow-no-auth", "--service", "history"}, []string{"history"}}, + } { + c, _, stderr := newTestCommand(&fakeServer{}, nil) + var got []string + c.newServer = func(services []string, _ ...temporal.ServerOption) (temporal.Server, error) { + got = services + return &fakeServer{}, nil + } + if err := c.start(tt.args); err != nil { + t.Fatalf("%s: start = %v (%s)", name, err, stderr.String()) + } + if !slices.Equal(got, tt.want) { + t.Errorf("%s: services = %v, want %v", name, got, tt.want) + } + } +} + +func TestStartRefusesAnAPIProfileWithoutAService(t *testing.T) { + c, _, _ := newTestCommand(&fakeServer{}, nil) + if err := c.start([]string{"--runtime-config", "testdata/runtime-api.toml", "--allow-no-auth"}); !errors.Is(err, runtimeconfig.ErrNoServices) { + t.Fatalf("start = %v, want %v", err, runtimeconfig.ErrNoServices) + } +} + +func TestNewTemporalServerBuildsAServer(t *testing.T) { + rt, err := runtimeconfig.Load("testdata/runtime-sqlite.toml") + if err != nil { + t.Fatal(err) + } + if _, err := newTemporalServer([]string{"frontend"}, temporal.WithConfig(&rt.Temporal)); err != nil { + t.Fatalf("newTemporalServer = %v", err) + } +} diff --git a/engine/internal/cli/testdata/certs/engine.crt b/engine/internal/cli/testdata/certs/engine.crt new file mode 100644 index 0000000..7751d49 --- /dev/null +++ b/engine/internal/cli/testdata/certs/engine.crt @@ -0,0 +1 @@ +placeholder: the fake server never reads it diff --git a/engine/internal/cli/testdata/certs/engine.key b/engine/internal/cli/testdata/certs/engine.key new file mode 100644 index 0000000..7751d49 --- /dev/null +++ b/engine/internal/cli/testdata/certs/engine.key @@ -0,0 +1 @@ +placeholder: the fake server never reads it diff --git a/engine/internal/cli/testdata/runtime-api.toml b/engine/internal/cli/testdata/runtime-api.toml new file mode 100644 index 0000000..4a660c9 --- /dev/null +++ b/engine/internal/cli/testdata/runtime-api.toml @@ -0,0 +1,6 @@ +[runtime] +profiles = ["api"] + +[database] +type = "sqlite" +inMemory = true diff --git a/engine/internal/cli/testdata/runtime-auth.toml b/engine/internal/cli/testdata/runtime-auth.toml new file mode 100644 index 0000000..07bd8f0 --- /dev/null +++ b/engine/internal/cli/testdata/runtime-auth.toml @@ -0,0 +1,20 @@ +[runtime] +profiles = ["frontend", "history"] + +[engine.tls] +certFile = "testdata/certs/engine.crt" +keyFile = "testdata/certs/engine.key" + +[engine.auth] +type = "jwt" +jwksUrls = ["http://127.0.0.1:1/jwks"] +rolesClaim = "cognito:groups" + +[[engine.auth.rules]] +value = "workflow-admins" +namespace = "*" +role = "admin" + +[database] +type = "sqlite" +inMemory = true diff --git a/engine/internal/runtimeconfig/fixtures_test.go b/engine/internal/runtimeconfig/fixtures_test.go index 8d47b71..6386f74 100644 --- a/engine/internal/runtimeconfig/fixtures_test.go +++ b/engine/internal/runtimeconfig/fixtures_test.go @@ -123,7 +123,7 @@ func TestConfigFixtures(t *testing.T) { case err != nil: t.Fatalf("parse: %v", err) default: - rendered, err := Render(rt) + rendered, err := Render(&rt.Temporal) if err != nil { t.Fatal(err) } diff --git a/engine/internal/runtimeconfig/profiles.go b/engine/internal/runtimeconfig/profiles.go new file mode 100644 index 0000000..cb18098 --- /dev/null +++ b/engine/internal/runtimeconfig/profiles.go @@ -0,0 +1,84 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package runtimeconfig + +import ( + "fmt" + "slices" + "strings" + + "github.com/knadh/koanf/v2" + "go.temporal.io/server/common/primitives" +) + +const ( + profileAll = "all" + profileEngine = "engine" + // profileAPI is the API server's profile; the engine starts nothing for it. + profileAPI = "api" +) + +var engineServices = []string{ + string(primitives.FrontendService), string(primitives.InternalFrontendService), string(primitives.HistoryService), + string(primitives.MatchingService), string(primitives.WorkerService), +} + +// profileServices maps the [runtime] profiles to the Temporal services a node runs. The internal frontend runs with +// the frontend: Temporal's own services find it through membership. +var profileServices = map[string][]string{ + profileAll: engineServices, + profileEngine: engineServices, + "frontend": {string(primitives.FrontendService), string(primitives.InternalFrontendService)}, + "history": {string(primitives.HistoryService)}, + "matching": {string(primitives.MatchingService)}, + "worker": {string(primitives.WorkerService)}, + profileAPI: nil, +} + +// services reads [runtime] profiles (["all"] when absent) and returns the services this node runs, in a stable order. +func services(k *koanf.Koanf) ([]string, error) { + profiles := []string{profileAll} + if k.Exists("runtime.profiles") { + profiles = k.Strings("runtime.profiles") + if len(profiles) == 0 { + return nil, fmt.Errorf("invalid runtime configuration: runtime.profiles must name at least one profile") + } + } + chosen := map[string]bool{} + for _, p := range profiles { + names, ok := profileServices[p] + if !ok { + known := make([]string, 0, len(profileServices)) + for name := range profileServices { + known = append(known, name) + } + slices.Sort(known) + return nil, fmt.Errorf("invalid runtime configuration: runtime.profiles: unknown profile %q (one of %s)", + p, strings.Join(known, ", ")) + } + for _, s := range names { + chosen[s] = true + } + } + var out []string + for _, s := range engineServices { + if chosen[s] { + out = append(out, s) + } + } + return out, nil +} diff --git a/engine/internal/runtimeconfig/runtimeconfig.go b/engine/internal/runtimeconfig/runtimeconfig.go index 32eaab4..76eb10b 100644 --- a/engine/internal/runtimeconfig/runtimeconfig.go +++ b/engine/internal/runtimeconfig/runtimeconfig.go @@ -16,7 +16,7 @@ // Package runtimeconfig turns the runtime's conf/runtime.toml into a Temporal server configuration. // -// Only the [engine] and [database] tables are read here; other tables belong to other components. +// The [engine] and [database] tables and [runtime] profiles are read here; other tables belong to other components. package runtimeconfig import ( @@ -37,8 +37,11 @@ import ( "go.temporal.io/server/common/auth" "go.temporal.io/server/common/cluster" "go.temporal.io/server/common/config" + "go.temporal.io/server/common/dynamicconfig" "go.temporal.io/server/common/log" "gopkg.in/yaml.v3" + + "github.com/wso2/integration-workflow-runtime/engine/plugins/jwtclaims" ) const ( @@ -68,17 +71,32 @@ var ( logLevels = []string{"debug", "info", "warn", "error"} ) +// Runtime is what the engine takes from runtime.toml. +type Runtime struct { + // Temporal is the generated, validated Temporal server configuration. + Temporal config.Config + // Services are the Temporal services this node runs, from [runtime] profiles. + Services []string + // Auth configures the identity-provider claim mapper; nil when [engine.auth] is off. + Auth *jwtclaims.Settings + // DynamicConfig holds the dynamic settings the configuration needs; nil when it needs none. + DynamicConfig dynamicconfig.StaticClient +} + type settings struct { Engine engineSettings `toml:"engine"` Database databaseSettings `toml:"database"` } type engineSettings struct { - BindAddress string `toml:"bindAddress"` - BroadcastAddress string `toml:"broadcastAddress"` - HistoryShards int32 `toml:"historyShards"` - LogLevel string `toml:"logLevel"` - Ports portsSettings `toml:"ports"` + BindAddress string `toml:"bindAddress"` + BroadcastAddress string `toml:"broadcastAddress"` + HistoryShards int32 `toml:"historyShards"` + LogLevel string `toml:"logLevel"` + Ports portsSettings `toml:"ports"` + TLS engineTLSSettings `toml:"tls"` + Auth authSettings `toml:"auth"` + Metrics metricsSettings `toml:"metrics"` } type portsSettings struct { @@ -113,8 +131,8 @@ type tlsSettings struct { EnableHostVerification *bool `toml:"enableHostVerification"` } -// Load reads a runtime.toml file and returns the validated Temporal server configuration it describes. -func Load(path string) (*config.Config, error) { +// Load reads a runtime.toml file and returns the validated configuration it describes. +func Load(path string) (*Runtime, error) { data, err := os.ReadFile(filepath.Clean(path)) //nolint:gosec // G304: the path is the operator's --runtime-config flag if err != nil { return nil, fmt.Errorf("unable to read %s: %w", path, err) @@ -137,7 +155,7 @@ func Render(cfg *config.Config) ([]byte, error) { return yaml.Marshal(&copied) } -func parse(data []byte, lookupEnv func(string) (string, bool)) (*config.Config, error) { +func parse(data []byte, lookupEnv func(string) (string, bool)) (*Runtime, error) { values, err := toml.Parser().Unmarshal(data) if err != nil { return nil, fmt.Errorf("invalid runtime configuration: %w", err) @@ -153,6 +171,10 @@ func parse(data []byte, lookupEnv func(string) (string, bool)) (*config.Config, if err := decodeTable(k, "database", &s.Database); err != nil { return nil, err } + nodeServices, err := services(k) + if err != nil { + return nil, err + } s.applyDefaults() if err := s.validate(); err != nil { return nil, err @@ -165,7 +187,16 @@ func parse(data []byte, lookupEnv func(string) (string, bool)) (*config.Config, if err := cfg.Validate(); err != nil { return nil, fmt.Errorf("invalid Temporal configuration: %w", err) } - return cfg, nil + rt := &Runtime{Temporal: *cfg, Services: nodeServices} + // Temporal keeps membership (ringpop) in plain text unless this switch is on, even with internode TLS. + if s.Engine.TLS.Internode.Enabled { + rt.DynamicConfig = dynamicconfig.StaticClient{dynamicconfig.EnableRingpopTLS.Key(): true} + } + if s.Engine.Auth.on() { + claims := s.Engine.Auth.claimSettings() + rt.Auth = &claims + } + return rt, nil } // decodeTable fills target from one of the tables this package owns, rejecting unknown keys (typos) in it; the @@ -235,6 +266,10 @@ func (s *settings) validate() error { problems = append(problems, "engine.historyShards must be at least 1") } problems = append(problems, e.Ports.problems()...) + problems = append(problems, e.TLS.problems()...) + problems = append(problems, e.Auth.problems()...) + problems = append(problems, e.securityProblems()...) + problems = append(problems, e.Metrics.problems()...) if d.MaxConns < 1 { problems = append(problems, "database.maxConns must be at least 1") } @@ -276,6 +311,11 @@ func (s *settings) validate() error { problems = append(problems, "database.tls.serverName is not supported for a postgresql database; "+ "set database.host to the name on the database certificate") } + if len(problems) == 0 { + if err := s.Engine.TLS.defaultInternodeServerName(); err != nil { + problems = append(problems, err.Error()) + } + } if len(problems) > 0 { return errors.New("invalid runtime configuration: " + strings.Join(problems, "; ")) } @@ -335,7 +375,10 @@ func (s *settings) temporalConfig(password string) *config.Config { frontendHTTP := net.JoinHostPort(e.BroadcastAddress, strconv.Itoa(e.Ports.FrontendHTTP)) return &config.Config{ Global: config.Global{ - Membership: config.Membership{MaxJoinDuration: 30 * time.Second, BroadcastAddress: e.BroadcastAddress}, + Membership: config.Membership{MaxJoinDuration: 30 * time.Second, BroadcastAddress: e.BroadcastAddress}, + TLS: e.TLS.temporalTLS(), + Authorization: e.Auth.temporalAuthorization(), + Metrics: e.Metrics.temporalMetrics(), }, Persistence: config.Persistence{ DefaultStore: defaultStore, diff --git a/engine/internal/runtimeconfig/runtimeconfig_test.go b/engine/internal/runtimeconfig/runtimeconfig_test.go index 1e79efe..d774a38 100644 --- a/engine/internal/runtimeconfig/runtimeconfig_test.go +++ b/engine/internal/runtimeconfig/runtimeconfig_test.go @@ -32,22 +32,22 @@ func noEnv(string) (string, bool) { return "", false } func mustParse(t *testing.T, toml string) *config.Config { t.Helper() - cfg, err := parse([]byte(toml), noEnv) + rt, err := parse([]byte(toml), noEnv) if err != nil { t.Fatalf("parse: %v", err) } - return cfg + return &rt.Temporal } func TestPasswordFromEnvironment(t *testing.T) { t.Parallel() lookup := func(name string) (string, bool) { return "from-env", name == "WF_DB_PASSWORD" } - cfg, err := parse([]byte("[database]\ntype = \"postgresql\"\nhost = \"db\"\npassword = \"$env{WF_DB_PASSWORD}\"\n"), lookup) + rt, err := parse([]byte("[database]\ntype = \"postgresql\"\nhost = \"db\"\npassword = \"$env{WF_DB_PASSWORD}\"\n"), lookup) if err != nil { t.Fatal(err) } for _, store := range []string{defaultStore, visibilityStore} { - if got := cfg.Persistence.DataStores[store].SQL.Password; got != "from-env" { + if got := rt.Temporal.Persistence.DataStores[store].SQL.Password; got != "from-env" { t.Fatalf("%s password = %q, want the environment value", store, got) } } diff --git a/engine/internal/runtimeconfig/security.go b/engine/internal/runtimeconfig/security.go new file mode 100644 index 0000000..5daffcd --- /dev/null +++ b/engine/internal/runtimeconfig/security.go @@ -0,0 +1,305 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package runtimeconfig + +import ( + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "net" + "os" + "strconv" + "strings" + "time" + + "go.temporal.io/server/common/config" + "go.temporal.io/server/common/metrics" + + "github.com/wso2/integration-workflow-runtime/engine/plugins/jwtclaims" +) + +// ClaimMapperName marks the generated configuration as using jwtclaims; the start command builds that mapper. +const ClaimMapperName = "wso2-jwt" + +const authTypeJWT = "jwt" + +type engineTLSSettings struct { + CertFile string `toml:"certFile"` + KeyFile string `toml:"keyFile"` + ClientCAFile string `toml:"clientCaFile"` + Internode internodeTLSSettings `toml:"internode"` +} + +type internodeTLSSettings struct { + Enabled bool `toml:"enabled"` + CertFile string `toml:"certFile"` + KeyFile string `toml:"keyFile"` + CAFile string `toml:"caFile"` + ServerName string `toml:"serverName"` +} + +type authSettings struct { + Type string `toml:"type"` + JWKSURLs []string `toml:"jwksUrls"` + KeyRefresh string `toml:"keyRefreshInterval"` + Issuer string `toml:"issuer"` + Audience string `toml:"audience"` + SubjectClaim string `toml:"subjectClaim"` + RolesClaim string `toml:"rolesClaim"` + ValueRegex string `toml:"valueRegex"` + LeewaySeconds int `toml:"leewaySeconds"` + Rules []ruleSettings `toml:"rules"` +} + +type ruleSettings struct { + Value string `toml:"value"` + Namespace string `toml:"namespace"` + Role string `toml:"role"` +} + +type metricsSettings struct { + PrometheusAddress string `toml:"prometheusAddress"` +} + +func (t engineTLSSettings) enabled() bool { return t.CertFile != "" || t.KeyFile != "" } + +func (t engineTLSSettings) problems() []string { + var problems []string + if (t.CertFile == "") != (t.KeyFile == "") { + problems = append(problems, "engine.tls needs both certFile and keyFile") + } + if t.ClientCAFile != "" && !t.enabled() { + problems = append(problems, "engine.tls.clientCaFile needs engine.tls.certFile and keyFile") + } + in := t.Internode + if in.Enabled { + if in.CAFile == "" { + problems = append(problems, "engine.tls.internode.caFile is required when internode TLS is enabled") + } + if (in.CertFile == "") != (in.KeyFile == "") { + problems = append(problems, "engine.tls.internode needs both certFile and keyFile") + } + if in.CertFile == "" && !t.enabled() { + problems = append(problems, "engine.tls.internode needs its own certFile and keyFile, or engine.tls's") + } + } else if in.CertFile != "" || in.KeyFile != "" || in.CAFile != "" || in.ServerName != "" { + problems = append(problems, "engine.tls.internode files are set but engine.tls.internode.enabled is false") + } + for _, f := range []struct{ key, path string }{ + {"engine.tls.certFile", t.CertFile}, {"engine.tls.keyFile", t.KeyFile}, {"engine.tls.clientCaFile", t.ClientCAFile}, + {"engine.tls.internode.certFile", in.CertFile}, {"engine.tls.internode.keyFile", in.KeyFile}, + {"engine.tls.internode.caFile", in.CAFile}, + } { + if f.path == "" { + continue + } + if _, err := os.Stat(f.path); err != nil { + problems = append(problems, fmt.Sprintf("%s: %v", f.key, err)) + } + } + return problems +} + +// defaultInternodeServerName settles the name every node verifies in the others' internode certificates. Temporal +// reaches the internal frontend through its membership resolver, a target with no host name, so without a server name +// that connection fails, and with it the search attribute, namespace and system worker calls behind it. The name +// defaults to the certificate's DNS name when it has exactly one; an explicit name must be in the certificate. +func (t *engineTLSSettings) defaultInternodeServerName() error { + in := &t.Internode + if !in.Enabled { + return nil + } + file := in.CertFile + if file == "" { + file = t.CertFile + } + cert, err := readCertificate(file) + if err != nil { + return fmt.Errorf("engine.tls.internode: %w", err) + } + if in.ServerName != "" { + if err := cert.VerifyHostname(in.ServerName); err != nil { + return fmt.Errorf("engine.tls.internode.serverName %q is not a name in %s", in.ServerName, file) + } + return nil + } + switch len(cert.DNSNames) { + case 1: + in.ServerName = cert.DNSNames[0] + return nil + case 0: + return fmt.Errorf("engine.tls.internode.serverName is required: %s has no DNS name; issue the internode "+ + "certificates with a DNS name every node shares, or set serverName to a name every node's certificate "+ + "carries", file) + default: + return fmt.Errorf("engine.tls.internode.serverName is required: %s has several DNS names (%s); set it to "+ + "the one every node's certificate carries", file, strings.Join(cert.DNSNames, ", ")) + } +} + +func readCertificate(file string) (*x509.Certificate, error) { + data, err := os.ReadFile(file) //nolint:gosec // the configured certificate + if err != nil { + return nil, err + } + block, _ := pem.Decode(data) + if block == nil || block.Type != "CERTIFICATE" { + return nil, fmt.Errorf("%s holds no PEM certificate", file) + } + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, fmt.Errorf("%s: %w", file, err) + } + return cert, nil +} + +func (t engineTLSSettings) temporalTLS() config.RootTLS { + var root config.RootTLS + if t.enabled() { + root.Frontend.Server = config.ServerTLS{CertFile: t.CertFile, KeyFile: t.KeyFile} + if t.ClientCAFile != "" { + root.Frontend.Server.ClientCAFiles = []string{t.ClientCAFile} + root.Frontend.Server.RequireClientAuth = true + } + } + if in := t.Internode; in.Enabled { + cert, key := in.CertFile, in.KeyFile + if cert == "" { + cert, key = t.CertFile, t.KeyFile + } + root.Internode.Server = config.ServerTLS{ + CertFile: cert, KeyFile: key, ClientCAFiles: []string{in.CAFile}, RequireClientAuth: true, + } + root.Internode.Client = config.ClientTLS{RootCAFiles: []string{in.CAFile}, ServerName: in.ServerName} + // Temporal's own workers present the internode certificate to the internal frontend. + root.SystemWorker = config.WorkerTLS{CertFile: cert, KeyFile: key, Client: root.Internode.Client} + } + return root +} + +func (a authSettings) on() bool { return a.Type == authTypeJWT } + +// securityProblems are the rules that join auth, TLS and the listen address. +func (e engineSettings) securityProblems() []string { + if !e.Auth.on() { + return nil + } + var problems []string + if !e.TLS.enabled() { + problems = append(problems, `engine.auth.type = "jwt" needs engine.tls (certFile and keyFile): tokens would cross `+ + "the network in plain text") + } + // The internal frontend gives Temporal's own services system access without a token, and the other services' + // ports are open to anyone who reaches them, so beyond this machine they need internode mutual TLS. + if ip := net.ParseIP(e.BindAddress); !e.TLS.Internode.Enabled && (ip == nil || !ip.IsLoopback()) { + problems = append(problems, fmt.Sprintf("engine.auth needs engine.tls.internode when engine.bindAddress is %s: "+ + "the internal frontend and the other services' ports accept calls without a token, so they need mutual TLS "+ + "between the engine's nodes", e.BindAddress)) + } + return problems +} + +func (a authSettings) problems() []string { + switch a.Type { + case "", "none": + if len(a.JWKSURLs) > 0 || len(a.Rules) > 0 || a.Issuer != "" { + return []string{`engine.auth settings are present but engine.auth.type is not "jwt"`} + } + return nil + case authTypeJWT: + default: + return []string{fmt.Sprintf(`engine.auth.type %q must be "jwt" or "none"`, a.Type)} + } + var problems []string + if len(a.JWKSURLs) == 0 && a.Issuer == "" { + problems = append(problems, "engine.auth needs the identity provider's issuer (its key set is discovered) or jwksUrls") + } + for _, u := range a.JWKSURLs { + if err := jwtclaims.CheckURL(u); err != nil { + problems = append(problems, "engine.auth.jwksUrls: "+err.Error()) + } + } + if err := jwtclaims.CheckURL(a.Issuer); len(a.JWKSURLs) == 0 && a.Issuer != "" && err != nil { + problems = append(problems, "engine.auth.issuer (its key set is discovered from it): "+err.Error()) + } + if a.KeyRefresh != "" { + if d, err := time.ParseDuration(a.KeyRefresh); err != nil || d < time.Second { + problems = append(problems, fmt.Sprintf("engine.auth.keyRefreshInterval %q must be a duration of at least 1s", a.KeyRefresh)) + } + } + if a.LeewaySeconds < 0 { + problems = append(problems, "engine.auth.leewaySeconds must not be negative") + } + if _, err := jwtclaims.New(nil, a.claimSettings()); err != nil { + problems = append(problems, "engine.auth: "+err.Error()) + } + return problems +} + +// claimSettings is what the start command passes to jwtclaims. +func (a authSettings) claimSettings() jwtclaims.Settings { + rules := make([]jwtclaims.Rule, len(a.Rules)) + for i, r := range a.Rules { + rules[i] = jwtclaims.Rule{Value: r.Value, Namespace: r.Namespace, Role: r.Role} + } + return jwtclaims.Settings{ + Issuer: a.Issuer, Audience: a.Audience, SubjectClaim: a.SubjectClaim, RolesClaim: a.RolesClaim, + ValueRegex: a.ValueRegex, Rules: rules, Leeway: time.Duration(a.LeewaySeconds) * time.Second, + } +} + +func (a authSettings) temporalAuthorization() config.Authorization { + if !a.on() { + return config.Authorization{} + } + refresh := time.Minute + if a.KeyRefresh != "" { + refresh, _ = time.ParseDuration(a.KeyRefresh) + } + return config.Authorization{ + Authorizer: "default", + ClaimMapper: ClaimMapperName, + JWTKeyProvider: config.JWTKeyProvider{KeySourceURIs: a.JWKSURLs, RefreshInterval: refresh}, + } +} + +func (m metricsSettings) problems() []string { + if m.PrometheusAddress == "" { + return nil + } + _, port, err := net.SplitHostPort(m.PrometheusAddress) + if err != nil || port == "" { + return []string{fmt.Sprintf("engine.metrics.prometheusAddress %q must be host:port", m.PrometheusAddress)} + } + if n, err := strconv.Atoi(port); err != nil || n < 0 || n > 65535 { + return []string{fmt.Sprintf("engine.metrics.prometheusAddress %q has an invalid port", m.PrometheusAddress)} + } + return nil +} + +func (m metricsSettings) temporalMetrics() *metrics.Config { + if m.PrometheusAddress == "" { + return nil + } + return &metrics.Config{Prometheus: &metrics.PrometheusConfig{ + Framework: metrics.FrameworkOpentelemetry, ListenAddress: m.PrometheusAddress, HandlerPath: "/metrics", + }} +} + +// ErrNoServices is returned by the CLI when profiles select no engine service and no --service is given. +var ErrNoServices = errors.New("runtime.profiles names no engine service; this node runs only other components") diff --git a/engine/internal/runtimeconfig/security_test.go b/engine/internal/runtimeconfig/security_test.go new file mode 100644 index 0000000..0edae2f --- /dev/null +++ b/engine/internal/runtimeconfig/security_test.go @@ -0,0 +1,314 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package runtimeconfig + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "net" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "go.temporal.io/server/common/dynamicconfig" +) + +const sqliteDB = "[database]\ntype = \"sqlite\"\ninMemory = true\n" + +func mustParseRuntime(t *testing.T, toml string) *Runtime { + t.Helper() + rt, err := parse([]byte(toml), noEnv) + if err != nil { + t.Fatalf("parse: %v", err) + } + return rt +} + +func TestProfilesChooseServices(t *testing.T) { + all := []string{"frontend", "internal-frontend", "history", "matching", "worker"} + tests := map[string][]string{ + "": all, + `profiles = ["all"]`: all, + `profiles = ["engine", "api"]`: all, + `profiles = ["frontend"]`: {"frontend", "internal-frontend"}, + `profiles = ["matching", "history"]`: {"history", "matching"}, + `profiles = ["worker"]`: {"worker"}, + `profiles = ["api"]`: nil, + } + for profiles, want := range tests { + rt := mustParseRuntime(t, "[runtime]\n"+profiles+"\n"+sqliteDB) + if !slices.Equal(rt.Services, want) { + t.Errorf("%q: services = %v, want %v", profiles, rt.Services, want) + } + } +} + +func TestProfileErrors(t *testing.T) { + for profiles, want := range map[string]string{ + `profiles = []`: "at least one profile", + `profiles = ["manager"]`: `unknown profile "manager"`, + } { + _, err := parse([]byte("[runtime]\n"+profiles+"\n"+sqliteDB), noEnv) + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: err = %v, want %q", profiles, err, want) + } + } +} + +// certFiles writes a certificate for engine.internal and placeholder key and CA files, which the parser only checks +// exist. +func certFiles(t *testing.T) (cert, key, ca string) { + t.Helper() + dir := t.TempDir() + for _, name := range []string{"engine.key", "ca.pem"} { + if err := os.WriteFile(filepath.Join(dir, name), []byte("placeholder"), 0o600); err != nil { + t.Fatal(err) + } + } + return certificate(t, dir, "engine.crt", "engine.internal"), filepath.Join(dir, "engine.key"), + filepath.Join(dir, "ca.pem") +} + +// certificate writes a self-signed certificate for the names given: IP addresses become IP SANs, others DNS names. +func certificate(t *testing.T, dir, name string, names ...string) string { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "engine"}, + NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour)} + for _, n := range names { + if ip := net.ParseIP(n); ip != nil { + tmpl.IPAddresses = append(tmpl.IPAddresses, ip) + } else { + tmpl.DNSNames = append(tmpl.DNSNames, n) + } + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, name) + if err := os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func TestInternodeServerNameDefaultsToTheCertificatesOnlyDNSName(t *testing.T) { + cert, key, ca := certFiles(t) + tls := "[engine.tls]\ncertFile = \"" + cert + "\"\nkeyFile = \"" + key + "\"\n" + internode := "[engine.tls.internode]\nenabled = true\ncaFile = \"" + ca + "\"\n" + got := mustParseRuntime(t, tls+internode+sqliteDB).Temporal.Global.TLS + if got.Internode.Client.ServerName != "engine.internal" || got.SystemWorker.Client.ServerName != "engine.internal" { + t.Fatalf("internode server name = %q, system worker %q; want the certificate's engine.internal", + got.Internode.Client.ServerName, got.SystemWorker.Client.ServerName) + } + dir := t.TempDir() + own := func(certFile, serverName string) string { + toml := internode + "certFile = \"" + certFile + "\"\nkeyFile = \"" + key + "\"\n" + if serverName != "" { + toml += "serverName = \"" + serverName + "\"\n" + } + return tls + toml + sqliteDB + } + several := certificate(t, dir, "several.crt", "node-1.internal", "nodes.internal") + ipOnly := certificate(t, dir, "ip.crt", "10.0.1.21") + for name, tt := range map[string]struct{ toml, want string }{ + "one of several DNS names": {own(several, "nodes.internal"), "nodes.internal"}, + "an IP address it carries": {own(ipOnly, "10.0.1.21"), "10.0.1.21"}, + "a wildcard it carries": {own(certificate(t, dir, "wild.crt", "*.nodes.internal"), "a.nodes.internal"), "a.nodes.internal"}, + } { + rt := mustParseRuntime(t, tt.toml) + if got := rt.Temporal.Global.TLS.Internode.Client.ServerName; got != tt.want { + t.Errorf("%s: server name %q, want %q", name, got, tt.want) + } + } + for name, tt := range map[string]struct{ toml, want string }{ + "several DNS names": {own(several, ""), "several DNS names (node-1.internal, nodes.internal)"}, + "an IP address only": {own(ipOnly, ""), "has no DNS name"}, + "no names at all": {own(certificate(t, dir, "none.crt"), ""), "has no DNS name"}, + "a name it does not carry": {own(several, "other.internal"), `serverName "other.internal" is not a name in`}, + "an IP it does not carry": {own(ipOnly, "10.0.1.22"), `serverName "10.0.1.22" is not a name in`}, + "not a PEM file": {own(ca, ""), "holds no PEM certificate"}, + "a file that does not exist": {own(filepath.Join(dir, "gone.crt"), ""), "internode.certFile"}, + } { + if _, err := parse([]byte(tt.toml), noEnv); err == nil || !strings.Contains(err.Error(), tt.want) { + t.Errorf("%s: err = %v, want %q", name, err, tt.want) + } + } +} + +func TestInternodeTLSTurnsOnMembershipTLS(t *testing.T) { + cert, key, ca := certFiles(t) + tls := "[engine.tls]\ncertFile = \"" + cert + "\"\nkeyFile = \"" + key + "\"\n" + on := mustParseRuntime(t, tls+"[engine.tls.internode]\nenabled = true\ncaFile = \""+ca+"\"\n"+sqliteDB) + if v, ok := on.DynamicConfig[dynamicconfig.EnableRingpopTLS.Key()].(bool); !ok || !v { + t.Fatalf("dynamic config = %v, want %s on", on.DynamicConfig, dynamicconfig.EnableRingpopTLS.Key()) + } + if off := mustParseRuntime(t, tls+sqliteDB); off.DynamicConfig != nil { + t.Fatalf("dynamic config without internode TLS = %v, want none", off.DynamicConfig) + } +} + +func TestTLSMapsToTemporal(t *testing.T) { + cert, key, ca := certFiles(t) + toml := "[engine.tls]\ncertFile = \"" + cert + "\"\nkeyFile = \"" + key + "\"\nclientCaFile = \"" + ca + "\"\n" + + "[engine.tls.internode]\nenabled = true\ncaFile = \"" + ca + "\"\nserverName = \"engine.internal\"\n" + sqliteDB + tls := mustParseRuntime(t, toml).Temporal.Global.TLS + f := tls.Frontend.Server + if f.CertFile != cert || f.KeyFile != key || !f.RequireClientAuth || !slices.Equal(f.ClientCAFiles, []string{ca}) { + t.Errorf("frontend = %+v", f) + } + in := tls.Internode + if in.Server.CertFile != cert || !in.Server.RequireClientAuth || in.Client.ServerName != "engine.internal" || + !slices.Equal(in.Client.RootCAFiles, []string{ca}) { + t.Errorf("internode = %+v", in) + } + if tls.SystemWorker.CertFile != cert || tls.SystemWorker.Client.ServerName != "engine.internal" { + t.Errorf("system worker = %+v", tls.SystemWorker) + } +} + +func TestTLSWithoutClientCertificates(t *testing.T) { + cert, key, _ := certFiles(t) + tls := mustParseRuntime(t, "[engine.tls]\ncertFile = \""+cert+"\"\nkeyFile = \""+key+"\"\n"+sqliteDB).Temporal.Global.TLS + if tls.Frontend.Server.RequireClientAuth || tls.Internode.Server.CertFile != "" { + t.Errorf("tls = %+v", tls) + } + if off := mustParseRuntime(t, sqliteDB).Temporal.Global.TLS; off.Frontend.Server.CertFile != "" { + t.Errorf("tls without settings = %+v", off) + } +} + +func TestTLSErrors(t *testing.T) { + cert, key, ca := certFiles(t) + for toml, want := range map[string]string{ + "[engine.tls]\ncertFile = \"" + cert + "\"\n": "both certFile and keyFile", + "[engine.tls]\nclientCaFile = \"" + ca + "\"\n": "clientCaFile needs", + "[engine.tls]\ncertFile = \"/no/cert\"\nkeyFile = \"" + key + "\"\n": "engine.tls.certFile", + "[engine.tls.internode]\nenabled = true\n": "internode.caFile is required", + "[engine.tls.internode]\nenabled = true\ncaFile = \"" + ca + "\"\n": "its own certFile and keyFile", + "[engine.tls.internode]\ncaFile = \"" + ca + "\"\n": "internode.enabled is false", + "[engine.tls.internode]\nenabled = true\ncaFile = \"" + ca + "\"\ncertFile = \"" + cert + "\"\n": "internode needs both", + } { + _, err := parse([]byte(toml+sqliteDB), noEnv) + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: err = %v, want %q", toml, err, want) + } + } +} + +func TestAuthMapsToTemporalAndClaims(t *testing.T) { + cert, key, _ := certFiles(t) + rt := mustParseRuntime(t, "[engine.tls]\ncertFile = \""+cert+"\"\nkeyFile = \""+key+"\"\n"+`[engine.auth] +type = "jwt" +jwksUrls = ["https://idp.example.com/jwks"] +keyRefreshInterval = "5m" +issuer = "https://idp.example.com" +audience = "workflow-engine" +rolesClaim = "realm_access.roles" +leewaySeconds = 30 + +[[engine.auth.rules]] +value = "workflow-admins" +namespace = "*" +role = "admin" +`+sqliteDB) + a := rt.Temporal.Global.Authorization + if a.Authorizer != "default" || a.ClaimMapper != ClaimMapperName || a.JWTKeyProvider.KeySourceURIs[0] != "https://idp.example.com/jwks" || + a.JWTKeyProvider.RefreshInterval.Minutes() != 5 { + t.Errorf("authorization = %+v", a) + } + if rt.Auth == nil || rt.Auth.Issuer != "https://idp.example.com" || rt.Auth.RolesClaim != "realm_access.roles" || + len(rt.Auth.Rules) != 1 || rt.Auth.Leeway.Seconds() != 30 { + t.Errorf("claim settings = %+v", rt.Auth) + } + if off := mustParseRuntime(t, sqliteDB); off.Auth != nil || off.Temporal.Global.Authorization.Authorizer != "" { + t.Errorf("auth without settings = %+v", off.Temporal.Global.Authorization) + } +} + +func TestAuthErrors(t *testing.T) { + for toml, want := range map[string]string{ + "[engine.auth]\ntype = \"oauth\"\n": `must be "jwt" or "none"`, + "[engine.auth]\ntype = \"jwt\"\n": "needs the identity provider's issuer", + "[engine.auth]\njwksUrls = [\"https://idp\"]\n": `type is not "jwt"`, + "[engine.auth]\ntype = \"jwt\"\njwksUrls = [\"x\"]\nkeyRefreshInterval = \"soon\"\n": "keyRefreshInterval", + "[engine.auth]\ntype = \"jwt\"\njwksUrls = [\"http://idp.example/jwks\"]\n": "jwksUrls: \"http://idp.example/jwks\" must use https", + "[engine.auth]\ntype = \"jwt\"\nissuer = \"http://idp.example\"\n": "issuer (its key set is discovered from it)", + "[engine.auth]\ntype = \"jwt\"\njwksUrls = [\"x\"]\nleewaySeconds = -1\n": "leewaySeconds", + "[engine.auth]\ntype = \"jwt\"\njwksUrls = [\"x\"]\n[[engine.auth.rules]]\nvalue = \"a\"\nnamespace = \"b\"\nrole = \"owner\"\n": `role "owner"`, + } { + _, err := parse([]byte(toml+sqliteDB), noEnv) + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: err = %v, want %q", toml, err, want) + } + } +} + +func TestMetrics(t *testing.T) { + m := mustParseRuntime(t, "[engine.metrics]\nprometheusAddress = \"0.0.0.0:9464\"\n"+sqliteDB).Temporal.Global.Metrics + if m == nil || m.Prometheus.ListenAddress != "0.0.0.0:9464" || m.Prometheus.HandlerPath != "/metrics" { + t.Errorf("metrics = %+v", m) + } + if off := mustParseRuntime(t, sqliteDB).Temporal.Global.Metrics; off != nil { + t.Errorf("metrics without settings = %+v", off) + } + for address, want := range map[string]string{"9464": "must be host:port", "0.0.0.0:70000": "invalid port", + "0.0.0.0:metrics": "invalid port"} { + _, err := parse([]byte("[engine.metrics]\nprometheusAddress = \""+address+"\"\n"+sqliteDB), noEnv) + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%s: err = %v, want %q", address, err, want) + } + } +} + +func TestJWTNeedsTLSAndProtectedInternalPorts(t *testing.T) { + cert, key, ca := certFiles(t) + tls := "[engine.tls]\ncertFile = \"" + cert + "\"\nkeyFile = \"" + key + "\"\n" + internode := "[engine.tls.internode]\nenabled = true\ncaFile = \"" + ca + "\"\n" + auth := "[engine.auth]\ntype = \"jwt\"\nissuer = \"https://idp.example.com\"\n" + everywhere := "[engine]\nbindAddress = \"0.0.0.0\"\nbroadcastAddress = \"10.0.0.5\"\n" + for name, tt := range map[string]struct{ toml, want string }{ + "jwt without tls": {auth + sqliteDB, `needs engine.tls (certFile and keyFile)`}, + "jwt on all interfaces": {everywhere + tls + auth + sqliteDB, "needs engine.tls.internode when engine.bindAddress is 0.0.0.0"}, + "jwt on another machine's view": {"[engine]\nbindAddress = \"10.0.0.5\"\n" + tls + auth + sqliteDB, "needs engine.tls.internode"}, + } { + if _, err := parse([]byte(tt.toml), noEnv); err == nil || !strings.Contains(err.Error(), tt.want) { + t.Errorf("%s: err = %v, want %q", name, err, tt.want) + } + } + for name, toml := range map[string]string{ + "loopback with tls": tls + auth + sqliteDB, + "all interfaces with internode": everywhere + tls + internode + auth + sqliteDB, + "no auth on all interfaces": everywhere + sqliteDB, + } { + if _, err := parse([]byte(toml), noEnv); err != nil { + t.Errorf("%s: %v", name, err) + } + } +} diff --git a/engine/plugins/jwtclaims/discovery.go b/engine/plugins/jwtclaims/discovery.go new file mode 100644 index 0000000..f979065 --- /dev/null +++ b/engine/plugins/jwtclaims/discovery.go @@ -0,0 +1,98 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package jwtclaims + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "time" +) + +// discoveryTimeout bounds the OpenID Connect discovery request made at start. +const discoveryTimeout = 15 * time.Second + +// Discover reads the provider's OpenID Connect discovery document (/.well-known/openid-configuration) and +// returns its key set URL. The document must name the same issuer, as the OpenID Connect specification requires. +func Discover(ctx context.Context, client *http.Client, issuer string) (string, error) { + if err := CheckURL(issuer); err != nil { + return "", fmt.Errorf("invalid issuer: %w", err) + } + url := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration" + ctx, cancel := context.WithTimeout(ctx, discoveryTimeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return "", fmt.Errorf("invalid issuer %q: %w", issuer, err) + } + res, err := client.Do(req) + if err != nil { + return "", fmt.Errorf("unable to read %s: %w", url, err) + } + defer func() { _ = res.Body.Close() }() + if res.StatusCode != http.StatusOK { + return "", fmt.Errorf("unable to read %s: %s", url, res.Status) + } + var doc struct { + Issuer string `json:"issuer"` + JWKSURI string `json:"jwks_uri"` + } + if err := json.NewDecoder(io.LimitReader(res.Body, maxDocumentBytes)).Decode(&doc); err != nil { + return "", fmt.Errorf("invalid discovery document at %s: %w", url, err) + } + // Exactly: tokens are checked against the configured issuer as written, trailing slash included. + if doc.Issuer != issuer { + return "", fmt.Errorf("the discovery document at %s names issuer %q, not %q", url, doc.Issuer, issuer) + } + if doc.JWKSURI == "" { + return "", errors.New("the discovery document at " + url + " has no jwks_uri") + } + if err := CheckURL(doc.JWKSURI); err != nil { + return "", fmt.Errorf("the discovery document at %s names an unsafe jwks_uri: %w", url, err) + } + return doc.JWKSURI, nil +} + +// CheckURL accepts an https URL, and plain http only to a loopback host: keys and discovery documents fetched over +// the network in plain text could be replaced on the way, letting anyone sign tokens the engine trusts. +func CheckURL(raw string) error { + u, err := url.Parse(raw) + if err != nil || u.Host == "" { + return fmt.Errorf("%q is not an absolute URL", raw) + } + switch { + case u.Scheme == "https": + return nil + case u.Scheme == "http" && isLoopback(u.Hostname()): + return nil + case u.Scheme == "http": + return fmt.Errorf("%q must use https; plain http is accepted only for a loopback host", raw) + default: + return fmt.Errorf("%q must be an https URL", raw) + } +} + +func isLoopback(host string) bool { + ip := net.ParseIP(host) + return host == "localhost" || ip != nil && ip.IsLoopback() +} diff --git a/engine/plugins/jwtclaims/discovery_test.go b/engine/plugins/jwtclaims/discovery_test.go new file mode 100644 index 0000000..f7ae58f --- /dev/null +++ b/engine/plugins/jwtclaims/discovery_test.go @@ -0,0 +1,106 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package jwtclaims + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func discoveryServer(t *testing.T, body func(base string) string, status int) *httptest.Server { + t.Helper() + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/oauth2/token/.well-known/openid-configuration" { + http.NotFound(w, r) + return + } + w.WriteHeader(status) + _, _ = fmt.Fprint(w, body(srv.URL)) + })) + t.Cleanup(srv.Close) + return srv +} + +func TestDiscover(t *testing.T) { + srv := discoveryServer(t, func(base string) string { + return `{"issuer":"` + base + `/oauth2/token","jwks_uri":"` + base + `/oauth2/jwks"}` + }, http.StatusOK) + got, err := Discover(context.Background(), srv.Client(), srv.URL+"/oauth2/token") + if err != nil || got != srv.URL+"/oauth2/jwks" { + t.Fatalf("Discover = %q, %v", got, err) + } +} + +func TestDiscoverErrors(t *testing.T) { + tests := map[string]struct { + body func(string) string + status int + want string + }{ + "other issuer": {func(string) string { return `{"issuer":"https://evil","jwks_uri":"https://evil/jwks"}` }, 200, "names issuer"}, + "oversized": {func(string) string { return `{"issuer":"` + strings.Repeat("a", maxDocumentBytes) + `"}` }, 200, "invalid discovery document"}, + "issuer with a trailing slash": {func(b string) string { return `{"issuer":"` + b + `/oauth2/token/","jwks_uri":"` + b + `/jwks"}` }, + 200, "names issuer"}, + "plain jwks_uri": {func(b string) string { + return `{"issuer":"` + b + `/oauth2/token","jwks_uri":"http://idp.example/jwks"}` + }, + 200, "unsafe jwks_uri"}, + "no jwks": {func(b string) string { return `{"issuer":"` + b + `/oauth2/token"}` }, 200, "no jwks_uri"}, + "not json": {func(string) string { return "" }, 200, "invalid discovery document"}, + "not found": {func(string) string { return "" }, 404, "404"}, + } + for name, tt := range tests { + srv := discoveryServer(t, tt.body, tt.status) + if _, err := Discover(context.Background(), srv.Client(), srv.URL+"/oauth2/token"); err == nil || + !strings.Contains(err.Error(), tt.want) { + t.Errorf("%s: err = %v, want %q", name, err, tt.want) + } + } + if _, err := Discover(context.Background(), http.DefaultClient, "http://127.0.0.1:1/x"); err == nil { + t.Error("an unreachable issuer was accepted") + } + if _, err := Discover(context.Background(), http.DefaultClient, "://bad"); err == nil { + t.Error("an invalid issuer was accepted") + } + if _, err := Discover(context.Background(), http.DefaultClient, "http://idp.example/oauth2/token"); err == nil || + !strings.Contains(err.Error(), "must use https") { + t.Errorf("a plain http issuer: err = %v", err) + } +} + +func TestCheckURL(t *testing.T) { + for raw, ok := range map[string]bool{ + "https://idp.example/jwks": true, + "http://127.0.0.1:8080/jwks": true, + "http://[::1]:8080/jwks": true, + "http://localhost/jwks": true, + "http://idp.example/jwks": false, + "http://10.0.0.5/jwks": false, + "ftp://idp.example/jwks": false, + "idp.example/jwks": false, + "": false, + } { + if err := CheckURL(raw); (err == nil) != ok { + t.Errorf("CheckURL(%q) = %v, want ok = %v", raw, err, ok) + } + } +} diff --git a/engine/plugins/jwtclaims/jwtclaims.go b/engine/plugins/jwtclaims/jwtclaims.go new file mode 100644 index 0000000..d509114 --- /dev/null +++ b/engine/plugins/jwtclaims/jwtclaims.go @@ -0,0 +1,263 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Package jwtclaims maps tokens from a customer's identity provider to Temporal's namespace roles. +// +// Temporal's default claim mapper reads one top-level claim holding ":" values. Identity providers +// rarely issue that, so this mapper also reads nested or space-separated claims, checks the issuer, and maps group or +// role names to namespace roles through rules. +package jwtclaims + +import ( + "errors" + "fmt" + "regexp" + "strings" + "time" + + "github.com/golang-jwt/jwt/v5" + "go.temporal.io/server/common/authorization" +) + +// AllNamespaces in a rule grants the role in every namespace (Temporal's system-level role). +const AllNamespaces = "*" + +// temporalSystemNamespace is how Temporal's own permission format names the system scope. +const temporalSystemNamespace = "temporal-system" + +const bearer = "bearer" + +// Settings configure the mapper; the zero value of each field has a working default. +type Settings struct { + // Issuer, when set, must equal the token's "iss". + Issuer string + // Audience, when set, must be in the token's "aud". + Audience string + // SubjectClaim names the caller's identity; "sub" by default. + SubjectClaim string + // RolesClaim is a dotted path to a list of strings, or a string of space- or comma-separated values. + RolesClaim string + // ValueRegex parses each value without rules; it needs the named groups "namespace" and "role". + ValueRegex string + // Rules map claim values to namespace roles. Without rules, values are ":". + Rules []Rule + // Leeway tolerates clock skew in "exp", "nbf" and "iat". + Leeway time.Duration +} + +// Rule grants Role in Namespace (or every namespace) to callers whose roles claim contains Value. +type Rule struct { + Value string + Namespace string + Role string +} + +// Mapper is an authorization.ClaimMapper for identity-provider tokens. +type Mapper struct { + keys authorization.TokenKeyProvider + settings Settings + regex *regexp.Regexp + rules map[string][]grant +} + +type grant struct { + namespace string + role authorization.Role +} + +var _ authorization.ClaimMapper = (*Mapper)(nil) + +// New validates the settings and returns a mapper that verifies tokens with keys. +func New(keys authorization.TokenKeyProvider, s Settings) (*Mapper, error) { + if s.SubjectClaim == "" { + s.SubjectClaim = "sub" + } + if s.RolesClaim == "" { + s.RolesClaim = "permissions" + } + m := &Mapper{keys: keys, settings: s, rules: map[string][]grant{}} + if s.ValueRegex != "" { + if len(s.Rules) > 0 { + return nil, errors.New("use either a value regex or rules, not both") + } + r, err := regexp.Compile(s.ValueRegex) + if err != nil { + return nil, fmt.Errorf("invalid value regex: %w", err) + } + if r.SubexpIndex("namespace") < 0 || r.SubexpIndex("role") < 0 { + return nil, errors.New("the value regex needs the named groups \"namespace\" and \"role\"") + } + m.regex = r + } + for _, rule := range s.Rules { + role, ok := ParseRole(rule.Role) + if strings.EqualFold(strings.TrimSpace(rule.Role), "worker") { + return nil, fmt.Errorf("rule for %q: grant write, not worker: Temporal's authorizer needs write for "+ + "an integration's workers to poll and complete tasks", rule.Value) + } + if !ok { + return nil, fmt.Errorf("rule for %q: role %q must be read, write or admin", rule.Value, rule.Role) + } + if rule.Value == "" || rule.Namespace == "" { + return nil, errors.New("every rule needs a value and a namespace") + } + m.rules[rule.Value] = append(m.rules[rule.Value], grant{namespace: rule.Namespace, role: role}) + } + return m, nil +} + +// GetClaims verifies the bearer token and maps its roles claim. A call without a token gets no roles. +func (m *Mapper) GetClaims(info *authorization.AuthInfo) (*authorization.Claims, error) { + claims := &authorization.Claims{AuthType: "jwt"} + if info == nil || info.AuthToken == "" { + return claims, nil + } + scheme, raw, ok := strings.Cut(info.AuthToken, " ") + if !ok || !strings.EqualFold(scheme, bearer) { + return nil, errors.New("the authorization header is not a bearer token") + } + token, err := m.parse(strings.TrimSpace(raw)) + if err != nil { + return nil, err + } + subject, ok := lookup(token, m.settings.SubjectClaim).(string) + if !ok || subject == "" { + return nil, fmt.Errorf("the token has no string %q claim", m.settings.SubjectClaim) + } + claims.Subject = subject + for _, value := range values(lookup(token, m.settings.RolesClaim)) { + m.apply(claims, value) + } + return claims, nil +} + +func (m *Mapper) parse(raw string) (jwt.MapClaims, error) { + opts := []jwt.ParserOption{ + jwt.WithValidMethods(m.keys.SupportedMethods()), + jwt.WithExpirationRequired(), + jwt.WithIssuedAt(), + jwt.WithLeeway(m.settings.Leeway), + } + if m.settings.Issuer != "" { + opts = append(opts, jwt.WithIssuer(m.settings.Issuer)) + } + if m.settings.Audience != "" { + opts = append(opts, jwt.WithAudience(m.settings.Audience)) + } + claims := jwt.MapClaims{} + if _, err := jwt.ParseWithClaims(raw, claims, m.key, opts...); err != nil { + return nil, fmt.Errorf("invalid token: %w", err) + } + return claims, nil +} + +func (m *Mapper) key(token *jwt.Token) (any, error) { + kid, _ := token.Header["kid"].(string) + alg := token.Method.Alg() + switch token.Method.(type) { + case *jwt.SigningMethodRSA, *jwt.SigningMethodRSAPSS: + return m.keys.RsaKey(alg, kid) + case *jwt.SigningMethodECDSA: + return m.keys.EcdsaKey(alg, kid) + case *jwt.SigningMethodHMAC: + return m.keys.HmacKey(alg, kid) + default: + return nil, fmt.Errorf("unsupported signing method %s", alg) + } +} + +func (m *Mapper) apply(claims *authorization.Claims, value string) { + if len(m.rules) > 0 { + for _, g := range m.rules[value] { + grantRole(claims, g.namespace, g.role) + } + return + } + var namespace, roleName string + if m.regex != nil { + match := m.regex.FindStringSubmatch(value) + if match == nil { + return + } + namespace, roleName = match[m.regex.SubexpIndex("namespace")], match[m.regex.SubexpIndex("role")] + } else { + var ok bool + if namespace, roleName, ok = strings.Cut(value, ":"); !ok { + return + } + } + if role, ok := ParseRole(roleName); ok { + grantRole(claims, namespace, role) + } +} + +func grantRole(claims *authorization.Claims, namespace string, role authorization.Role) { + if namespace == AllNamespaces || namespace == temporalSystemNamespace { + claims.System |= role + return + } + if claims.Namespaces == nil { + claims.Namespaces = map[string]authorization.Role{} + } + claims.Namespaces[namespace] |= role +} + +// ParseRole maps a role name to Temporal's role. "worker" is not one: Temporal's default authorizer needs write for a +// worker to poll and complete tasks, so a worker-only grant would refuse every call it was meant for. +func ParseRole(name string) (authorization.Role, bool) { + switch strings.ToLower(strings.TrimSpace(name)) { + case "read", "reader": + return authorization.RoleReader, true + case "write", "writer": + return authorization.RoleWriter, true + case "admin": + return authorization.RoleAdmin, true + } + return authorization.RoleUndefined, false +} + +// lookup follows a dotted path ("realm_access.roles"); a key that itself contains dots is tried first. +func lookup(claims map[string]any, path string) any { + if v, ok := claims[path]; ok { + return v + } + head, rest, ok := strings.Cut(path, ".") + if !ok { + return nil + } + nested, ok := claims[head].(map[string]any) + if !ok { + return nil + } + return lookup(nested, rest) +} + +// values reads a list of strings, or one string of space- or comma-separated values (an OAuth "scope"). +func values(v any) []string { + switch t := v.(type) { + case []any: + out := make([]string, 0, len(t)) + for _, e := range t { + if s, ok := e.(string); ok && s != "" { + out = append(out, s) + } + } + return out + case string: + return strings.FieldsFunc(t, func(r rune) bool { return r == ' ' || r == ',' }) + } + return nil +} diff --git a/engine/plugins/jwtclaims/jwtclaims_test.go b/engine/plugins/jwtclaims/jwtclaims_test.go new file mode 100644 index 0000000..28b6e8c --- /dev/null +++ b/engine/plugins/jwtclaims/jwtclaims_test.go @@ -0,0 +1,259 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package jwtclaims + +import ( + "context" + "crypto/ecdsa" + "crypto/rand" + "crypto/rsa" + "errors" + "strings" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "go.temporal.io/server/common/authorization" +) + +type testKeys struct{ rsa *rsa.PublicKey } + +func (k testKeys) RsaKey(string, string) (*rsa.PublicKey, error) { return k.rsa, nil } +func (testKeys) EcdsaKey(string, string) (*ecdsa.PublicKey, error) { + return nil, errors.New("no ecdsa key") +} +func (testKeys) HmacKey(string, string) ([]byte, error) { return nil, errors.New("no hmac key") } +func (testKeys) SupportedMethods() []string { return []string{"RS256"} } +func (testKeys) Close() {} + +var signingKey = func() *rsa.PrivateKey { + k, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + panic(err) + } + return k +}() + +func token(t *testing.T, claims jwt.MapClaims) string { + t.Helper() + if _, ok := claims["exp"]; !ok { + claims["exp"] = time.Now().Add(time.Hour).Unix() + } + s, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(signingKey) + if err != nil { + t.Fatal(err) + } + return "Bearer " + s +} + +func mapper(t *testing.T, s Settings) *Mapper { + t.Helper() + m, err := New(testKeys{rsa: &signingKey.PublicKey}, s) + if err != nil { + t.Fatalf("New: %v", err) + } + return m +} + +func claimsFor(t *testing.T, m *Mapper, claims jwt.MapClaims) *authorization.Claims { + t.Helper() + c, err := m.GetClaims(&authorization.AuthInfo{AuthToken: token(t, claims)}) + if err != nil { + t.Fatalf("GetClaims: %v", err) + } + return c +} + +func TestTemporalPermissionFormat(t *testing.T) { + c := claimsFor(t, mapper(t, Settings{}), jwt.MapClaims{ + "sub": "worker-1", "permissions": []any{"default:writer", "orders:read", "temporal-system:admin", "bad"}, + }) + if c.Subject != "worker-1" || c.AuthType != "jwt" { + t.Fatalf("subject = %q, auth type = %q", c.Subject, c.AuthType) + } + if c.Namespaces["default"] != authorization.RoleWriter || c.Namespaces["orders"] != authorization.RoleReader { + t.Fatalf("namespaces = %v", c.Namespaces) + } + if c.System != authorization.RoleAdmin { + t.Fatalf("system = %v, want admin", c.System) + } +} + +func TestRulesOnANestedClaim(t *testing.T) { + m := mapper(t, Settings{RolesClaim: "realm_access.roles", Rules: []Rule{ + {Value: "workflow-admins", Namespace: AllNamespaces, Role: "admin"}, + {Value: "claims-team", Namespace: "claims", Role: "writer"}, + {Value: "claims-team", Namespace: "claims", Role: "read"}, + }}) + c := claimsFor(t, m, jwt.MapClaims{"sub": "ann", "realm_access": map[string]any{ + "roles": []any{"claims-team", "unrelated", 7}}}) + if c.Namespaces["claims"] != authorization.RoleWriter|authorization.RoleReader || c.System != 0 { + t.Fatalf("claims = %+v", c) + } + admin := claimsFor(t, m, jwt.MapClaims{"sub": "ops", "realm_access": map[string]any{"roles": []any{"workflow-admins"}}}) + if admin.System != authorization.RoleAdmin { + t.Fatalf("system = %v, want admin", admin.System) + } +} + +func TestScopeStringAndDottedKey(t *testing.T) { + m := mapper(t, Settings{RolesClaim: "scp", SubjectClaim: "client.id", Rules: []Rule{ + {Value: "workflow.read", Namespace: "default", Role: "read"}, + {Value: "workflow.write", Namespace: "default", Role: "write"}, + }}) + c := claimsFor(t, m, jwt.MapClaims{"client.id": "orders-app", "scp": "openid workflow.read,workflow.write"}) + if c.Subject != "orders-app" || c.Namespaces["default"] != authorization.RoleReader|authorization.RoleWriter { + t.Fatalf("claims = %+v", c) + } +} + +func TestValueRegex(t *testing.T) { + m := mapper(t, Settings{RolesClaim: "groups", ValueRegex: `^wf-(?P\w+)-(?P\w+)$`}) + c := claimsFor(t, m, jwt.MapClaims{"sub": "ann", "groups": []any{"wf-claims-admin", "other", "wf-hr-nope"}}) + if c.Namespaces["claims"] != authorization.RoleAdmin || len(c.Namespaces) != 1 { + t.Fatalf("namespaces = %v", c.Namespaces) + } +} + +func TestIssuerAudienceAndExpiry(t *testing.T) { + m := mapper(t, Settings{Issuer: "https://idp", Audience: "workflow-engine"}) + ok := jwt.MapClaims{"sub": "a", "iss": "https://idp", "aud": []any{"workflow-engine", "other"}} + if _, err := m.GetClaims(&authorization.AuthInfo{AuthToken: token(t, ok)}); err != nil { + t.Fatalf("valid token refused: %v", err) + } + for name, claims := range map[string]jwt.MapClaims{ + "wrong issuer": {"sub": "a", "iss": "https://evil", "aud": "workflow-engine"}, + "wrong audience": {"sub": "a", "iss": "https://idp", "aud": "other"}, + "expired": {"sub": "a", "iss": "https://idp", "aud": "workflow-engine", "exp": time.Now().Add(-time.Hour).Unix()}, + "no subject": {"iss": "https://idp", "aud": "workflow-engine"}, + } { + if _, err := m.GetClaims(&authorization.AuthInfo{AuthToken: token(t, claims)}); err == nil { + t.Errorf("%s: token accepted", name) + } + } +} + +func TestTokensThatAreRefused(t *testing.T) { + m := mapper(t, Settings{}) + other, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + forged, err := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"sub": "a", "exp": time.Now().Add(time.Hour).Unix()}). + SignedString(other) + if err != nil { + t.Fatal(err) + } + noExpiry, err := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"sub": "a"}).SignedString(signingKey) + if err != nil { + t.Fatal(err) + } + future, err := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"sub": "a", + "exp": time.Now().Add(2 * time.Hour).Unix(), "iat": time.Now().Add(time.Hour).Unix()}).SignedString(signingKey) + if err != nil { + t.Fatal(err) + } + for name, header := range map[string]string{ + "basic": "Basic dXNlcjpwYXNz", + "no scheme": "abc", + "forged": "Bearer " + forged, + "no expiry": "Bearer " + noExpiry, + "issued in the future": "Bearer " + future, + "garbage": "Bearer not.a.token", + } { + if _, err := m.GetClaims(&authorization.AuthInfo{AuthToken: header}); err == nil { + t.Errorf("%s: accepted", name) + } + } +} + +func TestNoTokenGetsNoRoles(t *testing.T) { + c, err := mapper(t, Settings{}).GetClaims(&authorization.AuthInfo{}) + if err != nil || c.Subject != "" || c.System != 0 || len(c.Namespaces) != 0 { + t.Fatalf("claims = %+v, err = %v", c, err) + } + if c, err := mapper(t, Settings{}).GetClaims(nil); err != nil || c == nil { + t.Fatalf("nil auth info: %+v, %v", c, err) + } +} + +func TestInvalidSettings(t *testing.T) { + for name, s := range map[string]Settings{ + "bad regex": {ValueRegex: "("}, + "missing groups": {ValueRegex: `^(\w+)$`}, + "regex and rules": {ValueRegex: `^(?P\w+):(?P\w+)$`, Rules: []Rule{{Value: "a", Namespace: "b", Role: "read"}}}, + "bad role": {Rules: []Rule{{Value: "a", Namespace: "b", Role: "owner"}}}, + "empty rule": {Rules: []Rule{{Role: "read"}}}, + } { + if _, err := New(testKeys{}, s); err == nil { + t.Errorf("%s: accepted", name) + } + } +} + +func TestUnsupportedKeyType(t *testing.T) { + m := mapper(t, Settings{}) + if _, err := m.key(&jwt.Token{Method: jwt.SigningMethodNone, Header: map[string]any{}}); err == nil || + !strings.Contains(err.Error(), "unsupported") { + t.Fatalf("key = %v", err) + } + if _, err := m.key(&jwt.Token{Method: jwt.SigningMethodES256, Header: map[string]any{}}); err == nil { + t.Fatal("ecdsa key without a provider key accepted") + } + if _, err := m.key(&jwt.Token{Method: jwt.SigningMethodHS256, Header: map[string]any{}}); err == nil { + t.Fatal("hmac key without a provider key accepted") + } +} + +func TestWorkerRoleIsRefused(t *testing.T) { + _, err := New(testKeys{}, Settings{Rules: []Rule{{Value: "orders-app", Namespace: "orders", Role: "worker"}}}) + if err == nil || !strings.Contains(err.Error(), "grant write, not worker") { + t.Fatalf("New = %v, want the worker role refused", err) + } + c := claimsFor(t, mapper(t, Settings{}), jwt.MapClaims{"sub": "app", "permissions": []any{"orders:worker"}}) + if c.Namespaces["orders"] != authorization.RoleUndefined { + t.Fatalf("namespaces = %v, want no role from orders:worker", c.Namespaces) + } +} + +// TestGrantsThroughTemporalsAuthorizer checks the mapped roles against the authorizer the engine configures. +func TestGrantsThroughTemporalsAuthorizer(t *testing.T) { + m := mapper(t, Settings{RolesClaim: "groups", Rules: []Rule{ + {Value: "orders-app", Namespace: "orders", Role: "write"}, + {Value: "auditors", Namespace: "orders", Role: "read"}, + }}) + authorizer := authorization.NewDefaultAuthorizer() + poll := &authorization.CallTarget{APIName: "/temporal.api.workflowservice.v1.WorkflowService/PollWorkflowTaskQueue", + Namespace: "orders"} + for name, tt := range map[string]struct { + groups []any + namespace string + want authorization.Decision + }{ + "write polls": {[]any{"orders-app"}, "orders", authorization.DecisionAllow}, + "read cannot poll": {[]any{"auditors"}, "orders", authorization.DecisionDeny}, + "write in another namespace": {[]any{"orders-app"}, "billing", authorization.DecisionDeny}, + } { + c := claimsFor(t, m, jwt.MapClaims{"sub": "caller", "groups": tt.groups}) + target := *poll + target.Namespace = tt.namespace + result, err := authorizer.Authorize(context.Background(), c, &target) + if err != nil || result.Decision != tt.want { + t.Errorf("%s: decision = %v (%v), want %v", name, result.Decision, err, tt.want) + } + } +} diff --git a/engine/plugins/jwtclaims/keyset.go b/engine/plugins/jwtclaims/keyset.go new file mode 100644 index 0000000..03d2d1c --- /dev/null +++ b/engine/plugins/jwtclaims/keyset.go @@ -0,0 +1,282 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package jwtclaims + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rsa" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "math/big" + "net/http" + "slices" + "strings" + "sync" + "time" + + "github.com/golang-jwt/jwt/v5" + "go.temporal.io/server/common/authorization" + "go.temporal.io/server/common/log" + "go.temporal.io/server/common/log/tag" +) + +// maxRedirects is net/http's own limit. +const maxRedirects = 10 + +// maxDocumentBytes bounds a discovery document or key set, which are a few kilobytes in practice. +const maxDocumentBytes = 1 << 20 + +// Client returns the HTTP client for discovery and key sets. It follows a redirect only to a URL CheckURL accepts, so +// an https endpoint cannot hand the request to plain http. +func Client(timeout time.Duration) *http.Client { + return &http.Client{Timeout: timeout, CheckRedirect: checkRedirect} +} + +func checkRedirect(req *http.Request, via []*http.Request) error { + if len(via) >= maxRedirects { + return fmt.Errorf("stopped after %d redirects", maxRedirects) + } + if err := CheckURL(req.URL.String()); err != nil { + return fmt.Errorf("refused a redirect: %w", err) + } + if via[0].URL.Scheme == "https" && req.URL.Scheme != "https" { + return fmt.Errorf("refused a redirect from https to %s", req.URL.Redacted()) + } + return nil +} + +// KeySet provides the RS256 and ES256 keys of JWKS URLs, refreshed on an interval, as Temporal's default provider +// does. It fetches through Client: Temporal's provider uses http.Get, which follows a redirect to plain http. +type KeySet struct { + urls []string + client *http.Client + logger log.Logger + + mu sync.RWMutex + rsa map[string]*rsa.PublicKey + ec map[string]*ecdsa.PublicKey + + stop chan struct{} + stopOnce sync.Once +} + +var _ authorization.TokenKeyProvider = (*KeySet)(nil) + +// NewKeySet reads the keys once and then every refresh (none when 0). A failed read is logged and the previous keys +// stay, so a provider that is briefly down does not stop the engine. +func NewKeySet(urls []string, refresh time.Duration, client *http.Client, logger log.Logger) *KeySet { + k := &KeySet{urls: urls, client: client, logger: logger, rsa: map[string]*rsa.PublicKey{}, + ec: map[string]*ecdsa.PublicKey{}, stop: make(chan struct{})} + if err := k.Refresh(); err != nil { + logger.Error("unable to read the token keys", tag.Error(err)) + } + if refresh > 0 { + go k.refreshEvery(refresh) + } + return k +} + +func (k *KeySet) refreshEvery(interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-k.stop: + return + case <-ticker.C: + if err := k.Refresh(); err != nil { + k.logger.Error("unable to refresh the token keys", tag.Error(err)) + } + } + } +} + +// Refresh reads every URL and replaces the keys only when all of them were read. +func (k *KeySet) Refresh() error { + rsaKeys, ecKeys := map[string]*rsa.PublicKey{}, map[string]*ecdsa.PublicKey{} + for _, u := range k.urls { + if strings.TrimSpace(u) == "" { + continue + } + if err := k.read(u, rsaKeys, ecKeys); err != nil { + return err + } + } + k.mu.Lock() + k.rsa, k.ec = rsaKeys, ecKeys + k.mu.Unlock() + return nil +} + +func (k *KeySet) read(u string, rsaKeys map[string]*rsa.PublicKey, ecKeys map[string]*ecdsa.PublicKey) error { + if err := CheckURL(u); err != nil { + return err + } + res, err := k.client.Get(u) + if err != nil { + return fmt.Errorf("unable to read %s: %w", u, err) + } + defer func() { _ = res.Body.Close() }() + if res.StatusCode != http.StatusOK { + return fmt.Errorf("unable to read %s: %s", u, res.Status) + } + // A pointer tells a missing "keys" (an error page served with 200) from an empty set, which is valid. + var set struct { + Keys *[]jwk `json:"keys"` + } + if err := json.NewDecoder(io.LimitReader(res.Body, maxDocumentBytes)).Decode(&set); err != nil { + return fmt.Errorf("invalid key set at %s: %w", u, err) + } + if set.Keys == nil { + return fmt.Errorf("invalid key set at %s: it has no keys member", u) + } + for _, key := range *set.Keys { + if err := key.store(rsaKeys, ecKeys); err != nil { + k.logger.Warn(fmt.Sprintf("ignoring key %q from %s: %v", key.Kid, u, err)) + } + } + return nil +} + +// store adds the key to its map when it is valid and published for verifying signatures with RS256 or ES256; a bad +// entry never replaces a good key with the same ID. +func (j jwk) store(rsaKeys map[string]*rsa.PublicKey, ecKeys map[string]*ecdsa.PublicKey) error { + switch j.Kty { + case "RSA": + if err := j.allows(jwt.SigningMethodRS256.Name); err != nil { + return err + } + pub, err := j.rsa() + if err != nil { + return err + } + rsaKeys[j.Kid] = pub + case "EC": + if err := j.allows(jwt.SigningMethodES256.Name); err != nil { + return err + } + pub, err := j.ecdsa() + if err != nil { + return err + } + ecKeys[j.Kid] = pub + default: + return fmt.Errorf("unsupported key type %q", j.Kty) + } + return nil +} + +// allows refuses a key whose published use, operations or algorithm exclude verifying alg signatures; a key that +// states none of them is accepted, as most providers publish only kty and kid. +func (j jwk) allows(alg string) error { + if j.Use != "" && j.Use != "sig" { + return fmt.Errorf("its use is %q, not sig", j.Use) + } + if len(j.KeyOps) > 0 && !slices.Contains(j.KeyOps, "verify") { + return errors.New("its key_ops do not include verify") + } + if j.Alg != "" && j.Alg != alg { + return fmt.Errorf("its alg is %q, not %s", j.Alg, alg) + } + return nil +} + +// jwk is the part of a JSON Web Key (RFC 7517, 7518) that RS256 and ES256 need. +type jwk struct { + Kty string `json:"kty"` + Kid string `json:"kid"` + Use string `json:"use"` + KeyOps []string `json:"key_ops"` + Alg string `json:"alg"` + N string `json:"n"` + E string `json:"e"` + Crv string `json:"crv"` + X string `json:"x"` + Y string `json:"y"` +} + +func (j jwk) rsa() (*rsa.PublicKey, error) { + n, err := base64.RawURLEncoding.DecodeString(j.N) + if err != nil || len(n) == 0 { + return nil, errors.New("invalid RSA modulus") + } + e, err := base64.RawURLEncoding.DecodeString(j.E) + if err != nil || len(e) == 0 || len(e) > 4 { + return nil, errors.New("invalid RSA exponent") + } + exp := int(new(big.Int).SetBytes(e).Int64()) + if exp < 3 || exp%2 == 0 { + return nil, errors.New("invalid RSA exponent") + } + return &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: exp}, nil +} + +// ecdsa reads a P-256 key, the curve ES256 signs with; the point is checked to be on the curve. +func (j jwk) ecdsa() (*ecdsa.PublicKey, error) { + if j.Crv != "P-256" { + return nil, fmt.Errorf("unsupported curve %q", j.Crv) + } + x, errX := base64.RawURLEncoding.DecodeString(j.X) + y, errY := base64.RawURLEncoding.DecodeString(j.Y) + if errX != nil || errY != nil || len(x) != 32 || len(y) != 32 { + return nil, errors.New("invalid P-256 coordinates") + } + return ecdsa.ParseUncompressedPublicKey(elliptic.P256(), append(append([]byte{4}, x...), y...)) +} + +// RsaKey returns the RS256 key with the key ID kid. +func (k *KeySet) RsaKey(alg, kid string) (*rsa.PublicKey, error) { + if !strings.EqualFold(alg, jwt.SigningMethodRS256.Name) { + return nil, fmt.Errorf("unexpected signing algorithm: %s", alg) + } + k.mu.RLock() + defer k.mu.RUnlock() + if key, ok := k.rsa[kid]; ok { + return key, nil + } + return nil, fmt.Errorf("RSA key not found for key ID: %s", kid) +} + +// EcdsaKey returns the ES256 key with the key ID kid. +func (k *KeySet) EcdsaKey(alg, kid string) (*ecdsa.PublicKey, error) { + if !strings.EqualFold(alg, jwt.SigningMethodES256.Name) { + return nil, fmt.Errorf("unexpected signing algorithm: %s", alg) + } + k.mu.RLock() + defer k.mu.RUnlock() + if key, ok := k.ec[kid]; ok { + return key, nil + } + return nil, fmt.Errorf("ECDSA key not found for key ID: %s", kid) +} + +// HmacKey refuses HMAC: a shared secret is not a key set. +func (k *KeySet) HmacKey(alg, _ string) ([]byte, error) { + return nil, fmt.Errorf("unsupported key type HMAC for: %s", alg) +} + +// SupportedMethods is RS256 and ES256, as Temporal's default provider. +func (k *KeySet) SupportedMethods() []string { + return []string{jwt.SigningMethodRS256.Name, jwt.SigningMethodES256.Name} +} + +// Close stops the refresh. +func (k *KeySet) Close() { k.stopOnce.Do(func() { close(k.stop) }) } diff --git a/engine/plugins/jwtclaims/keyset_test.go b/engine/plugins/jwtclaims/keyset_test.go new file mode 100644 index 0000000..135067a --- /dev/null +++ b/engine/plugins/jwtclaims/keyset_test.go @@ -0,0 +1,292 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package jwtclaims + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "encoding/base64" + "fmt" + "math/big" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "go.temporal.io/server/common/log" +) + +var b64 = base64.RawURLEncoding.EncodeToString + +func keySetJSON(t *testing.T, ec *ecdsa.PrivateKey) string { + t.Helper() + point, err := ec.PublicKey.Bytes() + if err != nil { + t.Fatal(err) + } + pub := signingKey.PublicKey + return fmt.Sprintf(`{"keys":[ + {"kty":"RSA","kid":"rsa-1","alg":"RS256","use":"sig","n":%q,"e":%q}, + {"kty":"EC","kid":"ec-1","alg":"ES256","crv":"P-256","x":%q,"y":%q}, + {"kty":"oct","kid":"hmac-1","k":"c2VjcmV0"}, + {"kty":"EC","kid":"off-curve","crv":"P-256","x":%q,"y":%q}]}`, + b64(pub.N.Bytes()), b64(big.NewInt(int64(pub.E)).Bytes()), b64(point[1:33]), b64(point[33:]), + b64(point[1:33]), b64(point[1:33])) +} + +// tlsClient is Client trusting the test server's certificate. +func tlsClient(srv *httptest.Server) *http.Client { + c := Client(5 * time.Second) + c.Transport = srv.Client().Transport + return c +} + +func TestKeySetReadsAndRefreshesKeys(t *testing.T) { + ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + var down atomic.Bool + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if down.Load() { + http.Error(w, "down", http.StatusServiceUnavailable) + return + } + _, _ = w.Write([]byte(keySetJSON(t, ec))) + })) + t.Cleanup(srv.Close) + + k := NewKeySet([]string{srv.URL + "/jwks"}, 0, tlsClient(srv), log.NewNoopLogger()) + t.Cleanup(k.Close) + if key, err := k.RsaKey("RS256", "rsa-1"); err != nil || !key.Equal(&signingKey.PublicKey) { + t.Fatalf("RsaKey = %v, %v", key, err) + } + if key, err := k.EcdsaKey("ES256", "ec-1"); err != nil || !key.Equal(&ec.PublicKey) { + t.Fatalf("EcdsaKey = %v, %v", key, err) + } + if _, err := k.RsaKey("RS512", "rsa-1"); err == nil { + t.Fatal("RsaKey accepted another algorithm") + } + if _, err := k.RsaKey("RS256", "unknown"); err == nil { + t.Fatal("RsaKey found an unknown key ID") + } + if _, err := k.EcdsaKey("ES256", "off-curve"); err == nil { + t.Fatal("EcdsaKey accepted a point that is not on the curve") + } + + down.Store(true) + if err := k.Refresh(); err == nil || !strings.Contains(err.Error(), "503") { + t.Fatalf("Refresh = %v, want the provider's 503", err) + } + if _, err := k.RsaKey("RS256", "rsa-1"); err != nil { + t.Fatalf("a failed refresh dropped the keys: %v", err) + } +} + +// redirectServer is an https server that redirects every request to target. +func redirectServer(t *testing.T, target string) *httptest.Server { + t.Helper() + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target, http.StatusFound) + })) + t.Cleanup(srv.Close) + return srv +} + +func TestRedirectsToPlainHTTPAreRefused(t *testing.T) { + // Never reached: the client refuses the redirect before it connects. + srv := redirectServer(t, "http://idp.example/jwks") + + k := NewKeySet([]string{srv.URL + "/jwks"}, 0, tlsClient(srv), log.NewNoopLogger()) + t.Cleanup(k.Close) + if err := k.Refresh(); err == nil || !strings.Contains(err.Error(), "refused a redirect") { + t.Fatalf("key set Refresh = %v, want a refused redirect", err) + } + if _, err := Discover(context.Background(), tlsClient(srv), srv.URL); err == nil || + !strings.Contains(err.Error(), "refused a redirect") { + t.Fatalf("Discover = %v, want a refused redirect", err) + } +} + +func TestRedirectsToHTTPSAreFollowed(t *testing.T) { + ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + target := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(keySetJSON(t, ec))) + })) + t.Cleanup(target.Close) + srv := redirectServer(t, target.URL+"/jwks") + + k := NewKeySet([]string{srv.URL + "/jwks"}, 0, tlsClient(srv), log.NewNoopLogger()) + t.Cleanup(k.Close) + if _, err := k.RsaKey("RS256", "rsa-1"); err != nil { + t.Fatalf("an https redirect was not followed: %v", err) + } +} + +func TestKeySetRefusesPlainHTTPURLs(t *testing.T) { + k := NewKeySet([]string{"http://idp.example/jwks"}, 0, Client(time.Second), log.NewNoopLogger()) + t.Cleanup(k.Close) + if err := k.Refresh(); err == nil || !strings.Contains(err.Error(), "must use https") { + t.Fatalf("Refresh = %v, want a refused URL", err) + } +} + +func TestKeySetRefreshesOnItsInterval(t *testing.T) { + var reads atomic.Int32 + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + reads.Add(1) + _, _ = w.Write([]byte(`{"keys":[]}`)) + })) + t.Cleanup(srv.Close) + k := NewKeySet([]string{srv.URL}, 10*time.Millisecond, tlsClient(srv), log.NewNoopLogger()) + deadline := time.Now().Add(5 * time.Second) + for reads.Load() < 3 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + k.Close() + k.Close() // a second Close is harmless + if reads.Load() < 3 { + t.Fatalf("the key set was read %d times, want a refresh", reads.Load()) + } +} + +func TestInvalidKeysAreRejected(t *testing.T) { + for name, key := range map[string]jwk{ + "RSA without a modulus": {Kty: "RSA", E: "AQAB"}, + "RSA with an even e": {Kty: "RSA", N: "AQAB", E: "Ag"}, + "RSA with a huge e": {Kty: "RSA", N: "AQAB", E: "AQIDBAU"}, + "EC on another curve": {Kty: "EC", Crv: "P-384", X: "AA", Y: "AA"}, + "EC with short points": {Kty: "EC", Crv: "P-256", X: "AA", Y: "AA"}, + "EC with bad base64url": {Kty: "EC", Crv: "P-256", X: "!", Y: "!"}, + } { + var err error + if key.Kty == "RSA" { + _, err = key.rsa() + } else { + _, err = key.ecdsa() + } + if err == nil { + t.Errorf("%s: accepted", name) + } + } +} + +func TestRedirectsFromHTTPSToLoopbackHTTPAreRefused(t *testing.T) { + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"keys":[]}`)) + })) + t.Cleanup(target.Close) + srv := redirectServer(t, target.URL+"/jwks") + k := NewKeySet([]string{srv.URL + "/jwks"}, 0, tlsClient(srv), log.NewNoopLogger()) + t.Cleanup(k.Close) + if err := k.Refresh(); err == nil || !strings.Contains(err.Error(), "from https to") { + t.Fatalf("Refresh = %v, want the downgrade refused", err) + } +} + +func TestOnlySignatureKeysAreKept(t *testing.T) { + ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + point, err := ec.PublicKey.Bytes() + if err != nil { + t.Fatal(err) + } + pub := signingKey.PublicKey + n, e := b64(pub.N.Bytes()), b64(big.NewInt(int64(pub.E)).Bytes()) + x, y := b64(point[1:33]), b64(point[33:]) + set := fmt.Sprintf(`{"keys":[ + {"kty":"RSA","kid":"dup","n":%[1]q,"e":%[2]q}, + {"kty":"RSA","kid":"dup","n":%[1]q,"e":"Ag"}, + {"kty":"RSA","kid":"sig","use":"sig","alg":"RS256","key_ops":["verify"],"n":%[1]q,"e":%[2]q}, + {"kty":"RSA","kid":"enc","use":"enc","n":%[1]q,"e":%[2]q}, + {"kty":"RSA","kid":"ops","key_ops":["encrypt"],"n":%[1]q,"e":%[2]q}, + {"kty":"RSA","kid":"rs512","alg":"RS512","n":%[1]q,"e":%[2]q}, + {"kty":"EC","kid":"ec-enc","use":"enc","crv":"P-256","x":%[3]q,"y":%[4]q}, + {"kty":"EC","kid":"ec-alg","alg":"ES384","crv":"P-256","x":%[3]q,"y":%[4]q}]}`, n, e, x, y) + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(set)) + })) + t.Cleanup(srv.Close) + k := NewKeySet([]string{srv.URL}, 0, tlsClient(srv), log.NewNoopLogger()) + t.Cleanup(k.Close) + for _, kid := range []string{"dup", "sig"} { + if _, err := k.RsaKey("RS256", kid); err != nil { + t.Errorf("RSA key %s was dropped: %v", kid, err) + } + } + for _, kid := range []string{"enc", "ops", "rs512"} { + if _, err := k.RsaKey("RS256", kid); err == nil { + t.Errorf("RSA key %s, not for RS256 signatures, was kept", kid) + } + } + for _, kid := range []string{"ec-enc", "ec-alg"} { + if _, err := k.EcdsaKey("ES256", kid); err == nil { + t.Errorf("EC key %s, not for ES256 signatures, was kept", kid) + } + } +} + +func TestOversizedKeySetsAreRefused(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"keys":[{"kty":"RSA","kid":"` + strings.Repeat("a", maxDocumentBytes) + `"}]}`)) + })) + t.Cleanup(srv.Close) + k := NewKeySet([]string{srv.URL}, 0, tlsClient(srv), log.NewNoopLogger()) + t.Cleanup(k.Close) + if err := k.Refresh(); err == nil || !strings.Contains(err.Error(), "invalid key set") { + t.Fatalf("Refresh = %v, want an oversized key set refused", err) + } +} + +func TestKeySetWithoutKeysKeepsThePreviousKeys(t *testing.T) { + ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + var body atomic.Value + body.Store(keySetJSON(t, ec)) + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(body.Load().(string))) + })) + t.Cleanup(srv.Close) + k := NewKeySet([]string{srv.URL}, 0, tlsClient(srv), log.NewNoopLogger()) + t.Cleanup(k.Close) + + body.Store(`{"error":"upstream"}`) + if err := k.Refresh(); err == nil || !strings.Contains(err.Error(), "no keys member") { + t.Fatalf("Refresh = %v, want a set without keys refused", err) + } + if _, err := k.RsaKey("RS256", "rsa-1"); err != nil { + t.Fatalf("a refused refresh dropped the keys: %v", err) + } + body.Store(`{"keys":[]}`) + if err := k.Refresh(); err != nil { + t.Fatalf("an empty key set was refused: %v", err) + } + if _, err := k.RsaKey("RS256", "rsa-1"); err == nil { + t.Fatal("an empty key set kept the old keys") + } +} diff --git a/third-party/go-licenses.csv b/third-party/go-licenses.csv index 007de66..1735003 100644 --- a/third-party/go-licenses.csv +++ b/third-party/go-licenses.csv @@ -87,6 +87,7 @@ github.com/go-viper/mapstructure/v2,https://github.com/go-viper/mapstructure/blo github.com/gocql/gocql,https://github.com/gocql/gocql/blob/v1.7.0/LICENSE,Apache-2.0 github.com/gogo/protobuf,https://github.com/gogo/protobuf/blob/v1.3.2/LICENSE,BSD-3-Clause github.com/golang-jwt/jwt/v4,https://github.com/golang-jwt/jwt/blob/v4.5.2/LICENSE,MIT +github.com/golang-jwt/jwt/v5,https://github.com/golang-jwt/jwt/blob/v5.3.1/LICENSE,MIT github.com/golang/mock,https://github.com/golang/mock/blob/v1.6.0/LICENSE,Apache-2.0 github.com/golang/snappy,https://github.com/golang/snappy/blob/v1.0.0/LICENSE,BSD-3-Clause github.com/google/gnostic-models,https://github.com/google/gnostic-models/blob/v0.7.1/LICENSE,Apache-2.0 diff --git a/tools/internal/enginetest/cluster_test.go b/tools/internal/enginetest/cluster_test.go new file mode 100644 index 0000000..60bd466 --- /dev/null +++ b/tools/internal/enginetest/cluster_test.go @@ -0,0 +1,81 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package enginetest + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// TestTwoSecuredNodesFormOneEngine runs the secured configuration as two nodes on one SQLite file: the first runs the +// frontend, matching and worker, the second the frontend and history. A workflow started through the first node needs +// the second node's history, so it runs only if the nodes find each other over TLS-protected membership and call each +// other over internode TLS. +// startBusy is start, tried again when the engine stopped on SQLITE_BUSY: two processes on one SQLite file, which +// only this test does, can collide on the start-up write of the cluster metadata. +func startBusy(t *testing.T, binary string, base int, flags []string, args ...string) *engine { + t.Helper() + for attempt := 1; ; attempt++ { + e, err := launch(t, binary, base, flags, args...) + if err == nil { + return e + } + if attempt == 3 || !strings.Contains(err.Error(), "SQLITE_BUSY") { + t.Fatal(err) + } + t.Logf("attempt %d stopped on SQLITE_BUSY; starting the node again", attempt) + } +} + +func TestTwoSecuredNodesFormOneEngine(t *testing.T) { + binary := engineBinary(t) + se := newSecuredEngine(t) + data, err := os.ReadFile(se.config) //nolint:gosec // a test file + if err != nil { + t.Fatal(err) + } + memory := "[database]\ntype = \"sqlite\"\ninMemory = true\n" + if !strings.Contains(string(data), memory) { + t.Fatal("the secured configuration no longer uses an in-memory database") + } + shared := strings.Replace(string(data), memory, + "[database]\ntype = \"sqlite\"\npath = "+tomlString(filepath.Join(t.TempDir(), "engine.db"))+"\n", 1) + node := func(base int, profiles string) string { + toml := "[runtime]\nprofiles = " + profiles + "\n" + strings.Replace(shared, ports(se.base), ports(base), 1) + return writeConfig(t, t.TempDir(), toml) + } + admin := []string{"--tls-ca-path", se.frontend.caFile("frontend-ca"), + "--api-key", se.idp.token(map[string]any{"sub": "ops", "groups": []any{"workflow-admins"}}, nil)} + + first := start(t, binary, se.base, admin, "start", "--runtime-config", + node(se.base, `["frontend", "matching", "worker"]`)) + base := freeBase(t) + second := startBusy(t, binary, base, admin, "start", "--runtime-config", node(base, `["frontend", "history"]`)) + first.must("operator", "namespace", "create", "--namespace", "orders", "--retention", "24h") + first.must("workflow", "start", "--namespace", "orders", "--type", "Order", "--task-queue", "orders", + "--workflow-id", "order-1") + if got := second.workflow("orders", "order-1"); got.Status != "WORKFLOW_EXECUTION_STATUS_RUNNING" { + t.Fatalf("the second node sees order-1 as %q, want it running", got.Status) + } + for _, e := range []*engine{first, second} { + if strings.Contains(e.log.String(), "either ServerName or InsecureSkipVerify") { + t.Errorf("an internode connection had no server name:\n%s", e.log) + } + } +} diff --git a/tools/internal/enginetest/engine_test.go b/tools/internal/enginetest/engine_test.go index 417a96e..82e1a99 100644 --- a/tools/internal/enginetest/engine_test.go +++ b/tools/internal/enginetest/engine_test.go @@ -40,20 +40,21 @@ type engine struct { log *bytes.Buffer address string done chan struct{} // closed when the process exits + // flags go on every Temporal CLI call, such as the CA and a token for a secured engine. + flags []string } -// binaries returns the engine binary and the temporal CLI, or skips the test. -func binaries(t *testing.T) (string, string) { +// engineBinary returns the engine binary, or skips the test when it or the temporal CLI is missing. +func engineBinary(t *testing.T) string { t.Helper() path := os.Getenv("WORKFLOW_ENGINE") if path == "" { t.Skip("WORKFLOW_ENGINE does not name the engine binary") } - cli, err := exec.LookPath("temporal") - if err != nil { + if _, err := exec.LookPath("temporal"); err != nil { t.Skip("the temporal CLI is not on PATH") } - return path, cli + return path } // freeBase finds a frontend port whose service ports (+1 to +10) and membership ports (-300) are free. It holds the @@ -94,15 +95,25 @@ func writeConfig(t *testing.T, dir, toml string) string { return path } -// start runs the engine with args and waits until its frontend reports SERVING. -func start(t *testing.T, binary string, base int, args ...string) *engine { +// start runs the engine with args and waits until its frontend reports SERVING to a CLI call with flags. +func start(t *testing.T, binary string, base int, flags []string, args ...string) *engine { + t.Helper() + e, err := launch(t, binary, base, flags, args...) + if err != nil { + t.Fatal(err) + } + return e +} + +// launch is start, returning an engine that stopped or never reported SERVING as an error. +func launch(t *testing.T, binary string, base int, flags []string, args ...string) (*engine, error) { t.Helper() lockPorts(t) // already held when freeBase or a restart took it - e := &engine{t: t, log: &bytes.Buffer{}, address: fmt.Sprintf("127.0.0.1:%d", base)} + e := &engine{t: t, log: &bytes.Buffer{}, address: fmt.Sprintf("127.0.0.1:%d", base), flags: flags} e.cmd = exec.Command(binary, args...) //nolint:gosec // the engine under test e.cmd.Stdout, e.cmd.Stderr = e.log, e.log if err := e.cmd.Start(); err != nil { - t.Fatal(err) + return nil, err } e.done = make(chan struct{}) go func() { _ = e.cmd.Wait(); close(e.done) }() @@ -111,17 +122,17 @@ func start(t *testing.T, binary string, base int, args ...string) *engine { for time.Now().Before(deadline) { select { case <-e.done: - t.Fatalf("the engine exited before it reported SERVING:\n%s", e.log) + return nil, fmt.Errorf("the engine exited before it reported SERVING:\n%s", e.log) default: } if out, err := e.temporal("operator", "cluster", "health"); err == nil && strings.Contains(out, "SERVING") { unlockPorts() - return e + return e, nil } time.Sleep(time.Second) } - t.Fatalf("the engine did not report SERVING within %s:\n%s", startTimeout, e.log) - return nil + e.stop() // free its ports before a caller starts another engine on them + return nil, fmt.Errorf("the engine did not report SERVING within %s:\n%s", startTimeout, e.log) } // stop ends the engine with SIGTERM, as a service manager does, and waits for it. @@ -144,11 +155,17 @@ func (e *engine) stop() { } } -// temporal runs the Temporal CLI against this engine. +// temporal runs the Temporal CLI against this engine's frontend with its flags. func (e *engine) temporal(args ...string) (string, error) { + return e.temporalAt(e.address, e.flags, args...) +} + +// temporalAt runs the Temporal CLI against any address with the given flags. +func (e *engine) temporalAt(address string, flags []string, args ...string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - cmd := exec.CommandContext(ctx, "temporal", append(args, "--address", e.address)...) //nolint:gosec // test calls + all := append(append(append([]string{}, args...), "--address", address), flags...) + cmd := exec.CommandContext(ctx, "temporal", all...) //nolint:gosec // test calls out, err := cmd.CombinedOutput() return string(out), err } diff --git a/tools/internal/enginetest/security_helpers_test.go b/tools/internal/enginetest/security_helpers_test.go new file mode 100644 index 0000000..afc8748 --- /dev/null +++ b/tools/internal/enginetest/security_helpers_test.go @@ -0,0 +1,189 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package enginetest + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/json" + "encoding/pem" + "errors" + "math/big" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" +) + +// pki is a test certificate authority writing PEM files into a directory. +type pki struct { + t *testing.T + dir string + key *rsa.PrivateKey + cert *x509.Certificate +} + +func newPKI(t *testing.T, dir, name string) *pki { + t.Helper() + key := rsaKey(t) + tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: name}, IsCA: true, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), + KeyUsage: x509.KeyUsageCertSign, BasicConstraintsValid: true} + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + cert, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + p := &pki{t: t, dir: dir, key: key, cert: cert} + p.write(name+".pem", "CERTIFICATE", der) + return p +} + +// issue writes .crt and .key for 127.0.0.1 and localhost, usable by servers and clients. +func (p *pki) issue(name string) (certFile, keyFile string) { + p.t.Helper() + key := rsaKey(p.t) + tmpl := &x509.Certificate{SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: name}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, DNSNames: []string{"localhost"}} + der, err := x509.CreateCertificate(rand.Reader, tmpl, p.cert, &key.PublicKey, p.key) + if err != nil { + p.t.Fatal(err) + } + return p.write(name+".crt", "CERTIFICATE", der), p.write(name+".key", "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(key)) +} + +func (p *pki) caFile(name string) string { return filepath.Join(p.dir, name+".pem") } + +func (p *pki) write(name, kind string, der []byte) string { + p.t.Helper() + path := filepath.Join(p.dir, name) + if err := os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: kind, Bytes: der}), 0o600); err != nil { + p.t.Fatal(err) + } + return path +} + +func rsaKey(t *testing.T) *rsa.PrivateKey { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + return key +} + +// identityProvider serves an OpenID Connect discovery document and a key set, and signs RS256 tokens. +type identityProvider struct { + t *testing.T + key *rsa.PrivateKey + issuer string +} + +func newIdentityProvider(t *testing.T) *identityProvider { + t.Helper() + p := &identityProvider{t: t, key: rsaKey(t)} + mux := http.NewServeMux() + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + p.issuer = srv.URL + "/oauth2/token" + mux.HandleFunc("/oauth2/token/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]string{"issuer": p.issuer, "jwks_uri": srv.URL + "/oauth2/jwks"}) + }) + mux.HandleFunc("/oauth2/jwks", func(w http.ResponseWriter, _ *http.Request) { + b64 := base64.RawURLEncoding.EncodeToString + _ = json.NewEncoder(w).Encode(map[string]any{"keys": []any{map[string]string{"kty": "RSA", "kid": "k1", + "alg": "RS256", "use": "sig", "n": b64(p.key.N.Bytes()), "e": b64(big.NewInt(int64(p.key.E)).Bytes())}}}) + }) + return p +} + +// token signs claims with key (the provider's own unless forged), adding the issuer and an hour's expiry. +func (p *identityProvider) token(claims map[string]any, key *rsa.PrivateKey) string { + p.t.Helper() + if key == nil { + key = p.key + } + if _, ok := claims["iss"]; !ok { + claims["iss"] = p.issuer + } + if _, ok := claims["exp"]; !ok { + claims["exp"] = time.Now().Add(time.Hour).Unix() + } + enc := func(v any) string { + b, err := json.Marshal(v) + if err != nil { + p.t.Fatal(err) + } + return base64.RawURLEncoding.EncodeToString(b) + } + signing := enc(map[string]string{"alg": "RS256", "typ": "JWT", "kid": "k1"}) + "." + enc(claims) + digest := sha256.Sum256([]byte(signing)) + sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:]) + if err != nil { + p.t.Fatal(err) + } + return signing + "." + base64.RawURLEncoding.EncodeToString(sig) +} + +// tlsAccepts opens a TLS connection with an optional client certificate and reports whether the server kept it. A +// refused client certificate surfaces on the first read under TLS 1.3, so a read that only times out means accepted; +// it offers h2, which gRPC servers require. +func tlsAccepts(addr, caFile, certFile, keyFile string) error { + caPEM, err := os.ReadFile(caFile) //nolint:gosec // a test file + if err != nil { + return err + } + pool := x509.NewCertPool() + pool.AppendCertsFromPEM(caPEM) + cfg := &tls.Config{RootCAs: pool, ServerName: "localhost", MinVersion: tls.VersionTLS12, NextProtos: []string{"h2"}} + if certFile != "" { + cert, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return err + } + cfg.Certificates = []tls.Certificate{cert} + } + conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp", addr, cfg) + if err != nil { + return err + } + defer func() { _ = conn.Close() }() + _ = conn.SetReadDeadline(time.Now().Add(time.Second)) + if _, err := conn.Read(make([]byte, 1)); err != nil { + var ne net.Error + if errors.As(err, &ne) && ne.Timeout() { + return nil + } + return err + } + return nil +} diff --git a/tools/internal/enginetest/security_test.go b/tools/internal/enginetest/security_test.go new file mode 100644 index 0000000..4083019 --- /dev/null +++ b/tools/internal/enginetest/security_test.go @@ -0,0 +1,195 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package enginetest + +import ( + "fmt" + "slices" + "strings" + "testing" + "time" +) + +// securedEngine is an engine configuration with frontend TLS, internode TLS and tokens from a test identity provider: +// workflow-admins administer every namespace, orders-app writes and auditors read in orders. +type securedEngine struct { + config string + base int + frontend *pki + internode *pki + nodeCert, nodeKey string + idp *identityProvider +} + +func newSecuredEngine(t *testing.T) securedEngine { + t.Helper() + dir := t.TempDir() + frontend := newPKI(t, dir, "frontend-ca") + engineCert, engineKey := frontend.issue("engine") + internode := newPKI(t, dir, "internode-ca") + nodeCert, nodeKey := internode.issue("node") + idp := newIdentityProvider(t) + base := freeBase(t) + config := writeConfig(t, dir, ports(base)+fmt.Sprintf(` +[engine.tls] +certFile = %s +keyFile = %s + +[engine.tls.internode] +enabled = true +certFile = %s +keyFile = %s +caFile = %s + +[engine.auth] +type = "jwt" +issuer = %s +rolesClaim = "groups" + +[[engine.auth.rules]] +value = "workflow-admins" +namespace = "*" +role = "admin" + +[[engine.auth.rules]] +value = "orders-app" +namespace = "orders" +role = "write" + +[[engine.auth.rules]] +value = "auditors" +namespace = "orders" +role = "read" + +[database] +type = "sqlite" +inMemory = true +`, tomlString(engineCert), tomlString(engineKey), tomlString(nodeCert), tomlString(nodeKey), + tomlString(internode.caFile("internode-ca")), tomlString(idp.issuer))) + return securedEngine{config: config, base: base, frontend: frontend, internode: internode, nodeCert: nodeCert, + nodeKey: nodeKey, idp: idp} +} + +// TestSecuredEngine runs the engine with TLS, internode mutual TLS and tokens from an OpenID Connect provider, and +// checks who may do what: callers through the frontend with tokens, and callers of the internal frontend. +func TestSecuredEngine(t *testing.T) { + binary := engineBinary(t) + se := newSecuredEngine(t) + frontend, internode, idp, base, config := se.frontend, se.internode, se.idp, se.base, se.config + nodeCert, nodeKey := se.nodeCert, se.nodeKey + + tls := []string{"--tls-ca-path", frontend.caFile("frontend-ca")} + token := func(claims map[string]any) []string { + return append(append([]string{}, tls...), "--api-key", idp.token(claims, nil)) + } + admin := token(map[string]any{"sub": "ops", "groups": []any{"workflow-admins"}}) + e := start(t, binary, base, admin, "start", "--runtime-config", config) + + for _, ns := range []string{"orders", "billing"} { + e.must("operator", "namespace", "create", "--namespace", ns, "--retention", "24h") + } + // The frontend adds a search attribute through the internal frontend, over internode TLS with the server name + // taken from the internode certificate; without one, that call fails the TLS handshake. + e.must("operator", "search-attribute", "create", "--namespace", "orders", "--name", "Customer", "--type", "Keyword") + app := token(map[string]any{"sub": "orders-app", "groups": []any{"orders-app"}}) + auditor := token(map[string]any{"sub": "audit", "groups": []any{"auditors"}}) + startIn := func(ns string) []string { + return []string{"workflow", "start", "--namespace", ns, "--type", "Order", "--task-queue", "orders", + "--workflow-id", fmt.Sprintf("order-%d", time.Now().UnixNano())} + } + list := []string{"workflow", "list", "--namespace", "orders"} + + // An integration's token starts and lists workflows in its namespace. + for _, args := range [][]string{startIn("orders"), list} { + if out, err := e.temporalAt(e.address, app, args...); err != nil { + t.Fatalf("the orders token was refused %v: %v\n%s\n%s", args, err, out, e.log) + } + } + if out, err := e.temporalAt(e.address, auditor, list...); err != nil { + t.Fatalf("the reader token could not list: %v\n%s", err, out) + } + + other := rsaKey(t) + refused := map[string]struct { + flags []string + args []string + }{ + "another namespace": {app, startIn("billing")}, + "a reader writing": {auditor, startIn("orders")}, + "no token": {tls, list}, + "an expired token": {token(map[string]any{"sub": "x", "groups": []any{"orders-app"}, "exp": time.Now().Add(-time.Hour).Unix()}), list}, + "a forged token": {append(append([]string{}, tls...), "--api-key", idp.token(map[string]any{"sub": "x", "groups": []any{"workflow-admins"}}, other)), list}, + "another issuer": {token(map[string]any{"sub": "x", "groups": []any{"workflow-admins"}, "iss": "https://elsewhere"}), list}, + "no matching group": {token(map[string]any{"sub": "x", "groups": []any{"employees"}}), list}, + "a plaintext client": {[]string{"--tls=false", "--api-key", idp.token(map[string]any{"sub": "ops", "groups": []any{"workflow-admins"}}, nil)}, list}, + } + for name, tt := range refused { + want := []string{"Request unauthorized"} + if name == "a plaintext client" { + want = tlsRefusals + } + if out, err := e.temporalAt(e.address, tt.flags, tt.args...); err == nil || !containsAny(out, want) { + t.Errorf("%s: %v, want a refusal with one of %q:\n%s", name, err, want, out) + } + } + + // The internal frontend grants system access without a token, so only internode certificates may reach it. + internal := fmt.Sprintf("127.0.0.1:%d", base+3) + internalCA := []string{"--tls-ca-path", internode.caFile("internode-ca")} + for name, flags := range map[string][]string{ + "without a client certificate": internalCA, + "in plain text": {"--tls=false"}, + "with a frontend token only": append(append([]string{}, internalCA...), admin[len(admin)-2:]...), + } { + if out, err := e.temporalAt(internal, flags, "operator", "namespace", "list"); err == nil || + !containsAny(out, tlsRefusals) { + t.Errorf("the internal frontend did not refuse the connection of a caller %s: %v\n%s", name, err, out) + } + } + withCert := append(append([]string{}, internalCA...), "--tls-cert-path", nodeCert, "--tls-key-path", nodeKey) + if out, err := e.temporalAt(internal, withCert, "operator", "cluster", "health"); err != nil || !strings.Contains(out, "SERVING") { + t.Errorf("the internal frontend refused a node certificate: %v\n%s", err, out) + } + + // Every other internode port, membership (ringpop) included, takes TLS with a node certificate only. + ca := internode.caFile("internode-ca") + for name, port := range map[string]int{ + "history": base + 1, "matching": base + 2, "worker": base + 6, + "frontend membership": base - 300, "history membership": base - 299, "matching membership": base - 298, + "internal frontend membership": base - 297, "worker membership": base - 294, + } { + addr := fmt.Sprintf("127.0.0.1:%d", port) + if err := tlsAccepts(addr, ca, nodeCert, nodeKey); err != nil { + t.Errorf("%s (%s) did not accept a node certificate over TLS: %v", name, addr, err) + } + if err := tlsAccepts(addr, ca, "", ""); err == nil { + t.Errorf("%s (%s) accepted a caller without a node certificate", name, addr) + } + } + // The server name comes from the node certificate; without one Temporal's system worker cannot connect. + if strings.Contains(e.log.String(), "either ServerName or InsecureSkipVerify") { + t.Errorf("an internode connection had no server name:\n%s", e.log) + } +} + +// tlsRefusals are how the Temporal CLI reports a refused TLS connection: before 1.9 as a connection error, from 1.9 +// with the reason. +var tlsRefusals = []string{"connection error", "requires TLS", "requires client certificate"} + +func containsAny(s string, subs []string) bool { + return slices.ContainsFunc(subs, func(sub string) bool { return strings.Contains(s, sub) }) +} diff --git a/tools/internal/enginetest/sqlite_test.go b/tools/internal/enginetest/sqlite_test.go index 301c042..076c4e8 100644 --- a/tools/internal/enginetest/sqlite_test.go +++ b/tools/internal/enginetest/sqlite_test.go @@ -26,13 +26,13 @@ import ( // TestSQLiteFileSurvivesRestart starts the engine on a new SQLite file (which creates the schema), records a // namespace and a waiting workflow, restarts the engine on the same file, and finds both still there. func TestSQLiteFileSurvivesRestart(t *testing.T) { - binary, _ := binaries(t) + binary := engineBinary(t) dir := t.TempDir() db := filepath.Join(dir, "engine.db") base := freeBase(t) config := writeConfig(t, dir, ports(base)+"[database]\ntype = \"sqlite\"\npath = "+tomlString(db)+"\n") - first := start(t, binary, base, "start", "--runtime-config", config, "--allow-no-auth") + first := start(t, binary, base, nil, "start", "--runtime-config", config, "--allow-no-auth") if _, err := os.Stat(db); err != nil { t.Fatalf("the first start did not create the database file: %v", err) } @@ -43,7 +43,7 @@ func TestSQLiteFileSurvivesRestart(t *testing.T) { lockPorts(t) // keep the range until the restarted engine reports SERVING first.stop() - second := start(t, binary, base, "start", "--runtime-config", config, "--allow-no-auth") + second := start(t, binary, base, nil, "start", "--runtime-config", config, "--allow-no-auth") if out := second.must("operator", "namespace", "describe", "--namespace", "persisted"); !strings.Contains(out, "persisted") { t.Fatalf("the namespace did not survive the restart:\n%s", out) }