Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Allow changing source repo/branch/key for theme after installation (#38169)

David Taylor0b37b99fdea1
diff --git a/app/controllers/admin/themes_controller.rb b/app/controllers/admin/themes_controller.rb
index 66da2bf5062..1aabb1fb5d1 100644
--- a/app/controllers/admin/themes_controller.rb
+++ b/app/controllers/admin/themes_controller.rb
@@ -363,6 +363,67 @@ class Admin::ThemesController < Admin::AdminController
render_serialized(theme_setting, ThemeObjectsSettingMetadataSerializer, root: false)
end
+ def update_source
+ @theme = Theme.include_relations.find_by(id: params[:id])
+ raise Discourse::InvalidParameters.new(:id) unless @theme
+ raise Discourse::InvalidParameters.new(:remote_theme) unless @theme.remote_theme&.is_git?
+
+ remote_url = params[:remote_url]&.strip
+ raise Discourse::InvalidParameters.new(:remote_url) if remote_url.blank?
+
+ if remote_url.length > MAX_REMOTE_LENGTH
+ error = I18n.t("themes.import_error.not_allowed_theme", { repo: remote_url[0..100] })
+ return render_json_error(error, status: 422)
+ end
+
+ begin
+ guardian.ensure_allowed_theme_repo_import!(remote_url)
+ rescue Discourse::InvalidAccess
+ return(
+ render_json_error I18n.t("themes.import_error.not_allowed_theme", { repo: remote_url }),
+ status: :forbidden
+ )
+ end
+
+ theme_id = @theme.id
+
+ hijack do
+ begin
+ private_key = nil
+ if params[:public_key].present?
+ private_key = Discourse.redis.get("ssh_key_#{params[:public_key]}")
+ return render_json_error I18n.t("themes.import_error.ssh_key_gone") if private_key.blank?
+ end
+
+ theme = Theme.include_relations.find(theme_id)
+ remote_theme = theme.remote_theme
+ original_url = remote_theme.remote_url
+ original_branch = remote_theme.branch
+ original_private_key = remote_theme.private_key
+
+ remote_theme.remote_url = remote_url
+ remote_theme.branch = params[:branch].presence
+ remote_theme.private_key = private_key if private_key.present?
+ remote_theme.local_version = nil
+ remote_theme.remote_version = nil
+ remote_theme.commits_behind = nil
+ remote_theme.save!
+
+ remote_theme.update_from_remote
+
+ log_theme_change(nil, theme.reload)
+ render json: serialize_data(theme, ThemeSerializer), status: :ok
+ rescue RemoteTheme::ImportError, ActiveRecord::RecordInvalid => e
+ remote_theme.update!(
+ remote_url: original_url,
+ branch: original_branch,
+ private_key: original_private_key,
+ )
+ render_json_error e.message
+ end
+ end
+ end
+
private
def ban_in_allowlist_mode!
diff --git a/app/serializers/remote_theme_serializer.rb b/app/serializers/remote_theme_serializer.rb
index 3f7d4e7ef22..45d821f0a87 100644
--- a/app/serializers/remote_theme_serializer.rb
+++ b/app/serializers/remote_theme_serializer.rb
@@ -17,7 +17,12 @@ class RemoteThemeSerializer < ApplicationSerializer
:authors,
:theme_version,
:minimum_discourse_version,
- :maximum_discourse_version
+ :maximum_discourse_version,
+ :has_private_key
+
+ def has_private_key
+ object.private_key.present?
+ end
# ActiveModelSerializer has some pretty nutty logic where it tries to find
# the path here from action dispatch, tell it not to
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index ae4251757ef..fa6a4d72743 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -7598,6 +7598,16 @@ en:
update_success: "%{theme} Update complete"
up_to_date: "Theme is up-to-date, last checked:"
has_overwritten_history: "Current theme version no longer exists because the Git history has been overwritten by a force push."
+ change_source:
+ button: "Change source"
+ title: "Change Theme Source"
+ repository_url: "Repository URL"
+ branch: "Branch (optional)"
+ updating: "Updating theme source…"
+ update: "Update Source"
+ has_existing_key: "This theme has an existing SSH key configured."
+ generate_new_key: "Generate new SSH key"
+ keep_existing_key: "Keep existing SSH key"
add: "Add"
theme_settings: "Custom theme settings"
theme_site_settings: "Settings the theme can override"
diff --git a/config/routes.rb b/config/routes.rb
index 22f9529f319..f516cd2e3ca 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -256,6 +256,7 @@ Discourse::Application.routes.draw do
get "translations/:locale" => "themes#get_translations"
put "setting" => "themes#update_single_setting"
put "site-setting" => "themes#update_theme_site_setting"
+ put "source" => "themes#update_source"
get "objects_setting_metadata/:setting_name" => "themes#objects_setting_metadata"
end
diff --git a/frontend/discourse/admin/components/modal/change-theme-source.gjs b/frontend/discourse/admin/components/modal/change-theme-source.gjs
new file mode 100644
index 00000000000..723d8c2b876
--- /dev/null
+++ b/frontend/discourse/admin/components/modal/change-theme-source.gjs
@@ -0,0 +1,201 @@
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import ConditionalLoadingSection from "discourse/components/conditional-loading-section";
+import CopyButton from "discourse/components/copy-button";
+import DButton from "discourse/components/d-button";
+import DModal from "discourse/components/d-modal";
+import Form from "discourse/components/form";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { i18n } from "discourse-i18n";
+
+export default class ChangeThemeSourceModal extends Component {
+ @tracked publicKey = null;
+ @tracked loading = false;
+ @tracked generateNewKey = false;
+ @tracked remoteUrl = this.args.model.theme.remote_theme?.remote_url || "";
+
+ @cached
+ get data() {
+ return {
+ remoteUrl: this.args.model.theme.remote_theme?.remote_url || "",
+ branch: this.args.model.theme.remote_theme?.branch || "",
+ };
+ }
+
+ get showPublicKey() {
+ return this.remoteUrl?.match?.(/^ssh:\/\/.+@.+$|.+@.+:.+$/);
+ }
+
+ get hasExistingPrivateKey() {
+ return this.args.model.theme.remote_theme?.has_private_key;
+ }
+
+ get showKeySection() {
+ return (
+ this.showPublicKey && (this.generateNewKey || !this.hasExistingPrivateKey)
+ );
+ }
+
+ @action
+ onRemoteUrlChange(value) {
+ this.remoteUrl = value;
+ }
+
+ @action
+ async generatePublicKey() {
+ try {
+ const pair = await ajax("/admin/themes/generate_key_pair", {
+ type: "POST",
+ });
+ this.publicKey = pair.public_key;
+ } catch (err) {
+ popupAjaxError(err);
+ }
+ }
+
+ @action
+ toggleGenerateNewKey() {
+ this.generateNewKey = !this.generateNewKey;
+ if (!this.generateNewKey) {
+ this.publicKey = null;
+ }
+ }
+
+ @action
+ registerApi(api) {
+ this.formApi = api;
+ }
+
+ @action
+ async onFormSubmit(data) {
+ this.loading = true;
+ try {
+ const requestData = {
+ remote_url: data.remoteUrl,
+ branch: data.branch || null,
+ };
+
+ if (this.publicKey) {
+ requestData.public_key = this.publicKey;
+ }
+
+ const result = await ajax(
+ `/admin/themes/${this.args.model.theme.id}/source`,
+ {
+ type: "PUT",
+ data: requestData,
+ }
+ );
+
+ this.args.model.onSuccess?.(result.theme);
+ this.args.closeModal();
+ } catch (err) {
+ popupAjaxError(err);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ <template>
+ <DModal
+ @bodyClass="change-theme-source"
+ class="admin-change-theme-source-modal"
+ @title={{i18n "admin.customize.theme.change_source.title"}}
+ @closeModal={{@closeModal}}
+ >
+ <:body>
+ <ConditionalLoadingSection
+ @isLoading={{this.loading}}
+ @title={{i18n "admin.customize.theme.change_source.updating"}}
+ >
+ <Form
+ @data={{this.data}}
+ @onSubmit={{this.onFormSubmit}}
+ @onRegisterApi={{this.registerApi}}
+ as |form|
+ >
+ <form.Field
+ @name="remoteUrl"
+ @type="input"
+ @title={{i18n
+ "admin.customize.theme.change_source.repository_url"
+ }}
+ @format="full"
+ @validation="required"
+ @onSet={{this.onRemoteUrlChange}}
+ as |field|
+ >
+ <field.Control
+ placeholder="https://github.com/user/repo.git"
+ class="repo-url"
+ />
+ </form.Field>
+
+ <form.Field
+ @name="branch"
+ @type="input"
+ @title={{i18n "admin.customize.theme.change_source.branch"}}
+ @format="full"
+ as |field|
+ >
+ <field.Control placeholder="main" class="branch" />
+ </form.Field>
+
+ {{#if this.showPublicKey}}
+ <div class="ssh-key-section">
+ {{#if this.hasExistingPrivateKey}}
+ <div class="existing-key-notice">
+ {{i18n
+ "admin.customize.theme.change_source.has_existing_key"
+ }}
+ </div>
+ <DButton
+ @action={{this.toggleGenerateNewKey}}
+ @label={{if
+ this.generateNewKey
+ "admin.customize.theme.change_source.keep_existing_key"
+ "admin.customize.theme.change_source.generate_new_key"
+ }}
+ class="btn-default"
+ />
+ {{/if}}
+
+ {{#if this.showKeySection}}
+ <div class="public-key">
+ <div class="label">
+ {{i18n "admin.customize.theme.public_key"}}
+ </div>
+ <div class="public-key-text-wrapper">
+ <textarea
+ class="public-key-value"
+ readonly="true"
+ {{didInsert this.generatePublicKey}}
+ >{{this.publicKey}}</textarea>
+ <CopyButton @selector="textarea.public-key-value" />
+ </div>
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+ </Form>
+ </ConditionalLoadingSection>
+ </:body>
+ <:footer>
+ <DButton
+ @action={{this.formApi.submit}}
+ @disabled={{this.loading}}
+ class="btn-primary"
+ @label="admin.customize.theme.change_source.update"
+ />
+ <DButton
+ class="btn-flat d-modal-cancel"
+ @action={{@closeModal}}
+ @label="cancel"
+ />
+ </:footer>
+ </DModal>
+ </template>
+}
diff --git a/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js b/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js
index db9b73e2377..25a28d8623b 100644
--- a/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js
+++ b/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js
@@ -8,6 +8,7 @@ import {
readOnly,
} from "@ember/object/computed";
import { service } from "@ember/service";
+import ChangeThemeSourceModal from "discourse/admin/components/modal/change-theme-source";
import ThemeSettingsEditor from "discourse/admin/components/theme-settings-editor";
import SiteSetting from "discourse/admin/models/site-setting";
import { COMPONENTS, THEMES } from "discourse/admin/models/theme";
@@ -314,6 +315,18 @@ export default class AdminCustomizeThemesShowIndexController extends Controller
});
}
+ @action
+ changeSource() {
+ this.modal.show(ChangeThemeSourceModal, {
+ model: {
+ theme: this.model,
+ onSuccess: () => {
+ this.send("routeRefreshModel");
+ },
+ },
+ });
+ }
+
@action
addUploadModal() {
this.modal.show(ThemeUploadAddModal, {
diff --git a/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs b/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs
index e6ed5251959..14dab8ae192 100644
--- a/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs
+++ b/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs
@@ -41,6 +41,13 @@ export default <template>
/>
{{/if}}
+ <DButton
+ @action={{@controller.changeSource}}
+ @icon="code-branch"
+ @label="admin.customize.theme.change_source.button"
+ class="btn-default"
+ />
+
<span class="status-message">
{{#if @controller.updatingRemote}}
{{i18n "admin.customize.theme.updating"}}
diff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rb
index 7d519e28701..e1adf31fcfc 100644
--- a/lib/svg_sprite.rb
+++ b/lib/svg_sprite.rb
@@ -71,6 +71,7 @@ module SvgSprite
cloud-arrow-down
cloud-arrow-up
code
+ code-branch
comment
compress
copy
diff --git a/spec/requests/admin/themes_controller_spec.rb b/spec/requests/admin/themes_controller_spec.rb
index efad8681d1b..3a125f86ae4 100644
--- a/spec/requests/admin/themes_controller_spec.rb
+++ b/spec/requests/admin/themes_controller_spec.rb
@@ -1685,6 +1685,158 @@ RSpec.describe Admin::ThemesController do
end
end
+ describe "#update_source" do
+ fab!(:theme)
+
+ let!(:other_repo) { setup_git_repo("about.json" => { name: "other-theme" }.to_json) }
+
+ let!(:other_repo_url) do
+ MockGitImporter.register("https://github.com/discourse/other-theme.git", other_repo)
+ end
+
+ context "when logged in as an admin" do
+ before { sign_in(admin) }
+
+ it "updates the remote theme source" do
+ theme.remote_theme =
+ RemoteTheme.create!(remote_url: repo_url, branch: "main", local_version: "abc")
+ theme.save!
+
+ put "/admin/themes/#{theme.id}/source.json",
+ params: {
+ remote_url: other_repo_url,
+ branch: "develop",
+ }
+
+ expect(response.status).to eq(200)
+ theme.reload
+ expect(theme.remote_theme.remote_url).to eq(other_repo_url)
+ expect(theme.remote_theme.branch).to eq("develop")
+ end
+
+ it "returns error for non-git theme" do
+ put "/admin/themes/#{theme.id}/source.json", params: { remote_url: other_repo_url }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "returns error for zip-imported theme" do
+ theme.remote_theme = RemoteTheme.create!(remote_url: "")
+ theme.save!
+
+ put "/admin/themes/#{theme.id}/source.json", params: { remote_url: other_repo_url }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "returns error for missing remote_url" do
+ theme.remote_theme = RemoteTheme.create!(remote_url: repo_url)
+ theme.save!
+
+ put "/admin/themes/#{theme.id}/source.json", params: { remote_url: "" }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "returns error for disallowed repo when allowlist is configured" do
+ global_setting :allowed_theme_repos, repo_url
+ theme.remote_theme = RemoteTheme.create!(remote_url: repo_url)
+ theme.save!
+
+ put "/admin/themes/#{theme.id}/source.json",
+ params: {
+ remote_url: "https://github.com/not-allowed/theme.git",
+ }
+
+ expect(response.status).to eq(403)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t(
+ "themes.import_error.not_allowed_theme",
+ { repo: "https://github.com/not-allowed/theme.git" },
+ ),
+ )
+ end
+
+ it "can use SSH key from Redis" do
+ theme.remote_theme = RemoteTheme.create!(remote_url: repo_url, local_version: "abc")
+ theme.save!
+ Discourse.redis.setex("ssh_key_test_public_key", 1.hour, "test_private_key")
+
+ put "/admin/themes/#{theme.id}/source.json",
+ params: {
+ remote_url: other_repo_url,
+ public_key: "test_public_key",
+ }
+
+ expect(response.status).to eq(200)
+ expect(theme.reload.remote_theme.private_key).to eq("test_private_key")
+ end
+
+ it "returns error when SSH key has expired" do
+ theme.remote_theme = RemoteTheme.create!(remote_url: repo_url)
+ theme.save!
+
+ put "/admin/themes/#{theme.id}/source.json",
+ params: {
+ remote_url: other_repo_url,
+ public_key: "expired_key",
+ }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("themes.import_error.ssh_key_gone"),
+ )
+ end
+
+ it "reverts changes on import failure" do
+ theme.remote_theme =
+ RemoteTheme.create!(remote_url: repo_url, branch: "main", private_key: "old_key")
+ theme.save!
+
+ RemoteTheme
+ .any_instance
+ .stubs(:update_from_remote)
+ .raises(RemoteTheme::ImportError.new("error message"))
+
+ put "/admin/themes/#{theme.id}/source.json",
+ params: {
+ remote_url: other_repo_url,
+ branch: "develop",
+ }
+
+ expect(response.status).to eq(422)
+ theme.reload
+ expect(theme.remote_theme.remote_url).to eq(repo_url)
+ expect(theme.remote_theme.branch).to eq("main")
+ expect(theme.remote_theme.private_key).to eq("old_key")
+ end
+ end
+
+ shared_examples "source update not allowed" do
+ it "prevents source update with a 404 response" do
+ theme.remote_theme = RemoteTheme.create!(remote_url: repo_url)
+ theme.save!
+
+ put "/admin/themes/#{theme.id}/source.json", params: { remote_url: other_repo_url }
+
+ expect(response.status).to eq(404)
+ expect(response.parsed_body["errors"]).to include(I18n.t("not_found"))
+ end
+ end
+
+ context "when logged in as a moderator" do
+ before { sign_in(moderator) }
+
+ include_examples "source update not allowed"
+ end
+
+ context "when logged in as a non-staff user" do
+ before { sign_in(user) }
+
+ include_examples "source update not allowed"
+ end
+ end
+
describe "#show" do
let(:theme) { Fabricate(:theme) }
diff --git a/spec/system/admin_customize_themes_spec.rb b/spec/system/admin_customize_themes_spec.rb
index 14217794468..fd73dc2c9f6 100644
--- a/spec/system/admin_customize_themes_spec.rb
+++ b/spec/system/admin_customize_themes_spec.rb
@@ -290,6 +290,43 @@ describe "Admin Customize Themes" do
end
end
+ describe "changing theme source" do
+ fab!(:git_theme) do
+ theme = Fabricate(:theme, name: "Git Theme")
+ theme.remote_theme =
+ RemoteTheme.create!(
+ remote_url: "https://github.com/discourse/example-theme.git",
+ branch: "main",
+ local_version: "abc123",
+ remote_version: "abc123",
+ commits_behind: 0,
+ )
+ theme.save!
+ theme
+ end
+
+ it "shows the change source button for git themes" do
+ theme_page.visit(git_theme)
+ expect(page).to have_button(I18n.t("admin_js.admin.customize.theme.change_source.button"))
+ end
+
+ it "opens the change source modal with pre-filled values" do
+ theme_page.visit(git_theme)
+ find("button", text: I18n.t("admin_js.admin.customize.theme.change_source.button")).click
+
+ expect(page).to have_css(".admin-change-theme-source-modal")
+ expect(find(".admin-change-theme-source-modal input.repo-url").value).to eq(
+ "https://github.com/discourse/example-theme.git",
+ )
+ expect(find(".admin-change-theme-source-modal input.branch").value).to eq("main")
+ end
+
+ it "does not show the change source button for local themes" do
+ theme_page.visit(theme)
+ expect(page).to have_no_button(I18n.t("admin_js.admin.customize.theme.change_source.button"))
+ end
+ end
+
describe "editing theme site settings" do
it "shows all themeable site settings and allows editing values" do
theme_page.visit(theme.id)