diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.go index 7d0abc1751..a8f18f18d7 100644 --- a/backend/internal/database/database_test.go +++ b/backend/internal/database/database_test.go @@ -358,7 +358,7 @@ func TestMigration102_CleansUpRBACPermissions(t *testing.T) { for i, permission := range authz.AllPermissions() { if slices.Contains([]string{ authz.PermGitOpsBidirectional, authz.PermProjectsJobsRun, authz.PermProjectsExport, authz.PermProjectsBackup, authz.PermProjectsRestore, - }, permission) { + }, permission) || strings.HasPrefix(permission, "variables:sources:") { continue } id := fmt.Sprintf("c%d", i) @@ -443,7 +443,7 @@ func TestMigration102_CleansUpRBACPermissions(t *testing.T) { return out } - require.NoError(t, migrateDatabase(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 124)) + require.NoError(t, migrateDatabase(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 130)) checker := expanded("image-updates:check", "image-updates:apply") assert.Equal(t, map[string][]string{ "r1": {"containers:list"}, @@ -1841,3 +1841,89 @@ func TestMigration00129_GitOpsRedeployPolicyUpDown(t *testing.T) { require.NoError(t, rawDB.QueryRowContext(ctx, `SELECT COUNT(*) FROM pragma_table_info('gitops_syncs') WHERE name = 'redeploy_policy'`).Scan(&hasCol)) assert.Zero(t, hasCol) } + +func TestMigration130_AddsSecretSourcesAndGrantsFullAdmins(t *testing.T) { + ctx := t.Context() + rawDB, _ := newSQLiteSQLDB(t, t.TempDir(), "arcane-secret-sources.db") + schemaObjects := func() int { + var count int + require.NoError(t, rawDB.QueryRowContext(ctx, `SELECT COUNT(*) FROM sqlite_master + WHERE (type = 'table' AND name IN ('secret_sources', 'secret_source_environments')) + OR (type = 'index' AND name IN ('idx_secret_sources_name', 'idx_secret_source_environments_env'))`).Scan(&count)) + return count + } + secretSourcePermissions := slices.DeleteFunc(authz.AllPermissions(), func(permission string) bool { + return !strings.HasPrefix(permission, "variables:sources:") + }) + priorPermissions := slices.DeleteFunc(authz.AllPermissions(), func(permission string) bool { + return strings.HasPrefix(permission, "variables:sources:") + }) + require.Len(t, secretSourcePermissions, 6) + + require.NoError(t, migrateDatabase(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 129)) + priorJSON, err := json.Marshal(priorPermissions) + require.NoError(t, err) + almostPermissions := append(slices.Clone(priorPermissions[1:]), "unknown:one") + almostJSON, err := json.Marshal(almostPermissions) + require.NoError(t, err) + _, err = rawDB.ExecContext(ctx, `INSERT INTO roles (id, name, permissions) VALUES + ('admin', 'Custom admin', ?), + ('almost', 'Almost admin', ?), + ('editor', 'Editor-like', '["variables:list","variables:read","variables:create"]')`, string(priorJSON), string(almostJSON)) + require.NoError(t, err) + _, err = rawDB.ExecContext(ctx, `INSERT INTO api_keys (id, name, key_hash, key_prefix) VALUES + ('ka', 'Admin key', 'hash-ka', 'ka'), + ('kn', 'Almost admin key', 'hash-kn', 'kn'), + ('kv', 'Variables key', 'hash-kv', 'kv')`) + require.NoError(t, err) + for i, permission := range priorPermissions { + _, err = rawDB.ExecContext(ctx, `INSERT INTO api_key_permissions (id, api_key_id, permission) VALUES (?, 'ka', ?)`, fmt.Sprintf("ka%d", i), permission) + require.NoError(t, err) + } + for i, permission := range almostPermissions { + _, err = rawDB.ExecContext(ctx, `INSERT INTO api_key_permissions (id, api_key_id, permission) VALUES (?, 'kn', ?)`, fmt.Sprintf("kn%d", i), permission) + require.NoError(t, err) + } + _, err = rawDB.ExecContext(ctx, `INSERT INTO api_key_permissions (id, api_key_id, permission) VALUES ('kv1', 'kv', 'variables:create')`) + require.NoError(t, err) + state := func() (admin, editor []string, adminKeyGrants, variablesKeyGrants int) { + for id, target := range map[string]*[]string{"admin": &admin, "editor": &editor} { + var raw string + require.NoError(t, rawDB.QueryRowContext(ctx, `SELECT permissions FROM roles WHERE id = ?`, id).Scan(&raw)) + require.NoError(t, json.Unmarshal([]byte(raw), target)) + } + require.NoError(t, rawDB.QueryRowContext(ctx, `SELECT COUNT(*) FROM api_key_permissions WHERE api_key_id = 'ka' AND permission LIKE 'variables:sources:%'`).Scan(&adminKeyGrants)) + require.NoError(t, rawDB.QueryRowContext(ctx, `SELECT COUNT(*) FROM api_key_permissions WHERE api_key_id = 'kv' AND permission LIKE 'variables:sources:%'`).Scan(&variablesKeyGrants)) + return admin, editor, adminKeyGrants, variablesKeyGrants + } + + require.NoError(t, migrateDatabase(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 130)) + assert.Equal(t, 4, schemaObjects()) + admin, editor, adminKeyGrants, variablesKeyGrants := state() + assert.ElementsMatch(t, authz.AllPermissions(), admin, "full admins keep global admin status") + assert.NotContains(t, editor, "variables:sources:list") + assert.Equal(t, 6, adminKeyGrants) + assert.Zero(t, variablesKeyGrants) + var almostRole string + var almostKeyGrants int + require.NoError(t, rawDB.QueryRowContext(ctx, `SELECT permissions FROM roles WHERE id = 'almost'`).Scan(&almostRole)) + require.NoError(t, rawDB.QueryRowContext(ctx, `SELECT COUNT(*) FROM api_key_permissions WHERE api_key_id = 'kn' AND permission LIKE 'variables:sources:%'`).Scan(&almostKeyGrants)) + assert.NotContains(t, almostRole, "variables:sources:", "a role missing one prior permission is not a full admin") + assert.Zero(t, almostKeyGrants, "an API key missing one prior permission is not a full admin") + + _, err = rawDB.ExecContext(ctx, `INSERT INTO secret_sources (id, created_at, name, kind, definition) VALUES ('s1', CURRENT_TIMESTAMP, 'vault', 'http', '{}')`) + require.NoError(t, err) + _, err = rawDB.ExecContext(ctx, `INSERT INTO secret_sources (id, created_at, name, kind, definition) VALUES ('s2', CURRENT_TIMESTAMP, 'vault', 'http', '{}')`) + require.Error(t, err, "source names are unique") + _, err = rawDB.ExecContext(ctx, `INSERT INTO webhooks (id, name, token_hash, token_prefix, target_type, target_id) VALUES ('w1', 'refresh', 'h1', 'p1', 'secretsource', 's1')`) + require.NoError(t, err) + + require.NoError(t, migrateDatabase(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}, 129)) + assert.Zero(t, schemaObjects()) + admin, _, adminKeyGrants, _ = state() + assert.ElementsMatch(t, priorPermissions, admin) + assert.Zero(t, adminKeyGrants) + var webhooks int + require.NoError(t, rawDB.QueryRowContext(ctx, `SELECT COUNT(*) FROM webhooks WHERE target_type = 'secretsource'`).Scan(&webhooks)) + assert.Zero(t, webhooks) +} diff --git a/backend/internal/database/migrations/00130_add_secret_sources.go b/backend/internal/database/migrations/00130_add_secret_sources.go new file mode 100644 index 0000000000..ecb6b84fa1 --- /dev/null +++ b/backend/internal/database/migrations/00130_add_secret_sources.go @@ -0,0 +1,208 @@ +package migrations + +import ( + "github.com/pressly/goose/v3" +) + +const ( + v130SecretSourcePermissions = `["variables:sources:list","variables:sources:read","variables:sources:create","variables:sources:update","variables:sources:delete","variables:sources:refresh"]` + v130PriorPermissions = `[ + "users:list", "users:read", "users:create", "users:update", "users:delete", "roles:list", "roles:read", + "groups:list", "groups:read", + "apikeys:list", "apikeys:read", "apikeys:create", "apikeys:update", "apikeys:delete", "federated:list", + "federated:read", "federated:create", "federated:update", "federated:delete", "settings:read", + "settings:update", "environments:list", "environments:read", "environments:create", + "environments:update", "environments:delete", "environments:pair", "environments:sync", + "environments:restart", "registries:list", "registries:read", "registries:create", "registries:update", + "registries:delete", "registries:test", "registries:browse", "registries:delete-tags", "templates:list", + "templates:read", "templates:create", "templates:update", "templates:delete", "variables:list", + "variables:read", "variables:create", "variables:update", "variables:delete", "variables:sync", + "git-repositories:list", "git-repositories:read", "git-repositories:create", "git-repositories:update", + "git-repositories:delete", "git-repositories:test", "git-repositories:sync", "s3-destinations:list", + "s3-destinations:read", "s3-destinations:create", "s3-destinations:update", "s3-destinations:delete", + "s3-destinations:test", "s3-destinations:sync", "system-backups:list", "system-backups:read", + "system-backups:create", "system-backups:update", "system-backups:delete", "system-backups:upload", + "system-backups:restore", "system-backups:recovery-key", "events:list", "events:delete", + "diagnostics:read", "diagnostics:profile", "containers:list", "containers:read", "containers:logs", + "containers:create", "containers:start", "containers:stop", "containers:restart", "containers:redeploy", + "containers:update", "containers:kill", "containers:pause", "containers:delete", "containers:exec", + "containers:autoupdate", "projects:list", "projects:read", "projects:logs", "projects:create", + "projects:update", "projects:deploy", "projects:jobs:run", "projects:backup", "projects:restore", + "projects:down", "projects:restart", "projects:delete", + "projects:archive", "projects:export", "images:list", "images:read", "images:pull", "images:push", "images:build", + "images:tag", "images:commit", "images:prune", "images:delete", "images:upload", "images:patch", + "volumes:list", "volumes:read", "volumes:create", "volumes:rename", "volumes:delete", "volumes:prune", + "volumes:upload", "volumes:backup", "networks:list", "networks:read", "networks:create", + "networks:delete", "networks:prune", "networks:connect", "networks:disconnect", "swarm:read", + "swarm:update", "swarm:init", "swarm:join", "swarm:leave", "swarm:unlock", "swarm-services:list", + "swarm-services:read", "swarm-services:create", "swarm-services:update", "swarm-services:delete", + "swarm-services:logs", "swarm-stacks:list", "swarm-stacks:read", "swarm-stacks:create", + "swarm-stacks:update", "swarm-stacks:delete", "swarm-nodes:list", "swarm-nodes:read", + "swarm-nodes:update", "swarm-nodes:delete", "swarm-nodes:promote", "swarm-nodes:demote", + "swarm-configs:list", "swarm-configs:read", "swarm-configs:create", "swarm-configs:update", + "swarm-configs:delete", "swarm-secrets:list", "swarm-secrets:read", "swarm-secrets:create", + "swarm-secrets:update", "swarm-secrets:delete", "podman:read", "podman:autoupdate", "podman-pods:list", + "podman-pods:read", "podman-pods:create", "podman-pods:delete", "podman-pods:prune", "podman-pods:start", + "podman-pods:stop", "podman-pods:restart", "podman-pods:pause", "podman-pods:kill", + "podman-quadlets:list", "podman-quadlets:read", "podman-quadlets:create", "podman-quadlets:update", + "podman-quadlets:delete", "podman-quadlets:start", "podman-quadlets:stop", "podman-quadlets:restart", + "podman-secrets:list", "podman-secrets:read", "podman-secrets:create", "podman-secrets:update", + "podman-secrets:delete", "podman-kube:read", "podman-kube:create", "podman-kube:delete", "gitops:list", + "gitops:read", "gitops:create", "gitops:update", "gitops:delete", "gitops:sync", "gitops:lifecycle", + "gitops:backup", "gitops:bidirectional", "webhooks:list", "webhooks:create", "webhooks:update", + "webhooks:delete", "jobs:list", "jobs:read", "jobs:update", "jobs:run", "jobs:restart", "jobs:retry", + "jobs:cancel", "jobs:ack", "notifications:list", "notifications:read", "notifications:update", + "notifications:delete", "notifications:test", "system:read", "system:prune", "system:upgrade", + "image-updates:list", "image-updates:read", "image-updates:check", "image-updates:apply", + "vulnerabilities:list", "vulnerabilities:read", "vulnerabilities:scan", "vulnerabilities:update", + "build-workspaces:list", "build-workspaces:read", "build-workspaces:create", "build-workspaces:delete", + "activities:list", "activities:read", "activities:cancel", "activities:delete", + "environment-settings:read", "environment-settings:update" +]` + + v130SQLiteUp = ` +CREATE TABLE secret_sources ( + id TEXT PRIMARY KEY, + created_at DATETIME NOT NULL, + updated_at DATETIME, + name TEXT NOT NULL, + kind TEXT NOT NULL, + preset_id TEXT NOT NULL DEFAULT '', + definition TEXT NOT NULL, + inputs TEXT NOT NULL DEFAULT '{}', + credentials TEXT NOT NULL DEFAULT '', + path TEXT NOT NULL DEFAULT '', + key_prefix TEXT NOT NULL DEFAULT '', + all_environments BOOLEAN NOT NULL DEFAULT TRUE, + inject_into_containers BOOLEAN NOT NULL DEFAULT FALSE, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + last_fetched_at DATETIME, + last_error TEXT NOT NULL DEFAULT '', + last_key_count INTEGER NOT NULL DEFAULT 0, + last_skipped_key_count INTEGER NOT NULL DEFAULT 0 +); +CREATE UNIQUE INDEX idx_secret_sources_name ON secret_sources (name); +CREATE TABLE secret_source_environments ( + secret_source_id TEXT NOT NULL REFERENCES secret_sources(id) ON DELETE CASCADE, + environment_id TEXT NOT NULL REFERENCES environments(id) ON DELETE CASCADE, + PRIMARY KEY (secret_source_id, environment_id) +); +CREATE INDEX idx_secret_source_environments_env ON secret_source_environments (environment_id); +UPDATE roles +SET permissions = ( + SELECT json_group_array(value) FROM ( + SELECT value FROM json_each(roles.permissions) + UNION + SELECT value FROM json_each('` + v130SecretSourcePermissions + `') + ) +) +WHERE NOT EXISTS ( + SELECT 1 FROM json_each('` + v130PriorPermissions + `') AS prior + WHERE prior.value NOT IN (SELECT value FROM json_each(roles.permissions)) +); +INSERT INTO api_key_permissions (id, api_key_id, permission, environment_id, created_at) +SELECT + lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-4' || substr(hex(randomblob(2)), 2) || '-' || + substr('89ab', 1 + (abs(random()) % 4), 1) || substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6))), + admins.api_key_id, + granted.value, + admins.environment_id, + CURRENT_TIMESTAMP +FROM ( + SELECT api_key_id, MIN(environment_id) AS environment_id + FROM api_key_permissions + WHERE COALESCE(environment_id, '') = '' + AND permission IN (SELECT value FROM json_each('` + v130PriorPermissions + `')) + GROUP BY api_key_id + HAVING COUNT(DISTINCT permission) = (SELECT COUNT(*) FROM json_each('` + v130PriorPermissions + `')) +) AS admins +CROSS JOIN json_each('` + v130SecretSourcePermissions + `') AS granted +WHERE NOT EXISTS ( + SELECT 1 FROM api_key_permissions AS existing + WHERE existing.api_key_id = admins.api_key_id + AND existing.permission = granted.value + AND COALESCE(existing.environment_id, '') = '' +); +` + v130PostgresUp = ` +CREATE TABLE IF NOT EXISTS secret_sources ( + id text PRIMARY KEY, + created_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone, + name text NOT NULL, + kind text NOT NULL, + preset_id text NOT NULL DEFAULT '', + definition text NOT NULL, + inputs text NOT NULL DEFAULT '{}', + credentials text NOT NULL DEFAULT '', + path text NOT NULL DEFAULT '', + key_prefix text NOT NULL DEFAULT '', + all_environments boolean NOT NULL DEFAULT true, + inject_into_containers boolean NOT NULL DEFAULT false, + enabled boolean NOT NULL DEFAULT true, + last_fetched_at timestamp with time zone, + last_error text NOT NULL DEFAULT '', + last_key_count integer NOT NULL DEFAULT 0, + last_skipped_key_count integer NOT NULL DEFAULT 0 +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_secret_sources_name ON secret_sources (name); +CREATE TABLE IF NOT EXISTS secret_source_environments ( + secret_source_id text NOT NULL REFERENCES secret_sources(id) ON DELETE CASCADE, + environment_id text NOT NULL REFERENCES environments(id) ON DELETE CASCADE, + PRIMARY KEY (secret_source_id, environment_id) +); +CREATE INDEX IF NOT EXISTS idx_secret_source_environments_env ON secret_source_environments (environment_id); +UPDATE roles +SET permissions = permissions || ( + SELECT COALESCE(jsonb_agg(granted), '[]'::jsonb) + FROM jsonb_array_elements_text('` + v130SecretSourcePermissions + `'::jsonb) AS granted + WHERE NOT roles.permissions @> jsonb_build_array(granted) +) +WHERE roles.permissions @> '` + v130PriorPermissions + `'::jsonb; +INSERT INTO api_key_permissions (id, api_key_id, permission, environment_id, created_at) +SELECT gen_random_uuid()::text, admins.api_key_id, granted, admins.environment_id, CURRENT_TIMESTAMP +FROM ( + SELECT api_key_id, MIN(environment_id) AS environment_id + FROM api_key_permissions + WHERE COALESCE(environment_id, '') = '' + AND permission IN (SELECT jsonb_array_elements_text('` + v130PriorPermissions + `'::jsonb)) + GROUP BY api_key_id + HAVING COUNT(DISTINCT permission) = jsonb_array_length('` + v130PriorPermissions + `'::jsonb) +) AS admins +CROSS JOIN jsonb_array_elements_text('` + v130SecretSourcePermissions + `'::jsonb) AS granted +WHERE NOT EXISTS ( + SELECT 1 FROM api_key_permissions AS existing + WHERE existing.api_key_id = admins.api_key_id + AND existing.permission = granted + AND COALESCE(existing.environment_id, '') = '' +); +` + v130SQLiteDown = ` +DROP TABLE secret_source_environments; +DROP TABLE secret_sources; +DELETE FROM webhooks WHERE target_type = 'secretsource'; +UPDATE roles +SET permissions = ( + SELECT json_group_array(value) FROM json_each(roles.permissions) WHERE value NOT LIKE 'variables:sources:%' +) +WHERE EXISTS (SELECT 1 FROM json_each(roles.permissions) WHERE value LIKE 'variables:sources:%'); +DELETE FROM api_key_permissions WHERE permission LIKE 'variables:sources:%'; +` + v130PostgresDown = ` +DROP TABLE IF EXISTS secret_source_environments; +DROP TABLE IF EXISTS secret_sources; +DELETE FROM webhooks WHERE target_type = 'secretsource'; +UPDATE roles +SET permissions = ( + SELECT COALESCE(jsonb_agg(value), '[]'::jsonb) + FROM jsonb_array_elements_text(roles.permissions) AS value + WHERE value NOT LIKE 'variables:sources:%' +) +WHERE EXISTS (SELECT 1 FROM jsonb_array_elements_text(roles.permissions) AS value WHERE value LIKE 'variables:sources:%'); +DELETE FROM api_key_permissions WHERE permission LIKE 'variables:sources:%'; +` +) + +func init() { + goose.AddMigrationContext(run(v130SQLiteUp, v130PostgresUp), run(v130SQLiteDown, v130PostgresDown)) +} diff --git a/backend/internal/environment/scope.go b/backend/internal/environment/scope.go new file mode 100644 index 0000000000..8832391baa --- /dev/null +++ b/backend/internal/environment/scope.go @@ -0,0 +1,111 @@ +package environment + +import ( + "context" + "errors" + "fmt" + "slices" + "strings" + + "gorm.io/gorm" + + kit "kit.getarcane.app" + + "getarcane.dev/arcane/v3/internal/common" + "getarcane.dev/arcane/v3/internal/database" +) + +type ( + ScopeTable struct { + Table string + OwnerColumn string + } + + ScopeChange struct { + Submitted map[string]bool + Current []Environment + EnvironmentIDs []string + AllEnvironments bool + CurrentAll bool + } +) + +func IDs(environments []Environment) []string { + ids := make([]string, 0, len(environments)) + for _, env := range environments { + ids = append(ids, env.ID) + } + return ids +} + +func (t ScopeTable) Replace(tx *gorm.DB, ownerID string, envIDs []string) error { + if err := tx.Table(t.Table).Where(t.OwnerColumn+" = ?", ownerID).Delete(map[string]any{}).Error; err != nil { + return fmt.Errorf("failed to clear %s scope: %w", t.Table, err) + } + if len(envIDs) == 0 { + return nil + } + rows := make([]map[string]any, 0, len(envIDs)) + for _, envID := range envIDs { + rows = append(rows, map[string]any{ + t.OwnerColumn: ownerID, + "environment_id": envID, + }) + } + if err := tx.Table(t.Table).Create(rows).Error; err != nil { + return fmt.Errorf("failed to set %s scope: %w", t.Table, err) + } + return nil +} + +func NormalizeScope(ctx context.Context, db *database.DB, allEnvironments bool, envIDs []string) ([]string, error) { + if allEnvironments { + return nil, nil + } + + unique := make([]string, 0, len(envIDs)) + for _, id := range envIDs { + id = strings.TrimSpace(id) + if id != "" && !slices.Contains(unique, id) { + unique = append(unique, id) + } + } + if len(unique) == 0 { + return nil, common.Classify( + common.ErrGlobalVariableScopeRequired, + errors.New( + "at least one environment is required when a variable is not scoped to all environments", + ), + ) + } + + var count int64 + if err := db.WithContext(ctx).Model(&Environment{}).Where("id IN ?", unique).Count(&count).Error; err != nil { + return nil, fmt.Errorf("failed to update global variables: %w", err) + } + if count != int64(len(unique)) { + return nil, common.Classify( + common.ErrGlobalVariableUnknownEnvironment, + errors.New("failed to update global variables: one or more environments do not exist"), + ) + } + return unique, nil +} + +func ResolveScope(ctx context.Context, db *database.DB, change ScopeChange) ([]string, bool, error) { + envIDs := IDs(change.Current) + if !change.Submitted["allEnvironments"] && !change.Submitted["environmentIds"] { + return envIDs, change.CurrentAll, nil + } + + normalized, err := NormalizeScope( + ctx, + db, + kit.Ternary(change.Submitted["allEnvironments"], change.AllEnvironments, change.CurrentAll), + kit.Ternary(change.Submitted["environmentIds"], change.EnvironmentIDs, envIDs), + ) + if err != nil { + return nil, false, err + } + return normalized, len(normalized) == 0, nil +} diff --git a/backend/internal/project/children/lifecycle/service.go b/backend/internal/project/children/lifecycle/service.go index ad4bf53686..9920f2a17d 100644 --- a/backend/internal/project/children/lifecycle/service.go +++ b/backend/internal/project/children/lifecycle/service.go @@ -11,7 +11,6 @@ import ( "os" "path" "path/filepath" - "regexp" "strings" "time" @@ -50,8 +49,6 @@ const ( LifecycleStatusTimeout = "timeout" ) -var lifecycleEnvKeyRegex = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) - func New(dockerService *dockerInternal.DockerClientService, imageService *image.ImageService) *Service { return &Service{ dockerService: dockerService, @@ -114,7 +111,7 @@ func ParseKeyValueEnv(stdout string) (map[string]string, error) { if !found || key == "" { return nil, fmt.Errorf("line %d: expected KEY=VALUE, got %q", lineNum, line) } - if !lifecycleEnvKeyRegex.MatchString(key) { + if !projects.EnvKeyPattern.MatchString(key) { return nil, fmt.Errorf("line %d: invalid env key %q", lineNum, key) } env[key] = value diff --git a/backend/internal/variable/children/source/handler.go b/backend/internal/variable/children/source/handler.go new file mode 100644 index 0000000000..c009807b1b --- /dev/null +++ b/backend/internal/variable/children/source/handler.go @@ -0,0 +1,194 @@ +package source + +import ( + "context" + + "github.com/danielgtaylor/huma/v2" + + "getarcane.dev/arcane/v3/internal/middleware" + "getarcane.dev/arcane/v3/pkg/handlerutil" + "getarcane.dev/types/v3" +) + +type ( + SecretSourceHandler struct { + service *Service + sync func(ctx context.Context) []types.EnvironmentSyncStatus + } + + ListSecretSourcesInput struct{} + + ListSecretSourcePresetsInput struct{} + + SecretSourceIDInput struct { + ID string `path:"id" doc:"Secret source ID"` + } + + CreateSecretSourceInput struct { + types.Create[types.SecretSourceInput] + } + + UpdateSecretSourceInput struct { + ID string `path:"id" doc:"Secret source ID"` + types.Update[types.SecretSourceInput] + } + + TestSecretSourceInput struct { + types.Create[types.SecretSourceTestInput] + } + + ValidateSecretSourceInput struct { + Body types.SecretSourceValidateInput + } +) + +func NewHandler(service *Service, sync func(ctx context.Context) []types.EnvironmentSyncStatus) *SecretSourceHandler { + return &SecretSourceHandler{ + service: service, + sync: sync, + } +} + +func (h *SecretSourceHandler) ListSecretSources(ctx context.Context, _ *ListSecretSourcesInput) (*handlerutil.Out[[]types.SecretSource], error) { + sources, err := h.service.List(ctx) + if err != nil { + return nil, handlerutil.APIError(err) + } + return &handlerutil.Out[[]types.SecretSource]{ + Body: types.ApiResponse[[]types.SecretSource]{ + Success: true, + Data: sources, + }, + }, nil +} + +func (h *SecretSourceHandler) GetSecretSource(ctx context.Context, input *SecretSourceIDInput) (*handlerutil.Out[types.SecretSource], error) { + source, err := h.service.Get(ctx, input.ID) + if err != nil { + return nil, handlerutil.APIError(err) + } + return &handlerutil.Out[types.SecretSource]{ + Body: types.ApiResponse[types.SecretSource]{ + Success: true, + Data: source, + }, + }, nil +} + +func (h *SecretSourceHandler) CreateSecretSource(ctx context.Context, input *CreateSecretSourceInput) (*handlerutil.Out[types.SecretSourceMutationResponse], error) { + submitted, err := input.SubmittedFields() + if err != nil { + return nil, huma.Error400BadRequest("invalid request body", err) + } + source, err := h.service.Create(ctx, input.Body, submitted) + if err != nil { + return nil, handlerutil.APIError(err) + } + return &handlerutil.Out[types.SecretSourceMutationResponse]{ + Body: types.ApiResponse[types.SecretSourceMutationResponse]{ + Success: true, + Data: types.SecretSourceMutationResponse{ + Source: &source, + SyncResults: h.sync(ctx), + }, + }, + }, nil +} + +func (h *SecretSourceHandler) UpdateSecretSource(ctx context.Context, input *UpdateSecretSourceInput) (*handlerutil.Out[types.SecretSourceMutationResponse], error) { + submitted, err := input.SubmittedFields() + if err != nil { + return nil, huma.Error400BadRequest("invalid request body", err) + } + source, err := h.service.Update(ctx, input.ID, input.Body, submitted) + if err != nil { + return nil, handlerutil.APIError(err) + } + return &handlerutil.Out[types.SecretSourceMutationResponse]{ + Body: types.ApiResponse[types.SecretSourceMutationResponse]{ + Success: true, + Data: types.SecretSourceMutationResponse{ + Source: &source, + SyncResults: h.sync(ctx), + }, + }, + }, nil +} + +func (h *SecretSourceHandler) DeleteSecretSource(ctx context.Context, input *SecretSourceIDInput) (*handlerutil.Out[types.SecretSourceMutationResponse], error) { + if err := h.service.Delete(ctx, input.ID); err != nil { + return nil, handlerutil.APIError(err) + } + return &handlerutil.Out[types.SecretSourceMutationResponse]{ + Body: types.ApiResponse[types.SecretSourceMutationResponse]{ + Success: true, + Data: types.SecretSourceMutationResponse{ + SyncResults: h.sync(ctx), + }, + }, + }, nil +} + +func (h *SecretSourceHandler) RefreshSecretSource(ctx context.Context, input *SecretSourceIDInput) (*handlerutil.Out[types.SecretSourceMutationResponse], error) { + source, err := h.service.Refresh(ctx, input.ID) + if err != nil { + return nil, handlerutil.APIError(err) + } + return &handlerutil.Out[types.SecretSourceMutationResponse]{ + Body: types.ApiResponse[types.SecretSourceMutationResponse]{ + Success: true, + Data: types.SecretSourceMutationResponse{ + Source: &source, + SyncResults: h.sync(ctx), + }, + }, + }, nil +} + +func (h *SecretSourceHandler) TestSecretSource(ctx context.Context, input *TestSecretSourceInput) (*handlerutil.Out[types.SecretSourceTestResult], error) { + submitted, err := input.SubmittedFields() + if err != nil { + return nil, huma.Error400BadRequest("invalid request body", err) + } + permissions, _ := middleware.PermissionsFromContext(ctx) + result, err := h.service.Test(ctx, TestRequest{ + Permissions: permissions, + Submitted: submitted, + Input: input.Body, + }) + if err != nil { + return nil, handlerutil.APIError(err) + } + return &handlerutil.Out[types.SecretSourceTestResult]{ + Body: types.ApiResponse[types.SecretSourceTestResult]{ + Success: true, + Data: result, + }, + }, nil +} + +func (h *SecretSourceHandler) ValidateDefinition(_ context.Context, input *ValidateSecretSourceInput) (*handlerutil.Out[types.SecretSourceDefinition], error) { + definition, err := h.service.ValidateDefinition(input.Body.Definition) + if err != nil { + return nil, handlerutil.APIError(err) + } + return &handlerutil.Out[types.SecretSourceDefinition]{ + Body: types.ApiResponse[types.SecretSourceDefinition]{ + Success: true, + Data: definition, + }, + }, nil +} + +func (h *SecretSourceHandler) ListPresets(_ context.Context, _ *ListSecretSourcePresetsInput) (*handlerutil.Out[[]types.SecretSourcePreset], error) { + presets, err := h.service.Presets() + if err != nil { + return nil, handlerutil.APIError(err) + } + return &handlerutil.Out[[]types.SecretSourcePreset]{ + Body: types.ApiResponse[[]types.SecretSourcePreset]{ + Success: true, + Data: presets, + }, + }, nil +} diff --git a/backend/internal/variable/children/source/model.go b/backend/internal/variable/children/source/model.go new file mode 100644 index 0000000000..4283ebab37 --- /dev/null +++ b/backend/internal/variable/children/source/model.go @@ -0,0 +1,33 @@ +package source + +import ( + "time" + + "getarcane.dev/arcane/v3/internal/database" + "getarcane.dev/arcane/v3/internal/environment" +) + +type ( + SecretSource struct { + database.BaseModel + + LastFetchedAt *time.Time `gorm:"column:last_fetched_at"` + Name string `gorm:"column:name" sortable:"true"` + Kind string `gorm:"column:kind"` + PresetID string `gorm:"column:preset_id"` + Definition string `gorm:"column:definition"` + Inputs map[string]string `gorm:"column:inputs;serializer:json"` + Credentials string `gorm:"column:credentials"` + Path string `gorm:"column:path"` + KeyPrefix string `gorm:"column:key_prefix"` + LastError string `gorm:"column:last_error"` + Environments []environment.Environment `gorm:"many2many:secret_source_environments;joinForeignKey:SecretSourceID;joinReferences:EnvironmentID"` + LastKeyCount int `gorm:"column:last_key_count"` + LastSkippedKeyCount int `gorm:"column:last_skipped_key_count"` + AllEnvironments bool `gorm:"column:all_environments"` + InjectIntoContainers bool `gorm:"column:inject_into_containers"` + Enabled bool `gorm:"column:enabled"` + } +) + +func (SecretSource) TableName() string { return "secret_sources" } diff --git a/backend/internal/variable/children/source/module.go b/backend/internal/variable/children/source/module.go new file mode 100644 index 0000000000..015853526b --- /dev/null +++ b/backend/internal/variable/children/source/module.go @@ -0,0 +1,103 @@ +package source + +import ( + "net/http" + + "github.com/danielgtaylor/huma/v2" + + "getarcane.dev/arcane/v3/internal/middleware" + "getarcane.dev/arcane/v3/pkg/authz" + "getarcane.dev/arcane/v3/pkg/handlerutil" +) + +func RegisterRoutes(api huma.API, h *SecretSourceHandler) { + middleware.RegisterWithPermission(api, huma.Operation{ + OperationID: "listSecretSourcePresets", + Method: http.MethodGet, + Path: "/variables/source-presets", + Summary: "List secret source presets", + Description: "List the built-in secret source definitions with their form metadata", + Tags: []string{"Variables"}, + Security: handlerutil.DefaultOperationSecurity(), + }, authz.PermVariablesSourcesList, h.ListPresets) + + middleware.RegisterWithPermission(api, huma.Operation{ + OperationID: "validateSecretSourceDefinition", + Method: http.MethodPost, + Path: "/variables/source-presets/validate", + Summary: "Validate a secret source definition", + Description: "Parse and validate a custom secret source definition YAML", + Tags: []string{"Variables"}, + Security: handlerutil.DefaultOperationSecurity(), + }, authz.PermVariablesSourcesRead, h.ValidateDefinition) + + middleware.RegisterWithPermission(api, huma.Operation{ + OperationID: "listSecretSources", + Method: http.MethodGet, + Path: "/variables/sources", + Summary: "List secret sources", + Description: "List external secret sources (credentials are never returned)", + Tags: []string{"Variables"}, + Security: handlerutil.DefaultOperationSecurity(), + }, authz.PermVariablesSourcesList, h.ListSecretSources) + + middleware.RegisterWithPermission(api, huma.Operation{ + OperationID: "createSecretSource", + Method: http.MethodPost, + Path: "/variables/sources", + Summary: "Create a secret source", + Description: "Create an external secret source, fetch it, and re-sync variables", + Tags: []string{"Variables"}, + Security: handlerutil.DefaultOperationSecurity(), + }, authz.PermVariablesSourcesCreate, h.CreateSecretSource) + + middleware.RegisterWithPermission(api, huma.Operation{ + OperationID: "testSecretSource", + Method: http.MethodPost, + Path: "/variables/sources/test", + Summary: "Test a secret source", + Description: "Fetch a saved or unsaved secret source and return only the key names", + Tags: []string{"Variables"}, + Security: handlerutil.DefaultOperationSecurity(), + }, authz.PermVariablesSourcesRefresh, h.TestSecretSource) + + middleware.RegisterWithPermission(api, huma.Operation{ + OperationID: "getSecretSource", + Method: http.MethodGet, + Path: "/variables/sources/{id}", + Summary: "Get a secret source", + Description: "Get one external secret source and its fetch status", + Tags: []string{"Variables"}, + Security: handlerutil.DefaultOperationSecurity(), + }, authz.PermVariablesSourcesRead, h.GetSecretSource) + + middleware.RegisterWithPermission(api, huma.Operation{ + OperationID: "updateSecretSource", + Method: http.MethodPatch, + Path: "/variables/sources/{id}", + Summary: "Update a secret source", + Description: "Update submitted fields of a secret source; omitted credential keys are kept", + Tags: []string{"Variables"}, + Security: handlerutil.DefaultOperationSecurity(), + }, authz.PermVariablesSourcesUpdate, h.UpdateSecretSource) + + middleware.RegisterWithPermission(api, huma.Operation{ + OperationID: "deleteSecretSource", + Method: http.MethodDelete, + Path: "/variables/sources/{id}", + Summary: "Delete a secret source", + Description: "Delete a secret source and re-sync variables", + Tags: []string{"Variables"}, + Security: handlerutil.DefaultOperationSecurity(), + }, authz.PermVariablesSourcesDelete, h.DeleteSecretSource) + + middleware.RegisterWithPermission(api, huma.Operation{ + OperationID: "refreshSecretSource", + Method: http.MethodPost, + Path: "/variables/sources/{id}/refresh", + Summary: "Refresh a secret source", + Description: "Fetch a secret source now and re-sync variables", + Tags: []string{"Variables"}, + Security: handlerutil.DefaultOperationSecurity(), + }, authz.PermVariablesSourcesRefresh, h.RefreshSecretSource) +} diff --git a/backend/internal/variable/children/source/service.go b/backend/internal/variable/children/source/service.go new file mode 100644 index 0000000000..22fb206a45 --- /dev/null +++ b/backend/internal/variable/children/source/service.go @@ -0,0 +1,643 @@ +package source + +import ( + "bytes" + "context" + "encoding/json/v2" + "errors" + "fmt" + "log/slog" + "maps" + "slices" + "strings" + "time" + + "gorm.io/gorm" + + kit "kit.getarcane.app" + "kit.getarcane.app/cache" + "kit.getarcane.app/concurrency" + "kit.getarcane.app/sys/crypto" + + "getarcane.dev/arcane/v3/internal/common" + "getarcane.dev/arcane/v3/internal/database" + "getarcane.dev/arcane/v3/internal/environment" + "getarcane.dev/arcane/v3/pkg/authz" + "getarcane.dev/arcane/v3/pkg/projects" + "getarcane.dev/arcane/v3/pkg/secretsource" + "getarcane.dev/arcane/v3/resources" + "getarcane.dev/types/v3" +) + +type ( + Service struct { + db *database.DB + engine *secretsource.Engine + entries *cache.Cache[string, []types.EnvVariable] + fetchLocks concurrency.KeyedMutex + } + + ServiceParams struct { + DB *database.DB + DockerClient secretsource.DockerClientFunc + } + + TestRequest struct { + Permissions *authz.PermissionSet + Submitted map[string]bool + Input types.SecretSourceTestInput + } + + sourceConfig struct { + inputs map[string]string + credentials map[string]string + presetID string + path string + keyPrefix string + definition types.SecretSourceDefinition + } +) + +const presetsDir = "secretsources" + +var ( + ErrSecretSourceNotFound = common.Classify(common.ErrNotFound, errors.New("secret source not found")) + ErrSecretSourceConflict = common.Classify(common.ErrConflict, errors.New("a secret source with this name already exists")) + ErrSecretSourceNameRequired = common.Classify(common.ErrValidation, &types.FieldError{Field: "name", Err: errors.New("name is required")}) + ErrDefinitionChangeDenied = common.Classify(common.ErrForbidden, fmt.Errorf("testing a saved secret source with changed settings requires %s", authz.PermVariablesSourcesUpdate)) + ErrUnsavedTestDenied = common.Classify(common.ErrForbidden, fmt.Errorf("testing an unsaved secret source requires %s", authz.PermVariablesSourcesCreate)) + sourceScope = environment.ScopeTable{ + Table: "secret_source_environments", + OwnerColumn: "secret_source_id", + } +) + +func NewService(p ServiceParams) *Service { + return &Service{ + db: p.DB, + engine: secretsource.NewEngine(secretsource.EngineConfig{DockerClient: p.DockerClient}), + entries: &cache.Cache[string, []types.EnvVariable]{}, + } +} + +func (s *Service) Presets() ([]types.SecretSourcePreset, error) { + return secretsource.LoadPresets(resources.FS, presetsDir) +} + +func (s *Service) ValidateDefinition(source string) (types.SecretSourceDefinition, error) { + definition, err := secretsource.ParseDefinition([]byte(source)) + if err != nil { + return types.SecretSourceDefinition{}, common.Classify(common.ErrValidation, err) + } + return definition, nil +} + +func (s *Service) List(ctx context.Context) ([]types.SecretSource, error) { + var records []SecretSource + if err := s.db.WithContext(ctx).Preload("Environments").Order("created_at, id").Find(&records).Error; err != nil { + return nil, fmt.Errorf("failed to list secret sources: %w", err) + } + result := make([]types.SecretSource, 0, len(records)) + for _, record := range records { + dto, err := toDTO(record) + if err != nil { + return nil, err + } + result = append(result, dto) + } + return result, nil +} + +func (s *Service) Get(ctx context.Context, id string) (types.SecretSource, error) { + record, err := s.load(ctx, id) + if err != nil { + return types.SecretSource{}, err + } + return toDTO(record) +} + +func (s *Service) Create(ctx context.Context, input types.SecretSourceInput, submitted map[string]bool) (types.SecretSource, error) { + name := strings.TrimSpace(input.Name) + if name == "" { + return types.SecretSource{}, ErrSecretSourceNameRequired + } + config, err := s.mergeConfig(sourceConfig{}, input, submitted) + if err != nil { + return types.SecretSource{}, err + } + envIDs, err := environment.NormalizeScope(ctx, s.db, input.AllEnvironments, input.EnvironmentIDs) + if err != nil { + return types.SecretSource{}, err + } + definition, credentials, err := encodeConfig(config) + if err != nil { + return types.SecretSource{}, err + } + + record := SecretSource{ + Name: name, + Kind: config.definition.Kind, + PresetID: config.presetID, + Definition: definition, + Inputs: config.inputs, + Credentials: credentials, + Path: config.path, + KeyPrefix: config.keyPrefix, + AllEnvironments: len(envIDs) == 0, + InjectIntoContainers: input.InjectIntoContainers, + Enabled: !submitted["enabled"] || input.Enabled, + } + err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + if createErr := tx.Omit("Environments").Create(&record).Error; createErr != nil { + if database.IsDuplicateKeyError(tx, createErr) { + return ErrSecretSourceConflict + } + return fmt.Errorf("failed to create secret source: %w", createErr) + } + return sourceScope.Replace(tx, record.ID, envIDs) + }) + if err != nil { + return types.SecretSource{}, err + } + + unlock, err := s.fetchLocks.LockContext(ctx, record.ID) + if err != nil { + return types.SecretSource{}, err + } + defer unlock() + return s.refetch(ctx, record.ID, true) +} + +func (s *Service) Update(ctx context.Context, id string, input types.SecretSourceInput, submitted map[string]bool) (types.SecretSource, error) { + unlock, err := s.fetchLocks.LockContext(ctx, id) + if err != nil { + return types.SecretSource{}, err + } + defer unlock() + + record, err := s.load(ctx, id) + if err != nil { + return types.SecretSource{}, err + } + base, err := configOf(record) + if err != nil { + return types.SecretSource{}, err + } + config, err := s.mergeConfig(base, input, submitted) + if err != nil { + return types.SecretSource{}, err + } + name := kit.Ternary(submitted["name"], strings.TrimSpace(input.Name), record.Name) + if name == "" { + return types.SecretSource{}, ErrSecretSourceNameRequired + } + envIDs, allEnvironments, err := environment.ResolveScope(ctx, s.db, environment.ScopeChange{ + Submitted: submitted, + Current: record.Environments, + EnvironmentIDs: input.EnvironmentIDs, + AllEnvironments: input.AllEnvironments, + CurrentAll: record.AllEnvironments, + }) + if err != nil { + return types.SecretSource{}, err + } + definition, credentials, err := encodeConfig(config) + if err != nil { + return types.SecretSource{}, err + } + + updated := SecretSource{ + BaseModel: record.BaseModel, + LastFetchedAt: record.LastFetchedAt, + Name: name, + Kind: config.definition.Kind, + PresetID: config.presetID, + Definition: definition, + Inputs: config.inputs, + Credentials: credentials, + Path: config.path, + KeyPrefix: config.keyPrefix, + LastError: record.LastError, + LastKeyCount: record.LastKeyCount, + LastSkippedKeyCount: record.LastSkippedKeyCount, + AllEnvironments: allEnvironments, + InjectIntoContainers: kit.Ternary(submitted["injectIntoContainers"], input.InjectIntoContainers, record.InjectIntoContainers), + Enabled: kit.Ternary(submitted["enabled"], input.Enabled, record.Enabled), + } + err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + result := tx.Model(&SecretSource{}).Where("id = ?", id).Select("*").Omit("Environments").Updates(&updated) + if result.Error != nil { + if database.IsDuplicateKeyError(tx, result.Error) { + return ErrSecretSourceConflict + } + return fmt.Errorf("failed to update secret source: %w", result.Error) + } + if result.RowsAffected == 0 { + return ErrSecretSourceNotFound + } + return sourceScope.Replace(tx, id, envIDs) + }) + if err != nil { + return types.SecretSource{}, err + } + if sameFetch(base, config) { + return s.Get(ctx, id) + } + return s.refetch(ctx, id, true) +} + +func (s *Service) Delete(ctx context.Context, id string) error { + unlock, err := s.fetchLocks.LockContext(ctx, id) + if err != nil { + return err + } + defer unlock() + + err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + result := tx.Delete(&SecretSource{}, "id = ?", id) + if result.Error != nil { + return fmt.Errorf("failed to delete secret source: %w", result.Error) + } + if result.RowsAffected == 0 { + return ErrSecretSourceNotFound + } + return sourceScope.Replace(tx, id, nil) + }) + if err != nil { + return err + } + s.engine.ForgetSource(id) + s.entries.Delete(id) + return nil +} + +func (s *Service) Refresh(ctx context.Context, id string) (types.SecretSource, error) { + unlock, err := s.fetchLocks.LockContext(ctx, id) + if err != nil { + return types.SecretSource{}, err + } + defer unlock() + return s.refetch(ctx, id, false) +} + +func (s *Service) Test(ctx context.Context, req TestRequest) (types.SecretSourceTestResult, error) { + id := strings.TrimSpace(req.Input.ID) + base, err := s.testBase(ctx, id) + if err != nil { + return types.SecretSourceTestResult{}, err + } + config, err := s.mergeConfig(base, req.Input.SecretSourceInput, req.Submitted) + if err != nil { + return types.SecretSourceTestResult{}, err + } + if id == "" && !req.Permissions.Allows(authz.PermVariablesSourcesCreate, "") { + return types.SecretSourceTestResult{}, ErrUnsavedTestDenied + } + if id != "" && !sameFetch(base, config) && !req.Permissions.Allows(authz.PermVariablesSourcesUpdate, "") { + return types.SecretSourceTestResult{}, ErrDefinitionChangeDenied + } + + entries, skipped, err := s.fetchConfig(ctx, id, config) + if err != nil { + return types.SecretSourceTestResult{Error: err.Error()}, nil + } + keys := make([]string, 0, len(entries)) + for _, entry := range entries { + keys = append(keys, entry.Key) + } + return types.SecretSourceTestResult{ + Keys: keys, + KeyCount: len(keys), + SkippedKeyCount: skipped, + Success: true, + }, nil +} + +func (s *Service) testBase(ctx context.Context, id string) (sourceConfig, error) { + if id == "" { + return sourceConfig{}, nil + } + record, err := s.load(ctx, id) + if err != nil { + return sourceConfig{}, err + } + return configOf(record) +} + +func (s *Service) EffectiveLayers(ctx context.Context, envID string) ([][]types.EnvVariable, error) { + var records []SecretSource + if err := s.db.WithContext(ctx).Preload("Environments").Where("enabled = ?", true).Order("created_at, id").Find(&records).Error; err != nil { + return nil, fmt.Errorf("failed to load secret sources: %w", err) + } + + var global, scoped [][]types.EnvVariable + for _, record := range records { + if !record.AllEnvironments && !slices.Contains(environment.IDs(record.Environments), envID) { + continue + } + entries, allEnvironments, err := s.scopedEntries(ctx, record.ID, envID) + if err != nil { + return nil, fmt.Errorf("secret source %q has no values: %w", record.Name, err) + } + if entries == nil { + continue + } + if allEnvironments { + global = append(global, entries) + } else { + scoped = append(scoped, entries) + } + } + return append(global, scoped...), nil +} + +func (s *Service) refetch(ctx context.Context, id string, invalidate bool) (types.SecretSource, error) { + record, err := s.load(ctx, id) + if err != nil { + return types.SecretSource{}, err + } + if invalidate { + s.engine.ForgetSource(id) + s.entries.Delete(id) + if record.Enabled { + _, _ = s.fetch(ctx, record) + } + return s.Get(ctx, id) + } + + _, fetchErr := s.fetch(ctx, record) + source, err := s.Get(ctx, id) + if err != nil { + return types.SecretSource{}, err + } + if fetchErr != nil { + return source, common.Classify(common.ErrUnavailable, fmt.Errorf("failed to refresh secret source %q: %w", record.Name, fetchErr)) + } + return source, nil +} + +func (s *Service) scopedEntries(ctx context.Context, id, envID string) ([]types.EnvVariable, bool, error) { + unlock, err := s.fetchLocks.LockContext(ctx, id) + if err != nil { + return nil, false, err + } + defer unlock() + + current, err := s.load(ctx, id) + if errors.Is(err, ErrSecretSourceNotFound) { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + if !current.Enabled || (!current.AllEnvironments && !slices.Contains(environment.IDs(current.Environments), envID)) { + return nil, false, nil + } + entries, ok, _ := s.entries.Get(current.ID) + if !ok { + if entries, err = s.fetch(context.WithoutCancel(ctx), current); err != nil { + return nil, false, err + } + } + + result := make([]types.EnvVariable, 0, len(entries)) + for _, entry := range entries { + result = append(result, types.EnvVariable{ + Key: entry.Key, + Value: entry.Value, + NoInject: !current.InjectIntoContainers, + }) + } + return result, current.AllEnvironments, nil +} + +func (s *Service) fetch(ctx context.Context, record SecretSource) ([]types.EnvVariable, error) { + config, err := configOf(record) + if err != nil { + return nil, err + } + entries, skipped, err := s.fetchConfig(ctx, record.ID, config) + status := map[string]any{ + "last_error": "", + "last_fetched_at": time.Now(), + "last_key_count": len(entries), + "last_skipped_key_count": skipped, + } + if err != nil { + status = map[string]any{"last_error": err.Error()} + slog.WarnContext(ctx, "Secret source fetch failed", "secretSourceId", record.ID, "error", err) + } + if updateErr := s.db.WithContext(ctx).Model(&SecretSource{}).Where("id = ?", record.ID).UpdateColumns(status).Error; updateErr != nil { + slog.WarnContext(ctx, "Failed to record secret source fetch status", "secretSourceId", record.ID, "error", updateErr) + } + if err != nil { + return nil, err + } + s.entries.Set(cache.Entry[string, []types.EnvVariable]{ + Key: record.ID, + Value: entries, + }) + return entries, nil +} + +func (s *Service) fetchConfig(ctx context.Context, sourceID string, config sourceConfig) ([]types.EnvVariable, int, error) { + entries, err := s.engine.Fetch(ctx, secretsource.Request{ + Definition: config.definition, + Inputs: config.inputs, + Credentials: config.credentials, + SourceID: sourceID, + Path: config.path, + }) + if err != nil { + return nil, 0, err + } + + accepted := make([]types.EnvVariable, 0, len(entries)) + for _, entry := range entries { + key := config.keyPrefix + strings.TrimSpace(entry.Key) + if projects.EnvKeyPattern.MatchString(key) { + accepted = append(accepted, types.EnvVariable{ + Key: key, + Value: entry.Value, + }) + } + } + return accepted, len(entries) - len(accepted), nil +} + +func (s *Service) mergeConfig(base sourceConfig, input types.SecretSourceInput, submitted map[string]bool) (sourceConfig, error) { + definition := base.definition + switch { + case submitted["definition"] && strings.TrimSpace(input.Definition) != "": + parsed, err := s.ValidateDefinition(input.Definition) + if err != nil { + return sourceConfig{}, err + } + definition = parsed + case submitted["presetId"] && strings.TrimSpace(input.PresetID) != "": + presets, err := s.Presets() + if err != nil { + return sourceConfig{}, err + } + index := slices.IndexFunc(presets, func(preset types.SecretSourcePreset) bool { + return preset.Definition.ID == strings.TrimSpace(input.PresetID) + }) + if index < 0 { + return sourceConfig{}, common.Classify(common.ErrValidation, &types.FieldError{Field: "presetId", Err: fmt.Errorf("unknown preset %q", input.PresetID)}) + } + definition = presets[index].Definition + } + if definition.Kind == "" { + return sourceConfig{}, common.Classify(common.ErrValidation, &types.FieldError{Field: "definition", Err: errors.New("a presetId or definition is required")}) + } + + inputs := base.inputs + if submitted["inputs"] { + inputs = make(map[string]string, len(input.Inputs)) + for key, value := range input.Inputs { + if trimmed := strings.TrimSpace(value); trimmed != "" { + inputs[key] = trimmed + } + } + } + presetID := kit.Ternary(submitted["presetId"], strings.TrimSpace(input.PresetID), base.presetID) + retargeted := presetID != base.presetID || + !sameDefinition(definition, base.definition) || + inputs[secretsource.BaseURLInput] != base.inputs[secretsource.BaseURLInput] || + (definition.Kind == secretsource.KindContainer && !maps.Equal(inputs, base.inputs)) + credentials := make(map[string]string, len(definition.Credentials)) + for _, field := range definition.Credentials { + if stored, kept := base.credentials[field.Key]; kept && !retargeted { + credentials[field.Key] = stored + } + } + if submitted["credentials"] { + for key, value := range input.Credentials { + if value == "" { + delete(credentials, key) + continue + } + credentials[key] = value + } + } + + config := sourceConfig{ + definition: definition, + inputs: inputs, + credentials: credentials, + presetID: presetID, + path: kit.Ternary(submitted["path"], strings.TrimSpace(input.Path), base.path), + keyPrefix: kit.Ternary(submitted["keyPrefix"], strings.TrimSpace(input.KeyPrefix), base.keyPrefix), + } + if err := secretsource.ValidateValues(secretsource.Request{ + Definition: config.definition, + Inputs: config.inputs, + Credentials: config.credentials, + Path: config.path, + }); err != nil { + return sourceConfig{}, common.Classify(common.ErrValidation, err) + } + if config.keyPrefix != "" && !projects.EnvKeyPattern.MatchString(config.keyPrefix) { + return sourceConfig{}, common.Classify(common.ErrValidation, &types.FieldError{Field: "keyPrefix", Err: fmt.Errorf("invalid key prefix %q", config.keyPrefix)}) + } + return config, nil +} + +func (s *Service) load(ctx context.Context, id string) (SecretSource, error) { + var record SecretSource + err := s.db.WithContext(ctx).Preload("Environments").First(&record, "id = ?", id).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return SecretSource{}, ErrSecretSourceNotFound + } + if err != nil { + return SecretSource{}, fmt.Errorf("failed to load secret source: %w", err) + } + return record, nil +} + +func configOf(record SecretSource) (sourceConfig, error) { + var definition types.SecretSourceDefinition + if err := json.Unmarshal([]byte(record.Definition), &definition); err != nil { + return sourceConfig{}, fmt.Errorf("failed to decode secret source definition: %w", err) + } + credentials := map[string]string{} + if record.Credentials != "" { + decrypted, decryptErr := crypto.Decrypt(record.Credentials) + if decryptErr != nil { + return sourceConfig{}, fmt.Errorf("failed to decrypt secret source credentials: %w", decryptErr) + } + if unmarshalErr := json.Unmarshal([]byte(decrypted), &credentials); unmarshalErr != nil { + return sourceConfig{}, fmt.Errorf("failed to decode secret source credentials: %w", unmarshalErr) + } + } + return sourceConfig{ + definition: definition, + inputs: record.Inputs, + credentials: credentials, + presetID: record.PresetID, + path: record.Path, + keyPrefix: record.KeyPrefix, + }, nil +} + +func encodeConfig(config sourceConfig) (string, string, error) { + definition, err := json.Marshal(config.definition, json.Deterministic(true)) + if err != nil { + return "", "", fmt.Errorf("failed to encode secret source definition: %w", err) + } + if len(config.credentials) == 0 { + return string(definition), "", nil + } + credentials, err := json.Marshal(config.credentials, json.Deterministic(true)) + if err != nil { + return "", "", fmt.Errorf("failed to encode secret source credentials: %w", err) + } + encrypted, err := crypto.Encrypt(string(credentials)) + if err != nil { + return "", "", fmt.Errorf("failed to encrypt secret source credentials: %w", err) + } + return string(definition), encrypted, nil +} + +func sameDefinition(a, b types.SecretSourceDefinition) bool { + encodedA, errA := json.Marshal(a, json.Deterministic(true)) + encodedB, errB := json.Marshal(b, json.Deterministic(true)) + return errA == nil && errB == nil && bytes.Equal(encodedA, encodedB) +} + +func sameFetch(a, b sourceConfig) bool { + return a.presetID == b.presetID && + sameDefinition(a.definition, b.definition) && + a.path == b.path && + a.keyPrefix == b.keyPrefix && + maps.Equal(a.inputs, b.inputs) && + maps.Equal(a.credentials, b.credentials) +} + +func toDTO(record SecretSource) (types.SecretSource, error) { + config, err := configOf(record) + if err != nil { + return types.SecretSource{}, err + } + return types.SecretSource{ + CreatedAt: record.CreatedAt, + UpdatedAt: record.UpdatedAt, + LastFetchedAt: record.LastFetchedAt, + ID: record.ID, + Name: record.Name, + Kind: record.Kind, + PresetID: record.PresetID, + Definition: config.definition, + Inputs: record.Inputs, + CredentialKeys: slices.Sorted(maps.Keys(config.credentials)), + Path: record.Path, + KeyPrefix: record.KeyPrefix, + EnvironmentIDs: environment.IDs(record.Environments), + LastError: record.LastError, + LastKeyCount: record.LastKeyCount, + LastSkippedKeyCount: record.LastSkippedKeyCount, + AllEnvironments: record.AllEnvironments, + InjectIntoContainers: record.InjectIntoContainers, + Enabled: record.Enabled, + }, nil +} diff --git a/backend/internal/variable/children/source/service_test.go b/backend/internal/variable/children/source/service_test.go new file mode 100644 index 0000000000..a8e9e48658 --- /dev/null +++ b/backend/internal/variable/children/source/service_test.go @@ -0,0 +1,97 @@ +package source + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/libtnb/sqlite" + mobyClient "github.com/moby/moby/client" + "github.com/stretchr/testify/require" + "gorm.io/gorm" + + "kit.getarcane.app/sys/crypto" + + "getarcane.dev/arcane/v3/internal/database" + "getarcane.dev/arcane/v3/internal/environment" + "getarcane.dev/types/v3" +) + +func unavailableDocker(context.Context) (*mobyClient.Client, error) { + return nil, errors.New("docker is not available in tests") +} + +func serveSecrets(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/secrets" || r.Header.Get("Authorization") != "Bearer secret-token" { + w.WriteHeader(http.StatusUnauthorized) + return + } + if _, err := w.Write([]byte(`{"DB_PASSWORD": "pw", "bad-key": "x"}`)); err != nil { + panic(err) + } +} + +func TestSecretSource_PresetFetchesKeysForScopedEnvironment(t *testing.T) { + ctx := t.Context() + db, err := gorm.Open(sqlite.Open("file:secret-source-test?mode=memory&cache=shared"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(&SecretSource{}, &environment.Environment{})) + sqlDB, err := db.DB() + require.NoError(t, err) + sqlDB.SetMaxOpenConns(1) + crypto.InitEncryption(crypto.Config{ + EncryptionKey: "test-encryption-key-for-testing-32bytes-min", + Environment: "test", + }) + dbWrap := &database.DB{DB: db} + require.NoError(t, dbWrap.Create(&environment.Environment{ + ID: "1", + Name: "one", + ApiUrl: "http://one", + Enabled: true, + }).Error) + server := httptest.NewServer(http.HandlerFunc(serveSecrets)) + t.Cleanup(server.Close) + service := NewService(ServiceParams{ + DB: dbWrap, + DockerClient: unavailableDocker, + }) + + created, err := service.Create(ctx, types.SecretSourceInput{ + Name: "vault", + PresetID: "generic-http-json", + Inputs: map[string]string{"baseUrl": server.URL, "endpoint": "/secrets"}, + Credentials: map[string]string{"token": "secret-token"}, + KeyPrefix: "APP_", + EnvironmentIDs: []string{"1"}, + }, map[string]bool{ + "name": true, + "presetId": true, + "inputs": true, + "credentials": true, + "keyPrefix": true, + "environmentIds": true, + }) + require.NoError(t, err) + require.Equal(t, []string{"token"}, created.CredentialKeys) + require.Equal(t, 1, created.LastKeyCount) + require.Equal(t, 1, created.LastSkippedKeyCount) + + var stored SecretSource + require.NoError(t, db.First(&stored, "id = ?", created.ID).Error) + require.NotContains(t, stored.Credentials, "secret-token") + + layers, err := service.EffectiveLayers(ctx, "1") + require.NoError(t, err) + require.Equal(t, [][]types.EnvVariable{{{ + Key: "APP_DB_PASSWORD", + Value: "pw", + NoInject: true, + }}}, layers) + + layers, err = service.EffectiveLayers(ctx, "2") + require.NoError(t, err) + require.Empty(t, layers) +} diff --git a/backend/internal/variable/module.go b/backend/internal/variable/module.go index 90b85f30dd..3262df67d5 100644 --- a/backend/internal/variable/module.go +++ b/backend/internal/variable/module.go @@ -1,11 +1,14 @@ package variable import ( + "cmp" + "github.com/danielgtaylor/huma/v2" "getarcane.dev/arcane/v3/internal/config" "getarcane.dev/arcane/v3/internal/environment" "getarcane.dev/arcane/v3/internal/middleware" + "getarcane.dev/arcane/v3/internal/variable/children/source" "getarcane.dev/arcane/v3/pkg/authz" "getarcane.dev/arcane/v3/pkg/handlerutil" ) @@ -106,6 +109,8 @@ func RegisterVariables(api huma.API, variableService *VariableService, proxyRemo Tags: []string{"Variables"}, Security: handlerutil.DefaultOperationSecurity(), }, authz.PermVariablesRead, h.GetSyncStatus) + + source.RegisterRoutes(api, source.NewHandler(cmp.Or(variableService, &VariableService{}).sources, variableService.SyncAllBackground)) } func RegisterMaterializedVariables(api huma.API, variableService *VariableService, proxyRemoteJSON handlerutil.RemoteJSONProxy) { diff --git a/backend/internal/variable/service.go b/backend/internal/variable/service.go index 9ad7fe451a..cce26e7845 100644 --- a/backend/internal/variable/service.go +++ b/backend/internal/variable/service.go @@ -12,7 +12,6 @@ import ( "net/http" "os" "path/filepath" - "regexp" "slices" "strings" "sync" @@ -31,9 +30,11 @@ import ( "getarcane.dev/arcane/v3/internal/common" "getarcane.dev/arcane/v3/internal/database" + dockerInternal "getarcane.dev/arcane/v3/internal/docker" "getarcane.dev/arcane/v3/internal/environment" "getarcane.dev/arcane/v3/internal/kv" "getarcane.dev/arcane/v3/internal/settings" + "getarcane.dev/arcane/v3/internal/variable/children/source" "getarcane.dev/arcane/v3/pkg/agent" "getarcane.dev/arcane/v3/pkg/projects" "getarcane.dev/types/v3" @@ -46,6 +47,7 @@ type ( tunnels *agent.TunnelRegistry settingsService *settings.SettingsService kvService *kv.KVService + sources *source.Service syncStatus map[string]types.EnvironmentSyncStatus importLocks concurrency.KeyedMutex @@ -65,6 +67,7 @@ type ( Tunnels *agent.TunnelRegistry SettingsService *settings.SettingsService KVService *kv.KVService + DockerService *dockerInternal.DockerClientService } ) @@ -74,10 +77,13 @@ const ( variableSyncTimeout = 15 * time.Second ) -var envKeyPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) +var variableScope = environment.ScopeTable{ + Table: "global_variable_environments", + OwnerColumn: "global_variable_id", +} func validateVariableKey(key string) error { - if envKeyPattern.MatchString(key) { + if projects.EnvKeyPattern.MatchString(key) { return nil } return common.Classify(common.ErrInvalidEnvKey, &types.FieldError{Field: "key", Err: fmt.Errorf("invalid key %q: use letters, numbers, and underscores, and do not start with a number", key)}) @@ -91,7 +97,11 @@ func NewVariableService(p VariableServiceParams) *VariableService { tunnels: p.Tunnels, settingsService: p.SettingsService, kvService: p.KVService, - syncStatus: make(map[string]types.EnvironmentSyncStatus), + sources: source.NewService(source.ServiceParams{ + DB: p.DB, + DockerClient: p.DockerService.GetClient, + }), + syncStatus: make(map[string]types.EnvironmentSyncStatus), } } @@ -114,7 +124,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, req types.GlobalVa return nil, validateKeyErr } - envIDs, err := s.normalizeScope(ctx, req.AllEnvironments, req.EnvironmentIDs) + envIDs, err := environment.NormalizeScope(ctx, s.db, req.AllEnvironments, req.EnvironmentIDs) if err != nil { return nil, err } @@ -142,7 +152,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, req types.GlobalVa if createVariableErr := tx.Omit("Environments").Create(&variable).Error; createVariableErr != nil { return fmt.Errorf("failed to create global variable: %w", createVariableErr) } - return replaceVariableScopeRows(tx, variable.ID, envIDs) + return variableScope.Replace(tx, variable.ID, envIDs) }) if err != nil { return nil, wrapVariableMutationError(err) @@ -174,7 +184,13 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req typ return nil, err } - envIDs, allEnvironments, err := s.resolveUpdatedScope(ctx, &variable, req, submitted) + envIDs, allEnvironments, err := environment.ResolveScope(ctx, s.db, environment.ScopeChange{ + Submitted: submitted, + Current: variable.Environments, + EnvironmentIDs: req.EnvironmentIDs, + AllEnvironments: req.AllEnvironments, + CurrentAll: variable.AllEnvironments, + }) if err != nil { return nil, err } @@ -192,7 +208,7 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req typ if updateVariableErr := tx.Omit("Environments").Save(&variable).Error; updateVariableErr != nil { return fmt.Errorf("failed to update global variable: %w", updateVariableErr) } - return replaceVariableScopeRows(tx, variable.ID, envIDs) + return variableScope.Replace(tx, variable.ID, envIDs) }) if err != nil { return nil, wrapVariableMutationError(err) @@ -235,23 +251,6 @@ func resolveUpdatedValue(variable *GlobalVariable, reqValue string, valueSubmitt } } -func (s *VariableService) resolveUpdatedScope(ctx context.Context, variable *GlobalVariable, req types.GlobalVariable, submitted map[string]bool) ([]string, bool, error) { - envIDs := scopedEnvironmentIDs(variable.Environments) - if !submitted["allEnvironments"] && !submitted["environmentIds"] { - return envIDs, variable.AllEnvironments, nil - } - - normalized, err := s.normalizeScope( - ctx, - kit.Ternary(submitted["allEnvironments"], req.AllEnvironments, variable.AllEnvironments), - kit.Ternary(submitted["environmentIds"], req.EnvironmentIDs, envIDs), - ) - if err != nil { - return nil, false, err - } - return normalized, len(normalized) == 0, nil -} - func (s *VariableService) DeleteVariable(ctx context.Context, id string) error { err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { result := tx.Delete(&GlobalVariable{}, "id = ?", id) @@ -274,13 +273,20 @@ func (s *VariableService) resolveEffectiveVariables(ctx context.Context, envID s if err != nil { return nil, err } + layers, err := s.sources.EffectiveLayers(ctx, envID) + if err != nil { + return nil, fmt.Errorf("failed to resolve secret sources: %w", err) + } + return mergeVariableLayers(append(layers, explicitVariables(ctx, variables, envID))...), nil +} +func explicitVariables(ctx context.Context, variables []GlobalVariable, envID string) []types.EnvVariable { result := make([]types.EnvVariable, 0, len(variables)) positions := make(map[string]int, len(variables)) scopedKeys := make(map[string]bool) for _, variable := range variables { scoped := !variable.AllEnvironments - if scoped && !slices.Contains(scopedEnvironmentIDs(variable.Environments), envID) { + if scoped && !slices.Contains(environment.IDs(variable.Environments), envID) { continue } if !scoped && scopedKeys[variable.Key] { @@ -309,7 +315,35 @@ func (s *VariableService) resolveEffectiveVariables(ctx context.Context, envID s } scopedKeys[variable.Key] = scopedKeys[variable.Key] || scoped } - return result, nil + return result +} + +func mergeVariableLayers(layers ...[]types.EnvVariable) []types.EnvVariable { + var merged []types.EnvVariable + positions := make(map[string]int) + for _, layer := range layers { + for _, entry := range layer { + if index, ok := positions[entry.Key]; ok { + merged[index] = entry + continue + } + positions[entry.Key] = len(merged) + merged = append(merged, entry) + } + } + return merged +} + +func (s *VariableService) GetSecretSource(ctx context.Context, id string) (types.SecretSource, error) { + return s.sources.Get(ctx, id) +} + +func (s *VariableService) RefreshSecretSource(ctx context.Context, id string) error { + if _, err := s.sources.Refresh(ctx, id); err != nil { + return err + } + s.SyncAllBackground(ctx) + return nil } func (s *VariableService) SyncEnvironment(ctx context.Context, envID string) error { @@ -650,14 +684,14 @@ func (s *VariableService) importVariables(ctx context.Context, vars []types.EnvV covered := make(map[string]bool, len(existing)) for _, variable := range existing { if variable.AllEnvironments || scopeEnvID == "" || - slices.Contains(scopedEnvironmentIDs(variable.Environments), scopeEnvID) { + slices.Contains(environment.IDs(variable.Environments), scopeEnvID) { covered[variable.Key] = true } } for _, entry := range vars { key := strings.TrimSpace(entry.Key) - if key == "" || covered[key] || !envKeyPattern.MatchString(key) { + if key == "" || covered[key] || !projects.EnvKeyPattern.MatchString(key) { continue } @@ -674,7 +708,7 @@ func (s *VariableService) importVariables(ctx context.Context, vars []types.EnvV if scopeEnvID == "" { return nil } - return replaceVariableScopeRows(tx, variable.ID, []string{scopeEnvID}) + return variableScope.Replace(tx, variable.ID, []string{scopeEnvID}) }) if transactionErr != nil { return fmt.Errorf("failed to import legacy variable %q: %w", key, transactionErr) @@ -694,42 +728,6 @@ func (s *VariableService) loadVariables(ctx context.Context) ([]GlobalVariable, return variables, nil } -func (s *VariableService) normalizeScope(ctx context.Context, allEnvironments bool, envIDs []string) ([]string, error) { - if allEnvironments { - return nil, nil - } - - unique := make([]string, 0, len(envIDs)) - for _, id := range envIDs { - id = strings.TrimSpace(id) - if id != "" && !slices.Contains(unique, id) { - unique = append(unique, id) - } - } - // An explicitly specific scope with no environments must not silently - // widen to all environments. - if len(unique) == 0 { - return nil, common.Classify( - common.ErrGlobalVariableScopeRequired, - errors.New( - "at least one environment is required when a variable is not scoped to all environments", - ), - ) - } - - var count int64 - if err := s.db.WithContext(ctx).Model(&environment.Environment{}).Where("id IN ?", unique).Count(&count).Error; err != nil { - return nil, fmt.Errorf("failed to update global variables: %w", err) - } - if count != int64(len(unique)) { - return nil, common.Classify( - common.ErrGlobalVariableUnknownEnvironment, - errors.New("failed to update global variables: one or more environments do not exist"), - ) - } - return unique, nil -} - func (s *VariableService) validateScopeConflict(tx *gorm.DB, key, excludeID string, allEnvironments bool, envIDs []string) error { var others []GlobalVariable query := tx.Preload("Environments").Where("key = ?", key) @@ -753,7 +751,7 @@ func (s *VariableService) validateScopeConflict(tx *gorm.DB, key, excludeID stri ), ) } - otherIDs := scopedEnvironmentIDs(other.Environments) + otherIDs := environment.IDs(other.Environments) for _, id := range envIDs { if slices.Contains(otherIDs, id) { return common.Classify( @@ -769,18 +767,6 @@ func (s *VariableService) validateScopeConflict(tx *gorm.DB, key, excludeID stri return nil } -func replaceVariableScopeRows(tx *gorm.DB, variableID string, envIDs []string) error { - if err := tx.Exec("DELETE FROM global_variable_environments WHERE global_variable_id = ?", variableID).Error; err != nil { - return fmt.Errorf("failed to clear variable scope: %w", err) - } - for _, envID := range envIDs { - if err := tx.Exec("INSERT INTO global_variable_environments (global_variable_id, environment_id) VALUES (?, ?)", variableID, envID).Error; err != nil { - return fmt.Errorf("failed to set variable scope: %w", err) - } - } - return nil -} - func wrapVariableMutationError(err error) error { if err == nil || errors.Is(err, common.ErrGlobalVariableConflict) || errors.Is(err, common.ErrGlobalVariableNotFound) || errors.Is(err, common.ErrInvalidEnvKey) { return err @@ -788,14 +774,6 @@ func wrapVariableMutationError(err error) error { return fmt.Errorf("failed to update global variables: %w", err) } -func scopedEnvironmentIDs(environments []environment.Environment) []string { - ids := make([]string, 0, len(environments)) - for _, environment := range environments { - ids = append(ids, environment.ID) - } - return ids -} - func environmentsFromIDs(envIDs []string) []environment.Environment { environments := make([]environment.Environment, 0, len(envIDs)) for _, id := range envIDs { @@ -813,7 +791,7 @@ func globalVariableToDTO(variable GlobalVariable) types.GlobalVariable { IsSecret: variable.IsSecret, AllEnvironments: variable.AllEnvironments, InjectIntoContainers: variable.InjectIntoContainers, - EnvironmentIDs: scopedEnvironmentIDs(variable.Environments), + EnvironmentIDs: environment.IDs(variable.Environments), CreatedAt: variable.CreatedAt, UpdatedAt: variable.UpdatedAt, } diff --git a/backend/internal/variable/service_test.go b/backend/internal/variable/service_test.go index 73629b8ee1..f0a1f2cb98 100644 --- a/backend/internal/variable/service_test.go +++ b/backend/internal/variable/service_test.go @@ -25,6 +25,7 @@ import ( "getarcane.dev/arcane/v3/internal/environment" "getarcane.dev/arcane/v3/internal/kv" "getarcane.dev/arcane/v3/internal/settings" + "getarcane.dev/arcane/v3/internal/variable/children/source" "getarcane.dev/arcane/v3/pkg/agent" "getarcane.dev/arcane/v3/pkg/projects" "getarcane.dev/types/v3" @@ -65,6 +66,7 @@ func setupVariableServiceTest(t *testing.T, environments environment.RemoteProxy require.NoError(t, err) require.NoError(t, db.AutoMigrate( &GlobalVariable{}, + &source.SecretSource{}, &environment.Environment{}, &kv.KVEntry{}, &settings.SettingVariable{}, diff --git a/backend/internal/webhook/model.go b/backend/internal/webhook/model.go index 631315575e..fda7cdde38 100644 --- a/backend/internal/webhook/model.go +++ b/backend/internal/webhook/model.go @@ -25,19 +25,21 @@ type ( ) const ( - WebhookTargetTypeContainer = "container" - WebhookTargetTypeProject = "project" - WebhookTargetTypeUpdater = "updater" - WebhookTargetTypeGitOps = "gitops" - WebhookActionTypeUpdate = "update" - WebhookActionTypeStart = "start" - WebhookActionTypeStop = "stop" - WebhookActionTypeRestart = "restart" - WebhookActionTypeRedeploy = "redeploy" - WebhookActionTypeUp = "up" - WebhookActionTypeDown = "down" - WebhookActionTypeRun = "run" - WebhookActionTypeSync = "sync" + WebhookTargetTypeContainer = "container" + WebhookTargetTypeProject = "project" + WebhookTargetTypeUpdater = "updater" + WebhookTargetTypeGitOps = "gitops" + WebhookTargetTypeSecretSource = "secretsource" + WebhookActionTypeUpdate = "update" + WebhookActionTypeStart = "start" + WebhookActionTypeStop = "stop" + WebhookActionTypeRestart = "restart" + WebhookActionTypeRedeploy = "redeploy" + WebhookActionTypeUp = "up" + WebhookActionTypeDown = "down" + WebhookActionTypeRun = "run" + WebhookActionTypeSync = "sync" + WebhookActionTypeRefresh = "refresh" ) func (Webhook) TableName() string { diff --git a/backend/internal/webhook/service.go b/backend/internal/webhook/service.go index 43f9935de8..23dc38641f 100644 --- a/backend/internal/webhook/service.go +++ b/backend/internal/webhook/service.go @@ -36,6 +36,7 @@ import ( "getarcane.dev/arcane/v3/internal/gitops" "getarcane.dev/arcane/v3/internal/project" "getarcane.dev/arcane/v3/internal/updater" + "getarcane.dev/arcane/v3/internal/variable" activitylib "getarcane.dev/arcane/v3/pkg/activity" "getarcane.dev/arcane/v3/pkg/authz" "getarcane.dev/arcane/v3/pkg/pagination" @@ -77,6 +78,7 @@ type ( eventService *event.EventService activityService activitylib.Service environmentService *environment.EnvironmentService + variableService *variable.VariableService actions sync.WaitGroup tokenMu sync.RWMutex @@ -94,6 +96,7 @@ type ( EventService *event.EventService ActivityService activitylib.Service EnvironmentService *environment.EnvironmentService + VariableService *variable.VariableService } ) @@ -182,10 +185,11 @@ var ( ErrWebhookNotFound = common.Classify(common.ErrNotFound, errors.New("webhook not found")) ErrWebhookInvalid = errors.New("invalid webhook token") ErrWebhookDisabled = errors.New("webhook is disabled") - ErrWebhookInvalidType = common.Classify(common.ErrValidation, errors.New("invalid target type, must be 'container', 'project', 'updater', or 'gitops'")) + ErrWebhookInvalidType = common.Classify(common.ErrValidation, errors.New("invalid target type, must be 'container', 'project', 'updater', 'gitops', or 'secretsource'")) ErrWebhookInvalidAction = common.Classify(common.ErrValidation, errors.New("invalid action type for target type")) ErrWebhookMissingName = common.Classify(common.ErrValidation, errors.New("webhook name is required")) - ErrWebhookMissingTarget = common.Classify(common.ErrValidation, errors.New("target ID is required for container, project, and gitops webhook types")) + ErrWebhookMissingTarget = common.Classify(common.ErrValidation, errors.New("target ID is required for container, project, gitops, and secretsource webhook types")) + ErrWebhookSecretSourceLocal = common.Classify(common.ErrValidation, errors.New("secret source webhooks run on the manager; create them on the local environment")) ErrWebhookForbidden = common.Classify(common.ErrForbidden, errors.New("you do not have permission to run this webhook action")) remoteWebhookTargetListPaths = map[string]string{ WebhookTargetTypeProject: "/api/agents/" + types.LocalDockerEnvironmentID + "/projects/references", @@ -213,6 +217,9 @@ var ( WebhookTargetTypeGitOps: { WebhookActionTypeSync: {authz.PermGitOpsSync}, }, + WebhookTargetTypeSecretSource: { + WebhookActionTypeRefresh: {authz.PermVariablesSourcesRefresh}, + }, } containerWebhookActivities = map[string]webhookActivityConfig{ @@ -293,6 +300,7 @@ func NewWebhookService(p WebhookServiceParams) *WebhookService { eventService: p.EventService, activityService: p.ActivityService, environmentService: p.EnvironmentService, + variableService: p.VariableService, tokenHashes: make(map[string]struct{}), } } @@ -363,6 +371,8 @@ func defaultWebhookActionType(targetType string) (string, error) { return WebhookActionTypeRun, nil case WebhookTargetTypeGitOps: return WebhookActionTypeSync, nil + case WebhookTargetTypeSecretSource: + return WebhookActionTypeRefresh, nil default: return "", ErrWebhookInvalidType } @@ -370,7 +380,7 @@ func defaultWebhookActionType(targetType string) (string, error) { func resolveWebhookActionType(targetType, actionType string) (string, error) { switch targetType { - case WebhookTargetTypeContainer, WebhookTargetTypeProject, WebhookTargetTypeUpdater, WebhookTargetTypeGitOps: + case WebhookTargetTypeContainer, WebhookTargetTypeProject, WebhookTargetTypeUpdater, WebhookTargetTypeGitOps, WebhookTargetTypeSecretSource: default: return "", ErrWebhookInvalidType } @@ -403,6 +413,10 @@ func resolveWebhookActionType(targetType, actionType string) (string, error) { if normalizedActionType == WebhookActionTypeSync { return normalizedActionType, nil } + case WebhookTargetTypeSecretSource: + if normalizedActionType == WebhookActionTypeRefresh { + return normalizedActionType, nil + } } return "", ErrWebhookInvalidAction @@ -493,6 +507,14 @@ func (s *WebhookService) CreateWebhook( } else if strings.TrimSpace(targetID) == "" { return nil, "", ErrWebhookMissingTarget } + if targetType == WebhookTargetTypeSecretSource { + if environmentID != "" && environmentID != types.LocalDockerEnvironmentID { + return nil, "", ErrWebhookSecretSourceLocal + } + if _, sourceErr := s.variableService.GetSecretSource(ctx, targetID); sourceErr != nil { + return nil, "", sourceErr + } + } if targetType == WebhookTargetTypeGitOps { if modeErr := s.authorizeGitOpsSyncMode(ctx, callerPerms, environmentID, targetID); modeErr != nil { return nil, "", modeErr @@ -657,6 +679,9 @@ func (s *WebhookService) resolveWebhookTargetName(ctx context.Context, wh *Webho return "" } return localSync.Name + case WebhookTargetTypeSecretSource: + secretSource, _ := s.variableService.GetSecretSource(ctx, wh.TargetID) + return secretSource.Name default: return "" } @@ -871,6 +896,8 @@ func (s *WebhookService) executeWebhookAction(ctx context.Context, wh *Webhook, return s.executeUpdaterWebhookAction(ctx, wh, actionType) case WebhookTargetTypeGitOps: return s.executeGitOpsWebhookAction(ctx, wh, actionType) + case WebhookTargetTypeSecretSource: + return s.executeSecretSourceWebhookAction(ctx, wh, actionType) default: return nil, ErrWebhookInvalidType } @@ -1223,6 +1250,18 @@ func (s *WebhookService) executeGitOpsWebhookAction(ctx context.Context, wh *Web return nil, nil } +func (s *WebhookService) executeSecretSourceWebhookAction(ctx context.Context, wh *Webhook, actionType string) (*types.UpdaterResult, error) { + if actionType != WebhookActionTypeRefresh { + return nil, ErrWebhookInvalidAction + } + + if err := s.variableService.RefreshSecretSource(ctx, wh.TargetID); err != nil { + return nil, s.wrapWebhookActionError(ctx, wh, "secretsource", actionType, err) + } + + return nil, nil +} + func (s *WebhookService) wrapWebhookActionError(ctx context.Context, wh *Webhook, targetKind, actionType string, err error) error { msg := fmt.Sprintf("%s %s failed: %s", targetKind, actionType, err) s.logWebhookEvent(ctx, wh, actionType, event.EventSeverityError, msg) diff --git a/backend/pkg/authz/access_policy.go b/backend/pkg/authz/access_policy.go index f9bdd9c1e1..7c1745b9f1 100644 --- a/backend/pkg/authz/access_policy.go +++ b/backend/pkg/authz/access_policy.go @@ -108,7 +108,13 @@ var ( routeSurface("route.projects.templates.detail", "/projects/templates/{id}", "Template", AccessScopeModeGlobalOnly, []string{PermTemplatesList, PermTemplatesRead}, 0), routeSurface("route.images.registries", "/images/registries", "Container Registries", AccessScopeModeGlobalOnly, []string{PermRegistriesList, PermRegistriesRead}, 41), allOfRouteSurface("route.images.registries.browse", "/images/registries/{id}", "Registry browser", AccessScopeModeGlobalOnly, []string{PermRegistriesRead, PermRegistriesBrowse}), - routeSurface("route.projects.variables", "/projects/variables", "Variables", AccessScopeModeGlobalOnly, []string{PermVariablesList, PermVariablesRead}, 42), + routeSurface("route.projects.variables", "/projects/variables", "Variables & Secrets", AccessScopeModeGlobalOnly, []string{ + PermVariablesList, + PermVariablesRead, + PermVariablesSourcesList, + PermVariablesSourcesRead, + }, 42), + routeSurface("route.projects.variables.sources", "", "External Secrets", AccessScopeModeGlobalOnly, []string{PermVariablesSourcesList, PermVariablesSourcesRead}, 0), routeSurface("route.gitops.repositories", "/gitops/repositories", "Git Repositories", AccessScopeModeGlobalOnly, []string{PermGitReposList, PermGitReposRead}, 43), settingsCategorySurface("apikeys", "/system/api-keys", "API Keys", AccessScopeModeGlobalOnly, []string{PermApiKeysList, PermApiKeysRead}), diff --git a/backend/pkg/authz/access_policy_test.go b/backend/pkg/authz/access_policy_test.go index 7771b96159..0797ef2221 100644 --- a/backend/pkg/authz/access_policy_test.go +++ b/backend/pkg/authz/access_policy_test.go @@ -40,7 +40,7 @@ func TestAccessSurfaceRegistryDefinesSettingsCustomizeAndLandingSemantics(t *tes require.Equal(t, authz.AccessSurfaceKindRoute, variables.Kind) require.Equal(t, authz.AccessScopeModeGlobalOnly, variables.ScopeMode) require.Equal(t, authz.AccessMatchModeAnyOf, variables.MatchMode) - require.ElementsMatch(t, []string{authz.PermVariablesList, authz.PermVariablesRead}, variables.Permissions) + require.ElementsMatch(t, []string{authz.PermVariablesList, authz.PermVariablesRead, authz.PermVariablesSourcesList, authz.PermVariablesSourcesRead}, variables.Permissions) require.NotContains(t, variables.Permissions, authz.PermTemplatesRead) activities := requireAccessSurface(t, "route.activities") diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.go index 3938bdc507..089a480b9f 100644 --- a/backend/pkg/authz/catalog.go +++ b/backend/pkg/authz/catalog.go @@ -386,7 +386,7 @@ var permissionCatalog = []PermissionCatalogResource{ { Key: "variables", Label: "Variables", - Description: "Global variables shared with projects", + Description: "Global variables shared with projects and the external secrets that feed them", Scope: PermissionScopeGlobal, Actions: []PermissionCatalogAction{ { @@ -430,6 +430,47 @@ var permissionCatalog = []PermissionCatalogResource{ Description: "Sync global variables to environments", Requires: []string{PermVariablesRead}, }, + { + Key: "sources-list", + Permission: PermVariablesSourcesList, + Label: "List external secrets", + Description: "List secret sources and presets", + }, + { + Key: "sources-read", + Permission: PermVariablesSourcesRead, + Label: "Read external secrets", + Description: "View a secret source and its fetch status", + Requires: []string{PermVariablesSourcesList}, + }, + { + Key: "sources-create", + Permission: PermVariablesSourcesCreate, + Label: "Create external secrets", + Description: "Add secret sources, which can make the manager call remote APIs and run containers", + Requires: []string{PermVariablesSourcesRead}, + }, + { + Key: "sources-update", + Permission: PermVariablesSourcesUpdate, + Label: "Update external secrets", + Description: "Change secret sources and their credentials", + Requires: []string{PermVariablesSourcesRead}, + }, + { + Key: "sources-delete", + Permission: PermVariablesSourcesDelete, + Label: "Delete external secrets", + Description: "Remove secret sources", + Requires: []string{PermVariablesSourcesRead}, + }, + { + Key: "sources-refresh", + Permission: PermVariablesSourcesRefresh, + Label: "Refresh external secrets", + Description: "Test and refresh secret sources", + Requires: []string{PermVariablesSourcesRead}, + }, }, }, { diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.go index e328d40f6d..9b68602866 100644 --- a/backend/pkg/authz/permissions.go +++ b/backend/pkg/authz/permissions.go @@ -59,6 +59,12 @@ const ( PermVariablesUpdate = "variables:update" PermVariablesDelete = "variables:delete" PermVariablesSync = "variables:sync" + PermVariablesSourcesList = "variables:sources:list" + PermVariablesSourcesRead = "variables:sources:read" + PermVariablesSourcesCreate = "variables:sources:create" + PermVariablesSourcesUpdate = "variables:sources:update" + PermVariablesSourcesDelete = "variables:sources:delete" + PermVariablesSourcesRefresh = "variables:sources:refresh" PermGitReposList = "git-repositories:list" PermGitReposRead = "git-repositories:read" PermGitReposCreate = "git-repositories:create" diff --git a/backend/pkg/httpx/safe_remote.go b/backend/pkg/httpx/safe_remote.go index 3212c7e35a..3c32a1c447 100644 --- a/backend/pkg/httpx/safe_remote.go +++ b/backend/pkg/httpx/safe_remote.go @@ -19,29 +19,73 @@ import ( type ( LookupIPFunc func(ctx context.Context, host string) ([]net.IP, error) + + PrivateNetworkClientConfig struct { + Timeout time.Duration + ResponseHeaderTimeout time.Duration + } + + addressPolicy struct { + blockedPrefixes []netip.Prefix + blockedHosts []string + allowPrivate bool + } ) -// blockedRemotePrefixes lists special-use ranges the netip.Addr helpers in resolveAllowedIPs do not cover, -// keeping the SSRF policy reviewable in one place. -var blockedRemotePrefixes = []netip.Prefix{ - netip.MustParsePrefix("0.0.0.0/8"), - netip.MustParsePrefix("100.64.0.0/10"), - netip.MustParsePrefix("127.0.0.0/8"), - netip.MustParsePrefix("169.254.0.0/16"), - netip.MustParsePrefix("192.0.0.0/24"), - netip.MustParsePrefix("192.0.2.0/24"), - netip.MustParsePrefix("198.18.0.0/15"), - netip.MustParsePrefix("198.51.100.0/24"), - netip.MustParsePrefix("203.0.113.0/24"), - netip.MustParsePrefix("224.0.0.0/4"), - netip.MustParsePrefix("240.0.0.0/4"), - netip.MustParsePrefix("::/128"), - netip.MustParsePrefix("::1/128"), - netip.MustParsePrefix("2001:db8::/32"), - netip.MustParsePrefix("fc00::/7"), - netip.MustParsePrefix("fe80::/10"), - netip.MustParsePrefix("ff00::/8"), -} +var ( + // blockedRemotePrefixes lists special-use ranges the netip.Addr helpers in resolveAllowedIPs do not cover, + // keeping the SSRF policy reviewable in one place. + blockedRemotePrefixes = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), + netip.MustParsePrefix("100.64.0.0/10"), + netip.MustParsePrefix("127.0.0.0/8"), + netip.MustParsePrefix("169.254.0.0/16"), + netip.MustParsePrefix("192.0.0.0/24"), + netip.MustParsePrefix("192.0.2.0/24"), + netip.MustParsePrefix("198.18.0.0/15"), + netip.MustParsePrefix("198.51.100.0/24"), + netip.MustParsePrefix("203.0.113.0/24"), + netip.MustParsePrefix("224.0.0.0/4"), + netip.MustParsePrefix("240.0.0.0/4"), + netip.MustParsePrefix("::/128"), + netip.MustParsePrefix("::1/128"), + netip.MustParsePrefix("2001:db8::/32"), + netip.MustParsePrefix("fc00::/7"), + netip.MustParsePrefix("fe80::/10"), + netip.MustParsePrefix("ff00::/8"), + } + + privateNetworkBlockedPrefixes = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), + netip.MustParsePrefix("100.100.100.200/32"), + netip.MustParsePrefix("168.63.129.16/32"), + netip.MustParsePrefix("169.254.0.0/16"), + netip.MustParsePrefix("240.0.0.0/4"), + netip.MustParsePrefix("fd00:ec2::254/128"), + netip.MustParsePrefix("fe80::/10"), + } + + nat64Prefix = netip.MustParsePrefix("64:ff9b::/96") + sixToFourPrefix = netip.MustParsePrefix("2002::/16") + + metadataHostnames = []string{ + "metadata", + "metadata.goog", + "metadata.google.internal", + "instance-data", + "instance-data.ec2.internal", + } + + publicOnlyPolicy = addressPolicy{ + blockedPrefixes: blockedRemotePrefixes, + } + + privateNetworkPolicy = addressPolicy{ + blockedPrefixes: privateNetworkBlockedPrefixes, + blockedHosts: metadataHostnames, + allowPrivate: true, + } +) func unsafeRemoteURLError(err error) error { return common.Classify( @@ -61,7 +105,7 @@ func ValidateSafeRemoteURL(ctx context.Context, rawURL string, lookupIP LookupIP return nil, unsafeRemoteURLError(errors.New("missing or blocked hostname")) } - if _, err = resolveAllowedIPs(ctx, parsed.Hostname(), lookupIP); err != nil { + if _, err = resolveAllowedIPs(ctx, parsed.Hostname(), lookupIP, publicOnlyPolicy); err != nil { return nil, err } return parsed, nil @@ -88,27 +132,7 @@ func NewSafeOutboundHTTPClient(base *http.Client, lookupIP LookupIPFunc) (*http. baseDial = dialer.DialContext } - transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) { - host, port, err := net.SplitHostPort(address) - if err != nil { - return nil, unsafeRemoteURLError(err) - } - - ips, err := resolveAllowedIPs(ctx, host, lookupIP) - if err != nil { - return nil, err - } - - var dialErr error - for _, ip := range ips { - conn, connErr := baseDial(ctx, network, net.JoinHostPort(ip.String(), port)) - if connErr == nil { - return conn, nil - } - dialErr = connErr - } - return nil, dialErr - } + transport.DialContext = guardedDialContext(baseDial, lookupIP, publicOnlyPolicy) return &http.Client{ // Instrumented after the SSRF dialer is installed; the wrapper never dials itself. @@ -130,7 +154,62 @@ func NewSafeOutboundHTTPClient(base *http.Client, lookupIP LookupIPFunc) (*http. }, nil } -func resolveAllowedIPs(ctx context.Context, host string, lookupIP LookupIPFunc) ([]net.IP, error) { +func NewPrivateNetworkHTTPClient(cfg PrivateNetworkClientConfig) *http.Client { + dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second} + return &http.Client{ + Transport: otelhttp.NewTransport(NewTransport(TransportConfig{ + DialContext: guardedDialContext(dialer.DialContext, nil, privateNetworkPolicy), + ResponseHeaderTimeout: cfg.ResponseHeaderTimeout, + DisableProxy: true, + })), + Timeout: max(cfg.Timeout, 0), + CheckRedirect: sameOriginRedirect, + } +} + +func sameOriginRedirect(req *http.Request, via []*http.Request) error { + if len(via) >= 5 { + return errors.New("stopped after 5 redirects") + } + if !strings.EqualFold(req.URL.Host, via[0].URL.Host) || !strings.EqualFold(req.URL.Scheme, via[0].URL.Scheme) { + return common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("redirect to a different host is not allowed: %s", req.URL.Host)) + } + return nil +} + +func guardedDialContext( + baseDial func(ctx context.Context, network, address string) (net.Conn, error), + lookupIP LookupIPFunc, + policy addressPolicy, +) func(ctx context.Context, network, address string) (net.Conn, error) { + return func(ctx context.Context, network, address string) (net.Conn, error) { + host, port, err := net.SplitHostPort(address) + if err != nil { + return nil, unsafeRemoteURLError(err) + } + + ips, err := resolveAllowedIPs(ctx, host, lookupIP, policy) + if err != nil { + return nil, err + } + + var dialErr error + for _, ip := range ips { + conn, connErr := baseDial(ctx, network, net.JoinHostPort(ip.String(), port)) + if connErr == nil { + return conn, nil + } + dialErr = connErr + } + return nil, dialErr + } +} + +func resolveAllowedIPs(ctx context.Context, host string, lookupIP LookupIPFunc, policy addressPolicy) ([]net.IP, error) { + if slices.Contains(policy.blockedHosts, strings.TrimSuffix(strings.ToLower(host), ".")) { + return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("blocked hostname %s", host)) + } + literal, _, _ := strings.Cut(host, "%") ips := []net.IP{net.ParseIP(literal)} if ips[0] == nil { @@ -152,9 +231,7 @@ func resolveAllowedIPs(ctx context.Context, host string, lookupIP LookupIPFunc) } addr, ok := netip.AddrFromSlice(ip) addr = addr.Unmap() - blocked := !ok || addr.IsLoopback() || addr.IsPrivate() || addr.IsMulticast() || addr.IsUnspecified() || - addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() || slices.ContainsFunc(blockedRemotePrefixes, func(p netip.Prefix) bool { return p.Contains(addr) }) - if blocked { + if !ok || policy.blocks(addr) || policy.blocks(embeddedIPv4(addr)) { return nil, unsafeRemoteURLError(fmt.Errorf("blocked IP address %s", ip)) } allowed = append(allowed, ip) @@ -165,3 +242,23 @@ func resolveAllowedIPs(ctx context.Context, host string, lookupIP LookupIPFunc) } return allowed, nil } + +func (p addressPolicy) blocks(addr netip.Addr) bool { + return addr.IsMulticast() || addr.IsUnspecified() || addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() || + (!p.allowPrivate && (addr.IsLoopback() || addr.IsPrivate())) || + slices.ContainsFunc(p.blockedPrefixes, func(prefix netip.Prefix) bool { + return prefix.Contains(addr) + }) +} + +func embeddedIPv4(addr netip.Addr) netip.Addr { + raw := addr.As16() + switch { + case nat64Prefix.Contains(addr): + return netip.AddrFrom4([4]byte(raw[12:16])) + case sixToFourPrefix.Contains(addr): + return netip.AddrFrom4([4]byte(raw[2:6])) + default: + return addr + } +} diff --git a/backend/pkg/projects/env.go b/backend/pkg/projects/env.go index ddea5b9836..8ae2607282 100644 --- a/backend/pkg/projects/env.go +++ b/backend/pkg/projects/env.go @@ -103,6 +103,7 @@ var ( processEnvAllowlist = []string{"TZ", "LANG", "LANGUAGE", "LC_ALL"} envKeyLineRegex = regexp.MustCompile(`^(\s*(?:export\s+)?)([A-Za-z_][A-Za-z0-9_.-]*)(\s*=)(.*)$`) + EnvKeyPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) ) func NewEnvLoader(projectsDir, workdir string, autoInjectEnv bool) *EnvLoader { diff --git a/backend/pkg/secretsource/container.go b/backend/pkg/secretsource/container.go new file mode 100644 index 0000000000..73cd67eee0 --- /dev/null +++ b/backend/pkg/secretsource/container.go @@ -0,0 +1,149 @@ +package secretsource + +import ( + "cmp" + "context" + "encoding/json/jsontext" + "errors" + "fmt" + "io" + "log/slog" + "maps" + "slices" + "strings" + + cerrdefs "github.com/containerd/errdefs" + mobyContainer "github.com/moby/moby/api/types/container" + mobyClient "github.com/moby/moby/client" + + "kit.getarcane.app/capture" + "kit.getarcane.app/docker" + + "getarcane.dev/arcane/v3/pkg/projects" + "getarcane.dev/arcane/v3/pkg/selfcontainer" + "getarcane.dev/arcane/v3/pkg/timeouts" + "getarcane.dev/arcane/v3/pkg/volumes" + "getarcane.dev/types/v3" +) + +const secretSourceLabel = "com.getarcaneapp.secret-source" + +func (e *Engine) fetchContainer(ctx context.Context, definition types.SecretSourceDefinition, data map[string]any) ([]types.EnvVariable, error) { + rendered, err := render("image", definition.Image, data) + if err != nil { + return nil, err + } + image := strings.TrimSpace(rendered) + if image == "" { + return nil, errors.New("container image is empty") + } + format, err := render("format", definition.Format, data) + if err != nil { + return nil, err + } + format = cmp.Or(strings.ToLower(strings.TrimSpace(format)), formatJSON) + if format != formatJSON && format != formatDotenv { + return nil, fmt.Errorf("format must be %q or %q", formatJSON, formatDotenv) + } + env, err := renderMap("env", definition.Env, data) + if err != nil { + return nil, err + } + args := make([]string, 0, len(definition.Args)) + for i, text := range definition.Args { + arg, renderErr := render(fmt.Sprintf("args[%d]", i), text, data) + if renderErr != nil { + return nil, renderErr + } + args = append(args, arg) + } + containerEnv := make([]string, 0, len(env)) + for key, value := range env { + containerEnv = append(containerEnv, key+"="+value) + } + slices.Sort(containerEnv) + + dockerClient, err := e.dockerClient(ctx) + if err != nil { + return nil, fmt.Errorf("failed to connect to Docker: %w", err) + } + if _, inspectErr := dockerClient.ImageInspect(ctx, image); inspectErr != nil { + pull, pullErr := dockerClient.ImagePull(ctx, image, mobyClient.ImagePullOptions{}) + if pullErr != nil { + return nil, fmt.Errorf("failed to pull secret source image %s: %w", image, pullErr) + } + defer func() { _ = pull.Close() }() + if renderErr := docker.RenderJSONMessageStream(pull, io.Discard); renderErr != nil { + return nil, fmt.Errorf("failed to pull secret source image %s: %w", image, renderErr) + } + } + + created, err := dockerClient.ContainerCreate(ctx, mobyClient.ContainerCreateOptions{ + Config: &mobyContainer.Config{ + Image: image, + Cmd: args, + Env: containerEnv, + Labels: map[string]string{selfcontainer.InternalResourceLabel: "true", secretSourceLabel: "true"}, + }, + HostConfig: &mobyContainer.HostConfig{}, + }) + if err != nil { + return nil, fmt.Errorf("failed to create secret source container: %w", err) + } + defer func() { + removeCtx, removeCancel := context.WithTimeout(context.WithoutCancel(ctx), timeouts.DefaultDockerAPI) + defer removeCancel() + if _, removeErr := dockerClient.ContainerRemove(removeCtx, created.ID, volumes.RemoveOptions()); removeErr != nil && !cerrdefs.IsNotFound(removeErr) { + slog.WarnContext(removeCtx, "failed to remove secret source container", "containerId", created.ID, "error", removeErr) + } + }() + + if _, startErr := dockerClient.ContainerStart(ctx, created.ID, mobyClient.ContainerStartOptions{}); startErr != nil { + return nil, fmt.Errorf("failed to start secret source container: %w", startErr) + } + wait := dockerClient.ContainerWait(ctx, created.ID, mobyClient.ContainerWaitOptions{Condition: mobyContainer.WaitConditionNotRunning}) + var status mobyContainer.WaitResponse + select { + case waitErr := <-wait.Error: + if waitErr != nil { + return nil, fmt.Errorf("failed to wait for secret source container: %w", waitErr) + } + case status = <-wait.Result: + } + if status.StatusCode != 0 { + return nil, fmt.Errorf("secret source container exited with code %d", status.StatusCode) + } + + logs, err := dockerClient.ContainerLogs(ctx, created.ID, mobyClient.ContainerLogsOptions{ShowStdout: true}) + if err != nil { + return nil, fmt.Errorf("failed to read secret source container output: %w", err) + } + defer func() { _ = logs.Close() }() + stdout := capture.New(maxResponseBytes) + if copyErr := docker.WaitStdCopy(docker.StartStdCopy(logs, stdout, io.Discard)); copyErr != nil { + return nil, fmt.Errorf("failed to decode secret source container output: %w", copyErr) + } + if stdout.Truncated() { + return nil, fmt.Errorf("secret source container output exceeds %d bytes", maxResponseBytes) + } + + if format == formatDotenv { + values, parseErr := projects.ParseProjectEnvContent(stdout.String(), nil) + if parseErr != nil { + return nil, fmt.Errorf("container output is not valid dotenv: %w", parseErr) + } + entries := make([]types.EnvVariable, 0, len(values)) + for _, key := range slices.Sorted(maps.Keys(values)) { + entries = append(entries, types.EnvVariable{ + Key: key, + Value: values[key], + }) + } + return entries, nil + } + document := jsontext.Value(strings.TrimSpace(stdout.String())) + if !document.IsValid() { + return nil, errors.New("container output is not valid JSON") + } + return extract(document, definition.Extract) +} diff --git a/backend/pkg/secretsource/definition.go b/backend/pkg/secretsource/definition.go new file mode 100644 index 0000000000..5d626a4dc0 --- /dev/null +++ b/backend/pkg/secretsource/definition.go @@ -0,0 +1,234 @@ +package secretsource + +import ( + "errors" + "fmt" + "maps" + "net/http" + "slices" + "strings" + "text/template" + + "go.yaml.in/yaml/v4" + + "getarcane.dev/arcane/v3/pkg/projects" + "getarcane.dev/types/v3" +) + +const ( + APIVersion = "arcane.secretsource/v1" + KindHTTP = "http" + KindContainer = "container" + formatJSON = "json" + formatDotenv = "dotenv" + BaseURLInput = "baseUrl" + maxDefinitionBytes = 256 << 10 +) + +var allowedMethods = []string{http.MethodGet, http.MethodPost, http.MethodPut} + +func ParseDefinition(source []byte) (types.SecretSourceDefinition, error) { + if len(source) > maxDefinitionBytes { + return types.SecretSourceDefinition{}, fmt.Errorf("definition exceeds %d bytes", maxDefinitionBytes) + } + + var root yaml.Node + if err := yaml.Unmarshal(source, &root); err != nil { + return types.SecretSourceDefinition{}, fmt.Errorf("invalid definition YAML: %w", err) + } + if len(root.Content) == 0 || root.Content[0].Kind != yaml.MappingNode { + return types.SecretSourceDefinition{}, errors.New("definition must be a YAML mapping") + } + + document := root.Content[0] + for i := 0; i+1 < len(document.Content); i += 2 { + name, node := document.Content[i].Value, document.Content[i+1] + if name != "inputs" && name != "credentials" { + continue + } + switch { + case node.Kind == yaml.SequenceNode: + continue + case node.Kind == yaml.ScalarNode && node.Tag == "!!null": + document.Content[i+1] = &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq"} + continue + case node.Kind != yaml.MappingNode: + return types.SecretSourceDefinition{}, fmt.Errorf("%s must be a mapping of field keys", name) + } + + items := make([]*yaml.Node, 0, len(node.Content)/2) + for j := 0; j+1 < len(node.Content); j += 2 { + key, value := node.Content[j], node.Content[j+1] + content := []*yaml.Node{ + {Kind: yaml.ScalarNode, Tag: "!!str", Value: "key"}, + {Kind: yaml.ScalarNode, Tag: "!!str", Value: key.Value}, + } + switch { + case value.Kind == yaml.MappingNode: + content = append(content, value.Content...) + case value.Kind == yaml.ScalarNode && value.Tag != "!!null": + content = append(content, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "label"}, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: value.Value}, + ) + case value.Kind != yaml.ScalarNode: + return types.SecretSourceDefinition{}, fmt.Errorf("%s.%s must be a mapping", name, key.Value) + } + items = append(items, &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: content}) + } + document.Content[i+1] = &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Content: items} + } + + var definition types.SecretSourceDefinition + if err := document.Load(&definition, yaml.WithKnownFields()); err != nil { + return types.SecretSourceDefinition{}, fmt.Errorf("invalid definition: %w", err) + } + if err := validateDefinition(definition); err != nil { + return types.SecretSourceDefinition{}, err + } + return definition, nil +} + +func validateDefinition(definition types.SecretSourceDefinition) error { + var problems []error + if definition.APIVersion != APIVersion { + problems = append(problems, fmt.Errorf("apiVersion must be %q", APIVersion)) + } + if strings.TrimSpace(definition.ID) == "" { + problems = append(problems, errors.New("id is required")) + } + if strings.TrimSpace(definition.Name) == "" { + problems = append(problems, errors.New("name is required")) + } + + problems = append(problems, validateFields("inputs", definition.Inputs)...) + problems = append(problems, validateFields("credentials", definition.Credentials)...) + for _, input := range definition.Inputs { + if slices.ContainsFunc(definition.Credentials, func(credential types.SecretSourceField) bool { + return credential.Key == input.Key + }) { + problems = append(problems, fmt.Errorf("%q is declared as both an input and a credential", input.Key)) + } + } + + switch definition.Kind { + case KindHTTP: + problems = append(problems, validateHTTPDefinition(definition)...) + case KindContainer: + if strings.TrimSpace(definition.Image) == "" { + problems = append(problems, errors.New("container definitions need an image")) + } + if definition.Login != nil || definition.Fetch != nil { + problems = append(problems, errors.New("login and fetch are only valid for the http kind")) + } + default: + problems = append(problems, fmt.Errorf("kind must be %q or %q", KindHTTP, KindContainer)) + } + + for i, rule := range definition.Extract { + if strings.TrimSpace(rule.From) == "" { + problems = append(problems, fmt.Errorf("extract[%d].from is required", i)) + } + if rule.Object == (rule.List != nil) { + problems = append(problems, fmt.Errorf("extract[%d] needs exactly one of object or list", i)) + } + if rule.List != nil && (strings.TrimSpace(rule.List.Key) == "" || strings.TrimSpace(rule.List.Value) == "") { + problems = append(problems, fmt.Errorf("extract[%d].list needs key and value paths", i)) + } + } + + texts := []string{definition.Image, definition.Format} + texts = append(texts, definition.Args...) + texts = slices.AppendSeq(texts, maps.Values(definition.Env)) + for _, step := range []*types.SecretSourceHTTPStep{definition.Login, definition.Fetch} { + if step == nil { + continue + } + texts = append(texts, step.Path) + for _, values := range []map[string]string{step.Query, step.Headers, step.Form} { + texts = slices.AppendSeq(texts, maps.Values(values)) + } + texts = append(texts, templateStrings(step.JSON)...) + } + for _, text := range texts { + if _, err := template.New("definition").Parse(text); err != nil { + problems = append(problems, fmt.Errorf("invalid template %q: %w", text, err)) + } + } + + return errors.Join(problems...) +} + +func validateFields(section string, fields []types.SecretSourceField) []error { + var problems []error + seen := make(map[string]bool, len(fields)) + for _, field := range fields { + switch { + case !projects.EnvKeyPattern.MatchString(field.Key): + problems = append(problems, fmt.Errorf("%s key %q must use letters, numbers, and underscores", section, field.Key)) + case seen[field.Key]: + problems = append(problems, fmt.Errorf("%s key %q is declared twice", section, field.Key)) + } + seen[field.Key] = true + } + return problems +} + +func validateHTTPDefinition(definition types.SecretSourceDefinition) []error { + var problems []error + if !slices.ContainsFunc(definition.Inputs, func(field types.SecretSourceField) bool { + return field.Key == BaseURLInput + }) { + problems = append(problems, fmt.Errorf("http definitions need a %q input", BaseURLInput)) + } + if definition.Fetch == nil { + problems = append(problems, errors.New("http definitions need a fetch step")) + } + if definition.Image != "" || len(definition.Env) > 0 || len(definition.Args) > 0 || definition.Format != "" { + problems = append(problems, errors.New("image, env, args, and format are only valid for the container kind")) + } + for _, step := range []struct { + step *types.SecretSourceHTTPStep + name string + }{ + {name: "login", step: definition.Login}, + {name: "fetch", step: definition.Fetch}, + } { + if step.step == nil { + continue + } + if !strings.HasPrefix(step.step.Path, "{{") && (!strings.HasPrefix(step.step.Path, "/") || strings.HasPrefix(step.step.Path, "//")) { + problems = append(problems, fmt.Errorf("%s.path must start with a single /", step.name)) + } + if method := strings.ToUpper(step.step.Method); method != "" && !slices.Contains(allowedMethods, method) { + problems = append(problems, fmt.Errorf("%s.method must be one of %s", step.name, strings.Join(allowedMethods, ", "))) + } + if step.step.JSON != nil && step.step.Form != nil { + problems = append(problems, fmt.Errorf("%s cannot have both json and form bodies", step.name)) + } + } + if definition.Fetch != nil && len(definition.Fetch.Capture) > 0 { + problems = append(problems, errors.New("capture is only valid on the login step")) + } + if definition.Login != nil && len(definition.Login.Capture) == 0 { + problems = append(problems, errors.New("login needs at least one capture")) + } + return problems +} + +func templateStrings(value any) []string { + var texts []string + switch typed := value.(type) { + case string: + texts = append(texts, typed) + case map[string]any: + for _, item := range typed { + texts = append(texts, templateStrings(item)...) + } + case []any: + for _, item := range typed { + texts = append(texts, templateStrings(item)...) + } + } + return texts +} diff --git a/backend/pkg/secretsource/engine.go b/backend/pkg/secretsource/engine.go new file mode 100644 index 0000000000..8bafc2713a --- /dev/null +++ b/backend/pkg/secretsource/engine.go @@ -0,0 +1,114 @@ +package secretsource + +import ( + "context" + "encoding/json/v2" + "fmt" + "net/http" + "time" + + mobyClient "github.com/moby/moby/client" + + kit "kit.getarcane.app" + "kit.getarcane.app/cache" + + "getarcane.dev/arcane/v3/pkg/httpx" + "getarcane.dev/types/v3" +) + +type ( + DockerClientFunc func(ctx context.Context) (*mobyClient.Client, error) + + EngineConfig struct { + DockerClient DockerClientFunc + } + + Request struct { + Inputs map[string]string `json:"inputs"` + Credentials map[string]string `json:"credentials"` + SourceID string `json:"sourceId"` + Path string `json:"path"` + Definition types.SecretSourceDefinition `json:"definition"` + } + + Engine struct { + httpClient *http.Client + dockerClient DockerClientFunc + tokens *cache.Cache[string, loginToken] + } + + loginToken struct { + values map[string]string + sourceID string + } +) + +const ( + requestTimeout = 30 * time.Second + fetchTimeout = 2 * time.Minute + maxResponseBytes = 1 << 20 + defaultTokenTTL = 5 * time.Minute + expiresInCaptureID = "expiresIn" +) + +func NewEngine(cfg EngineConfig) *Engine { + return &Engine{ + httpClient: httpx.NewPrivateNetworkHTTPClient(httpx.PrivateNetworkClientConfig{ + Timeout: requestTimeout, + ResponseHeaderTimeout: requestTimeout, + }), + dockerClient: cfg.DockerClient, + tokens: &cache.Cache[string, loginToken]{ + TTL: defaultTokenTTL, + JanitorInterval: defaultTokenTTL, + }, + } +} + +func (e *Engine) Fetch(ctx context.Context, req Request) ([]types.EnvVariable, error) { + ctx, cancel := context.WithTimeout(ctx, fetchTimeout) + defer cancel() + + inputs, err := resolveFields("input", req.Definition.Inputs, req.Inputs) + if err != nil { + return nil, err + } + credentials, err := resolveFields("credential", req.Definition.Credentials, req.Credentials) + if err != nil { + return nil, err + } + + switch req.Definition.Kind { + case KindHTTP: + cacheKey, marshalErr := json.Marshal(req, json.Deterministic(true)) + if marshalErr != nil { + return nil, fmt.Errorf("failed to key login cache: %w", marshalErr) + } + document, fetchErr := e.fetchHTTP(ctx, httpFetch{ + definition: req.Definition, + inputs: inputs, + credentials: credentials, + path: req.Path, + sourceID: req.SourceID, + cacheKey: kit.SHA256Hex(string(cacheKey)), + }) + if fetchErr != nil { + return nil, fetchErr + } + return extract(document, req.Definition.Extract) + case KindContainer: + return e.fetchContainer(ctx, req.Definition, templateData(inputs, credentials, req.Path, map[string]string{})) + default: + return nil, fmt.Errorf("unsupported secret source kind %q", req.Definition.Kind) + } +} + +func (e *Engine) ForgetSource(sourceID string) { + var keys []string + for key, token := range e.tokens.Range { + if token.sourceID == sourceID { + keys = append(keys, key) + } + } + e.tokens.Delete(keys...) +} diff --git a/backend/pkg/secretsource/extract.go b/backend/pkg/secretsource/extract.go new file mode 100644 index 0000000000..02b15d7007 --- /dev/null +++ b/backend/pkg/secretsource/extract.go @@ -0,0 +1,214 @@ +package secretsource + +import ( + "bytes" + "encoding/json/jsontext" + "encoding/json/v2" + "fmt" + "strconv" + "strings" + + "getarcane.dev/types/v3" +) + +type ( + jsonMember struct { + name string + value jsontext.Value + } +) + +var rootObjectRules = []types.SecretSourceExtract{{From: ".", Object: true}} + +func extract(document jsontext.Value, rules []types.SecretSourceExtract) ([]types.EnvVariable, error) { + if len(rules) == 0 { + rules = rootObjectRules + } + + var entries []types.EnvVariable + positions := make(map[string]int) + matched := false + for i, rule := range rules { + nodes, err := lookup(document, rule.From) + if err != nil { + return nil, fmt.Errorf("extract[%d]: %w", i, err) + } + matched = matched || len(nodes) > 0 + for _, node := range nodes { + pairs, pairsErr := extractPairs(node, rule) + if pairsErr != nil { + return nil, fmt.Errorf("extract[%d] (%s): %w", i, rule.From, pairsErr) + } + for _, pair := range pairs { + if index, ok := positions[pair.Key]; ok { + entries[index] = pair + continue + } + positions[pair.Key] = len(entries) + entries = append(entries, pair) + } + } + } + if !matched { + paths := make([]string, 0, len(rules)) + for _, rule := range rules { + paths = append(paths, rule.From) + } + return nil, fmt.Errorf("no values found at %s", strings.Join(paths, ", ")) + } + return entries, nil +} + +func extractPairs(node jsontext.Value, rule types.SecretSourceExtract) ([]types.EnvVariable, error) { + if rule.List == nil { + if node.Kind() != '{' { + return nil, fmt.Errorf("expected an object, found %s", kindName(node.Kind())) + } + members, err := readObject(node) + if err != nil { + return nil, err + } + pairs := make([]types.EnvVariable, 0, len(members)) + for _, member := range members { + if value, ok := scalarText(member.value); ok { + pairs = append(pairs, types.EnvVariable{Key: member.name, Value: value}) + } + } + return pairs, nil + } + + if node.Kind() != '[' { + return nil, fmt.Errorf("expected a list, found %s", kindName(node.Kind())) + } + items, err := readArray(node) + if err != nil { + return nil, err + } + pairs := make([]types.EnvVariable, 0, len(items)) + for _, item := range items { + key, keyOK, keyErr := firstScalar(item, rule.List.Key) + if keyErr != nil { + return nil, keyErr + } + value, valueOK, valueErr := firstScalar(item, rule.List.Value) + if valueErr != nil { + return nil, valueErr + } + if keyOK && valueOK && key != "" { + pairs = append(pairs, types.EnvVariable{Key: key, Value: value}) + } + } + return pairs, nil +} + +func firstScalar(document jsontext.Value, path string) (string, bool, error) { + nodes, err := lookup(document, path) + if err != nil || len(nodes) == 0 { + return "", false, err + } + value, ok := scalarText(nodes[0]) + return value, ok, nil +} + +func lookup(document jsontext.Value, path string) ([]jsontext.Value, error) { + nodes := []jsontext.Value{document} + trimmed := strings.Trim(strings.TrimSpace(path), ".") + if trimmed == "" { + return nodes, nil + } + + for segment := range strings.SplitSeq(trimmed, ".") { + var next []jsontext.Value + for _, node := range nodes { + switch node.Kind() { + case '{': + members, err := readObject(node) + if err != nil { + return nil, err + } + for _, member := range members { + if segment == "*" || member.name == segment { + next = append(next, member.value) + } + } + case '[': + items, err := readArray(node) + if err != nil { + return nil, err + } + if segment == "*" { + next = append(next, items...) + } else if index, convErr := strconv.Atoi(segment); convErr == nil && index >= 0 && index < len(items) { + next = append(next, items[index]) + } + } + } + nodes = next + } + return nodes, nil +} + +func readObject(value jsontext.Value) ([]jsonMember, error) { + decoder := jsontext.NewDecoder(bytes.NewReader(value)) + if _, err := decoder.ReadToken(); err != nil { + return nil, fmt.Errorf("invalid JSON object: %w", err) + } + var members []jsonMember + for decoder.PeekKind() != '}' { + token, err := decoder.ReadToken() + if err != nil { + return nil, fmt.Errorf("invalid JSON object: %w", err) + } + name := token.String() + member, err := decoder.ReadValue() + if err != nil { + return nil, fmt.Errorf("invalid JSON object: %w", err) + } + members = append(members, jsonMember{name: name, value: member.Clone()}) + } + return members, nil +} + +func readArray(value jsontext.Value) ([]jsontext.Value, error) { + decoder := jsontext.NewDecoder(bytes.NewReader(value)) + if _, err := decoder.ReadToken(); err != nil { + return nil, fmt.Errorf("invalid JSON list: %w", err) + } + var items []jsontext.Value + for decoder.PeekKind() != ']' { + item, err := decoder.ReadValue() + if err != nil { + return nil, fmt.Errorf("invalid JSON list: %w", err) + } + items = append(items, item.Clone()) + } + return items, nil +} + +func scalarText(value jsontext.Value) (string, bool) { + switch value.Kind() { + case '"': + var text string + if err := json.Unmarshal(value, &text); err != nil { + return "", false + } + return text, true + case '0', 't', 'f': + return strings.TrimSpace(string(value)), true + default: + return "", false + } +} + +func kindName(kind jsontext.Kind) string { + switch kind { + case '{': + return "an object" + case '[': + return "a list" + case 'n': + return "null" + default: + return "a scalar" + } +} diff --git a/backend/pkg/secretsource/http.go b/backend/pkg/secretsource/http.go new file mode 100644 index 0000000000..a6a251ca15 --- /dev/null +++ b/backend/pkg/secretsource/http.go @@ -0,0 +1,227 @@ +package secretsource + +import ( + "bytes" + "cmp" + "context" + "encoding/json/jsontext" + "encoding/json/v2" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "kit.getarcane.app/cache" + + "getarcane.dev/arcane/v3/pkg/httpx" + "getarcane.dev/types/v3" +) + +type ( + httpFetch struct { + inputs map[string]string + credentials map[string]string + path string + sourceID string + cacheKey string + definition types.SecretSourceDefinition + } + + httpResponse struct { + body jsontext.Value + status int + } +) + +func (e *Engine) fetchHTTP(ctx context.Context, fetch httpFetch) (jsontext.Value, error) { + base, err := httpx.ValidateOutboundHTTPURL(fetch.inputs[BaseURLInput]) + if err != nil { + return nil, fmt.Errorf("invalid %s: %w", BaseURLInput, err) + } + + login, cached, err := e.login(ctx, base, fetch) + if err != nil { + return nil, err + } + response, err := e.send(ctx, base, "fetch", *fetch.definition.Fetch, templateData(fetch.inputs, fetch.credentials, fetch.path, login)) + if err != nil { + return nil, err + } + if cached && (response.status == http.StatusUnauthorized || response.status == http.StatusForbidden) { + e.tokens.Delete(fetch.cacheKey) + if login, _, err = e.login(ctx, base, fetch); err != nil { + return nil, err + } + if response, err = e.send(ctx, base, "fetch", *fetch.definition.Fetch, templateData(fetch.inputs, fetch.credentials, fetch.path, login)); err != nil { + return nil, err + } + } + if response.status < 200 || response.status > 299 { + return nil, fmt.Errorf("fetch failed: %s returned HTTP %d", base.Host, response.status) + } + return response.body, nil +} + +func (e *Engine) login(ctx context.Context, base *url.URL, fetch httpFetch) (map[string]string, bool, error) { + if fetch.definition.Login == nil { + return map[string]string{}, false, nil + } + if token, ok, _ := e.tokens.Get(fetch.cacheKey); ok { + return token.values, true, nil + } + + response, err := e.send(ctx, base, "login", *fetch.definition.Login, templateData(fetch.inputs, fetch.credentials, fetch.path, map[string]string{})) + if err != nil { + return nil, false, err + } + if response.status < 200 || response.status > 299 { + return nil, false, fmt.Errorf("login failed: %s returned HTTP %d", base.Host, response.status) + } + + values := make(map[string]string, len(fetch.definition.Login.Capture)) + for name, path := range fetch.definition.Login.Capture { + value, ok, captureErr := firstScalar(response.body, path) + if captureErr != nil { + return nil, false, fmt.Errorf("login response: %w", captureErr) + } + if !ok { + return nil, false, fmt.Errorf("login response has no %q value", path) + } + values[name] = value + } + + ttl := defaultTokenTTL + if seconds, parseErr := strconv.ParseFloat(values[expiresInCaptureID], 64); parseErr == nil && seconds > 0 { + ttl = time.Duration(seconds * 0.9 * float64(time.Second)) + } + e.tokens.Set(cache.Entry[string, loginToken]{ + Key: fetch.cacheKey, + Value: loginToken{ + values: values, + sourceID: fetch.sourceID, + }, + TTL: ttl, + }) + return values, false, nil +} + +func (e *Engine) send(ctx context.Context, base *url.URL, name string, step types.SecretSourceHTTPStep, data map[string]any) (httpResponse, error) { + path, err := render(name+".path", step.Path, data) + if err != nil { + return httpResponse{}, err + } + query, err := renderMap(name+".query", step.Query, data) + if err != nil { + return httpResponse{}, err + } + if strings.ContainsAny(path, "?#") { + return httpResponse{}, fmt.Errorf("%s: request path must not contain ? or #; use the step's query parameters", name) + } + ref, err := url.Parse(path) + if err != nil { + return httpResponse{}, fmt.Errorf("%s: invalid request path: %w", name, err) + } + if ref.Scheme != "" || ref.Host != "" || ref.User != nil || !strings.HasPrefix(path, "/") || strings.HasPrefix(path, "//") { + return httpResponse{}, fmt.Errorf("%s: request path must be a relative path starting with a single /", name) + } + for segment := range strings.SplitSeq(strings.ReplaceAll(ref.Path, "\\", "/"), "/") { + if segment == ".." { + return httpResponse{}, fmt.Errorf("%s: request path must not contain .. segments", name) + } + } + values := url.Values{} + for key, value := range query { + if value != "" { + values.Set(key, value) + } + } + target := url.URL{ + Scheme: base.Scheme, + Host: base.Host, + Path: strings.TrimSuffix(base.Path, "/") + ref.Path, + RawPath: strings.TrimSuffix(base.EscapedPath(), "/") + ref.EscapedPath(), + RawQuery: values.Encode(), + } + headers, err := renderMap(name+".headers", step.Headers, data) + if err != nil { + return httpResponse{}, err + } + body, contentType, err := requestBody(name, step, data) + if err != nil { + return httpResponse{}, err + } + + req, err := http.NewRequestWithContext(ctx, cmp.Or(strings.ToUpper(step.Method), http.MethodGet), target.String(), body) + if err != nil { + return httpResponse{}, fmt.Errorf("%s: failed to build request: %w", name, err) + } + req.Header.Set("Accept", "application/json") + if contentType != "" { + req.Header.Set("Content-Type", contentType) + } + for key, value := range headers { + if strings.TrimSpace(value) != "" { + req.Header.Set(key, value) + } + } + + resp, err := e.httpClient.Do(req) + if err != nil { + var urlErr *url.Error + if errors.As(err, &urlErr) { + err = urlErr.Err + } + return httpResponse{}, fmt.Errorf("%s request to %s failed: %w", name, base.Host, err) + } + defer func() { _ = resp.Body.Close() }() + + raw, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1)) + if err != nil { + return httpResponse{}, fmt.Errorf("%s: failed to read response: %w", name, err) + } + if len(raw) > maxResponseBytes { + return httpResponse{}, fmt.Errorf("%s: response exceeds %d bytes", name, maxResponseBytes) + } + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return httpResponse{status: resp.StatusCode}, nil + } + value := jsontext.Value(raw) + if !value.IsValid() { + return httpResponse{}, fmt.Errorf("%s: response from %s is not valid JSON", name, base.Host) + } + return httpResponse{ + body: value, + status: resp.StatusCode, + }, nil +} + +func requestBody(name string, step types.SecretSourceHTTPStep, data map[string]any) (io.Reader, string, error) { + switch { + case step.JSON != nil: + rendered, err := renderValue(name+".json", step.JSON, data) + if err != nil { + return nil, "", err + } + encoded, err := json.Marshal(rendered) + if err != nil { + return nil, "", fmt.Errorf("%s: failed to encode JSON body: %w", name, err) + } + return bytes.NewReader(encoded), "application/json", nil + case step.Form != nil: + rendered, err := renderMap(name+".form", step.Form, data) + if err != nil { + return nil, "", err + } + form := url.Values{} + for key, value := range rendered { + form.Set(key, value) + } + return strings.NewReader(form.Encode()), "application/x-www-form-urlencoded", nil + default: + return nil, "", nil + } +} diff --git a/backend/pkg/secretsource/presets.go b/backend/pkg/secretsource/presets.go new file mode 100644 index 0000000000..2269edb873 --- /dev/null +++ b/backend/pkg/secretsource/presets.go @@ -0,0 +1,41 @@ +package secretsource + +import ( + "fmt" + "io/fs" + "path" + "slices" + "strings" + + "getarcane.dev/types/v3" +) + +func LoadPresets(fsys fs.FS, dir string) ([]types.SecretSourcePreset, error) { + entries, err := fs.ReadDir(fsys, dir) + if err != nil { + return nil, fmt.Errorf("failed to read secret source presets: %w", err) + } + + presets := make([]types.SecretSourcePreset, 0, len(entries)) + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".yaml") { + continue + } + source, readErr := fs.ReadFile(fsys, path.Join(dir, entry.Name())) + if readErr != nil { + return nil, fmt.Errorf("failed to read secret source preset %s: %w", entry.Name(), readErr) + } + definition, parseErr := ParseDefinition(source) + if parseErr != nil { + return nil, fmt.Errorf("invalid secret source preset %s: %w", entry.Name(), parseErr) + } + presets = append(presets, types.SecretSourcePreset{ + Definition: definition, + Source: string(source), + }) + } + slices.SortFunc(presets, func(a, b types.SecretSourcePreset) int { + return strings.Compare(strings.ToLower(a.Definition.Name), strings.ToLower(b.Definition.Name)) + }) + return presets, nil +} diff --git a/backend/pkg/secretsource/template.go b/backend/pkg/secretsource/template.go new file mode 100644 index 0000000000..8ca912bc3b --- /dev/null +++ b/backend/pkg/secretsource/template.go @@ -0,0 +1,110 @@ +package secretsource + +import ( + "cmp" + "errors" + "fmt" + "strings" + "text/template" + + "getarcane.dev/types/v3" +) + +func render(name, text string, data map[string]any) (string, error) { + tmpl, err := template.New(name).Option("missingkey=error").Parse(text) + if err != nil { + return "", fmt.Errorf("invalid %s template: %w", name, err) + } + var out strings.Builder + if execErr := tmpl.Execute(&out, data); execErr != nil { + return "", fmt.Errorf("failed to render %s: %w", name, execErr) + } + return out.String(), nil +} + +func renderMap(name string, values map[string]string, data map[string]any) (map[string]string, error) { + rendered := make(map[string]string, len(values)) + for key, text := range values { + value, err := render(name+"."+key, text, data) + if err != nil { + return nil, err + } + rendered[key] = value + } + return rendered, nil +} + +func renderValue(name string, value any, data map[string]any) (any, error) { + switch typed := value.(type) { + case string: + return render(name, typed, data) + case map[string]any: + rendered := make(map[string]any, len(typed)) + for key, item := range typed { + renderedItem, err := renderValue(name+"."+key, item, data) + if err != nil { + return nil, err + } + rendered[key] = renderedItem + } + return rendered, nil + case []any: + rendered := make([]any, 0, len(typed)) + for i, item := range typed { + renderedItem, err := renderValue(fmt.Sprintf("%s[%d]", name, i), item, data) + if err != nil { + return nil, err + } + rendered = append(rendered, renderedItem) + } + return rendered, nil + default: + return value, nil + } +} + +func resolveFields(section string, fields []types.SecretSourceField, values map[string]string) (map[string]string, error) { + resolved := make(map[string]string, len(fields)) + for _, field := range fields { + value := cmp.Or(values[field.Key], field.Default) + if field.Required && strings.TrimSpace(value) == "" { + return nil, fmt.Errorf("%s %q is required", section, cmp.Or(field.Label, field.Key)) + } + resolved[field.Key] = value + } + return resolved, nil +} + +func templateData(inputs, credentials map[string]string, path string, login map[string]string) map[string]any { + return map[string]any{ + "inputs": inputs, + "credentials": credentials, + "path": path, + "login": login, + } +} + +func ValidateValues(req Request) error { + if req.Definition.PathRequired && strings.TrimSpace(req.Path) == "" { + return &types.FieldError{Field: "path", Err: errors.New("path is required")} + } + inputs, err := resolveFields("input", req.Definition.Inputs, req.Inputs) + if err != nil { + return err + } + credentials, err := resolveFields("credential", req.Definition.Credentials, req.Credentials) + if err != nil { + return err + } + for key := range req.Inputs { + if _, known := inputs[key]; !known { + return &types.FieldError{Field: "inputs", Err: fmt.Errorf("unknown input %q", key)} + } + } + for key := range req.Credentials { + if _, known := credentials[key]; !known { + return &types.FieldError{Field: "credentials", Err: fmt.Errorf("unknown credential %q", key)} + } + } + return nil +} diff --git a/backend/resources/embed.go b/backend/resources/embed.go index 35ac0dcd1e..8629bfac4c 100644 --- a/backend/resources/embed.go +++ b/backend/resources/embed.go @@ -4,5 +4,5 @@ package resources import "embed" -//go:embed images scalar aaguids.json +//go:embed images scalar aaguids.json secretsources var FS embed.FS diff --git a/backend/resources/excluded.go b/backend/resources/excluded.go index 1ebc7db892..3d9afbc68a 100644 --- a/backend/resources/excluded.go +++ b/backend/resources/excluded.go @@ -4,5 +4,5 @@ package resources import "embed" -//go:embed images aaguids.json +//go:embed images aaguids.json secretsources var FS embed.FS diff --git a/backend/resources/secretsources/doppler.yaml b/backend/resources/secretsources/doppler.yaml new file mode 100644 index 0000000000..b301fa94c1 --- /dev/null +++ b/backend/resources/secretsources/doppler.yaml @@ -0,0 +1,32 @@ +apiVersion: arcane.secretsource/v1 +id: doppler +name: Doppler +description: Doppler config secrets through a service token. +kind: http +inputs: + baseUrl: + label: URL + default: https://api.doppler.com + required: true + project: + label: Project + description: Leave empty when the token is a config-scoped service token. + config: + label: Config + description: Leave empty when the token is a config-scoped service token. +credentials: + token: + label: Service Token + required: true +fetch: + method: GET + path: /v3/configs/config/secrets/download + query: + format: json + project: "{{ .inputs.project }}" + config: "{{ .inputs.config }}" + headers: + Authorization: "Bearer {{ .credentials.token }}" +extract: + - from: . + object: true diff --git a/backend/resources/secretsources/generic-container.yaml b/backend/resources/secretsources/generic-container.yaml new file mode 100644 index 0000000000..f949f42c15 --- /dev/null +++ b/backend/resources/secretsources/generic-container.yaml @@ -0,0 +1,35 @@ +apiVersion: arcane.secretsource/v1 +id: generic-container +name: Generic container command +description: Run an image on the manager's Docker and read secrets from its stdout. +kind: container +inputs: + image: + label: Image + placeholder: alpine:3 + required: true + command: + label: Shell command + description: Runs with sh -c. Credentials are available as SECRET_TOKEN. + multiline: true + required: true + format: + label: Output format + description: json or dotenv. + default: json +credentials: + token: + label: Token + description: Passed to the container as SECRET_TOKEN. +image: "{{ .inputs.image }}" +args: + - sh + - -c + - "{{ .inputs.command }}" +env: + SECRET_TOKEN: "{{ .credentials.token }}" + SECRET_PATH: "{{ .path }}" +format: "{{ .inputs.format }}" +extract: + - from: . + object: true diff --git a/backend/resources/secretsources/generic-http-json.yaml b/backend/resources/secretsources/generic-http-json.yaml new file mode 100644 index 0000000000..8589514f83 --- /dev/null +++ b/backend/resources/secretsources/generic-http-json.yaml @@ -0,0 +1,27 @@ +apiVersion: arcane.secretsource/v1 +id: generic-http-json +name: Generic HTTP JSON +description: GET a JSON object of KEY/value pairs. +kind: http +inputs: + baseUrl: + label: URL + placeholder: https://secrets.example.com + required: true + endpoint: + label: Endpoint path + default: / + placeholder: /v1/secrets + required: true +credentials: + token: + label: Bearer token + description: Optional. +fetch: + method: GET + path: "{{ .inputs.endpoint }}" + headers: + Authorization: "{{ if .credentials.token }}Bearer {{ .credentials.token }}{{ end }}" +extract: + - from: . + object: true diff --git a/backend/resources/secretsources/infisical.yaml b/backend/resources/secretsources/infisical.yaml new file mode 100644 index 0000000000..fe666cc9e0 --- /dev/null +++ b/backend/resources/secretsources/infisical.yaml @@ -0,0 +1,53 @@ +apiVersion: arcane.secretsource/v1 +id: infisical +name: Infisical +description: Infisical secrets through a machine identity with Universal Auth. +kind: http +inputs: + baseUrl: + label: URL + default: https://app.infisical.com + required: true + projectId: + label: Project ID + required: true + environment: + label: Environment + placeholder: prod + required: true +credentials: + clientId: + label: Client ID + required: true + clientSecret: + label: Client Secret + required: true +login: + method: POST + path: /api/v1/auth/universal-auth/login + json: + clientId: "{{ .credentials.clientId }}" + clientSecret: "{{ .credentials.clientSecret }}" + capture: + token: accessToken + expiresIn: expiresIn +fetch: + method: GET + path: /api/v4/secrets + query: + projectId: "{{ .inputs.projectId }}" + environment: "{{ .inputs.environment }}" + secretPath: "{{ .path }}" + expandSecretReferences: "true" + includeImports: "true" + headers: + Authorization: "Bearer {{ .login.token }}" +extract: + - from: imports.*.secrets + list: + key: secretKey + value: secretValue + - from: secrets + list: + key: secretKey + value: secretValue diff --git a/backend/resources/secretsources/onepassword-connect.yaml b/backend/resources/secretsources/onepassword-connect.yaml new file mode 100644 index 0000000000..afd126d2ee --- /dev/null +++ b/backend/resources/secretsources/onepassword-connect.yaml @@ -0,0 +1,30 @@ +apiVersion: arcane.secretsource/v1 +id: onepassword-connect +name: 1Password Connect +description: Fields of one item from a 1Password Connect server. Field labels become keys. +kind: http +inputs: + baseUrl: + label: Connect server URL + placeholder: http://op-connect:8080 + required: true + vault: + label: Vault ID + required: true + item: + label: Item ID + required: true +credentials: + token: + label: Connect token + required: true +fetch: + method: GET + path: "/v1/vaults/{{ .inputs.vault }}/items/{{ .inputs.item }}" + headers: + Authorization: "Bearer {{ .credentials.token }}" +extract: + - from: fields + list: + key: label + value: value diff --git a/backend/resources/secretsources/vault-kv2-approle.yaml b/backend/resources/secretsources/vault-kv2-approle.yaml new file mode 100644 index 0000000000..66192d6c8d --- /dev/null +++ b/backend/resources/secretsources/vault-kv2-approle.yaml @@ -0,0 +1,49 @@ +apiVersion: arcane.secretsource/v1 +id: vault-kv2-approle +name: Vault / OpenBao KV v2 (AppRole) +description: Read one KV v2 secret from HashiCorp Vault or OpenBao with AppRole login. Set the source path to the secret path. +kind: http +pathRequired: true +inputs: + baseUrl: + label: URL + placeholder: https://vault.example.com:8200 + required: true + mount: + label: KV mount + default: secret + required: true + approleMount: + label: AppRole mount + default: approle + required: true + namespace: + label: Namespace + description: Vault Enterprise namespace; leave empty otherwise. +credentials: + roleId: + label: Role ID + required: true + secretId: + label: Secret ID + required: true +login: + method: POST + path: "/v1/auth/{{ .inputs.approleMount }}/login" + headers: + X-Vault-Namespace: "{{ .inputs.namespace }}" + json: + role_id: "{{ .credentials.roleId }}" + secret_id: "{{ .credentials.secretId }}" + capture: + token: auth.client_token + expiresIn: auth.lease_duration +fetch: + method: GET + path: "/v1/{{ .inputs.mount }}/data/{{ .path }}" + headers: + X-Vault-Token: "{{ .login.token }}" + X-Vault-Namespace: "{{ .inputs.namespace }}" +extract: + - from: data.data + object: true diff --git a/backend/resources/secretsources/vault-kv2-token.yaml b/backend/resources/secretsources/vault-kv2-token.yaml new file mode 100644 index 0000000000..1919a4a41f --- /dev/null +++ b/backend/resources/secretsources/vault-kv2-token.yaml @@ -0,0 +1,31 @@ +apiVersion: arcane.secretsource/v1 +id: vault-kv2-token +name: Vault / OpenBao KV v2 (token) +description: Read one KV v2 secret from HashiCorp Vault or OpenBao with a token. Set the source path to the secret path. +kind: http +pathRequired: true +inputs: + baseUrl: + label: URL + placeholder: https://vault.example.com:8200 + required: true + mount: + label: KV mount + default: secret + required: true + namespace: + label: Namespace + description: Vault Enterprise namespace; leave empty otherwise. +credentials: + token: + label: Token + required: true +fetch: + method: GET + path: "/v1/{{ .inputs.mount }}/data/{{ .path }}" + headers: + X-Vault-Token: "{{ .credentials.token }}" + X-Vault-Namespace: "{{ .inputs.namespace }}" +extract: + - from: data.data + object: true diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.go index 3388cf729d..255d3c8482 100644 --- a/cli/internal/types/endpoints.go +++ b/cli/internal/types/endpoints.go @@ -456,6 +456,16 @@ func Variable(id string) string { return pathf("/api/variables/%s", id) } func VariablesSync() string { return "/api/variables/sync" } +func VariableSources() string { return "/api/variables/sources" } + +func VariableSource(id string) string { return pathf("/api/variables/sources/%s", id) } + +func VariableSourceRefresh(id string) string { return pathf("/api/variables/sources/%s/refresh", id) } + +func VariableSourcesTest() string { return "/api/variables/sources/test" } + +func VariableSourcePresets() string { return "/api/variables/source-presets" } + func Backups() string { return "/api/backups" } func Backup(id string) string { diff --git a/cli/pkg/variables/cmd.go b/cli/pkg/variables/cmd.go index 8b38aab665..f4c486230c 100644 --- a/cli/pkg/variables/cmd.go +++ b/cli/pkg/variables/cmd.go @@ -36,9 +36,17 @@ func Command() *cobra.Command { command.AddCommand(newUpdateCmd()) command.AddCommand(newDeleteCmd()) command.AddCommand(newSyncCmd()) + command.AddCommand(newSourcesCmd()) return command } +func scopeLabel(allEnvironments bool, envIDs []string) string { + if allEnvironments { + return "all agents" + } + return cmp.Or(strings.Join(envIDs, ","), "-") +} + func printMutationResult(result types.GlobalVariableMutationResponse, message string) error { output.Success("%s", message) if result.Variable != nil { @@ -46,14 +54,7 @@ func printMutationResult(result types.GlobalVariableMutationResponse, message st output.KeyValue("Key", result.Variable.Key) output.KeyValue("Secret", strconv.FormatBool(result.Variable.IsSecret)) output.KeyValue("Inject", strconv.FormatBool(result.Variable.InjectIntoContainers)) - scope := "-" - switch { - case result.Variable.AllEnvironments: - scope = "all agents" - case len(result.Variable.EnvironmentIDs) > 0: - scope = strings.Join(result.Variable.EnvironmentIDs, ",") - } - output.KeyValue("Scope", scope) + output.KeyValue("Scope", scopeLabel(result.Variable.AllEnvironments, result.Variable.EnvironmentIDs)) } return nil } @@ -83,17 +84,10 @@ func newListCmd() *cobra.Command { if variable.IsSecret { value = secretMask } - scope := "-" - switch { - case variable.AllEnvironments: - scope = "all agents" - case len(variable.EnvironmentIDs) > 0: - scope = strings.Join(variable.EnvironmentIDs, ",") - } rows[i] = []string{ variable.ID, variable.Key, - scope, + scopeLabel(variable.AllEnvironments, variable.EnvironmentIDs), strconv.FormatBool(variable.IsSecret), strconv.FormatBool(variable.InjectIntoContainers), value, diff --git a/cli/pkg/variables/sources.go b/cli/pkg/variables/sources.go new file mode 100644 index 0000000000..84879d7a3e --- /dev/null +++ b/cli/pkg/variables/sources.go @@ -0,0 +1,404 @@ +package variables + +import ( + "cmp" + "errors" + "fmt" + "io" + "maps" + "net/http" + "os" + "slices" + "strconv" + "strings" + "time" + + "github.com/spf13/cobra" + + kit "kit.getarcane.app" + + "getarcane.dev/cli/v3/internal/cmdutil" + "getarcane.dev/cli/v3/internal/output" + clitypes "getarcane.dev/cli/v3/internal/types" + "getarcane.dev/types/v3" +) + +type ( + sourceFlags struct { + inputs map[string]string + credentials map[string]string + name string + preset string + definitionFile string + credentialFile string + path string + keyPrefix string + envIDs []string + inject bool + disabled bool + } +) + +func newSourcesCmd() *cobra.Command { + command := &cobra.Command{ + Use: "sources", + Aliases: []string{"source", "secret-sources"}, + Short: "Manage external secret sources", + } + command.AddCommand(newSourcesListCmd()) + command.AddCommand(newSourcesPresetsCmd()) + command.AddCommand(newSourcesCreateCmd()) + command.AddCommand(newSourcesUpdateCmd()) + command.AddCommand(newSourcesDeleteCmd()) + command.AddCommand(newSourcesRefreshCmd()) + command.AddCommand(newSourcesTestCmd()) + return command +} + +func bindSourceFlags(command *cobra.Command, opts *sourceFlags) { + command.Flags().StringVar(&opts.name, "name", "", "Source name") + command.Flags().StringVar(&opts.preset, "preset", "", "Preset ID (see 'variables sources presets')") + command.Flags().StringVar(&opts.definitionFile, "definition-file", "", "Custom definition YAML file; overrides --preset") + command.Flags().StringToStringVar(&opts.inputs, "input", nil, "Input value as key=value (repeatable)") + command.Flags().StringToStringVar(&opts.credentials, "credential", nil, "Credential value as key=value (repeatable; an empty value clears the key on update)") + command.Flags().StringVar(&opts.credentialFile, "credentials-file", "", "File of KEY=VALUE credential lines (use - for stdin); --credential overrides its keys") + command.Flags().StringVar(&opts.path, "path", "", "Path passed to the definition") + command.Flags().StringVar(&opts.keyPrefix, "key-prefix", "", "Prefix added to every key") + command.Flags().StringArrayVar(&opts.envIDs, "agent", nil, "Agent ID to scope the source to (repeatable; pass \"all\" for every agent)") + command.Flags().BoolVar(&opts.inject, "inject", false, "Inject the keys into every container's environment") + command.Flags().BoolVar(&opts.disabled, "disabled", false, "Keep the source disabled") +} + +func sourceRequest(cmd *cobra.Command, opts sourceFlags) (map[string]any, error) { + credentials := map[string]string{} + if opts.credentialFile != "" { + content, err := readCredentialFile(cmd, opts.credentialFile) + if err != nil { + return nil, err + } + for number, line := range strings.Split(string(content), "\n") { + if trimmed := strings.TrimSpace(line); trimmed == "" || strings.HasPrefix(trimmed, "#") { + continue + } + key, value, ok := strings.Cut(strings.TrimSuffix(line, "\r"), "=") + if !ok || strings.TrimSpace(key) == "" { + return nil, fmt.Errorf("credentials file line %d is not KEY=VALUE", number+1) + } + credentials[strings.TrimSpace(key)] = value + } + } + maps.Copy(credentials, opts.credentials) + + req := map[string]any{} + for _, field := range []struct { + value any + flag string + key string + }{ + {flag: "name", key: "name", value: opts.name}, + {flag: "preset", key: "presetId", value: opts.preset}, + {flag: "input", key: "inputs", value: opts.inputs}, + {flag: "credential", key: "credentials", value: credentials}, + {flag: "credentials-file", key: "credentials", value: credentials}, + {flag: "path", key: "path", value: opts.path}, + {flag: "key-prefix", key: "keyPrefix", value: opts.keyPrefix}, + {flag: "agent", key: "allEnvironments", value: slices.Equal(opts.envIDs, []string{"all"})}, + {flag: "agent", key: "environmentIds", value: kit.Ternary(slices.Equal(opts.envIDs, []string{"all"}), nil, opts.envIDs)}, + {flag: "inject", key: "injectIntoContainers", value: opts.inject}, + {flag: "disabled", key: "enabled", value: !opts.disabled}, + } { + if cmd.Flags().Changed(field.flag) { + req[field.key] = field.value + } + } + if opts.definitionFile != "" { + content, err := os.ReadFile(opts.definitionFile) + if err != nil { + return nil, fmt.Errorf("failed to read definition file: %w", err) + } + req["definition"] = string(content) + } + return req, nil +} + +func readCredentialFile(cmd *cobra.Command, path string) ([]byte, error) { + if path == "-" { + content, err := output.ReadWithContext(cmd.Context(), cmd.InOrStdin(), io.ReadAll) + if err != nil { + return nil, fmt.Errorf("failed to read credentials from stdin: %w", err) + } + return content, nil + } + content, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("failed to read credentials file: %w", err) + } + return content, nil +} + +func printSourceMutation(result types.SecretSourceMutationResponse, message string) error { + output.Success("%s", message) + if result.Source != nil { + output.KeyValue("ID", result.Source.ID) + output.KeyValue("Name", result.Source.Name) + output.KeyValue("Kind", result.Source.Kind) + output.KeyValue("Scope", scopeLabel(result.Source.AllEnvironments, result.Source.EnvironmentIDs)) + output.KeyValue("Keys", strconv.Itoa(result.Source.LastKeyCount)) + output.KeyValue("Last error", cmp.Or(result.Source.LastError, "-")) + } + return nil +} + +func newSourcesListCmd() *cobra.Command { + return &cobra.Command{ + Use: "list", + Aliases: []string{"ls"}, + Short: "List secret sources", + Args: cobra.NoArgs, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + c, err := cmdutil.ClientFromCommand(cmd) + if err != nil { + return err + } + return cmdutil.Run(cmd, c, cmdutil.Spec[[]types.SecretSource]{ + Method: http.MethodGet, + Path: clitypes.VariableSources(), + FailureMessage: "failed to list secret sources", + Render: func(data []types.SecretSource) error { + headers := []string{"ID", "NAME", "KIND", "PRESET", "SCOPE", "ENABLED", "KEYS", "LAST FETCH", "ERROR"} + rows := make([][]string, len(data)) + for i, source := range data { + lastFetch := "-" + if source.LastFetchedAt != nil { + lastFetch = source.LastFetchedAt.Format(time.RFC3339) + } + rows[i] = []string{ + source.ID, + source.Name, + source.Kind, + cmp.Or(source.PresetID, "-"), + scopeLabel(source.AllEnvironments, source.EnvironmentIDs), + strconv.FormatBool(source.Enabled), + strconv.Itoa(source.LastKeyCount), + lastFetch, + cmp.Or(source.LastError, "-"), + } + } + return output.Table(headers, rows) + }, + }) + }, + } +} + +func newSourcesPresetsCmd() *cobra.Command { + return &cobra.Command{ + Use: "presets", + Short: "List built-in secret source presets", + Args: cobra.NoArgs, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + c, err := cmdutil.ClientFromCommand(cmd) + if err != nil { + return err + } + return cmdutil.Run(cmd, c, cmdutil.Spec[[]types.SecretSourcePreset]{ + Method: http.MethodGet, + Path: clitypes.VariableSourcePresets(), + FailureMessage: "failed to list secret source presets", + Render: func(data []types.SecretSourcePreset) error { + headers := []string{"ID", "NAME", "KIND", "INPUTS", "CREDENTIALS"} + rows := make([][]string, len(data)) + for i, preset := range data { + rows[i] = []string{ + preset.Definition.ID, + preset.Definition.Name, + preset.Definition.Kind, + fieldList(preset.Definition.Inputs), + fieldList(preset.Definition.Credentials), + } + } + return output.Table(headers, rows) + }, + }) + }, + } +} + +func fieldList(fields []types.SecretSourceField) string { + names := make([]string, 0, len(fields)) + for _, field := range fields { + names = append(names, kit.Ternary(field.Required, field.Key+"*", field.Key)) + } + return cmp.Or(strings.Join(names, ","), "-") +} + +func newSourcesCreateCmd() *cobra.Command { + var opts sourceFlags + command := &cobra.Command{ + Use: "create", + Short: "Create a secret source", + Args: cobra.NoArgs, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + req, err := sourceRequest(cmd, opts) + if err != nil { + return err + } + if !cmd.Flags().Changed("agent") { + req["allEnvironments"] = true + } + c, err := cmdutil.ClientFromCommand(cmd) + if err != nil { + return err + } + return cmdutil.Run(cmd, c, cmdutil.Spec[types.SecretSourceMutationResponse]{ + Method: http.MethodPost, + Path: clitypes.VariableSources(), + FailureMessage: "failed to create secret source", + Body: req, + Render: func(data types.SecretSourceMutationResponse) error { + return printSourceMutation(data, fmt.Sprintf("Secret source %s created", opts.name)) + }, + }) + }, + } + bindSourceFlags(command, &opts) + _ = command.MarkFlagRequired("name") + return command +} + +func newSourcesUpdateCmd() *cobra.Command { + var opts sourceFlags + command := &cobra.Command{ + Use: "update ", + Short: "Update a secret source", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + req, err := sourceRequest(cmd, opts) + if err != nil { + return err + } + if len(req) == 0 { + return errors.New("no updates provided (set at least one flag)") + } + c, err := cmdutil.ClientFromCommand(cmd) + if err != nil { + return err + } + return cmdutil.Run(cmd, c, cmdutil.Spec[types.SecretSourceMutationResponse]{ + Method: http.MethodPatch, + Path: clitypes.VariableSource(args[0]), + FailureMessage: "failed to update secret source", + Body: req, + Render: func(data types.SecretSourceMutationResponse) error { + return printSourceMutation(data, "Secret source updated") + }, + }) + }, + } + bindSourceFlags(command, &opts) + return command +} + +func newSourcesDeleteCmd() *cobra.Command { + var opts struct { + force bool + } + command := &cobra.Command{ + Use: "delete ", + Aliases: []string{"rm", "remove"}, + Short: "Delete a secret source", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + c, err := cmdutil.ClientFromCommand(cmd) + if err != nil { + return err + } + return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{ + Force: opts.force, + Prompt: fmt.Sprintf("Are you sure you want to delete secret source %s?", args[0]), + Path: clitypes.VariableSource(args[0]), + FailureMessage: "failed to delete secret source", + SuccessMessage: "Secret source deleted", + }) + }, + } + command.Flags().BoolVarP(&opts.force, "force", "f", false, "Skip the confirmation prompt") + return command +} + +func newSourcesRefreshCmd() *cobra.Command { + return &cobra.Command{ + Use: "refresh ", + Short: "Fetch a secret source now and re-sync variables", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + c, err := cmdutil.ClientFromCommand(cmd) + if err != nil { + return err + } + return cmdutil.Run(cmd, c, cmdutil.Spec[types.SecretSourceMutationResponse]{ + Method: http.MethodPost, + Path: clitypes.VariableSourceRefresh(args[0]), + FailureMessage: "failed to refresh secret source", + Render: func(data types.SecretSourceMutationResponse) error { + return printSourceMutation(data, "Secret source refreshed") + }, + }) + }, + } +} + +func newSourcesTestCmd() *cobra.Command { + var opts sourceFlags + var id string + command := &cobra.Command{ + Use: "test", + Short: "Test a saved or unsaved secret source (prints key names only)", + Args: cobra.NoArgs, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + req, err := sourceRequest(cmd, opts) + if err != nil { + return err + } + if id != "" { + req["id"] = id + } + c, err := cmdutil.ClientFromCommand(cmd) + if err != nil { + return err + } + result, err := c.DoEnvelope[types.SecretSourceTestResult](cmd.Context(), http.MethodPost, clitypes.VariableSourcesTest(), req) + if err != nil { + return fmt.Errorf("failed to test secret source: %w", err) + } + if cmdutil.JSONOutputEnabled(cmd) { + if printErr := cmdutil.PrintJSON(result.Data); printErr != nil { + return printErr + } + } + if !result.Data.Success { + return fmt.Errorf("secret source test failed: %s", result.Data.Error) + } + if cmdutil.JSONOutputEnabled(cmd) { + return nil + } + output.Success("Secret source returned %d keys (%d skipped)", result.Data.KeyCount, result.Data.SkippedKeyCount) + for _, key := range result.Data.Keys { + if _, writeErr := fmt.Fprintln(output.Stdout(), key); writeErr != nil { + return writeErr + } + } + return nil + }, + } + bindSourceFlags(command, &opts) + command.Flags().StringVar(&id, "id", "", "Saved source to test; other flags override its stored values") + return command +} diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 333aa6c2b6..fc0a816505 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -4951,5 +4951,35 @@ "when_running": "When running", "never_files_only": "Never (files only)", "redeploy_policy_running_description": "Redeploy after a change only when the project is already running.", - "redeploy_policy_never_description": "Update files only without redeploying running or stopped containers." + "redeploy_policy_never_description": "Update files only without redeploying running or stopped containers.", + "external_secrets": "External Secrets", + "external_secret": "External Secret", + "create_external_secret": "Create External Secret", + "edit_external_secret": "Edit External Secret", + "external_secret_form_description": "Pull variables from an external secrets manager.", + "no_external_secrets": "No external secrets", + "no_external_secrets_description": "Add an external secret to pull variables from an external secrets manager.", + "preset": "Preset", + "preset_description": "Secrets manager this source connects to.", + "custom_definition": "Custom definition", + "custom_definition_description": "Write your own definition YAML.", + "definition_placeholder": "Paste an external secret definition in YAML", + "definition_keep_placeholder": "Leave empty to keep the current definition", + "path": "Path", + "path_placeholder": "/production", + "path_description": "Optional path passed to the definition.", + "key_prefix": "Key Prefix", + "key_prefix_placeholder": "APP_", + "key_prefix_description": "Added to the start of every fetched key.", + "external_secret_enabled_description": "Fetch this source and add its keys to variables.", + "keys_fetched": "Keys fetched", + "last_fetched": "Last fetched", + "count_keys_found": "{count} keys found", + "count_keys_skipped": "{count} keys skipped because they are not valid variable names", + "refresh_external_secret_target_description": "Refresh an external secret on this manager.", + "refresh_external_secret_action_description": "Fetch the source and sync its keys to agents.", + "clear_saved_value": "Clear saved value", + "variables_and_secrets": "Variables & Secrets", + "variables_and_secrets_subtitle": "Global variables and the external secrets that feed them, synced to your agents", + "enter_saved_value_again_or_clear": "Enter this value again or clear it. The saved value is not kept when the source changes." } diff --git a/frontend/src/lib/components/arcane-table/cells/scope-cell.svelte b/frontend/src/lib/components/arcane-table/cells/scope-cell.svelte new file mode 100644 index 0000000000..2f6ebc01d7 --- /dev/null +++ b/frontend/src/lib/components/arcane-table/cells/scope-cell.svelte @@ -0,0 +1,37 @@ + + + + +{#if allEnvironments || environmentIds.length === 0} + {m.all_environments()} +{:else} +
+ {#each environmentIds.slice(0, 2) as environmentId (environmentId)} + {envNameById.get(environmentId) ?? environmentId} + {/each} + {#if environmentIds.length > 2} + {m.plus_count({ count: environmentIds.length - 2 })} + {/if} +
+{/if} diff --git a/frontend/src/lib/components/sheets/environment-scope-select.svelte b/frontend/src/lib/components/sheets/environment-scope-select.svelte new file mode 100644 index 0000000000..e210c6fd90 --- /dev/null +++ b/frontend/src/lib/components/sheets/environment-scope-select.svelte @@ -0,0 +1,56 @@ + + +
+ + { + scope = value as 'all' | 'specific'; + error = null; + }} + > +
+ + +
+
+ {#if scope === 'specific'} +
+ +
+ {/if} + {#if error} +

{error}

+ {/if} +
diff --git a/frontend/src/lib/components/sheets/secret-source-form-sheet.svelte b/frontend/src/lib/components/sheets/secret-source-form-sheet.svelte new file mode 100644 index 0000000000..dbeb783efd --- /dev/null +++ b/frontend/src/lib/components/sheets/secret-source-form-sheet.svelte @@ -0,0 +1,469 @@ + + + +
+
+ + + {#if nameError} +

{nameError}

+ {/if} +
+ + + {#if presetsQuery.error} +

{extractApiErrorMessage(presetsQuery.error)}

+ {/if} + + {#if choice === CUSTOM} +
+ +