π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Use Polkit for Linux local auth
Neeraj Guptaadfd322917fa
diff --git a/.github/workflows/auth-build.yml b/.github/workflows/auth-build.ymlindex bbcaff525e..2e2ff19378 100644--- a/.github/workflows/auth-build.yml+++ b/.github/workflows/auth-build.yml@@ -245,7 +245,7 @@ jobs:- name: Install dependencies for Linux buildrun: |sudo apt-get update- sudo apt-get install -y libsecret-1-dev libsodium-dev libfuse2 ninja-build libgtk-3-dev libpam0g-dev dpkg-dev pkg-config rpm patchelf libsqlite3-dev locate libayatana-appindicator3-dev libffi-dev libtiff5 xz-utils libarchive-tools libcurl4-openssl-dev+ sudo apt-get install -y libsecret-1-dev libsodium-dev libfuse2 ninja-build libgtk-3-dev dpkg-dev pkg-config rpm patchelf libsqlite3-dev locate libayatana-appindicator3-dev libffi-dev libtiff5 xz-utils libarchive-tools libcurl4-openssl-devsudo updatedb --localpaths='/usr/lib/x86_64-linux-gnu'- name: Install fpm for RPM packagingdiff --git a/mobile/apps/auth/assets/polkit/io.ente.auth.policy b/mobile/apps/auth/assets/polkit/io.ente.auth.policynew file mode 100644index 0000000000..e67ff02183--- /dev/null+++ b/mobile/apps/auth/assets/polkit/io.ente.auth.policy@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE policyconfig PUBLIC+ "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"+ "http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">+<policyconfig>+ <vendor>Ente</vendor>+ <vendor_url>https://ente.io</vendor_url>++ <action id="io.ente.auth.unlock">+ <description>Unlock Ente Auth</description>+ <message>Authenticate to unlock Ente Auth.</message>+ <defaults>+ <allow_any>no</allow_any>+ <allow_inactive>no</allow_inactive>+ <allow_active>auth_self</allow_active>+ </defaults>+ </action>+</policyconfig>diff --git a/mobile/apps/auth/linux/packaging/build_rpm.sh b/mobile/apps/auth/linux/packaging/build_rpm.shindex 515bf56d00..eb643c0213 100755--- a/mobile/apps/auth/linux/packaging/build_rpm.sh+++ b/mobile/apps/auth/linux/packaging/build_rpm.sh@@ -44,6 +44,7 @@ mkdir -p "$STAGING_DIR/usr/share/enteauth"mkdir -p "$STAGING_DIR/usr/share/metainfo"mkdir -p "$STAGING_DIR/usr/share/pixmaps"mkdir -p "$STAGING_DIR/usr/share/applications"+mkdir -p "$STAGING_DIR/usr/share/polkit-1/actions"mkdir -p "$STAGING_DIR/usr/bin"# Create output directory@@ -72,6 +73,10 @@ cp "assets/generation-icons/icon-windows-linux.png" "$STAGING_DIR/usr/share/pixmecho -e "${YELLOW}Copying desktop file...${NC}"cp linux/packaging/enteauth.desktop "$STAGING_DIR/usr/share/applications/"+# Copy Polkit policy.+echo -e "${YELLOW}Copying Polkit policy...${NC}"+cp assets/polkit/io.ente.auth.policy "$STAGING_DIR/usr/share/polkit-1/actions/"+# Create symlinkecho -e "${YELLOW}Creating symlink...${NC}"ln -s /usr/share/enteauth/enteauth "$STAGING_DIR/usr/bin/enteauth"@@ -97,7 +102,7 @@ fpm -s dir -t rpm \--depends sqlite-libs \--depends libsecret \--depends libappindicator \- --depends pam \+ --depends polkit \-C "$STAGING_DIR" \-p "$OUTPUT_DIR/enteauth-VERSION.ARCH.rpm" \.diff --git a/mobile/apps/auth/linux/packaging/deb/make_config.yaml b/mobile/apps/auth/linux/packaging/deb/make_config.yamlindex d368274009..8cb8ef3369 100644--- a/mobile/apps/auth/linux/packaging/deb/make_config.yaml+++ b/mobile/apps/auth/linux/packaging/deb/make_config.yaml@@ -18,11 +18,17 @@ dependencies:- libsqlite3-0- libsodium23- libsecret-1-0- - libpam0g+ - policykit-1 | polkitd- libappindicator3-1 | libayatana-appindicator3-1- gir1.2-appindicator3-0.1 | gir1.2-ayatanaappindicator3-0.1- libayatana-ido3-0.4-0+postinstall_scripts:+ - install -D -m 0644 /usr/share/enteauth/data/flutter_assets/assets/polkit/io.ente.auth.policy /usr/share/polkit-1/actions/io.ente.auth.policy++postuninstall_scripts:+ - rm -f /usr/share/polkit-1/actions/io.ente.auth.policy+keywords:- Authentication- 2FAdiff --git a/mobile/apps/auth/linux/packaging/pacman/make_config.yaml b/mobile/apps/auth/linux/packaging/pacman/make_config.yamlindex 4c120ef519..fab9a782fd 100644--- a/mobile/apps/auth/linux/packaging/pacman/make_config.yaml+++ b/mobile/apps/auth/linux/packaging/pacman/make_config.yaml@@ -14,7 +14,7 @@ dependencies:- sqlite- libsecret- libappindicator-gtk3- - pam+ - polkitkeywords:- Authentication@@ -31,6 +31,7 @@ supported_mime_type:postinstall_scripts:- gtk-update-icon-cache -q -t -f usr/share/icons/hicolor- update-desktop-database -q+ - install -D -m 0644 /usr/share/enteauth/data/flutter_assets/assets/polkit/io.ente.auth.policy /usr/share/polkit-1/actions/io.ente.auth.policy- if [ ! -e /usr/lib/libsodium.so.23 ]; then- " ln -s /usr/lib/libsodium.so /usr/lib/libsodium.so.23"- fi@@ -41,6 +42,7 @@ postupgrade_scripts:postremove_scripts:- gtk-update-icon-cache -q -t -f usr/share/icons/hicolor- update-desktop-database -q+ - rm -f /usr/share/polkit-1/actions/io.ente.auth.policy- if [ -e /usr/lib/libsodium.so.23 ]; then- rm /usr/lib/libsodium.so.23- fidiff --git a/mobile/apps/auth/linux/packaging/post_process_appimage.sh b/mobile/apps/auth/linux/packaging/post_process_appimage.shindex c6020c2bcf..30aff80950 100755--- a/mobile/apps/auth/linux/packaging/post_process_appimage.sh+++ b/mobile/apps/auth/linux/packaging/post_process_appimage.sh@@ -60,6 +60,7 @@ cat >"$appdir/AppRun" <<'APPRUN'set -eAPPDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+export APPDIRcd "$APPDIR"HOST_LIBRARY_PATH="/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/lib64:/usr/lib64:/lib:/usr/lib"diff --git a/mobile/apps/auth/linux/packaging/rpm/make_config.yaml b/mobile/apps/auth/linux/packaging/rpm/make_config.yamlindex c3e1a39ea1..65f3df1f3c 100644--- a/mobile/apps/auth/linux/packaging/rpm/make_config.yaml+++ b/mobile/apps/auth/linux/packaging/rpm/make_config.yaml@@ -17,7 +17,13 @@ requires:- libsqlite3x- libsecret- libappindicator- - pam+ - polkit++postinstall_scripts:+ - install -D -m 0644 /usr/share/enteauth/data/flutter_assets/assets/polkit/io.ente.auth.policy /usr/share/polkit-1/actions/io.ente.auth.policy++postuninstall_scripts:+ - rm -f /usr/share/polkit-1/actions/io.ente.auth.policykeywords:- Authenticationdiff --git a/mobile/packages/local_auth_linux/lib/local_auth_linux.dart b/mobile/packages/local_auth_linux/lib/local_auth_linux.dartindex 2982c67050..f80c158242 100644--- a/mobile/packages/local_auth_linux/lib/local_auth_linux.dart+++ b/mobile/packages/local_auth_linux/lib/local_auth_linux.dart@@ -1,8 +1,62 @@+import 'dart:io';+import 'package:flutter/foundation.dart';import 'package:flutter/services.dart';import 'package:local_auth_platform_interface/local_auth_platform_interface.dart';const MethodChannel _defaultChannel = MethodChannel('ente.io/local_auth_linux');+const String linuxLocalAuthPolkitActionId = 'io.ente.auth.unlock';++class LinuxLocalAuthSetupStatus {+ const LinuxLocalAuthSetupStatus({+ required this.actionId,+ required this.policyAssetPath,+ required this.polkitAvailable,+ required this.policyInstalled,+ required this.isFlatpak,+ this.errorMessage,+ });++ factory LinuxLocalAuthSetupStatus.fromMap(Map<Object?, Object?> map) {+ return LinuxLocalAuthSetupStatus(+ actionId: map['actionId'] as String? ?? linuxLocalAuthPolkitActionId,+ policyAssetPath: map['policyAssetPath'] as String? ?? _policyAssetPath,+ polkitAvailable: map['polkitAvailable'] as bool? ?? false,+ policyInstalled: map['policyInstalled'] as bool? ?? false,+ isFlatpak: map['isFlatpak'] as bool? ?? _isFlatpak,+ errorMessage: map['errorMessage'] as String?,+ );+ }++ final String actionId;+ final String policyAssetPath;+ final bool polkitAvailable;+ final bool policyInstalled;+ final bool isFlatpak;+ final String? errorMessage;++ bool get setupRequired => polkitAvailable && !policyInstalled;++ String get policyInstallCommand {+ if (isFlatpak) {+ return '''+install_dir="\$(flatpak info --show-location io.ente.auth)"+pkexec install -D -m 0644 "\$install_dir/files/share/enteauth/data/flutter_assets/assets/polkit/io.ente.auth.policy" /usr/share/polkit-1/actions/io.ente.auth.policy+pkaction --action-id $actionId --verbose''';+ }+ return '''+pkexec install -D -m 0644 "$policyAssetPath" /usr/share/polkit-1/actions/io.ente.auth.policy+pkaction --action-id $actionId --verbose''';+ }+}++bool get _isFlatpak =>+ Platform.environment.containsKey('FLATPAK_ID') ||+ File('/.flatpak-info').existsSync();++String get _policyAssetPath => _isFlatpak+ ? '/app/share/enteauth/data/flutter_assets/assets/polkit/io.ente.auth.policy'+ : '/usr/share/enteauth/data/flutter_assets/assets/polkit/io.ente.auth.policy';class LocalAuthLinux extends LocalAuthPlatform {LocalAuthLinux({@visibleForTesting MethodChannel? channel})@@ -25,7 +79,7 @@ class LocalAuthLinux extends LocalAuthPlatform {if (options.biometricOnly) {throw UnsupportedError(- "Linux PAM authentication doesn't support the biometricOnly parameter.",+ "Linux Polkit authentication doesn't support the biometricOnly parameter.",);}if (_isAuthenticating) {@@ -66,6 +120,15 @@ class LocalAuthLinux extends LocalAuthPlatform {@overrideFuture<bool> stopAuthentication() async => false;++ Future<LinuxLocalAuthSetupStatus> getSetupStatus() async {+ final result = await _channel.invokeMapMethod<Object?, Object?>(+ 'getSetupStatus',+ );+ return LinuxLocalAuthSetupStatus.fromMap(+ result ?? const <Object?, Object?>{},+ );+ }}LocalAuthException _localAuthExceptionForPlatformException(@@ -73,12 +136,10 @@ LocalAuthException _localAuthExceptionForPlatformException() {final code = switch (error.code) {'authentication_canceled' => LocalAuthExceptionCode.userCanceled,- 'ui_unavailable' => LocalAuthExceptionCode.uiUnavailable,- 'pam_unavailable' ||- 'unsupported_runtime' ||- 'account_unavailable' => LocalAuthExceptionCode.deviceError,+ 'setup_required' => LocalAuthExceptionCode.noCredentialsSet,+ 'polkit_unavailable' => LocalAuthExceptionCode.deviceError,'authentication_failed' => LocalAuthExceptionCode.unknownError,- 'pam_error' => LocalAuthExceptionCode.unknownError,+ 'polkit_error' => LocalAuthExceptionCode.unknownError,_ => LocalAuthExceptionCode.unknownError,};return LocalAuthException(code: code, description: error.message);diff --git a/mobile/packages/local_auth_linux/linux/CMakeLists.txt b/mobile/packages/local_auth_linux/linux/CMakeLists.txtindex 88853aa01c..5b63b7663a 100644--- a/mobile/packages/local_auth_linux/linux/CMakeLists.txt+++ b/mobile/packages/local_auth_linux/linux/CMakeLists.txt@@ -15,14 +15,8 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL)target_include_directories(${PLUGIN_NAME} INTERFACE"${CMAKE_CURRENT_SOURCE_DIR}/include")-find_library(PAM_LIBRARY pam)-if(NOT PAM_LIBRARY)- message(FATAL_ERROR "libpam was not found. Install libpam0g-dev or the equivalent PAM development package.")-endif()-target_link_libraries(${PLUGIN_NAME} PRIVATE flutter)target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK)-target_link_libraries(${PLUGIN_NAME} PRIVATE ${PAM_LIBRARY})set(local_auth_linux_bundled_libraries""diff --git a/mobile/packages/local_auth_linux/linux/local_auth_linux_plugin.cc b/mobile/packages/local_auth_linux/linux/local_auth_linux_plugin.ccindex f45acb40b9..4cbe4b9a19 100644--- a/mobile/packages/local_auth_linux/linux/local_auth_linux_plugin.cc+++ b/mobile/packages/local_auth_linux/linux/local_auth_linux_plugin.cc@@ -1,22 +1,26 @@#include "include/local_auth_linux/local_auth_linux_plugin.h"#include <flutter_linux/flutter_linux.h>-#include <gtk/gtk.h>-#include <pwd.h>-#include <security/pam_appl.h>+#include <gio/gio.h>#include <string.h>-#include <unistd.h>--#include <cstdlib>-#include <cstring>#define LOCAL_AUTH_LINUX_PLUGIN(obj) \(G_TYPE_CHECK_INSTANCE_CAST((obj), local_auth_linux_plugin_get_type(), \LocalAuthLinuxPlugin))static constexpr const char* kChannelName = "ente.io/local_auth_linux";-static constexpr const char* kDefaultPamService = "login";-static constexpr const char* kPamServiceEnv = "ENTE_LOCAL_AUTH_PAM_SERVICE";+static constexpr const char* kPolkitBusName = "org.freedesktop.PolicyKit1";+static constexpr const char* kPolkitAuthorityPath =+ "/org/freedesktop/PolicyKit1/Authority";+static constexpr const char* kPolkitAuthorityInterface =+ "org.freedesktop.PolicyKit1.Authority";+static constexpr const char* kPolkitActionId = "io.ente.auth.unlock";+static constexpr const char* kPolicyAssetPath =+ "/usr/share/enteauth/data/flutter_assets/assets/polkit/io.ente.auth.policy";+static constexpr const char* kFlatpakPolicyAssetPath =+ "/app/share/enteauth/data/flutter_assets/assets/polkit/io.ente.auth.policy";+static constexpr const char* kBundledPolicyAssetRelativePath =+ "data/flutter_assets/assets/polkit/io.ente.auth.policy";struct _LocalAuthLinuxPlugin {GObject parent_instance;@@ -29,258 +33,214 @@ struct _LocalAuthLinuxPluginClass {GObjectClass parent_class;};-struct PamConversationData {- const gchar* title;- const gchar* reason;- const gchar* cancel_button;- gboolean cancelled;-};-static const gchar* string_or_default(const gchar* value,const gchar* fallback) {return value != nullptr && value[0] != '\0' ? value : fallback;}-static const char* pam_service_name() {- const char* service_name = std::getenv(kPamServiceEnv);- return service_name != nullptr && service_name[0] != '\0' ? service_name- : kDefaultPamService;-}--static const char* current_user_name() {- passwd* user = getpwuid(getuid());- return user != nullptr ? user->pw_name : nullptr;-}--static FlMethodResponse* error_response(const gchar* code,- const gchar* message) {- return FL_METHOD_RESPONSE(- fl_method_error_response_new(code, message, nullptr));+static gboolean is_flatpak() {+ return g_getenv("FLATPAK_ID") != nullptr ||+ g_file_test("/.flatpak-info", G_FILE_TEST_EXISTS);}-static const gchar* value_lookup_string(FlValue* map, const gchar* key) {- if (map == nullptr || fl_value_get_type(map) != FL_VALUE_TYPE_MAP) {- return nullptr;+static gchar* policy_asset_path() {+ if (is_flatpak() &&+ g_file_test(kFlatpakPolicyAssetPath, G_FILE_TEST_IS_REGULAR)) {+ return g_strdup(kFlatpakPolicyAssetPath);}- g_autoptr(FlValue) lookup_key = fl_value_new_string(key);- FlValue* value = fl_value_lookup(map, lookup_key);- if (value == nullptr || fl_value_get_type(value) != FL_VALUE_TYPE_STRING) {- return nullptr;+ if (g_file_test(kPolicyAssetPath, G_FILE_TEST_IS_REGULAR)) {+ return g_strdup(kPolicyAssetPath);}- return fl_value_get_string(value);-}-static gchar* show_prompt_dialog(PamConversationData* data,- const char* message,- gboolean secret) {- GtkWidget* dialog = gtk_dialog_new_with_buttons(- string_or_default(data->title, "Authentication required"), nullptr,- GTK_DIALOG_MODAL, string_or_default(data->cancel_button, "Cancel"),- GTK_RESPONSE_CANCEL, "OK", GTK_RESPONSE_OK, nullptr);-- gtk_window_set_keep_above(GTK_WINDOW(dialog), TRUE);- gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK);-- GtkWidget* content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog));- gtk_container_set_border_width(GTK_CONTAINER(content_area), 16);-- const gchar* reason = string_or_default(data->reason, "");- if (reason[0] != '\0') {- GtkWidget* reason_label = gtk_label_new(reason);- gtk_label_set_line_wrap(GTK_LABEL(reason_label), TRUE);- gtk_label_set_xalign(GTK_LABEL(reason_label), 0.0);- gtk_box_pack_start(GTK_BOX(content_area), reason_label, FALSE, FALSE, 8);+ const gchar* appdir = g_getenv("APPDIR");+ if (appdir != nullptr && appdir[0] != '\0') {+ g_autofree gchar* appimage_path =+ g_build_filename(appdir, kBundledPolicyAssetRelativePath, nullptr);+ if (g_file_test(appimage_path, G_FILE_TEST_IS_REGULAR)) {+ return g_strdup(appimage_path);+ }}- GtkWidget* message_label =- gtk_label_new(string_or_default(message, "Password"));- gtk_label_set_line_wrap(GTK_LABEL(message_label), TRUE);- gtk_label_set_xalign(GTK_LABEL(message_label), 0.0);- gtk_box_pack_start(GTK_BOX(content_area), message_label, FALSE, FALSE, 8);-- GtkWidget* entry = gtk_entry_new();- gtk_entry_set_visibility(GTK_ENTRY(entry), !secret);- gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE);- gtk_box_pack_start(GTK_BOX(content_area), entry, FALSE, FALSE, 0);-- gtk_widget_show_all(dialog);- gint response = gtk_dialog_run(GTK_DIALOG(dialog));- gchar* result = nullptr;- if (response == GTK_RESPONSE_OK) {- result = g_strdup(gtk_entry_get_text(GTK_ENTRY(entry)));- } else {- data->cancelled = TRUE;+ g_autofree gchar* cwd = g_get_current_dir();+ g_autofree gchar* cwd_path =+ g_build_filename(cwd, kBundledPolicyAssetRelativePath, nullptr);+ if (g_file_test(cwd_path, G_FILE_TEST_IS_REGULAR)) {+ return g_strdup(cwd_path);}- gtk_widget_destroy(dialog);- while (gtk_events_pending()) {- gtk_main_iteration();- }- return result;+ return g_strdup(is_flatpak() ? kFlatpakPolicyAssetPath : kPolicyAssetPath);}-static void show_message_dialog(PamConversationData* data,- const char* message,- GtkMessageType type) {- GtkWidget* dialog = gtk_message_dialog_new(- nullptr, GTK_DIALOG_MODAL, type, GTK_BUTTONS_OK, "%s",- string_or_default(message, ""));- gtk_window_set_title(GTK_WINDOW(dialog),- string_or_default(data->title, "Authentication"));- gtk_window_set_keep_above(GTK_WINDOW(dialog), TRUE);- gtk_dialog_run(GTK_DIALOG(dialog));- gtk_widget_destroy(dialog);- while (gtk_events_pending()) {- gtk_main_iteration();- }+static FlMethodResponse* error_response(const gchar* code,+ const gchar* message) {+ return FL_METHOD_RESPONSE(+ fl_method_error_response_new(code, message, nullptr));}-static void free_pam_responses(pam_response* responses, int count) {- if (responses == nullptr) {- return;- }- for (int i = 0; i < count; i++) {- std::free(responses[i].resp);- }- std::free(responses);+static GDBusConnection* system_bus_connection(GError** error) {+ return g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, error);}-static int pam_conversation(int num_msg,- const struct pam_message** msg,- struct pam_response** resp,- void* appdata_ptr) {- if (num_msg <= 0 || msg == nullptr || resp == nullptr ||- appdata_ptr == nullptr) {- return PAM_CONV_ERR;+static gboolean polkit_action_exists(GDBusConnection* connection,+ GError** error) {+ g_autoptr(GVariant) result = g_dbus_connection_call_sync(+ connection, kPolkitBusName, kPolkitAuthorityPath,+ kPolkitAuthorityInterface, "EnumerateActions", g_variant_new("(s)", ""),+ G_VARIANT_TYPE("(a(ssssssuuua{ss}))"), G_DBUS_CALL_FLAGS_NONE, -1,+ nullptr, error);+ if (result == nullptr) {+ return FALSE;}- PamConversationData* data =- static_cast<PamConversationData*>(appdata_ptr);- pam_response* responses =- static_cast<pam_response*>(std::calloc(num_msg, sizeof(pam_response)));- if (responses == nullptr) {- return PAM_BUF_ERR;- }+ g_autoptr(GVariant) actions = nullptr;+ g_variant_get(result, "(@a(ssssssuuua{ss}))", &actions);- for (int i = 0; i < num_msg; i++) {- const char* message = msg[i]->msg != nullptr ? msg[i]->msg : "";- switch (msg[i]->msg_style) {- case PAM_PROMPT_ECHO_ON:- case PAM_PROMPT_ECHO_OFF: {- g_autofree gchar* answer =- show_prompt_dialog(data, message,- msg[i]->msg_style == PAM_PROMPT_ECHO_OFF);- if (data->cancelled || answer == nullptr) {- free_pam_responses(responses, i);- return PAM_CONV_ERR;- }- responses[i].resp = strdup(answer);- if (responses[i].resp == nullptr) {- free_pam_responses(responses, i);- return PAM_BUF_ERR;- }- break;- }- case PAM_TEXT_INFO:- show_message_dialog(data, message, GTK_MESSAGE_INFO);- break;- case PAM_ERROR_MSG:- show_message_dialog(data, message, GTK_MESSAGE_ERROR);- break;- default:- free_pam_responses(responses, i);- return PAM_CONV_ERR;+ GVariantIter iter;+ g_variant_iter_init(&iter, actions);+ while (true) {+ g_autoptr(GVariant) action = g_variant_iter_next_value(&iter);+ if (action == nullptr) {+ break;+ }+ g_autoptr(GVariant) action_id_value = g_variant_get_child_value(action, 0);+ const gchar* action_id = g_variant_get_string(action_id_value, nullptr);+ if (g_strcmp0(action_id, kPolkitActionId) == 0) {+ return TRUE;}}-- *resp = responses;- return PAM_SUCCESS;+ return FALSE;}-static gboolean can_authenticate_with_pam() {- const char* user_name = current_user_name();- if (user_name == nullptr) {+static gboolean check_polkit_authorization(GDBusConnection* connection,+ gboolean allow_user_interaction,+ GError** error) {+ const gchar* unique_name = g_dbus_connection_get_unique_name(connection);+ if (unique_name == nullptr || unique_name[0] == '\0') {+ g_set_error(error, G_IO_ERROR, G_IO_ERROR_FAILED,+ "Unable to determine the app's system bus name.");return FALSE;}- pam_handle_t* pam_handle = nullptr;- pam_conv conversation = {nullptr, nullptr};- int status =- pam_start(pam_service_name(), user_name, &conversation, &pam_handle);- if (pam_handle != nullptr) {- pam_end(pam_handle, status);+ GVariantBuilder subject_details;+ g_variant_builder_init(&subject_details, G_VARIANT_TYPE("a{sv}"));+ g_variant_builder_add(&subject_details, "{sv}", "name",+ g_variant_new_string(unique_name));++ GVariantBuilder details;+ g_variant_builder_init(&details, G_VARIANT_TYPE("a{ss}"));++ g_autoptr(GVariant) result = g_dbus_connection_call_sync(+ connection, kPolkitBusName, kPolkitAuthorityPath,+ kPolkitAuthorityInterface, "CheckAuthorization",+ g_variant_new("((sa{sv})sa{ss}us)", "system-bus-name",+ &subject_details, kPolkitActionId, &details,+ allow_user_interaction ? 1u : 0u, ""),+ G_VARIANT_TYPE("((bba{ss}))"), G_DBUS_CALL_FLAGS_NONE, -1, nullptr,+ error);+ if (result == nullptr) {+ return FALSE;}- return status == PAM_SUCCESS;++ g_autoptr(GVariant) authorization = nullptr;+ g_variant_get(result, "(@(bba{ss}))", &authorization);++ gboolean is_authorized = FALSE;+ gboolean is_challenge = FALSE;+ g_autoptr(GVariant) result_details = nullptr;+ g_variant_get(authorization, "(bb@a{ss})", &is_authorized, &is_challenge,+ &result_details);+ return is_authorized;}-static gboolean authenticate_with_pam(const gchar* reason,- gchar** error_code,- gchar** error_message,- gboolean* authentication_failed) {- if (gdk_display_get_default() == nullptr) {- *error_code = g_strdup("ui_unavailable");- *error_message = g_strdup("No GTK display is available.");+static gboolean is_cancelled_error(GError* error) {+ if (error == nullptr) {return FALSE;}+ g_autofree gchar* remote_error = g_dbus_error_get_remote_error(error);+ return g_strcmp0(remote_error,+ "org.freedesktop.PolicyKit1.Error.Cancelled") == 0;+}- const char* user_name = current_user_name();- if (user_name == nullptr) {- *error_code = g_strdup("unsupported_runtime");- *error_message = g_strdup("Unable to determine the current user.");+static gboolean can_authenticate_with_polkit() {+ g_autoptr(GError) error = nullptr;+ g_autoptr(GDBusConnection) connection = system_bus_connection(&error);+ if (connection == nullptr) {return FALSE;}+ return polkit_action_exists(connection, &error);+}- PamConversationData conversation_data = {- "Authentication required",- string_or_default(reason, "Authenticate with your system password."),- "Cancel", FALSE};- pam_conv conversation = {pam_conversation, &conversation_data};- pam_handle_t* pam_handle = nullptr;-- int status =- pam_start(pam_service_name(), user_name, &conversation, &pam_handle);- if (status != PAM_SUCCESS) {- *error_code = g_strdup("pam_unavailable");- *error_message = g_strdup(pam_strerror(pam_handle, status));- if (pam_handle != nullptr) {- pam_end(pam_handle, status);- }+static gboolean authenticate_with_polkit(gchar** error_code,+ gchar** error_message) {+ g_autoptr(GError) error = nullptr;+ g_autoptr(GDBusConnection) connection = system_bus_connection(&error);+ if (connection == nullptr) {+ *error_code = g_strdup("polkit_unavailable");+ *error_message =+ g_strdup(string_or_default(error != nullptr ? error->message : nullptr,+ "Polkit is not available."));return FALSE;}- status = pam_authenticate(pam_handle, 0);- if (status == PAM_SUCCESS) {- status = pam_acct_mgmt(pam_handle, 0);+ if (!polkit_action_exists(connection, &error)) {+ *error_code = g_strdup("setup_required");+ *error_message = g_strdup(+ "The Ente Auth Polkit policy is not installed on this system.");+ return FALSE;}- g_autofree gchar* pam_message = g_strdup(pam_strerror(pam_handle, status));- pam_end(pam_handle, status);-- if (status == PAM_SUCCESS) {+ error = nullptr;+ if (check_polkit_authorization(connection, TRUE, &error)) {return TRUE;}- if (conversation_data.cancelled) {+ if (is_cancelled_error(error)) {*error_code = g_strdup("authentication_canceled");*error_message = g_strdup("Authentication was canceled.");- } else if (status == PAM_AUTH_ERR || status == PAM_USER_UNKNOWN ||- status == PAM_MAXTRIES) {- *authentication_failed = TRUE;- *error_message =- g_strdup(string_or_default(pam_message, "Authentication failed."));- } else if (status == PAM_ACCT_EXPIRED || status == PAM_PERM_DENIED ||- status == PAM_NEW_AUTHTOK_REQD) {- *error_code = g_strdup("account_unavailable");- *error_message =- g_strdup(string_or_default(pam_message, "Account is unavailable."));+ } else if (error != nullptr) {+ *error_code = g_strdup("polkit_error");+ *error_message = g_strdup(error->message);} else {- *error_code = g_strdup("pam_error");- *error_message =- g_strdup(string_or_default(pam_message, "PAM authentication failed."));+ *error_code = g_strdup("authentication_failed");+ *error_message = g_strdup("Authentication failed.");}return FALSE;}+static FlValue* setup_status() {+ gboolean polkit_available = FALSE;+ gboolean policy_installed = FALSE;+ g_autofree gchar* error_message = nullptr;++ g_autoptr(GError) error = nullptr;+ g_autoptr(GDBusConnection) connection = system_bus_connection(&error);+ if (connection != nullptr) {+ polkit_available = TRUE;+ policy_installed = polkit_action_exists(connection, &error);+ }+ if (error != nullptr) {+ error_message = g_strdup(error->message);+ }+ g_autofree gchar* asset_path = policy_asset_path();++ FlValue* status = fl_value_new_map();+ fl_value_set_take(status, fl_value_new_string("actionId"),+ fl_value_new_string(kPolkitActionId));+ fl_value_set_take(status, fl_value_new_string("policyAssetPath"),+ fl_value_new_string(asset_path));+ fl_value_set_take(status, fl_value_new_string("polkitAvailable"),+ fl_value_new_bool(polkit_available));+ fl_value_set_take(status, fl_value_new_string("policyInstalled"),+ fl_value_new_bool(policy_installed));+ fl_value_set_take(status, fl_value_new_string("isFlatpak"),+ fl_value_new_bool(is_flatpak()));+ if (error_message != nullptr) {+ fl_value_set_take(status, fl_value_new_string("errorMessage"),+ fl_value_new_string(error_message));+ }+ return status;+}+static void local_auth_linux_plugin_handle_method_call(LocalAuthLinuxPlugin* self,FlMethodCall* method_call) {@@ -290,25 +250,24 @@ static void local_auth_linux_plugin_handle_method_call(if (strcmp(method, "isDeviceSupported") == 0) {g_autoptr(FlValue) result =- fl_value_new_bool(can_authenticate_with_pam());+ fl_value_new_bool(can_authenticate_with_polkit());+ response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));+ } else if (strcmp(method, "getSetupStatus") == 0) {+ g_autoptr(FlValue) result = setup_status();response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));} else if (strcmp(method, "authenticate") == 0) {- FlValue* arguments = fl_method_call_get_args(method_call);- const gchar* reason = value_lookup_string(arguments, "localizedReason");g_autofree gchar* error_code = nullptr;g_autofree gchar* error_message = nullptr;- gboolean authentication_failed = FALSE;- if (authenticate_with_pam(reason, &error_code, &error_message,- &authentication_failed)) {+ if (authenticate_with_polkit(&error_code, &error_message)) {g_autoptr(FlValue) result = fl_value_new_bool(TRUE);response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));- } else if (authentication_failed) {+ } else if (g_strcmp0(error_code, "authentication_failed") == 0) {g_autoptr(FlValue) result = fl_value_new_bool(FALSE);response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));} else {response = error_response(- string_or_default(error_code, "pam_error"),+ string_or_default(error_code, "polkit_error"),string_or_default(error_message, "Authentication failed."));}} else {diff --git a/mobile/packages/local_auth_linux/test/local_auth_linux_test.dart b/mobile/packages/local_auth_linux/test/local_auth_linux_test.dartindex 8f19e36a10..b7a87d648f 100644--- a/mobile/packages/local_auth_linux/test/local_auth_linux_test.dart+++ b/mobile/packages/local_auth_linux/test/local_auth_linux_test.dart@@ -21,6 +21,13 @@ void main() {return switch (methodCall.method) {'authenticate' => true,'isDeviceSupported' => true,+ 'getSetupStatus' => <String, Object?>{+ 'actionId': linuxLocalAuthPolkitActionId,+ 'policyAssetPath': '/usr/share/enteauth/policy',+ 'polkitAvailable': true,+ 'policyInstalled': true,+ 'isFlatpak': false,+ },_ => null,};});@@ -131,10 +138,48 @@ void main() {await expectLater(first, completion(isTrue));});- test('reports PAM device support but no direct biometric support', () async {- expect(await localAuth.isDeviceSupported(), isTrue);- expect(await localAuth.deviceSupportsBiometrics(), isFalse);- expect(await localAuth.getEnrolledBiometrics(), isEmpty);- expect(await localAuth.stopAuthentication(), isFalse);+ test(+ 'reports Polkit device support but no direct biometric support',+ () async {+ expect(await localAuth.isDeviceSupported(), isTrue);+ expect(await localAuth.deviceSupportsBiometrics(), isFalse);+ expect(await localAuth.getEnrolledBiometrics(), isEmpty);+ expect(await localAuth.stopAuthentication(), isFalse);+ },+ );++ test('reads setup status from native code', () async {+ final status = await localAuth.getSetupStatus();++ expect(status.actionId, linuxLocalAuthPolkitActionId);+ expect(status.policyAssetPath, '/usr/share/enteauth/policy');+ expect(status.polkitAvailable, isTrue);+ expect(status.policyInstalled, isTrue);+ expect(status.isFlatpak, isFalse);+ expect(status.setupRequired, isFalse);+ });++ test('maps missing Polkit policy to no credentials set', () async {+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, (_) async {+ throw PlatformException(+ code: 'setup_required',+ message: 'The Ente Auth Polkit policy is not installed.',+ );+ });++ await expectLater(+ localAuth.authenticate(+ localizedReason: 'Unlock Ente Auth',+ authMessages: const <AuthMessages>[],+ ),+ throwsA(+ isA<LocalAuthException>().having(+ (e) => e.code,+ 'code',+ LocalAuthExceptionCode.noCredentialsSet,+ ),+ ),+ );});}diff --git a/mobile/packages/lock_screen/lib/auth_util.dart b/mobile/packages/lock_screen/lib/auth_util.dartindex b581499fe3..6a43d2e266 100644--- a/mobile/packages/lock_screen/lib/auth_util.dart+++ b/mobile/packages/lock_screen/lib/auth_util.dart@@ -21,7 +21,12 @@ enum WindowsLocalAuthIssue {disabledByPolicy,}-enum LocalAuthUnavailableIssue { notConfigured, noHardware, unavailable }+enum LocalAuthUnavailableIssue {+ notConfigured,+ noHardware,+ unavailable,+ linuxSetupRequired,+}class LocalAuthenticationUnavailableException implements Exception {const LocalAuthenticationUnavailableException({@@ -47,6 +52,9 @@ class LocalAuthenticationUnavailableException implements Exception {LocalAuthUnavailableIssue.unavailable => pendingTranslation("System authentication is not available right now. Try again, or switch Ente App lock to PIN/password.",),+ LocalAuthUnavailableIssue.linuxSetupRequired => pendingTranslation(+ "Linux system authentication needs one-time setup. Install the Ente Auth Polkit policy, or switch Ente App lock to PIN/password.",+ ),};}@@ -126,6 +134,16 @@ bool isExpectedLocalAuthFailure(LocalAuthException error) {LocalAuthenticationUnavailableException?localAuthenticationUnavailableExceptionForError(LocalAuthException error) {final code = error.code;+ if (Platform.isLinux &&+ code == LocalAuthExceptionCode.noCredentialsSet &&+ (error.description?.contains("Polkit policy") ?? false)) {+ return LocalAuthenticationUnavailableException(+ issue: LocalAuthUnavailableIssue.linuxSetupRequired,+ code: code.name,+ description: error.description,+ originalError: error,+ );+ }final issue = switch (code) {LocalAuthExceptionCode.noCredentialsSet ||LocalAuthExceptionCode.noBiometricsEnrolled =>diff --git a/mobile/packages/lock_screen/lib/local_authentication_service.dart b/mobile/packages/lock_screen/lib/local_authentication_service.dartindex 7a66b24de7..ced13ac782 100644--- a/mobile/packages/lock_screen/lib/local_authentication_service.dart+++ b/mobile/packages/lock_screen/lib/local_authentication_service.dart@@ -13,6 +13,7 @@ import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:local_auth/local_auth.dart';+import 'package:local_auth_linux/local_auth_linux.dart';import 'package:logging/logging.dart';class LocalAuthenticationService {@@ -181,6 +182,18 @@ class LocalAuthenticationService {Future<bool> isLocalAuthSupportedOnDevice() async {try {+ if (Platform.isLinux) {+ final status = await getLinuxLocalAuthSetupStatus();+ logger.info(+ "Linux local authentication support: "+ "polkitAvailable=${status?.polkitAvailable}, "+ "policyInstalled=${status?.policyInstalled}, "+ "isFlatpak=${status?.isFlatpak}, "+ "error=${status?.errorMessage}",+ );+ return status?.polkitAvailable == true &&+ status?.policyInstalled == true;+ }if (Platform.isWindows) {final localAuth = LocalAuthentication();final isSupported = await localAuth.isDeviceSupported();@@ -202,4 +215,19 @@ class LocalAuthenticationService {return false;}}++ Future<LinuxLocalAuthSetupStatus?> getLinuxLocalAuthSetupStatus() async {+ if (!Platform.isLinux) {+ return null;+ }+ try {+ return await LocalAuthLinux().getSetupStatus();+ } on MissingPluginException {+ logger.warning("Linux local authentication plugin is not available");+ return null;+ } on PlatformException catch (e, s) {+ logger.warning("Failed to check Linux local authentication setup", e, s);+ return null;+ }+ }}diff --git a/mobile/packages/lock_screen/lib/ui/lock_screen_options.dart b/mobile/packages/lock_screen/lib/ui/lock_screen_options.dartindex 55a5364256..a574dcdc89 100644--- a/mobile/packages/lock_screen/lib/ui/lock_screen_options.dart+++ b/mobile/packages/lock_screen/lib/ui/lock_screen_options.dart@@ -68,6 +68,27 @@ class _LockScreenOptionsState extends State<LockScreenOptions> {await _lockScreenSettings.removePinAndPassword();await _lockScreenSettings.setSystemLockScreen(!isSystemLockEnabled);} else {+ final linuxStatus = await LocalAuthenticationService.instance+ .getLinuxLocalAuthSetupStatus();+ if (Platform.isLinux && linuxStatus?.setupRequired == true) {+ await showDialogWidget(+ context: context,+ title: pendingTranslation("Linux setup required"),+ body: pendingTranslation(+ "Install the Ente Auth Polkit policy, then try device lock again.\n\n${linuxStatus!.policyInstallCommand}",+ ),+ isDismissible: true,+ buttons: [+ ButtonWidget(+ buttonType: ButtonType.secondary,+ labelText: context.strings.ok,+ isInAlert: true,+ ),+ ],+ );+ await _initializeSettings();+ return;+ }await showDialogWidget(context: context,title: context.strings.noSystemLockFound,