summaryrefslogtreecommitdiffstats
path: root/src/corelib/kernel/qpermissions.cpp
blob: d0d2d9eb1009c88b5ecad577b5da3209a70a07e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qpermissions.h"
#include "qpermissions_p.h"
#include "qhashfunctions.h"

#include <QtCore/qshareddata.h>
#include <QtCore/qdebug.h>

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(lcPermissions, "qt.permissions", QtWarningMsg);

/*!
    \page permissions.html
    \title Application Permissions
    \brief Managing application permissions

    Many features of today's devices and operating systems can have
    significant privacy, security, and performance implications if
    misused. It's therefore increasingly common for platforms to
    require explicit consent from the user before accessing these
    features.

    The Qt permission APIs allow the application to check or request
    permission for such features in a cross platform manner.

    \section1 Usage

    A feature that commonly requires user consent is access to the
    microphone of the device. An application for recording voice
    memos would perhaps look something like this initially:

    \code
    void VoiceMemoWidget::onRecordingInitiated()
    {
        m_microphone->startRecording();
    }
    \endcode

    To ensure this application works well on platforms that
    require user consent for microphone access we would extend
    it like this:

    \code
    void VoiceMemoWidget::onRecordingInitiated()
    {
        QMicrophonePermission microphonePermission;
        switch (qApp->checkPermission(microphonePermission)) {
        case Qt::PermissionStatus::Undetermined:
            qApp->requestPermission(microphonePermission, this,
                        &VoiceMemoWidget::onRecordingInitiated);
            return;
        case Qt::PermissionStatus::Denied:
            m_permissionInstructionsDialog->show();
            return;
        case Qt::PermissionStatus::Granted:
            m_microphone->startRecording();
        }
    }
    \endcode

    We first check if we already know the status of the microphone permission.
    If we don't we initiate a permission request to determine the current
    status, which will potentially ask the user for consent. We connect the
    result of the request to the slot we're already in, so that we get another
    chance at evaluating the permission status.

    Once the permission status is known, either because we had been granted or
    denied permission at an earlier time, or after getting the result back from
    the request we just initiated, we redirect the user to a dialog explaining
    why we can not record voice memos at this time (if the permission was denied),
    or proceed to using the microphone (if permission was granted).

    \note On \macOS and iOS permissions can currently only be requested for
    GUI applications.

    \section2 Declaring Permissions

    Some platforms require that the permissions you request are declared
    up front at build time.

    \section3 Apple platforms
    \target apple-usage-description

    Each permission you request must be accompanied by a so called
    \e {usage description} string in the application's \c Info.plist
    file, describing why the application needs to access the given
    permission. For example:

    \badcode
        <key>NSMicrophoneUsageDescription</key>
        <string>The microphone is used to record voice memos.</string>
    \endcode

    The relevant usage description keys are described in the documentation
    for each permission type.

    \sa {Information Property List Files}.

    \section3 Android
    \target android-uses-permission

    Each permission you request must be accompanied by a \c uses-permission
    entry in the application's \c AndroidManifest.xml file. For example:

    \badcode
        <manifest ...>
            <uses-permission android:name="android.permission.RECORD_AUDIO"/>
        </manifest>
    \endcode

    The relevant permission names are described in the documentation
    for each permission type.

    \sa {Qt Creator: Editing Manifest Files}.

    \section1 Available Permissions

    The following permissions types are available:

    \annotatedlist permissions

    \section1 Best Practices

    To ensure the best possible user experience for the end user we recommend
    adopting the following best practices for managing application permissions:

    \list

        \li Request the minimal set of permissions needed. For example, if you only
        need access to the microphone, do \e not request camera permission just in case.
        Use the properties of individual permission types to limit the permission scope
        even further, for example QContactsPermission::setReadOnly() to request read
        only access.

        \li Request permissions in response to specific actions by the user. For example,
        defer requesting microphone permission until the user presses the button to record
        audio. Associating the permission request to a specific action gives the user a clearer
        context of why the permission is needed. Do \e not request all needed permission on
        startup.

        \li Present extra context and explanation if needed. Sometimes the action by the user
        is not enough context. Consider presenting an explanation-dialog after the user has
        initiated the action, but before requesting the permission, so the user is aware of
        what's about to happen when the system permission dialog subsequently pops up.

        \li Be transparent and explicit about why permissions are needed. In explanation
        dialogs and usage descriptions, be transparent about why the particular permission
        is needed for your application to provide a specific feature, so users can make
        informed decisions.

        \li Account for denied permissions. The permissions you request may be denied
        for various reasons. You should always account for this situation, by gracefully
        degrading the experience of your application, and presenting clear explanations
        the user about the situation.

        \li Never request permissions from a library. The request of permissions should
        be done as close as possible to the user, where the information needed to make
        good decisions on the points above is available. Libraries can check permissions,
        to ensure they have the prerequisites for doing their work, but if the permission
        is undetermined or denied this should be reflected through the library's API,
        so that the application in turn can request the necessary permissions.

    \endlist
*/


