KiCad PCB EDA Suite
Loading...
Searching...
No Matches
git_credentials_prompt.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 3
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
24#include <confirm.h>
25#include <eda_base_frame.h>
26#include <wx/app.h>
27#include <wx/utils.h>
28#include <wx/weakref.h>
29#include <mutex>
30#include <git/git_backend.h>
33#include <git/kigit_ssh_keys.h>
34#include <pgm_base.h>
35#include <project.h>
37#include <kiplatform/secrets.h>
38#include <trace_helpers.h>
39#include <widgets/kistatusbar.h>
40
41
42// A session that never read its remote would show no address and offer no transport
43static void resolveMissingRemote( KIGIT_COMMON* aCommon )
44{
45 if( !aCommon->GetRemote().IsEmpty() || !aCommon->GetRepo() )
46 return;
47
48 // A status read holds the lock for moments at a time, so a short wait usually gets it
49 wxBusyCursor busy;
50 std::unique_lock<std::mutex> lock = aCommon->TryLockActionFor( KIGIT_COMMON::ACTION_LOCK_WAIT );
51
52 if( !lock.owns_lock() )
53 {
54 wxLogTrace( traceGit, "Credential prompt opens without an address, the repository is busy" );
55 return;
56 }
57
58 wxString remoteName = aCommon->GetRemoteNameOrDefault();
59 git_remote* remote = nullptr;
60
61 if( git_remote_lookup( &remote, aCommon->GetRepo(), remoteName.utf8_string().c_str() ) != GIT_OK )
62 return;
63
64 KIGIT::GitRemotePtr remotePtr( remote );
65
66 // The retry's credential callback compares against this, so both see one identity
67 if( const char* url = git_remote_url( remote ) )
68 aCommon->SyncRemoteUrl( wxString::FromUTF8( url ) );
69}
70
71
72// The window that asked can close while a prompt waits, freeing it and its project with it
73static bool askerGone( const wxWeakRef<wxWindow>& aParent, bool aHadParent )
74{
75 if( !aHadParent )
76 return false;
77
78 if( !aParent )
79 return true;
80
81 // Destroy() on a top level window only queues the delete, so its weak ref still answers
82 for( wxWindow* window = aParent.get(); window; window = window->GetParent() )
83 {
84 if( window->IsBeingDeleted() || wxTheApp->IsScheduledForDestruction( window ) )
85 return true;
86 }
87
88 return false;
89}
90
91
92// Any modal here can outlast its parent, so every answer short of acceptance says whether it did
93static KIGIT::PROMPT_ANSWER refusal( const wxWeakRef<wxWindow>& aParent, bool aHadParent )
94{
96}
97
98
99// The project's key outlives the session's list, which a host change regathers, but a deleted one is never offered
100static wxString initialSSHKey( KIGIT_COMMON* aCommon, PROJECT* aProject )
101{
102 // The server named this key as the one it takes, so its passphrase is the one to ask for
103 if( wxString accepted = aCommon->GetAcceptedSSHKey(); KIGIT::IsOfferableSSHKey( accepted ) )
104 return accepted;
105
106 if( aProject && KIGIT::IsOfferableSSHKey( aProject->GetLocalSettings().m_GitSSHKey ) )
107 return aProject->GetLocalSettings().m_GitSSHKey;
108
109 return aCommon->GetFirstOfferedSSHKey();
110}
111
112
114 const wxString& aExplanation )
115{
116 resolveMissingRemote( aCommon );
117
119 wxString shownUsername = identity.username;
120
121 if( shownUsername.IsEmpty() && aProject )
122 shownUsername = aProject->GetLocalSettings().m_GitRepoUsername;
123
124 wxWeakRef<wxWindow> parent( aParent );
125 DIALOG_GIT_CREDENTIALS dlg( aParent, identity.remote, aExplanation, identity.connType, shownUsername,
126 initialSSHKey( aCommon, aProject ) );
127
128 if( dlg.ShowModal() != wxID_OK || askerGone( parent, aParent != nullptr ) )
129 return refusal( parent, aParent != nullptr );
130
132
133 // An ssh remote's user comes from its address, and the server refuses a different one.
134 bool urlNamesUser = ssh && !KIGIT_COMMON::ParseRemoteURL( identity.remote ).username.IsEmpty();
135
137 entered.connType = dlg.GetConnType();
138 entered.password = dlg.GetPassword();
139
140 if( !urlNamesUser )
141 entered.username = dlg.GetUsername();
142
143 if( ssh )
144 entered.sshKey = dlg.GetSSHKey();
145
146 // A background fetch can move the session to another remote while the dialog is open
147 if( !aCommon->ApplyPromptedCredentials( identity, entered ) )
148 {
149 wxLogTrace( traceGit, "Credential prompt discarded, the remote changed while it was open" );
150 DisplayInfoMessage( aParent, _( "The remote changed while this window was open. Try the operation again." ) );
151 return refusal( parent, aParent != nullptr );
152 }
153
154 wxString username = entered.username ? *entered.username : identity.username;
155
156 if( dlg.SaveCredentials() )
157 {
158 // A locked keyring prompts to unlock, which must not hold the event loop
160 identity.remote, username, entered.password,
161 [parent]( bool aStored )
162 {
163 if( !aStored && parent )
164 {
165 DisplayInfoMessage( parent, _( "The credentials could not be saved to the system keychain, "
166 "so they are kept for this session only." ) );
167 }
168 } );
169
170 // Windows answers inline, so a failed save has already shown its message
171 if( askerGone( parent, aParent != nullptr ) )
173 }
174
175 // A correction only in the session would be reverted by the next attach.
176 if( aProject )
177 {
178 if( !urlNamesUser )
179 aProject->GetLocalSettings().m_GitRepoUsername = dlg.GetUsername();
180
181 if( ssh && !dlg.GetSSHKey().IsEmpty() )
182 aProject->GetLocalSettings().m_GitSSHKey = dlg.GetSSHKey();
183
185 aProject->GetLocalSettings().m_GitRepoType = ssh ? wxS( "ssh" ) : wxS( "https" );
186 }
187
188 return PROMPT_ANSWER::ACCEPTED;
189}
190
191
193 bool aRetriedAfterTrust )
194{
195 wxWeakRef<wxWindow> parent( aParent );
196 wxString host = aFailure.host;
197
198 if( aFailure.port != 22 )
199 host << wxS( ":" ) << aFailure.port;
200
201 if( !MayOfferTrust( aFailure, aRetriedAfterTrust ) )
202 {
203 DisplayErrorMessage( aParent, HostKeyRefusalMessage( aFailure ) );
204 return refusal( parent, aParent != nullptr );
205 }
206
207 wxString question;
208
210 {
211 question = _( "%s is already known by a different key type. The key it presented has fingerprint "
212 "SHA256:%s. Connect and remember this key too?" );
213 }
214 else
215 {
216 question = _( "This is the first time connecting to %s. Its key fingerprint is SHA256:%s. Connect and "
217 "remember this server?" );
218 }
219
220 // Enter must never trust a server
221 auto dlg = KICAD_MESSAGE_DIALOG( aParent, wxString::Format( question, host, aFailure.fingerprint ),
222 _( "Verify Server" ), wxYES_NO | wxNO_DEFAULT | wxICON_WARNING | wxCENTER );
223 dlg.SetYesNoLabels( _( "&Connect" ), _( "Cancel" ) );
224
225 if( dlg.ShowModal() != wxID_YES || askerGone( parent, aParent != nullptr ) )
226 return refusal( parent, aParent != nullptr );
227
228 if( !AddKnownHost( aFailure ) )
229 {
230 DisplayErrorMessage( aParent,
231 wxString::Format( _( "The key for %s could not be saved, so the connection was not "
232 "made. Check that your .ssh folder can be written to." ),
233 host ),
234 KnownHostsPath() );
235 return refusal( parent, aParent != nullptr );
236 }
237
239}
240
241
242KIGIT::TRANSFER_RETRY KIGIT::AnswerTransferFailure( wxWindow* aParent, const std::weak_ptr<bool>& aAlive,
243 KIGIT_COMMON* aCommon, PROJECT* aProject,
244 const TRANSFER_FAILURE& aFailure, bool aRetriedAfterTrust,
245 int& aPrompts )
246{
247 if( aFailure.cancelled )
248 {
249 aPrompts = 0;
251 }
252
253 // A prompt runs an event loop in which the window can close
254 if( aFailure.hostKey )
255 {
256 PROMPT_ANSWER answer = PromptToTrustHost( aParent, *aFailure.hostKey, aRetriedAfterTrust );
257
258 if( aAlive.expired() || answer == PROMPT_ANSWER::ABANDONED )
260
261 if( answer == PROMPT_ANSWER::DECLINED )
262 {
263 aPrompts = 0;
265 }
266
268 }
269
270 // A remote that keeps changing could otherwise send the request back to the keyring forever
271 if( !aFailure.authFailure || aPrompts >= MAX_CREDENTIAL_PROMPTS )
272 {
273 aPrompts = 0;
275 }
276
277 ++aPrompts;
278
279 // A stored secret answers before anyone is asked to type one
280 if( !aCommon->SecretRead() )
282
283 PROMPT_ANSWER answer = PromptForCredentials( aParent, aCommon, aProject, aFailure.error );
284
285 if( aAlive.expired() || answer == PROMPT_ANSWER::ABANDONED )
287
288 if( answer == PROMPT_ANSWER::DECLINED )
289 {
290 aPrompts = 0;
292 }
293
295}
296
297
298void KIGIT::ClearSyncWarnings( wxWindow* aWindow )
299{
300 for( wxWindow* window = aWindow; window; window = window->GetParent() )
301 {
302 if( wxFrame* frame = dynamic_cast<wxFrame*>( window ) )
303 {
304 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( frame->GetStatusBar() ) )
305 statusBar->ClearWarningMessages( SYNC_WARNING_SOURCE );
306
307 return;
308 }
309 }
310}
311
312
314{
315 // The manager lists the warnings, and an editor's pull or push answers them as well
316 for( wxWindow* window : wxTopLevelWindows )
317 {
318 EDA_BASE_FRAME* frame = dynamic_cast<EDA_BASE_FRAME*>( window );
319
320 if( frame && frame->HasKiway() && frame->Prj().GetGitCommon().get() == aCommon )
321 ClearSyncWarnings( frame );
322 }
323}
324
325
327{
328 GIT_IDENTITY identity;
329
330 if( !aCommon.GetRepo() )
331 return identity;
332
333 GIT_CONFIG_HANDLER handler( &aCommon );
334 identity.config.hasName = GetGitBackend()->GetConfigString( &handler, "user.name", identity.config.authorName );
335 identity.config.hasEmail = GetGitBackend()->GetConfigString( &handler, "user.email", identity.config.authorEmail );
336
337 git_signature* signature = nullptr;
338 identity.configured = git_signature_default( &signature, aCommon.GetRepo() ) == GIT_OK;
339 GitSignaturePtr signaturePtr( signature );
340 return identity;
341}
342
343
345 const wxString& aUserName )
346{
347 GitUserConfig config = aIdentity.config;
348
349 if( !aPreferences.useDefaultAuthor )
350 {
351 if( config.authorName.IsEmpty() )
352 config.authorName = aPreferences.authorName;
353
354 if( config.authorEmail.IsEmpty() )
355 config.authorEmail = aPreferences.authorEmail;
356 }
357
358 if( config.authorName.IsEmpty() )
359 config.authorName = aUserName;
360
361 return config;
362}
363
364
365namespace
366{
367
368bool identitySessionCurrent( EDA_BASE_FRAME* aFrame, const std::shared_ptr<KIGIT_COMMON>& aCommon )
369{
370 return aFrame && !aFrame->IsBeingDeleted() && aCommon && !aCommon->IsShuttingDown() && aCommon->GetRepo()
371 && aFrame->Prj().GetGitCommon() == aCommon && Pgm().GetCommonSettings()->m_Git.enableGit
373}
374
375} // namespace
376
377
378bool KIGIT::EditGitIdentity( wxWindow* aParent, EDA_BASE_FRAME* aFrame, const std::shared_ptr<KIGIT_COMMON>& aCommon,
379 const GIT_IDENTITY& aIdentity )
380{
381 if( !identitySessionCurrent( aFrame, aCommon ) )
382 return false;
383
384 wxWeakRef<EDA_BASE_FRAME> frame( aFrame );
385 wxWeakRef<wxWindow> parent( aParent );
386 GitUserConfig config = ResolveGitIdentity( aIdentity, Pgm().GetCommonSettings()->m_Git, wxGetUserName() );
387
388 {
389 DIALOG_GIT_IDENTITY dlg( aParent, _( "Set Author" ), config.authorName, config.authorEmail );
390
391 if( dlg.ShowModal() != wxID_OK )
392 return false;
393
394 config.authorName = dlg.GetAuthorName();
395 config.authorEmail = dlg.GetEmail();
396 }
397
398 if( !parent || parent->IsBeingDeleted() || !identitySessionCurrent( frame.get(), aCommon ) )
399 return false;
400
401 bool saved = false;
402
403 {
404 std::unique_lock<std::mutex> lock = KIGIT::WaitForActionLock( *aCommon, aParent );
405
406 if( !lock.owns_lock() )
407 return false;
408
409 if( !identitySessionCurrent( frame.get(), aCommon ) )
410 return false;
411
412 saved = aCommon->SetUserConfig( config.authorName, config.authorEmail );
413 }
414
415 if( !saved )
416 {
417 DisplayErrorMessage( aParent, _( "Could not save the name and email to the repository." ) );
418 return false;
419 }
420
421 aCommon->NotifyRefreshListeners();
422 return true;
423}
424
425
426bool KIGIT::EnsureGitIdentity( wxWindow* aParent, EDA_BASE_FRAME* aFrame, const std::shared_ptr<KIGIT_COMMON>& aCommon,
427 const GIT_IDENTITY& aIdentity )
428{
429 if( !identitySessionCurrent( aFrame, aCommon ) )
430 return false;
431
432 return aIdentity.configured || EditGitIdentity( aParent, aFrame, aCommon, aIdentity );
433}
KIGIT_COMMON::GIT_CONN_TYPE GetConnType() const
Ask for the name and email to record commits with.
wxString GetAuthorName() const
wxString GetEmail() const
int ShowModal() override
The base frame for deriving all KiCad main window classes.
virtual bool GetConfigString(GIT_CONFIG_HANDLER *aHandler, const wxString &aKey, wxString &aValue)=0
The project's git session.
wxString GetAcceptedSSHKey() const
The encrypted key the server last accepted for this remote, so the credential prompt asks for the rig...
void SyncRemoteUrl(const wxString &aRawUrl)
Bind the session to the URL a transfer is about to connect to.
wxString GetRemote() const
wxString GetRemoteNameOrDefault() const
Returns GetRemotename() when non-empty, otherwise "origin".
git_repository * GetRepo() const
CREDENTIAL_IDENTITY GetCredentialIdentity() const
std::unique_lock< std::mutex > TryLockActionFor(std::chrono::milliseconds aWait)
TryLockAction that keeps trying for aWait before giving up.
bool ApplyPromptedCredentials(const CREDENTIAL_IDENTITY &aFor, const PROMPTED_CREDENTIALS &aEntered)
Apply what the prompt collected, unless the session has moved to another remote since aFor was taken.
static constexpr std::chrono::milliseconds ACTION_LOCK_WAIT
Long enough for a status read to finish, short enough that a window does not look hung.
wxString GetFirstOfferedSSHKey() const
The key the next attempt will try first, for the credential prompt to show.
static REMOTE_URL ParseRemoteURL(const wxString &aURL)
bool SecretRead() const
False while the keyring has not been read for the current remote.
KISTATUSBAR is a wxStatusBar suitable for Kicad manager.
Definition kistatusbar.h:50
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
bool HasKiway() const
Safety check before asking for the Kiway reference.
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:600
bool m_GitIntegrationDisabled
If true, KiCad will not use Git integration for this project even if a .git directory exists.
Container for project specific data.
Definition project.h:63
virtual std::shared_ptr< KIGIT_COMMON > GetGitCommon() const
This project's Git session, created empty on first use.
Definition project.cpp:85
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition project.h:207
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition confirm.cpp:245
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
#define KICAD_MESSAGE_DIALOG
Definition confirm.h:48
#define _(s)
Base window classes and related definitions.
GIT_BACKEND * GetGitBackend()
static KIGIT::PROMPT_ANSWER refusal(const wxWeakRef< wxWindow > &aParent, bool aHadParent)
static wxString initialSSHKey(KIGIT_COMMON *aCommon, PROJECT *aProject)
static void resolveMissingRemote(KIGIT_COMMON *aCommon)
static bool askerGone(const wxWeakRef< wxWindow > &aParent, bool aHadParent)
const wxChar *const traceGit
Flag to enable Git debugging output.
constexpr int MAX_CREDENTIAL_PROMPTS
Keyring reads and credential prompts that may follow a request's failures before one is reported inst...
void ClearSyncWarnings(wxWindow *aWindow)
Clear the background fetch's warnings from the frame holding aWindow.
APIEXPORT bool IsOfferableSSHKey(const wxString &aKey)
Whether aKey can be offered to a server.
APIEXPORT bool AddKnownHost(const HOST_KEY_FAILURE &aKey)
Append the refused key to KnownHostsPath(), creating the file and its folder when missing.
GitUserConfig ResolveGitIdentity(const GIT_IDENTITY &aIdentity, const COMMON_SETTINGS::GIT &aPreferences, const wxString &aUserName)
Fill missing values from custom preferences, then use the OS user name if needed.
@ ABANDONED
The parent closed while the prompt was up, so the caller must not touch it.
constexpr const wxChar * SYNC_WARNING_SOURCE
The status bar source under which background fetch failures are listed.
@ OTHER_KEY_TYPE
Entries name the host only with keys of other types.
GIT_IDENTITY ReadGitIdentity(KIGIT_COMMON &aCommon)
Read on a worker while holding the session's action lock.
bool EnsureGitIdentity(wxWindow *aParent, EDA_BASE_FRAME *aFrame, const std::shared_ptr< KIGIT_COMMON > &aCommon, const GIT_IDENTITY &aIdentity)
Open the same editor when the worker snapshot has no usable Git identity.
std::unique_lock< std::mutex > WaitForActionLock(KIGIT_COMMON &aCommon, wxWindow *aParent)
TryLockAction that first waits a moment for a status read or fetch to let go.
TRANSFER_RETRY AnswerTransferFailure(wxWindow *aParent, const std::weak_ptr< bool > &aAlive, KIGIT_COMMON *aCommon, PROJECT *aProject, const TRANSFER_FAILURE &aFailure, bool aRetriedAfterTrust, int &aPrompts)
Answer a failed transfer the way every window does.
PROMPT_ANSWER PromptForCredentials(wxWindow *aParent, KIGIT_COMMON *aCommon, PROJECT *aProject=nullptr, const wxString &aExplanation=wxEmptyString)
Ask the user for the credentials of the session's remote and apply them to the session.
PROMPT_ANSWER PromptToTrustHost(wxWindow *aParent, const HOST_KEY_FAILURE &aFailure, bool aRetriedAfterTrust)
Ask whether to trust a server seen for the first time, and remember its key when the user agrees.
APIEXPORT bool MayOfferTrust(const HOST_KEY_FAILURE &aFailure, bool aRetriedAfterTrust)
Whether the user may be asked to trust a refused key.
TRANSFER_RETRY
What a window does after AnswerTransferFailure.
@ RETRY_TRUSTED
Run it again, now that the server's key is trusted.
@ GONE
The window closed during a prompt, so the caller must not touch it.
@ CANCELLED
Stop and say so, the user cancelled the transfer or a prompt.
@ RETRY
Run the transfer again.
@ HOST_DECLINED
Stop without a message, the user chose not to trust the server.
APIEXPORT wxString HostKeyRefusalMessage(const HOST_KEY_FAILURE &aFailure)
Why a key the user may not trust was refused, and what to do next.
bool EditGitIdentity(wxWindow *aParent, EDA_BASE_FRAME *aFrame, const std::shared_ptr< KIGIT_COMMON > &aCommon, const GIT_IDENTITY &aIdentity)
Edit the repository's author and refresh Git views after saving.
APIEXPORT wxString KnownHostsPath()
The known_hosts file libgit2 checks host keys against. Empty when it has no home folder.
std::unique_ptr< git_signature, decltype([](git_signature *aSignature) { git_signature_free(aSignature); })> GitSignaturePtr
A unique pointer for git_signature objects with automatic cleanup.
std::unique_ptr< git_remote, decltype([](git_remote *aRemote) { git_remote_free(aRemote); })> GitRemotePtr
A unique pointer for git_remote objects with automatic cleanup.
void StoreSecretAsync(const wxString &aService, const wxString &aKey, const wxString &aSecret, std::function< void(bool)> aDone=nullptr)
Like StoreSecret(), but never blocks the event loop while the platform asks the user to unlock the st...
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
Repository values and whether Git can use them to record a commit.
A server key the connection refused, for the UI to offer to trust or to report.
wxString fingerprint
SHA256 in unpadded base64, as ssh shows it after "SHA256:".
Why a transfer to a remote failed.
bool cancelled
The user cancelled the transfer.
std::optional< HOST_KEY_FAILURE > hostKey
The server's key is unknown or has changed.
bool authFailure
The remote refused every credential offered.
wxString error
Shown above the credential fields.
The remote the credential prompt was opened for.
What the credential prompt collected.
std::optional< wxString > username
wxLogTrace helper definitions.