Esempio n. 1
0
    def session(self):
        """Get an instance of ``requests.Session``.

        By default, the session will not use certificate verification.

        To enable certificate verification:

        - set ``GLUU_COUCHBASE_VERIFY`` environment variable to ``true`` (default to ``false``)
        - ensure ``GLUU_COUCHBASE_CERT_FILE`` pointed to valid Couchbase cluster
          certificate (default to ``/etc/certs/couchbase.crt``)
        - optionally, set ``GLUU_COUCHBASE_HOST_HEADER`` to match Common Name
          or any of SubjectAltName defined in certificate (default to ``localhost``)
        """
        suppress_verification_warning()

        if not self._session:
            self._session = requests.Session()
            self._session.verify = False

            verify = as_boolean(os.environ.get("GLUU_COUCHBASE_VERIFY", False))
            if verify:
                self._session.mount("https://", HostHeaderSSLAdapter())
                self._session.verify = os.environ.get(
                    "GLUU_COUCHBASE_CERT_FILE") or "/etc/certs/couchbase.crt"
                self._session.headers["Host"] = os.environ.get(
                    "GLUU_COUCHBASE_HOST_HEADER") or "localhost"
        return self._session
Esempio n. 2
0
def main():
    sync_enabled = as_boolean(os.environ.get("GLUU_SYNC_JKS_ENABLED", False))
    if not sync_enabled:
        logger.warning("JKS sync is disabled")
        return

    # delay between JKS sync (in seconds)
    sync_interval = os.environ.get("GLUU_SYNC_JKS_INTERVAL", 30)

    try:
        sync_interval = int(sync_interval)
        # if value is lower than 1, use default
        if sync_interval < 1:
            sync_interval = 30
    except ValueError:
        sync_interval = 30

    try:
        while True:
            try:
                if should_sync_jks():
                    sync_jks()
                    sync_jwks()
            except Exception as exc:
                logger.warning(f"Got unhandled error; reason={exc}")

            # sane interval
            time.sleep(sync_interval)
    except KeyboardInterrupt:
        logger.warning("Canceled by user; exiting ...")
    def initialize(self):
        def is_initialized():
            persistence_type = os.environ.get("GLUU_PERSISTENCE_TYPE",
                                              "couchbase")
            ldap_mapping = os.environ.get("GLUU_PERSISTENCE_LDAP_MAPPING",
                                          "default")
            bucket_prefix = os.environ.get("GLUU_COUCHBASE_BUCKET_PREFIX",
                                           "gluu")

            # only _default_ and _user_ buckets that may have initial data;
            # these data also affected by LDAP mapping selection;
            # by default we will choose the _default_ bucket
            bucket, key = bucket_prefix, "configuration_oxtrust"

            # if `hybrid` is selected and default mapping is stored in LDAP,
            # the _default_ bucket won't have data, hence we check the _user_ bucket
            if persistence_type == "hybrid" and ldap_mapping == "default":
                bucket, key = f"{bucket_prefix}_user", "groups_60B7"

            query = "SELECT objectClass FROM {0} USE KEYS '{1}'".format(
                bucket, key)

            req = self.client.exec_query(query)
            if req.ok:
                data = req.json()
                return bool(data["results"])
            return False

        num_replica = int(os.environ.get("GLUU_COUCHBASE_INDEX_NUM_REPLICA",
                                         0))
        num_indexer_nodes = len(self.get_index_nodes())

        if num_replica >= num_indexer_nodes:
            raise ValueError(
                f"Number of index replica ({num_replica}) must be less than available indexer nodes ({num_indexer_nodes})"
            )

        self.index_num_replica = num_replica

        bucket_mappings = get_bucket_mappings()

        time.sleep(5)
        self.create_buckets(bucket_mappings)

        time.sleep(5)
        self.create_indexes(bucket_mappings)

        time.sleep(5)
        should_skip = as_boolean(
            os.environ.get("GLUU_PERSISTENCE_SKIP_EXISTING", True), )
        if should_skip and is_initialized():
            logger.info("Couchbase backend already initialized")
            return
        self.import_ldif(bucket_mappings)

        time.sleep(5)
        self.create_couchbase_shib_user()