/*!
    \class QPermission
    \inmodule QtCore
    \inheaderfile QPermissions
    \since 6.5
    \brief An opaque wrapper of a typed permission.

    The QPermission class is an opaque wrapper of a \l{typed permission},
    used when checking or requesting permissions. You do not need to construct
    this type explicitly, as the type is automatically used when checking or
    requesting permissions:

    \code
    qApp->checkPermission(QCameraPermission{});
    \endcode

    When requesting permissions, the given functor will
    be passed an instance of a QPermission, which can be used
    to check the result of the request:

    \code
    qApp->requestPermission(QCameraPermission{}, [](const QPermission &permission) {
        if (permission.status() == Qt::PermissionStatus:Granted)
            takePhoto();
    });
    \endcode

    To inspect the properties of the original, typed permission,
    use the \l {QPermission::}{value()} function:

    \code
    QLocationPermission locationPermission;
    locationPermission.setAccuracy(QLocationPermission::Precise);
    qApp->requestPermission(locationPermission, this, &LocationWidget::permissionUpdated);
    \endcode

    \code
    void LocationWidget::permissionUpdated(const QPermission &permission)
    {
        if (permission.status() != Qt::PermissionStatus:Granted)
            return;
        auto locationPermission = permission.value<QLocationPermission>();
        if (!locationPermission || locationPermission->accuracy() != QLocationPermission::Precise)
            return;
        updatePreciseLocation();
    }
    \endcode

    \target typed permission
    \section2 Typed Permissions

    The following permissions are available:

    \annotatedlist permissions

    \sa {Application Permissions}
*/

/*!
    \fn template <typename T, QPermission::if_permission<T>> QPermission::QPermission(const T &type)

    Constructs a permission from the given \l{typed permission} \a type.

    You do not need to construct this type explicitly, as the type is automatically
    used when checking or requesting permissions.

    This constructor participates in overload resolution only if \c T is one of
    the \l{typed permission} classes:

    \annotatedlist permissions
*/

/*!
    \fn template <typename T, QPermission::if_permission<T>> std::optional<T> QPermission::value() const

    Returns the \l{typed permission} of type \c T, or \c{std::nullopt} if this
    QPermission object doesn't contain one.

    Use type() for dynamically choosing which typed permission to request.

    This function participates in overload resolution only if \c T is one of
    the \l{typed permission} classes:

    \annotatedlist permissions
*/

/*!
    \fn Qt::PermissionStatus QPermission::status() const
    Returns the status of the permission.
*/

/*!
    \fn QMetaType QPermission::type() const
    Returns the type of the permission.
*/

/*
    \internal
*/
const void *QPermission::data(QMetaType requestedType) const
{
    const auto actualType = type();
    if (requestedType != actualType)
        return nullptr;
    return m_data.data();
}

// check alignof(AlignmentCheck) instead of alignof(void*), in case
// pointers have different alignment inside structs:
struct AlignmentCheck { void *p; };

