workspaces 0.1.16 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,6 @@
1
1
  require 'yaml'
2
+ require 'json'
3
+ require 'digest'
2
4
  require_relative 'config'
3
5
  require_relative 'environment_overrides'
4
6
 
@@ -9,7 +11,7 @@ module Workspaces
9
11
  WORKSPACE_HOST WORKSPACE_CACHE_DIR WORKSPACE_RUN_ID).freeze
10
12
  LFS_STEP_ID = 'lfs'.freeze
11
13
  LFS_STEP_NAME = 'Fetch Git LFS files'.freeze
12
- attr_reader :steps, :environment, :default_editable_env, :environment_presets, :lfs_fetch
14
+ attr_reader :steps, :environment, :default_editable_env, :environment_presets, :lfs_fetch, :sleep_ignore_paths
13
15
 
14
16
  def initialize(root: Config.repo_root)
15
17
  @root = root
@@ -19,6 +21,7 @@ module Workspaces
19
21
  @environment_presets = validate_environment_presets!(document.fetch('environment_presets', {}))
20
22
  @environment = validate_env!(document.fetch('env', {}))
21
23
  @lfs_fetch = validate_lfs!(document.fetch('lfs', {}))
24
+ @sleep_ignore_paths = validate_sleep!(document.fetch('sleep', {}))
22
25
  @steps = document.fetch('steps').map { |step| validate_step!(step) }
23
26
  @steps = [lfs_step] + @steps unless lfs_fetch.empty?
24
27
  validate_editable_overlap!
@@ -33,6 +36,14 @@ module Workspaces
33
36
  restart ? steps.drop(steps.index { |step| step['background'] }) : steps
34
37
  end
35
38
 
39
+ # Changes when a step that runs before the server changes. A sleeping workspace wakes by running
40
+ # only the server and readiness steps, unless this no longer matches what it was prepared with.
41
+ def preparation_digest
42
+ server = steps.index { |step| step['background'] }
43
+ material = { 'env' => environment, 'steps' => steps.first(server).map { |step| step.slice('id', 'run', 'env', 'timeout') } }
44
+ Digest::SHA256.hexdigest(JSON.generate(material))
45
+ end
46
+
36
47
  # Files fetched into the workspace come from the LFS objects the source repository already
37
48
  # has, then are linked in by `git lfs pull`; the source's store is shared by every workspace.
38
49
  def lfs_step
@@ -61,7 +72,7 @@ module Workspaces
61
72
  raise Invalid,
62
73
  'Configuration must be a mapping with version: 1'
63
74
  end
64
- unknown_keys!(document, %w(version env default_editable_env environment_presets lfs steps))
75
+ unknown_keys!(document, %w(version env default_editable_env environment_presets lfs sleep steps))
65
76
  raise Invalid, 'steps must be a nonempty array' unless document['steps'].is_a?(Array) && !document['steps'].empty?
66
77
  end
67
78
 
@@ -131,6 +142,23 @@ module Workspaces
131
142
  paths.uniq
132
143
  end
133
144
 
145
+ # `sleep: { ignore_paths: [glob, ...] }` names preview paths that are background polling, so they
146
+ # do not keep an otherwise idle workspace awake. Globs match the request path (without the query).
147
+ def validate_sleep!(value)
148
+ raise Invalid, 'sleep must be a mapping' unless value.is_a?(Hash)
149
+
150
+ unknown_keys!(value, %w(ignore_paths))
151
+ paths = value.fetch('ignore_paths', [])
152
+ raise Invalid, 'sleep.ignore_paths must be an array of paths' unless paths.is_a?(Array)
153
+
154
+ paths.each do |path|
155
+ unless path.is_a?(String) && path.start_with?('/') && path == path.strip && !path.match?(/[[:cntrl:]]/)
156
+ raise Invalid, 'sleep.ignore_paths entries must be trimmed strings starting with /'
157
+ end
158
+ end
159
+ paths.uniq
160
+ end
161
+
134
162
  def validate_env!(values)
135
163
  raise Invalid, 'env must be a mapping' unless values.is_a?(Hash)
136
164
  values.each do |key, value|
@@ -41,6 +41,8 @@ module Workspaces
41
41
  end
42
42
  end
43
43
 
44
+ # Removes the workspace and its saved settings and secrets. Returns the secrets that could not be
45
+ # removed (empty when all went), so callers can say so rather than report a clean removal.
44
46
  def remove(id, force: false)
45
47
  with_lock(id) do |workspace|