Esempio n. 4
0
 def client(self):
     """Lazy-loaded client to interact with Kubernetes API.
     """
     if not self._client:
         if as_boolean(
                 self.settings["GLUU_SECRET_KUBERNETES_USE_KUBE_CONFIG"]):
             kubernetes.config.load_kube_config(self.kubeconfig_file)
         else:
             kubernetes.config.load_incluster_config()
         self._client = kubernetes.client.CoreV1Api()
     return self._client
Esempio n. 5
0
def main():
    persistence_type = os.environ.get("GLUU_PERSISTENCE_TYPE", "ldap")

    render_salt(manager, "/app/templates/salt.tmpl", "/etc/gluu/conf/salt")
    render_gluu_properties("/app/templates/gluu.properties.tmpl", "/etc/gluu/conf/gluu.properties")

    if persistence_type in ("ldap", "hybrid"):
        render_ldap_properties(
            manager,
            "/app/templates/gluu-ldap.properties.tmpl",
            "/etc/gluu/conf/gluu-ldap.properties",
        )
        sync_ldap_truststore(manager)

    if persistence_type in ("couchbase", "hybrid"):
        render_couchbase_properties(
            manager,
            "/app/templates/gluu-couchbase.properties.tmpl",
            "/etc/gluu/conf/gluu-couchbase.properties",
        )
        sync_couchbase_truststore(manager)

    if persistence_type == "hybrid":
        render_hybrid_properties("/etc/gluu/conf/gluu-hybrid.properties")

    if not os.path.isfile("/etc/certs/gluu_https.crt"):
        if as_boolean(os.environ.get("GLUU_SSL_CERT_FROM_SECRETS", False)):
            manager.secret.to_file("ssl_cert", "/etc/certs/gluu_https.crt")
        else:
            get_server_certificate(manager.config.get("hostname"), 443, "/etc/certs/gluu_https.crt")

    cert_to_truststore(
        "gluu_https",
        "/etc/certs/gluu_https.crt",
        "/usr/lib/jvm/default-jvm/jre/lib/security/cacerts",
        "changeit",
    )

    get_oxd_cert()
    cert_to_truststore(
        "gluu_oxd",
        "/etc/certs/oxd.crt",
        "/usr/lib/jvm/default-jvm/jre/lib/security/cacerts",
        "changeit",
    )
    modify_jetty_xml()
    modify_webdefault_xml()

    manager.secret.to_file("passport_rp_jks_base64", "/etc/certs/passport-rp.jks",
                           decode=True, binary_mode=True)

    config = CasaConfig(manager)
    config.setup()
Esempio n. 6
0
def wait_for_secret(manager, **kwargs):
    """Wait for readiness/availability of secret backend.

    If ``conn_only`` keyword argument is set to ``True``,
    this function only checks its connection status; if set
    to ``False`` or omitted, this function will check config entry.

    :param manager: An instance of :class:`~pygluu.containerlib.manager._Manager`.
    """
    conn_only = as_boolean(kwargs.get("conn_only", False))
    ssl_cert = manager.secret.get("ssl_cert")

    if not conn_only and not ssl_cert:
        raise WaitError("Secret 'ssl_cert' is not available")
Esempio n. 7
0
def wait_for_config(manager, **kwargs):
    """Wait for readiness/availability of config backend.

    If ``conn_only`` keyword argument is set to ``True``,
    this function only checks its connection status; if set
    to ``False`` or omitted, this function will check config entry.

    :param manager: An instance of :class:`~pygluu.containerlib.manager._Manager`.
    """
    conn_only = as_boolean(kwargs.get("conn_only", False))
    hostname = manager.config.get("hostname")

    if not conn_only and not hostname:
        raise WaitError("Config 'hostname' is not available")