#define QT_PERMISSION_IMPL_COMMON(ClassName) \
    /* Class##Private is unused until we need it: */ \
    static_assert(sizeof(ClassName) == sizeof(void*), \
                  "You have added too many members to " #ClassName "::ShortData. " \
                  "Decrease their size or switch to using a d-pointer."); \
    static_assert(alignof(ClassName) == alignof(AlignmentCheck), \
                  "You have added members to " #ClassName "::ShortData that are overaligned. " \
                  "Decrease their alignment or switch to using a d-pointer."); \
    ClassName::ClassName(const ClassName &other) noexcept = default; \
    ClassName::~ClassName() = default; \
    ClassName &ClassName::operator=(const ClassName &other) noexcept = default; \
    ClassName::ClassName() \
    /* impl supplied by caller */


/*!
    \class QCameraPermission
    \brief Access the camera for taking pictures or videos.

    \section1 Requirements

    \include permissions.qdocinc begin-usage-declarations
      \row
        \li Apple
        \li \l{apple-usage-description}{Usage description}
        \li \c NSCameraUsageDescription
      \row
        \li Android
        \li \l{android-uses-permission}{\c{uses-permission}}
        \li \c android.permission.CAMERA
    \include permissions.qdocinc end-usage-declarations

    \include permissions.qdocinc permission-metadata
*/

QT_PERMISSION_IMPL_COMMON(QCameraPermission)
    : u{} // stateless, atm
{}

/*!
    \class QMicrophonePermission
    \brief Access the microphone for monitoring or recording sound.

    \section1 Requirements

    \include permissions.qdocinc begin-usage-declarations
      \row
        \li Apple
        \li \l{apple-usage-description}{Usage description}
        \li \c NSMicrophoneUsageDescription
      \row
        \li Android
        \li \l{android-uses-permission}{\c{uses-permission}}
        \li \c android.permission.RECORD_AUDIO
    \include permissions.qdocinc end-usage-declarations

    \include permissions.qdocinc permission-metadata
*/

QT_PERMISSION_IMPL_COMMON(QMicrophonePermission)
    : u{} // stateless, atm
{}

/*!
    \class QBluetoothPermission
    \brief Access Bluetooth peripherals.

    \section1 Requirements

    \include permissions.qdocinc begin-usage-declarations
      \row
        \li Apple
        \li \l{apple-usage-description}{Usage description}
        \li \c NSBluetoothAlwaysUsageDescription
      \row
        \li Android
        \li \l{android-uses-permission}{\c{uses-permission}}
        \li Up to Android 11 (API Level < 31):
            \list
                \li \c android.permission.BLUETOOTH
                \li \c android.permission.ACCESS_FINE_LOCATION
            \endlist

            Starting from Android 12 (API Level >= 31):
            \list
                \li \c android.permission.BLUETOOTH_ADVERTISE
                \li \c android.permission.BLUETOOTH_CONNECT
                \li \c android.permission.BLUETOOTH_SCAN
                \li \c android.permission.ACCESS_FINE_LOCATION
            \endlist
    \include permissions.qdocinc end-usage-declarations

    \note Currently on Android the \c android.permission.ACCESS_FINE_LOCATION
    permission is requested together with Bluetooth permissions. This is
    required for Bluetooth to work properly, unless the application provides a
    strong assertion in the application manifest that it does not use Bluetooth
    to derive a physical location. This permission coupling may change in
    future.

    \include permissions.qdocinc permission-metadata
*/

QT_PERMISSION_IMPL_COMMON(QBluetoothPermission)
    : u{ShortData{CommunicationMode::Default, {}}}
{}

/*!
    \enum QBluetoothPermission::CommunicationMode
    \since 6.6

    This enum is used to control the allowed Bluetooth communication modes.

    \value Access Allow this device to access other Bluetooth devices. This
           includes scanning for nearby devices and connecting to them.
    \value Advertise Allow other Bluetooth devices to discover this device.
    \value Default This configuration is used by default.

    \note The fine-grained permissions are currently supported only on
    Android 12 and newer. On older Android versions, as well as on Apple
    operating systems, any mode results in full Bluetooth access.

    \note For now the \c Access mode on Android also requests the
    \l {QLocationPermission::Precise}{precise location} permission.
    This permission coupling may change in the future.
*/