46
48
  raise ArgumentError, 'Workspace has uncommitted/untracked work' if !force && workspace.dirty?
@@ -48,9 +50,33 @@ module Workspaces
48
50
  Backend.new(id).stop!
49
51
  workspace.remove!(force: force)
50
52
  StateStore.new(Config.state_file).delete(id)
53
+ EnvironmentOverrides.new(id).clear!
51
54
  end
52
55
  end
53
56
 
57
+ # Deletes stored secrets whose workspace no longer exists: removed by hand, with `git worktree
58
+ # remove`, or by a purge that failed. Returns { 'removed' => [...], 'kept' => [...],
59
+ # 'problems' => [...] }.
60
+ #
61
+ # It decides a workspace is gone only from the managed directory, and refuses to guess when that
62
+ # directory cannot be read, so a missing or unmounted volume is never mistaken for "everything
63
+ # was deleted". With dry_run it reports what it would remove and changes nothing.
64
+ def sweep_orphaned_secrets(dry_run: false)
65
+ root = Config.worktrees_dir(create: false)
66
+ unless root.directory? && !root.symlink?
67
+ raise ArgumentError, 'The workspaces directory cannot be read, so nothing was removed'
68
+ end
69
+
70
+ live = root.children.select { |path| path.directory? && !path.symlink? }.map { |path| path.basename.to_s }
71
+ orphans = Vault.scopes - live
72
+ result = { 'removed' => [], 'kept' => live & Vault.scopes, 'problems' => [] }
73
+ orphans.each do |id|
74
+ problems = dry_run ? [] : Vault.purge_everywhere(id)
75
+ problems.empty? ? result['removed'] << id : result['problems'].concat(problems.map { |problem| "#{id}: #{problem}" })
76
+ end
77
+ result
78
+ end
79
+
54
80
  def update_pr(id)
55
81
  with_lock(id) do |workspace|
