The personal finance app for everyone (by everyone)
Ruby
Add authenticated version API with explicit public opt-in (#4691)
Sure Admin (bot)3f5d33bed4e4
diff --git a/.env.local.example b/.env.local.exampleindex 7d40bb320a..9f1084e26a 100644--- a/.env.local.example+++ b/.env.local.example@@ -164,3 +164,7 @@ SKYLIGHT_ENABLED=# Temporary local PostHog testing only; off by default. Restart after changing.# Uses live projects and sends real survey responses.# POSTHOG_DEVELOPMENT_ENABLED=true++# Opt in to anonymous GET /api/v1/version (version + commit SHA).+# Default false: requires a read/read_write API key or OAuth token.+PUBLIC_VERSION_ENDPOINT=falsediff --git a/app/controllers/api/v1/versions_controller.rb b/app/controllers/api/v1/versions_controller.rbnew file mode 100644index 0000000000..0979f6552d--- /dev/null+++ b/app/controllers/api/v1/versions_controller.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++class Api::V1::VersionsController < Api::V1::BaseController+ prepend_before_action :prevent_version_caching+ skip_before_action :authenticate_request!, if: :public_version_request?+ before_action :ensure_read_scope, unless: :public_version_request?++ def show+ render_json({ version: Sure.version.to_s, commit_sha: Sure.commit_sha.presence })+ end++ private+ def public_version_request?+ Rails.configuration.public_version_endpoint &&+ request.headers["Authorization"].blank? && request.headers["X-Api-Key"].nil?+ end++ def prevent_version_caching+ response.headers["Cache-Control"] = "private, no-store"+ end+enddiff --git a/config/application.rb b/config/application.rbindex fbd5fc7399..f8b08e66be 100644--- a/config/application.rb+++ b/config/application.rb@@ -34,6 +34,9 @@ module Sure# TODO: This is here for incremental adoption of localization. This can be removed when all translations are implemented.config.i18n.fallbacks = true+ # Exact opt-in: version metadata is authenticated by default.+ config.public_version_endpoint = ENV["PUBLIC_VERSION_ENDPOINT"] == "true"+config.app_mode = (ENV["SELF_HOSTED"] == "true" || ENV["SELF_HOSTING_ENABLED"] == "true" ? "self_hosted" : "managed").inquiry# Self hosters can optionally set their own encryption keys if they want to use ActiveRecord encryption.diff --git a/config/routes.rb b/config/routes.rbindex 011368cfdd..5dd41429bc 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -781,6 +781,7 @@ Rails.application.routes.draw do# API routesnamespace :api donamespace :v1 do+ resource :version, only: :shownamespace :financekit doget "capabilities", to: "connections#capabilities"resources :connections, only: [ :create, :show, :destroy ] dodiff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex ad18af7167..50d4270561 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -32,6 +32,20 @@ components:read: Read accessread_write: Read and write accessschemas:+ Version:+ type: object+ additionalProperties: false+ required:+ - version+ - commit_sha+ properties:+ version:+ type: string+ description: Running Sure version, without a v prefix.+ commit_sha:+ type: string+ nullable: true+ description: Build commit SHA, or null when unavailable.SplitRequest:type: objectrequired:@@ -10843,3 +10857,26 @@ paths:type: stringdescription: Additional notesrequired: true+ "/api/v1/version":+ get:+ summary: Get the running Sure version+ tags:+ - Version+ description: Requires read or read_write access. Operators may explicitly enable+ anonymous access with PUBLIC_VERSION_ENDPOINT=true. Responses are not cacheable.+ Supplied credentials are still validated in public mode.+ security:+ - apiKeyAuth: []+ - oauth2:+ - read+ responses:+ '200':+ description: running version+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/Version"+ '401':+ description: missing or invalid credentials (default configuration)+ '403':+ description: insufficient scopediff --git a/docs/api/version.md b/docs/api/version.mdnew file mode 100644index 0000000000..9b873ec417--- /dev/null+++ b/docs/api/version.md@@ -0,0 +1,35 @@+# Query the running version++`GET /api/v1/version` returns only the running Sure version and build commit:++```json+{"version":"2026.11.2","commit_sha":"0123456789abcdef0123456789abcdef01234567"}+```++By default, supply an `X-Api-Key` or OAuth bearer token with `read` or+`read_write` scope. Browser session cookies do not authenticate this API.+The signed-in user menu already displays the same version and commit.++```sh+curl --fail --header "X-Api-Key: $SURE_API_KEY" "$SURE_URL/api/v1/version"+```++The version comes from Sure's existing version metadata, not a lookup of the+latest GitHub release. In production, the commit comes from `BUILD_COMMIT_SHA`;+it is `null` if unavailable. Development versions may contain a prerelease suffix.+Responses use `Cache-Control: private, no-store`, including authentication errors.++## Optional anonymous access++Set `PUBLIC_VERSION_ENDPOINT=true` in the web application's environment and+restart/redeploy it to explicitly allow anonymous queries. Only the exact value+`true` enables access; unset or other values leave authentication required.+For Docker Compose, pass this variable through the web service's `environment`+section; putting it only in Compose's interpolation `.env` file is not enough.+This option affects only the version endpoint. Supplied credentials are still+validated, with normal scope and API-key rate-limit checks.++Public version and commit information makes deployment fingerprinting easier.+Enable this only when that disclosure is appropriate for the deployment.+This is not a health/readiness endpoint, and disabling public access does not+promise that version information cannot be inferred from other app assets.diff --git a/spec/requests/api/v1/version_spec.rb b/spec/requests/api/v1/version_spec.rbnew file mode 100644index 0000000000..9f7ff7eb77--- /dev/null+++ b/spec/requests/api/v1/version_spec.rb@@ -0,0 +1,59 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'API V1 Version', type: :request do+ let(:family) do+ Family.create!(+ name: 'API Family',+ currency: 'USD',+ locale: 'en',+ date_format: '%m-%d-%Y'+ )+ end++ let(:user) do+ family.users.create!(+ email: '[email protected]',+ password: 'password123',+ password_confirmation: 'password123'+ )+ end++ let(:api_key) do+ key = ApiKey.generate_secure_key+ ApiKey.create!(+ user: user,+ name: 'API Docs Key',+ key: key,+ scopes: %w[read_write],+ source: 'web'+ )+ end++ let(:'X-Api-Key') { api_key.plain_key }++ path '/api/v1/version' do+ get 'Get the running Sure version' do+ tags 'Version'+ description 'Requires read or read_write access. Operators may explicitly enable anonymous access with PUBLIC_VERSION_ENDPOINT=true. Responses are not cacheable. Supplied credentials are still validated in public mode.'+ security [ { apiKeyAuth: [] }, { oauth2: [ 'read' ] } ]+ produces 'application/json'++ response '200', 'running version' do+ schema '$ref' => '#/components/schemas/Version'+ run_test!+ end++ response '401', 'missing or invalid credentials (default configuration)' do+ let(:'X-Api-Key') { nil }+ run_test!+ end++ response '403', 'insufficient scope' do+ before { api_key.update_columns(scopes: []) }+ run_test!+ end+ end+ end+enddiff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rbindex 87090ae347..41d3618659 100644--- a/spec/swagger_helper.rb+++ b/spec/swagger_helper.rb@@ -53,6 +53,15 @@ RSpec.configure do |config|}},schemas: {+ Version: {+ type: :object,+ additionalProperties: false,+ required: %w[version commit_sha],+ properties: {+ version: { type: :string, description: 'Running Sure version, without a v prefix.' },+ commit_sha: { type: :string, nullable: true, description: 'Build commit SHA, or null when unavailable.' }+ }+ },SplitRequest: {type: :object,required: %w[split],diff --git a/test/controllers/api/v1/versions_controller_test.rb b/test/controllers/api/v1/versions_controller_test.rbnew file mode 100644index 0000000000..d17259e343--- /dev/null+++ b/test/controllers/api/v1/versions_controller_test.rb@@ -0,0 +1,97 @@+# frozen_string_literal: true++require "test_helper"++class Api::V1::VersionsControllerTest < ActionDispatch::IntegrationTest+ setup do+ Rails.configuration.stubs(:public_version_endpoint).returns(false)+ Sure.stubs(:version).returns(Calver.new("2026.11.2"))+ Sure.stubs(:commit_sha).returns("a" * 40)+ @user = users(:family_admin)+ @user.api_keys.active.destroy_all+ @api_key = ApiKey.create!(user: @user, name: "Version reader", scopes: [ "read" ],+ source: "web", display_key: "version_#{SecureRandom.hex(16)}")+ end++ test "requires authentication by default without disclosing metadata" do+ get api_v1_version_url+ assert_response :unauthorized+ assert_not response.parsed_body.key?("version")+ assert_includes response.headers["Cache-Control"], "no-store"+ end++ test "read key returns only version and commit with no caching" do+ get api_v1_version_url, headers: api_headers(@api_key)+ assert_response :success+ assert_equal({ "version" => "2026.11.2", "commit_sha" => "a" * 40 }, response.parsed_body)+ assert_includes response.headers["Cache-Control"], "no-store"+ assert_equal "application/json", response.media_type+ end++ test "read write key can query version" do+ @api_key.update!(scopes: [ "read_write" ])+ get api_v1_version_url, headers: api_headers(@api_key)+ assert_response :success+ end++ test "key without read scope is forbidden" do+ @api_key.update_columns(scopes: [])+ get api_v1_version_url, headers: api_headers(@api_key)+ assert_response :forbidden+ end++ test "invalid and revoked keys cannot query version" do+ get api_v1_version_url, headers: { "X-Api-Key" => "invalid" }+ assert_response :unauthorized+ @api_key.update!(revoked_at: Time.current)+ get api_v1_version_url, headers: api_headers(@api_key)+ assert_response :unauthorized+ end++ test "public opt in allows anonymous access but does not open other APIs" do+ Rails.configuration.stubs(:public_version_endpoint).returns(true)+ get api_v1_version_url+ assert_response :success+ assert_equal [ "commit_sha", "version" ], response.parsed_body.keys.sort+ assert_includes response.headers["Cache-Control"], "no-store"+ get api_v1_accounts_url+ assert_response :unauthorized+ end++ test "public opt in still validates supplied credentials" do+ Rails.configuration.stubs(:public_version_endpoint).returns(true)+ get api_v1_version_url, headers: { "X-Api-Key" => "invalid" }+ assert_response :unauthorized+ end++ test "missing build commit is null" do+ Sure.stubs(:commit_sha).returns("")+ get api_v1_version_url, headers: api_headers(@api_key)+ assert_response :success+ assert_nil response.parsed_body.fetch("commit_sha")+ end++ test "public opt in rejects empty and whitespace API keys" do+ Rails.configuration.stubs(:public_version_endpoint).returns(true)++ [ "", " " ].each do |key|+ get api_v1_version_url, headers: { "X-Api-Key" => key }+ assert_response :unauthorized+ assert_not response.parsed_body.key?("version")+ assert_includes response.headers["Cache-Control"], "no-store"+ end+ end++ test "public opt in still enforces read scope on supplied keys" do+ Rails.configuration.stubs(:public_version_endpoint).returns(true)+ @api_key.update_columns(scopes: [])++ get api_v1_version_url, headers: api_headers(@api_key)+ assert_response :forbidden+ end++ private+ def api_headers(api_key)+ { "X-Api-Key" => api_key.display_key }+ end+end