/*!
    \since 6.6

    Sets the allowed Bluetooth communication modes to \a modes.

    \note A default-constructed instance of \l {QBluetoothPermission::}
    {CommunicationModes} has no sense, so an attempt to set such a mode will
    raise a \c {qWarning()} and fall back to using the
    \l {QBluetoothPermission::}{Default} mode.
*/
void QBluetoothPermission::setCommunicationModes(CommunicationModes modes)
{
    if (modes == CommunicationModes{}) {
        qCWarning(lcPermissions, "QBluetoothPermission: trying to set an invalid empty mode. "
                                 "Falling back to CommunicationMode::Default.");
        u.data.mode = Default;
    } else {
        u.data.mode = static_cast<CommunicationMode>(modes.toInt());
    }
}

/*!
    \since 6.6

    Returns the allowed Bluetooth communication modes.
*/
QBluetoothPermission::CommunicationModes QBluetoothPermission::communicationModes() const
{
    return u.data.mode;
}

/*!
    \class QLocationPermission
    \brief Access the user's location.

    By default the request is for approximate accuracy,
    and only while the application is in use. Use
    setAccuracy() and/or setAvailability() to override
    the default.

    \section1 Requirements

    \include permissions.qdocinc begin-usage-declarations
      \row
        \li \macos
        \li \l{apple-usage-description}{Usage description}
        \li \c NSLocationUsageDescription
      \row
        \li iOS
        \li \l{apple-usage-description}{Usage description}
        \li \c NSLocationWhenInUseUsageDescription, and
            \c NSLocationAlwaysAndWhenInUseUsageDescription if requesting
            QLocationPermission::Always
      \row
        \li Android
        \li \l{android-uses-permission}{\c{uses-permission}}
        \li \list
                \li \c android.permission.ACCESS_FINE_LOCATION for QLocationPermission::Precise
                \li \c android.permission.ACCESS_COARSE_LOCATION for QLocationPermission::Approximate
                \li \c android.permission.ACCESS_BACKGROUND_LOCATION for QLocationPermission::Always
            \endlist
            \note QLocationPermission::Always \c uses-permission string has
                to be combined with one or both of QLocationPermission::Precise
                and QLocationPermission::Approximate strings.
    \include permissions.qdocinc end-usage-declarations

    \include permissions.qdocinc permission-metadata
*/

QT_PERMISSION_IMPL_COMMON(QLocationPermission)
    : u{ShortData{Accuracy::Approximate, Availability::WhenInUse, {}}}
{}

/*!
    \enum QLocationPermission::Accuracy

    This enum is used to control the accuracy of the location data.

    \value Approximate An approximate location is requested.
    \value Precise A precise location is requested.
*/

/*!
    \enum QLocationPermission::Availability

    This enum is used to control the availability of the location data.

    \value WhenInUse The location is only available only when the
    application is in use.
    \value Always The location is available at all times, including when
    the application is in the background.
*/

/*!
    Sets the desired \a accuracy of the request.
*/
void QLocationPermission::setAccuracy(Accuracy accuracy)
{
    u.data.accuracy = accuracy;
}

/*!
    Returns the accuracy of the request.
*/
QLocationPermission::Accuracy QLocationPermission::accuracy() const
{
    return u.data.accuracy;
}

/*!
    Sets the desired \a availability of the request.
*/
void QLocationPermission::setAvailability(Availability availability)
{
    u.data.availability = availability;
}

/*!
    Returns the availability of the request.
*/
QLocationPermission::Availability QLocationPermission::availability() const
{
    return u.data.availability;
}

/*!
    \class QContactsPermission
    \brief Access the user's contacts.

    By default the request is for read-only access.
    Use setAccessMode() to override the default.

    \section1 Requirements

    \include permissions.qdocinc begin-usage-declarations
      \row
        \li Apple
        \li \l{apple-usage-description}{Usage description}
        \li \c NSContactsUsageDescription
      \row
        \li Android
        \li \l{android-uses-permission}{\c{uses-permission}}
        \li \c android.permission.READ_CONTACTS. \c android.permission.WRITE_CONTACTS if
            QContactsPermission::accessMode() is set to AccessMode::ReadWrite.
    \include permissions.qdocinc end-usage-declarations

    \include permissions.qdocinc permission-metadata
*/