56
82
  result = workspace.update_from_pr!
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'config'
4
+ require_relative 'recipe'
5
+
6
+ module Workspaces
7
+ # Which preview requests count as someone using a workspace. Health probes and the paths a recipe
8
+ # lists under `sleep.ignore_paths` are background traffic: they neither keep a workspace awake
9
+ # nor wake a sleeping one.
10
+ class SleepPolicy
11
+ DEFAULT_IGNORED_PATHS = %w(/health /up).freeze
12
+
13
+ def initialize(recipe_path: nil)
14
+ @recipe_path = recipe_path
15
+ @cached = nil
16
+ end
17
+
18
+ def ignored?(request_path)
19
+ globs.any? { |glob| File.fnmatch?(glob, request_path.to_s, File::FNM_EXTGLOB) }
20
+ end
21
+
22
+ private
23
+
24
+ def globs
25
+ path = @recipe_path || Config.repo_root.join('.workspaces.yml')
26
+ stamp = path.file? ? path.mtime : nil
27
+ return @cached[1] if @cached && @cached[0] == [path, stamp]
28
+
29
+ @cached = [[path, stamp], DEFAULT_IGNORED_PATHS + configured_globs(path)]
30
+ @cached[1]
31
+ end
32
+
33
+ def configured_globs(path)
34
+ Recipe.new(root: path.dirname).sleep_ignore_paths
35
+ rescue Recipe::Invalid
36
+ []
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'config'
4
+
5
+ module Workspaces
6
+ # Puts ready workspaces to sleep once they have seen no preview traffic for a while. It only
7
+ # decides when; stopping the server, and every check that must hold while it does, is the
8
+ # coordinator's. The tracker is what keeps a request that is being served from being cut off.
9
+ class Sleeper
10
+ def initialize(coordinator:, tracker:, threshold: Config.sleep_after_seconds, interval: Config.sleep_sweep_seconds)
11
+ @coordinator = coordinator
12
+ @tracker = tracker
13
+ @threshold = threshold
14
+ @interval = interval
15
+ @thread = nil
16
+ end
17
+
18
+ # Settles anything a previous front door left half done, then sweeps on a timer.
19
+ def start
20
+ return self if @threshold.nil?
21
+
22
+ @coordinator.reconcile_sleep
23
+ @thread = Thread.new do
24
+ loop do
25
+ sleep @interval
26
+ sweep
27
+ end
28
+ end
29
+ self
30
+ end
31
+
32
+ def stop
33
+ @thread&.kill
34
+ @thread = nil
35
+ end
36
+
37
+ def sweep
38
+ return [] if @threshold.nil?
39
+
40
+ @coordinator.sleep_candidates.select do |id|
41
+ @tracker.sleep_if_idle(id, @threshold) { @coordinator.sleep!(id) }
42
+ rescue StandardError => e
43
+ warn "[Workspaces] could not put #{id} to sleep: #{e.class}"
44
+ false
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,174 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'openssl'
4
+ require 'json'
5
+ require 'securerandom'
6
+ require_relative '../config'
7
+
8
+ module Workspaces
9
+ module Vault
10
+ # An encrypted file per workspace under $WORKSPACES_HOME/vault, readable only with the master key
11
+ # in WORKSPACES_MASTER_KEY (32 random bytes, base64 encoded: `openssl rand -base64 32`).
12
+ #
13
+ # Each workspace gets its own AES-256-GCM key, derived from the master key with HKDF, and its id is
14
+ # bound into the ciphertext, so a file copied to another workspace's name does not decrypt. Names
15
+ # are encrypted along with values. The master key lives only in the environment of the process
16
+ # that runs `serve`; ChildEnv keeps it out of everything that process starts.
17
+ class FileVault < Provider
18
+ KEY_ENV = 'WORKSPACES_MASTER_KEY'
19
+ FORMAT_VERSION = 1
20
+ HKDF_SALT = 'workspaces-vault-v1'
21
+ GENERATE_HINT = 'openssl rand -base64 32'
22
+
23
+ def initialize(home: Config.home, env: ENV)
24
+ super()
25
+ @home = home
26
+ @env = env
27
+ end
28
+
29
+ def name
30
+ 'file'
31
+ end
32
+
33
+ def problem
34
+ text = @env.fetch(KEY_ENV, '').to_s.strip
35
+ if text.empty?
36
+ return "Secrets are turned off. Set #{KEY_ENV} where `workspaces serve` runs " \
37
+ "(generate one with: #{GENERATE_HINT})."
38
+ end
39
+ return nil if master_key
40
+
41
+ "#{KEY_ENV} must be 32 random bytes, base64 encoded (generate one with: #{GENERATE_HINT})."
42
+ end
43
+
44
+ def read(scope)
45
+ path = file_for(scope)
46
+ return {} unless path.exist?
47
+
48
+ require_usable!
49
+ decrypt(scope, path.binread)
50
+ end
51
+
52
+ def write(scope, entries)
53
+ path = file_for(scope)
54
+ return purge(scope) if entries.empty?
55
+
56
+ require_usable!
57
+ ensure_directory!
58
+ store(path, encrypt(scope, entries))
59
+ end
60
+
61
+ def purge(scope)
62
+ path = file_for(scope)
63
+ File.unlink(path) if path.exist? || path.symlink?
64
+ end
65
+
66
+ # The workspace ids that have a file here, found by name alone (no key needed). A symlinked
67
+ # or missing directory has none that can be trusted, so it lists nothing.
68
+ def scopes
69
+ return [] if directory.symlink? || !directory.directory?
70
+
71
+ directory.children.filter_map do |path|
72
+ next unless path.extname == '.enc' && !path.symlink? && path.file?
73
+
74
+ id = path.basename('.enc').to_s
75
+ id if id.match?(/\A[a-z0-9]+(?:-[a-z0-9]+)*\z/) && id.length <= 48
76
+ end.sort
77
+ end
78
+
79
+ private
80
+
81
+ def require_usable!
82
+ reason = problem
83
+ raise Unavailable, reason if reason
84
+ end
85
+
86
+ def master_key
87
+ decoded = decode64(@env.fetch(KEY_ENV, '').to_s.strip)
88
+ decoded.bytesize == 32 ? decoded : nil
89
+ rescue ArgumentError
90
+ nil
91
+ end
92
+
93
+ # Strict base64 without the base64 gem, which is no longer a default gem from Ruby 3.4.
94
+ def encode64(bytes)
95
+ [bytes].pack('m0')
96
+ end
97
+
98
+ def decode64(text)
99
+ text.unpack1('m0')
100
+ end
101
+
102
+ def key_for(scope)
103
+ OpenSSL::KDF.hkdf(master_key, salt: HKDF_SALT, info: "workspace:#{scope}", length: 32, hash: 'SHA256')
104
+ end
105
+
106
+ def encrypt(scope, entries)
107
+ cipher = OpenSSL::Cipher.new('aes-256-gcm').encrypt
108
+ cipher.key = key_for(scope)
109
+ iv = cipher.random_iv
110
+ cipher.auth_data = scope
111
+ ciphertext = cipher.update(JSON.generate(entries)) + cipher.final
112
+ JSON.generate('v' => FORMAT_VERSION, 'iv' => encode64(iv),
113
+ 'tag' => encode64(cipher.auth_tag), 'data' => encode64(ciphertext))
114
+ end
115
+
116
+ def decrypt(scope, document)
117
+ parsed = JSON.parse(document)
118
+ raise Unavailable, 'The stored secrets use an unknown format' unless parsed['v'] == FORMAT_VERSION
119
+
120
+ cipher = OpenSSL::Cipher.new('aes-256-gcm').decrypt
121
+ cipher.key = key_for(scope)
122
+ cipher.iv = decode64(parsed.fetch('iv'))
123
+ cipher.auth_tag = decode64(parsed.fetch('tag'))
124
+ cipher.auth_data = scope
125
+ entries = JSON.parse(cipher.update(decode64(parsed.fetch('data'))) + cipher.final)
126
+ raise Unavailable, 'The stored secrets are damaged' unless entries.is_a?(Hash)
127
+
128
+ entries
129
+ rescue OpenSSL::Cipher::CipherError, JSON::ParserError, KeyError, ArgumentError, TypeError
130
+ raise Unavailable, "The stored secrets could not be decrypted: wrong #{KEY_ENV}, or the file is damaged"
131
+ end
132
+
133
+ def directory
134
+ @home.join('vault')
135
+ end
136
+
137
+ def file_for(scope)
138
+ Config.validate_id!(scope.to_s)
139
+ reject_symlink!(directory)
140
+ path = directory.join("#{scope}.enc")
141
+ reject_symlink!(path)
142
+ path
143
+ end
144
+
145
+ def ensure_directory!
146
+ directory.mkpath unless directory.exist?
147
+ raise Unavailable, 'The secret vault path is not a directory' unless directory.directory?
148
+
149
+ File.chmod(0o700, directory)
150
+ end
151
+
152
+ def store(path, document)
153
+ temp = directory.join(".#{path.basename}.#{Process.pid}.#{SecureRandom.hex(6)}.tmp")
154
+ begin
155
+ File.open(temp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file|
156
+ file.write(document)
157
+ file.flush
158
+ file.fsync
159
+ end
160
+ File.rename(temp, path)
161
+ File.chmod(0o600, path)
162
+ ensure
163
+ File.unlink(temp) if temp.exist?
164
+ end
165
+ end
166
+
167
+ def reject_symlink!(path)
168
+ raise Unavailable, 'The secret vault does not allow symlinks' if path.symlink?
169
+ end
170
+ end
171
+
172
+ register('file', FileVault)
173
+ end
174
+ end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Workspaces
4
+ # Where write-only secrets live. The dashboard can put a secret in and a workspace's steps can read it
5
+ # back out, but nothing here ever hands a value to the interface.
6
+ #
7
+ # A provider stores one set of name => value strings per scope (a workspace id) and is chosen with
8
+ # WORKSPACES_VAULT (default "file"). Register another with Vault.register(name, ProviderClass). The
9
+ # contract is small on purpose so that a remote store fits behind it:
10
+ #
11
+ # available? / problem whether it can be used, and if not, a plain-language reason that never
12
+ # contains key material
13
+ # read(scope) the whole set, {} when there is none; raises Unavailable when a set exists
14
+ # but cannot be read
15
+ # write(scope, entries) replaces the whole set; an empty hash removes it
16
+ # purge(scope) removes the set (used when a workspace is removed)
17
+ module Vault
18
+ class Error < StandardError; end
19
+ class Unavailable < Error; end
20
+
21
+ DEFAULT_PROVIDER = 'file'
22
+
23
+ # The shape every provider follows. Providers inherit it so a missing method fails loudly.
24
+ class Provider
25
+ def name
26
+ raise NotImplementedError, "#{self.class} must name itself"
27
+ end
28
+
29
+ def problem
30
+ nil
31
+ end
32
+
33
+ def available?
34
+ problem.nil?
35
+ end
36
+
37
+ def read(_scope)
38
+ raise NotImplementedError, "#{self.class} must implement read"
39
+ end
40
+
41
+ def write(_scope, _entries)
42
+ raise NotImplementedError, "#{self.class} must implement write"
43
+ end
44
+
45
+ def purge(_scope)
46
+ raise NotImplementedError, "#{self.class} must implement purge"
47
+ end
48
+
49
+ # Every scope this provider holds secrets for. Used to find the ones whose workspace is gone, so
50
+ # a provider that cannot list its scopes returns nil and is simply never swept.
51
+ def scopes
52
+ nil
53
+ end
54
+
55
+ def status
56
+ { 'provider' => name, 'available' => available?, 'problem' => problem }
57
+ end
58
+ end
59
+
60
+ # Stands in for a provider name nobody registered, so a typo shows up as a clear message in the
61
+ # dashboard rather than an exception while rendering it.
62
+ class Unknown < Provider
63
+ def initialize(requested)
64
+ super()
65
+ @requested = requested.to_s[0, 40]
66
+ end
67
+
68
+ def name
69
+ @requested
70
+ end
71
+
72
+ def problem
73
+ "Unknown secret vault provider #{@requested.inspect}"
74
+ end
75
+
76
+ # Nothing can be stored under an unknown provider, so there is nothing to read or remove; a typo
77
+ # in WORKSPACES_VAULT must not stop workspaces that have no secrets from running.
78
+ def read(_scope)
79
+ {}
80
+ end
81
+
82
+ def write(_scope, _entries)
83
+ raise Unavailable, problem
84
+ end
85
+
86
+ def purge(_scope)
87
+ nil
88
+ end
89
+
90
+ def scopes
91
+ nil
92
+ end
93
+ end
94
+
95
+ @providers = {}
96
+
97
+ class << self
98
+ def register(name, provider_class)
99
+ @providers[name.to_s] = provider_class
100
+ end
101
+
102
+ def provider(name = ENV.fetch('WORKSPACES_VAULT', nil))
103
+ requested = name.to_s.strip
104
+ requested = DEFAULT_PROVIDER if requested.empty?
105
+ klass = @providers[requested]
106
+ klass ? klass.new : Unknown.new(requested)
107
+ end
108
+
109
+ def status
110
+ provider.status
111
+ end
112
+
113
+ # Removes a workspace's secrets, whatever WORKSPACES_VAULT says now. The built-in file vault is
114
+ # always asked, because its files stay on disk when the setting is changed or mistyped; the
115
+ # configured provider is asked as well when it is a different one. Returns the problems it
116
+ # could not clear, as plain sentences with no key material, so a caller can say so instead of
117
+ # reporting a removal that left secrets behind.
118
+ # Scopes held by the built-in file vault and the configured provider, for finding orphans.
119
+ def scopes
120
+ [@providers.fetch(DEFAULT_PROVIDER).new, provider].uniq(&:name).flat_map { |vault| vault.scopes || [] }.uniq.sort
121
+ rescue StandardError
122
+ []
123
+ end
124
+
125
+ def purge_everywhere(scope)
126
+ providers = [@providers.fetch(DEFAULT_PROVIDER).new, provider]
127
+ providers.uniq(&:name).each_with_object([]) do |vault, problems|
128
+ vault.purge(scope)
129
+ rescue StandardError => e
130
+ problems << "#{vault.name}: #{e.message}"
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end
136
+
137
+ require_relative 'vault/file_vault'
@@ -1,3 +1,3 @@
1
1
  module Workspaces
2
- VERSION = '0.1.16'
2
+ VERSION = '0.1.18'
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: workspaces
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.16
4
+ version: 0.1.18
5
5
  platform: ruby
6
6
  authors:
7
7
  - Workspaces contributors
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-10-22 00:00:00.000000000 Z
11
+ date: 2026-10-27 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rack
@@ -70,6 +70,7 @@ files:
70
70
  - README.md
71
71
  - exe/workspaces
72
72
  - lib/workspaces.rb
73
+ - lib/workspaces/activity_tracker.rb
73
74
  - lib/workspaces/backend.rb
74
75
  - lib/workspaces/build_history.rb
75
76
  - lib/workspaces/child_env.rb
@@ -95,10 +96,14 @@ files:
95
96
  - lib/workspaces/recipe.rb
96
97
  - lib/workspaces/registry.rb
97
98
  - lib/workspaces/resume_plan.rb
99
+ - lib/workspaces/sleep_policy.rb
100
+ - lib/workspaces/sleeper.rb
98
101
  - lib/workspaces/state_store.rb
99
102
  - lib/workspaces/step_log.rb
100
103
  - lib/workspaces/tee_log.rb
101
104
  - lib/workspaces/tls.rb
105
+ - lib/workspaces/vault.rb
106
+ - lib/workspaces/vault/file_vault.rb
102
107
  - lib/workspaces/version.rb
103
108
  - lib/workspaces/workflow.rb
104
109
  - lib/workspaces/worktree.rb