From 875efd429b1e28e7a8c0d78b4b42664cb63a681a Mon Sep 17 00:00:00 2001 From: Dhruvraj-Rana Date: Sun, 29 Nov 2026 19:41:22 +0530 Subject: [PATCH] feat(secrets): wrap update secret RPC Signed-off-by: Dhruvraj-Rana --- README.md | 2 + docs/src/SUMMARY.md | 1 + docs/src/api/client.md | 1 + docs/src/api/fake.md | 6 + docs/src/api/secrets.md | 36 +++++ openshell/v1/client.go | 6 + openshell/v1/client_test.go | 1 + openshell/v1/fake/fake.go | 16 ++ openshell/v1/fake/secret.go | 78 +++++++++ openshell/v1/fake/secret_test.go | 130 +++++++++++++++ openshell/v1/internal/converter/secret.go | 72 +++++++++ .../v1/internal/converter/secret_test.go | 124 ++++++++++++++ openshell/v1/secret.go | 24 +++ openshell/v1/secret_client.go | 35 ++++ openshell/v1/secret_client_test.go | 151 ++++++++++++++++++ openshell/v1/types/secret.go | 38 +++++ 16 files changed, 721 insertions(+) create mode 100644 docs/src/api/secrets.md create mode 100644 openshell/v1/fake/secret.go create mode 100644 openshell/v1/fake/secret_test.go create mode 100644 openshell/v1/internal/converter/secret.go create mode 100644 openshell/v1/internal/converter/secret_test.go create mode 100644 openshell/v1/secret.go create mode 100644 openshell/v1/secret_client.go create mode 100644 openshell/v1/secret_client_test.go create mode 100644 openshell/v1/types/secret.go diff --git a/README.md b/README.md index b572088..bd573bf 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,7 @@ Client ├── Providers() → ProviderInterface (CRUD + ensure) │ ├── Profiles() → ProfileInterface (list, get, import, update, lint, delete) │ └── Refresh() → RefreshInterface (configure, status, rotate, delete) + ├── Secrets() → SecretInterface (update) ├── Workspaces() → WorkspaceInterface (create, get, list, delete, members) └── Policy() → PolicyInterface (draft review, approve, reject, merge, status) ``` @@ -318,6 +319,7 @@ stream completion. | Sandbox lifecycle (create, get, list, delete, watch, wait) | `SandboxInterface` | [Sandboxes](https://ai-openshell.github.io/sdk-go/api/sandboxes.html) | | Command execution (collected, streamed, interactive PTY) | `ExecInterface` | [Exec](https://ai-openshell.github.io/sdk-go/api/exec.html) | | Provider management (CRUD + idempotent ensure) | `ProviderInterface` | [Providers](https://ai-openshell.github.io/sdk-go/api/providers.html) | +| Secret metadata and value updates | `SecretInterface` | [Secrets](https://ai-openshell.github.io/sdk-go/api/secrets.html) | | Provider profiles (list, import, lint, update) | `ProfileInterface` | [Profiles](https://ai-openshell.github.io/sdk-go/api/profiles.html) | | Credential refresh (configure, rotate, status) | `RefreshInterface` | [Refresh](https://ai-openshell.github.io/sdk-go/api/refresh.html) | | Service exposure (expose, list, delete) | `ServiceInterface` | [Services](https://ai-openshell.github.io/sdk-go/api/services.html) | diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 9f6f1ae..7a7adaf 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -18,6 +18,7 @@ - [Sandbox Templates](api/sandbox-templates.md) - [Exec](api/exec.md) - [Providers](api/providers.md) +- [Secrets](api/secrets.md) - [Profiles](api/profiles.md) - [Refresh](api/refresh.md) - [Services](api/services.md) diff --git a/docs/src/api/client.md b/docs/src/api/client.md index be3e88a..adbdff5 100644 --- a/docs/src/api/client.md +++ b/docs/src/api/client.md @@ -14,6 +14,7 @@ for each resource domain and manages the underlying gRPC connection. The | `Sandboxes()` | `SandboxInterface` | Sandbox lifecycle management | | `SandboxTemplates()` | `SandboxTemplateInterface` | Reusable sandbox template management | | `Providers()` | `ProviderInterface` | Provider CRUD and idempotent ensure | +| `Secrets()` | `SecretInterface` | Workspace secret updates | | `Services()` | `ServiceInterface` | Service exposure and management | | `ServiceRoutes()` | `ServiceDiscoveryInterface` | Installed route snapshots and watches (concrete client) | | `Exec()` | `ExecInterface` | Command execution (run, stream, interactive) | diff --git a/docs/src/api/fake.md b/docs/src/api/fake.md index fef52dd..922347c 100644 --- a/docs/src/api/fake.md +++ b/docs/src/api/fake.md @@ -75,6 +75,11 @@ client.AddProvider("default", &types.Provider{ Spec: types.ProviderSpec{Type: "docker"}, }) +client.AddSecret("default", &types.Secret{ + Name: "provider-api-key", + ResourceVersion: 1, +}) + client.AddWorkspace(&types.Workspace{Name: "staging"}) client.AddMember("staging", &types.WorkspaceMember{ PrincipalSubject: "subject-123", @@ -95,6 +100,7 @@ additive concrete-client accessors such as `SandboxTemplates()`: | `Sandboxes()` | `SandboxInterface` | Full CRUD, Watch, WaitReady | | `SandboxTemplates()` | `SandboxTemplateInterface` | Full CRUD | | `Providers()` | `ProviderInterface` | Full CRUD, Ensure | +| `Secrets()` | `SecretInterface` | Partial update with optimistic concurrency | | `Workspaces()` | `WorkspaceInterface` | Full CRUD, Members | | `Health()` | `HealthInterface` | Configurable result | | `Policy()` | `PolicyInterface` | List, GetStatus (draft ops return Unimplemented) | diff --git a/docs/src/api/secrets.md b/docs/src/api/secrets.md new file mode 100644 index 0000000..5e0de5b --- /dev/null +++ b/docs/src/api/secrets.md @@ -0,0 +1,36 @@ +# Secrets + +Accessor: `client.Secrets()` + +Workspace secrets hold values that OpenShell does not return from ordinary +resource operations. Updating a secret returns metadata only; the value is not +included in the response. + +## Update + +`Update` applies only the fields whose pointers or maps are non-nil. Use a +non-nil empty labels map to remove all labels. `ExpectedResourceVersion` +provides optimistic concurrency when supplied. + +```go +value := os.Getenv("NEW_API_KEY") +description := "rotated API key" +expectedVersion := secret.ResourceVersion + +updated, err := client.Secrets().Update(ctx, "default", "provider-api-key", &v1.SecretUpdate{ + Value: &value, + Description: &description, + Labels: map[string]string{"environment": "production"}, + ExpectedResourceVersion: &expectedVersion, + RequestID: uuid.NewString(), +}) +if err != nil { + log.Fatal(err) +} +fmt.Printf("updated secret metadata to version %d\n", updated.ResourceVersion) +``` + +Do not log secret values or include them in error messages. A non-nil empty +`Value` is rejected by the server. + +See also: [Error Handling](../error-handling.md), [Testing](../testing.md) diff --git a/openshell/v1/client.go b/openshell/v1/client.go index 7d095c8..b3baea4 100644 --- a/openshell/v1/client.go +++ b/openshell/v1/client.go @@ -24,6 +24,7 @@ type ClientInterface interface { SandboxSuspendResume() SandboxSuspendResumeInterface SandboxLogsWatch() SandboxLogsWatchInterface Providers() ProviderInterface + Secrets() SecretInterface Services() ServiceInterface Exec() ExecInterface Files() FileInterface @@ -59,6 +60,7 @@ type Client struct { logsWatch SandboxLogsWatchInterface templates SandboxTemplateInterface providers ProviderInterface + secrets SecretInterface services ServiceInterface serviceRoutes ServiceDiscoveryInterface exec ExecInterface @@ -108,6 +110,7 @@ func NewClient(cfg Config) (*Client, error) { c.logsWatch = sandboxes c.templates = newSandboxTemplateClient(conn) c.providers = newProviderClient(conn) + c.secrets = newSecretClient(conn) c.services = newServiceClient(conn) c.serviceRoutes = newServiceDiscoveryClient(conn) c.exec = newExecClient(conn, c.sandboxes) @@ -143,6 +146,9 @@ func (c *Client) SandboxLogsWatch() SandboxLogsWatchInterface { return c.logsWat // Providers returns the provider sub-client. func (c *Client) Providers() ProviderInterface { return c.providers } +// Secrets returns the workspace secret sub-client. +func (c *Client) Secrets() SecretInterface { return c.secrets } + // Services returns the service sub-client. func (c *Client) Services() ServiceInterface { return c.services } diff --git a/openshell/v1/client_test.go b/openshell/v1/client_test.go index 668cbc2..66b1970 100644 --- a/openshell/v1/client_test.go +++ b/openshell/v1/client_test.go @@ -27,6 +27,7 @@ func TestNewClient_ValidConfig(t *testing.T) { assert.NotNil(t, client.Sandboxes()) assert.NotNil(t, client.Providers()) + assert.NotNil(t, client.Secrets()) assert.NotNil(t, client.Exec()) assert.NotNil(t, client.Files()) assert.NotNil(t, client.Health()) diff --git a/openshell/v1/fake/fake.go b/openshell/v1/fake/fake.go index a8bcad5..7111da7 100644 --- a/openshell/v1/fake/fake.go +++ b/openshell/v1/fake/fake.go @@ -19,6 +19,7 @@ type Client struct { sandboxStore *objectStore[*types.Sandbox] templateStore *objectStore[*types.SandboxWorkloadTemplate] providerStore *objectStore[*types.Provider] + secretStore *objectStore[*types.Secret] workspaceStore *objectStore[*types.Workspace] memberStore *objectStore[*types.WorkspaceMember] sandboxBroadcaster *watchBroadcaster[*types.Sandbox] @@ -29,6 +30,7 @@ type Client struct { logsWatch v1.SandboxLogsWatchInterface templates v1.SandboxTemplateInterface providers v1.ProviderInterface + secrets v1.SecretInterface services v1.ServiceInterface exec v1.ExecInterface files v1.FileInterface @@ -78,6 +80,7 @@ func NewClient(opts ...ClientOption) *Client { sandboxStore: newobjectStore(sandboxName, copySandbox), templateStore: newobjectStore(sandboxWorkloadTemplate, copySandboxWorkloadTemplate), providerStore: newobjectStore(providerName, copyProvider), + secretStore: newobjectStore(secretName, copySecret), workspaceStore: newobjectStore(workspaceName, copyWorkspace), memberStore: newobjectStore(memberName, copyMember), sandboxBroadcaster: newWatchBroadcaster[*types.Sandbox](), @@ -90,6 +93,7 @@ func NewClient(opts ...ClientOption) *Client { fc.logsWatch = sandboxes fc.templates = newFakeSandboxTemplateClient(fc.templateStore, fc.isClosed) fc.providers = newFakeProviderClient(fc.providerStore, fc.isClosed) + fc.secrets = newFakeSecretClient(fc.secretStore, fc.isClosed) fc.services = newFakeServiceClient(fc.isClosed) fc.exec = newFakeExecClient(fc.isClosed) fc.files = newFakeFileClient(fc.isClosed) @@ -138,6 +142,9 @@ func (fc *Client) SandboxLogsWatch() v1.SandboxLogsWatchInterface { // Providers returns the provider sub-client. func (fc *Client) Providers() v1.ProviderInterface { return fc.providers } +// Secrets returns the workspace secret sub-client. +func (fc *Client) Secrets() v1.SecretInterface { return fc.secrets } + // Services returns the service sub-client. func (fc *Client) Services() v1.ServiceInterface { return fc.services } @@ -209,6 +216,15 @@ func (fc *Client) AddProvider(workspace string, p *types.Provider) { fc.providerStore.Insert(workspace, p) } +// AddSecret inserts secret metadata directly into the store. The secret is +// deep-copied and its value is never retained by the fake client. +func (fc *Client) AddSecret(workspace string, secret *types.Secret) { + if secret == nil { + return + } + fc.secretStore.Insert(workspace, secret) +} + // AddWorkspace inserts a workspace directly into the store without triggering // any side effects. This is intended for pre-seeding test fixtures before // the test begins. The workspace is deep-copied on insert. diff --git a/openshell/v1/fake/secret.go b/openshell/v1/fake/secret.go new file mode 100644 index 0000000..7752478 --- /dev/null +++ b/openshell/v1/fake/secret.go @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package fake + +import ( + "context" + "fmt" + "time" + + "github.com/ai-openshell/sdk-go/openshell/v1/types" +) + +func secretName(secret *types.Secret) string { + return secret.Name +} + +func copySecret(secret *types.Secret) *types.Secret { + if secret == nil { + return nil + } + result := *secret + result.Labels = copyStringMap(secret.Labels) + result.Annotations = copyStringMap(secret.Annotations) + if secret.DeletionTimestamp != nil { + deletionTimestamp := *secret.DeletionTimestamp + result.DeletionTimestamp = &deletionTimestamp + } + if secret.RefreshUse != nil { + result.RefreshUse = &types.SecretRefreshUse{ + AllowedEndpoints: append([]string(nil), secret.RefreshUse.AllowedEndpoints...), + } + } + return &result +} + +type fakeSecretClient struct { + store *objectStore[*types.Secret] + closedFunc func() bool +} + +func newFakeSecretClient(store *objectStore[*types.Secret], closedFunc func() bool) *fakeSecretClient { + return &fakeSecretClient{store: store, closedFunc: closedFunc} +} + +func (c *fakeSecretClient) Update(_ context.Context, workspace, name string, update *types.SecretUpdate) (*types.Secret, error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + if update == nil { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "secret update must not be nil"} + } + + secret, err := c.store.Get(workspace, name) + if err != nil { + return nil, err + } + if update.ExpectedResourceVersion != nil && *update.ExpectedResourceVersion != secret.ResourceVersion { + return nil, &types.StatusError{ + Code: types.ErrorConflict, + Message: fmt.Sprintf("secret %q resource version does not match", name), + } + } + if update.Value != nil { + if *update.Value == "" { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "secret value must not be empty"} + } + secret.ValueUpdateTime = time.Now().UTC() + } + if update.Description != nil { + secret.Description = *update.Description + } + if update.Labels != nil { + secret.Labels = copyStringMap(update.Labels) + } + secret.ResourceVersion++ + return c.store.Update(workspace, secret) +} diff --git a/openshell/v1/fake/secret_test.go b/openshell/v1/fake/secret_test.go new file mode 100644 index 0000000..d74f103 --- /dev/null +++ b/openshell/v1/fake/secret_test.go @@ -0,0 +1,130 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package fake + +import ( + "context" + "testing" + "time" + + "github.com/ai-openshell/sdk-go/openshell/v1/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func newTestSecretClient() (*fakeSecretClient, *objectStore[*types.Secret]) { + store := newobjectStore(secretName, copySecret) + return newFakeSecretClient(store, func() bool { return false }), store +} + +func TestSecretUpdate(t *testing.T) { + client, store := newTestSecretClient() + store.Insert("default", &types.Secret{ + Name: "api-key", + Description: "old description", + Labels: map[string]string{"rotation": "pending"}, + ResourceVersion: 3, + ValueUpdateTime: time.Date(2026, time.November, 1, 0, 0, 0, 0, time.UTC), + RefreshUse: &types.SecretRefreshUse{AllowedEndpoints: []string{"https://auth.example.com/token"}}, + }) + + value := "new-value" + description := "rotated" + version := uint64(3) + result, err := client.Update(context.Background(), "default", "api-key", &types.SecretUpdate{ + Value: &value, + Description: &description, + Labels: map[string]string{"rotation": "complete"}, + ExpectedResourceVersion: &version, + }) + + require.NoError(t, err) + assert.Equal(t, "rotated", result.Description) + assert.Equal(t, map[string]string{"rotation": "complete"}, result.Labels) + assert.Equal(t, uint64(4), result.ResourceVersion) + assert.True(t, result.ValueUpdateTime.After(time.Date(2026, time.November, 1, 0, 0, 0, 0, time.UTC))) + assert.Equal(t, []string{"https://auth.example.com/token"}, result.RefreshUse.AllowedEndpoints) +} + +func TestSecretUpdateClearsLabelsAndDescription(t *testing.T) { + client, store := newTestSecretClient() + store.Insert("default", &types.Secret{ + Name: "api-key", + Description: "old description", + Labels: map[string]string{"environment": "production"}, + ResourceVersion: 1, + }) + emptyDescription := "" + + result, err := client.Update(context.Background(), "default", "api-key", &types.SecretUpdate{ + Description: &emptyDescription, + Labels: map[string]string{}, + }) + + require.NoError(t, err) + assert.Empty(t, result.Description) + assert.Empty(t, result.Labels) + assert.NotNil(t, result.Labels) +} + +func TestSecretUpdateDeepCopiesLabels(t *testing.T) { + client, store := newTestSecretClient() + store.Insert("default", &types.Secret{Name: "api-key", ResourceVersion: 1}) + labels := map[string]string{"environment": "production"} + + result, err := client.Update(context.Background(), "default", "api-key", &types.SecretUpdate{Labels: labels}) + require.NoError(t, err) + labels["environment"] = "mutated" + result.Labels["environment"] = "result-mutated" + + stored, err := store.Get("default", "api-key") + require.NoError(t, err) + assert.Equal(t, "production", stored.Labels["environment"]) +} + +func TestSecretUpdateRejectsResourceVersionMismatch(t *testing.T) { + client, store := newTestSecretClient() + store.Insert("default", &types.Secret{Name: "api-key", ResourceVersion: 2}) + version := uint64(1) + + result, err := client.Update(context.Background(), "default", "api-key", &types.SecretUpdate{ + ExpectedResourceVersion: &version, + }) + + assert.Nil(t, result) + require.Error(t, err) + assert.True(t, types.IsConflict(err)) +} + +func TestSecretUpdateRejectsEmptyValue(t *testing.T) { + client, store := newTestSecretClient() + store.Insert("default", &types.Secret{Name: "api-key", ResourceVersion: 1}) + emptyValue := "" + + result, err := client.Update(context.Background(), "default", "api-key", &types.SecretUpdate{Value: &emptyValue}) + + assert.Nil(t, result) + require.Error(t, err) + assert.True(t, types.IsInvalidArgument(err)) +} + +func TestSecretUpdateNotFound(t *testing.T) { + client, _ := newTestSecretClient() + + result, err := client.Update(context.Background(), "default", "missing", &types.SecretUpdate{}) + + assert.Nil(t, result) + require.Error(t, err) + assert.True(t, types.IsNotFound(err)) +} + +func TestSecretUpdateRejectsNilUpdate(t *testing.T) { + client, _ := newTestSecretClient() + + result, err := client.Update(context.Background(), "default", "api-key", nil) + + assert.Nil(t, result) + require.Error(t, err) + assert.True(t, types.IsInvalidArgument(err)) +} diff --git a/openshell/v1/internal/converter/secret.go b/openshell/v1/internal/converter/secret.go new file mode 100644 index 0000000..c132cce --- /dev/null +++ b/openshell/v1/internal/converter/secret.go @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package converter + +import ( + "github.com/ai-openshell/sdk-go/openshell/v1/types" + pb "github.com/ai-openshell/sdk-go/proto/openshellv1" +) + +// SecretFromProto converts secret metadata into its SDK representation. +func SecretFromProto(secret *pb.Secret) *types.Secret { + if secret == nil { + return nil + } + + result := &types.Secret{ + Description: secret.GetDescription(), + ValueUpdateTime: TimeFromProto(secret.GetValueUpdateTime()), + } + if metadata := secret.GetMetadata(); metadata != nil { + result.ID = metadata.GetId() + result.Name = metadata.GetName() + result.CreatedAt = TimeFromProto(metadata.GetCreatedTime()) + result.Labels = CopyStringMap(metadata.GetLabels()) + result.Annotations = CopyStringMap(metadata.GetAnnotations()) + result.ResourceVersion = metadata.GetResourceVersion() + result.Workspace = metadata.GetWorkspace() + result.DeletionTimestamp = TimePtrFromProto(metadata.GetDeletionTime()) + } + if refreshUse := secret.GetRefreshUse(); refreshUse != nil { + result.RefreshUse = &types.SecretRefreshUse{ + AllowedEndpoints: CopyStringSlice(refreshUse.GetAllowedEndpoints()), + } + } + return result +} + +// SecretUpdateToProto converts a partial SDK secret update into its protobuf +// representation. Workspace scope and name are populated by the client. +func SecretUpdateToProto(update *types.SecretUpdate) *pb.UpdateSecretRequest { + if update == nil { + return nil + } + + request := &pb.UpdateSecretRequest{ + Value: copyStringPtr(update.Value), + Description: copyStringPtr(update.Description), + ExpectedResourceVersion: copyUint64Ptr(update.ExpectedResourceVersion), + RequestId: update.RequestID, + } + if update.Labels != nil { + request.Labels = &pb.SecretLabels{Labels: CopyStringMap(update.Labels)} + } + return request +} + +func copyStringPtr(value *string) *string { + if value == nil { + return nil + } + result := *value + return &result +} + +func copyUint64Ptr(value *uint64) *uint64 { + if value == nil { + return nil + } + result := *value + return &result +} diff --git a/openshell/v1/internal/converter/secret_test.go b/openshell/v1/internal/converter/secret_test.go new file mode 100644 index 0000000..4d018b8 --- /dev/null +++ b/openshell/v1/internal/converter/secret_test.go @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package converter + +import ( + "testing" + "time" + + "github.com/ai-openshell/sdk-go/openshell/v1/types" + dm "github.com/ai-openshell/sdk-go/proto/datamodelv1" + pb "github.com/ai-openshell/sdk-go/proto/openshellv1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func TestSecretFromProto(t *testing.T) { + createdAt := time.Date(2026, time.November, 25, 7, 23, 0, 0, time.UTC) + updatedAt := createdAt.Add(time.Hour) + secret := &pb.Secret{ + Metadata: &dm.ObjectMeta{ + Id: "secret-1", + Name: "api-key", + CreatedTime: timestamppb.New(createdAt), + Labels: map[string]string{"environment": "production"}, + Annotations: map[string]string{"owner": "platform"}, + ResourceVersion: 7, + Workspace: "default", + }, + Description: "provider API key", + RefreshUse: &pb.SecretRefreshUse{ + AllowedEndpoints: []string{"https://auth.example.com/token"}, + }, + ValueUpdateTime: timestamppb.New(updatedAt), + } + + result := SecretFromProto(secret) + + require.NotNil(t, result) + assert.Equal(t, "secret-1", result.ID) + assert.Equal(t, "api-key", result.Name) + assert.Equal(t, createdAt, result.CreatedAt) + assert.Equal(t, uint64(7), result.ResourceVersion) + assert.Equal(t, "default", result.Workspace) + assert.Equal(t, "provider API key", result.Description) + assert.Equal(t, updatedAt, result.ValueUpdateTime) + assert.Equal(t, map[string]string{"environment": "production"}, result.Labels) + assert.Equal(t, map[string]string{"owner": "platform"}, result.Annotations) + require.NotNil(t, result.RefreshUse) + assert.Equal(t, []string{"https://auth.example.com/token"}, result.RefreshUse.AllowedEndpoints) +} + +func TestSecretFromProtoDeepCopiesCollections(t *testing.T) { + secret := &pb.Secret{ + Metadata: &dm.ObjectMeta{ + Labels: map[string]string{"environment": "production"}, + Annotations: map[string]string{"owner": "platform"}, + }, + RefreshUse: &pb.SecretRefreshUse{AllowedEndpoints: []string{"https://auth.example.com/token"}}, + } + + result := SecretFromProto(secret) + secret.Metadata.Labels["environment"] = "mutated" + secret.Metadata.Annotations["owner"] = "mutated" + secret.RefreshUse.AllowedEndpoints[0] = "https://mutated.example.com" + + assert.Equal(t, "production", result.Labels["environment"]) + assert.Equal(t, "platform", result.Annotations["owner"]) + assert.Equal(t, "https://auth.example.com/token", result.RefreshUse.AllowedEndpoints[0]) +} + +func TestSecretFromProtoNil(t *testing.T) { + assert.Nil(t, SecretFromProto(nil)) +} + +func TestSecretUpdateToProto(t *testing.T) { + value := "new-value" + description := "rotated" + version := uint64(12) + update := &types.SecretUpdate{ + Value: &value, + Description: &description, + Labels: map[string]string{"rotation": "complete"}, + ExpectedResourceVersion: &version, + RequestID: "934a7e0d-d9ba-4c7e-b606-e2e686768093", + } + + request := SecretUpdateToProto(update) + + require.NotNil(t, request) + require.NotNil(t, request.Value) + require.NotNil(t, request.Description) + require.NotNil(t, request.Labels) + require.NotNil(t, request.ExpectedResourceVersion) + assert.Equal(t, value, *request.Value) + assert.Equal(t, description, *request.Description) + assert.Equal(t, map[string]string{"rotation": "complete"}, request.Labels.Labels) + assert.Equal(t, version, *request.ExpectedResourceVersion) + assert.Equal(t, update.RequestID, request.RequestId) + + value = "mutated" + description = "mutated" + version = 99 + update.Labels["rotation"] = "mutated" + assert.Equal(t, "new-value", *request.Value) + assert.Equal(t, "rotated", *request.Description) + assert.Equal(t, uint64(12), *request.ExpectedResourceVersion) + assert.Equal(t, "complete", request.Labels.Labels["rotation"]) +} + +func TestSecretUpdateToProtoPreservesPresence(t *testing.T) { + request := SecretUpdateToProto(&types.SecretUpdate{Labels: map[string]string{}}) + + require.NotNil(t, request.Labels) + assert.Empty(t, request.Labels.Labels) + assert.Nil(t, request.Value) + assert.Nil(t, request.Description) + assert.Nil(t, request.ExpectedResourceVersion) +} + +func TestSecretUpdateToProtoNil(t *testing.T) { + assert.Nil(t, SecretUpdateToProto(nil)) +} diff --git a/openshell/v1/secret.go b/openshell/v1/secret.go new file mode 100644 index 0000000..9dfb798 --- /dev/null +++ b/openshell/v1/secret.go @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + + "github.com/ai-openshell/sdk-go/openshell/v1/types" +) + +// Secret is workspace-scoped secret metadata. +type Secret = types.Secret + +// SecretRefreshUse describes how a secret may be used as provider refresh material. +type SecretRefreshUse = types.SecretRefreshUse + +// SecretUpdate describes a partial secret update. +type SecretUpdate = types.SecretUpdate + +// SecretInterface defines operations for updating workspace secrets. +type SecretInterface interface { + Update(ctx context.Context, workspace, name string, update *SecretUpdate) (*Secret, error) +} diff --git a/openshell/v1/secret_client.go b/openshell/v1/secret_client.go new file mode 100644 index 0000000..99ea784 --- /dev/null +++ b/openshell/v1/secret_client.go @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/converter" + pb "github.com/ai-openshell/sdk-go/proto/openshellv1" + "google.golang.org/grpc" +) + +type secretClient struct { + client pb.OpenShellClient +} + +func newSecretClient(conn grpc.ClientConnInterface) *secretClient { + return &secretClient{client: pb.NewOpenShellClient(conn)} +} + +func (s *secretClient) Update(ctx context.Context, workspace, name string, update *SecretUpdate) (*Secret, error) { + if update == nil { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: "secret update must not be nil"} + } + + request := converter.SecretUpdateToProto(update) + request.WorkspaceScope = namedWorkspaceScope(workspace) + request.Name = name + response, err := s.client.UpdateSecret(ctx, request) + if err != nil { + return nil, converter.FromGRPCError(err) + } + return converter.SecretFromProto(response.GetSecret()), nil +} diff --git a/openshell/v1/secret_client_test.go b/openshell/v1/secret_client_test.go new file mode 100644 index 0000000..4598b30 --- /dev/null +++ b/openshell/v1/secret_client_test.go @@ -0,0 +1,151 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + "net" + "sync" + "testing" + + dm "github.com/ai-openshell/sdk-go/proto/datamodelv1" + pb "github.com/ai-openshell/sdk-go/proto/openshellv1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" +) + +type mockSecretServer struct { + pb.UnimplementedOpenShellServer + mu sync.Mutex + lastRequest *pb.UpdateSecretRequest + updateErr error +} + +func (s *mockSecretServer) UpdateSecret(_ context.Context, request *pb.UpdateSecretRequest) (*pb.SecretResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.lastRequest = request + if s.updateErr != nil { + return nil, s.updateErr + } + return &pb.SecretResponse{Secret: &pb.Secret{ + Metadata: &dm.ObjectMeta{ + Id: "secret-1", + Name: request.GetName(), + Labels: request.GetLabels().GetLabels(), + ResourceVersion: request.GetExpectedResourceVersion() + 1, + Workspace: request.GetWorkspaceScope().GetWorkspace(), + }, + Description: request.GetDescription(), + }}, nil +} + +func setupSecretTest(t *testing.T, mock *mockSecretServer) (*secretClient, func()) { + t.Helper() + listener := bufconn.Listen(bufSize) + server := grpc.NewServer() + pb.RegisterOpenShellServer(server, mock) + go func() { _ = server.Serve(listener) }() + + connection, err := grpc.NewClient("passthrough:///bufconn", + grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) { + return listener.Dial() + }), + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + require.NoError(t, err) + + return newSecretClient(connection), func() { + _ = connection.Close() + server.Stop() + } +} + +func TestSecretUpdate(t *testing.T) { + mock := &mockSecretServer{} + client, cleanup := setupSecretTest(t, mock) + defer cleanup() + + value := "new-value" + description := "rotated" + version := uint64(4) + result, err := client.Update(context.Background(), "default", "api-key", &SecretUpdate{ + Value: &value, + Description: &description, + Labels: map[string]string{"environment": "production"}, + ExpectedResourceVersion: &version, + RequestID: "934a7e0d-d9ba-4c7e-b606-e2e686768093", + }) + + require.NoError(t, err) + require.NotNil(t, result) + assert.Equal(t, "secret-1", result.ID) + assert.Equal(t, "api-key", result.Name) + assert.Equal(t, "default", result.Workspace) + assert.Equal(t, uint64(5), result.ResourceVersion) + assert.Equal(t, "rotated", result.Description) + assert.Equal(t, map[string]string{"environment": "production"}, result.Labels) + + mock.mu.Lock() + request := mock.lastRequest + mock.mu.Unlock() + require.NotNil(t, request) + assert.Equal(t, "default", request.GetWorkspaceScope().GetWorkspace()) + assert.Equal(t, "api-key", request.GetName()) + require.NotNil(t, request.Value) + assert.Equal(t, "new-value", *request.Value) + require.NotNil(t, request.Description) + assert.Equal(t, "rotated", *request.Description) + require.NotNil(t, request.Labels) + assert.Equal(t, map[string]string{"environment": "production"}, request.Labels.Labels) + require.NotNil(t, request.ExpectedResourceVersion) + assert.Equal(t, uint64(4), *request.ExpectedResourceVersion) + assert.Equal(t, "934a7e0d-d9ba-4c7e-b606-e2e686768093", request.GetRequestId()) +} + +func TestSecretUpdatePreservesAbsentFields(t *testing.T) { + mock := &mockSecretServer{} + client, cleanup := setupSecretTest(t, mock) + defer cleanup() + + _, err := client.Update(context.Background(), "default", "api-key", &SecretUpdate{}) + require.NoError(t, err) + + mock.mu.Lock() + request := mock.lastRequest + mock.mu.Unlock() + assert.Nil(t, request.Value) + assert.Nil(t, request.Description) + assert.Nil(t, request.Labels) + assert.Nil(t, request.ExpectedResourceVersion) +} + +func TestSecretUpdateRejectsNilUpdate(t *testing.T) { + mock := &mockSecretServer{} + client, cleanup := setupSecretTest(t, mock) + defer cleanup() + + result, err := client.Update(context.Background(), "default", "api-key", nil) + + assert.Nil(t, result) + require.Error(t, err) + assert.True(t, IsInvalidArgument(err)) +} + +func TestSecretUpdateConvertsGRPCError(t *testing.T) { + mock := &mockSecretServer{updateErr: status.Error(codes.NotFound, "secret not found")} + client, cleanup := setupSecretTest(t, mock) + defer cleanup() + + result, err := client.Update(context.Background(), "default", "missing", &SecretUpdate{}) + + assert.Nil(t, result) + require.Error(t, err) + assert.True(t, IsNotFound(err)) +} diff --git a/openshell/v1/types/secret.go b/openshell/v1/types/secret.go new file mode 100644 index 0000000..945a346 --- /dev/null +++ b/openshell/v1/types/secret.go @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package types + +import "time" + +// Secret is workspace-scoped secret metadata. Secret values are never +// returned by update responses. +type Secret struct { + ID string + Name string + CreatedAt time.Time + Labels map[string]string + Annotations map[string]string + ResourceVersion uint64 + Workspace string + DeletionTimestamp *time.Time + Description string + RefreshUse *SecretRefreshUse + ValueUpdateTime time.Time +} + +// SecretRefreshUse describes how a secret may be used as provider refresh +// material. It is fixed when the secret is created. +type SecretRefreshUse struct { + AllowedEndpoints []string +} + +// SecretUpdate describes a partial secret update. Nil pointer fields are left +// unchanged. A non-nil empty Labels map removes all labels. +type SecretUpdate struct { + Value *string + Description *string + Labels map[string]string + ExpectedResourceVersion *uint64 + RequestID string +}