/*!
    \enum QContactsPermission::AccessMode

    This enum is used to control access to the contacts data.

    \value ReadOnly Read-only access to the contacts data (the default).
    \value ReadWrite Read and write access to the contacts data.

    \sa setAccessMode, accessMode
*/

QT_PERMISSION_IMPL_COMMON(QContactsPermission)
    : u{ShortData{AccessMode::ReadOnly, {}}}
{}

/*!
    Sets whether the request is for read-write (\a mode == AccessMode::ReadOnly) or
    read-only (\a mode == AccessMode::ReadOnly) access to the contacts.
*/
void QContactsPermission::setAccessMode(AccessMode mode)
{
    u.data.mode = mode;
}

/*!
    Returns AccessMode::ReadWrite when the request is for read-write and
    AccessMode::ReadOnly when it is for read-only access to the contacts.
*/
QContactsPermission::AccessMode QContactsPermission::accessMode() const
{
    return u.data.mode;
}

/*!
    \class QCalendarPermission
    \brief Access the user's calendar.

    By default the request is for read-only access.
    Use setAccessMode() to override the default.

    \section1 Requirements

    \include permissions.qdocinc begin-usage-declarations
      \row
        \li Apple
        \li \l{apple-usage-description}{Usage description}
        \li \c NSCalendarsUsageDescription
      \row
        \li Android
        \li \l{android-uses-permission}{\c{uses-permission}}
        \li \c android.permission.READ_CALENDAR. \c android.permission.WRITE_CALENDAR if
            QCalendarPermission::accessMode() is set to AccessMode::ReadWrite.
    \include permissions.qdocinc end-usage-declarations

    \include permissions.qdocinc permission-metadata
*/

/*!
    \enum QCalendarPermission::AccessMode

    This enum is used to control access to the calendar data.

    \value ReadOnly Read-only access to the calendar data (the default).
    \value ReadWrite Read and write access to the calendar data.

    \sa setAccessMode, accessMode
*/

QT_PERMISSION_IMPL_COMMON(QCalendarPermission)
    : u{ShortData{AccessMode::ReadOnly, {}}}
{}

/*!
    Sets whether the request is for read-write (\a mode == AccessMode::ReadOnly) or
    read-only (\a mode == AccessMode::ReadOnly) access to the calendar.
*/
void QCalendarPermission::setAccessMode(AccessMode mode)
{
    u.data.mode = mode;
}

/*!
    Returns AccessMode::ReadWrite when the request is for read-write and
    AccessMode::ReadOnly when it is for read-only access to the calendar.
*/
QCalendarPermission::AccessMode QCalendarPermission::accessMode() const
{
    return u.data.mode;
}

/*!
 * \internal
*/

QPermissionPlugin::~QPermissionPlugin() = default;

#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const QPermission &permission)
{
    const auto verbosity = debug.verbosity();
    QDebugStateSaver saver(debug);
    debug.nospace().setVerbosity(0);
    if (verbosity >= QDebug::DefaultVerbosity)
        debug << permission.type().name() << "(";
    debug << permission.status();
    if (verbosity >= QDebug::DefaultVerbosity)
        debug << ")";
    return debug;
}
#endif

#undef QT_PERMISSION_IMPL_COMMON

#if !defined(Q_OS_DARWIN) && !defined(Q_OS_ANDROID) && !defined(Q_OS_WASM)
// Default backend for platforms without a permission implementation.
// Always returns Granted, to match behavior when not using permission APIs
// https://bugreports.qt.io/browse/QTBUG-90498?focusedCommentId=725085#comment-725085
namespace QPermissions::Private
{
    Qt::PermissionStatus checkPermission(const QPermission &permission)
    {
        qCDebug(lcPermissions) << "No permission backend on this platform."
            << "Optimistically returning Granted for" << permission;
        return Qt::PermissionStatus::Granted;
    }

    void requestPermission(const QPermission &permission, const PermissionCallback &callback)
    {
        qCDebug(lcPermissions) << "No permission backend on this platform."
            << "Optimistically returning Granted for" << permission;
        callback(Qt::PermissionStatus::Granted);
    }
}
#endif

QT_END_NAMESPACE

#include "moc_qpermissions.cpp"