repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/setup_spec.rb
match/spec/setup_spec.rb
describe Match do describe Match::Setup do it "creates a new Matchfile, containing the git_url" do git_url = "https://github.com/fastlane/fastlane/tree/master/certificates" expect(FastlaneCore::UI.ui_object).to receive(:select).and_return("git") expect(FastlaneCore::UI.ui_object).to receive(:input).and_return(git_url) path = File.join(Dir.mktmpdir, "Matchfile") Match::Setup.new.run(path) content = File.read(path) expect(content).to include("git_url(\"#{git_url}\")") expect(content).to include("type(\"development\")") expect(content).to include("match --help") end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/profile_includes_spec.rb
match/spec/profile_includes_spec.rb
describe Match do describe Match::ProfileIncludes do describe "counts" do let(:portal_profile) { double("profile") } let(:profile_device) { double("profile_device") } let(:profile_certificate) { double("profile_certificate") } before do allow(portal_profile).to receive(:devices).and_return([profile_device]) allow(portal_profile).to receive(:certificates).and_return([profile_certificate]) allow(profile_device).to receive(:id).and_return(1) allow(profile_certificate).to receive(:id).and_return(1) end describe "#devices_differ?" do it "returns false if devices are the same" do # WHEN devices_differ = Match::ProfileIncludes.devices_differ?(portal_profile: portal_profile, platform: 'ios', include_mac_in_profiles: true, cached_devices: [profile_device]) # THEN expect(devices_differ).to be(false) end it "returns true if devices differ even when the count is the same" do # GIVEN portal_device = double("profile_device") allow(portal_device).to receive(:id).and_return(2) # WHEN devices_differ = Match::ProfileIncludes.devices_differ?(portal_profile: portal_profile, platform: 'ios', include_mac_in_profiles: true, cached_devices: [portal_device]) # THEN expect(devices_differ).to be(true) end it "returns true if devices differ" do # GIVEN portal_device = double("profile_device") allow(portal_device).to receive(:id).and_return(2) # WHEN devices_differ = Match::ProfileIncludes.devices_differ?(portal_profile: portal_profile, platform: 'ios', include_mac_in_profiles: true, cached_devices: [portal_device, profile_device]) # THEN expect(devices_differ).to be(true) end end describe "#certificates_differ?" do it "returns false if certificates are the same" do # WHEN certificates_differ = Match::ProfileIncludes.certificates_differ?(portal_profile: portal_profile, platform: 'ios', cached_certificates: [profile_certificate]) # THEN expect(certificates_differ).to be(false) end it "returns true if certs differ even when the count is the same" do # GIVEN portal_cert = double("profile_device") allow(portal_cert).to receive(:id).and_return(2) # WHEN certificates_differ = Match::ProfileIncludes.certificates_differ?(portal_profile: portal_profile, platform: 'ios', cached_certificates: [portal_cert]) # THEN expect(certificates_differ).to be(true) end it "returns true if certs differ" do # GIVEN portal_cert = double("profile_device") allow(portal_cert).to receive(:id).and_return(2) # WHEN certificates_differ = Match::ProfileIncludes.certificates_differ?(portal_profile: portal_profile, platform: 'ios', cached_certificates: [profile_certificate, portal_cert]) # THEN expect(certificates_differ).to be(true) end end end describe "can's" do let(:params) { double("params") } before do allow(params).to receive(:[]).with(:type).and_return('development') allow(params).to receive(:[]).with(:readonly).and_return(false) allow(params).to receive(:[]).with(:force).and_return(false) allow(params).to receive(:[]).with(:force_for_new_devices).and_return(true) allow(params).to receive(:[]).with(:force_for_new_certificates).and_return(true) allow(params).to receive(:[]).with(:include_all_certificates).and_return(true) end describe "#can_force_include_all_devices?" do it "returns true if params ok" do # WHEN can_include_devices = Match::ProfileIncludes.can_force_include_all_devices?(params: params) # THEN expect(can_include_devices).to be(true) end it "returns false if readonly" do # GIVEN allow(params).to receive(:[]).with(:readonly).and_return(true) # WHEN can_include_devices = Match::ProfileIncludes.can_force_include_all_devices?(params: params) # THEN expect(can_include_devices).to be(false) end it "returns false if no force_for_new_devices" do # GIVEN allow(params).to receive(:[]).with(:force_for_new_devices).and_return(false) # WHEN can_include_devices = Match::ProfileIncludes.can_force_include_all_devices?(params: params) # THEN expect(can_include_devices).to be(false) end it "returns false if type is unsuitable" do # GIVEN allow(params).to receive(:[]).with(:type).and_return('appstore') # WHEN can_include_devices = Match::ProfileIncludes.can_force_include_all_devices?(params: params) # THEN expect(can_include_devices).to be(false) end end describe "#can_force_include_all_certificates?" do it "returns true if params ok" do # WHEN can_include_certs = Match::ProfileIncludes.can_force_include_all_certificates?(params: params) # THEN expect(can_include_certs).to be(true) end it "returns false if readonly" do # GIVEN allow(params).to receive(:[]).with(:readonly).and_return(true) # WHEN can_include_certs = Match::ProfileIncludes.can_force_include_all_certificates?(params: params) # THEN expect(can_include_certs).to be(false) end it "returns false if no force_for_new_devices" do # GIVEN allow(params).to receive(:[]).with(:force_for_new_certificates).and_return(false) # WHEN can_include_certs = Match::ProfileIncludes.can_force_include_all_certificates?(params: params) # THEN expect(can_include_certs).to be(false) end it "returns false if no include_all_certificates" do # GIVEN allow(params).to receive(:[]).with(:include_all_certificates).and_return(false) # WHEN can_include_certs = Match::ProfileIncludes.can_force_include_all_certificates?(params: params) # THEN expect(can_include_certs).to be(false) end it "returns false if type is unsuitable" do # GIVEN allow(params).to receive(:[]).with(:type).and_return('appstore') # WHEN can_include_certs = Match::ProfileIncludes.can_force_include_all_certificates?(params: params) # THEN expect(can_include_certs).to be(false) end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/commands_generator_spec.rb
match/spec/commands_generator_spec.rb
require 'match/commands_generator' describe Match::CommandsGenerator do let(:available_options) { Match::Options.available_options } def expect_runner_run_with(expected_options) fake_runner = "runner" expect(Match::Runner).to receive(:new).and_return(fake_runner) expect(fake_runner).to receive(:run) do |actual_options| expect(expected_options._values).to eq(actual_options._values) end end Match.environments.each do |env| describe ":#{env} option handling" do it "can use the git_url short flag from tool options" do stub_commander_runner_args([env, '-r', 'git@github.com:you/your_repo.git']) expected_options = FastlaneCore::Configuration.create(available_options, { git_url: 'git@github.com:you/your_repo.git', type: env }) expect_runner_run_with(expected_options) Match::CommandsGenerator.start end it "can use the git_branch flag from tool options" do stub_commander_runner_args([env, '--git_branch', 'my-branch']) expected_options = FastlaneCore::Configuration.create(available_options, { git_branch: 'my-branch', type: env }) expect_runner_run_with(expected_options) Match::CommandsGenerator.start end end end describe ":change_password option handling" do def expect_change_password_with(expected_options) expect(Match::ChangePassword).to receive(:update) do |args| expect(args[:params]._values).to eq(expected_options._values) end expect(FastlaneCore::UI).to receive(:success).with(/Successfully changed the password./) end it "can use the git_url short flag from tool options" do stub_commander_runner_args(['change_password', '-r', 'git@github.com:you/your_repo.git']) expected_options = FastlaneCore::Configuration.create(available_options, { git_url: 'git@github.com:you/your_repo.git' }) expect_change_password_with(expected_options) Match::CommandsGenerator.start end it "can use the shallow_clone flag from tool options" do stub_commander_runner_args(['change_password', '--shallow_clone', 'true']) expected_options = FastlaneCore::Configuration.create(available_options, { shallow_clone: true }) expect_change_password_with(expected_options) Match::CommandsGenerator.start end end describe ":decrypt option handling" do def expect_githelper_clone_with(git_url, shallow_clone, git_branch) fake_storage = "fake_storage" fake_working_directory = "fake_working_directory" fake_encryption = "fake_encryption" expect(Match::Storage::GitStorage).to receive(:configure).with({ git_url: git_url, shallow_clone: shallow_clone, skip_docs: false, git_branch: git_branch[:branch], clone_branch_directly: git_branch[:clone_branch_directly], git_full_name: nil, git_user_email: nil, git_private_key: nil, git_basic_authorization: nil, git_bearer_authorization: nil, type: "development", platform: "ios" }).and_return(fake_storage) expect(fake_storage).to receive(:download) allow(fake_storage).to receive(:working_directory).and_return(fake_working_directory) allow(fake_storage).to receive(:keychain_name).and_return("https://github.com/fastlane/certs") expect(Match::Encryption).to receive(:for_storage_mode).with("git", { git_url: git_url, s3_bucket: nil, s3_skip_encryption: false, working_directory: fake_working_directory }).and_return(fake_encryption) expect(fake_encryption).to receive(:decrypt_files) expect(FastlaneCore::UI).to receive(:success).with("Repo is at: '#{fake_working_directory}'") end it "can use the git_url short flag from tool options" do stub_const('ENV', { 'MATCH_PASSWORD' => '' }) stub_commander_runner_args(['decrypt', '-r', 'git@github.com:you/your_repo.git']) expect_githelper_clone_with('git@github.com:you/your_repo.git', false, { branch: 'master', clone_branch_directly: false }) Match::CommandsGenerator.start end it "can use the shallow_clone flag from tool options" do stub_const('ENV', { 'MATCH_PASSWORD' => '' }) stub_commander_runner_args(['decrypt', '-r', 'git@github.com:you/your_repo.git', '--shallow_clone', 'true']) expect_githelper_clone_with('git@github.com:you/your_repo.git', true, { branch: 'master', clone_branch_directly: false }) Match::CommandsGenerator.start end end describe ":import option handling" do let(:fake_match_importer) { double("fake match_importer") } before(:each) do allow(Match::Importer).to receive(:new).and_return(fake_match_importer) end def expect_import_with(expected_options) expect(fake_match_importer).to receive(:import_cert) do |actual_options| expect(actual_options._values).to eq(expected_options._values) end end it "can use the git_url short flag from tool options" do stub_commander_runner_args(['import', '-r', 'git@github.com:you/your_repo.git']) expected_options = FastlaneCore::Configuration.create(available_options, { git_url: 'git@github.com:you/your_repo.git' }) expect_import_with(expected_options) Match::CommandsGenerator.start end end def expect_nuke_run_with(expected_options, type) fake_nuke = "nuke" expect(Match::Nuke).to receive(:new).and_return(fake_nuke) expect(fake_nuke).to receive(:run) do |actual_options, args| expect(actual_options._values).to eq(expected_options._values) expect(args[:type]).to eq(type) end end ["development", "distribution"].each do |type| describe "nuke #{type} option handling" do it "can use the git_url short flag from tool options" do stub_commander_runner_args(['nuke', type, '-r', 'git@github.com:you/your_repo.git']) expected_options = FastlaneCore::Configuration.create(available_options, { git_url: 'git@github.com:you/your_repo.git' }) expect_nuke_run_with(expected_options, type) Match::CommandsGenerator.start end it "can use the git_branch flag from tool options" do # leaving out the command name defaults to 'run' stub_commander_runner_args(['nuke', type, '--git_branch', 'my-branch']) expected_options = FastlaneCore::Configuration.create(available_options, { git_branch: 'my-branch' }) expect_nuke_run_with(expected_options, type) Match::CommandsGenerator.start end end end # :init is not tested here because it does not use any tool options end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/encryption_spec.rb
match/spec/encryption_spec.rb
describe Match::Encryption do describe "for_storage_mode" do it "returns nil if storage mode is google_cloud" do storage_mode = "google_cloud" encryption = Match::Encryption.for_storage_mode(storage_mode, { git_url: "", s3_bucket: "", s3_skip_encryption: false, working_directory: "" }) expect(encryption).to be_nil end it "returns nil if storage mode is gitlab_secure_files" do storage_mode = "gitlab_secure_files" encryption = Match::Encryption.for_storage_mode(storage_mode, { git_url: "", s3_bucket: "", s3_skip_encryption: false, working_directory: "" }) expect(encryption).to be_nil end it "returns nil if storage mode is s3 and skip encryption is true" do storage_mode = "s3" encryption = Match::Encryption.for_storage_mode(storage_mode, { git_url: "", s3_bucket: "my-bucket", s3_skip_encryption: true, working_directory: "" }) expect(encryption).to be_nil end it "should return OpenSSL object for storage mode git" do storage_mode = "git" git_url = "git@github.com:you/your_repo.git" working_directory = "my-working-directory" encryption = Match::Encryption.for_storage_mode(storage_mode, { git_url: git_url, s3_bucket: "", s3_skip_encryption: false, working_directory: working_directory }) expect(encryption).to_not(be_nil) expect(encryption).to be_kind_of(Match::Encryption::OpenSSL) expect(encryption.keychain_name).to be(git_url) expect(encryption.working_directory).to be(working_directory) end it "should return OpenSSL object for storage mode s3 and skip encryption is false" do storage_mode = "s3" s3_bucket = "my-bucket" working_directory = "my-working-directory" encryption = Match::Encryption.for_storage_mode(storage_mode, { git_url: "", s3_bucket: s3_bucket, s3_skip_encryption: false, working_directory: working_directory }) expect(encryption).to_not(be_nil) expect(encryption).to be_kind_of(Match::Encryption::OpenSSL) expect(encryption.keychain_name).to be(s3_bucket) expect(encryption.working_directory).to be(working_directory) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/migrate_spec.rb
match/spec/migrate_spec.rb
describe Match do describe Match::Migrate do before do stub_const('ENV', { "MATCH_PASSWORD" => '2"QAHg@v(Qp{=*n^' }) end it "deletes decrypted files at the end", requires_security: true do git_url = "https://github.com/fastlane/fastlane/tree/master/certificates" values = { app_identifier: "tools.fastlane.app", type: "appstore", git_url: git_url, shallow_clone: true, username: "flapple@something.com" } config = FastlaneCore::Configuration.create(Match::Options.available_options, values) repo_dir = Dir.mktmpdir fake_google_cloud_storage = "fake_google_cloud_storage" expect(Match::Storage::GoogleCloudStorage).to receive(:configure).with({ type: nil, platform: nil, google_cloud_bucket_name: nil, google_cloud_keys_file: nil, google_cloud_project_id: nil, readonly: nil, username: nil, team_id: nil, team_name: nil, api_key_path: nil, api_key: nil, skip_google_cloud_account_confirmation: nil }).and_return(fake_google_cloud_storage) allow(fake_google_cloud_storage).to receive(:download) allow(fake_google_cloud_storage).to receive(:save_changes!) allow(fake_google_cloud_storage).to receive(:bucket_name).and_return("") fake_git_storage = "fake_git_storage" expect(Match::Storage::GitStorage).to receive(:configure).with({ type: nil, platform: nil, git_url: git_url, shallow_clone: true, skip_docs: nil, git_branch: "master", git_full_name: nil, git_user_email: nil, clone_branch_directly: false, git_basic_authorization: nil, git_bearer_authorization: nil, git_private_key: nil }).and_return(fake_git_storage) allow(fake_git_storage).to receive(:download) allow(fake_git_storage).to receive(:working_directory).and_return(repo_dir) spaceship = "spaceship" allow(spaceship).to receive(:team_id).and_return("team_id") allow(Match::SpaceshipEnsure).to receive(:new).and_return(spaceship) allow(UI).to receive(:input) expect(fake_google_cloud_storage).to receive(:clear_changes) expect(fake_git_storage).to receive(:clear_changes) Match::Migrate.new.migrate(config) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/portal_fetcher_spec.rb
match/spec/portal_fetcher_spec.rb
require 'spaceship/client' describe Match do describe Match::Portal::Fetcher do let(:default_sut) { Match::Portal::Fetcher } let(:portal_bundle_id) { double("portal_bundle_id") } let(:portal_device) { double("portal_device") } let(:portal_certificate) { double("portal_certificate") } let(:portal_profile) { double("portal_profile") } let(:portal_profile_udid) { double("portal_profile_udid") } let(:deviceClass) { Spaceship::ConnectAPI::Device::DeviceClass } let(:deviceStatus) { Spaceship::ConnectAPI::Device::Status } let(:certificateType) { Spaceship::ConnectAPI::Certificate::CertificateType } let(:profileState) { Spaceship::ConnectAPI::Profile::ProfileState } let(:default_device_all_params) do { filter: { platform: 'IOS', status: 'ENABLED' }, client: nil } end let(:default_certificates_all_params) do { filter: { certificateType: anything } } end let(:default_profile_all_params) do { filter: { profileType: anything }, includes: 'bundleId,devices,certificates' } end let(:default_bundle_id_all_params) do { filter: { identifier: anything } } end before do allow(portal_device).to receive(:device_class).and_return(deviceClass::IPHONE) allow(portal_device).to receive(:enabled?).and_return(true) allow(portal_certificate).to receive(:valid?).and_return(true) allow(portal_profile).to receive(:uuid).and_return(portal_profile_udid) allow(portal_profile).to receive(:profile_state).and_return(profileState::ACTIVE) allow(portal_profile).to receive(:devices).and_return([portal_device]) allow(portal_profile).to receive(:certificates).and_return([portal_certificate]) end before do allow(Spaceship::ConnectAPI::Device).to receive(:all).with(default_device_all_params).and_return([portal_device]) allow(Spaceship::ConnectAPI::Certificate).to receive(:all).with(default_certificates_all_params).and_return([portal_certificate]) allow(Spaceship::ConnectAPI::Profile).to receive(:all).with(default_profile_all_params).and_return([portal_profile]) allow(Spaceship::ConnectAPI::BundleId).to receive(:all).with(default_bundle_id_all_params).and_return([portal_bundle_id]) end describe "certificates" do it "fetches certificates" do # GIVEN sut = default_sut # WHEN portal_certificates = sut.certificates(platform: 'ios', profile_type: 'development', additional_cert_types: nil) # THEN expect(portal_certificates).to eq([portal_certificate]) end end describe "devices" do it "fetches devices" do # GIVEN sut = default_sut # WHEN portal_devices = sut.devices(platform: 'ios') # THEN expect(portal_devices).to eq([portal_device]) end end describe "bundle ids" do it "fetches bundle ids" do # GIVEN sut = default_sut # WHEN portal_bundle_ids = sut.bundle_ids(bundle_id_identifiers: ['bundle_id']) # THEN expect(portal_bundle_ids).to eq([portal_bundle_id]) end end describe "profiles" do it "fetches profiles" do # GIVEN sut = default_sut # WHEN portal_profiles = sut.profiles(profile_type: 'profile_type', needs_profiles_devices: true, needs_profiles_certificate_content: false, name: nil) # THEN expect(portal_profiles).to eq([portal_profile]) end it "fetches profiles with name" do # GIVEN sut = default_sut profile_params = default_profile_all_params profile_name = 'profile name' profile_params[:filter][:name] = profile_name allow(Spaceship::ConnectAPI::Profile).to receive(:all).with(profile_params).and_return([portal_profile]) # WHEN portal_profiles = sut.profiles(profile_type: 'profile_type', needs_profiles_devices: true, needs_profiles_certificate_content: false, name: profile_name) # THEN expect(portal_profiles).to eq([portal_profile]) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/nuke_spec.rb
match/spec/nuke_spec.rb
describe Match do describe Match::Nuke do before do allow(Spaceship::ConnectAPI).to receive(:login).and_return(nil) allow(Spaceship::ConnectAPI).to receive(:client).and_return("client") allow(Spaceship::ConnectAPI.client).to receive(:in_house?).and_return(false) allow(Spaceship::ConnectAPI.client).to receive(:portal_team_id).and_return(nil) stub_const('ENV', { "MATCH_PASSWORD" => '2"QAHg@v(Qp{=*n^' }) end it "deletes decrypted files at the end", requires_security: true do git_url = "https://github.com/fastlane/fastlane/tree/master/certificates" values = { app_identifier: "tools.fastlane.app", type: "appstore", git_url: git_url, shallow_clone: true, username: "flapple@something.com" } config = FastlaneCore::Configuration.create(Match::Options.available_options, values) repo_dir = Dir.mktmpdir fake_storage = "fake_storage" expect(Match::Storage::GitStorage).to receive(:configure).with({ git_url: git_url, shallow_clone: true, skip_docs: false, git_branch: "master", git_full_name: nil, git_user_email: nil, git_private_key: nil, git_basic_authorization: nil, git_bearer_authorization: nil, clone_branch_directly: false, type: config[:type], platform: config[:platform] }).and_return(fake_storage) allow(fake_storage).to receive(:download) allow(fake_storage).to receive(:working_directory).and_return(repo_dir) nuke = Match::Nuke.new allow(nuke).to receive(:prepare_list) allow(nuke).to receive(:filter_by_cert) allow(nuke).to receive(:print_tables) allow(nuke).to receive(:certs).and_return([]) allow(nuke).to receive(:profiles).and_return([]) allow(nuke).to receive(:files).and_return([]) expect(fake_storage).to receive(:clear_changes) nuke.run(config, type: config[:type]) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/module_spec.rb
match/spec/module_spec.rb
describe Match do context "#profile_types" do it "profile types for appstore" do profiles = Match.profile_types("appstore") expect(profiles).to eq([ Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_STORE, Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_STORE, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_STORE, Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_STORE ]) end it "profile types for development" do profiles = Match.profile_types("development") expect(profiles).to eq([ Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_DEVELOPMENT, Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DEVELOPMENT, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_DEVELOPMENT, Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DEVELOPMENT ]) end it "profile types for enterprise with Apple ID auth" do profiles = Match.profile_types("enterprise") expect(profiles).to eq([ Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE, Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE, Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE ]) end it "profile types for enterprise with API Key auth" do token = double("mock_token") allow(Spaceship::ConnectAPI).to receive(:token).and_return(token) profiles = Match.profile_types("enterprise") expect(profiles).to eq([ Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE ]) end it "profile types for adhoc" do profiles = Match.profile_types("adhoc") expect(profiles).to eq([ Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_ADHOC, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_ADHOC ]) end it "profile types for developer_id" do profiles = Match.profile_types("developer_id") expect(profiles).to eq([ Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DIRECT, Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DIRECT ]) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/portal_cache_spec.rb
match/spec/portal_cache_spec.rb
require 'spaceship/client' describe Match do describe Match::Portal::Cache do let(:default_params) do { platform: 'ios', type: 'development', additional_cert_types: nil, readonly: false, force: false, include_mac_in_profiles: true, force_for_new_devices: true, include_all_certificates: true, force_for_new_certificates: true } end let(:bundle_ids) { ['bundle_ID_1', 'bundle_ID_2'] } let(:default_sut) do Match::Portal::Cache.build(params: default_params, bundle_id_identifiers: bundle_ids) end describe "init" do it "builds correctly with params" do params = default_params bundle_ids = ['bundleID'] cache = Match::Portal::Cache.build(params: params, bundle_id_identifiers: bundle_ids) expect(cache.bundle_id_identifiers).to eq(bundle_ids) expect(cache.platform).to eq(params[:platform]) expect(cache.profile_type).to eq('IOS_APP_DEVELOPMENT') expect(cache.additional_cert_types).to eq(params[:additional_cert_types]) expect(cache.needs_profiles_devices).to eq(true) expect(cache.needs_profiles_certificate_content).to eq(false) expect(cache.include_mac_in_profiles).to eq(params[:include_mac_in_profiles]) end end describe "bundle_ids" do it 'caches bundle ids' do # GIVEN sut = default_sut allow(Match::Portal::Fetcher).to receive(:bundle_ids).with(bundle_id_identifiers: ['bundle_ID_1', 'bundle_ID_2']).and_return(['portal_bundle_id']).once # WHEN bundle_ids = sut.bundle_ids # THEN expect(bundle_ids).to eq(['portal_bundle_id']) # THEN used cached expect(sut.bundle_ids).to eq(['portal_bundle_id']) end end describe "devices" do it 'caches devices' do # GIVEN sut = default_sut allow(Match::Portal::Fetcher).to receive(:devices).with(include_mac_in_profiles: sut.include_mac_in_profiles, platform: sut.platform).and_return(['portal_device']).once # WHEN devices = sut.devices # THEN expect(devices).to eq(['portal_device']) # THEN used cached expect(sut.devices).to eq(['portal_device']) end end describe "devices" do it 'caches profiles' do # GIVEN sut = default_sut allow(Match::Portal::Fetcher).to receive(:profiles).with(needs_profiles_certificate_content: sut.needs_profiles_certificate_content, needs_profiles_devices: sut.needs_profiles_devices, profile_type: sut.profile_type).and_return(['portal_profile_1']).once # WHEN profiles = sut.profiles # THEN expect(profiles).to eq(['portal_profile_1']) # THEN used cached expect(sut.profiles).to eq(['portal_profile_1']) end it 'removes profile' do # GIVEN sut = default_sut allow(Match::Portal::Fetcher).to receive(:profiles).with(needs_profiles_certificate_content: sut.needs_profiles_certificate_content, needs_profiles_devices: sut.needs_profiles_devices, profile_type: sut.profile_type).and_return(['portal_profile_1', 'portal_profile_2']).once expect(sut.profiles).to eq(['portal_profile_1', 'portal_profile_2']) # WHEN sut.forget_portal_profile('portal_profile_1') # THEN expect(sut.profiles).to eq(['portal_profile_2']) end end describe "certificates" do it 'caches certificates' do # GIVEN sut = default_sut allow(Match::Portal::Fetcher).to receive(:certificates).with(additional_cert_types: sut.additional_cert_types, platform: sut.platform, profile_type: sut.profile_type).and_return(['portal_certificate_1']).once # WHEN certificates = sut.certificates # THEN expect(certificates).to eq(['portal_certificate_1']) # THEN used cached expect(sut.certificates).to eq(['portal_certificate_1']) end it 'resets certificates cache' do # GIVEN sut = default_sut allow(Match::Portal::Fetcher).to receive(:certificates).with(additional_cert_types: sut.additional_cert_types, platform: sut.platform, profile_type: sut.profile_type).and_return(['portal_certificate_1']).once certificates = sut.certificates expect(certificates).to eq(['portal_certificate_1']) allow(Match::Portal::Fetcher).to receive(:certificates).with(additional_cert_types: sut.additional_cert_types, platform: sut.platform, profile_type: sut.profile_type).and_return(['portal_certificate_2']).once # WHEN sut.reset_certificates # THEN expect(sut.certificates).to eq(['portal_certificate_2']) # THEN used cached expect(sut.certificates).to eq(['portal_certificate_2']) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/utils_spec.rb
match/spec/utils_spec.rb
describe Match do describe Match::Utils do let(:thread) { double } before(:each) do value = double allow(value).to receive(:success?).and_return(true) allow(thread).to receive(:value).and_return(value) allow(FastlaneCore::UI).to receive(:interactive?).and_return(false) allow(Security::InternetPassword).to receive(:find).and_return(nil) allow(FastlaneCore::Helper).to receive(:backticks).with('security -h | grep set-key-partition-list', print: false).and_return(' set-key-partition-list Set the partition list of a key.') end describe 'import' do it 'finds a normal keychain name relative to ~/Library/Keychains' do expected_command = "security import item.path -k '#{Dir.home}/Library/Keychains/login.keychain' -P #{''.shellescape} -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild -T /usr/bin/productsign 1> /dev/null" # this command is also sent on macOS Sierra and we need to allow it or else the test will fail expected_partition_command = "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k #{''.shellescape} #{Dir.home}/Library/Keychains/login.keychain 1> /dev/null" allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true) allow(File).to receive(:file?).and_return(false) expect(File).to receive(:file?).with("#{Dir.home}/Library/Keychains/login.keychain").and_return(true) allow(File).to receive(:exist?).and_return(false) expect(File).to receive(:exist?).with('item.path').and_return(true) expect(Open3).to receive(:popen3).with(expected_command).and_yield("", "", "", thread) expect(Open3).to receive(:popen3).with(expected_partition_command) Match::Utils.import('item.path', 'login.keychain', password: '') end it 'treats a keychain name it cannot find in ~/Library/Keychains as the full keychain path' do tmp_path = Dir.mktmpdir keychain = "#{tmp_path}/my/special.keychain" expected_command = "security import item.path -k '#{keychain}' -P #{''.shellescape} -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild -T /usr/bin/productsign 1> /dev/null" # this command is also sent on macOS Sierra and we need to allow it or else the test will fail expected_partition_command = "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k #{''.shellescape} #{keychain} 1> /dev/null" allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true) allow(File).to receive(:file?).and_return(false) expect(File).to receive(:file?).with(keychain).and_return(true) allow(File).to receive(:exist?).and_return(false) expect(File).to receive(:exist?).with('item.path').and_return(true) expect(Open3).to receive(:popen3).with(expected_command).and_yield("", "", "", thread) expect(Open3).to receive(:popen3).with(expected_partition_command) Match::Utils.import('item.path', keychain, password: '') end it 'shows a user error if the keychain path cannot be resolved' do allow(File).to receive(:exist?).and_return(false) expect do Match::Utils.import('item.path', '/my/special.keychain') end.to raise_error(/Could not locate the provided keychain/) end it "tries to find the macOS Sierra keychain too" do expected_command = "security import item.path -k '#{Dir.home}/Library/Keychains/login.keychain-db' -P #{''.shellescape} -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild -T /usr/bin/productsign 1> /dev/null" # this command is also sent on macOS Sierra and we need to allow it or else the test will fail expected_partition_command = "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k #{''.shellescape} #{Dir.home}/Library/Keychains/login.keychain-db 1> /dev/null" allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true) allow(File).to receive(:file?).and_return(false) expect(File).to receive(:file?).with("#{Dir.home}/Library/Keychains/login.keychain-db").and_return(true) allow(File).to receive(:exist?).and_return(false) expect(File).to receive(:exist?).with("item.path").and_return(true) expect(Open3).to receive(:popen3).with(expected_command).and_yield("", "", "", thread) expect(Open3).to receive(:popen3).with(expected_partition_command) Match::Utils.import('item.path', "login.keychain") end describe "keychain_password" do it 'prompts for keychain password when none given and not in keychain' do expected_command = "security import item.path -k '#{Dir.home}/Library/Keychains/login.keychain' -P #{''.shellescape} -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild -T /usr/bin/productsign 1> /dev/null" # this command is also sent on macOS Sierra and we need to allow it or else the test will fail expected_partition_command = "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k #{'user_entered'.shellescape} #{Dir.home}/Library/Keychains/login.keychain 1> /dev/null" allow(Security::InternetPassword).to receive(:find).and_return(nil) allow(FastlaneCore::UI).to receive(:interactive?).and_return(true) expect(FastlaneCore::Helper).to receive(:ask_password).and_return('user_entered') expect(Security::InternetPassword).to receive(:add).with('fastlane_keychain_login', anything, 'user_entered') allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true) allow(File).to receive(:file?).and_return(false) expect(File).to receive(:file?).with("#{Dir.home}/Library/Keychains/login.keychain").and_return(true) allow(File).to receive(:exist?).and_return(false) expect(File).to receive(:exist?).with('item.path').and_return(true) expect(Open3).to receive(:popen3).with(expected_command).and_yield("", "", "", thread) expect(Open3).to receive(:popen3).with(expected_partition_command) Match::Utils.import('item.path', 'login.keychain') end it 'find keychain password in keychain when none given' do expected_command = "security import item.path -k '#{Dir.home}/Library/Keychains/login.keychain' -P #{''.shellescape} -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild -T /usr/bin/productsign 1> /dev/null" # this command is also sent on macOS Sierra and we need to allow it or else the test will fail expected_partition_command = "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k #{'from_keychain'.shellescape} #{Dir.home}/Library/Keychains/login.keychain 1> /dev/null" item = double allow(item).to receive(:password).and_return('from_keychain') allow(Security::InternetPassword).to receive(:find).and_return(item) allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true) allow(File).to receive(:file?).and_return(false) expect(File).to receive(:file?).with("#{Dir.home}/Library/Keychains/login.keychain").and_return(true) allow(File).to receive(:exist?).and_return(false) expect(File).to receive(:exist?).with('item.path').and_return(true) expect(Open3).to receive(:popen3).with(expected_command).and_yield("", "", "", thread) expect(Open3).to receive(:popen3).with(expected_partition_command) Match::Utils.import('item.path', 'login.keychain') end end end describe "fill_environment" do it "#environment_variable_name uses the correct env variable" do result = Match::Utils.environment_variable_name(app_identifier: "tools.fastlane.app", type: "appstore") expect(result).to eq("sigh_tools.fastlane.app_appstore") end it "#environment_variable_name_team_id uses the correct env variable" do result = Match::Utils.environment_variable_name_team_id(app_identifier: "tools.fastlane.app", type: "appstore") expect(result).to eq("sigh_tools.fastlane.app_appstore_team-id") end it "#environment_variable_name_profile_name uses the correct env variable" do result = Match::Utils.environment_variable_name_profile_name(app_identifier: "tools.fastlane.app", type: "appstore") expect(result).to eq("sigh_tools.fastlane.app_appstore_profile-name") end it "#environment_variable_name_profile_path uses the correct env variable" do result = Match::Utils.environment_variable_name_profile_path(app_identifier: "tools.fastlane.app", type: "appstore") expect(result).to eq("sigh_tools.fastlane.app_appstore_profile-path") end it "#environment_variable_name_certificate_name uses the correct env variable" do result = Match::Utils.environment_variable_name_certificate_name(app_identifier: "tools.fastlane.app", type: "appstore") expect(result).to eq("sigh_tools.fastlane.app_appstore_certificate-name") end it "pre-fills the environment" do my_key = "my_test_key" uuid = "my_uuid" result = Match::Utils.fill_environment(my_key, uuid) expect(result).to eq(uuid) item = ENV.find { |k, v| v == uuid } expect(item[0]).to eq(my_key) expect(item[1]).to eq(uuid) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/change_password_spec.rb
match/spec/change_password_spec.rb
describe Match do describe Match::ChangePassword do before do stub_const('ENV', { "MATCH_PASSWORD" => '2"QAHg@v(Qp{=*n^' }) end it "deletes decrypted files at the end", requires_security: true do git_url = "https://github.com/fastlane/fastlane/tree/master/certificates" values = { app_identifier: "tools.fastlane.app", type: "appstore", git_url: git_url, shallow_clone: true, username: "flapple@something.com" } config = FastlaneCore::Configuration.create(Match::Options.available_options, values) repo_dir = Dir.mktmpdir fake_storage = "fake_storage" expect(Match::Storage::GitStorage).to receive(:configure).with({ git_url: git_url, shallow_clone: true, skip_docs: false, git_branch: "master", git_full_name: nil, git_user_email: nil, clone_branch_directly: false, git_basic_authorization: nil, git_bearer_authorization: nil, git_private_key: nil, type: config[:type], platform: config[:platform] }).and_return(fake_storage) allow(fake_storage).to receive(:download) allow(fake_storage).to receive(:working_directory).and_return(repo_dir) allow(fake_storage).to receive(:save_changes!) allow(Match::ChangePassword).to receive(:ensure_ui_interactive) allow(FastlaneCore::Helper).to receive(:ask_password).and_return("") expect(fake_storage).to receive(:clear_changes) Match::ChangePassword.update(params: config) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/runner_spec.rb
match/spec/runner_spec.rb
require_relative 'spec_helper' describe Match do describe Match::Runner do let(:keychain) { 'login.keychain' } before do allow(ENV).to receive(:[]).and_call_original allow(ENV).to receive(:[]).with('MATCH_KEYCHAIN_NAME').and_return(keychain) allow(ENV).to receive(:[]).with('MATCH_KEYCHAIN_PASSWORD').and_return(nil) # There is another test ENV.delete('FASTLANE_TEAM_ID') ENV.delete('FASTLANE_TEAM_NAME') end ["10", "11", "16"].each do |xcode_version| context "Xcode #{xcode_version}" do let(:generate_apple_certs) { xcode_version == "11" } before do allow(FastlaneCore::Helper).to receive(:mac?).and_return(true) allow(FastlaneCore::Helper).to receive(:xcode_version).and_return(xcode_version) stub_const('ENV', { "MATCH_PASSWORD" => '2"QAHg@v(Qp{=*n^' }) end it "creates a new profile and certificate if it doesn't exist yet", requires_security: true do git_url = "https://github.com/fastlane/fastlane/tree/master/certificates" values = { app_identifier: "tools.fastlane.app", type: "appstore", git_url: git_url, shallow_clone: true, username: "flapple@something.com" } config = FastlaneCore::Configuration.create(Match::Options.available_options, values) repo_dir = Dir.mktmpdir cert_path = File.join(repo_dir, "something.cer") profile_path = "./match/spec/fixtures/test.mobileprovision" keychain_path = FastlaneCore::Helper.keychain_path("login.keychain") # can be .keychain or .keychain-db destination = File.join(provisioning_path_for_xcode_version(xcode_version), "98264c6b-5151-4349-8d0f-66691e48ae35.mobileprovision") fake_cache = create_fake_cache fake_storage = "fake_storage" expect(Match::Storage::GitStorage).to receive(:configure).with({ git_url: git_url, shallow_clone: true, skip_docs: false, git_branch: "master", git_full_name: nil, git_user_email: nil, clone_branch_directly: false, git_basic_authorization: nil, git_bearer_authorization: nil, git_private_key: nil, type: config[:type], platform: config[:platform] }).and_return(fake_storage) expect(fake_storage).to receive(:download).and_return(nil) expect(fake_storage).to receive(:clear_changes).and_return(nil) allow(fake_storage).to receive(:working_directory).and_return(repo_dir) allow(fake_storage).to receive(:prefixed_working_directory).and_return(repo_dir) expect(Match::Generator).to receive(:generate_certificate).with(config, :distribution, fake_storage.working_directory, specific_cert_type: nil).and_return(cert_path) expect(Match::Generator).to receive(:generate_provisioning_profile).with(params: config, prov_type: :appstore, certificate_id: "something", app_identifier: values[:app_identifier], force: false, cache: fake_cache, working_directory: fake_storage.working_directory).and_return(profile_path) expect(FastlaneCore::ProvisioningProfile).to receive(:install).with(profile_path, keychain_path).and_return(destination) expect(fake_storage).to receive(:save_changes!).with( files_to_commit: [ File.join(repo_dir, "something.cer"), File.join(repo_dir, "something.p12"), # this is important, as a cert consists out of 2 files "./match/spec/fixtures/test.mobileprovision" ], files_to_delete: [] ) spaceship = "spaceship" allow(spaceship).to receive(:team_id).and_return("") expect(Match::SpaceshipEnsure).to receive(:new).and_return(spaceship) expect(spaceship).to receive(:certificates_exists).and_return(true) expect(spaceship).not_to receive(:profile_exists) expect(spaceship).to receive(:bundle_identifier_exists).and_return(true) expect(Match::Utils).to receive(:get_cert_info).and_return([["Common Name", "fastlane certificate name"]]) Match::Runner.new.run(config) expect(ENV[Match::Utils.environment_variable_name(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql('98264c6b-5151-4349-8d0f-66691e48ae35') expect(ENV[Match::Utils.environment_variable_name_team_id(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql('439BBM9367') expect(ENV[Match::Utils.environment_variable_name_profile_name(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql('tools.fastlane.app AppStore') profile_path = File.join(provisioning_path_for_xcode_version(xcode_version), '98264c6b-5151-4349-8d0f-66691e48ae35.mobileprovision') expect(ENV[Match::Utils.environment_variable_name_profile_path(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql(profile_path) expect(ENV[Match::Utils.environment_variable_name_certificate_name(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql("fastlane certificate name") end it "uses existing certificates and profiles if they exist", requires_security: true do git_url = "https://github.com/fastlane/fastlane/tree/master/certificates" values = { app_identifier: "tools.fastlane.app", type: "appstore", git_url: git_url, username: "flapple@something.com" } create_fake_cache config = FastlaneCore::Configuration.create(Match::Options.available_options, values) repo_dir = "./match/spec/fixtures/existing" cert_path = "./match/spec/fixtures/existing/certs/distribution/E7P4EE896K.cer" key_path = "./match/spec/fixtures/existing/certs/distribution/E7P4EE896K.p12" fake_storage = "fake_storage" expect(Match::Storage::GitStorage).to receive(:configure).with({ git_url: git_url, shallow_clone: false, skip_docs: false, git_branch: "master", git_full_name: nil, git_user_email: nil, clone_branch_directly: false, git_basic_authorization: nil, git_bearer_authorization: nil, git_private_key: nil, type: config[:type], platform: config[:platform] }).and_return(fake_storage) expect(fake_storage).to receive(:download).and_return(nil) expect(fake_storage).to receive(:clear_changes).and_return(nil) allow(fake_storage).to receive(:git_url).and_return(git_url) allow(fake_storage).to receive(:working_directory).and_return(repo_dir) allow(fake_storage).to receive(:prefixed_working_directory).and_return(repo_dir) fake_encryption = "fake_encryption" expect(Match::Encryption::OpenSSL).to receive(:new).with(keychain_name: fake_storage.git_url, working_directory: fake_storage.working_directory, force_legacy_encryption: false).and_return(fake_encryption) expect(fake_encryption).to receive(:decrypt_files).and_return(nil) expect(Match::Utils).to receive(:import).with(key_path, keychain, password: nil).and_return(nil) expect(fake_storage).to_not(receive(:save_changes!)) # To also install the certificate, fake that expect(FastlaneCore::CertChecker).to receive(:installed?).with(cert_path, in_keychain: nil).and_return(false) expect(Match::Utils).to receive(:import).with(cert_path, keychain, password: nil).and_return(nil) spaceship = "spaceship" allow(spaceship).to receive(:team_id).and_return("") expect(Match::SpaceshipEnsure).to receive(:new).and_return(spaceship) expect(spaceship).to receive(:certificates_exists).and_return(true) expect(spaceship).to receive(:profile_exists).and_return(true) expect(spaceship).to receive(:bundle_identifier_exists).and_return(true) expect(Match::Utils).to receive(:get_cert_info) expect(Match::Utils).to receive(:get_cert_info).and_return([["Common Name", "fastlane certificate name"]]) allow(Match::Utils).to receive(:is_cert_valid?).and_return(true) Match::Runner.new.run(config) expect(ENV[Match::Utils.environment_variable_name(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql('736590c3-dfe8-4c25-b2eb-2404b8e65fb8') expect(ENV[Match::Utils.environment_variable_name_team_id(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql('439BBM9367') expect(ENV[Match::Utils.environment_variable_name_profile_name(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql('match AppStore tools.fastlane.app 1449198835') profile_path = File.join(provisioning_path_for_xcode_version(xcode_version), '736590c3-dfe8-4c25-b2eb-2404b8e65fb8.mobileprovision') expect(ENV[Match::Utils.environment_variable_name_profile_path(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql(profile_path) expect(ENV[Match::Utils.environment_variable_name_certificate_name(app_identifier: "tools.fastlane.app", type: "appstore")]).to eql("fastlane certificate name") end it "fails because of an outdated certificate in readonly mode", requires_security: true do git_url = "https://github.com/fastlane/fastlane/tree/master/certificates" values = { app_identifier: "tools.fastlane.app", type: "appstore", git_url: git_url, username: "flapple@something.com", readonly: true } config = FastlaneCore::Configuration.create(Match::Options.available_options, values) repo_dir = "./match/spec/fixtures/existing" cert_path = "./match/spec/fixtures/existing/certs/distribution/E7P4EE896K.cer" key_path = "./match/spec/fixtures/existing/certs/distribution/E7P4EE896K.p12" create_fake_cache fake_storage = create_fake_storage(match_config: config, repo_dir: repo_dir) fake_encryption = "fake_encryption" expect(Match::Encryption::OpenSSL).to receive(:new).with(keychain_name: fake_storage.git_url, working_directory: fake_storage.working_directory, force_legacy_encryption: false).and_return(fake_encryption) expect(fake_encryption).to receive(:decrypt_files).and_return(nil) spaceship = "spaceship" allow(spaceship).to receive(:team_id).and_return("") expect(Match::SpaceshipEnsure).not_to receive(:new) expect(Match::Utils).to receive(:is_cert_valid?).and_return(false) expect do Match::Runner.new.run(config) end.to raise_error("Your certificate 'E7P4EE896K.cer' is not valid, please check end date and renew it if necessary") end it "installs profiles in read-only mode", requires_security: true do # GIVEN # Downloaded and decrypted storage location. repo_dir = "./match/spec/fixtures/existing" # Valid cert and key stored_valid_cert_path = "#{repo_dir}/certs/distribution/E7P4EE896K.cer" stored_valid_profile_path = "#{repo_dir}/profiles/appstore/AppStore_tools.fastlane.app.mobileprovision" # match options match_test_options = { output_path: "tmp/match_certs", # to test the expectation that we do a file copy when this option is provided readonly: true # Current test suite. } match_config = create_match_config_with_git_storage(extra_values: match_test_options) # EXPECTATIONS # Ensure cache is not used. create_fake_cache(allow_usage: false) # Storage fake_storage = create_fake_storage(match_config: match_config, repo_dir: repo_dir) # Ensure no changes in storage are made. expect(fake_storage).not_to receive(:save_changes!) # Encryption fake_encryption = create_fake_encryption(storage: fake_storage) # Ensure there are no new files to encrypt. expect(fake_encryption).not_to receive(:encrypt_files) # Utils # Ensure match validates stored certificate. expect(Match::Utils).to receive(:is_cert_valid?).with(stored_valid_cert_path).and_return(true) # Certificates # Ensure a new certificate is not generated. expect(Match::Generator).not_to receive(:generate_certificate).with(match_config, :distribution, fake_storage.working_directory, specific_cert_type: nil) # Profiles begin # Ensure profiles are installed, but not validated. keychain_path = FastlaneCore::Helper.keychain_path("login.keychain") expect(FastlaneCore::ProvisioningProfile).to receive(:install).with(stored_valid_profile_path, keychain_path) expect(Match::Generator).not_to receive(:generate_provisioning_profile) end # output_path expect(FileUtils).to receive(:mkdir_p).with(match_test_options[:output_path]) expect(FileUtils).to receive(:cp).with(stored_valid_cert_path, match_test_options[:output_path]) expect(FileUtils).to receive(:cp).with("#{repo_dir}/certs/distribution/E7P4EE896K.p12", match_test_options[:output_path]) expect(FileUtils).to receive(:cp).with(stored_valid_profile_path, match_test_options[:output_path]) # WHEN Match::Runner.new.run(match_config) # THEN # Rely on expectations defined above. end it "skips provisioning profiles when skip_provisioning_profiles set to true", requires_security: true do git_url = "https://github.com/fastlane/fastlane/tree/master/certificates" values = { app_identifier: "tools.fastlane.app", type: "appstore", git_url: git_url, shallow_clone: true, username: "flapple@something.com", skip_provisioning_profiles: true } config = FastlaneCore::Configuration.create(Match::Options.available_options, values) repo_dir = Dir.mktmpdir cert_path = File.join(repo_dir, "something.cer") create_fake_cache fake_storage = "fake_storage" expect(Match::Storage::GitStorage).to receive(:configure).with({ git_url: git_url, shallow_clone: true, skip_docs: false, git_branch: "master", git_full_name: nil, git_user_email: nil, clone_branch_directly: false, git_basic_authorization: nil, git_bearer_authorization: nil, git_private_key: nil, type: config[:type], platform: config[:platform] }).and_return(fake_storage) expect(fake_storage).to receive(:download).and_return(nil) expect(fake_storage).to receive(:clear_changes).and_return(nil) allow(fake_storage).to receive(:working_directory).and_return(repo_dir) allow(fake_storage).to receive(:prefixed_working_directory).and_return(repo_dir) expect(Match::Generator).to receive(:generate_certificate).with(config, :distribution, fake_storage.working_directory, specific_cert_type: nil).and_return(cert_path) expect(Match::Generator).to_not(receive(:generate_provisioning_profile)) expect(FastlaneCore::ProvisioningProfile).to_not(receive(:install)) expect(fake_storage).to receive(:save_changes!).with( files_to_commit: [ File.join(repo_dir, "something.cer"), File.join(repo_dir, "something.p12") # this is important, as a cert consists out of 2 files ], files_to_delete: [] ) spaceship = "spaceship" allow(spaceship).to receive(:team_id).and_return("") expect(Match::SpaceshipEnsure).to receive(:new).and_return(spaceship) expect(spaceship).to receive(:certificates_exists).and_return(true) expect(spaceship).to_not(receive(:profile_exists)) expect(spaceship).to receive(:bundle_identifier_exists).and_return(true) Match::Runner.new.run(config) # Nothing to check after the run end it "fails because enterprise type requested without in_house credentials", requires_security: true do git_url = "https://github.com/fastlane/fastlane/tree/master/certificates" values = { app_identifier: "tools.fastlane.app", type: "enterprise", git_url: git_url, username: "flapple@something.com", readonly: false } config = FastlaneCore::Configuration.create(Match::Options.available_options, values) repo_dir = "./match/spec/fixtures/existing" cert_path = "./match/spec/fixtures/existing/certs/distribution/E7P4EE896K.cer" key_path = "./match/spec/fixtures/existing/certs/distribution/E7P4EE896K.p12" create_fake_cache fake_storage = create_fake_storage(match_config: config, repo_dir: repo_dir) fake_encryption = "fake_encryption" expect(Match::Encryption::OpenSSL).to receive(:new).with(keychain_name: fake_storage.git_url, working_directory: fake_storage.working_directory, force_legacy_encryption: false).and_return(fake_encryption) expect(fake_encryption).to receive(:decrypt_files).and_return(nil) client = "client" expect(Match::SpaceshipEnsure).to receive(:new) expect(Spaceship::ConnectAPI).to receive(:client).and_return(client) allow(client).to receive(:in_house?).and_return(false) expect do Match::Runner.new.run(config) end.to raise_error("You defined the profile type 'enterprise', but your Apple account doesn't support In-House profiles") end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/generator_spec.rb
match/spec/generator_spec.rb
describe Match::Generator do describe 'calling through' do describe 'cert' do require 'cert' let(:fake_runner) { double } let(:common_config_hash) { { development: true, output_path: 'workspace/certs/development', force: true, username: 'username', team_id: 'team_id', platform: "ios", filename: nil, team_name: nil } } let(:params) { { type: 'development', workspace: 'workspace', username: 'username', team_id: 'team_id', keychain_name: 'login.keychain', keychain_password: 'password' } } let(:config) { FastlaneCore::Configuration.create( Cert::Options.available_options, common_config_hash.merge(keychain_config_hash) ) } before do allow(FastlaneCore::Helper).to receive(:mac?).and_return(is_mac) allow(FastlaneCore::Helper).to receive(:xcode_at_least?).and_return(false) allow(Cert::Runner).to receive(:new).and_return(fake_runner) allow(fake_runner).to receive(:launch).and_return("fake_path") allow(File).to receive(:exist?).and_call_original end context 'on macOS' do let(:is_mac) { true } let(:keychain_config_hash) { { keychain_path: FastlaneCore::Helper.keychain_path("login.keychain"), keychain_password: 'password' } } it 'configures correctly' do expect(FastlaneCore::Helper).to receive(:keychain_path).with("login.keychain").exactly(2).times.and_return("fake_keychain_name") expect(File).to receive(:expand_path).with("fake_keychain_name").exactly(2).times.and_return("fake_keychain_path") expect(File).to receive(:exist?).with("fake_keychain_path").exactly(2).times.and_return(true) expect(Cert).to receive(:config=).with(a_configuration_matching(config)) Match::Generator.generate_certificate(params, 'development', "workspace") end it 'receives keychain_path' do expect(FastlaneCore::Helper).to receive(:keychain_path).with("login.keychain").and_return("fake_keychain_name") expect(File).to receive(:expand_path).with("fake_keychain_name").and_return("fake_keychain_path") expect(File).to receive(:exist?).with("fake_keychain_path").and_return(true) Match::Generator.generate_certificate(params, 'development', "workspace") end end context 'on non-macOS' do let(:is_mac) { false } let(:keychain_config_hash) { { keychain_path: nil, keychain_password: nil } } context 'with keychain_path' do let(:keychain_config_hash) { { keychain_path: "fake_keychain_path", keychain_password: "password" } } it 'raises an error' do expect { config }.to raise_error(FastlaneCore::Interface::FastlaneError, "Keychain is not supported on platforms other than macOS") end end context 'without keychain_path' do it 'configures correctly' do expect(FastlaneCore::Helper).not_to receive(:keychain_path) expect(File).not_to receive(:expand_path) expect(Cert).to receive(:config=).with(a_configuration_matching(config)) Match::Generator.generate_certificate(params, 'development', "workspace") end it 'does not receive keychain_path' do expect(FastlaneCore::Helper).not_to receive(:keychain_path) expect(File).not_to receive(:expand_path) Match::Generator.generate_certificate(params, 'development', "workspace") end end end end describe 'sigh' do let(:config) { FastlaneCore::Configuration.create(Sigh::Options.available_options, { app_identifier: 'app_identifier', development: true, output_path: 'workspace/profiles/development', username: 'username', force: false, cert_id: 'fake_cert_id', provisioning_name: 'match Development app_identifier', ignore_profiles_with_different_name: true, team_id: 'team_id', platform: :ios, template_name: 'template_name', fail_on_name_taken: false, include_all_certificates: true, }) } require 'sigh' it 'configures correctly for nested execution' do # This is the important part. We need to see the right configuration come through # for sigh expect(Sigh).to receive(:config=).with(a_configuration_matching(config)) # This just mocks out the usual behavior of running sigh, since that's not what # we're testing allow(Sigh::Manager).to receive(:start).and_return("fake_path") params = { app_identifier: 'app_identifier', type: :development, workspace: 'workspace', username: 'username', team_id: 'team_id', platform: :ios, template_name: 'template_name', include_all_certificates: true, } Match::Generator.generate_provisioning_profile(params: params, prov_type: :development, certificate_id: 'fake_cert_id', app_identifier: params[:app_identifier], force: false, working_directory: "workspace") end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/spec_helper.rb
match/spec/spec_helper.rb
RSpec::Matchers.define(:a_configuration_matching) do |expected| match do |actual| actual.values == expected.values end end def before_each_match ENV["DELIVER_USER"] = "flapple@krausefx.com" ENV["DELIVER_PASSWORD"] = "so_secret" end def create_fake_storage(match_config:, repo_dir:) fake_storage = "fake_storage" expect(Match::Storage::GitStorage).to receive(:configure).with({ git_url: match_config[:git_url] || default_git_url, shallow_clone: match_config[:shallow_clone] || false, skip_docs: match_config[:skip_docs] || false, git_branch: match_config[:git_branch] || "master", git_full_name: nil, git_user_email: nil, clone_branch_directly: match_config[:clone_branch_directly] || false, git_basic_authorization: nil, git_bearer_authorization: nil, git_private_key: nil, type: match_config[:type], platform: match_config[:platform] }).and_return(fake_storage) allow(fake_storage).to receive(:git_url).and_return(match_config[:git_url]) allow(fake_storage).to receive(:working_directory).and_return(repo_dir) allow(fake_storage).to receive(:prefixed_working_directory).and_return(repo_dir) # Ensure match downloads storage. expect(fake_storage).to receive(:download).and_return(nil) # Ensure match clears changes after completion. expect(fake_storage).to receive(:clear_changes).and_return(nil) return fake_storage end def default_app_identifier "tools.fastlane.app" end def default_provisioning_type "appstore" end def default_git_url "https://github.com/fastlane/fastlane/tree/master/certificates" end def default_username "flapple@something.com" end def create_match_config_with_git_storage(extra_values: {}, git_url: nil, app_identifier: nil, type: nil, username: nil) values = { app_identifier: app_identifier || default_app_identifier, type: type || default_provisioning_type, git_url: git_url || default_git_url, username: username || default_username, shallow_clone: true } extra_values.each do |k, v| values[k] = v end match_config = FastlaneCore::Configuration.create(Match::Options.available_options, values) return match_config end def create_fake_encryption(storage:) fake_encryption = "fake_encryption" expect(Match::Encryption::OpenSSL).to receive(:new).with(keychain_name: storage.git_url, working_directory: storage.working_directory, force_legacy_encryption: false).and_return(fake_encryption) # Ensure files from storage are decrypted. expect(fake_encryption).to receive(:decrypt_files).and_return(nil) return fake_encryption end def create_fake_spaceship_ensure spaceship_ensure = "spaceship" allow(Match::SpaceshipEnsure).to receive(:new).and_return(spaceship_ensure) # Ensure app identifiers are validated. expect(spaceship_ensure).to receive(:bundle_identifier_exists).and_return(true) return spaceship_ensure end def provisioning_path_for_xcode_version(xcode_version) if xcode_version.split('.')[0].to_i < 16 return File.join(File.expand_path("~"), "Library/MobileDevice/Provisioning Profiles") else return File.join(File.expand_path("~"), "Library/Developer/Xcode/UserData/Provisioning Profiles") end end def create_fake_cache(allow_usage: true) fake_cache = 'fake_cache' allow(Match::Portal::Cache).to receive(:new).and_return(fake_cache) if allow_usage allow(fake_cache).to receive(:bundle_ids).and_return(nil) allow(fake_cache).to receive(:certificates).and_return(nil) allow(fake_cache).to receive(:profiles).and_return(nil) allow(fake_cache).to receive(:devices).and_return(nil) allow(fake_cache).to receive(:portal_profile).and_return(nil) allow(fake_cache).to receive(:reset_certificates) else expect(Match::Portal::Cache).not_to receive(:new) expect(fake_cache).not_to receive(:bundle_ids) expect(fake_cache).not_to receive(:certificates) expect(fake_cache).not_to receive(:profiles) expect(fake_cache).not_to receive(:devices) expect(fake_cache).not_to receive(:portal_profile) expect(fake_cache).not_to receive(:reset_certificates) end fake_cache end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/importer_spec.rb
match/spec/importer_spec.rb
describe Match do describe Match::Runner do let(:fake_storage) { "fake_storage" } let(:keychain) { 'login.keychain' } let(:mock_cert) { double } let(:cert_path) { "./match/spec/fixtures/test.cer" } let(:p12_path) { "./match/spec/fixtures/test.p12" } let(:ios_profile_path) { "./match/spec/fixtures/test.mobileprovision" } let(:osx_profile_path) { "./match/spec/fixtures/test.provisionprofile" } let(:values) { test_values } let(:config) { FastlaneCore::Configuration.create(Match::Options.available_options, values) } def test_values { app_identifier: "tools.fastlane.app", type: "appstore", git_url: "https://github.com/fastlane/fastlane/tree/master/certificates", shallow_clone: true, username: "flapple@something.com" } end def developer_id_test_values { app_identifier: "tools.fastlane.app", type: "developer_id", git_url: "https://github.com/fastlane/fastlane/tree/master/certificates", shallow_clone: true, username: "flapple@something.com" } end before do allow(mock_cert).to receive(:id).and_return("123456789") allow(mock_cert).to receive(:certificate_content).and_return(Base64.strict_encode64(File.binread(cert_path))) allow(ENV).to receive(:[]).and_call_original allow(ENV).to receive(:[]).with('MATCH_KEYCHAIN_NAME').and_return(keychain) allow(ENV).to receive(:[]).with('MATCH_KEYCHAIN_PASSWORD').and_return(nil) allow(ENV).to receive(:[]).with('MATCH_PASSWORD').and_return("test") ENV.delete('FASTLANE_TEAM_ID') ENV.delete('FASTLANE_TEAM_NAME') end it "imports a .cert, .p12 and .mobileprovision (iOS provision) into the match repo" do repo_dir = Dir.mktmpdir setup_fake_storage(repo_dir, config) expect(Spaceship::ConnectAPI).to receive(:login) expect(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([mock_cert]) expect(fake_storage).to receive(:save_changes!).with( files_to_commit: [ File.join(repo_dir, "certs", "distribution", "#{mock_cert.id}.cer"), File.join(repo_dir, "certs", "distribution", "#{mock_cert.id}.p12"), File.join(repo_dir, "profiles", "appstore", "AppStore_tools.fastlane.app.mobileprovision") ] ) expect(fake_storage).to receive(:clear_changes) Match::Importer.new.import_cert(config, cert_path: cert_path, p12_path: p12_path, profile_path: ios_profile_path) end it "imports a .cert, .p12 and .provisionprofile (osx provision) into the match repo" do repo_dir = Dir.mktmpdir setup_fake_storage(repo_dir, config) expect(Spaceship::ConnectAPI).to receive(:login) expect(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([mock_cert]) expect(fake_storage).to receive(:save_changes!).with( files_to_commit: [ File.join(repo_dir, "certs", "distribution", "#{mock_cert.id}.cer"), File.join(repo_dir, "certs", "distribution", "#{mock_cert.id}.p12"), File.join(repo_dir, "profiles", "appstore", "AppStore_tools.fastlane.app.provisionprofile") ] ) expect(fake_storage).to receive(:clear_changes) Match::Importer.new.import_cert(config, cert_path: cert_path, p12_path: p12_path, profile_path: osx_profile_path) end it "imports a .cert and .p12 without profile into the match repo (backwards compatibility)" do repo_dir = Dir.mktmpdir setup_fake_storage(repo_dir, config) expect(UI).to receive(:input).and_return("") expect(Spaceship::ConnectAPI).to receive(:login) expect(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([mock_cert]) expect(fake_storage).to receive(:save_changes!).with( files_to_commit: [ File.join(repo_dir, "certs", "distribution", "#{mock_cert.id}.cer"), File.join(repo_dir, "certs", "distribution", "#{mock_cert.id}.p12") ] ) expect(fake_storage).to receive(:clear_changes) Match::Importer.new.import_cert(config, cert_path: cert_path, p12_path: p12_path) end it "imports a .cert and .p12 when the type is set to developer_id" do repo_dir = Dir.mktmpdir developer_id_config = FastlaneCore::Configuration.create(Match::Options.available_options, developer_id_test_values) setup_fake_storage(repo_dir, developer_id_config) expect(UI).to receive(:input).and_return("") expect(Spaceship::ConnectAPI).to receive(:login) expect(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([mock_cert]) expect(fake_storage).to receive(:save_changes!).with( files_to_commit: [ File.join(repo_dir, "certs", "developer_id_application", "#{mock_cert.id}.cer"), File.join(repo_dir, "certs", "developer_id_application", "#{mock_cert.id}.p12") ] ) expect(fake_storage).to receive(:clear_changes) Match::Importer.new.import_cert(developer_id_config, cert_path: cert_path, p12_path: p12_path) end def setup_fake_storage(repo_dir, config) expect(Match::Storage::GitStorage).to receive(:configure).with({ git_url: config[:git_url], shallow_clone: true, skip_docs: false, git_branch: "master", git_full_name: nil, git_user_email: nil, git_private_key: nil, git_basic_authorization: nil, git_bearer_authorization: nil, clone_branch_directly: false, type: config[:type], platform: config[:platform] }).and_return(fake_storage) expect(fake_storage).to receive(:download).and_return(nil) allow(fake_storage).to receive(:working_directory).and_return(repo_dir) allow(fake_storage).to receive(:prefixed_working_directory).and_return(repo_dir) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/storage/git_storage_spec_helper.rb
match/spec/storage/git_storage_spec_helper.rb
def branch_checkout_commands(git_branch) [ # Check if branch exists. "git --no-pager branch --list origin/#{git_branch} --no-color -r", # Checkout branch. "git checkout --orphan #{git_branch}", # Reset all changes in the working branch copy. "git reset --hard" ] end def expect_command_execution(commands) [commands].flatten.each do |command| expect(FastlaneCore::CommandExecutor).to receive(:execute).once.with({ command: command, print_all: nil, print_command: nil }).and_return("") end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/storage/s3_storage_spec.rb
match/spec/storage/s3_storage_spec.rb
describe Match do describe Match::Storage::S3Storage do subject { described_class.new(s3_region: nil, s3_access_key: nil, s3_secret_access_key: nil, s3_bucket: 'foobar') } let(:working_directory) { '/var/folders/px/abcdefghijklmnop/T/d20181026-96528-1av4gge' } before do allow(subject).to receive(:working_directory).and_return(working_directory) allow(subject).to receive(:s3_client).and_return(s3_client) end describe '#upload_files' do let(:files_to_upload) do [ "#{working_directory}/ABCDEFG/certs/development/ABCDEFG.cer", "#{working_directory}/ABCDEFG/certs/development/ABCDEFG.p12" ] end let(:s3_client) { double(upload_file: true) } let!(:file) { class_double('File', read: 'body').as_stubbed_const } it 'reads the correct files from local storage' do files_to_upload.each do |file_name| expect(file).to receive(:read).with(file_name) end subject.upload_files(files_to_upload: files_to_upload) end it 'uploads files to the correct path in remote storage' do expect(s3_client).to receive(:upload_file).with('foobar', 'ABCDEFG/certs/development/ABCDEFG.cer', 'body', 'private') expect(s3_client).to receive(:upload_file).with('foobar', 'ABCDEFG/certs/development/ABCDEFG.p12', 'body', 'private') subject.upload_files(files_to_upload: files_to_upload) end it 'uploads files with s3_object_prefix if set' do allow(subject).to receive(:s3_object_prefix).and_return('123456/') expect(s3_client).to receive(:upload_file).with('foobar', '123456/ABCDEFG/certs/development/ABCDEFG.cer', 'body', 'private') expect(s3_client).to receive(:upload_file).with('foobar', '123456/ABCDEFG/certs/development/ABCDEFG.p12', 'body', 'private') subject.upload_files(files_to_upload: files_to_upload) end end describe '#delete_files' do let(:files_to_upload) do [ "#{working_directory}/ABCDEFG/certs/development/ABCDEFG.cer", "#{working_directory}/ABCDEFG/certs/development/ABCDEFG.p12" ] end let(:s3_client) { double(delete_file: true) } it 'deletes files with correct paths' do expect(s3_client).to receive(:delete_file).with('foobar', 'ABCDEFG/certs/development/ABCDEFG.cer') expect(s3_client).to receive(:delete_file).with('foobar', 'ABCDEFG/certs/development/ABCDEFG.p12') subject.delete_files(files_to_delete: files_to_upload) end it 'deletes files with s3_object_prefix if set' do allow(subject).to receive(:s3_object_prefix).and_return('123456/') expect(s3_client).to receive(:delete_file).with('foobar', '123456/ABCDEFG/certs/development/ABCDEFG.cer') expect(s3_client).to receive(:delete_file).with('foobar', '123456/ABCDEFG/certs/development/ABCDEFG.p12') subject.delete_files(files_to_delete: files_to_upload) end end describe '#download' do let(:files_to_download) do [ instance_double('Aws::S3::Object', key: 'TEAMID1/certs/development/CERTID1.cer'), instance_double('Aws::S3::Object', key: 'TEAMID1/certs/development/CERTID1.p12'), instance_double('Aws::S3::Object', key: 'TEAMID2/certs/development/CERTID2.cer'), instance_double('Aws::S3::Object', key: 'TEAMID2/certs/development/CERTID2.p12') ] end let(:bucket) { instance_double('Aws::S3::Bucket') } let(:s3_client) { instance_double('Fastlane::Helper::S3ClientHelper', find_bucket!: bucket, download_file: true) } def stub_bucket_content(objects: files_to_download) allow(bucket).to receive(:objects) do |options| objects.select { |file_object| file_object.key.start_with?(options[:prefix] || '') } end end before { class_double('FileUtils', mkdir_p: true).as_stubbed_const } it 'downloads to correct working directory' do stub_bucket_content files_to_download.each do |file_object| expect(s3_client).to receive(:download_file).with('foobar', file_object.key, "#{working_directory}/#{file_object.key}") end subject.download end it 'only downloads files specific to the provided team' do stub_bucket_content allow(subject).to receive(:team_id).and_return('TEAMID2') files_to_download.each do |file_object| if file_object.key.start_with?('TEAMID2') expect(s3_client).to receive(:download_file).with('foobar', file_object.key, "#{working_directory}/#{file_object.key}") else expect(s3_client).not_to receive(:download_file).with('foobar', file_object.key, anything) end end subject.download end it 'downloads files and strips the s3_object_prefix for working_directory path' do allow(subject).to receive(:s3_object_prefix).and_return('123456/') prefixed_objects = files_to_download.map do |obj| instance_double('Aws::S3::Object', key: "123456/#{obj.key}", download_file: true) end stub_bucket_content(objects: prefixed_objects) prefixed_objects.each do |file_object| expect(s3_client).to receive(:download_file).with('foobar', file_object.key, "#{working_directory}/#{file_object.key.delete_prefix('123456/')}") end subject.download end it 'downloads only file-like objects and skips folder-like objects' do valid_object = files_to_download[0] invalid_object = instance_double('Aws::S3::Object', key: 'ABCDEFG/certs/development/') allow(s3_client).to receive_message_chain(:find_bucket!, :objects).and_return([valid_object, invalid_object]) expect(s3_client).to receive(:download_file).with('foobar', valid_object.key, "#{working_directory}/#{valid_object.key}") expect(s3_client).not_to receive(:download_file).with('foobar', invalid_object.key, anything) subject.download end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/storage/git_storage_spec.rb
match/spec/storage/git_storage_spec.rb
require_relative 'git_storage_spec_helper' describe Match do describe Match::Storage::GitStorage do let(:git_url) { "https://github.com/fastlane/fastlane/tree/master/certificates" } let(:git_branch) { "test" } before(:each) do @path = Dir.mktmpdir # to have access to the actual path allow(Dir).to receive(:mktmpdir).and_return(@path) end describe "#generate_commit_message" do it "works" do storage = Match::Storage::GitStorage.new( type: "appstore", platform: "ios" ) result = storage.generate_commit_message expect(result).to eq("[fastlane] Updated appstore and platform ios") end end describe "#download" do describe "when no branch is specified" do it "checkouts the master branch" do # Override default "test" branch name. git_branch = "master" storage = Match::Storage::GitStorage.new( git_url: git_url ) clone_command = "git clone #{git_url.shellescape} #{@path.shellescape}" expect_command_execution(clone_command) expect_command_execution(branch_checkout_commands(git_branch)) storage.download expect(File.directory?(storage.working_directory)).to eq(true) expect(File.exist?(File.join(storage.working_directory, 'README.md'))).to eq(false) # because the README is being added when committing the changes end end describe "when using shallow_clone" do it "clones the repo with correct clone command" do storage = Match::Storage::GitStorage.new( git_url: git_url, branch: git_branch, # Test case: shallow_clone: true ) clone_command = "git clone #{git_url.shellescape} #{@path.shellescape} --depth 1 --no-single-branch" expect_command_execution(clone_command) expect_command_execution(branch_checkout_commands(git_branch)) storage.download expect(File.directory?(storage.working_directory)).to eq(true) expect(File.exist?(File.join(storage.working_directory, 'README.md'))).to eq(false) # because the README is being added when committing the changes end end describe "when using shallow_clone and clone_branch_directly" do it "clones the repo with correct clone command" do storage = Match::Storage::GitStorage.new( git_url: git_url, branch: git_branch, # Test case: clone_branch_directly: true, shallow_clone: true ) clone_command = "git clone #{git_url.shellescape} #{@path.shellescape} --depth 1 -b #{git_branch} --single-branch" expect_command_execution(clone_command) expect_command_execution(branch_checkout_commands(git_branch)) storage.download expect(File.directory?(storage.working_directory)).to eq(true) expect(File.exist?(File.join(storage.working_directory, 'README.md'))).to eq(false) # because the README is being added when committing the changes end end describe "when using clone_branch_directly" do it "clones the repo with correct clone command" do storage = Match::Storage::GitStorage.new( git_url: git_url, branch: git_branch, # Test case: clone_branch_directly: true ) clone_command = "git clone #{git_url.shellescape} #{@path.shellescape} -b #{git_branch} --single-branch" expect_command_execution(clone_command) expect_command_execution(branch_checkout_commands(git_branch)) storage.download expect(File.directory?(storage.working_directory)).to eq(true) expect(File.exist?(File.join(storage.working_directory, 'README.md'))).to eq(false) # because the README is being added when committing the changes end end describe "when not using shallow_clone and clone_branch_directly" do it "clones the repo with correct clone command" do storage = Match::Storage::GitStorage.new( git_url: git_url, branch: git_branch, # Test case: clone_branch_directly: false, shallow_clone: false ) clone_command = "git clone #{git_url.shellescape} #{@path.shellescape}" expect_command_execution(clone_command) expect_command_execution(branch_checkout_commands(git_branch)) storage.download expect(File.directory?(storage.working_directory)).to eq(true) expect(File.exist?(File.join(storage.working_directory, 'README.md'))).to eq(false) # because the README is being added when committing the changes end end end describe "#save_changes" do describe "when skip_docs is true" do it "skips README file generation" do random_file_to_commit = "random_file_to_commit" storage = Match::Storage::GitStorage.new( type: "appstore", platform: "ios", git_url: git_url, branch: git_branch, skip_docs: true ) checkout_command = "git clone #{git_url.shellescape} #{@path.shellescape}" expect_command_execution(checkout_command) expect_command_execution(branch_checkout_commands(git_branch)) expected_commit_commands = [ # Stage new file for commit. "git add #{random_file_to_commit}", # Stage match_version.txt for commit. "git add match_version.txt", # Commit changes. "git commit -m " + '[fastlane] Updated appstore and platform ios'.shellescape, # Push changes to the remote origin. "git push origin #{git_branch}" ] expect_command_execution(expected_commit_commands) expect(storage).to receive(:clear_changes).and_return(nil) # so we can inspect the folder storage.download storage.save_changes!(files_to_commit: [random_file_to_commit]) expect(File.directory?(storage.working_directory)).to eq(true) expect(File.exist?(File.join(storage.working_directory, 'README.md'))).to eq(false) expect(File.read(File.join(storage.working_directory, 'match_version.txt'))).to eq(Fastlane::VERSION) end end end describe "#authentication" do describe "when using a private key file" do it "wraps the git command in ssh-agent shell" do expect(File).to receive(:file?).twice.and_return(true) private_key = "#{@path}/fastlane.match.id_dsa" clone_command = "ssh-agent bash -c 'ssh-add #{private_key.shellescape}; git clone #{git_url.shellescape} #{@path.shellescape}'" expect_command_execution(clone_command) expect_command_execution(branch_checkout_commands(git_branch)) storage = Match::Storage::GitStorage.new( git_url: git_url, branch: git_branch, git_private_key: private_key ) storage.download expect(File.directory?(storage.working_directory)).to eq(true) expect(File.exist?(File.join(storage.working_directory, 'README.md'))).to eq(false) # because the README is being added when committing the changes end end describe "when using a raw private key" do it "wraps the git command in ssh-agent shell" do expect(File).to receive(:file?).twice.and_return(false) private_key = "-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n" clone_command = "ssh-agent bash -c 'ssh-add - <<< \"#{private_key}\"; git clone #{git_url.shellescape} #{@path.shellescape}'" expect_command_execution(clone_command) expect_command_execution(branch_checkout_commands(git_branch)) storage = Match::Storage::GitStorage.new( git_url: git_url, branch: git_branch, git_private_key: private_key ) storage.download expect(File.directory?(storage.working_directory)).to eq(true) expect(File.exist?(File.join(storage.working_directory, 'README.md'))).to eq(false) # because the README is being added when committing the changes end end end describe "#ssh-agent utilities" do describe "when using a raw private key" do it "wraps any given command in ssh-agent shell" do given_command = "any random command" private_key = "-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n" storage = Match::Storage::GitStorage.new( git_private_key: private_key ) expected_command = "ssh-agent bash -c 'ssh-add - <<< \"#{private_key}\"; #{given_command}'" expect(storage.command_from_private_key(given_command)).to eq(expected_command) end end describe "when using a private key file" do it "wraps any given command in ssh-agent shell" do given_command = "any random command" private_key = "#{Dir.mktmpdir}/fastlane.match.id_dsa" storage = Match::Storage::GitStorage.new( git_private_key: private_key ) expected_command = "ssh-agent bash -c 'ssh-add - <<< \"#{File.expand_path(private_key).shellescape}\"; #{given_command}'" expect(storage.command_from_private_key(given_command)).to eq(expected_command) end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/storage/gitlab_secure_files_spec.rb
match/spec/storage/gitlab_secure_files_spec.rb
describe Match do describe Match::Storage::GitLabSecureFiles do subject { described_class.new(private_token: 'abc123', project_id: 'fake-project') } let(:working_directory) { '/fake/path/to/files' } before do allow(subject).to receive(:working_directory).and_return(working_directory) end describe '.configure' do describe 'api_v4_url' do it 'sets the value to CI_API_V4_URL when supplied' do stub_const('ENV', ENV.to_hash.merge('CI_API_V4_URL' => 'https://gitlab.com/api/v4')) storage = described_class.configure({}) expect(storage.api_v4_url).to eq('https://gitlab.com/api/v4') end it 'sets the value based on the gitlab_host param' do storage = described_class.configure(gitlab_host: 'http://gitlab.foo.com') expect(storage.api_v4_url).to eq('http://gitlab.foo.com/api/v4') end end end describe '#upload_files' do let(:files_to_upload) do [ "#{working_directory}/ABCDEFG/certs/development/ABCDEFG.cer", "#{working_directory}/ABCDEFG/certs/development/ABCDEFG.p12" ] end let!(:file) { class_double('File', read: 'body').as_stubbed_const } it 'reads the correct files from local storage' do files_to_upload.each do |file_name| expect(file).to receive(:open).with(file_name) end subject.upload_files(files_to_upload: files_to_upload) end it 'uploads files to the correct path in remote storage' do expect(subject.gitlab_client).to receive(:upload_file).with("#{working_directory}/ABCDEFG/certs/development/ABCDEFG.cer", 'ABCDEFG/certs/development/ABCDEFG.cer') expect(subject.gitlab_client).to receive(:upload_file).with("#{working_directory}/ABCDEFG/certs/development/ABCDEFG.p12", 'ABCDEFG/certs/development/ABCDEFG.p12') subject.upload_files(files_to_upload: files_to_upload) end end describe '#delete_files' do let(:file_names) do [ 'ABCDEFG/certs/development/ABCDEFG.cer', 'ABCDEFG/certs/development/ABCDEFG.p12' ] end let(:secure_files) do file_names.map.with_index do |file_name, index| Match::Storage::GitLab::SecureFile.new(file: { id: index, name: file_name }, client: subject.gitlab_client) end end let(:files_to_delete) do file_names.map do |file_name| "#{working_directory}/#{file_name}" end end it 'deletes files with correct paths' do secure_files.each_with_index do |secure_file, index| expect(subject.gitlab_client).to receive(:find_file_by_name).with(file_names[index]).and_return(secure_file) expect(secure_file.file.name).to eq(file_names[index]) expect(secure_file).to receive(:delete) end subject.delete_files(files_to_delete: files_to_delete) end end describe '#download' do let(:file_names) do [ 'ABCDEFG/certs/development/ABCDEFG.cer', 'ABCDEFG/certs/development/ABCDEFG.p12' ] end let(:secure_files) do file_names.map.with_index do |file_name, index| Match::Storage::GitLab::SecureFile.new(file: { id: index, name: file_name }, client: subject.gitlab_client) end end it 'downloads to correct working directory' do expect(subject.gitlab_client).to receive(:files).and_return(secure_files) secure_files.each_with_index do |secure_file, index| expect(secure_file.file.name).to eq(file_names[index]) expect(secure_file).to receive(:download).with(working_directory) end subject.download end end describe '#human_readable_description' do it 'returns the correct human readable description for the configured storage mode' do expect(subject.human_readable_description).to eq('GitLab Secure Files Storage [fake-project]') end end describe '#generate_matchfile_content' do it 'returns the correct match file contents for the configured storage mode and project path' do expect(FastlaneCore::UI).to receive(:input).once.and_return("fake-project") expect(FastlaneCore::UI).to receive(:input).once.and_return(nil) expect(subject.generate_matchfile_content).to eq('gitlab_project("fake-project")') end it 'returns the correct match file contents for the configured storage mode and project path and gitlab host' do expect(FastlaneCore::UI).to receive(:input).once.and_return("fake-project") expect(FastlaneCore::UI).to receive(:input).once.and_return("https://gitlab.example.com") expect(subject.generate_matchfile_content).to eq("gitlab_project(\"fake-project\")\ngitlab_host(\"https://gitlab.example.com\")") end end end describe 'Runner Configuration' do let(:available_options) { Match::Options.available_options } let(:base_options) { { storage_mode: 'gitlab_secure_files', gitlab_project: 'test/project', readonly: true, skip_provisioning_profiles: true, app_identifier: 'fake-app-identifier' } } let(:configuration) { FastlaneCore::Configuration.create(available_options, base_options) } let(:runner) { Match::Runner.new.run(configuration) } before do allow_any_instance_of(Match::Runner).to receive(:fetch_certificate) expect(Match::Storage::GitLab::Client).to receive_message_chain(:new, :prompt_for_access_token) expect(Match::Storage::GitLab::Client).to receive_message_chain(:new, :files).and_return([]) end it 'allows the optional job_token param' do base_options[:job_token] = 'foo' expect(runner).to be true expect(configuration.fetch(:storage_mode)).to eq('gitlab_secure_files') expect(configuration.fetch(:job_token)).to eq('foo') expect(configuration.fetch(:private_token)).to be nil end it 'allows the optional private_token param' do base_options[:private_token] = 'bar' expect(runner).to be true expect(configuration.fetch(:storage_mode)).to eq('gitlab_secure_files') expect(configuration.fetch(:job_token)).to be nil expect(configuration.fetch(:private_token)).to eq('bar') end it 'uses the PRIVATE_TOKEN ENV variable when supplied' do stub_const('ENV', ENV.to_hash.merge('PRIVATE_TOKEN' => 'env-private')) expect(runner).to be true expect(configuration.fetch(:storage_mode)).to eq('gitlab_secure_files') expect(configuration.fetch(:job_token)).to be nil expect(configuration.fetch(:private_token)).to eq('env-private') end it 'uses the CI_JOB_TOKEN ENV variable when supplied' do stub_const('ENV', ENV.to_hash.merge('CI_JOB_TOKEN' => 'env-job')) expect(runner).to be true expect(configuration.fetch(:storage_mode)).to eq('gitlab_secure_files') expect(configuration.fetch(:job_token)).to eq('env-job') expect(configuration.fetch(:private_token)).to be nil end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/storage/gitlab/client_spec.rb
match/spec/storage/gitlab/client_spec.rb
describe Match do describe Match::Storage::GitLab::Client do subject { described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', private_token: 'abc123' ) } describe '#base_url' do it 'returns the expected base_url for the given configuration' do expect(subject.base_url).to eq('https://gitlab.example.com/api/v4/projects/sample%2Fproject/secure_files') end end describe '#authentication_key' do it 'returns the job_token header key if job_token defined' do client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', job_token: 'abc123' ) expect(client.authentication_key).to eq('JOB-TOKEN') end it 'returns private_token header key if private_key defined and job_token is not defined' do client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', private_token: 'xyz123' ) expect(client.authentication_key).to eq('PRIVATE-TOKEN') end it 'returns the job_token header key if both job_token and private_token are defined, and prints a warning to the logs' do expect_any_instance_of(FastlaneCore::Shell).to receive(:important).with("JOB_TOKEN and PRIVATE_TOKEN both defined, using JOB_TOKEN to execute this job.") client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', job_token: 'abc123', private_token: 'xyz123' ) expect(client.authentication_key).to eq('JOB-TOKEN') end it 'returns nil if job_token and private_token are both undefined' do client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project' ) expect(client.authentication_key).to be_nil end end describe '#authentication_value' do it 'returns the job_token value if job_token defined' do client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', job_token: 'abc123' ) expect(client.authentication_value).to eq('abc123') end it 'returns private_token value if private_key defined and job_token is not defined' do client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', private_token: 'xyz123' ) expect(client.authentication_value).to eq('xyz123') end it 'returns the job_token value if both job_token and private_token are defined, and prints a warning to the logs' do expect_any_instance_of(FastlaneCore::Shell).to receive(:important).with("JOB_TOKEN and PRIVATE_TOKEN both defined, using JOB_TOKEN to execute this job.") client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', job_token: 'abc123', private_token: 'xyz123' ) expect(client.authentication_value).to eq('abc123') end it 'returns nil if job_token and private_token are both undefined' do client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project' ) expect(client.authentication_value).to be_nil end end describe '#files' do it 'returns an array of secure files for a project' do response = [ { id: 1, name: 'file1' }, { id: 2, name: 'file2' } ].to_json stub_request(:get, /gitlab\.example\.com/). with(headers: { 'PRIVATE-TOKEN' => 'abc123' }). to_return(status: 200, body: response) files = subject.files expect(files.count).to be(2) expect(files.first.file.name).to eq('file1') end it 'returns an empty array if there are results' do stub_request(:get, /gitlab\.example\.com/). with(headers: { 'PRIVATE-TOKEN' => 'abc123' }). to_return(status: 200, body: [].to_json) expect(subject.files.count).to be(0) end it 'requests 100 files from the API' do stub_request(:get, /gitlab\.example\.com/). to_return(status: 200, body: [].to_json) files = subject.files assert_requested(:get, /gitlab.example.com/, query: "per_page=100") end it 'raises an exception for a non-json response' do stub_request(:get, /gitlab\.example\.com/). with(headers: { 'PRIVATE-TOKEN' => 'abc123' }). to_return(status: 200, body: 'foo') expect { subject.files }.to raise_error(JSON::ParserError) end end describe '#prompt_for_access_token' do it 'prompts the users for an access token if authentication is not supplied' do client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project' ) expect(UI).to receive(:input).with('Please supply a GitLab personal or project access token: ') client.prompt_for_access_token end it 'does not prompt the user for an access token when a job token is supplied' do client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', job_token: 'abc123' ) expect(UI).not_to receive(:input) client.prompt_for_access_token end it 'does not prompt the user for an access token when a private token is supplied' do client = described_class.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', private_token: 'xyz123' ) expect(UI).not_to receive(:input) client.prompt_for_access_token end end def error_response_formatter(string, file = nil) if file "GitLab storage error: #{string} (File: #{file}, API: https://gitlab.example.com/api/v4)" else "GitLab storage error: #{string} (API: https://gitlab.example.com/api/v4)" end end describe '#handle_response_error' do it 'returns a non-fatal error message when the file name has already been taken' do expected_error = "foo already exists in GitLab project sample/project, file not uploaded" expected_error_type = :error response_body = { message: { name: ["has already been taken" ] } }.to_json response = OpenStruct.new(code: "400", body: response_body) target_file = 'foo' expect(UI).to receive(expected_error_type).with(error_response_formatter(expected_error, target_file)) subject.handle_response_error(response, target_file) end it 'returns a fatal error message when an unexpected JSON response is supplied with a target file' do expected_error = "500: {\"message\":{\"bar\":\"baz\"}}" expected_error_type = :user_error! response_body = { message: { bar: "baz" } }.to_json response = OpenStruct.new(code: "500", body: response_body) target_file = 'foo' expect(UI).to receive(expected_error_type).with(error_response_formatter(expected_error, target_file)) subject.handle_response_error(response, target_file) end it 'returns a fatal error message when an unexpected JSON response is supplied without a target file' do expected_error = "500: {\"message\":{\"bar\":\"baz\"}}" expected_error_type = :user_error! response_body = { message: { bar: "baz" } }.to_json response = OpenStruct.new(code: "500", body: response_body) target_file = 'foo' expect(UI).to receive(expected_error_type).with(error_response_formatter(expected_error)) subject.handle_response_error(response) end it 'returns a fatal error message when a non-JSON response is supplied with a target file' do expected_error = "500: a generic error message" expected_error_type = :user_error! response = OpenStruct.new(code: "500", body: "a generic error message") target_file = 'foo' expect(UI).to receive(expected_error_type).with(error_response_formatter(expected_error, target_file)) subject.handle_response_error(response, target_file) end it 'returns a fatal error message when a non-JSON response is supplied without a target file' do expected_error = "500: a generic error message" expected_error_type = :user_error! response = OpenStruct.new(code: "500", body: "a generic error message") target_file = 'foo' expect(UI).to receive(expected_error_type).with(error_response_formatter(expected_error)) subject.handle_response_error(response) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/storage/gitlab/secure_file_spec.rb
match/spec/storage/gitlab/secure_file_spec.rb
describe Match do describe Match::Storage::GitLab::SecureFile do let(:client) { Match::Storage::GitLab::Client.new( api_v4_url: 'https://gitlab.example.com/api/v4', project_id: 'sample/project', private_token: 'abc123' ) } subject { described_class.new( file: file, client: client ) } describe '#file_url' do context 'returns the expected file_url for the given configuration' do let(:file) { { id: 1 } } it { expect(subject.file_url).to eq('https://gitlab.example.com/api/v4/projects/sample%2Fproject/secure_files/1') } end end describe '#destination_file_path' do context 'strips the leading / if supplied' do let(:file) { { name: '/a/b/c/myfile' } } it { expect(subject.destination_file_path).to eq('a/b/c/') } end context 'strips the file name from the path' do let(:file) { { name: 'a/b/c/myfile' } } it { expect(subject.destination_file_path).to eq('a/b/c/') } end context 'returns an empty string if no path is given' do let(:file) { { name: 'myfile' } } it { expect(subject.destination_file_path).to eq('') } end end describe '#create_subfolders' do context 'with a supplied sub-folder path' do let(:file) { { name: 'a/b/c/myfile' } } it 'creates the necessary sub-folders' do expect(FileUtils).to receive(:mkdir_p).with(Dir.pwd + '/a/b/c/') subject.create_subfolders(Dir.pwd) end end context 'with no sub-folders in the path' do let(:file) { { name: 'myfile' } } it 'does not create subfolders' do expect(FileUtils).to receive(:mkdir_p).with(Dir.pwd + '/') subject.create_subfolders(Dir.pwd) end end end describe '#valid_checksum?' do let(:file) { { checksum: checksum } } context 'when the checksum supplied matches the checksum of the file ' do let(:file_contents) { 'hello' } let(:file) { { checksum: Digest::SHA256.hexdigest(file_contents) } } it 'returns true' do tempfile = Tempfile.new tempfile.write(file_contents) tempfile.close expect(subject.valid_checksum?(tempfile.path)).to be true end end context 'when the checksum supplied does not match the checksum of the file' do let(:file_contents) { 'hello' } let(:file) { { checksum: 'foo' } } it 'returns false' do tempfile = Tempfile.new tempfile.write(file_contents) tempfile.close expect(subject.valid_checksum?(tempfile.path)).to be false end end end describe '#delete' do let(:file) { { id: 1 } } it 'sends the delete request to the client' do url = URI(subject.file_url) expect_any_instance_of(Match::Storage::GitLab::Client).to receive(:execute_request).with(url, anything) subject.delete end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/encryption/encryption_spec.rb
match/spec/encryption/encryption_spec.rb
describe Match do describe Match::Encryption::MatchDataEncryption do let(:v1) { Match::Encryption::EncryptionV1.new } let(:v2) { Match::Encryption::EncryptionV2.new } let(:e) { Match::Encryption::MatchDataEncryption.new } let(:salt) { salt = SecureRandom.random_bytes(8) } let(:data) { "Hello World" } let(:password) { '2"QAHg@v(Qp{=*n^' } it "decrypts V1 Encryption with default hash" do encryption = v1.encrypt(data: data, password: password, salt: salt) encrypted_data = Match::Encryption::MatchDataEncryption::V1_PREFIX + salt + encryption[:encrypted_data] encoded_encrypted_data = Base64.encode64(encrypted_data) expect(e.decrypt(base64encoded_encrypted: encoded_encrypted_data, password: password)).to eq(data) end it "decrypts V1 Encryption with SHA256 hash when the decryption fails when given the default hash" do encryption = v1.encrypt(data: data, password: password, salt: salt, hash_algorithm: "SHA256") encrypted_data = Match::Encryption::MatchDataEncryption::V1_PREFIX + salt + encryption[:encrypted_data] encoded_encrypted_data = Base64.encode64(encrypted_data) eMock = double("EncryptionV1") # make it fail with the default hash allow(eMock).to receive(:decrypt).with(encrypted_data: encryption[:encrypted_data], password: password, salt: salt).and_raise(OpenSSL::Cipher::CipherError) allow(eMock).to receive(:decrypt).with(encrypted_data: encryption[:encrypted_data], password: password, salt: salt, hash_algorithm: "SHA256").and_return(data) allow(Match::Encryption::EncryptionV1).to receive(:new).and_return(eMock) expect(e.decrypt(base64encoded_encrypted: encoded_encrypted_data, password: password)).to eq(data) end it "fails to decrypt V1 Encryption with SHA256 hash when the decryption doesn't fail when given the default hash" do encryption = v1.encrypt(data: data, password: password, salt: salt, hash_algorithm: "SHA256") encrypted_data = Match::Encryption::MatchDataEncryption::V1_PREFIX + salt + encryption[:encrypted_data] encoded_encrypted_data = Base64.encode64(encrypted_data) eMock = double("EncryptionV1") # make it return garbage garbage = "garbage" allow(eMock).to receive(:decrypt).with(encrypted_data: encryption[:encrypted_data], password: password, salt: salt).and_return(garbage) allow(Match::Encryption::EncryptionV1).to receive(:new).and_return(eMock) expect(e.decrypt(base64encoded_encrypted: encoded_encrypted_data, password: password)).to eq(garbage) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/spec/encryption/openssl_spec.rb
match/spec/encryption/openssl_spec.rb
describe Match do describe Match::Encryption::OpenSSL do before do @directory = Dir.mktmpdir profile_path = "./match/spec/fixtures/test.mobileprovision" FileUtils.cp(profile_path, @directory) @full_path = File.join(@directory, "test.mobileprovision") @content = File.binread(@full_path) @git_url = "https://github.com/fastlane/fastlane/tree/master/so_random" allow(Dir).to receive(:mktmpdir).and_return(@directory) stub_const('ENV', { "MATCH_PASSWORD" => '2"QAHg@v(Qp{=*n^' }) @e = Match::Encryption::OpenSSL.new( keychain_name: @git_url, working_directory: @directory ) end it "first encrypt, different content, then decrypt, initial content again" do @e.encrypt_files expect(File.binread(@full_path)).to_not(eq(@content)) @e.decrypt_files expect(File.binread(@full_path)).to eq(@content) end it "raises an exception if invalid password is passed" do stub_const('ENV', { "MATCH_PASSWORD" => '2"QAHg@v(Qp{=*n^' }) @e.encrypt_files expect(File.read(@full_path)).to_not(eq(@content)) stub_const('ENV', { "MATCH_PASSWORD" => "invalid" }) expect do @e.decrypt_files end.to raise_error("Invalid password passed via 'MATCH_PASSWORD'") end it "raises an exception if no password is supplied" do stub_const('ENV', { "MATCH_PASSWORD" => "" }) expect do @e.encrypt_files end.to raise_error("No password supplied") end it "doesn't raise an exception if no env var is supplied but custom password is" do stub_const('ENV', { "MATCH_PASSWORD" => "" }) expect do @e.encrypt_files(password: "some custom password") end.to_not(raise_error) end it "given a custom password argument, then it should be given precedence when encrypting file, even when MATCH_PASSWORD is set" do stub_const('ENV', { "MATCH_PASSWORD" => "something else" }) new_password = '2"QAHg@v(Qp{=*n^' @e.encrypt_files(password: new_password) expect(File.binread(@full_path)).to_not(eq(@content)) stub_const('ENV', { "MATCH_PASSWORD" => new_password }) @e.decrypt_files expect(File.binread(@full_path)).to eq(@content) end describe "behavior of force_legacy_encryption parameter" do before do @match_encryption_double = instance_double(Match::Encryption::MatchFileEncryption) expect(Match::Encryption::MatchFileEncryption) .to(receive(:new)) .and_return(@match_encryption_double) end it "defaults to false and uses v2 encryption" do expect(@match_encryption_double) .to(receive(:encrypt)) .with(file_path: anything, password: anything, version: 2) @e.encrypt_files end it "uses v1 when force_legacy_encryption is true" do enc = Match::Encryption::OpenSSL.new( keychain_name: @git_url, working_directory: @directory, force_legacy_encryption: true ) expect(@match_encryption_double) .to(receive(:encrypt)) .with(file_path: anything, password: anything, version: 1) enc.encrypt_files end it "uses v2 when force_legacy_encryption is false" do enc = Match::Encryption::OpenSSL.new( keychain_name: @git_url, working_directory: @directory, force_legacy_encryption: false ) expect(@match_encryption_double) .to(receive(:encrypt)) .with(file_path: anything, password: anything, version: 2) enc.encrypt_files end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match.rb
match/lib/match.rb
require_relative 'match/options' require_relative 'match/runner' require_relative 'match/nuke' require_relative 'match/utils' require_relative 'match/table_printer' require_relative 'match/generator' require_relative 'match/setup' require_relative 'match/spaceship_ensure' require_relative 'match/change_password' require_relative 'match/migrate' require_relative 'match/importer' require_relative 'match/storage' require_relative 'match/encryption' require_relative 'match/module' require_relative 'match/portal_cache' require_relative 'match/portal_fetcher' require_relative 'match/profile_includes'
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/storage.rb
match/lib/match/storage.rb
require_relative 'storage/interface' require_relative 'storage/git_storage' require_relative 'storage/google_cloud_storage' require_relative 'storage/s3_storage' require_relative 'storage/gitlab_secure_files' module Match module Storage class << self def backends @backends ||= { "git" => lambda { |params| return Storage::GitStorage.configure({ type: params[:type], platform: params[:platform], git_url: params[:git_url], shallow_clone: params[:shallow_clone], skip_docs: params[:skip_docs], git_branch: params[:git_branch], git_full_name: params[:git_full_name], git_user_email: params[:git_user_email], clone_branch_directly: params[:clone_branch_directly], git_basic_authorization: params[:git_basic_authorization], git_bearer_authorization: params[:git_bearer_authorization], git_private_key: params[:git_private_key] }) }, "google_cloud" => lambda { |params| return Storage::GoogleCloudStorage.configure({ type: params[:type], platform: params[:platform], google_cloud_bucket_name: params[:google_cloud_bucket_name], google_cloud_keys_file: params[:google_cloud_keys_file], google_cloud_project_id: params[:google_cloud_project_id], readonly: params[:readonly], username: params[:username], team_id: params[:team_id], team_name: params[:team_name], api_key_path: params[:api_key_path], api_key: params[:api_key], skip_google_cloud_account_confirmation: params[:skip_google_cloud_account_confirmation] }) }, "s3" => lambda { |params| return Storage::S3Storage.configure({ s3_region: params[:s3_region], s3_access_key: params[:s3_access_key], s3_secret_access_key: params[:s3_secret_access_key], s3_bucket: params[:s3_bucket], s3_object_prefix: params[:s3_object_prefix], readonly: params[:readonly], username: params[:username], team_id: params[:team_id], team_name: params[:team_name], api_key_path: params[:api_key_path], api_key: params[:api_key] }) }, "gitlab_secure_files" => lambda { |params| return Storage::GitLabSecureFiles.configure({ gitlab_host: params[:gitlab_host], gitlab_project: params[:gitlab_project], git_url: params[:git_url], # enables warning about unnecessary git_url job_token: params[:job_token], private_token: params[:private_token], readonly: params[:readonly], username: params[:username], team_id: params[:team_id], team_name: params[:team_name], api_key_path: params[:api_key_path], api_key: params[:api_key] }) } } end def register_backend(type: nil, storage_class: nil, &configurator) UI.user_error!("No type specified for storage backend") if type.nil? normalized_name = type.to_s UI.message("Replacing Match::Encryption backend for type '#{normalized_name}'") if backends.include?(normalized_name) if configurator @backends[normalized_name] = configurator elsif storage_class @backends[normalized_name] = ->(params) { return storage_class.configure(params) } else UI.user_error!("Specify either a `storage_class` or a configuration block when registering a storage backend") end end def from_params(params) storage_mode = params[:storage_mode] configurator = backends[storage_mode.to_s] return configurator.call(params) if configurator UI.user_error!("No storage backend for storage mode '#{storage_mode}'") end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/portal_fetcher.rb
match/lib/match/portal_fetcher.rb
require 'fastlane_core/provisioning_profile' require 'spaceship/client' require 'spaceship/connect_api/models/profile' module Match class Portal module Fetcher def self.profiles(profile_type:, needs_profiles_devices: false, needs_profiles_certificate_content: false, name: nil) includes = ['bundleId'] if needs_profiles_devices includes += ['devices', 'certificates'] end if needs_profiles_certificate_content includes += ['certificates'] end profiles = Spaceship::ConnectAPI::Profile.all( filter: { profileType: profile_type, name: name }.compact, includes: includes.uniq.join(',') ) profiles end def self.certificates(platform:, profile_type:, additional_cert_types:) require 'sigh' certificate_types = Sigh.certificate_types_for_profile_and_platform(platform: platform, profile_type: profile_type) additional_cert_types ||= [] additional_cert_types.map! do |cert_type| case Match.cert_type_sym(cert_type) when :mac_installer_distribution Spaceship::ConnectAPI::Certificate::CertificateType::MAC_INSTALLER_DISTRIBUTION when :developer_id_installer Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_INSTALLER end end certificate_types += additional_cert_types filter = { certificateType: certificate_types.uniq.sort.join(',') } unless certificate_types.empty? certificates = Spaceship::ConnectAPI::Certificate.all( filter: filter ).select(&:valid?) certificates end def self.devices(platform: nil, include_mac_in_profiles: false) devices = Spaceship::ConnectAPI::Device.devices_for_platform( platform: platform, include_mac_in_profiles: include_mac_in_profiles ) devices end def self.bundle_ids(bundle_id_identifiers: nil) filter = { identifier: bundle_id_identifiers.join(',') } if bundle_id_identifiers bundle_ids = Spaceship::ConnectAPI::BundleId.all( filter: filter ) bundle_ids end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/portal_cache.rb
match/lib/match/portal_cache.rb
require 'fastlane_core/provisioning_profile' require 'spaceship/client' require_relative 'portal_fetcher' module Match class Portal class Cache def self.build(params:, bundle_id_identifiers:) require_relative 'profile_includes' require 'sigh' profile_type = Sigh.profile_type_for_distribution_type( platform: params[:platform], distribution_type: params[:type] ) cache = Portal::Cache.new( platform: params[:platform], profile_type: profile_type, additional_cert_types: params[:additional_cert_types], bundle_id_identifiers: bundle_id_identifiers, needs_profiles_devices: ProfileIncludes.can_force_include_all_devices?(params: params, notify: true), needs_profiles_certificate_content: !ProfileIncludes.can_force_include_all_certificates?(params: params, notify: true), include_mac_in_profiles: params[:include_mac_in_profiles] ) return cache end attr_reader :platform, :profile_type, :bundle_id_identifiers, :additional_cert_types, :needs_profiles_devices, :needs_profiles_certificate_content, :include_mac_in_profiles def initialize(platform:, profile_type:, additional_cert_types:, bundle_id_identifiers:, needs_profiles_devices:, needs_profiles_certificate_content:, include_mac_in_profiles:) @platform = platform @profile_type = profile_type # Bundle Ids @bundle_id_identifiers = bundle_id_identifiers # Certs @additional_cert_types = additional_cert_types # Profiles @needs_profiles_devices = needs_profiles_devices @needs_profiles_certificate_content = needs_profiles_certificate_content # Devices @include_mac_in_profiles = include_mac_in_profiles end def portal_profile(stored_profile_path:, keychain_path:) parsed = FastlaneCore::ProvisioningProfile.parse(stored_profile_path, keychain_path) uuid = parsed["UUID"] portal_profile = self.profiles.detect { |i| i.uuid == uuid } portal_profile end def reset_certificates @certificates = nil end def forget_portal_profile(portal_profile) return unless @profiles && portal_profile @profiles -= [portal_profile] end def bundle_ids @bundle_ids ||= Match::Portal::Fetcher.bundle_ids( bundle_id_identifiers: @bundle_id_identifiers ) return @bundle_ids.dup end def certificates @certificates ||= Match::Portal::Fetcher.certificates( platform: @platform, profile_type: @profile_type, additional_cert_types: @additional_cert_types ) return @certificates.dup end def profiles @profiles ||= Match::Portal::Fetcher.profiles( profile_type: @profile_type, needs_profiles_devices: @needs_profiles_devices, needs_profiles_certificate_content: @needs_profiles_certificate_content ) return @profiles.dup end def devices @devices ||= Match::Portal::Fetcher.devices( platform: @platform, include_mac_in_profiles: @include_mac_in_profiles ) return @devices.dup end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/setup.rb
match/lib/match/setup.rb
require_relative 'module' require_relative 'storage' module Match class Setup def run(path, is_swift_fastfile: false) if is_swift_fastfile template = File.read("#{Match::ROOT}/lib/assets/MatchfileTemplate.swift") else template = File.read("#{Match::ROOT}/lib/assets/MatchfileTemplate") end storage_mode = UI.select( "fastlane match supports multiple storage modes, please select the one you want to use:", self.storage_options ) storage = Storage.from_params({ storage_mode: storage_mode }) specific_content = storage.generate_matchfile_content UI.crash!("Looks like `generate_matchfile_content` was `nil` for `#{storage_mode}`") if specific_content.nil? specific_content += "\n\n" if specific_content.length > 0 specific_content += "storage_mode(\"#{storage_mode}\")" template.gsub!("[[CONTENT]]", specific_content) File.write(path, template) UI.success("Successfully created '#{path}'. You can open the file using a code editor.") UI.important("You can now run `fastlane match development`, `fastlane match adhoc`, `fastlane match enterprise` and `fastlane match appstore`") UI.message("On the first run for each environment it will create the provisioning profiles and") UI.message("certificates for you. From then on, it will automatically import the existing profiles.") UI.message("For more information visit https://docs.fastlane.tools/actions/match/") end def storage_options return ["git", "google_cloud", "s3", "gitlab_secure_files"] end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/migrate.rb
match/lib/match/migrate.rb
require_relative 'spaceship_ensure' require_relative 'encryption' require_relative 'storage' require_relative 'module' require 'fileutils' module Match class Migrate def migrate(params) loaded_matchfile = params.load_configuration_file("Matchfile") ensure_parameters_are_valid(params) # We init the Google storage client before the git client # to ask for all the missing inputs *before* cloning the git repo google_cloud_storage = Storage.from_params({ storage_mode: "google_cloud", google_cloud_bucket_name: params[:google_cloud_bucket_name], google_cloud_keys_file: params[:google_cloud_keys_file], google_cloud_project_id: params[:google_cloud_project_id] }) git_storage = Storage.from_params({ storage_mode: "git", git_url: params[:git_url], shallow_clone: params[:shallow_clone], git_branch: params[:git_branch], clone_branch_directly: params[:clone_branch_directly] }) git_storage.download encryption = Encryption.for_storage_mode(params[:storage_mode], { git_url: params[:git_url], s3_bucket: params[:s3_bucket], s3_skip_encryption: params[:s3_skip_encryption], working_directory: git_storage.working_directory }) encryption.decrypt_files if encryption UI.success("Decrypted the git repo to '#{git_storage.working_directory}'") google_cloud_storage.download # Note how we always prefix the path in Google Cloud with the Team ID # while on Git we recommend using the git branch instead. As there is # no concept of branches in Google Cloud Storage (omg thanks), we use # the team id properly spaceship = SpaceshipEnsure.new(params[:username], params[:team_id], params[:team_name], api_token(params)) team_id = spaceship.team_id if team_id.to_s.empty? UI.user_error!("The `team_id` option is required. fastlane cannot automatically determine portal team id via the App Store Connect API (yet)") else UI.message("Detected team ID '#{team_id}' to use for Google Cloud Storage...") end files_to_commit = [] Dir.chdir(git_storage.working_directory) do Dir[File.join("**", "*")].each do |current_file| next if File.directory?(current_file) to_path = File.join(google_cloud_storage.working_directory, team_id, current_file) FileUtils.mkdir_p(File.expand_path("..", to_path)) if File.exist?(to_path) UI.user_error!("Looks like file already exists on Google Cloud Storage at path '#{to_path}', stopping the migration process. Please make sure the bucket is empty, or at least doesn't contain any files related to the same Team ID") end FileUtils.cp(current_file, to_path) files_to_commit << to_path end end google_cloud_storage.save_changes!(files_to_commit: files_to_commit) UI.success("Successfully migrated your code signing certificates and provisioning profiles to Google Cloud Storage") UI.success("Make sure to update your configuration to specify the `storage_mode`, as well as the bucket to use.") UI.message("") if loaded_matchfile UI.message("Update your Matchfile at path '#{loaded_matchfile.configfile_path}':") UI.message("") UI.command_output("\t\tstorage_mode \"google_cloud\"") UI.command_output("\t\tgoogle_cloud_bucket_name \"#{google_cloud_storage.bucket_name}\"") else UI.message("Update your Fastfile `match` call to include") UI.message("") UI.command_output("\t\tstorage_mode: \"google_cloud\",") UI.command_output("\t\tgoogle_cloud_bucket_name: \"#{google_cloud_storage.bucket_name}\",") end UI.message("") UI.success("You can also remove the `git_url`, as well as any other git related configurations from your Fastfile and Matchfile") UI.message("") UI.input("Please make sure to read the above and confirm with enter") ensure google_cloud_storage.clear_changes if google_cloud_storage git_storage.clear_changes if git_storage end def api_token(params) api_token = Spaceship::ConnectAPI::Token.from(hash: params[:api_key], filepath: params[:api_key_path]) return api_token end def ensure_parameters_are_valid(params) if params[:readonly] UI.user_error!("`fastlane match migrate` doesn't work in `readonly` mode") end if params[:storage_mode] != "git" UI.user_error!("`fastlane match migrate` only allows migration from `git` to `google_cloud` right now, looks like your currently selected `storage_mode` is '#{params[:storage_mode]}'") end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/options.rb
match/lib/match/options.rb
require 'fastlane_core/configuration/config_item' require 'fastlane/helper/lane_helper' require 'credentials_manager/appfile_config' require_relative 'module' module Match # rubocop:disable Metrics/ClassLength class Options # This is match specific, as users can append storage specific options def self.append_option(option) self.available_options # to ensure we created the initial `@available_options` array @available_options << option end def self.default_platform case Fastlane::Helper::LaneHelper.current_platform.to_s when "mac" "macos" else "ios" end end def self.available_options user = CredentialsManager::AppfileConfig.try_fetch_value(:apple_dev_portal_id) user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id) [ # main FastlaneCore::ConfigItem.new(key: :type, env_name: "MATCH_TYPE", description: "Define the profile type, can be #{Match.environments.join(', ')}", short_option: "-y", default_value: 'development', verify_block: proc do |value| unless Match.environments.include?(value) UI.user_error!("Unsupported environment #{value}, must be in #{Match.environments.join(', ')}") end end), FastlaneCore::ConfigItem.new(key: :additional_cert_types, env_name: "MATCH_ADDITIONAL_CERT_TYPES", description: "Create additional cert types needed for macOS installers (valid values: mac_installer_distribution, developer_id_installer)", optional: true, type: Array, verify_block: proc do |values| types = %w(mac_installer_distribution developer_id_installer) UI.user_error!("Unsupported types, must be: #{types}") unless (values - types).empty? end), FastlaneCore::ConfigItem.new(key: :readonly, env_name: "MATCH_READONLY", description: "Only fetch existing certificates and profiles, don't generate new ones", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :generate_apple_certs, env_name: "MATCH_GENERATE_APPLE_CERTS", description: "Create a certificate type for Xcode 11 and later (Apple Development or Apple Distribution)", type: Boolean, default_value: FastlaneCore::Helper.mac? && FastlaneCore::Helper.xcode_at_least?('11'), default_value_dynamic: true), FastlaneCore::ConfigItem.new(key: :skip_provisioning_profiles, env_name: "MATCH_SKIP_PROVISIONING_PROFILES", description: "Skip syncing provisioning profiles", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :app_identifier, short_option: "-a", env_name: "MATCH_APP_IDENTIFIER", description: "The bundle identifier(s) of your app (comma-separated string or array of strings)", type: Array, # we actually allow String and Array here skip_type_validation: true, code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier), default_value_dynamic: true), # App Store Connect API FastlaneCore::ConfigItem.new(key: :api_key_path, env_names: ["SIGH_API_KEY_PATH", "APP_STORE_CONNECT_API_KEY_PATH"], description: "Path to your App Store Connect API Key JSON file (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-json-file)", optional: true, conflicting_options: [:api_key], verify_block: proc do |value| UI.user_error!("Couldn't find API key JSON file at path '#{value}'") unless File.exist?(value) end), FastlaneCore::ConfigItem.new(key: :api_key, env_names: ["SIGH_API_KEY", "APP_STORE_CONNECT_API_KEY"], description: "Your App Store Connect API Key information (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-hash-option)", type: Hash, optional: true, sensitive: true, conflicting_options: [:api_key_path]), # Apple ID FastlaneCore::ConfigItem.new(key: :username, short_option: "-u", env_name: "MATCH_USERNAME", description: "Your Apple ID Username", optional: true, default_value: user, default_value_dynamic: true), FastlaneCore::ConfigItem.new(key: :team_id, short_option: "-b", env_name: "FASTLANE_TEAM_ID", description: "The ID of your Developer Portal team if you're in multiple teams", optional: true, code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_id), default_value_dynamic: true), FastlaneCore::ConfigItem.new(key: :team_name, short_option: "-l", env_name: "FASTLANE_TEAM_NAME", description: "The name of your Developer Portal team if you're in multiple teams", optional: true, code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_name), default_value_dynamic: true), # Storage FastlaneCore::ConfigItem.new(key: :storage_mode, env_name: "MATCH_STORAGE_MODE", description: "Define where you want to store your certificates", short_option: "-q", default_value: 'git', verify_block: proc do |value| unless Match.storage_modes.include?(value) UI.user_error!("Unsupported storage_mode #{value}, must be in #{Match.storage_modes.join(', ')}") end end), # Storage: Git FastlaneCore::ConfigItem.new(key: :git_url, env_name: "MATCH_GIT_URL", description: "URL to the git repo containing all the certificates", optional: false, short_option: "-r"), FastlaneCore::ConfigItem.new(key: :git_branch, env_name: "MATCH_GIT_BRANCH", description: "Specific git branch to use", default_value: 'master'), FastlaneCore::ConfigItem.new(key: :git_full_name, env_name: "MATCH_GIT_FULL_NAME", description: "git user full name to commit", optional: true, default_value: nil), FastlaneCore::ConfigItem.new(key: :git_user_email, env_name: "MATCH_GIT_USER_EMAIL", description: "git user email to commit", optional: true, default_value: nil), FastlaneCore::ConfigItem.new(key: :shallow_clone, env_name: "MATCH_SHALLOW_CLONE", description: "Make a shallow clone of the repository (truncate the history to 1 revision)", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :clone_branch_directly, env_name: "MATCH_CLONE_BRANCH_DIRECTLY", description: "Clone just the branch specified, instead of the whole repo. This requires that the branch already exists. Otherwise the command will fail", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :git_basic_authorization, env_name: "MATCH_GIT_BASIC_AUTHORIZATION", sensitive: true, description: "Use a basic authorization header to access the git repo (e.g.: access via HTTPS, GitHub Actions, etc), usually a string in Base64", conflicting_options: [:git_bearer_authorization, :git_private_key], optional: true, default_value: nil), FastlaneCore::ConfigItem.new(key: :git_bearer_authorization, env_name: "MATCH_GIT_BEARER_AUTHORIZATION", sensitive: true, description: "Use a bearer authorization header to access the git repo (e.g.: access to an Azure DevOps repository), usually a string in Base64", conflicting_options: [:git_basic_authorization, :git_private_key], optional: true, default_value: nil), FastlaneCore::ConfigItem.new(key: :git_private_key, env_name: "MATCH_GIT_PRIVATE_KEY", sensitive: true, description: "Use a private key to access the git repo (e.g.: access to GitHub repository via Deploy keys), usually a id_rsa named file or the contents hereof", conflicting_options: [:git_basic_authorization, :git_bearer_authorization], optional: true, default_value: nil), # Storage: Google Cloud FastlaneCore::ConfigItem.new(key: :google_cloud_bucket_name, env_name: "MATCH_GOOGLE_CLOUD_BUCKET_NAME", description: "Name of the Google Cloud Storage bucket to use", optional: true), FastlaneCore::ConfigItem.new(key: :google_cloud_keys_file, env_name: "MATCH_GOOGLE_CLOUD_KEYS_FILE", description: "Path to the gc_keys.json file", optional: true, verify_block: proc do |value| UI.user_error!("Could not find keys file at path '#{File.expand_path(value)}'") unless File.exist?(value) end), FastlaneCore::ConfigItem.new(key: :google_cloud_project_id, env_name: "MATCH_GOOGLE_CLOUD_PROJECT_ID", description: "ID of the Google Cloud project to use for authentication", optional: true), FastlaneCore::ConfigItem.new(key: :skip_google_cloud_account_confirmation, env_name: "MATCH_SKIP_GOOGLE_CLOUD_ACCOUNT_CONFIRMATION", description: "Skips confirming to use the system google account", type: Boolean, default_value: false), # Storage: S3 FastlaneCore::ConfigItem.new(key: :s3_region, env_name: "MATCH_S3_REGION", description: "Name of the S3 region", optional: true), FastlaneCore::ConfigItem.new(key: :s3_access_key, env_name: "MATCH_S3_ACCESS_KEY", description: "S3 access key", optional: true), FastlaneCore::ConfigItem.new(key: :s3_secret_access_key, env_name: "MATCH_S3_SECRET_ACCESS_KEY", description: "S3 secret access key", sensitive: true, optional: true), FastlaneCore::ConfigItem.new(key: :s3_bucket, env_name: "MATCH_S3_BUCKET", description: "Name of the S3 bucket", optional: true), FastlaneCore::ConfigItem.new(key: :s3_object_prefix, env_name: "MATCH_S3_OBJECT_PREFIX", description: "Prefix to be used on all objects uploaded to S3", optional: true), FastlaneCore::ConfigItem.new(key: :s3_skip_encryption, env_name: "MATCH_S3_SKIP_ENCRYPTION", description: "Skip encryption of all objects uploaded to S3. WARNING: only enable this on S3 buckets with sufficiently restricted permissions and server-side encryption enabled. See https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingEncryption.html", type: Boolean, default_value: false), # Storage: GitLab Secure Files FastlaneCore::ConfigItem.new(key: :gitlab_project, env_name: "MATCH_GITLAB_PROJECT", description: "GitLab Project Path (i.e. 'gitlab-org/gitlab')", optional: true), FastlaneCore::ConfigItem.new(key: :gitlab_host, env_name: "MATCH_GITLAB_HOST", default_value: 'https://gitlab.com', description: "GitLab Host (i.e. 'https://gitlab.com')", optional: true), FastlaneCore::ConfigItem.new(key: :job_token, env_name: "CI_JOB_TOKEN", description: "GitLab CI_JOB_TOKEN", optional: true), FastlaneCore::ConfigItem.new(key: :private_token, env_name: "PRIVATE_TOKEN", description: "GitLab Access Token", optional: true), # Keychain FastlaneCore::ConfigItem.new(key: :keychain_name, short_option: "-s", env_name: "MATCH_KEYCHAIN_NAME", description: "Keychain the items should be imported to", default_value: "login.keychain"), FastlaneCore::ConfigItem.new(key: :keychain_password, short_option: "-p", env_name: "MATCH_KEYCHAIN_PASSWORD", sensitive: true, description: "This might be required the first time you access certificates on a new mac. For the login/default keychain this is your macOS account password", optional: true), # settings FastlaneCore::ConfigItem.new(key: :force, env_name: "MATCH_FORCE", description: "Renew the provisioning profiles every time you run match", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :force_for_new_devices, env_name: "MATCH_FORCE_FOR_NEW_DEVICES", description: "Renew the provisioning profiles if the device count on the developer portal has changed. Ignored for profile types 'appstore' and 'developer_id'", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :include_mac_in_profiles, env_name: "MATCH_INCLUDE_MAC_IN_PROFILES", description: "Include Apple Silicon Mac devices in provisioning profiles for iOS/iPadOS apps", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :include_all_certificates, env_name: "MATCH_INCLUDE_ALL_CERTIFICATES", description: "Include all matching certificates in the provisioning profile. Works only for the 'development' provisioning profile type", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :certificate_id, env_name: "MATCH_CERTIFICATE_ID", description: "Select certificate by id. Useful if multiple certificates are stored in one place", type: String, optional: true), FastlaneCore::ConfigItem.new(key: :force_for_new_certificates, env_name: "MATCH_FORCE_FOR_NEW_CERTIFICATES", description: "Renew the provisioning profiles if the certificate count on the developer portal has changed. Works only for the 'development' provisioning profile type. Requires 'include_all_certificates' option to be 'true'", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :skip_confirmation, env_name: "MATCH_SKIP_CONFIRMATION", description: "Disables confirmation prompts during nuke, answering them with yes", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :safe_remove_certs, env_name: "MATCH_SAFE_REMOVE_CERTS", description: "Remove certs from repository during nuke without revoking them on the developer portal", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :skip_docs, env_name: "MATCH_SKIP_DOCS", description: "Skip generation of a README.md for the created git repository", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :platform, short_option: '-o', env_name: "MATCH_PLATFORM", description: "Set the provisioning profile's platform to work with (i.e. ios, tvos, macos, catalyst)", default_value: default_platform, default_value_dynamic: true, verify_block: proc do |value| value = value.to_s pt = %w(tvos ios macos catalyst) UI.user_error!("Unsupported platform, must be: #{pt}") unless pt.include?(value) end), FastlaneCore::ConfigItem.new(key: :derive_catalyst_app_identifier, env_name: "MATCH_DERIVE_CATALYST_APP_IDENTIFIER", description: "Enable this if you have the Mac Catalyst capability enabled and your project was created with Xcode 11.3 or earlier. Prepends 'maccatalyst.' to the app identifier for the provisioning profile mapping", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :template_name, env_name: "MATCH_PROVISIONING_PROFILE_TEMPLATE_NAME", description: "The name of provisioning profile template. If the developer account has provisioning profile templates (aka: custom entitlements), the template name can be found by inspecting the Entitlements drop-down while creating/editing a provisioning profile (e.g. \"Apple Pay Pass Suppression Development\")", optional: true, deprecated: "Removed since May 2025 on App Store Connect API OpenAPI v3.8.0 - Learn more: https://docs.fastlane.tools/actions/match/#managed-capabilities", default_value: nil), FastlaneCore::ConfigItem.new(key: :profile_name, env_name: "MATCH_PROVISIONING_PROFILE_NAME", description: "A custom name for the provisioning profile. This will replace the default provisioning profile name if specified", optional: true, default_value: nil), FastlaneCore::ConfigItem.new(key: :fail_on_name_taken, env_name: "MATCH_FAIL_ON_NAME_TAKEN", description: "Should the command fail if it was about to create a duplicate of an existing provisioning profile. It can happen due to issues on Apple Developer Portal, when profile to be recreated was not properly deleted first", optional: true, type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :skip_certificate_matching, env_name: "MATCH_SKIP_CERTIFICATE_MATCHING", description: "Set to true if there is no access to Apple developer portal but there are certificates, keys and profiles provided. Only works with match import action", optional: true, type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :output_path, env_name: "MATCH_OUTPUT_PATH", description: "Path in which to export certificates, key and profile", optional: true), FastlaneCore::ConfigItem.new(key: :skip_set_partition_list, short_option: "-P", env_name: "MATCH_SKIP_SET_PARTITION_LIST", description: "Skips setting the partition list (which can sometimes take a long time). Setting the partition list is usually needed to prevent Xcode from prompting to allow a cert to be used for signing", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :force_legacy_encryption, env_name: "MATCH_FORCE_LEGACY_ENCRYPTION", description: "Force encryption to use legacy cbc algorithm for backwards compatibility with older match versions", type: Boolean, default_value: false), # other FastlaneCore::ConfigItem.new(key: :verbose, env_name: "MATCH_VERBOSE", description: "Print out extra information and all commands", type: Boolean, default_value: false, verify_block: proc do |value| FastlaneCore::Globals.verbose = true if value end) ] end end # rubocop:enable Metrics/ClassLength end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/encryption.rb
match/lib/match/encryption.rb
require_relative 'encryption/interface' require_relative 'encryption/openssl' require_relative 'encryption/encryption' module Match module Encryption class << self def backends @backends ||= { "git" => lambda { |params| # OpenSSL is storage agnostic so this maps git_url # to keychain_name for the name of the keychain entry params[:keychain_name] = params[:git_url] return Encryption::OpenSSL.configure(params) }, "google_cloud" => lambda { |params| return nil }, "s3" => lambda { |params| params[:keychain_name] = params[:s3_bucket] return params[:s3_skip_encryption] ? nil : Encryption::OpenSSL.configure(params) }, "gitlab_secure_files" => lambda { |params| return nil } } end def register_backend(type: nil, encryption_class: nil, &configurator) UI.user_error!("No type specified for encryption backend") if type.nil? normalized_name = type.to_s UI.message("Replacing Match::Encryption backend for type '#{normalized_name}'") if backends.include?(normalized_name) if configurator @backends[normalized_name] = configurator elsif encryption_class @backends[normalized_name] = ->(params) { return encryption_class.configure(params) } else UI.user_error!("Specify either a `encryption_class` or a configuration block when registering a encryption backend") end end # Returns the class to be used for a given `storage_mode` def for_storage_mode(storage_mode, params) configurator = backends[storage_mode.to_s] return configurator.call(params) if configurator UI.user_error!("No encryption backend for storage mode '#{storage_mode}'") end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/utils.rb
match/lib/match/utils.rb
require 'fastlane_core/keychain_importer' require 'openssl' require_relative 'module' module Match class Utils def self.import(item_path, keychain, password: nil) keychain_path = FastlaneCore::Helper.keychain_path(keychain) FastlaneCore::KeychainImporter.import_file(item_path, keychain_path, keychain_password: password, output: FastlaneCore::Globals.verbose?) end # Fill in an environment variable, ready to be used in _xcodebuild_ def self.fill_environment(key, value) UI.important("Setting environment variable '#{key}' to '#{value}'") if FastlaneCore::Globals.verbose? ENV[key] = value end def self.environment_variable_name(app_identifier: nil, type: nil, platform: :ios) base_environment_variable_name(app_identifier: app_identifier, type: type, platform: platform).join("_") end def self.environment_variable_name_team_id(app_identifier: nil, type: nil, platform: :ios) (base_environment_variable_name(app_identifier: app_identifier, type: type, platform: platform) + ["team-id"]).join("_") end def self.environment_variable_name_profile_name(app_identifier: nil, type: nil, platform: :ios) (base_environment_variable_name(app_identifier: app_identifier, type: type, platform: platform) + ["profile-name"]).join("_") end def self.environment_variable_name_profile_path(app_identifier: nil, type: nil, platform: :ios) (base_environment_variable_name(app_identifier: app_identifier, type: type, platform: platform) + ["profile-path"]).join("_") end def self.environment_variable_name_certificate_name(app_identifier: nil, type: nil, platform: :ios) (base_environment_variable_name(app_identifier: app_identifier, type: type, platform: platform) + ["certificate-name"]).join("_") end def self.get_cert_info(cer_certificate) # can receive a certificate path or the file data begin if File.exist?(cer_certificate) cer_certificate = File.binread(cer_certificate) end rescue ArgumentError # cert strings have null bytes; suppressing output end cert = OpenSSL::X509::Certificate.new(cer_certificate) # openssl output: # subject= /UID={User ID}/CN={Certificate Name}/OU={Certificate User}/O={Organisation}/C={Country} cert_info = cert.subject.to_s.gsub(/\s*subject=\s*/, "").tr("/", "\n") out_array = cert_info.split("\n") openssl_keys_to_readable_keys = { 'UID' => 'User ID', 'CN' => 'Common Name', 'OU' => 'Organisation Unit', 'O' => 'Organisation', 'C' => 'Country', 'notBefore' => 'Start Datetime', 'notAfter' => 'End Datetime' } return out_array.map { |x| x.split(/=+/) if x.include?("=") } .compact .map { |k, v| [openssl_keys_to_readable_keys.fetch(k, k), v] } .push([openssl_keys_to_readable_keys.fetch("notBefore"), cert.not_before]) .push([openssl_keys_to_readable_keys.fetch("notAfter"), cert.not_after]) rescue => ex UI.error("get_cert_info: #{ex}") return {} end def self.is_cert_valid?(cer_certificate_path) cert = OpenSSL::X509::Certificate.new(File.binread(cer_certificate_path)) now = Time.now.utc return (now <=> cert.not_after) == -1 end def self.base_environment_variable_name(app_identifier: nil, type: nil, platform: :ios) if platform.to_s == :ios.to_s ["sigh", app_identifier, type] # We keep the ios profiles without the platform for backwards compatibility else ["sigh", app_identifier, type, platform.to_s] end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/nuke.rb
match/lib/match/nuke.rb
require 'terminal-table' require 'spaceship' require 'fastlane_core/provisioning_profile' require 'fastlane_core/print_table' require_relative 'module' require_relative 'storage' require_relative 'encryption' require 'tempfile' require 'base64' module Match # rubocop:disable Metrics/ClassLength class Nuke attr_accessor :params attr_accessor :type attr_accessor :safe_remove_certs attr_accessor :certs attr_accessor :profiles attr_accessor :files attr_accessor :storage attr_accessor :encryption def run(params, type: nil) self.params = params self.type = type update_optional_values_depending_on_storage_type(params) spaceship_login self.storage = Storage.from_params(params) self.storage.download # After the download was complete self.encryption = Encryption.for_storage_mode(params[:storage_mode], { git_url: params[:git_url], s3_bucket: params[:s3_bucket], s3_skip_encryption: params[:s3_skip_encryption], working_directory: storage.working_directory, force_legacy_encryption: params[:force_legacy_encryption] }) self.encryption.decrypt_files if self.encryption had_app_identifier = self.params.fetch(:app_identifier, ask: false) self.params[:app_identifier] = '' # we don't really need a value here FastlaneCore::PrintTable.print_values(config: params, hide_keys: [:app_identifier], title: "Summary for match nuke #{Fastlane::VERSION}") self.safe_remove_certs = params[:safe_remove_certs] || false prepare_list filter_by_cert print_tables if params[:readonly] UI.user_error!("`fastlane match nuke` doesn't delete anything when running with --readonly enabled") end if (self.certs + self.profiles + self.files).count > 0 unless params[:skip_confirmation] UI.error("---") remove_or_revoke_message = self.safe_remove_certs ? "remove" : "revoke" UI.error("Are you sure you want to completely delete and #{remove_or_revoke_message} all the") UI.error("certificates and delete provisioning profiles listed above? (y/n)") UI.error("Warning: By nuking distribution, both App Store and Ad Hoc profiles will be deleted") if type == "distribution" UI.error("Warning: The :app_identifier value will be ignored - this will delete all profiles for all your apps!") if had_app_identifier UI.error("---") print_safe_remove_certs_hint end if params[:skip_confirmation] || UI.confirm("Do you really want to nuke everything listed above?") nuke_it_now! UI.success("Successfully cleaned your account ♻️") else UI.success("Cancelled nuking #thanks 🏠 👨 ‍👩 ‍👧") end else UI.success("No relevant certificates or provisioning profiles found, nothing to nuke here :)") end ensure self.storage.clear_changes if self.storage end # Be smart about optional values here # Depending on the storage mode, different values are required def update_optional_values_depending_on_storage_type(params) if params[:storage_mode] != "git" params.option_for_key(:git_url).optional = true end end def spaceship_login if (api_token = Spaceship::ConnectAPI::Token.from(hash: params[:api_key], filepath: params[:api_key_path])) UI.message("Creating authorization token for App Store Connect API") Spaceship::ConnectAPI.token = api_token elsif !Spaceship::ConnectAPI.token.nil? UI.message("Using existing authorization token for App Store Connect API") else Spaceship::ConnectAPI.login(params[:username], use_portal: true, use_tunes: false, portal_team_id: params[:team_id], team_name: params[:team_name]) end if Spaceship::ConnectAPI.client.in_house? && (type == "distribution" || type == "enterprise") UI.error("---") UI.error("⚠️ Warning: This seems to be an Enterprise account!") unless self.safe_remove_certs UI.error("By nuking your account's distribution, all your apps deployed via ad-hoc will stop working!") if type == "distribution" UI.error("By nuking your account's enterprise, all your in-house apps will stop working!") if type == "enterprise" end UI.error("---") print_safe_remove_certs_hint UI.user_error!("Enterprise account nuke cancelled") unless UI.confirm("Do you really want to nuke your Enterprise account?") end end # Collect all the certs/profiles def prepare_list UI.message("Fetching certificates and profiles...") cert_type = Match.cert_type_sym(type) cert_types = [cert_type] prov_types = [] prov_types = [:development] if cert_type == :development prov_types = [:appstore, :adhoc, :developer_id] if cert_type == :distribution prov_types = [:enterprise] if cert_type == :enterprise # Get all iOS and macOS profile self.profiles = [] prov_types.each do |prov_type| types = Match.profile_types(prov_type) self.profiles += Spaceship::ConnectAPI::Profile.all(filter: { profileType: types.join(",") }, includes: "certificates") end # Gets the main and additional cert types cert_types += (params[:additional_cert_types] || []).map do |ct| Match.cert_type_sym(ct) end # Gets all the certs form the cert types self.certs = [] self.certs += cert_types.map do |ct| certificate_type(ct).flat_map do |cert| Spaceship::ConnectAPI::Certificate.all(filter: { certificateType: cert }) end end.flatten # Finds all the .cer and .p12 files in the file storage certs = [] keys = [] cert_types.each do |ct| certs += self.storage.list_files(file_name: ct.to_s, file_ext: "cer") keys += self.storage.list_files(file_name: ct.to_s, file_ext: "p12") end # Finds all the iOS and macOS profiles in the file storage profiles = [] prov_types.each do |prov_type| profiles += self.storage.list_files(file_name: prov_type.to_s, file_ext: "mobileprovision") profiles += self.storage.list_files(file_name: prov_type.to_s, file_ext: "provisionprofile") end self.files = certs + keys + profiles end def filter_by_cert # Force will continue to revoke and delete all certificates and profiles return if self.params[:force] || !UI.interactive? return if self.certs.count < 2 # Print table showing certificates that can be revoked puts("") rows = self.certs.each_with_index.collect do |cert, i| cert_expiration = cert.expiration_date.nil? ? "Unknown" : Time.parse(cert.expiration_date).strftime("%Y-%m-%d") [i + 1, cert.name, cert.id, cert.class.to_s.split("::").last, cert_expiration] end puts(Terminal::Table.new({ title: "Certificates that can be #{removed_or_revoked_message}".green, headings: ["Option", "Name", "ID", "Type", "Expires"], rows: FastlaneCore::PrintTable.transform_output(rows) })) puts("") UI.important("By default, all listed certificates and profiles will be nuked") if UI.confirm("Do you want to only nuke specific certificates and their associated profiles?") input_indexes = UI.input("Enter the \"Option\" number(s) from the table above? (comma-separated)").split(',') # Get certificates from option indexes self.certs = input_indexes.map do |index| self.certs[index.to_i - 1] end.compact if self.certs.empty? UI.user_error!("No certificates were selected based on option number(s) entered") end # Do profile selection logic cert_ids = self.certs.map(&:id) self.profiles = self.profiles.select do |profile| profile_cert_ids = profile.certificates.map(&:id) (cert_ids & profile_cert_ids).any? end # Do file selection logic self.files = self.files.select do |f| found = false ext = File.extname(f) filename = File.basename(f, ".*") # Attempt to find cert based on filename if ext == ".cer" || ext == ".p12" found ||= self.certs.any? do |cert| filename == cert.id.to_s end end # Attempt to find profile matched on UUIDs in profile if ext == ".mobileprovision" || ext == ".provisionprofile" storage_uuid = FastlaneCore::ProvisioningProfile.uuid(f) found ||= self.profiles.any? do |profile| tmp_file = Tempfile.new tmp_file.write(Base64.decode64(profile.profile_content)) tmp_file.close # Compare profile uuid in storage to profile uuid on developer portal portal_uuid = FastlaneCore::ProvisioningProfile.uuid(tmp_file.path) storage_uuid == portal_uuid end end found end end end # Print tables to ask the user def print_tables puts("") if self.certs.count > 0 rows = self.certs.collect do |cert| cert_expiration = cert.expiration_date.nil? ? "Unknown" : Time.parse(cert.expiration_date).strftime("%Y-%m-%d") [cert.name, cert.id, cert.class.to_s.split("::").last, cert_expiration] end puts(Terminal::Table.new({ title: "Certificates that are going to be #{removed_or_revoked_message}".green, headings: ["Name", "ID", "Type", "Expires"], rows: FastlaneCore::PrintTable.transform_output(rows) })) puts("") end if self.profiles.count > 0 rows = self.profiles.collect do |p| status = p.valid? ? p.profile_state.green : p.profile_state.red # Expires is sometimes nil expires = p.expiration_date ? Time.parse(p.expiration_date).strftime("%Y-%m-%d") : nil [p.name, p.id, status, p.profile_type, expires] end puts(Terminal::Table.new({ title: "Provisioning Profiles that are going to be revoked".green, headings: ["Name", "ID", "Status", "Type", "Expires"], rows: FastlaneCore::PrintTable.transform_output(rows) })) puts("") end if self.files.count > 0 rows = self.files.collect do |f| components = f.split(File::SEPARATOR)[-3..-1] # from "...1o7xtmh/certs/distribution/8K38XUY3AY.cer" to "distribution cert" file_type = components[0..1].reverse.join(" ")[0..-2] [file_type, components[2]] end puts(Terminal::Table.new({ title: "Files that are going to be deleted".green + "\n" + self.storage.human_readable_description, headings: ["Type", "File Name"], rows: rows })) puts("") end end def nuke_it_now! UI.header("Deleting #{self.profiles.count} provisioning profiles...") unless self.profiles.count == 0 self.profiles.each do |profile| UI.message("Deleting profile '#{profile.name}' (#{profile.id})...") begin profile.delete! rescue => ex UI.message(ex.to_s) end UI.success("Successfully deleted profile") end removing_or_revoking_message = self.safe_remove_certs ? "Removing" : "Revoking" UI.header("#{removing_or_revoking_message} #{self.certs.count} certificates...") unless self.certs.count == 0 self.certs.each do |cert| if self.safe_remove_certs UI.message("Certificate '#{cert.name}' (#{cert.id}) will be removed from repository without revoking it") next end UI.message("Revoking certificate '#{cert.name}' (#{cert.id})...") begin cert.delete! rescue => ex UI.message(ex.to_s) end UI.success("Successfully deleted certificate") end files_to_delete = delete_files! if self.files.count > 0 files_to_delete ||= [] self.encryption.encrypt_files if self.encryption if files_to_delete.count > 0 # Now we need to save all this to the storage too, if needed message = ["[fastlane]", "Nuked", "files", "for", type.to_s].join(" ") self.storage.save_changes!(files_to_commit: [], files_to_delete: files_to_delete, custom_message: message) else UI.message("Your storage had no files to be deleted. This happens when you run `nuke` with an empty storage. Nothing to be worried about!") end end private def delete_files! UI.header("Deleting #{self.files.count} files from the storage...") return self.files.collect do |file| UI.message("Deleting file '#{File.basename(file)}'...") # Check if the profile is installed on the local machine if file.end_with?("mobileprovision") parsed = FastlaneCore::ProvisioningProfile.parse(file) uuid = parsed["UUID"] path = Dir[File.join(FastlaneCore::ProvisioningProfile.profiles_path, "#{uuid}.mobileprovision")].last File.delete(path) if path end File.delete(file) UI.success("Successfully deleted file") file end end # The kind of certificate we're interested in def certificate_type(type) case type.to_sym when :mac_installer_distribution return [ Spaceship::ConnectAPI::Certificate::CertificateType::MAC_INSTALLER_DISTRIBUTION ] when :distribution return [ Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DISTRIBUTION, Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DISTRIBUTION, Spaceship::ConnectAPI::Certificate::CertificateType::DISTRIBUTION ] when :development return [ Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DEVELOPMENT, Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DEVELOPMENT, Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPMENT ] when :enterprise return [ Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DISTRIBUTION ] else raise "Unknown type '#{type}'" end end # Helpers for `safe_remove_certs` def print_safe_remove_certs_hint return if self.safe_remove_certs UI.important("Hint: You can use --safe_remove_certs option to remove certificates") UI.important("from repository without revoking them.") end def removed_or_revoked_message self.safe_remove_certs ? "removed" : "revoked" end end # rubocop:disable Metrics/ClassLength end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/spaceship_ensure.rb
match/lib/match/spaceship_ensure.rb
require 'spaceship' require_relative 'module' require_relative 'portal_fetcher' module Match # Ensures the certificate and profiles are also available on App Store Connect class SpaceshipEnsure attr_accessor :team_id def initialize(user, team_id, team_name, api_token) UI.message("Verifying that the certificate and profile are still valid on the Dev Portal...") if api_token UI.message("Creating authorization token for App Store Connect API") Spaceship::ConnectAPI.token = api_token self.team_id = team_id elsif !Spaceship::ConnectAPI.token.nil? UI.message("Using existing authorization token for App Store Connect API") self.team_id = team_id else # We'll try to manually fetch the password # to tell the user that a password is optional require 'credentials_manager/account_manager' keychain_entry = CredentialsManager::AccountManager.new(user: user) if keychain_entry.password(ask_if_missing: false).to_s.length == 0 UI.important("You can also run `fastlane match` in readonly mode to not require any access to the") UI.important("Developer Portal. This way you only share the keys and credentials") UI.command("fastlane match --readonly") UI.important("More information https://docs.fastlane.tools/actions/match/#access-control") end # Prompts select team if multiple teams and none specified Spaceship::ConnectAPI.login(user, use_portal: true, use_tunes: false, portal_team_id: team_id, team_name: team_name) self.team_id = Spaceship::ConnectAPI.client.portal_team_id end end # The team ID of the currently logged in team def team_id return @team_id end def bundle_identifier_exists(username: nil, app_identifier: nil, cached_bundle_ids: nil) search_bundle_ids = cached_bundle_ids || Match::Portal::Fetcher.bundle_ids(bundle_id_identifiers: [app_identifier]) found = search_bundle_ids.any? { |bundle_id| bundle_id.identifier == app_identifier } return if found require 'sigh/runner' Sigh::Runner.new.print_produce_command({ username: username, app_identifier: app_identifier }) UI.error("An app with that bundle ID needs to exist in order to create a provisioning profile for it") UI.error("================================================================") all_bundle_ids = Match::Portal::Fetcher.bundle_ids available_apps = all_bundle_ids.collect { |a| "#{a.identifier} (#{a.name})" } UI.message("Available apps:\n- #{available_apps.join("\n- ")}") UI.error("Make sure to run `fastlane match` with the same user and team every time.") UI.user_error!("Couldn't find bundle identifier '#{app_identifier}' for the user '#{username}'") end def certificates_exists(username: nil, certificate_ids: [], platform:, profile_type:, cached_certificates:) certificates = cached_certificates certificates ||= Match::Portal::Fetcher.certificates(platform: platform, profile_type: profile_type) certificates.each do |cert| certificate_ids.delete(cert.id) end return if certificate_ids.empty? certificate_ids.each do |certificate_id| UI.error("Certificate '#{certificate_id}' (stored in your storage) is not available on the Developer Portal") end UI.error("for the user #{username}") UI.error("Make sure to use the same user and team every time you run 'match' for this") UI.error("Git repository. This might be caused by revoking the certificate on the Dev Portal") UI.error("If missing certificate is a Developer ID Installer, you may need to auth with Apple ID instead of App Store API Key") UI.user_error!("To reset the certificates of your Apple account, you can use the `fastlane match nuke` feature, more information on https://docs.fastlane.tools/actions/match/") end def profile_exists(profile_type: nil, name: nil, username: nil, uuid: nil, cached_profiles: nil) profiles = cached_profiles profiles ||= Match::Portal::Fetcher.profiles(profile_type: profile_type, name: name) found = profiles.find do |profile| profile.uuid == uuid end unless found UI.error("Provisioning profile '#{uuid}' is not available on the Developer Portal for the user #{username}, fixing this now for you 🔨") return false end if found.valid? return found else UI.important("'#{found.name}' is available on the Developer Portal, however it's 'Invalid', fixing this now for you 🔨") # it's easier to just create a new one, than to repair an existing profile # it has the same effects anyway, including a new UUID of the provisioning profile found.delete! # return nil to re-download the new profile in runner.rb return nil end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/commands_generator.rb
match/lib/match/commands_generator.rb
require 'commander' require 'fastlane_core/configuration/configuration' require 'fastlane_core/ui/help_formatter' require_relative 'nuke' require_relative 'change_password' require_relative 'setup' require_relative 'runner' require_relative 'options' require_relative 'migrate' require_relative 'importer' require_relative 'storage' require_relative 'encryption' require_relative 'module' HighLine.track_eof = false module Match class CommandsGenerator include Commander::Methods def self.start self.new.run end def run program :name, 'match' program :version, Fastlane::VERSION program :description, Match::DESCRIPTION program :help, 'Author', 'Felix Krause <match@krausefx.com>' program :help, 'Website', 'https://fastlane.tools' program :help, 'Documentation', 'https://docs.fastlane.tools/actions/match/' program :help_formatter, FastlaneCore::HelpFormatter global_option('--verbose') { FastlaneCore::Globals.verbose = true } global_option('--env STRING[,STRING2]', String, 'Add environment(s) to use with `dotenv`') command :run do |c| c.syntax = 'fastlane match' c.description = Match::DESCRIPTION FastlaneCore::CommanderGenerator.new.generate(Match::Options.available_options, command: c) c.action do |args, options| if args.count > 0 FastlaneCore::UI.user_error!("Please run `fastlane match [type]`, allowed values: development, adhoc, enterprise or appstore") end params = FastlaneCore::Configuration.create(Match::Options.available_options, options.__hash__) params.load_configuration_file("Matchfile") Match::Runner.new.run(params) end end Match.environments.each do |type| command type do |c| c.syntax = "fastlane match #{type}" c.description = "Run match for a #{type} provisioning profile" FastlaneCore::CommanderGenerator.new.generate(Match::Options.available_options, command: c) c.action do |args, options| params = FastlaneCore::Configuration.create(Match::Options.available_options, options.__hash__) params.load_configuration_file("Matchfile") # this has to be done *before* overwriting the value params[:type] = type.to_s Match::Runner.new.run(params) end end end command :init do |c| c.syntax = 'fastlane match init' c.description = 'Create the Matchfile for you' c.action do |args, options| containing = FastlaneCore::Helper.fastlane_enabled_folder_path is_swift_fastfile = args.include?("swift") if is_swift_fastfile path = File.join(containing, "Matchfile.swift") else path = File.join(containing, "Matchfile") end if File.exist?(path) FastlaneCore::UI.user_error!("You already have a Matchfile in this directory (#{path})") return 0 end Match::Setup.new.run(path, is_swift_fastfile: is_swift_fastfile) end end command :change_password do |c| c.syntax = 'fastlane match change_password' c.description = 'Re-encrypt all files with a different password' FastlaneCore::CommanderGenerator.new.generate(Match::Options.available_options, command: c) c.action do |args, options| params = FastlaneCore::Configuration.create(Match::Options.available_options, options.__hash__) params.load_configuration_file("Matchfile") Match::ChangePassword.update(params: params) UI.success("Successfully changed the password. Make sure to update the password on all your clients and servers by running `fastlane match [environment]`") end end command :decrypt do |c| c.syntax = "fastlane match decrypt" c.description = "Decrypts the repository and keeps it on the filesystem" FastlaneCore::CommanderGenerator.new.generate(Match::Options.available_options, command: c) c.action do |args, options| params = FastlaneCore::Configuration.create(Match::Options.available_options, options.__hash__) params.load_configuration_file("Matchfile") storage = Storage.from_params(params) storage.download encryption = Encryption.for_storage_mode(params[:storage_mode], { git_url: params[:git_url], s3_bucket: params[:s3_bucket], s3_skip_encryption: params[:s3_skip_encryption], working_directory: storage.working_directory }) encryption.decrypt_files if encryption UI.success("Repo is at: '#{storage.working_directory}'") end end command :import do |c| c.syntax = "fastlane match import" c.description = "Imports certificates and profiles into the encrypted repository" FastlaneCore::CommanderGenerator.new.generate(Match::Options.available_options, command: c) c.action do |args, options| params = FastlaneCore::Configuration.create(Match::Options.available_options, options.__hash__) params.load_configuration_file("Matchfile") # this has to be done *before* overwriting the value Match::Importer.new.import_cert(params) end end command :migrate do |c| c.syntax = "fastlane match migrate" c.description = "Migrate from one storage backend to another one" FastlaneCore::CommanderGenerator.new.generate(Match::Options.available_options, command: c) c.action do |args, options| params = FastlaneCore::Configuration.create(Match::Options.available_options, options.__hash__) Match::Migrate.new.migrate(params) end end command "nuke" do |c| # We have this empty command here, since otherwise the normal `match` command will be executed c.syntax = "fastlane match nuke" c.description = "Delete all certificates and provisioning profiles from the Apple Dev Portal" c.action do |args, options| FastlaneCore::UI.user_error!("Please run `fastlane match nuke [type], allowed values: development, distribution and enterprise. For the 'adhoc' type, please use 'distribution' instead.") end end ["development", "distribution", "enterprise"].each do |type| command "nuke #{type}" do |c| c.syntax = "fastlane match nuke #{type}" c.description = "Delete all certificates and provisioning profiles from the Apple Dev Portal of the type #{type}" FastlaneCore::CommanderGenerator.new.generate(Match::Options.available_options, command: c) c.action do |args, options| params = FastlaneCore::Configuration.create(Match::Options.available_options, options.__hash__) params.load_configuration_file("Matchfile") Match::Nuke.new.run(params, type: type.to_s) end end end default_command(:run) run! end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/runner.rb
match/lib/match/runner.rb
require 'fastlane_core/cert_checker' require 'fastlane_core/provisioning_profile' require 'fastlane_core/print_table' require 'spaceship/client' require 'sigh/module' require_relative 'generator' require_relative 'module' require_relative 'table_printer' require_relative 'spaceship_ensure' require_relative 'utils' require_relative 'storage' require_relative 'encryption' require_relative 'profile_includes' require_relative 'portal_cache' module Match # rubocop:disable Metrics/ClassLength class Runner attr_accessor :files_to_commit attr_accessor :files_to_delete attr_accessor :spaceship attr_accessor :storage attr_accessor :cache # rubocop:disable Metrics/PerceivedComplexity def run(params) self.files_to_commit = [] self.files_to_delete = [] FileUtils.mkdir_p(params[:output_path]) if params[:output_path] FastlaneCore::PrintTable.print_values(config: params, title: "Summary for match #{Fastlane::VERSION}") update_optional_values_depending_on_storage_type(params) # Choose the right storage and encryption implementations storage_params = params storage_params[:username] = params[:readonly] ? nil : params[:username] # only pass username if not readonly self.storage = Storage.from_params(storage_params) storage.download # Init the encryption only after the `storage.download` was called to have the right working directory encryption = Encryption.for_storage_mode(params[:storage_mode], { git_url: params[:git_url], s3_bucket: params[:s3_bucket], s3_skip_encryption: params[:s3_skip_encryption], working_directory: storage.working_directory, force_legacy_encryption: params[:force_legacy_encryption] }) encryption.decrypt_files if encryption unless params[:readonly] self.spaceship = SpaceshipEnsure.new(params[:username], params[:team_id], params[:team_name], api_token(params)) if params[:type] == "enterprise" && !Spaceship::ConnectAPI.client.in_house? UI.user_error!("You defined the profile type 'enterprise', but your Apple account doesn't support In-House profiles") end end if params[:app_identifier].kind_of?(Array) app_identifiers = params[:app_identifier] else app_identifiers = params[:app_identifier].to_s.split(/\s*,\s*/).uniq end # sometimes we get an array with arrays, this is a bug. To unblock people using match, I suggest we flatten # then in the future address the root cause of https://github.com/fastlane/fastlane/issues/11324 app_identifiers = app_identifiers.flatten.uniq if spaceship # Cache bundle ids, certificates, profiles, and devices. self.cache = Portal::Cache.build( params: params, bundle_id_identifiers: app_identifiers ) # Verify the App ID (as we don't want 'match' to fail at a later point) app_identifiers.each do |app_identifier| spaceship.bundle_identifier_exists(username: params[:username], app_identifier: app_identifier, cached_bundle_ids: self.cache.bundle_ids) end end # Certificate cert_id = fetch_certificate(params: params, renew_expired_certs: false) # Mac Installer Distribution Certificate additional_cert_types = params[:additional_cert_types] || [] cert_ids = additional_cert_types.map do |additional_cert_type| fetch_certificate(params: params, renew_expired_certs: false, specific_cert_type: additional_cert_type) end profile_type = Sigh.profile_type_for_distribution_type( platform: params[:platform], distribution_type: params[:type] ) cert_ids << cert_id spaceship.certificates_exists(username: params[:username], certificate_ids: cert_ids, platform: params[:platform], profile_type: profile_type, cached_certificates: self.cache.certificates) if spaceship # Provisioning Profiles unless params[:skip_provisioning_profiles] app_identifiers.each do |app_identifier| loop do break if fetch_provisioning_profile(params: params, profile_type: profile_type, certificate_id: cert_id, app_identifier: app_identifier, working_directory: storage.working_directory) end end end has_file_changes = self.files_to_commit.count > 0 || self.files_to_delete.count > 0 if has_file_changes && !params[:readonly] encryption.encrypt_files if encryption storage.save_changes!(files_to_commit: self.files_to_commit, files_to_delete: self.files_to_delete) end # Print a summary table for each app_identifier app_identifiers.each do |app_identifier| TablePrinter.print_summary(app_identifier: app_identifier, type: params[:type], platform: params[:platform]) end UI.success("All required keys, certificates and provisioning profiles are installed 🙌".green) rescue Spaceship::Client::UnexpectedResponse, Spaceship::Client::InvalidUserCredentialsError, Spaceship::Client::NoUserCredentialsError => ex UI.error("An error occurred while verifying your certificates and profiles with the Apple Developer Portal.") UI.error("If you already have your certificates stored in git, you can run `fastlane match` in readonly mode") UI.error("to just install the certificates and profiles without accessing the Dev Portal.") UI.error("To do so, just pass `readonly: true` to your match call.") raise ex ensure storage.clear_changes if storage end # rubocop:enable Metrics/PerceivedComplexity def api_token(params) api_token = Spaceship::ConnectAPI::Token.from(hash: params[:api_key], filepath: params[:api_key_path]) return api_token end # Used when creating a new certificate or profile def prefixed_working_directory return self.storage.prefixed_working_directory end # Be smart about optional values here # Depending on the storage mode, different values are required def update_optional_values_depending_on_storage_type(params) if params[:storage_mode] != "git" params.option_for_key(:git_url).optional = true end end RENEWABLE_CERT_TYPES_VIA_API = [:mac_installer_distribution, :development, :distribution, :enterprise] def fetch_certificate(params: nil, renew_expired_certs: false, specific_cert_type: nil) cert_type = Match.cert_type_sym(specific_cert_type || params[:type]) certs = Dir[File.join(prefixed_working_directory, "certs", cert_type.to_s, "*.cer")] keys = Dir[File.join(prefixed_working_directory, "certs", cert_type.to_s, "*.p12")] storage_has_certs = certs.count != 0 && keys.count != 0 # Determine if cert is renewable. # Can't renew developer_id certs with Connect API token. Account holder access is required. is_authenticated_with_login = Spaceship::ConnectAPI.token.nil? is_cert_renewable_via_api = RENEWABLE_CERT_TYPES_VIA_API.include?(cert_type) is_cert_renewable = is_authenticated_with_login || is_cert_renewable_via_api # Validate existing certificate first. if renew_expired_certs && is_cert_renewable && storage_has_certs && !params[:readonly] cert_path = select_cert_or_key(paths: certs) unless Utils.is_cert_valid?(cert_path) UI.important("Removing invalid certificate '#{File.basename(cert_path)}'") # Remove expired cert. self.files_to_delete << cert_path File.delete(cert_path) # Key filename is the same as cert but with .p12 extension. key_path = cert_path.gsub(/\.cer$/, ".p12") # Remove expired key .p12 file. if File.exist?(key_path) self.files_to_delete << key_path File.delete(key_path) end certs = [] keys = [] storage_has_certs = false end end if !storage_has_certs UI.important("Couldn't find a valid code signing identity for #{cert_type}... creating one for you now") UI.crash!("No code signing identity found and cannot create a new one because you enabled `readonly`") if params[:readonly] cert_path = Generator.generate_certificate(params, cert_type, prefixed_working_directory, specific_cert_type: specific_cert_type) private_key_path = cert_path.gsub(".cer", ".p12") self.files_to_commit << cert_path self.files_to_commit << private_key_path # Reset certificates cache since we have a new cert. self.cache.reset_certificates else cert_path = select_cert_or_key(paths: certs) # Check validity of certificate if Utils.is_cert_valid?(cert_path) UI.verbose("Your certificate '#{File.basename(cert_path)}' is valid") else UI.user_error!("Your certificate '#{File.basename(cert_path)}' is not valid, please check end date and renew it if necessary") end if Helper.mac? UI.message("Installing certificate...") # Only looking for cert in "custom" (non login.keychain) keychain # Doing this for backwards compatibility keychain_name = params[:keychain_name] == "login.keychain" ? nil : params[:keychain_name] if FastlaneCore::CertChecker.installed?(cert_path, in_keychain: keychain_name) UI.verbose("Certificate '#{File.basename(cert_path)}' is already installed on this machine") else Utils.import(cert_path, params[:keychain_name], password: params[:keychain_password]) # Import the private key # there seems to be no good way to check if it's already installed - so just install it # Key will only be added to the partition list if it isn't already installed Utils.import(select_cert_or_key(paths: keys), params[:keychain_name], password: params[:keychain_password]) end else UI.message("Skipping installation of certificate as it would not work on this operating system.") end if params[:output_path] FileUtils.cp(cert_path, params[:output_path]) FileUtils.cp(select_cert_or_key(paths: keys), params[:output_path]) end # Get and print info of certificate info = Utils.get_cert_info(cert_path) TablePrinter.print_certificate_info(cert_info: info) end return File.basename(cert_path).gsub(".cer", "") # Certificate ID end # @return [String] Path to certificate or P12 key def select_cert_or_key(paths:) cert_id_path = ENV['MATCH_CERTIFICATE_ID'] ? paths.find { |path| path.include?(ENV['MATCH_CERTIFICATE_ID']) } : nil cert_id_path || paths.last end # rubocop:disable Metrics/PerceivedComplexity # @return [String] The UUID of the provisioning profile so we can verify it with the Apple Developer Portal def fetch_provisioning_profile(params: nil, profile_type:, certificate_id: nil, app_identifier: nil, working_directory: nil) prov_type = Match.profile_type_sym(params[:type]) names = [Match::Generator.profile_type_name(prov_type), app_identifier] if params[:platform].to_s == :tvos.to_s || params[:platform].to_s == :catalyst.to_s names.push(params[:platform]) end profile_name = names.join("_").gsub("*", '\*') # this is important, as it shouldn't be a wildcard base_dir = File.join(prefixed_working_directory, "profiles", prov_type.to_s) extension = ".mobileprovision" if [:macos.to_s, :catalyst.to_s].include?(params[:platform].to_s) extension = ".provisionprofile" end profile_file = "#{profile_name}#{extension}" profiles = Dir[File.join(base_dir, profile_file)] if Helper.mac? keychain_path = FastlaneCore::Helper.keychain_path(params[:keychain_name]) unless params[:keychain_name].nil? end # Install the provisioning profiles stored_profile_path = profiles.last force = params[:force] if spaceship # check if profile needs to be updated only if not in readonly mode portal_profile = self.cache.portal_profile(stored_profile_path: stored_profile_path, keychain_path: keychain_path) if stored_profile_path if params[:force_for_new_devices] force ||= ProfileIncludes.should_force_include_all_devices?(params: params, portal_profile: portal_profile, cached_devices: self.cache.devices) end if params[:include_all_certificates] # Clearing specified certificate id which will prevent a profile being created with only one certificate certificate_id = nil force ||= ProfileIncludes.should_force_include_all_certificates?(params: params, portal_profile: portal_profile, cached_certificates: self.cache.certificates) end end is_new_profile_created = false if stored_profile_path.nil? || force if params[:readonly] UI.error("No matching provisioning profiles found for '#{profile_file}'") UI.error("A new one cannot be created because you enabled `readonly`") if Dir.exist?(base_dir) # folder for `prov_type` does not exist on first match use for that type all_profiles = Dir.entries(base_dir).reject { |f| f.start_with?(".") } UI.error("Provisioning profiles in your repo for type `#{prov_type}`:") all_profiles.each { |p| UI.error("- '#{p}'") } end UI.error("If you are certain that a profile should exist, double-check the recent changes to your match repository") UI.user_error!("No matching provisioning profiles found and cannot create a new one because you enabled `readonly`. Check the output above for more information.") end stored_profile_path = Generator.generate_provisioning_profile( params: params, prov_type: prov_type, certificate_id: certificate_id, app_identifier: app_identifier, force: force, cache: self.cache, working_directory: prefixed_working_directory ) # Recreation of the profile means old profile is invalid. # Removing it from cache. We don't need a new profile in cache. self.cache.forget_portal_profile(portal_profile) if portal_profile self.files_to_commit << stored_profile_path is_new_profile_created = true end parsed = FastlaneCore::ProvisioningProfile.parse(stored_profile_path, keychain_path) uuid = parsed["UUID"] name = parsed["Name"] check_profile_existence = !is_new_profile_created && spaceship if check_profile_existence && !spaceship.profile_exists(profile_type: profile_type, name: name, username: params[:username], uuid: uuid, cached_profiles: self.cache.profiles) # This profile is invalid, let's remove the local file and generate a new one File.delete(stored_profile_path) # This method will be called again, no need to modify `files_to_commit` return nil end if Helper.mac? installed_profile = FastlaneCore::ProvisioningProfile.install(stored_profile_path, keychain_path) end if params[:output_path] FileUtils.cp(stored_profile_path, params[:output_path]) end Utils.fill_environment(Utils.environment_variable_name(app_identifier: app_identifier, type: prov_type, platform: params[:platform]), uuid) # TeamIdentifier is returned as an array, but we're not sure why there could be more than one Utils.fill_environment(Utils.environment_variable_name_team_id(app_identifier: app_identifier, type: prov_type, platform: params[:platform]), parsed["TeamIdentifier"].first) cert_info = Utils.get_cert_info(parsed["DeveloperCertificates"].first.string).to_h Utils.fill_environment(Utils.environment_variable_name_certificate_name(app_identifier: app_identifier, type: prov_type, platform: params[:platform]), cert_info["Common Name"]) Utils.fill_environment(Utils.environment_variable_name_profile_name(app_identifier: app_identifier, type: prov_type, platform: params[:platform]), parsed["Name"]) Utils.fill_environment(Utils.environment_variable_name_profile_path(app_identifier: app_identifier, type: prov_type, platform: params[:platform]), installed_profile) return uuid end # rubocop:enable Metrics/PerceivedComplexity end # rubocop:enable Metrics/ClassLength end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/profile_includes.rb
match/lib/match/profile_includes.rb
require_relative 'portal_fetcher' require_relative 'module' module Match class ProfileIncludes PROV_TYPES_WITH_DEVICES = [:adhoc, :development] PROV_TYPES_WITH_MULTIPLE_CERTIFICATES = [:development] def self.can_force_include?(params:, notify:) self.can_force_include_all_devices?(params: params, notify: notify) && self.can_force_include_all_certificates?(params: params, notify: notify) end ############### # # DEVICES # ############### def self.should_force_include_all_devices?(params:, portal_profile:, cached_devices:) return false unless self.can_force_include_all_devices?(params: params) force = devices_differ?(portal_profile: portal_profile, platform: params[:platform], include_mac_in_profiles: params[:include_mac_in_profiles], cached_devices: cached_devices) return force end def self.can_force_include_all_devices?(params:, notify: false) return false if params[:readonly] || params[:force] return false unless params[:force_for_new_devices] provisioning_type = params[:type].to_sym can_force = PROV_TYPES_WITH_DEVICES.include?(provisioning_type) if !can_force && notify # App Store provisioning profiles don't contain device identifiers and # thus shouldn't be renewed if the device count has changed. UI.important("Warning: `force_for_new_devices` is set but is ignored for #{provisioning_type}.") UI.important("You can safely stop specifying `force_for_new_devices` when running Match for type '#{provisioning_type}'.") end can_force end def self.devices_differ?(portal_profile:, platform:, include_mac_in_profiles:, cached_devices:) return false unless portal_profile profile_devices = portal_profile.devices || [] portal_devices = cached_devices portal_devices ||= Match::Portal::Fetcher.devices(platform: platform, include_mac_in_profiles: include_mac_in_profiles) profile_device_ids = profile_devices.map(&:id).sort portal_devices_ids = portal_devices.map(&:id).sort devices_differs = profile_device_ids != portal_devices_ids UI.important("Devices in the profile and available on the portal differ. Recreating a profile") if devices_differs return devices_differs end ############### # # CERTIFICATES # ############### def self.should_force_include_all_certificates?(params:, portal_profile:, cached_certificates:) return false unless self.can_force_include_all_certificates?(params: params) force = certificates_differ?(portal_profile: portal_profile, platform: params[:platform], cached_certificates: cached_certificates) return force end def self.can_force_include_all_certificates?(params:, notify: false) return false if params[:readonly] || params[:force] return false unless params[:force_for_new_certificates] unless params[:include_all_certificates] UI.important("You specified 'force_for_new_certificates: true', but new certificates will not be added, cause 'include_all_certificates' is 'false'") if notify return false end provisioning_type = params[:type].to_sym can_force = PROV_TYPES_WITH_MULTIPLE_CERTIFICATES.include?(provisioning_type) if !can_force && notify # All other (not development) provisioning profiles don't contain # multiple certificates, thus shouldn't be renewed # if the certificates count has changed. UI.important("Warning: `force_for_new_certificates` is set but is ignored for non-'development' provisioning profiles.") UI.important("You can safely stop specifying `force_for_new_certificates` when running Match for '#{provisioning_type}' provisioning profiles.") end can_force end def self.certificates_differ?(portal_profile:, platform:, cached_certificates:) return false unless portal_profile profile_certs = portal_profile.certificates || [] portal_certs = cached_certificates portal_certs ||= Match::Portal::Fetcher.certificates(platform: platform, profile_type: portal_profile.profile_type) profile_certs_ids = profile_certs.map(&:id).sort portal_certs_ids = portal_certs.map(&:id).sort certificates_differ = profile_certs_ids != portal_certs_ids UI.important("Certificates in the profile and available on the portal differ. Recreating a profile") if certificates_differ return certificates_differ end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/generator.rb
match/lib/match/generator.rb
require_relative 'module' require_relative 'profile_includes' module Match # Generate missing resources class Generator def self.generate_certificate(params, cert_type, working_directory, specific_cert_type: nil) require 'cert/runner' require 'cert/options' output_path = File.join(working_directory, "certs", cert_type.to_s) # Mapping match option to cert option for "Developer ID Application" if cert_type.to_sym == :developer_id_application specific_cert_type = cert_type.to_s end platform = params[:platform] if platform.to_s == :catalyst.to_s platform = :macos.to_s end arguments = FastlaneCore::Configuration.create(Cert::Options.available_options, { platform: platform, development: params[:type] == "development", type: specific_cert_type, generate_apple_certs: params[:generate_apple_certs], output_path: output_path, force: true, # we don't need a certificate without its private key, we only care about a new certificate api_key_path: params[:api_key_path], api_key: params[:api_key], username: params[:username], team_id: params[:team_id], team_name: params[:team_name], keychain_path: Helper.mac? ? FastlaneCore::Helper.keychain_path(params[:keychain_name]) : nil, keychain_password: Helper.mac? ? params[:keychain_password] : nil, skip_set_partition_list: params[:skip_set_partition_list] }) Cert.config = arguments begin cert_path = Cert::Runner.new.launch rescue => ex if ex.to_s.include?("You already have a current") UI.user_error!("Could not create a new certificate as you reached the maximum number of certificates for this account. You can use the `fastlane match nuke` command to revoke your existing certificates. More information https://docs.fastlane.tools/actions/match/") else raise ex end end # We don't care about the signing request Dir[File.join(working_directory, "**", "*.certSigningRequest")].each { |path| File.delete(path) } # we need to return the path # Inside this directory, there is the `.p12` file and the `.cer` file with the same name, but different extension return cert_path end # @return (String) The UUID of the newly generated profile def self.generate_provisioning_profile(params: nil, prov_type: nil, certificate_id: nil, app_identifier: nil, force: true, cache: nil, working_directory: nil) require 'sigh/manager' require 'sigh/options' prov_type = Match.profile_type_sym(params[:type]) names = ["match", profile_type_name(prov_type), app_identifier] if params[:platform].to_s != :ios.to_s # For ios we do not include the platform for backwards compatibility names << params[:platform] end if params[:profile_name].to_s.empty? profile_name = names.join(" ") else profile_name = params[:profile_name] end values = { app_identifier: app_identifier, output_path: File.join(working_directory, "profiles", prov_type.to_s), username: params[:username], force: force, cert_id: certificate_id, provisioning_name: profile_name, ignore_profiles_with_different_name: true, api_key_path: params[:api_key_path], api_key: params[:api_key], team_id: params[:team_id], team_name: params[:team_name], template_name: params[:template_name], fail_on_name_taken: params[:fail_on_name_taken], include_all_certificates: params[:include_all_certificates], include_mac_in_profiles: params[:include_mac_in_profiles], } values[:platform] = params[:platform] # These options are all conflicting so can only set one if params[:type] == "developer_id" values[:developer_id] = true elsif prov_type == :adhoc values[:adhoc] = true elsif prov_type == :development values[:development] = true end if cache values[:cached_certificates] = cache.certificates values[:cached_devices] = cache.devices values[:cached_bundle_ids] = cache.bundle_ids values[:cached_profiles] = cache.profiles end arguments = FastlaneCore::Configuration.create(Sigh::Options.available_options, values) Sigh.config = arguments path = Sigh::Manager.start return path end # @return the name of the provisioning profile type def self.profile_type_name(type) return "Direct" if type == :developer_id return "Development" if type == :development return "AdHoc" if type == :adhoc return "AppStore" if type == :appstore return "InHouse" if type == :enterprise return "Unknown" end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/table_printer.rb
match/lib/match/table_printer.rb
require 'terminal-table' require 'fastlane_core/print_table' require_relative 'module' require_relative 'utils' module Match class TablePrinter # logs public key's name, user, organisation, country, availability dates def self.print_certificate_info(cert_info: nil) params = { rows: cert_info, title: "Installed Certificate".green } puts("") puts(Terminal::Table.new(params)) puts("") rescue => ex UI.error(ex) end def self.print_summary(app_identifier: nil, type: nil, platform: :ios) rows = [] type = type.to_sym rows << ["App Identifier", "", app_identifier] rows << ["Type", "", type] rows << ["Platform", "", platform.to_s] { Utils.environment_variable_name(app_identifier: app_identifier, type: type, platform: platform) => "Profile UUID", Utils.environment_variable_name_profile_name(app_identifier: app_identifier, type: type, platform: platform) => "Profile Name", Utils.environment_variable_name_profile_path(app_identifier: app_identifier, type: type, platform: platform) => "Profile Path", Utils.environment_variable_name_team_id(app_identifier: app_identifier, type: type, platform: platform) => "Development Team ID", Utils.environment_variable_name_certificate_name(app_identifier: app_identifier, type: type, platform: platform) => "Certificate Name" }.each do |env_key, name| rows << [name, env_key, ENV[env_key]] end params = {} params[:rows] = FastlaneCore::PrintTable.transform_output(rows) params[:title] = "Installed Provisioning Profile".green params[:headings] = ['Parameter', 'Environment Variable', 'Value'] puts("") puts(Terminal::Table.new(params)) puts("") end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/module.rb
match/lib/match/module.rb
require 'spaceship' require 'fastlane_core/helper' require 'fastlane/boolean' module Match Helper = FastlaneCore::Helper # you gotta love Ruby: Helper.* should use the Helper class contained in FastlaneCore UI = FastlaneCore::UI Boolean = Fastlane::Boolean ROOT = Pathname.new(File.expand_path('../../..', __FILE__)) DESCRIPTION = "Easily sync your certificates and profiles across your team" def self.environments return %w(appstore adhoc development enterprise developer_id mac_installer_distribution developer_id_installer) end def self.storage_modes return %w(git google_cloud s3 gitlab_secure_files) end def self.profile_type_sym(type) return type.to_sym end def self.cert_type_sym(type) # To determine certificate types to fetch from the portal, we use `Sigh.certificate_types_for_profile_and_platform`, and it returns typed `Spaceship::ConnectAPI::Certificate::CertificateType` with the same values but uppercased, so we downcase them here type = type.to_s.downcase return :mac_installer_distribution if type == "mac_installer_distribution" return :developer_id_installer if type == "developer_id_installer" return :developer_id_application if type == "developer_id" return :enterprise if type == "enterprise" return :development if type == "development" return :distribution if ["adhoc", "appstore", "distribution"].include?(type) raise "Unknown cert type: '#{type}'" end # Converts provisioning profile type (i.e. development, enterprise) to an array of profile types # That can be used for filtering when using Spaceship::ConnectAPI::Profile API def self.profile_types(prov_type) case prov_type.to_sym when :appstore return [ Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_STORE, Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_STORE, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_STORE, Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_STORE ] when :development return [ Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_DEVELOPMENT, Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DEVELOPMENT, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_DEVELOPMENT, Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DEVELOPMENT ] when :enterprise profiles = [ Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE ] # As of 2022-06-25, only available with Apple ID auth if Spaceship::ConnectAPI.token UI.important("Skipping #{Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE} and #{Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE}... only available with Apple ID auth") else profiles += [ Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE, Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE ] end return profiles when :adhoc return [ Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_ADHOC, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_ADHOC ] when :developer_id return [ Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DIRECT, Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DIRECT ] else raise "Unknown provisioning type '#{prov_type}'" end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/change_password.rb
match/lib/match/change_password.rb
require_relative 'module' require_relative 'storage' require_relative 'encryption' module Match # These functions should only be used while in (UI.) interactive mode class ChangePassword def self.update(params: nil) if params[:storage_mode] != "git" # Only git supports changing the password # All other storage options will most likely use more advanced # ways to encrypt files UI.user_error!("Only git-based match allows you to change your password, current `storage_mode` is #{params[:storage_mode]}") end ensure_ui_interactive new_password = FastlaneCore::Helper.ask_password(message: "New passphrase for Git Repo: ", confirm: true) # Choose the right storage and encryption implementations storage = Storage.from_params(params) storage.download encryption = Encryption.for_storage_mode(params[:storage_mode], { git_url: params[:git_url], s3_bucket: params[:s3_bucket], s3_skip_encryption: params[:s3_skip_encryption], working_directory: storage.working_directory, force_legacy_encryption: params[:force_legacy_encryption] }) encryption.decrypt_files encryption.clear_password encryption.store_password(new_password) message = "[fastlane] Changed passphrase" files_to_commit = encryption.encrypt_files(password: new_password) storage.save_changes!(files_to_commit: files_to_commit, custom_message: message) ensure storage.clear_changes if storage end def self.ensure_ui_interactive raise "This code should only run in interactive mode" unless UI.interactive? end private_class_method :ensure_ui_interactive end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/importer.rb
match/lib/match/importer.rb
require_relative 'spaceship_ensure' require_relative 'encryption' require_relative 'storage' require_relative 'module' require_relative 'generator' require 'fastlane_core/provisioning_profile' require 'fileutils' module Match class Importer def import_cert(params, cert_path: nil, p12_path: nil, profile_path: nil) # Get and verify cert, p12 and profiles path cert_path = ensure_valid_file_path(cert_path, "Certificate", ".cer") p12_path = ensure_valid_file_path(p12_path, "Private key", ".p12") profile_path = ensure_valid_file_path(profile_path, "Provisioning profile", ".mobileprovision or .provisionprofile", optional: true) # Storage storage = Storage.from_params(params) storage.download # Encryption encryption = Encryption.for_storage_mode(params[:storage_mode], { git_url: params[:git_url], s3_bucket: params[:s3_bucket], s3_skip_encryption: params[:s3_skip_encryption], working_directory: storage.working_directory, force_legacy_encryption: params[:force_legacy_encryption] }) encryption.decrypt_files if encryption UI.success("Repo is at: '#{storage.working_directory}'") # Map match type into Spaceship::ConnectAPI::Certificate::CertificateType cert_type = Match.cert_type_sym(params[:type]) case cert_type when :development certificate_type = [ Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DEVELOPMENT, Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DEVELOPMENT, Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPMENT ].join(',') when :distribution, :enterprise certificate_type = [ Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DISTRIBUTION, Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DISTRIBUTION, Spaceship::ConnectAPI::Certificate::CertificateType::DISTRIBUTION ].join(',') when :developer_id_application certificate_type = [ Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_APPLICATION, Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_APPLICATION_G2 ].join(',') when :mac_installer_distribution certificate_type = [ Spaceship::ConnectAPI::Certificate::CertificateType::MAC_INSTALLER_DISTRIBUTION ].join(',') when :developer_id_installer certificate_type = [ Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_INSTALLER ].join(',') else UI.user_error!("Cert type '#{cert_type}' is not supported") end prov_type = Match.profile_type_sym(params[:type]) output_dir_certs = File.join(storage.prefixed_working_directory, "certs", cert_type.to_s) output_dir_profiles = File.join(storage.prefixed_working_directory, "profiles", prov_type.to_s) should_skip_certificate_matching = params[:skip_certificate_matching] # In case there is no access to Apple Developer portal but we have the certificates, keys and profiles if should_skip_certificate_matching cert_name = File.basename(cert_path, ".*") p12_name = File.basename(p12_path, ".*") # Make dir if doesn't exist FileUtils.mkdir_p(output_dir_certs) dest_cert_path = File.join(output_dir_certs, "#{cert_name}.cer") dest_p12_path = File.join(output_dir_certs, "#{p12_name}.p12") else if (api_token = Spaceship::ConnectAPI::Token.from(hash: params[:api_key], filepath: params[:api_key_path])) UI.message("Creating authorization token for App Store Connect API") Spaceship::ConnectAPI.token = api_token elsif !Spaceship::ConnectAPI.token.nil? UI.message("Using existing authorization token for App Store Connect API") else UI.message("Login to App Store Connect (#{params[:username]})") Spaceship::ConnectAPI.login(params[:username], use_portal: true, use_tunes: false, portal_team_id: params[:team_id], team_name: params[:team_name]) end # Need to get the cert id by comparing base64 encoded cert content with certificate content from the API responses certs = Spaceship::ConnectAPI::Certificate.all(filter: { certificateType: certificate_type }) # Base64 encode contents to find match from API to find a cert ID cert_contents_base_64 = Base64.strict_encode64(File.binread(cert_path)) matching_cert = certs.find do |cert| cert.certificate_content == cert_contents_base_64 end UI.user_error!("This certificate cannot be imported - the certificate contents did not match with any available on the Developer Portal") if matching_cert.nil? # Make dir if doesn't exist FileUtils.mkdir_p(output_dir_certs) dest_cert_path = File.join(output_dir_certs, "#{matching_cert.id}.cer") dest_p12_path = File.join(output_dir_certs, "#{matching_cert.id}.p12") end files_to_commit = [dest_cert_path, dest_p12_path] # Copy files IO.copy_stream(cert_path, dest_cert_path) IO.copy_stream(p12_path, dest_p12_path) unless profile_path.nil? FileUtils.mkdir_p(output_dir_profiles) bundle_id = FastlaneCore::ProvisioningProfile.bundle_id(profile_path) profile_extension = FastlaneCore::ProvisioningProfile.profile_extension(profile_path) profile_type_name = Match::Generator.profile_type_name(prov_type) dest_profile_path = File.join(output_dir_profiles, "#{profile_type_name}_#{bundle_id}#{profile_extension}") files_to_commit.push(dest_profile_path) IO.copy_stream(profile_path, dest_profile_path) end # Encrypt and commit encryption.encrypt_files if encryption storage.save_changes!(files_to_commit: files_to_commit) ensure storage.clear_changes if storage end def ensure_valid_file_path(file_path, file_description, file_extension, optional: false) optional_file_message = optional ? " or leave empty to skip this file" : "" file_path ||= UI.input("#{file_description} (#{file_extension}) path#{optional_file_message}:") file_path = File.absolute_path(file_path) unless file_path == "" file_path = File.exist?(file_path) ? file_path : nil UI.user_error!("#{file_description} does not exist at path: #{file_path}") unless !file_path.nil? || optional file_path end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/storage/interface.rb
match/lib/match/storage/interface.rb
require_relative '../module' module Match module Storage class Interface MATCH_VERSION_FILE_NAME = "match_version.txt" # The working directory in which we download all the profiles # and decrypt/encrypt them attr_accessor :working_directory # To make debugging easier, we have a custom exception here def prefixed_working_directory not_implemented(__method__) end # To make debugging easier, we have a custom exception here def working_directory if @working_directory.nil? raise "`working_directory` for the current storage provider is `nil` as the `#download` method was never called" end return @working_directory end # Call this method after creating a new object to configure # the given Storage object. This method will take # different parameters depending on specific class being used def configure not_implemented(__method__) end # Call this method for the initial clone/download of the # user's certificates & profiles # As part of this method, the `self.working_directory` attribute # will be set def download not_implemented(__method__) end # Returns a short string describing + identifying the current # storage backend. This will be printed when nuking a storage def human_readable_description not_implemented(__method__) end # Call this method after locally modifying the files # This will commit the changes and push it back to the # given remote server # This method is blocking, meaning it might take multiple # seconds or longer to run # @parameter files_to_commit [Array] Array to paths to files # that should be committed to the storage provider # @parameter custom_message: [String] Custom change message # that's optional, is used for commit title def save_changes!(files_to_commit: nil, files_to_delete: nil, custom_message: nil) # Custom init to `[]` in case `nil` is passed files_to_commit ||= [] files_to_delete ||= [] files_to_delete -= files_to_commit # Make sure we are not removing added files. if files_to_commit.count == 0 && files_to_delete.count == 0 UI.user_error!("Neither `files_to_commit` nor `files_to_delete` were provided to the `save_changes!` method call") end Dir.chdir(File.expand_path(self.working_directory)) do if files_to_commit.count > 0 # everything that isn't `match nuke` if !File.exist?(MATCH_VERSION_FILE_NAME) || File.read(MATCH_VERSION_FILE_NAME) != Fastlane::VERSION.to_s files_to_commit << MATCH_VERSION_FILE_NAME File.write(MATCH_VERSION_FILE_NAME, Fastlane::VERSION) # stored unencrypted end template = File.read("#{Match::ROOT}/lib/assets/READMETemplate.md") readme_path = "README.md" if (!File.exist?(readme_path) || File.read(readme_path) != template) && !self.skip_docs files_to_commit << readme_path File.write(readme_path, template) end self.upload_files(files_to_upload: files_to_commit, custom_message: custom_message) UI.message("Finished uploading files to #{self.human_readable_description}") end if files_to_delete.count > 0 self.delete_files(files_to_delete: files_to_delete, custom_message: custom_message) UI.message("Finished deleting files from #{self.human_readable_description}") end end ensure # Always clear working_directory after save self.clear_changes end def upload_files(files_to_upload: [], custom_message: nil) not_implemented(__method__) end def delete_files(files_to_delete: [], custom_message: nil) not_implemented(__method__) end def skip_docs not_implemented(__method__) end def list_files(file_name: "", file_ext: "") not_implemented(__method__) end # Implement this for the `fastlane match init` command # This method must return the content of the Matchfile # that should be generated def generate_matchfile_content(template: nil) not_implemented(__method__) end # Call this method to reset any changes made locally to the files def clear_changes return unless @working_directory FileUtils.rm_rf(self.working_directory) self.working_directory = nil end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/storage/google_cloud_storage.rb
match/lib/match/storage/google_cloud_storage.rb
require 'fastlane_core/command_executor' require 'fastlane_core/configuration/configuration' require 'google/cloud/storage' require_relative '../options' require_relative '../module' require_relative '../spaceship_ensure' require_relative './interface' module Match module Storage # Store the code signing identities in on Google Cloud Storage class GoogleCloudStorage < Interface DEFAULT_KEYS_FILE_NAME = "gc_keys.json" # User provided values attr_reader :type attr_reader :platform attr_reader :bucket_name attr_reader :google_cloud_keys_file attr_reader :google_cloud_project_id attr_reader :readonly attr_reader :username attr_reader :team_id attr_reader :team_name attr_reader :api_key_path attr_reader :api_key # Managed values attr_accessor :gc_storage def self.configure(params) if params[:git_url].to_s.length > 0 UI.important("Looks like you still define a `git_url` somewhere, even though") UI.important("you use Google Cloud Storage. You can remove the `git_url`") UI.important("from your Matchfile and Fastfile") UI.message("The above is just a warning, fastlane will continue as usual now...") end return self.new( type: params[:type].to_s, platform: params[:platform].to_s, google_cloud_bucket_name: params[:google_cloud_bucket_name], google_cloud_keys_file: params[:google_cloud_keys_file], google_cloud_project_id: params[:google_cloud_project_id], readonly: params[:readonly], username: params[:username], team_id: params[:team_id], team_name: params[:team_name], api_key_path: params[:api_key_path], api_key: params[:api_key], skip_google_cloud_account_confirmation: params[:skip_google_cloud_account_confirmation] ) end def initialize(type: nil, platform: nil, google_cloud_bucket_name: nil, google_cloud_keys_file: nil, google_cloud_project_id: nil, readonly: nil, username: nil, team_id: nil, team_name: nil, api_key_path: nil, api_key: nil, skip_google_cloud_account_confirmation: nil) @type = type if type @platform = platform if platform @google_cloud_project_id = google_cloud_project_id if google_cloud_project_id @bucket_name = google_cloud_bucket_name @readonly = readonly @username = username @team_id = team_id @team_name = team_name @api_key_path = api_key_path @api_key = api_key @google_cloud_keys_file = ensure_keys_file_exists(google_cloud_keys_file, google_cloud_project_id, skip_google_cloud_account_confirmation) if self.google_cloud_keys_file.to_s.length > 0 # Extract the Project ID from the `JSON` file # so the user doesn't have to provide it manually keys_file_content = JSON.parse(File.read(self.google_cloud_keys_file)) if google_cloud_project_id.to_s.length > 0 && google_cloud_project_id != keys_file_content["project_id"] UI.important("The google_cloud_keys_file's project ID ('#{keys_file_content['project_id']}') doesn't match the google_cloud_project_id ('#{google_cloud_project_id}'). This may be the wrong keys file.") end @google_cloud_project_id = keys_file_content["project_id"] if self.google_cloud_project_id.to_s.length == 0 UI.user_error!("Provided keys file on path #{File.expand_path(self.google_cloud_keys_file)} doesn't include required value for `project_id`") end end # Create the Google Cloud Storage client # If the JSON auth file is invalid, this line will # raise an exception begin self.gc_storage = Google::Cloud::Storage.new( credentials: self.google_cloud_keys_file, project_id: self.google_cloud_project_id ) rescue => ex UI.error(ex) UI.verbose(ex.backtrace.join("\n")) UI.user_error!("Couldn't log into your Google Cloud account using the provided JSON file at path '#{File.expand_path(self.google_cloud_keys_file)}'") end ensure_bucket_is_selected check_bucket_permissions end def currently_used_team_id if self.readonly # In readonly mode, we still want to see if the user provided a team_id # see `prefixed_working_directory` comments for more details return self.team_id else UI.user_error!("The `team_id` option is required. fastlane cannot automatically determine portal team id via the App Store Connect API (yet)") if self.team_id.to_s.empty? spaceship = SpaceshipEnsure.new(self.username, self.team_id, self.team_name, self.api_token) return spaceship.team_id end end def api_token api_token = Spaceship::ConnectAPI::Token.from(hash: self.api_key, filepath: self.api_key_path) api_token ||= Spaceship::ConnectAPI.token return api_token end def prefixed_working_directory # We fall back to "*", which means certificates and profiles # from all teams that use this bucket would be installed. This is not ideal, but # unless the user provides a `team_id`, we can't know which one to use # This only happens if `readonly` is activated, and no `team_id` was provided @_folder_prefix ||= currently_used_team_id if @_folder_prefix.nil? # We use a `@_folder_prefix` variable, to keep state between multiple calls of this # method, as the value won't change. This way the warning is only printed once UI.important("Looks like you run `match` in `readonly` mode, and didn't provide a `team_id`. This will still work, however it is recommended to provide a `team_id` in your Appfile or Matchfile") @_folder_prefix = "*" end return File.join(working_directory, @_folder_prefix) end def download # Check if we already have a functional working_directory return if @working_directory # No existing working directory, creating a new one now self.working_directory = Dir.mktmpdir bucket.files.each do |current_file| file_path = current_file.name # e.g. "N8X438SEU2/certs/distribution/XD9G7QCACF.cer" download_path = File.join(self.working_directory, file_path) FileUtils.mkdir_p(File.expand_path("..", download_path)) UI.verbose("Downloading file from Google Cloud Storage '#{file_path}' on bucket #{self.bucket_name}") current_file.download(download_path) end UI.verbose("Successfully downloaded files from GCS to #{self.working_directory}") end def delete_files(files_to_delete: [], custom_message: nil) files_to_delete.each do |current_file| target_path = current_file.gsub(self.working_directory + "/", "") file = bucket.file(target_path) UI.message("Deleting '#{target_path}' from Google Cloud Storage bucket '#{self.bucket_name}'...") file.delete end end def human_readable_description "Google Cloud Bucket [#{self.google_cloud_project_id}/#{self.bucket_name}]" end def upload_files(files_to_upload: [], custom_message: nil) # `files_to_upload` is an array of files that need to be uploaded to Google Cloud # Those doesn't mean they're new, it might just be they're changed # Either way, we'll upload them using the same technique files_to_upload.each do |current_file| # Go from # "/var/folders/px/bz2kts9n69g8crgv4jpjh6b40000gn/T/d20181026-96528-1av4gge/profiles/development/Development_me.mobileprovision" # to # "profiles/development/Development_me.mobileprovision" # # We also have to remove the trailing `/` as Google Cloud doesn't handle it nicely target_path = current_file.gsub(self.working_directory + "/", "") UI.verbose("Uploading '#{target_path}' to Google Cloud Storage...") bucket.create_file(current_file, target_path) end end def skip_docs false end def list_files(file_name: "", file_ext: "") Dir[File.join(working_directory, self.team_id, "**", file_name, "*.#{file_ext}")] end def generate_matchfile_content return "google_cloud_bucket_name(\"#{self.bucket_name}\")" end private def bucket @_bucket ||= self.gc_storage.bucket(self.bucket_name) if @_bucket.nil? UI.user_error!("Couldn't find Google Cloud Storage bucket with name #{self.bucket_name} for the currently used account. Please make sure you have access") end return @_bucket end ########################## # Setup related methods ########################## # This method will make sure the keys file exists # If it's missing, it will help the user set things up def ensure_keys_file_exists(google_cloud_keys_file, google_cloud_project_id, skip_google_cloud_account_confirmation) if google_cloud_keys_file && File.exist?(google_cloud_keys_file) return google_cloud_keys_file end return DEFAULT_KEYS_FILE_NAME if File.exist?(DEFAULT_KEYS_FILE_NAME) fastlane_folder_gc_keys_path = File.join(FastlaneCore::FastlaneFolder.path || Dir.pwd, DEFAULT_KEYS_FILE_NAME) return fastlane_folder_gc_keys_path if File.exist?(fastlane_folder_gc_keys_path) if google_cloud_project_id.to_s.length > 0 # Check to see if this system has application default keys installed. # These are the default keys that the Google Cloud APIs use when no other keys are specified. # Users with the Google Cloud SDK installed can generate them by running... # `gcloud auth application-default login` # ...and then they'll be automatically available. # The nice thing about these keys is they can be associated with the user's login in GCP # (e.g. my_account@gmail.com), so teams can control access to the certificate bucket # using a mailing list of developer logins instead of generating service accounts # and keys. application_default_keys = nil begin application_default_keys = Google::Auth.get_application_default rescue # This means no application default keys have been installed. That's perfectly OK, # we can continue and ask the user if they want to use a keys file. end if application_default_keys && (skip_google_cloud_account_confirmation || UI.confirm("Do you want to use this system's Google Cloud application default keys?")) return nil end end # User doesn't seem to have provided a keys file UI.message("Looks like you don't have a Google Cloud #{DEFAULT_KEYS_FILE_NAME.cyan} file yet.") UI.message("If you have one, make sure to put it into the '#{Dir.pwd}' directory and call it '#{DEFAULT_KEYS_FILE_NAME.cyan}'.") unless UI.confirm("Do you want fastlane to help you to create a #{DEFAULT_KEYS_FILE_NAME} file?") UI.user_error!("Process stopped, run fastlane again to start things up again") end UI.message("fastlane will help you create a keys file. Start by opening the following website:") UI.message("") UI.message("\t\thttps://console.cloud.google.com".cyan) UI.message("") UI.input("Press [Enter] once you're logged in") UI.message("First, switch to the Google Cloud project you want to use.") UI.message("If you don't have one yet, create a new one and switch to it.") UI.message("") UI.message("\t\thttps://console.cloud.google.com/projectcreate".cyan) UI.message("") UI.input("Press [Enter] once you selected the right project") UI.message("Next fastlane will show you the steps to create a keys file.") UI.message("For this it might be useful to switch the Google Cloud interface to English.") UI.message("Append " + "&hl=en".cyan + " to the URL and the interface should be in English.") UI.input("Press [Enter] to continue") UI.message("Now it's time to generate a new JSON auth file for fastlane to access Google Cloud Storage:") UI.message("") UI.message("\t\t 1. From the side menu choose 'APIs & Services' and then 'Credentials'".cyan) UI.message("\t\t 2. Click 'Create credentials'".cyan) UI.message("\t\t 3. Choose 'Service account key'".cyan) UI.message("\t\t 4. Select 'New service account'".cyan) UI.message("\t\t 5. Enter a name and ID for the service account".cyan) UI.message("\t\t 6. Don't give the service account a role just yet!".cyan) UI.message("\t\t 7. Make sure the key type is set to 'JSON'".cyan) UI.message("\t\t 8. Click 'Create'".cyan) UI.message("") UI.input("Confirm with [Enter] once you created and downloaded the JSON file") UI.message("Copy the file to the current directory (#{Dir.pwd})") UI.message("and rename it to `#{DEFAULT_KEYS_FILE_NAME.cyan}`") UI.message("") UI.input("Confirm with [Enter]") until File.exist?(DEFAULT_KEYS_FILE_NAME) UI.message("Make sure to place the file in '#{Dir.pwd.cyan}' and name it '#{DEFAULT_KEYS_FILE_NAME.cyan}'") UI.message("") UI.input("Confirm with [Enter]") end UI.important("Please never add the #{DEFAULT_KEYS_FILE_NAME.cyan} file in version control.") UI.important("Instead please add the file to your `.gitignore` file") UI.message("") UI.input("Confirm with [Enter]") return DEFAULT_KEYS_FILE_NAME end def ensure_bucket_is_selected # Skip the instructions if the user provided a bucket name return unless self.bucket_name.to_s.length == 0 created_bucket = UI.confirm("Did you already create a Google Cloud Storage bucket?") while self.bucket_name.to_s.length == 0 unless created_bucket UI.message("Create a bucket at the following URL:") UI.message("") UI.message("\t\thttps://console.cloud.google.com/storage/browser".cyan) UI.message("") UI.message("Make sure to select the right project at the top of the page!") UI.message("") UI.message("\t\t 1. Click 'Create bucket'".cyan) UI.message("\t\t 2. Enter a unique name".cyan) UI.message("\t\t 3. Select a geographic location for your bucket".cyan) UI.message("\t\t 4. Make sure the storage class is set to 'Standard'".cyan) UI.message("\t\t 5. Click 'Create' to create the bucket".cyan) UI.message("") UI.input("Press [Enter] once you created a bucket") end bucket_name = UI.input("Enter the name of your bucket: ") # Verify if the bucket exists begin bucket_exists = !self.gc_storage.bucket(bucket_name).nil? rescue Google::Cloud::PermissionDeniedError bucket_exists = true end created_bucket = bucket_exists if bucket_exists @bucket_name = bucket_name else UI.error("It looks like the bucket '#{bucket_name}' doesn't exist. Make sure to create it first.") end end end def check_bucket_permissions bucket = nil while bucket.nil? begin bucket = self.gc_storage.bucket(self.bucket_name) rescue Google::Cloud::PermissionDeniedError bucket = nil end return if bucket.nil? == false UI.error("Looks like your Google Cloud account for the project ID '#{self.google_cloud_project_id}' doesn't") UI.error("have access to the storage bucket '#{self.bucket_name}'. Please visit the following URL:") UI.message("") UI.message("\t\thttps://console.cloud.google.com/storage/browser".cyan) UI.message("") UI.message("You need to give your account the correct permissions:") UI.message("") UI.message("\t\t 1. Click on your bucket to open it".cyan) UI.message("\t\t 2. Click 'Permissions'".cyan) UI.message("\t\t 3. Click 'Add members'".cyan) UI.message("\t\t 4. Enter the service account email address".cyan) UI.message("\t\t 5. Set the role to 'Storage Admin'".cyan) UI.message("\t\t 6. Click 'Save'".cyan) UI.message("") UI.input("Confirm with [Enter] once you're finished") end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/storage/s3_storage.rb
match/lib/match/storage/s3_storage.rb
require 'fastlane_core/command_executor' require 'fastlane_core/configuration/configuration' require 'fastlane/helper/s3_client_helper' require_relative '../options' require_relative '../module' require_relative '../spaceship_ensure' require_relative './interface' module Match module Storage # Store the code signing identities on AWS S3 class S3Storage < Interface attr_reader :s3_bucket attr_reader :s3_region attr_reader :s3_client attr_reader :s3_object_prefix attr_reader :readonly attr_reader :username attr_reader :team_id attr_reader :team_name attr_reader :api_key_path attr_reader :api_key def self.configure(params) s3_region = params[:s3_region] s3_access_key = params[:s3_access_key] s3_secret_access_key = params[:s3_secret_access_key] s3_bucket = params[:s3_bucket] s3_object_prefix = params[:s3_object_prefix] if params[:git_url].to_s.length > 0 UI.important("Looks like you still define a `git_url` somewhere, even though") UI.important("you use S3 Storage. You can remove the `git_url`") UI.important("from your Matchfile and Fastfile") UI.message("The above is just a warning, fastlane will continue as usual now...") end return self.new( s3_region: s3_region, s3_access_key: s3_access_key, s3_secret_access_key: s3_secret_access_key, s3_bucket: s3_bucket, s3_object_prefix: s3_object_prefix, readonly: params[:readonly], username: params[:username], team_id: params[:team_id], team_name: params[:team_name], api_key_path: params[:api_key_path], api_key: params[:api_key] ) end def initialize(s3_region: nil, s3_access_key: nil, s3_secret_access_key: nil, s3_bucket: nil, s3_object_prefix: nil, readonly: nil, username: nil, team_id: nil, team_name: nil, api_key_path: nil, api_key: nil) @s3_bucket = s3_bucket @s3_region = s3_region @s3_client = Fastlane::Helper::S3ClientHelper.new(access_key: s3_access_key, secret_access_key: s3_secret_access_key, region: s3_region) @s3_object_prefix = s3_object_prefix.to_s @readonly = readonly @username = username @team_id = team_id @team_name = team_name @api_key_path = api_key_path @api_key = api_key end # To make debugging easier, we have a custom exception here def prefixed_working_directory # We fall back to "*", which means certificates and profiles # from all teams that use this bucket would be installed. This is not ideal, but # unless the user provides a `team_id`, we can't know which one to use # This only happens if `readonly` is activated, and no `team_id` was provided @_folder_prefix ||= currently_used_team_id if @_folder_prefix.nil? # We use a `@_folder_prefix` variable, to keep state between multiple calls of this # method, as the value won't change. This way the warning is only printed once UI.important("Looks like you run `match` in `readonly` mode, and didn't provide a `team_id`. This will still work, however it is recommended to provide a `team_id` in your Appfile or Matchfile") @_folder_prefix = "*" end return File.join(working_directory, @_folder_prefix) end # Call this method for the initial clone/download of the # user's certificates & profiles # As part of this method, the `self.working_directory` attribute # will be set def download # Check if we already have a functional working_directory return if @working_directory && Dir.exist?(@working_directory) # No existing working directory, creating a new one now self.working_directory = Dir.mktmpdir # If team_id is defined, use `:team/` as a prefix (appending it at the end of the `s3_object_prefix` if one provided by the user), # so that we limit the download to only files that are specific to this team, and avoid downloads + decryption of unnecessary files. key_prefix = team_id.nil? ? s3_object_prefix : File.join(s3_object_prefix, team_id, '').delete_prefix('/') objects_to_download = s3_client.find_bucket!(s3_bucket).objects(prefix: key_prefix).reject { |object| object.key.end_with?("/") } UI.message("Downloading #{objects_to_download.count} files from S3 bucket...") objects_to_download.each do |object| file_path = strip_s3_object_prefix(object.key) # :s3_object_prefix:team_id/path/to/file # strip s3_prefix from file_path download_path = File.join(self.working_directory, file_path) FileUtils.mkdir_p(File.expand_path("..", download_path)) UI.verbose("Downloading file from S3 '#{file_path}' on bucket #{self.s3_bucket}") s3_client.download_file(s3_bucket, object.key, download_path) end UI.verbose("Successfully downloaded files from S3 to #{self.working_directory}") end # Returns a short string describing + identifying the current # storage backend. This will be printed when nuking a storage def human_readable_description return "S3 Bucket [#{s3_bucket}] on region #{s3_region}" end def upload_files(files_to_upload: [], custom_message: nil) # `files_to_upload` is an array of files that need to be uploaded to S3 # Those doesn't mean they're new, it might just be they're changed # Either way, we'll upload them using the same technique files_to_upload.each do |file_name| # Go from # "/var/folders/px/bz2kts9n69g8crgv4jpjh6b40000gn/T/d20181026-96528-1av4gge/:team_id/profiles/development/Development_me.mobileprovision" # to # ":s3_object_prefix:team_id/profiles/development/Development_me.mobileprovision" # target_path = s3_object_path(file_name) UI.verbose("Uploading '#{target_path}' to S3 Storage...") body = File.read(file_name) acl = 'private' s3_url = s3_client.upload_file(s3_bucket, target_path, body, acl) UI.verbose("Uploaded '#{s3_url}' to S3 Storage.") end end def delete_files(files_to_delete: [], custom_message: nil) files_to_delete.each do |file_name| target_path = s3_object_path(file_name) UI.verbose("Deleting '#{target_path}' from S3 Storage...") s3_client.delete_file(s3_bucket, target_path) end end def skip_docs false end def list_files(file_name: "", file_ext: "") Dir[File.join(working_directory, self.team_id, "**", file_name, "*.#{file_ext}")] end # Implement this for the `fastlane match init` command # This method must return the content of the Matchfile # that should be generated def generate_matchfile_content(template: nil) return "s3_bucket(\"#{self.s3_bucket}\")" end private def s3_object_path(file_name) sanitized = sanitize_file_name(file_name) return sanitized if sanitized.start_with?(s3_object_prefix) s3_object_prefix + sanitized end def strip_s3_object_prefix(object_path) object_path.delete_prefix(s3_object_prefix.to_s).delete_prefix('/') end def sanitize_file_name(file_name) file_name.gsub(self.working_directory + "/", "") end def currently_used_team_id if self.readonly # In readonly mode, we still want to see if the user provided a team_id # see `prefixed_working_directory` comments for more details return self.team_id else UI.user_error!("The `team_id` option is required. fastlane cannot automatically determine portal team id via the App Store Connect API (yet)") if self.team_id.to_s.empty? spaceship = SpaceshipEnsure.new(self.username, self.team_id, self.team_name, api_token) return spaceship.team_id end end def api_token api_token = Spaceship::ConnectAPI::Token.from(hash: self.api_key, filepath: self.api_key_path) api_token ||= Spaceship::ConnectAPI.token return api_token end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/storage/git_storage.rb
match/lib/match/storage/git_storage.rb
require 'fastlane_core/command_executor' require_relative '../module' require_relative './interface' module Match module Storage # Store the code signing identities in a git repo class GitStorage < Interface # User provided values attr_accessor :git_url attr_accessor :shallow_clone attr_accessor :skip_docs attr_accessor :branch attr_accessor :git_full_name attr_accessor :git_user_email attr_accessor :clone_branch_directly attr_accessor :type attr_accessor :platform attr_accessor :git_basic_authorization attr_accessor :git_bearer_authorization attr_accessor :git_private_key def self.configure(params) return self.new( type: params[:type].to_s, platform: params[:platform].to_s, git_url: params[:git_url], shallow_clone: params[:shallow_clone], skip_docs: params[:skip_docs], branch: params[:git_branch], git_full_name: params[:git_full_name], git_user_email: params[:git_user_email], clone_branch_directly: params[:clone_branch_directly], git_basic_authorization: params[:git_basic_authorization], git_bearer_authorization: params[:git_bearer_authorization], git_private_key: params[:git_private_key] ) end def initialize(type: nil, platform: nil, git_url: nil, shallow_clone: nil, skip_docs: false, branch: "master", git_full_name: nil, git_user_email: nil, clone_branch_directly: false, git_basic_authorization: nil, git_bearer_authorization: nil, git_private_key: nil) self.git_url = git_url self.shallow_clone = shallow_clone self.skip_docs = skip_docs self.branch = branch self.git_full_name = git_full_name self.git_user_email = git_user_email self.clone_branch_directly = clone_branch_directly self.git_basic_authorization = git_basic_authorization self.git_bearer_authorization = git_bearer_authorization self.git_private_key = convert_private_key_path_to_absolute(git_private_key) self.type = type if type self.platform = platform if platform end def convert_private_key_path_to_absolute(git_private_key) if !git_private_key.nil? && File.file?(File.expand_path(git_private_key)) File.expand_path(git_private_key).shellescape.to_s else git_private_key end end def prefixed_working_directory return working_directory end def download # Check if we already have a functional working_directory return if @working_directory # No existing working directory, creating a new one now self.working_directory = Dir.mktmpdir command = "git clone #{self.git_url.shellescape} #{self.working_directory.shellescape}" # HTTP headers are supposed to be case-insensitive but # Bitbucket requires `Authorization: Basic` and `Authorization Bearer` to work # https://github.com/fastlane/fastlane/pull/15928 command << " -c http.extraheader='Authorization: Basic #{self.git_basic_authorization}'" unless self.git_basic_authorization.nil? command << " -c http.extraheader='Authorization: Bearer #{self.git_bearer_authorization}'" unless self.git_bearer_authorization.nil? if self.shallow_clone command << " --depth 1" end if self.clone_branch_directly command += " -b #{self.branch.shellescape} --single-branch" elsif self.shallow_clone # shallow clone all branches if not cloning branch directly command += " --no-single-branch" end command = command_from_private_key(command) unless self.git_private_key.nil? UI.message("Cloning remote git repo...") if self.branch && !self.clone_branch_directly UI.message("If cloning the repo takes too long, you can use the `clone_branch_directly` option in match.") end begin # GIT_TERMINAL_PROMPT will fail the `git clone` command if user credentials are missing Helper.with_env_values('GIT_TERMINAL_PROMPT' => '0') do FastlaneCore::CommandExecutor.execute(command: command, print_all: FastlaneCore::Globals.verbose?, print_command: FastlaneCore::Globals.verbose?) end rescue UI.error("Error cloning certificates repo, please make sure you have read access to the repository you want to use") if self.branch && self.clone_branch_directly UI.error("You passed '#{self.branch}' as branch in combination with the `clone_branch_directly` flag. Please remove `clone_branch_directly` flag on the first run for _match_ to create the branch.") end UI.error("Run the following command manually to make sure you're properly authenticated:") UI.command(command) UI.user_error!("Error cloning certificates git repo, please make sure you have access to the repository - see instructions above") end add_user_config(self.git_full_name, self.git_user_email) unless File.directory?(self.working_directory) UI.user_error!("Error cloning repo, make sure you have access to it '#{self.git_url}'") end checkout_branch end def human_readable_description "Git Repo [#{self.git_url}]" end def delete_files(files_to_delete: [], custom_message: nil) if files_to_delete.count > 0 commands = files_to_delete.map { |filename| "git rm #{filename.shellescape}" } git_push(commands: commands, commit_message: custom_message) end end def upload_files(files_to_upload: [], custom_message: nil) commands = files_to_upload.map do |current_file| "git add #{current_file.shellescape}" end git_push(commands: commands, commit_message: custom_message) end # Generate the commit message based on the user's parameters def generate_commit_message [ "[fastlane]", "Updated", self.type, "and platform", self.platform ].join(" ") end def generate_matchfile_content UI.important("Please create a new, private git repository to store the certificates and profiles there") url = UI.input("URL of the Git Repo: ") return "git_url(\"#{url}\")" end def list_files(file_name: "", file_ext: "") Dir[File.join(working_directory, "**", file_name, "*.#{file_ext}")] end def command_from_private_key(command) if File.file?(self.git_private_key) ssh_add = File.expand_path(self.git_private_key).shellescape.to_s else UI.message("Private key file does not exist, will continue by using it as a raw key.") ssh_add = "- <<< \"#{self.git_private_key}\"" end return "ssh-agent bash -c 'ssh-add #{ssh_add}; #{command}'" end private # Create and checkout an specific branch in the git repo def checkout_branch return unless self.working_directory commands = [] if branch_exists?(self.branch) # Checkout the branch if it already exists commands << "git checkout #{self.branch.shellescape}" else # If a new branch is being created, we create it as an 'orphan' to not inherit changes from the master branch. commands << "git checkout --orphan #{self.branch.shellescape}" # We also need to reset the working directory to not transfer any uncommitted changes to the new branch. commands << "git reset --hard" end UI.message("Checking out branch #{self.branch}...") Dir.chdir(self.working_directory) do commands.each do |command| FastlaneCore::CommandExecutor.execute(command: command, print_all: FastlaneCore::Globals.verbose?, print_command: FastlaneCore::Globals.verbose?) end end end # Checks if a specific branch exists in the git repo def branch_exists?(branch) return unless self.working_directory result = Dir.chdir(self.working_directory) do FastlaneCore::CommandExecutor.execute(command: "git --no-pager branch --list origin/#{branch.shellescape} --no-color -r", print_all: FastlaneCore::Globals.verbose?, print_command: FastlaneCore::Globals.verbose?) end return !result.empty? end def add_user_config(user_name, user_email) # Add git config if needed commands = [] commands << "git config user.name \"#{user_name}\"" unless user_name.nil? commands << "git config user.email \"#{user_email}\"" unless user_email.nil? return if commands.empty? UI.message("Add git user config to local git repo...") Dir.chdir(self.working_directory) do commands.each do |command| FastlaneCore::CommandExecutor.execute(command: command, print_all: FastlaneCore::Globals.verbose?, print_command: FastlaneCore::Globals.verbose?) end end end def git_push(commands: [], commit_message: nil) commit_message ||= generate_commit_message commands << "git commit -m #{commit_message.shellescape}" git_push_command = "git push origin #{self.branch.shellescape}" git_push_command = command_from_private_key(git_push_command) unless self.git_private_key.nil? commands << git_push_command UI.message("Pushing changes to remote git repo...") Helper.with_env_values('GIT_TERMINAL_PROMPT' => '0') do commands.each do |command| FastlaneCore::CommandExecutor.execute(command: command, print_all: FastlaneCore::Globals.verbose?, print_command: FastlaneCore::Globals.verbose?) end end rescue => ex UI.error("Couldn't commit or push changes back to git...") UI.error(ex) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/storage/gitlab_secure_files.rb
match/lib/match/storage/gitlab_secure_files.rb
require 'fastlane_core/command_executor' require 'fastlane_core/configuration/configuration' require 'net/http/post/multipart' require_relative './gitlab/client' require_relative './gitlab/secure_file' require_relative '../options' require_relative '../module' require_relative '../spaceship_ensure' require_relative './interface' module Match module Storage # Store the code signing identities in GitLab Secure Files class GitLabSecureFiles < Interface attr_reader :gitlab_client attr_reader :project_id attr_reader :readonly attr_reader :username attr_reader :team_id attr_reader :team_name attr_reader :api_key_path attr_reader :api_key attr_reader :api_v4_url def self.configure(params) api_v4_url = ENV['CI_API_V4_URL'] || "#{params[:gitlab_host]}/api/v4" project_id = params[:gitlab_project] || ENV['GITLAB_PROJECT'] || ENV['CI_PROJECT_ID'] job_token = params[:job_token] || ENV['CI_JOB_TOKEN'] private_token = params[:private_token] || ENV['PRIVATE_TOKEN'] if params[:git_url].to_s.length > 0 UI.important("Looks like you still define a `git_url` somewhere, even though") UI.important("you use GitLab Secure Files. You can remove the `git_url`") UI.important("from your Matchfile and Fastfile") UI.message("The above is just a warning, fastlane will continue as usual now...") end return self.new( api_v4_url: api_v4_url, project_id: project_id, job_token: job_token, private_token: private_token, readonly: params[:readonly], username: params[:username], team_id: params[:team_id], team_name: params[:team_name], api_key_path: params[:api_key_path], api_key: params[:api_key], gitlab_host: params[:gitlab_host] ) end def initialize(api_v4_url: nil, project_id: nil, job_token: nil, private_token: nil, readonly: nil, username: nil, team_id: nil, team_name: nil, api_key_path: nil, api_key: nil, gitlab_host: nil) @readonly = readonly @username = username @team_id = team_id @team_name = team_name @api_key_path = api_key_path @api_key = api_key @gitlab_host = gitlab_host @job_token = job_token @private_token = private_token @api_v4_url = api_v4_url @project_id = project_id @gitlab_client = GitLab::Client.new(job_token: @job_token, private_token: @private_token, project_id: @project_id, api_v4_url: @api_v4_url) UI.message("Initializing match for GitLab project #{@project_id} on #{@gitlab_host}") end # To make debugging easier, we have a custom exception here def prefixed_working_directory # We fall back to "*", which means certificates and profiles # from all teams that use this bucket would be installed. This is not ideal, but # unless the user provides a `team_id`, we can't know which one to use # This only happens if `readonly` is activated, and no `team_id` was provided @_folder_prefix ||= currently_used_team_id if @_folder_prefix.nil? # We use a `@_folder_prefix` variable, to keep state between multiple calls of this # method, as the value won't change. This way the warning is only printed once UI.important("Looks like you run `match` in `readonly` mode, and didn't provide a `team_id`. This will still work, however it is recommended to provide a `team_id` in your Appfile or Matchfile") @_folder_prefix = "*" end return File.join(working_directory, @_folder_prefix) end def download gitlab_client.prompt_for_access_token # Check if we already have a functional working_directory return if @working_directory # No existing working directory, creating a new one now self.working_directory = Dir.mktmpdir @gitlab_client.files.each do |secure_file| secure_file.download(self.working_directory) end UI.verbose("Successfully downloaded all Secure Files from GitLab to #{self.working_directory}") end def currently_used_team_id if self.readonly # In readonly mode, we still want to see if the user provided a team_id # see `prefixed_working_directory` comments for more details return self.team_id else UI.user_error!("The `team_id` option is required. fastlane cannot automatically determine portal team id via the App Store Connect API (yet)") if self.team_id.to_s.empty? spaceship = SpaceshipEnsure.new(self.username, self.team_id, self.team_name, api_token) return spaceship.team_id end end def api_token api_token = Spaceship::ConnectAPI::Token.from(hash: self.api_key, filepath: self.api_key_path) api_token ||= Spaceship::ConnectAPI.token return api_token end # Returns a short string describing + identifying the current # storage backend. This will be printed when nuking a storage def human_readable_description "GitLab Secure Files Storage [#{self.project_id}]" end def upload_files(files_to_upload: [], custom_message: nil) # `files_to_upload` is an array of files that need to be uploaded to GitLab Secure Files # Those doesn't mean they're new, it might just be they're changed # Either way, we'll upload them using the same technique files_to_upload.each do |current_file| # Go from # "/var/folders/px/bz2kts9n69g8crgv4jpjh6b40000gn/T/d20181026-96528-1av4gge/profiles/development/Development_me.mobileprovision" # to # "profiles/development/Development_me.mobileprovision" # # We also remove the trailing `/` target_file = current_file.gsub(self.working_directory + "/", "") UI.verbose("Uploading '#{target_file}' to GitLab Secure Files...") @gitlab_client.upload_file(current_file, target_file) end end def delete_files(files_to_delete: [], custom_message: nil) files_to_delete.each do |current_file| target_path = current_file.gsub(self.working_directory + "/", "") secure_file = @gitlab_client.find_file_by_name(target_path) UI.message("Deleting '#{target_path}' from GitLab Secure Files...") secure_file.delete end end def skip_docs true end def list_files(file_name: "", file_ext: "") Dir[File.join(working_directory, self.team_id, "**", file_name, "*.#{file_ext}")] end # Implement this for the `fastlane match init` command # This method must return the content of the Matchfile # that should be generated def generate_matchfile_content(template: nil) project = UI.input("What is your GitLab Project (i.e. gitlab-org/gitlab): ") host = UI.input("What is your GitLab Host (i.e. https://gitlab.example.com, skip to default to https://gitlab.com): ") content = "gitlab_project(\"#{project}\")" content += "\ngitlab_host(\"#{host}\")" if host return content end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/storage/gitlab/secure_file.rb
match/lib/match/storage/gitlab/secure_file.rb
require 'open-uri' require_relative '../../module' module Match module Storage class GitLab class SecureFile attr_reader :client, :file def initialize(file:, client:) @file = OpenStruct.new(file) @client = client end def file_url "#{@client.base_url}/#{@file.id}" end def create_subfolders(working_directory) FileUtils.mkdir_p("#{working_directory}/#{destination_file_path}") end def destination_file_path filename = @file.name.split('/').last @file.name.gsub(filename, '').gsub(%r{^/}, '') end def valid_checksum?(file) Digest::SHA256.hexdigest(File.read(file)) == @file.checksum end def download(working_directory) url = URI("#{file_url}/download") begin destination_file = "#{working_directory}/#{@file.name}" create_subfolders(working_directory) File.open(destination_file, "wb") do |saved_file| URI.open(url, "rb", { @client.authentication_key => @client.authentication_value }) do |data| saved_file.write(data.read) end FileUtils.chmod('u=rw,go-r', destination_file) end UI.crash!("Checksum validation failed for #{@file.name}") unless valid_checksum?(destination_file) rescue OpenURI::HTTPError => msg UI.error("Unable to download #{@file.name} - #{msg}") end end def delete url = URI(file_url) request = Net::HTTP::Delete.new(url.request_uri) @client.execute_request(url, request) end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/storage/gitlab/client.rb
match/lib/match/storage/gitlab/client.rb
require 'net/http/post/multipart' require 'securerandom' require_relative '../../module' require_relative './secure_file' module Match module Storage class GitLab class Client def initialize(api_v4_url:, project_id:, job_token: nil, private_token: nil) @job_token = job_token @private_token = private_token @api_v4_url = api_v4_url @project_id = project_id UI.important("JOB_TOKEN and PRIVATE_TOKEN both defined, using JOB_TOKEN to execute this job.") if @job_token && @private_token end def base_url return "#{@api_v4_url}/projects/#{CGI.escape(@project_id)}/secure_files" end def authentication_key if @job_token return "JOB-TOKEN" elsif @private_token return "PRIVATE-TOKEN" end end def authentication_value if @job_token return @job_token elsif @private_token return @private_token end end def files @files ||= begin url = URI.parse(base_url) # 100 is maximum number of Secure files available on GitLab https://docs.gitlab.com/ee/api/secure_files.html url.query = [url.query, "per_page=100"].compact.join('&') request = Net::HTTP::Get.new(url.request_uri) res = execute_request(url, request) data = [] JSON.parse(res.body).each do |file| data << SecureFile.new(client: self, file: file) end data end end def find_file_by_name(name) files.select { |secure_file| secure_file.file.name == name }.first end def upload_file(current_file, target_file) url = URI.parse(base_url) File.open(current_file) do |file| request = Net::HTTP::Post::Multipart.new( url.path, "file" => UploadIO.new(file, "application/octet-stream"), "name" => target_file ) execute_request(url, request, target_file) end end def execute_request(url, request, target_file = nil) request[authentication_key] = authentication_value http = Net::HTTP.new(url.host, url.port) http.use_ssl = url.instance_of?(URI::HTTPS) begin response = http.request(request) rescue Errno::ECONNREFUSED, SocketError => message UI.user_error!("GitLab connection error: #{message}") end unless response.kind_of?(Net::HTTPSuccess) handle_response_error(response, target_file) end response end def handle_response_error(response, target_file = nil) error_prefix = "GitLab storage error:" file_debug_string = "File: #{target_file}" unless target_file.nil? api_debug_string = "API: #{@api_v4_url}" debug_info = "(#{[file_debug_string, api_debug_string].compact.join(', ')})" begin parsed = JSON.parse(response.body) rescue JSON::ParserError end if parsed && parsed["message"] && (parsed["message"]["name"] == ["has already been taken"]) error_handler = :error error = "#{target_file} already exists in GitLab project #{@project_id}, file not uploaded" else error_handler = :user_error! error = "#{response.code}: #{response.body}" end error_message = [error_prefix, error, debug_info].join(' ') UI.send(error_handler, error_message) end def prompt_for_access_token unless authentication_key @private_token = UI.input("Please supply a GitLab personal or project access token: ") end end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/encryption/interface.rb
match/lib/match/encryption/interface.rb
module Match module Encryption class Interface # Call this method to trigger the actual # encryption def encrypt_files(password: nil) not_implemented(__method__) end # Call this method to trigger the actual # decryption def decrypt_files not_implemented(__method__) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/encryption/encryption.rb
match/lib/match/encryption/encryption.rb
require 'base64' require 'openssl' require 'securerandom' module Match module Encryption # This is to keep backwards compatibility with the old fastlane version which used the local openssl installation. # The encryption parameters in this implementation reflect the old behavior which was the most common default value in those versions. # As for decryption, 1.0.x OpenSSL and earlier versions use MD5, 1.1.0c and newer uses SHA256, we try both before giving an error class EncryptionV1 ALGORITHM = 'aes-256-cbc' def encrypt(data:, password:, salt:, hash_algorithm: "MD5") cipher = ::OpenSSL::Cipher.new(ALGORITHM) cipher.encrypt keyivgen(cipher, password, salt, hash_algorithm) encrypted_data = cipher.update(data) encrypted_data << cipher.final { encrypted_data: encrypted_data } end def decrypt(encrypted_data:, password:, salt:, hash_algorithm: "MD5") cipher = ::OpenSSL::Cipher.new(ALGORITHM) cipher.decrypt keyivgen(cipher, password, salt, hash_algorithm) data = cipher.update(encrypted_data) data << cipher.final end private def keyivgen(cipher, password, salt, hash_algorithm) cipher.pkcs5_keyivgen(password, salt, 1, hash_algorithm) end end # The newer encryption mechanism, which features a more secure key and IV generation. # # The IV is randomly generated and provided unencrypted. # The salt should be randomly generated and provided unencrypted (like in the current implementation). # The key is generated with OpenSSL::KDF::pbkdf2_hmac with properly chosen parameters. # # Short explanation about salt and IV: https://stackoverflow.com/a/1950674/6324550 class EncryptionV2 ALGORITHM = 'aes-256-gcm' def encrypt(data:, password:, salt:) cipher = ::OpenSSL::Cipher.new(ALGORITHM) cipher.encrypt keyivgen(cipher, password, salt) encrypted_data = cipher.update(data) encrypted_data << cipher.final auth_tag = cipher.auth_tag { encrypted_data: encrypted_data, auth_tag: auth_tag } end def decrypt(encrypted_data:, password:, salt:, auth_tag:) cipher = ::OpenSSL::Cipher.new(ALGORITHM) cipher.decrypt keyivgen(cipher, password, salt) cipher.auth_tag = auth_tag data = cipher.update(encrypted_data) data << cipher.final end private def keyivgen(cipher, password, salt) keyIv = ::OpenSSL::KDF.pbkdf2_hmac(password, salt: salt, iterations: 10_000, length: 32 + 12 + 24, hash: "sha256") key = keyIv[0..31] iv = keyIv[32..43] auth_data = keyIv[44..-1] cipher.key = key cipher.iv = iv cipher.auth_data = auth_data end end class MatchDataEncryption V1_PREFIX = "Salted__" V2_PREFIX = "match_encrypted_v2__" def encrypt(data:, password:, version: 2) salt = SecureRandom.random_bytes(8) if version == 2 e = EncryptionV2.new encryption = e.encrypt(data: data, password: password, salt: salt) encrypted_data = V2_PREFIX + salt + encryption[:auth_tag] + encryption[:encrypted_data] else e = EncryptionV1.new encryption = e.encrypt(data: data, password: password, salt: salt) encrypted_data = V1_PREFIX + salt + encryption[:encrypted_data] end Base64.encode64(encrypted_data) end def decrypt(base64encoded_encrypted:, password:) stored_data = Base64.decode64(base64encoded_encrypted) if stored_data.start_with?(V2_PREFIX) salt = stored_data[20..27] auth_tag = stored_data[28..43] data_to_decrypt = stored_data[44..-1] e = EncryptionV2.new e.decrypt(encrypted_data: data_to_decrypt, password: password, salt: salt, auth_tag: auth_tag) else salt = stored_data[8..15] data_to_decrypt = stored_data[16..-1] e = EncryptionV1.new begin # Note that we are not guaranteed to catch the decryption errors here if the password or the hash is wrong # as there's no integrity checks. # see https://github.com/fastlane/fastlane/issues/21663 e.decrypt(encrypted_data: data_to_decrypt, password: password, salt: salt) # With the wrong hash_algorithm, there's here 0.4% chance that the decryption failure will go undetected rescue => _ex # With a wrong password, there's a 0.4% chance it will decrypt garbage and not fail fallback_hash_algorithm = "SHA256" e.decrypt(encrypted_data: data_to_decrypt, password: password, salt: salt, hash_algorithm: fallback_hash_algorithm) end end end end # The methods of this class will encrypt or decrypt files in place, by default. class MatchFileEncryption def encrypt(file_path:, password:, output_path: nil, version: 2) output_path = file_path unless output_path data_to_encrypt = File.binread(file_path) e = MatchDataEncryption.new data = e.encrypt(data: data_to_encrypt, password: password, version: version) File.write(output_path, data) end def decrypt(file_path:, password:, output_path: nil) output_path = file_path unless output_path content = File.read(file_path) e = MatchDataEncryption.new decrypted_data = e.decrypt(base64encoded_encrypted: content, password: password) File.binwrite(output_path, decrypted_data) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/match/lib/match/encryption/openssl.rb
match/lib/match/encryption/openssl.rb
require 'base64' require 'openssl' require 'securerandom' require 'security' require 'shellwords' require_relative '../change_password' require_relative '../module' module Match module Encryption class OpenSSL < Interface attr_accessor :keychain_name attr_accessor :working_directory attr_accessor :force_legacy_encryption def self.configure(params) return self.new( keychain_name: params[:keychain_name], working_directory: params[:working_directory], force_legacy_encryption: params[:force_legacy_encryption] ) end # @param keychain_name: The identifier used to store the passphrase in the Keychain # @param working_directory: The path to where the certificates are stored # @param force_legacy_encryption: Force use of legacy EncryptionV1 algorithm def initialize(keychain_name: nil, working_directory: nil, force_legacy_encryption: false) self.keychain_name = keychain_name self.working_directory = working_directory self.force_legacy_encryption = force_legacy_encryption end def encrypt_files(password: nil) files = [] password ||= fetch_password! iterate(self.working_directory) do |current| files << current encrypt_specific_file(path: current, password: password, version: force_legacy_encryption ? 1 : 2) UI.success("🔒 Encrypted '#{File.basename(current)}'") if FastlaneCore::Globals.verbose? end UI.success("🔒 Successfully encrypted certificates repo") return files end def decrypt_files files = [] password = fetch_password! iterate(self.working_directory) do |current| files << current begin decrypt_specific_file(path: current, password: password) rescue => ex UI.verbose(ex.to_s) UI.error("Couldn't decrypt the repo, please make sure you enter the right password!") UI.user_error!("Invalid password passed via 'MATCH_PASSWORD'") if ENV["MATCH_PASSWORD"] clear_password self.decrypt_files # Call itself return end UI.success("🔓 Decrypted '#{File.basename(current)}'") if FastlaneCore::Globals.verbose? end UI.success("🔓 Successfully decrypted certificates repo") return files end def store_password(password) Security::InternetPassword.add(server_name(self.keychain_name), "", password) end # removes the password from the keychain again def clear_password Security::InternetPassword.delete(server: server_name(self.keychain_name)) end private def iterate(source_path) Dir[File.join(source_path, "**", "*.{cer,p12,mobileprovision,provisionprofile}")].each do |path| next if File.directory?(path) yield(path) end end # server name used for accessing the macOS keychain def server_name(keychain_name) ["match", keychain_name].join("_") end # Access the MATCH_PASSWORD, either from ENV variable, Keychain or user input def fetch_password! password = ENV["MATCH_PASSWORD"] unless password item = Security::InternetPassword.find(server: server_name(self.keychain_name)) password = item.password if item end unless password if !UI.interactive? UI.error("Neither the MATCH_PASSWORD environment variable nor the local keychain contained a password.") UI.error("Bailing out instead of asking for a password, since this is non-interactive mode.") UI.user_error!("Try setting the MATCH_PASSWORD environment variable, or temporarily enable interactive mode to store a password.") else UI.important("Enter the passphrase that should be used to encrypt/decrypt your certificates") UI.important("This passphrase is specific per repository and will be stored in your local keychain") UI.important("Make sure to remember the password, as you'll need it when you run match on a different machine") password = FastlaneCore::Helper.ask_password(message: "Passphrase for Match storage: ", confirm: true) store_password(password) end end return password end def encrypt_specific_file(path: nil, password: nil, version: nil) UI.user_error!("No password supplied") if password.to_s.strip.length == 0 e = MatchFileEncryption.new e.encrypt(file_path: path, password: password, version: version) rescue FastlaneCore::Interface::FastlaneError raise rescue => error UI.error(error.to_s) UI.crash!("Error encrypting '#{path}'") end def decrypt_specific_file(path: nil, password: nil) e = MatchFileEncryption.new e.decrypt(file_path: path, password: password) rescue => error UI.error(error.to_s) UI.crash!("Error decrypting '#{path}'") end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/spec/commands_generator_spec.rb
screengrab/spec/commands_generator_spec.rb
require 'screengrab/commands_generator' describe Screengrab::CommandsGenerator do let(:available_options) { Screengrab::Options.available_options } describe ":run option handling" do def expect_runner_run_with(android_home) allow(Screengrab::DetectValues).to receive(:set_additional_default_values) expect(Screengrab::AndroidEnvironment).to receive(:new).with(android_home, nil) allow(Screengrab::DependencyChecker).to receive(:check) expect(Screengrab::Runner).to receive_message_chain(:new, :run) end it "can use the android_home short flag from tool options" do # leaving out the command name defaults to 'run' stub_commander_runner_args(['-n', 'home/path']) expect_runner_run_with('home/path') Screengrab::CommandsGenerator.start end it "can use the output_directory flag from tool options" do # leaving out the command name defaults to 'run' stub_commander_runner_args(['-n', 'home/path', '--output_directory', 'output/dir']) expect_runner_run_with('home/path') Screengrab::CommandsGenerator.start expect(Screengrab.config[:output_directory]).to eq('output/dir') end end # :init is not tested here because it does not use any tool options end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/spec/android_environment_spec.rb
screengrab/spec/android_environment_spec.rb
describe Screengrab do describe Screengrab::AndroidEnvironment do before(:each) do allow(FastlaneCore::Helper).to receive(:windows?).and_return(false) end describe "with an empty ANDROID_HOME and an empty PATH" do it "finds no useful values" do FastlaneSpec::Env.with_env_values('PATH' => 'screengrab/spec/fixtures/empty_home_empty_path/path') do android_env = Screengrab::AndroidEnvironment.new('screengrab/spec/fixtures/empty_home_empty_path/android_home') expect(android_env.android_home).to eq('screengrab/spec/fixtures/empty_home_empty_path/android_home') expect(android_env.platform_tools_path).to be_nil expect(android_env.adb_path).to be_nil end end end describe "with an empty ANDROID_HOME and a complete PATH" do it "finds commands on the PATH" do FastlaneSpec::Env.with_env_values('PATH' => 'screengrab/spec/fixtures/empty_home_complete_path/path') do android_env = Screengrab::AndroidEnvironment.new('screengrab/spec/fixtures/empty_home_complete_path/android_home') expect(android_env.android_home).to eq('screengrab/spec/fixtures/empty_home_complete_path/android_home') expect(android_env.platform_tools_path).to be_nil expect(android_env.adb_path).to eq('screengrab/spec/fixtures/empty_home_complete_path/path/adb') end end end describe "with a complete ANDROID_HOME and a complete PATH" do it "finds adb in platform-tools" do FastlaneSpec::Env.with_env_values('PATH' => 'screengrab/spec/fixtures/complete_home_complete_path/path') do android_env = Screengrab::AndroidEnvironment.new('screengrab/spec/fixtures/complete_home_complete_path/android_home') expect(android_env.android_home).to eq('screengrab/spec/fixtures/complete_home_complete_path/android_home') expect(android_env.platform_tools_path).to eq('screengrab/spec/fixtures/complete_home_complete_path/android_home/platform-tools') expect(android_env.adb_path).to eq('screengrab/spec/fixtures/complete_home_complete_path/android_home/platform-tools/adb') end end end end describe "on windows", if: FastlaneCore::Helper.windows? do describe "with an empty ANDROID_HOME and a complete PATH" do it "finds commands on the PATH" do FastlaneSpec::Env.with_env_values('PATH' => 'screengrab\\spec\\fixtures\\empty_home_complete_path_windows\\path', 'PATHEXT' => ".EXE") do android_env = Screengrab::AndroidEnvironment.new('screengrab\\spec\\fixtures\\empty_home_complete_path_windows\\android_home', nil) expect(android_env.android_home).to eq('screengrab\\spec\\fixtures\\empty_home_complete_path_windows\\android_home') expect(android_env.platform_tools_path).to be_nil expect(android_env.adb_path).to eq('screengrab\\spec\\fixtures\\empty_home_complete_path_windows\\path\\adb.exe') end end end describe "with a complete ANDROID_HOME and a complete PATH and no build tools version specified" do it "finds adb.exe in platform-tools and aapt in the highest version build tools dir" do FastlaneSpec::Env.with_env_values('PATH' => 'screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\path', 'PATHEXT' => ".EXE") do android_env = Screengrab::AndroidEnvironment.new('screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\android_home', nil) expect(android_env.android_home).to eq('screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\android_home') expect(android_env.platform_tools_path).to eq('screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\android_home\\platform-tools') expect(android_env.adb_path).to eq('screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\android_home\\platform-tools\\adb.exe') end end end describe "with a complete ANDROID_HOME and a complete PATH and no build tools version specified" do it "finds adb in platform-tools and aapt in the highest version build tools dir" do FastlaneSpec::Env.with_env_values('PATH' => 'screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\path', 'PATHEXT' => ".EXE") do android_env = Screengrab::AndroidEnvironment.new('screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\android_home', nil) expect(android_env.android_home).to eq('screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\android_home') expect(android_env.platform_tools_path).to eq('screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\android_home\\platform-tools') expect(android_env.adb_path).to eq('screengrab\\spec\\fixtures\\complete_home_complete_path_windows\\android_home\\platform-tools\\adb.exe') end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/spec/runner_spec.rb
screengrab/spec/runner_spec.rb
describe Screengrab::Runner do let(:config) { { tests_package_name: "com.package.app", test_instrumentation_runner: "Runner" } } let(:ui) { Screengrab::UI } let(:mock_android_environment) { double(Screengrab.android_environment) } let(:mock_executor) { class_double('FastlaneCore::CommandExecutor') } before do @runner = Screengrab::Runner.new(mock_executor, config, mock_android_environment) end def mock_adb_response_for_command(command, mock_response) expect(mock_executor).to receive(:execute) .with(hash_including(command: command)) .and_return(mock_response) end def mock_adb_response(mock_response) expect(mock_executor).to receive(:execute) .and_return(mock_response) end describe :run_tests_for_locale do let(:device_serial) { 'device_serial' } let(:test_classes_to_use) { nil } let(:test_packages_to_use) { nil } before do expect(mock_android_environment).to receive(:adb_path).and_return("adb") end context "when launch arguments are specified" do before do config[:launch_arguments] = ["username hjanuschka", "build_type x500"] config[:locales] = %w(en-US) config[:use_timestamp_suffix] = true end it 'sets custom launch_arguments' do # Don't actually try to pull screenshot from device allow(@runner).to receive(:pull_screenshots_from_device) expect(mock_executor).to receive(:execute) .with(hash_including(command: "adb -s device_serial shell am instrument --no-window-animation -w \\\n-e testLocale en-US \\\n-e appendTimestamp true \\\n-e username hjanuschka -e build_type x500 \\\ncom.package.app/Runner")) @runner.run_tests_for_locale('device', 'en-US', device_serial, test_classes_to_use, test_packages_to_use, config[:launch_arguments], 27) end end context 'when a locale is specified' do before do config[:locales] = %w(en-US) end context 'when tests produce a failure' do before do mock_adb_response('FAILURES!!!') end context 'when exit_on_test_failure is true' do before do config[:exit_on_test_failure] = true end it 'prints an error and exits the program' do # Don't actually try to pull screenshot from device allow(@runner).to receive(:pull_screenshots_from_device) expect(ui).to receive(:test_failure!).with("Tests failed for locale en-US on device #{device_serial}").and_call_original expect { @runner.run_tests_for_locale('device', 'en-US', device_serial, test_classes_to_use, test_packages_to_use, nil, 27) }.to raise_fastlane_test_failure end end context 'when exit_on_test_failure is false' do before do config[:exit_on_test_failure] = false end it 'prints an error and does not exit the program' do # Don't actually try to pull screenshot from device allow(@runner).to receive(:pull_screenshots_from_device) expect(ui).to receive(:error).with("Tests failed").and_call_original @runner.run_tests_for_locale('device', 'en-US', device_serial, test_classes_to_use, test_packages_to_use, nil, 27) end end end end context 'when using use_timestamp_suffix' do context 'when set to false' do before do @runner = Screengrab::Runner.new( mock_executor, FastlaneCore::Configuration.create(Screengrab::Options.available_options, { use_timestamp_suffix: false, tests_package_name: "com.package.app", test_instrumentation_runner: "Runner" }), mock_android_environment ) end it 'sets appendTimestamp as false' do # Don't actually try to pull screenshot from device allow(@runner).to receive(:pull_screenshots_from_device) expect(mock_executor).to receive(:execute) .with(hash_including(command: "adb -s device_serial shell am instrument --no-window-animation -w \\\n-e testLocale en-US \\\n-e appendTimestamp false \\\ncom.package.app/Runner")) @runner.run_tests_for_locale('device', 'en-US', device_serial, test_classes_to_use, test_packages_to_use, nil, 27) end end context 'use_timestamp_suffix is not specified' do before do @runner = Screengrab::Runner.new( mock_executor, FastlaneCore::Configuration.create(Screengrab::Options.available_options, { tests_package_name: "com.package.app", test_instrumentation_runner: "Runner" }), mock_android_environment ) end it 'should set appendTimestamp by default' do # Don't actually try to pull screenshot from device allow(@runner).to receive(:pull_screenshots_from_device) expect(mock_executor).to receive(:execute) .with(hash_including(command: "adb -s device_serial shell am instrument --no-window-animation -w \\\n-e testLocale en-US \\\n-e appendTimestamp true \\\ncom.package.app/Runner")) @runner.run_tests_for_locale('device', 'en-US', device_serial, test_classes_to_use, test_packages_to_use, nil, 27) end end end context 'when sdk_version is >= 28' do before do @runner = Screengrab::Runner.new( mock_executor, FastlaneCore::Configuration.create(Screengrab::Options.available_options, { tests_package_name: "com.package.app", test_instrumentation_runner: "Runner" }), mock_android_environment ) end it 'disables hidden api checks' do # Don't actually try to pull screenshot from device allow(@runner).to receive(:pull_screenshots_from_device) expect(mock_executor).to receive(:execute) .with(hash_including(command: "adb -s device_serial shell am instrument --no-window-animation -w \\\n-e testLocale en-US \\\n--no-hidden-api-checks \\\n-e appendTimestamp true \\\ncom.package.app/Runner")) @runner.run_tests_for_locale('device', 'en-US', device_serial, test_classes_to_use, test_packages_to_use, nil, 28) end end end describe :uninstall_existing do let(:device_serial) { 'device_serial' } let(:app_package_name) { 'tools.fastlane.dev' } let(:test_package_name) { 'tools.fastlane.dev.test' } let(:adb_list_packages_command) { "adb -s #{device_serial} shell pm list packages" } context 'app and test package installed' do before do expect(mock_android_environment).to receive(:adb_path).and_return("adb").exactly(3).times adb_response = strip_heredoc(<<-ADB_OUTPUT) package:android package:com.android.contacts package:com.google.android.webview package:tools.fastlane.dev package:tools.fastlane.dev.test ADB_OUTPUT mock_adb_response_for_command(adb_list_packages_command, adb_response) end it 'uninstalls app and test package' do expect(mock_executor).to receive(:execute).with(hash_including(command: "adb -s #{device_serial} uninstall #{app_package_name}")) expect(mock_executor).to receive(:execute).with(hash_including(command: "adb -s #{device_serial} uninstall #{test_package_name}")) @runner.uninstall_apks(device_serial, app_package_name, test_package_name) end end context 'app and test package not installed' do before do expect(mock_android_environment).to receive(:adb_path).and_return("adb") adb_response = strip_heredoc(<<-ADB_OUTPUT) package:android package:com.android.contacts package:com.google.android.webview ADB_OUTPUT mock_adb_response_for_command(adb_list_packages_command, adb_response) end it 'skips uninstall of app' do expect(mock_executor).not_to(receive(:execute)).with(hash_including(command: "adb -s #{device_serial} uninstall #{app_package_name}")) expect(mock_executor).not_to(receive(:execute)).with(hash_including(command: "adb -s #{device_serial} uninstall #{test_package_name}")) @runner.uninstall_apks(device_serial, app_package_name, test_package_name) end end end describe :installed_packages do let(:device_serial) { 'device_serial' } let(:adb_list_packages_command) { "adb -s #{device_serial} shell pm list packages" } before do expect(mock_android_environment).to receive(:adb_path).and_return("adb") end it 'returns installed packages' do adb_response = strip_heredoc(<<-ADB_OUTPUT) package:android package:com.android.contacts package:com.google.android.webview package:tools.fastlane.dev package:tools.fastlane.dev.test ADB_OUTPUT mock_adb_response_for_command(adb_list_packages_command, adb_response) expect(@runner.installed_packages(device_serial)).to eq(['android', 'com.android.contacts', 'com.google.android.webview', 'tools.fastlane.dev', 'tools.fastlane.dev.test']) end end describe :run_adb_command do before do expect(mock_android_environment).to receive(:adb_path).and_return("adb") end it 'filters out lines which are ADB warnings' do adb_response = strip_heredoc(<<-ADB_OUTPUT) adb: /home/me/rubystack-2.3.1-4/common/lib/libcrypto.so.1.0.0: no version information available (required by adb) List of devices attached e1dbf228 device usb:1-1.2 product:a33gdd model:SM_A270H device:a33g ADB_OUTPUT mock_adb_response_for_command("adb test", adb_response) expect(@runner.run_adb_command("test").lines.any? { |line| line.start_with?('adb: ') }).to eq(false) end end describe :select_device do it 'connects to host if specified' do config[:adb_host] = "device_farm" mock_helper = double('mock helper') device = Fastlane::Helper::AdbDevice.new(serial: 'e1dbf228') expect(mock_android_environment).to receive(:adb_path).and_return("adb") expect(Fastlane::Helper::AdbHelper).to receive(:new).with(adb_path: 'adb', adb_host: 'device_farm').and_return(mock_helper) expect(mock_helper).to receive(:load_all_devices).and_return([device]) expect(@runner.select_device).to eq('e1dbf228') end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/spec/spec_helper.rb
screengrab/spec/spec_helper.rb
def raise_fastlane_error raise_error(FastlaneCore::Interface::FastlaneError) end def raise_fastlane_test_failure raise_error(FastlaneCore::Interface::FastlaneTestFailure) end # The following methods is taken from activesupport, # # https://github.com/rails/rails/blob/d66e7835bea9505f7003e5038aa19b6ea95ceea1/activesupport/lib/active_support/core_ext/string/strip.rb # # All credit for this method goes to the original authors. # The code is used under the MIT license. # # Strips indentation by removing the amount of leading whitespace in the least indented non-empty line in the whole string # def strip_heredoc(str) str.gsub(/^#{str.scan(/^[ \t]*(?=\S)/).min}/, "".freeze) end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab.rb
screengrab/lib/screengrab.rb
require_relative 'screengrab/runner' require_relative 'screengrab/reports_generator' require_relative 'screengrab/detect_values' require_relative 'screengrab/dependency_checker' require_relative 'screengrab/options' require_relative 'screengrab/android_environment' require_relative 'screengrab/module'
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab/setup.rb
screengrab/lib/screengrab/setup.rb
require_relative 'module' module Screengrab class Setup # This method will take care of creating a screengrabfile and other necessary files def self.create(path, is_swift_fastfile: false) if is_swift_fastfile template_location = "#{Screengrab::ROOT}/lib/assets/ScreengrabfileTemplate.swift" screengrabfile_path = File.join(path, 'Screengrabfile.swift') else template_location = "#{Screengrab::ROOT}/lib/assets/ScreengrabfileTemplate" screengrabfile_path = File.join(path, 'Screengrabfile') end if File.exist?(screengrabfile_path) UI.user_error!("Screengrabfile already exists at path '#{screengrabfile_path}'. Run 'screengrab' to use screengrab.") end File.write(screengrabfile_path, File.read(template_location)) UI.success("Successfully created new Screengrabfile at '#{screengrabfile_path}'") end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab/options.rb
screengrab/lib/screengrab/options.rb
require 'fastlane_core/configuration/config_item' require 'credentials_manager/appfile_config' require_relative 'module' module Screengrab class Options DEVICE_TYPES = ["phone", "sevenInch", "tenInch", "tv", "wear"].freeze # Temporarily make non-Mac environments default to skipping the open summary # step until we make it cross-platform DEFAULT_SKIP_OPEN_SUMMARY = !FastlaneCore::Helper.mac? def self.available_options @options ||= [ FastlaneCore::ConfigItem.new(key: :android_home, short_option: "-n", optional: true, code_gen_sensitive: true, default_value: ENV['ANDROID_HOME'] || ENV['ANDROID_SDK_ROOT'] || ENV['ANDROID_SDK'], default_value_dynamic: true, description: "Path to the root of your Android SDK installation, e.g. ~/tools/android-sdk-macosx"), FastlaneCore::ConfigItem.new(key: :build_tools_version, short_option: "-i", optional: true, description: "The Android build tools version to use, e.g. '23.0.2'", deprecated: true), FastlaneCore::ConfigItem.new(key: :locales, description: "A list of locales which should be used", short_option: "-q", type: Array, default_value: ['en-US']), FastlaneCore::ConfigItem.new(key: :clear_previous_screenshots, env_name: 'SCREENGRAB_CLEAR_PREVIOUS_SCREENSHOTS', description: "Enabling this option will automatically clear previously generated screenshots before running screengrab", default_value: false, type: Boolean), FastlaneCore::ConfigItem.new(key: :output_directory, short_option: "-o", env_name: "SCREENGRAB_OUTPUT_DIRECTORY", description: "The directory where to store the screenshots", default_value: File.join("fastlane", "metadata", "android")), FastlaneCore::ConfigItem.new(key: :skip_open_summary, env_name: 'SCREENGRAB_SKIP_OPEN_SUMMARY', description: "Don't open the summary after running _screengrab_", default_value: DEFAULT_SKIP_OPEN_SUMMARY, default_value_dynamic: true, type: Boolean), FastlaneCore::ConfigItem.new(key: :app_package_name, env_name: 'SCREENGRAB_APP_PACKAGE_NAME', short_option: "-a", description: "The package name of the app under test (e.g. com.yourcompany.yourapp)", code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:package_name), default_value_dynamic: true), FastlaneCore::ConfigItem.new(key: :tests_package_name, env_name: 'SCREENGRAB_TESTS_PACKAGE_NAME', optional: true, description: "The package name of the tests bundle (e.g. com.yourcompany.yourapp.test)"), FastlaneCore::ConfigItem.new(key: :use_tests_in_packages, env_name: 'SCREENGRAB_USE_TESTS_IN_PACKAGES', optional: true, short_option: "-p", type: Array, description: "Only run tests in these Java packages"), FastlaneCore::ConfigItem.new(key: :use_tests_in_classes, env_name: 'SCREENGRAB_USE_TESTS_IN_CLASSES', optional: true, short_option: "-l", type: Array, description: "Only run tests in these Java classes"), FastlaneCore::ConfigItem.new(key: :launch_arguments, env_name: 'SCREENGRAB_LAUNCH_ARGUMENTS', optional: true, short_option: "-e", type: Array, description: "Additional launch arguments"), FastlaneCore::ConfigItem.new(key: :test_instrumentation_runner, env_name: 'SCREENGRAB_TEST_INSTRUMENTATION_RUNNER', optional: true, default_value: 'androidx.test.runner.AndroidJUnitRunner', description: "The fully qualified class name of your test instrumentation runner"), FastlaneCore::ConfigItem.new(key: :ending_locale, env_name: 'SCREENGRAB_ENDING_LOCALE', optional: true, default_value: 'en-US', description: "Return the device to this locale after running tests", deprecated: true), FastlaneCore::ConfigItem.new(key: :use_adb_root, env_name: 'SCREENGRAB_USE_ADB_ROOT', description: "Restarts the adb daemon using `adb root` to allow access to screenshots directories on device. Use if getting 'Permission denied' errors", deprecated: true, default_value: false, type: Boolean), FastlaneCore::ConfigItem.new(key: :app_apk_path, env_name: 'SCREENGRAB_APP_APK_PATH', optional: true, description: "The path to the APK for the app under test", short_option: "-k", code_gen_sensitive: true, default_value: Dir[File.join("app", "build", "outputs", "apk", "app-debug.apk")].last, default_value_dynamic: true, verify_block: proc do |value| UI.user_error!("Could not find APK file at path '#{value}'") unless File.exist?(value) end), FastlaneCore::ConfigItem.new(key: :tests_apk_path, env_name: 'SCREENGRAB_TESTS_APK_PATH', optional: true, description: "The path to the APK for the tests bundle", short_option: "-b", code_gen_sensitive: true, default_value: Dir[File.join("app", "build", "outputs", "apk", "app-debug-androidTest-unaligned.apk")].last, default_value_dynamic: true, verify_block: proc do |value| UI.user_error!("Could not find APK file at path '#{value}'") unless File.exist?(value) end), FastlaneCore::ConfigItem.new(key: :specific_device, env_name: 'SCREENGRAB_SPECIFIC_DEVICE', optional: true, description: "Use the device or emulator with the given serial number or qualifier", short_option: "-s"), FastlaneCore::ConfigItem.new(key: :device_type, env_name: 'SCREENGRAB_DEVICE_TYPE', description: "Type of device used for screenshots. Matches Google Play Types (phone, sevenInch, tenInch, tv, wear)", short_option: "-d", default_value: "phone", verify_block: proc do |value| UI.user_error!("device_type must be one of: #{DEVICE_TYPES}") unless DEVICE_TYPES.include?(value) end), FastlaneCore::ConfigItem.new(key: :exit_on_test_failure, env_name: 'EXIT_ON_TEST_FAILURE', description: "Whether or not to exit Screengrab on test failure. Exiting on failure will not copy screenshots to local machine nor open screenshots summary", default_value: true, type: Boolean), FastlaneCore::ConfigItem.new(key: :reinstall_app, env_name: 'SCREENGRAB_REINSTALL_APP', description: "Enabling this option will automatically uninstall the application before running it", default_value: false, type: Boolean), FastlaneCore::ConfigItem.new(key: :use_timestamp_suffix, env_name: 'SCREENGRAB_USE_TIMESTAMP_SUFFIX', description: "Add timestamp suffix to screenshot filename", default_value: true, type: Boolean), FastlaneCore::ConfigItem.new(key: :adb_host, env_name: 'SCREENGRAB_ADB_HOST', description: "Configure the host used by adb to connect, allows running on remote devices farm", optional: true) ] end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab/detect_values.rb
screengrab/lib/screengrab/detect_values.rb
module Screengrab class DetectValues # This is needed to supply default values which are based on config values determined in the initial # configuration pass def self.set_additional_default_values config = Screengrab.config # First, try loading the Screengrabfile from the current directory config.load_configuration_file(Screengrab.screengrabfile_name) unless config[:tests_package_name] config[:tests_package_name] = "#{config[:app_package_name]}.test" end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab/android_environment.rb
screengrab/lib/screengrab/android_environment.rb
require_relative 'module' require 'fastlane_core/command_executor' module Screengrab class AndroidEnvironment attr_reader :android_home # android_home - the String path to the install location of the Android SDK # build_tools_version - the String version of the Android build tools that should be used, ignored def initialize(android_home, build_tools_version = nil) @android_home = android_home end def platform_tools_path @platform_tools_path ||= find_platform_tools(android_home) end def adb_path @adb_path ||= find_adb(platform_tools_path) end private def find_platform_tools(android_home) return nil unless android_home platform_tools_path = Helper.localize_file_path(File.join(android_home, 'platform-tools')) File.directory?(platform_tools_path) ? platform_tools_path : nil end def find_adb(platform_tools_path) return FastlaneCore::CommandExecutor.which('adb') unless platform_tools_path adb_path = Helper.get_executable_path(File.join(platform_tools_path, 'adb')) adb_path = Helper.localize_file_path(adb_path) return executable_command?(adb_path) ? adb_path : nil end def executable_command?(cmd_path) Helper.executable?(cmd_path) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab/dependency_checker.rb
screengrab/lib/screengrab/dependency_checker.rb
require_relative 'module' module Screengrab class DependencyChecker def self.check(android_env) return if Helper.test? check_adb(android_env) end def self.check_adb(android_env) android_home = android_env.android_home adb_path = android_env.adb_path warn_if_command_path_not_relative_to_android_home('adb', android_home, adb_path) # adb is required to function, so we'll quit noisily if we couldn't find it raise_missing_adb(android_home) unless adb_path end def self.raise_missing_adb(android_home) if android_home UI.error("The `adb` command could not be found relative to your provided ANDROID_HOME at #{android_home}") UI.error("Please ensure that the Android SDK is installed and the platform-tools directory is present") else UI.error('The `adb` command could not be found on your PATH') UI.error('Please ensure that the Android SDK is installed and the platform-tools directory is present and on your PATH') end UI.user_error!('adb command not found') end def self.warn_if_command_path_not_relative_to_android_home(cmd_name, android_home, cmd_path) if android_home && cmd_path && !cmd_path.start_with?(android_home) UI.important("Using `#{cmd_name}` found at #{cmd_path} which is not within the specified ANDROID_HOME at #{android_home}") end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab/reports_generator.rb
screengrab/lib/screengrab/reports_generator.rb
require_relative 'module' module Screengrab class ReportsGenerator require 'erb' def generate UI.message("Generating HTML Report") screens_path = Screengrab.config[:output_directory] @data = {} Dir[File.join(screens_path, "*")].sort.each do |language_folder| language = File.basename(language_folder) Dir[File.join(language_folder, 'images', '*', '*.png')].sort.each do |screenshot| device_type_folder = File.basename(File.dirname(screenshot)) @data[language] ||= {} @data[language][device_type_folder] ||= [] resulting_path = File.join('.', language, 'images', device_type_folder, File.basename(screenshot)) @data[language][device_type_folder] << resulting_path end end html_path = File.join(Screengrab::ROOT, "lib", "screengrab/page.html.erb") html = ERB.new(File.read(html_path)).result(binding) # https://web.archive.org/web/20160430190141/www.rrn.dk/rubys-erb-templating-system export_path = "#{screens_path}/screenshots.html" File.write(export_path, html) export_path = File.expand_path(export_path) UI.success("Successfully created HTML file with an overview of all the screenshots: '#{export_path}'") system("open '#{export_path}'") unless Screengrab.config[:skip_open_summary] end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab/commands_generator.rb
screengrab/lib/screengrab/commands_generator.rb
require 'commander' require 'fastlane/version' require 'fastlane_core/ui/help_formatter' require 'fastlane_core/fastlane_folder' require 'fastlane_core/configuration/configuration' require_relative 'android_environment' require_relative 'dependency_checker' require_relative 'runner' require_relative 'options' require_relative 'module' HighLine.track_eof = false module Screengrab class CommandsGenerator include Commander::Methods def self.start self.new.run end def run program :name, 'screengrab' program :version, Fastlane::VERSION program :description, 'CLI for \'screengrab\' - Automate taking localized screenshots of your Android app on emulators or real devices' program :help, 'Authors', 'Andrea Falcone <asfalcone@google.com>, Michael Furtak <mfurtak@google.com>' program :help, 'Website', 'https://fastlane.tools' program :help, 'Documentation', 'https://docs.fastlane.tools/actions/screengrab/' program :help_formatter, FastlaneCore::HelpFormatter global_option('--verbose', 'Shows a more verbose output') { FastlaneCore::Globals.verbose = true } always_trace! command :run do |c| c.syntax = 'fastlane screengrab' c.description = 'Take new screenshots based on the Screengrabfile.' FastlaneCore::CommanderGenerator.new.generate(Screengrab::Options.available_options, command: c) c.action do |args, options| o = options.__hash__.dup o.delete(:verbose) Screengrab.config = FastlaneCore::Configuration.create(Screengrab::Options.available_options, o) Screengrab.android_environment = Screengrab::AndroidEnvironment.new(Screengrab.config[:android_home], Screengrab.config[:build_tools_version]) Screengrab::DependencyChecker.check(Screengrab.android_environment) Screengrab::Runner.new.run end end command :init do |c| c.syntax = 'fastlane screengrab init' c.description = "Creates a new Screengrabfile in the current directory" c.action do |args, options| require 'screengrab/setup' path = Screengrab::Helper.fastlane_enabled? ? FastlaneCore::FastlaneFolder.path : '.' is_swift_fastfile = args.include?("swift") Screengrab::Setup.create(path, is_swift_fastfile: is_swift_fastfile) end end default_command(:run) run! end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab/runner.rb
screengrab/lib/screengrab/runner.rb
require 'fastlane_core/print_table' require 'fastlane_core/command_executor' require 'fastlane/helper/adb_helper' require_relative 'reports_generator' require_relative 'module' module Screengrab class Runner attr_accessor :number_of_retries def initialize(executor = FastlaneCore::CommandExecutor, config = Screengrab.config, android_env = Screengrab.android_environment) @executor = executor @config = config @android_env = android_env end def run # Standardize the locales FastlaneCore::PrintTable.print_values(config: @config, hide_keys: [], title: "Summary for screengrab #{Fastlane::VERSION}") app_apk_path = @config.fetch(:app_apk_path, ask: false) tests_apk_path = @config.fetch(:tests_apk_path, ask: false) discovered_apk_paths = Dir[File.join('**', '*.apk')] apk_paths_provided = app_apk_path && !app_apk_path.empty? && tests_apk_path && !tests_apk_path.empty? unless apk_paths_provided || discovered_apk_paths.any? UI.error('No APK paths were provided and no APKs could be found') UI.error("Please provide APK paths with 'app_apk_path' and 'tests_apk_path' and make sure you have assembled APKs prior to running this command.") return end test_classes_to_use = @config[:use_tests_in_classes] test_packages_to_use = @config[:use_tests_in_packages] if test_classes_to_use && test_classes_to_use.any? && test_packages_to_use && test_packages_to_use.any? UI.error("'use_tests_in_classes' and 'use_tests_in_packages' cannot be combined. Please use one or the other.") return end if (test_classes_to_use.nil? || test_classes_to_use.empty?) && (test_packages_to_use.nil? || test_packages_to_use.empty?) UI.important('Limiting the test classes run by `screengrab` to just those that generate screenshots can make runs faster.') UI.important('Consider using the :use_tests_in_classes or :use_tests_in_packages option, and organize your tests accordingly.') end device_type_dir_name = "#{@config[:device_type]}Screenshots" clear_local_previous_screenshots(device_type_dir_name) device_serial = select_device device_screenshots_paths = [ determine_external_screenshots_path(device_serial, @config[:app_package_name], @config[:locales]), determine_internal_screenshots_paths(device_serial, @config[:app_package_name], @config[:locales]) ].flatten(1) # Root is needed to access device paths at /data if @config[:use_adb_root] run_adb_command("-s #{device_serial.shellescape} root", print_all: false, print_command: true) run_adb_command("-s #{device_serial.shellescape} wait-for-device", print_all: false, print_command: true) end clear_device_previous_screenshots(@config[:app_package_name], device_serial, device_screenshots_paths) app_apk_path ||= select_app_apk(discovered_apk_paths) tests_apk_path ||= select_tests_apk(discovered_apk_paths) number_of_screenshots = run_tests(device_type_dir_name, device_serial, app_apk_path, tests_apk_path, test_classes_to_use, test_packages_to_use, @config[:launch_arguments]) ReportsGenerator.new.generate UI.success("Captured #{number_of_screenshots} new screenshots! 📷✨") end def select_device adb = Fastlane::Helper::AdbHelper.new(adb_path: @android_env.adb_path, adb_host: @config[:adb_host]) devices = adb.load_all_devices UI.user_error!('There are no connected and authorized devices or emulators') if devices.empty? specific_device = @config[:specific_device] if specific_device devices.select! do |d| d.serial.include?(specific_device) end end UI.user_error!("No connected devices matched your criteria: #{specific_device}") if devices.empty? if devices.length > 1 UI.important("Multiple connected devices, selecting the first one") UI.important("To specify which connected device to use, use the -s (specific_device) config option") end devices.first.serial end def select_app_apk(discovered_apk_paths) UI.important("To not be asked about this value, you can specify it using 'app_apk_path'") UI.select('Select your debug app APK', discovered_apk_paths) end def select_tests_apk(discovered_apk_paths) UI.important("To not be asked about this value, you can specify it using 'tests_apk_path'") UI.select('Select your debug tests APK', discovered_apk_paths) end def clear_local_previous_screenshots(device_type_dir_name) if @config[:clear_previous_screenshots] UI.message("Clearing #{device_type_dir_name} within #{@config[:output_directory]}") # We'll clear the temporary directory where screenshots wind up after being pulled from # the device as well, in case those got stranded on a previous run/failure ['screenshots', device_type_dir_name].each do |dir_name| files = screenshot_file_names_in(@config[:output_directory], dir_name) File.delete(*files) end end end def screenshot_file_names_in(output_directory, device_type) Dir.glob(File.join(output_directory, '**', device_type, '*.png'), File::FNM_CASEFOLD) end def get_device_environment_variable(device_serial, variable_name) # macOS evaluates $foo in `echo $foo` before executing the command, # Windows doesn't - hence the double backslash vs. single backslash command = Helper.windows? ? "shell echo \$#{variable_name.shellescape.shellescape}" : "shell echo \\$#{variable_name.shellescape.shellescape}" value = run_adb_command("-s #{device_serial.shellescape} #{command}", print_all: true, print_command: true) return value.strip end # Don't need to use to use run-as if external def use_adb_run_as?(path, device_serial) device_ext_storage = get_device_environment_variable(device_serial, "EXTERNAL_STORAGE") return !path.start_with?(device_ext_storage) end def determine_external_screenshots_path(device_serial, app_package_name, locales) device_ext_storage = get_device_environment_variable(device_serial, "EXTERNAL_STORAGE") return locales.map do |locale| [ File.join(device_ext_storage, app_package_name, 'screengrab', locale, "images", "screenshots"), File.join(device_ext_storage, "Android", "data", app_package_name, 'files', 'screengrab', locale, "images", "screenshots") ] end.flatten.map { |path| [path, false] } end def determine_internal_screenshots_paths(device_serial, app_package_name, locales) device_data = get_device_environment_variable(device_serial, "ANDROID_DATA") return locales.map do |locale| [ "#{device_data}/user/0/#{app_package_name}/files/#{app_package_name}/screengrab/#{locale}/images/screenshots", # https://github.com/fastlane/fastlane/issues/15653#issuecomment-578541663 "#{device_data}/data/#{app_package_name}/files/#{app_package_name}/screengrab/#{locale}/images/screenshots", "#{device_data}/data/#{app_package_name}/app_screengrab/#{locale}/images/screenshots", "#{device_data}/data/#{app_package_name}/screengrab/#{locale}/images/screenshots" ] end.flatten.map { |path| [path, true] } end def clear_device_previous_screenshots(app_package_name, device_serial, device_screenshots_paths) UI.message('Cleaning screenshots on device') device_screenshots_paths.each do |(device_path, needs_run_as)| if_device_path_exists(app_package_name, device_serial, device_path, needs_run_as) do |path| # Determine if path needs the run-as permission run_as = needs_run_as ? " run-as #{app_package_name.shellescape.shellescape}" : "" run_adb_command("-s #{device_serial.shellescape} shell#{run_as} rm -rf #{path.shellescape.shellescape}", print_all: true, print_command: true) end end end def install_apks(device_serial, app_apk_path, tests_apk_path) UI.message('Installing app APK') apk_install_output = run_adb_command("-s #{device_serial.shellescape} install -t -r #{app_apk_path.shellescape}", print_all: true, print_command: true) UI.user_error!("App APK could not be installed") if apk_install_output.include?("Failure [") UI.message('Installing tests APK') apk_install_output = run_adb_command("-s #{device_serial.shellescape} install -t -r #{tests_apk_path.shellescape}", print_all: true, print_command: true) UI.user_error!("Tests APK could not be installed") if apk_install_output.include?("Failure [") end def uninstall_apks(device_serial, app_package_name, tests_package_name) packages = installed_packages(device_serial) if packages.include?(app_package_name.to_s) UI.message('Uninstalling app APK') run_adb_command("-s #{device_serial.shellescape} uninstall #{app_package_name.shellescape}", print_all: true, print_command: true) end if packages.include?(tests_package_name.to_s) UI.message('Uninstalling tests APK') run_adb_command("-s #{device_serial.shellescape} uninstall #{tests_package_name.shellescape}", print_all: true, print_command: true) end end def grant_permissions(device_serial) UI.message('Granting the permission necessary to change locales on the device') run_adb_command("-s #{device_serial.shellescape} shell pm grant #{@config[:app_package_name].shellescape.shellescape} android.permission.CHANGE_CONFIGURATION", print_all: true, print_command: true, raise_errors: false) UI.message('Granting the permissions necessary to access device external storage') run_adb_command("-s #{device_serial.shellescape} shell pm grant #{@config[:app_package_name].shellescape.shellescape} android.permission.WRITE_EXTERNAL_STORAGE", print_all: true, print_command: true, raise_errors: false) run_adb_command("-s #{device_serial.shellescape} shell pm grant #{@config[:app_package_name].shellescape.shellescape} android.permission.READ_EXTERNAL_STORAGE", print_all: true, print_command: true, raise_errors: false) end def kill_app(device_serial, package_name) run_adb_command("-s #{device_serial.shellescape} shell am force-stop #{package_name.shellescape.shellescape}.test", print_all: true, print_command: true) run_adb_command("-s #{device_serial.shellescape} shell am force-stop #{package_name.shellescape.shellescape}", print_all: true, print_command: true) end def run_tests(device_type_dir_name, device_serial, app_apk_path, tests_apk_path, test_classes_to_use, test_packages_to_use, launch_arguments) sdk_version = device_api_version(device_serial) unless @config[:reinstall_app] install_apks(device_serial, app_apk_path, tests_apk_path) grant_permissions(device_serial) enable_clean_status_bar(device_serial, sdk_version) end number_of_screenshots = 0 @config[:locales].each do |locale| if @config[:reinstall_app] uninstall_apks(device_serial, @config[:app_package_name], @config[:tests_package_name]) install_apks(device_serial, app_apk_path, tests_apk_path) grant_permissions(device_serial) else kill_app(device_serial, @config[:app_package_name]) end number_of_screenshots += run_tests_for_locale(device_type_dir_name, locale, device_serial, test_classes_to_use, test_packages_to_use, launch_arguments, sdk_version) end number_of_screenshots end def run_tests_for_locale(device_type_dir_name, locale, device_serial, test_classes_to_use, test_packages_to_use, launch_arguments, sdk_version) UI.message("Running tests for locale: #{locale}") instrument_command = ["-s #{device_serial.shellescape} shell am instrument --no-window-animation -w", "-e testLocale #{locale.shellescape.shellescape}"] if sdk_version >= 28 instrument_command << "--no-hidden-api-checks" end instrument_command << "-e appendTimestamp #{@config[:use_timestamp_suffix]}" instrument_command << "-e class #{test_classes_to_use.join(',').shellescape.shellescape}" if test_classes_to_use instrument_command << "-e package #{test_packages_to_use.join(',').shellescape.shellescape}" if test_packages_to_use instrument_command << launch_arguments.map { |item| '-e ' + item }.join(' ') if launch_arguments instrument_command << "#{@config[:tests_package_name].shellescape.shellescape}/#{@config[:test_instrumentation_runner].shellescape.shellescape}" test_output = run_adb_command(instrument_command.join(" \\\n"), print_all: true, print_command: true) if test_output.include?("FAILURES!!!") if @config[:exit_on_test_failure] UI.test_failure!("Tests failed for locale #{locale} on device #{device_serial}") else UI.error("Tests failed") end end pull_screenshots_from_device(locale, device_serial, device_type_dir_name) end def pull_screenshots_from_device(locale, device_serial, device_type_dir_name) UI.message("Pulling captured screenshots for locale #{locale} from the device") starting_screenshot_count = screenshot_file_names_in(@config[:output_directory], device_type_dir_name).length UI.verbose("Starting screenshot count is: #{starting_screenshot_count}") device_screenshots_paths = [ determine_external_screenshots_path(device_serial, @config[:app_package_name], [locale]), determine_internal_screenshots_paths(device_serial, @config[:app_package_name], [locale]) ].flatten(1) # Make a temp directory into which to pull the screenshots before they are moved to their final location. # This makes directory cleanup easier, as the temp directory will be removed when the block completes. Dir.mktmpdir do |tempdir| device_screenshots_paths.each do |(device_path, needs_run_as)| if_device_path_exists(@config[:app_package_name], device_serial, device_path, needs_run_as) do |path| UI.message(path) next unless path.include?(locale) out = run_adb_command("-s #{device_serial.shellescape} pull #{path.shellescape} #{tempdir.shellescape}", print_all: false, print_command: true, raise_errors: false) if out =~ /Permission denied/ dir = File.dirname(path) base = File.basename(path) # Determine if path needs the run-as permission run_as = needs_run_as ? " run-as #{@config[:app_package_name].shellescape.shellescape}" : "" run_adb_command("-s #{device_serial.shellescape} shell#{run_as} \"tar -cC #{dir} #{base}\" | tar -xv -f- -C #{tempdir}", print_all: false, print_command: true) end end end # The SDK can't 100% determine what kind of device it is running on relative to the categories that # supply and Google Play care about (phone, 7" tablet, TV, etc.). # # Therefore, we'll move the pulled screenshots from their genericly named folder to one named by the # user provided device_type option value to match the directory structure that supply expects move_pulled_screenshots(locale, tempdir, device_type_dir_name) end ending_screenshot_count = screenshot_file_names_in(@config[:output_directory], device_type_dir_name).length UI.verbose("Ending screenshot count is: #{ending_screenshot_count}") # Because we can't guarantee the screenshot output directory will be empty when we pull, we determine # success based on whether there are more screenshots there than when we started. # This is only applicable though when `clear_previous_screenshots` is set to `true`. if starting_screenshot_count == ending_screenshot_count && @config[:clear_previous_screenshots] UI.error("Make sure you've used Screengrab.screenshot() in your tests and that your expected tests are being run.") UI.abort_with_message!("No screenshots were detected 📷❌") end ending_screenshot_count - starting_screenshot_count end def move_pulled_screenshots(locale, pull_dir, device_type_dir_name) # Glob pattern that finds the pulled screenshots directory for each locale # Possible matches: # [pull_dir]/en-US/images/screenshots # [pull_dir]/screengrab/en-US/images/screenshots screenshots_dir_pattern = File.join(pull_dir, '**', "screenshots") Dir.glob(screenshots_dir_pattern, File::FNM_CASEFOLD).each do |screenshots_dir| src_screenshots = Dir.glob(File.join(screenshots_dir, '*.png'), File::FNM_CASEFOLD) # The :output_directory is the final location for the screenshots, so we begin by replacing # the temp directory portion of the path, with the output directory dest_dir = screenshots_dir.gsub(pull_dir, @config[:output_directory]) # Different versions of adb are inconsistent about whether they will pull down the containing # directory for the screenshots, so we'll try to remove that path from the directory name when # creating the destination path. # See: https://github.com/fastlane/fastlane/pull/4915#issuecomment-236368649 dest_dir = dest_dir.gsub(%r{(app_)?screengrab/}, '') # We then replace the last segment of the screenshots directory path with the device_type # specific name, as expected by supply # # (Moved to: fastlane/metadata/android/en-US/images/phoneScreenshots) dest_dir = File.join(File.dirname(dest_dir), locale, 'images', device_type_dir_name) FileUtils.mkdir_p(dest_dir) FileUtils.cp_r(src_screenshots, dest_dir) UI.success("Screenshots copied to #{dest_dir}") end end # Some device commands fail if executed against a device path that does not exist, so this helper method # provides a way to conditionally execute a block only if the provided path exists on the device. def if_device_path_exists(app_package_name, device_serial, device_path, needs_run_as) # Determine if path needs the run-as permission run_as = needs_run_as ? " run-as #{app_package_name.shellescape.shellescape}" : "" return if run_adb_command("-s #{device_serial.shellescape} shell#{run_as} ls #{device_path.shellescape.shellescape}", print_all: false, print_command: false).include?('No such file') yield(device_path) rescue # Some versions of ADB will have a non-zero exit status for this, which will cause the executor to raise. # We can safely ignore that and treat it as if it returned 'No such file' end # Return an array of packages that are installed on the device def installed_packages(device_serial) packages = run_adb_command("-s #{device_serial.shellescape} shell pm list packages", print_all: true, print_command: true) packages.split("\n").map { |package| package.gsub("package:", "") } end def run_adb_command(command, print_all: false, print_command: false, raise_errors: true) adb_host = @config[:adb_host] host = adb_host.nil? ? '' : "-H #{adb_host.shellescape} " output = '' begin errout = nil cmdout = @executor.execute(command: @android_env.adb_path + " " + host + command, print_all: print_all, print_command: print_command, error: raise_errors ? nil : proc { |out, status| errout = out }) || '' output = errout || cmdout rescue => ex if raise_errors raise ex end end output.lines.reject do |line| # Debug/Warning output from ADB line.start_with?('adb: ') && !line.start_with?('adb: error: ') end.join('') # Lines retain their newline chars end def device_api_version(device_serial) run_adb_command("-s #{device_serial.shellescape} shell getprop ro.build.version.sdk", print_all: true, print_command: true).to_i end def enable_clean_status_bar(device_serial, sdk_version) return unless sdk_version >= 23 UI.message('Enabling clean status bar') # Grant the DUMP permission run_adb_command("-s #{device_serial.shellescape} shell pm grant #{@config[:app_package_name].shellescape.shellescape} android.permission.DUMP", print_all: true, print_command: true, raise_errors: false) # Enable the SystemUI demo mode run_adb_command("-s #{device_serial.shellescape} shell settings put global sysui_demo_allowed 1", print_all: true, print_command: true) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/screengrab/lib/screengrab/module.rb
screengrab/lib/screengrab/module.rb
require 'fastlane_core/helper' require 'fastlane/boolean' require_relative 'detect_values' module Screengrab # Use this to just setup the configuration attribute and set it later somewhere else class << self attr_accessor :config attr_accessor :android_environment def config=(value) @config = value DetectValues.set_additional_default_values end def screengrabfile_name "Screengrabfile" end end Helper = FastlaneCore::Helper # you gotta love Ruby: Helper.* should use the Helper class contained in FastlaneCore UI = FastlaneCore::UI Boolean = Fastlane::Boolean ROOT = Pathname.new(File.expand_path('../../..', __FILE__)) DESCRIPTION = "Automated localized screenshots of your Android app on every device".freeze end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/spec/rule_processor_spec.rb
precheck/spec/rule_processor_spec.rb
require 'precheck' require 'spaceship' require 'webmock' describe Precheck do describe Precheck::RuleProcessor do let(:fake_happy_app) { "fake_app_object" } let(:fake_happy_app_version) { "fake_app_version_object" } let(:fake_happy_app_info) { "fake_app_info_object" } let(:fake_in_app_purchase) { "fake_in_app_purchase" } let(:fake_in_app_purchase_edit) { "fake_in_app_purchase_edit" } let(:fake_in_app_purchase_edit_version) { { "de-DE": { name: "iap name", description: "iap desc" } } } let(:fake_in_app_purchases) { [fake_in_app_purchase] } before do setup_happy_app config = FastlaneCore::Configuration.create(Precheck::Options.available_options, {}) Precheck.config = config end def setup_happy_app allow(fake_happy_app).to receive(:id).and_return("3838204") allow(fake_happy_app).to receive(:name).and_return("My Fake App") allow(fake_happy_app).to receive(:in_app_purchases).and_return(fake_in_app_purchases) allow(fake_happy_app).to receive(:fetch_latest_app_info).and_return(fake_happy_app_info) allow(fake_happy_app_info).to receive(:get_app_info_localizations).and_return([fake_info_localization]) allow(fake_happy_app_version).to receive(:copyright).and_return("Copyright taquitos, #{DateTime.now.year}") allow(fake_happy_app_version).to receive(:get_app_store_version_localizations).and_return([fake_version_localization]) allow(Precheck::RuleProcessor).to receive(:get_iaps).and_return(fake_in_app_purchases) allow(fake_in_app_purchase).to receive(:edit).and_return(fake_in_app_purchase_edit) allow(fake_in_app_purchase_edit).to receive(:versions).and_return(fake_in_app_purchase_edit_version) setup_happy_url_rule_mock end def setup_happy_url_rule_mock request = "fake request" head_object = "fake head object" allow(head_object).to receive(:status).and_return(200) allow(request).to receive(:use).and_return(nil) allow(request).to receive(:adapter).and_return(nil) allow(request).to receive(:head).and_return(head_object) allow(Faraday).to receive(:new).and_return(request) end def fake_version_localization Spaceship::ConnectAPI::AppStoreVersionLocalization.new("id", { "description" => "hi! this is fake data", "locale" => "locale", "keywords" => "hi! this is fake data", "marketingUrl" => "http://fastlane.tools", "promotionalText" => "hi! this is fake data", "supportUrl" => "http://fastlane.tools", "whatsNew" => "hi! this is fake data" }) end def fake_info_localization Spaceship::ConnectAPI::AppInfoLocalization.new("id", { "locale" => "locale", "name" => "hi! this is fake data", "subtitle" => "hi! this is fake data", "privacyPolicyUrl" => "http://fastlane.tools", "privacyPolicyText" => "hi! this is fake data" }) end def fake_language_item_for_text_item(fieldname: nil) Spaceship::Tunes::LanguageItem.new(fieldname, [{ fieldname => { "value" => "hi! this is fake data" }, "language" => "en-US" }]) end def fake_language_item_for_url_item(fieldname: nil) Spaceship::Tunes::LanguageItem.new(fieldname, [{ fieldname => { "value" => "http://fastlane.tools" }, "language" => "en-US" }]) end it "successfully passes for happy values" do result = Precheck::RuleProcessor.process_app_and_version( app: fake_happy_app, app_version: fake_happy_app_version, rules: Precheck::Options.rules ) expect(result.error_results).to eq({}) expect(result.warning_results).to eq({}) expect(result.skipped_rules).to eq([]) expect(result.items_not_checked).to eq([]) expect(result.should_trigger_user_error?).to be(false) expect(result.has_errors_or_warnings?).to be(false) expect(result.items_not_checked?).to be(false) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/spec/rules/rule_spec.rb
precheck/spec/rules/rule_spec.rb
require 'precheck' module Precheck class TestItemToCheck < ItemToCheck attr_accessor :data def initialize(data: nil, item_name: :a, friendly_name: "none", is_optional: false) @data = data super(item_name, friendly_name, is_optional) end def item_data return data end end class TestRule < Rule def self.key :test_rule end def self.env_name "TEST_RULE_ENV" end def self.friendly_name "This is a test only" end def self.description "test rule" end def handle_item?(item) item.kind_of?(TestItemToCheck) ? true : false end def supported_fields_symbol_set [:a, :b, :c].to_set end def rule_block return lambda { |item_data| if item_data == "fail" return RuleReturn.new(validation_state: VALIDATION_STATES[:failed], failure_data: "set failure") end if item_data == "success" return RuleReturn.new(validation_state: VALIDATION_STATES[:passed]) end return RuleReturn.new(validation_state: VALIDATION_STATES[:failed], failure_data: "I was something else") } end end describe Precheck do describe Precheck::Rule do let(:rule) { TestRule.new } it "passes" do item = TestItemToCheck.new(data: "success") result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "properly returns a RuleResult with failed_data" do item = TestItemToCheck.new(data: "fail") result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("set failure") end it "skips items it is not explicitly support to handle via handle_item?" do # Note: TextItemToCheck not TestItemToCheck item = TextItemToCheck.new("nothing", :description, "description") result = rule.check_item(item) expect(result).to eq(nil) end it "skips item names not in supported_fields_symbol_set" do item = TestItemToCheck.new(data: "fail", item_name: :d) result = rule.check_item(item) expect(result).to eq(nil) end it "passes when items are set is_optional == true and they have nil content" do item = TestItemToCheck.new(data: nil, is_optional: true) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "passes when items are set is_optional == true and they have empty content" do item = TestItemToCheck.new(data: "", is_optional: true) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "includes fields from supported_fields_symbol_set" do item = TestItemToCheck.new(data: "success", item_name: :a) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) item = TestItemToCheck.new(data: "success", item_name: :b) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) item = TestItemToCheck.new(data: "success", item_name: :c) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/spec/rules/other_platforms_rule_spec.rb
precheck/spec/rules/other_platforms_rule_spec.rb
require 'precheck' module Precheck describe Precheck do describe Precheck::OtherPlatformsRule do let(:rule) { OtherPlatformsRule.new } let(:allowed_item) { TextItemToCheck.new("We have integration with the Files app so you can open documents stored in your Google Drive.", :description, "description") } let(:forbidden_item) { TextItemToCheck.new("Google is really great.", :description, "description") } it "passes for allowed text" do result = rule.check_item(allowed_item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "fails for mentioning competitors" do result = rule.check_item(forbidden_item) expect(result.status).to eq(VALIDATION_STATES[:failed]) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/spec/rules/curse_words_rule_spec.rb
precheck/spec/rules/curse_words_rule_spec.rb
require 'precheck' module Precheck describe Precheck do describe Precheck::CurseWordsRule do let(:rule) { CurseWordsRule.new } let(:happy_item) { TextItemToCheck.new("tacos are really delicious, seriously, I can't even", :description, "description") } let(:curse_item) { TextItemToCheck.new("please excuse the use of 'shit' in this description", :description, "description") } it "passes for non-curse item" do result = rule.check_item(happy_item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "fails for curse word" do result = rule.check_item(curse_item) expect(result.status).to eq(VALIDATION_STATES[:failed]) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/spec/rules/unreachable_urls_rule_spec.rb
precheck/spec/rules/unreachable_urls_rule_spec.rb
require 'precheck' module Precheck describe Precheck do describe Precheck::UnreachableURLRule do let(:rule) { UnreachableURLRule.new } def setup_url_rule_mock(url: "http://fastlane.tools", return_status: 200) request = "fake request" head_object = "fake head object" allow(head_object).to receive(:status).and_return(return_status) allow(request).to receive(:use).and_return(nil) allow(request).to receive(:adapter).and_return(nil) allow(request).to receive(:head).and_return(head_object) uri = Addressable::URI.parse(url) allow(Faraday).to receive(:new).with(uri.normalize.to_s).and_return(request) end it "passes for 200 status URL" do setup_url_rule_mock item = URLItemToCheck.new("http://fastlane.tools", "some_url", "test URL") result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "passes for valid non encoded URL" do setup_url_rule_mock(url: "http://fastlane.tools/%E3%83%86%E3%82%B9%E3%83%88") item = URLItemToCheck.new("http://fastlane.tools/テスト", "some_url", "test URL") result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "fails for anything else" do setup_url_rule_mock(return_status: 500) item = URLItemToCheck.new("http://fastlane.tools", "some_url", "test URL") result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("HTTP 500: http://fastlane.tools") setup_url_rule_mock(return_status: 404) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("HTTP 404: http://fastlane.tools") setup_url_rule_mock(return_status: 409) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("HTTP 409: http://fastlane.tools") setup_url_rule_mock(return_status: 403) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("HTTP 403: http://fastlane.tools") end it "fails if not optional and URL is nil" do setup_url_rule_mock item = URLItemToCheck.new(nil, "some_url", "test URL", false) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("empty url") end it "fails if not optional and URL is empty" do setup_url_rule_mock item = URLItemToCheck.new("", "some_url", "test URL", false) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("empty url") end it "passes if empty and optional is true" do setup_url_rule_mock item = URLItemToCheck.new("", "some_url", "test URL", true) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "passes if nil and optional is true" do setup_url_rule_mock item = URLItemToCheck.new(nil, "some_url", "test URL", true) result = rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/spec/rules/abstract_text_match_rule_spec.rb
precheck/spec/rules/abstract_text_match_rule_spec.rb
require 'precheck' module Precheck # all the stuff we need that doesn't matter for testing class TestingRule < AbstractTextMatchRule def self.key return :test_rule_key end def self.env_name return "JUST_A_TEST_RULE" end def self.description return "test descriptions" end end # always pass as long as these words are found class FailOnExclusionTestingTextMatchRule < TestingRule def lowercased_words_to_look_for ["tacos", "taquitos"].map(&:downcase) end def word_search_type WORD_SEARCH_TYPES[:fail_on_exclusion] end end # always pass as long as these words are not found class PassOnExclusionOrEmptyTestingTextMatchRule < TestingRule def lowercased_words_to_look_for ["tacos", "puppies"].map(&:downcase) end end # always fail as long as any of these words are found class PassOnExclusionTestingTextMatchRule < TestingRule def lowercased_words_to_look_for ["tacos", "puppies", "taquitos"].map(&:downcase) end def pass_if_empty? return false end end describe Precheck do describe Precheck::AbstractTextMatchRule do let(:fail_on_exclusion_rule) { FailOnExclusionTestingTextMatchRule.new } let(:pass_on_exclusion_or_empty_rule) { PassOnExclusionOrEmptyTestingTextMatchRule.new } let(:pass_on_exclusion_rule) { PassOnExclusionTestingTextMatchRule.new } # let(:inclusion_rule) { InclusionTestingTextMatchRule.new() } # pass on exclusion or empty tests it "ensures string is flagged if words found in exclusion rule" do item = TextItemToCheck.new("tacos are really delicious and puppies shouldn't eat them.", :description, "description") result = pass_on_exclusion_or_empty_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("found: tacos, puppies") end it "ensures string is flagged if words found in exclusion rule ignoring capitalization" do item = TextItemToCheck.new("TaCoS are really delicious and PupPies shouldn't eat them.", :description, "description") result = pass_on_exclusion_or_empty_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("found: tacos, puppies") end it "ensures string is flagged if even one word is found in exclusion rule" do item = TextItemToCheck.new("I think puppies are the best", :description, "description") result = pass_on_exclusion_or_empty_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("found: puppies") end it "ensures passing if text item is nil" do item = TextItemToCheck.new(nil, :description, "description") result = pass_on_exclusion_or_empty_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "ensures passing if text item is empty" do item = TextItemToCheck.new("", :description, "description") result = pass_on_exclusion_or_empty_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end # pass on exclusion, but fail on empty or nil it "ensures failing if text item is nil pass_if_empty? is false" do item = TextItemToCheck.new(nil, :description, "description") result = pass_on_exclusion_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) end it "ensures failing if text item is empty when pass_if_empty? is false" do item = TextItemToCheck.new("", :description, "description") result = pass_on_exclusion_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) end it "ensures failing if text item is empty when pass_if_empty? is false" do item = TextItemToCheck.new("", :description, "description") result = pass_on_exclusion_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) end # fail on exclusion tests it "ensures string is not flagged if all words are found in fail_on_exclusion rule" do item = TextItemToCheck.new("tacos and taquitos are really delicious, too bad I'm vegetarian now", :description, "description") result = fail_on_exclusion_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "ensures string is flagged if missing some words in fail_on_exclusion rule" do item = TextItemToCheck.new("tacos are really delicious, too bad I'm vegetarian now", :description, "description") result = fail_on_exclusion_rule.check_item(item) expect(result.status).to eq(VALIDATION_STATES[:failed]) expect(result.rule_return.failure_data).to eq("missing: taquitos") end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/spec/rules/copyright_date_rule_spec.rb
precheck/spec/rules/copyright_date_rule_spec.rb
require 'precheck' module Precheck describe Precheck do describe Precheck::CopyrightDateRule do let(:rule) { CopyrightDateRule.new } let(:happy_item) { TextItemToCheck.new("Copyright taquitos, #{DateTime.now.year}", :copyright, "copyright") } let(:old_copyright_item) { TextItemToCheck.new("Copyright taquitos, 2016", :copyright, "copyright") } let(:empty_copyright_item) { TextItemToCheck.new(nil, :copyright, "copyright") } it "passes for current date" do result = rule.check_item(happy_item) expect(result.status).to eq(VALIDATION_STATES[:passed]) end it "skips for fields that aren't copyright" do not_copyright_item = TextItemToCheck.new("not copyright", :description, "description") result = rule.check_item(not_copyright_item) expect(result).to eq(nil) end it "fails for old date" do result = rule.check_item(old_copyright_item) expect(result.status).to eq(VALIDATION_STATES[:failed]) end it "fails for empty date" do result = rule.check_item(empty_copyright_item) expect(result.status).to eq(VALIDATION_STATES[:failed]) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck.rb
precheck/lib/precheck.rb
require_relative 'precheck/runner' require_relative 'precheck/options' require 'spaceship'
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rule_processor.rb
precheck/lib/precheck/rule_processor.rb
require 'spaceship/tunes/language_item' require 'spaceship/tunes/iap_list' require 'fastlane/markdown_table_formatter' require_relative 'module' require_relative 'item_to_check' require_relative 'rule' module Precheck # encapsulated the results of the rule processing, needed to return not just an array of the results of our # checks, but also an array of items we didn't check, just in-case we were expecting to check everything class RuleProcessResult attr_accessor :error_results # { rule: [result, result, ...] } attr_accessor :warning_results # { rule: [result, result, ...] } attr_accessor :skipped_rules attr_accessor :items_not_checked def initialize(error_results: nil, warning_results: nil, skipped_rules: nil, items_not_checked: nil) @error_results = error_results @warning_results = warning_results @skipped_rules = skipped_rules @items_not_checked = items_not_checked end def should_trigger_user_error? return true if error_results.length > 0 return false end def has_errors_or_warnings? return true if error_results.length > 0 || warning_results.length > 0 return false end def items_not_checked? return true if items_not_checked.length > 0 return false end end class RuleProcessor def self.process_app_and_version(app: nil, app_version: nil, rules: nil) items_to_check = [] items_to_check += generate_app_items_to_check(app: app) items_to_check += generate_version_items_to_check(app_version: app_version) return process_rules(items_to_check: items_to_check, rules: rules) end def self.process_rules(items_to_check: nil, rules: nil) items_not_checked = items_to_check.to_set # items we haven't checked by at least one rule error_results = {} # rule to fields map warning_results = {} # rule to fields map skipped_rules = [] rules.each do |rule| rule_config = Precheck.config[rule.key] rule_level = rule_config[:level].to_sym unless rule_config.nil? rule_level ||= Precheck.config[:default_rule_level].to_sym if rule_level == RULE_LEVELS[:skip] skipped_rules << rule UI.message("Skipped: #{rule.class.friendly_name}-> #{rule.description}".yellow) next end if rule.needs_customization? if rule_config.nil? || rule_config[:data].nil? UI.verbose("#{rule.key} excluded because no data was passed to it e.g.: #{rule.key}(data: <data here>)") next end custom_data = rule_config[:data] rule.customize_with_data(data: custom_data) end # if the rule failed at least once, we won't print a success message rule_failed_at_least_once = false items_to_check.each do |item| result = rule.check_item(item) # each rule will determine if it can handle this item, if not, it will just pass nil back next if result.nil? # we've checked this item, remove it from list of items not checked items_not_checked.delete(item) # if we passed, then go to the next item, otherwise, recode the failure next unless result.status == VALIDATION_STATES[:failed] error_results = add_new_result_to_rule_hash(rule_hash: error_results, result: result) if rule_level == RULE_LEVELS[:error] warning_results = add_new_result_to_rule_hash(rule_hash: warning_results, result: result) if rule_level == RULE_LEVELS[:warn] rule_failed_at_least_once = true end if rule_failed_at_least_once message = "😵 Failed: #{rule.class.friendly_name}-> #{rule.description}" if rule_level == RULE_LEVELS[:error] UI.error(message) else UI.important(message) end else UI.message("✅ Passed: #{rule.class.friendly_name}") end end return RuleProcessResult.new( error_results: error_results, warning_results: warning_results, skipped_rules: skipped_rules, items_not_checked: items_not_checked.to_a ) end # hash will be { rule: [result, result, result] } def self.add_new_result_to_rule_hash(rule_hash: nil, result: nil) unless rule_hash.include?(result.rule) rule_hash[result.rule] = [] end rule_results = rule_hash[result.rule] rule_results << result return rule_hash end def self.generate_app_items_to_check(app: nil) items = [] # App info localizations app_info = Precheck.config[:use_live] ? app.fetch_live_app_info : app.fetch_latest_app_info app_info_localizations = app_info.get_app_info_localizations app_info_localizations.each do |localization| items << collect_text_items_from_language_item(locale: localization.locale, value: localization.name, item_name: :app_name, friendly_name_postfix: "app name") items << collect_text_items_from_language_item(locale: localization.locale, value: localization.subtitle, item_name: :app_subtitle, friendly_name_postfix: "app name subtitle", is_optional: true) items << collect_text_items_from_language_item(locale: localization.locale, value: localization.privacy_policy_text, item_name: :privacy_policy_text, friendly_name_postfix: " tv privacy policy") items << collect_urls_from_language_item(locale: localization.locale, value: localization.privacy_policy_url, item_name: :privacy_policy_url, friendly_name_postfix: "privacy URL", is_optional: true) end should_include_iap = Precheck.config[:include_in_app_purchases] if should_include_iap UI.message("Reading in-app purchases. If you have a lot, this might take a while") UI.message("You can disable IAP checking by setting the `include_in_app_purchases` flag to `false`") in_app_purchases = get_iaps(app_id: app.id) in_app_purchases ||= [] in_app_purchases.each do |purchase| items += collect_iap_language_items(purchase_edit_versions: purchase.edit.versions) end UI.message("Done reading in-app purchases") end return items end def self.generate_version_items_to_check(app_version: nil) items = [] items << TextItemToCheck.new(app_version.copyright, :copyright, "copyright") # Version localizations version_localizations = app_version.get_app_store_version_localizations version_localizations.each do |localization| items << collect_text_items_from_language_item(locale: localization.locale, value: localization.keywords, item_name: :keywords, friendly_name_postfix: "keywords") items << collect_text_items_from_language_item(locale: localization.locale, value: localization.description, item_name: :description, friendly_name_postfix: "description") items << collect_text_items_from_language_item(locale: localization.locale, value: localization.whats_new, item_name: :release_notes, friendly_name_postfix: "what's new") items << collect_urls_from_language_item(locale: localization.locale, value: localization.support_url, item_name: :support_url, friendly_name_postfix: "support URL") items << collect_urls_from_language_item(locale: localization.locale, value: localization.marketing_url, item_name: :marketing_url, friendly_name_postfix: "marketing URL", is_optional: true) end return items end # As of 2020-09-04, this is the only non App Store Connect call in prechecks # This will need to get replaced when the API becomes available def self.get_iaps(app_id: nil, include_deleted: false) r = Spaceship::Tunes.client.iaps(app_id: app_id) return_iaps = [] r.each do |product| attrs = product # This is not great but Spaceship::Tunes::IAPList.factory looks # for `application.apple_id` mock_application = OpenStruct.new({ apple_id: app_id }) attrs[:application] = mock_application loaded_iap = Spaceship::Tunes::IAPList.factory(attrs) next if loaded_iap.status == "deleted" && !include_deleted return_iaps << loaded_iap end return return_iaps end def self.collect_iap_language_items(purchase_edit_versions: nil, is_optional: false) items = [] purchase_edit_versions.each do |language_key, hash| name = hash[:name] description = hash[:description] items << TextItemToCheck.new(name, :in_app_purchase, "in-app purchase name: #{name}: (#{language_key})", is_optional) items << TextItemToCheck.new(description, :in_app_purchase, "in-app purchase desc: #{description}: (#{language_key})", is_optional) end return items end # a few attributes are LanguageItem this method creates a TextItemToCheck for each pair def self.collect_text_items_from_language_item(locale: nil, value: nil, item_name: nil, friendly_name_postfix: nil, is_optional: false) return TextItemToCheck.new(value, item_name, "#{friendly_name_postfix}: (#{locale})", is_optional) end def self.collect_urls_from_language_item(locale: nil, value: nil, item_name: nil, friendly_name_postfix: nil, is_optional: false) return URLItemToCheck.new(value, item_name, "#{friendly_name_postfix}: (#{locale})", is_optional) end end end # we want to get some of the same behavior hashes has, so use this mixin specifically designed for Spaceship::Tunes::LanguageItem # because we use .each module LanguageItemHashBehavior # this is used to create a hash-like .each method. def each(&block) keys.each { |key| yield(key, get_value(key: key)) } end end class Spaceship::Tunes::LanguageItem include LanguageItemHashBehavior end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/options.rb
precheck/lib/precheck/options.rb
require 'fastlane_core/configuration/config_item' require 'credentials_manager/appfile_config' require_relative 'rules/all' module Precheck class Options def self.rules [ NegativeAppleSentimentRule, PlaceholderWordsRule, OtherPlatformsRule, FutureFunctionalityRule, TestWordsRule, CurseWordsRule, FreeStuffIAPRule, CustomTextRule, CopyrightDateRule, UnreachableURLRule ].map(&:new) end def self.available_options user = CredentialsManager::AppfileConfig.try_fetch_value(:itunes_connect_id) user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id) [ FastlaneCore::ConfigItem.new(key: :api_key_path, env_names: ["PRECHECK_API_KEY_PATH", "APP_STORE_CONNECT_API_KEY_PATH"], description: "Path to your App Store Connect API Key JSON file (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-json-file)", optional: true, conflicting_options: [:username], verify_block: proc do |value| UI.user_error!("Couldn't find API key JSON file at path '#{value}'") unless File.exist?(value) end), FastlaneCore::ConfigItem.new(key: :api_key, env_names: ["PRECHECK_API_KEY", "APP_STORE_CONNECT_API_KEY"], description: "Your App Store Connect API Key information (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-hash-option)", type: Hash, optional: true, sensitive: true, conflicting_options: [:api_key_path, :username]), FastlaneCore::ConfigItem.new(key: :app_identifier, short_option: "-a", env_name: "PRECHECK_APP_IDENTIFIER", description: "The bundle identifier of your app", code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier), default_value_dynamic: true), FastlaneCore::ConfigItem.new(key: :username, short_option: "-u", env_name: "PRECHECK_USERNAME", description: "Your Apple ID Username", optional: true, default_value: user, default_value_dynamic: true), FastlaneCore::ConfigItem.new(key: :team_id, short_option: "-b", env_name: "PRECHECK_TEAM_ID", description: "The ID of your App Store Connect team if you're in multiple teams", optional: true, code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:itc_team_id), default_value_dynamic: true, verify_block: proc do |value| ENV["FASTLANE_ITC_TEAM_ID"] = value.to_s end), FastlaneCore::ConfigItem.new(key: :team_name, short_option: "-l", env_name: "PRECHECK_TEAM_NAME", description: "The name of your App Store Connect team if you're in multiple teams", optional: true, code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:itc_team_name), default_value_dynamic: true, verify_block: proc do |value| ENV["FASTLANE_ITC_TEAM_NAME"] = value.to_s end), FastlaneCore::ConfigItem.new(key: :platform, short_option: "-j", env_name: "PRECHECK_PLATFORM", description: "The platform to use (optional)", optional: true, default_value: "ios", verify_block: proc do |value| UI.user_error!("The platform can only be ios, appletvos/tvos or osx") unless %w(ios appletvos tvos osx).include?(value) end), FastlaneCore::ConfigItem.new(key: :default_rule_level, short_option: "-r", env_name: "PRECHECK_DEFAULT_RULE_LEVEL", description: "The default rule level unless otherwise configured", type: Symbol, default_value: RULE_LEVELS[:error]), FastlaneCore::ConfigItem.new(key: :include_in_app_purchases, short_option: "-i", env_name: "PRECHECK_INCLUDE_IN_APP_PURCHASES", description: "Should check in-app purchases?", type: Boolean, optional: true, default_value: true), FastlaneCore::ConfigItem.new(key: :use_live, env_name: "PRECHECK_USE_LIVE", description: "Should force check live app?", type: Boolean, default_value: false) ] + rules end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/commands_generator.rb
precheck/lib/precheck/commands_generator.rb
require "commander" require "fastlane_core/globals" require "fastlane_core/configuration/commander_generator" require "fastlane_core/configuration/configuration" require "fastlane_core/helper" require "fastlane/version" require 'fastlane_core/ui/help_formatter' require_relative 'module' require_relative 'options' require_relative 'runner' HighLine.track_eof = false module Precheck class CommandsGenerator include Commander::Methods def self.start new.run end def run program :name, 'precheck' program :version, Fastlane::VERSION program :description, Precheck::DESCRIPTION program :help, "Author", "Joshua Liebowitz <taquitos@gmail.com>, @taquitos" program :help, "Website", "https://fastlane.tools" program :help, "Documentation", "https://docs.fastlane.tools/actions/precheck/" program :help_formatter, FastlaneCore::HelpFormatter global_option("--verbose") { FastlaneCore::Globals.verbose = true } command :check_metadata do |c| c.syntax = "fastlane precheck" c.description = Precheck::DESCRIPTION FastlaneCore::CommanderGenerator.new.generate(Precheck::Options.available_options, command: c) c.action do |_args, options| Precheck.config = FastlaneCore::Configuration.create(Precheck::Options.available_options, options.__hash__) Precheck::Runner.new.run end end command :init do |c| c.syntax = "fastlane precheck init" c.description = "Creates a new Precheckfile for you" c.action do |args, options| containing = FastlaneCore::Helper.fastlane_enabled_folder_path path = File.join(containing, Precheck.precheckfile_name) UI.user_error!("Precheckfile already exists") if File.exist?(path) is_swift_fastfile = args.include?("swift") if is_swift_fastfile path = File.join(containing, Precheck.precheckfile_name + ".swift") UI.user_error!("Precheckfile.swift already exists") if File.exist?(path) end if is_swift_fastfile template = File.read("#{Precheck::ROOT}/lib/assets/PrecheckfileTemplate.swift") else template = File.read("#{Precheck::ROOT}/lib/assets/PrecheckfileTemplate") end File.write(path, template) UI.success("Successfully created '#{path}'. Open the file using a code editor.") end end default_command(:check_metadata) run! end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/runner.rb
precheck/lib/precheck/runner.rb
require 'terminal-table' require 'fastlane_core/print_table' require 'spaceship/tunes/tunes' require 'spaceship/tunes/application' require_relative 'rule_processor' require_relative 'options' module Precheck class Runner attr_accessor :spaceship # Uses the spaceship to download app metadata and then run all rule checkers def run Precheck.config.load_configuration_file(Precheck.precheckfile_name) FastlaneCore::PrintTable.print_values(config: Precheck.config, hide_keys: [:output_path], title: "Summary for precheck #{Fastlane::VERSION}") api_token = if (token = Spaceship::ConnectAPI::Token.from(hash: Precheck.config[:api_key], filepath: Precheck.config[:api_key_path])) UI.message("Creating authorization token for App Store Connect API") token elsif (token = Spaceship::ConnectAPI.token) UI.message("Using existing authorization token for App Store Connect API") token end if api_token # As of 2020-09-15, App Store Connect API does not have support for IAPs yet # This means that API Key will fail if checking for IAPs. # # There is also a check in Deliver::Runner for this. # Please remove check in Deliver when the API support IAPs. if Precheck.config[:include_in_app_purchases] UI.user_error!("Precheck cannot check In-app purchases with the App Store Connect API Key (yet). Exclude In-app purchases from precheck, disable the precheck step in your build step, or use Apple ID login") end Spaceship::ConnectAPI.token = api_token elsif Spaceship::Tunes.client.nil? # Username is now optional since addition of App Store Connect API Key # Force asking for username to prompt user if not already set Precheck.config.fetch(:username, force_ask: true) # Team selection passed though FASTLANE_ITC_TEAM_ID and FASTLANE_ITC_TEAM_NAME environment variables # Prompts select team if multiple teams and none specified UI.message("Starting login with user '#{Precheck.config[:username]}'") Spaceship::ConnectAPI.login(Precheck.config[:username], use_portal: false, use_tunes: true) UI.message("Successfully logged in") end UI.message("Checking app for precheck rule violations") ensure_app_exists! processor_result = check_for_rule_violations(app: app, app_version: latest_app_version) if processor_result.items_not_checked? print_items_not_checked(processor_result: processor_result) end if processor_result.has_errors_or_warnings? summary_table = build_potential_problems_table(processor_result: processor_result) puts(summary_table) end if processor_result.should_trigger_user_error? UI.user_error!("precheck 👮‍♀️ 👮 found one or more potential problems that must be addressed before submitting to review") return false end if processor_result.has_errors_or_warnings? UI.important("precheck 👮‍♀️ 👮 found one or more potential metadata problems, but this won't prevent fastlane from completing 👍".yellow) end if !processor_result.has_errors_or_warnings? && !processor_result.items_not_checked? UI.message("precheck 👮‍♀️ 👮 finished without detecting any potential problems 🛫".green) end return true end def print_items_not_checked(processor_result: nil) names = processor_result.items_not_checked.map(&:friendly_name) UI.message("😶 Metadata fields not checked by any rule: #{names.join(', ')}".yellow) if names.length > 0 end def build_potential_problems_table(processor_result: nil) error_results = processor_result.error_results warning_results = processor_result.warning_results rows = [] warning_results.each do |rule, results| results.each do |result| rows << [result.item.friendly_name, result.rule_return.failure_data.yellow] end end error_results.each do |rule, results| results.each do |result| rows << [result.item.friendly_name, result.rule_return.failure_data.red] end end if rows.length == 0 return nil else title_text = "Potential problems" if error_results.length > 0 title_text = title_text.red else title_text = title_text.yellow end return Terminal::Table.new( title: title_text, headings: ["Field", "Failure reason"], rows: FastlaneCore::PrintTable.transform_output(rows) ).to_s end end def check_for_rule_violations(app: nil, app_version: nil) Precheck::RuleProcessor.process_app_and_version( app: app, app_version: app_version, rules: Precheck::Options.rules ) end def rendered_failed_results_table(failed_results: nil) rows = [] failed_results.each do |failed_result| rows << [failed_result.rule.key, failed_result.item.friendly_name] end return Terminal::Table.new( title: "Failed rules".red, headings: ["Name", "App metadata field: (language code)"], rows: FastlaneCore::PrintTable.transform_output(rows) ).to_s end def rendered_rules_checked_table(rules_checked: nil) rows = [] rules_checked.each do |rule| rows << [rule.key, rule.description] end return Terminal::Table.new( title: "Enabled rules".green, headings: ["Name", "Description"], rows: FastlaneCore::PrintTable.transform_output(rows) ).to_s end def rendered_skipped_rules_table(skipped_rules: nil) return nil if skipped_rules.empty? rows = [] skipped_rules.each do |rule| rows << [rule.key, rule.description] end return Terminal::Table.new( title: "Skipped rules".yellow, headings: ["Name", "Description"], rows: FastlaneCore::PrintTable.transform_output(rows) ).to_s end def build_items_not_checked_table(items_not_checked: nil) rows = [] items_not_checked.each do |item| rows << [item.item_name, item.friendly_name] end return Terminal::Table.new( title: "Not analyzed".yellow, headings: ["Name", "Friendly name"], rows: FastlaneCore::PrintTable.transform_output(rows) ).to_s end def app Spaceship::ConnectAPI::App.find(Precheck.config[:app_identifier]) end def latest_app_version platform = Spaceship::ConnectAPI::Platform.map(Precheck.config[:platform]) @latest_version ||= Precheck.config[:use_live] ? app.get_live_app_store_version(platform: platform) : app.get_latest_app_store_version(platform: platform) end # Makes sure the current App ID exists. If not, it will show an appropriate error message def ensure_app_exists! return if app UI.user_error!("Could not find app with App Identifier '#{Precheck.config[:app_identifier]}'") end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rule.rb
precheck/lib/precheck/rule.rb
require 'credentials_manager/appfile_config' require 'fastlane_core/configuration/config_item' require_relative 'module' require_relative 'item_to_check' require_relative 'rule_check_result' module Precheck VALIDATION_STATES = { passed: "passed", failed: "failed" } # rules can cause warnings, errors, or be skipped all together # by default they are set to indicate a RULE_LEVELS[:error] RULE_LEVELS = { warn: :warn, error: :error, skip: :skip } # Abstract super class attr_accessor :rule_block class Rule < FastlaneCore::ConfigItem # when a rule evaluates a single item, it has a validation state # if it fails, it has some data like what text failed to pass, or maybe a bad url # this class encapsulates that return value and state # it is the return value from each evaluated @rule_block class RuleReturn attr_accessor :validation_state attr_accessor :failure_data def initialize(validation_state: nil, failure_data: nil) @validation_state = validation_state @failure_data = failure_data end end def initialize(short_option: nil, verify_block: nil, is_string: nil, type: nil, conflicting_options: nil, conflict_block: nil, deprecated: nil, sensitive: nil, display_in_shell: nil) super(key: self.class.key, env_name: self.class.env_name, description: self.class.description, short_option: short_option, default_value: self.class.default_value, verify_block: verify_block, is_string: is_string, type: type, optional: true, conflicting_options: conflicting_options, conflict_block: conflict_block, deprecated: deprecated, sensitive: sensitive, display_in_shell: display_in_shell) end def to_s @key end def self.env_name not_implemented(__method__) end def self.key not_implemented(__method__) end def self.description not_implemented(__method__) end def self.friendly_name not_implemented(__method__) end def self.default_value CredentialsManager::AppfileConfig.try_fetch_value(self.key) end def friendly_name return self.class.friendly_name end def inspect "#{self.class}(description: #{@description}, key: #{@key})" end # some rules can be customized with extra data at runtime, see CustomTextRule as an example def needs_customization? return false end # some rules can be customized with extra data at runtime, see CustomTextRule as an example def customize_with_data(data: nil) not_implemented(__method__) end # some rules only support specific fields, by default, all fields are supported unless restricted by # providing a list of symbols matching the item_name as defined as the ItemToCheck is generated def supported_fields_symbol_set return nil end def rule_block not_implemented(__method__) end def check_item(item) # validate the item we have was properly matched to this rule: TextItem -> TextRule, URLItem -> URLRule return skip_item_not_meant_for_this_rule(item) unless handle_item?(item) return skip_item_not_meant_for_this_rule(item) unless item_field_supported?(item_name: item.item_name) # do the actual checking now return perform_check(item: item) end def skip_item_not_meant_for_this_rule(item) # item isn't mean for this rule, which is fine, we can just keep passing it along return nil end # each rule can define what type of ItemToCheck subclass they support # override this method and return true or false def handle_item?(item) not_implemented(__method__) end def item_field_supported?(item_name: nil) return true if supported_fields_symbol_set.nil? return true if supported_fields_symbol_set.include?(item_name) return false end def perform_check(item: nil) if item.item_data.to_s == "" && item.is_optional # item is optional, and empty, so that's totally fine check_result = RuleReturn.new(validation_state: VALIDATION_STATES[:passed]) return RuleCheckResult.new(item, check_result, self) end check_result = self.rule_block.call(item.item_data) return RuleCheckResult.new(item, check_result, self) end end # Rule types are more or less just marker classes that are intended to communicate what types of things each rule # expects to deal with. TextRules deal with checking text values, URLRules will check url specific things like connectivity # TextRules expect that text values will be passed to the rule_block, likewise, URLs are expected to be passed to the # URLRule rule_block class TextRule < Rule def handle_item?(item) item.kind_of?(TextItemToCheck) ? true : false end end class URLRule < Rule def handle_item?(item) item.kind_of?(URLItemToCheck) ? true : false end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/module.rb
precheck/lib/precheck/module.rb
require 'fastlane_core/helper' require 'fastlane_core/ui/ui' require 'fastlane/boolean' module Precheck # Use this to just setup the configuration attribute and set it later somewhere else class << self attr_accessor :config def precheckfile_name "Precheckfile" end end Helper = FastlaneCore::Helper # you gotta love Ruby: Helper.* should use the Helper class contained in FastlaneCore UI = FastlaneCore::UI Boolean = Fastlane::Boolean ROOT = Pathname.new(File.expand_path('../../..', __FILE__)) ENV['APP_IDENTIFIER'] ||= ENV["PRECHECK_APP_IDENTIFIER"] DESCRIPTION = 'Check your app using a community driven set of App Store review rules to avoid being rejected' end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rule_check_result.rb
precheck/lib/precheck/rule_check_result.rb
module Precheck # after each item is checked for rule conformance to a single rule, a result is generated # a result can have a status of success or fail for a given rule/item class RuleCheckResult attr_accessor :item attr_accessor :rule_return # RuleReturn attr_accessor :rule def initialize(item, rule_return, rule) @item = item @rule_return = rule_return @rule = rule end def status rule_return.validation_state end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/item_to_check.rb
precheck/lib/precheck/item_to_check.rb
module Precheck # each attribute on a app version is a single item. # for example: .name, .keywords, .description, will all have a single item to represent them # which includes their name and a more user-friendly name we can use to print out information class ItemToCheck attr_accessor :item_name attr_accessor :friendly_name attr_accessor :is_optional def initialize(item_name, friendly_name, is_optional = false) @item_name = item_name @friendly_name = friendly_name @is_optional = is_optional end def item_data not_implemented(__method__) end def inspect "#{self.class}(friendly_name: #{@friendly_name}, data: #{@item_data})" end def to_s "#{self.class}: #{item_name}: #{friendly_name}" end end # if the data point we want to check is a text field (like 'description'), we'll use this object to encapsulate it # this includes the text, the property name, and what that name maps to in plain english so that we can print out nice, friendly messages. class TextItemToCheck < ItemToCheck attr_accessor :text def initialize(text, item_name, friendly_name, is_optional = false) @text = text super(item_name, friendly_name, is_optional) end def item_data return text end end # if the data point we want to check is a URL field (like 'marketing_url'), we'll use this object to encapsulate it # this includes the url, the property name, and what that name maps to in plain english so that we can print out nice, friendly messages. class URLItemToCheck < ItemToCheck attr_accessor :url def initialize(url, item_name, friendly_name, is_optional = false) @url = url super(item_name, friendly_name, is_optional) end def item_data return url end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/negative_apple_sentiment_rule.rb
precheck/lib/precheck/rules/negative_apple_sentiment_rule.rb
require_relative 'abstract_text_match_rule' module Precheck class NegativeAppleSentimentRule < AbstractTextMatchRule def self.key :negative_apple_sentiment end def self.env_name "RULE_NEGATIVE_APPLE_SENTIMENT" end def self.friendly_name "No negative  sentiment" end def self.description "mentioning  in a way that could be considered negative" end def lowercased_words_to_look_for [ "ios", "macos", "safari", "webkit", "uikit", "apple store" ].map { |word| (word + " bug").downcase } + [ "slow iphone", "slow ipad", "old iphone" ] end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/unreachable_urls_rule.rb
precheck/lib/precheck/rules/unreachable_urls_rule.rb
require 'addressable' require 'faraday_middleware' require_relative '../rule' module Precheck class UnreachableURLRule < URLRule def self.key :unreachable_urls end def self.env_name "RULE_UNREACHABLE_URLS" end def self.friendly_name "No broken urls" end def self.description "unreachable URLs in app metadata" end def rule_block return lambda { |url| url = url.to_s.strip return RuleReturn.new(validation_state: Precheck::VALIDATION_STATES[:failed], failure_data: "empty url") if url.empty? begin uri = Addressable::URI.parse(url) uri.fragment = nil request = Faraday.new(uri.normalize.to_s) do |connection| connection.use(FaradayMiddleware::FollowRedirects) connection.adapter(:net_http) end return RuleReturn.new(validation_state: Precheck::VALIDATION_STATES[:failed], failure_data: "HTTP #{request.head.status}: #{url}") unless request.head.status == 200 rescue StandardError => e UI.verbose("URL #{url} not reachable 😵: #{e.message}") # I can only return :fail here, but I also want to return #{url} return RuleReturn.new(validation_state: VALIDATION_STATES[:failed], failure_data: "unreachable: #{url}") end return RuleReturn.new(validation_state: VALIDATION_STATES[:passed]) } end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/abstract_text_match_rule.rb
precheck/lib/precheck/rules/abstract_text_match_rule.rb
require_relative '../rule' module Precheck # abstract class that defines a default way to check for the presence of a list of words within a block of text class AbstractTextMatchRule < TextRule WORD_SEARCH_TYPES = { fail_on_inclusion: "fail_on_inclusion", fail_on_exclusion: "fail_on_exclusion" } attr_accessor :lowercased_words_to_look_for def lowercased_words_to_look_for not_implemented(__method__) end # list of words or phrases that should be excluded from this rule # they will be removed from the text string before the rule is executed def allowed_lowercased_words [] end def pass_if_empty? return true end def word_search_type WORD_SEARCH_TYPES[:fail_on_inclusion] end def remove_safe_words(text: nil) text_without_safe_words = text allowed_lowercased_words.each do |safe_word| text_without_safe_words.gsub!(safe_word, '') end return text_without_safe_words end # rule block that checks text for any instance of each string in lowercased_words_to_look_for def rule_block return lambda { |text| text = text.to_s.strip.downcase if text.empty? if pass_if_empty? return RuleReturn.new(validation_state: Precheck::VALIDATION_STATES[:passed]) else return RuleReturn.new(validation_state: VALIDATION_STATES[:failed], failure_data: "missing text") end end text = remove_safe_words(text: text) matches = lowercased_words_to_look_for.each_with_object([]) do |word, found_words| if text.include?(word) found_words << word end end if matches.length > 0 && word_search_type == WORD_SEARCH_TYPES[:fail_on_inclusion] # we are supposed to fail if any of the words are found friendly_matches = matches.join(', ') UI.verbose("😭 #{self.class.name.split('::').last ||= self.class.name} found words \"#{friendly_matches}\"") return RuleReturn.new(validation_state: VALIDATION_STATES[:failed], failure_data: "found: #{friendly_matches}") elsif matches.length < lowercased_words_to_look_for.length && word_search_type == WORD_SEARCH_TYPES[:fail_on_exclusion] # we are supposed to fail if any of the words are not found (like current copyright date in the copyright field) search_data_set = lowercased_words_to_look_for.to_set search_data_set.subtract(matches) missing_words = search_data_set.to_a.join(', ') UI.verbose("😭 #{self.class.name.split('::').last ||= self.class.name} didn't find words \"#{missing_words}\"") return RuleReturn.new(validation_state: VALIDATION_STATES[:failed], failure_data: "missing: #{missing_words}") else return RuleReturn.new(validation_state: VALIDATION_STATES[:passed]) end } end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/free_stuff_iap_rule.rb
precheck/lib/precheck/rules/free_stuff_iap_rule.rb
require_relative 'abstract_text_match_rule' module Precheck class FreeStuffIAPRule < AbstractTextMatchRule def self.key :free_stuff_in_iap end def self.env_name "RULE_FREE_STUFF_IN_IAP" end def self.friendly_name "No words indicating your IAP is free" end def self.description "using text indicating that your IAP is free" end def supported_fields_symbol_set [:in_app_purchase].to_set end def lowercased_words_to_look_for [ "free" ].map(&:downcase) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/copyright_date_rule.rb
precheck/lib/precheck/rules/copyright_date_rule.rb
require_relative 'abstract_text_match_rule' module Precheck class CopyrightDateRule < AbstractTextMatchRule def self.key :copyright_date end def self.env_name "RULE_COPYRIGHT_DATE" end def self.friendly_name "Incorrect, or missing copyright date" end def self.description "using a copyright date that is any different from this current year, or missing a date" end def pass_if_empty? return false end def supported_fields_symbol_set [:copyright].to_set end def word_search_type WORD_SEARCH_TYPES[:fail_on_exclusion] end def lowercased_words_to_look_for [DateTime.now.year.to_s] end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/placeholder_words_rule.rb
precheck/lib/precheck/rules/placeholder_words_rule.rb
require_relative 'abstract_text_match_rule' module Precheck class PlaceholderWordsRule < AbstractTextMatchRule def self.key :placeholder_text end def self.env_name "RULE_PLACEHOLDER_TEXT_THINGS" end def self.friendly_name "No placeholder text" end def self.description "using placeholder text (e.g.:\"lorem ipsum\", \"text here\", etc...)" end def lowercased_words_to_look_for [ "hipster ipsum", "bacon ipsum", "lorem ipsum", "placeholder", "text here" ].map(&:downcase) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/curse_words_rule.rb
precheck/lib/precheck/rules/curse_words_rule.rb
require 'digest' require_relative '../rule' module Precheck class CurseWordsRule < TextRule def self.key :curse_words end def self.env_name "RULE_CURSE_WORDS" end def self.friendly_name "No curse words" end def self.description "including words that might be considered objectionable" end def rule_block return lambda { |text| return RuleReturn.new(validation_state: Precheck::VALIDATION_STATES[:passed]) if text.to_s.strip.empty? text = text.downcase split_words = text.split split_words_without_punctuation = text.gsub(/\W/, ' ').split # remove punctuation and add only unique words all_metadata_words_list = (split_words + split_words_without_punctuation).uniq metadata_word_hashes = all_metadata_words_list.map { |word| Digest::SHA256.hexdigest(word) } curse_hashes_set = hashed_curse_word_set found_words = [] metadata_word_hashes.each_with_index do |word, index| if curse_hashes_set.include?(word) found_words << all_metadata_words_list[index] end end if found_words.length > 0 friendly_found_words = found_words.join(', ') UI.verbose("#{self.class.name.split('::').last ||= self.class.name} found potential curse words 😬") UI.verbose("Keep in mind, these words might be ok given the context they are used in") UI.verbose("Matched: \"#{friendly_found_words}\"") return RuleReturn.new(validation_state: VALIDATION_STATES[:failed], failure_data: "found: #{friendly_found_words}") else return RuleReturn.new(validation_state: VALIDATION_STATES[:passed]) end } end def hashed_curse_word_set curse_hashes = [] File.open(File.dirname(__FILE__) + '/rules_data/curse_word_hashes/en_us.txt').each do |line| curse_hashes << line.to_s.strip end return curse_hashes.to_set end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/test_words_rule.rb
precheck/lib/precheck/rules/test_words_rule.rb
require_relative 'abstract_text_match_rule' module Precheck class TestWordsRule < AbstractTextMatchRule def self.key :test_words end def self.env_name "RULE_TEST_WORDS" end def self.friendly_name "No words indicating test content" end def self.description "using text indicating this release is a test" end def lowercased_words_to_look_for [ "testing", "just a test", "alpha test", "beta test" ].map(&:downcase) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/custom_text_rule.rb
precheck/lib/precheck/rules/custom_text_rule.rb
require_relative 'abstract_text_match_rule' module Precheck class CustomTextRule < AbstractTextMatchRule attr_accessor :data def self.key :custom_text end def self.env_name "RULE_CUSTOM_TEXT" end def self.friendly_name "No user-specified words are included" end def self.description "mentioning any of the user-specified words passed to #{self.key}(data: [words])" end def needs_customization? return true end def lowercased_words_to_look_for return @data end def customize_with_data(data: nil) @data = data.map { |word| word.strip.downcase } end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/other_platforms_rule.rb
precheck/lib/precheck/rules/other_platforms_rule.rb
require_relative 'abstract_text_match_rule' module Precheck class OtherPlatformsRule < AbstractTextMatchRule def self.key :other_platforms end def self.env_name "RULE_OTHER_PLATFORMS" end def self.friendly_name "No mentioning  competitors" end def self.description "mentioning other platforms, like Android or Blackberry" end def allowed_lowercased_words [ "google analytics", "google drive" ] end def lowercased_words_to_look_for [ "android", "google", "compuserve", "windows phone", "windows 10 mobile", "sailfish os", "windows universal app", "blackberry", "palm os", "symbian" ].map(&:downcase) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/future_functionality_rule.rb
precheck/lib/precheck/rules/future_functionality_rule.rb
require_relative 'abstract_text_match_rule' module Precheck class FutureFunctionalityRule < AbstractTextMatchRule def self.key :future_functionality end def self.env_name "RULE_FUTURE_FUNCTIONALITY" end def self.friendly_name "No future functionality promises" end def self.description "mentioning features or content that is not currently available in your app" end def lowercased_words_to_look_for [ "coming soon", "coming shortly", "in the next release", "arriving soon", "arriving shortly", "here soon", "here shortly" ].map(&:downcase) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/precheck/lib/precheck/rules/all.rb
precheck/lib/precheck/rules/all.rb
Dir[File.dirname(__FILE__) + '/*.rb'].each { |file| require_relative file }
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/cert/spec/commands_generator_spec.rb
cert/spec/commands_generator_spec.rb
require 'cert/commands_generator' describe Cert::CommandsGenerator do let(:runner) do runner = Cert::Runner.new expect(Cert::Runner).to receive(:new).and_return(runner) runner end describe ":create option handling" do it "can use the username short flag from tool options" do # leaving out the command name defaults to 'create' stub_commander_runner_args(['-u', 'me@it.com']) # launch takes no params, but we want to expect the call and prevent # actual execution of the method expect(runner).to receive(:launch) Cert::CommandsGenerator.start expect(Cert.config[:username]).to eq('me@it.com') end it "can use the platform flag from tool options" do # leaving out the command name defaults to 'create' stub_commander_runner_args(['--platform', 'macos']) # launch takes no params, but we want to expect the call and prevent # actual execution of the method expect(runner).to receive(:launch) Cert::CommandsGenerator.start expect(Cert.config[:platform]).to eq('macos') end end describe ":revoke_expired option handling" do it "can use the development flag from tool options" do stub_commander_runner_args(['revoke_expired', '--development', 'true']) # revoke_expired_certs! takes no params, but we want to expect the call # and prevent actual execution of the method expect(runner).to receive(:revoke_expired_certs!) Cert::CommandsGenerator.start expect(Cert.config[:development]).to be(true) end it "can use the output_path short flag from tool options" do stub_commander_runner_args(['revoke_expired', '-o', 'output/path']) # revoke_expired_certs! takes no params, but we want to expect the call # and prevent actual execution of the method expect(runner).to receive(:revoke_expired_certs!) Cert::CommandsGenerator.start expect(Cert.config[:output_path]).to eq('output/path') end end describe ":filename option handling" do it "can use the filename flag from tool options" do stub_commander_runner_args(['-q', 'cert_name']) # launch takes no params, but we want to expect the call and prevent # actual execution of the method expect(runner).to receive(:launch) Cert::CommandsGenerator.start expect(Cert.config[:filename]).to eq('cert_name') end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/cert/spec/runner_spec.rb
cert/spec/runner_spec.rb
require 'tmpdir' describe Cert do describe Cert::Runner do before do ENV["DELIVER_USER"] = "test@fastlane.tools" ENV["DELIVER_PASSWORD"] = "123" end xcode_versions = { "10" => Spaceship.certificate.production, "11" => Spaceship.certificate.apple_distribution } # Iterates over different Xcode versions to test different cert types # Xcode 10 and earlier - Spaceship.certificate.production # Xcode 11 and later - Spaceship.certificate.apple_distribution xcode_versions.each do |xcode_version, dist_cert_type| context "Xcode #{xcode_version}" do before do allow(FastlaneCore::Helper).to receive(:mac?).and_return(true) allow(FastlaneCore::Helper).to receive(:xcode_version).and_return(xcode_version) end it "Successful run" do certificate = stub_certificate allow(Spaceship::ConnectAPI).to receive(:login).and_return(nil) allow(Spaceship::ConnectAPI).to receive(:client).and_return("client") allow(Spaceship::ConnectAPI.client).to receive(:in_house?).and_return(false) allow(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([certificate]) certificate_path = "#{Dir.pwd}/cert_id.cer" keychain_path = Dir.pwd.to_s expect(FastlaneCore::CertChecker).to receive(:installed?) .with(certificate_path, in_keychain: keychain_path) .twice .and_return(true) options = { keychain_path: "." } Cert.config = FastlaneCore::Configuration.create(Cert::Options.available_options, options) Cert::Runner.new.launch expect(ENV["CER_CERTIFICATE_ID"]).to eq("cert_id") expect(ENV["CER_FILE_PATH"]).to eq(certificate_path) expect(ENV["CER_KEYCHAIN_PATH"]).to eq(keychain_path) File.delete(ENV["CER_FILE_PATH"]) end it "correctly selects expired certificates" do expired_cert = stub_certificate("expired_cert", false) good_cert = stub_certificate allow(Spaceship::ConnectAPI).to receive(:login).and_return(nil) allow(Spaceship::ConnectAPI).to receive(:client).and_return("client") allow(Spaceship::ConnectAPI.client).to receive(:in_house?).and_return(false) allow(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([expired_cert, good_cert]) expect(Cert::Runner.new.expired_certs).to eq([expired_cert]) end it "revokes expired certificates via revoke_expired sub-command" do expired_cert = stub_certificate("expired_cert", false) good_cert = stub_certificate allow(Spaceship::ConnectAPI).to receive(:login).and_return(nil) allow(Spaceship::ConnectAPI).to receive(:client).and_return("client") allow(Spaceship::ConnectAPI.client).to receive(:in_house?).and_return(false) allow(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([expired_cert, good_cert]) allow(FastlaneCore::CertChecker).to receive(:installed?).and_return(true) expect(expired_cert).to receive(:delete!) expect(good_cert).to_not(receive(:delete!)) Cert.config = FastlaneCore::Configuration.create(Cert::Options.available_options, keychain_path: ".") Cert::Runner.new.revoke_expired_certs! end it "tries to revoke all expired certificates even if one has an error" do expired_cert_1 = stub_certificate("expired_cert_1", false) expired_cert_2 = stub_certificate("expired_cert_2", false) allow(Spaceship::ConnectAPI).to receive(:login).and_return(nil) allow(Spaceship::ConnectAPI).to receive(:client).and_return("client") allow(Spaceship::ConnectAPI.client).to receive(:in_house?).and_return(false) allow(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([expired_cert_1, expired_cert_2]) allow(FastlaneCore::CertChecker).to receive(:installed?).and_return(true) expect(expired_cert_1).to receive(:delete!).and_raise("Boom!") expect(expired_cert_2).to receive(:delete!) Cert.config = FastlaneCore::Configuration.create(Cert::Options.available_options, keychain_path: ".") Cert::Runner.new.revoke_expired_certs! end describe ":filename option handling" do filename = "" let(:temp) { Dir.tmpdir } let(:certificate) { stub_certificate } let(:filepath) do filename_ext = File.extname(filename) == ".cer" ? filename : "#{filename}.cer" File.extname(filename) == ".cer" ? "#{temp}/#{filename}" : "#{temp}/#{filename}.cer" end before do allow(Spaceship::ConnectAPI).to receive(:login).and_return(nil) allow(Spaceship::ConnectAPI).to receive(:client).and_return("client") allow(Spaceship::ConnectAPI.client).to receive(:in_house?).and_return(false) allow(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([certificate]) allow(FastlaneCore::CertChecker).to receive(:installed?).and_return(true) end let(:generate) do options = { output_path: temp, filename: filename, keychain_path: "." } Cert.config = FastlaneCore::Configuration.create(Cert::Options.available_options, options) Cert::Runner.new.launch end context 'with filename flag' do it "can forget the file extension" do filename = "cert_name" expect(File.exist?(filepath)).to be false generate expect(File.exist?(filepath)).to be true File.delete(filepath) end it "can use the file extension" do filename = "cert_name.cer" expect(File.exist?(filepath)).to be false generate expect(File.exist?(filepath)).to be true File.delete(filepath) end end context 'without filename flag' do it "can generate certificate" do filename = "cert_name.cer" expect(File.exist?(filepath)).to be false generate expect(File.exist?(filepath)).to be true File.delete(filepath) end end end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/cert/spec/spec_helper.rb
cert/spec/spec_helper.rb
# Create a stub certificate object that reports its expiration date # as the provided Time, or 1 day from now by default def stub_certificate(name = "certificate", valid = true) name.tap do |cert| allow(cert).to receive(:id).and_return("cert_id") allow(cert).to receive(:valid?).and_return(valid) allow(cert).to receive(:display_name).and_return("name") allow(cert).to receive(:certificate_content).and_return(Base64.encode64("download_raw")) end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/cert/lib/cert.rb
cert/lib/cert.rb
require_relative 'cert/runner' require_relative 'cert/options' require_relative 'cert/module'
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/cert/lib/cert/options.rb
cert/lib/cert/options.rb
require 'credentials_manager/appfile_config' require 'fastlane_core/configuration/config_item' require_relative 'module' module Cert class Options def self.available_options user = CredentialsManager::AppfileConfig.try_fetch_value(:apple_dev_portal_id) user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id) [ FastlaneCore::ConfigItem.new(key: :development, env_name: "CERT_DEVELOPMENT", description: "Create a development certificate instead of a distribution one", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :type, env_name: "CERT_TYPE", description: "Create specific certificate type (takes precedence over :development)", optional: true, verify_block: proc do |value| value = value.to_s types = %w(mac_installer_distribution developer_id_installer developer_id_application developer_id_kext) UI.user_error!("Unsupported types, must be: #{types}") unless types.include?(value) end), FastlaneCore::ConfigItem.new(key: :force, env_name: "CERT_FORCE", description: "Create a certificate even if an existing certificate exists", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :generate_apple_certs, env_name: "CERT_GENERATE_APPLE_CERTS", description: "Create a certificate type for Xcode 11 and later (Apple Development or Apple Distribution)", type: Boolean, default_value: FastlaneCore::Helper.mac? && FastlaneCore::Helper.xcode_at_least?('11'), default_value_dynamic: true), # App Store Connect API FastlaneCore::ConfigItem.new(key: :api_key_path, env_names: ["CERT_API_KEY_PATH", "DELIVER_API_KEY_PATH", "APP_STORE_CONNECT_API_KEY_PATH"], description: "Path to your App Store Connect API Key JSON file (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-json-file)", optional: true, conflicting_options: [:api_key], verify_block: proc do |value| UI.user_error!("Couldn't find API key JSON file at path '#{value}'") unless File.exist?(value) end), FastlaneCore::ConfigItem.new(key: :api_key, env_names: ["CERT_API_KEY", "DELIVER_API_KEY", "APP_STORE_CONNECT_API_KEY"], description: "Your App Store Connect API Key information (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-hash-option)", type: Hash, optional: true, sensitive: true, conflicting_options: [:api_key_path]), # Apple ID FastlaneCore::ConfigItem.new(key: :username, short_option: "-u", env_name: "CERT_USERNAME", description: "Your Apple ID Username", optional: true, default_value: user, default_value_dynamic: true), FastlaneCore::ConfigItem.new(key: :team_id, short_option: "-b", env_name: "CERT_TEAM_ID", code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_id), default_value_dynamic: true, description: "The ID of your Developer Portal team if you're in multiple teams", optional: true, verify_block: proc do |value| ENV["FASTLANE_TEAM_ID"] = value.to_s end), FastlaneCore::ConfigItem.new(key: :team_name, short_option: "-l", env_name: "CERT_TEAM_NAME", description: "The name of your Developer Portal team if you're in multiple teams", optional: true, code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_name), default_value_dynamic: true, verify_block: proc do |value| ENV["FASTLANE_TEAM_NAME"] = value.to_s end), # Other Options FastlaneCore::ConfigItem.new(key: :filename, short_option: "-q", env_name: "CERT_FILE_NAME", optional: true, description: "The filename of certificate to store"), FastlaneCore::ConfigItem.new(key: :output_path, short_option: "-o", env_name: "CERT_OUTPUT_PATH", description: "The path to a directory in which all certificates and private keys should be stored", default_value: "."), FastlaneCore::ConfigItem.new(key: :keychain_path, short_option: "-k", env_name: "CERT_KEYCHAIN_PATH", description: "Path to a custom keychain", code_gen_sensitive: true, default_value: Helper.mac? ? Dir["#{Dir.home}/Library/Keychains/login.keychain", "#{Dir.home}/Library/Keychains/login.keychain-db"].last : nil, default_value_dynamic: true, optional: true, verify_block: proc do |value| UI.user_error!("Keychain is not supported on platforms other than macOS") if !Helper.mac? && value value = File.expand_path(value) UI.user_error!("Keychain not found at path '#{value}'") unless File.exist?(value) end), FastlaneCore::ConfigItem.new(key: :keychain_password, short_option: "-p", env_name: "CERT_KEYCHAIN_PASSWORD", sensitive: true, description: "This might be required the first time you access certificates on a new mac. For the login/default keychain this is your macOS account password", optional: true, verify_block: proc do |value| UI.user_error!("Keychain is not supported on platforms other than macOS") unless Helper.mac? end), FastlaneCore::ConfigItem.new(key: :skip_set_partition_list, short_option: "-P", env_name: "CERT_SKIP_SET_PARTITION_LIST", description: "Skips setting the partition list (which can sometimes take a long time). Setting the partition list is usually needed to prevent Xcode from prompting to allow a cert to be used for signing", type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :platform, env_name: "CERT_PLATFORM", description: "Set the provisioning profile's platform (ios, macos, tvos)", default_value: "ios", verify_block: proc do |value| value = value.to_s pt = %w(macos ios tvos) UI.user_error!("Unsupported platform, must be: #{pt}") unless pt.include?(value) end) ] end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/cert/lib/cert/commands_generator.rb
cert/lib/cert/commands_generator.rb
require 'commander' require 'fastlane/version' require 'fastlane_core/ui/help_formatter' require 'fastlane_core/configuration/configuration' require 'fastlane_core/globals' require_relative 'options' require_relative 'runner' HighLine.track_eof = false module Cert class CommandsGenerator include Commander::Methods def self.start self.new.run end def run program :name, 'cert' program :version, Fastlane::VERSION program :description, 'CLI for \'cert\' - Create new iOS code signing certificates' program :help, 'Author', 'Felix Krause <cert@krausefx.com>' program :help, 'Website', 'https://fastlane.tools' program :help, 'Documentation', 'https://docs.fastlane.tools/actions/cert/' program :help_formatter, FastlaneCore::HelpFormatter global_option('--verbose') { FastlaneCore::Globals.verbose = true } global_option('--env STRING[,STRING2]', String, 'Add environment(s) to use with `dotenv`') command :create do |c| c.syntax = 'fastlane cert create' c.description = 'Create new iOS code signing certificates' FastlaneCore::CommanderGenerator.new.generate(Cert::Options.available_options, command: c) c.action do |args, options| Cert.config = FastlaneCore::Configuration.create(Cert::Options.available_options, options.__hash__) Cert::Runner.new.launch end end command :revoke_expired do |c| c.syntax = 'fastlane cert revoke_expired' c.description = 'Revoke expired iOS code signing certificates' FastlaneCore::CommanderGenerator.new.generate(Cert::Options.available_options, command: c) c.action do |args, options| Cert.config = FastlaneCore::Configuration.create(Cert::Options.available_options, options.__hash__) Cert::Runner.new.revoke_expired_certs! end end default_command(:create) run! end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false