bullion 0.12.0 → 0.12.2

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: ff6022efee880f75147cc1a4ce9a25dd9525075002c20f3c2be0c917a550d167
4
- data.tar.gz: 114a84d226ef0e2c613be0b6e80f33fe73b379ee20016291baca59662beac094
3
+ metadata.gz: e3f045be66d6e2b4dcf448edd875bec385862e2b67741a615d53a2b60bff5ceb
4
+ data.tar.gz: 896eb9e41ecbd96b2333c9bd3cc647388f469547efe4ee1b3e90611d81c66d16
5
5
  SHA512:
6
- metadata.gz: a82cec86d1143c61349ad216337646ef80e12c0a6d1b03af48bce0b0608db08b0edabe8d012b8375c9603a6a721c09d190551994549ac269b56c13406333cadd
7
- data.tar.gz: 423cc0b9ea94aa2c28076d860bd58502af1383065e6eecf3db1e19b5d00b3a7f8756f0c09b7c839c3b36128563264f58a2e4176ada4051127f73bd58f3757db7
6
+ metadata.gz: 30edde9b4403f74aaa1e678425c38f9fc946fca13f75c1d482dde1d605ab10f16d71f79d9e31117a4f79881f508fb276f9d2ed36fe3c374ce911bab93734fcca
7
+ data.tar.gz: 25effef65ad92e025752e3182667a71eb13f6a1e4343cd9e8a71d08cf8b5aa6a6080c214d2f7803e8a8d614cadc4a2a1be30a0feca8d2b81655d7f05e2ae51f0
data/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.12.2](https://github.com/jgnagy/bullion/compare/bullion/v0.12.1...bullion/v0.12.2) (2026-12-03)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * address review findings on ACME error responses ([0cd7a03](https://github.com/jgnagy/bullion/commit/0cd7a032f1c7854b49f6aa5965aca1e442b029b8))
9
+ * return ACME problem+json errors from the CA service ([bba9382](https://github.com/jgnagy/bullion/commit/bba9382d5f90675d7991446477eddab19e1c869e))
10
+ * return ACME problem+json errors from the CA service ([b595460](https://github.com/jgnagy/bullion/commit/b595460b8df8e33f6ac5a2db789fc6f0ba417a87)), closes [#110](https://github.com/jgnagy/bullion/issues/110)
11
+
12
+ ## [0.12.1](https://github.com/jgnagy/bullion/compare/bullion/v0.12.0...bullion/v0.12.1) (2026-11-02)
13
+
14
+
15
+ ### Bug Fixes
16
+
17
+ * accept the full RFC 8555 revocation set, add problem docs (ghostex-d76.1) ([e68c9a1](https://github.com/jgnagy/bullion/commit/e68c9a12f17e0655b2a8d9587fd78550df9cc7ab))
18
+ * bound ACME nonce minting and expire stale nonces (ghostex-d76.3) ([3938285](https://github.com/jgnagy/bullion/commit/3938285d6dc9b6c91cbd6d9aff5a9729a3cf0760))
19
+ * bump trilogy to 2.13.2 for GHSA-744p-w4gc-m3gh (ghostex-d76.7) ([4b3c657](https://github.com/jgnagy/bullion/commit/4b3c657c9eda1a4348f6f1d6aeeb4327269c80ba))
20
+ * emit full-width EC JWK coordinates; 400 on malformed EC points (ghostex-d76.4) ([2e98fed](https://github.com/jgnagy/bullion/commit/2e98fed5a227a77548426d797a444c207f0ae58c))
21
+ * emit full-width EC JWK coordinates; return 400 malformed on invalid EC points (ghostex-d76.4) ([b23dfd1](https://github.com/jgnagy/bullion/commit/b23dfd1a7219ed6fc7137369ed4370ad57d42223))
22
+ * enforce account ownership across ACME by-ID resources (ghostex-d76.1) ([0dfd9b2](https://github.com/jgnagy/bullion/commit/0dfd9b2f74567a051b55c767f6681c4b441eba57))
23
+ * enforce authorization and order expiration (ghostex-d76.6) ([c909fc9](https://github.com/jgnagy/bullion/commit/c909fc96d5f97856bd1e2117dcd7bd1b993eee9a))
24
+ * fail closed when CA_SECRET is unset outside development/test (ghostex-d76.2) ([f203327](https://github.com/jgnagy/bullion/commit/f2033274f83f7e2de43c20accea0259694cf39f1))
25
+ * mint 64-bit certificate serials (ghostex-d76.3) ([db594c6](https://github.com/jgnagy/bullion/commit/db594c6075b42e6521f827094a9c28ad4015c44d))
26
+ * sanitize unhandled errors for ACME clients (ghostex-d76.3) ([c382457](https://github.com/jgnagy/bullion/commit/c3824577186dcbc7f9e4eb0572571659df288ecd))
27
+
3
28
  ## [0.12.0](https://github.com/jgnagy/bullion/compare/bullion/v0.11.6...bullion/v0.12.0) (2026-10-24)
4
29
 
5
30
 
data/README.md CHANGED
@@ -24,7 +24,7 @@ The goal of the Bullion project is to make running a scalable, internal ACMEv2 C
24
24
 
25
25
  Before running Bullion, you need a CA key pair. Bullion requires two PEM files:
26
26
 
27
- - **`tls.key`** — An encrypted private key (RSA, ECDSA, or EdDSA) for signing certificates. Bullion supports encrypted PEM keys using AES-128-CBC.
27
+ - **`tls.key`** — An encrypted private key (RSA, ECDSA, or EdDSA) for signing certificates. Bullion supports encrypted PEM keys using AES-128-CBC. The key must be encrypted with the passphrase given in `CA_SECRET` (see [CA Secret](#ca-secret)).
28
28
  - **`tls.crt`** — The corresponding public certificate. If Bullion is an intermediate CA, include the root CA's certificate in this file as well (certificate chain order: intermediate first, then root).
29
29
 
30
30
  You can generate these with OpenSSL. For example, a self-signed root CA:
@@ -84,7 +84,7 @@ Install the gem:
84
84
  gem install bullion
85
85
  ```
86
86
 
87
- Bullion is a Rack application served by [Itsi](https://itsi.fyi/). After installing the gem, you'll need a `config.ru` and an `Itsi.rb` configuration file. The simplest approach is to create a working directory with your CA key pair and a minimal Rack config:
87
+ Bullion is a Rack application served by [Puma](https://puma.io/). After installing the gem, you'll need a `config.ru` and a `config/puma.rb` configuration file. The simplest approach is to create a working directory with your CA key pair and a minimal Rack config:
88
88
 
89
89
  ```bash
90
90
  mkdir bullion-server && cd bullion-server
@@ -116,13 +116,12 @@ mappings = {
116
116
  run Rack::URLMap.new(mappings)
117
117
  RUBY
118
118
 
119
- # Initialize Itsi and run database migrations
120
- itsi init
119
+ # Run database migrations
121
120
  DATABASE_URL=sqlite3:./bullion.db bullion-exec rake db:migrate
122
121
 
123
122
  # Start the server
124
123
  CA_DIR=. CA_SECRET=your-key-password CA_DOMAINS=example.com \
125
- DATABASE_URL=sqlite3:./bullion.db itsi
124
+ DATABASE_URL=sqlite3:./bullion.db bundle exec puma -C config/puma.rb
126
125
  ```
127
126
 
128
127
  ### Database Setup
@@ -155,21 +154,57 @@ Whether run locally or via Docker, the following environment variables configure
155
154
  | Environment Variable | Default Value | Description |
156
155
  | --- | --- | --- |
157
156
  | `CA_DIR` | `./tmp/` | Path to directory container the public and private key for Bullion. |
158
- | `CA_SECRET` | `SomeS3cret` | Secret used to read the encrypted `$CA_KEY` PEM. |
157
+ | `CA_SECRET` | _None_ | **(Required outside development/test)** Passphrase used to decrypt the encrypted CA private key PEM. Bullion refuses to boot when it is missing. See [CA Secret](#ca-secret). |
159
158
  | `CA_KEY_PATH` | `$CA_DIR/tls.key` | Private signer key for Bullion. Keep this safe! |
160
159
  | `CA_CERT_PATH` | `$CA_DIR/tls.crt` | Public cert for Bullion. If Bullion is an intermediate CA, you'll want to include the root CA's public cert in this file as well the signed cert for Bullion. |
161
160
  | `CA_DOMAINS` | `example.com` | A comma-delimited list of domains for which Bullion will sign certificate requests. Subdomains are automatically allowed. Certificates containing other domains will be rejected. |
162
161
  | `CERT_VALIDITY_DURATION` | `7776000` | How long should issued certs be valid (in seconds)? Default is 90 days. |
163
- | `DATABASE_URL` | _None_ | **(Required)** A shorthand for telling Bullion how to connect to a database. Acceptable URLs will either begin with `sqlite3:` or [`trilogy://`](https://github.com/trilogy-libraries/trilogy/tree/main/contrib/ruby). ActiveRecord connection options may be passed as query parameters, e.g. `trilogy://user:pass@host:3306/bullion?max_connections=25&checkout_timeout=5`. |
162
+ | `DATABASE_URL` | _None_ | **(Required)** A shorthand for telling Bullion how to connect to a database. Acceptable URLs will either begin with `sqlite3:` or [`trilogy://`](https://github.com/trilogy-libraries/trilogy/tree/main/contrib/ruby). ActiveRecord connection options may be passed as query parameters, e.g. `trilogy://user:pass@host:3306/bullion?max_connections=25&checkout_timeout=5`. MySQL/MariaDB connections default to the `utf8mb4` charset; the legacy `sjis`, `cp932`, `big5`, `gbk` and `gb18030` charsets are not supported by Trilogy 2.13.2 and raise `ArgumentError` if requested. |
164
163
  | `DNS01_NAMESERVERS` | _None_ | A comma-delimited list of nameservers to use for resolving [DNS-01](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge) challenges. Usually you'll want this to be set to your _internal_ nameservers so internal names resolve correctly. When not set, it'll use the host's DNS. |
165
164
  | `LOG_LEVEL` | `warn` | Log level for Bullion. Supported levels (starting with the noisiest) are debug, info, warn, error, and fatal. |
166
165
  | `BULLION_PORT` | `9292` | TCP port Bullion will listen on. |
167
- | `THREADS` | `3` | Number of [Itsi threads](https://itsi.fyi/options/threads/) for processing requests. |
168
- | `WORKERS` | `1` | Number of [Itsi workers](https://itsi.fyi/options/workers/) to spawn. |
169
- | `WORKER_MEMORY_LIMIT` | `1024**3` | [Itsi worker memory limit](https://itsi.fyi/options/worker_memory_limit/) for each worker process (in bytes). Default is 1GiB. |
166
+ | `THREADS` | `3` | Number of [Puma threads](https://puma.io/puma/file.deployment.html) for processing requests. |
167
+ | `WORKERS` | `1` | Number of [Puma workers](https://puma.io/puma/file.deployment.html) to spawn. |
170
168
  | `RACK_ENV` | `production`* | When run via Docker, the default is `production`, when run via `rake local_demo` it is `development`. Used to tell Bullion if it is run in development mode or for testing. |
171
169
 
172
- Because Bullion serves requests through Itsi's [fiber scheduler](https://itsi.fyi/options/fiber_scheduler/), each in-flight request leases its own database connection. ActiveRecord's connection pool defaults to 5 connections, so raise `max_connections` on `DATABASE_URL` if you expect more concurrent requests. `checkout_timeout` (default 5 seconds) controls how long a request waits for a connection before failing.
170
+ Because Bullion serves requests through Puma's [fiber-per-request](https://puma.io/puma/file.deployment.html), each in-flight request leases its own database connection. ActiveRecord's connection pool defaults to 5 connections, so raise `max_connections` on `DATABASE_URL` if you expect more concurrent requests. `checkout_timeout` (default 5 seconds) controls how long a request waits for a connection before failing.
171
+
172
+ #### CA Secret
173
+
174
+ `CA_SECRET` is the passphrase that decrypts the CA private key (`tls.key`). Bullion
175
+ **refuses to boot** (raising `Bullion::ConfigError`) when `CA_SECRET` is missing or
176
+ blank and `RACK_ENV` is anything other than `development` or `test` — there is no
177
+ default passphrase in production.
178
+
179
+ Generate a strong passphrase and keep it in your secret manager:
180
+
181
+ ```bash
182
+ openssl rand -base64 48 # e.g. a 64-character random string
183
+ ```
184
+
185
+ The CA private key **must be encrypted with that exact passphrase**. Bullion decrypts
186
+ encrypted PEM keys with OpenSSL, so AES-128-CBC and AES-256-CBC both work:
187
+
188
+ ```bash
189
+ # Generate a new encrypted key
190
+ openssl genrsa -aes256 -out tls.key 4096
191
+
192
+ # Or re-encrypt an existing key with a new passphrase
193
+ openssl pkey -aes256 -in tls.key -out tls.key.new
194
+ ```
195
+
196
+ Then start Bullion with that same passphrase in the environment:
197
+
198
+ ```bash
199
+ export CA_SECRET='<the passphrase you encrypted the key with>'
200
+ bundle exec puma -C config/puma.rb
201
+ ```
202
+
203
+ In development and test environments (`RACK_ENV=development` or `RACK_ENV=test`),
204
+ Bullion falls back to a well-known, development-only passphrase so that the `rake`
205
+ demo and test tasks work out of the box; it logs a warning whenever it does so.
206
+ That fallback is never used when `RACK_ENV` is `production` — or when `RACK_ENV` is
207
+ unset, which is treated as a production-like environment.
173
208
 
174
209
  ### Integrating
175
210
 
data/Rakefile CHANGED
@@ -25,17 +25,20 @@ if %w[development test].include? ENV["RACK_ENV"]
25
25
  rack_env = "test"
26
26
  database_url = "sqlite3:#{File.expand_path(".")}/tmp/db/#{rack_env}.sqlite3"
27
27
  system("RACK_ENV=\"#{rack_env}\" DATABASE_URL=\"#{database_url}\" bundle exec rake db:migrate")
28
- system(
29
- "RACK_ENV=\"#{rack_env}\" DATABASE_URL=\"#{database_url}\" " \
30
- "LOG_LEVEL='#{ENV.fetch("LOG_LEVEL", "info")}' " \
31
- "itsi --daemonize"
28
+ pid = Process.spawn(
29
+ { "RACK_ENV" => rack_env, "DATABASE_URL" => database_url,
30
+ "LOG_LEVEL" => ENV.fetch("LOG_LEVEL", "info") },
31
+ "bundle", "exec", "puma", "-C", "config/puma.rb",
32
+ out: File.join(File.expand_path("."), "tmp", "puma.log"),
33
+ err: File.join(File.expand_path("."), "tmp", "puma.log"),
34
+ pgroup: true
32
35
  )
33
- FileUtils.touch(File.join(File.expand_path("."), "tmp", "daemon.pid"))
36
+ File.write(File.join(File.expand_path("."), "tmp", "daemon.pid"), pid.to_s)
34
37
  end
35
38
 
36
39
  desc "Runs a foregrounded demo environment"
37
40
  task :foreground_demo do
38
- system("itsi")
41
+ system("bundle exec puma -C config/puma.rb")
39
42
  end
40
43
 
41
44
  desc "Cleans up test or demo environment"
@@ -43,7 +46,12 @@ if %w[development test].include? ENV["RACK_ENV"]
43
46
  at_exit do
44
47
  pid_file = File.join(File.expand_path("."), "tmp", "daemon.pid")
45
48
  if File.exist?(pid_file)
46
- system("itsi stop")
49
+ pid = File.read(pid_file).to_i
50
+ begin
51
+ Process.kill("TERM", -pid) # kill the whole process group
52
+ rescue Errno::ESRCH
53
+ nil
54
+ end
47
55
  FileUtils.rm_f(pid_file)
48
56
  end
49
57
  FileUtils.rm_f(File.join(File.expand_path("."), "tmp", "tls.crt"))
data/config/puma.rb ADDED
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Puma configuration for Bullion. Replaces the Itsi configuration file.
4
+ #
5
+ # Each request is served in its own fiber (via `fiber_per_request`) so that
6
+ # ActiveSupport execution state and ActiveRecord connection leases stay
7
+ # isolated per request, matching the fiber-per-request semantics Itsi provided.
8
+
9
+ env = ENV.fetch("APP_ENV", ENV.fetch("RACK_ENV", "development"))
10
+
11
+ # Number of worker processes to spawn. 0 means single mode (one process).
12
+ workers ENV["WORKERS"]&.to_i || (env == "development" ? 1 : 0)
13
+
14
+ # Number of threads to spawn per worker process.
15
+ threads ENV.fetch("THREADS", 3).to_i
16
+
17
+ # Load the application before forking workers.
18
+ preload_app!
19
+
20
+ bind "tcp://0.0.0.0:#{ENV.fetch("BULLION_PORT", 9292)}"
21
+
22
+ rackup "./config.ru"
23
+
24
+ # Run each request in its own fiber (clean slate per request).
25
+ fiber_per_request
26
+
27
+ # Number of seconds to wait for workers to gracefully shut down before killing them.
28
+ worker_shutdown_timeout 5
29
+
30
+ # Clean up any non-threadsafe resources before forking a new worker.
31
+ before_fork do
32
+ end
33
+
34
+ # Reinitialize any non-threadsafe resources after forking a new worker.
35
+ before_worker_boot do
36
+ end
data/config.ru CHANGED
@@ -6,7 +6,11 @@ Bullion.validate_config!
6
6
  require "prometheus/middleware/collector"
7
7
  require "prometheus/middleware/exporter"
8
8
 
9
- use Rack::ShowExceptions
9
+ # Rack::ShowExceptions renders exception messages and backtraces; keep it out
10
+ # of production so a request that escapes Sinatra's handlers cannot leak them.
11
+ use Rack::ShowExceptions if Bullion::DEV_OR_TEST_ENVIRONMENTS.include?(
12
+ ENV.fetch("RACK_ENV", "development")
13
+ )
10
14
  use Rack::Deflater
11
15
  use Prometheus::Middleware::Collector
12
16
  use Prometheus::Middleware::Exporter
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Index nonce expiry/pruning queries by creation time.
4
+ class AddCreatedAtIndexToNonces < ActiveRecord::Migration[8.1]
5
+ def change
6
+ add_index :nonces, :created_at
7
+ end
8
+ end
data/db/schema.rb CHANGED
@@ -10,7 +10,7 @@
10
10
  #
11
11
  # It's strongly recommended that you check this file into your version control system.
12
12
 
13
- ActiveRecord::Schema[8.1].define(version: 2026_07_16_000000) do
13
+ ActiveRecord::Schema[8.1].define(version: 2026_11_02_000000) do
14
14
  create_table "accounts", force: :cascade do |t|
15
15
  t.text "contacts", null: false
16
16
  t.datetime "created_at", null: false
@@ -72,6 +72,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_07_16_000000) do
72
72
  t.datetime "created_at", null: false
73
73
  t.string "token", null: false
74
74
  t.datetime "updated_at", null: false
75
+ t.index ["created_at"], name: "index_nonces_on_created_at"
75
76
  t.index ["token"], name: "index_nonces_on_token", unique: true
76
77
  end
77
78
 
@@ -5,8 +5,11 @@ module Bullion
5
5
  # ACME protocol errors super class
6
6
  class Error < Bullion::Error
7
7
  # @see https://tools.ietf.org/html/rfc8555#section-6.7
8
+ # RFC 8555 section 6.7 says the ACME URN namespace must not be used for
9
+ # unregistered error types, so the generic fallback is the registered
10
+ # "serverInternal" type.
8
11
  def acme_type
9
- "genericError"
12
+ "serverInternal"
10
13
  end
11
14
 
12
15
  def acme_preface
@@ -39,9 +42,14 @@ module Bullion
39
42
  def acme_type = "badPublicKey"
40
43
  end
41
44
 
42
- # ACME exception for bad certificates
45
+ # ACME exception for unidentifiable certificates, e.g. a revocation
46
+ # request for a certificate this CA never issued. RFC 8555 section 6.7
47
+ # and the IANA ACME Error Types registry have no dedicated type for
48
+ # this situation, and a client-correctable 400 must not be labelled a
49
+ # server-internal error, so this uses the Bullion-specific URN
50
+ # namespace (as with UnsupportedChallengeType).
43
51
  class BadCertificate < Bullion::Acme::Error
44
- def acme_type = "badCertificate"
52
+ def acme_error = "urn:ietf:params:bullion:error:badCertificate"
45
53
  end
46
54
 
47
55
  # ACME exception for already-revoked certificates
@@ -54,16 +62,22 @@ module Bullion
54
62
  def acme_type = "invalidContact"
55
63
  end
56
64
 
57
- # ACME exception for invalid orders
58
- class InvalidOrder < Bullion::Acme::Error
59
- def acme_type = "invalidOrder"
60
- end
61
-
62
65
  # ACME exception for malformed requests
63
66
  class Malformed < Bullion::Acme::Error
64
67
  def acme_type = "malformed"
65
68
  end
66
69
 
70
+ # ACME exception for identifiers the server will not issue
71
+ # certificates for
72
+ class RejectedIdentifier < Bullion::Acme::Error
73
+ def acme_type = "rejectedIdentifier"
74
+ end
75
+
76
+ # ACME exception for unsupported identifier types
77
+ class UnsupportedIdentifier < Bullion::Acme::Error
78
+ def acme_type = "unsupportedIdentifier"
79
+ end
80
+
67
81
  # ACME exception for orders that aren't ready to be finalized
68
82
  class OrderNotReady < Bullion::Acme::Error
69
83
  def acme_type = "orderNotReady"
@@ -74,7 +88,19 @@ module Bullion
74
88
  def acme_type = "unsupportedContact"
75
89
  end
76
90
 
77
- # Non-standard exception for unsupported challenge types
91
+ # ACME exception for requests the account is not authorized to make.
92
+ # Also used for not-found-style refusals: the ACME registry has no
93
+ # generic "notFound" problem type, and "unauthorized" is its closest
94
+ # entry ("a request for an identifier the account is not authorized
95
+ # to manage"); the identical response for missing and foreign-owned
96
+ # resources keeps the two cases indistinguishable.
97
+ class Unauthorized < Bullion::Acme::Error
98
+ def acme_type = "unauthorized"
99
+ end
100
+
101
+ # Non-standard exception for unsupported challenge types. Per RFC 8555
102
+ # section 6.7, non-registered error types must not use the ACME URN
103
+ # namespace, so this uses the Bullion-specific one.
78
104
  class UnsupportedChallengeType < Bullion::Acme::Error
79
105
  def acme_error = "urn:ietf:params:bullion:error:unsupportedChallengeType"
80
106
  end
@@ -4,6 +4,9 @@ module Bullion
4
4
  # Common helper functions
5
5
  module Helpers
6
6
  # ACME-specific helper functions
7
+ # The ownership and revocation enforcement work grew this module past
8
+ # the default limit; the helpers are one cohesive ACME concern
9
+ # rubocop:disable-next Metrics/ModuleLength
7
10
  module Acme
8
11
  # Parses and verifies the incoming ACME JWT for authentication
9
12
  # @see https://tools.ietf.org/html/rfc8555#section-6.2
@@ -114,6 +117,130 @@ module Bullion
114
117
  true
115
118
  end
116
119
 
120
+ # Ownership enforcement
121
+ #
122
+ # ACME resources are private to the account that created them. Requests
123
+ # are authenticated via the JWS "kid" (see #parse_acme_jwt), and every
124
+ # by-ID lookup below is scoped to that account: a resource that is
125
+ # missing and a resource owned by someone else are both answered with a
126
+ # 404, so an attacker cannot even learn that another account's order,
127
+ # authorization, challenge, or certificate exists.
128
+
129
+ # Returns the Order named by params[:id] when the authenticated account
130
+ # owns it; nil when it is missing or belongs to a different account.
131
+ def owned_order
132
+ Models::Order.find_by(id: params[:id], account_id: @user.id)
133
+ end
134
+
135
+ # Returns the Authorization named by params[:id] when the authenticated
136
+ # account owns its order; nil when it is missing or foreign-owned.
137
+ def owned_authorization
138
+ Models::Authorization.joins(:order)
139
+ .find_by(id: params[:id], orders: { account_id: @user.id })
140
+ end
141
+
142
+ # Returns the Challenge named by params[:id] when the authenticated
143
+ # account owns the challenge's order; nil when missing or foreign-owned.
144
+ def owned_challenge
145
+ Models::Challenge.joins(authorization: :order)
146
+ .find_by(id: params[:id], orders: { account_id: @user.id })
147
+ end
148
+
149
+ # The identifiers whose authorizations this order has proven and whose
150
+ # proofs have not yet expired.
151
+ def validated_domains(order)
152
+ order.authorizations.select(&:valid_for_issuance?).map { it.identifier["value"] }.sort
153
+ end
154
+
155
+ # Marks a just-validated challenge's authorization valid, and marks the
156
+ # order ready once every one of its authorizations is valid: a single
157
+ # valid challenge proves control of only one identifier, so a
158
+ # multi-identifier order must not become finalizable early.
159
+ def advance_validation!(challenge)
160
+ authorization = challenge.authorization
161
+
162
+ # An elapsed proof must never be promoted or counted. The stored
163
+ # status may remain "valid" for client rendering, but issuance and
164
+ # order readiness rely on #valid_for_issuance?.
165
+ return if challenge.expired? || authorization.expired?
166
+
167
+ authorization.update!(status: "valid") unless authorization.valid_status?
168
+
169
+ order = authorization.order
170
+ return if order.ready_status?
171
+
172
+ order.update!(status: "ready") if order.authorizations.all?(&:valid_for_issuance?)
173
+ end
174
+
175
+ # The refusal detail for a finalize attempt that cannot proceed,
176
+ # distinguishing an elapsed order or authorization from one that is
177
+ # merely not ready. RFC 8555 has no dedicated expiry error, so all
178
+ # three refusals use orderNotReady.
179
+ def finalize_refusal_detail(order)
180
+ return "Order has expired" if order.expired?
181
+ return "An authorization has expired" if order.authorizations.any?(&:expired?)
182
+
183
+ "Order is not ready to be finalized"
184
+ end
185
+
186
+ # Halts with an RFC 7807 problem document for an ACME error
187
+ def halt_acme_error(status, error_class, detail)
188
+ content_type "application/problem+json"
189
+ halt status, { type: error_class.new.acme_error, detail: }.to_json
190
+ end
191
+
192
+ # Refuses a request in the ACME not-found style (RFC 8555 section
193
+ # 6.7): the same problem document answers for resources that do not
194
+ # exist and resources owned by another account, so the existence of
195
+ # someone else's order, authorization, challenge, or certificate is
196
+ # never revealed.
197
+ def halt_acme_not_found
198
+ halt_acme_error(404, Bullion::Acme::Errors::Unauthorized, "Resource not found")
199
+ end
200
+
201
+ # Authenticates a revocation request per RFC 8555 section 7.6: a
202
+ # "kid" in the protected header authenticates the signing account as
203
+ # usual, while a bare "jwk" takes the emergency path — the JWS is
204
+ # verified against the certificate's own public key, so only the
205
+ # holder of the certificate's private key can produce such a request.
206
+ # The header's jwk is a JOSE marker here, not the trusted key: a
207
+ # valid signature under the certificate key proves possession, which
208
+ # is what the spec requires.
209
+ def authenticate_revocation!(cert)
210
+ return parse_acme_jwt if extract_header_data["kid"]
211
+
212
+ begin
213
+ parse_acme_jwt(cert.public_key)
214
+ rescue JWT::DecodeError, OpenSSL::PKey::PKeyError
215
+ halt_acme_not_found
216
+ end
217
+ end
218
+
219
+ # Whether the account may revoke the certificate record under RFC
220
+ # 8555 section 7.6: either it is the account the certificate was
221
+ # issued to, or it holds valid, unexpired authorizations covering
222
+ # every identifier in the certificate. The jwk path needs no account
223
+ # check: its signature already proved possession of the certificate's
224
+ # private key.
225
+ def revocation_authorized?(account, record)
226
+ return true if record.order&.account_id == account.id
227
+
228
+ covered = Models::Authorization.joins(:order)
229
+ .where(orders: { account_id: account.id },
230
+ authorizations: { status: "valid" })
231
+ .select(&:valid_for_issuance?)
232
+ .map { it.identifier["value"] }
233
+
234
+ certificate_domains(record).all? { |domain| covered.include?(domain) }
235
+ end
236
+
237
+ # The identifiers a certificate covers (its subjectAltNames)
238
+ def certificate_domains(record)
239
+ domains = Array(record.alternate_names).map { it.delete_prefix("DNS:") }
240
+ domains = record.order.domains if domains.empty? && record.order
241
+ domains.sort
242
+ end
243
+
117
244
  def acme_csr_valid?(order_csr)
118
245
  csr = order_csr.csr
119
246
  order = order_csr.order
@@ -125,8 +252,13 @@ module Bullion
125
252
  # Make sure the CSR has a valid public key
126
253
  raise Bullion::Acme::Errors::BadCsr unless csr.verify(csr.public_key)
127
254
 
128
- raise Bullion::Acme::Errors::BadCsr if csr_cn && !csr_domains.include?(csr_cn)
129
- raise Bullion::Acme::Errors::BadCsr unless csr_domains.sort == order.domains.sort
255
+ # The CA may only sign identifiers the order has proven control of:
256
+ # the CSR's names must match the validated identifier set exactly, so
257
+ # no extra or substituted name can make it into a certificate.
258
+ validated = validated_domains(order)
259
+
260
+ raise Bullion::Acme::Errors::BadCsr if csr_cn && !validated.include?(csr_cn)
261
+ raise Bullion::Acme::Errors::BadCsr unless csr_domains.sort == validated
130
262
 
131
263
  true
132
264
  end
@@ -134,14 +266,17 @@ module Bullion
134
266
  def order_valid?(hash)
135
267
  validate_order_nb_and_na(hash["notBefore"], hash["notAfter"])
136
268
 
269
+ identifiers = hash["identifiers"]
270
+ validate_identifiers(identifiers)
271
+
137
272
  # Don't approve empty orders
138
- raise Bullion::Acme::Errors::InvalidOrder, "Empty order!" if hash["identifiers"].empty?
273
+ raise Bullion::Acme::Errors::Malformed, "Empty order!" if identifiers.empty?
139
274
 
140
- order_domains = hash["identifiers"].select { it["type"] == "dns" }
275
+ order_domains = identifiers.select { it["type"] == "dns" }
141
276
 
142
277
  # Don't approve an order with identifiers that _aren't_ of type 'dns'
143
- unless hash["identifiers"] == order_domains
144
- raise Bullion::Acme::Errors::InvalidOrder, 'Only type "dns" allowed'
278
+ unless identifiers == order_domains
279
+ raise Bullion::Acme::Errors::UnsupportedIdentifier, 'Only type "dns" allowed'
145
280
  end
146
281
 
147
282
  # Extract domains that end with something in our allowed domains list
@@ -150,7 +285,7 @@ module Bullion
150
285
  # Only allow configured domains...
151
286
  unless order_domains == valid_domains
152
287
  raise(
153
- Bullion::Acme::Errors::InvalidOrder,
288
+ Bullion::Acme::Errors::RejectedIdentifier,
154
289
  "Domains #{order_domains - valid_domains} not allowed"
155
290
  )
156
291
  end
@@ -167,28 +302,59 @@ module Bullion
167
302
 
168
303
  return unless not_before && not_after
169
304
 
170
- nb = Time.parse(not_before)
171
- na = Time.parse(not_after)
305
+ nb = parse_time(not_before)
306
+ na = parse_time(not_after)
172
307
 
173
308
  # don't allow nonsense certs
174
- raise Bullion::Acme::Errors::InvalidOrder unless nb < na
309
+ raise Bullion::Acme::Errors::Malformed, "notBefore must be before notAfter" unless nb < na
175
310
  # don't allow far-future certs
176
311
  if nb > Time.now + (7 * 86_400) || na > Time.now + Bullion.config.ca.cert_validity_duration
177
- raise Bullion::Acme::Errors::InvalidOrder
312
+ raise Bullion::Acme::Errors::Malformed, "notBefore/notAfter outside the allowed window"
178
313
  end
179
314
 
180
315
  # don't allow really "old" certs
181
- raise Bullion::Acme::Errors::InvalidOrder if nb < Time.now - (14 * 86_400)
316
+ if nb < Time.now - (14 * 86_400)
317
+ raise Bullion::Acme::Errors::Malformed, "notBefore is too far in the past"
318
+ end
182
319
  # don't allow creating certs that are already expired
183
- raise Bullion::Acme::Errors::InvalidOrder if na <= Time.now
320
+ raise Bullion::Acme::Errors::Malformed, "notAfter is in the past" if na <= Time.now
184
321
  end
185
322
  # rubocop:enable Metrics/AbcSize
186
323
  # rubocop:enable Metrics/CyclomaticComplexity
187
324
  # rubocop:enable Metrics/PerceivedComplexity
188
325
 
326
+ # Parses an ISO-8601-ish timestamp; an unparseable value is a
327
+ # client-malformed request, never a server fault.
328
+ def parse_time(value)
329
+ Time.parse(value)
330
+ rescue ArgumentError, TypeError
331
+ raise Bullion::Acme::Errors::Malformed, "Unparseable time value: #{value.inspect}"
332
+ end
333
+
334
+ # Validates that the newOrder identifiers are objects with string
335
+ # "type" and "value" members; anything else is a malformed request.
336
+ def validate_identifiers(identifiers)
337
+ unless identifiers.is_a?(Array)
338
+ raise Bullion::Acme::Errors::Malformed, "identifiers must be an array of objects"
339
+ end
340
+
341
+ identifiers.each do |identifier|
342
+ next if identifier.is_a?(Hash) &&
343
+ identifier["type"].is_a?(String) &&
344
+ identifier["value"].is_a?(String)
345
+
346
+ raise Bullion::Acme::Errors::Malformed,
347
+ 'each identifier must be an object with string "type" and "value"'
348
+ end
349
+ end
350
+
189
351
  def extract_valid_order_domains(order_domains)
190
352
  order_domains.reject do |domain|
191
- Bullion.config.ca.domains.none? { domain["value"].end_with?(it) }
353
+ # Only allow a configured domain itself or a proper subdomain of it;
354
+ # the dot boundary stops "nottest.domain" from matching "test.domain"
355
+ Bullion.config.ca.domains.none? do |configured|
356
+ domain["value"] == configured || domain["value"].end_with?(".#{configured}")
357
+ end
192
358
  end
193
359
  end
194
360