Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(wif): bind workload identity tokens to an audience and a subject (#21350)

Vincent Huang1d84ac5b0fa7
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index f8afd4f333..f9f01d99e6 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -22223,17 +22223,27 @@ components:
issuerUrl:
type: string
title: issuer_url
- description: OIDC Issuer URL (auto-filled based on provider_type, can be overridden)
+ description: |-
+ HTTPS URL of the OIDC issuer. The exchange fetches
+ {issuer_url}/.well-known/openid-configuration to verify a token, unless
+ jwks_url names the key set directly.
allowedAudiences:
type: array
items:
type: string
title: allowed_audiences
- description: Allowed audiences for token validation
+ description: |-
+ Audiences a token may be minted for. A token authenticates if its `aud`
+ claim matches any entry.
subjectPattern:
type: string
title: subject_pattern
- description: Subject pattern to match (e.g., "repo:owner/repo:ref:refs/heads/main")
+ description: |-
+ The subject a token must carry, e.g. "repo:owner/repo:ref:refs/heads/main".
+ A trailing "*" is a prefix match. For GitHub and GitLab subjects it must
+ complete an owner or group segment, so "repo:my-org/*" is accepted and
+ "repo:*" is not. Other issuers write other vocabularies, so a wildcard
+ outside those two is accepted as given.
jwksUrl:
type: string
title: jwks_url
diff --git a/backend/api/v1/workload_identity_service.go b/backend/api/v1/workload_identity_service.go
index 854ee53edf..bd220a7579 100644
--- a/backend/api/v1/workload_identity_service.go
+++ b/backend/api/v1/workload_identity_service.go
@@ -89,12 +89,12 @@ func (s *WorkloadIdentityService) CreateWorkloadIdentity(ctx context.Context, re
}
// Convert API workload identity config to store workload identity config
- var storeConfig *storepb.WorkloadIdentityConfig
- if wi.WorkloadIdentityConfig != nil {
- if err := validateWorkloadIdentityConfig(wi.WorkloadIdentityConfig); err != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrap(err, "invalid workload_identity_config"))
- }
- storeConfig = convertToStoreWorkloadIdentityConfig(wi.WorkloadIdentityConfig)
+ if wi.WorkloadIdentityConfig == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("workload_identity_config is required"))
+ }
+ storeConfig := convertToStoreWorkloadIdentityConfig(wi.WorkloadIdentityConfig)
+ if err := validateWorkloadIdentityConfig(storeConfig); err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrap(err, "invalid workload_identity_config"))
}
// Create the workload identity
@@ -235,14 +235,15 @@ func (s *WorkloadIdentityService) UpdateWorkloadIdentity(ctx context.Context, re
case "title":
patch.Name = &request.Msg.WorkloadIdentity.Title
case "workload_identity_config":
- if request.Msg.WorkloadIdentity.WorkloadIdentityConfig != nil {
- if err := validateWorkloadIdentityConfig(request.Msg.WorkloadIdentity.WorkloadIdentityConfig); err != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrap(err, "invalid workload_identity_config"))
- }
- patch.Config = convertToStoreWorkloadIdentityConfig(request.Msg.WorkloadIdentity.WorkloadIdentityConfig)
- } else {
- patch.Config = &storepb.WorkloadIdentityConfig{}
+ // An empty config is an identity nothing can authenticate as.
+ if request.Msg.WorkloadIdentity.WorkloadIdentityConfig == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("workload_identity_config is required"))
+ }
+ storeConfig := convertToStoreWorkloadIdentityConfig(request.Msg.WorkloadIdentity.WorkloadIdentityConfig)
+ if err := validateWorkloadIdentityConfig(storeConfig); err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrap(err, "invalid workload_identity_config"))
}
+ patch.Config = storeConfig
default:
// Ignore unknown fields
}
@@ -315,45 +316,47 @@ func (s *WorkloadIdentityService) UndeleteWorkloadIdentity(ctx context.Context,
return connect.NewResponse(convertToWorkloadIdentity(restoredWI)), nil
}
-func validateWorkloadIdentityConfig(config *v1pb.WorkloadIdentityConfig) error {
+// validateWorkloadIdentityConfig judges the configuration as it will be
+// stored, so the caller converts first: every comparison at the exchange is
+// exact, and the stored form is the one it compares.
+func validateWorkloadIdentityConfig(config *storepb.WorkloadIdentityConfig) error {
if config == nil {
return nil
}
switch config.ProviderType {
- case v1pb.WorkloadIdentityConfig_GITHUB, v1pb.WorkloadIdentityConfig_GITLAB:
- return nil
- case v1pb.WorkloadIdentityConfig_OIDC:
- issuerURL := strings.TrimSpace(config.IssuerUrl)
- if issuerURL == "" {
- return errors.New("issuer_url is required for OIDC")
- }
- if err := wif.ValidateIssuerURL(issuerURL); err != nil {
- return err
- }
- jwksURL := strings.TrimSpace(config.JwksUrl)
- if jwksURL != "" {
- if err := wif.ValidateJWKSURL(jwksURL); err != nil {
- return err
- }
- }
- if len(config.AllowedAudiences) == 0 {
- return errors.New("allowed_audiences is required for OIDC")
- }
- for _, audience := range config.AllowedAudiences {
- if strings.TrimSpace(audience) == "" {
- return errors.New("allowed_audiences must not contain an empty value")
- }
- }
- if strings.TrimSpace(config.SubjectPattern) == "" {
- return errors.New("subject_pattern is required for OIDC")
- }
- return nil
- case v1pb.WorkloadIdentityConfig_PROVIDER_TYPE_UNSPECIFIED:
+ case storepb.WorkloadIdentityConfig_GITHUB,
+ storepb.WorkloadIdentityConfig_GITLAB,
+ storepb.WorkloadIdentityConfig_OIDC:
+ case storepb.WorkloadIdentityConfig_PROVIDER_TYPE_UNSPECIFIED:
return errors.New("provider_type is required")
default:
return errors.New("provider_type is invalid")
}
+
+ // Every provider reaches the same token exchange, so every provider needs
+ // the same binding: an issuer whose keys can be fetched, an audience the
+ // token has to name, and a subject it has to match.
+ if config.IssuerUrl == "" {
+ return errors.New("issuer_url is required")
+ }
+ if err := wif.ValidateIssuerURL(config.IssuerUrl); err != nil {
+ return err
+ }
+ if config.JwksUrl != "" {
+ if err := wif.ValidateJWKSURL(config.JwksUrl); err != nil {
+ return err
+ }
+ }
+ if len(config.AllowedAudiences) == 0 {
+ return errors.New("allowed_audiences is required")
+ }
+ for _, audience := range config.AllowedAudiences {
+ if audience == "" {
+ return errors.New("allowed_audiences must not contain an empty value")
+ }
+ }
+ return wif.ValidateSubjectPattern(config.SubjectPattern)
}
// convertToWorkloadIdentity converts a store.WorkloadIdentityMessage to a v1pb.WorkloadIdentity.
@@ -379,19 +382,16 @@ func convertToStoreWorkloadIdentityConfig(config *v1pb.WorkloadIdentityConfig) *
return nil
}
- issuerURL := config.IssuerUrl
- jwksURL := config.JwksUrl
- allowedAudiences := config.AllowedAudiences
- subjectPattern := config.SubjectPattern
- if config.ProviderType == v1pb.WorkloadIdentityConfig_OIDC {
- issuerURL = strings.TrimSpace(issuerURL)
- jwksURL = strings.TrimSpace(jwksURL)
- allowedAudiences = make([]string, len(config.AllowedAudiences))
- for i, audience := range config.AllowedAudiences {
- allowedAudiences[i] = strings.TrimSpace(audience)
- }
- subjectPattern = strings.TrimSpace(subjectPattern)
+ // Normalized here for every provider, and validated in this form: every
+ // comparison at the exchange is exact, so a value that reaches the column
+ // untrimmed could never match a token.
+ allowedAudiences := make([]string, len(config.AllowedAudiences))
+ for i, audience := range config.AllowedAudiences {
+ allowedAudiences[i] = strings.TrimSpace(audience)
}
+ issuerURL := strings.TrimSpace(config.IssuerUrl)
+ jwksURL := strings.TrimSpace(config.JwksUrl)
+ subjectPattern := strings.TrimSpace(config.SubjectPattern)
return &storepb.WorkloadIdentityConfig{
ProviderType: storepb.WorkloadIdentityConfig_ProviderType(config.ProviderType),
diff --git a/backend/api/v1/workload_identity_service_test.go b/backend/api/v1/workload_identity_service_test.go
index 78d67e687e..6da05679e2 100644
--- a/backend/api/v1/workload_identity_service_test.go
+++ b/backend/api/v1/workload_identity_service_test.go
@@ -16,19 +16,25 @@ func TestValidateWorkloadIdentityConfig(t *testing.T) {
wantErr string
}{
{
- name: "nil config",
- },
- {
- name: "github compatibility",
+ // issuer_url is free-form, so a wildcard carrying no "/" is the
+ // operator's call outside the two vocabularies we model.
+ name: "oidc namespace wildcard stays legal",
config: &v1pb.WorkloadIdentityConfig{
- ProviderType: v1pb.WorkloadIdentityConfig_GITHUB,
+ ProviderType: v1pb.WorkloadIdentityConfig_OIDC,
+ IssuerUrl: "https://oidc.eks.us-east-1.amazonaws.com/id/9F8E",
+ AllowedAudiences: []string{"bytebase"},
+ SubjectPattern: "system:serviceaccount:prod:*",
},
},
{
- name: "gitlab compatibility",
+ name: "github audience with a blank entry",
config: &v1pb.WorkloadIdentityConfig{
- ProviderType: v1pb.WorkloadIdentityConfig_GITLAB,
+ ProviderType: v1pb.WorkloadIdentityConfig_GITHUB,
+ IssuerUrl: "https://token.actions.githubusercontent.com",
+ AllowedAudiences: []string{"bytebase", " "},
+ SubjectPattern: "repo:acme-corp/deploy:ref:refs/heads/main",
},
+ wantErr: "allowed_audiences must not contain an empty value",
},
{
name: "oidc valid",
@@ -126,7 +132,8 @@ func TestValidateWorkloadIdentityConfig(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
- err := validateWorkloadIdentityConfig(test.config)
+ err := validateWorkloadIdentityConfig(
+ convertToStoreWorkloadIdentityConfig(test.config))
if test.wantErr == "" {
require.NoError(t, err)
return
@@ -136,8 +143,11 @@ func TestValidateWorkloadIdentityConfig(t *testing.T) {
}
}
-func TestConvertToStoreWorkloadIdentityConfigNormalizesOIDCValues(t *testing.T) {
+func TestConvertToStoreWorkloadIdentityConfigNormalizes(t *testing.T) {
t.Parallel()
+ // Every comparison at the exchange is exact, so a padded value stored
+ // verbatim is an identity that passes Create and can never authenticate.
+ // The write path validates this normalized form for that reason.
config := &v1pb.WorkloadIdentityConfig{
ProviderType: v1pb.WorkloadIdentityConfig_OIDC,
IssuerUrl: " https://nomad.example.com ",
@@ -145,12 +155,23 @@ func TestConvertToStoreWorkloadIdentityConfigNormalizesOIDCValues(t *testing.T)
AllowedAudiences: []string{" bytebase ", " terraform "},
SubjectPattern: " nomad_job:atlantis:* ",
}
- require.NoError(t, validateWorkloadIdentityConfig(config))
-
- converted := convertToStoreWorkloadIdentityConfig(config)
+ stored := convertToStoreWorkloadIdentityConfig(config)
+ require.NoError(t, validateWorkloadIdentityConfig(stored))
+ require.Equal(t, "https://nomad.example.com", stored.IssuerUrl)
+ require.Equal(t, "https://keys.example.com/jwks.json", stored.JwksUrl)
+ require.Equal(t, []string{"bytebase", "terraform"}, stored.AllowedAudiences)
+ require.Equal(t, "nomad_job:atlantis:*", stored.SubjectPattern)
- require.Equal(t, "https://nomad.example.com", converted.IssuerUrl)
- require.Equal(t, "https://keys.example.com/jwks.json", converted.JwksUrl)
- require.Equal(t, []string{"bytebase", "terraform"}, converted.AllowedAudiences)
- require.Equal(t, "nomad_job:atlantis:*", converted.SubjectPattern)
+ // A pattern that only looks bindable before normalization. Validating the
+ // request instead of the stored form let these through, and the matcher
+ // then refused them forever.
+ for _, pattern := range []string{" * ", " repo:* "} {
+ padded := convertToStoreWorkloadIdentityConfig(&v1pb.WorkloadIdentityConfig{
+ ProviderType: v1pb.WorkloadIdentityConfig_GITHUB,
+ IssuerUrl: "https://token.actions.githubusercontent.com",
+ AllowedAudiences: []string{"bytebase"},
+ SubjectPattern: pattern,
+ })
+ require.Error(t, validateWorkloadIdentityConfig(padded), "pattern=%q", pattern)
+ }
}
diff --git a/backend/api/v1/workload_identity_service_validation_test.go b/backend/api/v1/workload_identity_service_validation_test.go
new file mode 100644
index 0000000000..5b35d535ce
--- /dev/null
+++ b/backend/api/v1/workload_identity_service_validation_test.go
@@ -0,0 +1,96 @@
+package v1
+
+import (
+ "context"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/fieldmaskpb"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/component/config"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+// TestWorkloadIdentityConfigValidation pins that Create and Update reach the
+// configuration validator, and how Update treats each update-mask shape. The
+// rules themselves are pinned without a database in
+// TestValidateWorkloadIdentityConfig.
+//
+//nolint:tparallel // Subtests share one seeded identity.
+func TestWorkloadIdentityConfigValidation(t *testing.T) {
+ t.Parallel()
+ ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")
+ db, stores, _ := testcontainer.NewMetadataDB(t)
+ _, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default')`)
+ require.NoError(t, err)
+ service := &WorkloadIdentityService{store: stores, profile: &config.Profile{}}
+
+ valid := func() *v1pb.WorkloadIdentityConfig {
+ return &v1pb.WorkloadIdentityConfig{
+ ProviderType: v1pb.WorkloadIdentityConfig_GITHUB,
+ IssuerUrl: "https://token.actions.githubusercontent.com",
+ AllowedAudiences: []string{"bytebase"},
+ SubjectPattern: "repo:acme-corp/deploy:ref:refs/heads/main",
+ }
+ }
+ create := func(id string, config *v1pb.WorkloadIdentityConfig) error {
+ _, err := service.CreateWorkloadIdentity(ctx, connect.NewRequest(&v1pb.CreateWorkloadIdentityRequest{
+ Parent: "workspaces/default",
+ WorkloadIdentityId: id,
+ WorkloadIdentity: &v1pb.WorkloadIdentity{Title: id, WorkloadIdentityConfig: config},
+ }))
+ return err
+ }
+
+ // One row, not the rule table: what this test pins is that Create and
+ // Update reach the validator at all.
+ t.Run("create rejects an unbindable config", func(t *testing.T) {
+ a := require.New(t)
+ config := valid()
+ config.AllowedAudiences = nil
+ err := create("wi-no-audience", config)
+ a.Error(err)
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
+ })
+ t.Run("create accepts a bindable config", func(t *testing.T) {
+ require.New(t).NoError(create("wi-valid", valid()))
+ })
+ t.Run("create rejects a missing config", func(t *testing.T) {
+ a := require.New(t)
+ err := create("wi-none", nil)
+ a.Error(err)
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
+ })
+
+ update := func(config *v1pb.WorkloadIdentityConfig, paths ...string) error {
+ _, err := service.UpdateWorkloadIdentity(ctx, connect.NewRequest(&v1pb.UpdateWorkloadIdentityRequest{
+ WorkloadIdentity: &v1pb.WorkloadIdentity{
+ Name: "workloadIdentities/[email protected]",
+ Title: "renamed",
+ WorkloadIdentityConfig: config,
+ },
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: paths},
+ }))
+ return err
+ }
+ t.Run("update rejects an unbindable config", func(t *testing.T) {
+ a := require.New(t)
+ config := valid()
+ config.AllowedAudiences = nil
+ err := update(config, "workload_identity_config")
+ a.Error(err)
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
+ })
+ t.Run("update rejects a config cleared through the mask", func(t *testing.T) {
+ a := require.New(t)
+ err := update(nil, "workload_identity_config")
+ a.Error(err)
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
+ })
+ t.Run("update accepts a title-only mask over a bindable config", func(t *testing.T) {
+ require.New(t).NoError(update(nil, "title"))
+ })
+}
diff --git a/backend/generated-go/v1/workload_identity_service.pb.go b/backend/generated-go/v1/workload_identity_service.pb.go
index 51962343a0..c5ab5e0b78 100644
--- a/backend/generated-go/v1/workload_identity_service.pb.go
+++ b/backend/generated-go/v1/workload_identity_service.pb.go
@@ -178,11 +178,18 @@ type WorkloadIdentityConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Provider configuration mode.
ProviderType WorkloadIdentityConfig_ProviderType `protobuf:"varint,1,opt,name=provider_type,json=providerType,proto3,enum=bytebase.v1.WorkloadIdentityConfig_ProviderType" json:"provider_type,omitempty"`
- // OIDC Issuer URL (auto-filled based on provider_type, can be overridden)
+ // HTTPS URL of the OIDC issuer. The exchange fetches
+ // {issuer_url}/.well-known/openid-configuration to verify a token, unless
+ // jwks_url names the key set directly.
IssuerUrl string `protobuf:"bytes,2,opt,name=issuer_url,json=issuerUrl,proto3" json:"issuer_url,omitempty"`
- // Allowed audiences for token validation
+ // Audiences a token may be minted for. A token authenticates if its `aud`
+ // claim matches any entry.
AllowedAudiences []string `protobuf:"bytes,3,rep,name=allowed_audiences,json=allowedAudiences,proto3" json:"allowed_audiences,omitempty"`
- // Subject pattern to match (e.g., "repo:owner/repo:ref:refs/heads/main")
+ // The subject a token must carry, e.g. "repo:owner/repo:ref:refs/heads/main".
+ // A trailing "*" is a prefix match. For GitHub and GitLab subjects it must
+ // complete an owner or group segment, so "repo:my-org/*" is accepted and
+ // "repo:*" is not. Other issuers write other vocabularies, so a wildcard
+ // outside those two is accepted as given.
SubjectPattern string `protobuf:"bytes,4,opt,name=subject_pattern,json=subjectPattern,proto3" json:"subject_pattern,omitempty"`
// Optional JWKS endpoint. When empty, use OIDC discovery from issuer_url.
JwksUrl string `protobuf:"bytes,5,opt,name=jwks_url,json=jwksUrl,proto3" json:"jwks_url,omitempty"`
@@ -685,22 +692,22 @@ var File_v1_workload_identity_service_proto protoreflect.FileDescriptor
const file_v1_workload_identity_service_proto_rawDesc = "" +
"\n" +
- "\"v1/workload_identity_service.proto\x12\vbytebase.v1\x1a\x1bbuf/validate/validate.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x13v1/annotation.proto\x1a\x0fv1/common.proto\"\xf1\x02\n" +
+ "\"v1/workload_identity_service.proto\x12\vbytebase.v1\x1a\x1bbuf/validate/validate.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x13v1/annotation.proto\x1a\x0fv1/common.proto\"\xf6\x02\n" +
"\x10WorkloadIdentity\x12\x17\n" +
"\x04name\x18\x01 \x01(\tB\x03\xe0A\x03R\x04name\x12(\n" +
"\x05state\x18\x02 \x01(\x0e2\x12.bytebase.v1.StateR\x05state\x12\x19\n" +
"\x05email\x18\x03 \x01(\tB\x03\xe0A\x03R\x05email\x12\x1e\n" +
"\x05title\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\xc8\x01R\x05title\x12@\n" +
"\vcreate_time\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampB\x03\xe0A\x03R\n" +
- "createTime\x12]\n" +
- "\x18workload_identity_config\x18\x06 \x01(\v2#.bytebase.v1.WorkloadIdentityConfigR\x16workloadIdentityConfig:>\xeaA;\n" +
- "\x1dbytebase.com/WorkloadIdentity\x12\x1aworkloadIdentities/{email}\"\xd0\x02\n" +
- "\x16WorkloadIdentityConfig\x12U\n" +
- "\rprovider_type\x18\x01 \x01(\x0e20.bytebase.v1.WorkloadIdentityConfig.ProviderTypeR\fproviderType\x12\x1d\n" +
+ "createTime\x12b\n" +
+ "\x18workload_identity_config\x18\x06 \x01(\v2#.bytebase.v1.WorkloadIdentityConfigB\x03\xe0A\x02R\x16workloadIdentityConfig:>\xeaA;\n" +
+ "\x1dbytebase.com/WorkloadIdentity\x12\x1aworkloadIdentities/{email}\"\xe4\x02\n" +
+ "\x16WorkloadIdentityConfig\x12Z\n" +
+ "\rprovider_type\x18\x01 \x01(\x0e20.bytebase.v1.WorkloadIdentityConfig.ProviderTypeB\x03\xe0A\x02R\fproviderType\x12\"\n" +
"\n" +
- "issuer_url\x18\x02 \x01(\tR\tissuerUrl\x12+\n" +
- "\x11allowed_audiences\x18\x03 \x03(\tR\x10allowedAudiences\x12'\n" +
- "\x0fsubject_pattern\x18\x04 \x01(\tR\x0esubjectPattern\x12\x19\n" +
+ "issuer_url\x18\x02 \x01(\tB\x03\xe0A\x02R\tissuerUrl\x120\n" +
+ "\x11allowed_audiences\x18\x03 \x03(\tB\x03\xe0A\x02R\x10allowedAudiences\x12,\n" +
+ "\x0fsubject_pattern\x18\x04 \x01(\tB\x03\xe0A\x02R\x0esubjectPattern\x12\x19\n" +
"\bjwks_url\x18\x05 \x01(\tR\ajwksUrl\"O\n" +
"\fProviderType\x12\x1d\n" +
"\x19PROVIDER_TYPE_UNSPECIFIED\x10\x00\x12\n" +
diff --git a/backend/migrator/migration/3.23/0004##workload_identity_audiences.sql b/backend/migrator/migration/3.23/0004##workload_identity_audiences.sql
new file mode 100644
index 0000000000..3ac47922e2
--- /dev/null
+++ b/backend/migrator/migration/3.23/0004##workload_identity_audiences.sql
@@ -0,0 +1,80 @@
+-- Record the audiences that deployed pipelines already request, so that turning
+-- on audience validation does not break them.
+--
+-- Bytebase has shipped two audience conventions and stored neither. The
+-- in-product GitOps generator requests the literal "bytebase"; the docs tell
+-- operators to request the provider default. Which one a given pipeline sends
+-- is not recorded anywhere, so no single value is derivable from the row.
+-- allowed_audiences is repeated and matched any-of, so both are recorded.
+--
+-- "bytebase" is recorded for every repairable row, whatever the provider or the
+-- issuer, because it is what our own generator asks for and does not depend on
+-- either. The provider default is appended only where it can be derived: for
+-- GitHub that needs the public issuer, since GitHub Enterprise Server has its
+-- own; for GitLab it is the instance URL, which is the issuer.
+--
+-- Rows with no issuer never authenticated -- FetchJWKS rejects an empty URL --
+-- so there is nothing to preserve and they are left alone. Rows that already
+-- hold an audience are left alone too. An empty list is stored as a missing
+-- key: every writer serializes with protojson, which omits an empty repeated
+-- field, so that is the only shape the guard needs.
+--
+-- A pipeline requesting neither value stops authenticating: the audience it
+-- requests is recorded nowhere, so it cannot be preserved.
+--
+-- The GitHub arm is keyed on the row's own evidence, the issuer and the shape
+-- of the subject, not on provider_type: that enum is optional, nothing on the
+-- token path reads it, and identities created through the API often leave it
+-- unset. The GitLab arm accepts the enum as well as the subject shape, because
+-- a GitLab row's issuer is its instance URL whatever its subject looks like.
+--
+-- Soft-deleted rows are repaired too, so that undeleting one restores a working
+-- identity wherever an audience is derivable.
+--
+-- Repositories created after 2026-07-15 carry an immutable id on the owner
+-- segment ("repo:octocat@123456/...", GitHub changelog 2026-04-23); the
+-- audience names the owner alone.
+UPDATE workload_identity
+SET config = jsonb_set(
+ config,
+ '{allowedAudiences}',
+ to_jsonb(
+ ARRAY['bytebase'] || CASE
+ WHEN config->>'issuerUrl' = 'https://token.actions.githubusercontent.com'
+ AND split_part(substring(config->>'subjectPattern' FROM '^repo:([^/]+)/'), '@', 1) NOT IN ('', '*')
+ THEN ARRAY['https://github.com/' || split_part(substring(config->>'subjectPattern' FROM '^repo:([^/]+)/'), '@', 1)]
+
+ WHEN config->>'subjectPattern' LIKE 'project\_path:%'
+ OR config->>'providerType' = 'GITLAB'
+ THEN ARRAY[config->>'issuerUrl']
+
+ ELSE ARRAY[]::text[]
+ END
+ )
+ )
+WHERE config->'allowedAudiences' IS NULL
+ AND COALESCE(config->>'issuerUrl', '') <> '';
+
+-- Type the rows that never declared a provider.
+--
+-- provider_type was optional until this release, so identities written through
+-- the API carry no value. The subject's own prefix says which vocabulary the
+-- row uses, and it is the same evidence the audience arms above read, so the
+-- label can be settled once here instead of being inferred on every read.
+--
+-- Keyed on the subject prefix alone: the issuer is not evidence about the
+-- subject vocabulary, and a self-hosted GitLab or GitHub Enterprise row must
+-- be typed too. No `deleted` filter, matching the arms above, so undeleting a
+-- row cannot bring back an untyped one.
+--
+-- The values are the enum names as JSON strings, which is how protojson writes
+-- the field and how the GitLab arm above reads it.
+UPDATE workload_identity
+SET config = jsonb_set(config, '{providerType}', '"GITHUB"')
+WHERE config->'providerType' IS NULL
+ AND config->>'subjectPattern' LIKE 'repo:%';
+
+UPDATE workload_identity
+SET config = jsonb_set(config, '{providerType}', '"GITLAB"')
+WHERE config->'providerType' IS NULL
+ AND config->>'subjectPattern' LIKE 'project\_path:%';
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 74fd26e243..86c25d2a54 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -10,8 +10,8 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.23.3"), *files[len(files)-1].version)
- require.Equal(t, "migration/3.23/0003##identity_provider_list_permission.sql", files[len(files)-1].path)
+ require.Equal(t, semver.MustParse("3.23.4"), *files[len(files)-1].version)
+ require.Equal(t, "migration/3.23/0004##workload_identity_audiences.sql", files[len(files)-1].path)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/plugin/idp/wif/subject.go b/backend/plugin/idp/wif/subject.go
new file mode 100644
index 0000000000..8b51dd5b8b
--- /dev/null
+++ b/backend/plugin/idp/wif/subject.go
@@ -0,0 +1,57 @@
+package wif
+
+import (
+ "strings"
+
+ "github.com/pkg/errors"
+)
+
+// The subject vocabularies this package can reason about. GitHub writes
+// "repo:<owner>/<repo>:...", GitLab writes "project_path:<group>/<project>:...".
+const (
+ githubSubjectPrefix = "repo:"
+ gitlabSubjectPrefix = "project_path:"
+)
+
+// ValidateSubjectPattern refuses the patterns that match every subject the
+// issuer signs. The write paths call it so such a pattern cannot be stored,
+// and matchSubjectPattern calls it so one stored before this rule existed
+// still matches nothing.
+//
+// A trailing "*" is a prefix test, so a pattern addressing either vocabulary
+// must pin at least the owner segment: "repo:*", "repo:acme*" and "r*" all
+// admit every repository on GitHub.
+//
+// The rule reads the pattern only. provider_type is client-set and says
+// nothing about which subjects the issuer signs, so honoring it would let
+// "repo*" through on a row that merely claims not to be GitHub.
+func ValidateSubjectPattern(pattern string) error {
+ if strings.TrimSpace(pattern) == "" {
+ return errors.New("subject_pattern is required")
+ }
+ if !strings.HasSuffix(pattern, "*") {
+ return nil
+ }
+ prefix := strings.TrimSuffix(pattern, "*")
+ if prefix == "" {
+ return errors.New(`subject pattern "*" matches every subject from this issuer`)
+ }
+ // A prefix carrying "/" has named an owner or a group, which is what the
+ // rule asks for.
+ if strings.Contains(prefix, "/") {
+ return nil
+ }
+ for _, marker := range []string{githubSubjectPrefix, gitlabSubjectPrefix} {
+ // The pattern either spells a marker out, or stops part-way inside one
+ // ("r*", "project*") and so still addresses everything written with it.
+ if strings.HasPrefix(pattern, marker) || strings.HasPrefix(marker, prefix) {
+ return errors.Errorf(
+ "subject pattern %q matches every subject from this issuer; name an owner, as in \"repo:my-org/*\" or \"project_path:my-group/*\"",
+ pattern)
+ }
+ }
+ // issuer_url is free-form, so a wildcard outside both vocabularies is the
+ // operator's call: "system:serviceaccount:prod:*" on EKS names one
+ // namespace and carries no "/".
+ return nil
+}
diff --git a/backend/plugin/idp/wif/subject_test.go b/backend/plugin/idp/wif/subject_test.go
new file mode 100644
index 0000000000..6408652a03
--- /dev/null
+++ b/backend/plugin/idp/wif/subject_test.go
@@ -0,0 +1,236 @@
+package wif
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/rsa"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/go-jose/go-jose/v4"
+ "github.com/go-jose/go-jose/v4/jwt"
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+const testIssuer = "https://token.actions.githubusercontent.com"
+
+// seedIssuer registers a signing key for the test issuer in the JWKS cache and
+// returns it, which keeps ValidateToken off the network.
+func seedIssuer(t *testing.T) *rsa.PrivateKey {
+ t.Helper()
+ const issuerURL = testIssuer
+ key, err := rsa.GenerateKey(rand.Reader, 2048)
+ require.NoError(t, err)
+
+ jwks := &jose.JSONWebKeySet{Keys: []jose.JSONWebKey{
+ {Key: &key.PublicKey, KeyID: "test-key", Algorithm: "RS256", Use: "sig"},
+ }}
+ // Discovery mode (no jwks_url on the config) caches under the issuer key.
+ cacheKey := "issuer:" + issuerURL
+ jwksCacheLock.Lock()
+ jwksCache[cacheKey] = &cachedJWKS{jwks: jwks, fetchedAt: time.Now()}
+ jwksCacheLock.Unlock()
+
+ t.Cleanup(func() {
+ jwksCacheLock.Lock()
+ delete(jwksCache, cacheKey)
+ jwksCacheLock.Unlock()
+ })
+ return key
+}
+
+func signToken(t *testing.T, key *rsa.PrivateKey, subject, audience string) string {
+ t.Helper()
+ if audience == "" {
+ return signTokenWithAudience(t, key, subject, nil)
+ }
+ return signTokenWithAudience(t, key, subject, jwt.Audience{audience})
+}
+
+// signTokenWithAudience sets the aud claim verbatim, so a test can mint the
+// `"aud": ""` a legacy row with a blank entry used to match.
+func signTokenWithAudience(t *testing.T, key *rsa.PrivateKey, subject string, audience jwt.Audience) string {
+ t.Helper()
+ signer, err := jose.NewSigner(
+ jose.SigningKey{Algorithm: jose.RS256, Key: key},
+ (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", "test-key"))
+ require.NoError(t, err)
+
+ now := time.Now()
+ claims := jwt.Claims{
+ Issuer: testIssuer,
+ Subject: subject,
+ IssuedAt: jwt.NewNumericDate(now),
+ Expiry: jwt.NewNumericDate(now.Add(10 * time.Minute)),
+ }
+ claims.Audience = audience
+ token, err := jwt.Signed(signer).Claims(claims).Serialize()
+ require.NoError(t, err)
+ return token
+}
+
+func githubConfig() *storepb.WorkloadIdentityConfig {
+ return &storepb.WorkloadIdentityConfig{
+ ProviderType: storepb.WorkloadIdentityConfig_GITHUB,
+ IssuerUrl: testIssuer,
+ AllowedAudiences: []string{"bytebase"},
+ SubjectPattern: "repo:acme-corp/deploy:ref:refs/heads/main",
+ }
+}
+
+// TestValidateTokenFailsClosedOnUnbindableConfig is the regression for
+// BYT-10151, at the caller boundary rather than the helper: validateAudience
+// already returned false for an empty allowlist, and ValidateToken's own guard
+// short-circuited past it, so a helper-level test passed while the exchange
+// stayed open. Every token below is exchanged successfully before this change.
+func TestValidateTokenFailsClosedOnUnbindableConfig(t *testing.T) {
+ key := seedIssuer(t)
+ subject := "repo:acme-corp/deploy:ref:refs/heads/main"
+
+ tests := []struct {
+ name string
+ mutate func(*storepb.WorkloadIdentityConfig)
+ want string
+ }{
+ {"no audiences", func(c *storepb.WorkloadIdentityConfig) { c.AllowedAudiences = nil }, "audience mismatch"},
+ {"empty audience list", func(c *storepb.WorkloadIdentityConfig) { c.AllowedAudiences = []string{} }, "audience mismatch"},
+ // A row stored before the write paths refused blank entries: go-jose
+ // reads `"aud": ""` as one empty string, which used to match it.
+ {"blank audience entry", func(c *storepb.WorkloadIdentityConfig) { c.AllowedAudiences = []string{""} }, "audience mismatch"},
+ {"whitespace audience entry", func(c *storepb.WorkloadIdentityConfig) { c.AllowedAudiences = []string{" "} }, "audience mismatch"},
+ {"empty subject pattern", func(c *storepb.WorkloadIdentityConfig) { c.SubjectPattern = "" }, "subject mismatch"},
+ {"bare wildcard subject pattern", func(c *storepb.WorkloadIdentityConfig) { c.SubjectPattern = "*" }, "subject mismatch"},
+ // The migration gives these rows the requestable "bytebase" audience,
+ // so the subject is the only thing standing between a broad prefix and
+ // every workflow the issuer signs for.
+ {"wildcard over every repository", func(c *storepb.WorkloadIdentityConfig) { c.SubjectPattern = "repo:*" }, "subject mismatch"},
+ {"wildcard over a partial owner", func(c *storepb.WorkloadIdentityConfig) { c.SubjectPattern = "repo:acme*" }, "subject mismatch"},
+ {"wildcard inside the vocabulary marker", func(c *storepb.WorkloadIdentityConfig) { c.SubjectPattern = "r*" }, "subject mismatch"},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ config := githubConfig()
+ // A validly signed token from the configured issuer, matching both
+ // the subject and the audience the identity was meant to carry:
+ // everything except the configuration is correct.
+ signed := signToken(t, key, subject, "bytebase")
+ tc.mutate(config)
+ if len(config.AllowedAudiences) == 1 && strings.TrimSpace(config.AllowedAudiences[0]) == "" {
+ // The token has to carry the same blank audience for the row to
+ // have matched before this change.
+ signed = signTokenWithAudience(t, key, subject,
+ jwt.Audience{config.AllowedAudiences[0]})
+ }
+
+ _, err := ValidateToken(context.Background(), signed, config)
+ require.ErrorContains(t, err, tc.want)
+ })
+ }
+}
+
+// TestValidateTokenAudienceBinding is the control: a complete configuration
+// accepts only the audience it names.
+func TestValidateTokenAudienceBinding(t *testing.T) {
+ key := seedIssuer(t)
+ config := githubConfig()
+ config.AllowedAudiences = []string{"https://bytebase.acme.com/workloadIdentities/ci"}
+ subject := "repo:acme-corp/deploy:ref:refs/heads/main"
+
+ claims, err := ValidateToken(context.Background(),
+ signToken(t, key, subject, config.AllowedAudiences[0]), config)
+ require.NoError(t, err)
+ require.Equal(t, subject, claims.Subject)
+
+ for _, wrong := range []string{
+ "https://some-other-saas.example.com", // minted for another vendor
+ "sts.amazonaws.com",
+ "bytebase", // what the in-product generator requests
+ "https://github.com/acme-corp", // GitHub's default audience
+ } {
+ _, err := ValidateToken(context.Background(), signToken(t, key, subject, wrong), config)
+ require.ErrorContains(t, err, "audience mismatch", "audience %q must not authenticate", wrong)
+ }
+}
+
+// TestValidateTokenRefusesLegacyPartialMarker is the exchange-level regression
+// for the population this PR is about: a row written before provider_type was
+// required, bound with a wildcard that stops inside GitHub's subject marker.
+// The migration hands such a row the literal "bytebase", which any GitHub
+// workflow can request, so the subject is the only thing standing between it
+// and every repository the issuer signs for.
+func TestValidateTokenRefusesLegacyPartialMarker(t *testing.T) {
+ key := seedIssuer(t)
+
+ // The rule reads the pattern, not the row's label, so the provider it
+ // claims makes no difference to any of these.
+ for _, pattern := range []string{"r*", "repo*", "repo:*", "repo:acme*"} {
+ config := githubConfig()
+ config.ProviderType = storepb.WorkloadIdentityConfig_PROVIDER_TYPE_UNSPECIFIED
+ config.SubjectPattern = pattern
+
+ _, err := ValidateToken(context.Background(),
+ signToken(t, key, "repo:attacker-org/evil:ref:refs/heads/main", "bytebase"),
+ config)
+ require.ErrorContains(t, err, "subject mismatch", "pattern=%q", pattern)
+ }
+}
+
+// TestValidateTokenUnspecifiedProviderStillBinds pins the upgrade path for
+// identities stored before provider_type was required. Nothing on the token
+// path reads that field, so a configuration that is otherwise bound keeps
+// working.
+func TestValidateTokenUnspecifiedProviderStillBinds(t *testing.T) {
+ key := seedIssuer(t)
+ config := githubConfig()
+ config.ProviderType = storepb.WorkloadIdentityConfig_PROVIDER_TYPE_UNSPECIFIED
+ subject := "repo:acme-corp/deploy:ref:refs/heads/main"
+
+ claims, err := ValidateToken(context.Background(), signToken(t, key, subject, "bytebase"), config)
+ require.NoError(t, err)
+ require.Equal(t, subject, claims.Subject)
+}
+
+func TestValidateSubjectPattern(t *testing.T) {
+ accepted := []string{
+ "repo:acme-corp/deploy:ref:refs/heads/main",
+ "repo:acme-corp/*",
+ "repo:acme-corp/deploy:*",
+ "project_path:grp/*",
+ "project_path:grp/proj:ref_type:branch:ref:main",
+ // issuer_url is free-form, so a wildcard outside the two vocabularies
+ // we model is the operator's call.
+ "system:serviceaccount:prod:*",
+ "organization:acme:project:prod:workspace:db-prod:*",
+ "svc-bytebase-*",
+ }
+ for _, pattern := range accepted {
+ require.NoError(t, ValidateSubjectPattern(pattern), "pattern=%q", pattern)
+ }
+
+ rejected := []string{
+ "",
+ " ",
+ "*",
+ // Spells a marker out.
+ "repo:*",
+ "repo:acme*",
+ "project_path:*",
+ "project_path:grp*",
+ // Stops part-way inside one, so it still addresses everything written
+ // with that marker.
+ "r*",
+ "repo*",
+ "p*",
+ "project*",
+ "project_path*",
+ }
+ for _, pattern := range rejected {
+ require.Error(t, ValidateSubjectPattern(pattern), "pattern=%q", pattern)
+ }
+ require.ErrorContains(t, ValidateSubjectPattern(""), "subject_pattern is required")
+ require.ErrorContains(t, ValidateSubjectPattern("repo*"), "matches every subject")
+}
diff --git a/backend/plugin/idp/wif/wif.go b/backend/plugin/idp/wif/wif.go
index d81ee04159..60e4c9297c 100644
--- a/backend/plugin/idp/wif/wif.go
+++ b/backend/plugin/idp/wif/wif.go
@@ -59,8 +59,8 @@ func ValidateToken(ctx context.Context, tokenString string, config *storepb.Work
return nil, errors.Errorf("issuer mismatch: expected %q, got %q", config.IssuerUrl, claims.Issuer)
}
- // Validate audience (skip if no allowed audiences configured)
- if len(config.AllowedAudiences) > 0 && !validateAudience(claims.Audience, config.AllowedAudiences) {
+ // Validate audience
+ if !validateAudience(claims.Audience, config.AllowedAudiences) {
return nil, errors.Errorf("audience mismatch: token has %v, allowed %v", claims.Audience, config.AllowedAudiences)
}
@@ -79,6 +79,12 @@ func ValidateToken(ctx context.Context, tokenString string, config *storepb.Work
func validateAudience(tokenAudience []string, allowedAudiences []string) bool {
for _, allowed := range allowedAudiences {
+ // A blank entry is not a binding. The write paths refuse one, but a row
+ // stored before they did still holds it, and go-jose reads a token's
+ // `"aud": ""` as one empty string, which would match it.
+ if strings.TrimSpace(allowed) == "" {
+ continue
+ }
for _, aud := range tokenAudience {
if aud == allowed {
return true
@@ -89,9 +95,11 @@ func validateAudience(tokenAudience []string, allowedAudiences []string) bool {
}
func matchSubjectPattern(subject, pattern string) bool {
- // Simple pattern matching - exact match or wildcard suffix
- if pattern == "" {
- return true
+ // The write-time rule is the read-time rule: a pattern the write paths
+ // would refuse matches nothing, so a row stored before that rule existed
+ // fails closed instead of admitting every subject behind a broad prefix.
+ if ValidateSubjectPattern(pattern) != nil {
+ return false
}
if strings.HasSuffix(pattern, "*") {
prefix := strings.TrimSuffix(pattern, "*")
diff --git a/backend/plugin/idp/wif/wif_test.go b/backend/plugin/idp/wif/wif_test.go
index 1c91ede61e..bf2bfc1d7d 100644
--- a/backend/plugin/idp/wif/wif_test.go
+++ b/backend/plugin/idp/wif/wif_test.go
@@ -14,9 +14,44 @@ func TestMatchSubjectPattern(t *testing.T) {
expected bool
}{
{
- name: "empty pattern matches any subject",
+ name: "empty pattern matches nothing",
subject: "repo:owner/repo:ref:refs/heads/main",
pattern: "",
+ expected: false,
+ },
+ {
+ name: "bare wildcard matches nothing",
+ subject: "repo:owner/repo:ref:refs/heads/main",
+ pattern: "*",
+ expected: false,
+ },
+ {
+ // A trailing "*" is a prefix test, so "repo:*" is every repository
+ // on the issuer: the same hole as "*", refused the same way.
+ name: "wildcard over every repository matches nothing",
+ subject: "repo:owner/repo:ref:refs/heads/main",
+ pattern: "repo:*",
+ expected: false,
+ },
+ {
+ name: "wildcard over a partial owner matches nothing",
+ subject: "repo:owner/repo:ref:refs/heads/main",
+ pattern: "repo:own*",
+ expected: false,
+ },
+ {
+ // "r*" stops inside "repo:", so it addresses every repository the
+ // issuer signs whatever the row calls itself.
+ name: "wildcard inside the marker matches nothing",
+ subject: "repo:owner/repo:ref:refs/heads/main",
+ pattern: "r*",
+ expected: false,
+ },
+ {
+ // Not a modelled vocabulary, so the owner rule does not apply.
+ name: "custom issuer wildcard still matches by prefix",
+ subject: "system:serviceaccount:prod:deployer",
+ pattern: "system:serviceaccount:prod:*",
expected: true,
},
{
diff --git a/backend/store/migration_3_23_4_test.go b/backend/store/migration_3_23_4_test.go
new file mode 100644
index 0000000000..1f5d8bb831
--- /dev/null
+++ b/backend/store/migration_3_23_4_test.go
@@ -0,0 +1,184 @@
+package store_test
+
+import (
+ "context"
+ "os"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+func TestMigration3_23_4_WorkloadIdentityAudiences(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ db, _, _ := testcontainer.NewMetadataDB(t)
+
+ // workload_identity.workspace is a foreign key, and the template carries the
+ // real table, so the row the fixtures reference has to exist first.
+ _, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws')`)
+ require.NoError(t, err)
+
+ const ghIssuer = "https://token.actions.githubusercontent.com"
+ tests := []struct {
+ email string
+ deleted bool
+ config *storepb.WorkloadIdentityConfig
+ expected []string // nil means the row must be left alone
+ // The provider the backfill types the row with, for rows stored
+ // without one. Zero value means it stays untyped.
+ expectedProvider storepb.WorkloadIdentityConfig_ProviderType
+ }{
+ {
+ email: "legacy-github",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, IssuerUrl: ghIssuer, SubjectPattern: "repo:acme-corp/*"},
+ expected: []string{"bytebase", "https://github.com/acme-corp"},
+ },
+ {
+ // Repositories created after 2026-07-15 carry an immutable id on
+ // each segment; the audience names the owner alone.
+ email: "immutable-subject",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, IssuerUrl: ghIssuer, SubjectPattern: "repo:acme-corp@123456/deploy@789:ref:refs/heads/main"},
+ expected: []string{"bytebase", "https://github.com/acme-corp"},
+ },
+ {
+ // GitHub Enterprise Server has its own issuer and its own default
+ // audience, so github.com would be the wrong guess. The literal is
+ // not a guess: our generator requests it on every provider.
+ email: "enterprise-server",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, IssuerUrl: "https://ghes.acme.com", SubjectPattern: "repo:acme-corp/*"},
+ expected: []string{"bytebase"},
+ },
+ {
+ email: "gitlab",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITLAB, IssuerUrl: "https://gitlab.acme.com", SubjectPattern: "project_path:grp/*"},
+ expected: []string{"bytebase", "https://gitlab.acme.com"},
+ },
+ {
+ email: "empty-subject",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, IssuerUrl: ghIssuer},
+ expected: []string{"bytebase"},
+ },
+ {
+ email: "bare-wildcard-subject",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, IssuerUrl: ghIssuer, SubjectPattern: "*"},
+ expected: []string{"bytebase"},
+ },
+ {
+ email: "wildcard-owner",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, IssuerUrl: ghIssuer, SubjectPattern: "repo:*/deploy:ref:refs/heads/main"},
+ expected: []string{"bytebase"},
+ },
+ {
+ // provider_type is optional and nothing on the token path reads it,
+ // so identities created through the API often omit it. protojson
+ // drops the zero enum, leaving no key at all. These rows are still
+ // repairable from the issuer and the subject.
+ email: "unspecified-provider-github",
+ expectedProvider: storepb.WorkloadIdentityConfig_GITHUB,
+ config: &storepb.WorkloadIdentityConfig{IssuerUrl: ghIssuer, SubjectPattern: "repo:acme-corp/*"},
+ expected: []string{"bytebase", "https://github.com/acme-corp"},
+ },
+ {
+ email: "unspecified-provider-gitlab",
+ expectedProvider: storepb.WorkloadIdentityConfig_GITLAB,
+ config: &storepb.WorkloadIdentityConfig{IssuerUrl: "https://gitlab.acme.com", SubjectPattern: "project_path:grp/*"},
+ expected: []string{"bytebase", "https://gitlab.acme.com"},
+ },
+ {
+ // No provider and an unreadable subject: the provider default
+ // cannot be derived, but the literal still applies.
+ email: "unspecified-provider-unreadable",
+ config: &storepb.WorkloadIdentityConfig{IssuerUrl: ghIssuer, SubjectPattern: "custom:whatever"},
+ expected: []string{"bytebase"},
+ },
+ {
+ // A GitLab row whose subject is not in the project_path shape: the
+ // enum alone earns the instance URL, because a GitLab issuer is its
+ // instance URL whatever the subject looks like.
+ email: "gitlab-enum-only",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITLAB, IssuerUrl: "https://gitlab.acme.com", SubjectPattern: "custom:deployer"},
+ expected: []string{"bytebase", "https://gitlab.acme.com"},
+ },
+ {
+ // A row declaring GITLAB whose issuer is GitHub's: the first arm
+ // reads the evidence and the enum does not override it.
+ email: "mislabeled-provider",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITLAB, IssuerUrl: ghIssuer, SubjectPattern: "repo:acme-corp/*"},
+ expected: []string{"bytebase", "https://github.com/acme-corp"},
+ },
+ {
+ // The Terraform tutorial's shape: accepted at write time, never able
+ // to authenticate.
+ email: "no-issuer",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, SubjectPattern: "repo:acme-corp/deploy:ref:refs/heads/main"},
+ },
+ {
+ // A GitLab identity whose stored enum says GITHUB. The arms key on
+ // the subject's shape, so it still gets the instance URL.
+ email: "gitlab-mislabeled-github",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, IssuerUrl: "https://gitlab.acme.com", SubjectPattern: "project_path:grp/*"},
+ expected: []string{"bytebase", "https://gitlab.acme.com"},
+ },
+ {
+ email: "already-bound",
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, IssuerUrl: ghIssuer, SubjectPattern: "repo:acme-corp/*", AllowedAudiences: []string{"https://bytebase.acme.com/workloadIdentities/[email protected]"}},
+ expected: []string{"https://bytebase.acme.com/workloadIdentities/[email protected]"},
+ },
+ {
+ // Undeleting a row must not resurrect an identity that can no
+ // longer authenticate.
+ email: "soft-deleted",
+ deleted: true,
+ config: &storepb.WorkloadIdentityConfig{ProviderType: storepb.WorkloadIdentityConfig_GITHUB, IssuerUrl: ghIssuer, SubjectPattern: "repo:acme-corp/*"},
+ expected: []string{"bytebase", "https://github.com/acme-corp"},
+ },
+ }
+
+ for _, tc := range tests {
+ // Seeded through the real serializer, so the test exercises the key
+ // names the store actually writes rather than repeating a guess.
+ payload, err := protojson.Marshal(tc.config)
+ require.NoError(t, err)
+ _, err = db.ExecContext(ctx,
+ `INSERT INTO workload_identity (name, email, workspace, deleted, config) VALUES ($1, $1, 'ws', $2, $3)`,
+ tc.email, tc.deleted, string(payload))
+ require.NoError(t, err)
+ }
+
+ statement, err := os.ReadFile("../migrator/migration/3.23/0004##workload_identity_audiences.sql")
+ require.NoError(t, err)
+ // Applied twice: the migration must be idempotent, because its own guard
+ // (a missing audience list) is what stops it re-running.
+ for range 2 {
+ _, err = db.ExecContext(ctx, string(statement))
+ require.NoError(t, err)
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.email, func(t *testing.T) {
+ t.Parallel()
+ var raw string
+ require.NoError(t, db.QueryRowContext(ctx,
+ `SELECT config FROM workload_identity WHERE email = $1`, tc.email).Scan(&raw))
+ var got storepb.WorkloadIdentityConfig
+ require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal([]byte(raw), &got))
+ require.Equal(t, tc.expected, got.AllowedAudiences)
+ if tc.config.ProviderType == storepb.WorkloadIdentityConfig_PROVIDER_TYPE_UNSPECIFIED {
+ // "unspecified-provider-unreadable" names no vocabulary, so it
+ // stays untyped and the zero value is the assertion.
+ require.Equal(t, tc.expectedProvider, got.ProviderType)
+ } else {
+ // A declared provider is evidence the operator supplied; the
+ // backfill keys on an absent one and must not overwrite it,
+ // including "gitlab-mislabeled-github", whose subject prefix
+ // disagrees with its label.
+ require.Equal(t, tc.config.ProviderType, got.ProviderType)
+ }
+ })
+ }
+}
diff --git a/backend/tests/login_audit_test.go b/backend/tests/login_audit_test.go
index 74cb2c0afc..c6e03a851c 100644
--- a/backend/tests/login_audit_test.go
+++ b/backend/tests/login_audit_test.go
@@ -644,6 +644,7 @@ func TestAuditLogFormat(t *testing.T) {
Title: "Audit reset workload identity",
WorkloadIdentityConfig: &v1pb.WorkloadIdentityConfig{
ProviderType: v1pb.WorkloadIdentityConfig_GITHUB,
+ IssuerUrl: "https://token.actions.githubusercontent.com",
AllowedAudiences: []string{"audit-reset"},
SubjectPattern: "repo:bytebase/bytebase:*",
},
diff --git a/frontend/src/components/CreateWorkloadIdentitySheet.test.tsx b/frontend/src/components/CreateWorkloadIdentitySheet.test.tsx
index 452fbfd7e6..237245b42e 100644
--- a/frontend/src/components/CreateWorkloadIdentitySheet.test.tsx
+++ b/frontend/src/components/CreateWorkloadIdentitySheet.test.tsx
@@ -1,4 +1,5 @@
import { create } from "@bufbuild/protobuf";
+import { Code, ConnectError } from "@connectrpc/connect";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, test, vi } from "vitest";
@@ -170,7 +171,7 @@ describe("CreateWorkloadIdentitySheet", () => {
});
});
- test("omits the blank preset audience when creating a GitHub identity", async () => {
+ test("presets the generated-workflow audience when creating a GitHub identity", async () => {
const created = create(WorkloadIdentitySchema, {
name: "workloadIdentities/[email protected]",
@@ -230,9 +231,12 @@ describe("CreateWorkloadIdentitySheet", () => {
expect(mocks.store.createWorkloadIdentity).toHaveBeenCalledOnce();
const [, workloadIdentity] =
mocks.store.createWorkloadIdentity.mock.calls[0];
+ // BYT-10151: this shipped as [] and the exchange skipped the audience
+ // check when the list was empty, so the identity accepted a token minted
+ // for anyone. The preset is what the generated workflows request.
expect(
workloadIdentity.workloadIdentityConfig?.allowedAudiences
- ).toEqual([]);
+ ).toEqual(["bytebase"]);
act(() => {
root.unmount();
@@ -621,39 +625,6 @@ describe("CreateWorkloadIdentitySheet", () => {
act(() => root.unmount());
});
- test("opens an identity that never declared a provider", async () => {
- const identity = editableIdentity(
- WorkloadIdentityConfig_ProviderType.PROVIDER_TYPE_UNSPECIFIED,
- "repo:acme-corp/deploy:ref:refs/heads/main"
- );
- mocks.store.updateWorkloadIdentity.mockResolvedValue(identity);
- const { container, root } = renderSheet(identity);
-
- // The subject names the provider, so the fields parse and the form is
- // usable; reading the stored enum leaves owner empty and Update dead.
- expect(
- inputFor(container, "settings.members.workload-identity-owner").value
- ).toBe("acme-corp");
-
- type(inputFor(container, "common.name"), "CI deploy renamed");
- const update = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent === "common.update"
- );
- expect(update?.hasAttribute("disabled")).toBe(false);
- await act(async () => {
- update?.click();
- });
-
- const sent =
- mocks.store.updateWorkloadIdentity.mock.calls[0]?.[0]
- ?.workloadIdentityConfig;
- expect(sent?.subjectPattern).toBe("repo:acme-corp/deploy:ref:refs/heads/main");
- // provider_type is required on write now, so the save must name one.
- expect(sent?.providerType).toBe(WorkloadIdentityConfig_ProviderType.GITHUB);
-
- act(() => root.unmount());
- });
-
test("recomputes the subject pattern from every derived control", () => {
const { container, root } = renderSheet(
editableIdentity(
@@ -676,4 +647,111 @@ describe("CreateWorkloadIdentitySheet", () => {
act(() => root.unmount());
});
+
+ const audienceField = (container: HTMLElement) =>
+ Array.from(container.querySelectorAll('[data-slot="form-field"]')).find(
+ (field) =>
+ field.textContent?.includes("settings.members.workload-identity-audience")
+ );
+
+ const audienceInput = (container: HTMLElement) =>
+ audienceField(container)?.querySelector("input") as HTMLInputElement;
+
+ test("shows the audience field without opening Advanced Settings", () => {
+ const { container, root } = renderSheet();
+
+ // A required field the operator cannot see leaves Create disabled with
+ // nothing on screen to explain why.
+ expect(audienceInput(container)).toBeTruthy();
+ expect(audienceInput(container).value).toBe("bytebase");
+ expect(audienceField(container)?.textContent).toContain("*");
+
+ act(() => root.unmount());
+ });
+
+ test("blocks a save with no audience", () => {
+ const identity = editableIdentity(
+ WorkloadIdentityConfig_ProviderType.GITHUB,
+ "repo:acme-corp/deploy:ref:refs/heads/main"
+ );
+ const { container, root } = renderSheet(identity);
+ const update = () =>
+ Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "common.update"
+ );
+
+ type(audienceInput(container), " ");
+ expect(update()?.hasAttribute("disabled")).toBe(true);
+
+ type(audienceInput(container), "https://bytebase.acme.com/wi/ci");
+ expect(update()?.hasAttribute("disabled")).toBe(false);
+
+ act(() => root.unmount());
+ });
+
+ // An identity whose audience list is empty, which an older replica can still
+ // write after the backfill has run. Prefilling would make the form look
+ // unchanged, so Update would stay disabled and the row could never be
+ // repaired.
+ test("does not prefill an audience the identity does not hold", () => {
+ const unrepaired = create(WorkloadIdentitySchema, {
+ name: "workloadIdentities/[email protected]",
+ email: "[email protected]",
+ title: "GHES deploy",
+ workloadIdentityConfig: create(WorkloadIdentityConfigSchema, {
+ providerType: WorkloadIdentityConfig_ProviderType.GITHUB,
+ issuerUrl: "https://ghes.acme.com",
+ allowedAudiences: [],
+ subjectPattern: "repo:acme-corp/deploy:ref:refs/heads/main",
+ }),
+ });
+ const { container, root } = renderSheet(unrepaired);
+
+ expect(audienceInput(container).value).toBe("");
+ type(audienceInput(container), "https://ghes.acme.com/oidc");
+ expect(
+ Array.from(container.querySelectorAll("button"))
+ .find((button) => button.textContent === "common.update")
+ ?.hasAttribute("disabled")
+ ).toBe(false);
+
+ act(() => root.unmount());
+ });
+
+ // validateWorkloadIdentityConfig owns the configuration rules; the form does
+ // not restate them. What it owes the operator is the server's reason, beside
+ // the fields, with Advanced open so the field the reason names is visible.
+ test("shows the server's rejection beside the fields", async () => {
+ const identity = editableIdentity(
+ WorkloadIdentityConfig_ProviderType.GITHUB,
+ "repo:acme-corp/deploy:ref:refs/heads/main"
+ );
+ const { container, root } = renderSheet(identity);
+ mocks.store.updateWorkloadIdentity.mockRejectedValueOnce(
+ new ConnectError(
+ 'subject pattern "repo:acme*" matches every repository from this issuer',
+ Code.InvalidArgument
+ )
+ );
+ expect(container.textContent).not.toContain(
+ "settings.members.workload-identity-subject"
+ );
+
+ type(audienceInput(container), "bytebase-prod");
+ const update = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "common.update"
+ );
+ await act(async () => {
+ update?.click();
+ });
+
+ expect(
+ container.querySelector('[data-slot="form-error"]')?.textContent
+ ).toContain("matches every repository");
+ expect(container.textContent).toContain(
+ "settings.members.workload-identity-subject"
+ );
+
+ act(() => root.unmount());
+ });
});
diff --git a/frontend/src/components/CreateWorkloadIdentitySheet.tsx b/frontend/src/components/CreateWorkloadIdentitySheet.tsx
index 432ad291b9..bb1cd67505 100644
--- a/frontend/src/components/CreateWorkloadIdentitySheet.tsx
+++ b/frontend/src/components/CreateWorkloadIdentitySheet.tsx
@@ -1,11 +1,12 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import { Code, ConnectError } from "@connectrpc/connect";
import { ChevronDown, ChevronUp, PlusIcon, XIcon } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { RoleSelect } from "@/components/RoleSelect";
import { Button } from "@/components/ui/button";
-import { FormField } from "@/components/ui/form";
+import { FormError, FormField } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
Select,
@@ -39,11 +40,11 @@ import {
WorkloadIdentitySchema,
} from "@/types/proto-es/v1/workload_identity_service_pb";
import {
+ GENERATED_WORKFLOW_AUDIENCE,
getWorkloadIdentityProviderText,
hasProjectPermissionV2,
hasWorkspacePermissionV2,
parseWorkloadIdentitySubjectPattern,
- resolveWorkloadIdentityProviderType,
} from "@/utils";
type RefType = "branch" | "tag" | "all";
@@ -56,11 +57,11 @@ const PLATFORM_PRESETS: Partial<
> = {
[WorkloadIdentityConfig_ProviderType.GITHUB]: {
issuerUrl: "https://token.actions.githubusercontent.com",
- audience: "",
+ audience: GENERATED_WORKFLOW_AUDIENCE,
},
[WorkloadIdentityConfig_ProviderType.GITLAB]: {
issuerUrl: "https://gitlab.com",
- audience: "",
+ audience: GENERATED_WORKFLOW_AUDIENCE,
},
};
@@ -171,13 +172,19 @@ function WorkloadIdentityForm({
: undefined,
[]
);
- // Resolved, not read raw: an identity written before provider_type was
- // required may carry PROVIDER_TYPE_UNSPECIFIED, which names no platform and
- // parses no subject.
+ // PROVIDER_TYPE_UNSPECIFIED names no platform, so the form has no tab to
+ // open on. Migration 3.23.4 types the rows whose subject prefix says which
+ // vocabulary they use; a row whose subject says neither, and a row an older
+ // replica writes after that backfill, still arrive untyped. Both open on the
+ // GitHub tab, and picking the platform types them on save.
+ const storedProviderType =
+ workloadIdentity?.workloadIdentityConfig?.providerType;
const initialProviderType =
- resolveWorkloadIdentityProviderType(
- workloadIdentity?.workloadIdentityConfig
- ) ?? WorkloadIdentityConfig_ProviderType.GITHUB;
+ storedProviderType === undefined ||
+ storedProviderType ===
+ WorkloadIdentityConfig_ProviderType.PROVIDER_TYPE_UNSPECIFIED
+ ? WorkloadIdentityConfig_ProviderType.GITHUB
+ : storedProviderType;
const initialIssuerUrl =
workloadIdentity?.workloadIdentityConfig?.issuerUrl ??
PLATFORM_PRESETS[initialProviderType]?.issuerUrl ??
@@ -185,7 +192,16 @@ function WorkloadIdentityForm({
const initialAudiences = useMemo(() => {
const audiences =
workloadIdentity?.workloadIdentityConfig?.allowedAudiences;
- return audiences?.length ? [...audiences] : [""];
+ if (audiences?.length) return [...audiences];
+ // A new identity gets the audience the generated workflows request. A
+ // stored one the migration could not repair stays visibly empty: prefilling
+ // it would make the form look unchanged, leaving Update disabled and the
+ // operator unable to set the real value.
+ return [
+ workloadIdentity
+ ? ""
+ : (PLATFORM_PRESETS[initialProviderType]?.audience ?? ""),
+ ];
}, []);
const initialJwksUrl =
workloadIdentity?.workloadIdentityConfig?.jwksUrl ?? "";
@@ -228,6 +244,7 @@ function WorkloadIdentityForm({
const [showAdvanced, setShowAdvanced] = useState(false);
const [roles, setRoles] = useState<string[]>([]);
const [isRequesting, setIsRequesting] = useState(false);
+ const [serverError, setServerError] = useState<string>();
const isGenericOIDC =
providerType === WorkloadIdentityConfig_ProviderType.OIDC;
@@ -278,6 +295,13 @@ function WorkloadIdentityForm({
};
const handlePlatformChange = (value: WorkloadIdentityConfig_ProviderType) => {
+ // Re-selecting the platform already shown changes nothing, and the reset
+ // below would drop the provider-default audience migration 3.23.4 records
+ // alongside "bytebase". A real change makes that value stale, so only a
+ // real change resets it.
+ if (value === providerType) {
+ return;
+ }
const preset = PLATFORM_PRESETS[value];
if (preset) {
setIssuerUrl(preset.issuerUrl);
@@ -296,18 +320,17 @@ function WorkloadIdentityForm({
setBranch("");
};
+ // Required-ness only, for every provider: the exchange refuses an identity
+ // with no audience or no subject whatever minted its tokens, so the form
+ // must not offer to save one. The configuration rules themselves live in
+ // validateWorkloadIdentityConfig, and its rejection is rendered below.
const isFormValid = useMemo(() => {
if (!emailPrefix && !workloadIdentity?.email) return false;
- if (isGenericOIDC) {
- return (
- !!issuerUrl.trim() &&
- audiences.length > 0 &&
- audiences.every((audience) => !!audience.trim()) &&
- !!subjectPattern.trim()
- );
- }
- if (!owner) return false;
- if (!issuerUrl) return false;
+ if (!issuerUrl.trim()) return false;
+ if (!audiences.length) return false;
+ if (!audiences.every((audience) => audience.trim())) return false;
+ if (!subjectPattern.trim()) return false;
+ if (!isGenericOIDC && !owner) return false;
return true;
}, [
emailPrefix,
@@ -371,14 +394,21 @@ function WorkloadIdentityForm({
const handleSubmit = async () => {
if (!allowConfirm || !hasPermission) return;
setIsRequesting(true);
+ setServerError(undefined);
try {
if (isEditMode) {
await handleUpdate();
} else {
await handleCreate();
}
- } catch {
- // error shown by store
+ } catch (err) {
+ // A rejected configuration is shown beside the fields, not only as the
+ // toast every failed call gets. The message names the field, which for a
+ // GitHub or GitLab identity is under Advanced Settings.
+ if (err instanceof ConnectError && err.code === Code.InvalidArgument) {
+ setServerError(err.rawMessage);
+ setShowAdvanced(true);
+ }
} finally {
setIsRequesting(false);
}
@@ -767,6 +797,23 @@ function WorkloadIdentityForm({
</FormField>
)}
+ {/* Audience */}
+ {!isGenericOIDC && (
+ <FormField
+ title={
+ <>
+ {t("settings.members.workload-identity-audience")}
+ <span className="ml-0.5 text-error">*</span>
+ </>
+ }
+ description={
+ <>{t("settings.members.workload-identity-audience-hint")}</>
+ }
+ >
+ {audienceInputs}
+ </FormField>
+ )}
+
{isGenericOIDC && (
<>
<FormField
@@ -849,16 +896,14 @@ function WorkloadIdentityForm({
/>
</FormField>
- {/* Audience */}
- <FormField
- title={<>{t("settings.members.workload-identity-audience")}</>}
- >
- {audienceInputs}
- </FormField>
-
{/* Subject Pattern */}
<FormField
- title={<>{t("settings.members.workload-identity-subject")}</>}
+ title={
+ <>
+ {t("settings.members.workload-identity-subject")}
+ <span className="ml-0.5 text-error">*</span>
+ </>
+ }
>
<Input
value={subjectPattern}
@@ -870,6 +915,13 @@ function WorkloadIdentityForm({
</div>
)}
+ {serverError && (
+ <FormError>
+ {t("settings.members.workload-identity-config-rejected")}{" "}
+ {serverError}
+ </FormError>
+ )}
+
{/* Advanced Settings Toggle */}
{!isGenericOIDC && (
<button
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index c1c8ba0169..fe05ea4f28 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2769,8 +2769,10 @@
"workload-identity-all-branches-tags": "All branches and tags",
"workload-identity-allowed-branches-tags": "Allowed Branches/Tags",
"workload-identity-audience": "Audience",
+ "workload-identity-audience-hint": "The audience your pipeline requests. Bytebase's generated workflows request bytebase; the setup guides request the provider default, so add that line too if your pipeline uses it.",
"workload-identity-branch": "Branch",
"workload-identity-branch-hint": "Leave empty for all branches",
+ "workload-identity-config-rejected": "Bytebase cannot accept this configuration:",
"workload-identity-generic-oidc": "Generic OIDC",
"workload-identity-gitlab-url": "GitLab URL",
"workload-identity-gitlab-url-hint": "Your GitLab instance URL",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 548f994540..4a57edcdd8 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2769,8 +2769,10 @@
"workload-identity-all-branches-tags": "Todas las ramas y etiquetas",
"workload-identity-allowed-branches-tags": "Ramas/etiquetas permitidas",
"workload-identity-audience": "Audiencia",
+ "workload-identity-audience-hint": "La audiencia que solicita tu pipeline. Los flujos de trabajo generados por Bytebase solicitan bytebase; las guías de configuración solicitan el valor predeterminado del proveedor, así que añade también esa línea si tu pipeline lo usa.",
"workload-identity-branch": "Rama",
"workload-identity-branch-hint": "Dejar vacío para todas las ramas",
+ "workload-identity-config-rejected": "Bytebase no puede aceptar esta configuración:",
"workload-identity-generic-oidc": "OIDC genérico",
"workload-identity-gitlab-url": "GitLab URL",
"workload-identity-gitlab-url-hint": "La URL de su instancia de GitLab",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 7b6effd49a..bd94f7e281 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2769,8 +2769,10 @@
"workload-identity-all-branches-tags": "すべてのブランチとタグ",
"workload-identity-allowed-branches-tags": "許可するブランチ/タグ",
"workload-identity-audience": "Audience",
+ "workload-identity-audience-hint": "パイプラインが要求する audience。Bytebase が生成するワークフローは bytebase を要求します。セットアップガイドはプロバイダーの既定値を要求するため、パイプラインがそちらを使う場合は行を追加してください。",
"workload-identity-branch": "ブランチ",
"workload-identity-branch-hint": "すべてのブランチを対象とする場合は空欄にしてください",
+ "workload-identity-config-rejected": "Bytebase はこの設定を受け付けられません:",
"workload-identity-generic-oidc": "汎用 OIDC",
"workload-identity-gitlab-url": "GitLab URL",
"workload-identity-gitlab-url-hint": "GitLab インスタンスの URL",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index be769026b0..8b153f580d 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2769,8 +2769,10 @@
"workload-identity-all-branches-tags": "Tất cả branch và tag",
"workload-identity-allowed-branches-tags": "Branch/Tag được phép",
"workload-identity-audience": "Audience",
+ "workload-identity-audience-hint": "Audience mà pipeline của bạn yêu cầu. Các workflow do Bytebase tạo yêu cầu bytebase; hướng dẫn thiết lập yêu cầu giá trị mặc định của nhà cung cấp, vì vậy hãy thêm dòng đó nếu pipeline của bạn dùng nó.",
"workload-identity-branch": "Branch",
"workload-identity-branch-hint": "Để trống cho tất cả branch",
+ "workload-identity-config-rejected": "Bytebase không thể chấp nhận cấu hình này:",
"workload-identity-generic-oidc": "OIDC chung",
"workload-identity-gitlab-url": "GitLab URL",
"workload-identity-gitlab-url-hint": "URL phiên bản GitLab của bạn",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 4730e85fa9..18fecd99ee 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2769,8 +2769,10 @@
"workload-identity-all-branches-tags": "所有分支和标签",
"workload-identity-allowed-branches-tags": "允许的分支/标签",
"workload-identity-audience": "受众",
+ "workload-identity-audience-hint": "流水线请求的 audience。Bytebase 生成的工作流请求 bytebase;配置指南请求提供方默认值,如果流水线使用该值,请另起一行添加。",
"workload-identity-branch": "分支",
"workload-identity-branch-hint": "留空表示允许所有分支",
+ "workload-identity-config-rejected": "Bytebase 无法接受此配置:",
"workload-identity-generic-oidc": "通用 OIDC",
"workload-identity-gitlab-url": "GitLab 地址",
"workload-identity-gitlab-url-hint": "您的 GitLab 实例地址",
diff --git a/frontend/src/routes/project/ProjectGitOpsPage.tsx b/frontend/src/routes/project/ProjectGitOpsPage.tsx
index e05b67bf94..aff71a1a8d 100644
--- a/frontend/src/routes/project/ProjectGitOpsPage.tsx
+++ b/frontend/src/routes/project/ProjectGitOpsPage.tsx
@@ -22,10 +22,10 @@ import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb
import type { WorkloadIdentity } from "@/types/proto-es/v1/workload_identity_service_pb";
import { WorkloadIdentityConfig_ProviderType } from "@/types/proto-es/v1/workload_identity_service_pb";
import {
+ GENERATED_WORKFLOW_AUDIENCE,
getWorkloadIdentityProviderText,
hasProjectPermissionV2,
parseWorkloadIdentitySubjectPattern,
- resolveWorkloadIdentityProviderType,
} from "@/utils";
import { WorkloadIdentitySelect } from "./WorkloadIdentitySelect";
@@ -88,12 +88,8 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {
}, [selectedIdentityName, fetchWorkloadIdentity]);
const selectedConfig = selectedIdentity?.workloadIdentityConfig;
- // Resolved, not read raw: the subject parser below resolves an unspecified
- // provider from the subject prefix, so a page reading the stored enum would
- // render this identity's repository under a "provider does not match" alert
- // naming no provider.
const selectedProviderType =
- resolveWorkloadIdentityProviderType(selectedConfig) ??
+ selectedConfig?.providerType ??
WorkloadIdentityConfig_ProviderType.PROVIDER_TYPE_UNSPECIFIED;
// Sync active tab with selected identity provider
@@ -686,7 +682,7 @@ const exchangeTokenStep = (indent: string) =>
${indent} id: bytebase-auth
${indent} run: |
${indent} OIDC_TOKEN=$(curl -s -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \\
-${indent} "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=bytebase" | jq -r '.value')
+${indent} "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=${GENERATED_WORKFLOW_AUDIENCE}" | jq -r '.value')
${indent} ACCESS_TOKEN=$(curl -s -X POST "$BYTEBASE_URL/v1/auth:exchangeToken" \\
${indent} -H "Content-Type: application/json" \\
${indent} -d "{\\"token\\":\\"$OIDC_TOKEN\\",\\"email\\":\\"$BYTEBASE_WORKLOAD_IDENTITY\\"}" \\
@@ -837,7 +833,7 @@ sql-review:
image: bytebase/bytebase-action
id_tokens:
GITLAB_OIDC_TOKEN:
- aud: bytebase
+ aud: ${GENERATED_WORKFLOW_AUDIENCE}
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script:
@@ -849,7 +845,7 @@ create-rollout:
image: bytebase/bytebase-action
id_tokens:
GITLAB_OIDC_TOKEN:
- aud: bytebase
+ aud: ${GENERATED_WORKFLOW_AUDIENCE}
rules:
- if: $CI_COMMIT_BRANCH == "${p.branch}"
script:
@@ -864,7 +860,7 @@ deploy-to-test:
needs: [create-rollout]
id_tokens:
GITLAB_OIDC_TOKEN:
- aud: bytebase
+ aud: ${GENERATED_WORKFLOW_AUDIENCE}
rules:
- if: $CI_COMMIT_BRANCH == "${p.branch}"
environment: test
@@ -879,7 +875,7 @@ deploy-to-prod:
needs: [deploy-to-test]
id_tokens:
GITLAB_OIDC_TOKEN:
- aud: bytebase
+ aud: ${GENERATED_WORKFLOW_AUDIENCE}
rules:
- if: $CI_COMMIT_BRANCH == "${p.branch}"
environment: prod
diff --git a/frontend/src/types/proto-es/v1/workload_identity_service_pb.d.ts b/frontend/src/types/proto-es/v1/workload_identity_service_pb.d.ts
index ad53cb27be..f92f85d3cf 100644
--- a/frontend/src/types/proto-es/v1/workload_identity_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/workload_identity_service_pb.d.ts
@@ -84,21 +84,28 @@ export declare type WorkloadIdentityConfig = Message<"bytebase.v1.WorkloadIdenti
providerType: WorkloadIdentityConfig_ProviderType;
/**
- * OIDC Issuer URL (auto-filled based on provider_type, can be overridden)
+ * HTTPS URL of the OIDC issuer. The exchange fetches
+ * {issuer_url}/.well-known/openid-configuration to verify a token, unless
+ * jwks_url names the key set directly.
*
* @generated from field: string issuer_url = 2;
*/
issuerUrl: string;
/**
- * Allowed audiences for token validation
+ * Audiences a token may be minted for. A token authenticates if its `aud`
+ * claim matches any entry.
*
* @generated from field: repeated string allowed_audiences = 3;
*/
allowedAudiences: string[];
/**
- * Subject pattern to match (e.g., "repo:owner/repo:ref:refs/heads/main")
+ * The subject a token must carry, e.g. "repo:owner/repo:ref:refs/heads/main".
+ * A trailing "*" is a prefix match. For GitHub and GitLab subjects it must
+ * complete an owner or group segment, so "repo:my-org/*" is accepted and
+ * "repo:*" is not. Other issuers write other vocabularies, so a wildcard
+ * outside those two is accepted as given.
*
* @generated from field: string subject_pattern = 4;
*/
diff --git a/frontend/src/types/proto-es/v1/workload_identity_service_pb.js b/frontend/src/types/proto-es/v1/workload_identity_service_pb.js
index 96600d669c..110a103133 100644
--- a/frontend/src/types/proto-es/v1/workload_identity_service_pb.js
+++ b/frontend/src/types/proto-es/v1/workload_identity_service_pb.js
@@ -16,7 +16,7 @@ import { file_v1_common } from "./common_pb";
* Describes the file v1/workload_identity_service.proto.
*/
export const file_v1_workload_identity_service = /*@__PURE__*/
- fileDesc("CiJ2MS93b3JrbG9hZF9pZGVudGl0eV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSKyAgoQV29ya2xvYWRJZGVudGl0eRIRCgRuYW1lGAEgASgJQgPgQQMSIQoFc3RhdGUYAiABKA4yEi5ieXRlYmFzZS52MS5TdGF0ZRISCgVlbWFpbBgDIAEoCUID4EEDEhcKBXRpdGxlGAQgASgJQgi6SAVyAxjIARI0CgtjcmVhdGVfdGltZRgFIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxJFChh3b3JrbG9hZF9pZGVudGl0eV9jb25maWcYBiABKAsyIy5ieXRlYmFzZS52MS5Xb3JrbG9hZElkZW50aXR5Q29uZmlnOj7qQTsKHWJ5dGViYXNlLmNvbS9Xb3JrbG9hZElkZW50aXR5Ehp3b3JrbG9hZElkZW50aXRpZXMve2VtYWlsfSKMAgoWV29ya2xvYWRJZGVudGl0eUNvbmZpZxJHCg1wcm92aWRlcl90eXBlGAEgASgOMjAuYnl0ZWJhc2UudjEuV29ya2xvYWRJZGVudGl0eUNvbmZpZy5Qcm92aWRlclR5cGUSEgoKaXNzdWVyX3VybBgCIAEoCRIZChFhbGxvd2VkX2F1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ASoiKC92MS97bmFtZT13b3JrbG9hZElkZW50aXRpZXMvKn06dW5kZWxldGVCsgEKD2NvbS5ieXRlYmFzZS52MUIcV29ya2xvYWRJZGVudGl0eVNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common]);
+ fileDesc("CiJ2MS93b3JrbG9hZF9pZGVudGl0eV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSK3AgoQV29ya2xvYWRJZGVudGl0eRIRCgRuYW1lGAEgASgJQgPgQQMSIQoFc3RhdGUYAiABKA4yEi5ieXRlYmFzZS52MS5TdGF0ZRISCgVlbWFpbBgDIAEoCUID4EEDEhcKBXRpdGxlGAQgASgJQgi6SAVyAxjIARI0CgtjcmVhdGVfdGltZRgFIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxJKChh3b3JrbG9hZF9pZGVudGl0eV9jb25maWcYBiABKAsyIy5ieXRlYmFzZS52MS5Xb3JrbG9hZElkZW50aXR5Q29uZmlnQgPgQQI6PupBOwodYnl0ZWJhc2UuY29tL1dvcmtsb2FkSWRlbnRpdHkSGndvcmtsb2FkSWRlbnRpdGllcy97ZW1haWx9IqACChZXb3JrbG9hZElkZW50aXR5Q29uZmlnEkwKDXByb3ZpZGVyX3R5cGUYASABKA4yMC5ieXRlYmFzZS52MS5Xb3JrbG9hZElkZW50aXR5Q29uZmlnLlByb3ZpZGVyVHlwZUID4EECEhcKCmlzc3Vlcl91cmwYAi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WxldGWQ6jABmOowAaDqMASo6jAJgtPkkwItOgEqIigvdjEve25hbWU9d29ya2xvYWRJZGVudGl0aWVzLyp9OnVuZGVsZXRlQrIBCg9jb20uYnl0ZWJhc2UudjFCHFdvcmtsb2FkSWRlbnRpdHlTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common]);
/**
* Describes the message bytebase.v1.WorkloadIdentity.
diff --git a/frontend/src/utils/workloadIdentity.test.ts b/frontend/src/utils/workloadIdentity.test.ts
deleted file mode 100644
index 8362d446e1..0000000000
--- a/frontend/src/utils/workloadIdentity.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { describe, expect, test } from "vitest";
-import { WorkloadIdentityConfig_ProviderType } from "@/types/proto-es/v1/workload_identity_service_pb";
-import {
- parseWorkloadIdentitySubjectPattern,
- resolveWorkloadIdentityProviderType,
-} from "./workloadIdentity";
-
-const { GITHUB, GITLAB, PROVIDER_TYPE_UNSPECIFIED } =
- WorkloadIdentityConfig_ProviderType;
-
-describe("resolveWorkloadIdentityProviderType", () => {
- test("returns a declared provider unchanged", () => {
- expect(
- resolveWorkloadIdentityProviderType({
- providerType: GITLAB,
- subjectPattern: "repo:acme-corp/*",
- })
- ).toBe(GITLAB);
- });
-
- // provider_type is optional and identities created through the API often
- // omit it. Leaving those unresolved seeds the edit form with an unspecified
- // provider, which recomputes an empty subject pattern on mount and locks the
- // operator out of the identity.
- test("infers the provider from the subject when none was declared", () => {
- expect(
- resolveWorkloadIdentityProviderType({
- providerType: PROVIDER_TYPE_UNSPECIFIED,
- subjectPattern: "repo:acme-corp/deploy:ref:refs/heads/main",
- })
- ).toBe(GITHUB);
- expect(
- resolveWorkloadIdentityProviderType({
- providerType: PROVIDER_TYPE_UNSPECIFIED,
- subjectPattern: "project_path:grp/proj:*",
- })
- ).toBe(GITLAB);
- });
-
- test("returns undefined when the subject names no provider", () => {
- expect(
- resolveWorkloadIdentityProviderType({
- providerType: PROVIDER_TYPE_UNSPECIFIED,
- subjectPattern: "custom:whatever",
- })
- ).toBeUndefined();
- expect(resolveWorkloadIdentityProviderType(undefined)).toBeUndefined();
- });
-});
-
-describe("parseWorkloadIdentitySubjectPattern", () => {
- // The parser and the form's initial provider must agree, so both read the
- // same resolution.
- test("parses an identity that never declared a provider", () => {
- expect(
- parseWorkloadIdentitySubjectPattern({
- workloadIdentityConfig: {
- providerType: PROVIDER_TYPE_UNSPECIFIED,
- subjectPattern: "repo:acme-corp/deploy:ref:refs/heads/main",
- },
- })
- ).toEqual({ owner: "acme-corp", repo: "deploy", branch: "main" });
- });
-});
diff --git a/frontend/src/utils/workloadIdentity.ts b/frontend/src/utils/workloadIdentity.ts
index 4770c03b1f..57c3315ede 100644
--- a/frontend/src/utils/workloadIdentity.ts
+++ b/frontend/src/utils/workloadIdentity.ts
@@ -1,28 +1,9 @@
import { WorkloadIdentityConfig_ProviderType } from "@/types/proto-es/v1/workload_identity_service_pb";
-// provider_type is optional in storage and identities written before it was
-// required may carry PROVIDER_TYPE_UNSPECIFIED. Every reader that needs a
-// provider for such an identity resolves it here, or two readers disagree
-// about the same record.
-export const resolveWorkloadIdentityProviderType = (config?: {
- subjectPattern: string;
- providerType: WorkloadIdentityConfig_ProviderType;
-}): WorkloadIdentityConfig_ProviderType | undefined => {
- if (!config) return undefined;
- if (
- config.providerType !==
- WorkloadIdentityConfig_ProviderType.PROVIDER_TYPE_UNSPECIFIED
- ) {
- return config.providerType;
- }
- if (config.subjectPattern.startsWith("repo:")) {
- return WorkloadIdentityConfig_ProviderType.GITHUB;
- }
- if (config.subjectPattern.startsWith("project_path:")) {
- return WorkloadIdentityConfig_ProviderType.GITLAB;
- }
- return undefined;
-};
+// The audience the GitOps page's generated workflows request, and the one the
+// create form presets. An identity and the pipeline that authenticates to it
+// must name the same audience, so both read it here.
+export const GENERATED_WORKFLOW_AUDIENCE = "bytebase";
// Parse subject pattern and extract owner/repo/branch/refType
export const parseWorkloadIdentitySubjectPattern = (wi: {
@@ -40,10 +21,7 @@ export const parseWorkloadIdentitySubjectPattern = (wi: {
return;
}
- const providerType = resolveWorkloadIdentityProviderType(
- wi.workloadIdentityConfig
- );
- switch (providerType) {
+ switch (wi.workloadIdentityConfig.providerType) {
case WorkloadIdentityConfig_ProviderType.GITHUB: {
const match = /^repo:([^/]+)\/(.*)$/.exec(pattern);
if (!match) return;
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 29949160e4..113f8b2ae4 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -33635,6 +33635,8 @@ components:
description: The workload identity configuration for OIDC token validation.
$ref: '#/components/schemas/bytebase.v1.WorkloadIdentityConfig'
title: WorkloadIdentity
+ required:
+ - workloadIdentityConfig
additionalProperties: false
description: WorkloadIdentity represents an external CI/CD workload identity.
bytebase.v1.WorkloadIdentityConfig:
@@ -33647,22 +33649,37 @@ components:
issuerUrl:
type: string
title: issuer_url
- description: OIDC Issuer URL (auto-filled based on provider_type, can be overridden)
+ description: |-
+ HTTPS URL of the OIDC issuer. The exchange fetches
+ {issuer_url}/.well-known/openid-configuration to verify a token, unless
+ jwks_url names the key set directly.
allowedAudiences:
type: array
items:
type: string
title: allowed_audiences
- description: Allowed audiences for token validation
+ description: |-
+ Audiences a token may be minted for. A token authenticates if its `aud`
+ claim matches any entry.
subjectPattern:
type: string
title: subject_pattern
- description: Subject pattern to match (e.g., "repo:owner/repo:ref:refs/heads/main")
+ description: |-
+ The subject a token must carry, e.g. "repo:owner/repo:ref:refs/heads/main".
+ A trailing "*" is a prefix match. For GitHub and GitLab subjects it must
+ complete an owner or group segment, so "repo:my-org/*" is accepted and
+ "repo:*" is not. Other issuers write other vocabularies, so a wildcard
+ outside those two is accepted as given.
jwksUrl:
type: string
title: jwks_url
description: Optional JWKS endpoint. When empty, use OIDC discovery from issuer_url.
title: WorkloadIdentityConfig
+ required:
+ - providerType
+ - issuerUrl
+ - allowedAudiences
+ - subjectPattern
additionalProperties: false
description: WorkloadIdentityConfig for API layer
bytebase.v1.WorkloadIdentityConfig.ProviderType:
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index fb46aeda3f..3c577b8990 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -12824,9 +12824,9 @@ WorkloadIdentityConfig for API layer
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| provider_type | [WorkloadIdentityConfig.ProviderType](#bytebase-v1-WorkloadIdentityConfig-ProviderType) | | Provider configuration mode. |
-| issuer_url | [string](#string) | | OIDC Issuer URL (auto-filled based on provider_type, can be overridden) |
-| allowed_audiences | [string](#string) | repeated | Allowed audiences for token validation |
-| subject_pattern | [string](#string) | | Subject pattern to match (e.g., &#34;repo:owner/repo:ref:refs/heads/main&#34;) |
+| issuer_url | [string](#string) | | HTTPS URL of the OIDC issuer. The exchange fetches {issuer_url}/.well-known/openid-configuration to verify a token, unless jwks_url names the key set directly. |
+| allowed_audiences | [string](#string) | repeated | Audiences a token may be minted for. A token authenticates if its `aud` claim matches any entry. |
+| subject_pattern | [string](#string) | | The subject a token must carry, e.g. &#34;repo:owner/repo:ref:refs/heads/main&#34;. A trailing &#34;*&#34; is a prefix match. For GitHub and GitLab subjects it must complete an owner or group segment, so &#34;repo:my-org/*&#34; is accepted and &#34;repo:*&#34; is not. Other issuers write other vocabularies, so a wildcard outside those two is accepted as given. |
| jwks_url | [string](#string) | | Optional JWKS endpoint. When empty, use OIDC discovery from issuer_url. |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 7d9d63f704..14181d75cc 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -36488,21 +36488,28 @@ For project-level: {name}@{project-id}.workload.bytebase.com </p></td>
<td>issuer_url</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>OIDC Issuer URL (auto-filled based on provider_type, can be overridden) </p></td>
+ <td><p>HTTPS URL of the OIDC issuer. The exchange fetches
+{issuer_url}/.well-known/openid-configuration to verify a token, unless
+jwks_url names the key set directly. </p></td>
</tr>
<tr>
<td>allowed_audiences</td>
<td><a href="#string">string</a></td>
<td>repeated</td>
- <td><p>Allowed audiences for token validation </p></td>
+ <td><p>Audiences a token may be minted for. A token authenticates if its `aud`
+claim matches any entry. </p></td>
</tr>
<tr>
<td>subject_pattern</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>Subject pattern to match (e.g., &#34;repo:owner/repo:ref:refs/heads/main&#34;) </p></td>
+ <td><p>The subject a token must carry, e.g. &#34;repo:owner/repo:ref:refs/heads/main&#34;.
+A trailing &#34;*&#34; is a prefix match. For GitHub and GitLab subjects it must
+complete an owner or group segment, so &#34;repo:my-org/*&#34; is accepted and
+&#34;repo:*&#34; is not. Other issuers write other vocabularies, so a wildcard
+outside those two is accepted as given. </p></td>
</tr>
<tr>
diff --git a/proto/v1/v1/workload_identity_service.proto b/proto/v1/v1/workload_identity_service.proto
index 2496c50677..075d217751 100644
--- a/proto/v1/v1/workload_identity_service.proto
+++ b/proto/v1/v1/workload_identity_service.proto
@@ -131,7 +131,7 @@ message WorkloadIdentity {
google.protobuf.Timestamp create_time = 5 [(google.api.field_behavior) = OUTPUT_ONLY];
// The workload identity configuration for OIDC token validation.
- WorkloadIdentityConfig workload_identity_config = 6;
+ WorkloadIdentityConfig workload_identity_config = 6 [(google.api.field_behavior) = REQUIRED];
}
// WorkloadIdentityConfig for API layer
@@ -145,13 +145,20 @@ message WorkloadIdentityConfig {
}
// Provider configuration mode.
- ProviderType provider_type = 1;
- // OIDC Issuer URL (auto-filled based on provider_type, can be overridden)
- string issuer_url = 2;
- // Allowed audiences for token validation
- repeated string allowed_audiences = 3;
- // Subject pattern to match (e.g., "repo:owner/repo:ref:refs/heads/main")
- string subject_pattern = 4;
+ ProviderType provider_type = 1 [(google.api.field_behavior) = REQUIRED];
+ // HTTPS URL of the OIDC issuer. The exchange fetches
+ // {issuer_url}/.well-known/openid-configuration to verify a token, unless
+ // jwks_url names the key set directly.
+ string issuer_url = 2 [(google.api.field_behavior) = REQUIRED];
+ // Audiences a token may be minted for. A token authenticates if its `aud`
+ // claim matches any entry.
+ repeated string allowed_audiences = 3 [(google.api.field_behavior) = REQUIRED];
+ // The subject a token must carry, e.g. "repo:owner/repo:ref:refs/heads/main".
+ // A trailing "*" is a prefix match. For GitHub and GitLab subjects it must
+ // complete an owner or group segment, so "repo:my-org/*" is accepted and
+ // "repo:*" is not. Other issuers write other vocabularies, so a wildcard
+ // outside those two is accepted as given.
+ string subject_pattern = 4 [(google.api.field_behavior) = REQUIRED];
// Optional JWKS endpoint. When empty, use OIDC discovery from issuer_url.
string jwks_url = 5;
}