From b7a6810cd69de76635bbeda63588f99e858e1af3 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Mon, 2 Nov 2026 13:00:09 +0530 Subject: [PATCH 01/21] feat(engine): map identity-provider tokens to temporal roles Temporal's default claim mapper reads one top-level claim of ":" values, which identity providers rarely issue. jwtclaims verifies the token against the provider's key set (Temporal's token key provider), checks expiry, issuer and audience, reads a nested or space-separated roles claim, and maps its values to namespace roles through rules, Temporal's own format, or a regular expression with named groups. A role in namespace "*" becomes Temporal's system role, which applies to every namespace. Uses github.com/golang-jwt/jwt/v5 (MIT, in the WSO2 registry for all scopes); Temporal links v4. --- engine/go.mod | 1 + engine/go.sum | 2 + engine/plugins/jwtclaims/jwtclaims.go | 259 +++++++++++++++++++++ engine/plugins/jwtclaims/jwtclaims_test.go | 213 +++++++++++++++++ third-party/go-licenses.csv | 1 + 5 files changed, 476 insertions(+) create mode 100644 engine/plugins/jwtclaims/jwtclaims.go create mode 100644 engine/plugins/jwtclaims/jwtclaims_test.go diff --git a/engine/go.mod b/engine/go.mod index af24c12..0f114d8 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 c876332..b3ce442 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/plugins/jwtclaims/jwtclaims.go b/engine/plugins/jwtclaims/jwtclaims.go new file mode 100644 index 0000000..3aa5d57 --- /dev/null +++ b/engine/plugins/jwtclaims/jwtclaims.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 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 !ok { + return nil, fmt.Errorf("rule for %q: role %q must be read, write, worker 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.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. +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 "worker": + return authorization.RoleWorker, 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..432dee3 --- /dev/null +++ b/engine/plugins/jwtclaims/jwtclaims_test.go @@ -0,0 +1,213 @@ +// 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/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: "worker"}, + }}) + 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.RoleWorker || 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.worker", Namespace: "default", Role: "worker"}, + {Value: "workflow.write", Namespace: "default", Role: "write"}, + }}) + c := claimsFor(t, m, jwt.MapClaims{"client.id": "orders-app", "scp": "openid workflow.worker,workflow.write"}) + if c.Subject != "orders-app" || c.Namespaces["default"] != authorization.RoleWorker|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) + } + for name, header := range map[string]string{ + "basic": "Basic dXNlcjpwYXNz", + "no scheme": "abc", + "forged": "Bearer " + forged, + "no expiry": "Bearer " + noExpiry, + "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") + } +} diff --git a/third-party/go-licenses.csv b/third-party/go-licenses.csv index b84c9f1..12c36ff 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 From d46dbf78f7263ce8a0bfe2a2f86039c184769fa1 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Mon, 2 Nov 2026 13:00:10 +0530 Subject: [PATCH 02/21] feat(engine): secure the frontend and choose services from runtime.toml [engine.tls] puts TLS on the frontend, optionally requiring client certificates, and on internode traffic. [engine.auth] turns on Temporal's default authorizer with the jwtclaims mapper built by the start command. [engine.metrics] serves Prometheus metrics. [runtime] profiles choose the services a node runs (all, engine, frontend with the internal frontend, history, matching, worker; api starts nothing), and --service still overrides them. Every setting is validated, certificate files included. Checked against a real engine: TLS required, an admin token creates namespaces and starts workflows, a reader token lists but cannot start, tokens without a matching group or no token are refused, and a ballerina/workflow integration connects with its token and the CA. --- distribution/conf/runtime.toml | 25 +- docs/features/README.md | 1 + docs/features/engine-security.md | 93 ++++++++ docs/features/engine.md | 6 +- docs/features/runtime-config.md | 19 +- engine/internal/cli/cli.go | 47 +++- engine/internal/cli/cli_test.go | 37 +++ .../internal/cli/testdata/runtime-auth.toml | 16 ++ .../internal/runtimeconfig/fixtures_test.go | 2 +- engine/internal/runtimeconfig/profiles.go | 84 +++++++ .../internal/runtimeconfig/runtimeconfig.go | 55 ++++- .../runtimeconfig/runtimeconfig_test.go | 8 +- engine/internal/runtimeconfig/security.go | 215 ++++++++++++++++++ .../internal/runtimeconfig/security_test.go | 185 +++++++++++++++ 14 files changed, 756 insertions(+), 37 deletions(-) create mode 100644 docs/features/engine-security.md create mode 100644 engine/internal/cli/testdata/runtime-auth.toml create mode 100644 engine/internal/runtimeconfig/profiles.go create mode 100644 engine/internal/runtimeconfig/security.go create mode 100644 engine/internal/runtimeconfig/security_test.go diff --git a/distribution/conf/runtime.toml b/distribution/conf/runtime.toml index 8b39e63..8af3cfe 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,25 @@ 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" +# jwksUrls = ["https://idp.example.com/.well-known/jwks.json"] +# issuer = "https://idp.example.com" +# 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..0080ea8 --- /dev/null +++ b/docs/features/engine-security.md @@ -0,0 +1,93 @@ +# 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` | | Name to verify in internode certificates, when it differs from the host | + +### `[engine.auth]` + +| Key | Default | Meaning | +|---|---|---| +| `type` | `none` | `jwt` checks a bearer token on every call; `none` needs `--allow-no-auth` | +| `jwksUrls` | required for `jwt` | The identity provider's key set (JWKS) URLs | +| `keyRefreshInterval` | `1m` | How often the key set is fetched again | +| `issuer` | not checked | Required value of `iss` | +| `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`, `worker`, `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; `worker` lets an integration's worker poll; `admin` adds namespace management. +- Every token is checked for its signature, an expiry, the issuer and audience when set, and a subject. 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, which Temporal's key provider supports. +- 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/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, 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 | 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/engine/internal/cli/cli.go b/engine/internal/cli/cli.go index 3c301ab..a6dac7c 100644 --- a/engine/internal/cli/cli.go +++ b/engine/internal/cli/cli.go @@ -39,6 +39,7 @@ 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 @@ -110,11 +111,15 @@ 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 { + switch { + case len(services) > 0: + case rt != nil: + services = rt.Services + default: services = defaultServices(cfg) } logger := log.NewZapLogger(log.BuildZapLogger(cfg.Log)) @@ -136,7 +141,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) } @@ -170,11 +175,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 +187,40 @@ 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") + } +} + +// 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) } + keys := authorization.NewDefaultTokenKeyProvider(&cfg.Global.Authorization, 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..d9f8f0b 100644 --- a/engine/internal/cli/cli_test.go +++ b/engine/internal/cli/cli_test.go @@ -25,7 +25,11 @@ import ( "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" @@ -287,3 +291,36 @@ 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) + } +} diff --git a/engine/internal/cli/testdata/runtime-auth.toml b/engine/internal/cli/testdata/runtime-auth.toml new file mode 100644 index 0000000..a99e486 --- /dev/null +++ b/engine/internal/cli/testdata/runtime-auth.toml @@ -0,0 +1,16 @@ +[runtime] +profiles = ["frontend", "history"] + +[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..200e668 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..affcfb2 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 ( @@ -39,6 +39,8 @@ import ( "go.temporal.io/server/common/config" "go.temporal.io/server/common/log" "gopkg.in/yaml.v3" + + "github.com/wso2/integration-workflow-runtime/engine/plugins/jwtclaims" ) const ( @@ -68,17 +70,30 @@ 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 +} + 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 +128,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 +152,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 +168,13 @@ 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 + } + if len(nodeServices) == 0 { + return nil, errNoServices + } s.applyDefaults() if err := s.validate(); err != nil { return nil, err @@ -165,7 +187,12 @@ 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} + 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 +262,9 @@ 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.Metrics.problems()...) if d.MaxConns < 1 { problems = append(problems, "database.maxConns must be at least 1") } @@ -335,7 +365,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..1d1eb69 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..a93c793 --- /dev/null +++ b/engine/internal/runtimeconfig/security.go @@ -0,0 +1,215 @@ +// 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 ( + "errors" + "fmt" + "net" + "os" + "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 +} + +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 } + +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 { + problems = append(problems, "engine.auth.jwksUrls needs the identity provider's key set URL") + } + 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 + } + if _, port, err := net.SplitHostPort(m.PrometheusAddress); err != nil || port == "" { + return []string{fmt.Sprintf("engine.metrics.prometheusAddress %q must be host: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", + }} +} + +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..0d7069a --- /dev/null +++ b/engine/internal/runtimeconfig/security_test.go @@ -0,0 +1,185 @@ +// 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 ( + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +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"}, + } + 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 = ["api"]`: "names no engine service", + `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) + } + } +} + +func certFiles(t *testing.T) (cert, key, ca string) { + t.Helper() + dir := t.TempDir() + for _, name := range []string{"engine.crt", "engine.key", "ca.pem"} { + if err := os.WriteFile(filepath.Join(dir, name), []byte("placeholder"), 0o600); err != nil { + t.Fatal(err) + } + } + return filepath.Join(dir, "engine.crt"), filepath.Join(dir, "engine.key"), filepath.Join(dir, "ca.pem") +} + +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) { + rt := mustParseRuntime(t, `[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": "jwksUrls needs", + "[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 = [\"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) + } + if _, err := parse([]byte("[engine.metrics]\nprometheusAddress = \"9464\"\n"+sqliteDB), noEnv); err == nil || + !strings.Contains(err.Error(), "must be host:port") { + t.Errorf("err = %v", err) + } +} From eceab09499e785eff18f2dcfc27f2acbcaa46109 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Mon, 2 Nov 2026 14:01:16 +0530 Subject: [PATCH 03/21] docs: add the user guide and require it in every change docs/user-guide is the source of the Workflow Runtime section of the WSO2 Integrator documentation, shaped like its ICP section: configure the runtime, secure the engine (TLS, the identity-provider permission model, rules per provider), connect an integration, run across nodes, monitor, troubleshoot, and a runtime.toml reference. AGENTS.md now requires every user-visible change to update it with working instructions and to check the whole guide for consistency. --- AGENTS.md | 12 +++ README.md | 2 + docs/user-guide/README.md | 15 +++ docs/user-guide/configure.md | 85 +++++++++++++++++ docs/user-guide/connect-an-integration.md | 43 +++++++++ docs/user-guide/monitor.md | 34 +++++++ docs/user-guide/reference/runtime-toml.md | 106 +++++++++++++++++++++ docs/user-guide/scale-across-nodes.md | 46 +++++++++ docs/user-guide/secure-the-engine.md | 111 ++++++++++++++++++++++ docs/user-guide/troubleshoot.md | 18 ++++ docs/user-guide/workflow-runtime.md | 37 ++++++++ 11 files changed, 509 insertions(+) create mode 100644 docs/user-guide/README.md create mode 100644 docs/user-guide/configure.md create mode 100644 docs/user-guide/connect-an-integration.md create mode 100644 docs/user-guide/monitor.md create mode 100644 docs/user-guide/reference/runtime-toml.md create mode 100644 docs/user-guide/scale-across-nodes.md create mode 100644 docs/user-guide/secure-the-engine.md create mode 100644 docs/user-guide/troubleshoot.md create mode 100644 docs/user-guide/workflow-runtime.md diff --git a/AGENTS.md b/AGENTS.md index a685b38..5f78977 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` @@ -116,6 +123,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/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..c8fca21 --- /dev/null +++ b/docs/user-guide/configure.md @@ -0,0 +1,85 @@ +--- +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 +SQL="bin/workflow-engine-sql --plugin postgres12 --ep db.example.com -p 5432 -u workflow --pw " +$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) 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..706c7a5 --- /dev/null +++ b/docs/user-guide/connect-an-integration.md @@ -0,0 +1,43 @@ +--- +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. Create it once with the Temporal CLI (an `admin` token is needed when auth is on): + + ```bash + temporal operator namespace create --namespace orders --retention 720h \ + --address engine.example.com:7233 --tls-ca-path ca.pem --api-key "$ADMIN_TOKEN" + ``` + +- The integration has a token with `worker` and `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..f9773b7 --- /dev/null +++ b/docs/user-guide/reference/runtime-toml.md @@ -0,0 +1,106 @@ +--- +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` | | Name to verify, when it differs from the host | + +### `[engine.auth]` + +| Key | Default | Description | +|---|---|---| +| `type` | `none` | `jwt` to require tokens; `none` needs `--allow-no-auth` | +| `jwksUrls` | required for `jwt` | Your identity provider's key set URLs | +| `keyRefreshInterval` | `1m` | How often the key set is fetched again (a duration, at least `1s`) | +| `issuer` | not checked | Required `iss` | +| `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`, `worker` or `admin` | + +### `[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 | + +### `[database.tls]` + +| Key | Default | Description | +|---|---|---| +| `enabled` | `false` | TLS to the database server | +| `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 | Name to verify in the server's certificate | +| `enableHostVerification` | `false` | Verify that the certificate matches the host | diff --git a/docs/user-guide/scale-across-nodes.md b/docs/user-guide/scale-across-nodes.md new file mode 100644 index 0000000..f6161d3 --- /dev/null +++ b/docs/user-guide/scale-across-nodes.md @@ -0,0 +1,46 @@ +--- +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. +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. +::: diff --git a/docs/user-guide/secure-the-engine.md b/docs/user-guide/secure-the-engine.md new file mode 100644 index 0000000..e804990 --- /dev/null +++ b/docs/user-guide/secure-the-engine.md @@ -0,0 +1,111 @@ +--- +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 | +| `worker` | Poll task queues and complete tasks: what an integration's workers need | +| `admin` | Everything, including creating and changing namespaces | + +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) | `worker` and `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. On several nodes, encrypt traffic between them too: + + ```toml + [engine.tls.internode] + enabled = true + caFile = "conf/certs/internode-ca.pem" + ``` + +## Turn on your identity provider's tokens + +1. Find your provider's key set (JWKS) URL and issuer, and the claim that carries groups, roles or scopes. +2. Add `[engine.auth]` and one rule per group: + + ```toml + [engine.auth] + type = "jwt" + jwksUrls = ["https://idp.example.com/.well-known/jwks.json"] + issuer = "https://idp.example.com" + audience = "workflow-engine" # optional + rolesClaim = "groups" + + [[engine.auth.rules]] + value = "workflow-admins" + namespace = "*" + role = "admin" + + [[engine.auth.rules]] + value = "orders-integration" + namespace = "orders" + role = "worker" + + [[engine.auth.rules]] + value = "orders-integration" + namespace = "orders" + role = "write" + ``` + +3. Restart the engine. + +| Provider | `rolesClaim` | Notes | +|---|---|---| +| Amazon Cognito | `cognito:groups` | Issuer `https://cognito-idp..amazonaws.com/`; key set at `/.well-known/jwks.json` | +| 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 | + +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..0659bcc --- /dev/null +++ b/docs/user-guide/troubleshoot.md @@ -0,0 +1,18 @@ +--- +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 | +| `engine.tls.certFile: ... no such file or directory` | A wrong path | Paths are relative to the directory the engine starts in | +| 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) From 3f54bb29eb813dc138cf2ec7edde469a53a348e9 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Mon, 2 Nov 2026 14:37:23 +0530 Subject: [PATCH 04/21] feat(engine): discover the identity provider's key set from its issuer With issuer and no jwksUrls, the start command reads /.well-known/openid-configuration and uses its jwks_uri, so any OpenID Connect provider needs only its issuer. The document must name the same issuer, and the engine does not start when it cannot read it. The user guide adds WSO2 Identity Server, Asgardeo and other OpenID Connect providers. --- distribution/conf/runtime.toml | 3 +- docs/features/engine-security.md | 7 +- docs/user-guide/reference/runtime-toml.md | 4 +- docs/user-guide/secure-the-engine.md | 19 +++-- docs/user-guide/troubleshoot.md | 1 + engine/internal/cli/cli.go | 9 +++ engine/internal/cli/cli_test.go | 39 ++++++++++ engine/internal/runtimeconfig/security.go | 4 +- .../internal/runtimeconfig/security_test.go | 2 +- engine/plugins/jwtclaims/discovery.go | 64 +++++++++++++++ engine/plugins/jwtclaims/discovery_test.go | 77 +++++++++++++++++++ 11 files changed, 215 insertions(+), 14 deletions(-) create mode 100644 engine/plugins/jwtclaims/discovery.go create mode 100644 engine/plugins/jwtclaims/discovery_test.go diff --git a/distribution/conf/runtime.toml b/distribution/conf/runtime.toml index 8af3cfe..f4f9989 100644 --- a/distribution/conf/runtime.toml +++ b/distribution/conf/runtime.toml @@ -17,8 +17,7 @@ logLevel = "info" # # [engine.auth] # type = "jwt" -# jwksUrls = ["https://idp.example.com/.well-known/jwks.json"] -# issuer = "https://idp.example.com" +# issuer = "https://idp.example.com/oauth2/token" # its key set is discovered; or set jwksUrls # rolesClaim = "groups" # # [[engine.auth.rules]] diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index 0080ea8..5c07f86 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -25,9 +25,9 @@ connection, and tokens from the customer's own identity provider mapped to Tempo | Key | Default | Meaning | |---|---|---| | `type` | `none` | `jwt` checks a bearer token on every call; `none` needs `--allow-no-auth` | -| `jwksUrls` | required for `jwt` | The identity provider's key set (JWKS) URLs | +| `jwksUrls` | discovered from `issuer` | The identity provider's key set (JWKS) URLs, when it has no OpenID Connect discovery document | | `keyRefreshInterval` | `1m` | How often the key set is fetched again | -| `issuer` | not checked | Required value of `iss` | +| `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`) | @@ -67,6 +67,8 @@ role = "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; `worker` lets an integration's worker poll; `admin` adds namespace management. +- 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 the same issuer, and the engine does not start if it cannot read it. - Every token is checked for its signature, an expiry, the issuer and audience when set, and a subject. 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. @@ -88,6 +90,7 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | Test | Covers | |---|---| +| `engine/plugins/jwtclaims/discovery_test.go` | Discovery: the key set URL, another issuer, no key set, invalid documents, unreachable providers | | `engine/plugins/jwtclaims/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, 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 | diff --git a/docs/user-guide/reference/runtime-toml.md b/docs/user-guide/reference/runtime-toml.md index f9773b7..691827a 100644 --- a/docs/user-guide/reference/runtime-toml.md +++ b/docs/user-guide/reference/runtime-toml.md @@ -58,9 +58,9 @@ Each gRPC service also uses a membership port 300 below its port (6933, 6936, 69 | Key | Default | Description | |---|---|---| | `type` | `none` | `jwt` to require tokens; `none` needs `--allow-no-auth` | -| `jwksUrls` | required for `jwt` | Your identity provider's key set URLs | +| `jwksUrls` | discovered from `issuer` | Your identity provider's key set URLs; 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` | not checked | Required `iss` | +| `issuer` | | Required `iss`; also where the key set is discovered (`/.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 | diff --git a/docs/user-guide/secure-the-engine.md b/docs/user-guide/secure-the-engine.md index e804990..eb3aa1f 100644 --- a/docs/user-guide/secure-the-engine.md +++ b/docs/user-guide/secure-the-engine.md @@ -53,14 +53,17 @@ A role in namespace `*` applies to every namespace. Roles add up: a caller in tw ## Turn on your identity provider's tokens -1. Find your provider's key set (JWKS) URL and issuer, and the claim that carries groups, roles or scopes. -2. Add `[engine.auth]` and one rule per group: +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" - jwksUrls = ["https://idp.example.com/.well-known/jwks.json"] - issuer = "https://idp.example.com" + issuer = "https://idp.example.com/oauth2/token" audience = "workflow-engine" # optional rolesClaim = "groups" @@ -84,11 +87,17 @@ A role in namespace `*` applies to every namespace. Roles add up: a caller in tw | Provider | `rolesClaim` | Notes | |---|---|---| -| Amazon Cognito | `cognito:groups` | Issuer `https://cognito-idp..amazonaws.com/`; key set at `/.well-known/jwks.json` | +| 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`. diff --git a/docs/user-guide/troubleshoot.md b/docs/user-guide/troubleshoot.md index 0659bcc..a9b036b 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -13,6 +13,7 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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 | | `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 | Check `issuer` (it must equal the tokens' `iss`) and the network, or set `jwksUrls` | | 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/engine/internal/cli/cli.go b/engine/internal/cli/cli.go index a6dac7c..e711113 100644 --- a/engine/internal/cli/cli.go +++ b/engine/internal/cli/cli.go @@ -21,10 +21,12 @@ package cli import ( + "context" "errors" "flag" "fmt" "io" + "net/http" "os" "strings" @@ -219,6 +221,13 @@ func newClaimMapper(cfg *config.Config, rt *runtimeconfig.Runtime, logger log.Lo return nil, fmt.Errorf("claim mapper %q is configured only through runtime.toml [engine.auth]", runtimeconfig.ClaimMapperName) } + if len(cfg.Global.Authorization.JWTKeyProvider.KeySourceURIs) == 0 { + jwks, err := jwtclaims.Discover(context.Background(), http.DefaultClient, 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} + } keys := authorization.NewDefaultTokenKeyProvider(&cfg.Global.Authorization, logger) return jwtclaims.New(keys, *rt.Auth) } diff --git a/engine/internal/cli/cli_test.go b/engine/internal/cli/cli_test.go index d9f8f0b..2eb0555 100644 --- a/engine/internal/cli/cli_test.go +++ b/engine/internal/cli/cli_test.go @@ -19,6 +19,10 @@ package cli import ( "bytes" "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" "path/filepath" "slices" "strings" @@ -324,3 +328,38 @@ func TestNewClaimMapper(t *testing.T) { 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") + toml := "[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) + } +} diff --git a/engine/internal/runtimeconfig/security.go b/engine/internal/runtimeconfig/security.go index a93c793..d1eea61 100644 --- a/engine/internal/runtimeconfig/security.go +++ b/engine/internal/runtimeconfig/security.go @@ -149,8 +149,8 @@ func (a authSettings) problems() []string { return []string{fmt.Sprintf(`engine.auth.type %q must be "jwt" or "none"`, a.Type)} } var problems []string - if len(a.JWKSURLs) == 0 { - problems = append(problems, "engine.auth.jwksUrls needs the identity provider's key set URL") + 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") } if a.KeyRefresh != "" { if d, err := time.ParseDuration(a.KeyRefresh); err != nil || d < time.Second { diff --git a/engine/internal/runtimeconfig/security_test.go b/engine/internal/runtimeconfig/security_test.go index 0d7069a..bbf1af5 100644 --- a/engine/internal/runtimeconfig/security_test.go +++ b/engine/internal/runtimeconfig/security_test.go @@ -157,7 +157,7 @@ role = "admin" 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": "jwksUrls needs", + "[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 = [\"x\"]\nleewaySeconds = -1\n": "leewaySeconds", diff --git a/engine/plugins/jwtclaims/discovery.go b/engine/plugins/jwtclaims/discovery.go new file mode 100644 index 0000000..ddaf3e6 --- /dev/null +++ b/engine/plugins/jwtclaims/discovery.go @@ -0,0 +1,64 @@ +// 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" + "net/http" + "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) { + 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(res.Body).Decode(&doc); err != nil { + return "", fmt.Errorf("invalid discovery document at %s: %w", url, err) + } + if strings.TrimSuffix(doc.Issuer, "/") != strings.TrimSuffix(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") + } + return doc.JWKSURI, nil +} diff --git a/engine/plugins/jwtclaims/discovery_test.go b/engine/plugins/jwtclaims/discovery_test.go new file mode 100644 index 0000000..8622dad --- /dev/null +++ b/engine/plugins/jwtclaims/discovery_test.go @@ -0,0 +1,77 @@ +// 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"}, + "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") + } +} From 0b2bc0930ea5c0639b4122a7cad580f0d559bf03 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Mon, 2 Nov 2026 15:07:04 +0530 Subject: [PATCH 05/21] docs: create the WorkflowKind search attribute with the namespace When ballerina/workflow registers WorkflowKind itself and starts a workflow at once, the frontend refuses it until its namespace cache refreshes; creating the attribute with the namespace avoids that (seen with Compose). --- docs/user-guide/connect-an-integration.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/user-guide/connect-an-integration.md b/docs/user-guide/connect-an-integration.md index 706c7a5..2630024 100644 --- a/docs/user-guide/connect-an-integration.md +++ b/docs/user-guide/connect-an-integration.md @@ -11,13 +11,18 @@ An integration that uses the `ballerina/workflow` module connects to the runtime ## Before you start -- The namespace exists. Create it once with the Temporal CLI (an `admin` token is needed when auth is on): +- 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 - temporal operator namespace create --namespace orders --retention 720h \ - --address engine.example.com:7233 --tls-ca-path ca.pem --api-key "$ADMIN_TOKEN" + 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 `worker` and `write` in that namespace ([Secure the engine](secure-the-engine.md)), and the CA certificate that signed the engine's certificate. From 109b680f99ed473bf12de94deddf6df7f74eaf29 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Tue, 3 Nov 2026 12:12:46 +0530 Subject: [PATCH 06/21] fix(engine): require tls with tokens and protect the internal frontend With engine.auth.type = "jwt", the engine now refuses to start without [engine.tls], so tokens never cross the network in plain text, and without [engine.tls.internode] when bindAddress is not a loopback address: Temporal gives the internal frontend system access without a token (its internal claim mapper), so it and the other service ports must accept only internode certificates. A rule granting "worker" is refused with "grant write": Temporal's default authorizer needs write for polling, so a worker-only grant refused every call it was for. A start with neither issuer nor audience logs a warning. Runtime.Temporal is held by value, and the server factory receives the services, so a test sees what the profiles and --service choose. The guide drops the worker role, states the TLS and internode requirements with firewall advice and the issuer/audience risk, and the architecture's profile table uses api, the API server's profile. tools/internal/enginetest/security_test.go runs a real engine with TLS, internode mutual TLS and an OpenID Connect provider: an integration token works 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. Mapped grants are also checked through Temporal's authorizer (polling). --- docs/features/engine-security.md | 13 +- docs/guides/ARCHITECTURE.md | 10 +- docs/user-guide/connect-an-integration.md | 2 +- docs/user-guide/reference/runtime-toml.md | 6 +- docs/user-guide/scale-across-nodes.md | 4 +- docs/user-guide/secure-the-engine.md | 32 ++-- docs/user-guide/troubleshoot.md | 3 + engine/internal/cli/cli.go | 20 ++- engine/internal/cli/cli_test.go | 49 +++++- engine/internal/cli/testdata/certs/engine.crt | 1 + engine/internal/cli/testdata/certs/engine.key | 1 + .../internal/cli/testdata/runtime-auth.toml | 4 + .../internal/runtimeconfig/fixtures_test.go | 2 +- .../internal/runtimeconfig/runtimeconfig.go | 5 +- .../runtimeconfig/runtimeconfig_test.go | 2 +- engine/internal/runtimeconfig/security.go | 20 +++ .../internal/runtimeconfig/security_test.go | 29 +++- engine/plugins/jwtclaims/jwtclaims.go | 11 +- engine/plugins/jwtclaims/jwtclaims_test.go | 50 +++++- tools/internal/enginetest/engine_test.go | 27 ++-- .../enginetest/security_helpers_test.go | 153 ++++++++++++++++++ tools/internal/enginetest/security_test.go | 143 ++++++++++++++++ tools/internal/enginetest/sqlite_test.go | 6 +- 23 files changed, 533 insertions(+), 60 deletions(-) create mode 100644 engine/internal/cli/testdata/certs/engine.crt create mode 100644 engine/internal/cli/testdata/certs/engine.key create mode 100644 tools/internal/enginetest/security_helpers_test.go create mode 100644 tools/internal/enginetest/security_test.go diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index 5c07f86..00cf11f 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -33,7 +33,7 @@ connection, and tokens from the customer's own identity provider mapped to Tempo | `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`, `worker`, `admin`) in `namespace` (or `*` for all) to callers whose roles claim holds `value` | +| `[[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] @@ -66,7 +66,13 @@ role = "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; `worker` lets an integration's worker poll; `admin` adds namespace management. + 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. +- With neither `issuer` nor `audience`, every unexpired token the key set signs is accepted; the start logs a + warning. - 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 the same issuer, and the engine does not start if it cannot read it. - Every token is checked for its signature, an expiry, the issuer and audience when set, and a subject. A call @@ -93,4 +99,5 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | `engine/plugins/jwtclaims/discovery_test.go` | Discovery: the key set URL, another issuer, no key set, invalid documents, unreachable providers | | `engine/plugins/jwtclaims/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, 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 | +| `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 | +| `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 | 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/user-guide/connect-an-integration.md b/docs/user-guide/connect-an-integration.md index 2630024..a686242 100644 --- a/docs/user-guide/connect-an-integration.md +++ b/docs/user-guide/connect-an-integration.md @@ -23,7 +23,7 @@ An integration that uses the `ballerina/workflow` module connects to the runtime 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 `worker` and `write` in that namespace +- 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 diff --git a/docs/user-guide/reference/runtime-toml.md b/docs/user-guide/reference/runtime-toml.md index 691827a..4b964f4 100644 --- a/docs/user-guide/reference/runtime-toml.md +++ b/docs/user-guide/reference/runtime-toml.md @@ -55,6 +55,8 @@ Each gRPC service also uses a membership port 300 below its port (6933, 6936, 69 ### `[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` | @@ -73,7 +75,7 @@ Each gRPC service also uses a membership port 300 below its port (6933, 6936, 69 |---|---| | `value` | A value of the roles claim, such as a group name | | `namespace` | A namespace, or `*` for every namespace | -| `role` | `read`, `write`, `worker` or `admin` | +| `role` | `read`, `write` or `admin` (an integration needs `write`) | ### `[engine.metrics]` @@ -103,4 +105,4 @@ Each gRPC service also uses a membership port 300 below its port (6933, 6936, 69 | `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 | Name to verify in the server's certificate | -| `enableHostVerification` | `false` | Verify that the certificate matches the host | +| `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 index f6161d3..564e45a 100644 --- a/docs/user-guide/scale-across-nodes.md +++ b/docs/user-guide/scale-across-nodes.md @@ -34,7 +34,9 @@ other through the shared database: there is no list of peers to maintain. ``` 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. + 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. diff --git a/docs/user-guide/secure-the-engine.md b/docs/user-guide/secure-the-engine.md index eb3aa1f..ac83498 100644 --- a/docs/user-guide/secure-the-engine.md +++ b/docs/user-guide/secure-the-engine.md @@ -18,15 +18,17 @@ issues; `conf/runtime.toml` says which group, role or scope gives which permissi | Role | Allows | |---|---| | `read` | List and describe workflows and namespaces | -| `write` | `read`, plus start, signal, cancel and terminate workflows | -| `worker` | Poll task queues and complete tasks: what an integration's workers need | +| `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) | `worker` and `write` in its namespace, through a client-credentials token | +| 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` | @@ -43,14 +45,24 @@ A role in namespace `*` applies to every namespace. Roles add up: a caller in tw 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. On several nodes, encrypt traffic between them too: +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" ``` + :::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 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, @@ -72,17 +84,19 @@ Keycloak, Auth0 and others. namespace = "*" role = "admin" - [[engine.auth.rules]] - value = "orders-integration" - namespace = "orders" - role = "worker" - [[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 + Set `issuer`, and `audience` when your provider sets one for the engine. Without either, the engine accepts any + unexpired token the provider signed, including tokens it issued for other applications, and logs a warning. + ::: + 3. Restart the engine. | Provider | `rolesClaim` | Notes | diff --git a/docs/user-guide/troubleshoot.md b/docs/user-guide/troubleshoot.md index a9b036b..f8447b7 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -14,6 +14,9 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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 | | `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 | Check `issuer` (it must equal the tokens' `iss`) and the network, or set `jwksUrls` | +| `engine.auth.type = "jwt" needs engine.tls` | Tokens without TLS | Add `[engine.tls]` ([Secure the engine](secure-the-engine.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/engine/internal/cli/cli.go b/engine/internal/cli/cli.go index e711113..0bc75f3 100644 --- a/engine/internal/cli/cli.go +++ b/engine/internal/cli/cli.go @@ -48,7 +48,12 @@ 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 @@ -59,7 +64,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) } @@ -152,8 +157,7 @@ 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), + server, err := c.newServer(services, temporal.WithConfig(cfg), temporal.WithLogger(logger), temporal.InterruptOn(temporal.InterruptCh()), @@ -181,7 +185,7 @@ func (c command) renderConfig(args []string) error { if err != nil { return err } - rendered, err := runtimeconfig.Render(rt.Temporal) + rendered, err := runtimeconfig.Render(&rt.Temporal) if err != nil { return fmt.Errorf("unable to render the configuration: %w", err) } @@ -200,7 +204,7 @@ func loadConfig(runtimeConfig, configFile string) (*config.Config, *runtimeconfi if err != nil { return nil, nil, err } - return rt.Temporal, rt, nil + return &rt.Temporal, rt, nil case configFile != "": cfg, err := config.Load(config.WithConfigFile(configFile)) if err != nil { @@ -228,6 +232,10 @@ func newClaimMapper(cfg *config.Config, rt *runtimeconfig.Runtime, logger log.Lo } 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") + } keys := authorization.NewDefaultTokenKeyProvider(&cfg.Global.Authorization, logger) return jwtclaims.New(keys, *rt.Auth) } diff --git a/engine/internal/cli/cli_test.go b/engine/internal/cli/cli_test.go index 2eb0555..333b0bd 100644 --- a/engine/internal/cli/cli_test.go +++ b/engine/internal/cli/cli_test.go @@ -56,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 }, } @@ -313,14 +313,14 @@ func TestNewClaimMapper(t *testing.T) { if !slices.Equal(rt.Services, []string{"frontend", "internal-frontend", "history"}) { t.Fatalf("services = %v", rt.Services) } - m, err := newClaimMapper(rt.Temporal, rt, logger) + 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") { + 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"}}} @@ -338,7 +338,10 @@ func TestNewClaimMapperDiscoversTheKeySet(t *testing.T) { base = srv.URL write := func(issuer string) string { p := filepath.Join(t.TempDir(), "runtime.toml") - toml := "[engine.auth]\ntype = \"jwt\"\nissuer = \"" + issuer + "\"\n[database]\ntype = \"sqlite\"\ninMemory = true\n" + 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) } @@ -348,7 +351,7 @@ func TestNewClaimMapperDiscoversTheKeySet(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := newClaimMapper(rt.Temporal, rt, log.NewNoopLogger()); err != nil { + 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"}) { @@ -358,8 +361,42 @@ func TestNewClaimMapperDiscoversTheKeySet(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := newClaimMapper(rt.Temporal, rt, log.NewNoopLogger()); err == nil || + 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"}}, + } { + 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 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-auth.toml b/engine/internal/cli/testdata/runtime-auth.toml index a99e486..07bd8f0 100644 --- a/engine/internal/cli/testdata/runtime-auth.toml +++ b/engine/internal/cli/testdata/runtime-auth.toml @@ -1,6 +1,10 @@ [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"] diff --git a/engine/internal/runtimeconfig/fixtures_test.go b/engine/internal/runtimeconfig/fixtures_test.go index 200e668..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.Temporal) + rendered, err := Render(&rt.Temporal) if err != nil { t.Fatal(err) } diff --git a/engine/internal/runtimeconfig/runtimeconfig.go b/engine/internal/runtimeconfig/runtimeconfig.go index affcfb2..e031b61 100644 --- a/engine/internal/runtimeconfig/runtimeconfig.go +++ b/engine/internal/runtimeconfig/runtimeconfig.go @@ -73,7 +73,7 @@ var ( // Runtime is what the engine takes from runtime.toml. type Runtime struct { // Temporal is the generated, validated Temporal server configuration. - Temporal *config.Config + 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. @@ -187,7 +187,7 @@ func parse(data []byte, lookupEnv func(string) (string, bool)) (*Runtime, error) if err := cfg.Validate(); err != nil { return nil, fmt.Errorf("invalid Temporal configuration: %w", err) } - rt := &Runtime{Temporal: cfg, Services: nodeServices} + rt := &Runtime{Temporal: *cfg, Services: nodeServices} if s.Engine.Auth.on() { claims := s.Engine.Auth.claimSettings() rt.Auth = &claims @@ -264,6 +264,7 @@ func (s *settings) validate() error { 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") diff --git a/engine/internal/runtimeconfig/runtimeconfig_test.go b/engine/internal/runtimeconfig/runtimeconfig_test.go index 1d1eb69..d774a38 100644 --- a/engine/internal/runtimeconfig/runtimeconfig_test.go +++ b/engine/internal/runtimeconfig/runtimeconfig_test.go @@ -36,7 +36,7 @@ func mustParse(t *testing.T, toml string) *config.Config { if err != nil { t.Fatalf("parse: %v", err) } - return rt.Temporal + return &rt.Temporal } func TestPasswordFromEnvironment(t *testing.T) { diff --git a/engine/internal/runtimeconfig/security.go b/engine/internal/runtimeconfig/security.go index d1eea61..4e32b49 100644 --- a/engine/internal/runtimeconfig/security.go +++ b/engine/internal/runtimeconfig/security.go @@ -137,6 +137,26 @@ func (t engineTLSSettings) temporalTLS() config.RootTLS { 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": diff --git a/engine/internal/runtimeconfig/security_test.go b/engine/internal/runtimeconfig/security_test.go index bbf1af5..6e255a6 100644 --- a/engine/internal/runtimeconfig/security_test.go +++ b/engine/internal/runtimeconfig/security_test.go @@ -126,7 +126,8 @@ func TestTLSErrors(t *testing.T) { } func TestAuthMapsToTemporalAndClaims(t *testing.T) { - rt := mustParseRuntime(t, `[engine.auth] + 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" @@ -183,3 +184,29 @@ func TestMetrics(t *testing.T) { t.Errorf("err = %v", err) } } + +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/jwtclaims.go b/engine/plugins/jwtclaims/jwtclaims.go index 3aa5d57..f90d04d 100644 --- a/engine/plugins/jwtclaims/jwtclaims.go +++ b/engine/plugins/jwtclaims/jwtclaims.go @@ -104,8 +104,12 @@ func New(keys authorization.TokenKeyProvider, s Settings) (*Mapper, error) { } 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, worker or admin", rule.Value, rule.Role) + 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") @@ -210,15 +214,14 @@ func grantRole(claims *authorization.Claims, namespace string, role authorizatio claims.Namespaces[namespace] |= role } -// ParseRole maps a role name to Temporal's 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 "worker": - return authorization.RoleWorker, true case "admin": return authorization.RoleAdmin, true } diff --git a/engine/plugins/jwtclaims/jwtclaims_test.go b/engine/plugins/jwtclaims/jwtclaims_test.go index 432dee3..f090e79 100644 --- a/engine/plugins/jwtclaims/jwtclaims_test.go +++ b/engine/plugins/jwtclaims/jwtclaims_test.go @@ -17,6 +17,7 @@ package jwtclaims import ( + "context" "crypto/ecdsa" "crypto/rand" "crypto/rsa" @@ -96,11 +97,11 @@ 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: "worker"}, + {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.RoleWorker || c.System != 0 { + 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"}}}) @@ -111,11 +112,11 @@ func TestRulesOnANestedClaim(t *testing.T) { func TestScopeStringAndDottedKey(t *testing.T) { m := mapper(t, Settings{RolesClaim: "scp", SubjectClaim: "client.id", Rules: []Rule{ - {Value: "workflow.worker", Namespace: "default", Role: "worker"}, + {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.worker,workflow.write"}) - if c.Subject != "orders-app" || c.Namespaces["default"] != authorization.RoleWorker|authorization.RoleWriter { + 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) } } @@ -211,3 +212,42 @@ func TestUnsupportedKeyType(t *testing.T) { 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/tools/internal/enginetest/engine_test.go b/tools/internal/enginetest/engine_test.go index 417a96e..cc903d3 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,11 +95,11 @@ 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() 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 { @@ -144,11 +145,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..959a6c0 --- /dev/null +++ b/tools/internal/enginetest/security_helpers_test.go @@ -0,0 +1,153 @@ +// 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/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/json" + "encoding/pem" + "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) +} diff --git a/tools/internal/enginetest/security_test.go b/tools/internal/enginetest/security_test.go new file mode 100644 index 0000000..d82cc55 --- /dev/null +++ b/tools/internal/enginetest/security_test.go @@ -0,0 +1,143 @@ +// 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" + "strings" + "testing" + "time" +) + +// 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) + 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))) + + 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") + } + 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 := "Request unauthorized" + if name == "a plaintext client" { + want = "connection error" + } + if out, err := e.temporalAt(e.address, tt.flags, tt.args...); err == nil || !strings.Contains(out, want) { + t.Errorf("%s: %v, want a refusal with %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 || + !strings.Contains(out, "connection error") { + 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) + } +} 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) } From 72b53a6c2de3ec6ae7fca7e644a6a2d338f3f4fc Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Tue, 3 Nov 2026 13:16:44 +0530 Subject: [PATCH 07/21] docs: note the sqlite limits in the user guide --- docs/user-guide/reference/runtime-toml.md | 4 ++-- docs/user-guide/troubleshoot.md | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/user-guide/reference/runtime-toml.md b/docs/user-guide/reference/runtime-toml.md index 4b964f4..26e3624 100644 --- a/docs/user-guide/reference/runtime-toml.md +++ b/docs/user-guide/reference/runtime-toml.md @@ -95,13 +95,13 @@ Each gRPC service also uses a membership port 300 below its port (6933, 6936, 69 | `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 | +| `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 | +| `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 | Name to verify in the server's certificate | diff --git a/docs/user-guide/troubleshoot.md b/docs/user-guide/troubleshoot.md index f8447b7..a03e3e2 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -12,6 +12,7 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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 | | `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 | Check `issuer` (it must equal the tokens' `iss`) and the network, or set `jwksUrls` | | `engine.auth.type = "jwt" needs engine.tls` | Tokens without TLS | Add `[engine.tls]` ([Secure the engine](secure-the-engine.md)) | From 2af849048c8e1c002313f8ff3577194c0f1ff19a Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Tue, 3 Nov 2026 14:00:04 +0530 Subject: [PATCH 08/21] test: accept the temporal cli 1.9 wording of a tls refusal CLI 1.9 (the CI pin) names the reason, "requires TLS" or "requires client certificate", where 1.6 printed a connection error, so TestSecuredEngine failed on CI only. --- tools/internal/enginetest/security_test.go | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/tools/internal/enginetest/security_test.go b/tools/internal/enginetest/security_test.go index d82cc55..cc3eb34 100644 --- a/tools/internal/enginetest/security_test.go +++ b/tools/internal/enginetest/security_test.go @@ -18,6 +18,7 @@ package enginetest import ( "fmt" + "slices" "strings" "testing" "time" @@ -114,12 +115,12 @@ inMemory = true "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 := "Request unauthorized" + want := []string{"Request unauthorized"} if name == "a plaintext client" { - want = "connection error" + want = tlsRefusals } - if out, err := e.temporalAt(e.address, tt.flags, tt.args...); err == nil || !strings.Contains(out, want) { - t.Errorf("%s: %v, want a refusal with %q:\n%s", name, err, want, out) + 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) } } @@ -132,7 +133,7 @@ inMemory = true "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 || - !strings.Contains(out, "connection error") { + !containsAny(out, tlsRefusals) { t.Errorf("the internal frontend did not refuse the connection of a caller %s: %v\n%s", name, err, out) } } @@ -141,3 +142,11 @@ inMemory = true t.Errorf("the internal frontend refused a node certificate: %v\n%s", err, out) } } + +// 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) }) +} From 946453d34d8a423fdcb502d8713265d99e23af09 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 06:37:18 +0530 Subject: [PATCH 09/21] fix(engine): fetch identity provider keys only over https jwksUrls, a discovery issuer and a discovered jwks_uri must use https, or plain http to a loopback host: a key set replaced on the way would let anyone sign tokens the engine trusts. Discovery compares the issuer exactly, since tokens are checked against it as written. prometheusAddress needs a numeric port up to 65535. The guide says that issuer alone does not limit tokens to this engine and gives the SQLite historyShards default. --- docs/features/engine-security.md | 8 +++-- docs/user-guide/configure.md | 2 +- docs/user-guide/reference/runtime-toml.md | 4 +-- docs/user-guide/secure-the-engine.md | 11 ++++-- docs/user-guide/troubleshoot.md | 4 ++- engine/internal/runtimeconfig/security.go | 15 +++++++- .../internal/runtimeconfig/security_test.go | 21 ++++++----- engine/plugins/jwtclaims/discovery.go | 35 +++++++++++++++++- engine/plugins/jwtclaims/discovery_test.go | 36 ++++++++++++++++--- 9 files changed, 113 insertions(+), 23 deletions(-) diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index 00cf11f..df32db1 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -25,7 +25,7 @@ connection, and tokens from the customer's own identity provider mapped to Tempo | 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 | +| `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` | @@ -74,7 +74,9 @@ role = "write" - With neither `issuer` nor `audience`, every unexpired token the key set signs is accepted; the start logs a warning. - 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 the same issuer, and the engine does not start if it cannot read it. + 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. - Every token is checked for its signature, an expiry, the issuer and audience when set, and a subject. 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. @@ -96,7 +98,7 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | Test | Covers | |---|---| -| `engine/plugins/jwtclaims/discovery_test.go` | Discovery: the key set URL, another issuer, no key set, invalid documents, unreachable providers | +| `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/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, 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 | diff --git a/docs/user-guide/configure.md b/docs/user-guide/configure.md index c8fca21..26f12f1 100644 --- a/docs/user-guide/configure.md +++ b/docs/user-guide/configure.md @@ -60,7 +60,7 @@ For MySQL use `--plugin mysql8`, port 3306 and the schema names `mysql/v8/tempor 3. For production, add `[engine.tls]` and `[engine.auth]` ([Secure the engine](secure-the-engine.md)). :::caution -`historyShards` (default 512) cannot change after the first start. Decide it before the first start. +`historyShards` (default 512; 1 for SQLite) cannot change after the first start. Decide it before the first start. ::: ## Check the configuration diff --git a/docs/user-guide/reference/runtime-toml.md b/docs/user-guide/reference/runtime-toml.md index 26e3624..19220c4 100644 --- a/docs/user-guide/reference/runtime-toml.md +++ b/docs/user-guide/reference/runtime-toml.md @@ -60,9 +60,9 @@ Each gRPC service also uses a membership port 300 below its port (6933, 6936, 69 | 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; set them when the provider has no OpenID Connect discovery document | +| `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`; also where the key set is discovered (`/.well-known/openid-configuration`). `issuer` or `jwksUrls` is required for `jwt` | +| `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 | diff --git a/docs/user-guide/secure-the-engine.md b/docs/user-guide/secure-the-engine.md index ac83498..71d41ac 100644 --- a/docs/user-guide/secure-the-engine.md +++ b/docs/user-guide/secure-the-engine.md @@ -93,10 +93,17 @@ Keycloak, Auth0 and others. `[engine.auth]` needs `[engine.tls]`: the engine refuses to accept tokens in plain text. :::caution - Set `issuer`, and `audience` when your provider sets one for the engine. Without either, the engine accepts any - unexpired token the provider signed, including tokens it issued for other applications, and logs a warning. + `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. The issuer must match the discovery document's `issuer` exactly, trailing slash + included. + 3. Restart the engine. | Provider | `rolesClaim` | Notes | diff --git a/docs/user-guide/troubleshoot.md b/docs/user-guide/troubleshoot.md index a03e3e2..3c93d59 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -14,7 +14,9 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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 | | `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 | Check `issuer` (it must equal the tokens' `iss`) and the network, or set `jwksUrls` | +| `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 | +| `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.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 | diff --git a/engine/internal/runtimeconfig/security.go b/engine/internal/runtimeconfig/security.go index 4e32b49..60bccb9 100644 --- a/engine/internal/runtimeconfig/security.go +++ b/engine/internal/runtimeconfig/security.go @@ -21,6 +21,7 @@ import ( "fmt" "net" "os" + "strconv" "time" "go.temporal.io/server/common/config" @@ -172,6 +173,14 @@ func (a authSettings) 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)) @@ -217,9 +226,13 @@ func (m metricsSettings) problems() []string { if m.PrometheusAddress == "" { return nil } - if _, port, err := net.SplitHostPort(m.PrometheusAddress); err != nil || port == "" { + _, 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 } diff --git a/engine/internal/runtimeconfig/security_test.go b/engine/internal/runtimeconfig/security_test.go index 6e255a6..618a140 100644 --- a/engine/internal/runtimeconfig/security_test.go +++ b/engine/internal/runtimeconfig/security_test.go @@ -157,11 +157,13 @@ role = "admin" 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 = [\"x\"]\nleewaySeconds = -1\n": "leewaySeconds", + "[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) @@ -179,9 +181,12 @@ func TestMetrics(t *testing.T) { if off := mustParseRuntime(t, sqliteDB).Temporal.Global.Metrics; off != nil { t.Errorf("metrics without settings = %+v", off) } - if _, err := parse([]byte("[engine.metrics]\nprometheusAddress = \"9464\"\n"+sqliteDB), noEnv); err == nil || - !strings.Contains(err.Error(), "must be host:port") { - t.Errorf("err = %v", err) + 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) + } } } diff --git a/engine/plugins/jwtclaims/discovery.go b/engine/plugins/jwtclaims/discovery.go index ddaf3e6..7d1dd5c 100644 --- a/engine/plugins/jwtclaims/discovery.go +++ b/engine/plugins/jwtclaims/discovery.go @@ -21,7 +21,9 @@ import ( "encoding/json" "errors" "fmt" + "net" "net/http" + "net/url" "strings" "time" ) @@ -32,6 +34,9 @@ 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() @@ -54,11 +59,39 @@ func Discover(ctx context.Context, client *http.Client, issuer string) (string, if err := json.NewDecoder(res.Body).Decode(&doc); err != nil { return "", fmt.Errorf("invalid discovery document at %s: %w", url, err) } - if strings.TrimSuffix(doc.Issuer, "/") != strings.TrimSuffix(issuer, "/") { + // 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 index 8622dad..49fbfd7 100644 --- a/engine/plugins/jwtclaims/discovery_test.go +++ b/engine/plugins/jwtclaims/discovery_test.go @@ -44,7 +44,7 @@ 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/") + 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) } @@ -57,9 +57,15 @@ func TestDiscoverErrors(t *testing.T) { want string }{ "other issuer": {func(string) string { return `{"issuer":"https://evil","jwks_uri":"https://evil/jwks"}` }, 200, "names issuer"}, - "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"}, + "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) @@ -74,4 +80,26 @@ func TestDiscoverErrors(t *testing.T) { 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) + } + } } From f735a1d9bd219f00ec8b240cdcf633e1e4ef9a5e Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 10:47:46 +0530 Subject: [PATCH 10/21] docs: note that postgresql verifies the database host name --- docs/user-guide/reference/runtime-toml.md | 2 +- docs/user-guide/troubleshoot.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/reference/runtime-toml.md b/docs/user-guide/reference/runtime-toml.md index 19220c4..b441d0b 100644 --- a/docs/user-guide/reference/runtime-toml.md +++ b/docs/user-guide/reference/runtime-toml.md @@ -104,5 +104,5 @@ Each gRPC service also uses a membership port 300 below its port (6933, 6936, 69 | `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 | Name to verify in the server's certificate | +| `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/troubleshoot.md b/docs/user-guide/troubleshoot.md index 3c93d59..622b863 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -13,6 +13,7 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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 | From fa2b1fa84e83eb42d562f949890fc9eacf0cc030 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 11:18:14 +0530 Subject: [PATCH 11/21] fix(engine): refuse identity provider redirects to plain http --- docs/features/engine-security.md | 7 +- docs/user-guide/secure-the-engine.md | 3 +- docs/user-guide/troubleshoot.md | 1 + engine/go.mod | 2 +- engine/internal/cli/cli.go | 11 +- engine/plugins/jwtclaims/keyset.go | 184 ++++++++++++++++++++++++ engine/plugins/jwtclaims/keyset_test.go | 162 +++++++++++++++++++++ 7 files changed, 363 insertions(+), 7 deletions(-) create mode 100644 engine/plugins/jwtclaims/keyset.go create mode 100644 engine/plugins/jwtclaims/keyset_test.go diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index df32db1..507da8f 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -76,7 +76,9 @@ role = "write" - 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. + 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. - Every token is checked for its signature, an expiry, the issuer and audience when set, and a subject. 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. @@ -86,7 +88,7 @@ role = "write" ## Limits -- Tokens must be signed with RS256 or ES256, which Temporal's key provider supports. +- 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. @@ -99,6 +101,7 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | 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, one to https followed | | `engine/plugins/jwtclaims/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, 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 | diff --git a/docs/user-guide/secure-the-engine.md b/docs/user-guide/secure-the-engine.md index 71d41ac..a85f040 100644 --- a/docs/user-guide/secure-the-engine.md +++ b/docs/user-guide/secure-the-engine.md @@ -101,7 +101,8 @@ Keycloak, Auth0 and others. 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. The issuer must match the discovery document's `issuer` exactly, trailing slash + 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. diff --git a/docs/user-guide/troubleshoot.md b/docs/user-guide/troubleshoot.md index 622b863..c96b120 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -17,6 +17,7 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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 | | `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.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)) | diff --git a/engine/go.mod b/engine/go.mod index 0f114d8..8340e43 100644 --- a/engine/go.mod +++ b/engine/go.mod @@ -5,6 +5,7 @@ go 1.26.8 toolchain go1.26.10 require ( + github.com/go-jose/go-jose/v4 v4.1.4 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 @@ -78,7 +79,6 @@ require ( github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fxamacker/cbor/v2 v2.9.1 // indirect - github.com/go-jose/go-jose/v4 v4.1.4 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/jsonpointer v0.23.1 // indirect diff --git a/engine/internal/cli/cli.go b/engine/internal/cli/cli.go index 0bc75f3..e6ef656 100644 --- a/engine/internal/cli/cli.go +++ b/engine/internal/cli/cli.go @@ -26,9 +26,9 @@ import ( "flag" "fmt" "io" - "net/http" "os" "strings" + "time" "go.temporal.io/server/common/authorization" "go.temporal.io/server/common/config" @@ -216,6 +216,9 @@ func loadConfig(runtimeConfig, configFile string) (*config.Config, *runtimeconfi } } +// 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 { @@ -225,8 +228,9 @@ func newClaimMapper(cfg *config.Config, rt *runtimeconfig.Runtime, logger log.Lo 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(), http.DefaultClient, rt.Auth.Issuer) + 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) } @@ -236,7 +240,8 @@ func newClaimMapper(cfg *config.Config, rt *runtimeconfig.Runtime, logger log.Lo 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") } - keys := authorization.NewDefaultTokenKeyProvider(&cfg.Global.Authorization, logger) + kp := cfg.Global.Authorization.JWTKeyProvider + keys := jwtclaims.NewKeySet(kp.KeySourceURIs, kp.RefreshInterval, client, logger) return jwtclaims.New(keys, *rt.Auth) } diff --git a/engine/plugins/jwtclaims/keyset.go b/engine/plugins/jwtclaims/keyset.go new file mode 100644 index 0000000..4d64c42 --- /dev/null +++ b/engine/plugins/jwtclaims/keyset.go @@ -0,0 +1,184 @@ +// 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/rsa" + "encoding/json" + "fmt" + "net/http" + "strings" + "sync" + "time" + + "github.com/go-jose/go-jose/v4" + "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 + +// 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) + } + 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) + } + var set jose.JSONWebKeySet + if err := json.NewDecoder(res.Body).Decode(&set); err != nil { + return fmt.Errorf("invalid key set at %s: %w", u, err) + } + for _, key := range set.Keys { + switch pub := key.Key.(type) { + case *rsa.PublicKey: + rsaKeys[key.KeyID] = pub + case *ecdsa.PublicKey: + ecKeys[key.KeyID] = pub + default: + k.logger.Warn(fmt.Sprintf("ignoring key %q of unsupported type %T from %s", key.KeyID, key.Key, u)) + } + } + return nil +} + +// 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..5e2de8b --- /dev/null +++ b/engine/plugins/jwtclaims/keyset_test.go @@ -0,0 +1,162 @@ +// 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/json" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/go-jose/go-jose/v4" + "go.temporal.io/server/common/log" +) + +func keySetJSON(t *testing.T, ec *ecdsa.PrivateKey) string { + t.Helper() + b, err := json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{ + {Key: &signingKey.PublicKey, KeyID: "rsa-1", Algorithm: "RS256", Use: "sig"}, + {Key: &ec.PublicKey, KeyID: "ec-1", Algorithm: "ES256", Use: "sig"}, + }}) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// 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") + } + + 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()) + } +} From 11cbf82619f09d7494a2c00d02059d74ba173c14 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 11:18:49 +0530 Subject: [PATCH 12/21] fix(engine): honour --service on a node whose profiles name only api --- docs/features/engine-security.md | 2 +- docs/user-guide/scale-across-nodes.md | 3 ++- docs/user-guide/troubleshoot.md | 1 + engine/internal/cli/cli.go | 3 +++ engine/internal/cli/cli_test.go | 14 +++++++++++--- engine/internal/cli/testdata/runtime-api.toml | 6 ++++++ engine/internal/runtimeconfig/runtimeconfig.go | 3 --- engine/internal/runtimeconfig/security.go | 3 ++- engine/internal/runtimeconfig/security_test.go | 2 +- 9 files changed, 27 insertions(+), 10 deletions(-) create mode 100644 engine/internal/cli/testdata/runtime-api.toml diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index 507da8f..d0330bf 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -104,5 +104,5 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | `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, one to https followed | | `engine/plugins/jwtclaims/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, 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 | +| `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/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 | diff --git a/docs/user-guide/scale-across-nodes.md b/docs/user-guide/scale-across-nodes.md index 564e45a..bd98072 100644 --- a/docs/user-guide/scale-across-nodes.md +++ b/docs/user-guide/scale-across-nodes.md @@ -44,5 +44,6 @@ A starting point: two frontend nodes, three history nodes, two matching nodes an 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. +`--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/troubleshoot.md b/docs/user-guide/troubleshoot.md index c96b120..ba29164 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -18,6 +18,7 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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.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)) | diff --git a/engine/internal/cli/cli.go b/engine/internal/cli/cli.go index e6ef656..0e20df2 100644 --- a/engine/internal/cli/cli.go +++ b/engine/internal/cli/cli.go @@ -129,6 +129,9 @@ func (c command) start(args []string) error { 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) diff --git a/engine/internal/cli/cli_test.go b/engine/internal/cli/cli_test.go index 333b0bd..adf528b 100644 --- a/engine/internal/cli/cli_test.go +++ b/engine/internal/cli/cli_test.go @@ -372,9 +372,10 @@ func TestServicesReachTheServerFactory(t *testing.T) { 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"}}, + "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 @@ -391,6 +392,13 @@ func TestServicesReachTheServerFactory(t *testing.T) { } } +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 { 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/runtimeconfig/runtimeconfig.go b/engine/internal/runtimeconfig/runtimeconfig.go index e031b61..8ed80c7 100644 --- a/engine/internal/runtimeconfig/runtimeconfig.go +++ b/engine/internal/runtimeconfig/runtimeconfig.go @@ -172,9 +172,6 @@ func parse(data []byte, lookupEnv func(string) (string, bool)) (*Runtime, error) if err != nil { return nil, err } - if len(nodeServices) == 0 { - return nil, errNoServices - } s.applyDefaults() if err := s.validate(); err != nil { return nil, err diff --git a/engine/internal/runtimeconfig/security.go b/engine/internal/runtimeconfig/security.go index 60bccb9..304a343 100644 --- a/engine/internal/runtimeconfig/security.go +++ b/engine/internal/runtimeconfig/security.go @@ -245,4 +245,5 @@ func (m metricsSettings) temporalMetrics() *metrics.Config { }} } -var errNoServices = errors.New("runtime.profiles names no engine service; this node runs only other components") +// 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 index 618a140..ff8bfc1 100644 --- a/engine/internal/runtimeconfig/security_test.go +++ b/engine/internal/runtimeconfig/security_test.go @@ -44,6 +44,7 @@ func TestProfilesChooseServices(t *testing.T) { `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) @@ -55,7 +56,6 @@ func TestProfilesChooseServices(t *testing.T) { func TestProfileErrors(t *testing.T) { for profiles, want := range map[string]string{ - `profiles = ["api"]`: "names no engine service", `profiles = []`: "at least one profile", `profiles = ["manager"]`: `unknown profile "manager"`, } { From 0f0da0fb98e51257c1dcdeb0fd6ab46024fa4c24 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 11:42:34 +0530 Subject: [PATCH 13/21] fix(engine): read key sets without the unapproved go-jose module --- engine/go.mod | 2 +- engine/plugins/jwtclaims/keyset.go | 67 ++++++++++++++++++++++--- engine/plugins/jwtclaims/keyset_test.go | 45 ++++++++++++++--- 3 files changed, 98 insertions(+), 16 deletions(-) diff --git a/engine/go.mod b/engine/go.mod index 8340e43..0f114d8 100644 --- a/engine/go.mod +++ b/engine/go.mod @@ -5,7 +5,6 @@ go 1.26.8 toolchain go1.26.10 require ( - github.com/go-jose/go-jose/v4 v4.1.4 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 @@ -79,6 +78,7 @@ require ( github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fxamacker/cbor/v2 v2.9.1 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/jsonpointer v0.23.1 // indirect diff --git a/engine/plugins/jwtclaims/keyset.go b/engine/plugins/jwtclaims/keyset.go index 4d64c42..eead28d 100644 --- a/engine/plugins/jwtclaims/keyset.go +++ b/engine/plugins/jwtclaims/keyset.go @@ -18,15 +18,18 @@ package jwtclaims import ( "crypto/ecdsa" + "crypto/elliptic" "crypto/rsa" + "encoding/base64" "encoding/json" + "errors" "fmt" + "math/big" "net/http" "strings" "sync" "time" - "github.com/go-jose/go-jose/v4" "github.com/golang-jwt/jwt/v5" "go.temporal.io/server/common/authorization" "go.temporal.io/server/common/log" @@ -127,23 +130,71 @@ func (k *KeySet) read(u string, rsaKeys map[string]*rsa.PublicKey, ecKeys map[st if res.StatusCode != http.StatusOK { return fmt.Errorf("unable to read %s: %s", u, res.Status) } - var set jose.JSONWebKeySet + var set struct { + Keys []jwk `json:"keys"` + } if err := json.NewDecoder(res.Body).Decode(&set); err != nil { return fmt.Errorf("invalid key set at %s: %w", u, err) } for _, key := range set.Keys { - switch pub := key.Key.(type) { - case *rsa.PublicKey: - rsaKeys[key.KeyID] = pub - case *ecdsa.PublicKey: - ecKeys[key.KeyID] = pub + var err error + switch key.Kty { + case "RSA": + rsaKeys[key.Kid], err = key.rsa() + case "EC": + ecKeys[key.Kid], err = key.ecdsa() default: - k.logger.Warn(fmt.Sprintf("ignoring key %q of unsupported type %T from %s", key.KeyID, key.Key, u)) + err = fmt.Errorf("unsupported key type %q", key.Kty) + } + if err != nil { + delete(rsaKeys, key.Kid) + delete(ecKeys, key.Kid) + k.logger.Warn(fmt.Sprintf("ignoring key %q from %s: %v", key.Kid, u, err)) } } 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"` + 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) { diff --git a/engine/plugins/jwtclaims/keyset_test.go b/engine/plugins/jwtclaims/keyset_test.go index 5e2de8b..f570344 100644 --- a/engine/plugins/jwtclaims/keyset_test.go +++ b/engine/plugins/jwtclaims/keyset_test.go @@ -21,7 +21,9 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" - "encoding/json" + "encoding/base64" + "fmt" + "math/big" "net/http" "net/http/httptest" "strings" @@ -29,20 +31,25 @@ import ( "testing" "time" - "github.com/go-jose/go-jose/v4" "go.temporal.io/server/common/log" ) +var b64 = base64.RawURLEncoding.EncodeToString + func keySetJSON(t *testing.T, ec *ecdsa.PrivateKey) string { t.Helper() - b, err := json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{ - {Key: &signingKey.PublicKey, KeyID: "rsa-1", Algorithm: "RS256", Use: "sig"}, - {Key: &ec.PublicKey, KeyID: "ec-1", Algorithm: "ES256", Use: "sig"}, - }}) + point, err := ec.PublicKey.Bytes() if err != nil { t.Fatal(err) } - return string(b) + 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. @@ -81,6 +88,9 @@ func TestKeySetReadsAndRefreshesKeys(t *testing.T) { 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") { @@ -160,3 +170,24 @@ func TestKeySetRefreshesOnItsInterval(t *testing.T) { 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) + } + } +} From 9e2d3cd7557ebcfefba6e113f9c0c85ea0956b12 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 13:04:31 +0530 Subject: [PATCH 14/21] fix(engine): default the internode server name to the certificate's --- docs/features/engine-security.md | 4 +- docs/user-guide/reference/runtime-toml.md | 2 +- docs/user-guide/secure-the-engine.md | 4 ++ docs/user-guide/troubleshoot.md | 1 + .../internal/runtimeconfig/runtimeconfig.go | 5 ++ engine/internal/runtimeconfig/security.go | 42 ++++++++++++ .../internal/runtimeconfig/security_test.go | 68 ++++++++++++++++++- tools/internal/enginetest/security_test.go | 3 + 8 files changed, 124 insertions(+), 5 deletions(-) diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index d0330bf..74ebaa8 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -18,7 +18,7 @@ connection, and tokens from the customer's own identity provider mapped to Tempo | `[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` | | Name to verify in internode certificates, when it differs from the host | +| `[engine.tls.internode]` `serverName` | the internode certificate's first DNS name | 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; a certificate without a DNS name needs this set | ### `[engine.auth]` @@ -105,4 +105,4 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | `engine/plugins/jwtclaims/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, 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/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 | +| `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 | diff --git a/docs/user-guide/reference/runtime-toml.md b/docs/user-guide/reference/runtime-toml.md index b441d0b..85a8203 100644 --- a/docs/user-guide/reference/runtime-toml.md +++ b/docs/user-guide/reference/runtime-toml.md @@ -51,7 +51,7 @@ Each gRPC service also uses a membership port 300 below its port (6933, 6936, 69 | `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` | | Name to verify, when it differs from the host | +| `serverName` | the certificate's first DNS name | Name the nodes verify in each other's certificates; set it when the internode certificate has no DNS name | ### `[engine.auth]` diff --git a/docs/user-guide/secure-the-engine.md b/docs/user-guide/secure-the-engine.md index a85f040..69d9975 100644 --- a/docs/user-guide/secure-the-engine.md +++ b/docs/user-guide/secure-the-engine.md @@ -56,6 +56,10 @@ A role in namespace `*` applies to every namespace. Roles add up: a caller in tw caFile = "conf/certs/internode-ca.pem" ``` + Issue the internode certificates with a DNS name every node shares, such as `workflow-nodes.internal`, along + with each node's own address. The nodes verify that name in each other's certificates; the engine reads it from + the certificate, or from `serverName` when you set it. + :::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 diff --git a/docs/user-guide/troubleshoot.md b/docs/user-guide/troubleshoot.md index ba29164..03b0e4b 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -21,6 +21,7 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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 not set and ... has no DNS name` | The internode certificate carries only IP addresses | Reissue it with a DNS name every node shares, or set `serverName` to a name it carries | | `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 | diff --git a/engine/internal/runtimeconfig/runtimeconfig.go b/engine/internal/runtimeconfig/runtimeconfig.go index 8ed80c7..45d0fc4 100644 --- a/engine/internal/runtimeconfig/runtimeconfig.go +++ b/engine/internal/runtimeconfig/runtimeconfig.go @@ -304,6 +304,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, "; ")) } diff --git a/engine/internal/runtimeconfig/security.go b/engine/internal/runtimeconfig/security.go index 304a343..c0155cc 100644 --- a/engine/internal/runtimeconfig/security.go +++ b/engine/internal/runtimeconfig/security.go @@ -17,6 +17,8 @@ package runtimeconfig import ( + "crypto/x509" + "encoding/pem" "errors" "fmt" "net" @@ -112,6 +114,46 @@ func (t engineTLSSettings) problems() []string { return problems } +// defaultInternodeServerName sets the internode server name to the internode certificate's first DNS name. Temporal +// reaches the internal frontend through its membership resolver, a target with no host name to verify, so without a +// server name that connection fails and with it the search attribute, namespace and system worker calls behind it. +func (t *engineTLSSettings) defaultInternodeServerName() error { + in := &t.Internode + if !in.Enabled || in.ServerName != "" { + return nil + } + cert := in.CertFile + if cert == "" { + cert = t.CertFile + } + name, err := firstDNSName(cert) + if err != nil { + return fmt.Errorf("engine.tls.internode.serverName is not set and %w", err) + } + in.ServerName = name + return nil +} + +func firstDNSName(certFile string) (string, error) { + data, err := os.ReadFile(certFile) //nolint:gosec // the configured certificate + if err != nil { + return "", fmt.Errorf("the internode certificate cannot be read: %w", err) + } + block, _ := pem.Decode(data) + if block == nil || block.Type != "CERTIFICATE" { + return "", fmt.Errorf("%s holds no PEM certificate", certFile) + } + c, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return "", fmt.Errorf("%s: %w", certFile, err) + } + if len(c.DNSNames) == 0 { + return "", fmt.Errorf("%s has no DNS name; issue the internode certificates with a DNS name every node "+ + "shares, or set it as serverName", certFile) + } + return c.DNSNames[0], nil +} + func (t engineTLSSettings) temporalTLS() config.RootTLS { var root config.RootTLS if t.enabled() { diff --git a/engine/internal/runtimeconfig/security_test.go b/engine/internal/runtimeconfig/security_test.go index ff8bfc1..d0704d7 100644 --- a/engine/internal/runtimeconfig/security_test.go +++ b/engine/internal/runtimeconfig/security_test.go @@ -17,11 +17,19 @@ package runtimeconfig import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" "os" "path/filepath" "slices" "strings" "testing" + "time" ) const sqliteDB = "[database]\ntype = \"sqlite\"\ninMemory = true\n" @@ -66,15 +74,71 @@ func TestProfileErrors(t *testing.T) { } } +// 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.crt", "engine.key", "ca.pem"} { + 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 filepath.Join(dir, "engine.crt"), filepath.Join(dir, "engine.key"), filepath.Join(dir, "ca.pem") + return certificate(t, dir, "engine.crt", "engine.internal"), filepath.Join(dir, "engine.key"), + filepath.Join(dir, "ca.pem") +} + +// certificate writes a self-signed certificate with the DNS names given. +func certificate(t *testing.T, dir, name string, dnsNames ...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), DNSNames: dnsNames} + 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 TestInternodeServerNameDefaultsToTheCertificatesDNSName(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) + } + explicit := mustParseRuntime(t, tls+internode+"serverName = \"nodes.example\"\n"+sqliteDB).Temporal.Global.TLS + if explicit.Internode.Client.ServerName != "nodes.example" { + t.Fatalf("an explicit server name was replaced: %q", explicit.Internode.Client.ServerName) + } + dir := t.TempDir() + ipOnly := certificate(t, dir, "ip-only.crt") + own := func(certFile string) string { + return internode + "certFile = \"" + certFile + "\"\nkeyFile = \"" + key + "\"\n" + } + if got := mustParseRuntime(t, tls+own(certificate(t, dir, "node.crt", "nodes.internal", "other"))+sqliteDB). + Temporal.Global.TLS.Internode.Client.ServerName; got != "nodes.internal" { + t.Fatalf("with an internode certificate of its own: %q, want nodes.internal", got) + } + for name, tt := range map[string]struct{ toml, want string }{ + "no DNS name": {tls + own(ipOnly), "has no DNS name"}, + "not a PEM file": {tls + own(ca), "holds no PEM certificate"}, + "not readable yet": {tls + own(filepath.Join(dir, "gone.crt")), "internode.certFile"}, + } { + if _, err := parse([]byte(tt.toml+sqliteDB), noEnv); err == nil || !strings.Contains(err.Error(), tt.want) { + t.Errorf("%s: err = %v, want %q", name, err, tt.want) + } + } } func TestTLSMapsToTemporal(t *testing.T) { diff --git a/tools/internal/enginetest/security_test.go b/tools/internal/enginetest/security_test.go index cc3eb34..fd98f26 100644 --- a/tools/internal/enginetest/security_test.go +++ b/tools/internal/enginetest/security_test.go @@ -82,6 +82,9 @@ inMemory = true 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 { From 3d6bec0349d80499aeb2317ec03d408b04991856 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 14:04:09 +0530 Subject: [PATCH 15/21] fix(engine): encrypt membership traffic and settle the internode name --- docs/features/engine-security.md | 8 ++- docs/user-guide/reference/runtime-toml.md | 2 +- docs/user-guide/secure-the-engine.md | 12 ++-- docs/user-guide/troubleshoot.md | 3 +- engine/internal/cli/cli.go | 18 ++++- .../internal/runtimeconfig/runtimeconfig.go | 7 ++ engine/internal/runtimeconfig/security.go | 58 ++++++++++------ .../internal/runtimeconfig/security_test.go | 69 ++++++++++++++----- .../enginetest/security_helpers_test.go | 36 ++++++++++ tools/internal/enginetest/security_test.go | 20 ++++++ 10 files changed, 181 insertions(+), 52 deletions(-) diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index 74ebaa8..278745c 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -18,7 +18,7 @@ connection, and tokens from the customer's own identity provider mapped to Tempo | `[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 first DNS name | 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; a certificate without a DNS name needs this set | +| `[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]` @@ -71,6 +71,10 @@ role = "write" - `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`, every unexpired token the key set signs is accepted; the start logs a warning. - With `issuer` and no `jwksUrls`, the start command reads the provider's OpenID Connect discovery document and uses @@ -105,4 +109,4 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | `engine/plugins/jwtclaims/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, 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/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 | +| `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/user-guide/reference/runtime-toml.md b/docs/user-guide/reference/runtime-toml.md index 85a8203..fd70e15 100644 --- a/docs/user-guide/reference/runtime-toml.md +++ b/docs/user-guide/reference/runtime-toml.md @@ -51,7 +51,7 @@ Each gRPC service also uses a membership port 300 below its port (6933, 6936, 69 | `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 first DNS name | Name the nodes verify in each other's certificates; set it when the internode certificate has no DNS name | +| `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]` diff --git a/docs/user-guide/secure-the-engine.md b/docs/user-guide/secure-the-engine.md index 69d9975..7512c19 100644 --- a/docs/user-guide/secure-the-engine.md +++ b/docs/user-guide/secure-the-engine.md @@ -56,15 +56,17 @@ A role in namespace `*` applies to every namespace. Roles add up: a caller in tw caFile = "conf/certs/internode-ca.pem" ``` - Issue the internode certificates with a DNS name every node shares, such as `workflow-nodes.internal`, along - with each node's own address. The nodes verify that name in each other's certificates; the engine reads it from - the certificate, or from `serverName` when you set it. + 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, or only IP addresses, set `serverName = "workflow-nodes.internal"`. The + engine checks that the certificate carries the name you set. :::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 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. + 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 diff --git a/docs/user-guide/troubleshoot.md b/docs/user-guide/troubleshoot.md index 03b0e4b..88cd487 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -21,7 +21,8 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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 not set and ... has no DNS name` | The internode certificate carries only IP addresses | Reissue it with a DNS name every node shares, or set `serverName` to a name it carries | +| `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 | | `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 | diff --git a/engine/internal/cli/cli.go b/engine/internal/cli/cli.go index 0e20df2..dfe7e30 100644 --- a/engine/internal/cli/cli.go +++ b/engine/internal/cli/cli.go @@ -27,6 +27,7 @@ import ( "fmt" "io" "os" + "slices" "strings" "time" @@ -122,8 +123,9 @@ func (c command) start(args []string) error { if err != nil { return err } + explicit := len(services) > 0 switch { - case len(services) > 0: + case explicit: case rt != nil: services = rt.Services default: @@ -160,14 +162,24 @@ func (c command) start(args []string) error { return fmt.Errorf("unable to create the audience mapper: %w", err) } - server, err := c.newServer(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) } diff --git a/engine/internal/runtimeconfig/runtimeconfig.go b/engine/internal/runtimeconfig/runtimeconfig.go index 45d0fc4..76eb10b 100644 --- a/engine/internal/runtimeconfig/runtimeconfig.go +++ b/engine/internal/runtimeconfig/runtimeconfig.go @@ -37,6 +37,7 @@ 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" @@ -78,6 +79,8 @@ type Runtime struct { 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 { @@ -185,6 +188,10 @@ func parse(data []byte, lookupEnv func(string) (string, bool)) (*Runtime, error) return nil, fmt.Errorf("invalid Temporal configuration: %w", err) } 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 diff --git a/engine/internal/runtimeconfig/security.go b/engine/internal/runtimeconfig/security.go index c0155cc..5daffcd 100644 --- a/engine/internal/runtimeconfig/security.go +++ b/engine/internal/runtimeconfig/security.go @@ -24,6 +24,7 @@ import ( "net" "os" "strconv" + "strings" "time" "go.temporal.io/server/common/config" @@ -114,44 +115,57 @@ func (t engineTLSSettings) problems() []string { return problems } -// defaultInternodeServerName sets the internode server name to the internode certificate's first DNS name. Temporal -// reaches the internal frontend through its membership resolver, a target with no host name to verify, so without a -// server name that connection fails and with it the search attribute, namespace and system worker calls behind it. +// 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 || in.ServerName != "" { + if !in.Enabled { return nil } - cert := in.CertFile - if cert == "" { - cert = t.CertFile + file := in.CertFile + if file == "" { + file = t.CertFile } - name, err := firstDNSName(cert) + cert, err := readCertificate(file) if err != nil { - return fmt.Errorf("engine.tls.internode.serverName is not set and %w", err) + 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, ", ")) } - in.ServerName = name - return nil } -func firstDNSName(certFile string) (string, error) { - data, err := os.ReadFile(certFile) //nolint:gosec // the configured certificate +func readCertificate(file string) (*x509.Certificate, error) { + data, err := os.ReadFile(file) //nolint:gosec // the configured certificate if err != nil { - return "", fmt.Errorf("the internode certificate cannot be read: %w", err) + return nil, err } block, _ := pem.Decode(data) if block == nil || block.Type != "CERTIFICATE" { - return "", fmt.Errorf("%s holds no PEM certificate", certFile) + return nil, fmt.Errorf("%s holds no PEM certificate", file) } - c, err := x509.ParseCertificate(block.Bytes) + cert, err := x509.ParseCertificate(block.Bytes) if err != nil { - return "", fmt.Errorf("%s: %w", certFile, err) - } - if len(c.DNSNames) == 0 { - return "", fmt.Errorf("%s has no DNS name; issue the internode certificates with a DNS name every node "+ - "shares, or set it as serverName", certFile) + return nil, fmt.Errorf("%s: %w", file, err) } - return c.DNSNames[0], nil + return cert, nil } func (t engineTLSSettings) temporalTLS() config.RootTLS { diff --git a/engine/internal/runtimeconfig/security_test.go b/engine/internal/runtimeconfig/security_test.go index d0704d7..0edae2f 100644 --- a/engine/internal/runtimeconfig/security_test.go +++ b/engine/internal/runtimeconfig/security_test.go @@ -24,12 +24,15 @@ import ( "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" @@ -88,15 +91,22 @@ func certFiles(t *testing.T) (cert, key, ca string) { filepath.Join(dir, "ca.pem") } -// certificate writes a self-signed certificate with the DNS names given. -func certificate(t *testing.T, dir, name string, dnsNames ...string) string { +// 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), DNSNames: dnsNames} + 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) @@ -108,7 +118,7 @@ func certificate(t *testing.T, dir, name string, dnsNames ...string) string { return path } -func TestInternodeServerNameDefaultsToTheCertificatesDNSName(t *testing.T) { +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" @@ -117,30 +127,53 @@ func TestInternodeServerNameDefaultsToTheCertificatesDNSName(t *testing.T) { t.Fatalf("internode server name = %q, system worker %q; want the certificate's engine.internal", got.Internode.Client.ServerName, got.SystemWorker.Client.ServerName) } - explicit := mustParseRuntime(t, tls+internode+"serverName = \"nodes.example\"\n"+sqliteDB).Temporal.Global.TLS - if explicit.Internode.Client.ServerName != "nodes.example" { - t.Fatalf("an explicit server name was replaced: %q", explicit.Internode.Client.ServerName) - } dir := t.TempDir() - ipOnly := certificate(t, dir, "ip-only.crt") - own := func(certFile string) string { - return internode + "certFile = \"" + certFile + "\"\nkeyFile = \"" + key + "\"\n" + own := func(certFile, serverName string) string { + toml := internode + "certFile = \"" + certFile + "\"\nkeyFile = \"" + key + "\"\n" + if serverName != "" { + toml += "serverName = \"" + serverName + "\"\n" + } + return tls + toml + sqliteDB } - if got := mustParseRuntime(t, tls+own(certificate(t, dir, "node.crt", "nodes.internal", "other"))+sqliteDB). - Temporal.Global.TLS.Internode.Client.ServerName; got != "nodes.internal" { - t.Fatalf("with an internode certificate of its own: %q, want nodes.internal", got) + 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 }{ - "no DNS name": {tls + own(ipOnly), "has no DNS name"}, - "not a PEM file": {tls + own(ca), "holds no PEM certificate"}, - "not readable yet": {tls + own(filepath.Join(dir, "gone.crt")), "internode.certFile"}, + "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+sqliteDB), noEnv); err == nil || !strings.Contains(err.Error(), tt.want) { + 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" + diff --git a/tools/internal/enginetest/security_helpers_test.go b/tools/internal/enginetest/security_helpers_test.go index 959a6c0..afc8748 100644 --- a/tools/internal/enginetest/security_helpers_test.go +++ b/tools/internal/enginetest/security_helpers_test.go @@ -21,11 +21,13 @@ import ( "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" @@ -151,3 +153,37 @@ func (p *identityProvider) token(claims map[string]any, key *rsa.PrivateKey) str } 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 index fd98f26..f90ea25 100644 --- a/tools/internal/enginetest/security_test.go +++ b/tools/internal/enginetest/security_test.go @@ -144,6 +144,26 @@ inMemory = true 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 From 4caeda00423d669a1bad3c4ab2f14a1962ccc53e Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 14:08:40 +0530 Subject: [PATCH 16/21] fix(engine): harden key set reads and check when tokens were issued --- docs/features/engine-security.md | 12 ++-- engine/plugins/jwtclaims/discovery.go | 3 +- engine/plugins/jwtclaims/discovery_test.go | 1 + engine/plugins/jwtclaims/jwtclaims.go | 1 + engine/plugins/jwtclaims/jwtclaims_test.go | 16 +++-- engine/plugins/jwtclaims/keyset.go | 81 +++++++++++++++++----- engine/plugins/jwtclaims/keyset_test.go | 69 ++++++++++++++++++ 7 files changed, 154 insertions(+), 29 deletions(-) diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index 278745c..fd1bc2e 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -83,8 +83,12 @@ role = "write" 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. -- Every token is checked for its signature, an expiry, the issuer and audience when set, and a subject. A call - without a token, or with a token that maps to no role, is refused, except Temporal's health checks. +- 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`. +- 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` @@ -105,8 +109,8 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | 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, one to https followed | -| `engine/plugins/jwtclaims/jwtclaims_test.go` | Temporal's format, rules on nested claims, scope strings, regex, issuer, audience, expiry, forged and malformed tokens | +| `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 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/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/engine/plugins/jwtclaims/discovery.go b/engine/plugins/jwtclaims/discovery.go index 7d1dd5c..f979065 100644 --- a/engine/plugins/jwtclaims/discovery.go +++ b/engine/plugins/jwtclaims/discovery.go @@ -21,6 +21,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "net" "net/http" "net/url" @@ -56,7 +57,7 @@ func Discover(ctx context.Context, client *http.Client, issuer string) (string, Issuer string `json:"issuer"` JWKSURI string `json:"jwks_uri"` } - if err := json.NewDecoder(res.Body).Decode(&doc); err != nil { + 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. diff --git a/engine/plugins/jwtclaims/discovery_test.go b/engine/plugins/jwtclaims/discovery_test.go index 49fbfd7..f7ae58f 100644 --- a/engine/plugins/jwtclaims/discovery_test.go +++ b/engine/plugins/jwtclaims/discovery_test.go @@ -57,6 +57,7 @@ func TestDiscoverErrors(t *testing.T) { 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 { diff --git a/engine/plugins/jwtclaims/jwtclaims.go b/engine/plugins/jwtclaims/jwtclaims.go index f90d04d..d509114 100644 --- a/engine/plugins/jwtclaims/jwtclaims.go +++ b/engine/plugins/jwtclaims/jwtclaims.go @@ -148,6 +148,7 @@ 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 != "" { diff --git a/engine/plugins/jwtclaims/jwtclaims_test.go b/engine/plugins/jwtclaims/jwtclaims_test.go index f090e79..28b6e8c 100644 --- a/engine/plugins/jwtclaims/jwtclaims_test.go +++ b/engine/plugins/jwtclaims/jwtclaims_test.go @@ -162,12 +162,18 @@ func TestTokensThatAreRefused(t *testing.T) { 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, - "garbage": "Bearer not.a.token", + "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) diff --git a/engine/plugins/jwtclaims/keyset.go b/engine/plugins/jwtclaims/keyset.go index eead28d..6b427f1 100644 --- a/engine/plugins/jwtclaims/keyset.go +++ b/engine/plugins/jwtclaims/keyset.go @@ -24,8 +24,10 @@ import ( "encoding/json" "errors" "fmt" + "io" "math/big" "net/http" + "slices" "strings" "sync" "time" @@ -39,6 +41,9 @@ import ( // 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 { @@ -52,6 +57,9 @@ func checkRedirect(req *http.Request, via []*http.Request) error { 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 } @@ -133,37 +141,72 @@ func (k *KeySet) read(u string, rsaKeys map[string]*rsa.PublicKey, ecKeys map[st var set struct { Keys []jwk `json:"keys"` } - if err := json.NewDecoder(res.Body).Decode(&set); err != nil { + if err := json.NewDecoder(io.LimitReader(res.Body, maxDocumentBytes)).Decode(&set); err != nil { return fmt.Errorf("invalid key set at %s: %w", u, err) } for _, key := range set.Keys { - var err error - switch key.Kty { - case "RSA": - rsaKeys[key.Kid], err = key.rsa() - case "EC": - ecKeys[key.Kid], err = key.ecdsa() - default: - err = fmt.Errorf("unsupported key type %q", key.Kty) + 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 { - delete(rsaKeys, key.Kid) - delete(ecKeys, key.Kid) - k.logger.Warn(fmt.Sprintf("ignoring key %q from %s: %v", key.Kid, u, err)) + 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"` - N string `json:"n"` - E string `json:"e"` - Crv string `json:"crv"` - X string `json:"x"` - Y string `json:"y"` + 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) { diff --git a/engine/plugins/jwtclaims/keyset_test.go b/engine/plugins/jwtclaims/keyset_test.go index f570344..e6316e2 100644 --- a/engine/plugins/jwtclaims/keyset_test.go +++ b/engine/plugins/jwtclaims/keyset_test.go @@ -191,3 +191,72 @@ func TestInvalidKeysAreRejected(t *testing.T) { } } } + +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) + } +} From ff4c23231aff126db177eeaf8374971c853593cb Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 14:10:24 +0530 Subject: [PATCH 17/21] docs: keep the schema tool's password out of the command line --- docs/user-guide/configure.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/user-guide/configure.md b/docs/user-guide/configure.md index 26f12f1..b6a3e9e 100644 --- a/docs/user-guide/configure.md +++ b/docs/user-guide/configure.md @@ -22,13 +22,14 @@ The runtime uses two databases on the same server: `temporal` (workflow state) a (search). Create them and their schemas once with the schema tool shipped next to the engine: ```bash -SQL="bin/workflow-engine-sql --plugin postgres12 --ep db.example.com -p 5432 -u workflow --pw " -$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 +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`. From 14064174ce03a85faebf14b53eb7849d02a4f6a1 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 14:58:19 +0530 Subject: [PATCH 18/21] fix(engine): keep the keys when a key set response has none --- docs/features/engine-security.md | 4 ++-- docs/guides/DEVELOPING.md | 1 + docs/user-guide/secure-the-engine.md | 5 +++-- docs/user-guide/troubleshoot.md | 1 + engine/plugins/jwtclaims/keyset.go | 8 +++++-- engine/plugins/jwtclaims/keyset_test.go | 30 +++++++++++++++++++++++++ 6 files changed, 43 insertions(+), 6 deletions(-) diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index fd1bc2e..68ccc43 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -85,7 +85,7 @@ role = "write" 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`. + 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. @@ -109,7 +109,7 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | 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 refused | +| `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 | diff --git a/docs/guides/DEVELOPING.md b/docs/guides/DEVELOPING.md index 5026302..8003275 100644 --- a/docs/guides/DEVELOPING.md +++ b/docs/guides/DEVELOPING.md @@ -84,3 +84,4 @@ Integrator. | Ballerina tests fail with `Failed to start workflow` | The namespace lacks the `WorkflowKind` search attribute | Run the suites through `make test-smoke` / `make test-full` (the `balsuite` runner adds it) | | 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 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/secure-the-engine.md b/docs/user-guide/secure-the-engine.md index 7512c19..f156730 100644 --- a/docs/user-guide/secure-the-engine.md +++ b/docs/user-guide/secure-the-engine.md @@ -58,8 +58,9 @@ A role in namespace `*` applies to every namespace. Roles add up: a caller in tw 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, or only IP addresses, set `serverName = "workflow-nodes.internal"`. The - engine checks that the certificate carries the name you set. + 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 diff --git a/docs/user-guide/troubleshoot.md b/docs/user-guide/troubleshoot.md index 88cd487..654cb6d 100644 --- a/docs/user-guide/troubleshoot.md +++ b/docs/user-guide/troubleshoot.md @@ -23,6 +23,7 @@ keywords: [wso2 integrator, workflow runtime, troubleshooting, errors] | `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 | diff --git a/engine/plugins/jwtclaims/keyset.go b/engine/plugins/jwtclaims/keyset.go index 6b427f1..03d2d1c 100644 --- a/engine/plugins/jwtclaims/keyset.go +++ b/engine/plugins/jwtclaims/keyset.go @@ -138,13 +138,17 @@ func (k *KeySet) read(u string, rsaKeys map[string]*rsa.PublicKey, ecKeys map[st 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"` + 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) } - for _, key := range set.Keys { + 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)) } diff --git a/engine/plugins/jwtclaims/keyset_test.go b/engine/plugins/jwtclaims/keyset_test.go index e6316e2..135067a 100644 --- a/engine/plugins/jwtclaims/keyset_test.go +++ b/engine/plugins/jwtclaims/keyset_test.go @@ -260,3 +260,33 @@ func TestOversizedKeySetsAreRefused(t *testing.T) { 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") + } +} From 3b755936680db9baa3037864e876d7140f0060f3 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 15:01:22 +0530 Subject: [PATCH 19/21] test: join two secured nodes into one engine --- docs/features/engine-security.md | 1 + tools/internal/enginetest/cluster_test.go | 65 ++++++++++++++++++++++ tools/internal/enginetest/security_test.go | 28 ++++++++-- 3 files changed, 90 insertions(+), 4 deletions(-) create mode 100644 tools/internal/enginetest/cluster_test.go diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index 68ccc43..c8fa9b4 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -113,4 +113,5 @@ Roles from client certificate subjects, tokens issued by the Manager, and task-q | `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/tools/internal/enginetest/cluster_test.go b/tools/internal/enginetest/cluster_test.go new file mode 100644 index 0000000..3fd3dcc --- /dev/null +++ b/tools/internal/enginetest/cluster_test.go @@ -0,0 +1,65 @@ +// 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. +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 := start(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/security_test.go b/tools/internal/enginetest/security_test.go index f90ea25..4083019 100644 --- a/tools/internal/enginetest/security_test.go +++ b/tools/internal/enginetest/security_test.go @@ -24,10 +24,19 @@ import ( "time" ) -// 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) +// 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") @@ -71,6 +80,17 @@ 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 { From a8d23a55f8b46d047222592d4ded55578bad90d1 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Thu, 5 Nov 2026 11:55:06 +0530 Subject: [PATCH 20/21] test: start the second sqlite node again after SQLITE_BUSY --- tools/internal/enginetest/cluster_test.go | 18 +++++++++++++++++- tools/internal/enginetest/engine_test.go | 19 ++++++++++++++----- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/tools/internal/enginetest/cluster_test.go b/tools/internal/enginetest/cluster_test.go index 3fd3dcc..60bd466 100644 --- a/tools/internal/enginetest/cluster_test.go +++ b/tools/internal/enginetest/cluster_test.go @@ -27,6 +27,22 @@ import ( // 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) @@ -50,7 +66,7 @@ func TestTwoSecuredNodesFormOneEngine(t *testing.T) { first := start(t, binary, se.base, admin, "start", "--runtime-config", node(se.base, `["frontend", "matching", "worker"]`)) base := freeBase(t) - second := start(t, binary, base, admin, "start", "--runtime-config", node(base, `["frontend", "history"]`)) + 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") diff --git a/tools/internal/enginetest/engine_test.go b/tools/internal/enginetest/engine_test.go index cc903d3..d11c2b8 100644 --- a/tools/internal/enginetest/engine_test.go +++ b/tools/internal/enginetest/engine_test.go @@ -97,13 +97,23 @@ func writeConfig(t *testing.T, dir, toml string) string { // 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), 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) }() @@ -112,17 +122,16 @@ func start(t *testing.T, binary string, base int, flags []string, args ...string 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 + 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. From c84221e9dad53ca1f8786756018b1397d598474f Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Thu, 5 Nov 2026 14:36:33 +0530 Subject: [PATCH 21/21] test: stop an engine that never reported serving A retry on the same ports could otherwise reach the old process. The engine-security doc now says which checks still apply without issuer and audience. --- docs/features/engine-security.md | 4 ++-- tools/internal/enginetest/engine_test.go | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/features/engine-security.md b/docs/features/engine-security.md index c8fa9b4..cde0ec0 100644 --- a/docs/features/engine-security.md +++ b/docs/features/engine-security.md @@ -75,8 +75,8 @@ role = "write" 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`, every unexpired token the key set signs is accepted; the start logs a - warning. +- 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 diff --git a/tools/internal/enginetest/engine_test.go b/tools/internal/enginetest/engine_test.go index d11c2b8..82e1a99 100644 --- a/tools/internal/enginetest/engine_test.go +++ b/tools/internal/enginetest/engine_test.go @@ -131,6 +131,7 @@ func launch(t *testing.T, binary string, base int, flags []string, args ...strin } time.Sleep(time.Second) } + 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) }