QGIS API Documentation 3.99.0-Master (d31f8633d82)
Loading...
Searching...
No Matches
qgsauthmanager.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsauthmanager.cpp
3 ---------------------
4 begin : October 5, 2014
5 copyright : (C) 2014 by Boundless Spatial, Inc. USA
6 author : Larry Shaffer
7 email : lshaffer at boundlessgeo dot com
8 ***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
17#include <QCoreApplication>
18#include <QDir>
19#include <QDomDocument>
20#include <QDomElement>
21#include <QEventLoop>
22#include <QFile>
23#include <QFileInfo>
24#include <QMutexLocker>
25#include <QObject>
26#include <QRandomGenerator>
27#include <QRegularExpression>
28#include <QSet>
29#include <QSqlDatabase>
30#include <QSqlDriver>
31#include <QSqlError>
32#include <QSqlQuery>
33#include <QString>
34#include <QTextStream>
35#include <QTime>
36#include <QTimer>
37#include <QVariant>
38
39using namespace Qt::StringLiterals;
40
41#ifdef HAVE_AUTH
42#include <QtCrypto>
43#endif
44
45#ifndef QT_NO_SSL
46#include <QSslConfiguration>
47#endif
48
49// QGIS includes
50#ifdef HAVE_AUTH
51#include "qgsauthcertutils.h"
52#endif
53#include "qgsauthcrypto.h"
54#include "qgsauthmethod.h"
57#include "qgscredentials.h"
58#include "qgslogger.h"
59#include "qgsmessagelog.h"
60#include "qgsauthmanager.h"
61#include "moc_qgsauthmanager.cpp"
64#include "qgsvariantutils.h"
65#include "qgssettings.h"
66#include "qgsruntimeprofiler.h"
68#include "qgssettingstree.h"
69
70QgsAuthManager *QgsAuthManager::sInstance = nullptr;
71
72const QString QgsAuthManager::AUTH_CONFIG_TABLE = u"auth_configs"_s;
73const QString QgsAuthManager::AUTH_SERVERS_TABLE = u"auth_servers"_s;
74const QString QgsAuthManager::AUTH_MAN_TAG = QObject::tr( "Authentication Manager" );
75const QString QgsAuthManager::AUTH_CFG_REGEX = u"authcfg=([a-z]|[A-Z]|[0-9]){7}"_s;
76
77
78const QLatin1String QgsAuthManager::AUTH_PASSWORD_HELPER_KEY_NAME_BASE( "QGIS-Master-Password" );
79const QLatin1String QgsAuthManager::AUTH_PASSWORD_HELPER_FOLDER_NAME( "QGIS" );
80
81const QgsSettingsEntryBool *QgsAuthManager::settingsGenerateRandomPasswordForPasswordHelper = new QgsSettingsEntryBool( u"generate-random-password-for-keychain"_s, QgsSettingsTree::sTreeAuthentication, true, u"Whether a random password should be automatically generated for the authentication database and stored in the system keychain."_s );
82const QgsSettingsEntryBool *QgsAuthManager::settingsUsingGeneratedRandomPassword = new QgsSettingsEntryBool( u"using-generated-random-password"_s, QgsSettingsTree::sTreeAuthentication, false, u"True if the user is using an autogenerated random password stored in the system keychain."_s );
83
85#if defined(Q_OS_MAC)
87#elif defined(Q_OS_WIN)
88const QString QgsAuthManager::AUTH_PASSWORD_HELPER_DISPLAY_NAME( "Password Manager" );
89#elif defined(Q_OS_LINUX)
90const QString QgsAuthManager::AUTH_PASSWORD_HELPER_DISPLAY_NAME( u"Wallet/KeyRing"_s );
91#else
92const QString QgsAuthManager::AUTH_PASSWORD_HELPER_DISPLAY_NAME( "Password Manager" );
93#endif
95
97{
98#ifdef HAVE_AUTH
99 static QMutex sMutex;
100 QMutexLocker locker( &sMutex );
101 if ( !sInstance )
102 {
103 sInstance = new QgsAuthManager( );
104 }
105 return sInstance;
106#else
107 return new QgsAuthManager();
108#endif
109}
110
111
113{
114#ifdef HAVE_AUTH
115 mMutex = std::make_unique<QRecursiveMutex>();
116 mMasterPasswordMutex = std::make_unique<QRecursiveMutex>();
117 connect( this, &QgsAuthManager::messageLog,
118 this, &QgsAuthManager::writeToConsole );
119#endif
120}
121
123{
124#ifdef HAVE_AUTH
126
127 QSqlDatabase authdb;
128
129 if ( isDisabled() )
130 return authdb;
131
132 // while everything we use from QSqlDatabase here is thread safe, we need to ensure
133 // that the connection cleanup on thread finalization happens in a predictable order
134 QMutexLocker locker( mMutex.get() );
135
136 // Get the first enabled DB storage from the registry
138 {
139 return storage->authDatabaseConnection();
140 }
141
142 return authdb;
143#else
144 return QSqlDatabase();
145#endif
146}
147
149{
150#ifdef HAVE_AUTH
151 if ( ! isDisabled() )
152 {
154
155 // Returns the first enabled and ready "DB" storage
157 const QList<QgsAuthConfigurationStorage *> storages { storageRegistry->readyStorages() };
158 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
159 {
160 if ( auto dbStorage = qobject_cast<QgsAuthConfigurationStorageDb *>( storage ) )
161 {
162 if ( dbStorage->capabilities() & Qgis::AuthConfigurationStorageCapability::ReadConfiguration )
163 {
164 return dbStorage->quotedQualifiedIdentifier( dbStorage->methodConfigTableName() );
165 }
166 }
167 }
168 }
169
170 return QString();
171#else
172 return QString();
173#endif
174}
175
177{
178#ifdef HAVE_AUTH
179 // Loop through all registered SQL drivers and return false if
180 // the URI starts with one of them except the SQLite based drivers
181 const auto drivers { QSqlDatabase::drivers() };
182 for ( const QString &driver : std::as_const( drivers ) )
183 {
184 if ( driver != ( u"QSQLITE"_s ) && driver != ( u"QSPATIALITE"_s ) && uri.startsWith( driver ) )
185 {
186 return false;
187 }
188 }
189 return true;
190#else
191 Q_UNUSED( uri )
192 return false;
193#endif
194}
195
197{
198#ifdef HAVE_AUTH
199 return mAuthDatabaseConnectionUri;
200#else
201 return QString();
202#endif
203}
204
206{
207#ifdef HAVE_AUTH
208 QRegularExpression re( u"password=(.*)"_s );
209 QString uri = mAuthDatabaseConnectionUri;
210 return uri.replace( re, u"password=*****"_s );
211#else
212 return QString();
213#endif
214}
215
216
217bool QgsAuthManager::init( const QString &pluginPath, const QString &authDatabasePath )
218{
219#ifdef HAVE_AUTH
220 mAuthDatabaseConnectionUri = authDatabasePath.startsWith( "QSQLITE://"_L1 ) ? authDatabasePath : u"QSQLITE://"_s + authDatabasePath;
221 return initPrivate( pluginPath );
222#else
223 Q_UNUSED( pluginPath )
224 Q_UNUSED( authDatabasePath )
225 return false;
226#endif
227}
228
230{
231#ifdef HAVE_AUTH
232 static QRecursiveMutex sInitializationMutex;
233 static bool sInitialized = false;
234
235 sInitializationMutex.lock();
236 if ( sInitialized )
237 {
238 sInitializationMutex.unlock();
239 return mLazyInitResult;
240 }
241
242 mLazyInitResult = const_cast< QgsAuthManager * >( this )->initPrivate( mPluginPath );
243 sInitialized = true;
244 sInitializationMutex.unlock();
245
246 return mLazyInitResult;
247#else
248 return false;
249#endif
250}
251
252static char *sPassFileEnv = nullptr;
253
254bool QgsAuthManager::initPrivate( const QString &pluginPath )
255{
256#ifdef HAVE_AUTH
257 if ( mAuthInit )
258 return true;
259
260 mAuthInit = true;
261 QgsScopedRuntimeProfile profile( tr( "Initializing authentication manager" ) );
262
263 QgsDebugMsgLevel( u"Initializing QCA..."_s, 2 );
264 mQcaInitializer = std::make_unique<QCA::Initializer>( QCA::Practical, 256 );
265
266 QgsDebugMsgLevel( u"QCA initialized."_s, 2 );
267 QCA::scanForPlugins();
268
269 QgsDebugMsgLevel( u"QCA Plugin Diagnostics Context: %1"_s.arg( QCA::pluginDiagnosticText() ), 2 );
270 QStringList capabilities;
271
272 capabilities = QCA::supportedFeatures();
273 QgsDebugMsgLevel( u"QCA supports: %1"_s.arg( capabilities.join( "," ) ), 2 );
274
275 // do run-time check for qca-ossl plugin
276 if ( !QCA::isSupported( "cert", u"qca-ossl"_s ) )
277 {
278 mAuthDisabled = true;
279 mAuthDisabledMessage = tr( "QCA's OpenSSL plugin (qca-ossl) is missing" );
280 return isDisabled();
281 }
282
283 QgsDebugMsgLevel( u"Prioritizing qca-ossl over all other QCA providers..."_s, 2 );
284 const QCA::ProviderList provds = QCA::providers();
285 QStringList prlist;
286 for ( QCA::Provider *p : provds )
287 {
288 QString pn = p->name();
289 int pr = 0;
290 if ( pn != "qca-ossl"_L1 )
291 {
292 pr = QCA::providerPriority( pn ) + 1;
293 }
294 QCA::setProviderPriority( pn, pr );
295 prlist << u"%1:%2"_s.arg( pn ).arg( QCA::providerPriority( pn ) );
296 }
297 QgsDebugMsgLevel( u"QCA provider priorities: %1"_s.arg( prlist.join( ", " ) ), 2 );
298
299 QgsDebugMsgLevel( u"Populating auth method registry"_s, 3 );
300 QgsAuthMethodRegistry *authreg = QgsAuthMethodRegistry::instance( pluginPath );
301
302 QStringList methods = authreg->authMethodList();
303
304 QgsDebugMsgLevel( u"Authentication methods found: %1"_s.arg( methods.join( ", " ) ), 2 );
305
306 if ( methods.isEmpty() )
307 {
308 mAuthDisabled = true;
309 mAuthDisabledMessage = tr( "No authentication method plugins found" );
310 return isDisabled();
311 }
312
314 {
315 mAuthDisabled = true;
316 mAuthDisabledMessage = tr( "No authentication method plugins could be loaded" );
317 return isDisabled();
318 }
319
320 QgsDebugMsgLevel( u"Auth database URI: %1"_s.arg( mAuthDatabaseConnectionUri ), 2 );
321
322 // Add the default configuration storage
323 const QString sqliteDbPath { sqliteDatabasePath() };
324 if ( ! sqliteDbPath.isEmpty() )
325 {
326 authConfigurationStorageRegistry()->addStorage( new QgsAuthConfigurationStorageSqlite( sqliteDbPath ) );
327 }
328 else if ( ! mAuthDatabaseConnectionUri.isEmpty() )
329 {
330 // For safety reasons we don't allow writing on potentially shared storages by default, plugins may override
331 // this behavior by registering their own storage subclass or by explicitly setting read-only to false.
332 QgsAuthConfigurationStorageDb *storage = new QgsAuthConfigurationStorageDb( mAuthDatabaseConnectionUri );
333 if ( !QgsAuthManager::isFilesystemBasedDatabase( mAuthDatabaseConnectionUri ) )
334 {
335 storage->setReadOnly( true );
336 }
338 }
339
340 // Loop through all registered storages and call initialize
341 const QList<QgsAuthConfigurationStorage *> storages { authConfigurationStorageRegistry()->storages() };
342 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
343 {
344 if ( ! storage->isEnabled() )
345 {
346 QgsDebugMsgLevel( u"Storage %1 is disabled"_s.arg( storage->name() ), 2 );
347 continue;
348 }
349 if ( !storage->initialize() )
350 {
351 const QString err = tr( "Failed to initialize storage %1: %2" ).arg( storage->name(), storage->lastError() );
352 QgsDebugError( err );
354 }
355 else
356 {
357 QgsDebugMsgLevel( u"Storage %1 initialized"_s.arg( storage->name() ), 2 );
358 }
359 connect( storage, &QgsAuthConfigurationStorage::methodConfigChanged, this, [this] { updateConfigAuthMethods(); } );
361 }
362
364
365#ifndef QT_NO_SSL
367#endif
368 // set the master password from first line of file defined by QGIS_AUTH_PASSWORD_FILE env variable
369 if ( sPassFileEnv && masterPasswordHashInDatabase() )
370 {
371 QString passpath( sPassFileEnv );
372 free( sPassFileEnv );
373 sPassFileEnv = nullptr;
374
375 QString masterpass;
376 QFile passfile( passpath );
377 if ( passfile.exists() && passfile.open( QIODevice::ReadOnly | QIODevice::Text ) )
378 {
379 QTextStream passin( &passfile );
380 while ( !passin.atEnd() )
381 {
382 masterpass = passin.readLine();
383 break;
384 }
385 passfile.close();
386 }
387 if ( !masterpass.isEmpty() )
388 {
389 if ( setMasterPassword( masterpass, true ) )
390 {
391 QgsDebugMsgLevel( u"Authentication master password set from QGIS_AUTH_PASSWORD_FILE"_s, 2 );
392 }
393 else
394 {
395 QgsDebugError( "QGIS_AUTH_PASSWORD_FILE set, but FAILED to set password using: " + passpath );
396 return false;
397 }
398 }
399 else
400 {
401 QgsDebugError( "QGIS_AUTH_PASSWORD_FILE set, but FAILED to read password from: " + passpath );
402 return false;
403 }
404 }
405
406#ifndef QT_NO_SSL
408#endif
409
410 return true;
411#else
412 Q_UNUSED( pluginPath )
413 return false;
414#endif
415}
416
417void QgsAuthManager::setup( const QString &pluginPath, const QString &authDatabasePath )
418{
419#ifdef HAVE_AUTH
420 mPluginPath = pluginPath;
421 mAuthDatabaseConnectionUri = authDatabasePath;
422
423 const char *p = getenv( "QGIS_AUTH_PASSWORD_FILE" );
424 if ( p )
425 {
426 sPassFileEnv = qstrdup( p );
427
428 // clear the env variable, so it can not be accessed from plugins, etc.
429 // (note: stored QgsApplication::systemEnvVars() skips this env variable as well)
430#ifdef Q_OS_WIN
431 putenv( "QGIS_AUTH_PASSWORD_FILE" );
432#else
433 unsetenv( "QGIS_AUTH_PASSWORD_FILE" );
434#endif
435 }
436#else
437 Q_UNUSED( pluginPath )
438 Q_UNUSED( authDatabasePath )
439#endif
440}
441
442QString QgsAuthManager::generatePassword()
443{
444#ifdef HAVE_AUTH
445 QRandomGenerator generator = QRandomGenerator::securelySeeded();
446 QString pw;
447 pw.resize( 32 );
448 static const QString sPwChars = u"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-{}[]"_s;
449 for ( int i = 0; i < pw.size(); ++i )
450 {
451 pw[i] = sPwChars.at( generator.bounded( 0, sPwChars.length() ) );
452 }
453 return pw;
454#else
455 return QString();
456#endif
457}
458
460{
461#ifdef HAVE_AUTH
463
464 if ( mAuthDisabled )
465 {
466 QgsDebugError( u"Authentication system DISABLED: QCA's qca-ossl (OpenSSL) plugin is missing"_s );
467 }
468 return mAuthDisabled;
469#else
470 return false;
471#endif
472}
473
475{
476#ifdef HAVE_AUTH
478
479 return tr( "Authentication system is DISABLED:\n%1" ).arg( mAuthDisabledMessage );
480#else
481 return QString();
482#endif
483}
484
486{
487#ifdef HAVE_AUTH
488 QMutexLocker locker( mMasterPasswordMutex.get() );
489 if ( isDisabled() )
490 return false;
491
492 if ( mScheduledDbErase )
493 return false;
494
495 if ( !passwordHelperEnabled() )
496 return false;
497
498 if ( !mMasterPass.isEmpty() )
499 {
500 QgsDebugError( u"Master password is already set!"_s );
501 return false;
502 }
503
504 const QString newPassword = generatePassword();
505 if ( passwordHelperWrite( newPassword ) )
506 {
507 mMasterPass = newPassword;
508 }
509 else
510 {
511 emit passwordHelperMessageLog( tr( "Master password could not be written to the %1" ).arg( passwordHelperDisplayName() ), authManTag(), Qgis::MessageLevel::Warning );
512 return false;
513 }
514
515 if ( !verifyMasterPassword() )
516 {
517 emit passwordHelperMessageLog( tr( "Master password was written to the %1 but could not be verified" ).arg( passwordHelperDisplayName() ), authManTag(), Qgis::MessageLevel::Warning );
518 return false;
519 }
520
521 QgsDebugMsgLevel( u"Master password is set and verified"_s, 2 );
522 settingsUsingGeneratedRandomPassword->setValue( true );
523 return true;
524#else
525 return false;
526#endif
527}
528
529
531{
532#ifdef HAVE_AUTH
533 if ( !QgsAuthManager::isFilesystemBasedDatabase( mAuthDatabaseConnectionUri ) )
534 {
535 return QString();
536 }
537
538 // Remove the driver:// prefix if present
539 QString path = mAuthDatabaseConnectionUri;
540 if ( path.startsWith( u"QSQLITE://"_s, Qt::CaseSensitivity::CaseInsensitive ) )
541 {
542 path = path.mid( 10 );
543 }
544 else if ( path.startsWith( u"QSPATIALITE://"_s, Qt::CaseSensitivity::CaseInsensitive ) )
545 {
546 path = path.mid( 14 );
547 }
548
549 return QDir::cleanPath( path );
550#else
551 return QString();
552#endif
553}
554
556{
557#ifdef HAVE_AUTH
558 return sqliteDatabasePath();
559#else
560 return QString();
561#endif
562}
563
565{
566#ifdef HAVE_AUTH
568
569 QMutexLocker locker( mMasterPasswordMutex.get() );
570 if ( isDisabled() )
571 return false;
572
573 if ( mScheduledDbErase )
574 return false;
575
576 if ( mMasterPass.isEmpty() )
577 {
578 QgsDebugMsgLevel( u"Master password is not yet set by user"_s, 2 );
579 if ( !masterPasswordInput() )
580 {
581 QgsDebugMsgLevel( u"Master password input canceled by user"_s, 2 );
582 return false;
583 }
584 }
585 else
586 {
587 QgsDebugMsgLevel( u"Master password is set"_s, 2 );
588 if ( !verify )
589 return true;
590 }
591
592 if ( !verifyMasterPassword() )
593 return false;
594
595 QgsDebugMsgLevel( u"Master password is set and verified"_s, 2 );
596 return true;
597#else
598 Q_UNUSED( verify )
599 return false;
600#endif
601}
602
603bool QgsAuthManager::setMasterPassword( const QString &pass, bool verify )
604{
605#ifdef HAVE_AUTH
607
608 QMutexLocker locker( mMutex.get() );
609 if ( isDisabled() )
610 return false;
611
612 if ( mScheduledDbErase )
613 return false;
614
615 // since this is generally for automation, we don't care if passed-in is same as existing
616 QString prevpass = QString( mMasterPass );
617 mMasterPass = pass;
618 if ( verify && !verifyMasterPassword() )
619 {
620 mMasterPass = prevpass;
621 const char *err = QT_TR_NOOP( "Master password set: FAILED to verify, reset to previous" );
622 QgsDebugError( err );
624 return false;
625 }
626
627 QgsDebugMsgLevel( u"Master password set: SUCCESS%1"_s.arg( verify ? " and verified" : "" ), 2 );
628 return true;
629#else
630 Q_UNUSED( pass )
631 Q_UNUSED( verify )
632 return false;
633#endif
634}
635
636bool QgsAuthManager::verifyMasterPassword( const QString &compare )
637{
638#ifdef HAVE_AUTH
640
641 if ( isDisabled() )
642 return false;
643
644 int rows = 0;
645 if ( !masterPasswordRowsInDb( rows ) )
646 {
647 const char *err = QT_TR_NOOP( "Master password: FAILED to access database" );
648 QgsDebugError( err );
650
652 return false;
653 }
654
655 QgsDebugMsgLevel( u"Master password: %1 rows in database"_s.arg( rows ), 2 );
656
657 if ( rows > 1 )
658 {
659 const char *err = QT_TR_NOOP( "Master password: FAILED to find just one master password record in database" );
660 QgsDebugError( err );
662
664 return false;
665 }
666 else if ( rows == 1 )
667 {
668 if ( !masterPasswordCheckAgainstDb( compare ) )
669 {
670 if ( compare.isNull() ) // don't complain when comparing, since it could be an incomplete comparison string
671 {
672 const char *err = QT_TR_NOOP( "Master password: FAILED to verify against hash in database" );
673 QgsDebugError( err );
675
677
678 emit masterPasswordVerified( false );
679 }
680 ++mPassTries;
681 if ( mPassTries >= 5 )
682 {
683 mAuthDisabled = true;
684 const char *err = QT_TR_NOOP( "Master password: failed 5 times authentication system DISABLED" );
685 QgsDebugError( err );
687 }
688 return false;
689 }
690 else
691 {
692 QgsDebugMsgLevel( u"Master password: verified against hash in database"_s, 2 );
693 if ( compare.isNull() )
694 emit masterPasswordVerified( true );
695 }
696 }
697 else if ( compare.isNull() ) // compares should never be stored
698 {
699 if ( !masterPasswordStoreInDb() )
700 {
701 const char *err = QT_TR_NOOP( "Master password: hash FAILED to be stored in database" );
702 QgsDebugError( err );
704
706 return false;
707 }
708 else
709 {
710 QgsDebugMsgLevel( u"Master password: hash stored in database"_s, 2 );
711 }
712 // double-check storing
713 if ( !masterPasswordCheckAgainstDb() )
714 {
715 const char *err = QT_TR_NOOP( "Master password: FAILED to verify against hash in database" );
716 QgsDebugError( err );
718
720 emit masterPasswordVerified( false );
721 return false;
722 }
723 else
724 {
725 QgsDebugMsgLevel( u"Master password: verified against hash in database"_s, 2 );
726 emit masterPasswordVerified( true );
727 }
728 }
729
730 return true;
731#else
732 Q_UNUSED( compare )
733 return false;
734#endif
735}
736
738{
739#ifdef HAVE_AUTH
741
742 return !mMasterPass.isEmpty();
743#else
744 return false;
745#endif
746}
747
748bool QgsAuthManager::masterPasswordSame( const QString &pass ) const
749{
750#ifdef HAVE_AUTH
752
753 return mMasterPass == pass;
754#else
755 Q_UNUSED( pass )
756 return false;
757#endif
758}
759
760bool QgsAuthManager::resetMasterPassword( const QString &newpass, const QString &oldpass,
761 bool keepbackup, QString *backuppath )
762{
763#ifdef HAVE_AUTH
765
766 if ( isDisabled() )
767 return false;
768
769 // verify caller knows the current master password
770 // this means that the user will have had to already set the master password as well
771 if ( !masterPasswordSame( oldpass ) )
772 return false;
773
774 QString dbbackup;
775 if ( !backupAuthenticationDatabase( &dbbackup ) )
776 return false;
777
778 QgsDebugMsgLevel( u"Master password reset: backed up current database"_s, 2 );
779
780 // store current password and civ
781 QString prevpass = QString( mMasterPass );
782 QString prevciv = QString( masterPasswordCiv() );
783
784 // on ANY FAILURE from this point, reinstate previous password and database
785 bool ok = true;
786
787 // clear password hash table (also clears mMasterPass)
788 if ( ok && !masterPasswordClearDb() )
789 {
790 ok = false;
791 const char *err = QT_TR_NOOP( "Master password reset FAILED: could not clear current password from database" );
792 QgsDebugError( err );
794 }
795 if ( ok )
796 {
797 QgsDebugMsgLevel( u"Master password reset: cleared current password from database"_s, 2 );
798 }
799
800 // mMasterPass empty, set new password (don't verify, since not stored yet)
801 setMasterPassword( newpass, false );
802
803 // store new password hash
804 if ( ok && !masterPasswordStoreInDb() )
805 {
806 ok = false;
807 const char *err = QT_TR_NOOP( "Master password reset FAILED: could not store new password in database" );
808 QgsDebugError( err );
810 }
811 if ( ok )
812 {
813 QgsDebugMsgLevel( u"Master password reset: stored new password in database"_s, 2 );
814 }
815
816 // verify it stored password properly
817 if ( ok && !verifyMasterPassword() )
818 {
819 ok = false;
820 const char *err = QT_TR_NOOP( "Master password reset FAILED: could not verify new password in database" );
821 QgsDebugError( err );
823 }
824
825 // re-encrypt everything with new password
826 if ( ok && !reencryptAllAuthenticationConfigs( prevpass, prevciv ) )
827 {
828 ok = false;
829 const char *err = QT_TR_NOOP( "Master password reset FAILED: could not re-encrypt configs in database" );
830 QgsDebugError( err );
832 }
833 if ( ok )
834 {
835 QgsDebugMsgLevel( u"Master password reset: re-encrypted configs in database"_s, 2 );
836 }
837
838 // verify it all worked
839 if ( ok && !verifyPasswordCanDecryptConfigs() )
840 {
841 ok = false;
842 const char *err = QT_TR_NOOP( "Master password reset FAILED: could not verify password can decrypt re-encrypted configs" );
843 QgsDebugError( err );
845 }
846
847 if ( ok && !reencryptAllAuthenticationSettings( prevpass, prevciv ) )
848 {
849 ok = false;
850 const char *err = QT_TR_NOOP( "Master password reset FAILED: could not re-encrypt settings in database" );
851 QgsDebugError( err );
853 }
854
855 if ( ok && !reencryptAllAuthenticationIdentities( prevpass, prevciv ) )
856 {
857 ok = false;
858 const char *err = QT_TR_NOOP( "Master password reset FAILED: could not re-encrypt identities in database" );
859 QgsDebugError( err );
861 }
862
863 if ( qgetenv( "QGIS_CONTINUOUS_INTEGRATION_RUN" ) != u"true"_s && passwordHelperEnabled() && !passwordHelperSync() )
864 {
865 ok = false;
866 const QString err = tr( "Master password reset FAILED: could not sync password helper: %1" ).arg( passwordHelperErrorMessage() );
867 QgsDebugError( err );
869 }
870
871 // something went wrong, reinstate previous password and database
872 if ( !ok )
873 {
874 // backup database of failed attempt, for inspection
875 QString errdbbackup( dbbackup );
876 errdbbackup.replace( ".db"_L1, "_ERROR.db"_L1 );
877 QFile::rename( sqliteDatabasePath(), errdbbackup );
878 QgsDebugError( u"Master password reset FAILED: backed up failed db at %1"_s.arg( errdbbackup ) );
879 // reinstate previous database and password
880 QFile::rename( dbbackup, sqliteDatabasePath() );
881 mMasterPass = prevpass;
882 QgsDebugError( u"Master password reset FAILED: reinstated previous password and database"_s );
883
884 // assign error db backup
885 if ( backuppath )
886 *backuppath = errdbbackup;
887
888 return false;
889 }
890
891 if ( !keepbackup && !QFile::remove( dbbackup ) )
892 {
893 const char *err = QT_TR_NOOP( "Master password reset: could not remove old database backup" );
894 QgsDebugError( err );
896 // a non-blocking error, continue
897 }
898
899 if ( keepbackup )
900 {
901 QgsDebugMsgLevel( u"Master password reset: backed up previous db at %1"_s.arg( dbbackup ), 2 );
902 if ( backuppath )
903 *backuppath = dbbackup;
904 }
905
906 settingsUsingGeneratedRandomPassword->setValue( false );
907
908 QgsDebugMsgLevel( u"Master password reset: SUCCESS"_s, 2 );
909 emit authDatabaseChanged();
910 return true;
911#else
912 Q_UNUSED( newpass )
913 Q_UNUSED( oldpass )
914 Q_UNUSED( keepbackup )
915 Q_UNUSED( backuppath )
916 return false;
917#endif
918}
919
920bool QgsAuthManager::resetMasterPasswordUsingStoredPasswordHelper( const QString &newPassword, bool keepBackup, QString *backupPath )
921{
922#ifdef HAVE_AUTH
924 {
925 emit passwordHelperMessageLog( tr( "Master password stored in your %1 is not valid" ).arg( passwordHelperDisplayName() ), authManTag(), Qgis::MessageLevel::Warning );
926 return false;
927 }
928
929 bool readOk = false;
930 const QString existingPassword = passwordHelperRead( readOk );
931 if ( !readOk )
932 {
933 emit passwordHelperMessageLog( tr( "Master password could not be read from the %1" ).arg( passwordHelperDisplayName() ), authManTag(), Qgis::MessageLevel::Warning );
934 return false;
935 }
936
937 return resetMasterPassword( newPassword, existingPassword, keepBackup, backupPath );
938#else
939 Q_UNUSED( newPassword )
940 Q_UNUSED( keepBackup )
941 Q_UNUSED( backupPath )
942 return false;
943#endif
944}
945
947{
948#ifdef HAVE_AUTH
950
951 mScheduledDbErase = scheduleErase;
952 // any call (start or stop) should reset these
953 mScheduledDbEraseRequestEmitted = false;
954 mScheduledDbEraseRequestCount = 0;
955
956 if ( scheduleErase )
957 {
958 if ( !mScheduledDbEraseTimer )
959 {
960 mScheduledDbEraseTimer = std::make_unique<QTimer>( this );
961 connect( mScheduledDbEraseTimer.get(), &QTimer::timeout, this, &QgsAuthManager::tryToStartDbErase );
962 mScheduledDbEraseTimer->start( mScheduledDbEraseRequestWait * 1000 );
963 }
964 else if ( !mScheduledDbEraseTimer->isActive() )
965 {
966 mScheduledDbEraseTimer->start();
967 }
968 }
969 else
970 {
971 if ( mScheduledDbEraseTimer && mScheduledDbEraseTimer->isActive() )
972 mScheduledDbEraseTimer->stop();
973 }
974#else
975 Q_UNUSED( scheduleErase )
976#endif
977}
978
980{
981#ifdef HAVE_AUTH
982 if ( isDisabled() )
983 return false;
984
985 qDeleteAll( mAuthMethods );
986 mAuthMethods.clear();
987 const QStringList methods = QgsAuthMethodRegistry::instance()->authMethodList();
988 for ( const auto &authMethodKey : methods )
989 {
990 mAuthMethods.insert( authMethodKey, QgsAuthMethodRegistry::instance()->createAuthMethod( authMethodKey ) );
991 }
992
993 return !mAuthMethods.isEmpty();
994#else
995 return false;
996#endif
997}
998
1000{
1001#ifdef HAVE_AUTH
1003
1004 QStringList configids = configIds();
1005 QString id;
1006 int len = 7;
1007
1008 // Suppress warning: Potential leak of memory in qtimer.h [clang-analyzer-cplusplus.NewDeleteLeaks]
1009#ifndef __clang_analyzer__
1010 // sleep just a bit to make sure the current time has changed
1011 QEventLoop loop;
1012 QTimer::singleShot( 3, &loop, &QEventLoop::quit );
1013 loop.exec();
1014#endif
1015
1016 while ( true )
1017 {
1018 id.clear();
1019 for ( int i = 0; i < len; i++ )
1020 {
1021 switch ( QRandomGenerator::system()->generate() % 2 )
1022 {
1023 case 0:
1024 id += static_cast<char>( '0' + QRandomGenerator::system()->generate() % 10 );
1025 break;
1026 case 1:
1027 id += static_cast<char>( 'a' + QRandomGenerator::system()->generate() % 26 );
1028 break;
1029 }
1030 }
1031 if ( !configids.contains( id ) )
1032 {
1033 break;
1034 }
1035 }
1036 QgsDebugMsgLevel( u"Generated unique ID: %1"_s.arg( id ), 2 );
1037 return id;
1038#else
1039 return QString();
1040#endif
1041}
1042
1043bool QgsAuthManager::configIdUnique( const QString &id ) const
1044{
1045#ifdef HAVE_AUTH
1047
1048 if ( isDisabled() )
1049 return false;
1050
1051 if ( id.isEmpty() )
1052 {
1053 const char *err = QT_TR_NOOP( "Config ID is empty" );
1054 QgsDebugError( err );
1056 return false;
1057 }
1058 QStringList configids = configIds();
1059 return !configids.contains( id );
1060#else
1061 Q_UNUSED( id )
1062 return false;
1063#endif
1064}
1065
1066bool QgsAuthManager::hasConfigId( const QString &txt )
1067{
1068#ifdef HAVE_AUTH
1069 const thread_local QRegularExpression authCfgRegExp( AUTH_CFG_REGEX );
1070 return txt.indexOf( authCfgRegExp ) != -1;
1071#else
1072 Q_UNUSED( txt )
1073 return false;
1074#endif
1075}
1076
1078{
1079#ifdef HAVE_AUTH
1081
1082 QMutexLocker locker( mMutex.get() );
1083 QStringList providerAuthMethodsKeys;
1084 if ( !dataprovider.isEmpty() )
1085 {
1086 providerAuthMethodsKeys = authMethodsKeys( dataprovider.toLower() );
1087 }
1088
1089 QgsAuthMethodConfigsMap baseConfigs;
1090
1091 if ( isDisabled() )
1092 return baseConfigs;
1093
1094 // Loop through all storages with capability ReadConfiguration and get the auth methods
1096 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
1097 {
1098 QgsAuthMethodConfigsMap configs = storage->authMethodConfigs();
1099 for ( const QgsAuthMethodConfig &config : std::as_const( configs ) )
1100 {
1101 if ( providerAuthMethodsKeys.isEmpty() || providerAuthMethodsKeys.contains( config.method() ) )
1102 {
1103 // Check if the config with that id is already in the list and warn if it is
1104 if ( baseConfigs.contains( config.id() ) )
1105 {
1106 // This may not be an error, since the same config may be stored in multiple storages.
1107 emit messageLog( tr( "A config with same id %1 was already added, skipping from %2" ).arg( config.id(), storage->name() ), authManTag(), Qgis::MessageLevel::Warning );
1108 }
1109 else
1110 {
1111 baseConfigs.insert( config.id(), config );
1112 }
1113 }
1114 }
1115 }
1116
1117 if ( storages.empty() )
1118 {
1119 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
1120 QgsDebugError( u"No credentials storages found"_s );
1121 }
1122
1123 return baseConfigs;
1124
1125#else
1126 Q_UNUSED( dataprovider )
1127 return QgsAuthMethodConfigsMap();
1128#endif
1129}
1130
1132{
1133#ifdef HAVE_AUTH
1135
1136 // Loop through all registered storages and get the auth methods
1138 QStringList configIds;
1139 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
1140 {
1141 const QgsAuthMethodConfigsMap configs = storage->authMethodConfigs();
1142 for ( const QgsAuthMethodConfig &config : std::as_const( configs ) )
1143 {
1144 if ( ! configIds.contains( config.id() ) )
1145 {
1146 mConfigAuthMethods.insert( config.id(), config.method() );
1147 QgsDebugMsgLevel( u"Stored auth config/methods:\n%1 %2"_s.arg( config.id(), config.method() ), 2 );
1148 }
1149 else
1150 {
1151 // This may not be an error, since the same config may be stored in multiple storages.
1152 // A warning is issued when creating the list initially from availableAuthMethodConfigs()
1153 QgsDebugMsgLevel( u"A config with same id %1 was already added, skipping from %2"_s.arg( config.id(), storage->name() ), 2 );
1154 }
1155 }
1156 }
1157#endif
1158}
1159
1161{
1162#ifdef HAVE_AUTH
1164
1165 if ( isDisabled() )
1166 return nullptr;
1167
1168 if ( !mConfigAuthMethods.contains( authcfg ) )
1169 {
1170 QgsDebugError( u"No config auth method found in database for authcfg: %1"_s.arg( authcfg ) );
1171 return nullptr;
1172 }
1173
1174 QString authMethodKey = mConfigAuthMethods.value( authcfg );
1175
1176 return authMethod( authMethodKey );
1177#else
1178 Q_UNUSED( authcfg )
1179 return nullptr;
1180#endif
1181}
1182
1183QString QgsAuthManager::configAuthMethodKey( const QString &authcfg ) const
1184{
1185#ifdef HAVE_AUTH
1187
1188 if ( isDisabled() )
1189 return QString();
1190
1191 return mConfigAuthMethods.value( authcfg, QString() );
1192#else
1193 Q_UNUSED( authcfg )
1194 return QString();
1195#endif
1196}
1197
1198
1199QStringList QgsAuthManager::authMethodsKeys( const QString &dataprovider )
1200{
1201#ifdef HAVE_AUTH
1203
1204 return authMethodsMap( dataprovider.toLower() ).keys();
1205#else
1206 Q_UNUSED( dataprovider )
1207 return QStringList();
1208#endif
1209}
1210
1211QgsAuthMethod *QgsAuthManager::authMethod( const QString &authMethodKey )
1212{
1213#ifdef HAVE_AUTH
1215
1216 if ( !mAuthMethods.contains( authMethodKey ) )
1217 {
1218 QgsDebugError( u"No auth method registered for auth method key: %1"_s.arg( authMethodKey ) );
1219 return nullptr;
1220 }
1221
1222 return mAuthMethods.value( authMethodKey );
1223#else
1224 Q_UNUSED( authMethodKey )
1225 return nullptr;
1226#endif
1227}
1228
1229const QgsAuthMethodMetadata *QgsAuthManager::authMethodMetadata( const QString &authMethodKey )
1230{
1231#ifdef HAVE_AUTH
1233
1234 if ( !mAuthMethods.contains( authMethodKey ) )
1235 {
1236 QgsDebugError( u"No auth method registered for auth method key: %1"_s.arg( authMethodKey ) );
1237 return nullptr;
1238 }
1239
1240 return QgsAuthMethodRegistry::instance()->authMethodMetadata( authMethodKey );
1241#else
1242 Q_UNUSED( authMethodKey )
1243 return nullptr;
1244#endif
1245}
1246
1247
1249{
1250#ifdef HAVE_AUTH
1252
1253 if ( dataprovider.isEmpty() )
1254 {
1255 return mAuthMethods;
1256 }
1257
1258 QgsAuthMethodsMap filteredmap;
1259 QgsAuthMethodsMap::const_iterator i = mAuthMethods.constBegin();
1260 while ( i != mAuthMethods.constEnd() )
1261 {
1262 if ( i.value()
1263 && ( i.value()->supportedDataProviders().contains( u"all"_s )
1264 || i.value()->supportedDataProviders().contains( dataprovider ) ) )
1265 {
1266 filteredmap.insert( i.key(), i.value() );
1267 }
1268 ++i;
1269 }
1270 return filteredmap;
1271#else
1272 Q_UNUSED( dataprovider )
1273 return QgsAuthMethodsMap();
1274#endif
1275}
1276
1277#ifdef HAVE_GUI
1278QWidget *QgsAuthManager::authMethodEditWidget( const QString &authMethodKey, QWidget *parent )
1279{
1281
1282 QgsAuthMethod *method = authMethod( authMethodKey );
1283 if ( method )
1284 return method->editWidget( parent );
1285 else
1286 return nullptr;
1287}
1288#endif
1289
1291{
1292#ifdef HAVE_AUTH
1294
1295 if ( isDisabled() )
1297
1298 QgsAuthMethod *authmethod = configAuthMethod( authcfg );
1299 if ( authmethod )
1300 {
1301 return authmethod->supportedExpansions();
1302 }
1304#else
1305 Q_UNUSED( authcfg )
1306
1308#endif
1309}
1310
1312{
1313#ifdef HAVE_AUTH
1315
1316 QMutexLocker locker( mMutex.get() );
1317 if ( !setMasterPassword( true ) )
1318 return false;
1319
1320 // don't need to validate id, since it has not be defined yet
1321 if ( !config.isValid() )
1322 {
1323 const char *err = QT_TR_NOOP( "Store config: FAILED because config is invalid" );
1324 QgsDebugError( err );
1326 return false;
1327 }
1328
1329 QString uid = config.id();
1330 bool passedinID = !uid.isEmpty();
1331 if ( uid.isEmpty() )
1332 {
1333 uid = uniqueConfigId();
1334 }
1335 else if ( configIds().contains( uid ) )
1336 {
1337 if ( !overwrite )
1338 {
1339 const char *err = QT_TR_NOOP( "Store config: FAILED because pre-defined config ID %1 is not unique" );
1340 QgsDebugError( err );
1342 return false;
1343 }
1344 locker.unlock();
1345 if ( ! removeAuthenticationConfig( uid ) )
1346 {
1347 const char *err = QT_TR_NOOP( "Store config: FAILED because pre-defined config ID %1 could not be removed" );
1348 QgsDebugError( err );
1350 return false;
1351 }
1352 locker.relock();
1353 }
1354
1355 QString configstring = config.configString();
1356 if ( configstring.isEmpty() )
1357 {
1358 const char *err = QT_TR_NOOP( "Store config: FAILED because config string is empty" );
1359 QgsDebugError( err );
1361 return false;
1362 }
1363
1364 if ( QgsAuthConfigurationStorage *defaultStorage = firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability::CreateConfiguration ) )
1365 {
1366 if ( defaultStorage->isEncrypted() )
1367 {
1368 configstring = QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), configstring );
1369 }
1370
1371 // Make a copy to not alter the original config
1372 QgsAuthMethodConfig configCopy { config };
1373 configCopy.setId( uid );
1374 if ( !defaultStorage->storeMethodConfig( configCopy, configstring ) )
1375 {
1376 emit messageLog( tr( "Store config: FAILED to store config in default storage: %1" ).arg( defaultStorage->lastError() ), authManTag(), Qgis::MessageLevel::Warning );
1377 return false;
1378 }
1379 }
1380 else
1381 {
1382 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
1383 return false;
1384 }
1385
1386 // passed-in config should now be like as if it was just loaded from db
1387 if ( !passedinID )
1388 config.setId( uid );
1389
1391
1392 QgsDebugMsgLevel( u"Store config SUCCESS for authcfg: %1"_s.arg( uid ), 2 );
1393 return true;
1394#else
1395 Q_UNUSED( config )
1396 Q_UNUSED( overwrite )
1397 return false;
1398#endif
1399}
1400
1402{
1403#ifdef HAVE_AUTH
1405
1406 QMutexLocker locker( mMutex.get() );
1407 if ( !setMasterPassword( true ) )
1408 return false;
1409
1410 // validate id
1411 if ( !config.isValid( true ) )
1412 {
1413 const char *err = QT_TR_NOOP( "Update config: FAILED because config is invalid" );
1414 QgsDebugError( err );
1416 return false;
1417 }
1418
1419 QString configstring = config.configString();
1420 if ( configstring.isEmpty() )
1421 {
1422 const char *err = QT_TR_NOOP( "Update config: FAILED because config is empty" );
1423 QgsDebugError( err );
1425 return false;
1426 }
1427
1428 // Loop through all storages with capability ReadConfiguration and update the first one that has the config
1430
1431 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
1432 {
1433 if ( storage->methodConfigExists( config.id() ) )
1434 {
1436 {
1437 emit messageLog( tr( "Update config: FAILED because storage %1 does not support updating" ).arg( storage->name( ) ), authManTag(), Qgis::MessageLevel::Warning );
1438 return false;
1439 }
1440 if ( storage->isEncrypted() )
1441 {
1442 configstring = QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), configstring );
1443 }
1444 if ( !storage->storeMethodConfig( config, configstring ) )
1445 {
1446 emit messageLog( tr( "Store config: FAILED to store config in the storage: %1" ).arg( storage->lastError() ), authManTag(), Qgis::MessageLevel::Critical );
1447 return false;
1448 }
1449 break;
1450 }
1451 }
1452
1453 if ( storages.empty() )
1454 {
1455 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
1456 return false;
1457 }
1458
1459 // should come before updating auth methods, in case user switched auth methods in config
1460 clearCachedConfig( config.id() );
1461
1463
1464 QgsDebugMsgLevel( u"Update config SUCCESS for authcfg: %1"_s.arg( config.id() ), 2 );
1465
1466 return true;
1467#else
1468 Q_UNUSED( config )
1469 return false;
1470#endif
1471}
1472
1473bool QgsAuthManager::loadAuthenticationConfig( const QString &authcfg, QgsAuthMethodConfig &config, bool full )
1474{
1475#ifdef HAVE_AUTH
1477
1478 if ( isDisabled() )
1479 return false;
1480
1481 if ( full && !setMasterPassword( true ) )
1482 return false;
1483
1484 QMutexLocker locker( mMutex.get() );
1485
1486 // Loop through all storages with capability ReadConfiguration and get the config from the first one that has the config
1488
1489 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
1490 {
1491 if ( storage->methodConfigExists( authcfg ) )
1492 {
1493 QString payload;
1494 config = storage->loadMethodConfig( authcfg, payload, full );
1495
1496 if ( ! config.isValid( true ) || ( full && payload.isEmpty() ) )
1497 {
1498 emit messageLog( tr( "Load config: FAILED to load config %1 from default storage: %2" ).arg( authcfg, storage->lastError() ), authManTag(), Qgis::MessageLevel::Critical );
1499 return false;
1500 }
1501
1502 if ( full )
1503 {
1504 if ( storage->isEncrypted() )
1505 {
1506 payload = QgsAuthCrypto::decrypt( mMasterPass, masterPasswordCiv(), payload );
1507 }
1508 config.loadConfigString( payload );
1509 }
1510
1511 QString authMethodKey = configAuthMethodKey( authcfg );
1512 QgsAuthMethod *authmethod = authMethod( authMethodKey );
1513 if ( authmethod )
1514 {
1515 authmethod->updateMethodConfig( config );
1516 }
1517 else
1518 {
1519 QgsDebugError( u"Update of authcfg %1 FAILED for auth method %2"_s.arg( authcfg, authMethodKey ) );
1520 }
1521
1522 QgsDebugMsgLevel( u"Load %1 config SUCCESS for authcfg: %2"_s.arg( full ? "full" : "base", authcfg ), 2 );
1523 return true;
1524 }
1525 }
1526
1527 if ( storages.empty() )
1528 {
1529 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
1530 }
1531 else
1532 {
1533 emit messageLog( tr( "Load config: FAILED to load config %1 from any storage" ).arg( authcfg ), authManTag(), Qgis::MessageLevel::Critical );
1534 }
1535
1536 return false;
1537#else
1538 Q_UNUSED( authcfg )
1539 Q_UNUSED( config )
1540 Q_UNUSED( full )
1541 return false;
1542#endif
1543}
1544
1546{
1547#ifdef HAVE_AUTH
1549
1550 QMutexLocker locker( mMutex.get() );
1551 if ( isDisabled() )
1552 return false;
1553
1554 if ( authcfg.isEmpty() )
1555 return false;
1556
1557 // Loop through all storages with capability DeleteConfiguration and delete the first one that has the config
1559
1560 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
1561 {
1562 if ( storage->methodConfigExists( authcfg ) )
1563 {
1564 if ( !storage->removeMethodConfig( authcfg ) )
1565 {
1566 emit messageLog( tr( "Remove config: FAILED to remove config from the storage: %1" ).arg( storage->lastError() ), authManTag(), Qgis::MessageLevel::Critical );
1567 return false;
1568 }
1569 else
1570 {
1571 clearCachedConfig( authcfg );
1573 QgsDebugMsgLevel( u"REMOVED config for authcfg: %1"_s.arg( authcfg ), 2 );
1574 return true;
1575 }
1576 break;
1577 }
1578 }
1579
1580 if ( storages.empty() )
1581 {
1582 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
1583 }
1584 else
1585 {
1586 emit messageLog( tr( "Remove config: FAILED to remove config %1 from any storage" ).arg( authcfg ), authManTag(), Qgis::MessageLevel::Critical );
1587 }
1588
1589 return false;
1590
1591#else
1592 Q_UNUSED( authcfg )
1593 return false;
1594#endif
1595}
1596
1597bool QgsAuthManager::exportAuthenticationConfigsToXml( const QString &filename, const QStringList &authcfgs, const QString &password )
1598{
1599#ifdef HAVE_AUTH
1601
1602 if ( filename.isEmpty() )
1603 return false;
1604
1605 QDomDocument document( u"qgis_authentication"_s );
1606 QDomElement root = document.createElement( u"qgis_authentication"_s );
1607 document.appendChild( root );
1608
1609 QString civ;
1610 if ( !password.isEmpty() )
1611 {
1612 QString salt;
1613 QString hash;
1614 QgsAuthCrypto::passwordKeyHash( password, &salt, &hash, &civ );
1615 root.setAttribute( u"salt"_s, salt );
1616 root.setAttribute( u"hash"_s, hash );
1617 root.setAttribute( u"civ"_s, civ );
1618 }
1619
1620 QDomElement configurations = document.createElement( u"configurations"_s );
1621 for ( const QString &authcfg : authcfgs )
1622 {
1623 QgsAuthMethodConfig authMethodConfig;
1624
1625 bool ok = loadAuthenticationConfig( authcfg, authMethodConfig, true );
1626 if ( ok )
1627 {
1628 authMethodConfig.writeXml( configurations, document );
1629 }
1630 }
1631 if ( !password.isEmpty() )
1632 {
1633 QString configurationsString;
1634 QTextStream ts( &configurationsString );
1635 configurations.save( ts, 2 );
1636 root.appendChild( document.createTextNode( QgsAuthCrypto::encrypt( password, civ, configurationsString ) ) );
1637 }
1638 else
1639 {
1640 root.appendChild( configurations );
1641 }
1642
1643 QFile file( filename );
1644 if ( !file.open( QFile::WriteOnly | QIODevice::Truncate ) )
1645 return false;
1646
1647 QTextStream ts( &file );
1648 document.save( ts, 2 );
1649 file.close();
1650 return true;
1651#else
1652 Q_UNUSED( filename )
1653 Q_UNUSED( authcfgs )
1654 Q_UNUSED( password )
1655 return false;
1656#endif
1657}
1658
1659bool QgsAuthManager::importAuthenticationConfigsFromXml( const QString &filename, const QString &password, bool overwrite )
1660{
1661#ifdef HAVE_AUTH
1663
1664 QFile file( filename );
1665 if ( !file.open( QFile::ReadOnly ) )
1666 {
1667 return false;
1668 }
1669
1670 QDomDocument document( u"qgis_authentication"_s );
1671 if ( !document.setContent( &file ) )
1672 {
1673 file.close();
1674 return false;
1675 }
1676 file.close();
1677
1678 QDomElement root = document.documentElement();
1679 if ( root.tagName() != "qgis_authentication"_L1 )
1680 {
1681 return false;
1682 }
1683
1684 QDomElement configurations;
1685 if ( root.hasAttribute( u"salt"_s ) )
1686 {
1687 QString salt = root.attribute( u"salt"_s );
1688 QString hash = root.attribute( u"hash"_s );
1689 QString civ = root.attribute( u"civ"_s );
1690 if ( !QgsAuthCrypto::verifyPasswordKeyHash( password, salt, hash ) )
1691 return false;
1692
1693 document.setContent( QgsAuthCrypto::decrypt( password, civ, root.text() ) );
1694 configurations = document.firstChild().toElement();
1695 }
1696 else
1697 {
1698 configurations = root.firstChildElement( u"configurations"_s );
1699 }
1700
1701 QDomElement configuration = configurations.firstChildElement();
1702 while ( !configuration.isNull() )
1703 {
1704 QgsAuthMethodConfig authMethodConfig;
1705 ( void )authMethodConfig.readXml( configuration );
1706 storeAuthenticationConfig( authMethodConfig, overwrite );
1707
1708 configuration = configuration.nextSiblingElement();
1709 }
1710 return true;
1711#else
1712 Q_UNUSED( filename )
1713 Q_UNUSED( password )
1714 Q_UNUSED( overwrite )
1715 return false;
1716#endif
1717}
1718
1720{
1721#ifdef HAVE_AUTH
1723
1724 QMutexLocker locker( mMutex.get() );
1725 if ( isDisabled() )
1726 return false;
1727
1728 if ( QgsAuthConfigurationStorage *defaultStorage = firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability::DeleteConfiguration ) )
1729 {
1730 if ( defaultStorage->clearMethodConfigs() )
1731 {
1734 QgsDebugMsgLevel( u"REMOVED all configs from the default storage"_s, 2 );
1735 return true;
1736 }
1737 else
1738 {
1739 QgsDebugMsgLevel( u"FAILED to remove all configs from the default storage"_s, 2 );
1740 return false;
1741 }
1742 }
1743 else
1744 {
1745 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
1746 return false;
1747 }
1748#else
1749 return false;
1750#endif
1751}
1752
1753
1755{
1756#ifdef HAVE_AUTH
1758
1759 QMutexLocker locker( mMutex.get() );
1760
1761 if ( sqliteDatabasePath().isEmpty() )
1762 {
1763 const char *err = QT_TR_NOOP( "The authentication storage is not filesystem-based" );
1764 QgsDebugError( err );
1766 return false;
1767 }
1768
1769 if ( !QFile::exists( sqliteDatabasePath() ) )
1770 {
1771 const char *err = QT_TR_NOOP( "No authentication database file found" );
1772 QgsDebugError( err );
1774 return false;
1775 }
1776
1777 // close any connection to current db
1779 QSqlDatabase authConn = authDatabaseConnection();
1781 if ( authConn.isValid() && authConn.isOpen() )
1782 authConn.close();
1783
1784 // duplicate current db file to 'qgis-auth_YYYY-MM-DD-HHMMSS.db' backup
1785 QString datestamp( QDateTime::currentDateTime().toString( u"yyyy-MM-dd-hhmmss"_s ) );
1786 QString dbbackup( sqliteDatabasePath() );
1787 dbbackup.replace( ".db"_L1, u"_%1.db"_s.arg( datestamp ) );
1788
1789 if ( !QFile::copy( sqliteDatabasePath(), dbbackup ) )
1790 {
1791 const char *err = QT_TR_NOOP( "Could not back up authentication database" );
1792 QgsDebugError( err );
1794 return false;
1795 }
1796
1797 if ( backuppath )
1798 *backuppath = dbbackup;
1799
1800 QgsDebugMsgLevel( u"Backed up auth database at %1"_s.arg( dbbackup ), 2 );
1801 return true;
1802#else
1803 Q_UNUSED( backuppath )
1804 return false;
1805#endif
1806}
1807
1808bool QgsAuthManager::eraseAuthenticationDatabase( bool backup, QString *backuppath )
1809{
1810#ifdef HAVE_AUTH
1812
1813 QMutexLocker locker( mMutex.get() );
1814 if ( isDisabled() )
1815 return false;
1816
1817 QString dbbackup;
1818 if ( backup && !backupAuthenticationDatabase( &dbbackup ) )
1819 {
1820 emit messageLog( tr( "Failed to backup authentication database" ), authManTag(), Qgis::MessageLevel::Warning );
1821 return false;
1822 }
1823
1824 if ( backuppath && !dbbackup.isEmpty() )
1825 *backuppath = dbbackup;
1826
1827 if ( QgsAuthConfigurationStorage *defaultStorage = firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability::ClearStorage ) )
1828 {
1829 if ( defaultStorage->erase() )
1830 {
1831 mMasterPass = QString();
1834 QgsDebugMsgLevel( u"ERASED all configs"_s, 2 );
1835 return true;
1836 }
1837 else
1838 {
1839 QgsDebugMsgLevel( u"FAILED to erase all configs"_s, 2 );
1840 return false;
1841 }
1842 }
1843 else
1844 {
1845 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
1846 return false;
1847 }
1848
1849#ifndef QT_NO_SSL
1850 initSslCaches();
1851#endif
1852
1853 emit authDatabaseChanged();
1854
1855 return true;
1856#else
1857 Q_UNUSED( backup )
1858 Q_UNUSED( backuppath )
1859 return false;
1860#endif
1861}
1862
1863bool QgsAuthManager::updateNetworkRequest( QNetworkRequest &request, const QString &authcfg,
1864 const QString &dataprovider )
1865{
1866#ifdef HAVE_AUTH
1868
1869 if ( isDisabled() )
1870 return false;
1871
1872 QgsAuthMethod *authmethod = configAuthMethod( authcfg );
1873 if ( authmethod )
1874 {
1875 if ( !( authmethod->supportedExpansions() & QgsAuthMethod::NetworkRequest ) )
1876 {
1877 QgsDebugError( u"Network request updating not supported by authcfg: %1"_s.arg( authcfg ) );
1878 return true;
1879 }
1880
1881 if ( !authmethod->updateNetworkRequest( request, authcfg, dataprovider.toLower() ) )
1882 {
1883 authmethod->clearCachedConfig( authcfg );
1884 return false;
1885 }
1886 return true;
1887 }
1888 return false;
1889#else
1890 Q_UNUSED( request )
1891 Q_UNUSED( authcfg )
1892 Q_UNUSED( dataprovider )
1893 return false;
1894#endif
1895}
1896
1897bool QgsAuthManager::updateNetworkReply( QNetworkReply *reply, const QString &authcfg,
1898 const QString &dataprovider )
1899{
1900#ifdef HAVE_AUTH
1902
1903 if ( isDisabled() )
1904 return false;
1905
1906 QgsAuthMethod *authmethod = configAuthMethod( authcfg );
1907 if ( authmethod )
1908 {
1909 if ( !( authmethod->supportedExpansions() & QgsAuthMethod::NetworkReply ) )
1910 {
1911 QgsDebugMsgLevel( u"Network reply updating not supported by authcfg: %1"_s.arg( authcfg ), 3 );
1912 return true;
1913 }
1914
1915 if ( !authmethod->updateNetworkReply( reply, authcfg, dataprovider.toLower() ) )
1916 {
1917 authmethod->clearCachedConfig( authcfg );
1918 return false;
1919 }
1920 return true;
1921 }
1922
1923 return false;
1924#else
1925 Q_UNUSED( reply )
1926 Q_UNUSED( authcfg )
1927 Q_UNUSED( dataprovider )
1928 return false;
1929#endif
1930}
1931
1932bool QgsAuthManager::updateDataSourceUriItems( QStringList &connectionItems, const QString &authcfg,
1933 const QString &dataprovider )
1934{
1935#ifdef HAVE_AUTH
1937
1938 if ( isDisabled() )
1939 return false;
1940
1941 QgsAuthMethod *authmethod = configAuthMethod( authcfg );
1942 if ( authmethod )
1943 {
1944 if ( !( authmethod->supportedExpansions() & QgsAuthMethod::DataSourceUri ) )
1945 {
1946 QgsDebugError( u"Data source URI updating not supported by authcfg: %1"_s.arg( authcfg ) );
1947 return true;
1948 }
1949
1950 if ( !authmethod->updateDataSourceUriItems( connectionItems, authcfg, dataprovider.toLower() ) )
1951 {
1952 authmethod->clearCachedConfig( authcfg );
1953 return false;
1954 }
1955 return true;
1956 }
1957
1958 return false;
1959#else
1960 Q_UNUSED( connectionItems )
1961 Q_UNUSED( authcfg )
1962 Q_UNUSED( dataprovider )
1963 return false;
1964#endif
1965}
1966
1967bool QgsAuthManager::updateNetworkProxy( QNetworkProxy &proxy, const QString &authcfg, const QString &dataprovider )
1968{
1969#ifdef HAVE_AUTH
1971
1972 if ( isDisabled() )
1973 return false;
1974
1975 QgsAuthMethod *authmethod = configAuthMethod( authcfg );
1976 if ( authmethod )
1977 {
1978 if ( !( authmethod->supportedExpansions() & QgsAuthMethod::NetworkProxy ) )
1979 {
1980 QgsDebugError( u"Proxy updating not supported by authcfg: %1"_s.arg( authcfg ) );
1981 return true;
1982 }
1983
1984 if ( !authmethod->updateNetworkProxy( proxy, authcfg, dataprovider.toLower() ) )
1985 {
1986 authmethod->clearCachedConfig( authcfg );
1987 return false;
1988 }
1989 QgsDebugMsgLevel( u"Proxy updated successfully from authcfg: %1"_s.arg( authcfg ), 2 );
1990 return true;
1991 }
1992
1993 return false;
1994#else
1995 Q_UNUSED( proxy )
1996 Q_UNUSED( authcfg )
1997 Q_UNUSED( dataprovider )
1998 return false;
1999#endif
2000}
2001
2002bool QgsAuthManager::storeAuthSetting( const QString &key, const QVariant &value, bool encrypt )
2003{
2004#ifdef HAVE_AUTH
2006
2007 QMutexLocker locker( mMutex.get() );
2008 if ( key.isEmpty() )
2009 return false;
2010
2011 QString storeval( value.toString() );
2012 if ( encrypt )
2013 {
2014 if ( !setMasterPassword( true ) )
2015 {
2016 return false;
2017 }
2018 else
2019 {
2020 storeval = QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), value.toString() );
2021 }
2022 }
2023
2024 if ( existsAuthSetting( key ) && ! removeAuthSetting( key ) )
2025 {
2026 emit messageLog( tr( "Store setting: FAILED to remove pre-existing setting %1" ).arg( key ), authManTag(), Qgis::MessageLevel::Warning );
2027 return false;
2028 }
2029
2030 // Set the setting in the first storage that has the capability to store it
2031
2032 if ( QgsAuthConfigurationStorage *defaultStorage = firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability::CreateSetting ) )
2033 {
2034 if ( !defaultStorage->storeAuthSetting( key, storeval ) )
2035 {
2036 emit messageLog( tr( "Store setting: FAILED to store setting in default storage" ), authManTag(), Qgis::MessageLevel::Warning );
2037 return false;
2038 }
2039 return true;
2040 }
2041 else
2042 {
2043 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
2044 return false;
2045 }
2046#else
2047 Q_UNUSED( key )
2048 Q_UNUSED( value )
2049 Q_UNUSED( encrypt )
2050 return false;
2051#endif
2052}
2053
2054QVariant QgsAuthManager::authSetting( const QString &key, const QVariant &defaultValue, bool decrypt )
2055{
2056#ifdef HAVE_AUTH
2058
2059 QMutexLocker locker( mMutex.get() );
2060 if ( key.isEmpty() )
2061 return QVariant();
2062
2063 if ( decrypt && !setMasterPassword( true ) )
2064 return QVariant();
2065
2066 QVariant value = defaultValue;
2067
2068 // Loop through all storages with capability ReadSetting and get the setting from the first one that has the setting
2070
2071 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2072 {
2073 QString storeval = storage->loadAuthSetting( key );
2074 if ( !storeval.isEmpty() )
2075 {
2076 if ( decrypt )
2077 {
2078 storeval = QgsAuthCrypto::decrypt( mMasterPass, masterPasswordCiv(), storeval );
2079 }
2080 value = storeval;
2081 break;
2082 }
2083 }
2084
2085 if ( storages.empty() )
2086 {
2087 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
2088 }
2089
2090 return value;
2091#else
2092 Q_UNUSED( key )
2093 Q_UNUSED( defaultValue )
2094 Q_UNUSED( decrypt )
2095 return QVariant();
2096#endif
2097}
2098
2099bool QgsAuthManager::existsAuthSetting( const QString &key )
2100{
2101#ifdef HAVE_AUTH
2103
2104 QMutexLocker locker( mMutex.get() );
2105 if ( key.isEmpty() )
2106 return false;
2107
2108 // Loop through all storages with capability ReadSetting and get the setting from the first one that has the setting
2110
2111 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2112 {
2113
2114 if ( storage->authSettingExists( key ) )
2115 { return true; }
2116
2117 }
2118
2119 if ( storages.empty() )
2120 {
2121 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
2122 }
2123
2124 return false;
2125#else
2126 Q_UNUSED( key )
2127 return false;
2128#endif
2129}
2130
2131bool QgsAuthManager::removeAuthSetting( const QString &key )
2132{
2133#ifdef HAVE_AUTH
2135
2136 QMutexLocker locker( mMutex.get() );
2137 if ( key.isEmpty() )
2138 return false;
2139
2140 // Loop through all storages with capability ReadSetting and delete from the first one that has the setting, fail if it has no capability
2142
2143 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2144 {
2145 if ( storage->authSettingExists( key ) )
2146 {
2148 {
2149 if ( !storage->removeAuthSetting( key ) )
2150 {
2151 emit messageLog( tr( "Remove setting: FAILED to remove setting from storage: %1" ).arg( storage->lastError() ), authManTag(), Qgis::MessageLevel::Warning );
2152 return false;
2153 }
2154 return true;
2155 }
2156 else
2157 {
2158 emit messageLog( tr( "Remove setting: FAILED to remove setting from storage %1: storage is read only" ).arg( storage->name() ), authManTag(), Qgis::MessageLevel::Warning );
2159 return false;
2160 }
2161 }
2162 }
2163
2164 if ( storages.empty() )
2165 {
2166 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
2167 }
2168 return false;
2169#else
2170 Q_UNUSED( key )
2171 return false;
2172#endif
2173}
2174
2175#ifndef QT_NO_SSL
2176
2178
2180{
2181#ifdef HAVE_AUTH
2182 QgsScopedRuntimeProfile profile( "Initialize SSL cache" );
2183
2184 QMutexLocker locker( mMutex.get() );
2185 bool res = true;
2186 res = res && rebuildCaCertsCache();
2187 res = res && rebuildCertTrustCache();
2188 res = res && rebuildTrustedCaCertsCache();
2189 res = res && rebuildIgnoredSslErrorCache();
2190 mCustomConfigByHostCache.clear();
2191 mHasCheckedIfCustomConfigByHostExists = false;
2192
2193 if ( !res )
2194 QgsDebugError( u"Init of SSL caches FAILED"_s );
2195 return res;
2196#else
2197 return false;
2198#endif
2199}
2200
2201bool QgsAuthManager::storeCertIdentity( const QSslCertificate &cert, const QSslKey &key )
2202{
2203#ifdef HAVE_AUTH
2205
2206 QMutexLocker locker( mMutex.get() );
2207 if ( cert.isNull() )
2208 {
2209 QgsDebugError( u"Passed certificate is null"_s );
2210 return false;
2211 }
2212 if ( key.isNull() )
2213 {
2214 QgsDebugError( u"Passed private key is null"_s );
2215 return false;
2216 }
2217
2218 if ( !setMasterPassword( true ) )
2219 return false;
2220
2221 QString id( QgsAuthCertUtils::shaHexForCert( cert ) );
2222
2223
2224 if ( existsCertIdentity( id ) && ! removeCertIdentity( id ) )
2225 {
2226 QgsDebugError( u"Store certificate identity: FAILED to remove pre-existing certificate identity %1"_s.arg( id ) );
2227 return false;
2228 }
2229
2230 QString keypem( QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), key.toPem() ) );
2231
2233 {
2234 if ( !defaultStorage->storeCertIdentity( cert, keypem ) )
2235 {
2236 emit messageLog( tr( "Store certificate identity: FAILED to store certificate identity in default storage" ), authManTag(), Qgis::MessageLevel::Warning );
2237 return false;
2238 }
2239 return true;
2240 }
2241 else
2242 {
2243 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
2244 return false;
2245 }
2246#else
2247 Q_UNUSED( cert )
2248 Q_UNUSED( key )
2249 return false;
2250#endif
2251}
2252
2253const QSslCertificate QgsAuthManager::certIdentity( const QString &id )
2254{
2255#ifdef HAVE_AUTH
2257
2258 QMutexLocker locker( mMutex.get() );
2259
2260 QSslCertificate cert;
2261
2262 if ( id.isEmpty() )
2263 return cert;
2264
2265 // Loop through all storages with capability ReadCertificateIdentity and get the certificate from the first one that has the certificate
2267
2268 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2269 {
2270 cert = storage->loadCertIdentity( id );
2271 if ( !cert.isNull() )
2272 {
2273 return cert;
2274 }
2275 }
2276
2277 if ( storages.empty() )
2278 {
2279 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
2280 }
2281
2282 return cert;
2283#else
2284 Q_UNUSED( id )
2285 return QSslCertificate();
2286#endif
2287}
2288
2289const QPair<QSslCertificate, QSslKey> QgsAuthManager::certIdentityBundle( const QString &id )
2290{
2292
2293 QMutexLocker locker( mMutex.get() );
2294 QPair<QSslCertificate, QSslKey> bundle;
2295 if ( id.isEmpty() )
2296 return bundle;
2297
2298 if ( !setMasterPassword( true ) )
2299 return bundle;
2300
2301 // Loop through all storages with capability ReadCertificateIdentity and get the certificate from the first one that has the certificate
2303
2304 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2305 {
2306 if ( storage->certIdentityExists( id ) )
2307 {
2308 QPair<QSslCertificate, QString> encryptedBundle { storage->loadCertIdentityBundle( id ) };
2309 if ( encryptedBundle.first.isNull() )
2310 {
2311 QgsDebugError( u"Certificate identity bundle is null for id: %1"_s.arg( id ) );
2312 return bundle;
2313 }
2314 QSslKey key( QgsAuthCrypto::decrypt( mMasterPass, masterPasswordCiv(), encryptedBundle.second ).toLatin1(),
2315 QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey );
2316 if ( key.isNull() )
2317 {
2318 QgsDebugError( u"Certificate identity bundle: FAILED to create private key"_s );
2319 return bundle;
2320 }
2321 bundle = qMakePair( encryptedBundle.first, key );
2322 break;
2323 }
2324 }
2325
2326 if ( storages.empty() )
2327 {
2328 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
2329 return bundle;
2330 }
2331
2332 return bundle;
2333}
2334
2335const QStringList QgsAuthManager::certIdentityBundleToPem( const QString &id )
2336{
2337#ifdef HAVE_AUTH
2339
2340 QMutexLocker locker( mMutex.get() );
2341 QPair<QSslCertificate, QSslKey> bundle( certIdentityBundle( id ) );
2342 if ( QgsAuthCertUtils::certIsViable( bundle.first ) && !bundle.second.isNull() )
2343 {
2344 return QStringList() << QString( bundle.first.toPem() ) << QString( bundle.second.toPem() );
2345 }
2346 return QStringList();
2347#else
2348 Q_UNUSED( id )
2349 return QStringList();
2350#endif
2351}
2352
2353const QList<QSslCertificate> QgsAuthManager::certIdentities()
2354{
2355#ifdef HAVE_AUTH
2357
2358 QMutexLocker locker( mMutex.get() );
2359 QList<QSslCertificate> certs;
2360
2361 // Loop through all storages with capability ReadCertificateIdentity and collect the certificates from all storages
2363
2364 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2365 {
2366 const QList<QSslCertificate> storageCerts = storage->certIdentities();
2367 // Add if not already in the list, warn otherwise
2368 for ( const QSslCertificate &cert : std::as_const( storageCerts ) )
2369 {
2370 if ( !certs.contains( cert ) )
2371 {
2372 certs.append( cert );
2373 }
2374 else
2375 {
2376 emit messageLog( tr( "Certificate already in the list: %1" ).arg( cert.issuerDisplayName() ), authManTag(), Qgis::MessageLevel::Warning );
2377 }
2378 }
2379 }
2380
2381 if ( storages.empty() )
2382 {
2383 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
2384 }
2385
2386 return certs;
2387#else
2388 return QList<QSslCertificate>();
2389#endif
2390}
2391
2393{
2394#ifdef HAVE_AUTH
2396
2397 QMutexLocker locker( mMutex.get() );
2398
2399 if ( isDisabled() )
2400 return {};
2401
2402 // Loop through all storages with capability ReadCertificateIdentity and collect the certificate ids from all storages
2404
2405 QStringList ids;
2406
2407 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2408 {
2409 const QStringList storageIds = storage->certIdentityIds();
2410 // Add if not already in the list, warn otherwise
2411 for ( const QString &id : std::as_const( storageIds ) )
2412 {
2413 if ( !ids.contains( id ) )
2414 {
2415 ids.append( id );
2416 }
2417 else
2418 {
2419 emit messageLog( tr( "Certificate identity id already in the list: %1" ).arg( id ), authManTag(), Qgis::MessageLevel::Warning );
2420 }
2421 }
2422 }
2423
2424 return ids;
2425#else
2426 return QStringList();
2427#endif
2428}
2429
2430bool QgsAuthManager::existsCertIdentity( const QString &id )
2431{
2432#ifdef HAVE_AUTH
2434
2435 QMutexLocker locker( mMutex.get() );
2436 if ( id.isEmpty() )
2437 return false;
2438
2439 // Loop through all storages with capability ReadCertificateIdentity and check if the certificate exists in any storage
2441
2442 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2443 {
2444 if ( storage->certIdentityExists( id ) )
2445 {
2446 return true;
2447 }
2448 }
2449
2450 if ( storages.empty() )
2451 {
2452 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
2453 }
2454
2455 return false;
2456#else
2457 Q_UNUSED( id )
2458 return false;
2459#endif
2460}
2461
2462bool QgsAuthManager::removeCertIdentity( const QString &id )
2463{
2464#ifdef HAVE_AUTH
2466
2467 QMutexLocker locker( mMutex.get() );
2468 if ( id.isEmpty() )
2469 {
2470 QgsDebugError( u"Passed bundle ID is empty"_s );
2471 return false;
2472 }
2473
2474 // Loop through all storages with capability ReadCertificateIdentity and delete from the first one that has the bundle, fail if it has no capability
2476
2477 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2478 {
2479 if ( storage->certIdentityExists( id ) )
2480 {
2481 if ( !storage->removeCertIdentity( id ) )
2482 {
2483 emit messageLog( tr( "Remove certificate identity: FAILED to remove certificate identity from storage: %1" ).arg( storage->lastError() ), authManTag(), Qgis::MessageLevel::Warning );
2484 return false;
2485 }
2486 return true;
2487 }
2488 }
2489
2490 if ( storages.empty() )
2491 {
2492 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
2493 }
2494
2495 return false;
2496
2497#else
2498 Q_UNUSED( id )
2499 return false;
2500#endif
2501}
2502
2504{
2505#ifdef HAVE_AUTH
2507
2508 QMutexLocker locker( mMutex.get() );
2509 if ( config.isNull() )
2510 {
2511 QgsDebugError( u"Passed config is null"_s );
2512 return false;
2513 }
2514
2515 const QSslCertificate cert( config.sslCertificate() );
2516 const QString id( QgsAuthCertUtils::shaHexForCert( cert ) );
2517
2518 if ( existsSslCertCustomConfig( id, config.sslHostPort() ) && !removeSslCertCustomConfig( id, config.sslHostPort() ) )
2519 {
2520 QgsDebugError( u"Store SSL certificate custom config: FAILED to remove pre-existing config %1"_s.arg( id ) );
2521 return false;
2522 }
2523
2525 {
2526 if ( !defaultStorage->storeSslCertCustomConfig( config ) )
2527 {
2528 emit messageLog( tr( "Store SSL certificate custom config: FAILED to store config in default storage" ), authManTag(), Qgis::MessageLevel::Warning );
2529 return false;
2530 }
2531 }
2532 else
2533 {
2534 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
2535 return false;
2536 }
2537
2539 mCustomConfigByHostCache.clear();
2540
2541 return true;
2542#else
2543 Q_UNUSED( config )
2544 return false;
2545#endif
2546}
2547
2548const QgsAuthConfigSslServer QgsAuthManager::sslCertCustomConfig( const QString &id, const QString &hostport )
2549{
2550#ifdef HAVE_AUTH
2552
2553 QMutexLocker locker( mMutex.get() );
2555
2556 if ( id.isEmpty() || hostport.isEmpty() )
2557 {
2558 QgsDebugError( u"Passed config ID or host:port is empty"_s );
2559 return config;
2560 }
2561
2562 // Loop through all storages with capability ReadSslCertificateCustomConfig and get the config from the first one that has the config
2564
2565 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2566 {
2567 if ( storage->sslCertCustomConfigExists( id, hostport ) )
2568 {
2569 config = storage->loadSslCertCustomConfig( id, hostport );
2570 if ( !config.isNull() )
2571 {
2572 return config;
2573 }
2574 else
2575 {
2576 emit messageLog( tr( "Could not load SSL custom config %1 %2 from the storage." ).arg( id, hostport ), authManTag(), Qgis::MessageLevel::Critical );
2577 return config;
2578 }
2579 }
2580 }
2581
2582 if ( storages.empty() )
2583 {
2584 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
2585 }
2586
2587 return config;
2588
2589#else
2590 Q_UNUSED( id )
2591 Q_UNUSED( hostport )
2592 return QgsAuthConfigSslServer();
2593#endif
2594}
2595
2597{
2598#ifdef HAVE_AUTH
2600
2602 if ( hostport.isEmpty() )
2603 {
2604 return config;
2605 }
2606
2607 QMutexLocker locker( mMutex.get() );
2608
2609 if ( mCustomConfigByHostCache.contains( hostport ) )
2610 return mCustomConfigByHostCache.value( hostport );
2611
2612 // Loop through all storages with capability ReadSslCertificateCustomConfig and get the config from the first one that has the config
2614
2615 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2616 {
2617 config = storage->loadSslCertCustomConfigByHost( hostport );
2618 if ( !config.isNull() )
2619 {
2620 mCustomConfigByHostCache.insert( hostport, config );
2621 }
2622
2623 }
2624
2625 if ( storages.empty() )
2626 {
2627 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
2628 }
2629
2630 return config;
2631#else
2632 Q_UNUSED( hostport )
2633 return QgsAuthConfigSslServer();
2634#endif
2635}
2636
2637const QList<QgsAuthConfigSslServer> QgsAuthManager::sslCertCustomConfigs()
2638{
2639#ifdef HAVE_AUTH
2641
2642 QMutexLocker locker( mMutex.get() );
2643 QList<QgsAuthConfigSslServer> configs;
2644
2645 // Loop through all storages with capability ReadSslCertificateCustomConfig
2647
2648 QStringList ids;
2649
2650 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2651 {
2652 const QList<QgsAuthConfigSslServer> storageConfigs = storage->sslCertCustomConfigs();
2653 // Check if id + hostPort is not already in the list, warn otherwise
2654 for ( const auto &config : std::as_const( storageConfigs ) )
2655 {
2656 const QString id( QgsAuthCertUtils::shaHexForCert( config.sslCertificate() ) );
2657 const QString hostPort = config.sslHostPort();
2658 const QString shaHostPort( u"%1:%2"_s.arg( id, hostPort ) );
2659 if ( ! ids.contains( shaHostPort ) )
2660 {
2661 ids.append( shaHostPort );
2662 configs.append( config );
2663 }
2664 else
2665 {
2666 emit messageLog( tr( "SSL custom config already in the list: %1" ).arg( hostPort ), authManTag(), Qgis::MessageLevel::Warning );
2667 }
2668 }
2669 }
2670
2671 if ( storages.empty() )
2672 {
2673 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
2674 }
2675
2676 return configs;
2677#else
2678 return QList<QgsAuthConfigSslServer>();
2679#endif
2680}
2681
2682bool QgsAuthManager::existsSslCertCustomConfig( const QString &id, const QString &hostPort )
2683{
2684#ifdef HAVE_AUTH
2686
2687 QMutexLocker locker( mMutex.get() );
2688 if ( id.isEmpty() || hostPort.isEmpty() )
2689 {
2690 QgsDebugError( u"Passed config ID or host:port is empty"_s );
2691 return false;
2692 }
2693
2694 // Loop through all storages with capability ReadSslCertificateCustomConfig
2696
2697 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2698 {
2699 if ( storage->sslCertCustomConfigExists( id, hostPort ) )
2700 {
2701 return true;
2702 }
2703 }
2704
2705 if ( storages.empty() )
2706 {
2707 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
2708 }
2709
2710 return false;
2711#else
2712 Q_UNUSED( id )
2713 Q_UNUSED( hostPort )
2714 return false;
2715#endif
2716}
2717
2718bool QgsAuthManager::removeSslCertCustomConfig( const QString &id, const QString &hostport )
2719{
2720#ifdef HAVE_AUTH
2722
2723 QMutexLocker locker( mMutex.get() );
2724 if ( id.isEmpty() || hostport.isEmpty() )
2725 {
2726 QgsDebugError( u"Passed config ID or host:port is empty"_s );
2727 return false;
2728 }
2729
2730 mCustomConfigByHostCache.clear();
2731
2732 // Loop through all storages with capability DeleteSslCertificateCustomConfig
2734
2735 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2736 {
2737 if ( storage->sslCertCustomConfigExists( id, hostport ) )
2738 {
2739 if ( !storage->removeSslCertCustomConfig( id, hostport ) )
2740 {
2741 emit messageLog( tr( "FAILED to remove SSL cert custom config for host:port, id: %1, %2: %3" ).arg( hostport, id, storage->lastError() ), authManTag(), Qgis::MessageLevel::Warning );
2742 return false;
2743 }
2744 const QString shaHostPort( u"%1:%2"_s.arg( id, hostport ) );
2745 if ( mIgnoredSslErrorsCache.contains( shaHostPort ) )
2746 {
2747 mIgnoredSslErrorsCache.remove( shaHostPort );
2748 }
2749 return true;
2750 }
2751 }
2752
2753 if ( storages.empty() )
2754 {
2755 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
2756 }
2757
2758 return false;
2759#else
2760 Q_UNUSED( id )
2761 Q_UNUSED( hostport )
2762 return false;
2763#endif
2764}
2765
2766
2768{
2769#ifdef HAVE_AUTH
2771
2772 QMutexLocker locker( mMutex.get() );
2773 if ( !mIgnoredSslErrorsCache.isEmpty() )
2774 {
2775 QgsDebugMsgLevel( u"Ignored SSL errors cache items:"_s, 1 );
2776 QHash<QString, QSet<QSslError::SslError> >::const_iterator i = mIgnoredSslErrorsCache.constBegin();
2777 while ( i != mIgnoredSslErrorsCache.constEnd() )
2778 {
2779 QStringList errs;
2780 for ( auto err : i.value() )
2781 {
2782 errs << QgsAuthCertUtils::sslErrorEnumString( err );
2783 }
2784 QgsDebugMsgLevel( u"%1 = %2"_s.arg( i.key(), errs.join( ", " ) ), 1 );
2785 ++i;
2786 }
2787 }
2788 else
2789 {
2790 QgsDebugMsgLevel( u"Ignored SSL errors cache EMPTY"_s, 2 );
2791 }
2792#endif
2793}
2794
2796{
2797#ifdef HAVE_AUTH
2799
2800 QMutexLocker locker( mMutex.get() );
2801 if ( config.isNull() )
2802 {
2803 QgsDebugError( u"Passed config is null"_s );
2804 return false;
2805 }
2806
2807 QString shahostport( u"%1:%2"_s
2808 .arg( QgsAuthCertUtils::shaHexForCert( config.sslCertificate() ).trimmed(),
2809 config.sslHostPort().trimmed() ) );
2810 if ( mIgnoredSslErrorsCache.contains( shahostport ) )
2811 {
2812 mIgnoredSslErrorsCache.remove( shahostport );
2813 }
2814 const QList<QSslError::SslError> errenums( config.sslIgnoredErrorEnums() );
2815 if ( !errenums.isEmpty() )
2816 {
2817 mIgnoredSslErrorsCache.insert( shahostport, QSet<QSslError::SslError>( errenums.begin(), errenums.end() ) );
2818 QgsDebugMsgLevel( u"Update of ignored SSL errors cache SUCCEEDED for sha:host:port = %1"_s.arg( shahostport ), 2 );
2820 return true;
2821 }
2822
2823 QgsDebugMsgLevel( u"No ignored SSL errors to cache for sha:host:port = %1"_s.arg( shahostport ), 2 );
2824 return true;
2825#else
2826 Q_UNUSED( config )
2827 return false;
2828#endif
2829}
2830
2831bool QgsAuthManager::updateIgnoredSslErrorsCache( const QString &shahostport, const QList<QSslError> &errors )
2832{
2833#ifdef HAVE_AUTH
2835
2836 QMutexLocker locker( mMutex.get() );
2837 const thread_local QRegularExpression rx( QRegularExpression::anchoredPattern( "\\S+:\\S+:\\d+" ) );
2838 if ( !rx.match( shahostport ).hasMatch() )
2839 {
2840 QgsDebugError( "Passed shahostport does not match \\S+:\\S+:\\d+, "
2841 "e.g. 74a4ef5ea94512a43769b744cda0ca5049a72491:www.example.com:443" );
2842 return false;
2843 }
2844
2845 if ( mIgnoredSslErrorsCache.contains( shahostport ) )
2846 {
2847 mIgnoredSslErrorsCache.remove( shahostport );
2848 }
2849
2850 if ( errors.isEmpty() )
2851 {
2852 QgsDebugError( u"Passed errors list empty"_s );
2853 return false;
2854 }
2855
2856 QSet<QSslError::SslError> errs;
2857 for ( const auto &error : errors )
2858 {
2859 if ( error.error() == QSslError::NoError )
2860 continue;
2861
2862 errs.insert( error.error() );
2863 }
2864
2865 if ( errs.isEmpty() )
2866 {
2867 QgsDebugError( u"Passed errors list does not contain errors"_s );
2868 return false;
2869 }
2870
2871 mIgnoredSslErrorsCache.insert( shahostport, errs );
2872
2873 QgsDebugMsgLevel( u"Update of ignored SSL errors cache SUCCEEDED for sha:host:port = %1"_s.arg( shahostport ), 2 );
2875 return true;
2876#else
2877 Q_UNUSED( shahostport )
2878 Q_UNUSED( errors )
2879 return false;
2880#endif
2881}
2882
2884{
2885#ifdef HAVE_AUTH
2887
2888 QMutexLocker locker( mMutex.get() );
2889 QHash<QString, QSet<QSslError::SslError> > prevcache( mIgnoredSslErrorsCache );
2890 QHash<QString, QSet<QSslError::SslError> > nextcache;
2891
2892 // Loop through all storages with capability ReadSslCertificateCustomConfig
2894
2895 QStringList ids;
2896
2897 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
2898 {
2899 const auto customConfigs { storage->sslCertCustomConfigs() };
2900 for ( const auto &config : std::as_const( customConfigs ) )
2901 {
2902 const QString shaHostPort( u"%1:%2"_s.arg( QgsAuthCertUtils::shaHexForCert( config.sslCertificate() ), config.sslHostPort() ) );
2903 if ( ! ids.contains( shaHostPort ) )
2904 {
2905 ids.append( shaHostPort );
2906 if ( !config.sslIgnoredErrorEnums().isEmpty() )
2907 {
2908 nextcache.insert( shaHostPort, QSet<QSslError::SslError>( config.sslIgnoredErrorEnums().cbegin(), config.sslIgnoredErrorEnums().cend() ) );
2909 }
2910 if ( prevcache.contains( shaHostPort ) )
2911 {
2912 prevcache.remove( shaHostPort );
2913 }
2914 }
2915 else
2916 {
2917 emit messageLog( tr( "SSL custom config already in the list: %1" ).arg( config.sslHostPort() ), authManTag(), Qgis::MessageLevel::Warning );
2918 }
2919 }
2920 }
2921
2922 if ( !prevcache.isEmpty() )
2923 {
2924 // preserve any existing per-session ignored errors for hosts
2925 QHash<QString, QSet<QSslError::SslError> >::const_iterator i = prevcache.constBegin();
2926 while ( i != prevcache.constEnd() )
2927 {
2928 nextcache.insert( i.key(), i.value() );
2929 ++i;
2930 }
2931 }
2932
2933 if ( nextcache != mIgnoredSslErrorsCache )
2934 {
2935 mIgnoredSslErrorsCache.clear();
2936 mIgnoredSslErrorsCache = nextcache;
2937 QgsDebugMsgLevel( u"Rebuild of ignored SSL errors cache SUCCEEDED"_s, 2 );
2939 return true;
2940 }
2941
2942 QgsDebugMsgLevel( u"Rebuild of ignored SSL errors cache SAME AS BEFORE"_s, 2 );
2944 return true;
2945#else
2946 return false;
2947#endif
2948}
2949
2950bool QgsAuthManager::storeCertAuthorities( const QList<QSslCertificate> &certs )
2951{
2952#ifdef HAVE_AUTH
2954
2955 QMutexLocker locker( mMutex.get() );
2956 if ( certs.isEmpty() )
2957 {
2958 QgsDebugError( u"Passed certificate list has no certs"_s );
2959 return false;
2960 }
2961
2962 for ( const auto &cert : certs )
2963 {
2964 if ( !storeCertAuthority( cert ) )
2965 return false;
2966 }
2967 return true;
2968#else
2969 Q_UNUSED( certs )
2970 return false;
2971#endif
2972}
2973
2974bool QgsAuthManager::storeCertAuthority( const QSslCertificate &cert )
2975{
2976#ifdef HAVE_AUTH
2978
2979 QMutexLocker locker( mMutex.get() );
2980 // don't refuse !cert.isValid() (actually just expired) CAs,
2981 // as user may want to ignore that SSL connection error
2982 if ( cert.isNull() )
2983 {
2984 QgsDebugError( u"Passed certificate is null"_s );
2985 return false;
2986 }
2987
2988 if ( existsCertAuthority( cert ) && !removeCertAuthority( cert ) )
2989 {
2990 QgsDebugError( u"Store certificate authority: FAILED to remove pre-existing certificate authority"_s );
2991 return false;
2992 }
2993
2995 {
2996 return defaultStorage->storeCertAuthority( cert );
2997 }
2998 else
2999 {
3000 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
3001 return false;
3002 }
3003
3004 return false;
3005#else
3006 Q_UNUSED( cert )
3007 return false;
3008#endif
3009}
3010
3011const QSslCertificate QgsAuthManager::certAuthority( const QString &id )
3012{
3013#ifdef HAVE_AUTH
3015
3016 QMutexLocker locker( mMutex.get() );
3017 QSslCertificate emptycert;
3018 QSslCertificate cert;
3019 if ( id.isEmpty() )
3020 return emptycert;
3021
3022 // Loop through all storages with capability ReadCertificateAuthority and get the certificate from the first one that has the certificate
3024
3025 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
3026 {
3027 cert = storage->loadCertAuthority( id );
3028 if ( !cert.isNull() )
3029 {
3030 return cert;
3031 }
3032 }
3033
3034 if ( storages.empty() )
3035 {
3036 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
3037 return emptycert;
3038 }
3039
3040 return cert;
3041#else
3042 Q_UNUSED( id )
3043 return QSslCertificate();
3044#endif
3045}
3046
3047bool QgsAuthManager::existsCertAuthority( const QSslCertificate &cert )
3048{
3049#ifdef HAVE_AUTH
3051
3052 QMutexLocker locker( mMutex.get() );
3053 if ( cert.isNull() )
3054 {
3055 QgsDebugError( u"Passed certificate is null"_s );
3056 return false;
3057 }
3058
3059 // Loop through all storages with capability ReadCertificateAuthority and get the certificate from the first one that has the certificate
3061
3062 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
3063 {
3064 if ( storage->certAuthorityExists( cert ) )
3065 {
3066 return true;
3067 }
3068 }
3069
3070 if ( storages.empty() )
3071 {
3072 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
3073 }
3074
3075 return false;
3076#else
3077 return false;
3078#endif
3079}
3080
3081bool QgsAuthManager::removeCertAuthority( const QSslCertificate &cert )
3082{
3083#ifdef HAVE_AUTH
3085
3086 QMutexLocker locker( mMutex.get() );
3087 if ( cert.isNull() )
3088 {
3089 QgsDebugError( u"Passed certificate is null"_s );
3090 return false;
3091 }
3092
3093 // Loop through all storages with capability ReadCertificateAuthority and delete from the first one that has the certificate, fail if it has no capability
3095
3096 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
3097 {
3098 if ( storage->certAuthorityExists( cert ) )
3099 {
3100
3102 {
3103 emit messageLog( tr( "Remove certificate: FAILED to remove setting from storage %1: storage is read only" ).arg( storage->name() ), authManTag(), Qgis::MessageLevel::Warning );
3104 return false;
3105 }
3106
3107 if ( !storage->removeCertAuthority( cert ) )
3108 {
3109 emit messageLog( tr( "Remove certificate authority: FAILED to remove certificate authority from storage: %1" ).arg( storage->lastError() ), authManTag(), Qgis::MessageLevel::Warning );
3110 return false;
3111 }
3112 return true;
3113 }
3114 }
3115
3116 if ( storages.empty() )
3117 {
3118 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
3119 }
3120
3121 return false;
3122#else
3123 Q_UNUSED( cert )
3124 return false;
3125#endif
3126}
3127
3128const QList<QSslCertificate> QgsAuthManager::systemRootCAs()
3129{
3130#ifdef HAVE_AUTH
3131 return QSslConfiguration::systemCaCertificates();
3132#else
3133 return QList<QSslCertificate>();
3134#endif
3135}
3136
3137const QList<QSslCertificate> QgsAuthManager::extraFileCAs()
3138{
3139#ifdef HAVE_AUTH
3141
3142 QMutexLocker locker( mMutex.get() );
3143 QList<QSslCertificate> certs;
3144 QList<QSslCertificate> filecerts;
3145 QVariant cafileval = QgsAuthManager::instance()->authSetting( u"cafile"_s );
3146 if ( QgsVariantUtils::isNull( cafileval ) )
3147 return certs;
3148
3149 QVariant allowinvalid = QgsAuthManager::instance()->authSetting( u"cafileallowinvalid"_s, QVariant( false ) );
3150 if ( QgsVariantUtils::isNull( allowinvalid ) )
3151 return certs;
3152
3153 QString cafile( cafileval.toString() );
3154 if ( !cafile.isEmpty() && QFile::exists( cafile ) )
3155 {
3156 filecerts = QgsAuthCertUtils::certsFromFile( cafile );
3157 }
3158 // only CAs or certs capable of signing other certs are allowed
3159 for ( const auto &cert : std::as_const( filecerts ) )
3160 {
3161 if ( !allowinvalid.toBool() && ( cert.isBlacklisted()
3162 || cert.isNull()
3163 || cert.expiryDate() <= QDateTime::currentDateTime()
3164 || cert.effectiveDate() > QDateTime::currentDateTime() ) )
3165 {
3166 continue;
3167 }
3168
3169 if ( QgsAuthCertUtils::certificateIsAuthorityOrIssuer( cert ) )
3170 {
3171 certs << cert;
3172 }
3173 }
3174 return certs;
3175#else
3176 return QList<QSslCertificate>();
3177#endif
3178}
3179
3180const QList<QSslCertificate> QgsAuthManager::databaseCAs()
3181{
3182#ifdef HAVE_AUTH
3184
3185 QMutexLocker locker( mMutex.get() );
3186
3187 // Loop through all storages with capability ReadCertificateAuthority and collect the certificates from all storages
3189
3190 QList<QSslCertificate> certs;
3191
3192 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
3193 {
3194 const QList<QSslCertificate> storageCerts = storage->caCerts();
3195 // Add if not already in the list, warn otherwise
3196 for ( const QSslCertificate &cert : std::as_const( storageCerts ) )
3197 {
3198 if ( !certs.contains( cert ) )
3199 {
3200 certs.append( cert );
3201 }
3202 else
3203 {
3204 emit messageLog( tr( "Certificate already in the list: %1" ).arg( cert.issuerDisplayName() ), authManTag(), Qgis::MessageLevel::Warning );
3205 }
3206 }
3207 }
3208
3209 if ( storages.empty() )
3210 {
3211 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
3212 }
3213
3214 return certs;
3215#else
3216 return QList<QSslCertificate>();
3217#endif
3218}
3219
3220const QMap<QString, QSslCertificate> QgsAuthManager::mappedDatabaseCAs()
3221{
3223
3224 QMutexLocker locker( mMutex.get() );
3225 return QgsAuthCertUtils::mapDigestToCerts( databaseCAs() );
3226}
3227
3229{
3230#ifdef HAVE_AUTH
3232
3233 QMutexLocker locker( mMutex.get() );
3234 mCaCertsCache.clear();
3235 // in reverse order of precedence, with regards to duplicates, so QMap inserts overwrite
3236 insertCaCertInCache( QgsAuthCertUtils::SystemRoot, systemRootCAs() );
3237 insertCaCertInCache( QgsAuthCertUtils::FromFile, extraFileCAs() );
3238 insertCaCertInCache( QgsAuthCertUtils::InDatabase, databaseCAs() );
3239
3240 bool res = !mCaCertsCache.isEmpty(); // should at least contain system root CAs
3241 if ( !res )
3242 QgsDebugError( u"Rebuild of CA certs cache FAILED"_s );
3243 return res;
3244#else
3245 return false;
3246#endif
3247}
3248
3250{
3251#ifdef HAVE_AUTH
3253
3254 QMutexLocker locker( mMutex.get() );
3255 if ( cert.isNull() )
3256 {
3257 QgsDebugError( u"Passed certificate is null."_s );
3258 return false;
3259 }
3260
3261 if ( certTrustPolicy( cert ) == policy )
3262 {
3263 return true;
3264 }
3265
3267 {
3268 emit messageLog( tr( "Could not delete pre-existing certificate trust policy." ), authManTag(), Qgis::MessageLevel::Warning );
3269 return false;
3270 }
3271
3273 {
3274 return defaultStorage->storeCertTrustPolicy( cert, policy );
3275 }
3276 else
3277 {
3278 emit messageLog( tr( "Could not connect to any authentication configuration storage." ), authManTag(), Qgis::MessageLevel::Critical );
3279 return false;
3280 }
3281#else
3282 Q_UNUSED( cert )
3283 Q_UNUSED( policy )
3284 return false;
3285#endif
3286}
3287
3289{
3290#ifdef HAVE_AUTH
3292
3293 QMutexLocker locker( mMutex.get() );
3294 if ( cert.isNull() )
3295 {
3296 QgsDebugError( u"Passed certificate is null"_s );
3298 }
3299
3300 // Loop through all storages with capability ReadCertificateTrustPolicy and get the policy from the first one that has the policy
3302
3303 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
3304 {
3306 if ( policy != QgsAuthCertUtils::DefaultTrust )
3307 {
3308 return policy;
3309 }
3310 }
3311
3312 if ( storages.empty() )
3313 {
3314 emit messageLog( tr( "Could not connect to any credentials storage." ), authManTag(), Qgis::MessageLevel::Critical );
3315 }
3316
3318#else
3319 Q_UNUSED( cert )
3321#endif
3322}
3323
3324bool QgsAuthManager::removeCertTrustPolicies( const QList<QSslCertificate> &certs )
3325{
3326#ifdef HAVE_AUTH
3328
3329 QMutexLocker locker( mMutex.get() );
3330 if ( certs.empty() )
3331 {
3332 QgsDebugError( u"Passed certificate list has no certs"_s );
3333 return false;
3334 }
3335
3336 for ( const auto &cert : certs )
3337 {
3338 if ( !removeCertTrustPolicy( cert ) )
3339 return false;
3340 }
3341 return true;
3342#else
3343 Q_UNUSED( certs )
3344 return false;
3345#endif
3346}
3347
3348bool QgsAuthManager::removeCertTrustPolicy( const QSslCertificate &cert )
3349{
3350#ifdef HAVE_AUTH
3352
3353 QMutexLocker locker( mMutex.get() );
3354 if ( cert.isNull() )
3355 {
3356 QgsDebugError( u"Passed certificate is null"_s );
3357 return false;
3358 }
3359
3360 // Loop through all storages with capability ReadCertificateTrustPolicy and delete from the first one that has the policy, fail if it has no capability
3362
3363 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
3364 {
3365 if ( storage->certTrustPolicyExists( cert ) )
3366 {
3368 {
3369 emit messageLog( tr( "Remove certificate trust policy: FAILED to remove setting from storage %1: storage is read only" ).arg( storage->name() ), authManTag(), Qgis::MessageLevel::Warning );
3370 return false;
3371 }
3372
3373 if ( !storage->removeCertTrustPolicy( cert ) )
3374 {
3375 emit messageLog( tr( "Remove certificate trust policy: FAILED to remove certificate trust policy from storage: %1" ).arg( storage->lastError() ), authManTag(), Qgis::MessageLevel::Warning );
3376 return false;
3377 }
3378 return true;
3379 }
3380 }
3381
3382 if ( storages.empty() )
3383 {
3384 emit messageLog( tr( "Could not connect to any authentication configuration storage." ), authManTag(), Qgis::MessageLevel::Critical );
3385 }
3386
3387 return false;
3388#else
3389 Q_UNUSED( cert )
3390 return false;
3391#endif
3392}
3393
3395{
3396#ifdef HAVE_AUTH
3398
3399 QMutexLocker locker( mMutex.get() );
3400 if ( cert.isNull() )
3401 {
3403 }
3404
3405 QString id( QgsAuthCertUtils::shaHexForCert( cert ) );
3406 const QStringList &trustedids = mCertTrustCache.value( QgsAuthCertUtils::Trusted );
3407 const QStringList &untrustedids = mCertTrustCache.value( QgsAuthCertUtils::Untrusted );
3408
3410 if ( trustedids.contains( id ) )
3411 {
3413 }
3414 else if ( untrustedids.contains( id ) )
3415 {
3417 }
3418 return policy;
3419#else
3420 Q_UNUSED( cert )
3422#endif
3423}
3424
3426{
3427#ifdef HAVE_AUTH
3429
3430 if ( policy == QgsAuthCertUtils::DefaultTrust )
3431 {
3432 // set default trust policy to Trusted by removing setting
3433 return removeAuthSetting( u"certdefaulttrust"_s );
3434 }
3435 return storeAuthSetting( u"certdefaulttrust"_s, static_cast< int >( policy ) );
3436#else
3437 Q_UNUSED( policy )
3438 return false;
3439#endif
3440}
3441
3443{
3444#ifdef HAVE_AUTH
3446
3447 QMutexLocker locker( mMutex.get() );
3448 QVariant policy( authSetting( u"certdefaulttrust"_s ) );
3449 if ( QgsVariantUtils::isNull( policy ) )
3450 {
3452 }
3453 return static_cast< QgsAuthCertUtils::CertTrustPolicy >( policy.toInt() );
3454#else
3456#endif
3457}
3458
3460{
3461#ifdef HAVE_AUTH
3463
3464 QMutexLocker locker( mMutex.get() );
3465 mCertTrustCache.clear();
3466
3467 // Loop through all storages with capability ReadCertificateTrustPolicy
3469
3470 QStringList ids;
3471
3472 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
3473 {
3474
3475 const auto trustedCerts { storage->caCertsPolicy() };
3476 for ( auto it = trustedCerts.cbegin(); it != trustedCerts.cend(); ++it )
3477 {
3478 const QString id { it.key( )};
3479 if ( ! ids.contains( id ) )
3480 {
3481 ids.append( id );
3482 const QgsAuthCertUtils::CertTrustPolicy policy( it.value() );
3484 {
3485 QStringList ids;
3486 if ( mCertTrustCache.contains( QgsAuthCertUtils::Trusted ) )
3487 {
3488 ids = mCertTrustCache.value( QgsAuthCertUtils::Trusted );
3489 }
3490 mCertTrustCache.insert( QgsAuthCertUtils::Trusted, ids << it.key() );
3491 }
3492 }
3493 else
3494 {
3495 emit messageLog( tr( "Certificate already in the list: %1" ).arg( it.key() ), authManTag(), Qgis::MessageLevel::Warning );
3496 }
3497 }
3498 }
3499
3500 if ( ! storages.empty() )
3501 {
3502 QgsDebugMsgLevel( u"Rebuild of cert trust policy cache SUCCEEDED"_s, 2 );
3503 return true;
3504 }
3505 else
3506 {
3507 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
3508 return false;
3509 }
3510#else
3511 return false;
3512#endif
3513}
3514
3515const QList<QSslCertificate> QgsAuthManager::trustedCaCerts( bool includeinvalid )
3516{
3517#ifdef HAVE_AUTH
3519
3520 QMutexLocker locker( mMutex.get() );
3522 QStringList trustedids = mCertTrustCache.value( QgsAuthCertUtils::Trusted );
3523 QStringList untrustedids = mCertTrustCache.value( QgsAuthCertUtils::Untrusted );
3524 const QList<QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > &certpairs( mCaCertsCache.values() );
3525
3526 QList<QSslCertificate> trustedcerts;
3527 for ( int i = 0; i < certpairs.size(); ++i )
3528 {
3529 QSslCertificate cert( certpairs.at( i ).second );
3530 QString certid( QgsAuthCertUtils::shaHexForCert( cert ) );
3531 if ( trustedids.contains( certid ) )
3532 {
3533 // trusted certs are always added regardless of their validity
3534 trustedcerts.append( cert );
3535 }
3536 else if ( defaultpolicy == QgsAuthCertUtils::Trusted && !untrustedids.contains( certid ) )
3537 {
3538 if ( !includeinvalid && !QgsAuthCertUtils::certIsViable( cert ) )
3539 continue;
3540 trustedcerts.append( cert );
3541 }
3542 }
3543
3544 // update application default SSL config for new requests
3545 QSslConfiguration sslconfig( QSslConfiguration::defaultConfiguration() );
3546 sslconfig.setCaCertificates( trustedcerts );
3547 QSslConfiguration::setDefaultConfiguration( sslconfig );
3548
3549 return trustedcerts;
3550#else
3551 Q_UNUSED( includeinvalid )
3552 return QList<QSslCertificate>();
3553#endif
3554}
3555
3556const QList<QSslCertificate> QgsAuthManager::untrustedCaCerts( QList<QSslCertificate> trustedCAs )
3557{
3558#ifdef HAVE_AUTH
3560
3561 QMutexLocker locker( mMutex.get() );
3562 if ( trustedCAs.isEmpty() )
3563 {
3564 if ( mTrustedCaCertsCache.isEmpty() )
3565 {
3567 }
3568 trustedCAs = trustedCaCertsCache();
3569 }
3570
3571 const QList<QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > &certpairs( mCaCertsCache.values() );
3572
3573 QList<QSslCertificate> untrustedCAs;
3574 for ( int i = 0; i < certpairs.size(); ++i )
3575 {
3576 QSslCertificate cert( certpairs.at( i ).second );
3577 if ( !trustedCAs.contains( cert ) )
3578 {
3579 untrustedCAs.append( cert );
3580 }
3581 }
3582 return untrustedCAs;
3583#else
3584 Q_UNUSED( trustedCAs )
3585 return QList<QSslCertificate>();
3586#endif
3587}
3588
3590{
3591#ifdef HAVE_AUTH
3593
3594 QMutexLocker locker( mMutex.get() );
3595 mTrustedCaCertsCache = trustedCaCerts();
3596 QgsDebugMsgLevel( u"Rebuilt trusted cert authorities cache"_s, 2 );
3597 // TODO: add some error trapping for the operation
3598 return true;
3599#else
3600 return false;
3601#endif
3602}
3603
3605{
3606#ifdef HAVE_AUTH
3608
3609 QMutexLocker locker( mMutex.get() );
3610 return QgsAuthCertUtils::certsToPemText( trustedCaCertsCache() );
3611#else
3612 return QByteArray();
3613#endif
3614}
3615
3617{
3618#ifdef HAVE_AUTH
3620
3621 QMutexLocker locker( mMutex.get() );
3622 if ( masterPasswordIsSet() )
3623 {
3624 return passwordHelperWrite( mMasterPass );
3625 }
3626 return false;
3627#else
3628 return false;
3629#endif
3630}
3631
3633{
3634#ifdef HAVE_AUTH
3635 if ( !passwordHelperEnabled() )
3636 return false;
3637
3638 bool readOk = false;
3639 const QString currentPass = passwordHelperRead( readOk );
3640 if ( !readOk )
3641 return false;
3642
3643 if ( !currentPass.isEmpty() && ( mPasswordHelperErrorCode == QKeychain::NoError ) )
3644 {
3645 return verifyMasterPassword( currentPass );
3646 }
3647 return false;
3648#else
3649 return false;
3650#endif
3651}
3652
3654{
3655#ifdef HAVE_AUTH
3656#if defined(Q_OS_MAC)
3657 return titleCase ? QObject::tr( "Keychain" ) : QObject::tr( "keychain" );
3658#elif defined(Q_OS_WIN)
3659 return titleCase ? QObject::tr( "Password Manager" ) : QObject::tr( "password manager" );
3660#elif defined(Q_OS_LINUX)
3661
3662 const QString desktopSession = qgetenv( "DESKTOP_SESSION" );
3663 const QString currentDesktop = qgetenv( "XDG_CURRENT_DESKTOP" );
3664 const QString gdmSession = qgetenv( "GDMSESSION" );
3665 // lets use a more precise string if we're running on KDE!
3666 if ( desktopSession.contains( "kde"_L1, Qt::CaseInsensitive ) || currentDesktop.contains( "kde"_L1, Qt::CaseInsensitive ) || gdmSession.contains( "kde"_L1, Qt::CaseInsensitive ) )
3667 {
3668 return titleCase ? QObject::tr( "Wallet" ) : QObject::tr( "wallet" );
3669 }
3670
3671 return titleCase ? QObject::tr( "Wallet/Key Ring" ) : QObject::tr( "wallet/key ring" );
3672#else
3673 return titleCase ? QObject::tr( "Password Manager" ) : QObject::tr( "password manager" );
3674#endif
3675#else
3676 Q_UNUSED( titleCase )
3677 return QString();
3678#endif
3679}
3680
3681
3683
3684#endif
3685
3687{
3688#ifdef HAVE_AUTH
3690
3691 if ( isDisabled() )
3692 return;
3693
3694 const QStringList ids = configIds();
3695 for ( const auto &authcfg : ids )
3696 {
3697 clearCachedConfig( authcfg );
3698 }
3699#endif
3700}
3701
3702void QgsAuthManager::clearCachedConfig( const QString &authcfg )
3703{
3704#ifdef HAVE_AUTH
3706
3707 if ( isDisabled() )
3708 return;
3709
3710 QgsAuthMethod *authmethod = configAuthMethod( authcfg );
3711 if ( authmethod )
3712 {
3713 authmethod->clearCachedConfig( authcfg );
3714 }
3715#else
3716 Q_UNUSED( authcfg )
3717#endif
3718}
3719
3720void QgsAuthManager::writeToConsole( const QString &message,
3721 const QString &tag,
3722 Qgis::MessageLevel level )
3723{
3724#ifdef HAVE_AUTH
3725 Q_UNUSED( tag )
3726
3728
3729 // only output WARNING and CRITICAL messages
3730 if ( level == Qgis::MessageLevel::Info )
3731 return;
3732
3733 QString msg;
3734 switch ( level )
3735 {
3737 msg += "WARNING: "_L1;
3738 break;
3740 msg += "ERROR: "_L1;
3741 break;
3742 default:
3743 break;
3744 }
3745 msg += message;
3746
3747 QTextStream out( stdout, QIODevice::WriteOnly );
3748 out << msg << Qt::endl;
3749#else
3750 Q_UNUSED( message )
3751 Q_UNUSED( tag )
3752 Q_UNUSED( level )
3753#endif
3754}
3755
3756void QgsAuthManager::tryToStartDbErase()
3757{
3758#ifdef HAVE_AUTH
3760
3761 ++mScheduledDbEraseRequestCount;
3762 // wait a total of 90 seconds for GUI availiability or user interaction, then cancel schedule
3763 int trycutoff = 90 / ( mScheduledDbEraseRequestWait ? mScheduledDbEraseRequestWait : 3 );
3764 if ( mScheduledDbEraseRequestCount >= trycutoff )
3765 {
3767 QgsDebugMsgLevel( u"authDatabaseEraseRequest emitting/scheduling canceled"_s, 2 );
3768 return;
3769 }
3770 else
3771 {
3772 QgsDebugMsgLevel( u"authDatabaseEraseRequest attempt (%1 of %2)"_s
3773 .arg( mScheduledDbEraseRequestCount ).arg( trycutoff ), 2 );
3774 }
3775
3776 if ( scheduledAuthDatabaseErase() && !mScheduledDbEraseRequestEmitted && mMutex->tryLock() )
3777 {
3778 // see note in header about this signal's use
3779 mScheduledDbEraseRequestEmitted = true;
3781
3782 mMutex->unlock();
3783
3784 QgsDebugMsgLevel( u"authDatabaseEraseRequest emitted"_s, 2 );
3785 return;
3786 }
3787 QgsDebugMsgLevel( u"authDatabaseEraseRequest emit skipped"_s, 2 );
3788#endif
3789}
3790
3791
3793{
3794#ifdef HAVE_AUTH
3795 QMutexLocker locker( mMutex.get() );
3796
3797 QMapIterator<QThread *, QMetaObject::Connection> iterator( mConnectedThreads );
3798 while ( iterator.hasNext() )
3799 {
3800 iterator.next();
3801 QThread::disconnect( iterator.value() );
3802 }
3803
3804 if ( !mAuthInit )
3805 return;
3806
3807 locker.unlock();
3808
3809 if ( !isDisabled() )
3810 {
3812 qDeleteAll( mAuthMethods );
3813
3815 QSqlDatabase authConn = authDatabaseConnection();
3817 if ( authConn.isValid() && authConn.isOpen() )
3818 authConn.close();
3819 }
3820
3821 QSqlDatabase::removeDatabase( u"authentication.configs"_s );
3822#endif
3823}
3824
3826{
3827 QMutexLocker locker( mMutex.get() );
3828 if ( ! mAuthConfigurationStorageRegistry )
3829 {
3830 mAuthConfigurationStorageRegistry = std::make_unique<QgsAuthConfigurationStorageRegistry>();
3831 }
3832 return mAuthConfigurationStorageRegistry.get();
3833}
3834
3835
3836QString QgsAuthManager::passwordHelperName() const
3837{
3838#ifdef HAVE_AUTH
3839 return tr( "Password Helper" );
3840#else
3841 return QString();
3842#endif
3843}
3844
3845
3846void QgsAuthManager::passwordHelperLog( const QString &msg ) const
3847{
3848#ifdef HAVE_AUTH
3850
3852 {
3853 QgsMessageLog::logMessage( msg, passwordHelperName() );
3854 }
3855#else
3856 Q_UNUSED( msg )
3857#endif
3858}
3859
3861{
3862#ifdef HAVE_AUTH
3864
3865 passwordHelperLog( tr( "Opening %1 for DELETE…" ).arg( passwordHelperDisplayName() ) );
3866 bool result;
3867 QKeychain::DeletePasswordJob job( AUTH_PASSWORD_HELPER_FOLDER_NAME );
3868 QgsSettings settings;
3869 job.setInsecureFallback( settings.value( u"password_helper_insecure_fallback"_s, false, QgsSettings::Section::Auth ).toBool() );
3870 job.setAutoDelete( false );
3871 job.setKey( authPasswordHelperKeyName() );
3872 QEventLoop loop;
3873 connect( &job, &QKeychain::Job::finished, &loop, &QEventLoop::quit );
3874 job.start();
3875 loop.exec();
3876 if ( job.error() )
3877 {
3878 mPasswordHelperErrorCode = job.error();
3879 mPasswordHelperErrorMessage = tr( "Delete password failed: %1." ).arg( job.errorString() );
3880 // Signals used in the tests to exit main application loop
3881 emit passwordHelperFailure();
3882 result = false;
3883 }
3884 else
3885 {
3886 // Signals used in the tests to exit main application loop
3887 emit passwordHelperSuccess();
3888 result = true;
3889 }
3890 passwordHelperProcessError();
3891 return result;
3892#else
3893 return false;
3894#endif
3895}
3896
3897QString QgsAuthManager::passwordHelperRead( bool &ok )
3898{
3899#ifdef HAVE_AUTH
3900 ok = false;
3902
3903 // Retrieve it!
3904 QString password;
3905 passwordHelperLog( tr( "Opening %1 for READ…" ).arg( passwordHelperDisplayName() ) );
3906 QKeychain::ReadPasswordJob job( AUTH_PASSWORD_HELPER_FOLDER_NAME );
3907 QgsSettings settings;
3908 job.setInsecureFallback( settings.value( u"password_helper_insecure_fallback"_s, false, QgsSettings::Section::Auth ).toBool() );
3909 job.setAutoDelete( false );
3910 job.setKey( authPasswordHelperKeyName() );
3911 QEventLoop loop;
3912 connect( &job, &QKeychain::Job::finished, &loop, &QEventLoop::quit );
3913 job.start();
3914 loop.exec();
3915 if ( job.error() )
3916 {
3917 mPasswordHelperErrorCode = job.error();
3918 mPasswordHelperErrorMessage = tr( "Retrieving password from the %1 failed: %2." ).arg( passwordHelperDisplayName(), job.errorString() );
3919 // Signals used in the tests to exit main application loop
3920 emit passwordHelperFailure();
3921 }
3922 else
3923 {
3924 password = job.textData();
3925 // Password is there but it is empty, treat it like if it was not found
3926 if ( password.isEmpty() )
3927 {
3928 mPasswordHelperErrorCode = QKeychain::EntryNotFound;
3929 mPasswordHelperErrorMessage = tr( "Empty password retrieved from the %1." ).arg( passwordHelperDisplayName( true ) );
3930 // Signals used in the tests to exit main application loop
3931 emit passwordHelperFailure();
3932 }
3933 else
3934 {
3935 ok = true;
3936 // Signals used in the tests to exit main application loop
3937 emit passwordHelperSuccess();
3938 }
3939 }
3940 passwordHelperProcessError();
3941 return password;
3942#else
3943 Q_UNUSED( ok )
3944 return QString();
3945#endif
3946}
3947
3948bool QgsAuthManager::passwordHelperWrite( const QString &password )
3949{
3950#ifdef HAVE_AUTH
3952
3953 Q_ASSERT( !password.isEmpty() );
3954 bool result;
3955 passwordHelperLog( tr( "Opening %1 for WRITE…" ).arg( passwordHelperDisplayName() ) );
3956 QKeychain::WritePasswordJob job( AUTH_PASSWORD_HELPER_FOLDER_NAME );
3957 QgsSettings settings;
3958 job.setInsecureFallback( settings.value( u"password_helper_insecure_fallback"_s, false, QgsSettings::Section::Auth ).toBool() );
3959 job.setAutoDelete( false );
3960 job.setKey( authPasswordHelperKeyName() );
3961 job.setTextData( password );
3962 QEventLoop loop;
3963 connect( &job, &QKeychain::Job::finished, &loop, &QEventLoop::quit );
3964 job.start();
3965 loop.exec();
3966 if ( job.error() )
3967 {
3968 mPasswordHelperErrorCode = job.error();
3969 mPasswordHelperErrorMessage = tr( "Storing password in the %1 failed: %2." ).arg( passwordHelperDisplayName(), job.errorString() );
3970 // Signals used in the tests to exit main application loop
3971 emit passwordHelperFailure();
3972 result = false;
3973 }
3974 else
3975 {
3976 passwordHelperClearErrors();
3977 // Signals used in the tests to exit main application loop
3978 emit passwordHelperSuccess();
3979 result = true;
3980 }
3981 passwordHelperProcessError();
3982 return result;
3983#else
3984 Q_UNUSED( password )
3985 return false;
3986#endif
3987}
3988
3990{
3991#ifdef HAVE_AUTH
3992 // Does the user want to store the password in the wallet?
3993 QgsSettings settings;
3994 return settings.value( u"use_password_helper"_s, true, QgsSettings::Section::Auth ).toBool();
3995#else
3996 return false;
3997#endif
3998}
3999
4001{
4002#ifdef HAVE_AUTH
4003 QgsSettings settings;
4004 settings.setValue( u"use_password_helper"_s, enabled, QgsSettings::Section::Auth );
4005 emit messageLog( enabled ? tr( "Your %1 will be <b>used from now</b> on to store and retrieve the master password." )
4006 .arg( passwordHelperDisplayName() ) :
4007 tr( "Your %1 will <b>not be used anymore</b> to store and retrieve the master password." )
4008 .arg( passwordHelperDisplayName() ) );
4009#else
4010 Q_UNUSED( enabled )
4011#endif
4012}
4013
4015{
4016#ifdef HAVE_AUTH
4017 // Does the user want to store the password in the wallet?
4018 QgsSettings settings;
4019 return settings.value( u"password_helper_logging"_s, false, QgsSettings::Section::Auth ).toBool();
4020#else
4021 return false;
4022#endif
4023}
4024
4026{
4027#ifdef HAVE_AUTH
4028 QgsSettings settings;
4029 settings.setValue( u"password_helper_logging"_s, enabled, QgsSettings::Section::Auth );
4030#else
4031 Q_UNUSED( enabled )
4032#endif
4033}
4034
4035void QgsAuthManager::passwordHelperClearErrors()
4036{
4037#ifdef HAVE_AUTH
4038 mPasswordHelperErrorCode = QKeychain::NoError;
4039 mPasswordHelperErrorMessage.clear();
4040#endif
4041}
4042
4043void QgsAuthManager::passwordHelperProcessError()
4044{
4045#ifdef HAVE_AUTH
4047
4048 if ( mPasswordHelperErrorCode == QKeychain::AccessDenied ||
4049 mPasswordHelperErrorCode == QKeychain::AccessDeniedByUser ||
4050 mPasswordHelperErrorCode == QKeychain::NoBackendAvailable ||
4051 mPasswordHelperErrorCode == QKeychain::NotImplemented )
4052 {
4053 // If the error is permanent or the user denied access to the wallet
4054 // we also want to disable the wallet system to prevent annoying
4055 // notification on each subsequent access.
4056 setPasswordHelperEnabled( false );
4057 mPasswordHelperErrorMessage = tr( "There was an error and integration with your %1 has been disabled. "
4058 "You can re-enable it at any time through the \"Utilities\" menu "
4059 "in the Authentication pane of the options dialog. %2" )
4060 .arg( passwordHelperDisplayName(), mPasswordHelperErrorMessage );
4061 }
4062 if ( mPasswordHelperErrorCode != QKeychain::NoError )
4063 {
4064 // We've got an error from the wallet
4065 passwordHelperLog( tr( "Error in %1: %2" ).arg( passwordHelperDisplayName(), mPasswordHelperErrorMessage ) );
4066 emit passwordHelperMessageLog( mPasswordHelperErrorMessage, authManTag(), Qgis::MessageLevel::Critical );
4067 }
4068 passwordHelperClearErrors();
4069#endif
4070}
4071
4072
4073bool QgsAuthManager::masterPasswordInput()
4074{
4075#ifdef HAVE_AUTH
4077
4078 if ( isDisabled() )
4079 return false;
4080
4081 QString pass;
4082 bool storedPasswordIsValid = false;
4083 bool ok = false;
4084
4085 // Read the password from the wallet
4086 if ( passwordHelperEnabled() )
4087 {
4088 bool readOk = false;
4089 pass = passwordHelperRead( readOk );
4090 if ( readOk && ! pass.isEmpty() && ( mPasswordHelperErrorCode == QKeychain::NoError ) )
4091 {
4092 // Let's check the password!
4093 if ( verifyMasterPassword( pass ) )
4094 {
4095 ok = true;
4096 storedPasswordIsValid = true;
4097 }
4098 else
4099 {
4100 emit passwordHelperMessageLog( tr( "Master password stored in the %1 is not valid" ).arg( passwordHelperDisplayName() ), authManTag(), Qgis::MessageLevel::Warning );
4101 }
4102 }
4103 }
4104
4105 if ( ! ok )
4106 {
4107 pass.clear();
4109 }
4110
4111 if ( ok && !pass.isEmpty() && mMasterPass != pass )
4112 {
4113 mMasterPass = pass;
4114 if ( passwordHelperEnabled() && ! storedPasswordIsValid )
4115 {
4116 if ( !passwordHelperWrite( pass ) )
4117 {
4118 emit passwordHelperMessageLog( tr( "Master password could not be written to the %1" ).arg( passwordHelperDisplayName() ), authManTag(), Qgis::MessageLevel::Warning );
4119 }
4120 }
4121 return true;
4122 }
4123 return false;
4124#else
4125 return false;
4126#endif
4127}
4128
4129bool QgsAuthManager::masterPasswordRowsInDb( int &rows ) const
4130{
4131#ifdef HAVE_AUTH
4132 bool res = false;
4134
4135 if ( isDisabled() )
4136 return res;
4137
4138 rows = 0;
4139
4140 QMutexLocker locker( mMutex.get() );
4141
4142 // Loop through all storages with capability ReadMasterPassword and count the number of master passwords
4144
4145 if ( storages.empty() )
4146 {
4147 emit messageLog( tr( "Could not connect to any authentication configuration storage." ), authManTag(), Qgis::MessageLevel::Critical );
4148 }
4149 else
4150 {
4151 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4152 {
4153 try
4154 {
4155 rows += storage->masterPasswords( ).count();
4156 // if we successfully queuried at least one storage, the result from this function must be true
4157 res = true;
4158 }
4159 catch ( const QgsNotSupportedException &e )
4160 {
4161 // It should not happen because we are checking the capability in advance
4163 }
4164 }
4165 }
4166
4167 return res;
4168#else
4169 Q_UNUSED( rows )
4170 return false;
4171#endif
4172}
4173
4175{
4176#ifdef HAVE_AUTH
4178
4179 if ( isDisabled() )
4180 return false;
4181
4182 int rows = 0;
4183 if ( !masterPasswordRowsInDb( rows ) )
4184 {
4185 const char *err = QT_TR_NOOP( "Master password: FAILED to access database" );
4186 QgsDebugError( err );
4188
4189 return false;
4190 }
4191 return ( rows == 1 );
4192#else
4193 return false;
4194#endif
4195}
4196
4197bool QgsAuthManager::masterPasswordCheckAgainstDb( const QString &compare ) const
4198{
4199#ifdef HAVE_AUTH
4201
4202 if ( isDisabled() )
4203 return false;
4204
4205 // Only check the default DB
4206 if ( QgsAuthConfigurationStorage *defaultStorage = firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability::ReadMasterPassword ) )
4207 {
4208 try
4209 {
4210 const QList<QgsAuthConfigurationStorage::MasterPasswordConfig> passwords { defaultStorage->masterPasswords( ) };
4211 if ( passwords.size() == 0 )
4212 {
4213 emit messageLog( tr( "Master password: FAILED to access database" ), authManTag(), Qgis::MessageLevel::Critical );
4214 return false;
4215 }
4216 const QgsAuthConfigurationStorage::MasterPasswordConfig storedPassword { passwords.first() };
4217 return QgsAuthCrypto::verifyPasswordKeyHash( compare.isNull() ? mMasterPass : compare, storedPassword.salt, storedPassword.hash );
4218 }
4219 catch ( const QgsNotSupportedException &e )
4220 {
4221 // It should not happen because we are checking the capability in advance
4223 return false;
4224 }
4225
4226 }
4227 else
4228 {
4229 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
4230 return false;
4231 }
4232#else
4233 Q_UNUSED( compare )
4234 return false;
4235#endif
4236}
4237
4238bool QgsAuthManager::masterPasswordStoreInDb() const
4239{
4240#ifdef HAVE_AUTH
4242
4243 if ( isDisabled() )
4244 return false;
4245
4246 QString salt, hash, civ;
4247 QgsAuthCrypto::passwordKeyHash( mMasterPass, &salt, &hash, &civ );
4248
4249 // Only store in the default DB
4250 if ( QgsAuthConfigurationStorage *defaultStorage = firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability::CreateMasterPassword ) )
4251 {
4252 try
4253 {
4254 return defaultStorage->storeMasterPassword( { salt, civ, hash } );
4255 }
4256 catch ( const QgsNotSupportedException &e )
4257 {
4258 // It should not happen because we are checking the capability in advance
4260 return false;
4261 }
4262 }
4263 else
4264 {
4265 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
4266 return false;
4267 }
4268#else
4269 return false;
4270#endif
4271}
4272
4273bool QgsAuthManager::masterPasswordClearDb()
4274{
4275#ifdef HAVE_AUTH
4277
4278 if ( isDisabled() )
4279 return false;
4280
4281 if ( QgsAuthConfigurationStorage *defaultStorage = firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability::DeleteMasterPassword ) )
4282 {
4283
4284 try
4285 {
4286 return defaultStorage->clearMasterPasswords();
4287 }
4288 catch ( const QgsNotSupportedException &e )
4289 {
4290 // It should not happen because we are checking the capability in advance
4292 return false;
4293 }
4294
4295 }
4296 else
4297 {
4298 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
4299 return false;
4300 }
4301#else
4302 return false;
4303#endif
4304}
4305
4306const QString QgsAuthManager::masterPasswordCiv() const
4307{
4308#ifdef HAVE_AUTH
4310
4311 if ( isDisabled() )
4312 return QString();
4313
4314 if ( QgsAuthConfigurationStorage *defaultStorage = firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability::ReadMasterPassword ) )
4315 {
4316 try
4317 {
4318 const QList<QgsAuthConfigurationStorage::MasterPasswordConfig> passwords { defaultStorage->masterPasswords( ) };
4319 if ( passwords.size() == 0 )
4320 {
4321 emit messageLog( tr( "Master password: FAILED to access database" ), authManTag(), Qgis::MessageLevel::Critical );
4322 return QString();
4323 }
4324 return passwords.first().civ;
4325 }
4326 catch ( const QgsNotSupportedException &e )
4327 {
4328 // It should not happen because we are checking the capability in advance
4330 return QString();
4331 }
4332 }
4333 else
4334 {
4335 emit messageLog( tr( "Could not connect to the default storage." ), authManTag(), Qgis::MessageLevel::Critical );
4336 return QString();
4337 }
4338#else
4339 return QString();
4340#endif
4341}
4342
4343QStringList QgsAuthManager::configIds() const
4344{
4345#ifdef HAVE_AUTH
4347
4348 QStringList configKeys = QStringList();
4349
4350 if ( isDisabled() )
4351 return configKeys;
4352
4353 // Loop through all storages with capability ReadConfiguration and get the config ids
4355
4356 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4357 {
4358 try
4359 {
4360 const QgsAuthMethodConfigsMap configs = storage->authMethodConfigs();
4361 // Check if the config ids are already in the list
4362 for ( auto it = configs.cbegin(); it != configs.cend(); ++it )
4363 {
4364 if ( !configKeys.contains( it.key() ) )
4365 {
4366 configKeys.append( it.key() );
4367 }
4368 else
4369 {
4370 emit messageLog( tr( "Config id %1 is already in the list" ).arg( it.key() ), authManTag(), Qgis::MessageLevel::Warning );
4371 }
4372 }
4373 }
4374 catch ( const QgsNotSupportedException &e )
4375 {
4376 // It should not happen because we are checking the capability in advance
4378 }
4379 }
4380
4381 return configKeys;
4382#else
4383 return QStringList();
4384#endif
4385}
4386
4387bool QgsAuthManager::verifyPasswordCanDecryptConfigs() const
4388{
4389#ifdef HAVE_AUTH
4391
4392 if ( isDisabled() )
4393 return false;
4394
4395 // no need to check for setMasterPassword, since this is private and it will be set
4396
4397 // Loop through all storages with capability ReadConfiguration and check if the password can decrypt the configs
4399
4400 for ( const QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4401 {
4402
4403 if ( ! storage->isEncrypted() )
4404 {
4405 continue;
4406 }
4407
4408 try
4409 {
4410 const QgsAuthMethodConfigsMap configs = storage->authMethodConfigsWithPayload();
4411 for ( auto it = configs.cbegin(); it != configs.cend(); ++it )
4412 {
4413 QString configstring( QgsAuthCrypto::decrypt( mMasterPass, masterPasswordCiv(), it.value().config( u"encrypted_payload"_s ) ) );
4414 if ( configstring.isEmpty() )
4415 {
4416 QgsDebugError( u"Verify password can decrypt configs FAILED, could not decrypt a config (id: %1) from storage %2"_s
4417 .arg( it.key(), storage->name() ) );
4418 return false;
4419 }
4420 }
4421 }
4422 catch ( const QgsNotSupportedException &e )
4423 {
4424 // It should not happen because we are checking the capability in advance
4426 return false;
4427 }
4428
4429 }
4430
4431 if ( storages.empty() )
4432 {
4433 emit messageLog( tr( "Could not connect to any authentication configuration storage." ), authManTag(), Qgis::MessageLevel::Critical );
4434 return false;
4435 }
4436
4437 return true;
4438#else
4439 return false;
4440#endif
4441}
4442
4443bool QgsAuthManager::reencryptAllAuthenticationConfigs( const QString &prevpass, const QString &prevciv )
4444{
4445#ifdef HAVE_AUTH
4447
4448 if ( isDisabled() )
4449 return false;
4450
4451 bool res = true;
4452 const QStringList ids = configIds();
4453 for ( const auto &configid : ids )
4454 {
4455 res = res && reencryptAuthenticationConfig( configid, prevpass, prevciv );
4456 }
4457 return res;
4458#else
4459 Q_UNUSED( prevpass )
4460 Q_UNUSED( prevciv )
4461 return false;
4462#endif
4463}
4464
4465bool QgsAuthManager::reencryptAuthenticationConfig( const QString &authcfg, const QString &prevpass, const QString &prevciv )
4466{
4467#ifdef HAVE_AUTH
4469
4470 if ( isDisabled() )
4471 return false;
4472
4473 // no need to check for setMasterPassword, since this is private and it will be set
4474
4475 // Loop through all storages with capability ReadConfiguration and reencrypt the config
4477
4478 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4479 {
4480 try
4481 {
4482 if ( storage->methodConfigExists( authcfg ) )
4483 {
4484 if ( ! storage->isEncrypted() )
4485 {
4486 return true;
4487 }
4488
4489 QString payload;
4490 const QgsAuthMethodConfig config = storage->loadMethodConfig( authcfg, payload, true );
4491 if ( payload.isEmpty() || ! config.isValid( true ) )
4492 {
4493 QgsDebugError( u"Reencrypt FAILED, could not find config (id: %1)"_s.arg( authcfg ) );
4494 return false;
4495 }
4496
4497 QString configstring( QgsAuthCrypto::decrypt( prevpass, prevciv, payload ) );
4498 if ( configstring.isEmpty() )
4499 {
4500 QgsDebugError( u"Reencrypt FAILED, could not decrypt config (id: %1)"_s.arg( authcfg ) );
4501 return false;
4502 }
4503
4504 configstring = QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), configstring );
4505
4506 if ( !storage->storeMethodConfig( config, configstring ) )
4507 {
4508 emit messageLog( tr( "Store config: FAILED to store config in default storage: %1" ).arg( storage->lastError() ), authManTag(), Qgis::MessageLevel::Warning );
4509 return false;
4510 }
4511 return true;
4512 }
4513 }
4514 catch ( const QgsNotSupportedException &e )
4515 {
4516 // It should not happen because we are checking the capability in advance
4518 return false;
4519 }
4520 }
4521
4522 if ( storages.empty() )
4523 {
4524 emit messageLog( tr( "Could not connect to any authentication configuration storage." ), authManTag(), Qgis::MessageLevel::Critical );
4525 }
4526 else
4527 {
4528 emit messageLog( tr( "Reencrypt FAILED, could not find config (id: %1)" ).arg( authcfg ), authManTag(), Qgis::MessageLevel::Critical );
4529 }
4530
4531 return false;
4532#else
4533 Q_UNUSED( authcfg )
4534 Q_UNUSED( prevpass )
4535 Q_UNUSED( prevciv )
4536 return false;
4537#endif
4538}
4539
4540bool QgsAuthManager::reencryptAllAuthenticationSettings( const QString &prevpass, const QString &prevciv )
4541{
4543
4544 // TODO: start remove (when function is actually used)
4545 Q_UNUSED( prevpass )
4546 Q_UNUSED( prevciv )
4547 return true;
4548 // end remove
4549
4550#if 0
4551 if ( isDisabled() )
4552 return false;
4553
4555 // When adding settings that require encryption, add to list //
4557
4558 QStringList encryptedsettings;
4559 encryptedsettings << "";
4560
4561 for ( const auto & sett, std::as_const( encryptedsettings ) )
4562 {
4563 if ( sett.isEmpty() || !existsAuthSetting( sett ) )
4564 continue;
4565
4566 // no need to check for setMasterPassword, since this is private and it will be set
4567
4568 QSqlQuery query( authDbConnection() );
4569
4570 query.prepare( QStringLiteral( "SELECT value FROM %1 "
4571 "WHERE setting = :setting" ).arg( authDbSettingsTable() ) );
4572
4573 query.bindValue( ":setting", sett );
4574
4575 if ( !authDbQuery( &query ) )
4576 return false;
4577
4578 if ( !query.isActive() || !query.isSelect() )
4579 {
4580 QgsDebugError( u"Reencrypt FAILED, query not active or a select operation for setting: %2"_s.arg( sett ) );
4581 return false;
4582 }
4583
4584 if ( query.first() )
4585 {
4586 QString settvalue( QgsAuthCrypto::decrypt( prevpass, prevciv, query.value( 0 ).toString() ) );
4587
4588 query.clear();
4589
4590 query.prepare( QStringLiteral( "UPDATE %1 "
4591 "SET value = :value "
4592 "WHERE setting = :setting" ).arg( authDbSettingsTable() ) );
4593
4594 query.bindValue( ":setting", sett );
4595 query.bindValue( ":value", QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), settvalue ) );
4596
4597 if ( !authDbStartTransaction() )
4598 return false;
4599
4600 if ( !authDbQuery( &query ) )
4601 return false;
4602
4603 if ( !authDbCommit() )
4604 return false;
4605
4606 QgsDebugMsgLevel( u"Reencrypt SUCCESS for setting: %2"_s.arg( sett ), 2 );
4607 return true;
4608 }
4609 else
4610 {
4611 QgsDebugError( u"Reencrypt FAILED, could not find in db setting: %2"_s.arg( sett ) );
4612 return false;
4613 }
4614
4615 if ( query.next() )
4616 {
4617 QgsDebugError( u"Select contains more than one for setting: %1"_s.arg( sett ) );
4618 emit messageOut( tr( "Authentication database contains duplicate setting keys" ), authManTag(), WARNING );
4619 }
4620
4621 return false;
4622 }
4623
4624 return true;
4625#endif
4626}
4627
4628bool QgsAuthManager::reencryptAllAuthenticationIdentities( const QString &prevpass, const QString &prevciv )
4629{
4630#ifdef HAVE_AUTH
4632
4633 if ( isDisabled() )
4634 return false;
4635
4636 bool res = true;
4637 const QStringList ids = certIdentityIds();
4638 for ( const auto &identid : ids )
4639 {
4640 res = res && reencryptAuthenticationIdentity( identid, prevpass, prevciv );
4641 }
4642 return res;
4643#else
4644 Q_UNUSED( prevpass )
4645 Q_UNUSED( prevciv )
4646 return false;
4647#endif
4648}
4649
4650bool QgsAuthManager::reencryptAuthenticationIdentity(
4651 const QString &identid,
4652 const QString &prevpass,
4653 const QString &prevciv )
4654{
4655#ifdef HAVE_AUTH
4657
4658 if ( isDisabled() )
4659 return false;
4660
4661 // no need to check for setMasterPassword, since this is private and it will be set
4662
4663 // Loop through all storages with capability ReadCertificateIdentity and reencrypt the identity
4665
4666
4667 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4668 {
4669
4670 try
4671 {
4672
4673 if ( storage->certIdentityExists( identid ) )
4674 {
4675 if ( ! storage->isEncrypted() )
4676 {
4677 return true;
4678 }
4679
4680 const QPair<QSslCertificate, QString> identityBundle = storage->loadCertIdentityBundle( identid );
4681 QString keystring( QgsAuthCrypto::decrypt( prevpass, prevciv, identityBundle.second ) );
4682 if ( keystring.isEmpty() )
4683 {
4684 QgsDebugError( u"Reencrypt FAILED, could not decrypt identity id: %1"_s.arg( identid ) );
4685 return false;
4686 }
4687
4688 keystring = QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), keystring );
4689 return storage->storeCertIdentity( identityBundle.first, keystring );
4690 }
4691 }
4692 catch ( const QgsNotSupportedException &e )
4693 {
4694 // It should not happen because we are checking the capability in advance
4696 return false;
4697 }
4698 }
4699
4700 if ( storages.empty() )
4701 {
4702 emit messageLog( tr( "Could not connect to any authentication configuration storage." ), authManTag(), Qgis::MessageLevel::Critical );
4703 }
4704 else
4705 {
4706 emit messageLog( tr( "Reencrypt FAILED, could not find identity (id: %1)" ).arg( identid ), authManTag(), Qgis::MessageLevel::Critical );
4707 }
4708
4709 return false;
4710#else
4711 Q_UNUSED( identid )
4712 Q_UNUSED( prevpass )
4713 Q_UNUSED( prevciv )
4714 return false;
4715#endif
4716}
4717
4718#ifndef QT_NO_SSL
4719void QgsAuthManager::insertCaCertInCache( QgsAuthCertUtils::CaCertSource source, const QList<QSslCertificate> &certs )
4720{
4721#ifdef HAVE_AUTH
4723
4724 for ( const auto &cert : certs )
4725 {
4726 mCaCertsCache.insert( QgsAuthCertUtils::shaHexForCert( cert ),
4727 QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate>( source, cert ) );
4728 }
4729#else
4730 Q_UNUSED( source )
4731 Q_UNUSED( certs )
4732#endif
4733}
4734#endif
4735
4736QString QgsAuthManager::authPasswordHelperKeyName() const
4737{
4738#ifdef HAVE_AUTH
4740
4741 QString dbProfilePath;
4742
4743 // TODO: get the current profile name from the application
4744
4745 if ( isFilesystemBasedDatabase( mAuthDatabaseConnectionUri ) )
4746 {
4747 const QFileInfo info( mAuthDatabaseConnectionUri );
4748 dbProfilePath = info.dir().dirName();
4749 }
4750 else
4751 {
4752 dbProfilePath = QCryptographicHash::hash( ( mAuthDatabaseConnectionUri.toUtf8() ), QCryptographicHash::Md5 ).toHex();
4753 }
4754
4755 // if not running from the default profile, ensure that a different key is used
4756 return AUTH_PASSWORD_HELPER_KEY_NAME_BASE + ( dbProfilePath.compare( "default"_L1, Qt::CaseInsensitive ) == 0 ? QString() : dbProfilePath );
4757#else
4758 return QString();
4759#endif
4760}
4761
4763{
4764#ifdef HAVE_AUTH
4766 const auto storages = storageRegistry->readyStorages( );
4767 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4768 {
4769 if ( qobject_cast<QgsAuthConfigurationStorageDb *>( storage ) )
4770 {
4771 return static_cast<QgsAuthConfigurationStorageDb *>( storage );
4772 }
4773 }
4774#endif
4775 return nullptr;
4776}
4777
4778QgsAuthConfigurationStorage *QgsAuthManager::firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability capability ) const
4779{
4780#ifdef HAVE_AUTH
4782 return storageRegistry->firstReadyStorageWithCapability( capability );
4783#else
4784 Q_UNUSED( capability )
4785 return nullptr;
4786#endif
4787}
MessageLevel
Level for messages This will be used both for message log and message bar in application.
Definition qgis.h:159
@ Warning
Warning message.
Definition qgis.h:161
@ Critical
Critical/error message.
Definition qgis.h:162
@ Info
Information message.
Definition qgis.h:160
AuthConfigurationStorageCapability
Authentication configuration storage capabilities.
Definition qgis.h:105
@ CreateSetting
Can create a new authentication setting.
Definition qgis.h:141
@ CreateConfiguration
Can create a new authentication configuration.
Definition qgis.h:111
@ ClearStorage
Can clear all configurations from storage.
Definition qgis.h:106
@ DeleteCertificateAuthority
Can delete a certificate authority.
Definition qgis.h:125
@ DeleteSslCertificateCustomConfig
Can delete a SSL certificate custom config.
Definition qgis.h:120
@ DeleteSetting
Can delete the authentication setting.
Definition qgis.h:140
@ ReadSslCertificateCustomConfig
Can read a SSL certificate custom config.
Definition qgis.h:118
@ DeleteMasterPassword
Can delete the master password.
Definition qgis.h:135
@ CreateSslCertificateCustomConfig
Can create a new SSL certificate custom config.
Definition qgis.h:121
@ ReadCertificateTrustPolicy
Can read a certificate trust policy.
Definition qgis.h:128
@ ReadConfiguration
Can read an authentication configuration.
Definition qgis.h:108
@ UpdateConfiguration
Can update an authentication configuration.
Definition qgis.h:109
@ ReadCertificateAuthority
Can read a certificate authority.
Definition qgis.h:123
@ CreateCertificateAuthority
Can create a new certificate authority.
Definition qgis.h:126
@ DeleteConfiguration
Can deleet an authentication configuration.
Definition qgis.h:110
@ ReadSetting
Can read the authentication settings.
Definition qgis.h:138
@ CreateCertificateIdentity
Can create a new certificate identity.
Definition qgis.h:116
@ ReadCertificateIdentity
Can read a certificate identity.
Definition qgis.h:113
@ CreateCertificateTrustPolicy
Can create a new certificate trust policy.
Definition qgis.h:131
@ ReadMasterPassword
Can read the master password.
Definition qgis.h:133
@ CreateMasterPassword
Can create a new master password.
Definition qgis.h:136
@ DeleteCertificateTrustPolicy
Can delete a certificate trust policy.
Definition qgis.h:130
CertTrustPolicy
Type of certificate trust policy.
CaCertSource
Type of CA certificate source.
Configuration container for SSL server connection exceptions or overrides.
bool isNull() const
Whether configuration is null (missing components).
const QList< QSslError::SslError > sslIgnoredErrorEnums() const
SSL server errors (as enum list) to ignore in connections.
const QSslCertificate sslCertificate() const
Server certificate object.
const QString sslHostPort() const
Server host:port string.
QSqlDatabase based implementation of QgsAuthConfigurationStorage.
bool removeCertTrustPolicy(const QSslCertificate &cert) override
Remove certificate trust policy.
const QgsAuthConfigSslServer loadSslCertCustomConfigByHost(const QString &hostport) const override
Loads an SSL certificate custom config by hostport (host:port).
QString loadAuthSetting(const QString &key) const override
Load an authentication setting from the storage.
bool removeAuthSetting(const QString &key) override
Remove an authentication setting from the storage.
const QMap< QString, QgsAuthCertUtils::CertTrustPolicy > caCertsPolicy() const override
Returns the map of CA certificates hashes in the storages and their trust policy.
QgsAuthCertUtils::CertTrustPolicy loadCertTrustPolicy(const QSslCertificate &cert) const override
Load certificate trust policy.
bool sslCertCustomConfigExists(const QString &id, const QString &hostport) override
Check if SSL certificate custom config exists.
bool removeCertIdentity(const QSslCertificate &cert) override
Remove a certificate identity from the storage.
const QPair< QSslCertificate, QString > loadCertIdentityBundle(const QString &id) const override
Returns a certificate identity bundle by id (sha hash).
const QList< QgsAuthConfigurationStorage::MasterPasswordConfig > masterPasswords() const override
Returns the list of (encrypted) master passwords stored in the database.
bool methodConfigExists(const QString &id) const override
Check if an authentication configuration exists in the storage.
QStringList certIdentityIds() const override
certIdentityIds get list of certificate identity ids from database
bool initialize() override
Initializes the storage.
bool storeMethodConfig(const QgsAuthMethodConfig &mconfig, const QString &payload) override
Store an authentication config in the database.
bool removeCertAuthority(const QSslCertificate &cert) override
Remove a certificate authority.
const QSslCertificate loadCertIdentity(const QString &id) const override
certIdentity get a certificate identity by id (sha hash)
const QList< QgsAuthConfigSslServer > sslCertCustomConfigs() const override
sslCertCustomConfigs get SSL certificate custom configs
QgsAuthMethodConfigsMap authMethodConfigs(const QStringList &allowedMethods=QStringList()) const override
Returns a mapping of authentication configurations available from this storage.
const QList< QSslCertificate > caCerts() const override
Returns the list of CA certificates in the storage.
bool certTrustPolicyExists(const QSslCertificate &cert) const override
Check if certificate trust policy exists.
const QSslCertificate loadCertAuthority(const QString &id) const override
certAuthority get a certificate authority by id (sha hash)
bool removeMethodConfig(const QString &id) override
Removes the authentication configuration with the specified id.
QgsAuthMethodConfigsMap authMethodConfigsWithPayload() const override
Returns a mapping of authentication configurations available from this storage.
bool certIdentityExists(const QString &id) const override
Check if the certificate identity exists.
bool certAuthorityExists(const QSslCertificate &cert) const override
Check if a certificate authority exists.
QgsAuthMethodConfig loadMethodConfig(const QString &id, QString &payload, bool full=false) const override
Load an authentication configuration from the database.
bool storeCertIdentity(const QSslCertificate &cert, const QString &keyPem) override
Store a certificate identity in the storage.
bool removeSslCertCustomConfig(const QString &id, const QString &hostport) override
Remove an SSL certificate custom config.
const QList< QSslCertificate > certIdentities() const override
certIdentities get certificate identities
QString name() const override
Returns a human readable localized short name of the storage implementation (e.g "SQLite").
bool authSettingExists(const QString &key) const override
Check if an authentication setting exists in the storage.
const QgsAuthConfigSslServer loadSslCertCustomConfig(const QString &id, const QString &hostport) const override
Loads an SSL certificate custom config by id (sha hash) and hostport (host:port).
Registry for authentication configuration storages.
QgsAuthConfigurationStorage * firstReadyStorageWithCapability(Qgis::AuthConfigurationStorageCapability capability) const
Returns the first ready (and enabled) authentication configuration storage which has the required cap...
QList< QgsAuthConfigurationStorage * > storages() const
Returns the list of all registered authentication configuration storages.
QList< QgsAuthConfigurationStorage * > readyStoragesWithCapability(Qgis::AuthConfigurationStorageCapability capability) const
Returns the list of all ready (and enabled) authentication configuration storage with the required ca...
QList< QgsAuthConfigurationStorage * > readyStorages() const
Returns the list of all ready (and enabled) authentication configuration storage.
bool addStorage(QgsAuthConfigurationStorage *storage)
Add an authentication configuration storage to the registry.
Abstract class that defines the interface for all authentication configuration storage implementation...
void messageLog(const QString &message, const QString &tag=u"Authentication"_s, Qgis::MessageLevel level=Qgis::MessageLevel::Info)
Custom logging signal to relay to console output and QgsMessageLog.
virtual void setReadOnly(bool readOnly)
Utility method to unset all editing capabilities.
void methodConfigChanged()
Emitted when the storage method config table was changed.
Qgis::AuthConfigurationStorageCapabilities capabilities() const
Returns the capabilities of the storage.
bool isEnabled() const
Returns true if the storage is enabled.
bool isEncrypted() const
Returns true if the storage is encrypted.
virtual QString lastError() const
Returns the last error message.
static void passwordKeyHash(const QString &pass, QString *salt, QString *hash, QString *cipheriv=nullptr)
Generate SHA256 hash for master password, with iterations and salt.
static const QString encrypt(const QString &pass, const QString &cipheriv, const QString &text)
Encrypt data using master password.
static bool verifyPasswordKeyHash(const QString &pass, const QString &salt, const QString &hash, QString *hashderived=nullptr)
Verify existing master password hash to a re-generated one.
static const QString decrypt(const QString &pass, const QString &cipheriv, const QString &text)
Decrypt data using master password.
Singleton which offers an interface to manage the authentication configuration database and to utiliz...
bool storeAuthSetting(const QString &key, const QVariant &value, bool encrypt=false)
Stores an authentication setting.
bool setDefaultCertTrustPolicy(QgsAuthCertUtils::CertTrustPolicy policy)
Sets the default certificate trust policy preferred by user.
void clearAllCachedConfigs()
Clear all authentication configs from authentication method caches.
const QSslCertificate certIdentity(const QString &id)
certIdentity get a certificate identity by id (sha hash)
const QStringList certIdentityBundleToPem(const QString &id)
certIdentityBundleToPem get a certificate identity bundle by id (sha hash) returned as PEM text
bool updateIgnoredSslErrorsCache(const QString &shahostport, const QList< QSslError > &errors)
Update ignored SSL error cache with possible ignored SSL errors, using sha:host:port key.
bool verifyMasterPassword(const QString &compare=QString())
Verify the supplied master password against any existing hash in authentication database.
bool updateIgnoredSslErrorsCacheFromConfig(const QgsAuthConfigSslServer &config)
Update ignored SSL error cache with possible ignored SSL errors, using server config.
const QString disabledMessage() const
Standard message for when QCA's qca-ossl plugin is missing and system is disabled.
const QList< QSslCertificate > trustedCaCertsCache()
trustedCaCertsCache cache of trusted certificate authorities, ready for network connections
QgsAuthMethod * configAuthMethod(const QString &authcfg)
Gets authentication method from the config/provider cache.
static bool isFilesystemBasedDatabase(const QString &uri)
Returns the true if the uri is a filesystem-based database (SQLite).
bool storeCertIdentity(const QSslCertificate &cert, const QSslKey &key)
Store a certificate identity.
QgsAuthMethodsMap authMethodsMap(const QString &dataprovider=QString())
Gets available authentication methods mapped to their key.
bool rebuildIgnoredSslErrorCache()
Rebuild ignoredSSL error cache.
bool initSslCaches()
Initialize various SSL authentication caches.
const QList< QSslCertificate > extraFileCAs()
extraFileCAs extra file-based certificate authorities
bool removeAuthSetting(const QString &key)
Remove an authentication setting.
bool storeCertTrustPolicy(const QSslCertificate &cert, QgsAuthCertUtils::CertTrustPolicy policy)
Store user trust value for a certificate.
bool rebuildCaCertsCache()
Rebuild certificate authority cache.
bool scheduledAuthDatabaseErase()
Whether there is a scheduled opitonal erase of authentication database.
bool eraseAuthenticationDatabase(bool backup, QString *backuppath=nullptr)
Erase all rows from all tables in authentication database.
static bool passwordHelperEnabled()
Password helper enabled getter.
void passwordHelperMessageLog(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level=Qgis::MessageLevel::Info)
Custom logging signal to inform the user about master password <-> password manager interactions.
bool exportAuthenticationConfigsToXml(const QString &filename, const QStringList &authcfgs, const QString &password=QString())
Export authentication configurations to an XML file.
QString sqliteDatabasePath() const
Returns the path to the authentication database file or an empty string if the database is not SQLite...
Q_DECL_DEPRECATED bool init(const QString &pluginPath=QString(), const QString &authDatabasePath=QString())
init initialize QCA, prioritize qca-ossl plugin and optionally set up the authentication database
void authDatabaseChanged()
Emitted when the authentication db is significantly changed, e.g. large record removal,...
void setPasswordHelperEnabled(bool enabled)
Password helper enabled setter.
void setScheduledAuthDatabaseErase(bool scheduleErase)
Schedule an optional erase of authentication database, starting when mutex is lockable.
const QList< QgsAuthConfigSslServer > sslCertCustomConfigs()
sslCertCustomConfigs get SSL certificate custom configs
const QList< QSslCertificate > untrustedCaCerts(QList< QSslCertificate > trustedCAs=QList< QSslCertificate >())
untrustedCaCerts get list of untrusted certificate authorities
const QString uniqueConfigId() const
Gets a unique generated 7-character string to assign to as config id.
const QPair< QSslCertificate, QSslKey > certIdentityBundle(const QString &id)
Gets a certificate identity bundle by id (sha hash).
bool isDisabled() const
Whether QCA has the qca-ossl plugin, which a base run-time requirement.
QVariant authSetting(const QString &key, const QVariant &defaultValue=QVariant(), bool decrypt=false)
Returns a previously set authentication setting.
static const QString AUTH_MAN_TAG
The display name of the Authentication Manager.
QgsAuthCertUtils::CertTrustPolicy defaultCertTrustPolicy()
Gets the default certificate trust policy preferred by user.
const QByteArray trustedCaCertsPemText()
trustedCaCertsPemText get concatenated string of all trusted CA certificates
static bool hasConfigId(const QString &txt)
Returns whether a string includes an authcfg ID token.
bool removeAllAuthenticationConfigs()
Clear all authentication configs from table in database and from provider caches.
QgsAuthCertUtils::CertTrustPolicy certificateTrustPolicy(const QSslCertificate &cert)
certificateTrustPolicy get trust policy for a particular certificate cert
static bool passwordHelperLoggingEnabled()
Password helper logging enabled getter.
QgsAuthConfigurationStorageRegistry * authConfigurationStorageRegistry() const
Returns the authentication configuration storage registry.
bool rebuildCertTrustCache()
Rebuild certificate authority cache.
Q_DECL_DEPRECATED const QString authenticationDatabasePath() const
The standard authentication database file in ~/.qgis3/ or defined location.
static const QList< QSslCertificate > systemRootCAs()
systemRootCAs get root system certificate authorities
bool removeCertAuthority(const QSslCertificate &cert)
Remove a certificate authority.
const QList< QSslCertificate > trustedCaCerts(bool includeinvalid=false)
trustedCaCerts get list of all trusted CA certificates
bool existsCertAuthority(const QSslCertificate &cert)
Check if a certificate authority exists.
const QMap< QString, QSslCertificate > mappedDatabaseCAs()
mappedDatabaseCAs get sha1-mapped database-stored certificate authorities
bool importAuthenticationConfigsFromXml(const QString &filename, const QString &password=QString(), bool overwrite=false)
Import authentication configurations from an XML file.
bool configIdUnique(const QString &id) const
Verify if provided authentication id is unique.
static const QgsSettingsEntryBool * settingsGenerateRandomPasswordForPasswordHelper
QStringList configIds() const
Gets list of authentication ids from database.
QString authManTag() const
Simple text tag describing authentication system for message logs.
bool loadAuthenticationConfig(const QString &authcfg, QgsAuthMethodConfig &mconfig, bool full=false)
Load an authentication config from the database into subclass.
QgsAuthCertUtils::CertTrustPolicy certTrustPolicy(const QSslCertificate &cert)
certTrustPolicy get whether certificate cert is trusted by user
bool masterPasswordHashInDatabase() const
Verify a password hash existing in authentication database.
Q_DECL_DEPRECATED void messageOut(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, QgsAuthManager::MessageLevel level=QgsAuthManager::INFO) const
Custom logging signal to relay to console output and QgsMessageLog.
QgsAuthConfigurationStorageDb * defaultDbStorage() const
Transitional proxy to the first ready storage of database type.
bool updateNetworkProxy(QNetworkProxy &proxy, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QNetworkProxy with an authentication config.
const QSslCertificate certAuthority(const QString &id)
Gets a certificate authority by id (sha hash).
void passwordHelperSuccess()
Signals emitted on password helper success, mainly used in the tests to exit main application loop.
bool registerCoreAuthMethods()
Instantiate and register existing C++ core authentication methods from plugins.
bool passwordHelperDelete()
Delete master password from wallet.
~QgsAuthManager() override
void dumpIgnoredSslErrorsCache_()
Utility function to dump the cache for debug purposes.
const QList< QSslCertificate > databaseCAs()
databaseCAs get database-stored certificate authorities
void messageLog(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level=Qgis::MessageLevel::Info) const
Custom logging signal to relay to console output and QgsMessageLog.
bool backupAuthenticationDatabase(QString *backuppath=nullptr)
Close connection to current authentication database and back it up.
void authDatabaseEraseRequested()
Emitted when a user has indicated they may want to erase the authentication db.
void passwordHelperFailure()
Signals emitted on password helper failure, mainly used in the tests to exit main application loop.
bool existsSslCertCustomConfig(const QString &id, const QString &hostport)
Check if SSL certificate custom config exists.
bool existsAuthSetting(const QString &key)
Check if an authentication setting exists.
void clearCachedConfig(const QString &authcfg)
Clear an authentication config from its associated authentication method cache.
void clearMasterPassword()
Clear supplied master password.
bool updateNetworkRequest(QNetworkRequest &request, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QNetworkRequest with an authentication config.
bool createAndStoreRandomMasterPasswordInKeyChain()
Creates a new securely seeded random password and stores it in the system keychain as the new master ...
const QList< QSslCertificate > certIdentities()
certIdentities get certificate identities
bool storeCertAuthority(const QSslCertificate &cert)
Store a certificate authority.
QStringList certIdentityIds() const
certIdentityIds get list of certificate identity ids from database
bool removeCertTrustPolicies(const QList< QSslCertificate > &certs)
Remove a group certificate authorities.
QgsAuthMethod * authMethod(const QString &authMethodKey)
Gets authentication method from the config/provider cache via its key.
bool updateDataSourceUriItems(QStringList &connectionItems, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QgsDataSourceUri with an authentication config.
void setup(const QString &pluginPath=QString(), const QString &authDatabasePath=QString())
Sets up the authentication manager configuration.
const QString passwordHelperErrorMessage()
Error message getter.
Q_DECL_DEPRECATED QSqlDatabase authDatabaseConnection() const
Sets up the application instance of the authentication database connection.
void updateConfigAuthMethods()
Sync the confg/authentication method cache with what is in database.
bool storeSslCertCustomConfig(const QgsAuthConfigSslServer &config)
Store an SSL certificate custom config.
static void setPasswordHelperLoggingEnabled(bool enabled)
Password helper logging enabled setter.
bool ensureInitialized() const
Performs lazy initialization of the authentication framework, if it has not already been done.
const QgsAuthConfigSslServer sslCertCustomConfigByHost(const QString &hostport)
sslCertCustomConfigByHost get an SSL certificate custom config by hostport (host:port)
bool updateAuthenticationConfig(const QgsAuthMethodConfig &config)
Update an authentication config in the database.
bool existsCertIdentity(const QString &id)
Check if a certificate identity exists.
const QString authenticationDatabaseUri() const
Returns the authentication database connection URI.
static const QgsSettingsEntryBool * settingsUsingGeneratedRandomPassword
bool resetMasterPassword(const QString &newpass, const QString &oldpass, bool keepbackup, QString *backuppath=nullptr)
Reset the master password to a new one, then re-encrypts all previous configs with the new password.
QStringList authMethodsKeys(const QString &dataprovider=QString())
Gets keys of supported authentication methods.
bool passwordHelperSync()
Store the password manager into the wallet.
bool masterPasswordIsSet() const
Whether master password has be input and verified, i.e. authentication database is accessible.
const QString methodConfigTableName() const
Returns the database table from the first ready storage that stores authentication configs,...
static QgsAuthManager * instance()
Enforce singleton pattern.
void masterPasswordVerified(bool verified)
Emitted when a password has been verify (or not).
bool setMasterPassword(bool verify=false)
Main call to initially set or continually check master password is set.
bool storeCertAuthorities(const QList< QSslCertificate > &certs)
Store multiple certificate authorities.
bool removeSslCertCustomConfig(const QString &id, const QString &hostport)
Remove an SSL certificate custom config.
bool updateNetworkReply(QNetworkReply *reply, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QNetworkReply with an authentication config (used to skip known SSL errors,...
bool rebuildTrustedCaCertsCache()
Rebuild trusted certificate authorities cache.
const QgsAuthMethodMetadata * authMethodMetadata(const QString &authMethodKey)
Gets authentication method metadata via its key.
bool removeAuthenticationConfig(const QString &authcfg)
Remove an authentication config in the database.
bool removeCertTrustPolicy(const QSslCertificate &cert)
Remove a certificate authority.
const QString authenticationDatabaseUriStripped() const
Returns the authentication database connection URI with the password stripped.
QgsAuthMethod::Expansions supportedAuthMethodExpansions(const QString &authcfg)
Gets supported authentication method expansion(s), e.g.
const QgsAuthConfigSslServer sslCertCustomConfig(const QString &id, const QString &hostport)
sslCertCustomConfig get an SSL certificate custom config by id (sha hash) and hostport (host:port)
QgsAuthMethodConfigsMap availableAuthMethodConfigs(const QString &dataprovider=QString())
Gets mapping of authentication config ids and their base configs (not decrypted data).
bool masterPasswordSame(const QString &password) const
Check whether supplied password is the same as the one already set.
static const QString AUTH_PASSWORD_HELPER_DISPLAY_NAME
The display name of the password helper (platform dependent).
bool storeAuthenticationConfig(QgsAuthMethodConfig &mconfig, bool overwrite=false)
Store an authentication config in the database.
bool verifyStoredPasswordHelperPassword()
Verify the password stored in the password helper.
bool removeCertIdentity(const QString &id)
Remove a certificate identity.
static QString passwordHelperDisplayName(bool titleCase=false)
Returns a translated display name of the password helper (platform dependent).
bool resetMasterPasswordUsingStoredPasswordHelper(const QString &newPassword, bool keepBackup, QString *backupPath=nullptr)
Reset the master password to a new one, hen re-encrypts all previous configs with the new password.
QString configAuthMethodKey(const QString &authcfg) const
Gets key of authentication method associated with config ID.
Configuration storage class for authentication method configurations.
bool isValid(bool validateid=false) const
Whether the configuration is valid.
bool readXml(const QDomElement &element)
from a DOM element.
const QString configString() const
The extended configuration, as stored and retrieved from the authentication database.
const QString id() const
Gets 'authcfg' 7-character alphanumeric ID of the config.
void loadConfigString(const QString &configstr)
Load existing extended configuration.
bool writeXml(QDomElement &parentElement, QDomDocument &document)
Stores the configuration in a DOM.
void setId(const QString &id)
Sets auth config ID.
Holds data auth method key, description, and associated shared library file information.
const QgsAuthMethodMetadata * authMethodMetadata(const QString &authMethodKey) const
Returns metadata of the auth method or nullptr if not found.
static QgsAuthMethodRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
QStringList authMethodList() const
Returns list of available auth methods by their keys.
Abstract base class for authentication method plugins.
virtual bool updateNetworkProxy(QNetworkProxy &proxy, const QString &authcfg, const QString &dataprovider=QString())
Update proxy settings with authentication components.
virtual bool updateNetworkRequest(QNetworkRequest &request, const QString &authcfg, const QString &dataprovider=QString())
Update a network request with authentication components.
QgsAuthMethod::Expansions supportedExpansions() const
Flags that represent the update points (where authentication configurations are expanded) supported b...
virtual void clearCachedConfig(const QString &authcfg)=0
Clear any cached configuration.
virtual void updateMethodConfig(QgsAuthMethodConfig &mconfig)=0
Update an authentication configuration in place.
virtual bool updateNetworkReply(QNetworkReply *reply, const QString &authcfg, const QString &dataprovider=QString())
Update a network reply with authentication components.
virtual bool updateDataSourceUriItems(QStringList &connectionItems, const QString &authcfg, const QString &dataprovider=QString())
Update data source connection items with authentication components.
QFlags< Expansion > Expansions
static QgsCredentials * instance()
retrieves instance
bool getMasterPassword(QString &password, bool stored=false)
QString what() const
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
Custom exception class which is raised when an operation is not supported.
Scoped object for logging of the runtime for a single operation or group of operations.
A boolean settings entry.
static QgsSettingsTreeNode * sTreeAuthentication
Stores settings for use within QGIS.
Definition qgssettings.h:68
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:7486
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:7485
QHash< QString, QgsAuthMethodConfig > QgsAuthMethodConfigsMap
QHash< QString, QgsAuthMethod * > QgsAuthMethodsMap
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59