Esempio n. 8
0
def render_repository_xml():
    is_cluster = as_boolean(os.environ.get("GLUU_JACKRABBIT_CLUSTER", False))
    pg_user = os.environ.get("GLUU_JACKRABBIT_POSTGRES_USER", "postgres")
    pg_password_file = os.environ.get("GLUU_JACKRABBIT_POSTGRES_PASSWORD_FILE", "/etc/gluu/conf/postgres_password")

    pg_password = ""
    with contextlib.suppress(FileNotFoundError):
        with open(pg_password_file) as f:
            pg_password = f.read().strip()

    pg_host = os.environ.get("GLUU_JACKRABBIT_POSTGRES_HOST", "localhost")
    pg_port = os.environ.get("GLUU_JACKRABBIT_POSTGRES_PORT", "5432")
    pg_database = os.environ.get("GLUU_JACKRABBIT_POSTGRES_DATABASE", "jackrabbit")

    # anon_id = "anonymous"
    # anon_id_file = os.environ.get("GLUU_JACKRABBIT_ANONYMOUS_ID_FILE", "/etc/gluu/conf/jackrabbit_anonymous_id")
    # with contextlib.suppress(FileNotFoundError):
    #     with open(anon_id_file) as f:
    #         anon_id = f.read().strip()

    # admin_id = "admin"
    # admin_id_file = os.environ.get("GLUU_JACKRABBIT_ADMIN_ID_FILE", "/etc/gluu/conf/jackrabbit_admin_id")
    # with contextlib.suppress(FileNotFoundError):
    #     with open(admin_id_file) as f:
    #         admin_id = f.read().strip()
    admin_id = os.environ.get("GLUU_JACKRABBIT_ADMIN_ID", "admin")

    ctx = {
        "node_name": socket.getfqdn(),
        "pg_host": pg_host,
        "pg_port": pg_port,
        "pg_database": pg_database,
        "pg_password": base64.b64encode(pg_password.encode()).decode(),
        "pg_user": pg_user,
        # "jackrabbit_anonymous_id": anon_id,
        "jackrabbit_anonymous_id": get_random_chars(),
        "jackrabbit_admin_id": admin_id,
    }

    if is_cluster:
        src = "/app/templates/repository.cluster.xml.tmpl"
    else:
        src = "/app/templates/repository.standalone.xml.tmpl"
    dest = "/opt/jackrabbit/repository.xml"

    with open(src) as f:
        txt = f.read()

    with open(dest, "w") as f:
        f.write(safe_render(txt, ctx))
    def _set_secret(self, key, value):
        if as_boolean(os.environ.get("GLUU_OVERWRITE_ALL", False)):
            logger.info("updating secret {!r}".format(key))
            self.ctx["secret"][key] = value
            return value

        # check existing key first
        if key in self.remote_secret_ctx:
            logger.info("ignoring secret {!r}".format(key))
            self.ctx["secret"][key] = value = self.remote_secret_ctx[key]
            return value

        logger.info("adding secret {!r}".format(key))
        self.ctx["secret"][key] = value
        return value
Esempio n. 10
0
    def initialize(self):
        def is_initialized():
            persistence_type = os.environ.get("GLUU_PERSISTENCE_TYPE", "ldap")
            ldap_mapping = os.environ.get("GLUU_PERSISTENCE_LDAP_MAPPING",
                                          "default")

            # a minimum service stack is having oxTrust, hence check whether entry
            # for oxTrust exists in LDAP
            default_search = ("ou=oxtrust,ou=configuration,o=gluu",
                              "(objectClass=oxTrustConfiguration)")

            if persistence_type == "hybrid":
                # `cache` and `token` mapping only have base entries
                search_mapping = {
                    "default":
                    default_search,
                    "user":
                    ("inum=60B7,ou=groups,o=gluu", "(objectClass=gluuGroup)"),
                    "site": ("ou=cache-refresh,o=site", "(ou=people)"),
                    "cache": ("o=gluu", "(objectClass=gluuOrganization)"),
                    "token": ("ou=tokens,o=gluu", "(ou=tokens)"),
                }
                search = search_mapping[ldap_mapping]
            else:
                search = default_search

            with self.conn as conn:
                conn.search(
                    search_base=search[0],
                    search_filter=search[1],
                    search_scope=SUBTREE,
                    attributes=['objectClass'],
                    size_limit=1,
                )
                return bool(conn.entries)

        should_skip = as_boolean(
            os.environ.get("GLUU_PERSISTENCE_SKIP_EXISTING", True), )
        if should_skip and is_initialized():
            logger.info("LDAP backend already initialized")
            return
        self.import_ldif()
