blob: f09a47d7905428ba0f8744b0c237cdc8a194232b [file] [log] [blame]
Matthias Andreas Benkard97f12022026-10-23 08:46:40 +02001<?php
2
3require_once(__DIR__ . '/../web/inc/vars.inc.php');
4if (file_exists(__DIR__ . '/../web/inc/vars.local.inc.php')) {
5 include_once(__DIR__ . '/../web/inc/vars.local.inc.php');
6}
7require_once __DIR__ . '/../web/inc/lib/vendor/autoload.php';
8
9// Init database
10//$dsn = $database_type . ':host=' . $database_host . ';dbname=' . $database_name;
11$dsn = $database_type . ":unix_socket=" . $database_sock . ";dbname=" . $database_name;
12$opt = [
13 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
14 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
15 PDO::ATTR_EMULATE_PREPARES => false,
16];
17try {
18 $pdo = new PDO($dsn, $database_user, $database_pass, $opt);
19}
20catch (PDOException $e) {
21 logMsg("err", $e->getMessage());
22 session_destroy();
23 exit;
24}
25
26// Init Redis
27$redis = new Redis();
28try {
29 if (!empty(getenv('REDIS_SLAVEOF_IP'))) {
30 $redis->connect(getenv('REDIS_SLAVEOF_IP'), getenv('REDIS_SLAVEOF_PORT'));
31 }
32 else {
33 $redis->connect('redis-mailcow', 6379);
34 }
35 $redis->auth(getenv("REDISPASS"));
36}
37catch (Exception $e) {
38 echo "Exiting: " . $e->getMessage();
39 session_destroy();
40 exit;
41}
42
43function logMsg($priority, $message, $task = "Keycloak Sync") {
44 global $redis;
45
46 $finalMsg = array(
47 "time" => time(),
48 "priority" => $priority,
49 "task" => $task,
50 "message" => $message
51 );
52 $redis->lPush('CRON_LOG', json_encode($finalMsg));
53}
54
55// Load core functions first
56require_once __DIR__ . '/../web/inc/functions.inc.php';
57require_once __DIR__ . '/../web/inc/functions.auth.inc.php';
58require_once __DIR__ . '/../web/inc/sessions.inc.php';
59require_once __DIR__ . '/../web/inc/functions.mailbox.inc.php';
60require_once __DIR__ . '/../web/inc/functions.ratelimit.inc.php';
61require_once __DIR__ . '/../web/inc/functions.acl.inc.php';
62
63$_SESSION['mailcow_cc_username'] = "admin";
64$_SESSION['mailcow_cc_role'] = "admin";
65$_SESSION['acl']['tls_policy'] = "1";
66$_SESSION['acl']['quarantine_notification'] = "1";
67$_SESSION['acl']['quarantine_category'] = "1";
68$_SESSION['acl']['ratelimit'] = "1";
69$_SESSION['acl']['sogo_access'] = "1";
70$_SESSION['acl']['protocol_access'] = "1";
71$_SESSION['acl']['mailbox_relayhost'] = "1";
72$_SESSION['acl']['unlimited_quota'] = "1";
73
74$iam_settings = identity_provider('get');
75if ($iam_settings['authsource'] != "keycloak" || (intval($iam_settings['periodic_sync']) != 1 && intval($iam_settings['import_users']) != 1)) {
76 session_destroy();
77 exit;
78}
79
80// Set pagination variables
81$start = 0;
82$max = 100;
83
84// lock sync if already running
85$lock_file = '/tmp/iam-sync.lock';
86if (file_exists($lock_file)) {
87 $lock_file_parts = explode("\n", file_get_contents($lock_file));
88 $pid = $lock_file_parts[0];
89 if (count($lock_file_parts) > 1){
90 $last_execution = $lock_file_parts[1];
91 $elapsed_time = (time() - $last_execution) / 60;
92 if ($elapsed_time < intval($iam_settings['sync_interval'])) {
93 logMsg("warning", "Sync not ready (".number_format((float)$elapsed_time, 2, '.', '')."min / ".$iam_settings['sync_interval']."min)");
94 session_destroy();
95 exit;
96 }
97 }
98
99 if (posix_kill($pid, 0)) {
100 logMsg("warning", "Sync is already running");
101 session_destroy();
102 exit;
103 } else {
104 unlink($lock_file);
105 }
106}
107$lock_file_handle = fopen($lock_file, 'w');
108fwrite($lock_file_handle, getmypid());
109fclose($lock_file_handle);
110
111// Init Keycloak Provider
112$iam_provider = identity_provider('init');
113
114// Loop until all users have been retrieved
115while (true) {
116 // Get admin access token
117 $admin_token = identity_provider("get-keycloak-admin-token");
118
119 // Make the API request to retrieve the users
120 $url = "{$iam_settings['server_url']}/admin/realms/{$iam_settings['realm']}/users?first=$start&max=$max";
121 $ch = curl_init();
122 curl_setopt($ch, CURLOPT_URL, $url);
123 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
124 curl_setopt($ch, CURLOPT_HTTPHEADER, [
125 "Content-Type: application/json",
126 "Authorization: Bearer " . $admin_token
127 ]);
128 $response = curl_exec($ch);
129 $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
130 curl_close($ch);
131
132 if ($code != 200){
133 logMsg("err", "Received HTTP {$code}");
134 session_destroy();
135 exit;
136 }
137 try {
138 $response = json_decode($response, true);
139 } catch (Exception $e) {
140 logMsg("err", $e->getMessage());
141 break;
142 }
143 if (!is_array($response)){
144 logMsg("err", "Received malformed response from keycloak api");
145 break;
146 }
147 if (count($response) == 0) {
148 break;
149 }
150
151 // Process the batch of users
152 foreach ($response as $user) {
153 if (empty($user['email'])){
154 logMsg("warning", "No email address in keycloak found for user " . $user['name']);
155 continue;
156 }
157
158 // try get mailbox user
159 $stmt = $pdo->prepare("SELECT
160 mailbox.*,
161 domain.active AS d_active
162 FROM `mailbox`
163 INNER JOIN domain on mailbox.domain = domain.domain
164 WHERE `kind` NOT REGEXP 'location|thing|group'
165 AND `username` = :user");
166 $stmt->execute(array(':user' => $user['email']));
167 $row = $stmt->fetch(PDO::FETCH_ASSOC);
168
169 // check if matching attribute mapping exists
170 $user_template = $user['attributes']['mailcow_template'][0];
171 $mapper_key = array_search($user_template, $iam_settings['mappers']);
172
173 $_SESSION['access_all_exception'] = '1';
174 if (!$row && intval($iam_settings['import_users']) == 1){
175 if ($mapper_key === false){
176 if (!empty($iam_settings['default_template'])) {
177 $mbox_template = $iam_settings['default_template'];
178 logMsg("warning", "Using default template for user " . $user['email']);
179 } else {
180 logMsg("warning", "No matching attribute mapping found for user " . $user['email']);
181 continue;
182 }
183 } else {
184 $mbox_template = $iam_settings['templates'][$mapper_key];
185 }
186 // mailbox user does not exist, create...
187 logMsg("info", "Creating user " . $user['email']);
188 $create_res = mailbox('add', 'mailbox_from_template', array(
189 'domain' => explode('@', $user['email'])[1],
190 'local_part' => explode('@', $user['email'])[0],
191 'name' => $user['firstName'] . " " . $user['lastName'],
192 'authsource' => 'keycloak',
193 'template' => $mbox_template
194 ));
195 if (!$create_res){
196 logMsg("err", "Could not create user " . $user['email']);
197 continue;
198 }
199 } else if ($row && intval($iam_settings['periodic_sync']) == 1 && $row['authsource'] == "keycloak") {
200 if ($mapper_key === false){
201 logMsg("warning", "No matching attribute mapping found for user " . $user['email']);
202 continue;
203 }
204 $mbox_template = $iam_settings['templates'][$mapper_key];
205 // mailbox user does exist, sync attribtues...
206 logMsg("info", "Syncing attributes for user " . $user['email']);
207 mailbox('edit', 'mailbox_from_template', array(
208 'username' => $user['email'],
209 'name' => $user['firstName'] . " " . $user['lastName'],
210 'template' => $mbox_template
211 ));
212 } else {
213 // skip mailbox user
214 logMsg("info", "Skipping user " . $user['email']);
215 }
216 $_SESSION['access_all_exception'] = '0';
217
218 sleep(0.025);
219 }
220
221 // Update the pagination variables for the next batch
222 $start += $max;
223 sleep(1);
224}
225
226logMsg("info", "DONE!");
227// add last execution time to lock file
228$lock_file_handle = fopen($lock_file, 'w');
229fwrite($lock_file_handle, getmypid() . "\n" . time());
230fclose($lock_file_handle);
231session_destroy();