From a93ec341571f54fe2aa52b5856bbecb89867411e Mon Sep 17 00:00:00 2001
From: Jakub Hrozek <jhrozek@redhat.com>
Date: Wed, 7 Nov 2018 13:26:59 +0100
Subject: [PATCH] SYSDB: Fall back to the MPG result of getgrgid search if the
 non-MPG search for override doesn't match anything

---
 src/db/sysdb_search.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/src/db/sysdb_search.c b/src/db/sysdb_search.c
index 43341d446..3549ffd89 100644
--- a/src/db/sysdb_search.c
+++ b/src/db/sysdb_search.c
@@ -1088,6 +1088,7 @@ int sysdb_getgrgid_attrs(TALLOC_CTX *mem_ctx,
     const char *fmt_filter;
     struct ldb_dn *base_dn;
     struct ldb_result *res = NULL;
+    struct ldb_result *mpg_res = NULL;
     int ret;
     static const char *default_attrs[] = SYSDB_GRSRC_ATTRS;
     const char **attrs = NULL;
@@ -1116,6 +1117,10 @@ int sysdb_getgrgid_attrs(TALLOC_CTX *mem_ctx,
          * In case those are not the same, we're dealing with an
          * override and in order to return the proper overridden group
          * we must use the very same search used by a non-mpg domain
+         * to make sure that if the GID points to a group, it will
+         * be resolved. But we must also make sure to fall back
+         * to using the MPG result if the GID does not resolve
+         * to a group
          */
         fmt_filter = SYSDB_GRGID_MPG_FILTER;
         base_dn = sysdb_domain_dn(tmp_ctx, domain);
@@ -1138,6 +1143,7 @@ int sysdb_getgrgid_attrs(TALLOC_CTX *mem_ctx,
             if (ul_originalad_gid != 0 && ul_originalad_gid != ul_gid) {
                 fmt_filter = SYSDB_GRGID_FILTER;
                 base_dn = sysdb_group_base_dn(tmp_ctx, domain);
+                mpg_res = res;
                 res = NULL;
             }
         }
@@ -1162,6 +1168,14 @@ int sysdb_getgrgid_attrs(TALLOC_CTX *mem_ctx,
         }
     }
 
+    if (mpg_res != NULL && res->count > 0
+            && (res == NULL || res->count == 0)) {
+        /* The overriden group does not resolve to a proper group object,
+         * just use it as a result
+         */
+        res = mpg_res;
+    }
+
     ret = mpg_res_convert(res);
     if (ret) {
         goto done;
