rodauth-bankid 1.0.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 231f8cbd24cb2618dcb3ff95b6ce0c63402dce76e9620ba0a96574f02adabf6e
4
+ data.tar.gz: 38af7ea1cd028e5cd7b2d9cfaae162142a20620c01d03c7941c751033d5f2e49
5
+ SHA512:
6
+ metadata.gz: df1dcc74aaf3820bbc01ae10709660d7e8710209dc663a686503ce9325b39160c0e153de3428722606bc591850036dad4c203e312e71b46e77d1ca798de0ed8f
7
+ data.tar.gz: ba13fff3c002e8c39f866f7717b58a2f8602f97eb362d1a706a7fe10ab26f9b03291f04854788ef01acdab382beea2b368c9a6776c266b0a5afdd264ec96f2e5
data/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ All notable changes to rodauth-bankid. Format roughly follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project uses
5
+ SemVer per [SemVer 2.0](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [1.0.0] - 2026-12-03
8
+
9
+ ### Added
10
+
11
+ - Initial release, see the README for what the gem does
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marcel Asio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,266 @@
1
+ # rodauth-bankid
2
+
3
+ Swedish BankID login, signing and re-authentication for [Rodauth](https://github.com/jeremyevans/rodauth). Implements the BankID RP API v6 flows: animated QR code, same-device autostart with return URL, server-side attempt state, identity linking to Rodauth accounts, signing with stored evidence, and BankID as the confirmation step for sensitive actions. Step-up (MRTD) works on all three.
4
+
5
+ Status: 1.0.0. Ruby and JavaScript test suites run green on Rodauth 2.47. Requires Ruby 3.4 or newer. See "What is verified" below before you trust it.
6
+
7
+ ## How it works
8
+
9
+ 1. `GET /bankid-login` renders the page. No side effects.
10
+ 2. `POST /bankid-auth` calls BankID `/auth`. The order state goes into `account_bankid_attempts`. The browser session gets a random token only.
11
+ 3. The page polls `POST /bankid-qr` every second and `POST /bankid-collect` every two seconds. The server enforces the collect interval.
12
+ 4. On `complete`, the collect request claims the attempt, resolves the account, updates the identity row, and runs `after_bankid_collect`. All of that is one database transaction; the claim goes first, so a cancelled or expired attempt rolls the rest back and a concurrent collector that loses the claim writes nothing.
13
+ 5. The page posts `/bankid-login`. That request calls Rodauth's `login("bankid")`. Inside Rodauth's login transaction, after `before_login` and the session update, it consumes the attempt, sets `first_login_at` and `last_login_at`, and writes the login log row. A `before_login` that rejects halts before anything is consumed or recorded; a later exception rolls everything back and clears the half-built session. A completion that is never posted records no login.
14
+
15
+ Without JavaScript the same forms work: Start, then open the app, then Continue. Continue runs the collect itself.
16
+
17
+ ## Install
18
+
19
+ ```ruby
20
+ gem "rodauth-bankid"
21
+ ```
22
+
23
+ Copy `db/migrations/001_create_bankid_tables.rb` into your migration sequence. It creates four tables:
24
+
25
+ | Table | Purpose |
26
+ | --- | --- |
27
+ | `account_bankid_identities` | One row per linked BankID. Digest of the personnummer, name, issue date, first and last login |
28
+ | `account_bankid_attempts` | Order state while a login or signing runs. Short-lived |
29
+ | `account_bankid_logins` | Append-only log, one row per successful login |
30
+ | `account_bankid_signatures` | Sign orders and their evidence. Only used with the `bankid_sign` feature |
31
+
32
+ ## Configuration
33
+
34
+ ```ruby
35
+ plugin :rodauth do
36
+ enable :login, :logout, :bankid
37
+
38
+ bankid_environment :test # :production
39
+ bankid_p12_path "config/bankid/rp.p12" # RP certificate from bankid.com
40
+ bankid_p12_password ENV.fetch("BANKID_P12_PASSWORD")
41
+ bankid_ca_file "config/bankid/server-ca.pem" # BankID server CA. Their chain is not in system stores
42
+ bankid_identity_secret ENV.fetch("BANKID_IDENTITY_SECRET")
43
+ bankid_return_url "https://members.example.se/bankid-login"
44
+ end
45
+ ```
46
+
47
+ Add a link to `rodauth.bankid_login_path` on your login page.
48
+
49
+ ### Identity secret
50
+
51
+ `bankid_identity_secret` keys the HMAC that replaces the personnummer in `account_bankid_identities`. Generate 32 or more random bytes. It is separate from `hmac_secret` on purpose: Rodauth rotates `hmac_secret` with `hmac_old_secret`, but a rotated identity secret would orphan every linked BankID, since the plain personnummer is never stored. Keep it fixed and back it up like a database key.
52
+
53
+ The environment is part of the digest input, so test and production identities never match. The environment comes from the client in use, not from `bankid_environment`: an injected test client hashes under `test` even if you forget to set `bankid_environment`.
54
+
55
+ ### Client
56
+
57
+ Set `bankid_client` to your own `Rodauth::BankID::Client` if you build it elsewhere:
58
+
59
+ ```ruby
60
+ bankid_client Rodauth::BankID::Client.from_p12(path, password, environment: :test, ca_file: ca)
61
+ ```
62
+
63
+ The client pins TLS 1.2, verifies the hostname, sends the p12 intermediate chain, ignores proxy environment variables, and never retries. Errors are `TransportError`, `ProtocolError`, or `APIError`. Messages carry no provider text; `APIError#code` and `#details` are there for your logs.
64
+
65
+ ### Order options
66
+
67
+ | Method | Default | Purpose |
68
+ | --- | --- | --- |
69
+ | `bankid_end_user_ip` | `request.ip` | Must be the real client IP. Behind HAProxy, trust `X-Forwarded-For` from the proxy only |
70
+ | `bankid_auth_requirement` | `nil` | BankID `requirement` object, e.g. `{ "pinCode" => true }` |
71
+ | `bankid_return_url` | `nil` | HTTPS URL of your BankID login page. Enables the mobile return flow |
72
+ | `bankid_return_risk?` | `false` | Ask BankID for a risk indication |
73
+ | `bankid_web_parameters` | `nil` | v6.1 `web` object (`referringDomain`, `userAgent`, `deviceIdentifier`) |
74
+ | `bankid_attempt_ttl` | `180` | Seconds an order may run |
75
+ | `bankid_completion_ttl` | `60` | Seconds between completion and the login POST |
76
+ | `bankid_collect_interval` | `2` | Server-enforced polling interval |
77
+
78
+ ### Stored data
79
+
80
+ Two events write to `account_bankid_identities`. Identity verification happens at collect time and updates the profile columns. Login happens at the login POST and updates the login columns. Set a column to `nil` to stop storing it:
81
+
82
+ ```ruby
83
+ # verification, at collect
84
+ bankid_identities_name_column :name
85
+ bankid_identities_given_name_column :given_name
86
+ bankid_identities_surname_column :surname
87
+ bankid_identities_issue_date_column :bankid_issue_date
88
+ bankid_identities_verified_at_column :last_verified_at
89
+ # login, at the login POST
90
+ bankid_identities_first_login_column :first_login_at
91
+ bankid_identities_last_login_column :last_login_at
92
+ ```
93
+
94
+ The login log gets one row per completed login with `ip_address`, `uhi`, `step_up_mrtd`, and `risk`. Between collect and login these values sit as JSON on the attempt row, for at most `bankid_completion_ttl` seconds. Signatures are off by default because the signature XML contains the personnummer in clear:
95
+
96
+ ```ruby
97
+ bankid_logins_table :account_bankid_logins # nil disables the log
98
+ bankid_log_signature? false # signature and ocspResponse
99
+ ```
100
+
101
+ ## Linking BankID to accounts
102
+
103
+ Default lookup: `account_bankid_identities` by digest. Link an identity from your own code:
104
+
105
+ ```ruby
106
+ rodauth.bankid_link_identity(account_id, personal_number)
107
+ ```
108
+
109
+ Or resolve accounts your own way. The hook receives BankID's `completionData`:
110
+
111
+ ```ruby
112
+ bankid_account_from_completion do |completion|
113
+ member = db[:members].where(personal_number: completion["user"]["personalNumber"]).first
114
+ member && account_ds(member[:account_id]).first
115
+ end
116
+ ```
117
+
118
+ To create accounts on first login:
119
+
120
+ ```ruby
121
+ bankid_create_account? true
122
+
123
+ bankid_new_account do |completion|
124
+ id = db[:accounts].insert(email: "bankid-#{SecureRandom.uuid}@placeholder.invalid", status_id: 2)
125
+ bankid_link_identity(id, completion["user"]["personalNumber"])
126
+ account_ds(id).first
127
+ end
128
+ ```
129
+
130
+ BankID returns no email address. Use a random placeholder and collect a real one in a separate verified step. Do not derive the login from the personnummer.
131
+
132
+ ## Hooks
133
+
134
+ - `after_bankid_collect`: identity verified. Runs inside the claim transaction, so your database writes roll back with it. `account` and `bankid_completion` (the full payload) are set. For effects outside the database, use `db.after_commit { ... }` inside the hook so they never fire for a rolled-back claim.
135
+ - `before_bankid_login`: before Rodauth's `login`, outside its transaction. `after_bankid_login`: inside the login transaction, after the login was recorded. `bankid_completion` holds the stored subset in both.
136
+ - `bankid_new_account` runs inside a savepoint. If another request links the same identity first, the savepoint rolls back and the winner's account is used.
137
+ - `before_bankid_auth_route`, `before_bankid_qr_route`, `before_bankid_collect_route`, `before_bankid_cancel_route`, `before_bankid_login_route`.
138
+
139
+ ## JSON contract
140
+
141
+ Every endpoint is POST with a CSRF token in the `_csrf` form field. Send `Accept: application/json` to get JSON; forms get redirects.
142
+
143
+ | Route | 200 response |
144
+ | --- | --- |
145
+ | `/bankid-auth` | `status`, `autoStartToken`, `autostartUrl`, `universalUrl`, `pollAfter` |
146
+ | `/bankid-qr` | `svg` (null once completed) |
147
+ | `/bankid-collect` | `status` pending/failed/complete, `hint`, `pollAfter` |
148
+ | `/bankid-cancel` | `status: cancelled` |
149
+ | `/bankid-login` | Rodauth login redirect |
150
+
151
+ Errors: 409 already logged in, 410 attempt expired or consumed, 429 polled too early (`Retry-After`), 403 no usable account, 502 BankID unreachable. Every BankID route, including the HTML page and redirects, sets `Cache-Control: no-store`.
152
+
153
+ ## Signing
154
+
155
+ Enable `bankid_sign` next to `bankid`. It needs a logged-in account.
156
+
157
+ ```ruby
158
+ enable :login, :logout, :bankid, :bankid_sign
159
+
160
+ bankid_sign_return_url "https://members.example.se/bankid-sign"
161
+ bankid_sign_redirect { "/agreements/#{bankid_signature[:reference]}" }
162
+
163
+ # Optional. The account's personnummer, if your app knows it. Locks the
164
+ # order to that BankID and is used to verify the signer.
165
+ bankid_sign_personal_number { db[:members].where(account_id: account_id).get(:personal_number) }
166
+ ```
167
+
168
+ From your own route, record what the account is about to sign and send the browser to the sign page:
169
+
170
+ ```ruby
171
+ r.post "agreements/:reference/sign" do |reference|
172
+ rodauth.require_account
173
+ rodauth.bankid_sign_prepare(
174
+ visible_data: "I accept the membership terms for 2026.", # shown in the app
175
+ non_visible_data: "terms:2026:member:#{member_id}", # optional, signed but not shown
176
+ format: nil, # or "simpleMarkdownV1"
177
+ reference: reference # your own key
178
+ )
179
+ r.redirect rodauth.bankid_sign_path
180
+ end
181
+ ```
182
+
183
+ The flow then mirrors login: `GET /bankid-sign` shows the text and a Sign button, `POST /bankid-sign-start` starts the order, the page polls `/bankid-sign-qr` and `/bankid-sign-collect`, and `POST /bankid-sign` finishes with `bankid_sign_redirect`. `/bankid-sign-cancel` marks the row cancelled.
184
+
185
+ Signer verification. A sign order is only valid if the BankID that signed belongs to the logged-in account. With `bankid_sign_personal_number` set, the number goes into the order's `requirement`, so BankID refuses any other BankID, and the completion is checked against it. Without it, the completion's personnummer must match a linked identity of the account. No match means 403 `signer_mismatch` and the row stays pending. Override `bankid_sign_verify_signer` if your rule differs.
186
+
187
+ What is stored on completion: `signature` (the XML that BankID produced, containing the signed text and the signer's identity), `ocsp_response`, `signer_name`, `identity_digest`, `bankid_issue_date`, `ip_address`, `uhi`, `step_up_mrtd`, `risk`, `order_ref`, `signed_at`. Rows are the evidence, so keep them under your own retention rule. Signing does not touch the login log.
188
+
189
+ Hooks: `before_bankid_sign` before the order starts, `after_bankid_sign` inside the claim transaction with `bankid_signature` and `bankid_completion` set. Same rollback rules as `after_bankid_collect`.
190
+
191
+ Step-up on signing: `bankid_sign_mrtd? true` adds `mrtd` to the requirement. Login has no named option for this; set it through `bankid_auth_requirement` instead. Both flows record what BankID reports back in `step_up_mrtd`.
192
+
193
+ ## Confirming a sensitive action
194
+
195
+ Enable `bankid_confirm` next to `bankid`. It is the BankID counterpart of Rodauth's `confirm_password`: guard an action with `require_bankid_authentication` and the request is sent to `/bankid-confirm` unless the session holds a BankID proof younger than `bankid_confirm_grace_period` (300 seconds by default).
196
+
197
+ ```ruby
198
+ enable :login, :logout, :bankid, :bankid_confirm
199
+
200
+ bankid_confirm_grace_period 300
201
+ bankid_confirm_personal_number { db[:members].where(account_id: account_id).get(:personal_number) }
202
+ ```
203
+
204
+ ```ruby
205
+ r.on "agreements" do
206
+ rodauth.require_bankid_authentication
207
+ # ...
208
+ end
209
+ ```
210
+
211
+ The order is an identification order bound to the logged-in account, so the account is known before BankID answers. With `bankid_confirm_personal_number` set, the number goes into the order's `requirement` and the completion is checked against it; without it, the completion's personnummer must match a linked identity. No match means 403 `identity_mismatch` for a JSON caller and no proof is granted. A BankID login stamps the same proof, so a visitor who just logged in with BankID is not asked to confirm twice. An HTML request without a proof is redirected to the confirm page; `bankid_authentication_required_error_status` (401) applies to JSON callers.
212
+
213
+ ## Same-device flow
214
+
215
+ Desktop gets `bankid:///?autostarttoken=...&redirect=null`. Mobile gets `https://app.bankid.com/?autostarttoken=...&redirect=<return url>`. iOS requires a redirect value, so set `bankid_return_url` to your BankID login page. The URL sent to BankID carries a per-attempt nonce as `#bankid=<32 hex>`. The page parses that exact fragment and refuses to continue when it names a different attempt than the session holds.
216
+
217
+ The page script keeps one generation per attempt. Restarting aborts in-flight requests, and responses from an older attempt are dropped. Start is disabled while the start request runs.
218
+
219
+ ## Operations
220
+
221
+ - Run `Rodauth::BankID::Store.new(DB).prune` from a scheduler, once a minute is fine.
222
+ - All app workers must share the database.
223
+ - If your tables sit under PostgreSQL row level security, `accounts`, `account_bankid_identities`, and `account_bankid_attempts` must be readable before any tenant context is set. Login runs before you know the organization.
224
+ - Closed-account checks depend on Rodauth: `open_account?` is only enforced when `verify_account` or `close_account` is enabled.
225
+ - Replace the `bankid_hint_*` texts with BankID's RFA texts in Swedish.
226
+ - Add rate limiting on `/bankid-auth` at your edge. The collect throttle is per attempt, not per IP.
227
+
228
+ ## Development
229
+
230
+ | Task | What it does |
231
+ | --- | --- |
232
+ | `rake test` | Ruby suite on in-memory SQLite, then the page script tests on node if installed |
233
+ | `rake test:postgres[url]` | Ruby suite on PostgreSQL. Also reads `BANKID_TEST_DATABASE_URL`. Enables the registration race test that needs row-level locking |
234
+ | `rake test:all` | SQLite, JavaScript, and PostgreSQL when the URL is set |
235
+ | `rake lint`, `rake fix` | RuboCop, and RuboCop with safe autocorrect |
236
+ | `rake check` | Tests and lint. Point your pipeline at this |
237
+ | `rake console` | IRB with the gem loaded |
238
+ | `rake bankid:cert[path,password]` | Print subject, issuer, validity, and chain of an RP `.p12`. Warns 30 days before expiry |
239
+ | `rake bankid:smoke[test]` | Start, collect, and cancel one auth order and one sign order against BankID with your certificate. Verifies mutual TLS, the CA bundle, and the v6 contract. Reads `BANKID_P12_PATH`, `BANKID_P12_PASSWORD`, `BANKID_CA_FILE`, and optionally `BANKID_RETURN_URL` and `BANKID_END_USER_IP` |
240
+ | `rake build`, `rake install`, `rake release` | Bundler gem tasks |
241
+
242
+ Example PostgreSQL run:
243
+
244
+ ```
245
+ rake test:postgres[postgres://user@localhost/bankid_test]
246
+ ```
247
+
248
+ ## What is verified
249
+
250
+ Verified by the test suites in this repository:
251
+
252
+ - Attempt state, throttling, claim, consume, expiry, environment namespacing, no-store headers, login recording only inside Rodauth's login transaction, rollback when `before_login` rejects or a later hook raises.
253
+ - Races between two database connections: cancel during the BankID round trip, cancel while the claim transaction is open, a second claim blocking on the first and losing, and (PostgreSQL only) two connections registering the same identity.
254
+ - The sign flow: prepare, page, order options including `requirement.personalNumber` and `mrtd`, evidence storage, signer verification against an app-supplied number and against linked identities, cancellation, and isolation from a login attempt in the same session.
255
+ - The confirm flow: the guard, the grace period including its expiry and the proof a BankID login stamps, the order being bound to the account before BankID answers, and the 403 on another person's BankID.
256
+ - The client's request bodies, IP and return URL validation, error mapping, no retries. WebMock stands in for BankID; TLS is not exercised.
257
+ - The page script's double-start guard, abort on restart, late responses from an old attempt arriving after the new one began, `Retry-After`, and nonce parsing, against a fake DOM.
258
+ - The animated QR HMAC against the example vector in BankID's documentation.
259
+
260
+ Not verified. Do these against BankID's test environment before production:
261
+
262
+ - That BankID accepts `returnUrl` as a plain string on the API version you use. This gem sends it unencoded per the /auth reference.
263
+ - The same-device return flow on iOS Safari and Android Chrome, including whether the browser lands back on the page with the fragment intact.
264
+ - Real mutual TLS, including a wrong CA and an expired RP certificate, to confirm the client fails closed.
265
+ - Whether BankID accepts `web` without `deviceIdentifier` if you enable `bankid_web_parameters`.
266
+ - Review what your `after_bankid_collect` hook stores.
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copy into your migration sequence with a suitable number. Expects an
4
+ # accounts table with a Bignum primary key named id. PostgreSQL only.
5
+ Sequel.migration do
6
+ up do
7
+ # Order kinds: auth (login), sign, confirm (re-authentication).
8
+ create_table(:bankid_attempt_kinds) do
9
+ String :kind, primary_key: true
10
+ String :description
11
+ end
12
+ self[:bankid_attempt_kinds].multi_insert([
13
+ { kind: 'auth', description: 'Login' },
14
+ { kind: 'sign', description: 'Signing' },
15
+ { kind: 'confirm', description: 'Re-authentication' }
16
+ ])
17
+
18
+ create_table(:bankid_signature_statuses) do
19
+ String :status, primary_key: true
20
+ String :description
21
+ end
22
+ self[:bankid_signature_statuses].multi_insert([
23
+ { status: 'pending', description: 'Order prepared, not yet signed' },
24
+ { status: 'signed', description: 'Evidence stored' },
25
+ { status: 'cancelled', description: 'Abandoned by the user' }
26
+ ])
27
+
28
+ # One row per linked BankID. The personnummer is never stored; only its
29
+ # HMAC digest (see bankid_identity_secret).
30
+ create_table(:account_bankid_identities) do
31
+ primary_key :account_bankid_identity_id
32
+ foreign_key :account_id, :accounts, type: :Bignum, null: false, on_delete: :cascade
33
+ String :identity_digest, size: 64, fixed: true, null: false, unique: true
34
+ String :name
35
+ String :given_name
36
+ String :surname
37
+ Date :bankid_issue_date
38
+ column :last_verified_at, :timestamptz
39
+ column :first_login_at, :timestamptz
40
+ column :last_login_at, :timestamptz
41
+ column :created_at, :timestamptz, null: false, default: Sequel::CURRENT_TIMESTAMP
42
+ index :account_id
43
+ end
44
+
45
+ # Sign orders and their evidence (bankid_sign feature). The signature
46
+ # XML contains the signer's personnummer in clear — keep rows under your
47
+ # own retention rule.
48
+ create_table(:account_bankid_signatures) do
49
+ primary_key :account_bankid_signature_id
50
+ foreign_key :account_id, :accounts, type: :Bignum, null: false, on_delete: :cascade
51
+ String :reference
52
+ String :visible_data, text: true, null: false
53
+ String :non_visible_data, text: true
54
+ String :visible_data_format
55
+ foreign_key :status, :bankid_signature_statuses, type: String, null: false, default: 'pending'
56
+ String :order_ref
57
+ String :signature, text: true
58
+ String :ocsp_response, text: true
59
+ String :signer_name
60
+ String :identity_digest, size: 64, fixed: true
61
+ Date :bankid_issue_date
62
+ String :ip_address
63
+ String :uhi
64
+ TrueClass :step_up_mrtd
65
+ String :risk
66
+ column :created_at, :timestamptz, null: false, default: Sequel::CURRENT_TIMESTAMP
67
+ column :signed_at, :timestamptz
68
+ index %i[account_id created_at]
69
+ index %i[account_id reference]
70
+ end
71
+
72
+ # Order state while a login, signing, or confirmation runs. Short-lived;
73
+ # the browser session holds only a token whose digest is the key.
74
+ create_table(:account_bankid_attempts) do
75
+ String :token_digest, size: 64, fixed: true, primary_key: true
76
+ foreign_key :kind, :bankid_attempt_kinds, type: String, null: false
77
+ String :order_ref, null: false, unique: true
78
+ String :auto_start_token, null: false
79
+ String :qr_start_token, null: false
80
+ String :qr_start_secret, null: false
81
+ String :nonce, size: 32, fixed: true, null: false
82
+ column :started_at, :timestamptz, null: false
83
+ column :expires_at, :timestamptz, null: false
84
+ column :next_collect_at, :timestamptz, null: false
85
+ column :completed_at, :timestamptz
86
+ String :identity_digest, size: 64, fixed: true
87
+ String :completion, text: true
88
+ foreign_key :account_id, :accounts, type: :Bignum, on_delete: :cascade
89
+ foreign_key :account_bankid_signature_id, :account_bankid_signatures, on_delete: :cascade
90
+ index :expires_at
91
+ end
92
+
93
+ # Append-only log, one row per successful BankID login.
94
+ create_table(:account_bankid_logins) do
95
+ primary_key :account_bankid_login_id
96
+ foreign_key :account_id, :accounts, type: :Bignum, null: false, on_delete: :cascade
97
+ String :ip_address
98
+ String :uhi
99
+ TrueClass :step_up_mrtd
100
+ String :risk
101
+ String :signature, text: true
102
+ String :ocsp_response, text: true
103
+ column :created_at, :timestamptz, null: false, default: Sequel::CURRENT_TIMESTAMP
104
+ index %i[account_id created_at]
105
+ end
106
+ end
107
+
108
+ down do
109
+ drop_table :account_bankid_logins
110
+ drop_table :account_bankid_attempts
111
+ drop_table :account_bankid_signatures
112
+ drop_table :account_bankid_identities
113
+ drop_table :bankid_signature_statuses
114
+ drop_table :bankid_attempt_kinds
115
+ end
116
+ end
@@ -0,0 +1,192 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ipaddr'
4
+ require 'json'
5
+ require 'net/http'
6
+ require 'openssl'
7
+ require 'uri'
8
+
9
+ module Rodauth
10
+ module BankID
11
+ # HTTP client for the BankID RP API v6 over mutual TLS with the relying
12
+ # party certificate. The features build one from the +bankid_p12_path+
13
+ # / +bankid_cert_pem+ settings; pass your own via +bankid_client+ when
14
+ # you construct it elsewhere.
15
+ #
16
+ # client = Rodauth::BankID::Client.from_p12('rp.p12', 'secret',
17
+ # environment: :test, ca_file: 'bankid-test-ca.pem')
18
+ # order = client.auth(end_user_ip: '203.0.113.7')
19
+ #
20
+ # The client pins TLS 1.2, verifies the hostname, sends the p12
21
+ # intermediate chain, ignores proxy environment variables, and never
22
+ # retries. Errors are TransportError, ProtocolError, or APIError;
23
+ # messages carry no provider text.
24
+ #
25
+ # = Options
26
+ #
27
+ # certificate :: OpenSSL::X509::Certificate of the relying party.
28
+ # private_key :: OpenSSL::PKey matching +certificate+.
29
+ # ca_file :: Path to BankID's server CA bundle (PEM). Required — their
30
+ # chain is not in system trust stores.
31
+ # environment :: +:production+ or +:test+. Default: +:production+.
32
+ # certificate_chain :: Intermediate certificates sent along with
33
+ # +certificate+. Default: none.
34
+ # open_timeout, read_timeout, write_timeout :: Seconds. Defaults: 5,
35
+ # 10, 5.
36
+ class Client
37
+ ENDPOINTS = {
38
+ production: 'https://appapi2.bankid.com/rp/v6.0/',
39
+ test: 'https://appapi2.test.bankid.com/rp/v6.0/'
40
+ }.freeze
41
+
42
+ RETURN_URL_MAX = 512
43
+
44
+ # The environment Symbol this client talks to. Identity digests are
45
+ # namespaced by it (see the +bankid+ feature).
46
+ attr_reader :environment
47
+
48
+ # Builds a client from the +.p12+ bundle BankID issues to relying
49
+ # parties, forwarding +opts+ to +new+. Raises OpenSSL::PKCS12Error
50
+ # for a wrong password.
51
+ def self.from_p12(path, password, **)
52
+ p12 = OpenSSL::PKCS12.new(File.binread(path), password)
53
+ new(certificate: p12.certificate, private_key: p12.key,
54
+ certificate_chain: p12.ca_certs || [], **)
55
+ end
56
+
57
+ def initialize(certificate:, private_key:, ca_file:, environment: :production,
58
+ certificate_chain: [], open_timeout: 5, read_timeout: 10, write_timeout: 5)
59
+ @environment = environment.to_sym
60
+ @endpoint = URI(ENDPOINTS.fetch(@environment) do
61
+ raise ArgumentError, "unknown environment #{environment.inspect}"
62
+ end)
63
+ unless certificate.check_private_key(private_key)
64
+ raise ArgumentError,
65
+ 'certificate and private key do not match'
66
+ end
67
+
68
+ @certificate = certificate
69
+ @private_key = private_key
70
+ @certificate_chain = certificate_chain
71
+ @ca_file = ca_file
72
+ @open_timeout = open_timeout
73
+ @read_timeout = read_timeout
74
+ @write_timeout = write_timeout
75
+ end
76
+
77
+ # Starts an authentication order and returns BankID's response Hash.
78
+ # +opts+ are +requirement+, +return_url+, +return_risk+, +web+, and
79
+ # +app+; empty and +nil+ values are left out of the request body.
80
+ # Raises ArgumentError for a malformed IP or return URL.
81
+ def auth(end_user_ip:, **)
82
+ post('auth', order_body(end_user_ip, **))
83
+ end
84
+
85
+ # Starts a signing order. +user_visible_data+ is required by BankID
86
+ # and Base64-encoded here; +user_non_visible_data+ and
87
+ # +user_visible_data_format+ are optional, plus the +auth+ options.
88
+ def sign(end_user_ip:, user_visible_data:, **)
89
+ post('sign', order_body(end_user_ip, user_visible_data: user_visible_data, **))
90
+ end
91
+
92
+ # Returns the order status. Poll at most every two seconds until
93
+ # +status+ is +complete+ or +failed+.
94
+ def collect(order_ref:)
95
+ post('collect', { 'orderRef' => order_ref })
96
+ end
97
+
98
+ # Cancels the order. Returns an empty Hash on success.
99
+ def cancel(order_ref:)
100
+ post('cancel', { 'orderRef' => order_ref })
101
+ end
102
+
103
+ private
104
+
105
+ def order_body(end_user_ip, requirement: nil, return_url: nil, return_risk: nil,
106
+ user_visible_data: nil, user_non_visible_data: nil,
107
+ user_visible_data_format: nil, web: nil, app: nil)
108
+ body = { 'endUserIp' => validate_ip(end_user_ip) }
109
+ body['requirement'] = requirement if requirement && !requirement.empty?
110
+ body['returnUrl'] = validate_return_url(return_url) if return_url
111
+ body['returnRisk'] = true if return_risk
112
+ body['userVisibleData'] = [user_visible_data].pack('m0') if user_visible_data
113
+ body['userNonVisibleData'] = [user_non_visible_data].pack('m0') if user_non_visible_data
114
+ body['userVisibleDataFormat'] = user_visible_data_format if user_visible_data_format
115
+ body['web'] = web if web
116
+ body['app'] = app if app
117
+ body
118
+ end
119
+
120
+ def validate_ip(ip)
121
+ IPAddr.new(ip.to_s)
122
+ ip.to_s
123
+ rescue IPAddr::Error
124
+ raise ArgumentError, 'end_user_ip is not a valid IP address'
125
+ end
126
+
127
+ # Plain string per the BankID reference, 1 to 512 characters.
128
+ def validate_return_url(url)
129
+ uri = begin
130
+ URI(url.to_s)
131
+ rescue URI::InvalidURIError
132
+ nil
133
+ end
134
+ ok = uri && uri.scheme == 'https' && uri.host && !uri.userinfo && url.to_s.length.between?(1, RETURN_URL_MAX)
135
+ unless ok
136
+ raise ArgumentError,
137
+ "return_url must be an absolute https URL of at most #{RETURN_URL_MAX} characters"
138
+ end
139
+
140
+ url.to_s
141
+ end
142
+
143
+ def http_for(uri)
144
+ # Third argument nil: ignore proxy environment variables.
145
+ http = Net::HTTP.new(uri.host, uri.port, nil)
146
+ http.use_ssl = true
147
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
148
+ http.verify_hostname = true
149
+ http.min_version = OpenSSL::SSL::TLS1_2_VERSION
150
+ http.cert = @certificate
151
+ http.key = @private_key
152
+ http.extra_chain_cert = @certificate_chain unless @certificate_chain.empty?
153
+ http.ca_file = @ca_file
154
+ http.open_timeout = @open_timeout
155
+ http.read_timeout = @read_timeout
156
+ http.write_timeout = @write_timeout
157
+ http.max_retries = 0
158
+ http
159
+ end
160
+
161
+ def post(operation, body)
162
+ uri = @endpoint + operation
163
+ http = http_for(uri)
164
+
165
+ req = Net::HTTP::Post.new(uri.request_uri)
166
+ req['Content-Type'] = 'application/json'
167
+ req['Accept'] = 'application/json'
168
+ req.body = JSON.generate(body)
169
+
170
+ res = http.start { |conn| conn.request(req) }
171
+ data = parse(res.body)
172
+
173
+ return data if res.is_a?(Net::HTTPSuccess)
174
+
175
+ raise APIError.new(res.code.to_i, data['errorCode'], data['details'])
176
+ rescue Timeout::Error, SocketError, IOError, SystemCallError, OpenSSL::SSL::SSLError
177
+ raise TransportError, 'BankID connection failed'
178
+ end
179
+
180
+ def parse(body)
181
+ return {} if body.nil? || body.strip.empty?
182
+
183
+ data = JSON.parse(body)
184
+ raise ProtocolError, 'BankID response is not a JSON object' unless data.is_a?(Hash)
185
+
186
+ data
187
+ rescue JSON::ParserError
188
+ raise ProtocolError, 'BankID response is not valid JSON'
189
+ end
190
+ end
191
+ end
192
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rodauth
4
+ module BankID
5
+ # Base class for everything the gem raises.
6
+ class Error < StandardError; end
7
+
8
+ # Network, TLS, or timeout failure. Never includes provider text.
9
+ class TransportError < Error; end
10
+
11
+ # BankID answered with something we do not understand or trust.
12
+ class ProtocolError < Error; end
13
+
14
+ # BankID answered with an error. The message stays generic;
15
+ # +code+ and +details+ are available for logging.
16
+ class APIError < Error
17
+ attr_reader :http_status, :code, :details
18
+
19
+ def initialize(http_status, code, details)
20
+ @http_status = http_status
21
+ @code = code
22
+ @details = details
23
+ super("BankID request failed (HTTP #{http_status}#{", #{code}" if code})")
24
+ end
25
+ end
26
+
27
+ # The browser token does not match an active attempt.
28
+ class InvalidAttempt < Error; end
29
+
30
+ # Collect was called before the polling interval passed.
31
+ class TooFrequent < Error; end
32
+ end
33
+ end