-
Notifications
You must be signed in to change notification settings - Fork 1
fix: Regenerate non-UTF-8 adopted generated secrets #300
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
wnevis-cmyk
wants to merge
4
commits into
main
Choose a base branch
from
wnevis/migration-weave-auth-utf8
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2a1ad59
fix: Regenerate non-UTF-8 adopted generated secrets
wnevis-cmyk 0ad75ba
Merge branch 'main' into wnevis/migration-weave-auth-utf8
wnevis-cmyk eae0610
Merge branch 'main' into wnevis/migration-weave-auth-utf8
wnevis-cmyk 50aad4d
Adjusts to fail on non-UTF-8 secret
wnevis-cmyk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
155 changes: 155 additions & 0 deletions
155
internal/controller/reconciler/generate_secrets_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| /* | ||
| Copyright 2025. | ||
|
|
||
| Licensed 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 reconciler | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
| "unicode/utf8" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| corev1 "k8s.io/api/core/v1" | ||
| apimeta "k8s.io/apimachinery/pkg/api/meta" | ||
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
| "k8s.io/apimachinery/pkg/runtime" | ||
| "k8s.io/apimachinery/pkg/types" | ||
| "k8s.io/client-go/tools/record" | ||
| ctrlClient "sigs.k8s.io/controller-runtime/pkg/client" | ||
| "sigs.k8s.io/controller-runtime/pkg/client/fake" | ||
|
|
||
| apiv2 "github.com/wandb/operator/api/v2" | ||
| "github.com/wandb/operator/internal/controller/common" | ||
| serverManifest "github.com/wandb/operator/pkg/wandb/manifest" | ||
| ) | ||
|
|
||
| func newGenerateSecretsFixture( | ||
| t *testing.T, | ||
| seed ...ctrlClient.Object, | ||
| ) (ctrlClient.Client, *apiv2.WeightsAndBiases) { | ||
| t.Helper() | ||
| scheme := runtime.NewScheme() | ||
| require.NoError(t, corev1.AddToScheme(scheme)) | ||
| require.NoError(t, apiv2.AddToScheme(scheme)) | ||
|
|
||
| wandb := &apiv2.WeightsAndBiases{ | ||
| TypeMeta: metav1.TypeMeta{APIVersion: "apps.wandb.com/v2", Kind: "WeightsAndBiases"}, | ||
| ObjectMeta: metav1.ObjectMeta{Name: "wandb", Namespace: "default"}, | ||
| } | ||
| objects := append([]ctrlClient.Object{wandb}, seed...) | ||
| client := fake.NewClientBuilder(). | ||
| WithScheme(scheme). | ||
| WithStatusSubresource(&apiv2.WeightsAndBiases{}). | ||
| WithObjects(objects...). | ||
| Build() | ||
| return client, wandb | ||
| } | ||
|
|
||
| // effectiveSecretValue returns the value under key. The fake client does not | ||
| // fold StringData into Data, so prefer StringData then fall back to Data. | ||
| func effectiveSecretValue(sec *corev1.Secret, key string) string { | ||
| if v, ok := sec.StringData[key]; ok { | ||
| return v | ||
| } | ||
| return string(sec.Data[key]) | ||
| } | ||
|
|
||
| func weaveWorkerAuthManifest() serverManifest.Manifest { | ||
| return serverManifest.Manifest{ | ||
| GeneratedSecrets: []serverManifest.GeneratedSecret{ | ||
| {Name: "weave-worker-auth", Length: 32, CharacterType: "password", UseExactName: true}, | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| // TestGenerateSecrets_FailsOnNonUTF8AdoptedSecret: a non-UTF-8 token must fail | ||
| // the reconcile loudly (error + Ready=false condition + warning event) rather | ||
| // than being silently rewritten. | ||
| func TestGenerateSecrets_FailsOnNonUTF8AdoptedSecret(t *testing.T) { | ||
| invalid := []byte{0xff, 0xfe, 0xfd, 0x00, 0x80} | ||
| require.False(t, utf8.Valid(invalid), "test precondition: bytes must be invalid UTF-8") | ||
|
|
||
| seeded := &corev1.Secret{ | ||
| ObjectMeta: metav1.ObjectMeta{Name: "weave-worker-auth", Namespace: "default"}, | ||
| Type: corev1.SecretTypeOpaque, | ||
| Data: map[string][]byte{"key": invalid}, | ||
| } | ||
| client, wandb := newGenerateSecretsFixture(t, seeded) | ||
| recorder := record.NewFakeRecorder(10) | ||
|
|
||
| _, err := generateSecrets(context.Background(), client, recorder, wandb, weaveWorkerAuthManifest()) | ||
| require.Error(t, err) | ||
| require.Contains(t, err.Error(), "non-UTF-8") | ||
|
|
||
| var sec corev1.Secret | ||
| require.NoError(t, client.Get(context.Background(), | ||
| types.NamespacedName{Name: "weave-worker-auth", Namespace: "default"}, &sec)) | ||
| require.Equal(t, invalid, sec.Data["key"], "invalid secret must not be overwritten") | ||
| require.NotContains(t, sec.StringData, "key", "no regeneration should have occurred") | ||
|
|
||
| require.False(t, wandb.Status.Ready) | ||
| cond := apimeta.FindStatusCondition(wandb.Status.Conditions, readyConditionType) | ||
| require.NotNil(t, cond) | ||
| require.Equal(t, metav1.ConditionFalse, cond.Status) | ||
| require.Equal(t, common.InvalidSecretEncodingReason, cond.Reason) | ||
|
|
||
| select { | ||
| case ev := <-recorder.Events: | ||
| require.Contains(t, ev, common.InvalidSecretEncodingReason) | ||
| default: | ||
| t.Fatal("expected a warning event to be recorded") | ||
| } | ||
| } | ||
|
|
||
| // TestGenerateSecrets_LeavesValidExistingValueUntouched: a valid adopted token | ||
| // is preserved (no needless rotation). | ||
| func TestGenerateSecrets_LeavesValidExistingValueUntouched(t *testing.T) { | ||
| valid := []byte("already-valid-token-123") | ||
| seeded := &corev1.Secret{ | ||
| ObjectMeta: metav1.ObjectMeta{Name: "weave-worker-auth", Namespace: "default"}, | ||
| Type: corev1.SecretTypeOpaque, | ||
| Data: map[string][]byte{"key": valid}, | ||
| } | ||
| client, wandb := newGenerateSecretsFixture(t, seeded) | ||
|
|
||
| _, err := generateSecrets(context.Background(), client, record.NewFakeRecorder(10), wandb, weaveWorkerAuthManifest()) | ||
| require.NoError(t, err) | ||
|
|
||
| var sec corev1.Secret | ||
| require.NoError(t, client.Get(context.Background(), | ||
| types.NamespacedName{Name: "weave-worker-auth", Namespace: "default"}, &sec)) | ||
|
|
||
| require.Equal(t, valid, sec.Data["key"], "valid existing value must not be overwritten") | ||
| require.NotContains(t, sec.StringData, "key", "no regeneration should have occurred") | ||
| } | ||
|
|
||
| // TestGenerateSecrets_CreatesMissingSecretWithUTF8Token: fresh secrets hold a | ||
| // UTF-8-safe token. | ||
| func TestGenerateSecrets_CreatesMissingSecretWithUTF8Token(t *testing.T) { | ||
| client, wandb := newGenerateSecretsFixture(t) | ||
|
|
||
| _, err := generateSecrets(context.Background(), client, record.NewFakeRecorder(10), wandb, weaveWorkerAuthManifest()) | ||
| require.NoError(t, err) | ||
|
|
||
| var sec corev1.Secret | ||
| require.NoError(t, client.Get(context.Background(), | ||
| types.NamespacedName{Name: "weave-worker-auth", Namespace: "default"}, &sec)) | ||
|
|
||
| value := effectiveSecretValue(&sec, "key") | ||
| require.NotEmpty(t, value) | ||
| require.True(t, utf8.ValidString(value)) | ||
| require.Len(t, value, 32) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,6 +24,7 @@ import ( | |
| "net/url" | ||
| "strings" | ||
| "time" | ||
| "unicode/utf8" | ||
|
|
||
| "github.com/samber/lo" | ||
| apiv2 "github.com/wandb/operator/api/v2" | ||
|
|
@@ -374,7 +375,7 @@ func Reconcile( | |
| return ctrl.Result{RequeueAfter: defaultRequeueDuration}, nil | ||
| } | ||
|
|
||
| res, err = ReconcileWandbManifest(ctx, client, wandb, manifest, telemetryConfig) | ||
| res, err = ReconcileWandbManifest(ctx, client, recorder, wandb, manifest, telemetryConfig) | ||
| // send up the manifest error for now | ||
| if err != nil { | ||
| return res, err | ||
|
|
@@ -402,6 +403,7 @@ func consolidateResults(results []ctrl.Result) ctrl.Result { | |
| func ReconcileWandbManifest( | ||
| ctx context.Context, | ||
| client ctrlClient.Client, | ||
| recorder record.EventRecorder, | ||
| wandb *apiv2.WeightsAndBiases, | ||
| manifest serverManifest.Manifest, | ||
| telemetryConfig TelemetryRuntimeConfig, | ||
|
|
@@ -442,7 +444,7 @@ func ReconcileWandbManifest( | |
|
|
||
| validateLegacyOverrides(ctx, wandb, manifest) | ||
|
|
||
| result, err = generateSecrets(ctx, client, wandb, manifest) | ||
| result, err = generateSecrets(ctx, client, recorder, wandb, manifest) | ||
| if err != nil { | ||
| return result, err | ||
| } | ||
|
|
@@ -1410,7 +1412,7 @@ func runMigrations(ctx context.Context, client ctrlClient.Client, wandb *apiv2.W | |
| return ctrl.Result{RequeueAfter: 5 * time.Second}, nil | ||
| } | ||
|
|
||
| func generateSecrets(ctx context.Context, client ctrlClient.Client, wandb *apiv2.WeightsAndBiases, manifest serverManifest.Manifest) (ctrl.Result, error) { | ||
| func generateSecrets(ctx context.Context, client ctrlClient.Client, recorder record.EventRecorder, wandb *apiv2.WeightsAndBiases, manifest serverManifest.Manifest) (ctrl.Result, error) { | ||
| statusBefore := wandb.DeepCopy().Status | ||
| // Ensure any manifest-declared generated secrets exist and capture their selectors in status | ||
| if wandb.Status.GeneratedSecrets == nil { | ||
|
|
@@ -1460,12 +1462,23 @@ func generateSecrets(ctx context.Context, client ctrlClient.Client, wandb *apiv2 | |
| return ctrl.Result{}, err | ||
| } | ||
| } else { | ||
| // Secret exists. Ensure it has the expected key; do not overwrite existing value. | ||
| if sec.Data == nil || (sec.Data != nil && sec.Data[keyName] == nil && sec.StringData == nil) { | ||
| if sec.StringData == nil { | ||
| sec.StringData = map[string]string{} | ||
| // Secret exists; don't overwrite a valid existing value. | ||
| existing, hasKey := sec.Data[keyName] | ||
| // Non-UTF-8 secretKeyRef env vars break container creation. | ||
| if hasKey && !utf8.Valid(existing) { | ||
| msg := fmt.Sprintf( | ||
| "generated secret %q key %q contains non-UTF-8 bytes; values consumed as container environment variables must be valid UTF-8 — replace it with a UTF-8-safe value", | ||
| secretName, keyName, | ||
| ) | ||
| recorder.Event(wandb, corev1.EventTypeWarning, common.InvalidSecretEncodingReason, msg) | ||
| if err := updateReadyStatus(ctx, client, wandb, statusBefore, false, common.InvalidSecretEncodingReason, msg); err != nil { | ||
| return ctrl.Result{}, err | ||
| } | ||
| // Generate a value only if missing | ||
| return ctrl.Result{}, errors.New(msg) | ||
| } | ||
| if !hasKey && sec.StringData == nil { | ||
| // Secret exists but has no usable key; populate one. | ||
| sec.StringData = map[string]string{} | ||
|
Comment on lines
+1465
to
+1481
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win Align the implementation and test with regeneration. The implementation and test encode rejection. The PR objective requires regeneration of invalid adopted values.
📍 Affects 2 files
🤖 Prompt for AI Agents |
||
| valueLen := gs.Length | ||
| if valueLen <= 0 { | ||
| valueLen = 32 | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: wandb/operator
Length of output: 50371
🏁 Script executed:
Repository: wandb/operator
Length of output: 42962
Use the required test framework and run validation before merge.
internal/controller/reconciler/generate_secrets_test.gousestesting, Testify, andfake.NewClientBuilder. The repository policy requires Ginkgo/Gomega specs attached tosuite_test.gofiles with envtest.Also run
make lintandmake testand include their results before merge.🤖 Prompt for AI Agents
Source: Coding guidelines