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 +4 -4
- data/CHANGELOG.md +26 -0
- data/README.md +74 -3
- data/lib/envpact/agent.rb +197 -0
- data/lib/envpact/atomic_file.rb +27 -0
- data/lib/envpact/boot.rb +25 -0
- data/lib/envpact/cli/check.rb +6 -0
- data/lib/envpact/cli/command.rb +17 -1
- data/lib/envpact/cli/exec.rb +2 -15
- data/lib/envpact/cli/lock.rb +20 -0
- data/lib/envpact/cli/login.rb +97 -0
- data/lib/envpact/cli/pull.rb +63 -0
- data/lib/envpact/cli/push.rb +52 -0
- data/lib/envpact/cli/run.rb +46 -0
- data/lib/envpact/cli/set.rb +52 -0
- data/lib/envpact/cli/status.rb +40 -0
- data/lib/envpact/cli/unlock.rb +68 -0
- data/lib/envpact/cli.rb +16 -0
- data/lib/envpact/credentials.rb +61 -0
- data/lib/envpact/dotenv.rb +4 -1
- data/lib/envpact/dotenv_writer.rb +19 -0
- data/lib/envpact/keyfile.rb +109 -0
- data/lib/envpact/oidc_login.rb +144 -0
- data/lib/envpact/open_bao.rb +163 -0
- data/lib/envpact/parser.rb +30 -3
- data/lib/envpact/problem.rb +5 -1
- data/lib/envpact/prompt.rb +56 -0
- data/lib/envpact/scan_prompt.md +2 -0
- data/lib/envpact/source.rb +22 -0
- data/lib/envpact/source_ref.rb +94 -0
- data/lib/envpact/syntax.md +9 -0
- data/lib/envpact/types.rb +5 -3
- data/lib/envpact/version.rb +1 -1
- data/lib/envpact/write_flow.rb +70 -0
- data/lib/envpact.rb +12 -0
- metadata +32 -6
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
require "socket"
|
|
2
|
+
require "securerandom"
|
|
3
|
+
require "uri"
|
|
4
|
+
|
|
5
|
+
class EnvPact
|
|
6
|
+
# OIDC login through a loopback listener, like `bao login -method=oidc`:
|
|
7
|
+
# asks the server for the IdP URL, hands it to a browser, waits for the
|
|
8
|
+
# redirect back to 127.0.0.1, and trades code+state for a client token.
|
|
9
|
+
class OIDCLogin
|
|
10
|
+
CALLBACK_PATH = "/oidc/callback".freeze
|
|
11
|
+
PAGE = "envpact: login ok, you can close this tab\n".freeze
|
|
12
|
+
|
|
13
|
+
# opener is called with the IdP URL; the URL is always printed on stderr
|
|
14
|
+
# too, so a missing browser is not fatal. wait: is the time (seconds) to
|
|
15
|
+
# wait for the redirect.
|
|
16
|
+
def initialize(client:, mount:, role:, port:, opener: self.class.default_opener, wait: 120)
|
|
17
|
+
@client = client
|
|
18
|
+
@mount = mount
|
|
19
|
+
@role = role
|
|
20
|
+
@port = port
|
|
21
|
+
@opener = opener
|
|
22
|
+
@wait = wait
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def self.default_opener
|
|
26
|
+
lambda do |url|
|
|
27
|
+
%w[open xdg-open wslview].each do |bin|
|
|
28
|
+
next unless on_path?(bin)
|
|
29
|
+
system(bin, url, out: File::NULL, err: File::NULL)
|
|
30
|
+
return
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def self.on_path?(bin)
|
|
36
|
+
ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).any? { |d| File.executable?(File.join(d, bin)) }
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def token
|
|
40
|
+
server = listen
|
|
41
|
+
begin
|
|
42
|
+
port = server.addr[1]
|
|
43
|
+
nonce = SecureRandom.hex(16)
|
|
44
|
+
redirect_uri = "http://localhost:#{port}#{CALLBACK_PATH}"
|
|
45
|
+
|
|
46
|
+
params = { "redirect_uri" => redirect_uri, "client_nonce" => nonce }
|
|
47
|
+
params["role"] = @role if @role
|
|
48
|
+
resp = @client.post_unauthenticated("auth/#{@mount}/oidc/auth_url", params)
|
|
49
|
+
auth_url = resp.is_a?(Hash) && resp["data"].is_a?(Hash) ? resp["data"]["auth_url"] : nil
|
|
50
|
+
raise Error, "OpenBao returned no auth_url (is the OIDC role configured?)" if auth_url.to_s.empty?
|
|
51
|
+
expected_state = state_of(auth_url)
|
|
52
|
+
|
|
53
|
+
warn "Open this URL to log in (waiting for the browser):\n #{auth_url}"
|
|
54
|
+
opener = @opener
|
|
55
|
+
Thread.new { begin; opener.call(auth_url); rescue StandardError; nil; end }
|
|
56
|
+
|
|
57
|
+
code, state = wait_for_callback(server, expected_state)
|
|
58
|
+
|
|
59
|
+
out = @client.get_unauthenticated("auth/#{@mount}/oidc/callback",
|
|
60
|
+
"state" => state, "code" => code, "client_nonce" => nonce)
|
|
61
|
+
tok = out.is_a?(Hash) && out["auth"].is_a?(Hash) ? out["auth"]["client_token"] : nil
|
|
62
|
+
raise Error, "OpenBao returned no token for this login" if tok.to_s.empty?
|
|
63
|
+
tok
|
|
64
|
+
ensure
|
|
65
|
+
server.close unless server.closed?
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
private
|
|
70
|
+
|
|
71
|
+
def listen
|
|
72
|
+
TCPServer.new("127.0.0.1", @port)
|
|
73
|
+
rescue SystemCallError => e
|
|
74
|
+
raise Error, "cannot listen on 127.0.0.1:#{@port} (#{e.class.name.split('::').last}); " \
|
|
75
|
+
"pick another with --port"
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def state_of(url)
|
|
79
|
+
q = URI.parse(url).query
|
|
80
|
+
q && URI.decode_www_form(q).to_h["state"]
|
|
81
|
+
rescue URI::InvalidURIError, ArgumentError
|
|
82
|
+
nil
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# Serves requests until one is the callback; returns [code, state]. Other
|
|
86
|
+
# paths get a 404 and are ignored; a callback with the wrong state aborts.
|
|
87
|
+
def wait_for_callback(server, expected_state)
|
|
88
|
+
deadline = Time.now + @wait
|
|
89
|
+
loop do
|
|
90
|
+
left = deadline - Time.now
|
|
91
|
+
raise Error, "login timed out" if left <= 0
|
|
92
|
+
next unless IO.select([server], nil, nil, left)
|
|
93
|
+
sock = server.accept
|
|
94
|
+
begin
|
|
95
|
+
path, query = read_request(sock, deadline)
|
|
96
|
+
if path != CALLBACK_PATH
|
|
97
|
+
respond(sock, 404, "not found\n")
|
|
98
|
+
next
|
|
99
|
+
end
|
|
100
|
+
q = query ? URI.decode_www_form(query).to_h : {}
|
|
101
|
+
if q["code"].to_s.empty? || q["state"].to_s.empty?
|
|
102
|
+
respond(sock, 400, "envpact: missing code or state\n")
|
|
103
|
+
next
|
|
104
|
+
end
|
|
105
|
+
if expected_state.nil? || q["state"] != expected_state
|
|
106
|
+
respond(sock, 400, "envpact: login failed (state mismatch)\n")
|
|
107
|
+
raise Error, "login state mismatch"
|
|
108
|
+
end
|
|
109
|
+
respond(sock, 200, PAGE)
|
|
110
|
+
return [q["code"], q["state"]]
|
|
111
|
+
ensure
|
|
112
|
+
sock.close unless sock.closed?
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def read_request(sock, deadline)
|
|
118
|
+
line = timed_gets(sock, deadline)
|
|
119
|
+
return [nil, nil] unless line
|
|
120
|
+
64.times do
|
|
121
|
+
l = timed_gets(sock, deadline)
|
|
122
|
+
break if l.nil? || l == "\r\n" || l == "\n"
|
|
123
|
+
end
|
|
124
|
+
target = line.split(" ")[1].to_s
|
|
125
|
+
uri = URI.parse(target)
|
|
126
|
+
[uri.path, uri.query]
|
|
127
|
+
rescue URI::InvalidURIError
|
|
128
|
+
[nil, nil]
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def timed_gets(sock, deadline)
|
|
132
|
+
left = [deadline - Time.now, 5].min
|
|
133
|
+
return nil if left <= 0 || !IO.select([sock], nil, nil, left)
|
|
134
|
+
sock.gets
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def respond(sock, status, text)
|
|
138
|
+
sock.write("HTTP/1.1 #{status} X\r\nContent-Type: text/plain; charset=utf-8\r\n" \
|
|
139
|
+
"Content-Length: #{text.bytesize}\r\nConnection: close\r\n\r\n#{text}")
|
|
140
|
+
rescue SystemCallError, IOError
|
|
141
|
+
nil
|
|
142
|
+
end
|
|
143
|
+
end
|
|
144
|
+
end
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
require "net/http"
|
|
2
|
+
require "openssl"
|
|
3
|
+
require "json"
|
|
4
|
+
require "uri"
|
|
5
|
+
|
|
6
|
+
class EnvPact
|
|
7
|
+
# The only piece of envpact that speaks HTTP: a KV v2 client for OpenBao.
|
|
8
|
+
# Error messages carry the address, mount/path and HTTP status, never a
|
|
9
|
+
# token, a request or response body, or a header.
|
|
10
|
+
module OpenBao
|
|
11
|
+
class Error < EnvPact::Error; end
|
|
12
|
+
class NotFound < Error; end
|
|
13
|
+
class Denied < Error; end
|
|
14
|
+
|
|
15
|
+
class Client
|
|
16
|
+
SAFE_PATH_RE = %r{\A[A-Za-z0-9_./-]+\z}.freeze
|
|
17
|
+
TOKEN_RE = /\A[!-~]+\z/.freeze
|
|
18
|
+
DEFAULT_TIMEOUT = 10
|
|
19
|
+
|
|
20
|
+
# role (:read or :write) only picks the hint in the Denied message.
|
|
21
|
+
def initialize(addr:, token: nil, role: :read, timeout: DEFAULT_TIMEOUT)
|
|
22
|
+
if addr.nil? || addr.to_s.strip.empty?
|
|
23
|
+
raise Error, "no OpenBao address: set addr= in [source] or $BAO_ADDR"
|
|
24
|
+
end
|
|
25
|
+
@addr = addr.to_s.strip.sub(%r{/+\z}, "")
|
|
26
|
+
@uri = parse_addr(@addr)
|
|
27
|
+
if token && !TOKEN_RE.match?(token)
|
|
28
|
+
raise Error, "invalid token format"
|
|
29
|
+
end
|
|
30
|
+
@token = token
|
|
31
|
+
@role = role
|
|
32
|
+
@timeout = timeout
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def inspect
|
|
36
|
+
"#<#{self.class} addr=#{addr} token=[redacted]>"
|
|
37
|
+
end
|
|
38
|
+
alias to_s inspect
|
|
39
|
+
|
|
40
|
+
attr_reader :addr
|
|
41
|
+
|
|
42
|
+
# -> Hash{String=>String} or nil when the path does not exist.
|
|
43
|
+
def read(mount, path)
|
|
44
|
+
label = location(mount, path)
|
|
45
|
+
code, body = request("GET", "/v1/#{label_to_data(mount, path)}", label: label, ok: [404])
|
|
46
|
+
return nil if code == 404
|
|
47
|
+
data = body.is_a?(Hash) && body["data"].is_a?(Hash) ? body["data"]["data"] : nil
|
|
48
|
+
return {} unless data.is_a?(Hash)
|
|
49
|
+
data.each do |key, value|
|
|
50
|
+
raise Error, "non-string value for key '#{key}' at #{label}" unless value.is_a?(String)
|
|
51
|
+
end
|
|
52
|
+
data
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Merge-patch; on first write (404) creates the secret.
|
|
56
|
+
def write(mount, path, data)
|
|
57
|
+
label = location(mount, path)
|
|
58
|
+
url = "/v1/#{label_to_data(mount, path)}"
|
|
59
|
+
payload = JSON.generate("data" => data)
|
|
60
|
+
code, = request("PATCH", url, payload, label: label, ok: [404],
|
|
61
|
+
content_type: "application/merge-patch+json")
|
|
62
|
+
request("POST", url, payload, label: label) if code == 404
|
|
63
|
+
nil
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def lookup_self
|
|
67
|
+
_, body = request("GET", "/v1/auth/token/lookup-self", label: "auth/token/lookup-self")
|
|
68
|
+
d = (body.is_a?(Hash) && body["data"]) || {}
|
|
69
|
+
{
|
|
70
|
+
"ttl" => d["ttl"].to_i,
|
|
71
|
+
"expire_time" => d["expire_time"],
|
|
72
|
+
"display_name" => d["display_name"].to_s,
|
|
73
|
+
"policies" => Array(d["policies"]),
|
|
74
|
+
# The auth role the token came from (OIDC/JWT put it in meta.role).
|
|
75
|
+
"role" => (d["meta"]["role"] if d["meta"].is_a?(Hash))
|
|
76
|
+
}
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# A token that cannot be renewed (400) is not an error.
|
|
80
|
+
def renew_self
|
|
81
|
+
code, body = request("POST", "/v1/auth/token/renew-self", "{}", label: "auth/token/renew-self", ok: [400])
|
|
82
|
+
code == 400 ? nil : body
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def post_unauthenticated(path, body)
|
|
86
|
+
_, parsed = request("POST", "/v1/#{safe(path)}", JSON.generate(body), label: path, auth: false)
|
|
87
|
+
parsed
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def get_unauthenticated(path, query)
|
|
91
|
+
qs = URI.encode_www_form(query)
|
|
92
|
+
_, parsed = request("GET", "/v1/#{safe(path)}?#{qs}", label: path, auth: false)
|
|
93
|
+
parsed
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
private
|
|
97
|
+
|
|
98
|
+
def parse_addr(addr)
|
|
99
|
+
uri = URI.parse(addr)
|
|
100
|
+
unless %w[http https].include?(uri.scheme.to_s.downcase) && !uri.host.to_s.empty?
|
|
101
|
+
raise Error, "invalid OpenBao address (expected http(s)://host[:port])"
|
|
102
|
+
end
|
|
103
|
+
uri
|
|
104
|
+
rescue URI::InvalidURIError
|
|
105
|
+
raise Error, "invalid OpenBao address (expected http(s)://host[:port])"
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def safe(path)
|
|
109
|
+
ok = SAFE_PATH_RE.match?(path) && !path.start_with?("/") && !path.split("/").include?("..")
|
|
110
|
+
raise Error, "unsafe OpenBao path '#{path}'" unless ok
|
|
111
|
+
path
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def location(mount, path)
|
|
115
|
+
"#{safe(mount)}/#{safe(path)}"
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def label_to_data(mount, path)
|
|
119
|
+
"#{mount}/data/#{path}"
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Returns [code, parsed_body]. Codes in ok: are returned instead of
|
|
123
|
+
# raised. 2xx always returns.
|
|
124
|
+
def request(method, url, body = nil, label:, ok: [], content_type: "application/json", auth: true)
|
|
125
|
+
http = Net::HTTP.new(@uri.host, @uri.port, nil) # nil: never an env proxy
|
|
126
|
+
http.use_ssl = @uri.scheme.casecmp("https").zero?
|
|
127
|
+
http.open_timeout = @timeout
|
|
128
|
+
http.read_timeout = @timeout
|
|
129
|
+
|
|
130
|
+
req = Net::HTTPGenericRequest.new(method, !body.nil?, true, url)
|
|
131
|
+
req["Accept"] = "application/json"
|
|
132
|
+
req["X-Vault-Token"] = @token if auth && @token
|
|
133
|
+
if body
|
|
134
|
+
req["Content-Type"] = content_type
|
|
135
|
+
req.body = body
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
res = http.start { |h| h.request(req) }
|
|
139
|
+
code = res.code.to_i
|
|
140
|
+
parsed = parse_body(res.body)
|
|
141
|
+
return [code, parsed] if code.between?(200, 299) || ok.include?(code)
|
|
142
|
+
|
|
143
|
+
if code == 403
|
|
144
|
+
raise Denied, "token rejected for #{label} (expired, revoked or not allowed); " \
|
|
145
|
+
"run envpact login --#{@role}"
|
|
146
|
+
end
|
|
147
|
+
raise NotFound, "#{label} not found at #{addr}" if code == 404
|
|
148
|
+
raise Error, "OpenBao at #{addr} answered HTTP #{code} for #{label}"
|
|
149
|
+
rescue Net::OpenTimeout, Net::ReadTimeout, Timeout::Error
|
|
150
|
+
raise Error, "OpenBao at #{addr} timed out"
|
|
151
|
+
rescue SocketError, SystemCallError, EOFError, IOError, OpenSSL::SSL::SSLError => e
|
|
152
|
+
raise Error, "cannot reach OpenBao at #{addr} (#{e.class})"
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
def parse_body(text)
|
|
156
|
+
return {} if text.nil? || text.empty?
|
|
157
|
+
JSON.parse(text)
|
|
158
|
+
rescue JSON::ParserError
|
|
159
|
+
{}
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
end
|
data/lib/envpact/parser.rb
CHANGED
|
@@ -20,7 +20,7 @@ class EnvPact
|
|
|
20
20
|
VALID_TYPES = %i[str int bool url enum].freeze
|
|
21
21
|
ENV_NAME_RE = /\A[A-Za-z0-9_-]+\z/.freeze
|
|
22
22
|
|
|
23
|
-
attr_reader :configmap, :secrets
|
|
23
|
+
attr_reader :configmap, :secrets, :sources
|
|
24
24
|
|
|
25
25
|
def self.parse(text)
|
|
26
26
|
new.tap { |spec| spec.send(:_parse, text) }
|
|
@@ -33,6 +33,13 @@ class EnvPact
|
|
|
33
33
|
def initialize
|
|
34
34
|
@configmap = {}
|
|
35
35
|
@secrets = {}
|
|
36
|
+
@sources = []
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Where the secrets of env live (a SourceRef from the [source] section),
|
|
40
|
+
# or nil when the spec has none for that env.
|
|
41
|
+
def source_for(env)
|
|
42
|
+
SourceParser.resolve(@sources, env)
|
|
36
43
|
end
|
|
37
44
|
|
|
38
45
|
# Returns array of env names declared in the spec (excluding "*").
|
|
@@ -61,6 +68,7 @@ class EnvPact
|
|
|
61
68
|
def _parse(text)
|
|
62
69
|
scope = [SHARED]
|
|
63
70
|
type = :configmap
|
|
71
|
+
in_source = false
|
|
64
72
|
|
|
65
73
|
text = EnvPact.utf8(text).sub(/\A\uFEFF/, "")
|
|
66
74
|
text.each_line.with_index(1) do |raw, line_no|
|
|
@@ -69,7 +77,14 @@ class EnvPact
|
|
|
69
77
|
|
|
70
78
|
if line.start_with?("[") && line.end_with?("]")
|
|
71
79
|
inner = line[1..-2].strip
|
|
72
|
-
|
|
80
|
+
in_source = false
|
|
81
|
+
if inner == "source"
|
|
82
|
+
# No previous scope to inherit: keys after the next header start
|
|
83
|
+
# from shared.
|
|
84
|
+
in_source = true
|
|
85
|
+
scope = [SHARED]
|
|
86
|
+
type = :configmap
|
|
87
|
+
elsif inner == "secrets"
|
|
73
88
|
type = :secret
|
|
74
89
|
elsif inner == "shared"
|
|
75
90
|
scope = [SHARED]
|
|
@@ -88,11 +103,16 @@ class EnvPact
|
|
|
88
103
|
scope = envs
|
|
89
104
|
type = :configmap
|
|
90
105
|
else
|
|
91
|
-
raise ParseError.new("unknown header [#{inner}] (only [secrets], [shared] and [env: ...] allowed)", line_no)
|
|
106
|
+
raise ParseError.new("unknown header [#{inner}] (only [secrets], [shared], [source] and [env: ...] allowed)", line_no)
|
|
92
107
|
end
|
|
93
108
|
next
|
|
94
109
|
end
|
|
95
110
|
|
|
111
|
+
if in_source
|
|
112
|
+
SourceParser.add(@sources, SourceParser.parse_line(line, line_no))
|
|
113
|
+
next
|
|
114
|
+
end
|
|
115
|
+
|
|
96
116
|
entry = parse_key_line(line, line_no)
|
|
97
117
|
if type == :secret && !entry[:default].nil?
|
|
98
118
|
raise ParseError.new("secret '#{entry[:name]}' cannot have a default value", line_no)
|
|
@@ -161,6 +181,13 @@ class EnvPact
|
|
|
161
181
|
values = em[1].split(",").map(&:strip).reject(&:empty?)
|
|
162
182
|
raise ParseError.new("enum requires at least one value", line_no) if values.empty?
|
|
163
183
|
[:enum, values]
|
|
184
|
+
elsif type_str.start_with?("url(")
|
|
185
|
+
unless (um = type_str.match(/\Aurl\((.*)\)\z/))
|
|
186
|
+
raise ParseError.new("malformed url type: #{type_str}", line_no)
|
|
187
|
+
end
|
|
188
|
+
schemes = um[1].split(",").map { |v| v.strip.downcase }.reject(&:empty?)
|
|
189
|
+
raise ParseError.new("url() needs at least one scheme", line_no) if schemes.empty?
|
|
190
|
+
[:url, schemes]
|
|
164
191
|
else
|
|
165
192
|
sym = type_str.to_sym
|
|
166
193
|
unless VALID_TYPES.include?(sym)
|
data/lib/envpact/problem.rb
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
class EnvPact
|
|
2
2
|
# One thing wrong with a set of values checked against a spec.
|
|
3
3
|
#
|
|
4
|
-
# kind is :missing, :invalid or :extra
|
|
4
|
+
# kind is :missing, :invalid or :extra (type: :source marks an extra found
|
|
5
|
+
# in the OpenBao source rather than in the values). value is the offending value for
|
|
5
6
|
# configmap keys only -- it is always nil for secrets and extras, so a
|
|
6
7
|
# Problem can be printed or logged without leaking a secret.
|
|
7
8
|
Problem = Struct.new(:kind, :key, :secret, :line, :value, :type, :enum_values, keyword_init: true) do
|
|
@@ -22,6 +23,7 @@ class EnvPact
|
|
|
22
23
|
when :missing
|
|
23
24
|
"missing required env var '#{key}' (declared at line #{problem.line})"
|
|
24
25
|
when :extra
|
|
26
|
+
return "key '#{key}' in the source is not a declared secret for this env (ignored)" if problem.type == :source
|
|
25
27
|
"unknown env var '#{key}' (not declared in spec)"
|
|
26
28
|
when :invalid
|
|
27
29
|
subject = value.nil? ? "env var '#{key}' (secret)" : "env var '#{key}' = #{value.inspect}"
|
|
@@ -33,6 +35,8 @@ class EnvPact
|
|
|
33
35
|
case type
|
|
34
36
|
when :bool then "is not a valid bool #{BOOL_HINT}"
|
|
35
37
|
when :enum then "is not in enum(#{enum_values.join(', ')})"
|
|
38
|
+
when :url
|
|
39
|
+
enum_values.nil? ? "is not a valid url" : "is not a valid url (scheme: #{enum_values.join(', ')})"
|
|
36
40
|
else "is not a valid #{type}"
|
|
37
41
|
end
|
|
38
42
|
end
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
require "io/console"
|
|
2
|
+
|
|
3
|
+
class EnvPact
|
|
4
|
+
# Asks the human, on the controlling terminal and nowhere else: never stdin,
|
|
5
|
+
# argv or ENV, so a script or an agent driving envpact cannot answer for the
|
|
6
|
+
# user.
|
|
7
|
+
class Prompt
|
|
8
|
+
NO_TTY = "needs a terminal to confirm writes".freeze
|
|
9
|
+
|
|
10
|
+
def initialize(tty_path = "/dev/tty")
|
|
11
|
+
@tty_path = tty_path
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def available?
|
|
15
|
+
File.open(@tty_path, "r+") { |io| io.tty? }
|
|
16
|
+
rescue SystemCallError, IOError
|
|
17
|
+
false
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Reads a line without echo.
|
|
21
|
+
def secret(label)
|
|
22
|
+
with_tty do |tty|
|
|
23
|
+
tty.write(label)
|
|
24
|
+
tty.flush
|
|
25
|
+
line = tty.noecho(&:gets)
|
|
26
|
+
tty.write("\n")
|
|
27
|
+
line.to_s.chomp.chomp("\r")
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# Only "y" / "yes" (any case) is a yes.
|
|
32
|
+
def confirm(label)
|
|
33
|
+
with_tty do |tty|
|
|
34
|
+
tty.write(label)
|
|
35
|
+
tty.flush
|
|
36
|
+
%w[y yes].include?(tty.gets.to_s.strip.downcase)
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
private
|
|
41
|
+
|
|
42
|
+
def with_tty
|
|
43
|
+
tty = begin
|
|
44
|
+
File.open(@tty_path, "r+")
|
|
45
|
+
rescue SystemCallError, IOError
|
|
46
|
+
raise Error, NO_TTY
|
|
47
|
+
end
|
|
48
|
+
begin
|
|
49
|
+
raise Error, NO_TTY unless tty.tty?
|
|
50
|
+
yield tty
|
|
51
|
+
ensure
|
|
52
|
+
tty.close
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
data/lib/envpact/scan_prompt.md
CHANGED
|
@@ -44,6 +44,8 @@ Use exactly this syntax:
|
|
|
44
44
|
|
|
45
45
|
{{SYNTAX}}
|
|
46
46
|
|
|
47
|
+
Do not invent a `[source]` section: if the file already has one, preserve it as is.
|
|
48
|
+
|
|
47
49
|
Put shared keys on top. Group related keys with a short comment. If `env.spec`
|
|
48
50
|
already exists, update it in place: keep its comments and existing decisions, add
|
|
49
51
|
what is missing, and never silently drop a key — if a declared key looks unused,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
class EnvPact
|
|
2
|
+
# Reads the secrets of one env from where the spec's [source] says they
|
|
3
|
+
# live. This is the API the deploy tooling uses.
|
|
4
|
+
module Source
|
|
5
|
+
# -> Hash{String=>String}: only the keys declared as secrets for env. Keys
|
|
6
|
+
# in the source that are not declared secrets are dropped; when warnings
|
|
7
|
+
# (an Array) is given, a Problem(kind: :extra, type: :source) without any
|
|
8
|
+
# value is appended for each. A path that does not exist yields {}.
|
|
9
|
+
def self.fetch(spec, env:, client:, warnings: nil)
|
|
10
|
+
ref = spec.source_for(env)
|
|
11
|
+
raise Error, "no [source] for env '#{env}' in env.spec" if ref.nil?
|
|
12
|
+
|
|
13
|
+
data = client.read(ref.mount, ref.path) || {}
|
|
14
|
+
wanted = spec.secrets_for(env)
|
|
15
|
+
data.each_key do |key|
|
|
16
|
+
next if wanted.key?(key)
|
|
17
|
+
warnings << Problem.new(kind: :extra, key: key, secret: false, type: :source) if warnings
|
|
18
|
+
end
|
|
19
|
+
data.select { |key, _| wanted.key?(key) }
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
require "uri"
|
|
2
|
+
|
|
3
|
+
class EnvPact
|
|
4
|
+
# Where the secrets of one env live: a resolved `[source]` line.
|
|
5
|
+
SourceRef = Struct.new(:backend, :mount, :path, :addr, :line, keyword_init: true)
|
|
6
|
+
|
|
7
|
+
# One raw `[source]` line, before {env} is resolved. envs is nil for the
|
|
8
|
+
# fallback line.
|
|
9
|
+
SourceLine = Struct.new(:backend, :mount, :path, :addr, :envs, :line, keyword_init: true)
|
|
10
|
+
|
|
11
|
+
# Parsing of `openbao k=v ...` lines. The parser only dispatches here.
|
|
12
|
+
module SourceParser
|
|
13
|
+
BACKENDS = %w[openbao].freeze
|
|
14
|
+
OPTIONS = %w[path mount addr env].freeze
|
|
15
|
+
PATH_RE = %r{\A[A-Za-z0-9_./{}-]+\z}.freeze
|
|
16
|
+
MOUNT_RE = /\A[A-Za-z0-9_-]+\z/.freeze
|
|
17
|
+
EXPECTED = "expected 'openbao path=...' in [source]".freeze
|
|
18
|
+
|
|
19
|
+
# Returns a SourceLine. Messages never echo the line, only option names
|
|
20
|
+
# and the offending path/env names.
|
|
21
|
+
def self.parse_line(line, line_no)
|
|
22
|
+
tokens = line.split(/\s+/)
|
|
23
|
+
backend = tokens.shift
|
|
24
|
+
raise ParseError.new(EXPECTED, line_no) unless BACKENDS.include?(backend)
|
|
25
|
+
|
|
26
|
+
opts = {}
|
|
27
|
+
tokens.each do |tok|
|
|
28
|
+
k, v = tok.split("=", 2)
|
|
29
|
+
raise ParseError.new(EXPECTED, line_no) if v.nil? || v.empty?
|
|
30
|
+
raise ParseError.new("unknown option '#{k}' in [source] (valid: #{OPTIONS.join(', ')})", line_no) unless OPTIONS.include?(k)
|
|
31
|
+
raise ParseError.new("duplicate option '#{k}' in [source]", line_no) if opts.key?(k)
|
|
32
|
+
opts[k] = v
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
raise ParseError.new("[source] line needs path=...", line_no) unless opts.key?("path")
|
|
36
|
+
validate_path(opts["path"], line_no)
|
|
37
|
+
mount = opts.fetch("mount", "secret")
|
|
38
|
+
raise ParseError.new("invalid mount '#{mount}' in [source]", line_no) unless MOUNT_RE.match?(mount)
|
|
39
|
+
validate_addr(opts["addr"], line_no) if opts["addr"]
|
|
40
|
+
|
|
41
|
+
envs = opts["env"] && opts["env"].split(",").map(&:strip).reject(&:empty?)
|
|
42
|
+
if envs
|
|
43
|
+
raise ParseError.new("empty env= in [source]", line_no) if envs.empty?
|
|
44
|
+
envs.each do |e|
|
|
45
|
+
raise ParseError.new("invalid env name '#{e}' in [source] env=", line_no) unless EnvPact::ENV_NAME_RE.match?(e)
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
SourceLine.new(backend: backend, mount: mount, path: opts["path"], addr: opts["addr"], envs: envs, line: line_no)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def self.validate_path(path, line_no)
|
|
53
|
+
ok = PATH_RE.match?(path) && !path.start_with?("/") && !path.end_with?("/") &&
|
|
54
|
+
path.split("/", -1).none? { |seg| seg.empty? || seg == ".." || seg == "." } &&
|
|
55
|
+
path.gsub("{env}", "").count("{}").zero?
|
|
56
|
+
raise ParseError.new("invalid path '#{path}' in [source] (allowed: letters, digits, _ . / -, and {env}; " \
|
|
57
|
+
"no '..', no leading or trailing '/')", line_no) unless ok
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def self.validate_addr(addr, line_no)
|
|
61
|
+
uri = URI.parse(addr)
|
|
62
|
+
ok = %w[http https].include?(uri.scheme.to_s.downcase) && !uri.host.to_s.empty?
|
|
63
|
+
raise ParseError.new("addr must be http(s)://host[:port] in [source]", line_no) unless ok
|
|
64
|
+
rescue URI::InvalidURIError
|
|
65
|
+
raise ParseError.new("addr must be http(s)://host[:port] in [source]", line_no)
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# Registers a line into the list, rejecting overlaps.
|
|
69
|
+
def self.add(lines, sl)
|
|
70
|
+
if sl.envs.nil?
|
|
71
|
+
if (prev = lines.find { |l| l.envs.nil? })
|
|
72
|
+
raise ParseError.new("second fallback [source] line (the first is at line #{prev.line}); use env=... to scope it", sl.line)
|
|
73
|
+
end
|
|
74
|
+
else
|
|
75
|
+
sl.envs.each do |e|
|
|
76
|
+
if (prev = lines.find { |l| l.envs && l.envs.include?(e) })
|
|
77
|
+
raise ParseError.new("env '#{e}' is in two [source] lines (the first is at line #{prev.line})", sl.line)
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
lines << sl
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def self.resolve(lines, env)
|
|
85
|
+
unless EnvPact::ENV_NAME_RE.match?(env.to_s)
|
|
86
|
+
raise EnvPact::Error, "invalid env name '#{env}' (must match #{EnvPact::ENV_NAME_RE.source})"
|
|
87
|
+
end
|
|
88
|
+
sl = lines.find { |l| l.envs && l.envs.include?(env) } || lines.find { |l| l.envs.nil? }
|
|
89
|
+
return nil unless sl
|
|
90
|
+
SourceRef.new(backend: sl.backend, mount: sl.mount, path: sl.path.gsub("{env}", env),
|
|
91
|
+
addr: sl.addr, line: sl.line)
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
end
|
data/lib/envpact/syntax.md
CHANGED
|
@@ -6,6 +6,10 @@ DEBUG?: bool
|
|
|
6
6
|
PORT: int = 3000
|
|
7
7
|
PUBLIC_URL: url
|
|
8
8
|
|
|
9
|
+
[source]
|
|
10
|
+
openbao path=team/myapp/{env}
|
|
11
|
+
openbao path=cluster/selly/myapp-web env=production
|
|
12
|
+
|
|
9
13
|
[secrets]
|
|
10
14
|
DB_PASS
|
|
11
15
|
OPENAI_API_KEY
|
|
@@ -27,6 +31,7 @@ FEATURE_FLAGS?
|
|
|
27
31
|
- `KEY: type` — `str` (default) | `int` | `bool` | `url` | `enum(a, b, c)`.
|
|
28
32
|
- `bool` accepts `true false 1 0 yes no` (any case).
|
|
29
33
|
- `url` needs a scheme and a host: `postgres://u:p@h:5432/db`, `https://x.y`.
|
|
34
|
+
- `url(postgres, redis)` also restricts the scheme (case-insensitive).
|
|
30
35
|
- `KEY = default` — default value, ConfigMap only; secrets cannot have defaults.
|
|
31
36
|
The default must be valid for the type (`PORT: int = 3OOO` is a lint error).
|
|
32
37
|
Quote it to keep `#` or surrounding spaces: `GREETING = "hi # there "`
|
|
@@ -42,3 +47,7 @@ FEATURE_FLAGS?
|
|
|
42
47
|
declared in overlapping scopes, may not be both ConfigMap and Secret, and must
|
|
43
48
|
have the same type in every env.
|
|
44
49
|
- Empty values count as absent.
|
|
50
|
+
- `[source]` — where the secrets of each env live, one `openbao path=… [mount=secret]
|
|
51
|
+
[addr=URL] [env=a,b]` line per source. A line without `env=` is the fallback; one
|
|
52
|
+
with `env=` wins for those envs. `{env}` is the only placeholder in `path`.
|
|
53
|
+
- After `[source]` any other header resumes keys; `[secrets]` there applies to shared.
|
data/lib/envpact/types.rb
CHANGED
|
@@ -11,15 +11,17 @@ class EnvPact
|
|
|
11
11
|
when :int then !Integer(raw, 10).nil?
|
|
12
12
|
when :bool then BOOL_VALUES.include?(raw.downcase)
|
|
13
13
|
when :enum then enum_values.include?(raw)
|
|
14
|
-
when :url then valid_url?(raw)
|
|
14
|
+
when :url then valid_url?(raw, enum_values)
|
|
15
15
|
end
|
|
16
16
|
rescue ArgumentError
|
|
17
17
|
false
|
|
18
18
|
end
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
# schemes (optional) restricts the scheme, compared case-insensitively.
|
|
21
|
+
def self.valid_url?(raw, schemes = nil)
|
|
21
22
|
uri = URI.parse(raw)
|
|
22
|
-
|
|
23
|
+
return false if uri.scheme.nil? || uri.host.nil? || uri.host.empty?
|
|
24
|
+
schemes.nil? || schemes.include?(uri.scheme.downcase)
|
|
23
25
|
rescue URI::InvalidURIError
|
|
24
26
|
false
|
|
25
27
|
end
|
data/lib/envpact/version.rb
CHANGED