A platform for community discussion. Free, open, simple.
DEV: Move discourse-apple-auth to core (#33570)
Jarek Radosz863c3ecb1aef
diff --git a/.github/labeler.yml b/.github/labeler.ymlindex 19178ddf1a2..b6fa55c93ff 100644--- a/.github/labeler.yml+++ b/.github/labeler.yml@@ -30,6 +30,10 @@ discourse-reactions:- changed-files:- any-glob-to-any-file: plugins/discourse-reactions/**/*+discourse-apple-auth:+ - changed-files:+ - any-glob-to-any-file: plugins/discourse-apple-auth/**/*+footnote:- changed-files:- any-glob-to-any-file: plugins/footnote/**/*diff --git a/.gitignore b/.gitignoreindex e4a67bece50..33b36c249b2 100644--- a/.gitignore+++ b/.gitignore@@ -50,6 +50,7 @@!/plugins/checklist!/plugins/footnote!/plugins/discourse-reactions+!/plugins/discourse-apple-auth/plugins/*/auto_generated/spec/fixtures/plugins/my_plugin/auto_generateddiff --git a/plugins/discourse-apple-auth/README.md b/plugins/discourse-apple-auth/README.mdnew file mode 100644index 00000000000..8bbbd6c857f--- /dev/null+++ b/plugins/discourse-apple-auth/README.md@@ -0,0 +1,5 @@+# discourse-apple-auth++Login to Discourse using 'Sign in with Apple'++For information and support, see https://meta.discourse.org/t/sign-in-with-apple-plugin/171485diff --git a/plugins/discourse-apple-auth/config/locales/client.en.yml b/plugins/discourse-apple-auth/config/locales/client.en.ymlnew file mode 100644index 00000000000..31e83ceec75--- /dev/null+++ b/plugins/discourse-apple-auth/config/locales/client.en.yml@@ -0,0 +1,8 @@+en:+ js:+ login:+ apple:+ name: "Apple"+ title: "Sign in with Apple"+ sr_title: "Sign in with Apple"+ message: "Authenticating with Apple"diff --git a/plugins/discourse-apple-auth/config/locales/server.en.yml b/plugins/discourse-apple-auth/config/locales/server.en.ymlnew file mode 100644index 00000000000..1ff506de9fa--- /dev/null+++ b/plugins/discourse-apple-auth/config/locales/server.en.yml@@ -0,0 +1,7 @@+en:+ site_settings:+ sign_in_with_apple_enabled: 'Enable sign in with Apple?'+ apple_client_id: "(Sign in with Apple) The Apple 'Service Identifier' from the developer console. Normally a reverse-domain name style string (e.g. com.example.auth) (Sign in with Apple)"+ apple_team_id: '(Sign in with Apple) Apple Team ID (10 characters)'+ apple_key_id: '(Sign in with Apple) Apple Key ID (10 characters)'+ apple_pem: '(Sign in with Apple) Apple Pem File Content. Include the BEGIN and END lines'diff --git a/plugins/discourse-apple-auth/config/settings.yml b/plugins/discourse-apple-auth/config/settings.ymlnew file mode 100644index 00000000000..e89d257e01c--- /dev/null+++ b/plugins/discourse-apple-auth/config/settings.yml@@ -0,0 +1,8 @@+plugins:+ sign_in_with_apple_enabled: false+ apple_client_id: ''+ apple_team_id: ''+ apple_key_id: ''+ apple_pem:+ default: ''+ textarea: truediff --git a/plugins/discourse-apple-auth/lib/omniauth_apple.rb b/plugins/discourse-apple-auth/lib/omniauth_apple.rbnew file mode 100644index 00000000000..4d647bffa28--- /dev/null+++ b/plugins/discourse-apple-auth/lib/omniauth_apple.rb@@ -0,0 +1,115 @@+# frozen_string_literal: true++require "omniauth-oauth2"++# There is an omniauth-apple gem which we could use here+# But it has many more features than we need, and more surface area for bugs/exploits+#+# This implementation also has a workaround which redirects+# Apple's POST callbacks to GET requests, so that the browser sends SameSite=Lax+# cookies in the request.+#+# We may want to switch to the gem in future, especially if Apple change+# the implementation++module OmniAuth+ module Strategies+ class Apple < OmniAuth::Strategies::OAuth2+ option :name, "apple"++ option :client_options,+ site: "https://appleid.apple.com",+ authorize_url: "/auth/authorize",+ token_url: "/auth/token"++ option :authorize_params, response_mode: "form_post", scope: "email name"++ uid { id_token_info["sub"] }++ info do+ {}.tap do |h|+ h[:email] = id_token_info["email"] if id_token_info["email"]+ h[:first_name] = unsafe_user_info.dig("name", "firstName")+ h[:last_name] = unsafe_user_info.dig("name", "lastName")+ h[:name] = "#{h[:first_name]} #{h[:last_name]}" if h[:first_name] && h[:last_name]+ end+ end++ extra { { raw_info: { id_token_info: id_token_info, id_token: access_token["id_token"] } } }++ def client+ ensure_client_secret+ super+ end++ def callback_url+ full_host + script_name + callback_path+ end++ def callback_phase+ if request.request_method.downcase.to_sym == :post+ url = "#{callback_url}"+ if (code = request.params["code"]) && (state = request.params["state"])+ url += "?code=#{CGI.escape(code)}"+ url += "&state=#{CGI.escape(state)}"+ url += "&user=#{CGI.escape(request.params["user"])}" if request.params["user"]+ end+ session.options[:drop] = true # Do not set a session cookie on this response+ return redirect url+ end+ super+ end++ private++ def id_token_info+ # Verify the claims in the JWT+ # The signature does not need to be verified because the+ # token was acquired via a direct server-server connection to the issuer+ # But we verify it anyway to be double-safe+ @id_token_info ||=+ begin+ id_token = access_token.params["id_token"]+ jwt_options = {+ verify_iss: true,+ iss: "https://appleid.apple.com",+ verify_aud: true,+ aud: options.client_id,+ verify_not_before: true,+ verify_expiration: true,+ algorithms: ["RS256"],+ jwks: options.jwk_fetcher,+ }+ payload, _header = ::JWT.decode(id_token, nil, true, jwt_options)+ payload+ end+ end++ def unsafe_user_info+ @unsafe_user_info ||=+ begin+ JSON.parse(request.params["user"] || "")+ rescue JSON::ParserError+ {}+ end+ end++ def ensure_client_secret+ options[:client_secret] ||= client_secret+ end++ def client_secret+ payload = {+ iss: options.team_id,+ aud: "https://appleid.apple.com",+ sub: options.client_id,+ iat: Time.now.to_i,+ exp: Time.now.to_i + 60,+ }+ headers = { kid: options.key_id }++ ::JWT.encode(payload, ::OpenSSL::PKey::EC.new(options.pem), "ES256", headers)+ end+ end+ end+enddiff --git a/plugins/discourse-apple-auth/plugin.rb b/plugins/discourse-apple-auth/plugin.rbnew file mode 100644index 00000000000..e495d41a164--- /dev/null+++ b/plugins/discourse-apple-auth/plugin.rb@@ -0,0 +1,60 @@+# frozen_string_literal: true++# name: discourse-apple-auth+# about: Allows users to login using Apple authentication.+# meta_topic_id: 171485+# version: 1.0+# authors: Robert Barrow, David Taylor+# url: https://github.com/discourse/discourse/tree/main/plugins/discourse-apple-auth++require_relative "lib/omniauth_apple"++register_svg_icon "fab-apple"++enabled_site_setting :sign_in_with_apple_enabled++class AppleAuthenticator < ::Auth::ManagedAuthenticator+ def name+ "apple"+ end++ def enabled?+ SiteSetting.sign_in_with_apple_enabled?+ end++ def fetch_jwks(options)+ Discourse+ .cache+ .fetch("sign-in-with-apple-jwks", expires_in: 1.day) do+ connection = Faraday.new { |c| c.use Faraday::Response::RaiseError }+ JSON.parse(+ connection.get("https://appleid.apple.com/auth/keys").body,+ symbolize_names: true,+ )+ end+ rescue Faraday::Error, JSON::ParserError => e+ Rails.logger.error("Unable to fetch sign-in-with-apple-jwks #{e.class} #{e.message}")+ nil+ end++ def register_middleware(omniauth)+ omniauth.provider :apple,+ setup:+ lambda { |env|+ strategy = env["omniauth.strategy"]+ strategy.options[:client_id] = SiteSetting.apple_client_id+ strategy.options[:team_id] = SiteSetting.apple_team_id+ strategy.options[:key_id] = SiteSetting.apple_key_id+ strategy.options[:pem] = SiteSetting.apple_pem+ strategy.options[:jwk_fetcher] = ->(options) { fetch_jwks(options) }+ }+ end++ # apple requires email verification to create an account so we can assume+ # email is verified+ def primary_email_verified?(auth_token)+ true+ end+end++auth_provider icon: "fab-apple", authenticator: AppleAuthenticator.newdiff --git a/plugins/discourse-apple-auth/spec/requests/auth_apple_spec.rb b/plugins/discourse-apple-auth/spec/requests/auth_apple_spec.rbnew file mode 100644index 00000000000..2f222a720a7--- /dev/null+++ b/plugins/discourse-apple-auth/spec/requests/auth_apple_spec.rb@@ -0,0 +1,134 @@+# frozen_string_literal: true++require_relative "../../lib/omniauth_apple"+require "rails_helper"++pem = ::OpenSSL::PKey::EC.generate("prime256v1").to_pem++describe "sign in with apple" do+ let(:jwk) { ::JWT::JWK.new(OpenSSL::PKey::RSA.generate(1024)) }++ before do+ Discourse.cache.delete("sign-in-with-apple-jwks")+ SiteSetting.sign_in_with_apple_enabled = true+ SiteSetting.apple_client_id = "myclientid"+ SiteSetting.apple_team_id = "myteamid"+ SiteSetting.apple_key_id = "mykeyid"+ SiteSetting.apple_pem = pem++ stub_request(:get, "https://appleid.apple.com/auth/keys").to_return(+ body: { keys: [jwk.export] }.to_json,+ )+ end++ let(:user_payload) do+ { email: "[email protected]", name: { firstName: "Disco", lastName: "Bot" } }+ end++ it "starts the flow correctly" do+ post "/auth/apple"+ expect(response.status).to eq(302)+ expect(response.location).to start_with("https://appleid.apple.com/auth/authorize")+ expect(response.location).to include("client_id=myclientid")+ end++ describe "POST callback" do+ # Apple send the callback as a POST, which is incompatible+ # with samesite=lax cookies++ it "redirects to GET" do+ post "/auth/apple/callback", params: { code: "supersecretcode", state: "uniquestate" }+ expect(response.status).to eq(302)+ expect(response.location).to eq(+ "http://test.localhost/auth/apple/callback?code=supersecretcode&state=uniquestate",+ )+ end++ it "includes the user data if present" do+ post "/auth/apple/callback",+ params: {+ code: "supersecretcode",+ state: "uniquestate",+ user: user_payload.to_json,+ }+ expect(response.status).to eq(302)+ expect(response.location).to include("user=%7B")+ end++ it "does not set any cookies" do+ # This cross-site request has no cookies (because they're samesite=lax)+ # By default the session middleware will try and start a new session+ # which would break the existing session+ post "/auth/apple/callback"+ expect(response.status).to eq(302)+ expect(response.headers["Set-Cookie"]).to eq(nil)+ end+ end++ describe "GET callback" do+ before do+ post "/auth/apple"+ expect(response.status).to eq(302)++ # Mock the apple server+ stub_request(:post, "https://appleid.apple.com/auth/token").to_return do |request|+ # https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens+ # https://developer.apple.com/documentation/sign_in_with_apple/tokenresponse++ params = Rack::Utils.parse_nested_query(request.body)++ expect(params["client_id"]).to eq("myclientid")+ expect(params["code"]).to eq("supersecretcode")++ decoded, header = JWT.decode(params["client_secret"], nil, false)+ expect(decoded["iss"]).to eq("myteamid")+ expect(decoded["sub"]).to eq("myclientid")+ expect(header["kid"]).to eq("mykeyid")++ {+ status: 200,+ body: {+ access_token: "wedontusethis",+ expires_in: 10,+ id_token:+ ::JWT.encode(+ {+ iss: "https://appleid.apple.com",+ aud: "myclientid",+ sub: "unique-user-id",+ email: "[email protected]",+ },+ jwk.keypair,+ "RS256",+ { kid: jwk.kid },+ ),+ refresh_token: "wedontusethis",+ token_type: "bearer",+ }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ }+ end+ end++ it "works" do+ # Like an OAuth2 callback, but with some apple-specific stuff per+ # https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_js/incorporating_sign_in_with_apple_into_other_platforms+ get "/auth/apple/callback",+ params: {+ code: "supersecretcode",+ state: session["omniauth.state"],+ id_token: JWT.encode({ email: "wedontusethis" }, nil, "none"),+ user: user_payload.to_json,+ }+ expect(response.status).to eq(302)+ expect(response.location).to eq("http://test.localhost/")++ result = Auth::Result.from_session_data(session[:authentication], user: nil)+ expect(result.email).to eq("[email protected]")+ expect(result.name).to eq("Disco Bot")+ expect(result.extra_data[:uid]).to eq("unique-user-id")+ end+ end+enddiff --git a/plugins/discourse-apple-auth/spec/system/core_features_spec.rb b/plugins/discourse-apple-auth/spec/system/core_features_spec.rbnew file mode 100644index 00000000000..db86db283bd--- /dev/null+++ b/plugins/discourse-apple-auth/spec/system/core_features_spec.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++RSpec.describe "Core features", type: :system do+ before { enable_current_plugin }++ it_behaves_like "having working core features"+enddiff --git a/translator.yml b/translator.ymlindex bf5d7b7041b..11a4a5dedb1 100644--- a/translator.yml+++ b/translator.yml@@ -115,3 +115,10 @@ files:- source_path: plugins/discourse-reactions/config/locales/server.en.ymldestination_path: plugins/discourse-reactions/server.ymllabel: discourse-reactions++ - source_path: plugins/discourse-apple-auth/config/locales/client.en.yml+ destination_path: plugins/apple-auth/client.yml+ label: apple-auth+ - source_path: plugins/discourse-apple-auth/config/locales/server.en.yml+ destination_path: plugins/apple-auth/server.yml+ label: apple-auth