Esempio n. 11
0
    def initialize(self):
        def is_initialized():
            persistence_type = os.environ.get("GLUU_PERSISTENCE_TYPE",
                                              "couchbase")
            ldap_mapping = os.environ.get("GLUU_PERSISTENCE_LDAP_MAPPING",
                                          "default")

            # only `gluu` and `gluu_user` buckets that may have initial data;
            # these data also affected by LDAP mapping selection;
            # by default we will choose the `gluu` bucket
            bucket, key = "gluu", "configuration_oxtrust"

            # if `hybrid` is selected and default mapping is stored in LDAP,
            # the `gluu` bucket won't have data, hence we check the `gluu_user` instead
            if persistence_type == "hybrid" and ldap_mapping == "default":
                bucket, key = "gluu_user", "groups_60B7"

            query = "SELECT objectClass FROM {0} USE KEYS '{1}'".format(
                bucket, key)

            req = self.client.exec_query(query)
            if req.ok:
                data = req.json()
                return bool(data["results"])
            return False

        should_skip = as_boolean(
            os.environ.get("GLUU_PERSISTENCE_SKIP_EXISTING", True), )
        if should_skip and is_initialized():
            logger.info("Couchbase backend already initialized")
            return

        bucket_mappings = get_bucket_mappings()

        time.sleep(5)
        self.create_buckets(bucket_mappings)

        time.sleep(5)
        self.create_indexes(bucket_mappings)

        time.sleep(5)
        self.import_ldif(bucket_mappings)
Esempio n. 12
0
    def _verify_cert(self, scheme, verify, cacert_file, cert_file, key_file) -> Tuple[Union[None, tuple], Union[bool, str]]:
        """Verify client cert and key.

        :params scheme: Scheme of Consul address.
        :params verify: Mark whether client needs to verify the address.
        :params cacert_file: Path to CA cert file.
        :params cert_file: Path to client's cert file.
        :params key_file: Path to client's key file.
        :returns: A pair of cert key files (if exist) and verification.
        """
        cert = None

        if scheme == "https":
            verify = as_boolean(verify)

            # verify using CA cert (if any)
            if all([verify, os.path.isfile(cacert_file)]):
                verify = cacert_file

            if all([os.path.isfile(cert_file), os.path.isfile(key_file)]):
                cert = (cert_file, key_file)
        return cert, verify
    def should_rotate(self):
        force_rotate = as_boolean(
            os.environ.get("GLUU_KEY_ROTATION_FORCE", False))
        if force_rotate:
            logger.warn("key rotation is set to force mode")
            return True

        last_rotation = self.manager.config.get("oxauth_key_rotated_at")

        # keys are not rotated yet
        if not last_rotation:
            return True

        # when keys are supposed to be rotated
        next_rotation = int(last_rotation) + (60 * 60 *
                                              int(self.rotation_interval))

        # current timestamp
        now = int(time.time())

        # check if current timestamp surpassed expected rotation timestamp
        return now > next_rotation
