envpact 0.1.0 → 0.2.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ea8d94a55e0713c1d0d76ce40d98d6e968f8c7bdb9192c93321108fe30baf6bf
4
- data.tar.gz: 342ec3385b66b5e9cfbce86d0fb5b063545c5ccb46ca3850288664a2e994e515
3
+ metadata.gz: da974c4d12c7f439fcac9342baa8a11d26b5eead394db63293344d277c2b0f65
4
+ data.tar.gz: 3922e47cede517c75c27722a00d14a559597b585c2e57720f0e54fff61e3e2a7
5
5
  SHA512:
6
- metadata.gz: ef274e41ef38671428929c754517a70fe64d8a5ce537ede93a88afb9647ff29e8ffcfa7402612e715f5b626458c037b29e113458865cc857d0781d8b59b1f722
7
- data.tar.gz: '008ba026353f7bed742bb0c1dd509134bdb83f6e49d1091f13b75f7eba4fa70f31a9395c1ab6edb225ac0ae5948d43a0c312aa27c4a5eda6a5fa31f16f9af1cb'
6
+ metadata.gz: 1c4c504f56b25897ecd46df80291bb8b7c92558db003ac105d99d3f80725a4390f3a86b2c9dfba44dfaa5a2df68538dfcbcc29c7aaa7ac1331c1a971489b117c
7
+ data.tar.gz: 6aab60acae1b4e8edea71884a33c5d82eabe1e5c9e736d6bd6841168e2c0f59f2a025f468e9ac00959f00e662e025feb9861ae3ab969df9dbf155b2c55af3597
data/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 — 2026-11-22
4
+
5
+ envpact now talks to [OpenBao](https://openbao.org) (KV v2) and keeps the
6
+ env's secrets in sync with the contract.
7
+
8
+ - **Scope change:** 0.1 read only your files and wrote nothing. 0.2 talks to
9
+ OpenBao and writes `~/.ob_read`, `~/.ob_write` and the `pull` target, always
10
+ mode 0600 (temp file + rename, never through a symlink). Nothing else is
11
+ written, and no secret or token is ever printed.
12
+ - **`[source]` section** in `env.spec`: `openbao path=team/app/{env}
13
+ [mount=secret] [addr=URL] [env=a,b]`. API: `spec.source_for(env)`,
14
+ `spec.sources`, `EnvPact::Source.fetch`.
15
+ - **`url(schemes)` type:** `url(postgres, redis)` restricts the URL scheme.
16
+ - **`login`:** OIDC through a loopback listener, or `--token-stdin`; the token
17
+ is stored AES-256-GCM encrypted under a passphrase in `~/.ob_read` /
18
+ `~/.ob_write`.
19
+ - **`unlock` / `lock` / `status`:** a local agent (Unix socket, your uid only)
20
+ holds the read token for a window.
21
+ - **`pull`:** secrets into a 0600 `.env.<env>.local`, only if the contract is
22
+ satisfied.
23
+ - **`run`:** like `exec`, with the secrets injected into the process only.
24
+ - **`push` / `set`:** merge validated secrets into OpenBao after a y/N and the
25
+ write passphrase on the terminal; refused without a terminal.
26
+ - **`check --source`:** check with the OpenBao secrets overlaid in memory.
27
+ - Tests run with UTF-8 forced; `bundler` dev dependency is capped (`< 5`).
28
+
3
29
  ## 0.1.0 — 2026-10-25
4
30
 
5
31
  envpact is the successor of [envspec](https://rubygems.org/gems/envspec) 0.1.2:
data/README.md CHANGED
@@ -12,9 +12,12 @@ three moments:
12
12
  ENV and refuses to start the app if the contract isn't met.
13
13
 
14
14
  Pure Ruby, **zero runtime dependencies**, Ruby ≥ 2.5. envpact knows nothing about
15
- kdep, Infisical or Kubernetes: its interface is *contract + env name + values →
16
- ok or a list of problems*. It never writes to disk and never prints a secret
17
- value (unless you pass `--show-values`).
15
+ kdep or Kubernetes: its interface is *contract + env name + values → ok or a
16
+ list of problems*. It never prints a secret value (unless you pass
17
+ `--show-values` to a local `check`). Since 0.2 it can also fetch and store the
18
+ env's secrets in [OpenBao](https://openbao.org) (see below); that is the only
19
+ thing it talks to, and the only files it writes are `~/.ob_read`, `~/.ob_write`
20
+ and the target of `pull`, always mode 0600.
18
21
 
19
22
  ## Install
20
23
 
@@ -30,6 +33,15 @@ envpact check --env=test # check .env, .env.test, .env.test.local
30
33
  envpact check --env=x --from-env # check the current process ENV instead
31
34
  envpact exec --env=production -- bin/rails server # boot check, then exec
32
35
  envpact scan-prompt | claude # have an agent write env.spec for this repo
36
+
37
+ # secrets in OpenBao (0.2, see "Secrets with OpenBao")
38
+ envpact login --read # log in once a month, token stored encrypted
39
+ envpact unlock --for=2h # keep the read token in a local agent
40
+ envpact pull --env=development # secrets -> .env.development.local (0600)
41
+ envpact run --env=development -- bin/rails s # secrets only in the process
42
+ envpact push --env=production --from=.env.new # write secrets (asks you, on the tty)
43
+ envpact set --env=production STRIPE_KEY # write one secret
44
+ envpact status | envpact lock
33
45
  ```
34
46
 
35
47
  - The contract path defaults to `./env.spec`; override with `--spec=PATH` or
@@ -53,6 +65,54 @@ Composes with Infisical (or anything that injects env) without coupling:
53
65
  infisical run --env=dev -- envpact exec --env=development -- bin/rails s
54
66
  ```
55
67
 
68
+ ## Secrets with OpenBao
69
+
70
+ The `[source]` section of `env.spec` says where each env's secrets live (KV v2):
71
+
72
+ ```
73
+ [source]
74
+ openbao path=team/myapp/{env}
75
+ openbao path=cluster/selly/myapp-web env=production
76
+ ```
77
+
78
+ The server address is `addr=` on the line, else `$BAO_ADDR`. A token is only ever
79
+ sent to the address it was issued for; a spec naming another address is refused.
80
+ The source holds only the keys declared under `[secrets]`; ConfigMap values keep
81
+ coming from `.env*`, `app.yml` and defaults.
82
+
83
+ | Command | What it does |
84
+ |---|---|
85
+ | `login --read` / `login --write --role=NAME` | OIDC login through a loopback listener (`--port=8250`, `--oidc-mount=oidc`), or `--token-stdin` for a token you already have. Asks for a passphrase (min 12 chars) on the terminal and stores the token AES-256-GCM encrypted (PBKDF2-SHA256, 600 000 iterations) in `~/.ob_read` or `~/.ob_write`. A file readable by others is refused, like ssh does. |
86
+ | `unlock [--for=2h]` | Hands the read token to a local agent (Unix socket, 0600, your uid only) for up to 8h and never past the token's expiry. While unlocked, `pull`/`run` ask for nothing. Writes never use the agent. |
87
+ | `lock`, `status` | Stop the agent; show agent and token-file state (never the tokens). |
88
+ | `pull --env=E [--out=PATH]` | Reads the env's secrets, checks them together with the `.env*` files (not the target itself) and, only if the contract is satisfied, writes `.env.<E>.local` (0600). Warns if the file is not git-ignored. |
89
+ | `run --env=E -- CMD` | Like `exec`, but the secrets come from OpenBao and go only into CMD's environment. They override the current ENV; the OpenBao token never reaches CMD. |
90
+ | `push --env=E --from=FILE\|-` | Validates the secret keys in a dotenv file and merges them into the env's path (never deletes a key). |
91
+ | `set --env=E KEY` | Same for one key; the value comes from stdin, or a no-echo prompt on a terminal. |
92
+ | `check --env=E --source` | `check` with the OpenBao secrets overlaid in memory. Not combinable with `--show-values`. |
93
+
94
+ Writes (`push`/`set`) need a human: they show what will be written, ask `y/N` on
95
+ `/dev/tty`, then the passphrase of `~/.ob_write`. With no terminal they refuse
96
+ before any network call. No env var or flag can supply the passphrase or the
97
+ confirmation. Each use of the read token also renews it (`renew-self`).
98
+
99
+ What changed from 0.1: envpact used to read nothing but your own files and write
100
+ nothing. Now it talks to OpenBao and writes `~/.ob_read`, `~/.ob_write` and the
101
+ `pull` target (always 0600, through a temp file and rename, never through a
102
+ symlink).
103
+
104
+ With Claude Code, let it read and run, but make writes and logins ask you, and
105
+ keep it away from the token files (`.claude/settings.json`):
106
+
107
+ ```json
108
+ {
109
+ "permissions": {
110
+ "ask": ["Bash(envpact push:*)", "Bash(envpact set:*)", "Bash(envpact login:*)"],
111
+ "deny": ["Read(~/.ob_read)", "Read(~/.ob_write)", "Bash(cat ~/.ob_*)"]
112
+ }
113
+ }
114
+ ```
115
+
56
116
  ## env.spec syntax
57
117
 
58
118
  ```
@@ -63,6 +123,10 @@ DEBUG?: bool
63
123
  PORT: int = 3000
64
124
  PUBLIC_URL: url
65
125
 
126
+ [source]
127
+ openbao path=team/myapp/{env}
128
+ openbao path=cluster/selly/myapp-web env=production
129
+
66
130
  [secrets]
67
131
  DB_PASS
68
132
  OPENAI_API_KEY
@@ -84,6 +148,7 @@ FEATURE_FLAGS?
84
148
  - `KEY: type` — `str` (default) | `int` | `bool` | `url` | `enum(a, b, c)`.
85
149
  - `bool` accepts `true false 1 0 yes no` (any case).
86
150
  - `url` needs a scheme and a host: `postgres://u:p@h:5432/db`, `https://x.y`.
151
+ - `url(postgres, redis)` also restricts the scheme (case-insensitive).
87
152
  - `KEY = default` — default value, ConfigMap only; secrets cannot have defaults.
88
153
  The default must be valid for the type (`PORT: int = 3OOO` is a lint error).
89
154
  Quote it to keep `#` or surrounding spaces: `GREETING = "hi # there "`
@@ -99,6 +164,10 @@ FEATURE_FLAGS?
99
164
  declared in overlapping scopes, may not be both ConfigMap and Secret, and must
100
165
  have the same type in every env.
101
166
  - Empty values count as absent.
167
+ - `[source]` — where the secrets of each env live, one `openbao path=… [mount=secret]
168
+ [addr=URL] [env=a,b]` line per source. A line without `env=` is the fallback; one
169
+ with `env=` wins for those envs. `{env}` is the only placeholder in `path`.
170
+ - After `[source]` any other header resumes keys; `[secrets]` there applies to shared.
102
171
 
103
172
  ## Library API
104
173
 
@@ -109,6 +178,8 @@ spec = EnvPact.parse_file("env.spec") # or EnvPact.parse(text)
109
178
  spec.envs # env names that have sections
110
179
  spec.configmap_for("production") # shared + production, {key => Entry}
111
180
  spec.secrets_for("production")
181
+ spec.source_for("production") # EnvPact::SourceRef (mount, path, addr) or nil
182
+ EnvPact::Source.fetch(spec, env: "production", client: client) # {secret key => value} from OpenBao
112
183
 
113
184
  result = spec.check(values, env: "production", strict: false)
114
185
  result.ok? # no errors (warnings allowed)
@@ -0,0 +1,197 @@
1
+ require "socket"
2
+ require "json"
3
+ require "time"
4
+ require "tmpdir"
5
+ require "fileutils"
6
+
7
+ class EnvPact
8
+ # A small local agent that holds the READ token in memory for a window, so
9
+ # `pull`/`run` need no passphrase while it is unlocked. Never used for the
10
+ # write token.
11
+ #
12
+ # Protocol: one JSON line per connection on a Unix socket (0600, in a 0700
13
+ # directory). Ops: token, status (no token), lock.
14
+ module Agent
15
+ MAX_LIFETIME = 8 * 3600
16
+ IO_TIMEOUT = 2
17
+
18
+ # --- paths ------------------------------------------------------------
19
+
20
+ # $ENVPACT_AGENT_SOCK, or <runtime dir>/envpact-<uid>/agent.sock. The
21
+ # default directory is created 0700; one that exists with another owner,
22
+ # a looser mode, or as a symlink is an error.
23
+ def self.socket_path
24
+ if (explicit = ENV["ENVPACT_AGENT_SOCK"]) && !explicit.empty?
25
+ return explicit
26
+ end
27
+ dir = File.join(ENV["XDG_RUNTIME_DIR"] || Dir.tmpdir, "envpact-#{Process.uid}")
28
+ ensure_private_dir(dir)
29
+ File.join(dir, "agent.sock")
30
+ end
31
+
32
+ def self.ensure_private_dir(dir)
33
+ Dir.mkdir(dir, 0o700) unless File.exist?(dir) || File.symlink?(dir)
34
+ st = File.lstat(dir)
35
+ unless st.directory? && st.uid == Process.uid && (st.mode & 0o077).zero?
36
+ raise Error, "#{dir} must be a directory owned by you with mode 0700 (remove it or fix it)"
37
+ end
38
+ end
39
+
40
+ # --- peer checks ------------------------------------------------------
41
+
42
+ def self.uid_allowed?(uid)
43
+ uid == Process.uid
44
+ end
45
+
46
+ # Refuses a connection from another uid. When the OS gives no way to ask,
47
+ # the 0600 socket in a 0700 directory is the guard.
48
+ def self.peer_allowed?(sock)
49
+ uid = peer_uid(sock)
50
+ uid.nil? || uid_allowed?(uid)
51
+ end
52
+
53
+ def self.peer_uid(sock)
54
+ if sock.respond_to?(:getpeereid)
55
+ sock.getpeereid.first
56
+ elsif defined?(Socket::SO_PEERCRED)
57
+ sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_PEERCRED).data.unpack("iII")[1]
58
+ end
59
+ rescue StandardError
60
+ nil
61
+ end
62
+
63
+ def self.cap_until(time)
64
+ [time, Time.now + MAX_LIFETIME].min
65
+ end
66
+
67
+ # --- client -----------------------------------------------------------
68
+
69
+ # Returns the parsed reply, or nil when there is no agent (no socket, or
70
+ # nobody listening).
71
+ def self.request(op)
72
+ path = socket_path
73
+ return nil unless File.socket?(path)
74
+ sock = UNIXSocket.new(path)
75
+ begin
76
+ sock.write(JSON.generate("op" => op) + "\n")
77
+ return nil unless IO.select([sock], nil, nil, IO_TIMEOUT)
78
+ line = sock.gets
79
+ line && JSON.parse(line)
80
+ ensure
81
+ sock.close
82
+ end
83
+ rescue Errno::ENOENT, Errno::ECONNREFUSED, Errno::ENOTSOCK, Errno::EACCES, Errno::ECONNRESET,
84
+ Errno::EPIPE, JSON::ParserError
85
+ nil
86
+ end
87
+
88
+ # --- server -----------------------------------------------------------
89
+
90
+ # Starts the agent in a detached child and returns its pid. A running
91
+ # agent is replaced, a dead socket is cleaned up. The socket is bound
92
+ # here, before the fork, so failures surface in the caller and the socket
93
+ # is ready the moment this returns.
94
+ def self.start(token:, addr:, until_time:)
95
+ path = socket_path
96
+ replace_existing(path)
97
+ until_time = cap_until(until_time)
98
+
99
+ server = bind(path)
100
+ ino = File.stat(path).ino
101
+ pid = fork do
102
+ serve(server, path, ino, token, addr, until_time)
103
+ end
104
+ server.close
105
+ Process.detach(pid)
106
+ pid
107
+ end
108
+
109
+ def self.replace_existing(path)
110
+ return unless File.exist?(path) || File.symlink?(path)
111
+ raise Error, "#{path} exists and is not an agent socket; not touching it" unless File.lstat(path).socket?
112
+ if request("lock")
113
+ 50.times do
114
+ break unless File.exist?(path)
115
+ sleep 0.05
116
+ end
117
+ end
118
+ File.unlink(path) if File.exist?(path)
119
+ end
120
+
121
+ def self.bind(path)
122
+ old = File.umask(0o177)
123
+ begin
124
+ server = UNIXServer.new(path)
125
+ rescue ArgumentError, SystemCallError => e
126
+ raise Error, "cannot create agent socket #{path} (#{e.class.name.split('::').last})"
127
+ ensure
128
+ File.umask(old)
129
+ end
130
+ File.chmod(0o600, path)
131
+ server
132
+ end
133
+
134
+ # Runs in the forked child. Leaves through exit!, so the parent's at_exit
135
+ # hooks (minitest, for one) never run here.
136
+ def self.serve(server, path, ino, token, addr, until_time)
137
+ Process.setsid
138
+ $0 = "envpact-agent"
139
+ Process.setproctitle("envpact-agent") if Process.respond_to?(:setproctitle)
140
+ $stdin.reopen(File::NULL)
141
+ $stdout.reopen(File::NULL, "w")
142
+ $stderr.reopen(File::NULL, "w")
143
+ stop = false
144
+ %w[TERM INT HUP].each { |sig| trap(sig) { stop = true } }
145
+
146
+ until stop
147
+ left = until_time - Time.now
148
+ break if left <= 0
149
+ next unless IO.select([server], nil, nil, [left, 1].min)
150
+ sock = begin
151
+ server.accept
152
+ rescue SystemCallError, IOError
153
+ next
154
+ end
155
+ stop = true if handle(sock, token, addr, until_time)
156
+ end
157
+ rescue StandardError
158
+ nil
159
+ ensure
160
+ begin
161
+ File.unlink(path) if File.socket?(path) && File.stat(path).ino == ino
162
+ rescue SystemCallError
163
+ nil
164
+ end
165
+ exit!(0)
166
+ end
167
+
168
+ # Returns true when the agent should stop (lock).
169
+ def self.handle(sock, token, addr, until_time)
170
+ return false unless peer_allowed?(sock)
171
+ return false unless IO.select([sock], nil, nil, IO_TIMEOUT)
172
+ line = sock.gets
173
+ req = begin
174
+ JSON.parse(line.to_s)
175
+ rescue JSON::ParserError
176
+ nil
177
+ end
178
+ op = req.is_a?(Hash) ? req["op"] : nil
179
+ untill = until_time.utc.iso8601
180
+ reply, stop =
181
+ case op
182
+ when "token" then [{ "token" => token, "addr" => addr, "until" => untill }, false]
183
+ when "status" then [{ "addr" => addr, "until" => untill }, false]
184
+ when "lock" then [{ "ok" => true }, true]
185
+ else [{ "error" => "unknown op" }, false]
186
+ end
187
+ sock.write(JSON.generate(reply) + "\n")
188
+ stop
189
+ rescue SystemCallError, IOError
190
+ false
191
+ ensure
192
+ sock.close unless sock.closed?
193
+ end
194
+
195
+ private_class_method :ensure_private_dir, :peer_uid, :replace_existing, :bind, :serve, :handle
196
+ end
197
+ end
@@ -0,0 +1,27 @@
1
+ class EnvPact
2
+ # Writes a file that is 0600 from its first byte, via a temp file in the
3
+ # same directory and a rename, so readers never see a partial file.
4
+ module AtomicFile
5
+ def self.write(path, content)
6
+ raise Error, "refusing to write through symlink #{path}" if File.symlink?(path)
7
+
8
+ dir = File.dirname(path)
9
+ tmp = File.join(dir, ".#{File.basename(path)}.#{Process.pid}.tmp")
10
+ done = false
11
+ begin
12
+ File.open(tmp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |f|
13
+ f.chmod(0o600) # the umask can only remove bits, but be explicit
14
+ f.binmode
15
+ f.write(content)
16
+ f.flush
17
+ f.fsync
18
+ end
19
+ File.rename(tmp, path)
20
+ done = true
21
+ ensure
22
+ File.unlink(tmp) if !done && (File.exist?(tmp) || File.symlink?(tmp))
23
+ end
24
+ nil
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,25 @@
1
+ class EnvPact
2
+ # Shared by `exec` and `run`: the last steps before handing the process to
3
+ # the app.
4
+ module Boot
5
+ # Fills defaults for absent or empty keys of env into the process ENV.
6
+ def self.fill_defaults(spec, env)
7
+ spec.configmap_for(env).each do |key, entry|
8
+ next if entry.default.nil?
9
+ ENV[key] = entry.default if ENV[key].nil? || ENV[key].empty?
10
+ end
11
+ end
12
+
13
+ # Replaces this process with argv. Only returns on failure, with the
14
+ # exit code (127 not found, 126 not executable) after printing why.
15
+ def self.exec_command(argv)
16
+ Kernel.exec(*argv)
17
+ rescue Errno::ENOENT
18
+ warn "envpact: command not found: #{argv.first}"
19
+ 127
20
+ rescue Errno::EACCES, Errno::ENOEXEC => e
21
+ warn "envpact: cannot execute: #{argv.first} (#{e.message})"
22
+ 126
23
+ end
24
+ end
25
+ end
@@ -23,10 +23,12 @@ class EnvPact
23
23
  o.on("--from-env", "Check the current process ENV, not files") { opts[:from_env] = true }
24
24
  o.on("--strict", "Treat unknown env vars as errors") { opts[:strict] = true }
25
25
  o.on("--show-values", "Show secret values in problem messages") { opts[:show_values] = true }
26
+ o.on("--source", "Also read the env's secrets from OpenBao (in memory, nothing is written)") { opts[:source] = true }
26
27
  end
27
28
 
28
29
  def call(_rest, opts)
29
30
  env = opts[:env] or raise UsageError, "--env=NAME is required"
31
+ raise UsageError, "--show-values cannot be combined with --source" if opts[:source] && opts[:show_values]
30
32
  spec = load_spec(opts)
31
33
 
32
34
  if opts[:from_env]
@@ -37,7 +39,11 @@ class EnvPact
37
39
  puts "Read: #{loaded[:files].empty? ? '(no .env files found)' : loaded[:files].join(', ')}"
38
40
  end
39
41
 
42
+ source_warnings = []
43
+ values = values.merge(fetch_source(spec, env, warnings: source_warnings)) if opts[:source]
44
+
40
45
  result = spec.check(values, env: env, strict: opts[:strict], extras: !opts[:from_env])
46
+ source_warnings.each { |p| warn " ! #{p.message}" }
41
47
  report(spec, result, opts, reveal: opts[:show_values] ? values : nil)
42
48
  end
43
49
  end
@@ -37,9 +37,10 @@ class EnvPact
37
37
  end
38
38
  end
39
39
 
40
- def initialize
40
+ def initialize(prompt: nil)
41
41
  @opts = default_opts
42
42
  @help_requested = false
43
+ @prompt = prompt || EnvPact::Prompt.new
43
44
  end
44
45
 
45
46
  def default_opts
@@ -109,6 +110,21 @@ class EnvPact
109
110
 
110
111
  # Prints the result and returns the exit code. reveal: is the values
111
112
  # hash when the user asked for --show-values; extras never show values.
113
+ # The env's secrets from OpenBao (see EnvPact::Source.fetch). Extras
114
+ # found in the source go to warnings.
115
+ def fetch_source(spec, env, warnings: nil)
116
+ ref = spec.source_for(env)
117
+ raise EnvPact::Error, "no [source] for env '#{env}' in env.spec" if ref.nil?
118
+ client = Credentials.new(prompt: @prompt).read_client(ref.addr)
119
+ values = Source.fetch(spec, env: env, client: client, warnings: warnings)
120
+ begin
121
+ client.renew_self # keeps the monthly login monthly
122
+ rescue OpenBao::Error
123
+ nil
124
+ end
125
+ values
126
+ end
127
+
112
128
  def report(spec, result, opts, reveal: nil)
113
129
  name = File.basename(spec_path(opts))
114
130
  scope = "(#{scope_label(spec, result)})"
@@ -39,21 +39,8 @@ class EnvPact
39
39
  # stderr, so the app's stdout stays its own; shows which sections
40
40
  # applied, which is how an ENVPACT_ENV typo becomes visible at boot.
41
41
  warn "✓ #{File.basename(spec_path(opts))} satisfied (#{scope_label(spec, result)})"
42
- fill_defaults(spec, env)
43
- Kernel.exec(*@command)
44
- rescue Errno::ENOENT
45
- die("command not found: #{@command.first}", 127)
46
- rescue Errno::EACCES, Errno::ENOEXEC => e
47
- die("cannot execute: #{@command.first} (#{e.message})", 126)
48
- end
49
-
50
- private
51
-
52
- def fill_defaults(spec, env)
53
- spec.configmap_for(env).each do |key, entry|
54
- next if entry.default.nil?
55
- ENV[key] = entry.default if ENV[key].nil? || ENV[key].empty?
56
- end
42
+ Boot.fill_defaults(spec, env)
43
+ Boot.exec_command(@command)
57
44
  end
58
45
  end
59
46
  end
@@ -0,0 +1,20 @@
1
+ require_relative "command"
2
+
3
+ class EnvPact
4
+ class CLI
5
+ class Lock < Command
6
+ command_name "lock"
7
+ summary "Stop the local agent and forget the read token"
8
+ banner "Usage: envpact lock"
9
+
10
+ def call(_rest, _opts)
11
+ if Agent.request("lock")
12
+ puts "✓ agent locked"
13
+ else
14
+ puts "no agent running"
15
+ end
16
+ 0
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,97 @@
1
+ require "time"
2
+ require_relative "command"
3
+
4
+ class EnvPact
5
+ class CLI
6
+ class Login < Command
7
+ command_name "login"
8
+ summary "Log in to OpenBao and store the token, encrypted, in ~/.ob_read or ~/.ob_write"
9
+ banner "Usage: envpact login --read|--write [options]"
10
+ description <<~DESC
11
+ Logs in with OIDC (opens a browser, waits on 127.0.0.1) or takes a token
12
+ from stdin (--token-stdin), then asks for a passphrase on the terminal
13
+ and stores the token encrypted: ~/.ob_read (--read) or ~/.ob_write
14
+ (--write). Without --role, --read uses the server's default role;
15
+ --write needs --role (e.g. --role=escrita).
16
+ The address comes from --addr, $BAO_ADDR or addr= in the env.spec [source].
17
+ DESC
18
+
19
+ MIN_PASSPHRASE = 12
20
+
21
+ def default_opts
22
+ { oidc_mount: "oidc", port: 8250, token_stdin: false }
23
+ end
24
+
25
+ def configure(o, opts)
26
+ o.on("--read", "Store the read token (~/.ob_read)") { opts[:kind] = [*opts[:kind], :read] }
27
+ o.on("--write", "Store the write token (~/.ob_write)") { opts[:kind] = [*opts[:kind], :write] }
28
+ o.on("--addr=URL", "OpenBao address (default: $BAO_ADDR or [source] addr=)") { |v| opts[:addr] = v }
29
+ o.on("--role=NAME", "OIDC role") { |v| opts[:role] = v }
30
+ o.on("--oidc-mount=NAME", "OIDC auth mount (default: oidc)") { |v| opts[:oidc_mount] = v }
31
+ o.on("--port=N", Integer, "Loopback port for the OIDC redirect (default: 8250)") { |v| opts[:port] = v }
32
+ o.on("--token-stdin", "Read the token from one line of stdin instead of OIDC") { opts[:token_stdin] = true }
33
+ spec_option(o, opts)
34
+ end
35
+
36
+ def call(_rest, opts)
37
+ kinds = opts[:kind].to_a
38
+ raise UsageError, "give --read or --write" if kinds.empty?
39
+ raise UsageError, "--read and --write are exclusive" if kinds.uniq.size > 1
40
+ kind = kinds.first
41
+ raise UsageError, "--write needs --role=NAME" if kind == :write && opts[:role].nil? && !opts[:token_stdin]
42
+ raise UsageError, "--port must be 0..65535" unless (0..65_535).cover?(opts[:port])
43
+
44
+ addr = resolve_addr(opts)
45
+ unless @prompt.available?
46
+ raise EnvPact::Error, "login needs a terminal to ask for the passphrase"
47
+ end
48
+
49
+ client = OpenBao::Client.new(addr: addr)
50
+ token = opts[:token_stdin] ? read_token_stdin : oidc_token(client, opts)
51
+ authed = OpenBao::Client.new(addr: addr, token: token, role: kind)
52
+ info = authed.lookup_self
53
+
54
+ passphrase = ask_new_passphrase
55
+ role = opts[:role] || info["role"] || "default"
56
+ Keyfile.write(kind, token: token, addr: addr, role: role, expire_time: info["expire_time"], passphrase: passphrase)
57
+ puts "✓ logged in (#{kind}, role #{role}, #{expiry_text(info['expire_time'])}) → ~/#{File.basename(Keyfile.path(kind))}"
58
+ 0
59
+ end
60
+
61
+ private
62
+
63
+ def resolve_addr(opts)
64
+ return opts[:addr] if opts[:addr]
65
+ return ENV["BAO_ADDR"] if ENV["BAO_ADDR"] && !ENV["BAO_ADDR"].empty?
66
+ path = spec_path(opts)
67
+ File.file?(path) ? EnvPact.parse_file(path).sources.map(&:addr).compact.first : nil
68
+ end
69
+
70
+ def read_token_stdin
71
+ line = $stdin.gets
72
+ token = line.to_s.strip
73
+ raise EnvPact::Error, "no token on stdin" if token.empty?
74
+ token
75
+ end
76
+
77
+ def oidc_token(client, opts)
78
+ OIDCLogin.new(client: client, mount: opts[:oidc_mount], role: opts[:role], port: opts[:port]).token
79
+ end
80
+
81
+ def ask_new_passphrase
82
+ first = @prompt.secret("New passphrase for the token file (min #{MIN_PASSPHRASE} chars): ")
83
+ raise EnvPact::Error, "passphrase must have at least #{MIN_PASSPHRASE} characters" if first.length < MIN_PASSPHRASE
84
+ again = @prompt.secret("Repeat passphrase: ")
85
+ raise EnvPact::Error, "passphrases do not match" unless first == again
86
+ first
87
+ end
88
+
89
+ def expiry_text(expire_time)
90
+ return "no expiry" if expire_time.nil? || expire_time.to_s.empty?
91
+ "expires #{Time.iso8601(expire_time).localtime.strftime('%Y-%m-%d %H:%M')}"
92
+ rescue ArgumentError
93
+ "expires #{expire_time}"
94
+ end
95
+ end
96
+ end
97
+ end