feat(secrets): copy and move secrets between global and workspace scopes (#2583)

This commit is contained in:
Clément Fiere
2026-08-13 14:37:46 +02:00
committed by GitHub
parent 6aeaf4ad22
commit a95a0e1bd8
43 changed files with 6653 additions and 323 deletions
@@ -18,10 +18,12 @@ type inMemorySecretStore struct {
var _ secrets.SecretStore = (*inMemorySecretStore)(nil)
var _ secrets.ScopedSecretStore = (*inMemorySecretStore)(nil)
// newInMemorySecretStore returns an empty in-memory secret store for testing.
func newInMemorySecretStore() *inMemorySecretStore {
return &inMemorySecretStore{store: make(map[string]*secrets.SecretWithValue)}
}
// Create stores the secret, returning the injected error when set.
func (s *inMemorySecretStore) Create(_ context.Context, secret *secrets.SecretWithValue) error {
if s.err != nil {
return s.err
@@ -33,6 +35,7 @@ func (s *inMemorySecretStore) Create(_ context.Context, secret *secrets.SecretWi
return nil
}
// Get returns the stored secret for the given ID, or an error when absent.
func (s *inMemorySecretStore) Get(_ context.Context, id string) (*secrets.Secret, error) {
if sw, ok := s.store[id]; ok {
return &sw.Secret, nil
@@ -40,6 +43,7 @@ func (s *inMemorySecretStore) Get(_ context.Context, id string) (*secrets.Secret
return nil, fmt.Errorf("not found")
}
// Reveal returns the plaintext value for the given ID, or an error when absent.
func (s *inMemorySecretStore) Reveal(_ context.Context, id string) (string, error) {
if sw, ok := s.store[id]; ok {
return sw.Value, nil
@@ -47,15 +51,23 @@ func (s *inMemorySecretStore) Reveal(_ context.Context, id string) (string, erro
return "", fmt.Errorf("not found")
}
// Update is a no-op for the in-memory store.
func (s *inMemorySecretStore) Update(_ context.Context, _ string, _ *secrets.UpdateSecretRequest) error {
return nil
}
// Delete is a no-op for the in-memory store.
func (s *inMemorySecretStore) Delete(_ context.Context, _ string) error { return nil }
// List returns no items for the in-memory store.
func (s *inMemorySecretStore) List(_ context.Context) ([]*secrets.SecretListItem, error) {
return nil, nil
}
// Close is a no-op for the in-memory store.
func (s *inMemorySecretStore) Close() error { return nil }
// ListScoped returns stored secrets filtered by the requested scope and workspace.
func (s *inMemorySecretStore) ListScoped(_ context.Context, opts secrets.SecretListOptions) ([]*secrets.SecretListItem, error) {
items := make([]*secrets.SecretListItem, 0, len(s.store))
for _, stored := range s.store {
@@ -77,6 +89,7 @@ func (s *inMemorySecretStore) ListScoped(_ context.Context, opts secrets.SecretL
return items, nil
}
// GetForWorkspace returns the secret when it is global or belongs to the given workspace.
func (s *inMemorySecretStore) GetForWorkspace(_ context.Context, id, workspaceID string) (*secrets.Secret, error) {
secret, err := s.Get(context.Background(), id)
if err != nil {
@@ -88,6 +101,7 @@ func (s *inMemorySecretStore) GetForWorkspace(_ context.Context, id, workspaceID
return secret, nil
}
// RevealGlobal reveals a global secret's value, rejecting workspace-scoped secrets.
func (s *inMemorySecretStore) RevealGlobal(ctx context.Context, id string) (string, error) {
secret, err := s.Get(ctx, id)
if err != nil {
@@ -99,6 +113,7 @@ func (s *inMemorySecretStore) RevealGlobal(ctx context.Context, id string) (stri
return s.Reveal(ctx, id)
}
// RevealForWorkspace reveals a secret's value after confirming workspace access.
func (s *inMemorySecretStore) RevealForWorkspace(ctx context.Context, id, workspaceID string) (string, error) {
if _, err := s.GetForWorkspace(ctx, id, workspaceID); err != nil {
return "", err
@@ -106,6 +121,7 @@ func (s *inMemorySecretStore) RevealForWorkspace(ctx context.Context, id, worksp
return s.Reveal(ctx, id)
}
// DeleteWorkspaceSecrets removes all secrets belonging to the given workspace.
func (s *inMemorySecretStore) DeleteWorkspaceSecrets(_ context.Context, workspaceID string) error {
for id, stored := range s.store {
if stored.Scope == secrets.ScopeWorkspace && stored.WorkspaceID == workspaceID {
@@ -115,6 +131,7 @@ func (s *inMemorySecretStore) DeleteWorkspaceSecrets(_ context.Context, workspac
return nil
}
// TestPersistAuthToken verifies persistAuthToken stores the instance auth token as a secret, records its ID in execution metadata, and no-ops when the token or store is absent.
func TestPersistAuthToken(t *testing.T) {
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
@@ -202,6 +219,7 @@ func TestPersistAuthToken(t *testing.T) {
})
}
// TestPersistRuntimeSecrets verifies persistRuntimeSecrets stores the auth token and bootstrap nonce as secrets and records both IDs so they can be revealed later.
func TestPersistRuntimeSecrets(t *testing.T) {
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
store := newInMemorySecretStore()
+54 -1
View File
@@ -5,6 +5,7 @@ package backendapp
import (
"context"
"errors"
"flag"
"fmt"
"net"
@@ -107,6 +108,7 @@ import (
workflowengine "github.com/kandev/kandev/internal/workflow/engine"
taskhandlers "github.com/kandev/kandev/internal/task/handlers"
repoerrors "github.com/kandev/kandev/internal/task/repository/repoerrors"
tasksqlite "github.com/kandev/kandev/internal/task/repository/sqlite"
taskservice "github.com/kandev/kandev/internal/task/service"
workflowservice "github.com/kandev/kandev/internal/workflow/service"
@@ -150,6 +152,9 @@ type backendFlags struct {
Version bool
}
// parseBackendFlags parses the `kandev __backend` command-line flags into a
// backendFlags struct, returning the parsed flags, a usage printer, and any
// parse error.
func parseBackendFlags(args []string) (backendFlags, func(), error) {
flags := flag.NewFlagSet("kandev __backend", flag.ContinueOnError)
flags.SetOutput(os.Stderr)
@@ -269,6 +274,9 @@ func Run(args []string, build BuildInfo) int {
return 0
}
// acquireRuntimeStateOwnership acquires the advisory ownership lock over the
// backend's runtime state (home dir and database), preventing a second backend
// instance from acting on the same state.
func acquireRuntimeStateOwnership(cfg *config.Config) (*ownershiplock.Owner, error) {
targets, err := ownershiplock.Targets(cfg.ResolvedHomeDir(), cfg.Database.Driver, cfg.Database.Path)
if err != nil {
@@ -277,6 +285,8 @@ func acquireRuntimeStateOwnership(cfg *config.Config) (*ownershiplock.Owner, err
return ownershiplock.Acquire(targets)
}
// setBuildInfo stamps the package-level build variables with the provided
// build metadata, skipping fields that were not populated.
func setBuildInfo(build BuildInfo) {
if build.Version != "" {
Version = build.Version
@@ -309,6 +319,9 @@ func run(cfg *config.Config, log *logger.Logger, cleanups *[]func() error, runCl
return startServices(ctx, cfg, log, addCleanup, eventBus, runCleanups)
}
// applyStartupRuntimeFlags resolves persisted runtime-flag overrides and
// applies them to the config, returning false if resolution fails. It is a
// no-op when no runtime-flag repository is configured.
func applyStartupRuntimeFlags(ctx context.Context, cfg *config.Config, repos *Repositories, log *logger.Logger) bool {
if repos.RuntimeFlags == nil {
return true
@@ -1004,6 +1017,8 @@ func startGatewayAndServe(
return true
}
// serverListenAddr formats the host and port into a listen address, binding
// all interfaces when host is empty.
func serverListenAddr(host string, port int) string {
host = strings.TrimSpace(host)
if host == "" {
@@ -1012,6 +1027,8 @@ func serverListenAddr(host string, port int) string {
return net.JoinHostPort(host, fmt.Sprint(port))
}
// serverProbeAddr rewrites a listen address into a loopback address suitable
// for local probing, mapping wildcard hosts to 127.0.0.1 / ::1.
func serverProbeAddr(listenAddr string) string {
host, port, err := net.SplitHostPort(listenAddr)
if err != nil {
@@ -1163,6 +1180,8 @@ func initOfficeServices(
return runProcessorSvc, true
}
// newRunProcessorService constructs the office run-processor service, wiring
// its workspace, task, PR, and task-starter adapters to the backend services.
func newRunProcessorService(
cfg *config.Config,
repos *Repositories,
@@ -1284,12 +1303,14 @@ type officeRoutingRepoAdapter struct {
repo *officesqlite.Repository
}
// GetWorkspaceRouting returns the routing configuration for a workspace.
func (a *officeRoutingRepoAdapter) GetWorkspaceRouting(
ctx context.Context, workspaceID string,
) (*routing.WorkspaceConfig, error) {
return a.repo.GetWorkspaceRouting(ctx, workspaceID)
}
// ListProviderHealth returns the provider health statuses for a workspace.
func (a *officeRoutingRepoAdapter) ListProviderHealth(
ctx context.Context, workspaceID string,
) ([]officemodels.ProviderHealth, error) {
@@ -1302,6 +1323,7 @@ type schedulerTaskStarterAdapter struct {
orch *orchestrator.Service
}
// StartTask starts a task on the orchestrator with the given launch parameters.
func (a *schedulerTaskStarterAdapter) StartTask(
ctx context.Context,
taskID, agentProfileID, executorID, executorProfileID string,
@@ -1314,6 +1336,8 @@ func (a *schedulerTaskStarterAdapter) StartTask(
return err
}
// StartTaskWithRoute starts a task on the orchestrator with an explicit launch
// context and route override.
func (a *schedulerTaskStarterAdapter) StartTaskWithRoute(
ctx context.Context,
taskID, agentProfileID string,
@@ -1472,6 +1496,8 @@ type runsServiceEngineAdapter struct {
svc *runsservice.Service
}
// QueueRun enqueues a run, translating the engine's QueueRunRequest into the
// runs-service request shape.
func (a *runsServiceEngineAdapter) QueueRun(ctx context.Context, req workflowengine.QueueRunRequest) error {
return a.svc.QueueRun(ctx, runsservice.QueueRunRequest{
AgentProfileID: req.AgentProfileID,
@@ -1578,10 +1604,14 @@ type officeFailureInboxAdapter struct {
svc *officeservice.Service
}
// newOfficeFailureInboxAdapter wraps an office service in the dashboard
// failure-inbox adapter so its rows can be served through the dashboard API.
func newOfficeFailureInboxAdapter(svc *officeservice.Service) *officeFailureInboxAdapter {
return &officeFailureInboxAdapter{svc: svc}
}
// ListFailedRunInboxRows returns the failed-run inbox rows for a workspace and
// user, mapped into the dashboard failure-inbox row type.
func (a *officeFailureInboxAdapter) ListFailedRunInboxRows(
ctx context.Context, workspaceID, userID string,
) ([]officedashboard.FailureInboxRow, error) {
@@ -1604,6 +1634,8 @@ func (a *officeFailureInboxAdapter) ListFailedRunInboxRows(
return out, nil
}
// ListPausedAgentInboxRows returns the paused-agent inbox rows for a workspace
// and user, mapped into the dashboard failure-inbox row type.
func (a *officeFailureInboxAdapter) ListPausedAgentInboxRows(
ctx context.Context, workspaceID, userID string,
) ([]officedashboard.FailureInboxRow, error) {
@@ -1855,6 +1887,8 @@ func buildOfficeDashboardService(
// buildHTTPServer creates the HTTP server with all routes registered.
var newInterimSettingsInterlockToken = httpmw.NewInterimSettingsInterlockToken
// resolvedHTTPPort returns the configured HTTP server port, falling back to
// the default backend port when unset.
func resolvedHTTPPort(cfg *config.Config) int {
if cfg.Server.Port != 0 {
return cfg.Server.Port
@@ -1862,6 +1896,8 @@ func resolvedHTTPPort(cfg *config.Config) int {
return ports.Backend
}
// buildHTTPServer creates the HTTP server with all middleware and routes
// registered against the gateway and service layer.
func buildHTTPServer(
cfg *config.Config,
log *logger.Logger,
@@ -1927,7 +1963,24 @@ func buildHTTPServer(
router.Use(integrationWorkspaceScopeMiddleware(services.Auth, services.Task))
secretsSvc := secrets.NewService(userSecretStore, log)
secretsSvc.SetWorkspaceAuthorizer(services.Task.AuthorizeWorkspaceAccess)
// Workspace classification happens here, at the wiring boundary, where both
// packages are importable: the task service's not-found sentinel becomes
// the secrets sentinel (404), while raw lookup/storage errors pass through
// unclassified (sanitized 500).
secretsSvc.SetWorkspaceAuthorizer(func(ctx context.Context, workspaceID string) error {
err := services.Task.AuthorizeWorkspaceAccess(ctx, workspaceID)
if errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
return secrets.ErrWorkspaceAccessDenied
}
return err
})
secretsSvc.SetWorkspaceExistenceChecker(func(ctx context.Context, workspaceID string) error {
_, err := services.Task.GetWorkspace(ctx, workspaceID)
if errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
return secrets.ErrWorkspaceAccessDenied
}
return err
})
registerRoutes(routeParams{
router: router,
gateway: gateway,
@@ -0,0 +1,335 @@
package secrets
import (
"context"
"encoding/json"
"errors"
"fmt"
"testing"
"github.com/kandev/kandev/internal/auth/authn"
)
// testCopyMoveService builds a service over the user-visible SQLite store with
// an authorizer and existence checker that allow the listed workspaces.
func testCopyMoveService(t *testing.T, allowed map[string]bool) *Service {
t.Helper()
store := newTestSQLiteStore(t)
svc := NewService(NewUserVisibleStore(store), nil)
svc.SetWorkspaceAuthorizer(func(_ context.Context, workspaceID string) error {
if allowed[workspaceID] {
return nil
}
return ErrWorkspaceAccessDenied
})
svc.SetWorkspaceExistenceChecker(func(_ context.Context, workspaceID string) error {
if allowed[workspaceID] {
return nil
}
return ErrWorkspaceAccessDenied
})
return svc
}
// decodeCopyRequest unmarshals a JSON copy/move request body for testing.
func decodeCopyRequest(t *testing.T, body string) *CopySecretRequest {
t.Helper()
var req CopySecretRequest
if err := json.Unmarshal([]byte(body), &req); err != nil {
t.Fatalf("decode %s: %v", body, err)
}
return &req
}
// TestServiceCopy_GlobalToWorkspaceUsesSourceNameWhenOmitted verifies a global-to-workspace copy with no explicit name keeps the source name and value and retains the source.
func TestServiceCopy_GlobalToWorkspaceUsesSourceNameWhenOmitted(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
ctx := context.Background()
if _, err := svc.Create(ctx, &CreateSecretRequest{Name: "API Key", Value: "v1"}); err != nil {
t.Fatalf("create: %v", err)
}
item, err := svc.Copy(ctx, globalID(t, svc, "API Key"), "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-a"}`))
if err != nil {
t.Fatalf("Copy: %v", err)
}
if item.Scope != ScopeWorkspace || item.WorkspaceID != "workspace-a" || item.Name != "API Key" {
t.Fatalf("item = %+v", item)
}
if item.CreatedAt.IsZero() || item.UpdatedAt.IsZero() {
t.Fatalf("item timestamps zero: %+v", item)
}
value, err := svc.RevealForWorkspace(ctx, item.ID, "workspace-a")
if err != nil {
t.Fatalf("reveal: %v", err)
}
if value != "v1" {
t.Fatalf("value = %q, want v1", value)
}
// Source retained.
global, err := svc.List(ctx)
if err != nil || len(global) != 1 {
t.Fatalf("global list after copy = %+v, %v", global, err)
}
}
// TestServiceCopy_WorkspaceToGlobalWithExplicitName verifies a workspace-to-global copy with an explicit name keeps the source intact.
func TestServiceCopy_WorkspaceToGlobalWithExplicitName(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
ctx := context.Background()
w := mustCreateViaService(t, svc, "ws", "v2", ScopeWorkspace, "workspace-a")
item, err := svc.Copy(ctx, w.ID, "workspace-a", decodeCopyRequest(t, `{"target_scope":"global","name":"renamed"}`))
if err != nil {
t.Fatalf("Copy: %v", err)
}
if item.Scope != ScopeGlobal || item.Name != "renamed" {
t.Fatalf("item = %+v", item)
}
if _, err := svc.GetWorkspaceSecret(ctx, w.ID, "workspace-a"); err != nil {
t.Fatalf("source lost after copy: %v", err)
}
}
// TestServiceCopy_WorkspaceToWorkspace verifies a workspace-to-workspace copy lands in the target workspace.
func TestServiceCopy_WorkspaceToWorkspace(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true, "workspace-b": true})
ctx := context.Background()
w := mustCreateViaService(t, svc, "ws", "v3", ScopeWorkspace, "workspace-a")
item, err := svc.Copy(ctx, w.ID, "workspace-a", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-b","name":"to-b"}`))
if err != nil {
t.Fatalf("Copy: %v", err)
}
if item.WorkspaceID != "workspace-b" {
t.Fatalf("item workspace = %q", item.WorkspaceID)
}
}
// TestServiceMove_WorkspaceToGlobalRemovesSource verifies moving a workspace secret to global removes the source.
func TestServiceMove_WorkspaceToGlobalRemovesSource(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
ctx := context.Background()
w := mustCreateViaService(t, svc, "ws", "v4", ScopeWorkspace, "workspace-a")
item, err := svc.Move(ctx, w.ID, "workspace-a", decodeCopyRequest(t, `{"target_scope":"global","name":"moved"}`))
if err != nil {
t.Fatalf("Move: %v", err)
}
if item.Scope != ScopeGlobal {
t.Fatalf("item scope = %q", item.Scope)
}
if _, err := svc.GetWorkspaceSecret(ctx, w.ID, "workspace-a"); !errors.Is(err, ErrNotFound) {
t.Fatalf("source still present after move: %v", err)
}
}
// TestServiceMove_GlobalToWorkspaceRemovesSource verifies moving a global secret into a workspace removes the source.
func TestServiceMove_GlobalToWorkspaceRemovesSource(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
ctx := context.Background()
g := mustCreateViaService(t, svc, "g", "v5", ScopeGlobal, "")
item, err := svc.Move(ctx, g.ID, "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-a"}`))
if err != nil {
t.Fatalf("Move: %v", err)
}
if item.WorkspaceID != "workspace-a" {
t.Fatalf("item workspace = %q", item.WorkspaceID)
}
if _, err := svc.Get(ctx, g.ID); !errors.Is(err, ErrNotFound) {
t.Fatalf("source still present after move: %v", err)
}
}
// TestServiceCopy_NamePresenceSemantics verifies null, empty, whitespace, and over-long target names are rejected as ErrSecretValidation.
func TestServiceCopy_NamePresenceSemantics(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
ctx := context.Background()
g := mustCreateViaService(t, svc, "API Key", "v", ScopeGlobal, "")
t.Run("null is a validation error", func(t *testing.T) {
_, err := svc.Copy(ctx, g.ID, "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-a","name":null}`))
if !errors.Is(err, ErrSecretValidation) {
t.Fatalf("err = %v, want ErrSecretValidation", err)
}
})
t.Run("empty string is a validation error", func(t *testing.T) {
_, err := svc.Copy(ctx, g.ID, "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-a","name":""}`))
if !errors.Is(err, ErrSecretValidation) {
t.Fatalf("err = %v, want ErrSecretValidation", err)
}
})
t.Run("whitespace is a validation error", func(t *testing.T) {
_, err := svc.Copy(ctx, g.ID, "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-a","name":" "}`))
if !errors.Is(err, ErrSecretValidation) {
t.Fatalf("err = %v, want ErrSecretValidation", err)
}
})
t.Run("over 100 UTF-8 bytes is a validation error", func(t *testing.T) {
long := ""
for len(long) <= 100 {
long += "é" // 2 bytes per code point
}
req := decodeCopyRequest(t, fmt.Sprintf(`{"target_scope":"workspace","target_workspace_id":"workspace-a","name":%q}`, long))
_, err := svc.Copy(ctx, g.ID, "", req)
if !errors.Is(err, ErrSecretValidation) {
t.Fatalf("err = %v, want ErrSecretValidation", err)
}
})
}
// TestServiceCopy_SameScopeRejected verifies copying within the same scope returns ErrSecretValidation.
func TestServiceCopy_SameScopeRejected(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
ctx := context.Background()
g := mustCreateViaService(t, svc, "g", "v", ScopeGlobal, "")
w := mustCreateViaService(t, svc, "w", "v", ScopeWorkspace, "workspace-a")
if _, err := svc.Copy(ctx, g.ID, "", decodeCopyRequest(t, `{"target_scope":"global"}`)); !errors.Is(err, ErrSecretValidation) {
t.Fatalf("global->global err = %v, want ErrSecretValidation", err)
}
if _, err := svc.Copy(ctx, w.ID, "workspace-a", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-a"}`)); !errors.Is(err, ErrSecretValidation) {
t.Fatalf("workspace A->A err = %v, want ErrSecretValidation", err)
}
}
// TestServiceCopy_NameConflict verifies a target-name collision in the destination scope returns ErrSecretNameConflict.
func TestServiceCopy_NameConflict(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
ctx := context.Background()
// "taken" lives in the workspace target scope.
mustCreateViaService(t, svc, "taken", "other", ScopeWorkspace, "workspace-a")
g := mustCreateViaService(t, svc, "g", "v", ScopeGlobal, "")
_, err := svc.Copy(ctx, g.ID, "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-a","name":"taken"}`))
if !errors.Is(err, ErrSecretNameConflict) {
t.Fatalf("err = %v, want ErrSecretNameConflict", err)
}
}
// TestServiceCopy_MissingSourceIsNotFound verifies an unknown source ID returns ErrNotFound.
func TestServiceCopy_MissingSourceIsNotFound(t *testing.T) {
svc := testCopyMoveService(t, nil)
_, err := svc.Copy(context.Background(), "missing", "", decodeCopyRequest(t, `{"target_scope":"global"}`))
if !errors.Is(err, ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
}
// TestServiceCopy_UnauthorizedSourceIsDenied verifies revoking source-workspace access makes Copy fail with ErrWorkspaceAccessDenied.
func TestServiceCopy_UnauthorizedSourceIsDenied(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
ctx := context.Background()
w := mustCreateViaService(t, svc, "w", "v", ScopeWorkspace, "workspace-a")
// Revoke access to the source workspace after seeding the secret.
svc.SetWorkspaceAuthorizer(func(context.Context, string) error { return ErrWorkspaceAccessDenied })
svc.SetWorkspaceExistenceChecker(func(context.Context, string) error { return ErrWorkspaceAccessDenied })
_, err := svc.Copy(ctx, w.ID, "workspace-a", decodeCopyRequest(t, `{"target_scope":"global"}`))
if !errors.Is(err, ErrWorkspaceAccessDenied) {
t.Fatalf("err = %v, want ErrWorkspaceAccessDenied", err)
}
}
// TestServiceCopy_UnauthorizedDestinationIsDenied verifies an unallowed destination workspace returns ErrWorkspaceAccessDenied.
func TestServiceCopy_UnauthorizedDestinationIsDenied(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true}) // workspace-b not allowed
ctx := context.Background()
g := mustCreateViaService(t, svc, "g", "v", ScopeGlobal, "")
_, err := svc.Copy(ctx, g.ID, "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-b"}`))
if !errors.Is(err, ErrWorkspaceAccessDenied) {
t.Fatalf("err = %v, want ErrWorkspaceAccessDenied", err)
}
}
// TestServiceCopy_NilExistenceCheckerFailsClosed verifies a nil existence checker denies workspace targets (fails closed).
func TestServiceCopy_NilExistenceCheckerFailsClosed(t *testing.T) {
store := newTestSQLiteStore(t)
svc := NewService(NewUserVisibleStore(store), nil)
svc.SetWorkspaceAuthorizer(func(context.Context, string) error { return nil })
ctx := context.Background()
g := mustCreateViaService(t, svc, "g", "v", ScopeGlobal, "")
_, err := svc.Copy(ctx, g.ID, "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"any"}`))
if !errors.Is(err, ErrWorkspaceAccessDenied) {
t.Fatalf("err = %v, want ErrWorkspaceAccessDenied (nil checker fails closed)", err)
}
}
// TestServiceCopy_RawAuthorizerErrorPassesThroughUnclassified verifies a raw authorizer error is returned as-is rather than mapped to a sentinel.
func TestServiceCopy_RawAuthorizerErrorPassesThroughUnclassified(t *testing.T) {
store := newTestSQLiteStore(t)
svc := NewService(NewUserVisibleStore(store), nil)
rawErr := errors.New("database unreachable")
svc.SetWorkspaceAuthorizer(func(context.Context, string) error { return rawErr })
svc.SetWorkspaceExistenceChecker(func(context.Context, string) error { return nil })
ctx := context.Background()
g := mustCreateViaService(t, svc, "g", "v", ScopeGlobal, "")
_, err := svc.Copy(ctx, g.ID, "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-a"}`))
if !errors.Is(err, rawErr) {
t.Fatalf("err = %v, want the raw authorizer error (unclassified)", err)
}
if errors.Is(err, ErrNotFound) || errors.Is(err, ErrSecretValidation) || errors.Is(err, ErrWorkspaceAccessDenied) {
t.Fatalf("raw error misclassified as a sentinel: %v", err)
}
}
// TestServiceCopy_InternalSourceIDIsNotFound verifies internal (backend-owned) source IDs are rejected as ErrNotFound.
func TestServiceCopy_InternalSourceIDIsNotFound(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
_, err := svc.Copy(context.Background(), "github:user:workspace:user:access", "", decodeCopyRequest(t, `{"target_scope":"workspace","target_workspace_id":"workspace-a"}`))
if !errors.Is(err, ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
}
// TestServiceMove_CrossUserOwnershipEnforced verifies a user cannot move another user's workspace secret (ErrNotFound) while the owner can.
func TestServiceMove_CrossUserOwnershipEnforced(t *testing.T) {
svc := testCopyMoveService(t, map[string]bool{"workspace-a": true})
alice := authn.WithIdentity(context.Background(), authn.Identity{UserID: "user-a"})
bob := authn.WithIdentity(context.Background(), authn.Identity{UserID: "user-b"})
// Alice creates a workspace secret.
created, err := svc.Create(alice, &CreateSecretRequest{Name: "alice-ws", Value: "v", Scope: ScopeWorkspace, WorkspaceID: "workspace-a"})
if err != nil {
t.Fatalf("create as alice: %v", err)
}
// Bob cannot move it (store-level per-user scoping).
if _, err := svc.Move(bob, created.ID, "workspace-a", decodeCopyRequest(t, `{"target_scope":"global"}`)); !errors.Is(err, ErrNotFound) {
t.Fatalf("bob move err = %v, want ErrNotFound", err)
}
// Alice can.
if _, err := svc.Move(alice, created.ID, "workspace-a", decodeCopyRequest(t, `{"target_scope":"global","name":"alice-global"}`)); err != nil {
t.Fatalf("alice move: %v", err)
}
}
// mustCreateViaService is a small helper that returns the created item.
func mustCreateViaService(t *testing.T, svc *Service, name, value string, scope SecretScope, workspaceID string) *SecretListItem {
t.Helper()
item, err := svc.Create(context.Background(), &CreateSecretRequest{Name: name, Value: value, Scope: scope, WorkspaceID: workspaceID})
if err != nil {
t.Fatalf("create %s: %v", name, err)
}
return item
}
// globalID resolves a global secret's ID by name via List.
func globalID(t *testing.T, svc *Service, name string) string {
t.Helper()
items, err := svc.List(context.Background())
if err != nil {
t.Fatalf("list: %v", err)
}
for _, item := range items {
if item.Name == name {
return item.ID
}
}
t.Fatalf("no global secret named %s", name)
return ""
}
+172
View File
@@ -2,6 +2,8 @@ package secrets
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/gin-gonic/gin"
@@ -29,6 +31,7 @@ func RegisterRoutes(router *gin.Engine, dispatcher *ws.Dispatcher, svc *Service,
h.registerWS(dispatcher)
}
// registerHTTP registers the secrets HTTP routes under /api/v1.
func (h *Handler) registerHTTP(router *gin.Engine) {
api := router.Group("/api/v1")
api.POST("/secrets", h.httpCreateSecret)
@@ -37,18 +40,24 @@ func (h *Handler) registerHTTP(router *gin.Engine) {
api.PUT("/secrets/:id", h.httpUpdateSecret)
api.DELETE("/secrets/:id", h.httpDeleteSecret)
api.POST("/secrets/:id/reveal", h.httpRevealSecret)
api.POST("/secrets/:id/copy", h.httpCopySecret)
api.POST("/secrets/:id/move", h.httpMoveSecret)
}
// registerWS registers the secrets WebSocket actions on the dispatcher.
func (h *Handler) registerWS(dispatcher *ws.Dispatcher) {
dispatcher.RegisterFunc(ws.ActionSecretList, h.wsList)
dispatcher.RegisterFunc(ws.ActionSecretCreate, h.wsCreate)
dispatcher.RegisterFunc(ws.ActionSecretUpdate, h.wsUpdate)
dispatcher.RegisterFunc(ws.ActionSecretDelete, h.wsDelete)
dispatcher.RegisterFunc(ws.ActionSecretReveal, h.wsReveal)
dispatcher.RegisterFunc(ws.ActionSecretCopy, h.wsCopy)
dispatcher.RegisterFunc(ws.ActionSecretMove, h.wsMove)
}
// HTTP handlers
// httpCreateSecret handles POST /api/v1/secrets.
func (h *Handler) httpCreateSecret(c *gin.Context) {
var req CreateSecretRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -65,6 +74,7 @@ func (h *Handler) httpCreateSecret(c *gin.Context) {
c.JSON(http.StatusCreated, item)
}
// httpListSecrets handles GET /api/v1/secrets.
func (h *Handler) httpListSecrets(c *gin.Context) {
opts := SecretListOptions{
Scope: SecretScope(c.Query("scope")),
@@ -83,6 +93,7 @@ func (h *Handler) httpListSecrets(c *gin.Context) {
c.JSON(http.StatusOK, items)
}
// httpGetSecret handles GET /api/v1/secrets/:id.
func (h *Handler) httpGetSecret(c *gin.Context) {
id := c.Param("id")
secret, err := h.getSecret(c, id)
@@ -93,6 +104,7 @@ func (h *Handler) httpGetSecret(c *gin.Context) {
c.JSON(http.StatusOK, secret)
}
// httpUpdateSecret handles PUT /api/v1/secrets/:id.
func (h *Handler) httpUpdateSecret(c *gin.Context) {
id := c.Param("id")
var req UpdateSecretRequest
@@ -110,6 +122,7 @@ func (h *Handler) httpUpdateSecret(c *gin.Context) {
c.JSON(http.StatusOK, item)
}
// httpDeleteSecret handles DELETE /api/v1/secrets/:id.
func (h *Handler) httpDeleteSecret(c *gin.Context) {
id := c.Param("id")
if err := h.deleteSecret(c, id); err != nil {
@@ -119,6 +132,7 @@ func (h *Handler) httpDeleteSecret(c *gin.Context) {
c.Status(http.StatusNoContent)
}
// httpRevealSecret handles POST /api/v1/secrets/:id/reveal.
func (h *Handler) httpRevealSecret(c *gin.Context) {
id := c.Param("id")
value, err := h.revealSecret(c, id)
@@ -131,6 +145,7 @@ func (h *Handler) httpRevealSecret(c *gin.Context) {
// WS handlers
// wsList handles the secrets.list WebSocket action.
func (h *Handler) wsList(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
var req struct {
Scope SecretScope `json:"scope"`
@@ -152,6 +167,7 @@ func (h *Handler) wsList(ctx context.Context, msg *ws.Message) (*ws.Message, err
return ws.NewResponse(msg.ID, msg.Action, items)
}
// wsCreate handles the secrets.create WebSocket action.
func (h *Handler) wsCreate(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
var req CreateSecretRequest
if err := msg.ParsePayload(&req); err != nil {
@@ -165,6 +181,7 @@ func (h *Handler) wsCreate(ctx context.Context, msg *ws.Message) (*ws.Message, e
return ws.NewResponse(msg.ID, msg.Action, item)
}
// wsUpdate handles the secrets.update WebSocket action.
func (h *Handler) wsUpdate(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
var payload struct {
ID string `json:"id"`
@@ -182,6 +199,7 @@ func (h *Handler) wsUpdate(ctx context.Context, msg *ws.Message) (*ws.Message, e
return ws.NewResponse(msg.ID, msg.Action, item)
}
// wsDelete handles the secrets.delete WebSocket action.
func (h *Handler) wsDelete(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
var payload struct {
ID string `json:"id"`
@@ -197,6 +215,7 @@ func (h *Handler) wsDelete(ctx context.Context, msg *ws.Message) (*ws.Message, e
return ws.NewResponse(msg.ID, msg.Action, map[string]bool{"success": true})
}
// wsReveal handles the secrets.reveal WebSocket action.
func (h *Handler) wsReveal(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
var payload struct {
ID string `json:"id"`
@@ -213,6 +232,8 @@ func (h *Handler) wsReveal(ctx context.Context, msg *ws.Message) (*ws.Message, e
return ws.NewResponse(msg.ID, msg.Action, RevealSecretResponse{Value: value})
}
// getSecret fetches a secret by ID, resolving workspace-scoped access from
// the request's workspace_id query parameter.
func (h *Handler) getSecret(c *gin.Context, id string) (*Secret, error) {
if workspaceID := c.Query("workspace_id"); workspaceID != "" {
return h.service.GetWorkspaceSecret(c.Request.Context(), id, workspaceID)
@@ -220,6 +241,8 @@ func (h *Handler) getSecret(c *gin.Context, id string) (*Secret, error) {
return h.service.Get(c.Request.Context(), id)
}
// updateSecret updates a secret, resolving workspace-scoped access from the
// request's workspace_id query parameter.
func (h *Handler) updateSecret(c *gin.Context, id string, req *UpdateSecretRequest) (*SecretListItem, error) {
if workspaceID := c.Query("workspace_id"); workspaceID != "" {
return h.service.UpdateWorkspaceSecret(c.Request.Context(), id, workspaceID, req)
@@ -227,6 +250,8 @@ func (h *Handler) updateSecret(c *gin.Context, id string, req *UpdateSecretReque
return h.service.Update(c.Request.Context(), id, req)
}
// updateSecretForWorkspace updates a secret, targeting the workspace when
// workspaceID is non-empty and falling back to the global scope otherwise.
func (h *Handler) updateSecretForWorkspace(ctx context.Context, id, workspaceID string, req *UpdateSecretRequest) (*SecretListItem, error) {
if workspaceID != "" {
return h.service.UpdateWorkspaceSecret(ctx, id, workspaceID, req)
@@ -234,6 +259,8 @@ func (h *Handler) updateSecretForWorkspace(ctx context.Context, id, workspaceID
return h.service.Update(ctx, id, req)
}
// deleteSecret deletes a secret, resolving workspace-scoped access from the
// request's workspace_id query parameter.
func (h *Handler) deleteSecret(c *gin.Context, id string) error {
if workspaceID := c.Query("workspace_id"); workspaceID != "" {
return h.service.DeleteWorkspaceSecret(c.Request.Context(), id, workspaceID)
@@ -241,6 +268,8 @@ func (h *Handler) deleteSecret(c *gin.Context, id string) error {
return h.service.Delete(c.Request.Context(), id)
}
// deleteSecretForWorkspace deletes a secret, targeting the workspace when
// workspaceID is non-empty and falling back to the global scope otherwise.
func (h *Handler) deleteSecretForWorkspace(ctx context.Context, id, workspaceID string) error {
if workspaceID != "" {
return h.service.DeleteWorkspaceSecret(ctx, id, workspaceID)
@@ -248,6 +277,8 @@ func (h *Handler) deleteSecretForWorkspace(ctx context.Context, id, workspaceID
return h.service.Delete(ctx, id)
}
// revealSecret returns a secret's value, resolving workspace-scoped access
// from the request's workspace_id query parameter.
func (h *Handler) revealSecret(c *gin.Context, id string) (string, error) {
if workspaceID := c.Query("workspace_id"); workspaceID != "" {
return h.service.RevealWorkspaceSecret(c.Request.Context(), id, workspaceID)
@@ -255,9 +286,150 @@ func (h *Handler) revealSecret(c *gin.Context, id string) (string, error) {
return h.service.Reveal(c.Request.Context(), id)
}
// revealSecretForWorkspace returns a secret's value, targeting the workspace
// when workspaceID is non-empty and falling back to the global scope otherwise.
func (h *Handler) revealSecretForWorkspace(ctx context.Context, id, workspaceID string) (string, error) {
if workspaceID != "" {
return h.service.RevealWorkspaceSecret(ctx, id, workspaceID)
}
return h.service.Reveal(ctx, id)
}
// HTTP copy/move handlers
// httpCopySecret handles POST /api/v1/secrets/:id/copy.
func (h *Handler) httpCopySecret(c *gin.Context) {
h.httpTransferSecret(c, false)
}
// httpMoveSecret handles POST /api/v1/secrets/:id/move.
func (h *Handler) httpMoveSecret(c *gin.Context) {
h.httpTransferSecret(c, true)
}
// httpTransferSecret implements the shared HTTP copy/move flow for a secret;
// move selects move semantics, false selects copy.
func (h *Handler) httpTransferSecret(c *gin.Context, move bool) {
id := c.Param("id")
var req CopySecretRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
item, err := h.transferSecret(c.Request.Context(), id, c.Query("workspace_id"), &req, move)
if err != nil {
status, message := h.transferError(err)
c.JSON(status, gin.H{"error": message})
return
}
c.JSON(http.StatusCreated, item)
}
// transferSecret dispatches copy/move using the existing source-scoping
// convention: a non-empty workspace_id selects the workspace-scoped source.
func (h *Handler) transferSecret(ctx context.Context, id, sourceWorkspaceID string, req *CopySecretRequest, move bool) (*SecretListItem, error) {
if move {
return h.service.Move(ctx, id, sourceWorkspaceID, req)
}
return h.service.Copy(ctx, id, sourceWorkspaceID, req)
}
// transferError classifies a transfer error into an HTTP status and a safe
// message. Only the known sentinels map to 400/404/409; unexpected failures
// become a sanitized 500 with the details logged server-side.
func (h *Handler) transferError(err error) (int, string) {
switch {
case errors.Is(err, ErrSecretValidation):
return http.StatusBadRequest, err.Error()
case errors.Is(err, ErrNotFound), errors.Is(err, ErrWorkspaceAccessDenied):
return http.StatusNotFound, err.Error()
case errors.Is(err, ErrSecretNameConflict):
return http.StatusConflict, err.Error()
default:
h.logger.Error("secret transfer failed", zap.Error(err))
return http.StatusInternalServerError, "internal error"
}
}
// WS copy/move handlers
// wsCopy handles the secrets.copy WebSocket action.
func (h *Handler) wsCopy(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
return h.wsTransfer(ctx, msg, false)
}
// wsMove handles the secrets.move WebSocket action.
func (h *Handler) wsMove(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
return h.wsTransfer(ctx, msg, true)
}
// wsTransferPayload is the WS envelope for secrets.copy / secrets.move. It
// decodes id/workspace_id separately, then delegates the transfer fields to
// the presence-aware CopySecretRequest decoder (a flat struct would silently
// collapse an explicit null name into "omitted").
type wsTransferPayload struct {
ID string
WorkspaceID string
CopySecretRequest
}
// UnmarshalJSON implements the presence-aware envelope decode. The
// CopySecretRequest decoder runs on the whole payload and resets every field,
// including its presence markers, so a reused envelope cannot leak state
// between messages.
func (p *wsTransferPayload) UnmarshalJSON(data []byte) error {
// Reset every field before parsing so a failed decode can never leave
// stale state from an earlier message on a reused envelope, and assign
// only after every sub-decode succeeds so a semantic failure cannot leave
// a partially populated receiver.
p.ID = ""
p.WorkspaceID = ""
p.CopySecretRequest = CopySecretRequest{}
var aux struct {
ID string `json:"id"`
WorkspaceID string `json:"workspace_id"`
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
var req CopySecretRequest
if err := json.Unmarshal(data, &req); err != nil {
return err
}
p.ID = aux.ID
p.WorkspaceID = aux.WorkspaceID
p.CopySecretRequest = req
return nil
}
// wsTransfer implements the shared WebSocket copy/move flow for a secret;
// move selects move semantics, false selects copy.
func (h *Handler) wsTransfer(ctx context.Context, msg *ws.Message, move bool) (*ws.Message, error) {
var payload wsTransferPayload
if err := msg.ParsePayload(&payload); err != nil {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid payload: "+err.Error(), nil)
}
item, err := h.transferSecret(ctx, payload.ID, payload.WorkspaceID, &payload.CopySecretRequest, move)
if err != nil {
code, message := h.transferWSError(err)
return ws.NewError(msg.ID, msg.Action, code, message, nil)
}
return ws.NewResponse(msg.ID, msg.Action, item)
}
// transferWSError maps a transfer error to its WebSocket payload and status.
func (h *Handler) transferWSError(err error) (string, string) {
switch {
case errors.Is(err, ErrSecretValidation):
return ws.ErrorCodeBadRequest, err.Error()
case errors.Is(err, ErrNotFound), errors.Is(err, ErrWorkspaceAccessDenied):
return ws.ErrorCodeNotFound, err.Error()
case errors.Is(err, ErrSecretNameConflict):
return ws.ErrorCodeConflict, err.Error()
default:
h.logger.Error("secret transfer failed", zap.Error(err))
return ws.ErrorCodeInternalError, "internal error"
}
}
@@ -0,0 +1,580 @@
package secrets
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/kandev/kandev/internal/common/logger"
ws "github.com/kandev/kandev/pkg/websocket"
)
// testLogger returns an error-level JSON logger for tests.
func testLogger(t *testing.T) *logger.Logger {
t.Helper()
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
if err != nil {
t.Fatalf("logger: %v", err)
}
return log
}
// newSecretsHandlerService builds a service wired like main.go: the authorizer
// and existence checker classify missing/unauthorized workspaces as
// ErrWorkspaceAccessDenied, and injected raw errors pass through unclassified.
func newSecretsHandlerService(t *testing.T, allowed map[string]bool, authorizerErr, existenceErr error) *Service {
t.Helper()
store := newTestSQLiteStore(t)
svc := NewService(NewUserVisibleStore(store), nil)
svc.SetWorkspaceAuthorizer(func(_ context.Context, workspaceID string) error {
if authorizerErr != nil {
return authorizerErr
}
if allowed[workspaceID] {
return nil
}
return ErrWorkspaceAccessDenied
})
svc.SetWorkspaceExistenceChecker(func(_ context.Context, workspaceID string) error {
if existenceErr != nil {
return existenceErr
}
if allowed[workspaceID] {
return nil
}
return ErrWorkspaceAccessDenied
})
return svc
}
// newSecretsHTTPRouter builds a gin engine with the secrets handler's HTTP routes registered.
func newSecretsHTTPRouter(t *testing.T, svc *Service) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
router := gin.New()
NewHandler(svc, testLogger(t)).registerHTTP(router)
return router
}
// doTransferHTTP performs an HTTP request against the router and returns the response recorder.
func doTransferHTTP(t *testing.T, router *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
return rec
}
// decodeItem unmarshals a SecretListItem from the response body.
func decodeItem(t *testing.T, rec *httptest.ResponseRecorder) *SecretListItem {
t.Helper()
var item SecretListItem
if err := json.Unmarshal(rec.Body.Bytes(), &item); err != nil {
t.Fatalf("decode item from %d %s: %v", rec.Code, rec.Body.String(), err)
}
return &item
}
// seedGlobalViaService creates a global secret via the service and returns its ID.
func seedGlobalViaService(t *testing.T, svc *Service, name, value string) string {
t.Helper()
item := mustCreateViaService(t, svc, name, value, ScopeGlobal, "")
return item.ID
}
// TestHandlerCopy_GlobalToWorkspaceCreated verifies the copy endpoint returns 201 with the copied item and keeps the source.
func TestHandlerCopy_GlobalToWorkspaceCreated(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
id := seedGlobalViaService(t, svc, "API Key", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"workspace","target_workspace_id":"workspace-a","name":"copied"}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
}
item := decodeItem(t, rec)
if item.Scope != ScopeWorkspace || item.WorkspaceID != "workspace-a" || item.Name != "copied" {
t.Fatalf("item = %+v", item)
}
if _, err := svc.Get(context.Background(), id); err != nil {
t.Fatalf("source lost after copy: %v", err)
}
}
// TestHandlerCopy_WorkspaceToWorkspace verifies the copy endpoint handles a
// workspace source (via ?workspace_id=) with a workspace target: 201 with the
// item scoped to the destination workspace, source intact.
func TestHandlerCopy_WorkspaceToWorkspace(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true, "workspace-b": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
w := mustCreateViaService(t, svc, "ws-key", "v", ScopeWorkspace, "workspace-a")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+w.ID+"/copy?workspace_id=workspace-a",
`{"target_scope":"workspace","target_workspace_id":"workspace-b","name":"copied"}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
}
item := decodeItem(t, rec)
if item.Scope != ScopeWorkspace || item.WorkspaceID != "workspace-b" || item.Name != "copied" {
t.Fatalf("item = %+v", item)
}
if _, err := svc.GetForWorkspace(context.Background(), w.ID, "workspace-a"); err != nil {
t.Fatalf("source lost after copy: %v", err)
}
}
// TestHandlerCopy_WorkspaceSourceRequiresWorkspaceID verifies a workspace source without workspace_id is rejected with 404.
func TestHandlerCopy_WorkspaceSourceRequiresWorkspaceID(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
w := mustCreateViaService(t, svc, "ws", "v", ScopeWorkspace, "workspace-a")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+w.ID+"/copy",
`{"target_scope":"global","name":"x"}`)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 (workspace source without workspace_id)", rec.Code)
}
}
// TestHandlerCopy_OmittedNameUsesSourceName verifies an omitted copy name falls back to the source name.
func TestHandlerCopy_OmittedNameUsesSourceName(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
id := seedGlobalViaService(t, svc, "API Key", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"workspace","target_workspace_id":"workspace-a"}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
}
if item := decodeItem(t, rec); item.Name != "API Key" {
t.Fatalf("name = %q, want source name", item.Name)
}
}
// TestHandlerCopy_NullNameBadRequest verifies a null copy name is rejected with 400.
func TestHandlerCopy_NullNameBadRequest(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"workspace","target_workspace_id":"workspace-a","name":null}`)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 for null name", rec.Code)
}
}
// TestHandlerMove_WorkspaceToGlobal verifies the move endpoint moves a workspace secret to global and removes the source.
func TestHandlerMove_WorkspaceToGlobal(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
w := mustCreateViaService(t, svc, "ws", "v", ScopeWorkspace, "workspace-a")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+w.ID+"/move?workspace_id=workspace-a",
`{"target_scope":"global","name":"moved"}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
}
item := decodeItem(t, rec)
if item.Scope != ScopeGlobal || item.Name != "moved" {
t.Fatalf("item = %+v", item)
}
if _, err := svc.GetWorkspaceSecret(context.Background(), w.ID, "workspace-a"); !errors.Is(err, ErrNotFound) {
t.Fatalf("source still present after move: %v", err)
}
}
// TestHandlerCopy_SameScopeBadRequest verifies a same-scope copy is rejected with 400.
func TestHandlerCopy_SameScopeBadRequest(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"global","name":"other"}`)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 for same-scope", rec.Code)
}
}
// TestHandlerCopy_NameConflict verifies a target name collision returns 409.
func TestHandlerCopy_NameConflict(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
mustCreateViaService(t, svc, "taken", "other", ScopeWorkspace, "workspace-a")
id := seedGlobalViaService(t, svc, "g", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"workspace","target_workspace_id":"workspace-a","name":"taken"}`)
if rec.Code != http.StatusConflict {
t.Fatalf("status = %d, want 409", rec.Code)
}
}
// TestHandlerCopy_MissingSourceNotFound verifies an unknown copy source returns 404.
func TestHandlerCopy_MissingSourceNotFound(t *testing.T) {
svc := newSecretsHandlerService(t, nil, nil, nil)
router := newSecretsHTTPRouter(t, svc)
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/missing/copy",
`{"target_scope":"global","name":"x"}`)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", rec.Code)
}
}
// TestHandlerCopy_UnauthorizedSourceNotFound verifies an unauthorized source workspace is reported as 404.
func TestHandlerCopy_UnauthorizedSourceNotFound(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
w := mustCreateViaService(t, svc, "ws", "v", ScopeWorkspace, "workspace-a")
svc.SetWorkspaceAuthorizer(func(context.Context, string) error { return ErrWorkspaceAccessDenied })
svc.SetWorkspaceExistenceChecker(func(context.Context, string) error { return ErrWorkspaceAccessDenied })
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+w.ID+"/copy?workspace_id=workspace-a",
`{"target_scope":"global","name":"x"}`)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 for unauthorized source", rec.Code)
}
}
// TestHandlerCopy_UnauthorizedDestinationNotFound verifies an unauthorized destination workspace is reported as 404.
func TestHandlerCopy_UnauthorizedDestinationNotFound(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"workspace","target_workspace_id":"workspace-b","name":"x"}`)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 for unauthorized destination", rec.Code)
}
}
// TestHandlerCopy_NilExistenceCheckerNotFound verifies a nil existence checker fails closed with 404.
func TestHandlerCopy_NilExistenceCheckerNotFound(t *testing.T) {
store := newTestSQLiteStore(t)
svc := NewService(NewUserVisibleStore(store), nil)
svc.SetWorkspaceAuthorizer(func(context.Context, string) error { return nil })
router := newSecretsHTTPRouter(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"workspace","target_workspace_id":"any","name":"x"}`)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 (nil checker fails closed)", rec.Code)
}
}
// TestHandlerCopy_InternalErrorSanitized verifies internal errors return 500 without leaking the error message.
func TestHandlerCopy_InternalErrorSanitized(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, errors.New("database unreachable"), nil)
router := newSecretsHTTPRouter(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"workspace","target_workspace_id":"workspace-a","name":"x"}`)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500", rec.Code)
}
if strings.Contains(rec.Body.String(), "database unreachable") {
t.Fatalf("500 body leaked internal error: %s", rec.Body.String())
}
}
// TestHandlerCopy_ValidationLikeInternalErrorStays500 verifies sentinel-based classification keeps a validation-sounding internal error at 500.
func TestHandlerCopy_ValidationLikeInternalErrorStays500(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, errors.New("name must be 1-100 characters"), nil)
router := newSecretsHTTPRouter(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"workspace","target_workspace_id":"workspace-a","name":"x"}`)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500 (classification is sentinel-based, not text-based)", rec.Code)
}
}
// TestHandlerCopy_WhitespaceNameBadRequest verifies a whitespace-only name is rejected with 400.
func TestHandlerCopy_WhitespaceNameBadRequest(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
router := newSecretsHTTPRouter(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
rec := doTransferHTTP(t, router, http.MethodPost, "/api/v1/secrets/"+id+"/copy",
`{"target_scope":"workspace","target_workspace_id":"workspace-a","name":" "}`)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 for whitespace name", rec.Code)
}
}
// --- WebSocket handlers ---
// newWSHandler builds a secrets Handler for WebSocket tests.
func newWSHandler(t *testing.T, svc *Service) *Handler {
t.Helper()
return NewHandler(svc, testLogger(t))
}
// wsTransfer dispatches a WebSocket copy/move message and returns the response message.
func wsTransfer(t *testing.T, h *Handler, action, payload string) (*ws.Message, error) {
t.Helper()
msg := &ws.Message{ID: "1", Action: action, Payload: json.RawMessage(payload)}
switch action {
case ws.ActionSecretCopy:
return h.wsCopy(context.Background(), msg)
case ws.ActionSecretMove:
return h.wsMove(context.Background(), msg)
}
t.Fatalf("unknown action %s", action)
return nil, nil
}
type wsErrorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
}
// decodeWSError unmarshals a wsErrorPayload from a WebSocket response.
func decodeWSError(t *testing.T, resp *ws.Message) wsErrorPayload {
t.Helper()
var errPayload wsErrorPayload
if err := json.Unmarshal(resp.Payload, &errPayload); err != nil {
t.Fatalf("decode error payload %s: %v", string(resp.Payload), err)
}
return errPayload
}
// decodeWSItem unmarshals a SecretListItem from a WebSocket response.
func decodeWSItem(t *testing.T, resp *ws.Message) *SecretListItem {
t.Helper()
var item SecretListItem
if err := json.Unmarshal(resp.Payload, &item); err != nil {
t.Fatalf("decode item payload %s: %v", string(resp.Payload), err)
}
return &item
}
// TestWSHandler_CopySuccessAndShape verifies a WebSocket copy returns the copied item with the expected shape.
func TestWSHandler_CopySuccessAndShape(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
h := newWSHandler(t, svc)
id := seedGlobalViaService(t, svc, "API Key", "v")
resp, err := wsTransfer(t, h, ws.ActionSecretCopy,
`{"id":"`+id+`","target_scope":"workspace","target_workspace_id":"workspace-a","name":"copied"}`)
if err != nil {
t.Fatalf("wsCopy: %v", err)
}
item := decodeWSItem(t, resp)
if item.Scope != ScopeWorkspace || item.WorkspaceID != "workspace-a" || item.Name != "copied" {
t.Fatalf("item = %+v", item)
}
}
// TestWSHandler_CopyNullNameBadRequest verifies a WebSocket copy with a null name returns a BAD_REQUEST error.
func TestWSHandler_CopyNullNameBadRequest(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
h := newWSHandler(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
resp, err := wsTransfer(t, h, ws.ActionSecretCopy,
`{"id":"`+id+`","target_scope":"workspace","target_workspace_id":"workspace-a","name":null}`)
if err != nil {
t.Fatalf("wsCopy: %v", err)
}
if got := decodeWSError(t, resp); got.Code != ws.ErrorCodeBadRequest {
t.Fatalf("code = %q, want BAD_REQUEST", got.Code)
}
}
// TestWSHandler_CopyConflict verifies a WebSocket copy name collision returns a CONFLICT error.
func TestWSHandler_CopyConflict(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
h := newWSHandler(t, svc)
mustCreateViaService(t, svc, "taken", "other", ScopeWorkspace, "workspace-a")
id := seedGlobalViaService(t, svc, "g", "v")
resp, err := wsTransfer(t, h, ws.ActionSecretCopy,
`{"id":"`+id+`","target_scope":"workspace","target_workspace_id":"workspace-a","name":"taken"}`)
if err != nil {
t.Fatalf("wsCopy: %v", err)
}
if got := decodeWSError(t, resp); got.Code != ws.ErrorCodeConflict {
t.Fatalf("code = %q, want CONFLICT", got.Code)
}
}
// TestWSHandler_CopyMissingSourceNotFound verifies a WebSocket copy of an unknown source returns NOT_FOUND.
func TestWSHandler_CopyMissingSourceNotFound(t *testing.T) {
svc := newSecretsHandlerService(t, nil, nil, nil)
h := newWSHandler(t, svc)
resp, err := wsTransfer(t, h, ws.ActionSecretCopy,
`{"id":"missing","target_scope":"global","name":"x"}`)
if err != nil {
t.Fatalf("wsCopy: %v", err)
}
if got := decodeWSError(t, resp); got.Code != ws.ErrorCodeNotFound {
t.Fatalf("code = %q, want NOT_FOUND", got.Code)
}
}
// TestWSHandler_CopyUnauthorizedDestinationNotFound verifies an unauthorized WebSocket copy destination returns NOT_FOUND.
func TestWSHandler_CopyUnauthorizedDestinationNotFound(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
h := newWSHandler(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
resp, err := wsTransfer(t, h, ws.ActionSecretCopy,
`{"id":"`+id+`","target_scope":"workspace","target_workspace_id":"workspace-b","name":"x"}`)
if err != nil {
t.Fatalf("wsCopy: %v", err)
}
if got := decodeWSError(t, resp); got.Code != ws.ErrorCodeNotFound {
t.Fatalf("code = %q, want NOT_FOUND", got.Code)
}
}
// TestWSHandler_CopyInternalErrorSanitized verifies WebSocket copy internal errors return INTERNAL_ERROR without leaking details.
func TestWSHandler_CopyInternalErrorSanitized(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, errors.New("database unreachable"), nil)
h := newWSHandler(t, svc)
id := seedGlobalViaService(t, svc, "g", "v")
resp, err := wsTransfer(t, h, ws.ActionSecretCopy,
`{"id":"`+id+`","target_scope":"workspace","target_workspace_id":"workspace-a","name":"x"}`)
if err != nil {
t.Fatalf("wsCopy: %v", err)
}
got := decodeWSError(t, resp)
if got.Code != ws.ErrorCodeInternalError {
t.Fatalf("code = %q, want INTERNAL_ERROR", got.Code)
}
if strings.Contains(got.Message, "database unreachable") {
t.Fatalf("error message leaked internal detail: %q", got.Message)
}
}
// TestWSHandler_WorkspaceSourceWithoutWorkspaceIDNotFound verifies a WebSocket copy of a workspace source without workspace_id returns NOT_FOUND.
func TestWSHandler_WorkspaceSourceWithoutWorkspaceIDNotFound(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true}, nil, nil)
h := newWSHandler(t, svc)
w := mustCreateViaService(t, svc, "ws", "v", ScopeWorkspace, "workspace-a")
resp, err := wsTransfer(t, h, ws.ActionSecretCopy,
`{"id":"`+w.ID+`","target_scope":"global","name":"x"}`)
if err != nil {
t.Fatalf("wsCopy: %v", err)
}
if got := decodeWSError(t, resp); got.Code != ws.ErrorCodeNotFound {
t.Fatalf("code = %q, want NOT_FOUND (workspace source without workspace_id)", got.Code)
}
}
// TestWSHandler_ReusedEnvelopeResetsAllFields verifies reusing a wsTransferPayload across decodes fully resets all fields, including after malformed and semantic decode failures.
func TestWSHandler_ReusedEnvelopeResetsAllFields(t *testing.T) {
svc := newSecretsHandlerService(t, map[string]bool{"workspace-a": true, "workspace-b": true}, nil, nil)
h := newWSHandler(t, svc)
wsSecretA := mustCreateViaService(t, svc, "ws-a", "va", ScopeWorkspace, "workspace-a")
global2 := seedGlobalViaService(t, svc, "g2", "vg")
// First message: workspace source, workspace target, explicit null name.
first, err := wsTransfer(t, h, ws.ActionSecretCopy,
`{"id":"`+wsSecretA.ID+`","workspace_id":"workspace-a","target_scope":"workspace","target_workspace_id":"workspace-b","name":null}`)
if err != nil {
t.Fatalf("first message: %v", err)
}
if got := decodeWSError(t, first); got.Code != ws.ErrorCodeBadRequest {
t.Fatalf("first code = %q, want BAD_REQUEST", got.Code)
}
// Second message: a different source (Global), workspace target A, omitted
// name, NO source workspace_id. If the decoder leaked the stale source
// workspace_id, the Global source would be mis-dispatched as a workspace
// source (404); a clean reset succeeds with the default source name.
second, err := wsTransfer(t, h, ws.ActionSecretCopy,
`{"id":"`+global2+`","target_scope":"workspace","target_workspace_id":"workspace-a"}`)
if err != nil {
t.Fatalf("second message: %v", err)
}
item := decodeWSItem(t, second)
if item.Scope != ScopeWorkspace || item.WorkspaceID != "workspace-a" || item.Name != "g2" {
t.Fatalf("second item = %+v (stale fields leaked between decodes)", item)
}
// Decoder-level reuse: one wsTransferPayload instance decodes BOTH
// messages. The second decode must fully reset id, workspace_id, scope,
// and the name presence markers.
var payload wsTransferPayload
firstBody := `{"id":"` + wsSecretA.ID + `","workspace_id":"workspace-a","target_scope":"workspace","target_workspace_id":"workspace-b","name":null}`
if err := json.Unmarshal([]byte(firstBody), &payload); err != nil {
t.Fatalf("decode first into shared payload: %v", err)
}
// Local alias for the embedded request: promoted selectors for
// WorkspaceID would be ambiguous (the envelope's source workspace id
// shadows the embedded target workspace id).
target := &payload.CopySecretRequest
if !target.nameNull || payload.ID != wsSecretA.ID {
t.Fatalf("first shared decode = %+v", payload)
}
secondBody := `{"id":"` + global2 + `","target_scope":"workspace","target_workspace_id":"workspace-a"}`
if err := json.Unmarshal([]byte(secondBody), &payload); err != nil {
t.Fatalf("decode second into shared payload: %v", err)
}
if payload.ID != global2 || payload.WorkspaceID != "" ||
target.Scope != ScopeWorkspace || target.WorkspaceID != "workspace-a" ||
target.Name != nil || target.nameSet || target.nameNull {
t.Fatalf("shared payload after second decode = %+v (stale fields leaked)", payload)
}
// A malformed second decode must leave the receiver fully reset, never
// carrying state from the first decode.
staleName := "stale"
bad := wsTransferPayload{
ID: "stale-id",
WorkspaceID: "stale-ws",
CopySecretRequest: CopySecretRequest{
Scope: ScopeWorkspace,
WorkspaceID: "stale-ws",
Name: &staleName,
nameSet: true,
},
}
if err := bad.UnmarshalJSON([]byte(`{"id":`)); err == nil {
t.Fatal("malformed decode succeeded")
}
badTarget := &bad.CopySecretRequest
if bad.ID != "" || bad.WorkspaceID != "" || badTarget.Scope != "" ||
badTarget.WorkspaceID != "" || badTarget.Name != nil ||
badTarget.nameSet || badTarget.nameNull {
t.Fatalf("malformed decode left stale state: %+v", bad)
}
// A SEMANTIC decode failure (invalid `name` type after valid top-level
// fields) must also leave the receiver fully reset, never partially
// populated with the already-parsed scope/workspace fields.
var semantic wsTransferPayload
if err := json.Unmarshal([]byte(firstBody), &semantic); err != nil {
t.Fatalf("seed semantic payload: %v", err)
}
if err := json.Unmarshal(
[]byte(`{"id":"`+global2+`","target_scope":"workspace","target_workspace_id":"workspace-a","name":123}`),
&semantic,
); err == nil {
t.Fatal("semantic decode with a numeric name succeeded")
}
semanticTarget := &semantic.CopySecretRequest
if semantic.ID != "" || semantic.WorkspaceID != "" || semanticTarget.Scope != "" ||
semanticTarget.WorkspaceID != "" || semanticTarget.Name != nil ||
semanticTarget.nameSet || semanticTarget.nameNull {
t.Fatalf("semantic decode left partially populated state: %+v", semantic)
}
}
+63 -1
View File
@@ -1,6 +1,9 @@
package secrets
import "time"
import (
"encoding/json"
"time"
)
// SecretScope identifies the ownership boundary for a secret.
type SecretScope string
@@ -65,3 +68,62 @@ type UpdateSecretRequest struct {
type RevealSecretResponse struct {
Value string `json:"value"`
}
// CopySecretRequest is the request body for copy/move operations. Name uses
// presence semantics: a JSON-omitted name means "use the source secret's
// name"; an explicit null, empty, or whitespace-only name is a validation
// error.
type CopySecretRequest struct {
Scope SecretScope `json:"target_scope"`
WorkspaceID string `json:"target_workspace_id"`
Name *string `json:"name,omitempty"`
nameSet bool
nameNull bool
}
// UnmarshalJSON implements presence-aware decoding so handlers can distinguish
// an omitted name (default to the source name) from an explicit null (a
// validation error). Go's standard decoding collapses both to a nil pointer,
// so this is the only way to honor the contract. Every field, including the
// presence markers, is reset on each decode so a reused request struct cannot
// leak state between messages.
func (r *CopySecretRequest) UnmarshalJSON(data []byte) error {
// Reset every field (including the presence markers) BEFORE parsing so a
// failed decode can never leave stale state from an earlier message, and
// assign the receiver only after EVERY sub-decode succeeds so a semantic
// failure (e.g. `name: 123`) cannot leave a partially populated receiver.
r.Scope = ""
r.WorkspaceID = ""
r.Name = nil
r.nameSet = false
r.nameNull = false
var aux struct {
Scope SecretScope `json:"target_scope"`
WorkspaceID string `json:"target_workspace_id"`
Name json.RawMessage `json:"name"`
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
var name *string
nameSet := len(aux.Name) > 0
nameNull := false
if nameSet {
if string(aux.Name) == "null" {
nameNull = true
} else {
var value string
if err := json.Unmarshal(aux.Name, &value); err != nil {
return err
}
name = &value
}
}
r.Scope = aux.Scope
r.WorkspaceID = aux.WorkspaceID
r.Name = name
r.nameSet = nameSet
r.nameNull = nameNull
return nil
}
@@ -0,0 +1,390 @@
package secrets
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/kandev/kandev/internal/testutil"
)
// openPGWithConns opens an isolated Postgres schema with a pool of conns
// connections and search_path set per connection (via DSN options), so race
// tests can hold two real connections at once. A one-connection pool trivially
// serializes and proves nothing about the advisory locks.
func openPGWithConns(t *testing.T, conns int) *sqlx.DB {
t.Helper()
dsn := testutil.PostgresDSNFromEnv(t)
schema := "kandev_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
admin, err := sqlx.Open("pgx", dsn)
if err != nil {
t.Fatalf("open postgres: %v", err)
}
if _, err := admin.Exec("CREATE SCHEMA " + schema); err != nil {
_ = admin.Close()
t.Fatalf("create schema: %v", err)
}
_ = admin.Close()
t.Cleanup(func() {
cleanup, cerr := sqlx.Open("pgx", dsn)
if cerr == nil {
_, _ = cleanup.Exec("DROP SCHEMA IF EXISTS " + schema + " CASCADE")
_ = cleanup.Close()
}
})
db, err := sqlx.Open("pgx", dsn+" options=-csearch_path="+schema)
if err != nil {
t.Fatalf("open postgres pool: %v", err)
}
db.SetMaxOpenConns(conns)
db.SetMaxIdleConns(conns)
t.Cleanup(func() { _ = db.Close() })
return db
}
// newPGStore builds a secrets store over the given Postgres pool with a fresh master key.
func newPGStore(t *testing.T, db *sqlx.DB) *sqliteStore {
t.Helper()
crypto, err := NewMasterKeyProvider(t.TempDir())
if err != nil {
t.Fatalf("master key: %v", err)
}
store, cleanup, err := Provide(db, db, crypto)
if err != nil {
t.Fatalf("provide store: %v", err)
}
t.Cleanup(func() { _ = cleanup() })
return store
}
// TestPostgresTransfer_CopyMoveConflictAndOwnership verifies Postgres copy/move metadata, name conflicts (including legacy empty-scope globals), and source removal on move.
func TestPostgresTransfer_CopyMoveConflictAndOwnership(t *testing.T) {
db := openPGWithConns(t, 2)
store := newPGStore(t, db)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
// Copy global -> workspace with target identity.
got, err := store.CopyScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied"), nil)
if err != nil {
t.Fatalf("CopyScoped: %v", err)
}
if got.Scope != ScopeWorkspace || got.WorkspaceID != "workspace-a" || got.Name != "copied" {
t.Fatalf("copy metadata = %+v", got)
}
if got.CreatedAt.IsZero() || got.UpdatedAt.IsZero() {
t.Fatalf("copy timestamps zero: %+v", got)
}
if value, err := store.RevealForWorkspace(ctx, got.ID, "workspace-a"); err != nil || value != "v" {
t.Fatalf("reveal = %q, %v", value, err)
}
// Conflict on a second copy of the same target name.
if _, err := store.CopyScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied"), nil); !errors.Is(err, ErrSecretNameConflict) {
t.Fatalf("conflict err = %v", err)
}
// Move workspace -> global removes the source.
moved, err := store.MoveScoped(ctx, "g1", "", ScopeGlobal, "", strPtr("global-copy"), nil)
if err != nil {
t.Fatalf("MoveScoped: %v", err)
}
if moved.Scope != ScopeGlobal {
t.Fatalf("moved scope = %q", moved.Scope)
}
if _, err := store.Get(ctx, "g1"); !errors.Is(err, ErrNotFound) {
t.Fatalf("source still present: %v", err)
}
// Legacy empty-scope Global row conflicts with a Global target.
ciphertext, nonce, err := Encrypt([]byte("legacy"), store.crypto.Key())
if err != nil {
t.Fatalf("encrypt: %v", err)
}
now := time.Now().UTC()
if _, err := db.ExecContext(ctx, db.Rebind(`
INSERT INTO secrets (id, name, user_id, scope, workspace_id, encrypted_value, nonce, created_at, updated_at)
VALUES (?, ?, '', '', '', ?, ?, ?, ?)`),
"legacy-1", "legacy-name", ciphertext, nonce, now, now); err != nil {
t.Fatalf("seed legacy row: %v", err)
}
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g2", Name: "src2"}, Value: "v2"})
if _, err := store.CopyScoped(ctx, "g2", "", ScopeGlobal, "", strPtr("legacy-name"), nil); !errors.Is(err, ErrSecretNameConflict) {
t.Fatalf("legacy conflict err = %v", err)
}
}
// TestPostgresTransfer_MoveRollbackAfterInsert verifies a failed source delete after insert rolls back the copy, leaving the source intact and no destination row.
func TestPostgresTransfer_MoveRollbackAfterInsert(t *testing.T) {
db := openPGWithConns(t, 2)
store := newPGStore(t, db)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
store.failAfterInsert = func() error { return errors.New("injected delete failure") }
if _, err := store.MoveScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied"), nil); err == nil {
t.Fatal("MoveScoped succeeded despite failpoint")
}
if _, err := store.Get(ctx, "g1"); err != nil {
t.Fatalf("source lost after rollback: %v", err)
}
items, err := store.ListScoped(ctx, SecretListOptions{Scope: ScopeWorkspace, WorkspaceID: "workspace-a"})
if err != nil || len(items) != 0 {
t.Fatalf("workspace rows = %+v, %v; want none", items, err)
}
}
// TestPostgresTransfer_ConcurrentSameTarget proves exactly one winner for
// concurrent same-name transfers to a Global target, serialized by the Global
// advisory lock.
func TestPostgresTransfer_ConcurrentSameTarget(t *testing.T) {
db := openPGWithConns(t, 3)
storeA := newPGStore(t, db)
storeB := newPGStore(t, db)
ctx := context.Background()
mustCreate(t, storeA, &SecretWithValue{Secret: Secret{ID: "src", Name: "orig"}, Value: "v"})
locked := make(chan struct{})
release := make(chan struct{})
done := make(chan error, 1)
go func() {
_, err := storeA.CopyScoped(ctx, "src", "", ScopeGlobal, "", strPtr("dup"), func(context.Context) error {
close(locked)
<-release
return nil
})
done <- err
}()
<-locked
bErr := make(chan error, 1)
go func() {
_, err := storeB.CopyScoped(ctx, "src", "", ScopeGlobal, "", strPtr("dup"), nil)
bErr <- err
}()
select {
case err := <-bErr:
t.Fatalf("B completed while A held the advisory lock: %v", err)
case <-time.After(300 * time.Millisecond):
}
close(release)
if err := <-done; err != nil {
t.Fatalf("A: %v", err)
}
if err := <-bErr; !errors.Is(err, ErrSecretNameConflict) {
t.Fatalf("B error = %v, want ErrSecretNameConflict", err)
}
}
// TestPostgresTransfer_DeleteVsTransferRace pins both interleavings of the
// shared workspace advisory lock: a transfer that inserts before a deletion
// commits is cleaned up by that deletion, and a deletion that commits first
// leaves nothing for a later transfer to attach to.
func TestPostgresTransfer_DeleteVsTransferRace(t *testing.T) {
db := openPGWithConns(t, 3)
store := newPGStore(t, db)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "src", Name: "orig"}, Value: "v"})
t.Run("transfer locked before deletion cleanup", func(t *testing.T) {
locked := make(chan struct{})
release := make(chan struct{})
transferDone := make(chan error, 1)
go func() {
_, err := store.CopyScoped(ctx, "src", "", ScopeWorkspace, "workspace-a", strPtr("copied"), func(context.Context) error {
close(locked)
<-release
return nil
})
transferDone <- err
}()
<-locked
delDone := make(chan error, 1)
go func() {
tx, err := db.BeginTxx(ctx, nil)
if err != nil {
delDone <- err
return
}
defer func() { _ = tx.Rollback() }()
if err := store.DeleteWorkspaceSecretsTx(ctx, tx, "workspace-a"); err != nil {
delDone <- err
return
}
delDone <- tx.Commit()
}()
select {
case err := <-delDone:
t.Fatalf("deletion completed while the transfer held the lock: %v", err)
case <-time.After(300 * time.Millisecond):
}
close(release)
if err := <-transferDone; err != nil {
t.Fatalf("transfer: %v", err)
}
if err := <-delDone; err != nil {
t.Fatalf("deletion: %v", err)
}
// The deletion ran after the transfer inserted and removed the copy:
// no secret may remain attached to the deleted workspace.
items, err := store.ListScoped(ctx, SecretListOptions{Scope: ScopeWorkspace, WorkspaceID: "workspace-a"})
if err != nil {
t.Fatalf("list: %v", err)
}
if len(items) != 0 {
t.Fatalf("workspace rows = %+v, want none after deletion", items)
}
})
t.Run("deletion committed before transfer existence check", func(t *testing.T) {
tx, err := db.BeginTxx(ctx, nil)
if err != nil {
t.Fatalf("begin deletion: %v", err)
}
if err := store.DeleteWorkspaceSecretsTx(ctx, tx, "workspace-b"); err != nil {
_ = tx.Rollback()
t.Fatalf("delete: %v", err)
}
if err := tx.Commit(); err != nil {
t.Fatalf("commit deletion: %v", err)
}
// The transfer's existence check (the callback, run under the lock)
// denies a workspace that no longer exists; nothing is inserted.
denied := errors.New("workspace gone")
_, err = store.CopyScoped(ctx, "src", "", ScopeWorkspace, "workspace-b", strPtr("copied"), func(context.Context) error {
return denied
})
if !errors.Is(err, denied) {
t.Fatalf("err = %v, want the denied callback error", err)
}
items, err := store.ListScoped(ctx, SecretListOptions{Scope: ScopeWorkspace, WorkspaceID: "workspace-b"})
if err != nil || len(items) != 0 {
t.Fatalf("workspace rows = %+v, %v; want none", items, err)
}
})
}
// TestPostgresTransfer_MoveSerializesConcurrentUpdate proves the Move source
// row is locked with FOR UPDATE: a concurrent Update cannot interleave between
// Move's read and delete, so no newer value is lost.
func TestPostgresTransfer_MoveSerializesConcurrentUpdate(t *testing.T) {
db := openPGWithConns(t, 3)
store := newPGStore(t, db)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "src", Name: "orig"}, Value: "A"})
locked := make(chan struct{})
release := make(chan struct{})
moveDone := make(chan error, 1)
store.afterSourceLock = func() error {
close(locked)
<-release
return nil
}
go func() {
_, err := store.MoveScoped(ctx, "src", "", ScopeWorkspace, "workspace-a", strPtr("copied"), nil)
moveDone <- err
}()
// Move holds the FOR UPDATE source row lock.
<-locked
updateDone := make(chan error, 1)
go func() {
updateDone <- store.Update(ctx, "src", &UpdateSecretRequest{Value: stringPtr("B")})
}()
select {
case err := <-updateDone:
t.Fatalf("Update completed while Move held the source row lock: %v", err)
case <-time.After(300 * time.Millisecond):
// Blocked on the row lock, as intended.
}
close(release)
if err := <-moveDone; err != nil {
t.Fatalf("move: %v", err)
}
// The Update completes after Move commits; the row is gone, so it touches
// nothing and the newer value B is not lost anywhere.
if err := <-updateDone; err != nil {
t.Fatalf("update: %v", err)
}
if _, err := store.Get(ctx, "src"); !errors.Is(err, ErrNotFound) {
t.Fatalf("source still present after move: %v", err)
}
items, err := store.ListScoped(ctx, SecretListOptions{Scope: ScopeWorkspace, WorkspaceID: "workspace-a"})
if err != nil {
t.Fatalf("list workspace: %v", err)
}
var moved *SecretListItem
for _, item := range items {
if item.Name == "copied" {
moved = item
}
}
if moved == nil {
t.Fatalf("moved copy not found in workspace-a: %+v", items)
}
value, err := store.RevealForWorkspace(ctx, moved.ID, "workspace-a")
if err != nil {
t.Fatalf("reveal moved: %v", err)
}
if value != "A" {
t.Fatalf("moved value = %q, want A (concurrent update must not be lost)", value)
}
}
// TestPostgresTransfer_ConditionalInsertRejectsLateConflict verifies the
// transfer insert is guarded by an atomic NOT EXISTS: an ordinary create or
// rename (which does not take the transfer's advisory lock) committing the
// target name between the eager conflict check and the insert must produce a
// clean ErrSecretNameConflict, never a duplicate row.
func TestPostgresTransfer_ConditionalInsertRejectsLateConflict(t *testing.T) {
db := openPGWithConns(t, 2)
store := newPGStore(t, db)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
// Commit the target name from a second connection at the exact point
// between the transfer's conflict check and its conditional insert.
store.beforeTransferInsert = func() error {
_, err := db.Exec(`
INSERT INTO secrets (id, name, user_id, scope, workspace_id, encrypted_value, nonce, created_at, updated_at)
VALUES ('late', 'copied', '', 'workspace', 'workspace-a', '\x01'::bytea, '\x01'::bytea, now(), now())`)
return err
}
_, err := store.CopyScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied"), nil)
if !errors.Is(err, ErrSecretNameConflict) {
t.Fatalf("error = %v, want ErrSecretNameConflict (atomic NOT EXISTS must observe the late row)", err)
}
// Exactly one 'copied' row in workspace-a: the late create won, the
// transfer did not insert a duplicate.
items, err := store.ListScoped(ctx, SecretListOptions{Scope: ScopeWorkspace, WorkspaceID: "workspace-a"})
if err != nil {
t.Fatalf("list: %v", err)
}
count := 0
for _, item := range items {
if item.Name == "copied" {
count++
}
}
if count != 1 {
t.Fatalf("'copied' rows in workspace-a = %d, want 1 (no duplicate from the transfer)", count)
}
}
+137 -2
View File
@@ -13,6 +13,7 @@ type Service struct {
store SecretStore
logger *logger.Logger
workspaceAuthorizer func(context.Context, string) error
workspaceExistence func(context.Context, string) error
}
// NewService creates a new secrets service.
@@ -30,11 +31,21 @@ func (s *Service) SetWorkspaceAuthorizer(authorizer func(context.Context, string
s.workspaceAuthorizer = authorizer
}
// SetWorkspaceExistenceChecker wires a workspace-existence check that runs
// unconditionally for copy/move destinations, including auth-disabled
// contexts where the authorizer is a no-op. A nil checker fails closed:
// workspace destinations resolve as ErrWorkspaceAccessDenied.
func (s *Service) SetWorkspaceExistenceChecker(checker func(context.Context, string) error) {
s.workspaceExistence = checker
}
// validateCreate validates a create request, trimming the name and checking
// length, scope, and workspace constraints.
func (s *Service) validateCreate(req *CreateSecretRequest) error {
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" || len(req.Name) > 100 {
return fmt.Errorf("name must be 1-100 characters")
return fmt.Errorf("name must be 1-100 bytes")
}
if req.Value == "" || len(req.Value) > 10000 {
return fmt.Errorf("value must be 1-10000 characters")
@@ -48,12 +59,14 @@ func (s *Service) validateCreate(req *CreateSecretRequest) error {
return nil
}
// validateUpdate validates an update request, trimming the name and checking
// length constraints on the fields that are present.
func (s *Service) validateUpdate(req *UpdateSecretRequest) error {
if req.Name != nil {
name := strings.TrimSpace(*req.Name)
req.Name = &name
if name == "" || len(name) > 100 {
return fmt.Errorf("name must be 1-100 characters")
return fmt.Errorf("name must be 1-100 bytes")
}
}
if req.Value != nil && (len(*req.Value) == 0 || len(*req.Value) > 10000) {
@@ -154,6 +167,8 @@ func (s *Service) RevealForWorkspace(ctx context.Context, id, workspaceID string
return s.store.Reveal(ctx, id)
}
// RevealWorkspaceSecret returns the decrypted value of a Workspace secret
// after checking the caller's workspace access.
func (s *Service) RevealWorkspaceSecret(ctx context.Context, id, workspaceID string) (string, error) {
if _, err := s.GetWorkspaceSecret(ctx, id, workspaceID); err != nil {
return "", err
@@ -204,6 +219,8 @@ func (s *Service) UpdateForWorkspace(ctx context.Context, id, workspaceID string
return secretListItem(secret), nil
}
// UpdateWorkspaceSecret validates and updates a Workspace secret after
// checking the caller's workspace access.
func (s *Service) UpdateWorkspaceSecret(ctx context.Context, id, workspaceID string, req *UpdateSecretRequest) (*SecretListItem, error) {
if err := s.validateUpdate(req); err != nil {
return nil, fmt.Errorf("validation: %w", err)
@@ -237,6 +254,8 @@ func (s *Service) DeleteForWorkspace(ctx context.Context, id, workspaceID string
return s.store.Delete(ctx, id)
}
// DeleteWorkspaceSecret deletes a Workspace secret after checking the
// caller's workspace access.
func (s *Service) DeleteWorkspaceSecret(ctx context.Context, id, workspaceID string) error {
if _, err := s.GetWorkspaceSecret(ctx, id, workspaceID); err != nil {
return err
@@ -272,6 +291,8 @@ func (s *Service) ListScoped(ctx context.Context, opts SecretListOptions) ([]*Se
return nil, fmt.Errorf("workspace-scoped secret storage is unavailable")
}
// authorizeScope enforces workspace authorization for workspace-scoped
// requests; global scope requires no check.
func (s *Service) authorizeScope(ctx context.Context, scope SecretScope, workspaceID string) error {
if scope != ScopeWorkspace {
return nil
@@ -282,6 +303,8 @@ func (s *Service) authorizeScope(ctx context.Context, scope SecretScope, workspa
return s.workspaceAuthorizer(ctx, workspaceID)
}
// secretListItem converts a stored secret into a list item with a
// normalized scope.
func secretListItem(secret *Secret) *SecretListItem {
return &SecretListItem{
ID: secret.ID,
@@ -293,3 +316,115 @@ func secretListItem(secret *Secret) *SecretListItem {
UpdatedAt: secret.UpdatedAt,
}
}
// Copy copies a secret into another scope/workspace without removing the
// source. Errors are classified with the package sentinels: validation
// failures wrap ErrSecretValidation, missing/unauthorized sources and
// destinations surface ErrNotFound or ErrWorkspaceAccessDenied, and raw
// lookup/storage failures pass through unclassified (sanitized 500 upstream).
func (s *Service) Copy(ctx context.Context, sourceID, sourceWorkspaceID string, req *CopySecretRequest) (*SecretListItem, error) {
return s.copyOrMove(ctx, sourceID, sourceWorkspaceID, req, false)
}
// Move copies a secret into another scope/workspace and removes the source in
// one atomic store operation.
func (s *Service) Move(ctx context.Context, sourceID, sourceWorkspaceID string, req *CopySecretRequest) (*SecretListItem, error) {
return s.copyOrMove(ctx, sourceID, sourceWorkspaceID, req, true)
}
// copyOrMove is the shared implementation behind Copy and Move: it validates
// the request, resolves the source secret and target name, and performs the
// copy or move in one store operation.
func (s *Service) copyOrMove(ctx context.Context, sourceID, sourceWorkspaceID string, req *CopySecretRequest, move bool) (*SecretListItem, error) {
if req == nil {
return nil, fmt.Errorf("%w: request is required", ErrSecretValidation)
}
if err := validateSecretScope(req.Scope, req.WorkspaceID); err != nil {
return nil, fmt.Errorf("%w: %v", ErrSecretValidation, err)
}
var source *Secret
var err error
if strings.TrimSpace(sourceWorkspaceID) == "" {
source, err = s.Get(ctx, sourceID)
} else {
source, err = s.GetWorkspaceSecret(ctx, sourceID, sourceWorkspaceID)
}
if err != nil {
return nil, err
}
// An explicit name (or an explicit null) is validated here; an omitted
// name is resolved from the source row inside the store's transaction so
// a concurrent rename can never split the copied name from its value.
if req.nameNull || req.Name != nil {
if _, err := resolveTransferName(req, ""); err != nil {
return nil, err
}
}
if normalizeStoredScope(req.Scope) == normalizeStoredScope(source.Scope) && req.WorkspaceID == source.WorkspaceID {
return nil, fmt.Errorf("%w: source and destination scope are the same", ErrSecretValidation)
}
transferStore, ok := s.store.(SecretTransferStore)
if !ok {
return nil, fmt.Errorf("secret transfer storage is unavailable")
}
verifyDestination := s.destinationVerifier(ctx, req)
var secret *Secret
if move {
secret, err = transferStore.MoveScoped(ctx, sourceID, source.WorkspaceID, req.Scope, req.WorkspaceID, req.Name, verifyDestination)
} else {
secret, err = transferStore.CopyScoped(ctx, sourceID, source.WorkspaceID, req.Scope, req.WorkspaceID, req.Name, verifyDestination)
}
if err != nil {
return nil, err
}
return secretListItem(secret), nil
}
// resolveTransferName applies the name presence contract: an omitted name
// (and the absence of an explicit null) uses the source name; an explicit
// null, empty, whitespace-only, or over-length name is a validation error.
// The limit is 100 UTF-8 bytes, matching create/update validation.
func resolveTransferName(req *CopySecretRequest, sourceName string) (string, error) {
if req.nameNull {
return "", fmt.Errorf("%w: name must not be null", ErrSecretValidation)
}
if req.Name == nil {
return sourceName, nil
}
name := strings.TrimSpace(*req.Name)
if name == "" {
return "", fmt.Errorf("%w: name must not be empty", ErrSecretValidation)
}
if len(name) > 100 {
return "", fmt.Errorf("%w: name must be 1-100 bytes", ErrSecretValidation)
}
return name, nil
}
// destinationVerifier returns the in-transaction callback the store invokes
// while holding the destination lock: workspace existence (unconditional,
// fail-closed when unconfigured) then workspace authorization. Global targets
// need no verification.
func (s *Service) destinationVerifier(ctx context.Context, req *CopySecretRequest) func(context.Context) error {
if normalizeStoredScope(req.Scope) != ScopeWorkspace {
return nil
}
// The callback ignores the store-supplied context and uses the outer
// request ctx: the auth callbacks run inside the store's transaction,
// whose context is not the one the request handlers set up.
return func(_ context.Context) error {
if s.workspaceExistence == nil {
return ErrWorkspaceAccessDenied
}
if err := s.workspaceExistence(ctx, req.WorkspaceID); err != nil {
return err
}
return s.authorizeScope(ctx, ScopeWorkspace, req.WorkspaceID)
}
}
+342 -1
View File
@@ -3,7 +3,9 @@ package secrets
import (
"context"
"database/sql"
"errors"
"fmt"
"sort"
"strings"
"time"
@@ -20,6 +22,22 @@ type sqliteStore struct {
ro *sqlx.DB // reader
crypto *MasterKeyProvider
ownsDB bool
// failAfterInsert is a test-only hook. When set, it is invoked after the
// transfer inserts the target row and before the Move source delete runs,
// proving Move is transactional (the inserted copy must roll back).
failAfterInsert func() error
// afterSourceLock is a test-only hook invoked right after the source row
// is selected with FOR UPDATE (Move on PostgreSQL), giving tests a
// deterministic point where the source row lock is known to be held.
afterSourceLock func() error
// beforeTransferInsert is a test-only hook invoked after the conflict
// check and before the conditional insert, letting tests commit a
// competing row at the exact point where the atomic NOT EXISTS guard must
// observe it (PostgreSQL: ordinary creates do not take the transfer lock).
beforeTransferInsert func() error
}
var _ ScopedSecretStore = (*sqliteStore)(nil)
@@ -33,6 +51,7 @@ func Provide(writer, reader *sqlx.DB, crypto *MasterKeyProvider) (*sqliteStore,
return store, store.Close, nil
}
// initSchema creates the secrets table if needed and applies idempotent column migrations.
func (s *sqliteStore) initSchema() error {
binaryType := dialect.BlobType(s.db.DriverName())
schema := fmt.Sprintf(`
@@ -81,6 +100,7 @@ func (s *sqliteStore) ClaimUnowned(ctx context.Context, ownerID string) error {
return err
}
// Close closes the underlying writer connection when the store owns it.
func (s *sqliteStore) Close() error {
if !s.ownsDB {
return nil
@@ -88,6 +108,7 @@ func (s *sqliteStore) Close() error {
return s.db.Close()
}
// Create validates the scope, encrypts the value, and inserts a new secret.
func (s *sqliteStore) Create(ctx context.Context, secret *SecretWithValue) error {
if secret == nil {
return fmt.Errorf("secret is required")
@@ -121,6 +142,7 @@ func (s *sqliteStore) Create(ctx context.Context, secret *SecretWithValue) error
return nil
}
// Get returns a secret's metadata by id, scoped to the caller; ErrNotFound if absent.
func (s *sqliteStore) Get(ctx context.Context, id string) (*Secret, error) {
var row secretRow
err := s.ro.GetContext(ctx, &row, s.ro.Rebind(`
@@ -136,6 +158,7 @@ func (s *sqliteStore) Get(ctx context.Context, id string) (*Secret, error) {
return row.toSecret(), nil
}
// Reveal returns the decrypted plaintext value of the secret with the given id.
func (s *sqliteStore) Reveal(ctx context.Context, id string) (string, error) {
var ciphertext, nonce []byte
err := s.ro.QueryRowContext(ctx, s.ro.Rebind(`
@@ -157,6 +180,7 @@ func (s *sqliteStore) Reveal(ctx context.Context, id string) (string, error) {
return string(plaintext), nil
}
// Update applies the requested name and/or value changes to the secret with the given id.
func (s *sqliteStore) Update(ctx context.Context, id string, req *UpdateSecretRequest) error {
existing, err := s.Get(ctx, id)
if err != nil {
@@ -195,6 +219,7 @@ func (s *sqliteStore) Update(ctx context.Context, id string, req *UpdateSecretRe
return nil
}
// Delete removes the secret with the given id, scoped to the caller; ErrNotFound if absent.
func (s *sqliteStore) Delete(ctx context.Context, id string) error {
result, err := s.db.ExecContext(ctx, s.db.Rebind(`
DELETE FROM secrets WHERE id = ? AND (user_id = '' OR ? = '' OR user_id = ?)`),
@@ -209,10 +234,12 @@ func (s *sqliteStore) Delete(ctx context.Context, id string) error {
return nil
}
// List returns all global secrets visible to the caller.
func (s *sqliteStore) List(ctx context.Context) ([]*SecretListItem, error) {
return s.ListScoped(ctx, SecretListOptions{Scope: ScopeGlobal})
}
// ListScoped returns secrets matching the given scope options, newest first.
func (s *sqliteStore) ListScoped(ctx context.Context, opts SecretListOptions) ([]*SecretListItem, error) {
if err := validateListOptions(opts); err != nil {
return nil, err
@@ -243,6 +270,7 @@ func (s *sqliteStore) ListScoped(ctx context.Context, opts SecretListOptions) ([
return toSecretListItems(rows), nil
}
// GetForWorkspace returns the secret with id if it is global or belongs to the given workspace.
func (s *sqliteStore) GetForWorkspace(ctx context.Context, id, workspaceID string) (*Secret, error) {
if strings.TrimSpace(workspaceID) == "" {
return nil, fmt.Errorf("workspace id is required")
@@ -257,6 +285,7 @@ func (s *sqliteStore) GetForWorkspace(ctx context.Context, id, workspaceID strin
return secret, nil
}
// RevealGlobal returns the decrypted value of the global secret with the given id.
func (s *sqliteStore) RevealGlobal(ctx context.Context, id string) (string, error) {
secret, err := s.Get(ctx, id)
if err != nil {
@@ -268,6 +297,7 @@ func (s *sqliteStore) RevealGlobal(ctx context.Context, id string) (string, erro
return s.Reveal(ctx, id)
}
// RevealForWorkspace returns the decrypted value of a secret visible in the given workspace.
func (s *sqliteStore) RevealForWorkspace(ctx context.Context, id, workspaceID string) (string, error) {
if _, err := s.GetForWorkspace(ctx, id, workspaceID); err != nil {
return "", err
@@ -275,22 +305,43 @@ func (s *sqliteStore) RevealForWorkspace(ctx context.Context, id, workspaceID st
return s.Reveal(ctx, id)
}
// DeleteWorkspaceSecrets removes all workspace-owned secrets for the given workspace in a transaction.
func (s *sqliteStore) DeleteWorkspaceSecrets(ctx context.Context, workspaceID string) error {
if strings.TrimSpace(workspaceID) == "" {
return fmt.Errorf("workspace id is required")
}
return s.deleteWorkspaceSecrets(ctx, s.db, workspaceID)
// Run under a transaction so the PostgreSQL advisory lock is held to
// commit, keeping concurrent secret transfers from inserting into a
// workspace that is being deleted.
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("begin workspace secret cleanup: %w", err)
}
defer func() { _ = tx.Rollback() }()
if err := s.DeleteWorkspaceSecretsTx(ctx, tx, workspaceID); err != nil {
return err
}
return tx.Commit()
}
// DeleteWorkspaceSecretsTx removes workspace-owned secrets on the supplied
// transaction so workspace and secret deletion can commit or roll back as one.
// On PostgreSQL it first acquires the workspace's advisory lock (shared with
// secret transfers), guaranteeing a concurrent transfer cannot insert after
// this cleanup has run.
func (s *sqliteStore) DeleteWorkspaceSecretsTx(ctx context.Context, tx *sqlx.Tx, workspaceID string) error {
if tx == nil {
return fmt.Errorf("transaction is required")
}
if dialect.IsPostgres(s.db.DriverName()) {
if _, err := tx.ExecContext(ctx, s.db.Rebind("SELECT pg_advisory_xact_lock(?)"), WorkspaceLockKey(workspaceID)); err != nil {
return fmt.Errorf("acquire workspace lock: %w", err)
}
}
return s.deleteWorkspaceSecrets(ctx, tx, workspaceID)
}
// deleteWorkspaceSecrets runs the workspace-owned secret deletion on the supplied executor.
func (s *sqliteStore) deleteWorkspaceSecrets(ctx context.Context, exec sqlx.ExtContext, workspaceID string) error {
if strings.TrimSpace(workspaceID) == "" {
return fmt.Errorf("workspace id is required")
@@ -303,6 +354,7 @@ func (s *sqliteStore) deleteWorkspaceSecrets(ctx context.Context, exec sqlx.ExtC
return nil
}
// validateSecretScope rejects scope/workspace combinations that are not allowed.
func validateSecretScope(scope SecretScope, workspaceID string) error {
switch scope {
case ScopeGlobal:
@@ -319,6 +371,7 @@ func validateSecretScope(scope SecretScope, workspaceID string) error {
return nil
}
// validateListOptions rejects list options with an invalid scope or mismatched workspace.
func validateListOptions(opts SecretListOptions) error {
switch opts.Scope {
case ScopeGlobal:
@@ -345,6 +398,7 @@ type secretRow struct {
UpdatedAt time.Time `db:"updated_at"`
}
// toSecret converts the scanned row into a Secret with its stored scope normalized.
func (r *secretRow) toSecret() *Secret {
return &Secret{
ID: r.ID,
@@ -367,6 +421,7 @@ type secretListRow struct {
UpdatedAt time.Time `db:"updated_at"`
}
// toSecretListItems converts scanned list rows into SecretListItems with normalized scopes.
func toSecretListItems(rows []secretListRow) []*SecretListItem {
items := make([]*SecretListItem, len(rows))
for i, r := range rows {
@@ -383,9 +438,295 @@ func toSecretListItems(rows []secretListRow) []*SecretListItem {
return items
}
// normalizeStoredScope maps a legacy empty stored scope to Global.
func normalizeStoredScope(scope SecretScope) SecretScope {
if scope == "" {
return ScopeGlobal
}
return scope
}
// transferExec is the minimal transaction-bound executor used by
// transferBody. Both *sql.Conn (SQLite BEGIN IMMEDIATE path) and *sqlx.Tx
// (PostgreSQL advisory-lock path) satisfy it, so every transfer statement
// runs on the same transaction and never on the store's reader handle.
type transferExec interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
// CopyScoped copies a secret into the target scope under a new name and returns the copy.
func (s *sqliteStore) CopyScoped(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error) (*Secret, error) {
return s.transferScoped(ctx, sourceID, sourceWorkspaceID, targetScope, targetWorkspaceID, requestedName, verifyDestination, false)
}
// MoveScoped moves a secret into the target scope under a new name, deleting the source.
func (s *sqliteStore) MoveScoped(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error) (*Secret, error) {
return s.transferScoped(ctx, sourceID, sourceWorkspaceID, targetScope, targetWorkspaceID, requestedName, verifyDestination, true)
}
// transferScoped runs the atomic copy/move transfer: conflict check, insert, and optional source delete inside one transaction.
func (s *sqliteStore) transferScoped(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error, deleteSource bool) (*Secret, error) {
if err := validateSecretScope(targetScope, targetWorkspaceID); err != nil {
return nil, fmt.Errorf("scope validation: %w", err)
}
if requestedName != nil && strings.TrimSpace(*requestedName) == "" {
return nil, fmt.Errorf("target name is required")
}
if dialect.IsPostgres(s.db.DriverName()) {
return s.transferPostgres(ctx, sourceID, sourceWorkspaceID, targetScope, targetWorkspaceID, requestedName, verifyDestination, deleteSource)
}
return s.transferSQLite(ctx, sourceID, targetScope, targetWorkspaceID, requestedName, verifyDestination, deleteSource)
}
// transferSQLite runs the transfer on the single writer connection with
// BEGIN IMMEDIATE, taking the SQLite write lock up front so competing
// transfers serialize before any read.
func (s *sqliteStore) transferSQLite(ctx context.Context, sourceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error, deleteSource bool) (*Secret, error) {
conn, err := s.db.Conn(ctx)
if err != nil {
return nil, fmt.Errorf("acquire writer connection: %w", err)
}
defer func() { _ = conn.Close() }()
if _, err := conn.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil {
return nil, fmt.Errorf("begin immediate: %w", err)
}
committed := false
defer func() {
if !committed {
// The rollback must reach SQLite even when the caller canceled ctx:
// a canceled ROLLBACK would leave the BEGIN IMMEDIATE transaction
// and its write lock open on the pooled connection.
_, _ = conn.ExecContext(context.WithoutCancel(ctx), "ROLLBACK")
}
}()
// SQLite's single writer serializes all writers (BEGIN IMMEDIATE), so the
// source row cannot change under us; no row lock is needed.
secret, err := s.transferBody(ctx, conn, func(q string) string { return q }, sourceID, targetScope, targetWorkspaceID, requestedName, verifyDestination, deleteSource, false)
if err != nil {
return nil, err
}
if _, err := conn.ExecContext(ctx, "COMMIT"); err != nil {
return nil, fmt.Errorf("commit transfer: %w", err)
}
committed = true
return secret, nil
}
// transferPostgres runs the transfer in a transaction that acquires the
// destination's advisory lock (plus the source workspace's lock for Move) in
// sorted order before any read, serializing competing transfers and
// coordinating with workspace deletion under READ COMMITTED.
func (s *sqliteStore) transferPostgres(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error, deleteSource bool) (*Secret, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin transfer: %w", err)
}
defer func() { _ = tx.Rollback() }()
keys := []int64{transferTargetLockKey(targetScope, targetWorkspaceID)}
if deleteSource && strings.TrimSpace(sourceWorkspaceID) != "" {
keys = append(keys, WorkspaceLockKey(sourceWorkspaceID))
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
var prev int64
first := true
for _, key := range keys {
if !first && key == prev {
continue
}
if _, err := tx.ExecContext(ctx, s.db.Rebind("SELECT pg_advisory_xact_lock(?)"), key); err != nil {
return nil, fmt.Errorf("acquire transfer lock: %w", err)
}
prev = key
first = false
}
// A Move destroys the source, so the source row is locked with FOR UPDATE
// (deleteSource == true): a concurrent Update cannot commit a newer value
// between our read and delete, which would otherwise lose that value.
secret, err := s.transferBody(ctx, tx, s.db.Rebind, sourceID, targetScope, targetWorkspaceID, requestedName, verifyDestination, deleteSource, deleteSource)
if err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit transfer: %w", err)
}
return secret, nil
}
// transferTargetLockKey returns the advisory-lock key for a transfer target:
// the workspace key for Workspace targets, the Global constant otherwise.
func transferTargetLockKey(targetScope SecretScope, targetWorkspaceID string) int64 {
if normalizeStoredScope(targetScope) != ScopeWorkspace {
return GlobalSecretTransferLockKey
}
return WorkspaceLockKey(targetWorkspaceID)
}
// transferBody executes the shared transfer steps on the transaction-bound
// executor: destination verification (while the lock is held), source select,
// normalized-scope conflict check, insert of the copy (reusing the source's
// encrypted value), optional source delete, and the returned-row read. Every
// statement uses the same executor and the per-user visibility predicate.
func (s *sqliteStore) transferBody(ctx context.Context, exec transferExec, rebind func(string) string, sourceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error, deleteSource, lockSource bool) (*Secret, error) {
owner := scopeOwner(ctx)
if verifyDestination != nil {
if err := verifyDestination(ctx); err != nil {
return nil, err
}
}
src, err := s.transferSource(ctx, exec, rebind, sourceID, owner, lockSource)
if err != nil {
return nil, err
}
// An omitted name resolves from the transactional source row: a concurrent
// rename can never split the copied name from its value (or, for Move,
// delete the renamed row and recreate it under a stale name).
targetName := ""
if requestedName == nil {
targetName = src.Name
} else {
targetName = *requestedName
}
if err := s.transferConflictCheck(ctx, exec, rebind, targetScope, targetWorkspaceID, targetName, owner); err != nil {
return nil, err
}
now := time.Now().UTC()
storedScope := normalizeStoredScope(targetScope)
copyID := uuid.New().String()
if s.beforeTransferInsert != nil {
if err := s.beforeTransferInsert(); err != nil {
return nil, err
}
}
// The insert is guarded by the same conflict predicate atomically: on
// PostgreSQL, an ordinary create or rename does not take the transfer's
// advisory lock, so the eager check alone could race a late commit of the
// same name. NOT EXISTS turns that race into a clean conflict instead of a
// duplicate row.
predicate, predicateArgs := transferConflictPredicate(targetScope, targetWorkspaceID, targetName, owner)
result, err := exec.ExecContext(ctx, rebind(`
INSERT INTO secrets (id, name, user_id, scope, workspace_id, encrypted_value, nonce, created_at, updated_at)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?
WHERE NOT EXISTS (SELECT 1 FROM secrets WHERE `+predicate+`)`),
append([]any{copyID, targetName, owner, storedScope, targetWorkspaceID, src.Ciphertext, src.Nonce, now, now}, predicateArgs...)...)
if err != nil {
return nil, fmt.Errorf("insert transferred secret: %w", err)
}
rows, _ := result.RowsAffected()
if rows == 0 {
return nil, ErrSecretNameConflict
}
if deleteSource {
if err := s.deleteTransferredSource(ctx, exec, rebind, sourceID, owner); err != nil {
return nil, err
}
}
var meta secretRow
if err := exec.QueryRowContext(ctx, rebind(`
SELECT id, name, scope, workspace_id, created_at, updated_at FROM secrets WHERE id = ?`),
copyID).Scan(&meta.ID, &meta.Name, &meta.Scope, &meta.WorkspaceID, &meta.CreatedAt, &meta.UpdatedAt); err != nil {
return nil, fmt.Errorf("read transferred secret: %w", err)
}
return meta.toSecret(), nil
}
// deleteTransferredSource removes the source row using the same per-user
// visibility predicate as the source select. A missing row means the source
// vanished concurrently and the whole transfer rolls back.
func (s *sqliteStore) deleteTransferredSource(ctx context.Context, exec transferExec, rebind func(string) string, sourceID, owner string) error {
if s.failAfterInsert != nil {
if err := s.failAfterInsert(); err != nil {
return err
}
}
result, err := exec.ExecContext(ctx, rebind(`
DELETE FROM secrets WHERE id = ? AND (user_id = '' OR ? = '' OR user_id = ?)`),
sourceID, owner, owner)
if err != nil {
return fmt.Errorf("delete transferred source: %w", err)
}
rows, _ := result.RowsAffected()
if rows == 0 {
return fmt.Errorf("%w: %s", ErrNotFound, sourceID)
}
return nil
}
// transferSourceRow is the decrypted-source scan target for transferBody.
type transferSourceRow struct {
ID string
Name string
Scope SecretScope
WorkspaceID string
Ciphertext []byte
Nonce []byte
}
// transferSource selects the source row with the per-user visibility
// predicate. On PostgreSQL Moves (lockSource) it appends FOR UPDATE so a
// concurrent Update cannot interleave between the read and the delete; the
// afterSourceLock test hook fires once the row lock is known to be held.
func (s *sqliteStore) transferSource(ctx context.Context, exec transferExec, rebind func(string) string, sourceID, owner string, lockSource bool) (*transferSourceRow, error) {
query := `
SELECT id, name, scope, workspace_id, encrypted_value, nonce
FROM secrets WHERE id = ? AND (user_id = '' OR ? = '' OR user_id = ?)`
if lockSource {
query += " FOR UPDATE"
}
var src transferSourceRow
err := exec.QueryRowContext(ctx, rebind(query), sourceID, owner, owner).
Scan(&src.ID, &src.Name, &src.Scope, &src.WorkspaceID, &src.Ciphertext, &src.Nonce)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("%w: %s", ErrNotFound, sourceID)
}
return nil, fmt.Errorf("transfer source lookup: %w", err)
}
if lockSource && s.afterSourceLock != nil {
if err := s.afterSourceLock(); err != nil {
return nil, err
}
}
return &src, nil
}
// transferConflictPredicate returns the WHERE predicate and arguments that
// identify an existing secret with the given name in the destination scope,
// comparing the NORMALIZED scope so a legacy empty stored scope (which reads
// as Global) can never be bypassed. Shared by the eager conflict check and the
// atomic NOT EXISTS guard on the transfer insert.
func transferConflictPredicate(targetScope SecretScope, targetWorkspaceID, targetName, owner string) (string, []any) {
if normalizeStoredScope(targetScope) != ScopeWorkspace {
return `name = ? AND (scope = ? OR scope = '') AND (user_id = '' OR ? = '' OR user_id = ?)`,
[]any{targetName, ScopeGlobal, owner, owner}
}
return `name = ? AND scope = ? AND workspace_id = ? AND (user_id = '' OR ? = '' OR user_id = ?)`,
[]any{targetName, ScopeWorkspace, targetWorkspaceID, owner, owner}
}
// transferConflictCheck rejects a target name that already exists in the
// destination scope. It is the eager, pre-insert check; the insert itself is
// guarded by the same predicate atomically (see transferBody), so a competing
// create or rename that commits after this check can still never produce a
// duplicate name from the transfer.
func (s *sqliteStore) transferConflictCheck(ctx context.Context, exec transferExec, rebind func(string) string, targetScope SecretScope, targetWorkspaceID, targetName, owner string) error {
predicate, args := transferConflictPredicate(targetScope, targetWorkspaceID, targetName, owner)
query := `SELECT 1 FROM secrets WHERE ` + predicate + ` LIMIT 1`
var found int
if err := exec.QueryRowContext(ctx, rebind(query), args...).Scan(&found); err == nil {
return ErrSecretNameConflict
} else if !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("transfer conflict check: %w", err)
}
return nil
}
+57
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"hash/fnv"
"github.com/jmoiron/sqlx"
)
@@ -14,6 +15,40 @@ import (
// rather than string-matching the error text.
var ErrNotFound = errors.New("secret not found")
// ErrSecretNameConflict is returned when a copy/move target name already
// exists in the destination scope. Handlers map it to 409 Conflict.
var ErrSecretNameConflict = errors.New("a secret with this name already exists in the target scope")
// ErrWorkspaceAccessDenied is returned for missing or unauthorized
// destination workspaces (and unconfigured workspace verification). Handlers
// map it to 404 Not Found so a nonexistent workspace is indistinguishable
// from an inaccessible one.
var ErrWorkspaceAccessDenied = errors.New("workspace access denied or workspace not found")
// ErrSecretValidation marks validation failures on copy/move requests.
// Handlers map it to 400 Bad Request.
var ErrSecretValidation = errors.New("secret validation failed")
// GlobalSecretTransferLockKey is the advisory-lock key used for transfers
// whose target scope is Global. It is a distinct stable constant, never
// derived from a workspace ID, so concurrent same-name Global transfers
// serialize and exactly one wins.
const GlobalSecretTransferLockKey int64 = 0x4B53544600000001 // "KSTF"
const transferLockPrefix = "kandev-secret-transfer:"
// WorkspaceLockKey returns the deterministic advisory-lock key for a
// workspace. The FNV-1a 64-bit hash is stable across restarts and
// collision-safe for UUID inputs (a theoretical collision only over-serializes
// transfers, never corrupts data). PostgreSQL uses these keys to coordinate
// secret transfers with workspace deletion; SQLite's single writer needs no
// advisory locks.
func WorkspaceLockKey(workspaceID string) int64 {
h := fnv.New64a()
_, _ = h.Write([]byte(transferLockPrefix + workspaceID))
return int64(h.Sum64())
}
// SecretStore abstracts secret storage. Implementations handle
// encryption/decryption internally.
type SecretStore interface {
@@ -68,6 +103,28 @@ type ScopedSecretStore interface {
DeleteWorkspaceSecrets(ctx context.Context, workspaceID string) error
}
// SecretTransferStore is implemented by stores that can atomically copy or
// move a secret into another scope/workspace. It is a narrow optional
// interface, separate from ScopedSecretStore, so scope-aware read and
// lifecycle stores (and their test doubles) are not forced to implement
// transfer behavior.
type SecretTransferStore interface {
// CopyScoped atomically copies a secret into another scope/workspace and
// returns the new row's metadata. requestedName nil keeps the source
// name, resolved from the source row read inside the transaction (so a
// concurrent rename can never split the copied name from its value).
// verifyDestination runs inside the transaction while the destination
// lock is held, before the conflict check and insert; an error rolls back
// and surfaces. sourceWorkspaceID is the resolved source's workspace
// ("" for Global) and is locked alongside the destination for Move so
// concurrent same-source moves serialize without deadlock.
CopyScoped(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error) (*Secret, error)
// MoveScoped atomically copies a secret into another scope/workspace and
// deletes the source in the same transaction; the name contract matches
// CopyScoped.
MoveScoped(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error) (*Secret, error)
}
// WorkspaceSecretTransactionalDeleter is implemented by stores that can
// remove workspace-owned secrets on a caller-owned SQL transaction.
type WorkspaceSecretTransactionalDeleter interface {
@@ -0,0 +1,450 @@
package secrets
import (
"context"
"errors"
"path/filepath"
"testing"
"time"
"github.com/jmoiron/sqlx"
"github.com/kandev/kandev/internal/auth/authn"
"github.com/kandev/kandev/internal/db"
)
// testTransferContext returns a context carrying the given user identity, or a bare background context when userID is empty.
func testTransferContext(userID string) context.Context {
if userID == "" {
return context.Background()
}
return authn.WithIdentity(context.Background(), authn.Identity{UserID: userID})
}
// mustCreate seeds a secret via the store, failing the test on error.
func mustCreate(t *testing.T, store SecretStore, secret *SecretWithValue) {
t.Helper()
if err := store.Create(context.Background(), secret); err != nil {
t.Fatalf("seed secret: %v", err)
}
}
// strPtr returns a pointer to s for presence-aware transfer arguments.
func strPtr(s string) *string { return &s }
// TestTransferStore_CopyGlobalToWorkspace verifies a global-to-workspace copy keeps the source, sets timestamps, and carries the value server-side.
func TestTransferStore_CopyGlobalToWorkspace(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v1"})
got, err := store.CopyScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied"), nil)
if err != nil {
t.Fatalf("CopyScoped: %v", err)
}
if got.Scope != ScopeWorkspace || got.WorkspaceID != "workspace-a" || got.Name != "copied" {
t.Fatalf("copy metadata = %+v", got)
}
if got.CreatedAt.IsZero() || got.UpdatedAt.IsZero() {
t.Fatalf("copy timestamps are zero: %+v", got)
}
// Source intact.
if _, err := store.Get(ctx, "g1"); err != nil {
t.Fatalf("source missing after copy: %v", err)
}
// Value carried server-side, verifiable only through reveal.
value, err := store.RevealForWorkspace(ctx, got.ID, "workspace-a")
if err != nil {
t.Fatalf("reveal copy: %v", err)
}
if value != "v1" {
t.Fatalf("copy value = %q, want v1", value)
}
}
// TestTransferStore_CopyWorkspaceToGlobal verifies a workspace-to-global copy lands in the global scope with the value intact and the source kept.
func TestTransferStore_CopyWorkspaceToGlobal(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "w1", Name: "ws", Scope: ScopeWorkspace, WorkspaceID: "workspace-a"}, Value: "v2"})
got, err := store.CopyScoped(ctx, "w1", "workspace-a", ScopeGlobal, "", strPtr("global-copy"), nil)
if err != nil {
t.Fatalf("CopyScoped: %v", err)
}
if got.Scope != ScopeGlobal || got.WorkspaceID != "" || got.Name != "global-copy" {
t.Fatalf("copy metadata = %+v", got)
}
value, err := store.RevealGlobal(ctx, got.ID)
if err != nil {
t.Fatalf("reveal global copy: %v", err)
}
if value != "v2" {
t.Fatalf("copy value = %q, want v2", value)
}
if _, err := store.Get(ctx, "w1"); err != nil {
t.Fatalf("source missing after copy: %v", err)
}
}
// TestTransferStore_CopyWorkspaceToWorkspace verifies a workspace-to-workspace copy lands in the target workspace with the value intact.
func TestTransferStore_CopyWorkspaceToWorkspace(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "w1", Name: "ws", Scope: ScopeWorkspace, WorkspaceID: "workspace-a"}, Value: "v3"})
got, err := store.CopyScoped(ctx, "w1", "workspace-a", ScopeWorkspace, "workspace-b", strPtr("moved"), nil)
if err != nil {
t.Fatalf("CopyScoped: %v", err)
}
if got.WorkspaceID != "workspace-b" {
t.Fatalf("copy workspace = %q, want workspace-b", got.WorkspaceID)
}
value, err := store.RevealForWorkspace(ctx, got.ID, "workspace-b")
if err != nil {
t.Fatalf("reveal copy: %v", err)
}
if value != "v3" {
t.Fatalf("copy value = %q, want v3", value)
}
}
// TestTransferStore_MoveWorkspaceToGlobalRemovesSource verifies moving a workspace secret to global removes the source and preserves the value.
func TestTransferStore_MoveWorkspaceToGlobalRemovesSource(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "w1", Name: "ws", Scope: ScopeWorkspace, WorkspaceID: "workspace-a"}, Value: "v4"})
got, err := store.MoveScoped(ctx, "w1", "workspace-a", ScopeGlobal, "", strPtr("global-copy"), nil)
if err != nil {
t.Fatalf("MoveScoped: %v", err)
}
if got.Scope != ScopeGlobal {
t.Fatalf("moved metadata scope = %q", got.Scope)
}
if _, err := store.Get(ctx, "w1"); !errors.Is(err, ErrNotFound) {
t.Fatalf("source still present after move: %v", err)
}
value, err := store.RevealGlobal(ctx, got.ID)
if err != nil {
t.Fatalf("reveal moved copy: %v", err)
}
if value != "v4" {
t.Fatalf("moved value = %q, want v4", value)
}
}
// TestTransferStore_MoveGlobalToWorkspaceRemovesSource verifies moving a global secret into a workspace removes the source.
func TestTransferStore_MoveGlobalToWorkspaceRemovesSource(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v5"})
got, err := store.MoveScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied"), nil)
if err != nil {
t.Fatalf("MoveScoped: %v", err)
}
if got.WorkspaceID != "workspace-a" {
t.Fatalf("moved workspace = %q", got.WorkspaceID)
}
if _, err := store.Get(ctx, "g1"); !errors.Is(err, ErrNotFound) {
t.Fatalf("source still present after move: %v", err)
}
}
// TestTransferStore_ConflictGlobal verifies a Global target name collision returns ErrSecretNameConflict.
func TestTransferStore_ConflictGlobal(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g2", Name: "taken"}, Value: "other"})
_, err := store.CopyScoped(ctx, "g1", "", ScopeGlobal, "", strPtr("taken"), nil)
if !errors.Is(err, ErrSecretNameConflict) {
t.Fatalf("error = %v, want ErrSecretNameConflict", err)
}
}
// TestTransferStore_ConflictWorkspace verifies a workspace target name collision returns ErrSecretNameConflict.
func TestTransferStore_ConflictWorkspace(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "w1", Name: "taken", Scope: ScopeWorkspace, WorkspaceID: "workspace-a"}, Value: "other"})
_, err := store.CopyScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("taken"), nil)
if !errors.Is(err, ErrSecretNameConflict) {
t.Fatalf("error = %v, want ErrSecretNameConflict", err)
}
}
// TestTransferStore_ConflictLegacyEmptyScopeGlobal verifies a legacy empty-scope row conflicts with a Global target name.
func TestTransferStore_ConflictLegacyEmptyScopeGlobal(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
// Seed a legacy row whose stored scope is empty (pre-scope migration state).
ciphertext, nonce, err := Encrypt([]byte("legacy"), store.crypto.Key())
if err != nil {
t.Fatalf("encrypt legacy: %v", err)
}
now := time.Now().UTC()
if _, err := store.db.ExecContext(ctx, store.db.Rebind(`
INSERT INTO secrets (id, name, user_id, scope, workspace_id, encrypted_value, nonce, created_at, updated_at)
VALUES (?, ?, '', '', '', ?, ?, ?, ?)`),
"legacy-1", "taken", ciphertext, nonce, now, now); err != nil {
t.Fatalf("seed legacy row: %v", err)
}
_, err = store.CopyScoped(ctx, "g1", "", ScopeGlobal, "", strPtr("taken"), nil)
if !errors.Is(err, ErrSecretNameConflict) {
t.Fatalf("error = %v, want ErrSecretNameConflict (legacy empty scope is Global)", err)
}
}
// TestTransferStore_SourceMissing verifies copying an unknown source returns ErrNotFound.
func TestTransferStore_SourceMissing(t *testing.T) {
store := newTestSQLiteStore(t)
_, err := store.CopyScoped(context.Background(), "nope", "", ScopeWorkspace, "workspace-a", strPtr("x"), nil)
if !errors.Is(err, ErrNotFound) {
t.Fatalf("error = %v, want ErrNotFound", err)
}
}
// TestTransferStore_VerifyDestinationErrorRollsBack verifies a failing verifyDestination callback rolls back the copy, leaving no destination row and the source intact.
func TestTransferStore_VerifyDestinationErrorRollsBack(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
denied := errors.New("destination denied")
_, err := store.CopyScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied"), func(context.Context) error {
return denied
})
if !errors.Is(err, denied) {
t.Fatalf("error = %v, want the callback error", err)
}
items, err := store.ListScoped(ctx, SecretListOptions{Scope: ScopeWorkspace, WorkspaceID: "workspace-a"})
if err != nil {
t.Fatalf("list: %v", err)
}
if len(items) != 0 {
t.Fatalf("destination rows = %d, want 0 after callback rollback", len(items))
}
if _, err := store.Get(ctx, "g1"); err != nil {
t.Fatalf("source lost after callback rollback: %v", err)
}
}
// TestTransferStore_MoveFailpointAfterInsertRollsBack verifies Move is transactional: an injected delete failure rolls back the inserted copy.
func TestTransferStore_MoveFailpointAfterInsertRollsBack(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
store.failAfterInsert = func() error { return errors.New("injected delete failure") }
_, err := store.MoveScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied"), nil)
if err == nil {
t.Fatal("MoveScoped succeeded despite injected failpoint")
}
// Source intact, no destination row: Move is transactional, not copy-then-commit-delete.
if _, err := store.Get(ctx, "g1"); err != nil {
t.Fatalf("source lost after failpoint rollback: %v", err)
}
items, err := store.ListScoped(ctx, SecretListOptions{Scope: ScopeWorkspace, WorkspaceID: "workspace-a"})
if err != nil {
t.Fatalf("list: %v", err)
}
if len(items) != 0 {
t.Fatalf("destination rows = %d, want 0 after failpoint rollback", len(items))
}
}
// TestTransferStore_RollbackSurvivesCanceledContext verifies the deferred
// ROLLBACK reaches SQLite even when the caller cancels the context mid-transfer:
// a canceled rollback would leave the BEGIN IMMEDIATE transaction and its write
// lock open on the pooled connection, breaking every later transfer.
func TestTransferStore_RollbackSurvivesCanceledContext(t *testing.T) {
store := newTestSQLiteStore(t)
// Pin the writer pool to one connection so the follow-up transfer MUST
// reuse the connection that ran the failed transfer: a leaked BEGIN
// IMMEDIATE transaction on it would break the next transfer.
store.db.SetMaxOpenConns(1)
ctx, cancel := context.WithCancel(context.Background())
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
// Cancel after the destination insert: the source delete then fails with
// context.Canceled, and the deferred rollback must still reach SQLite.
store.failAfterInsert = func() error {
cancel()
return nil
}
_, err := store.MoveScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied"), nil)
if !errors.Is(err, context.Canceled) {
t.Fatalf("MoveScoped error = %v, want context.Canceled", err)
}
// The write lock must be released: a second transfer on the same pooled
// connection can BEGIN IMMEDIATE again. If the rollback leaked, this
// fails with "cannot start a transaction within a transaction".
store.failAfterInsert = nil
if _, err := store.MoveScoped(context.Background(), "g1", "", ScopeWorkspace, "workspace-a", strPtr("copied-again"), nil); err != nil {
t.Fatalf("second transfer failed: %v (leaked transaction/write lock?)", err)
}
}
// TestTransferStore_OmittedNameUsesCurrentSourceName verifies an omitted name
// resolves from the source row read inside the transaction: a rename that
// lands before the transfer is reflected in the copy (and Move removes the
// renamed row), never a stale pre-transaction read.
func TestTransferStore_OmittedNameUsesCurrentSourceName(t *testing.T) {
store := newTestSQLiteStore(t)
ctx := context.Background()
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "g1", Name: "orig"}, Value: "v"})
// Simulate a rename committing between a stale pre-read and the transfer.
if err := store.Update(ctx, "g1", &UpdateSecretRequest{Name: strPtr("renamed")}); err != nil {
t.Fatalf("rename: %v", err)
}
got, err := store.CopyScoped(ctx, "g1", "", ScopeWorkspace, "workspace-a", nil, nil)
if err != nil {
t.Fatalf("CopyScoped: %v", err)
}
if got.Name != "renamed" {
t.Fatalf("copy name = %q, want the current source name %q", got.Name, "renamed")
}
// Move with an omitted name deletes the renamed source and carries its name.
got2, err := store.MoveScoped(ctx, "g1", "", ScopeWorkspace, "workspace-b", nil, nil)
if err != nil {
t.Fatalf("MoveScoped: %v", err)
}
if got2.Name != "renamed" {
t.Fatalf("moved name = %q, want %q", got2.Name, "renamed")
}
if _, err := store.Get(ctx, "g1"); err == nil {
t.Fatal("source still present after move")
}
}
// TestTransferStore_PerUserScoping verifies secrets are per-user: another user cannot copy or read them, while the owner can move and read the copy.
func TestTransferStore_PerUserScoping(t *testing.T) {
store := newTestSQLiteStore(t)
alice := testTransferContext("user-a")
bob := testTransferContext("user-b")
// Alice owns a workspace secret; Bob must not see or move it.
mustCreate(t, store, &SecretWithValue{Secret: Secret{ID: "w1", Name: "alice-ws", Scope: ScopeWorkspace, WorkspaceID: "workspace-a"}, Value: "v"})
// The seed above ran unscoped (background ctx), so claim it for Alice by
// re-creating under her identity: delete the unowned row first.
if err := store.Delete(context.Background(), "w1"); err != nil {
t.Fatalf("cleanup seed: %v", err)
}
if err := store.Create(alice, &SecretWithValue{Secret: Secret{ID: "w1", Name: "alice-ws", Scope: ScopeWorkspace, WorkspaceID: "workspace-a"}, Value: "v"}); err != nil {
t.Fatalf("seed as alice: %v", err)
}
if _, err := store.CopyScoped(bob, "w1", "workspace-a", ScopeGlobal, "", strPtr("x"), nil); !errors.Is(err, ErrNotFound) {
t.Fatalf("bob copying alice's secret: err = %v, want ErrNotFound", err)
}
// Alice can move her own secret to Global.
got, err := store.MoveScoped(alice, "w1", "workspace-a", ScopeGlobal, "", strPtr("alice-global"), nil)
if err != nil {
t.Fatalf("alice move: %v", err)
}
// The moved copy is owned by Alice and invisible to Bob.
if _, err := store.Get(bob, got.ID); !errors.Is(err, ErrNotFound) {
t.Fatalf("bob reading alice's copy: err = %v, want ErrNotFound", err)
}
if _, err := store.Get(alice, got.ID); err != nil {
t.Fatalf("alice reading her copy: %v", err)
}
}
// TestTransferStore_UserVisibleStoreRejectsInternalSource verifies the user-visible wrapper rejects copying internal backend-owned secrets as ErrNotFound.
func TestTransferStore_UserVisibleStoreRejectsInternalSource(t *testing.T) {
raw := newTestSQLiteStore(t)
// Seed an internal backend-owned row through the RAW store (the wrapper
// refuses to create it).
mustCreate(t, raw, &SecretWithValue{Secret: Secret{ID: "github:user:workspace:user:access", Name: "internal"}, Value: "token"})
wrapper, ok := NewUserVisibleStore(raw).(SecretTransferStore)
if !ok {
t.Fatal("wrapper is not a SecretTransferStore")
}
_, err := wrapper.CopyScoped(context.Background(), "github:user:workspace:user:access", "", ScopeGlobal, "", strPtr("x"), nil)
if !errors.Is(err, ErrNotFound) {
t.Fatalf("error = %v, want ErrNotFound for internal source", err)
}
}
// TestTransferStore_ConcurrentSameTargetSQLite verifies concurrent same-name copies to a Global target serialize on the SQLite write lock with exactly one winner.
func TestTransferStore_ConcurrentSameTargetSQLite(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "secrets.db")
conn1, err := db.OpenSQLite(dbPath)
if err != nil {
t.Fatalf("open db 1: %v", err)
}
t.Cleanup(func() { _ = conn1.Close() })
conn2, err := db.OpenSQLite(dbPath)
if err != nil {
t.Fatalf("open db 2: %v", err)
}
t.Cleanup(func() { _ = conn2.Close() })
crypto, err := NewMasterKeyProvider(dir)
if err != nil {
t.Fatalf("master key: %v", err)
}
store1, cleanup1, err := Provide(sqlx.NewDb(conn1, "sqlite3"), sqlx.NewDb(conn1, "sqlite3"), crypto)
if err != nil {
t.Fatalf("provide store 1: %v", err)
}
t.Cleanup(func() { _ = cleanup1() })
store2, cleanup2, err := Provide(sqlx.NewDb(conn2, "sqlite3"), sqlx.NewDb(conn2, "sqlite3"), crypto)
if err != nil {
t.Fatalf("provide store 2: %v", err)
}
t.Cleanup(func() { _ = cleanup2() })
ctx := context.Background()
mustCreate(t, store1, &SecretWithValue{Secret: Secret{ID: "src", Name: "orig"}, Value: "v"})
locked := make(chan struct{})
release := make(chan struct{})
done := make(chan error, 1)
go func() {
_, err := store1.CopyScoped(ctx, "src", "", ScopeGlobal, "", strPtr("dup"), func(context.Context) error {
close(locked)
<-release
return nil
})
done <- err
}()
// A holds the SQLite write lock (BEGIN IMMEDIATE + callback in-flight).
<-locked
bErr := make(chan error, 1)
go func() {
_, err := store2.CopyScoped(ctx, "src", "", ScopeGlobal, "", strPtr("dup"), nil)
bErr <- err
}()
select {
case err := <-bErr:
t.Fatalf("B completed while A held the lock: %v", err)
case <-time.After(300 * time.Millisecond):
// B is blocked at the SQLite transaction lock, not at a Go pool.
}
close(release)
if err := <-done; err != nil {
t.Fatalf("A: %v", err)
}
err = <-bErr
if !errors.Is(err, ErrSecretNameConflict) {
t.Fatalf("B error = %v, want ErrSecretNameConflict", err)
}
}
@@ -20,18 +20,30 @@ func IsInternalID(id string) bool {
// underlying store remains available to integration services for their
// deterministic internal keys.
type UserVisibleStore struct {
store SecretStore
scoped ScopedSecretStore
store SecretStore
// scoped carries both the scope-aware read/lifecycle surface and the
// transfer surface the wrapper exposes to the service.
scoped userVisibleScopedStore
}
// userVisibleScopedStore is the store surface UserVisibleStore forwards:
// scope-aware reads/lifecycle plus atomic scope transfers.
type userVisibleScopedStore interface {
ScopedSecretStore
SecretTransferStore
}
// NewUserVisibleStore wraps a SecretStore, returning a store that exposes
// only user-managed credentials; it returns nil when store is nil.
func NewUserVisibleStore(store SecretStore) SecretStore {
if store == nil {
return nil
}
scoped, _ := store.(ScopedSecretStore)
scoped, _ := store.(userVisibleScopedStore)
return &UserVisibleStore{store: store, scoped: scoped}
}
// Create creates a secret owned by the current user.
func (s *UserVisibleStore) Create(ctx context.Context, secret *SecretWithValue) error {
if secret != nil && IsInternalID(secret.ID) {
return internalSecretNotFound(secret.ID)
@@ -39,6 +51,8 @@ func (s *UserVisibleStore) Create(ctx context.Context, secret *SecretWithValue)
return s.store.Create(ctx, secret)
}
// Get returns the global user-visible secret with the given id, treating
// internal ids and non-global scopes as not found.
func (s *UserVisibleStore) Get(ctx context.Context, id string) (*Secret, error) {
if IsInternalID(id) {
return nil, internalSecretNotFound(id)
@@ -53,6 +67,7 @@ func (s *UserVisibleStore) Get(ctx context.Context, id string) (*Secret, error)
return secret, nil
}
// Reveal returns the plaintext value of the user-visible secret with the given id.
func (s *UserVisibleStore) Reveal(ctx context.Context, id string) (string, error) {
if IsInternalID(id) {
return "", internalSecretNotFound(id)
@@ -63,6 +78,7 @@ func (s *UserVisibleStore) Reveal(ctx context.Context, id string) (string, error
return s.store.Reveal(ctx, id)
}
// Update updates the user-visible secret with the given id.
func (s *UserVisibleStore) Update(ctx context.Context, id string, req *UpdateSecretRequest) error {
if IsInternalID(id) {
return internalSecretNotFound(id)
@@ -73,6 +89,7 @@ func (s *UserVisibleStore) Update(ctx context.Context, id string, req *UpdateSec
return s.store.Update(ctx, id, req)
}
// Delete deletes the user-visible secret with the given id.
func (s *UserVisibleStore) Delete(ctx context.Context, id string) error {
if IsInternalID(id) {
return internalSecretNotFound(id)
@@ -83,6 +100,7 @@ func (s *UserVisibleStore) Delete(ctx context.Context, id string) error {
return s.store.Delete(ctx, id)
}
// List returns all user-visible (non-internal) secrets.
func (s *UserVisibleStore) List(ctx context.Context) ([]*SecretListItem, error) {
if s.scoped != nil {
return s.ListScoped(ctx, SecretListOptions{Scope: ScopeGlobal})
@@ -100,6 +118,7 @@ func (s *UserVisibleStore) List(ctx context.Context) ([]*SecretListItem, error)
return visible, nil
}
// ListScoped returns user-visible secrets matching the given scope options.
func (s *UserVisibleStore) ListScoped(ctx context.Context, opts SecretListOptions) ([]*SecretListItem, error) {
if opts.Scope == "" {
opts.Scope = ScopeGlobal
@@ -117,6 +136,7 @@ func (s *UserVisibleStore) ListScoped(ctx context.Context, opts SecretListOption
return filterInternalSecretItems(items), nil
}
// GetForWorkspace returns the user-visible secret with the given id scoped to the workspace.
func (s *UserVisibleStore) GetForWorkspace(ctx context.Context, id, workspaceID string) (*Secret, error) {
if IsInternalID(id) {
return nil, internalSecretNotFound(id)
@@ -127,6 +147,7 @@ func (s *UserVisibleStore) GetForWorkspace(ctx context.Context, id, workspaceID
return s.scoped.GetForWorkspace(ctx, id, workspaceID)
}
// RevealGlobal returns the plaintext value of the global user-visible secret with the given id.
func (s *UserVisibleStore) RevealGlobal(ctx context.Context, id string) (string, error) {
if IsInternalID(id) {
return "", internalSecretNotFound(id)
@@ -137,6 +158,7 @@ func (s *UserVisibleStore) RevealGlobal(ctx context.Context, id string) (string,
return s.store.Reveal(ctx, id)
}
// RevealForWorkspace returns the plaintext value of the user-visible secret with the given id scoped to the workspace.
func (s *UserVisibleStore) RevealForWorkspace(ctx context.Context, id, workspaceID string) (string, error) {
if IsInternalID(id) {
return "", internalSecretNotFound(id)
@@ -150,6 +172,7 @@ func (s *UserVisibleStore) RevealForWorkspace(ctx context.Context, id, workspace
return s.store.Reveal(ctx, id)
}
// DeleteWorkspaceSecrets deletes all user-visible secrets scoped to the given workspace.
func (s *UserVisibleStore) DeleteWorkspaceSecrets(ctx context.Context, workspaceID string) error {
if s.scoped == nil {
return fmt.Errorf("workspace-scoped secret storage is unavailable")
@@ -157,6 +180,29 @@ func (s *UserVisibleStore) DeleteWorkspaceSecrets(ctx context.Context, workspace
return s.scoped.DeleteWorkspaceSecrets(ctx, workspaceID)
}
// CopyScoped copies the user-visible secret to the target scope after the destination verifier approves.
func (s *UserVisibleStore) CopyScoped(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error) (*Secret, error) {
if IsInternalID(sourceID) {
return nil, internalSecretNotFound(sourceID)
}
if s.scoped == nil {
return nil, fmt.Errorf("workspace-scoped secret storage is unavailable")
}
return s.scoped.CopyScoped(ctx, sourceID, sourceWorkspaceID, targetScope, targetWorkspaceID, requestedName, verifyDestination)
}
// MoveScoped moves the user-visible secret to the target scope after the destination verifier approves.
func (s *UserVisibleStore) MoveScoped(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID string, requestedName *string, verifyDestination func(context.Context) error) (*Secret, error) {
if IsInternalID(sourceID) {
return nil, internalSecretNotFound(sourceID)
}
if s.scoped == nil {
return nil, fmt.Errorf("workspace-scoped secret storage is unavailable")
}
return s.scoped.MoveScoped(ctx, sourceID, sourceWorkspaceID, targetScope, targetWorkspaceID, requestedName, verifyDestination)
}
// DeleteWorkspaceSecretsTx deletes workspace-scoped user-visible secrets inside the given transaction.
func (s *UserVisibleStore) DeleteWorkspaceSecretsTx(ctx context.Context, tx *sqlx.Tx, workspaceID string) error {
if s.scoped == nil {
return fmt.Errorf("workspace-scoped secret storage is unavailable")
@@ -171,10 +217,12 @@ func (s *UserVisibleStore) DeleteWorkspaceSecretsTx(ctx context.Context, tx *sql
// The wrapped store is owned and closed by the repository container.
func (s *UserVisibleStore) Close() error { return nil }
// internalSecretNotFound returns the store's sentinel not-found error annotated with the given secret id.
func internalSecretNotFound(id string) error {
return fmt.Errorf("%w: %s", ErrNotFound, id)
}
// filterInternalSecretItems returns only the user-managed items, dropping internal ones.
func filterInternalSecretItems(items []*SecretListItem) []*SecretListItem {
visible := make([]*SecretListItem, 0, len(items))
for _, item := range items {
+2
View File
@@ -360,6 +360,8 @@ const (
ActionSecretUpdate = "secrets.update"
ActionSecretDelete = "secrets.delete"
ActionSecretReveal = "secrets.reveal"
ActionSecretCopy = "secrets.copy"
ActionSecretMove = "secrets.move"
// Sprites actions
ActionSpritesStatus = "sprites.status"
@@ -0,0 +1,339 @@
"use client";
import { useTranslation } from "react-i18next";
import { IconX } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import {
DialogClose,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@kandev/ui/dialog";
import { Input } from "@kandev/ui/input";
import { Label } from "@kandev/ui/label";
import { RadioGroup, RadioGroupItem } from "@kandev/ui/radio-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import type { CopyMoveMode, SecretDestination } from "./copy-move-secret-dialog";
/** Renders the Copy/Move dialog body: mode selector, destination picker, target name, and footer actions. */
export function CopyMoveDialogBody({
secretName,
originToken,
mode,
onModeChange,
destination,
destinations,
workspaceNameById,
onDestinationChange,
destinationsLoading,
destinationsError,
onRetryDestinations,
name,
onNameChange,
nameError,
setNameError,
conflict,
nameTooLong,
formError,
canSubmit,
busy,
onSubmit,
onClose,
}: {
secretName: string;
originToken: string;
mode: CopyMoveMode;
onModeChange: (mode: CopyMoveMode) => void;
destination: SecretDestination | null;
destinations: SecretDestination[];
workspaceNameById: Record<string, string>;
onDestinationChange: (destination: SecretDestination) => void;
destinationsLoading: boolean;
destinationsError: string | null;
onRetryDestinations: () => void;
name: string;
onNameChange: (name: string) => void;
nameError: string | null;
setNameError: (error: string | null) => void;
conflict: boolean;
nameTooLong: boolean;
formError: string | null;
canSubmit: boolean;
busy: boolean;
onSubmit: () => void;
onClose: () => void;
}) {
const { t } = useTranslation();
return (
<>
<DialogHeader>
<DialogTitle className="min-w-0 break-words">
{t("settings:copyMoveSecretNamed", { name: secretName })}
</DialogTitle>
<DialogDescription>{t("settings:copyMoveDialogHint")}</DialogDescription>
</DialogHeader>
{/* The middle section scrolls on short viewports; the header and the
footer stay pinned so actions are never pushed off-screen. */}
<div className="min-h-0 space-y-4 overflow-y-auto">
<TransferModeField mode={mode} onModeChange={onModeChange} originToken={originToken} />
<DestinationField
destinations={destinations}
workspaceNameById={workspaceNameById}
destination={destination}
onDestinationChange={onDestinationChange}
destinationsLoading={destinationsLoading}
destinationsError={destinationsError}
onRetryDestinations={onRetryDestinations}
disabled={busy}
/>
<TargetNameField
name={name}
onNameChange={onNameChange}
nameError={nameError}
setNameError={setNameError}
conflict={conflict}
nameTooLong={nameTooLong}
disabled={busy}
/>
{formError !== null && (
<p className="text-xs text-destructive" role="alert">
{formError}
</p>
)}
</div>
<TransferDialogFooter
mode={mode}
canSubmit={canSubmit}
busy={busy}
onSubmit={onSubmit}
onClose={onClose}
/>
</>
);
}
/** Renders the dialog footer with cancel, submit, and close actions for a copy/move transfer. */
function TransferDialogFooter({
mode,
canSubmit,
busy,
onSubmit,
onClose,
}: {
mode: CopyMoveMode;
canSubmit: boolean;
busy: boolean;
onSubmit: () => void;
onClose: () => void;
}) {
const { t } = useTranslation();
return (
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={onClose}
disabled={busy}
className="min-h-11 cursor-pointer"
>
{t("settings:cancel")}
</Button>
<Button
type="button"
onClick={onSubmit}
disabled={!canSubmit}
className="min-h-11 cursor-pointer"
>
{mode === "copy" ? t("settings:copySecretAction") : t("settings:moveSecretAction")}
</Button>
<DialogClose asChild>
<Button
variant="ghost"
size="icon"
aria-label={t("common:close")}
disabled={busy}
className="absolute top-2 right-2 min-h-11 min-w-11 cursor-pointer"
>
<IconX className="h-4 w-4" />
</Button>
</DialogClose>
</DialogFooter>
);
}
/** Renders the target-name input with conflict and validation error display. */
function TargetNameField({
name,
onNameChange,
nameError,
setNameError,
conflict,
nameTooLong,
disabled,
}: {
name: string;
onNameChange: (name: string) => void;
nameError: string | null;
setNameError: (error: string | null) => void;
conflict: boolean;
nameTooLong: boolean;
disabled: boolean;
}) {
const { t } = useTranslation();
const invalid = conflict || nameError !== null || nameTooLong;
return (
<div className="space-y-2">
<Label htmlFor="copy-move-name">{t("settings:secretTargetName")}</Label>
<Input
id="copy-move-name"
value={name}
onChange={(e) => {
onNameChange(e.target.value);
if (nameError !== null) {
setNameError(null);
}
}}
disabled={disabled}
aria-invalid={invalid}
aria-describedby={invalid ? "copy-move-name-error" : undefined}
className="min-h-11"
/>
{invalid && (
<p id="copy-move-name-error" className="text-xs text-destructive break-words">
{nameError ??
(nameTooLong
? t("settings:secretNameTooLong")
: t("settings:secretNameConflictInDestination", { name: name.trim() }))}
</p>
)}
</div>
);
}
/** Renders the copy/move mode radio group, including the move warning. */
function TransferModeField({
mode,
onModeChange,
originToken,
}: {
mode: CopyMoveMode;
onModeChange: (mode: CopyMoveMode) => void;
originToken: string;
}) {
const { t } = useTranslation();
return (
<fieldset className="space-y-2">
<legend className="sr-only">{t("settings:copyMoveMode")}</legend>
<RadioGroup
value={mode}
onValueChange={(value) => onModeChange(value as CopyMoveMode)}
className="flex flex-col gap-2"
>
<label className="flex items-start gap-2 rounded-lg border border-border/70 p-3 min-h-11 cursor-pointer">
<RadioGroupItem value="copy" className="mt-0.5" />
<span className="space-y-1">
<span className="block text-sm font-medium">{t("settings:copySecretAction")}</span>
<span className="block text-xs text-muted-foreground">
{t("settings:copyModeDescription")}
</span>
</span>
</label>
<label className="flex items-start gap-2 rounded-lg border border-border/70 p-3 min-h-11 cursor-pointer">
<RadioGroupItem value="move" className="mt-0.5" />
<span className="space-y-1">
<span className="block text-sm font-medium">{t("settings:moveSecretAction")}</span>
<span className="block text-xs text-muted-foreground">
{t("settings:moveModeWarning", { origin: originToken })}
</span>
</span>
</label>
</RadioGroup>
</fieldset>
);
}
/** Renders the destination picker with loading, error/retry, and empty states. */
function DestinationField({
destinations,
workspaceNameById,
destination,
onDestinationChange,
destinationsLoading,
destinationsError,
onRetryDestinations,
disabled,
}: {
destinations: SecretDestination[];
workspaceNameById: Record<string, string>;
destination: SecretDestination | null;
onDestinationChange: (destination: SecretDestination) => void;
destinationsLoading: boolean;
destinationsError: string | null;
onRetryDestinations: () => void;
disabled: boolean;
}) {
const { t } = useTranslation();
const noDestinations =
destinations.length === 0 && !destinationsLoading && destinationsError === null;
return (
<div className="space-y-2">
<Label htmlFor="copy-move-destination">{t("settings:destination")}</Label>
{destinationsLoading && (
<p className="text-xs text-muted-foreground">{t("settings:destinationsLoading")}</p>
)}
{destinationsError !== null && (
<div className="flex items-center gap-2">
<p className="text-xs text-destructive">{t("settings:destinationsLoadFailed")}</p>
<Button
variant="outline"
size="sm"
onClick={onRetryDestinations}
className="min-h-11 cursor-pointer"
>
{t("settings:retryDestinations")}
</Button>
</div>
)}
{noDestinations && (
<p className="text-xs text-destructive">{t("settings:noValidDestinations")}</p>
)}
{destination !== null && (
<Select
value={destination.scope === "global" ? "global" : `workspace:${destination.workspaceId}`}
onValueChange={(value) =>
onDestinationChange(
value === "global"
? { scope: "global" }
: { scope: "workspace", workspaceId: value.slice("workspace:".length) },
)
}
>
<SelectTrigger
id="copy-move-destination"
disabled={disabled}
className="min-h-11 w-full cursor-pointer"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{destinations.map((option) =>
option.scope === "global" ? (
<SelectItem key="global" value="global">
{t("settings:destinationGlobal")}
</SelectItem>
) : (
<SelectItem key={option.workspaceId} value={`workspace:${option.workspaceId}`}>
{workspaceNameById[option.workspaceId] ?? option.workspaceId}
</SelectItem>
),
)}
</SelectContent>
</Select>
)}
</div>
);
}
@@ -0,0 +1,459 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ApiError } from "@/lib/api/client";
import type { SecretListItem } from "@/lib/types/http-secrets";
import {
buildDefaultTargetName,
CopyMoveSecretDialog,
truncateUtf8Bytes,
} from "./copy-move-secret-dialog";
const { mockCopySecret, mockMoveSecret, mockUseDestinationNames, storeState } = vi.hoisted(() => {
const storeState = {
workspaces: {
items: [
{ id: "ws-1", name: "Alpha" },
{ id: "ws-2", name: "Beta" },
],
activeId: null,
},
setWorkspaces: vi.fn(),
};
return {
mockCopySecret: vi.fn(),
mockMoveSecret: vi.fn(),
mockUseDestinationNames: vi.fn<
(
scope: string,
workspaceId?: string,
) => { names: string[]; loaded: boolean; conflict: (name: string) => boolean }
>(() => ({ names: [], loaded: true, conflict: () => false })),
storeState,
};
});
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: typeof storeState) => unknown) => selector(storeState),
}));
vi.mock("@/hooks/domains/settings/use-workspace-destinations", () => ({
useWorkspaceDestinations: () => ({ loading: false, error: null, retry: vi.fn() }),
}));
vi.mock("@/hooks/domains/settings/use-secret-destination-names", () => ({
useSecretDestinationNames: (scope: string, workspaceId?: string) =>
mockUseDestinationNames(scope, workspaceId),
}));
vi.mock("@/lib/api/domains/secrets-api", () => ({
copySecret: (...args: unknown[]) => mockCopySecret(...args),
moveSecret: (...args: unknown[]) => mockMoveSecret(...args),
}));
const DEFAULT_GLOBAL_NAME = "API Key (from Global)";
const globalSecret: SecretListItem = {
id: "secret-1",
name: "API Key",
scope: "global",
has_value: true,
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
const workspaceSecret: SecretListItem = {
...globalSecret,
id: "secret-2",
name: "WS Key",
scope: "workspace",
workspace_id: "ws-1",
};
/** Renders the dialog with test fakes and returns the spies. */
function renderDialog(overrides: Partial<Parameters<typeof CopyMoveSecretDialog>[0]> = {}) {
const onCompleted = vi.fn();
const onClose = vi.fn();
const view = render(
<CopyMoveSecretDialog
secret={globalSecret}
originToken="Global"
open
onClose={onClose}
onCompleted={onCompleted}
{...overrides}
/>,
);
return { onCompleted, onClose, view };
}
afterEach(async () => {
cleanup();
mockCopySecret.mockReset();
mockMoveSecret.mockReset();
mockUseDestinationNames.mockReset();
mockUseDestinationNames.mockReturnValue({ names: [], loaded: true, conflict: () => false });
storeState.workspaces.items = [
{ id: "ws-1", name: "Alpha" },
{ id: "ws-2", name: "Beta" },
];
});
const TAKEN_NAME = "Taken";
const TAKEN_CONFLICT_MESSAGE = "A secret named Taken already exists in this destination.";
/** Whether the Copy/Move radio with the given name reports aria-checked. */
function radioChecked(name: RegExp): boolean {
return screen.getByRole("radio", { name }).getAttribute("aria-checked") === "true";
}
/** Whether the target-name input reports aria-invalid. */
function inputInvalid(): boolean {
return (
(screen.getByLabelText("Name") as HTMLInputElement).getAttribute("aria-invalid") === "true"
);
}
describe("CopyMoveSecretDialog", () => {
it("pre-fills the name with the origin suffix and defaults to Copy", () => {
renderDialog();
expect(screen.getByRole("heading", { name: `Copy or move ${globalSecret.name}` })).toBeTruthy();
expect((screen.getByLabelText("Name") as HTMLInputElement).value).toBe(DEFAULT_GLOBAL_NAME);
expect(radioChecked(/^Copy/)).toBe(true);
expect(screen.getByRole("button", { name: "Copy" })).toBeTruthy();
});
it("shows General as the default destination for a workspace source", () => {
renderDialog({ secret: workspaceSecret, originToken: "Alpha" });
expect((screen.getByLabelText("Name") as HTMLInputElement).value).toBe("WS Key (from Alpha)");
expect(screen.getByText("Global")).toBeTruthy();
});
it("resets the form when a different secret is targeted while mounted", async () => {
// The dialog stays mounted between opens so Radix can restore focus to the
// trigger on close; targeting a new secret must not leak the previous
// mode/name/destination.
const { view } = renderDialog({ secret: workspaceSecret, originToken: "Alpha" });
fireEvent.click(screen.getByRole("radio", { name: /^Move/ }));
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Custom name" } });
fireEvent.click(screen.getByRole("combobox", { name: "Destination" }));
fireEvent.click(await screen.findByRole("option", { name: "Beta" }));
view.rerender(
<CopyMoveSecretDialog
secret={globalSecret}
originToken="Global"
open
onClose={vi.fn()}
onCompleted={vi.fn()}
/>,
);
expect(radioChecked(/^Copy/)).toBe(true);
expect((screen.getByLabelText("Name") as HTMLInputElement).value).toBe(DEFAULT_GLOBAL_NAME);
// Destination re-defaults for the new source (Global source: first workspace).
expect(screen.getByRole("combobox", { name: "Destination" }).textContent).toContain("Alpha");
});
it("clears the form again when the same secret is reopened", () => {
// Close then reopen the dialog for the same secret: the stale name/mode
// from the previous session must not leak into the reopened dialog.
const { view } = renderDialog();
fireEvent.click(screen.getByRole("radio", { name: /^Move/ }));
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Custom name" } });
view.rerender(
<CopyMoveSecretDialog
secret={globalSecret}
originToken="Global"
open={false}
onClose={vi.fn()}
onCompleted={vi.fn()}
/>,
);
view.rerender(
<CopyMoveSecretDialog
secret={globalSecret}
originToken="Global"
open
onClose={vi.fn()}
onCompleted={vi.fn()}
/>,
);
expect(radioChecked(/^Copy/)).toBe(true);
expect((screen.getByLabelText("Name") as HTMLInputElement).value).toBe(DEFAULT_GLOBAL_NAME);
});
it("switches the submit label to Move and shows the warning", () => {
renderDialog();
fireEvent.click(screen.getByRole("radio", { name: /^Move/ }));
expect(screen.getByRole("button", { name: "Move" })).toBeTruthy();
expect(screen.getByText("The original secret will be removed from Global.")).toBeTruthy();
});
it("blocks submit on a conflicting target name with an invalid field", () => {
mockUseDestinationNames.mockReturnValue({
names: [TAKEN_NAME],
loaded: true,
conflict: (name: string) => name.trim() === TAKEN_NAME,
});
renderDialog();
fireEvent.change(screen.getByLabelText("Name"), { target: { value: TAKEN_NAME } });
expect(inputInvalid()).toBe(true);
expect(screen.getByText(TAKEN_CONFLICT_MESSAGE)).toBeTruthy();
expect((screen.getByRole("button", { name: "Copy" }) as HTMLButtonElement).disabled).toBe(true);
});
});
describe("CopyMoveSecretDialog submit", () => {
it("submits a copy with the destination workspace payload and calls onCompleted", async () => {
mockCopySecret.mockResolvedValue({ id: "new-1", name: DEFAULT_GLOBAL_NAME });
const { onCompleted } = renderDialog();
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
await waitFor(() => expect(mockCopySecret).toHaveBeenCalledTimes(1));
expect(mockCopySecret).toHaveBeenCalledWith(
"secret-1",
{
target_scope: "workspace",
target_workspace_id: "ws-1",
name: DEFAULT_GLOBAL_NAME,
},
undefined,
);
await waitFor(() => expect(onCompleted).toHaveBeenCalled());
});
it("clears the workspace id when the destination switches to General", async () => {
mockMoveSecret.mockResolvedValue({ id: "new-1", name: "moved" });
renderDialog({ secret: workspaceSecret, originToken: "Alpha" });
fireEvent.click(screen.getByRole("radio", { name: /^Move/ }));
fireEvent.click(screen.getByRole("button", { name: "Move" }));
await waitFor(() => expect(mockMoveSecret).toHaveBeenCalledTimes(1));
const payload = mockMoveSecret.mock.calls[0][1] as Record<string, unknown>;
expect(payload).toEqual({ target_scope: "global", name: "WS Key (from Alpha)" });
expect(JSON.stringify(payload)).not.toContain('"name":null');
expect(JSON.stringify(payload)).not.toContain("target_workspace_id");
// A workspace-scoped source must carry its workspace id in the query.
expect(mockMoveSecret.mock.calls[0][2]).toEqual({ workspaceId: "ws-1" });
});
it("surfaces a 409 conflict on the name field", async () => {
mockCopySecret.mockRejectedValue(new ApiError("conflict", 409, {}));
const { onCompleted } = renderDialog();
fireEvent.change(screen.getByLabelText("Name"), { target: { value: DEFAULT_GLOBAL_NAME } });
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
await waitFor(() =>
expect(
screen.getByText(
"A secret named API Key (from Global) already exists in this destination.",
),
).toBeTruthy(),
);
expect(onCompleted).not.toHaveBeenCalled();
});
});
describe("CopyMoveSecretDialog conflict handling", () => {
it("blocks an overlong target name with a localized byte-limit error", () => {
renderDialog();
const input = screen.getByLabelText("Name") as HTMLInputElement;
// 101 bytes: exceeds the 100-byte UTF-8 backend limit without submitting.
fireEvent.change(input, { target: { value: "x".repeat(101) } });
expect(screen.getByText("Name must be at most 100 bytes.")).toBeTruthy();
expect(inputInvalid()).toBe(true);
expect((screen.getByRole("button", { name: "Copy" }) as HTMLButtonElement).disabled).toBe(true);
// A multibyte name is counted in bytes, not characters.
fireEvent.change(input, { target: { value: "é".repeat(51) } }); // 102 bytes
expect(inputInvalid()).toBe(true);
fireEvent.change(input, { target: { value: "é".repeat(50) } }); // 100 bytes: valid
expect(inputInvalid()).toBe(false);
expect((screen.getByRole("button", { name: "Copy" }) as HTMLButtonElement).disabled).toBe(
false,
);
});
it("clears a 409 name conflict when the destination changes", async () => {
mockMoveSecret.mockRejectedValue(new ApiError("conflict", 409, {}));
renderDialog({ secret: workspaceSecret, originToken: "Alpha" });
fireEvent.click(screen.getByRole("radio", { name: /^Move/ }));
fireEvent.click(screen.getByRole("button", { name: "Move" }));
await waitFor(() => expect(screen.getByText(/already exists/)).toBeTruthy());
expect((screen.getByRole("button", { name: "Move" }) as HTMLButtonElement).disabled).toBe(true);
// The 409 is destination-specific: switching to a workspace where the name
// is free must clear the error and re-enable submission.
fireEvent.click(screen.getByRole("combobox", { name: "Destination" }));
fireEvent.click(await screen.findByRole("option", { name: "Beta" }));
// Prove the destination actually changed: the trigger must now display
// Beta (not the initial General), otherwise the assertions below could
// pass while the selection stayed on the original destination.
await waitFor(() =>
expect(screen.getByRole("combobox", { name: "Destination" }).textContent).toContain("Beta"),
);
await waitFor(() => expect(screen.queryByText(/already exists/)).toBeNull());
expect((screen.getByRole("button", { name: "Move" }) as HTMLButtonElement).disabled).toBe(
false,
);
});
it("shows a generic failure on 404 and never removes the source row", async () => {
mockMoveSecret.mockRejectedValue(new ApiError("not found", 404, {}));
const { onCompleted, onClose } = renderDialog({
secret: workspaceSecret,
originToken: "Alpha",
});
fireEvent.click(screen.getByRole("radio", { name: /^Move/ }));
fireEvent.click(screen.getByRole("button", { name: "Move" }));
await waitFor(() =>
expect(screen.getByText("Could not copy or move the secret.")).toBeTruthy(),
);
// A 404 is deliberately ambiguous (missing source OR missing/unauthorized
// destination): the dialog stays open, nothing is completed, and no row
// removal callback fires.
expect(onCompleted).not.toHaveBeenCalled();
expect(onClose).not.toHaveBeenCalled();
expect(screen.getByRole("dialog")).toBeTruthy();
});
it("disables submit synchronously when the selected workspace vanishes from the list", () => {
const { view, onClose, onCompleted } = renderDialog();
expect((screen.getByRole("button", { name: "Copy" }) as HTMLButtonElement).disabled).toBe(
false,
);
storeState.workspaces.items = [];
view.rerender(
<CopyMoveSecretDialog
secret={globalSecret}
originToken="Global"
open
onClose={onClose}
onCompleted={onCompleted}
/>,
);
// The validity check is synchronous: the stale workspace destination must
// not be submittable even before the cleanup effect runs.
expect((screen.getByRole("button", { name: "Copy" }) as HTMLButtonElement).disabled).toBe(true);
});
});
describe("CopyMoveSecretDialog in-flight transfers", () => {
it("ignores duplicate clicks while a transfer is in flight", async () => {
const { promise, resolve } = Promise.withResolvers<unknown>();
mockCopySecret.mockReturnValue(promise);
renderDialog();
const submit = screen.getByRole("button", { name: "Copy" });
fireEvent.click(submit);
fireEvent.click(submit);
expect(mockCopySecret).toHaveBeenCalledTimes(1);
await act(async () => {
resolve({ id: "new-1", name: DEFAULT_GLOBAL_NAME });
});
});
it("discards a stale transfer completion after switching to another secret", async () => {
// The dialog stays mounted between opens. Submit for secret A, then (while
// the request is in flight) reopen the dialog for secret B: A's completion
// must not fire onCompleted against B's dialog.
const { promise, resolve } = Promise.withResolvers<unknown>();
mockCopySecret.mockReturnValue(promise);
const { view, onCompleted } = renderDialog({ secret: workspaceSecret, originToken: "Alpha" });
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
expect(mockCopySecret).toHaveBeenCalledTimes(1);
// The close affordance is disabled while a transfer is in flight.
expect((screen.getByRole("button", { name: "Close" }) as HTMLButtonElement).disabled).toBe(
true,
);
view.rerender(
<CopyMoveSecretDialog
secret={globalSecret}
originToken="Global"
open
onClose={vi.fn()}
onCompleted={onCompleted}
/>,
);
await act(async () => {
resolve({ id: "new-1", name: DEFAULT_GLOBAL_NAME });
});
expect(onCompleted).not.toHaveBeenCalled();
});
it("discards a stale completion when the same secret is reopened", async () => {
// Submit for a secret, close the dialog (the X is disabled while busy but
// Escape/overlay could still dismiss), then reopen the SAME secret: the
// first session's completion must not fire against the reopened dialog.
const { promise, resolve } = Promise.withResolvers<unknown>();
mockCopySecret.mockReturnValue(promise);
const { view, onCompleted } = renderDialog({ secret: workspaceSecret, originToken: "Alpha" });
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
view.rerender(
<CopyMoveSecretDialog
secret={workspaceSecret}
originToken="Alpha"
open={false}
onClose={vi.fn()}
onCompleted={onCompleted}
/>,
);
view.rerender(
<CopyMoveSecretDialog
secret={workspaceSecret}
originToken="Alpha"
open
onClose={vi.fn()}
onCompleted={onCompleted}
/>,
);
await act(async () => {
resolve({ id: "new-1", name: DEFAULT_GLOBAL_NAME });
});
expect(onCompleted).not.toHaveBeenCalled();
});
});
describe("truncateUtf8Bytes", () => {
it("keeps ASCII under the limit unchanged", () => {
expect(truncateUtf8Bytes("short", 100)).toBe("short");
});
it("truncates multibyte input to the byte limit", () => {
const long = "é".repeat(60); // 120 bytes
const truncated = truncateUtf8Bytes(long, 100);
expect(new TextEncoder().encode(truncated).length).toBe(100);
expect(truncated).toBe("é".repeat(50));
});
it("never splits astral-plane surrogate pairs", () => {
const value = "🔐".repeat(40); // 160 bytes
const truncated = truncateUtf8Bytes(value, 100);
expect(truncated).toBe("🔐".repeat(25));
expect(new TextEncoder().encode(truncated).length).toBe(100);
expect(truncated.includes("\uFFFD")).toBe(false);
});
});
describe("buildDefaultTargetName", () => {
it("builds the locale-independent origin suffix within the byte limit", () => {
const name = buildDefaultTargetName("API Key", "Global");
expect(name).toBe(DEFAULT_GLOBAL_NAME);
expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(100);
});
it("truncates an over-long source name so the copy can never fail validation", () => {
const name = buildDefaultTargetName("K".repeat(120), "general");
expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(100);
});
});
@@ -0,0 +1,424 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Dialog, DialogContent } from "@kandev/ui/dialog";
import { useAppStore } from "@/components/state-provider";
import { ApiError } from "@/lib/api/client";
import { copySecret, moveSecret } from "@/lib/api/domains/secrets-api";
import { useSecretDestinationNames } from "@/hooks/domains/settings/use-secret-destination-names";
import { useWorkspaceDestinations } from "@/hooks/domains/settings/use-workspace-destinations";
import type { SecretListItem } from "@/lib/types/http-secrets";
import { CopyMoveDialogBody } from "./copy-move-dialog-body";
export const MAX_SECRET_NAME_BYTES = 100;
export type CopyMoveMode = "copy" | "move";
export type SecretDestination = { scope: "global" } | { scope: "workspace"; workspaceId: string };
/**
* Truncates a string so its UTF-8 byte length is at most `limit`, iterating
* code points (never splitting surrogate pairs or producing replacement
* characters). The backend name limit is 100 UTF-8 bytes.
*/
export function truncateUtf8Bytes(value: string, limit: number): string {
const encoder = new TextEncoder();
if (encoder.encode(value).length <= limit) {
return value;
}
let result = "";
for (const char of value) {
const next = result + char;
if (encoder.encode(next).length > limit) {
break;
}
result = next;
}
return result;
}
/** Default target name: `<name> (from <origin>)`, truncated to the byte limit. */
export function buildDefaultTargetName(name: string, originToken: string): string {
return truncateUtf8Bytes(`${name} (from ${originToken})`, MAX_SECRET_NAME_BYTES);
}
type CopyMoveSecretDialogProps = {
secret: SecretListItem;
/** `general` for a Global source, the workspace name otherwise (literal, locale-independent). */
originToken: string;
/** Controlled visibility. The dialog stays mounted while closed so Radix can
* restore focus to the trigger on close; callers must keep `secret` set. */
open: boolean;
onClose: () => void;
onCompleted: (item: SecretListItem, mode: CopyMoveMode) => void;
};
/** Renders the copy/move secret dialog, wiring form state, destinations, and submission. */
export function CopyMoveSecretDialog({
secret,
originToken,
open,
onClose,
onCompleted,
}: CopyMoveSecretDialogProps) {
const {
loading: destinationsLoading,
error: destinationsError,
retry: retryDestinations,
} = useWorkspaceDestinations();
const workspaces = useAppStore((state) => state.workspaces.items);
const [mode, setMode] = useState<CopyMoveMode>("copy");
const [destination, setDestination] = useState<SecretDestination | null>(null);
const [name, setName] = useState(() => buildDefaultTargetName(secret.name, originToken));
const [nameError, setNameError] = useState<string | null>(null);
const [destinationNamesKey, setDestinationNamesKey] = useState(0);
const { destinations, workspaceNameById, destinationValid } = useDestinationOptions(
secret,
workspaces,
destination,
setDestination,
);
const destinationNames = useSecretDestinationNames(
destination?.scope ?? "global",
destination?.scope === "workspace" ? destination.workspaceId : undefined,
destinationNamesKey,
);
const conflict = nameError === null && destination !== null && destinationNames.conflict(name);
// The backend limit is 100 UTF-8 bytes; a user-edited name that exceeds it
// would otherwise fail server-side with a generic transfer error.
const nameTooLong = new TextEncoder().encode(name.trim()).length > MAX_SECRET_NAME_BYTES;
const { busy, canSubmit, formError, clearError, run } = useTransferSubmit({
secret,
mode,
destination,
destinationValid,
name,
nameError,
conflict,
nameTooLong,
destinationsLoading,
destinationsError: destinationsError !== null,
setNameError,
onCompleted,
open,
});
const resetDestinationNames = useCallback(() => setDestinationNamesKey((key) => key + 1), []);
// Stable identity: the reset effect depends on this object, so it must not
// change every render (the guard inside useTransferFormReset would still
// keep behavior correct, but the effect would fire needlessly).
const transferSetters = useMemo(
() => ({ setMode, setDestination, setName, setNameError, clearError, resetDestinationNames }),
[setMode, setDestination, setName, setNameError, clearError, resetDestinationNames],
);
useTransferFormReset(secret, originToken, open, transferSetters);
return (
<Dialog
open={open}
onOpenChange={(next) => {
// While a transfer is in flight, no dismiss path (X, Escape, overlay)
// may close the dialog: a stale completion must not land in a
// reopened session for the same secret.
if (!next && !busy) {
onClose();
}
}}
>
<DialogContent
showCloseButton={false}
className="bottom-0 top-auto left-0 right-0 translate-x-0 translate-y-0 grid-cols-[minmax(0,1fr)] grid-rows-[auto_minmax(0,1fr)_auto] max-h-[100dvh] overflow-hidden rounded-b-none pb-[env(safe-area-inset-bottom)] sm:top-1/2 sm:left-1/2 sm:bottom-auto sm:translate-x-[-50%] sm:translate-y-[-50%] sm:rounded-b-lg"
>
<CopyMoveDialogBody
secretName={secret.name}
originToken={originToken}
mode={mode}
onModeChange={setMode}
destination={destination}
destinations={destinations}
workspaceNameById={workspaceNameById}
onDestinationChange={(next) => {
// A 409 pins the name field and a non-409 failure pins the alert;
// both are destination-specific, so clear them on target change.
if (nameError !== null) {
setNameError(null);
}
clearError();
setDestination(next);
}}
destinationsLoading={destinationsLoading}
destinationsError={destinationsError}
onRetryDestinations={retryDestinations}
name={name}
onNameChange={setName}
nameError={nameError}
nameTooLong={nameTooLong}
setNameError={setNameError}
conflict={conflict}
formError={formError}
canSubmit={canSubmit}
busy={busy}
onSubmit={run}
onClose={onClose}
/>
</DialogContent>
</Dialog>
);
}
/**
* The dialog stays mounted between opens so Radix can restore focus to the
* trigger on close. This resets every piece of form state when a new secret is
* targeted or when the dialog is reopened, while skipping the mount render so
* the initial useState values (and the destination auto-selection) survive.
*/
function useTransferFormReset(
secret: SecretListItem,
originToken: string,
open: boolean,
setters: {
setMode: (mode: CopyMoveMode) => void;
setDestination: (destination: SecretDestination | null) => void;
setName: (name: string) => void;
setNameError: (error: string | null) => void;
clearError: () => void;
resetDestinationNames: () => void;
},
) {
const lastSecretId = useRef(secret.id);
const prevOpen = useRef(open);
useEffect(() => {
const reopened = open && !prevOpen.current;
prevOpen.current = open;
if (!reopened && lastSecretId.current === secret.id) {
return;
}
lastSecretId.current = secret.id;
setters.setMode("copy");
setters.setDestination(null);
setters.setName(buildDefaultTargetName(secret.name, originToken));
setters.setNameError(null);
setters.clearError();
setters.resetDestinationNames();
}, [secret.id, originToken, open, setters]);
}
type TransferCanSubmitArgs = {
isBusy: boolean;
destination: SecretDestination | null;
destinationValid: boolean;
name: string;
nameError: string | null;
conflict: boolean;
nameTooLong: boolean;
destinationsLoading: boolean;
destinationsError: boolean;
};
/** Returns whether the transfer can be submitted given the current form, destination, and request state. */
function transferCanSubmit({
isBusy,
destination,
destinationValid,
name,
nameError,
conflict,
nameTooLong,
destinationsLoading,
destinationsError,
}: TransferCanSubmitArgs): boolean {
return (
!isBusy &&
destination !== null &&
destinationValid &&
name.trim().length > 0 &&
nameError === null &&
!conflict &&
!nameTooLong &&
!destinationsLoading &&
!destinationsError
);
}
type TransferSubmitArgs = {
secret: SecretListItem;
mode: CopyMoveMode;
destination: SecretDestination | null;
destinationValid: boolean;
name: string;
nameError: string | null;
conflict: boolean;
nameTooLong: boolean;
destinationsLoading: boolean;
destinationsError: boolean;
setNameError: (error: string | null) => void;
onCompleted: (item: SecretListItem, mode: CopyMoveMode) => void;
/** Controlled visibility; drives the session counter for stale-result guards. */
open: boolean;
};
/** Runs the copy/move request, guarding against stale results across dialog sessions, and exposes busy/canSubmit/formError state. */
function useTransferSubmit({
secret,
mode,
destination,
destinationValid,
name,
nameError,
conflict,
nameTooLong,
destinationsLoading,
destinationsError,
setNameError,
onCompleted,
open,
}: TransferSubmitArgs) {
const { t } = useTranslation();
const [isBusy, setIsBusy] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
// The dialog stays mounted across opens; a completion or error for a
// previously targeted secret must not mutate the dialog now showing another.
// The session counter also covers closing and reopening the SAME secret:
// a result from the previous session must not land in the reopened dialog.
const secretIdRef = useRef(secret.id);
const sessionRef = useRef(0);
useEffect(() => {
secretIdRef.current = secret.id;
}, [secret.id]);
useEffect(() => {
if (open) {
sessionRef.current += 1;
}
}, [open]);
const canSubmit = transferCanSubmit({
isBusy,
destination,
destinationValid,
name,
nameError,
conflict,
nameTooLong,
destinationsLoading,
destinationsError,
});
/** Runs the transfer request, guarding stale completions against dialog reopenings. */
const run = async () => {
if (!canSubmit || destination === null) {
return;
}
const startedSecretId = secret.id;
const startedSession = sessionRef.current;
setIsBusy(true);
setFormError(null);
const trimmedName = name.trim();
const payload = {
target_scope: destination.scope,
...(destination.scope === "workspace"
? { target_workspace_id: destination.workspaceId }
: {}),
name: trimmedName,
} as const;
try {
// A workspace-scoped source requires its workspace id in the query.
const sourceOptions =
secret.scope === "workspace" && secret.workspace_id
? { workspaceId: secret.workspace_id }
: undefined;
const item =
mode === "copy"
? await copySecret(secret.id, payload, sourceOptions)
: await moveSecret(secret.id, payload, sourceOptions);
if (secretIdRef.current === startedSecretId && sessionRef.current === startedSession) {
onCompleted(item, mode);
}
} catch (err) {
// A stale failure (user switched to another secret mid-flight, or closed
// and reopened the same one) must not paint onto the current dialog.
if (secretIdRef.current !== startedSecretId || sessionRef.current !== startedSession) {
return;
}
if (err instanceof ApiError && err.status === 409) {
setNameError(t("settings:secretNameConflictInDestination", { name: trimmedName }));
} else {
// 404 is deliberately ambiguous (missing source OR missing/unauthorized
// destination) to avoid disclosure; never remove the source row on it.
setFormError(t("settings:transferFailed"));
}
} finally {
setIsBusy(false);
}
};
const clearError = useCallback(() => setFormError(null), []);
return { busy: isBusy, canSubmit, formError, clearError, run };
}
type WorkspaceOption = { id: string; name: string };
/**
* Computes the valid destinations for a secret (General plus every other
* workspace) and keeps the selection in sync: auto-selects the first option
* when nothing is chosen, and clears a selection that vanished from the list
* (deleted workspace or failed list) so submission can never target a stale
* destination. `null` keeps canSubmit false when nothing valid remains (a
* Global source must never fall back to a same-scope target).
*/
function useDestinationOptions(
secret: SecretListItem,
workspaces: WorkspaceOption[],
destination: SecretDestination | null,
onDestinationChange: (destination: SecretDestination | null) => void,
) {
const workspaceNameById = Object.fromEntries(
workspaces.map((workspace) => [workspace.id, workspace.name]),
);
const destinations = useMemo(() => {
const list: SecretDestination[] = [];
if (secret.scope !== "global") {
list.push({ scope: "global" });
}
for (const workspace of workspaces) {
if (secret.scope === "workspace" && workspace.id === secret.workspace_id) {
continue;
}
list.push({ scope: "workspace", workspaceId: workspace.id });
}
return list;
}, [secret, workspaces]);
// Synchronous validity: the selected destination must be present in the
// CURRENT list. canSubmit consumes this on the same render, so a workspace
// that vanished (deleted or failed list) can never be submitted even
// between renders; the effect below only performs state cleanup.
const destinationValid =
destination !== null &&
destinations.some((option) => {
if (option.scope !== destination.scope) {
return false;
}
if (destination.scope === "workspace") {
return option.scope === "workspace" && option.workspaceId === destination.workspaceId;
}
return true;
});
useEffect(() => {
if (destination === null && destinations.length > 0) {
onDestinationChange(destinations[0]);
return;
}
if (destination !== null && !destinationValid) {
// The selected destination disappeared from the list: clear it so the
// UI cannot show a stale selection. null keeps canSubmit false when
// nothing valid remains (a Global source must never fall back to a
// same-scope target).
onDestinationChange(destinations[0] ?? null);
}
}, [destination, destinations, destinationValid, onDestinationChange]);
return { destinations, workspaceNameById, destinationValid };
}
@@ -0,0 +1,83 @@
"use client";
import { useTranslation } from "react-i18next";
import { Button } from "@kandev/ui/button";
import { Input } from "@kandev/ui/input";
import { Textarea } from "@kandev/ui/textarea";
export type SecretFormState = {
name: string;
value: string;
};
export const defaultFormState: SecretFormState = {
name: "",
value: "",
};
type SecretFormProps = {
title: string;
formState: SecretFormState;
onFormChange: (patch: Partial<SecretFormState>) => void;
onSubmit: () => void;
onCancel: () => void;
isValid: boolean;
isBusy: boolean;
submitLabel: string;
showSubmit?: boolean;
baselineState?: SecretFormState;
};
/** Renders the secret name/value form with submit and cancel actions. */
export function SecretForm({
title,
formState,
onFormChange,
onSubmit,
onCancel,
isValid,
isBusy,
submitLabel,
showSubmit = true,
baselineState,
}: SecretFormProps) {
const { t } = useTranslation();
const nameIsDirty = Boolean(baselineState) && formState.name.trim() !== baselineState?.name;
const valueIsDirty = Boolean(baselineState) && formState.value !== baselineState?.value;
return (
<div
className="rounded-lg border border-border/70 bg-background p-4 space-y-3"
data-settings-dirty={nameIsDirty || valueIsDirty}
>
<div className="text-sm font-medium text-foreground">{title}</div>
<div className="space-y-2">
<Input
value={formState.name}
onChange={(e) => onFormChange({ name: e.target.value })}
placeholder={t("settings:nameEGOpenaiProductionKey")}
disabled={isBusy}
data-settings-dirty={nameIsDirty}
/>
<Textarea
value={formState.value}
onChange={(e) => onFormChange({ value: e.target.value })}
placeholder={t("settings:secretValue")}
rows={2}
className="resize-y font-mono text-sm"
disabled={isBusy}
data-settings-dirty={valueIsDirty}
/>
</div>
<div className="flex items-center gap-2">
{showSubmit && (
<Button onClick={onSubmit} disabled={!isValid || isBusy} className="cursor-pointer">
{submitLabel}
</Button>
)}
<Button variant="ghost" onClick={onCancel} disabled={isBusy} className="cursor-pointer">
{t("settings:cancel")}
</Button>
</div>
</div>
);
}
@@ -2,7 +2,7 @@ import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { activateLocale } from "@/lib/i18n";
import type { SecretListItem } from "@/lib/types/http-secrets";
import { DeleteSecretDialog } from "./secrets-settings";
import { DeleteSecretDialog } from "./secrets-delete-dialog";
/**
* A secret's name is user data. It reaches the dialog as an interpolated value
@@ -0,0 +1,68 @@
"use client";
import { Trans, useTranslation } from "react-i18next";
import { Button } from "@kandev/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@kandev/ui/dialog";
import type { SecretListItem } from "@/lib/types/http-secrets";
type DeleteSecretDialogProps = {
target: SecretListItem | null;
onClose: () => void;
onConfirm: () => void;
isBusy: boolean;
};
/** Renders the confirm-delete dialog for a secret, with cancel and destructive confirm actions. */
export function DeleteSecretDialog({
target,
onClose,
onConfirm,
isBusy,
}: DeleteSecretDialogProps) {
const { t } = useTranslation();
// The secret's own name is user data: it is interpolated as a value and never
// routed through a catalog key.
const name = target?.name ?? t("settings:thisSecret");
return (
<Dialog
open={Boolean(target)}
onOpenChange={(open) => {
if (!open) onClose();
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("settings:deleteSecret")}</DialogTitle>
<DialogDescription>
<Trans i18nKey="settings:thisWillPermanentlyRemoveSecret" values={{ name }}>
This will permanently remove{" "}
<span className="font-medium text-foreground">{name}</span>. This action cannot be
undone.
</Trans>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose} className="cursor-pointer">
{t("settings:cancel")}
</Button>
<Button
type="button"
variant="destructive"
onClick={onConfirm}
disabled={isBusy}
className="cursor-pointer"
>
{t("settings:deleteSecret")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,65 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { SecretListItem } from "@/lib/types/http-secrets";
import { SecretListItemRow } from "./secrets-list-item-row";
const secret: SecretListItem = {
id: "secret-1",
name: "API Key",
scope: "global",
has_value: true,
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
/** Renders the row with test fakes and returns the spies. */
function renderRow(overrides: Partial<Parameters<typeof SecretListItemRow>[0]> = {}) {
const onEdit = vi.fn();
const onDelete = vi.fn();
const onCopyMove = vi.fn();
render(
<SecretListItemRow
secret={secret}
onEdit={onEdit}
onDelete={onDelete}
onCopyMove={onCopyMove}
isBusy={false}
showCreate={false}
isEditing={false}
{...overrides}
/>,
);
return { onEdit, onDelete, onCopyMove };
}
afterEach(() => cleanup());
const COPY_MOVE_BUTTON = "Copy or move API Key";
/** Returns whether the copy/move button is currently disabled. */
function copyMoveDisabled(): boolean {
return (screen.getByRole("button", { name: COPY_MOVE_BUTTON }) as HTMLButtonElement).disabled;
}
describe("SecretListItemRow", () => {
it("runs the copy/move action", () => {
const { onCopyMove } = renderRow();
screen.getByRole("button", { name: COPY_MOVE_BUTTON }).click();
expect(onCopyMove).toHaveBeenCalledWith(secret);
});
it("disables copy/move while a create draft is open", () => {
renderRow({ showCreate: true });
expect(copyMoveDisabled()).toBe(true);
});
it("disables copy/move while that row is being edited", () => {
renderRow({ isEditing: true });
expect(copyMoveDisabled()).toBe(true);
});
it("disables copy/move while a transfer is busy", () => {
renderRow({ isBusy: true });
expect(copyMoveDisabled()).toBe(true);
});
});
@@ -0,0 +1,128 @@
"use client";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { IconCopy, IconEdit, IconEye, IconEyeOff, IconKey, IconTrash } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Badge } from "@kandev/ui/badge";
import { revealSecret } from "@/lib/api/domains/secrets-api";
import type { SecretListItem } from "@/lib/types/http-secrets";
type SecretListItemRowProps = {
secret: SecretListItem;
workspaceId?: string;
onEdit: (secret: SecretListItem) => void;
onDelete: (secret: SecretListItem) => void;
onCopyMove: (secret: SecretListItem) => void;
isBusy: boolean;
showCreate: boolean;
isEditing: boolean;
};
/** Renders a single secret row: name, scope badge, and copy/move, reveal, edit, and delete actions. */
export function SecretListItemRow({
secret,
workspaceId,
onEdit,
onDelete,
onCopyMove,
isBusy,
showCreate,
isEditing,
}: SecretListItemRowProps) {
const { t } = useTranslation();
const [revealed, setRevealed] = useState(false);
const [revealedValue, setRevealedValue] = useState<string | null>(null);
const [revealing, setRevealing] = useState(false);
/** Fetches and shows the secret value, or hides it when already revealed. */
const handleReveal = async () => {
if (revealed) {
setRevealed(false);
setRevealedValue(null);
return;
}
setRevealing(true);
try {
const resp = await revealSecret(secret.id, {
cache: "no-store",
...(workspaceId ? { workspaceId } : {}),
});
setRevealedValue(resp.value);
setRevealed(true);
} catch {
// ignore
} finally {
setRevealing(false);
}
};
return (
<div className="rounded-lg border border-border/70 bg-background p-4 space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
<IconKey className="h-4 w-4 text-muted-foreground shrink-0" />
<div className="text-sm font-medium text-foreground truncate">{secret.name}</div>
<Badge variant="outline" className="shrink-0 text-[10px]">
{secret.scope === "workspace"
? t("settings:workspaceScope")
: t("settings:globalScope")}
</Badge>
</div>
<div className="flex flex-wrap items-center justify-end gap-1 shrink-0">
<Button
variant="ghost"
onClick={() => onCopyMove(secret)}
// A Move removes the source; it must never run while that secret's
// edit/create draft is open (the draft would outlive its row).
disabled={isBusy || showCreate || isEditing}
className="min-h-11 cursor-pointer"
aria-label={t("settings:copyMoveSecretNamed", { name: secret.name })}
>
<IconCopy className="h-4 w-4" />
{t("settings:copyMove")}
</Button>
<Button
variant="ghost"
size="icon"
onClick={handleReveal}
disabled={revealing || isBusy}
className="min-h-11 min-w-11 cursor-pointer"
aria-label={
revealed
? t("settings:hideSecretNamed", { name: secret.name })
: t("settings:revealSecretNamed", { name: secret.name })
}
>
{revealed ? <IconEyeOff className="h-4 w-4" /> : <IconEye className="h-4 w-4" />}
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => onEdit(secret)}
disabled={isBusy || showCreate || isEditing}
className="min-h-11 min-w-11 cursor-pointer"
aria-label={t("settings:editSecretNamed", { name: secret.name })}
>
<IconEdit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => onDelete(secret)}
disabled={isBusy}
className="min-h-11 min-w-11 cursor-pointer"
aria-label={t("settings:deleteSecretNamed", { name: secret.name })}
>
<IconTrash className="h-4 w-4" />
</Button>
</div>
</div>
{revealed && revealedValue !== null && (
<div className="text-xs font-mono bg-muted/50 rounded px-2 py-1 break-all">
{revealedValue}
</div>
)}
</div>
);
}
+208 -309
View File
@@ -1,282 +1,27 @@
"use client";
import { useCallback, useMemo, useState } from "react";
import { Trans, useTranslation } from "react-i18next";
import { useCallback, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { IconEdit, IconTrash, IconEye, IconEyeOff, IconKey } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Badge } from "@kandev/ui/badge";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@kandev/ui/dialog";
import { Input } from "@kandev/ui/input";
import { Textarea } from "@kandev/ui/textarea";
import { SettingsPageTemplate } from "@/components/settings/settings-page-template";
import { WorkspaceSectionHeader } from "@/components/settings/workspaces/workspace-section-header";
import { useAppStore } from "@/components/state-provider";
import { useSecrets } from "@/hooks/domains/settings/use-secrets";
import {
createSecret,
updateSecret,
deleteSecret,
revealSecret,
} from "@/lib/api/domains/secrets-api";
import type { ApiRequestOptions } from "@/lib/api/client";
import { createSecret, updateSecret, deleteSecret } from "@/lib/api/domains/secrets-api";
import { useRequest } from "@/lib/http/use-request";
import type { SecretListItem, SecretScope, UpdateSecretRequest } from "@/lib/types/http-secrets";
import { WorkspaceSectionHeader } from "@/components/settings/workspaces/workspace-section-header";
export type SecretFormState = {
name: string;
value: string;
};
const defaultFormState: SecretFormState = {
name: "",
value: "",
};
/* ------------------------------------------------------------------ */
/* Create / Edit form */
/* ------------------------------------------------------------------ */
type SecretFormProps = {
title: string;
formState: SecretFormState;
onFormChange: (patch: Partial<SecretFormState>) => void;
onSubmit: () => void;
onCancel: () => void;
isValid: boolean;
isBusy: boolean;
submitLabel: string;
showSubmit?: boolean;
baselineState?: SecretFormState;
};
function SecretForm({
title,
formState,
onFormChange,
onSubmit,
onCancel,
isValid,
isBusy,
submitLabel,
showSubmit = true,
baselineState,
}: SecretFormProps) {
const { t } = useTranslation();
const nameIsDirty = Boolean(baselineState) && formState.name.trim() !== baselineState?.name;
const valueIsDirty = Boolean(baselineState) && formState.value !== baselineState?.value;
return (
<div
className="rounded-lg border border-border/70 bg-background p-4 space-y-3"
data-settings-dirty={nameIsDirty || valueIsDirty}
>
<div className="text-sm font-medium text-foreground">{title}</div>
<div className="space-y-2">
<Input
value={formState.name}
onChange={(e) => onFormChange({ name: e.target.value })}
placeholder={t("settings:nameEGOpenaiProductionKey")}
disabled={isBusy}
data-settings-dirty={nameIsDirty}
/>
<Textarea
value={formState.value}
onChange={(e) => onFormChange({ value: e.target.value })}
placeholder={t("settings:secretValue")}
rows={2}
className="resize-y font-mono text-sm"
disabled={isBusy}
data-settings-dirty={valueIsDirty}
/>
</div>
<div className="flex items-center gap-2">
{showSubmit && (
<Button onClick={onSubmit} disabled={!isValid || isBusy} className="cursor-pointer">
{submitLabel}
</Button>
)}
<Button variant="ghost" onClick={onCancel} disabled={isBusy} className="cursor-pointer">
{t("settings:cancel")}
</Button>
</div>
</div>
);
}
/* ------------------------------------------------------------------ */
/* List item */
/* ------------------------------------------------------------------ */
type SecretListItemRowProps = {
secret: SecretListItem;
workspaceId?: string;
onEdit: (secret: SecretListItem) => void;
onDelete: (secret: SecretListItem) => void;
isBusy: boolean;
showCreate: boolean;
isEditing: boolean;
};
function SecretListItemRow({
secret,
workspaceId,
onEdit,
onDelete,
isBusy,
showCreate,
isEditing,
}: SecretListItemRowProps) {
const { t } = useTranslation();
const [revealed, setRevealed] = useState(false);
const [revealedValue, setRevealedValue] = useState<string | null>(null);
const [revealing, setRevealing] = useState(false);
const handleReveal = async () => {
if (revealed) {
setRevealed(false);
setRevealedValue(null);
return;
}
setRevealing(true);
try {
const resp = await revealSecret(secret.id, {
cache: "no-store",
...(workspaceId ? { workspaceId } : {}),
});
setRevealedValue(resp.value);
setRevealed(true);
} catch {
// ignore
} finally {
setRevealing(false);
}
};
return (
<div className="rounded-lg border border-border/70 bg-background p-4 space-y-2">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
<IconKey className="h-4 w-4 text-muted-foreground shrink-0" />
<div className="text-sm font-medium text-foreground truncate">{secret.name}</div>
<Badge variant="outline" className="shrink-0 text-[10px]">
{secret.scope === "workspace"
? t("settings:workspaceScope")
: t("settings:globalScope")}
</Badge>
</div>
<div className="flex items-center gap-1 shrink-0">
<Button
variant="ghost"
size="icon"
onClick={handleReveal}
disabled={revealing || isBusy}
className="min-h-11 min-w-11 cursor-pointer"
aria-label={
revealed
? t("settings:hideSecretNamed", { name: secret.name })
: t("settings:revealSecretNamed", { name: secret.name })
}
>
{revealed ? <IconEyeOff className="h-4 w-4" /> : <IconEye className="h-4 w-4" />}
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => onEdit(secret)}
disabled={isBusy || showCreate || isEditing}
className="min-h-11 min-w-11 cursor-pointer"
aria-label={t("settings:editSecretNamed", { name: secret.name })}
>
<IconEdit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => onDelete(secret)}
disabled={isBusy}
className="min-h-11 min-w-11 cursor-pointer"
aria-label={t("settings:deleteSecretNamed", { name: secret.name })}
>
<IconTrash className="h-4 w-4" />
</Button>
</div>
</div>
{revealed && revealedValue !== null && (
<div className="text-xs font-mono bg-muted/50 rounded px-2 py-1 break-all">
{revealedValue}
</div>
)}
</div>
);
}
/* ------------------------------------------------------------------ */
/* Delete dialog */
/* ------------------------------------------------------------------ */
type DeleteSecretDialogProps = {
target: SecretListItem | null;
onClose: () => void;
onConfirm: () => void;
isBusy: boolean;
};
export function DeleteSecretDialog({
target,
onClose,
onConfirm,
isBusy,
}: DeleteSecretDialogProps) {
const { t } = useTranslation();
// The secret's own name is user data: it is interpolated as a value and never
// routed through a catalog key.
const name = target?.name ?? t("settings:thisSecret");
return (
<Dialog
open={Boolean(target)}
onOpenChange={(open) => {
if (!open) onClose();
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("settings:deleteSecret")}</DialogTitle>
<DialogDescription>
<Trans i18nKey="settings:thisWillPermanentlyRemoveSecret" values={{ name }}>
This will permanently remove{" "}
<span className="font-medium text-foreground">{name}</span>. This action cannot be
undone.
</Trans>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose} className="cursor-pointer">
{t("settings:cancel")}
</Button>
<Button
type="button"
variant="destructive"
onClick={onConfirm}
disabled={isBusy}
className="cursor-pointer"
>
{t("settings:deleteSecret")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
import { SecretForm, defaultFormState, type SecretFormState } from "./secret-form";
import { SecretListItemRow } from "./secrets-list-item-row";
import { DeleteSecretDialog } from "./secrets-delete-dialog";
import { CopyMoveSecretDialog, type CopyMoveMode } from "./copy-move-secret-dialog";
/* ------------------------------------------------------------------ */
/* State + actions hooks */
/* ------------------------------------------------------------------ */
/** Holds the secrets list plus all settings-panel UI state (editing, create form, delete/transfer targets). */
function useSecretsState(
scope: SecretScope,
workspaceId?: string,
@@ -292,6 +37,8 @@ function useSecretsState(
const [showCreate, setShowCreate] = useState(false);
const [formState, setFormState] = useState<SecretFormState>(defaultFormState);
const [deleteTarget, setDeleteTarget] = useState<SecretListItem | null>(null);
const [transferTarget, setTransferTarget] = useState<SecretListItem | null>(null);
const [transferOpen, setTransferOpen] = useState(false);
return {
loaded,
@@ -309,42 +56,53 @@ function useSecretsState(
setFormState,
deleteTarget,
setDeleteTarget,
transferTarget,
setTransferTarget,
transferOpen,
setTransferOpen,
};
}
function useSecretsActions(state: ReturnType<typeof useSecretsState>) {
const {
addSecret: addToStore,
updateSecretInStore,
removeSecret: removeFromStore,
editingId,
setEditingId,
setShowCreate,
setFormState,
setDeleteTarget,
deleteTarget,
formState,
scope,
workspaceId,
} = state;
const requestOptions = {
cache: "no-store" as const,
...(scope === "workspace" && workspaceId ? { workspaceId } : {}),
};
const resetForm = useCallback(() => {
setEditingId(null);
setShowCreate(false);
setFormState(defaultFormState);
}, [setEditingId, setShowCreate, setFormState]);
const isValid = useMemo(() => {
const nameOk = formState.name.trim().length > 0;
const valueOk = editingId ? true : formState.value.trim().length > 0;
return nameOk && valueOk;
}, [formState, editingId]);
/**
* Remembers the focused element when a transfer dialog opens and returns
* focus to it on close. Radix restores to a stale node when the settings list
* re-renders mid-close, leaving focus on <body>; this makes the keyboard
* contract deterministic.
*/
function useTransferFocusRestore() {
const triggerRef = useRef<HTMLElement | null>(null);
const rememberTransferTrigger = useCallback(() => {
triggerRef.current =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
}, []);
const restoreTransferTrigger = useCallback(() => {
const trigger = triggerRef.current;
triggerRef.current = null;
if (trigger) {
window.setTimeout(() => {
if (document.contains(trigger)) {
trigger.focus();
}
}, 0);
}
}, []);
return { rememberTransferTrigger, restoreTransferTrigger };
}
/** Builds the create/update/delete request runners that mutate the store and reset the form on success. */
function useSecretRequests(
scope: SecretScope,
workspaceId: string | undefined,
requestOptions: ApiRequestOptions,
deps: {
addToStore: (item: SecretListItem) => void;
updateSecretInStore: (item: SecretListItem) => void;
removeFromStore: (id: string) => void;
resetForm: () => void;
editingId: string | null;
},
) {
const { addToStore, updateSecretInStore, removeFromStore, resetForm, editingId } = deps;
const createRequest = useRequest(async (s: SecretFormState) => {
const item = await createSecret(
{
@@ -359,7 +117,6 @@ function useSecretsActions(state: ReturnType<typeof useSecretsState>) {
addToStore(item);
resetForm();
});
const updateRequest = useRequest(async (id: string, s: SecretFormState) => {
const payload: UpdateSecretRequest = {
name: s.name.trim(),
@@ -369,13 +126,60 @@ function useSecretsActions(state: ReturnType<typeof useSecretsState>) {
updateSecretInStore(item);
resetForm();
});
const deleteRequest = useRequest(async (id: string) => {
await deleteSecret(id, requestOptions);
removeFromStore(id);
if (editingId === id) resetForm();
});
return { createRequest, updateRequest, deleteRequest };
}
/** Composes request runners and UI actions (create, edit, delete, transfer) from the secrets state. */
function useSecretsActions(state: ReturnType<typeof useSecretsState>) {
const { rememberTransferTrigger, restoreTransferTrigger } = useTransferFocusRestore();
const {
addSecret: addToStore,
updateSecretInStore,
removeSecret: removeFromStore,
editingId,
setEditingId,
setShowCreate,
setFormState,
setDeleteTarget,
deleteTarget,
formState,
scope,
workspaceId,
setTransferTarget,
setTransferOpen,
} = state;
const requestOptions = {
cache: "no-store" as const,
...(scope === "workspace" && workspaceId ? { workspaceId } : {}),
};
const resetForm = useCallback(() => {
setEditingId(null);
setShowCreate(false);
setFormState(defaultFormState);
}, [setEditingId, setShowCreate, setFormState]);
const isValid = useMemo(
() =>
formState.name.trim().length > 0 && (editingId ? true : formState.value.trim().length > 0),
[formState, editingId],
);
const { createRequest, updateRequest, deleteRequest } = useSecretRequests(
scope,
workspaceId,
requestOptions,
{
addToStore,
updateSecretInStore,
removeFromStore,
resetForm,
editingId,
},
);
const isBusy = createRequest.isLoading || updateRequest.isLoading || deleteRequest.isLoading;
return {
@@ -410,6 +214,17 @@ function useSecretsActions(state: ReturnType<typeof useSecretsState>) {
deleteRequest.run(deleteTarget.id).catch(() => undefined);
setDeleteTarget(null);
},
openTransfer: (secret: SecretListItem) => {
// Remember the focused Copy/Move button; close restores it because
// Radix targets a stale node when the list re-renders mid-close.
rememberTransferTrigger();
setTransferTarget(secret);
setTransferOpen(true);
},
closeTransfer: () => {
setTransferOpen(false);
restoreTransferTrigger();
},
items: state.items,
};
}
@@ -418,6 +233,7 @@ function useSecretsActions(state: ReturnType<typeof useSecretsState>) {
/* Main component */
/* ------------------------------------------------------------------ */
/** Computes the edit draft's revision, dirty flag, and baseline from the current form state. */
function getSecretEditState(
items: SecretListItem[],
editingId: string | null,
@@ -433,6 +249,7 @@ function getSecretEditState(
};
}
/** Computes the combined draft metadata (dirty flag, revision) covering both create and edit states. */
export function getSecretDraftMeta(
items: SecretListItem[],
editingId: string | null,
@@ -447,25 +264,63 @@ export function getSecretDraftMeta(
};
}
export type SecretsSettingsState = {
loaded: boolean;
items: SecretListItem[];
addSecret: (item: SecretListItem) => void;
updateSecretInStore: (item: SecretListItem) => void;
removeSecret: (id: string) => void;
scope: SecretScope;
workspaceId?: string;
editingId: string | null;
setEditingId: (id: string | null) => void;
showCreate: boolean;
setShowCreate: (show: boolean) => void;
formState: SecretFormState;
setFormState: (state: SecretFormState | ((prev: SecretFormState) => SecretFormState)) => void;
deleteTarget: SecretListItem | null;
setDeleteTarget: (target: SecretListItem | null) => void;
transferTarget: SecretListItem | null;
setTransferTarget: (target: SecretListItem | null) => void;
transferOpen: boolean;
setTransferOpen: (open: boolean) => void;
};
export type SecretsSettingsActions = {
resetForm: () => void;
isValid: boolean;
isBusy: boolean;
handleCreate: () => Promise<void>;
handleUpdate: () => Promise<void>;
startEditing: (secret: SecretListItem) => void;
startCreate: () => void;
openDelete: (secret: SecretListItem) => void;
closeDelete: () => void;
confirmDelete: () => void;
openTransfer: (secret: SecretListItem) => void;
closeTransfer: () => void;
items: SecretListItem[];
};
type SecretsSettingsProps = {
scope?: SecretScope;
workspaceId?: string;
initialItems?: SecretListItem[];
};
type SecretsSettingsState = ReturnType<typeof useSecretsState>;
type SecretsSettingsActions = ReturnType<typeof useSecretsActions>;
/** Returns the settings title for the given secret scope. */
function secretScopeTitle(t: TFunction, scope: SecretScope) {
return scope === "workspace" ? t("settings:secrets") : t("settings:globalSecrets");
}
/** Returns the settings description for the given secret scope. */
function secretScopeDescription(t: TFunction, scope: SecretScope) {
return scope === "workspace"
? t("settings:workspaceSecretsDescription")
: t("settings:manageApiKeysAndCredentialsSecrets");
}
/** Returns the reason a dirty draft cannot be saved, or undefined when it can. */
function secretDraftInvalidReason(
t: TFunction,
showCreate: boolean,
@@ -487,6 +342,7 @@ type SecretsSettingsBodyProps = {
onFormChange: (patch: Partial<SecretFormState>) => void;
};
/** Renders the secrets list, create/edit forms, and delete dialog for the current scope. */
function SecretsSettingsBody({
scope,
workspaceId,
@@ -563,6 +419,7 @@ function SecretsSettingsBody({
workspaceId={workspaceId}
onEdit={actions.startEditing}
onDelete={actions.openDelete}
onCopyMove={actions.openTransfer}
isBusy={isBusy}
showCreate={showCreate}
isEditing={editingId === secret.id}
@@ -581,6 +438,7 @@ function SecretsSettingsBody({
);
}
/** Renders the page-template wrapper with dirty-state handling for the secrets panel. */
function SecretsSettingsContent({
scope,
workspaceId,
@@ -598,6 +456,7 @@ function SecretsSettingsContent({
const { edit, isDirty, revision } = getSecretDraftMeta(items, editingId, showCreate, formState);
const invalidReason = secretDraftInvalidReason(t, showCreate, isDirty, isValid);
/** Applies a partial form patch to the draft state. */
const onFormChange = (patch: Partial<SecretFormState>) =>
setFormState((prev) => ({ ...prev, ...patch }));
@@ -633,6 +492,7 @@ function SecretsSettingsContent({
);
}
/** Renders the full secrets settings panel: state, actions, and the copy/move dialog. */
export function SecretsSettings({
scope = "global",
workspaceId,
@@ -640,12 +500,51 @@ export function SecretsSettings({
}: SecretsSettingsProps) {
const state = useSecretsState(scope, workspaceId, initialItems);
const actions = useSecretsActions(state);
const globalAdd = useAppStore((s) => s.addSecret);
const workspaceNames = useAppStore((s) => s.workspaces.items);
/** Resolves the display origin token for a secret's source scope. */
const originTokenFor = (secret: SecretListItem) =>
secret.scope === "workspace"
? (workspaceNames.find((workspace) => workspace.id === secret.workspace_id)?.name ??
secret.workspace_id ??
"workspace")
: "Global";
// Route the transfer result by the RETURNED item's scope, never the page
// scope: Global targets always land in the Global store (from any page),
// workspace targets join the page's list only when the page is that
// workspace, and a Move removes the source from the page's own list.
/** Routes a completed transfer: adds the returned item to the right store and removes the source on move. */
const handleTransferCompleted = (item: SecretListItem, mode: CopyMoveMode) => {
if (!item.scope || item.scope === "global") {
globalAdd(item);
} else if (scope === "workspace" && workspaceId === item.workspace_id) {
state.addSecret(item);
}
if (mode === "move" && state.transferTarget) {
state.removeSecret(state.transferTarget.id);
}
actions.closeTransfer();
};
return (
<SecretsSettingsContent
scope={scope}
workspaceId={workspaceId}
state={state}
actions={actions}
/>
<>
<SecretsSettingsContent
scope={scope}
workspaceId={workspaceId}
state={state}
actions={actions}
/>
{state.transferTarget && (
<CopyMoveSecretDialog
secret={state.transferTarget}
originToken={originTokenFor(state.transferTarget)}
open={state.transferOpen}
onClose={actions.closeTransfer}
onCompleted={handleTransferCompleted}
/>
)}
</>
);
}
@@ -0,0 +1,167 @@
import { test, expect } from "../../fixtures/test-base";
import {
assertNoDescendantOverflowsRight,
assertNoDocumentHorizontalOverflow,
} from "../../helpers/layout-assertions";
const WORKSPACE_VALUE = "e2e-mobile-copy-move-value";
const GLOBAL_VALUE = "e2e-mobile-copy-move-global";
/** Unique per run so retries never collide with leftovers from a failed attempt. */
const runToken = () => `${Date.now()}${Math.random().toString(36).slice(2, 6)}`;
test.describe("mobile-secrets-copy-move", () => {
test("moves a workspace secret to General and copies one back at phone width", async ({
testPage,
apiClient,
seedData,
prCapture,
}) => {
await testPage.setViewportSize({ width: 390, height: 844 });
const sourceName = `E2E Mobile Copy Move ${runToken()}`;
const movedName = `E2E Mobile Moved ${runToken()}`;
const copiedName = `E2E Mobile Copied ${runToken()}`;
// Seed a General secret whose name collides with the max-length target
// name, so the conflict message (not just the input) is exercised below.
const longName = "x".repeat(100);
await testPage.goto("/settings/general/secrets");
await testPage.getByRole("button", { name: "Add secret", exact: true }).click();
await testPage.getByPlaceholder("Name (e.g. OpenAI Production Key)").fill(longName);
await testPage.getByPlaceholder("Secret value").fill(GLOBAL_VALUE);
await testPage
.getByTestId("settings-floating-save")
.getByRole("button", { name: "Save changes" })
.click();
await expect(testPage.getByText(longName, { exact: true })).toBeVisible();
// Create a workspace secret through the mobile flow.
await testPage.goto(`/settings/workspace/${seedData.workspaceId}/secrets`);
await testPage.getByRole("button", { name: "Add secret", exact: true }).click();
await testPage.getByPlaceholder("Name (e.g. OpenAI Production Key)").fill(sourceName);
await testPage.getByPlaceholder("Secret value").fill(WORKSPACE_VALUE);
const secretSave = testPage
.getByTestId("settings-floating-save")
.getByRole("button", { name: "Save changes" });
await expect(secretSave).toBeEnabled();
await secretSave.click();
await expect(testPage.getByText(sourceName, { exact: true })).toBeVisible();
// Move it to General through the dialog's own controls.
await testPage.getByRole("button", { name: `Copy or move ${sourceName}` }).click();
const dialog = testPage.getByRole("dialog");
await expect(dialog).toBeVisible();
await dialog.getByRole("radio", { name: /Move/ }).click();
await dialog.getByLabel("Name").fill(movedName);
// The mode option CARDS are the touch targets (the radio indicator itself
// is the standard 16px control).
for (const control of [
dialog.getByLabel("Name"),
dialog.locator("label").filter({ hasText: "Copy" }),
dialog.locator("label").filter({ hasText: "Move" }),
dialog.getByRole("button", { name: "Move", exact: true }),
dialog.getByRole("button", { name: "Close", exact: true }),
]) {
const box = await control.boundingBox();
expect(box).not.toBeNull();
expect(box!.height).toBeGreaterThanOrEqual(44);
}
await assertNoDocumentHorizontalOverflow(testPage, "mobile copy/move dialog");
// Scroll contract: the settings content area is the single scroll owner.
// The bottom-sheet dialog must not create document scroll or push its
// actions below the viewport.
const documentVerticalOverflow = await testPage.evaluate(
() => document.documentElement.scrollHeight > window.innerHeight,
);
expect(documentVerticalOverflow).toBe(false);
const moveButtonBox = await dialog
.getByRole("button", { name: "Move", exact: true })
.boundingBox();
expect(moveButtonBox).not.toBeNull();
expect(moveButtonBox!.y + moveButtonBox!.height).toBeLessThanOrEqual(844);
// Max-length unbroken text must not push any dialog descendant past the
// sheet's right edge: fill the target name with a value that CONFLICTS
// with the seeded General secret, so the conflict message is rendered
// while its wrapping (break-words) is exercised.
await dialog.getByLabel("Name").fill(longName);
await expect(dialog.getByText(/already exists in this destination/)).toBeVisible();
await assertNoDescendantOverflowsRight(dialog, "mobile copy/move dialog with 100-char name");
await dialog.getByLabel("Name").fill(movedName);
await dialog.getByRole("button", { name: "Move", exact: true }).click();
await expect(dialog).toBeHidden();
await expect(testPage.getByText(sourceName, { exact: true })).toHaveCount(0);
await expect(testPage.locator("body")).not.toContainText(WORKSPACE_VALUE);
// The moved secret now lives in General.
await testPage.goto("/settings/general/secrets");
await expect(testPage.getByText(movedName, { exact: true })).toBeVisible();
// Copy it back to the workspace using the destination picker.
await testPage.getByRole("button", { name: `Copy or move ${movedName}` }).click();
const copyDialog = testPage.getByRole("dialog");
await expect(copyDialog).toBeVisible();
await copyDialog.getByLabel("Name").fill(copiedName);
const workspaces = await apiClient.listWorkspaces();
const workspaceName = workspaces.workspaces.find(
(workspace) => workspace.id === seedData.workspaceId,
)?.name;
expect(workspaceName).toBeTruthy();
await copyDialog.getByRole("combobox", { name: "Destination" }).click();
await testPage
.getByRole("listbox")
.getByRole("option", { name: workspaceName!, exact: true })
.click();
await copyDialog.getByRole("button", { name: "Copy", exact: true }).click();
await expect(copyDialog).toBeHidden();
await testPage.goto(`/settings/workspace/${seedData.workspaceId}/secrets`);
await expect(testPage.getByText(copiedName, { exact: true })).toBeVisible();
await expect(testPage.locator("body")).not.toContainText(WORKSPACE_VALUE);
await assertNoDocumentHorizontalOverflow(testPage, "mobile secrets after copy/move");
// Touch emulation does not move focus on tap, so focus restoration is
// covered in the desktop spec (keyboard/mouse focus contract) instead.
await prCapture.screenshot("mobile-secrets-copy-move", {
caption: "Mobile secrets copy/move flow",
});
});
test("keeps the dialog usable on a short viewport when an error is shown", async ({
testPage,
apiClient,
seedData,
}) => {
await testPage.setViewportSize({ width: 390, height: 480 });
const sourceName = `E2E Short Viewport ${Date.now()}`;
await apiClient.createSecret(sourceName, "short-viewport-value", {
scope: "workspace",
workspaceId: seedData.workspaceId,
});
await testPage.goto(`/settings/workspace/${seedData.workspaceId}/secrets`);
await testPage.getByRole("button", { name: `Copy or move ${sourceName}` }).click();
const dialog = testPage.getByRole("dialog");
await expect(dialog).toBeVisible();
// Trigger an in-dialog error: an overlong target name (101 bytes).
await dialog.getByLabel("Name").fill("x".repeat(101));
await expect(dialog.getByText(/at most 100 bytes/)).toBeVisible();
// The footer stays within the viewport and the sheet never exceeds it;
// the middle section scrolls internally instead.
const submitBox = await dialog.getByRole("button", { name: "Copy", exact: true }).boundingBox();
expect(submitBox).not.toBeNull();
expect(submitBox!.y + submitBox!.height).toBeLessThanOrEqual(480);
const dialogBox = await dialog.boundingBox();
expect(dialogBox).not.toBeNull();
expect(dialogBox!.y + dialogBox!.height).toBeLessThanOrEqual(480);
const documentOverflow = await testPage.evaluate(
() => document.documentElement.scrollHeight > window.innerHeight,
);
expect(documentOverflow).toBe(false);
});
});
@@ -0,0 +1,185 @@
import { test, expect } from "../../fixtures/test-base";
const GLOBAL_VALUE = "e2e-copy-move-global-value";
/** Unique per run so retries never collide with leftovers from a failed attempt. */
const runToken = () => `${Date.now()}${Math.random().toString(36).slice(2, 6)}`;
const WORKSPACE_VALUE = "e2e-copy-move-workspace-value";
/** Creates a secret from the settings page via the Add secret dialog. */
async function createSecretFromSettings(
page: import("@playwright/test").Page,
route: string,
name: string,
value: string,
) {
await page.goto(route);
await expect(page.getByRole("button", { name: "Add secret", exact: true })).toBeVisible();
await page.getByRole("button", { name: "Add secret", exact: true }).click();
await page.getByPlaceholder("Name (e.g. OpenAI Production Key)").fill(name);
await page.getByPlaceholder("Secret value").fill(value);
const save = page
.getByTestId("settings-floating-save")
.getByRole("button", { name: "Save changes" });
await expect(save).toBeEnabled();
await save.click();
await expect(page.getByText(name, { exact: true })).toBeVisible();
await expect(page.locator("body")).not.toContainText(value);
}
/**
* Opens the copy/move dialog for a named secret and submits through the
* dialog's OWN primary button (never the settings floating Save control).
*/
async function submitCopyMove(
page: import("@playwright/test").Page,
secretName: string,
mode: "Copy" | "Move",
) {
await page.getByRole("button", { name: `Copy or move ${secretName}` }).click();
const dialog = page.getByRole("dialog");
await expect(dialog).toBeVisible();
if (mode === "Move") {
await dialog.getByRole("radio", { name: /Move/ }).click();
}
await dialog.getByRole("button", { name: mode, exact: true }).click();
await expect(dialog).toBeHidden();
}
test.describe("secrets-copy-move", () => {
test("copies a global secret to a workspace with the default suffixed name", async ({
testPage,
apiClient,
seedData,
}) => {
const sourceName = `E2E Copy Move Global Copy ${runToken()}`;
const copiedName = `${sourceName} (from Global)`;
await createSecretFromSettings(testPage, "/settings/general/secrets", sourceName, GLOBAL_VALUE);
const global = (await apiClient.listSecrets()).find((secret) => secret.name === sourceName);
expect(global?.id).toBeTruthy();
await submitCopyMove(testPage, sourceName, "Copy");
// The source stays on the Global page; the copy appears in the workspace.
await expect(testPage.getByText(sourceName, { exact: true })).toBeVisible();
await testPage.goto(`/settings/workspace/${seedData.workspaceId}/secrets`);
await expect(testPage.getByText(copiedName, { exact: true })).toBeVisible();
await expect(testPage.locator("body")).not.toContainText(GLOBAL_VALUE);
const copied = (
await apiClient.listSecrets({ scope: "workspace", workspaceId: seedData.workspaceId })
).find((secret) => secret.name === copiedName);
expect(copied?.scope).toBe("workspace");
expect(copied?.workspace_id).toBe(seedData.workspaceId);
});
test("moves a workspace secret to General and removes the source", async ({
testPage,
apiClient,
seedData,
}) => {
const sourceName = `E2E Copy Move Workspace Move ${runToken()}`;
await createSecretFromSettings(
testPage,
`/settings/workspace/${seedData.workspaceId}/secrets`,
sourceName,
WORKSPACE_VALUE,
);
const workspaces = await apiClient.listWorkspaces();
const workspaceName = workspaces.workspaces.find(
(workspace) => workspace.id === seedData.workspaceId,
)?.name;
expect(workspaceName).toBeTruthy();
const movedName = `${sourceName} (from ${workspaceName})`;
await submitCopyMove(testPage, sourceName, "Move");
await expect(testPage.getByText(sourceName, { exact: true })).toHaveCount(0);
await expect(testPage.locator("body")).not.toContainText(WORKSPACE_VALUE);
await testPage.goto("/settings/general/secrets");
await expect(testPage.getByText(movedName, { exact: true })).toBeVisible();
const moved = (await apiClient.listSecrets()).find((secret) => secret.name === movedName);
expect(moved?.scope).toBe("global");
const workspaceSecret = (
await apiClient.listSecrets({ scope: "workspace", workspaceId: seedData.workspaceId })
).find((secret) => secret.name === sourceName);
expect(workspaceSecret).toBeUndefined();
});
test("moves a global secret to a workspace and removes the source", async ({
testPage,
apiClient,
seedData,
}) => {
const sourceName = `E2E Copy Move Global Move ${runToken()}`;
const movedName = `${sourceName} (from Global)`;
await createSecretFromSettings(testPage, "/settings/general/secrets", sourceName, GLOBAL_VALUE);
await submitCopyMove(testPage, sourceName, "Move");
await expect(testPage.getByText(sourceName, { exact: true })).toHaveCount(0);
await testPage.goto(`/settings/workspace/${seedData.workspaceId}/secrets`);
await expect(testPage.getByText(movedName, { exact: true })).toBeVisible();
await expect(testPage.locator("body")).not.toContainText(GLOBAL_VALUE);
const global = (await apiClient.listSecrets()).find((secret) => secret.name === sourceName);
expect(global).toBeUndefined();
const workspace = (
await apiClient.listSecrets({ scope: "workspace", workspaceId: seedData.workspaceId })
).find((secret) => secret.name === movedName);
expect(workspace?.workspace_id).toBe(seedData.workspaceId);
});
test("blocks a duplicate target name and marks the name field invalid", async ({
testPage,
seedData,
}) => {
const sourceName = `E2E Copy Move Conflict Source ${runToken()}`;
const conflictingName = `${sourceName} (from Global)`;
await createSecretFromSettings(testPage, "/settings/general/secrets", sourceName, GLOBAL_VALUE);
await createSecretFromSettings(
testPage,
`/settings/workspace/${seedData.workspaceId}/secrets`,
conflictingName,
WORKSPACE_VALUE,
);
await testPage.goto("/settings/general/secrets");
await testPage.getByRole("button", { name: `Copy or move ${sourceName}` }).click();
const dialog = testPage.getByRole("dialog");
await expect(dialog).toBeVisible();
const nameInput = dialog.getByLabel("Name");
await expect(nameInput).toHaveValue(conflictingName);
await expect(nameInput).toHaveAttribute("aria-invalid", "true");
await expect(
dialog.getByText(`A secret named ${conflictingName} already exists in this destination.`),
).toBeVisible();
await expect(dialog.getByRole("button", { name: "Copy", exact: true })).toBeDisabled();
// Editing the name clears the conflict and re-enables submission.
await nameInput.fill(`${sourceName} (copy)`);
await expect(nameInput).not.toHaveAttribute("aria-invalid", "true");
await expect(dialog.getByRole("button", { name: "Copy", exact: true })).toBeEnabled();
});
test("restores focus to the trigger after closing the dialog", async ({ testPage }) => {
// Unique per run: retries must not collide with a secret a previous
// attempt left behind (the fixture reset does not remove secrets).
const sourceName = `E2E Copy Move Focus ${Date.now()} ${Math.random().toString(36).slice(2, 6)}`;
await createSecretFromSettings(testPage, "/settings/general/secrets", sourceName, GLOBAL_VALUE);
await testPage.getByRole("button", { name: `Copy or move ${sourceName}` }).click();
const dialog = testPage.getByRole("dialog");
await expect(dialog).toBeVisible();
await dialog.getByRole("button", { name: "Close", exact: true }).click();
await expect(dialog).toBeHidden();
// Desktop mouse clicks focus the trigger; closing the dialog restores it.
await expect
.poll(async () =>
testPage.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? ""),
)
.toContain(`Copy or move ${sourceName}`);
});
});
@@ -0,0 +1,106 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { SecretListItem } from "@/lib/types/http-secrets";
const { mockListSecrets, storeState } = vi.hoisted(() => ({
mockListSecrets: vi.fn(),
storeState: {
secrets: { items: [] as SecretListItem[], loaded: true, loading: false },
setSecrets: vi.fn(),
setSecretsLoading: vi.fn(),
addSecret: vi.fn(),
updateSecret: vi.fn(),
removeSecret: vi.fn(),
},
}));
vi.mock("@/lib/api/domains/secrets-api", () => ({ listSecrets: mockListSecrets }));
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: typeof storeState) => unknown) => selector(storeState),
}));
import { secretNameConflict, useSecretDestinationNames } from "./use-secret-destination-names";
/** Deferred promise helper for controlling async test resolution. */
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((nextResolve) => {
resolve = nextResolve;
});
return { promise, resolve };
}
describe("secretNameConflict", () => {
it("matches exact trimmed names only", () => {
expect(secretNameConflict(["API Key"], "API Key")).toBe(true);
expect(secretNameConflict(["API Key"], " API Key ")).toBe(true);
expect(secretNameConflict(["API Key"], "api key")).toBe(false);
expect(secretNameConflict([], "API Key")).toBe(false);
expect(secretNameConflict(["API Key"], " ")).toBe(false);
});
});
describe("useSecretDestinationNames", () => {
beforeEach(() => {
mockListSecrets.mockReset();
storeState.secrets.items = [];
});
it("reads Global names from the store and excludes workspace entries", () => {
storeState.secrets.items = [
{ id: "g1", name: "Global Key" } as SecretListItem,
{ id: "w1", name: "Workspace Key", scope: "workspace" } as SecretListItem,
];
const view = renderHook(() => useSecretDestinationNames("global"));
expect(view.result.current.names).toEqual(["Global Key"]);
expect(view.result.current.loaded).toBe(true);
expect(view.result.current.conflict("Global Key")).toBe(true);
expect(view.result.current.conflict("Workspace Key")).toBe(false);
expect(mockListSecrets).not.toHaveBeenCalled();
});
it("fetches workspace names on demand and caches per workspace", async () => {
const pending = deferred<SecretListItem[]>();
mockListSecrets.mockReturnValue(pending.promise);
const view = renderHook(
({ workspaceId }: { workspaceId?: string }) =>
useSecretDestinationNames("workspace", workspaceId),
{ initialProps: { workspaceId: "workspace-a" } },
);
expect(view.result.current.loaded).toBe(false);
expect(view.result.current.conflict("anything")).toBe(false);
await act(async () => pending.resolve([{ id: "w1", name: "Taken" } as SecretListItem]));
await waitFor(() => expect(view.result.current.loaded).toBe(true));
expect(view.result.current.conflict("Taken")).toBe(true);
expect(view.result.current.conflict("other")).toBe(false);
// Same workspace does not refetch.
view.rerender({ workspaceId: "workspace-a" });
expect(mockListSecrets).toHaveBeenCalledTimes(1);
// A different workspace refetches.
view.rerender({ workspaceId: "workspace-b" });
expect(mockListSecrets).toHaveBeenCalledTimes(2);
});
it("refetches the same workspace when the refresh key changes", async () => {
mockListSecrets.mockResolvedValue([]);
const view = renderHook(
({ refreshKey }: { refreshKey: number }) =>
useSecretDestinationNames("workspace", "workspace-a", refreshKey),
{ initialProps: { refreshKey: 0 } },
);
await waitFor(() => expect(view.result.current.loaded).toBe(true));
expect(mockListSecrets).toHaveBeenCalledTimes(1);
// Same key: cached.
view.rerender({ refreshKey: 0 });
expect(mockListSecrets).toHaveBeenCalledTimes(1);
// New transfer session: the per-workspace cache must be invalidated so a
// secret copied in the previous session shows up as a conflict now.
view.rerender({ refreshKey: 1 });
await waitFor(() => expect(mockListSecrets).toHaveBeenCalledTimes(2));
});
});
@@ -0,0 +1,90 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useAppStore } from "@/components/state-provider";
import { listSecrets } from "@/lib/api/domains/secrets-api";
import type { SecretScope } from "@/lib/types/http-secrets";
/**
* Exact-trimmed name conflict helper: a copy/move target name conflicts when
* an identical (trimmed) name already exists in the destination scope. The
* backend remains authoritative; this only powers the dialog's pre-check.
*/
export function secretNameConflict(names: string[], name: string): boolean {
const trimmed = name.trim();
return trimmed !== "" && names.includes(trimmed);
}
/**
* Loads the existing secret names of a destination scope for the copy/move
* conflict pre-check. Global names come from the store; workspace names are
* fetched on demand and cached per workspace.
*/
export function useSecretDestinationNames(
scope: SecretScope,
workspaceId?: string,
refreshKey = 0,
) {
const globalItems = useAppStore((state) => state.secrets.items);
const [workspaceNames, setWorkspaceNames] = useState<string[]>([]);
const [workspaceLoaded, setWorkspaceLoaded] = useState(scope !== "workspace");
// Ref-based cache key: a state key would re-run the effect (and its
// cleanup, which cancels the in-flight request) on every fetch.
const cacheKeyRef = useRef("");
const lastRefreshKey = useRef(refreshKey);
useEffect(() => {
// A new transfer session (different secret or reopened dialog) must see
// fresh destination names, e.g. a secret copied in the previous session.
if (refreshKey !== lastRefreshKey.current) {
lastRefreshKey.current = refreshKey;
cacheKeyRef.current = "";
}
if (scope !== "workspace") {
return;
}
const key = workspaceId ?? "";
if (key === cacheKeyRef.current) {
return;
}
cacheKeyRef.current = key;
if (!workspaceId) {
setWorkspaceNames([]);
setWorkspaceLoaded(true);
return;
}
let cancelled = false;
setWorkspaceLoaded(false);
listSecrets({ scope: "workspace", workspaceId, cache: "no-store" })
.then((items) => {
if (!cancelled) {
setWorkspaceNames((items ?? []).map((item) => item.name));
}
})
.catch(() => {
if (!cancelled) {
setWorkspaceNames([]);
}
})
.finally(() => {
if (!cancelled) {
setWorkspaceLoaded(true);
}
});
return () => {
cancelled = true;
};
}, [scope, workspaceId, refreshKey]);
const names =
scope === "global"
? globalItems.filter((item) => item.scope !== "workspace").map((item) => item.name)
: workspaceNames;
const loaded = scope === "global" || workspaceLoaded;
return {
names,
loaded,
conflict: (name: string) => loaded && secretNameConflict(names, name),
};
}
@@ -0,0 +1,106 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { mockListWorkspaces, storeState } = vi.hoisted(() => ({
mockListWorkspaces: vi.fn(),
storeState: {
workspaces: { items: [] as { id: string; name: string }[], activeId: null },
setWorkspaces: vi.fn(),
},
}));
vi.mock("@/lib/api/domains/workspace-api", () => ({ listWorkspaces: mockListWorkspaces }));
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: typeof storeState) => unknown) => selector(storeState),
}));
import { useWorkspaceDestinations } from "./use-workspace-destinations";
/** Deferred promise helper for controlling async test resolution. */
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((nextResolve, nextReject) => {
resolve = nextResolve;
reject = nextReject;
});
return { promise, resolve, reject };
}
describe("useWorkspaceDestinations", () => {
beforeEach(() => {
mockListWorkspaces.mockReset();
storeState.setWorkspaces.mockClear();
storeState.workspaces.items = [];
});
it("fetches workspaces when the store list is empty and writes them to the store", async () => {
const pending = deferred<{ workspaces: { id: string; name: string }[]; total: number }>();
mockListWorkspaces.mockReturnValue(pending.promise);
const view = renderHook(() => useWorkspaceDestinations());
expect(view.result.current.loading).toBe(true);
expect(view.result.current.error).toBeNull();
await act(async () =>
pending.resolve({
workspaces: [
{ id: "ws-1", name: "One" },
{ id: "ws-2", name: "Two" },
],
total: 2,
}),
);
await waitFor(() => expect(view.result.current.loading).toBe(false));
const stored = storeState.setWorkspaces.mock.calls[0][0] as {
id: string;
name: string;
}[];
expect(stored.map((item) => [item.id, item.name])).toEqual([
["ws-1", "One"],
["ws-2", "Two"],
]);
expect(view.result.current.error).toBeNull();
});
it("does not fetch when the store already has workspaces", () => {
storeState.workspaces.items = [{ id: "ws-1", name: "One" }];
const view = renderHook(() => useWorkspaceDestinations());
expect(mockListWorkspaces).not.toHaveBeenCalled();
expect(view.result.current.error).toBeNull();
});
it("preserves failures as an error and retry re-runs the fetch", async () => {
const first = deferred<{ workspaces: never[]; total: number }>();
mockListWorkspaces.mockReturnValueOnce(first.promise);
const view = renderHook(() => useWorkspaceDestinations());
await act(async () => first.reject(new Error("boom")));
await waitFor(() => expect(view.result.current.error).not.toBeNull());
expect(storeState.setWorkspaces).not.toHaveBeenCalled();
const second = deferred<{ workspaces: { id: string; name: string }[]; total: number }>();
mockListWorkspaces.mockReturnValueOnce(second.promise);
act(() => view.result.current.retry());
await act(async () => second.resolve({ workspaces: [{ id: "ws-1", name: "One" }], total: 1 }));
await waitFor(() => expect(view.result.current.error).toBeNull());
expect(storeState.setWorkspaces).toHaveBeenCalledTimes(1);
});
it("stops fetching once a hydration or retry populated the store", async () => {
const pending = deferred<{ workspaces: never[]; total: number }>();
mockListWorkspaces.mockReturnValue(pending.promise);
const view = renderHook(() => useWorkspaceDestinations());
expect(view.result.current.loading).toBe(true);
storeState.workspaces.items = [{ id: "ws-1", name: "One" }];
view.rerender();
await act(async () => pending.reject(new Error("late failure")));
// The store was populated meanwhile, so the stale failure must not
// surface as an error, must not trigger another fetch, and must not leave
// loading stuck true (which would disable submission forever).
await waitFor(() => expect(view.result.current.error).toBeNull());
expect(view.result.current.loading).toBe(false);
expect(mockListWorkspaces).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,59 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useAppStore } from "@/components/state-provider";
import { listWorkspaces } from "@/lib/api/domains/workspace-api";
import { mapWorkspaceItem } from "@/lib/routing/route-bootstrap";
/**
* Ensures the workspace destination list is available to the copy/move
* dialog with a real retry path and a single source of truth. The picker
* reads the store only; this hook fetches `listWorkspaces` when the store's
* list is empty (e.g. settings hydration failed) and writes successful
* results into the store via `setWorkspaces`. Failures are preserved as
* `error` (never converted into an empty list), and `retry` re-runs the
* fetch. A newer hydration simply supersedes the fallback result.
*/
export function useWorkspaceDestinations() {
const workspaceItems = useAppStore((state) => state.workspaces.items);
const setWorkspaces = useAppStore((state) => state.setWorkspaces);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
if (workspaceItems.length > 0) {
// Hydration (or a retry result) superseded the fallback request: clear
// any in-flight loading state so submission is not disabled forever.
setError(null);
setLoading(false);
return;
}
let cancelled = false;
setLoading(true);
setError(null);
listWorkspaces({ cache: "no-store" })
.then((response) => {
if (!cancelled) {
setWorkspaces(response.workspaces.map(mapWorkspaceItem));
}
})
.catch(() => {
if (!cancelled) {
setError("failed");
}
})
.finally(() => {
if (!cancelled) {
setLoading(false);
}
});
return () => {
cancelled = true;
};
}, [workspaceItems.length, attempt, setWorkspaces]);
const retry = useCallback(() => setAttempt((value) => value + 1), []);
return { loading, error, retry };
}
+56 -1
View File
@@ -4,7 +4,14 @@ vi.mock("@/lib/config", () => ({
getBackendConfig: () => ({ apiBaseUrl: "http://backend.test" }),
}));
import { deleteSecret, listSecrets, revealSecret, updateSecret } from "./secrets-api";
import {
copySecret,
deleteSecret,
listSecrets,
moveSecret,
revealSecret,
updateSecret,
} from "./secrets-api";
describe("secrets API scope parameters", () => {
const fetchSpy = vi.fn<typeof fetch>();
@@ -45,4 +52,52 @@ describe("secrets API scope parameters", () => {
expect(new URL(String(requestURL)).searchParams.get("workspace_id")).toBe(WORKSPACE_ID);
}
});
it("copies to the target scope and workspace with the source workspace query", async () => {
fetchSpy.mockImplementation(async () => new Response("{}", { status: 201 }));
await copySecret(
"secret-1",
{ target_scope: "workspace", target_workspace_id: "workspace-2", name: "copied" },
{ workspaceId: WORKSPACE_ID },
);
const [requestURL, init] = fetchSpy.mock.calls[0]!;
const url = new URL(String(requestURL));
expect(url.pathname).toBe("/api/v1/secrets/secret-1/copy");
expect(url.searchParams.get("workspace_id")).toBe(WORKSPACE_ID);
expect(init?.method).toBe("POST");
expect(JSON.parse(String(init?.body))).toEqual({
target_scope: "workspace",
target_workspace_id: "workspace-2",
name: "copied",
});
});
it("moves to global without emitting a null name", async () => {
fetchSpy.mockImplementation(async () => new Response("{}", { status: 201 }));
await moveSecret("secret-1", { target_scope: "global" });
const [requestURL, init] = fetchSpy.mock.calls[0]!;
expect(new URL(String(requestURL)).pathname).toBe("/api/v1/secrets/secret-1/move");
const body = JSON.parse(String(init?.body));
expect(body.target_scope).toBe("global");
// The payload builder contract: `name` is undefined (omitted) or a string,
// never `null`.
expect(Object.prototype.hasOwnProperty.call(body, "name")).toBe(false);
expect(body).not.toHaveProperty("name", null);
expect(body).not.toHaveProperty("target_workspace_id");
});
it("surfaces the conflict status for callers", async () => {
fetchSpy.mockImplementation(
async () => new Response(JSON.stringify({ error: "conflict" }), { status: 409 }),
);
await expect(
copySecret("secret-1", {
target_scope: "workspace",
target_workspace_id: WORKSPACE_ID,
name: "x",
}),
).rejects.toMatchObject({ status: 409 });
});
});
+37
View File
@@ -3,20 +3,24 @@ import type {
SecretListItem,
CreateSecretRequest,
UpdateSecretRequest,
CopyMoveSecretRequest,
RevealSecretResponse,
SecretScope,
} from "@/lib/types/http-secrets";
/** Options for listing secrets: optional scope, workspace, and include-global filter. */
export type SecretListOptions = ApiRequestOptions & {
scope?: SecretScope;
workspaceId?: string;
includeGlobal?: boolean;
};
/** Common options that scope a secrets request to a workspace. */
export type SecretScopedOptions = ApiRequestOptions & {
workspaceId?: string;
};
/** Appends scope/workspace/includeGlobal query parameters to a secrets API path. */
function withSecretQuery(
path: string,
options?: { scope?: SecretScope; workspaceId?: string; includeGlobal?: boolean },
@@ -29,6 +33,7 @@ function withSecretQuery(
return suffix ? `${path}?${suffix}` : path;
}
/** Lists secrets, optionally filtered by scope, workspace, and global inclusion. */
export async function listSecrets(options?: SecretListOptions): Promise<SecretListItem[]> {
const { scope, workspaceId, includeGlobal, ...requestOptions } = options ?? {};
return fetchJson<SecretListItem[]>(
@@ -37,6 +42,7 @@ export async function listSecrets(options?: SecretListOptions): Promise<SecretLi
);
}
/** Creates a secret from the given payload and returns the new item. */
export async function createSecret(
payload: CreateSecretRequest,
options?: ApiRequestOptions,
@@ -47,6 +53,7 @@ export async function createSecret(
});
}
/** Updates the secret with the given id and returns the updated item. */
export async function updateSecret(
id: string,
payload: UpdateSecretRequest,
@@ -58,6 +65,7 @@ export async function updateSecret(
});
}
/** Deletes the secret with the given id. */
export async function deleteSecret(id: string, options?: SecretScopedOptions): Promise<void> {
return fetchJson<void>(withSecretQuery(`/api/v1/secrets/${id}`, options), {
...options,
@@ -65,6 +73,7 @@ export async function deleteSecret(id: string, options?: SecretScopedOptions): P
});
}
/** Reveals the value of the secret with the given id. */
export async function revealSecret(
id: string,
options?: SecretScopedOptions,
@@ -74,3 +83,31 @@ export async function revealSecret(
init: { method: "POST", ...(options?.init ?? {}) },
});
}
/**
* Copies a secret into another scope/workspace. The `workspaceId` option is
* the SOURCE workspace for a workspace-scoped source. Errors surface as
* `ApiError` with the HTTP status (409 = target name conflict).
*/
export async function copySecret(
id: string,
payload: CopyMoveSecretRequest,
options?: SecretScopedOptions,
): Promise<SecretListItem> {
return fetchJson<SecretListItem>(withSecretQuery(`/api/v1/secrets/${id}/copy`, options), {
...options,
init: { method: "POST", body: JSON.stringify(payload), ...(options?.init ?? {}) },
});
}
/** Moves a secret into another scope/workspace, removing the source. */
export async function moveSecret(
id: string,
payload: CopyMoveSecretRequest,
options?: SecretScopedOptions,
): Promise<SecretListItem> {
return fetchJson<SecretListItem>(withSecretQuery(`/api/v1/secrets/${id}/move`, options), {
...options,
init: { method: "POST", body: JSON.stringify(payload), ...(options?.init ?? {}) },
});
}
+16
View File
@@ -1,5 +1,7 @@
/** Scope of a secret: either global or bound to a workspace. */
export type SecretScope = "global" | "workspace";
/** A secret as returned by the secrets API. */
export interface SecretListItem {
id: string;
name: string;
@@ -10,6 +12,7 @@ export interface SecretListItem {
updated_at: string;
}
/** Request payload for creating a secret. */
export interface CreateSecretRequest {
name: string;
value: string;
@@ -17,11 +20,24 @@ export interface CreateSecretRequest {
workspace_id?: string;
}
/** Request payload for updating a secret. */
export interface UpdateSecretRequest {
name?: string;
value?: string;
}
/**
* Request body for copy/move operations. `name` is optional with presence
* semantics matching the backend: omitted means "use the source secret's
* name". It must never be emitted as `null` (the backend rejects it).
*/
export interface CopyMoveSecretRequest {
target_scope: SecretScope;
target_workspace_id?: string;
name?: string;
}
/** Response payload for revealing a secret's value. */
export interface RevealSecretResponse {
value: string;
}
+19 -1
View File
@@ -708,5 +708,23 @@
"shortcutReverseChatSearch": "Reverse Chat Search",
"shortcutTaskContentSearch": "Search Task Contents",
"shortcutTogglePlanMode": "Toggle Plan Mode",
"shortcutToggleSidebar": "Toggle Sidebar"
"shortcutToggleSidebar": "Toggle Sidebar",
"copyMove": "Copy/Move",
"copyMoveSecretNamed": "Copy or move {{name}}",
"copyMoveDialogHint": "Copies or moves the secret to another scope. The value is transferred server-side and never shown.",
"copyMoveMode": "Copy or move",
"copySecretAction": "Copy",
"moveSecretAction": "Move",
"copyModeDescription": "Creates a copy in the destination. The original secret stays.",
"moveModeWarning": "The original secret will be removed from {{origin}}.",
"destination": "Destination",
"secretTargetName": "Name",
"secretNameConflictInDestination": "A secret named {{name}} already exists in this destination.",
"destinationsLoading": "Loading destinations",
"destinationsLoadFailed": "Could not load destinations.",
"retryDestinations": "Retry",
"noValidDestinations": "No valid destinations available.",
"transferFailed": "Could not copy or move the secret.",
"destinationGlobal": "Global",
"secretNameTooLong": "Name must be at most 100 bytes."
}
+19 -1
View File
@@ -708,5 +708,23 @@
"shortcutReverseChatSearch": "Ŕēvēŕśē Ćĥàţ Śēàŕćĥ",
"shortcutTaskContentSearch": "Śēàŕćĥ Ţàśķ Ćōńţēńţś",
"shortcutTogglePlanMode": "Ţōĝĝĺē Ƥĺàń Ḿōďē",
"shortcutToggleSidebar": "Ţōĝĝĺē Śĩďēƀàŕ"
"shortcutToggleSidebar": "Ţōĝĝĺē Śĩďēƀàŕ",
"copyMove": "Ćōƥŷ/Ḿōvē",
"copyMoveSecretNamed": "Ćōƥŷ ōŕ ḿōvē {{name}}",
"copyMoveDialogHint": "Ćōƥĩēś ōŕ ḿōvēś ţĥē śēćŕēţ ţō àńōţĥēŕ śćōƥē. Ţĥē vàĺũē ĩś ţŕàńśƒēŕŕēď śēŕvēŕ-śĩďē àńď ńēvēŕ śĥōŵń.",
"copyMoveMode": "Ćōƥŷ ōŕ ḿōvē",
"copySecretAction": "Ćōƥŷ",
"moveSecretAction": "Ḿōvē",
"copyModeDescription": "Ćŕēàţēś à ćōƥŷ ĩń ţĥē ďēśţĩńàţĩōń. Ţĥē ōŕĩĝĩńàĺ śēćŕēţ śţàŷś.",
"moveModeWarning": "Ţĥē ōŕĩĝĩńàĺ śēćŕēţ ŵĩĺĺ ƀē ŕēḿōvēď ƒŕōḿ {{origin}}.",
"destination": "Ďēśţĩńàţĩōń",
"secretTargetName": "Ńàḿē",
"secretNameConflictInDestination": "À śēćŕēţ ńàḿēď {{name}} àĺŕēàďŷ ēxĩśţś ĩń ţĥĩś ďēśţĩńàţĩōń.",
"destinationsLoading": "Ĺōàďĩńĝ ďēśţĩńàţĩōńś",
"destinationsLoadFailed": "Ćōũĺď ńōţ ĺōàď ďēśţĩńàţĩōńś.",
"retryDestinations": "Ŕēţŕŷ",
"noValidDestinations": "Ńō vàĺĩď ďēśţĩńàţĩōńś àvàĩĺàƀĺē.",
"transferFailed": "Ćōũĺď ńōţ ćōƥŷ ōŕ ḿōvē ţĥē śēćŕēţ.",
"destinationGlobal": "Ĝĺōƀàĺ",
"secretNameTooLong": "Ńàḿē ḿŭśţ ƀē àţ ḿōśţ 100 ƀŷţēś."
}
+20 -1
View File
@@ -692,5 +692,24 @@
"shortcutReverseChatSearch": "Pesquisa inversa no chat",
"shortcutTaskContentSearch": "Pesquisar conteúdo da tarefa",
"shortcutTogglePlanMode": "Alternar modo de plano",
"shortcutToggleSidebar": "Alternar barra lateral"
"shortcutToggleSidebar": "Alternar barra lateral",
"copyMove": "Copiar/Mover",
"copyMoveSecretNamed": "Copiar ou mover {{name}}",
"copyMoveDialogHint": "Copia ou move o segredo para outro âmbito. O valor é transferido no servidor e nunca é mostrado.",
"copyMoveMode": "Copiar ou mover",
"copySecretAction": "Copiar",
"moveSecretAction": "Mover",
"copyModeDescription": "Cria uma cópia no destino. O segredo original permanece.",
"moveModeWarning": "O segredo original será removido de {{origin}}.",
"destination": "Destino",
"secretTargetName": "Nome",
"secretNameConflictInDestination": "Já existe um segredo com o nome {{name}} neste destino.",
"destinationsLoading": "A carregar destinos",
"destinationsLoadFailed": "Não foi possível carregar os destinos.",
"retryDestinations": "Repetir",
"noValidDestinations": "Não há destinos válidos disponíveis.",
"transferFailed": "Não foi possível copiar ou mover o segredo.",
"globalSecrets": "Segredos globais",
"destinationGlobal": "Global",
"secretNameTooLong": "O nome não pode exceder 100 bytes."
}
+25 -1
View File
@@ -708,5 +708,29 @@
"shortcutReverseChatSearch": "反向聊天搜索",
"shortcutTaskContentSearch": "搜索任务内容",
"shortcutTogglePlanMode": "切换计划模式",
"shortcutToggleSidebar": "切换侧边栏"
"shortcutToggleSidebar": "切换侧边栏",
"connectionLostDescription": "连接已丢失至少 10 秒,实时更新可能已过期。",
"connectionUnstableDescription": "连接不稳定,正在重新连接 Kandev。",
"home": "主页",
"openSettingsMenu": "打开设置菜单",
"openSettingsMenuWithConnectionIssue": "{{description}} 打开设置菜单",
"statusWithConnectionIssue": "状态。{{description}}",
"copyMove": "复制/移动",
"copyMoveSecretNamed": "复制或移动{{name}}",
"copyMoveDialogHint": "将密钥复制或移动到其他范围。值在服务端传输,绝不会显示。",
"copyMoveMode": "复制或移动",
"copySecretAction": "复制",
"moveSecretAction": "移动",
"copyModeDescription": "在目标位置创建副本。原密钥保持不变。",
"moveModeWarning": "原密钥将从{{origin}}中移除。",
"destination": "目标",
"secretTargetName": "名称",
"secretNameConflictInDestination": "目标位置已存在名为{{name}}的密钥。",
"destinationsLoading": "正在加载目标",
"destinationsLoadFailed": "无法加载目标。",
"retryDestinations": "重试",
"noValidDestinations": "没有可用的有效目标。",
"transferFailed": "无法复制或移动密钥。",
"destinationGlobal": "全局",
"secretNameTooLong": "名称不能超过 100 字节。"
}
+407
View File
@@ -0,0 +1,407 @@
---
spec: docs/specs/workspaces/secret-scope-transfer.md
created: 2026-08-11
status: completed
---
# Implementation Plan: Copy and Move Secrets Between Scopes
## Overview
Add copy/move operations that transfer an encrypted secret between Global and
Workspace scopes (and between workspaces) without exposing the value. The
service authorizes and validates, then delegates to new atomic store
operations (`CopyScoped`/`MoveScoped`) so name-conflict detection and move
deletion share one transaction. The frontend adds a shared Copy/Move dialog to
the existing `SecretsSettings` rows on both the Global and Workspace pages. No
schema changes: scope and `workspace_id` remain immutable.
Design decisions hardened by adversarial review rounds 1-2: conflict checks
and moves are transactional and dialect-serialized (no TOCTOU race, no
compensation window, exactly one winner under concurrency), only the known
missing/unauthorized sentinels resolve to `404` while raw internal failures
stay sanitized `500`s, the name limit is defined as UTF-8 bytes, destination
workspace existence is verified even in auth-disabled mode and fails closed
when unconfigured, copied rows keep the caller's ownership, legacy empty-scope
Global rows still conflict, the Global store always receives Global-target
results, the default target-name suffix uses locale-independent origin tokens,
and the destination payload is cleared when switching to General.
## Backend
### Service layer (`apps/backend/internal/secrets`)
- Add `CopySecretRequest` (request DTO with `target_scope`,
`target_workspace_id`, optional `name`) and the `ErrSecretNameConflict`
sentinel next to `ErrNotFound` in `store.go` or `models.go`.
- Add `Service.Copy(ctx, sourceID, sourceWorkspaceID, req)` and
`Service.Move(...)`:
1. Resolve the source: `sourceWorkspaceID == ""` → `Get` (Global only);
non-empty → `GetWorkspaceSecret` (authorized Workspace only). Store-level
missing rows surface as `ErrNotFound`; other errors pass through
unclassified (handlers turn only known sentinels into `404`).
2. Normalize the target name with presence semantics: `req.Name` is a
`*string`; JSON-omitted means "use the source name", explicit `null`,
present-but-empty, or whitespace-only is a validation error, and a
present name enforces the existing 1-100 UTF-8 byte rule. Because Go's
standard decoding maps omitted and `null` to the same nil pointer, the
request type implements a custom `UnmarshalJSON` that records `name`
presence, so the service can tell them apart.
3. Validate the target with `validateSecretScope` and reject a destination
equal to the source scope+workspace. Every validation failure is wrapped
with the `ErrSecretValidation` sentinel so handlers classify with
`errors.Is`, never by message text.
4. Authorize the destination: `authorizeScope` for authenticated callers
plus a workspace-existence callback that runs unconditionally (including
auth-disabled contexts). Missing/unauthorized destinations surface as the
secrets sentinel `ErrWorkspaceAccessDenied`; raw lookup/storage errors
inside the callbacks pass through unclassified so they stay `500`.
Destination verification is passed into the store operation as an in-tx
callback and runs while the transfer transaction holds the destination's
advisory lock (see store layer), so it is inside the lock boundary.
5. Call `store.CopyScoped`/`store.MoveScoped` (with the verification
callback) and wrap the result. Do not reveal or re-encrypt plaintext in
the service.
- Add the sentinels `ErrWorkspaceAccessDenied` and `ErrSecretValidation` next
to `ErrNotFound` and `ErrSecretNameConflict`. Classification uses
`errors.Is` exclusively; no handler matches error text.
- Add `SetWorkspaceExistenceChecker(func(context.Context, string) error)`.
A nil checker fails closed: any workspace destination resolves as
`ErrWorkspaceAccessDenied` (never a silent pass-through for phantom
workspaces).
- Classification happens at the wiring boundary (`backendapp/main.go`), which
can import both packages: adapters wrap the task service's
`AuthorizeWorkspaceAccess` and workspace-existence lookup so that
`errors.Is(err, repoerrors.ErrWorkspaceNotFound)` becomes
`secrets.ErrWorkspaceAccessDenied`, while any other error (e.g. a database
failure) is returned unchanged for the `500` classifier. The secrets service
never imports `repoerrors`.
- Do not touch shared methods (`Get`, `authorizeScope`, CRUD); wrap only at
the Copy/Move boundary.
- Tests in a new `copy_move_test.go` using `newTestSQLiteStore` wrapped in
`NewUserVisibleStore` (so the internal-ID boundary is real): copy
global→workspace, workspace→global, workspace A→workspace B; move both
directions; omitted-name default; name validation (empty, whitespace, >100
bytes with multibyte input); same-scope rejection; name conflict (Global and
workspace targets); unauthorized/missing source; unauthorized destination;
nonexistent destination with authorizer disabled (existence checker denies);
internal `github:` source ID seeded as a real row → not-found; list
consistency after each operation; values verifiable only through reveal.
### Store layer (`apps/backend/internal/secrets`)
- Extend `ScopedSecretStore` with callback-bearing transfer methods:
- `CopyScoped(ctx, sourceID, targetScope, targetWorkspaceID, targetName, verifyDestination func(context.Context) error) (*Secret, error)`
- `MoveScoped(ctx, sourceID, targetScope, targetWorkspaceID, targetName, verifyDestination func(context.Context) error) (*Secret, error)`
`verifyDestination` runs inside the transaction while the destination lock
is held, before the conflict check and insert; `UserVisibleStore` passes it
through; an error rolls back and surfaces for the service's 404 mapping.
- `sqliteStore` (serves SQLite AND PostgreSQL through `Provide`): one
transaction per operation, atomic on both dialects:
- `CopyScoped`: BEGIN with a defined lock contract; select the source row
with the existing per-user visibility predicate; verify no row with the
target `(name, normalized scope, workspace_id)` visible to the caller,
where an empty stored scope normalizes to Global (else ROLLBACK +
`ErrSecretNameConflict`); INSERT the copy with a new ID, the source's
encrypted value/nonce, the target scope/workspace, AND
`user_id = scopeOwner(ctx)` (never an unowned row); COMMIT.
- Lock contract (dialect-gated, defined in the store): SQLite starts the
transaction with `BEGIN IMMEDIATE` (writer lock up front); PostgreSQL
executes `BEGIN`, then `SELECT pg_advisory_xact_lock(<target scope key>)`
on that same transaction BEFORE the source select and conflict check,
serializing competing writers under READ COMMITTED. The PostgreSQL
statement never runs on SQLite. One authoritative lock scheme: exported
`WorkspaceLockKey(workspaceID string) int64` (deterministic FNV-1a 64-bit
of the `kandev-secret-transfer:` prefix + workspace ID; stable across
restarts; collision-safe for UUIDs — a collision only over-serializes)
plus a distinct stable `GlobalSecretTransferLockKey` for Global targets.
A Move additionally locks the source workspace key; multi-key acquisitions
happen in sorted key order.
- Shared deletion boundary: a workspace-scoped secret can never outlive its
workspace. Locks are workspace-keyed, not global: the secrets package
exports a deterministic `WorkspaceLockKey(workspaceID)` (pure function,
no new package cycle — the task service already consumes secrets
interfaces) used by both sides on PostgreSQL. The transfer transaction
acquires the destination workspace's key (plus the source workspace's key
for Move, in sorted order) and, while holding it, runs the destination
existence/authorization verification via an in-tx callback (wired to the
service's existence checker) before the conflict check and insert.
`DeleteWorkspaceSecretsTx` acquires the same key at its start and holds it
to commit, so a transfer that inserts before a deletion commits is cleaned
up by that deletion, and a transfer after the deletion commits observes
the workspace gone. SQLite's single writer serializes transfer and
cleanup; the residual cross-database window matches the existing create
path. A deterministic PostgreSQL race test (delete vs transfer on
separate connections, channel-scheduled) asserts no secret remains
attached to the deleted workspace.
- Transaction boundary: every statement in the operation — the source
select, the conflict check, the insert, the Move source delete, and the
returned-row read — executes on the transaction-bound executor (a pinned
writer connection), never on the store's reader handle (`s.ro`) or a
second connection. Lock-acquisition failure rolls back and surfaces as a
store error (sanitized `500` upstream).
- Return contract: both methods return the inserted row's metadata (ID,
name, scope, workspace, `created_at`, `updated_at`) via `RETURNING` where
portable or a same-transaction select; a zero-value struct is not a valid
result.
- `MoveScoped`: same plus DELETE the source row using the same visibility
predicate as the source select, before COMMIT. Missing source →
`ErrNotFound`; any failure rolls back (source intact, no copy).
- `UserVisibleStore`: delegate both, and reject internal (`github:` prefix)
source IDs up front.
- Every compile-time `ScopedSecretStore` implementer gains the two methods:
`sqliteStore`, `UserVisibleStore`, and the lifecycle test double
`inMemorySecretStore` (`internal/agent/runtime/lifecycle/manager_auth_test.go`).
- No schema change; no uniqueness constraint (existing create behavior allows
duplicate names; the serialized transaction provides transfer atomicity).
- Tests (`transfer_test.go`, SQLite by default): copy keeps source, move
removes source, conflict rolls back to no-op, copied row is owned
(`user_id = scopeOwner(ctx)`) with user A/user B ownership boundaries,
legacy empty-scope target conflicts with Global, per-user scoping,
UserVisibleStore internal-ID rejection, and a deterministic
concurrent-same-target-name test using a one-way schedule (transfer A
signals "lock acquired"; the test asserts B is still blocked on the lock;
A completes; B proceeds and receives `ErrSecretNameConflict`) — the schedule
never requires both transfers to hold the lock at once.
- Environment-gated PostgreSQL tests (existing `PostgresDSNFromEnv` pattern):
copy, Move rollback, scoped conflict detection, copied-row ownership,
legacy empty-scope conflict, and the concurrent same-name race under READ
COMMITTED with the advisory lock.
### HTTP + WebSocket handlers (`handlers.go`, `apps/backend/pkg/websocket/actions.go`)
- Add `ActionSecretCopy = "secrets.copy"` and `ActionSecretMove =
"secrets.move"` to `actions.go` next to the existing secret actions.
- Add `POST /api/v1/secrets/:id/copy` and `POST /api/v1/secrets/:id/move`
routes using the existing `?workspace_id=` source-scoping dispatch. Success:
`201 Created` with the new `SecretListItem`.
- Error mapping (HTTP and WS), classified exclusively via `errors.Is` against
the package sentinels — never by matching error text:
- `errors.Is(err, secrets.ErrSecretValidation)` (payload, scope/workspace
combination, same-scope, invalid/empty name) → `400` /
`ErrorCodeBadRequest`;
- `errors.Is(err, secrets.ErrNotFound)` (missing source, missing secret) or
`errors.Is(err, secrets.ErrWorkspaceAccessDenied)` (missing/unauthorized
destination, unconfigured existence checker) → `404` /
`ErrorCodeNotFound`;
- `errors.Is(err, secrets.ErrSecretNameConflict)` → `409` /
`ErrorCodeConflict`;
- everything else → `500` / `ErrorCodeInternalError` with a sanitized
message; details logged server-side.
- Handler tests with gin/httptest (conventions from
`internal/agent/settings/handlers/agent_update_handlers_test.go`): success
(201), conflict (409), validation (400), missing source (404), **unauthorized
source (404)**, **unauthorized destination (404)**, **nonexistent
destination with the existence checker denying (404)**, **unconfigured
(nil) existence checker denying (404)**, and injected internal failures from
the source lookup, the authorizer, and the existence checker (each `500`,
sanitized body, no raw error text), plus matching WS error-code mapping for
every case.
## Frontend
### API and types
- `apps/web/lib/types/http-secrets.ts`: add `CopyMoveSecretRequest`
(`target_scope`, `target_workspace_id`, optional `name`).
- `apps/web/lib/api/domains/secrets-api.ts`: add `copySecret(id, payload,
options?)` and `moveSecret(id, payload, options?)` POST helpers reusing
`withSecretQuery` for the source `workspace_id` (options include
`workspaceId` for the source scope). Surface the HTTP status so the dialog
can distinguish `409` (name field) from other errors.
- Add API tests in `secrets-api.test.ts` matching the existing fetch mocking
convention.
### Dialog and row wiring
- Extract sections from the 640-line `secrets-settings.tsx` (the frontend
limit is 600 lines) before adding wiring: move `SecretListItemRow`,
`SecretForm`, and the delete dialog into focused components. Keep
`secrets-settings.tsx` under the limit.
- New `apps/web/components/settings/copy-move-secret-dialog.tsx`:
- Props: `secret`, `originToken` (`general` for Global sources, the raw
workspace name for Workspace sources), `onClose`,
`onCompleted(item, mode)`.
- The dialog's primary submit label reflects the selected mode: distinct
localized keys (`copySecret` / `moveSecret`) or one interpolated mode
label, switching when the radio changes (never a static "Copy" button in
Move mode). The Move warning accompanies the Move label.
- Copy/Move radio (default Copy), destination `Select` (General + workspaces
from `useAppStore((s) => s.workspaces.items)`; exclude the source's own
scope; exclude General when the source is Global), editable name `Input`
pre-filled via the translated pattern `{{name}} (from {{origin}})` with the
literal origin token.
- Workspace hydration failure is handled explicitly: the destination hook
exposes loading/error state, the dialog shows a localized retry/failure
state instead of an empty picker (which would leave a Global source with
zero valid destinations), and the picker is never presented as a valid
transfer form when the workspace list failed to load.
- Mobile presentation is an implementation requirement, not just a spec
goal: the dialog uses a responsive presentation (a Drawer/sheet at phone
width or explicit `DialogContent` overrides) with safe-area padding, 44px
touch targets for the radios, destination picker, name input, actions,
and the close affordance, and focus restoration on close. The scroll
invariant is a single owner: the Settings content area
(`settings-scroll-container`) remains the only vertical scroller, and the
dialog is constrained to fit without nested vertical scrolling
(content-sized, with the picker list scrolling only when it cannot fit).
The shared `Dialog`/`Select` defaults are desktop-oriented and must be
overridden, not inherited.
- The request payload is modeled as a discriminated union with a payload
builder: `name?: string` (undefined = omitted, no nullable branch),
`target_workspace_id` cleared when the destination is General (never
submits `global` with a stale workspace ID, which the backend rejects),
and `name: null` never emitted. An API test asserts the serialized bodies
for a string name and an omitted name contain no `"name": null`.
- Default-name truncation: trim so the UTF-8 byte length is at most 100
(code-point aware), never relying on `String.prototype.length` semantics.
- Move mode shows an inline warning that the original is removed from the
source scope.
- Best-effort conflict pre-check: a small hook loads the destination scope's
names and marks the name field `aria-invalid` with an inline error on a
trimmed match; submit is disabled. Backend `409` also surfaces on the name
field; other backend errors show a generic message.
- Submit calls `copySecret`/`moveSecret`; on success calls `onCompleted`.
- New `apps/web/hooks/domains/settings/use-secret-destination-names.ts`
(testable hook): given a target scope+workspace, loads existing secret names
(`useSecrets("global")` for Global; `listSecrets({scope:"workspace",
workspaceId})` fetched on demand for Workspace, cached per workspace) and
returns `{ names, loaded, conflict(name) }`.
- Workspace-list state with a real retry path and a single source of truth:
the destination picker reads the workspace store only. A dedicated hook
exposes `{ loading, error, retry }`: when the store's workspace list is
empty or hydration failed, it fetches `listWorkspaces` on demand and writes
successful results into the store via `setWorkspaces` (with
request-generation/abort protection so a stale response never overwrites a
newer hydration). `retry` re-runs that fetch; failures are preserved as
`error`, never converted into `items: []`. A later hydration/store update
simply supersedes the fallback result. This covers the Workspace page too
(current workspace known, other-workspace list failed), and hydration
arriving mid-fallback is tested.
- `apps/web/components/settings/secrets-settings.tsx`:
- Add a Copy/Move button to the (extracted) row component with an accessible
label and touch-sized target; track the dialog target in state.
- `onCompleted` routes **by the returned item's scope, never the page scope**:
- target Global → `useAppStore` `addSecret` directly, from any page;
- target Workspace → the page's scoped `addSecret` only when the page is
that workspace's page;
- `mode === "move"` → remove the source via the page's own scoped
`removeSecret`.
- i18n: new keys in `apps/web/src/locales/en/settings.json` (Copy/Move label,
dialog title, Copy/Move radio labels, destination label, General option,
name label, conflict error, move warning, submit labels, origin suffix
pattern, destination-list loading state, workspace-list failure state, retry
action, submit-disabled hint), mirrored in pseudo, pt-pt, and zh-cn. No em
dashes; `t()` at render time only; origin tokens are values, never catalog
keys.
- Component tests: dialog rendering, destination filtering (source Global vs
Workspace), default-name construction with literal origin tokens, byte-aware
truncation (ASCII and multibyte), conflict pre-check blocking, move warning,
submit payloads, destination switching Workspace → General asserting the
request carries no workspace target, `409` surfacing on the name field, and
`onCompleted` routing (workspace page → Global target adds to the store).
Hook tests for destination-name loading and `conflict(name)`.
## E2E and documentation
- Desktop Chromium spec `apps/web/e2e/tests/settings/secrets-copy-move.spec.ts`
(conventions from `repository-secrets.spec.ts`): create a Global secret,
copy it to a workspace with the default suffixed name, verify both lists;
move a workspace secret to General and verify the source is gone; attempt a
conflicting target name and verify the blocked state. Add negative plaintext
assertions after each flow (`expect(page.locator("body")).not.toContainText(
<known value>)`), mirroring `repository-secrets.spec.ts`, so a value leak
fails the suite.
- Mobile coverage in the `mobile-chrome` project (extend
`mobile-repository-secrets.spec.ts` or add a sibling spec): open the dialog
at phone width, exercise the destination picker (including switching
Workspace → General), complete one copy and one move, and assert the mobile
design contract: ≥44px touch targets (mirroring the existing mobile spec's
bounding-box assertions), no horizontal overflow, single scroll owner, and
focus return on close.
- Make the desktop describe/title contain the literal `secrets-copy-move`
fragment so the `--grep` verification command actually selects the tests;
document the direct spec-path run as an alternative.
- Docs: add a short copy/move paragraph to the secret-scope section of
`docs/public/agents-and-profiles.md` (after the Workspace secrets paragraph);
add the new spec row to `docs/specs/INDEX.md` under `workspaces/`.
- i18n checks: `pnpm run i18n:check` and `pnpm run i18n:ratchet` pass.
## Implementation waves
Wave 1:
- [x] [Task 01: Backend copy/move service and store](task-01-backend-copy-move-service.md)
Wave 2:
- [x] [Task 02: Backend copy/move handlers](task-02-backend-copy-move-handlers.md)
(depends on Task 01)
Wave 3:
- [x] [Task 03: Frontend copy/move dialog and API](task-03-frontend-copy-move-dialog.md)
(depends on Tasks 01 and 02)
Wave 4:
- [x] [Task 04: E2E and documentation](task-04-e2e-and-docs.md)
(depends on Task 03)
The primary conversation executes these tasks sequentially unless the user
explicitly authorizes native implementation subagents.
## Risks
- The Global store slice must never receive workspace-scoped items, and every
Global-target result must reach the store even from a Workspace page: the
completion handler routes by the returned item's scope, not the page scope.
- Name-conflict checks are best-effort client-side; the transactional
`CopyScoped`/`MoveScoped` check is the contract and must remain
authoritative.
- The name limit is UTF-8 bytes on both sides: Go `len()` counts bytes, so the
dialog's truncation must be byte-aware, not `String.prototype.length`.
- Workspace existence must be enforced even when the authorizer is a no-op
(auth-disabled); the existence checker is a separate callback.
- `ScopedSecretStore` gains two methods; the compile-time implementers are
`sqliteStore`, `UserVisibleStore`, and the lifecycle test double
`inMemorySecretStore` (all three must be updated or the build breaks).
- The in-transaction conflict check is only atomic on both dialects with the
explicit serialization (SQLite `BEGIN IMMEDIATE`, PostgreSQL advisory
transaction lock); without it PostgreSQL READ COMMITTED allows duplicate
inserts under concurrency.
- The copied row must be written with `user_id = scopeOwner(ctx)` and the
source delete must reuse the visibility predicate; missing either turns a
user-scoped transfer into an ownership or cross-user leak.
- Handler error mapping must keep only the known sentinels
(`ErrNotFound`, `ErrWorkspaceAccessDenied`) at `404` and never expose
internal error text; unknown errors, including database failures inside the
authorizer/existence callbacks, stay sanitized `500`. Validation
classification uses `ErrSecretValidation` via `errors.Is`; a raw internal
error whose text resembles a validation message must still be `500`.
- The existence checker must fail closed when nil; an unconfigured service
must not accept phantom workspace destinations.
- The PostgreSQL advisory lock must be taken on the same transaction before
the conflict read with a stable named key, or the READ COMMITTED race
returns; the SQLite `BEGIN IMMEDIATE` path must never execute the PostgreSQL
statement.
- i18n ratchet: any touched line in `secrets-settings.tsx`/new files must use
`t()`; new keys must exist in all four locales; origin tokens are values.
- `secrets-settings.tsx` must stay under the 600-line lint limit; extraction
happens before new wiring.
## Completion verification
- Backend: `cd apps/backend && go test ./internal/secrets/... ./pkg/websocket/...`;
then `make -C apps/backend lint` and `make -C apps/backend build`.
- Frontend: `cd apps && pnpm --filter @kandev/web test -- --run`, plus
`cd apps/web && pnpm run typecheck`, `cd apps && pnpm --filter @kandev/web
lint`, and `cd apps/web && pnpm run i18n:check && pnpm run i18n:ratchet`.
- E2E: run the managed build-and-run form `pnpm e2e:run` for the new specs
(desktop `--grep="secrets-copy-move"` since the describe/title contains the
fragment, plus the mobile-chrome grep for the mobile flow), or explicitly
rebuild the backend binary and `apps/web` production bundle before
`pnpm e2e:raw` — `e2e:raw` launches the existing `apps/backend/bin/kandev`
and serves the existing `apps/web/dist`, which can be stale otherwise.
- Docs: public-doc markdown lint (if gated in CI) and `docs/specs/INDEX.md`
row present.
@@ -0,0 +1,189 @@
---
id: "01-backend-copy-move-service"
title: "Backend copy/move service and store"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/workspaces/secret-scope-transfer.md"
---
# Task 01: Backend Copy/Move Service and Store
## Acceptance
- `Service.Copy(ctx, sourceID, sourceWorkspaceID, req)` and
`Service.Move(ctx, sourceID, sourceWorkspaceID, req)` exist with the spec's
semantics: source resolution (Global via `Get`, workspace via
`GetWorkspaceSecret`), target validation + destination authorization, a
workspace-existence check that runs even in auth-disabled contexts, same
scope+workspace rejection, and the 1-100 UTF-8 byte name rule.
- Error classification is exact and non-contradictory: store-level missing
rows surface as `ErrNotFound` and missing/unauthorized destinations as
`ErrWorkspaceAccessDenied` (both `404`); validation failures are wrapped with
the `ErrSecretValidation` sentinel (`400`); every other error (raw database,
storage, or callback lookup failure) passes through unclassified and is a
sanitized `500`. No "any error" blanket wrapping exists anywhere.
- `name` uses presence semantics (`*string`): JSON-omitted means "use the
source name"; present-but-empty or whitespace-only is a validation error.
- `ScopedSecretStore` gains atomic, callback-bearing `CopyScoped`/`MoveScoped`
(`verifyDestination func(context.Context) error` invoked inside the
transaction while the destination lock is held, before the conflict check
and insert) implemented by `sqliteStore` in one transaction (conflict check
+ insert, plus source delete for Move, with rollback on any failure) and
delegated by `UserVisibleStore` with an internal-ID (`github:` prefix)
source guard. `ErrSecretNameConflict` is returned when the target name
exists; a missing source returns `ErrNotFound`.
- The transfer transaction is atomic on both dialects with a single
authoritative lock contract: SQLite starts with `BEGIN IMMEDIATE` (writer
lock up front); PostgreSQL executes `BEGIN`, then
`SELECT pg_advisory_xact_lock(<target scope key>)` on the same transaction
BEFORE the source select and conflict check, and the PostgreSQL statement
never runs on SQLite (dialect-gated). The lock key comes from the exported
`WorkspaceLockKey(workspaceID)` (deterministic FNV-1a 64-bit of the
`kandev-secret-transfer:` prefix + workspace ID) or the distinct
`GlobalSecretTransferLockKey` constant for Global targets; a Move also
locks the source workspace key, in sorted key order. Concurrent
same-target-name writers serialize and exactly one wins under READ
COMMITTED.
- Every statement in the operation (source select, conflict check, insert,
Move delete, returned-row read) executes on the transaction-bound writer
connection; the store's reader handle is never used inside the transaction.
Lock-acquisition failure rolls back and surfaces as a store error (sanitized
`500` upstream).
- Both methods return the inserted row's metadata (ID, name, scope, workspace,
`created_at`, `updated_at`) via `RETURNING` where portable or a
same-transaction select; tests assert non-zero timestamps matching the
inserted target row AND exact target identity: returned `Scope` equals the
requested target scope, `WorkspaceID` equals the requested target workspace
(empty for Global targets), and the returned `Name` equals the target name.
- The copied row is created with `user_id = scopeOwner(ctx)`; the Move source
delete reuses the same per-user visibility predicate as the source select.
- The conflict predicate compares the normalized scope (legacy empty stored
scope is Global), so a legacy Global row cannot be bypassed.
- Move has no compensation window: copy and delete share a transaction; a
crash or failure rolls back, leaving the source intact.
- The service exposes `ErrWorkspaceAccessDenied` and
`SetWorkspaceExistenceChecker`; a nil existence checker fails closed for
workspace destinations. Only known missing/unauthorized sentinels resolve as
not-found; raw lookup/storage errors pass through unclassified.
- Tests cover: copy/move in all scope directions, name presence semantics
(omitted → source name; explicit JSON `null`, present-but-empty, and
whitespace-only → validation error; >100 UTF-8 bytes with multibyte input →
validation error),
same-scope rejection, name conflict (Global and workspace targets), legacy
empty-scope Global target conflict, missing source, unauthorized source,
unauthorized destination, nonexistent destination with the authorizer
disabled (existence checker denies), unconfigured (nil) existence checker,
internal `github:` source ID seeded as a real row → not-found (via
`NewUserVisibleStore`), user A/user B ownership boundaries (copied row owned;
A cannot move B's row), a deterministic concurrent same-target-name race on
SQLite using a one-way schedule (A signals "lock acquired"; assert B is
still blocked on the lock; A completes; B receives
`ErrSecretNameConflict`; the schedule never requires both transfers to hold
the lock at once), lock-acquisition failure rolling back to no-op, a Move
failpoint injected AFTER the target insert and BEFORE the source delete
asserting the transaction rolls back (source intact, no destination row —
proving Move is not copy-then-commit-delete), a `verifyDestination`
callback error rolling back with no insert, injected raw storage/authorizer
errors that pass through unclassified (not `ErrNotFound`, not
`ErrSecretValidation`), and list consistency with values verifiable only
through reveal.
- Environment-gated PostgreSQL tests (`PostgresDSNFromEnv`) cover the same
transfer semantics under READ COMMITTED: copy, Move rollback, scoped
conflict, copied-row ownership, legacy empty-scope conflict, the
concurrent race with the advisory lock (including a same-name race with a
Global target on `GlobalSecretTransferLockKey`), and a deterministic
delete-vs-transfer race proving no workspace-scoped secret survives its
workspace's deletion. The PG race tests run on a multi-connection fixture
(pool `maxConns >= 2` or two explicitly opened connections — a
one-connection pool trivially serializes and proves nothing) with channel
barriers pinning the interleavings: transfer locked before deletion
cleanup, and deletion committed before the transfer's existence check.
## Files likely touched
- `apps/backend/internal/secrets/store.go` (or `models.go`):
`ErrSecretNameConflict`, `ErrWorkspaceAccessDenied`, `ErrSecretValidation`,
`CopyScoped`/`MoveScoped` on `ScopedSecretStore`
- `apps/backend/internal/secrets/models.go`: `CopySecretRequest`
- `apps/backend/internal/secrets/service.go`: `Copy`, `Move`,
`SetWorkspaceExistenceChecker`, private helpers
- `apps/backend/internal/secrets/sqlite_store.go`: `CopyScoped`/`MoveScoped`
transactions (BEGIN IMMEDIATE on SQLite, advisory xact lock on PostgreSQL)
- `apps/backend/internal/secrets/user_visible_store.go`: delegation +
internal-ID guard
- `apps/backend/internal/agent/runtime/lifecycle/manager_auth_test.go`:
`inMemorySecretStore` gains the two methods (compile-time interface member)
- `apps/backend/internal/backendapp/main.go`: wire the existence checker and
the authorizer/existence adapters that map
`repoerrors.ErrWorkspaceNotFound` → `secrets.ErrWorkspaceAccessDenied`
- New `copy_move_test.go`, `transfer_test.go`, and
`postgres_transfer_test.go`
## Inputs
- Spec: API surface (Go service + store section), Permissions, Failure modes,
Scenarios.
- Existing `Service` primitives: `Get`, `GetWorkspaceSecret`, `authorizeScope`,
`validateSecretScope`; existing store scoping filters (`scopeOwner`).
- Task service workspace APIs for the existence checker
(`apps/backend/internal/task/service/`).
## Dependencies
None.
## TDD sequence
1. Write failing store tests (`transfer_test.go`) for `CopyScoped`/`MoveScoped`
atomicity, ownership, legacy empty-scope conflicts, user scoping, and the
concurrent same-target-name race using the one-way schedule (A signals
"lock acquired"; assert B is still blocked on the lock; A completes; B
receives `ErrSecretNameConflict`); add the environment-gated
`postgres_transfer_test.go` equivalents. The SQLite race test observes lock
acquisition explicitly: a test-only lock-acquisition hook on the store, or
a two-writer helper opening separate connections to the same database file
with explicit synchronization, so B's block is proven to be at the SQLite
transaction lock and not merely at the single-connection Go pool (the
existing `newTestSQLiteStore` helper pins `SetMaxOpenConns(1)` and cannot
distinguish the two).
2. Implement the store methods, dialect serialization, and `UserVisibleStore`
delegation; add the two methods to `inMemorySecretStore`.
3. Write failing service tests (`copy_move_test.go` with
`NewUserVisibleStore(newTestSQLiteStore(t))` and the workspace-authorizer
pattern from `service_test.go`), including nil-checker and internal-error
pass-through cases.
4. Implement `CopySecretRequest`, `ErrSecretNameConflict`,
`ErrWorkspaceAccessDenied`, `Service.Copy`/`Service.Move`, the existence
checker, and the main.go adapters.
5. Re-run until green; keep existing secrets and lifecycle tests green.
## Verification
```bash
cd apps/backend && go test ./internal/secrets/... -run 'TestCopy|TestMove|TestTransfer' -count=1
cd apps/backend && go test ./internal/secrets/... ./internal/agent/runtime/lifecycle/...
```
(PostgreSQL-gated transfer tests run only when `PostgresDSNFromEnv` resolves,
matching the existing postgres test conventions.)
## Risks
- The service must not call the raw store directly for transfer; authorization
and the internal-ID boundary only hold through the wrapper.
- Name default and byte-length rule must match create validation exactly.
- The transactional conflict check must use the same user-scoping filter as
the rest of the store, and the serialization (BEGIN IMMEDIATE / advisory
lock) is required for the atomicity guarantee on each dialect.
- The copied row must carry `user_id = scopeOwner(ctx)`; an unowned copy is a
cross-user visibility leak in authenticated mode.
- Do not wrap raw lookup/storage errors as not-found; only the known sentinels
(`ErrNotFound`, `ErrWorkspaceAccessDenied`) classify as 404.
- Keep values out of errors and logs (spec redaction rule).
## Output contract
Report the new symbols, transaction shape, existence-checker wiring, test
names, and both `go test` results.
@@ -0,0 +1,119 @@
---
id: "02-backend-copy-move-handlers"
title: "Backend copy/move HTTP + WS handlers"
status: done
wave: 2
depends_on: ["01-backend-copy-move-service"]
plan: "plan.md"
spec: "../../specs/workspaces/secret-scope-transfer.md"
---
# Task 02: Backend Copy/Move Handlers
## Acceptance
- `POST /api/v1/secrets/:id/copy` and `POST /api/v1/secrets/:id/move` exist
with the spec's request body (`target_scope`, `target_workspace_id`, optional
`name`) and the existing `?workspace_id=` source-scoping pattern. Success:
`201 Created` + new `SecretListItem`.
- Error mapping is exact, for both HTTP and WS, classified exclusively with
`errors.Is` against package sentinels (never by matching error text):
- `errors.Is(err, secrets.ErrSecretValidation)` (payload, scope/workspace
combination, same-scope, invalid or explicitly-empty name) → `400` /
`ErrorCodeBadRequest`;
- `errors.Is(err, secrets.ErrNotFound)` (missing source, missing secret) or
`errors.Is(err, secrets.ErrWorkspaceAccessDenied)` (missing/unauthorized
destination, unconfigured existence checker) → `404` /
`ErrorCodeNotFound`;
- `errors.Is(err, secrets.ErrSecretNameConflict)` → `409` /
`ErrorCodeConflict`;
- any other failure → `500` / `ErrorCodeInternalError` with a sanitized
message (details logged server-side, never in the response). Raw
database/storage errors inside the source lookup, the authorizer, or the
existence checker must stay in this bucket, not become `404`.
- WS actions `secrets.copy` and `secrets.move` are registered with payload
`{id, workspace_id, target_scope, target_workspace_id, name}` (`name` with
the same presence semantics as HTTP). The WS envelope decoder must delegate
the transfer fields to the same presence-aware `CopySecretRequest` decoder
used by HTTP (a flat anonymous struct with `json.Unmarshal` would silently
collapse `name: null` into omitted); it resets the presence marker and all
fields before every decode. Success responses return the new
`SecretListItem` as the WS payload, mirroring the existing
`secrets.create` convention (`ws.NewResponse(..., item)`); response-shape
tests assert the same fields as the HTTP response, including exact target
identity: `Scope` equals `target_scope`, `WorkspaceID` equals
`target_workspace_id` (empty for Global), and `Name` equals the target
name.
- Handler tests (gin/httptest) cover: success (201), conflict (409),
validation (400), missing source (404), unauthorized source (404),
unauthorized destination (404), nonexistent destination with the existence
checker denying (404), unconfigured (nil) existence checker (404), and
injected internal failures from the source lookup, the authorizer, and the
existence checker (each `500` with a sanitized body and no raw error text),
including an injected internal error whose message contains validation-like
text that must still be `500`, plus the matching WS error codes for every
case. HTTP and WS tests cover all four `name` JSON cases: omitted (uses the
source name), `null` (`400`/`BAD_REQUEST`), empty string (`400`), and
whitespace-only (`400`). WS tests additionally cover the source-scope rule:
omitted/empty `workspace_id` selects a Global source (success path) and a
Workspace source without `workspace_id` resolves to `NOT_FOUND`, matching
the HTTP `?workspace_id=` semantics. A reused-request WS test reuses one
envelope across two messages: the first targets workspace A with a non-empty
source workspace and `name: null` (asserting `BAD_REQUEST`), the second
targets General while omitting both workspace IDs and the name, asserting
the second dispatch uses empty target/source workspace IDs, Global scope,
the second source ID, and the default source name (full field + presence
reset between decodes, not just the name marker).
## Files likely touched
- `apps/backend/internal/secrets/handlers.go`
- `apps/backend/pkg/websocket/actions.go`
- `apps/backend/internal/secrets/handlers_test.go` (new; follow
`internal/agent/settings/handlers/agent_update_handlers_test.go` gin
conventions, or `sqlite_store_test.go` fixtures for the store)
## Inputs
- Task 01's `Service.Copy`/`Move`, `ErrSecretNameConflict`, and
`ErrNotFound`-wrapping contract.
- Existing handler patterns: `httpCreateSecret`, `deleteSecretForWorkspace`
(query-param dispatch), `wsCreate`/`wsDelete` (payload parse + error codes).
## Dependencies
Task 01.
## TDD sequence
1. Write failing handler tests for the full status/error-code matrix above,
including an authorizer that denies source and destination independently,
an existence checker that denies a phantom workspace, a nil existence
checker, and injected internal errors (raw non-sentinel errors) from each
callback and the store.
2. Add `ActionSecretCopy`/`ActionSecretMove` constants, HTTP routes, WS
handlers, and the classification helper (validation / not-found /
workspace-denied / conflict / internal).
3. Run the secrets and websocket package tests until green.
## Verification
```bash
cd apps/backend && go test ./internal/secrets/... ./pkg/websocket/...
```
## Risks
- The source `workspace_id` query parameter must dispatch to the workspace
source resolution only when present, matching the existing CRUD dispatch.
- Never map internal failures to `400` or `404`: only the known sentinels
(`ErrNotFound`, `ErrWorkspaceAccessDenied`) are not-found; raw database or
storage errors stay sanitized `500`.
- WS error-code mapping must use the existing `ws.ErrorCode*` constants.
- Unauthorized and missing must be indistinguishable in responses (both `404`),
and `500` responses must never echo the underlying error string.
## Output contract
Report the routes/actions added, the classification helper, test names, and
verification output.
@@ -0,0 +1,166 @@
---
id: "03-frontend-copy-move-dialog"
title: "Frontend copy/move dialog and API"
status: done
wave: 3
depends_on: ["01-backend-copy-move-service", "02-backend-copy-move-handlers"]
plan: "plan.md"
spec: "../../specs/workspaces/secret-scope-transfer.md"
---
# Task 03: Frontend Copy/Move Dialog and API
## Acceptance
- `copySecret`/`moveSecret` API helpers and `CopyMoveSecretRequest` type exist
and are covered by API tests; the API layer surfaces the HTTP status so the
dialog can tell `409` (name field) from other errors.
- `secrets-settings.tsx` is reduced below the 600-line lint limit by extracting
`SecretListItemRow`, `SecretForm`, and the delete dialog into focused
components BEFORE the new wiring is added.
- Every secret row on the Global and Workspace secrets pages has a Copy/Move
button opening one shared dialog with: Copy/Move radio (default Copy),
destination picker (General + workspaces, excluding the source's own scope,
and excluding General for a Global source), and an editable name field
pre-filled with the translated pattern `<name> (from <origin>)` where the
origin value is the literal `general` for Global sources and the raw
workspace name for Workspace sources (locale-independent persisted names).
- The dialog handles workspace-list hydration failure explicitly with a real
retry path and a single source of truth: the picker reads the workspace
store only, and a dedicated hook exposes `{ loading, error, retry }`
(no local workspace list in its result). When the store's workspace list is
empty or hydration failed, the hook fetches `listWorkspaces` itself and
writes successful results into the store via `setWorkspaces` (with
request-generation/abort protection so a stale response never overwrites a
newer hydration). Failures are preserved as `error`, never converted to
`items: []`. The dialog shows a localized retry/failure state instead of an
empty picker (a Global source would otherwise have zero valid destinations),
submit is disabled until a valid destination is available, and the Workspace
page case is covered (current workspace known, other-workspace list failed).
- A successful-but-empty workspace list is distinct from a failure: the dialog
shows a localized "no valid destinations" state (never a bare empty picker)
and keeps submit disabled; a component test covers a Global source with
`listWorkspaces() === []`.
- Mobile presentation is implemented, not just specified: a responsive
presentation (Drawer/sheet at phone width or explicit `DialogContent`
overrides) with safe-area padding, 44px touch targets for the radios,
destination picker, name input, actions, AND the dialog close affordance
(the shared `DialogContent` close button is a 24px `icon-sm` and must be
overridden, e.g. `min-h-11 min-w-11`), and focus restoration on close. The
scroll invariant is one owner: the Settings content area stays the only
vertical scroller and the dialog fits without nested vertical scrolling
(the picker list scrolls only when it cannot fit).
- The default name is truncated so its UTF-8 byte length is at most 100
(code-point aware), and the copy succeeds for multibyte source names.
- The request payload is a discriminated union: selecting General always
clears `target_workspace_id`, so a Workspace → General destination switch
never submits a stale workspace ID (the backend rejects `global` with a
workspace ID).
- Move mode shows the "original will be removed" warning. A duplicate target
name blocks submit with the name field marked invalid (red + `aria-invalid`
+ inline error); backend `409` also surfaces on the name field; other
backend errors show a generic message.
- Submission is guarded against double-clicks: the submit handler checks an
`isBusy` flag and the primary button is `disabled={isBusy || ...}` while a
transfer is in flight; a deferred-response test asserts the button stays
disabled and a second click does not issue another copy/move request.
- A `404` from the backend is deliberately ambiguous (missing source OR
missing/unauthorized destination) and never discloses which: the dialog shows
a localized generic failure message and stays open; no rows are removed
automatically on a `404`, and no destination item is added.
- On success `onCompleted` routes **by the returned item's scope**: a
Global-target result is added to the Global store from any page; a
Workspace-target result joins the page's list only when the page is that
workspace's page; a Move removes the source from the page's own list.
- All new copy is localized in en, pseudo, pt-pt, and zh-cn, including the
destination-list loading state, the workspace-list failure state, the retry
action, and the submit-disabled hint; `i18n:check` and `i18n:ratchet` pass.
- Accessibility is explicit, not placeholder-dependent: the dialog has a
`DialogTitle`, the name and destination controls have real `Label`/`htmlFor`
associations, the Copy/Move radios form a labeled radio group
(`fieldset`/`legend` or `aria-label`), conflict errors are associated via
`aria-describedby`, and the radios are keyboard operable
(Tab/Arrow/Space). A component test exercises the keyboard path.
## Files likely touched
- `apps/web/lib/types/http-secrets.ts`
- `apps/web/lib/api/domains/secrets-api.ts` (+ `secrets-api.test.ts`)
- `apps/web/hooks/domains/settings/use-secret-destination-names.ts` (new, with
test)
- `apps/web/hooks/domains/settings/use-workspace-destinations.ts` (new, with
test; workspace-list loading/error/retry via `listWorkspaces`)
- `apps/web/components/settings/copy-move-secret-dialog.tsx` (new, with test)
- `apps/web/components/settings/secrets-settings.tsx` (extraction + row button
+ dialog state + `onCompleted` routing; extend `secrets-settings.test.ts`)
- Possibly new extracted component files (e.g.
`secrets-list-item-row.tsx`, `secret-form.tsx`)
- `apps/web/src/locales/{en,pseudo,pt-pt,zh-cn}/settings.json`
## Inputs
- Tasks 01-02 contracts (request/response shapes, `409`/`404`/`400`/`500`
semantics).
- Existing `DeleteSecretDialog`/`SecretsSettings` composition, `useSecrets`
scope routing (`addSecret`/`removeSecret`), store workspaces
(`workspaces.items` with `id`+`name`), and `useRequest` error handling.
## Dependencies
Tasks 01 and 02.
## TDD sequence
1. Failing API/hook tests for the new helpers, status surfacing, and
destination-name loading + conflict matching.
2. Failing component tests for dialog rendering, destination filtering,
default-name construction (literal origin tokens) and byte-aware
truncation (ASCII, multibyte, and astral-plane surrogate pairs such as
`😀`/`🔐` — asserting no unpaired surrogates or replacement characters and
`new TextEncoder().encode(result).length <= 100`), conflict blocking, move
warning, `409` surfacing, destination switching Workspace → General
asserting the payload carries no workspace target, a serialized-payload
test asserting `name: null` is never emitted, workspace-hydration-failure
rendering a retry/error state with submit disabled (Global source) and
`retry` re-fetching workspaces, mobile presentation (phone-width sheet,
44px targets, no overflow), keyboard operation of the Copy/Move radios,
the primary submit label switching between Copy and Move modes (toggling
the radio changes the button label), an in-flight duplicate-click test
(deferred response: button disabled, no second request), an ambiguous
`404` test (generic dialog feedback, dialog stays open, no row removal, no
destination item added), and `onCompleted` routing in both directions
(workspace page →
Global target lands in the store; Global page → workspace Move removes the
source from the Global list and routes the returned workspace item only
when the page is that workspace).
3. Extract the oversized sections from `secrets-settings.tsx` (existing tests
must stay green), then implement the dialog, row button, wiring, and i18n
keys; run focused frontend tests, typecheck, lint, and i18n checks.
## Verification
```bash
cd apps && pnpm --filter @kandev/web test -- --run
cd apps/web && pnpm run typecheck
cd apps && pnpm --filter @kandev/web lint
cd apps/web && pnpm run i18n:check && pnpm run i18n:ratchet
```
## Risks
- Route the `onCompleted` update by the returned item's scope, never the page
scope: a Workspace page move/copy to General must add to the Global store.
- The destination-name pre-check is best-effort; the backend `409` must still
be handled and shown on the name field.
- Persisted secret names are user data and must never be routed through a
catalog key; only the `{{name}} (from {{origin}})` pattern is translated,
and origin values stay literal.
- Truncation must be UTF-8 byte-aware to match the Go `len()` rule; do not use
`String.prototype.length` for the limit.
- No em dashes in user-facing copy; keep icon-action accessible labels.
- Keep `secrets-settings.tsx` under 600 lines after all changes.
## Output contract
Report the new/changed components, hooks, extraction result, keys, test names,
and the verification output.
@@ -0,0 +1,102 @@
---
id: "04-e2e-and-docs"
title: "E2E coverage and documentation"
status: done
wave: 4
depends_on: ["03-frontend-copy-move-dialog"]
plan: "plan.md"
spec: "../../specs/workspaces/secret-scope-transfer.md"
---
# Task 04: E2E Coverage and Documentation
## Acceptance
- Desktop Chromium E2E covers: copy a Global secret to a workspace with the
default suffixed name (both lists correct, source retained), move a
workspace secret to General (source gone, destination present), move a
Global secret to a workspace (source gone from the Global list, destination
present, returned-item scope routing correct), and a duplicate target name
blocked with the name field invalid.
- The desktop E2E actively proves plaintext never reaches the UI: after each
copy/move flow, `expect(page.locator("body")).not.toContainText(<known
value>)` is asserted (mirroring `repository-secrets.spec.ts`); known values
are never asserted or displayed positively.
- The E2E flow submits through the dialog's own primary button (a labeled
control inside the Copy/Move dialog that switches label with the selected
mode, e.g. `Copy`/`Move`), waits for the transfer response or the returned
list item to appear, and asserts the settings floating Save control was NOT
used for the transfer (the `createSecretFromSettings` helper's
floating-Save pattern is for page-draft creation only).
- The desktop spec's describe/title contains the literal `secrets-copy-move`
fragment so the `--grep` verification command selects the tests; the
direct spec-path run is documented as an alternative in the task's
verification block.
- Mobile-chrome E2E covers opening the dialog at phone width, exercising the
destination picker (including a Workspace → General switch), completing one
copy and one move, and asserting the implemented mobile presentation: ≥44px
touch targets for the radios, picker, name input, actions, and the dialog
close button (bounding-box assertions mirroring
`mobile-repository-secrets.spec.ts`), no horizontal overflow, single scroll
owner, and focus return on close.
- `docs/public/agents-and-profiles.md` gains a short copy/move paragraph in the
secret-scope section, and `docs/specs/INDEX.md` lists the new spec under
`workspaces/`.
## Files likely touched
- `apps/web/e2e/tests/settings/secrets-copy-move.spec.ts` (new)
- `apps/web/e2e/tests/settings/mobile-repository-secrets.spec.ts` or a sibling
mobile spec (new)
- `docs/public/agents-and-profiles.md`
- `docs/specs/INDEX.md`
## Inputs
- Task 03's dialog UI (selectors/labels from the i18n keys).
- Existing E2E conventions: `repository-secrets.spec.ts` helpers
(`createSecretFromSettings`, API client fixtures, negative-value assertions),
mobile-chrome project patterns from `mobile-repository-secrets.spec.ts`, and
the grep semantics documented in `apps/web/e2e/README.md`.
## Dependencies
Task 03.
## TDD sequence
1. Write the desktop spec with the `secrets-copy-move` describe fragment and
the negative plaintext assertions; run it after Task 03 lands.
2. Add the mobile spec with the picker interaction and geometry assertions.
3. Update the two docs files; run doc/i18n validation.
## Verification
```bash
cd apps/web && pnpm e2e:run -- --grep="secrets-copy-move"
cd apps/web && pnpm e2e:run -- --project=mobile-chrome --grep="copy/move|secrets-copy-move"
cd apps/web && pnpm run i18n:check && pnpm run i18n:ratchet
```
`e2e:run` performs the managed backend/web production build before running
(`e2e:raw` alone would launch whatever `apps/backend/bin/kandev` and
`apps/web/dist` already contain, which can be stale). If the repo runner
supports it, the direct spec-path form is the most reliable selector; use
whichever the runner accepts, and verify the grep actually matched (non-zero
test count).
## Risks
- E2E must assert via visible names/lists only and must never positively
assert secret values; negative body assertions are required to catch leaks.
- The mobile project gates on the repo's mobile-chrome config; follow the
existing mobile spec's structure exactly.
- Grep-based verification can silently match zero tests; confirm the describe
fragment or use the spec path.
- Keep the docs paragraph short and consistent with the existing scope
wording in `agents-and-profiles.md`.
## Output contract
Report the E2E specs added, results (including the grep match counts), docs
changes, and any residual risks.
+2
View File
@@ -160,6 +160,8 @@ Kandev has two secret scopes:
The General page manages Global secrets. Manage Workspace secrets from **Settings > Workspaces > _workspace_ > Secrets**. Agent and executor profile selectors intentionally show Global secrets only; a Workspace reference saved through an older or direct API path is rejected when the profile is saved or launched.
Copy or move a secret between scopes from the **Copy/Move** action on any secret row. The dialog picks Copy or Move, chooses a destination (Global or another workspace), and lets you edit the target name; it is pre-filled as `<name> (from Global)` or `<name> (from <workspace name>)` so copied secrets keep their origin visible. Moving removes the original after the copy is safely in place, and the value is transferred server-side between encrypted rows. It is never shown or copied through the browser. A target name that already exists in the destination blocks the action until you rename it.
Kandev encrypts secret values at rest with AES-256-GCM. The encryption key is `<KANDEV_HOME_DIR>/data/master.key` (by default `~/.kandev/data/master.key`) and is created with owner-only file permissions. `KANDEV_DATABASE_PATH` does not relocate this key. Protect and back it up with the Kandev database; losing it makes stored values unreadable. Anyone with access to the Secrets settings can reveal the plaintext.
Profile environment rules are:
+1
View File
@@ -150,6 +150,7 @@ Per-workspace credentials and triage triggers for external services.
| [deletion](workspaces/deletion.md) | shipped |
| [local-repositories](workspaces/local-repositories.md) | shipped |
| [repository-secrets](workspaces/repository-secrets.md) | shipped |
| [secret-scope-transfer](workspaces/secret-scope-transfer.md) | shipped |
## costs/ — cost tracking & budgets
@@ -0,0 +1,336 @@
---
status: shipped
created: 2026-08-11
owner: tbd
---
# Copy and Move Secrets Between Scopes
## Why
Moving a credential between a workspace and the user's Global set (or between
workspaces) currently means reveal, copy the plaintext, create a new secret,
and delete the old one. Users must handle the value outside Kandev, which is
both tedious and leak-prone. Kandev should copy or move a secret across scopes
as one operation, without ever showing the value.
## What
- Every secret row on the Global secrets page (`/settings/general/secrets`) and
on a Workspace secrets page (`/settings/workspace/:id/secrets`) offers a
**Copy/Move** action.
- The action opens one dialog that works the same on both pages. It contains:
- a **Copy / Move** radio (default Copy);
- a **destination** picker: **General** plus every workspace; when the source
secret is Workspace-scoped its own workspace is excluded, and when the
source is Global, General is excluded (a same-scope destination is a no-op);
- an editable **target name** field, pre-filled with
`<name> (from Global)` for a Global source or `<name> (from <workspace
name>)` for a Workspace source.
- **Copy** creates a new secret in the destination scope with the chosen name
and the source's value. The source stays.
- **Move** copies the secret to the destination and then removes the source, as
one atomic operation. The dialog states that the original will be removed
from its current scope.
- Workspace-to-workspace copy/move is supported through the destination picker.
- The persisted default target name is locale-independent: the origin token is
the literal string `Global` for a Global source and the raw workspace name
for a Workspace source. Only the surrounding pattern
(`<name> (from <origin>)`). The dialog default is truncated so
its UTF-8 encoding is at most 100 bytes, matching the backend's byte-based
name limit.
- If the chosen target name already exists in the destination scope, the
operation is blocked: the name field is marked invalid (red) with an error
message. The backend enforces this **atomically** inside the same transaction
that creates the copy and returns `409 Conflict`; the dialog also pre-checks
against loaded destination names when available.
- Copying or moving into the scope the secret already belongs to is rejected
with a clear validation error.
- Copying or moving a secret to a workspace requires that the destination
workspace exists and that the caller has access to it; a workspace source
also requires access to its owning workspace. Missing, unauthorized, or
nonexistent targets resolve to "not found" and never disclose whether the
secret or workspace exists.
- After a successful operation the visible lists update immediately: the
source list drops the secret after a Move, and the destination list shows
the new secret when it is the page being viewed. A Move or Copy into General
always adds the returned item to the Global store, regardless of which page
started it.
- The flow never reveals or copies plaintext through the UI; the encrypted
value moves between rows server-side.
## API surface
### HTTP
```text
POST /api/v1/secrets/:id/copy?workspace_id=<source-workspace-id>
POST /api/v1/secrets/:id/move?workspace_id=<source-workspace-id>
```text
The `workspace_id` query parameter identifies the source secret's workspace and
is required when the source is Workspace-scoped (matching the existing scoped
CRUD routes). The request body:
```json
{
"target_scope": "global" | "workspace",
"target_workspace_id": "<id>",
"name": "<optional target name>"
}
```
- `target_workspace_id` is required when `target_scope` is `workspace`.
- `name` is optional with presence semantics: a JSON-omitted `name` means "use
the source secret's name"; a present `name` must be non-empty after trimming
(an explicitly empty or whitespace-only name is a `400` validation error),
and an explicit JSON `null` is rejected as a `400` validation error rather
than treated as omitted. The name limit is 100 UTF-8 bytes after trimming,
matching the existing create/update validation.
- Success returns `201 Created` with the new `SecretListItem` (for Move the
source is already deleted at that point).
- Errors:
- `400` invalid payload or validation (bad scope/workspace combination,
same-scope destination, invalid name);
- `404` missing or unauthorized source, or missing/unauthorized destination
workspace;
- `409` target name conflict (atomically detected);
- `500` sanitized internal failure (decryption, storage). Details go to
server logs, never the response.
### WebSocket
```text
secrets.copy
secrets.move
```text
Payload: `{ "id": "<source>", "workspace_id": "<source-workspace>",
"target_scope": "global" | "workspace", "target_workspace_id": "<id>", "name":
"<optional>" }` (`name` follows the same presence semantics as HTTP;
`workspace_id` follows the same source-scoping rule as the HTTP query
parameter: omitted or empty selects a Global source, and a Workspace source
requires a non-empty value, resolving to not-found when missing). Success
responses return the new `SecretListItem` as the WS payload (same fields as
the HTTP response), mirroring the existing `secrets.create` convention. Error
codes: `ErrorCodeConflict` (name conflict), `ErrorCodeNotFound`
(missing/unauthorized source or destination), `ErrorCodeBadRequest`
(validation), `ErrorCodeInternalError` (unexpected failures, sanitized).
### Go service surface
```go
type CopySecretRequest struct {
Scope SecretScope `json:"target_scope"`
WorkspaceID string `json:"target_workspace_id"`
Name *string `json:"name,omitempty"` // omitted = use source name; null/empty/whitespace = validation error
}
var ErrSecretNameConflict = errors.New("a secret with this name already exists in the target scope")
var ErrWorkspaceAccessDenied = errors.New("workspace access denied or workspace not found")
var ErrSecretValidation = errors.New("secret validation failed")
```
Handlers classify exclusively with `errors.Is` against these sentinels and
`ErrNotFound`; they never match error text.
Because Go's standard JSON decoding maps both an omitted key and an explicit
`null` to a nil pointer, the request type (or the handler decode path)
implements presence-aware decoding: a custom `UnmarshalJSON` records whether
the `name` key was present, so the service rejects explicit `null` as a
validation error while defaulting a truly omitted key to the source name.
func (s *Service) Copy(ctx context.Context, sourceID, sourceWorkspaceID string, req *CopySecretRequest) (*SecretListItem, error)
func (s *Service) Move(ctx context.Context, sourceID, sourceWorkspaceID string, req *CopySecretRequest) (*SecretListItem, error)
```
The database schema is unchanged and `scope`/`workspace_id` stay immutable;
the `ScopedSecretStore` interface gains the two transfer methods below. The
service authorizes and validates, then delegates to atomic store operations:
```go
// ScopedSecretStore additions. sourceWorkspaceID is the RESOLVED source's
// workspace ("" for a Global source); a Move locks it alongside the
// destination so concurrent same-source moves serialize without deadlock.
// verifyDestination runs inside the transfer transaction while the
// destination lock is held, before the conflict check and insert; returning
// an error rolls back and surfaces that error (the service maps it to
// ErrWorkspaceAccessDenied / 404).
CopyScoped(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID, targetName string, verifyDestination func(context.Context) error) (*Secret, error)
MoveScoped(ctx context.Context, sourceID, sourceWorkspaceID string, targetScope SecretScope, targetWorkspaceID, targetName string, verifyDestination func(context.Context) error) (*Secret, error)
```
`CopyScoped` checks the target name and inserts the copy in one transaction;
`MoveScoped` additionally deletes the source in the same transaction. Both
return `ErrSecretNameConflict` when the target name is already taken and
`ErrNotFound` when the source row is absent. `UserVisibleStore` delegates and
rejects internal (`github:` prefix) source IDs. The encrypted value is copied
without passing plaintext through the service.
Store invariants for the transfer operations:
- The copied row is created with the caller's `user_id` (the same scoping the
regular create path writes); a transfer never produces an unowned row.
- The source select and the Move source delete use the same per-user
visibility predicate as the rest of the store, so a user can only move rows
they can see.
- The target-name conflict check compares the normalized scope (a legacy
empty stored scope is Global), so a legacy Global row can never be bypassed.
- The check-then-insert is atomic on both supported dialects: SQLite starts
the transaction with `BEGIN IMMEDIATE` (writer lock up front), and
PostgreSQL executes `BEGIN` then a `pg_advisory_xact_lock` on the target
scope's lock key on that same transaction before the source select and
conflict check, serializing competing writers so exactly one copy/move wins
a same-target-name race under READ COMMITTED. The PostgreSQL statement never
runs on SQLite. No schema or uniqueness-constraint change; pre-existing
duplicate names remain allowed by the regular create path.
- Lock scheme (single authoritative contract, PostgreSQL only): the secrets
package exports `WorkspaceLockKey(workspaceID string) int64`, a
deterministic FNV-1a 64-bit hash of the `kandev-secret-transfer:` prefix
plus the workspace ID — stable across restarts, collision-safe for UUID
inputs (a theoretical hash collision only over-serializes, never corrupts)
— plus a distinct stable constant `GlobalSecretTransferLockKey` for Global
targets. A transfer acquires the destination scope's key (and the source
workspace's key for Move, in sorted key order) and, while holding it, runs
the destination existence/authorization verification inside the transaction
before the conflict check and insert. The workspace-deletion transaction's
secret-cleanup step (`DeleteWorkspaceSecretsTx`) acquires the same
workspace key at its start and holds it to commit. Interleavings are
therefore closed: a transfer that inserts before a deletion commits is
cleaned up by that deletion under the same lock, and a transfer that starts
after the deletion commits observes the workspace gone and fails closed. On
SQLite the secrets database's single writer serializes transfer and
cleanup; the residual cross-database window matches the existing create
path (no schema change). A deterministic race test (separate connections,
channel-scheduled) proves no secret remains attached to a deleted workspace,
and a concurrent same-name test with a Global target proves exactly one
winner on the Global lock.
## Permissions
- A Global source is visible to the caller through the existing global access
rules; a Workspace source resolves only when the caller is authorized for
that workspace (same `GetWorkspaceSecret` path as the scoped CRUD routes).
- A workspace destination requires both existence and authorization. The
workspace authorizer is enforced for authenticated callers; a separate
existence check runs even in auth-disabled/unscoped contexts so a copy/move
can never attach a secret to a phantom workspace ID.
- Missing, unauthorized, or nonexistent sources/destinations all resolve to
"not found" — the error never reveals whether the secret or workspace
exists.
- Backend-owned internal secret IDs (`github:` prefix) are not addressable and
resolve to "not found".
## Failure modes
- **Target name conflict:** the operation fails closed with `409 Conflict` and
a message naming the scope and the conflicting name. The conflict check and
the copy share one transaction, and competing transfers are serialized
(writer lock up front on SQLite, advisory transaction lock on PostgreSQL), so
concurrent requests with the same target name yield exactly one success and
`409` for the others; nothing partial is created.
- **Same-scope destination:** rejected with a validation error before any
transfer mutation (a read-only source resolution may already have happened).
- **Source missing or unauthorized:** `404`, nothing changes.
- **Destination missing or unauthorized:** `404`, nothing changes; existence is
verified even when authorization is disabled. If the workspace-existence
checker is not wired, workspace destinations fail closed (same `404`).
- **Move failure:** the copy and the source deletion are one transaction. Any
failure (including a crash) rolls back; the source remains intact and no
copy exists. There is no intermediate dual-state or compensation window.
- **Internal failure (decryption, storage, or a database error inside an
authorization/existence lookup):** `500` with a sanitized message; full
details are logged server-side. Values never appear in error payloads. Only
the known "missing or unauthorized" sentinels (secret, workspace) map to
`404`; unknown errors are never reclassified as client mistakes.
- **Destination workspace fetch failure (dialog pre-check):** the dialog falls
back to the backend's authoritative `409`; the pre-check is best-effort only.
- **Workspace list failed to load (settings hydration failure):** the dialog
shows a localized retry/failure state and disables submit instead of
presenting an empty destination picker; a Global source must never see a
form with zero valid destinations.
- **Workspace list loaded successfully but is empty:** the dialog shows a
localized "no valid destinations" state (rather than an empty picker) and
keeps submit disabled; a Global source has no valid target and must not be
able to submit.
- **Source deleted or destination unavailable while the dialog is open:** the
backend returns `404` (deliberately ambiguous between a missing source and a
missing/unauthorized destination, so it never discloses which). The dialog
shows a localized generic failure message and stays open; rows are never
removed automatically on a `404`, and no destination item is added. The
source list refreshes on the next navigation or reload.
## Scenarios
- **GIVEN** a Global secret named `API Key`, **WHEN** the user opens Copy/Move
on it, chooses Copy, destination `My Workspace`, and keeps the default name
`API Key (from Global)`, **THEN** a Workspace secret named
`API Key (from Global)` with the same value appears in `My Workspace` and
the Global secret remains.
- **GIVEN** a Workspace secret in `My Workspace`, **WHEN** the user chooses
Move to General, **THEN** a Global secret with the chosen name exists with
the same value and the Workspace secret is gone, and the Global store gains
the returned item even though the operation started on the Workspace page.
- **GIVEN** a Global secret, **WHEN** the user chooses Move to `My Workspace`,
**THEN** the Workspace secret is created and the Global secret is removed.
- **GIVEN** a Workspace secret in `A`, **WHEN** the user copies it to
workspace `B`, **THEN** a Workspace secret in `B` exists with the same value
and the secret in `A` remains.
- **GIVEN** a destination scope that already has a secret with the chosen
name, **WHEN** the user submits Copy or Move, **THEN** the operation is
blocked with `409`, the name field is marked invalid with an error, and
neither the destination nor the source changes.
- **GIVEN** two concurrent copy requests with the same target name into an
empty destination scope, **WHEN** both submit, **THEN** exactly one succeeds
and the other receives `409`; the destination contains one secret.
- **GIVEN** a source secret and a destination equal to the source's own scope
and workspace, **WHEN** the user submits, **THEN** a validation error is
returned and nothing changes.
- **GIVEN** a caller without access to the destination workspace, **WHEN** the
caller submits a copy/move into it, **THEN** the operation fails with `404`
without disclosing the workspace's secrets.
- **GIVEN** a destination workspace ID that does not exist and authentication
disabled, **WHEN** the caller submits a copy/move into it, **THEN** the
operation fails with `404` and no secret is created.
- **GIVEN** an internal backend-owned secret ID (`github:` prefix), **WHEN**
the caller submits a copy/move of it, **THEN** the operation fails with
`404`.
- **GIVEN** a user on the Global secrets page who copies a secret to a
workspace, **WHEN** the copy completes, **THEN** the Global list is
unchanged and no workspace-scoped item is added to the Global store.
- **GIVEN** a user on a Workspace secrets page who moves a secret to General,
**WHEN** the move completes, **THEN** the workspace list no longer contains
the secret and the Global store gains it.
- **GIVEN** a Global source named with multibyte characters, **WHEN** the
dialog computes the default target name, **THEN** the default is truncated so
its UTF-8 length is at most 100 bytes and the copy succeeds without a
backend validation error.
## Mobile design contract
- Entry point: the Copy/Move button on a secret row opens the same dialog on
phone widths, from both the Global and Workspace secrets pages.
- Presentation: the dialog adapts to the phone viewport (full-height
sheet/drawer behavior rather than a centered desktop box), keeps the
Settings content area as the single scroll owner, respects safe areas, and
restores focus on close; Escape and back navigation close it.
- Interaction: the Copy/Move radios, destination picker, and name field use
touch-sized targets (at least 44px), rows stack to one column, and there is
no horizontal overflow. The destination picker is operable by touch and
keyboard alike.
- Accessibility: the dialog has a `DialogTitle`, real `Label`/`htmlFor`
associations for the name and destination controls (never placeholder-only),
a labeled Copy/Move radio group, conflict errors associated via
`aria-describedby`, and keyboard-operable radios (Tab/Arrow/Space).
- Parity: phone users can complete the full copy and move flows, including
choosing a workspace destination and correcting a conflicting target name.
## Out of scope
- Bulk copy/move of multiple secrets at once.
- Automatic conflict resolution (overwrite, auto-rename); conflicts always
block and require the user to change the target name.
- Copying values into literal environment variables or non-secret storage.
- Changing scope in place: scope and workspace remain immutable; copy/move is
the supported way to transfer authority.
- Live propagation of the copied value to running tasks or terminals.