Esempio n. 14
0
def get_base_ctx(manager):
    passport_oxtrust_config = '''
    "passportUmaClientId":"%(passport_rs_client_id)s",
    "passportUmaClientKeyId":"%(passport_rs_client_cert_alias)s",
    "passportUmaResourceId":"%(passport_resource_id)s",
    "passportUmaScope":"https://%(hostname)s/oxauth/restv1/uma/scopes/passport_access",
    "passportUmaClientKeyStoreFile":"%(passport_rs_client_jks_fn)s",
    "passportUmaClientKeyStorePassword":"******",
''' % {
        "passport_rs_client_id":
        manager.config.get("passport_rs_client_id"),
        "passport_resource_id":
        manager.config.get("passport_resource_id"),
        "hostname":
        manager.config.get("hostname"),
        "pdp_ep":
        manager.config.get("pdp_ep"),
        "passport_rs_client_jks_fn":
        manager.config.get("passport_rs_client_jks_fn"),
        "passport_rs_client_jks_pass_encoded":
        manager.secret.get("passport_rs_client_jks_pass_encoded"),
        "passport_rs_client_cert_alias":
        manager.config.get("passport_rs_client_cert_alias"),
    }

    redis_pw = manager.secret.get("redis_pw") or ""
    redis_pw_encoded = ""

    if redis_pw:
        redis_pw_encoded = encode_text(
            redis_pw,
            manager.secret.get("encoded_salt"),
        )

    ctx = {
        'cache_provider_type':
        GLUU_CACHE_TYPE,
        'redis_url':
        GLUU_REDIS_URL,
        'redis_type':
        GLUU_REDIS_TYPE,
        'pdp_ep':
        PDP_EP,
        'redis_pw':
        redis_pw,
        'redis_pw_encoded':
        redis_pw_encoded,
        "redis_use_ssl":
        "{}".format(as_boolean(GLUU_REDIS_USE_SSL)).lower(),
        "redis_ssl_truststore":
        GLUU_REDIS_SSL_TRUSTSTORE,
        "redis_sentinel_group":
        GLUU_REDIS_SENTINEL_GROUP,
        'memcached_url':
        GLUU_MEMCACHED_URL,
        'ldap_hostname':
        manager.config.get('ldap_init_host', "localhost"),
        'ldaps_port':
        manager.config.get('ldap_init_port', 1636),
        'ldap_binddn':
        manager.config.get('ldap_binddn'),
        'encoded_ox_ldap_pw':
        manager.secret.get('encoded_ox_ldap_pw'),
        'jetty_base':
        manager.config.get('jetty_base'),
        'orgName':
        manager.config.get('orgName'),
        'oxauth_client_id':
        manager.config.get('oxauth_client_id'),
        'oxauthClient_encoded_pw':
        manager.secret.get('oxauthClient_encoded_pw'),
        'hostname':
        manager.config.get('hostname'),
        'idp_client_id':
        manager.config.get('idp_client_id'),
        'idpClient_encoded_pw':
        manager.secret.get('idpClient_encoded_pw'),
        'oxauth_openid_key_base64':
        manager.secret.get('oxauth_openid_key_base64'),
        'passport_rs_client_id':
        manager.config.get('passport_rs_client_id'),
        'passport_rs_client_base64_jwks':
        manager.secret.get('passport_rs_client_base64_jwks'),
        'passport_rp_client_id':
        manager.config.get('passport_rp_client_id'),
        'passport_rp_client_base64_jwks':
        manager.secret.get('passport_rp_client_base64_jwks'),
        "passport_rp_client_jks_fn":
        manager.config.get("passport_rp_client_jks_fn"),
        "passport_rp_client_jks_pass":
        manager.secret.get("passport_rp_client_jks_pass"),
        # "encoded_ldap_pw": manager.secret.get('encoded_ldap_pw'),
        "encoded_oxtrust_admin_password":
        manager.secret.get('encoded_oxtrust_admin_password'),
        'scim_rs_client_id':
        manager.config.get('scim_rs_client_id'),
        'scim_rs_client_base64_jwks':
        manager.secret.get('scim_rs_client_base64_jwks'),
        'scim_rs_client_cert_alias':
        manager.config.get("scim_rs_client_cert_alias"),
        'scim_rp_client_id':
        manager.config.get('scim_rp_client_id'),
        'scim_rp_client_base64_jwks':
        manager.secret.get('scim_rp_client_base64_jwks'),
        'scim_resource_oxid':
        manager.config.get('scim_resource_oxid'),
        'passport_rp_ii_client_id':
        manager.config.get("passport_rp_ii_client_id"),
        'api_rs_client_base64_jwks':
        manager.secret.get("api_rs_client_base64_jwks"),
        'api_rs_client_cert_alias':
        manager.config.get("api_rs_client_cert_alias"),
        'api_rp_client_base64_jwks':
        manager.secret.get("api_rp_client_base64_jwks"),
        'admin_email':
        manager.config.get('admin_email'),
        'shibJksFn':
        manager.config.get('shibJksFn'),
        'shibJksPass':
        manager.secret.get('shibJksPass'),
        'oxTrustConfigGeneration':
        str(as_boolean(GLUU_OXTRUST_CONFIG_GENERATION)).lower(),
        'encoded_shib_jks_pw':
        manager.secret.get('encoded_shib_jks_pw'),
        'scim_rs_client_jks_fn':
        manager.config.get('scim_rs_client_jks_fn'),
        'scim_rs_client_jks_pass_encoded':
        manager.secret.get('scim_rs_client_jks_pass_encoded'),
        'passport_rs_client_jks_fn':
        manager.config.get('passport_rs_client_jks_fn'),
        'passport_rs_client_jks_pass_encoded':
        manager.secret.get('passport_rs_client_jks_pass_encoded'),
        'shibboleth_version':
        manager.config.get('shibboleth_version'),
        'idp3Folder':
        manager.config.get('idp3Folder'),
        'ldap_site_binddn':
        manager.config.get('ldap_site_binddn'),
        'api_rs_client_jks_fn':
        manager.config.get("api_rs_client_jks_fn"),
        'api_rs_client_jks_pass_encoded':
        manager.secret.get("api_rs_client_jks_pass_encoded"),
        "oxtrust_requesting_party_client_id":
        manager.config.get("oxtrust_requesting_party_client_id"),
        "oxtrust_resource_server_client_id":
        manager.config.get("oxtrust_resource_server_client_id"),
        "oxtrust_resource_id":
        manager.config.get("oxtrust_resource_id"),
        "passport_resource_id":
        manager.config.get("passport_resource_id"),
        "passport_oxtrust_config":
        passport_oxtrust_config,
        "gluu_radius_client_id":
        manager.config.get("gluu_radius_client_id"),
        "gluu_ro_encoded_pw":
        manager.secret.get("gluu_ro_encoded_pw"),
        # "super_gluu_ro_session_script": manager.config.get("super_gluu_ro_session_script"),
        # "super_gluu_ro_script": manager.config.get("super_gluu_ro_script"),
        "enableRadiusScripts":
        "false",  # @TODO: enable it?
        "gluu_ro_client_base64_jwks":
        manager.secret.get("gluu_ro_client_base64_jwks"),
        "gluuPassportEnabled":
        str(as_boolean(GLUU_PASSPORT_ENABLED)).lower(),
        "gluuRadiusEnabled":
        str(as_boolean(GLUU_RADIUS_ENABLED)).lower(),
        "gluuSamlEnabled":
        str(as_boolean(GLUU_SAML_ENABLED)).lower(),
        "gluuScimEnabled":
        str(as_boolean(GLUU_SCIM_ENABLED)).lower(),
        "pairwiseCalculationKey":
        manager.secret.get("pairwiseCalculationKey"),
        "pairwiseCalculationSalt":
        manager.secret.get("pairwiseCalculationSalt"),
        "default_openid_jks_dn_name":
        manager.config.get("default_openid_jks_dn_name"),
        "oxauth_openid_jks_fn":
        manager.config.get("oxauth_openid_jks_fn"),
        "oxauth_openid_jks_pass":
        manager.secret.get("oxauth_openid_jks_pass"),
        "oxauth_legacyIdTokenClaims":
        manager.config.get("oxauth_legacyIdTokenClaims"),
        "passportSpTLSCert":
        manager.config.get("passportSpTLSCert"),
        "passportSpTLSKey":
        manager.config.get("passportSpTLSKey"),
        "oxauth_openidScopeBackwardCompatibility":
        manager.config.get("oxauth_openidScopeBackwardCompatibility"),
        "fido2ConfigFolder":
        manager.config.get("fido2ConfigFolder"),
        "admin_inum":
        manager.config.get("admin_inum"),
        "enable_oxtrust_api_access_policy":
        str(as_boolean(GLUU_OXTRUST_API_ENABLED)).lower(),
        "oxtrust_api_test_mode":
        str(as_boolean(GLUU_OXTRUST_API_TEST_MODE)).lower(),
        "api_test_client_id":
        manager.config.get("api_test_client_id"),
        "encoded_api_test_client_secret":
        encode_text(
            manager.secret.get("api_test_client_secret"),
            manager.secret.get("encoded_salt"),
        ),
        "enable_scim_access_policy":
        str(
            as_boolean(GLUU_SCIM_ENABLED)
            or as_boolean(GLUU_PASSPORT_ENABLED)).lower(),
        "scimTestMode":
        str(as_boolean(GLUU_SCIM_TEST_MODE)).lower(),
        "scim_test_client_id":
        manager.config.get("scim_test_client_id"),
        "encoded_scim_test_client_secret":
        encode_text(
            manager.secret.get("scim_test_client_secret"),
            manager.secret.get("encoded_salt"),
        ),
        "casa_enable_script":
        str(as_boolean(GLUU_CASA_ENABLED)).lower(),
    }
    return ctx
