ops-cli 1.0.0.pre.1

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: af0f6cd65d976ac577a86491042d2949e50fb34bdc70caf79d4dbf243e87ec67
4
+ data.tar.gz: 3e8c9d349e2cf3792f3f61f7ea37c4132e821f7910ab7392ef87bbbb6f04957e
5
+ SHA512:
6
+ metadata.gz: 1f28c342a971431d78cb2bf2fabf57480122c2d82ec7fadf8a282302f925f9f5d568c21165d924b940b387cd3c061ed803ea9f66372022bf9758b48e28e791b9
7
+ data.tar.gz: e15fcc24dac66dd772567a1ab963bb26bf6dbf7151a0757f7e96cf35a088a8eaaa52a60d635a73b20510b1786a64ac03965607757ddbfe18cdb680d199d1e192
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2026 Janus Security
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,212 @@
1
+ # ops-cli
2
+
3
+ A small framework for repo-local operational CLIs. Drop the gem into a
4
+ project, write task classes under `ops/tasks/`, and `bin/ops` becomes the
5
+ single entry-point for build/deploy/console/whatever-else operational work
6
+ lives in that repo. Plain Ruby with no runtime dependencies: option parsing is
7
+ the standard library's `OptionParser`.
8
+
9
+ ## What's in the box
10
+
11
+ - **`Ops::Task`** — base class with a small dispatch protocol (`desc`,
12
+ `task_options`, `call`, optional `already_done?`).
13
+ - **`Ops::Runner` + `Ops::Registry`** — discovery + dispatch. Runner reads
14
+ argv via `Ops::Arguments`, looks up a class from the Registry, calls
15
+ `task.perform`, and renders the resulting `Ops::TaskResult`. Registry walks
16
+ `Ops::Tasks::` and registers any class that descends from `Ops::Task`; the
17
+ constant path becomes the colon-namespaced, kebab-cased command name
18
+ (`Ops::Tasks::Secrets::RotateMaster` → `secrets:rotate-master`).
19
+ - **`Ops::TaskResult`** — boundary value object with three terminal states
20
+ (`successful`, `skipped`, `failed`).
21
+ - **`Ops::PodExec`** — `kubectl`-based helpers (`find_pod`, `exec_in_pod`,
22
+ `open_in_pod`) for tasks that need to land in a running pod.
23
+ - **`Ops::Shell`** — `Shell.run(*cmd, display: false, stdin: nil)` for
24
+ side-effect commands; `Shell.capture(*cmd, stdin: nil)` for data-flow
25
+ commands. `cmd` is argv (program, then arguments), optionally after a Hash
26
+ of environment variables; the program is always run directly, never
27
+ through a shell, so a lone string is a program name, not a command line.
28
+ Both raise `Ops::Shell::Error` on non-zero exit, carrying `command`,
29
+ `stdout`, `stderr` and `status`; its message names the program and exit
30
+ status with the tool's stderr, never the arguments or environment, which
31
+ may hold secrets.
32
+ - **`Ops::SecretSealer`** — produces sealed-secret encrypted-data blobs with
33
+ `kubeseal`. One sealer per namespace; `#seal(secret_name:, values:, type:
34
+ :generic)` per target. It builds the Secret manifest itself and hands it to
35
+ kubeseal on stdin, so plaintext never appears on a command line. Types:
36
+ `:generic` (Opaque) and `:basic_auth`; TLS / docker-registry would be
37
+ separate sealer classes.
38
+ - **`exe/ops`** — the bin-stubbable executable.
39
+
40
+ ## Installation
41
+
42
+ ```ruby
43
+ # Gemfile
44
+ gem "ops-cli", "~> 1.0.0.pre"
45
+ ```
46
+
47
+ Until 1.0.0 is out, releases are prereleases (`1.0.0.pre.N`), which Bundler
48
+ only picks up when the requirement names one, as above; it also takes 1.0.0
49
+ and later 1.0.x when they come.
50
+
51
+ Then:
52
+
53
+ ```
54
+ bundle install
55
+ bundle binstubs ops-cli # creates ./bin/ops
56
+ ```
57
+
58
+ The gem was first published as `janus-ops`; `require "janus_ops"` still
59
+ works, as an alias for `require "ops/cli"`.
60
+
61
+ ## Writing tasks
62
+
63
+ Tasks live under `ops/tasks/` in the consuming repo. Each file defines a class
64
+ under `Ops::Tasks::` that inherits from `Ops::Task`. The constant path is the
65
+ command name: each segment kebab-cased, joined with colons
66
+ (`Ops::Tasks::Secrets::RotateMaster` → `secrets:rotate-master`).
67
+
68
+ ```ruby
69
+ # ops/tasks/build.rb
70
+ module Ops
71
+ module Tasks
72
+ class Build < Ops::Task
73
+ desc "build [TAG]", "Build and push the application image"
74
+
75
+ def task_options
76
+ opts.option :force_rebuild, type: :boolean, default: false
77
+ end
78
+
79
+ def call
80
+ tag = opts.positional.first || "latest"
81
+ # ...use opts.force_rebuild
82
+ end
83
+ end
84
+ end
85
+ end
86
+ ```
87
+
88
+ Invoke it: `bin/ops build v1.2.3 --force-rebuild`.
89
+
90
+ `desc` records the task's usage and summary (class-level metadata; used by
91
+ `bin/ops` for the listing). `task_options` is the instance method where you
92
+ declare options on `opts`. `call` is the work method (no args — read parsed
93
+ argv via `opts`); its return value is wrapped into a successful
94
+ `Ops::TaskResult`. If `call` raises, the runner reports it and exits 1.
95
+ Override `already_done?` (default `false`, no args) to short-circuit into a
96
+ skipped result when the work has already been applied.
97
+
98
+ Declared options are accessible as methods on `opts`: `opts.force_rebuild`
99
+ returns the parsed value for `option :force_rebuild`. Positional args live at
100
+ `opts.positional`. Typos raise `NoMethodError` rather than silently returning
101
+ `nil`. Reserved names (the methods that already exist on `Ops::TaskOptions` —
102
+ `parsed`, `positional`, `usage`, `description`, etc.) raise at declaration time.
103
+
104
+ Arguments are checked before the task runs: an unrecognized flag fails the
105
+ task (exit 1) before `already_done?` or `call`, even if the task never reads
106
+ its options.
107
+
108
+ ### Options
109
+
110
+ `opts.option NAME, **settings` (or its alias `opts.declare`) declares one
111
+ option. The flag is the name with underscores turned into dashes:
112
+
113
+ | Setting | Effect |
114
+ |---|---|
115
+ | `type: :boolean` | `--[no-]name`; the value is `true` or `false` |
116
+ | `type: :numeric` | `--name=VALUE`, converted with `Integer()` |
117
+ | no `type` | `--name=VALUE`, a string |
118
+ | `default:` | the value when the flag isn't given (otherwise `nil`) |
119
+ | `desc:` | the flag's line in `bin/ops <cmd> --help` |
120
+ | `aliases:` | extra flag spellings, e.g. `["-n"]` |
121
+
122
+ Nested namespaces become colon names automatically:
123
+
124
+ ```
125
+ ops/tasks/console/rails.rb → Ops::Tasks::Console::Rails → bin/ops console:rails
126
+ ```
127
+
128
+ ## Repo-specific base classes
129
+
130
+ Layer your own base class on top of `Ops::Task` in `ops/lib/` to share options
131
+ or helpers across tasks. Subclasses inherit their parent's options by calling
132
+ `super` inside `task_options`; skip `super` to start fresh. Plain Ruby method
133
+ override.
134
+
135
+ ```ruby
136
+ # ops/lib/tenant_task.rb
137
+ class TenantTask < Ops::Task
138
+ def task_options
139
+ opts.option :namespace, aliases: ["-n"]
140
+ end
141
+ end
142
+
143
+ # ops/tasks/deploy.rb
144
+ class Ops::Tasks::Deploy < TenantTask
145
+ desc "deploy NAME", "deploy a tenant"
146
+
147
+ def task_options
148
+ super # inherits :namespace
149
+ opts.option :dry_run, type: :boolean, default: false
150
+ end
151
+
152
+ def call
153
+ # opts.namespace and opts.dry_run are both available here
154
+ end
155
+ end
156
+ ```
157
+
158
+ ## Interactive tasks
159
+
160
+ ops-cli doesn't prompt for anything itself, but a task that needs to ask
161
+ (a confirmation before something destructive, a password that mustn't echo)
162
+ can use [cli-ui](https://github.com/Shopify/cli-ui). Add it to the consuming
163
+ repo's Gemfile:
164
+
165
+ ```ruby
166
+ gem "cli-ui", "~> 2.7"
167
+ ```
168
+
169
+ and in the task:
170
+
171
+ ```ruby
172
+ require "cli/ui"
173
+
174
+ def call
175
+ return unless CLI::UI::Prompt.confirm("Remove tenant #{name}?", default: false)
176
+
177
+ password = CLI::UI::Prompt.ask_password("New password:")
178
+ # ...
179
+ end
180
+ ```
181
+
182
+ Its `Prompt` (`ask`, `ask_password`, `confirm`, `ask` with `options:`) and
183
+ `Spinner` primitives fit tasks well. Its framing (`CLI::UI::Frame.open`) and
184
+ inline `{{color:...}}` formatting are a bigger visual layer, best left out so
185
+ task output stays plain and readable in logs.
186
+
187
+ ## Where tasks are discovered
188
+
189
+ The `ops/` directory in the consuming repo — containing `lib/` (eager-loaded
190
+ on startup so task files can reference shared base classes) and `tasks/`
191
+ (lazy-walked when commands are resolved). Resolution order:
192
+
193
+ 1. `ENV["OPS_ROOT"]` (escape hatch, mostly for tests)
194
+ 2. `Bundler.root / "ops"` (the normal case — consuming app has a Gemfile)
195
+ 3. `Dir.pwd / "ops"` (fallback if Bundler isn't loaded)
196
+
197
+ `bin/ops` runs the Ruby under that `ops/` directory, the way `rake` runs a
198
+ Rakefile: treat it as running the repo's code.
199
+
200
+ ## Top-level flags
201
+
202
+ - `bin/ops` / `bin/ops --help` / `bin/ops -T` — list all commands
203
+ - `bin/ops <cmd> --help` (or `-h`, or `help`) — per-command help: the task's
204
+ `desc` usage and description, then its options
205
+
206
+ ## Development
207
+
208
+ ```
209
+ bundle install
210
+ bundle exec rspec
211
+ bundle exec rubocop
212
+ ```
data/exe/ops ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "ops/cli"
5
+
6
+ exit Ops::Runner.new(ARGV).run
data/lib/janus_ops.rb ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The gem was first published as janus-ops, whose entry point was `require "janus_ops"`. Kept so
4
+ # code written against it loads unchanged; new code should `require "ops/cli"`.
5
+ require_relative "ops/cli"
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ops
4
+ # Parses `bin/ops` argv into the discrete intents the runner cares about.
5
+ #
6
+ # A pure value object: argv in, predicates out. No I/O, no mutation of the
7
+ # caller's array, no knowledge of the task registry — validity of a command
8
+ # name is the runner's concern, not ours.
9
+ class Arguments
10
+ LIST_FLAGS = %w[--help -h help -T --tasks].freeze
11
+ TASK_HELP_FLAGS = %w[--help -h help].freeze
12
+
13
+ def initialize(argv)
14
+ @argv = argv.dup.freeze
15
+ end
16
+
17
+ def list_tasks?
18
+ argv.empty? || LIST_FLAGS.include?(head)
19
+ end
20
+
21
+ def command_name
22
+ return nil if list_tasks?
23
+
24
+ head
25
+ end
26
+
27
+ def help_for_command?
28
+ return false unless command_name
29
+
30
+ TASK_HELP_FLAGS.include?(argv[1])
31
+ end
32
+
33
+ def task_argv
34
+ return [] unless command_name
35
+
36
+ argv.drop(1)
37
+ end
38
+
39
+ private
40
+
41
+ attr_reader :argv
42
+
43
+ def head
44
+ argv.first
45
+ end
46
+ end
47
+ end
data/lib/ops/cli.rb ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ # ops-cli: `require "ops/cli"` loads the framework (Ops::Task, Ops::Runner and the rest).
4
+ module Ops
5
+ # Namespace under which all task classes live in a consuming repo.
6
+ # Discovered tasks become constants under Ops::Tasks (e.g. Ops::Tasks::Deploy,
7
+ # Ops::Tasks::Secrets::Add) — the constant path IS the command name in colon
8
+ # form. Declared here so the namespace exists independent of any one component
9
+ # (Registry walks it, but it isn't Registry's to own).
10
+ module Tasks; end
11
+ end
12
+
13
+ require_relative "version"
14
+ require_relative "task_result"
15
+ require_relative "task_options"
16
+ require_relative "task"
17
+ require_relative "arguments"
18
+ require_relative "registry"
19
+ require_relative "runner"
20
+ require_relative "pod_exec"
21
+ require_relative "shell"
22
+ require_relative "secret_sealer"
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+
5
+ module Ops
6
+ # Helpers for finding a tenant's running pod and exec'ing into it. Mix into
7
+ # task classes that need shell access to a running pod (console:rails,
8
+ # console:shell, future logs/debug variants, etc.).
9
+ #
10
+ # All methods are private — these are helpers, not task entry points. The
11
+ # task class's #call (the public method) is the one Ops::Task.perform
12
+ # dispatches to.
13
+ #
14
+ # === Interface
15
+ #
16
+ # All methods take named arguments — no duck-typed config object. Callers
17
+ # pass the strings they need directly, which keeps this mixin decoupled from
18
+ # any one repo's config shape. Consuming repos typically wrap the call in a
19
+ # repo-local helper on their TenantTask base class (see README).
20
+ module PodExec
21
+ private
22
+
23
+ # Return the name of the most-recently-created Running pod for the named
24
+ # release in the given namespace, or "" if none found.
25
+ #
26
+ # Uses Open3 with array-form args so kubectl receives each argument as a
27
+ # separate argv element — no shell interpolation, no command-injection
28
+ # surface even if values someday come from less-trusted input.
29
+ def find_pod(namespace:, release_name:)
30
+ stdout, _status = Open3.capture2(
31
+ "kubectl", "get", "pods",
32
+ "-n", namespace,
33
+ "-l", "app.kubernetes.io/instance=#{release_name}",
34
+ "--field-selector", "status.phase=Running",
35
+ "--sort-by=.metadata.creationTimestamp",
36
+ "-o", "jsonpath={.items[-1:].metadata.name}"
37
+ )
38
+ stdout.strip
39
+ end
40
+
41
+ # Replace the current process with `kubectl exec` against the named pod.
42
+ # The Ruby process is gone after this call returns to its caller (it
43
+ # doesn't return). Used for interactive commands (Rails console, shell).
44
+ def exec_in_pod(namespace:, pod_name:, command:)
45
+ exec "kubectl", "exec", "-i", "-t", "-n", namespace, pod_name, "--",
46
+ "sh", "-c", command
47
+ end
48
+
49
+ # Combined helper: find a pod, fail cleanly if there isn't one, otherwise
50
+ # print a connecting message and exec the given command.
51
+ #
52
+ # `target` is a human-readable label for what's being connected to (e.g.
53
+ # the tenant name) — used only in the "No pods found" error and the
54
+ # "Connecting to ..." status line. `label` describes the activity ("Rails
55
+ # console", "shell").
56
+ def open_in_pod(namespace:, release_name:, target:, command:, label:)
57
+ pod_name = find_pod(namespace: namespace, release_name: release_name)
58
+ if pod_name.empty?
59
+ raise "No running pods found for #{target} " \
60
+ "(release: #{release_name}, namespace: #{namespace})"
61
+ end
62
+ puts "Connecting to #{target} #{label} (pod: #{pod_name})..."
63
+ exec_in_pod(namespace: namespace, pod_name: pod_name, command: command)
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+
5
+ require_relative "task"
6
+
7
+ module Ops
8
+ # Lazy {colon_name => Ops::Task subclass} map built from {ops_root}/tasks/**/*.rb.
9
+ class Registry
10
+ include Enumerable
11
+
12
+ def initialize(ops_root)
13
+ @ops_root = Pathname.new(ops_root)
14
+ load_tasks!
15
+ end
16
+
17
+ def [](name)
18
+ entries[name]
19
+ end
20
+
21
+ def each(&)
22
+ entries.each(&)
23
+ end
24
+
25
+ private
26
+
27
+ attr_reader :ops_root
28
+
29
+ def tasks_root
30
+ ops_root.join("tasks")
31
+ end
32
+
33
+ def entries
34
+ @entries ||= {}.tap { |reg| collect_tasks(Tasks, [], reg) }
35
+ end
36
+
37
+ def load_tasks!
38
+ return unless tasks_root.directory?
39
+
40
+ Dir.glob(tasks_root.join("**", "*.rb")).each { |path| require path }
41
+ end
42
+
43
+ def collect_tasks(mod, path, reg)
44
+ mod.constants.each do |sym|
45
+ const = mod.const_get(sym)
46
+
47
+ if const.is_a?(Class) && const < Ops::Task
48
+ name = (path + [sym.to_s]).map { |s| kebab_case(s) }.join(":")
49
+ reg[name] = const
50
+ elsif const.is_a?(Module)
51
+ collect_tasks(const, path + [sym.to_s], reg)
52
+ end
53
+ end
54
+ end
55
+
56
+ # Module path components join with ":" (the namespace separator); each
57
+ # CamelCase component becomes lower-kebab inside its own segment. So
58
+ # Ops::Tasks::Secrets::RotateMaster → "secrets:rotate-master".
59
+ def kebab_case(str)
60
+ str.gsub(/([A-Z]+)([A-Z][a-z])/, '\1-\2')
61
+ .gsub(/([a-z\d])([A-Z])/, '\1-\2')
62
+ .downcase
63
+ end
64
+ end
65
+ end
data/lib/ops/runner.rb ADDED
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+
5
+ require_relative "task"
6
+ require_relative "arguments"
7
+ require_relative "registry"
8
+
9
+ module Ops
10
+ # Entry-point for `bin/ops`. One instance per invocation.
11
+ class Runner
12
+ # Resolution order for the `ops/` directory:
13
+ # ENV["OPS_ROOT"] → Bundler.root/ops → Dir.pwd/ops
14
+ def self.default_ops_root
15
+ return Pathname.new(ENV["OPS_ROOT"]) if ENV["OPS_ROOT"]
16
+
17
+ base = defined?(Bundler) ? Bundler.root : Pathname.pwd
18
+ base.join("ops")
19
+ end
20
+
21
+ def initialize(argv, ops_root: self.class.default_ops_root)
22
+ @argv = argv
23
+ @ops_root = Pathname.new(ops_root)
24
+ load_lib!
25
+ end
26
+
27
+ def run
28
+ return print_task_list.then { 0 } if arguments.list_tasks?
29
+
30
+ klass = registry[arguments.command_name]
31
+ return print_unknown_command.then { 1 } if klass.nil?
32
+
33
+ task = klass.new(arguments.task_argv)
34
+ return task.show_help.then { 0 } if arguments.help_for_command?
35
+
36
+ result = task.perform
37
+ return print_error(result.error).then { 1 } if result.failed?
38
+
39
+ return 0
40
+ end
41
+
42
+ private
43
+
44
+ attr_reader :argv, :ops_root
45
+
46
+ def arguments
47
+ @arguments ||= Arguments.new(argv)
48
+ end
49
+
50
+ def registry
51
+ @registry ||= Registry.new(ops_root)
52
+ end
53
+
54
+ def load_lib!
55
+ lib_root = ops_root.join("lib")
56
+ return unless lib_root.directory?
57
+
58
+ Dir.glob(lib_root.join("**", "*.rb")).each { |path| require path }
59
+ end
60
+
61
+ def print_unknown_command
62
+ warn "Unknown command: #{arguments.command_name}"
63
+ warn "Run `bin/ops -T` to list available commands."
64
+ end
65
+
66
+ def print_task_list
67
+ entries = registry.map { |name, klass| [name, klass.task_description] }
68
+ width = entries.map { |name, _| name.length }.max || 0
69
+ entries.sort.each do |name, desc|
70
+ puts " bin/ops #{name.ljust(width)} # #{desc}"
71
+ end
72
+ end
73
+
74
+ def print_error(e)
75
+ warn "ERROR: #{e.message}"
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'yaml'
5
+
6
+ module Ops
7
+ # Seals plaintext values into kubeseal-encrypted blobs, for one or more
8
+ # SealedSecret targets in a single namespace.
9
+ #
10
+ # One sealer instance binds to a namespace; #seal is called per
11
+ # (secret_name, values) pair, so a caller that needs to seal several
12
+ # secrets for the same tenant constructs one sealer and seals each in
13
+ # turn:
14
+ #
15
+ # sealer = Ops::SecretSealer.new(namespace: config.namespace)
16
+ # master = sealer.seal(secret_name: 'foo-master-key', values: {...})
17
+ # stripe = sealer.seal(secret_name: 'foo-stripe-config', values: {...})
18
+ # dbcreds = sealer.seal(secret_name: 'foo-db', type: :basic_auth,
19
+ # values: { 'username' => '...', 'password' => '...' })
20
+ #
21
+ # The Secret manifest is built here and handed to kubeseal on stdin, so the
22
+ # plaintext is never on a command line (where `ps` and failure messages
23
+ # would show it). Supports the Secret types `kubectl create secret generic
24
+ # --type=...` would; TLS / docker-registry would be separate sealer classes,
25
+ # as they have different value shapes.
26
+ class SecretSealer
27
+ # Symbolic type name → Secret type.
28
+ TYPES = {
29
+ generic: 'Opaque',
30
+ basic_auth: 'kubernetes.io/basic-auth'
31
+ }.freeze
32
+
33
+ # What the API server would accept: names and namespaces are DNS names,
34
+ # data keys are restricted too. Checked here since kubectl no longer is.
35
+ NAME = /\A[a-z0-9]([-a-z0-9.]{0,251}[a-z0-9])?\z/
36
+ NAMESPACE = /\A[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\z/
37
+ DATA_KEY = /\A[-._a-zA-Z0-9]+\z/
38
+
39
+ def initialize(namespace:)
40
+ raise ArgumentError, "not a namespace: #{namespace.inspect}" unless NAMESPACE.match?(namespace.to_s)
41
+
42
+ @namespace = namespace
43
+ end
44
+
45
+ # @param secret_name [String] name of the SealedSecret resource to produce
46
+ # @param values [Hash{String=>String}] plaintext key=>value pairs to seal
47
+ # @param type [Symbol] one of TYPES.keys; default :generic
48
+ # @return [Hash{String=>String}] {key => base64 sealed blob}
49
+ def seal(secret_name:, values:, type: :generic)
50
+ raise ArgumentError, "unknown type: #{type.inspect} (known: #{TYPES.keys.inspect})" unless TYPES.key?(type)
51
+ raise ArgumentError, 'values must not be empty' if values.empty?
52
+ raise ArgumentError, "not a secret name: #{secret_name.inspect}" unless NAME.match?(secret_name.to_s)
53
+
54
+ bad = values.keys.reject { |k| DATA_KEY.match?(k.to_s) }
55
+ raise ArgumentError, "not secret data keys: #{bad.inspect}" if bad.any?
56
+
57
+ sealed_yaml = Ops::Shell.capture('kubeseal', '-o', 'yaml', stdin: manifest(secret_name, type, values))
58
+ encrypted_data = YAML.safe_load(sealed_yaml).dig('spec', 'encryptedData')
59
+ raise 'kubeseal output missing spec.encryptedData' unless encrypted_data
60
+
61
+ encrypted_data
62
+ end
63
+
64
+ private
65
+
66
+ attr_reader :namespace
67
+
68
+ # The Secret, as kubectl's --dry-run would print it: data base64-encoded.
69
+ def manifest(secret_name, type, values)
70
+ JSON.generate(
71
+ 'apiVersion' => 'v1',
72
+ 'kind' => 'Secret',
73
+ 'metadata' => { 'name' => secret_name, 'namespace' => namespace },
74
+ 'type' => TYPES.fetch(type),
75
+ 'data' => values.to_h { |k, v| [k.to_s, [v.to_s].pack('m0')] }
76
+ )
77
+ end
78
+ end
79
+ end
data/lib/ops/shell.rb ADDED
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'open3'
4
+
5
+ module Ops
6
+ # Thin uniform wrapper around shell execution. Two functions, split by
7
+ # caller intent:
8
+ #
9
+ # Ops::Shell.run(*cmd, display: false, stdin: nil)
10
+ # Side effect. Operator either watches output (display: true) or runs
11
+ # silent. Returns nil. Raises Ops::Shell::Error on non-zero.
12
+ #
13
+ # Ops::Shell.capture(*cmd, stdin: nil)
14
+ # Data flow. Returns stdout. Raises Ops::Shell::Error on non-zero.
15
+ #
16
+ # Stderr is captured in every mode so Ops::Shell::Error always carries the
17
+ # tool's actual diagnostic — callers don't need to hand-roll stderr capture
18
+ # to surface failure information.
19
+ #
20
+ # `cmd` is argv, the program then its arguments, with an optional leading
21
+ # Hash of environment variables (as Open3 takes). The program is always run
22
+ # directly, never through a shell: Ruby would hand a lone string with shell
23
+ # characters in it to `sh -c`, so the program is spawned as [program, argv0],
24
+ # which rules that out. Arguments and environment may hold secrets, so the
25
+ # error's message names the program only; see Error.
26
+ module Shell
27
+ class << self
28
+ def run(*cmd, display: false, stdin: nil)
29
+ env, argv = split_env(cmd)
30
+ display ? run_display(env, argv, stdin: stdin) : run_quiet(env, argv, stdin: stdin)
31
+ end
32
+
33
+ def capture(*cmd, stdin: nil)
34
+ env, argv = split_env(cmd)
35
+ stdout, stderr, status = capture3(env, argv, stdin)
36
+ raise_error!(argv, stdout, stderr, status) unless status.success?
37
+ stdout
38
+ end
39
+
40
+ private
41
+
42
+ def split_env(cmd)
43
+ cmd.first.is_a?(Hash) ? [cmd.first, cmd.drop(1)] : [{}, cmd]
44
+ end
45
+
46
+ # argv with its first element in [program, argv0] form, which Process.spawn
47
+ # never passes through a shell.
48
+ def direct(cmd)
49
+ raise ArgumentError, 'no command given' if cmd.empty?
50
+
51
+ program = Array(cmd.first).first
52
+ [[program, program], *cmd.drop(1)]
53
+ end
54
+
55
+ def run_quiet(env, cmd, stdin:)
56
+ stdout, stderr, status = capture3(env, cmd, stdin)
57
+ raise_error!(cmd, stdout, stderr, status) unless status.success?
58
+ nil
59
+ end
60
+
61
+ # popen3 with stdout tee'd to $stdout and stderr tee'd to $stderr —
62
+ # operator sees both live AND we keep a stderr buffer for the error.
63
+ def run_display(env, cmd, stdin:)
64
+ raise ArgumentError, 'display: true + stdin: not yet supported' if stdin
65
+
66
+ err_buf = String.new
67
+ status = Open3.popen3(env, *direct(cmd)) do |stdin_io, stdout_io, stderr_io, wait_thr|
68
+ stdin_io.close
69
+ out_t = Thread.new { stdout_io.each_line { |l| $stdout.write(l); $stdout.flush } }
70
+ err_t = Thread.new do
71
+ stderr_io.each_line { |l| $stderr.write(l); $stderr.flush; err_buf << l }
72
+ end
73
+ out_t.join
74
+ err_t.join
75
+ wait_thr.value
76
+ end
77
+
78
+ raise_error!(cmd, '', err_buf, status) unless status.success?
79
+ nil
80
+ end
81
+
82
+ def capture3(env, cmd, stdin)
83
+ argv = direct(cmd)
84
+ stdin ? Open3.capture3(env, *argv, stdin_data: stdin) : Open3.capture3(env, *argv)
85
+ end
86
+
87
+ def raise_error!(cmd, stdout, stderr, status)
88
+ raise Error.new(command: cmd, stdout: stdout, stderr: stderr, status: status)
89
+ end
90
+ end
91
+
92
+ # The message names the program and the exit status, with the tool's
93
+ # stderr: not the arguments, which can carry secrets (a value being
94
+ # sealed, a token), and not the environment, which isn't kept at all.
95
+ # Runner prints the message, so it has to be safe to show. The full argv
96
+ # is in #command for callers that know theirs is safe.
97
+ class Error < StandardError
98
+ attr_reader :command, :stdout, :stderr, :status
99
+
100
+ def initialize(command:, stdout:, stderr:, status:)
101
+ @command = command
102
+ @stdout = stdout
103
+ @stderr = stderr
104
+ @status = status
105
+ msg = String.new("`#{program}` exited #{status.exitstatus}")
106
+ trimmed_stderr = stderr.to_s.strip
107
+ msg << ": #{trimmed_stderr}" unless trimmed_stderr.empty?
108
+ super(msg)
109
+ end
110
+
111
+ # The program name; the first argv element may be [program, argv0].
112
+ def program
113
+ Array(command.first).first.to_s
114
+ end
115
+ end
116
+ end
117
+ end
data/lib/ops/task.rb ADDED
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "task_result"
4
+ require_relative "task_options"
5
+
6
+ module Ops
7
+ # Base class for tasks dispatched by Ops::Runner. See README for the DSL.
8
+ class Task
9
+ class << self
10
+ attr_reader :usage, :description
11
+
12
+ def desc(usage, description)
13
+ @usage = usage
14
+ @description = description
15
+ end
16
+
17
+ def task_description
18
+ @description || "(no description)"
19
+ end
20
+ end
21
+
22
+ attr_reader :opts
23
+
24
+ def initialize(argv = [])
25
+ @opts = Ops::TaskOptions.new(argv)
26
+ @opts.usage = self.class.usage
27
+ @opts.description = self.class.description
28
+ task_options
29
+ end
30
+
31
+ def task_options
32
+ end
33
+
34
+ def already_done?
35
+ false
36
+ end
37
+
38
+ def call
39
+ raise NotImplementedError, "#{self.class} must implement #call"
40
+ end
41
+
42
+ def perform
43
+ opts.parsed.options # eager-validate argv; raises on unknown flags
44
+ return Ops::TaskResult.skipped if already_done?
45
+
46
+ value = call
47
+ value.is_a?(Ops::TaskResult) ? value : Ops::TaskResult.successful(value)
48
+ rescue => e
49
+ Ops::TaskResult.failed(e)
50
+ end
51
+
52
+ def show_help
53
+ puts opts.help_text
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+
5
+ module Ops
6
+ # Holds a task's option declarations and renders them as either a parsed
7
+ # value object or a help string. See README for the DSL.
8
+ class TaskOptions
9
+ # Option names that would shadow public methods on this class and silently
10
+ # bypass method_missing. Declaring one raises at the call site.
11
+ RESERVED_NAMES = %i[
12
+ declarations declare option
13
+ usage description
14
+ parsed positional help_text
15
+ ].freeze
16
+
17
+ attr_accessor :usage, :description
18
+ attr_reader :declarations
19
+
20
+ def initialize(argv = [])
21
+ @argv = argv
22
+ @declarations = {}
23
+ end
24
+
25
+ def declare(name, **opts)
26
+ raise ArgumentError, "Reserved option name: :#{name}" if RESERVED_NAMES.include?(name)
27
+
28
+ @declarations[name] = opts
29
+ self
30
+ end
31
+
32
+ alias_method :option, :declare
33
+
34
+ def parsed
35
+ @parsed ||= Parsed.new(@declarations, @argv)
36
+ end
37
+
38
+ def positional
39
+ parsed.positional
40
+ end
41
+
42
+ def method_missing(name, *args)
43
+ return parsed.options[name] if @declarations.key?(name)
44
+
45
+ super
46
+ end
47
+
48
+ def respond_to_missing?(name, include_private = false)
49
+ @declarations.key?(name) || super
50
+ end
51
+
52
+ def help_text
53
+ String.new.tap do |s|
54
+ s << "Usage: bin/ops #{usage}\n" if usage
55
+ s << "\n#{description}\n" if description
56
+ # The option lines only: OptionParser#help would add its own "Usage: <program> [options]"
57
+ # banner under ours.
58
+ s << "\nOptions:\n#{option_parser.summarize.join}" unless declarations.empty?
59
+ end
60
+ end
61
+
62
+ private
63
+
64
+ def option_parser
65
+ OptionParserBuilder.build(declarations)
66
+ end
67
+
68
+ class Parsed
69
+ def initialize(declarations, argv)
70
+ @declarations = declarations
71
+ @argv = argv
72
+ end
73
+
74
+ def options
75
+ parse[:options]
76
+ end
77
+
78
+ def positional
79
+ parse[:positional]
80
+ end
81
+
82
+ private
83
+
84
+ def parse
85
+ @parse ||= compute
86
+ end
87
+
88
+ def compute
89
+ options = defaults_from(@declarations)
90
+ positional = build_parser(options).parse(@argv)
91
+ { options: options, positional: positional }
92
+ end
93
+
94
+ def defaults_from(declarations)
95
+ declarations.each_with_object({}) do |(name, opts), acc|
96
+ acc[name] = opts[:default]
97
+ end
98
+ end
99
+
100
+ def build_parser(options)
101
+ OptionParserBuilder.build(@declarations) do |name, value|
102
+ options[name] = value
103
+ end
104
+ end
105
+ end
106
+
107
+ module OptionParserBuilder
108
+ extend self
109
+
110
+ def build(declarations, &on_match)
111
+ OptionParser.new do |opts|
112
+ declarations.each { |name, opt_def| register(opts, name, opt_def, &on_match) }
113
+ end
114
+ end
115
+
116
+ def register(opts, name, opt_def, &on_match)
117
+ flag_strings = flags_for(name, opt_def)
118
+ desc = opt_def[:desc]
119
+ args = desc ? [*flag_strings, desc] : flag_strings
120
+ opts.on(*args) { |value| on_match&.call(name, coerce(value, opt_def[:type])) }
121
+ end
122
+
123
+ def flags_for(name, opt_def)
124
+ long_name = name.to_s.gsub("_", "-")
125
+ long = case opt_def[:type]
126
+ when :boolean then "--[no-]#{long_name}"
127
+ else "--#{long_name}=VALUE"
128
+ end
129
+ [*Array(opt_def[:aliases]), long]
130
+ end
131
+
132
+ def coerce(value, type)
133
+ case type
134
+ when :numeric then Integer(value)
135
+ else value
136
+ end
137
+ end
138
+ end
139
+ end
140
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ops
4
+ # Frozen outcome of running a task: one of successful / skipped / failed.
5
+ class TaskResult
6
+ def self.successful(value = nil)
7
+ new(:successful, value: value)
8
+ end
9
+
10
+ def self.skipped
11
+ new(:skipped)
12
+ end
13
+
14
+ def self.failed(error)
15
+ new(:failed, error: error)
16
+ end
17
+
18
+ attr_reader :value, :error
19
+
20
+ def initialize(state, value: nil, error: nil)
21
+ @state = state
22
+ @value = value
23
+ @error = error
24
+ freeze
25
+ end
26
+
27
+ def successful?
28
+ @state == :successful
29
+ end
30
+
31
+ def skipped?
32
+ @state == :skipped
33
+ end
34
+
35
+ def failed?
36
+ @state == :failed
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ops
4
+ VERSION = "1.0.0.pre.1"
5
+ end
metadata ADDED
@@ -0,0 +1,101 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ops-cli
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0.pre.1
5
+ platform: ruby
6
+ authors:
7
+ - Janus Security
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rake
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '13.0'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '13.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: rspec
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '3.13'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '3.13'
40
+ - !ruby/object:Gem::Dependency
41
+ name: rubocop
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '1.0'
47
+ type: :development
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '1.0'
54
+ description: 'Write task classes under ops/tasks/ and bin/ops becomes the one entry
55
+ point for a repo''s operational work: discovery and dispatch (Ops::Task, Ops::Runner),
56
+ standard-library option parsing, and helpers for running commands safely (Ops::Shell),
57
+ sealing Kubernetes secrets (Ops::SecretSealer) and reaching pods (Ops::PodExec).'
58
+ executables:
59
+ - ops
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - LICENSE
64
+ - README.md
65
+ - exe/ops
66
+ - lib/janus_ops.rb
67
+ - lib/ops/arguments.rb
68
+ - lib/ops/cli.rb
69
+ - lib/ops/pod_exec.rb
70
+ - lib/ops/registry.rb
71
+ - lib/ops/runner.rb
72
+ - lib/ops/secret_sealer.rb
73
+ - lib/ops/shell.rb
74
+ - lib/ops/task.rb
75
+ - lib/ops/task_options.rb
76
+ - lib/ops/task_result.rb
77
+ - lib/ops/version.rb
78
+ homepage: https://github.com/JanusSecurity/ops-cli
79
+ licenses:
80
+ - MIT
81
+ metadata:
82
+ source_code_uri: https://github.com/JanusSecurity/ops-cli
83
+ bug_tracker_uri: https://github.com/JanusSecurity/ops-cli/issues
84
+ rdoc_options: []
85
+ require_paths:
86
+ - lib
87
+ required_ruby_version: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ version: 3.3.0
92
+ required_rubygems_version: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ requirements: []
98
+ rubygems_version: 3.6.9
99
+ specification_version: 4
100
+ summary: A small framework for repo-local operational CLIs
101
+ test_files: []