keycloak-sync.php 7.1 KB

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