Esempio n. 15
0
def main():
    is_cluster = as_boolean(os.environ.get("GLUU_JACKRABBIT_CLUSTER", False))
    if not is_cluster:
        return

    wait_for_postgres(None, **{"label": "Postgres"})
Esempio n. 16
0
        )
        sync_ldap_truststore(manager)

    if persistence_type in ("couchbase", "hybrid"):
        render_couchbase_properties(
            manager,
            "/app/templates/gluu-couchbase.properties.tmpl",
            "/etc/gluu/conf/gluu-couchbase.properties",
        )
        sync_couchbase_truststore(manager)

    if persistence_type == "hybrid":
        render_hybrid_properties("/etc/gluu/conf/gluu-hybrid.properties")

    if not os.path.isfile("/etc/certs/gluu_https.crt"):
        if as_boolean(os.environ.get("GLUU_SSL_CERT_FROM_SECRETS", False)):
            manager.secret.to_file("ssl_cert", "/etc/certs/gluu_https.crt")
        else:
            get_server_certificate(manager.config.get("hostname"), 443,
                                   "/etc/certs/gluu_https.crt")

    cert_to_truststore(
        "gluu_https",
        "/etc/certs/gluu_https.crt",
        "/usr/lib/jvm/default-jvm/jre/lib/security/cacerts",
        "changeit",
    )

    if not os.path.isfile("/etc/certs/shibIDP.crt"):
        manager.secret.to_file("shibIDP_cert",
                               "/etc/certs/shibIDP.crt",
Esempio n. 17
0
def render_couchbase_properties(manager, src: str, dest: str) -> None:
    """Render file contains properties to connect to Couchbase server,
    i.e. ``/etc/gluu/conf/gluu-couchbase.properties``.

    :params manager: An instance of :class:`~pygluu.containerlib.manager._Manager`.
    :params src: Absolute path to the template.
    :params dest: Absolute path where generated file is located.
    """
    persistence_type = os.environ.get("GLUU_PERSISTENCE_TYPE", "couchbase")
    ldap_mapping = os.environ.get("GLUU_PERSISTENCE_LDAP_MAPPING", "default")
    hostname = os.environ.get("GLUU_COUCHBASE_URL", "localhost")
    bucket_prefix = os.environ.get("GLUU_COUCHBASE_BUCKET_PREFIX", "gluu")

    _couchbase_mappings = get_couchbase_mappings(persistence_type,
                                                 ldap_mapping)
    couchbase_buckets = []
    couchbase_mappings = []

    for _, mapping in _couchbase_mappings.items():
        couchbase_buckets.append(mapping["bucket"])

        if not mapping["mapping"]:
            continue

        couchbase_mappings.append(
            f"bucket.{mapping['bucket']}.mapping: {mapping['mapping']}")

    # always have  _default_ bucket
    if bucket_prefix not in couchbase_buckets:
        couchbase_buckets.insert(0, bucket_prefix)

    with open(src) as fr:
        txt = fr.read()

        with open(dest, "w") as fw:
            rendered_txt = txt % {
                "hostname":
                hostname,
                "couchbase_server_user":
                get_couchbase_user(manager),
                "encoded_couchbase_server_pw":
                get_encoded_couchbase_password(manager),
                "couchbase_buckets":
                ", ".join(couchbase_buckets),
                "default_bucket":
                bucket_prefix,
                "couchbase_mappings":
                "\n".join(couchbase_mappings),
                "encryption_method":
                "SSHA-256",
                "ssl_enabled":
                str(
                    as_boolean(
                        os.environ.get("GLUU_COUCHBASE_TRUSTSTORE_ENABLE",
                                       True))).lower(),
                "couchbaseTrustStoreFn":
                manager.config.get("couchbaseTrustStoreFn"),
                "encoded_couchbaseTrustStorePass":
                encode_text(
                    GLUU_COUCHBASE_TRUSTSTORE_PASSWORD,
                    manager.secret.get("encoded_salt"),
                ).decode(),
                "couchbase_conn_timeout":
                get_couchbase_conn_timeout(),
                "couchbase_conn_max_wait":
                get_couchbase_conn_max_wait(),
                "couchbase_scan_consistency":
                get_couchbase_scan_consistency(),
            }
            fw.write(rendered_txt)
def test_as_boolean(val, expected):
    from pygluu.containerlib.utils import as_boolean
    assert as_boolean(val) == expected
Esempio n. 19
0
def main():
    persistence_type = os.environ.get("GLUU_PERSISTENCE_TYPE", "ldap")

    render_salt(manager, "/app/templates/salt.tmpl", "/etc/gluu/conf/salt")
    render_gluu_properties("/app/templates/gluu.properties.tmpl",
                           "/etc/gluu/conf/gluu.properties")

    if persistence_type in ("ldap", "hybrid"):
        render_ldap_properties(
            manager,
            "/app/templates/gluu-ldap.properties.tmpl",
            "/etc/gluu/conf/gluu-ldap.properties",
        )
        sync_ldap_truststore(manager)

    if persistence_type in ("couchbase", "hybrid"):
        render_couchbase_properties(
            manager,
            "/app/templates/gluu-couchbase.properties.tmpl",
            "/etc/gluu/conf/gluu-couchbase.properties",
        )
        sync_couchbase_truststore(manager)

    if persistence_type == "hybrid":
        render_hybrid_properties("/etc/gluu/conf/gluu-hybrid.properties")

    if not os.path.isfile("/etc/certs/gluu_https.crt"):
        if as_boolean(os.environ.get("GLUU_SSL_CERT_FROM_SECRETS", False)):
            manager.secret.to_file("ssl_cert", "/etc/certs/gluu_https.crt")
        else:
            get_server_certificate(manager.config.get("hostname"), 443,
                                   "/etc/certs/gluu_https.crt")

    cert_to_truststore(
        "gluu_https",
        "/etc/certs/gluu_https.crt",
        "/usr/lib/jvm/default-jvm/jre/lib/security/cacerts",
        "changeit",
    )

    # if not os.path.isfile("/etc/certs/idp-signing.crt"):
    #     manager.secret.to_file("idp3SigningCertificateText", "/etc/certs/idp-signing.crt")

    # manager.secret.to_file("passport_rp_jks_base64", "/etc/certs/passport-rp.jks",
    #                        decode=True, binary_mode=True)

    manager.secret.to_file("scim_rs_jks_base64",
                           "/etc/certs/scim-rs.jks",
                           decode=True,
                           binary_mode=True)
    with open(manager.config.get("scim_rs_client_jwks_fn"), "w") as f:
        f.write(
            base64.b64decode(
                manager.secret.get("scim_rs_client_base64_jwks")).decode())

    manager.secret.to_file("scim_rp_jks_base64",
                           "/etc/certs/scim-rp.jks",
                           decode=True,
                           binary_mode=True)
    with open(manager.config.get("scim_rp_client_jwks_fn"), "w") as f:
        f.write(
            base64.b64decode(
                manager.secret.get("scim_rp_client_base64_jwks")).decode())

    modify_jetty_xml()
    modify_webdefault_xml()
Esempio n. 20
0
def suppress_verification_warning():
    import urllib3

    if as_boolean(os.environ.get("GLUU_COUCHBASE_SUPPRESS_VERIFICATION",
                                 True)):
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)