<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.ranger.authorization.kafka.authorizer;

import java.util.Date;
import java.util.Map;

import javax.security.auth.Subject;

import org.apache.kafka.common.network.LoginType;
import org.apache.kafka.common.security.auth.KafkaPrincipal;

import kafka.security.auth.*;
import kafka.network.RequestChannel.Session;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.kafka.common.security.authenticator.LoginManager;
import org.apache.ranger.audit.provider.MiscUtil;
import org.apache.ranger.plugin.audit.RangerDefaultAuditHandler;
import org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl;
import org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl;
import org.apache.ranger.plugin.policyengine.RangerAccessResult;
import org.apache.ranger.plugin.service.RangerBasePlugin;

import scala.collection.immutable.HashSet;
import scala.collection.immutable.Set;

public class RangerKafkaAuthorizer implements Authorizer {
	private static final Log logger = LogFactory
			.getLog(RangerKafkaAuthorizer.class);

	public static final String KEY_TOPIC = "topic";
	public static final String KEY_CLUSTER = "cluster";
	public static final String KEY_CONSUMER_GROUP = "consumer_group";

	public static final String ACCESS_TYPE_READ = "consume";
	public static final String ACCESS_TYPE_WRITE = "publish";
	public static final String ACCESS_TYPE_CREATE = "create";
	public static final String ACCESS_TYPE_DELETE = "delete";
	public static final String ACCESS_TYPE_CONFIGURE = "configure";
	public static final String ACCESS_TYPE_DESCRIBE = "describe";
	public static final String ACCESS_TYPE_KAFKA_ADMIN = "kafka_admin";

	private static volatile RangerBasePlugin rangerPlugin = null;

	public RangerKafkaAuthorizer() {
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see kafka.security.auth.Authorizer#configure(Map<String, Object>)
	 */
	@Override
	public void configure(Map<String, ?> configs) {
		RangerBasePlugin me = rangerPlugin;
		if (me == null) {
			synchronized(RangerKafkaAuthorizer.class) {
				me = rangerPlugin;
				if (me == null) {
					try {
						LoginManager loginManager = LoginManager.acquireLoginManager(LoginType.SERVER, true, configs);
						Subject subject = loginManager.subject();
						UserGroupInformation ugi = MiscUtil
								.createUGIFromSubject(subject);
						if (ugi != null) {
							MiscUtil.setUGILoginUser(ugi, subject);
						}
						logger.info("LoginUser=" + MiscUtil.getUGILoginUser());
					} catch (Throwable t) {
						logger.error("Error getting principal.", t);
					}
					me = rangerPlugin = new RangerBasePlugin("kafka", "kafka");
				}
			}
		}
		logger.info("Calling plugin.init()");
		rangerPlugin.init();
		RangerDefaultAuditHandler auditHandler = new RangerDefaultAuditHandler();
		rangerPlugin.setResultProcessor(auditHandler);
	}

	@Override
	public void close() {
		logger.info("close() called on authorizer.");
		try {
			if (rangerPlugin != null) {
				rangerPlugin.cleanup();
			}
		} catch (Throwable t) {
			logger.error("Error closing RangerPlugin.", t);
		}
	}

	@Override
	public boolean authorize(Session session, Operation operation,
			Resource resource) {

		if (rangerPlugin == null) {
			MiscUtil.logErrorMessageByInterval(logger,
					"Authorizer is still not initialized");
			return false;
		}

		// TODO: If resource type is consumer group, then allow it by default
		if (resource.resourceType().equals(Group$.MODULE$)) {
			if (logger.isDebugEnabled()) {
				logger.debug("If resource type is consumer group, then we allow it by default!  Returning true");
			}
			return true;
		}

		String userName = null;
		if (session.principal() != null) {
			userName = session.principal().getName();
			userName = StringUtils.substringBefore(userName, "/");
			userName = StringUtils.substringBefore(userName, "@");
		}
		java.util.Set<String> userGroups = MiscUtil
				.getGroupsForRequestUser(userName);
		String ip = session.clientAddress().getHostAddress();<commit_msg>RANGER-1648 : Ranger Kafka Plugin now should use the Short name from Kafka Session Object<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.ranger.authorization.kafka.authorizer;

import java.util.Date;
import java.util.Map;

import javax.security.auth.Subject;

import org.apache.kafka.common.network.LoginType;
import org.apache.kafka.common.security.auth.KafkaPrincipal;

import kafka.security.auth.*;
import kafka.network.RequestChannel.Session;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.kafka.common.security.authenticator.LoginManager;
import org.apache.ranger.audit.provider.MiscUtil;
import org.apache.ranger.plugin.audit.RangerDefaultAuditHandler;
import org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl;
import org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl;
import org.apache.ranger.plugin.policyengine.RangerAccessResult;
import org.apache.ranger.plugin.service.RangerBasePlugin;

import scala.collection.immutable.HashSet;
import scala.collection.immutable.Set;

public class RangerKafkaAuthorizer implements Authorizer {
	private static final Log logger = LogFactory
			.getLog(RangerKafkaAuthorizer.class);

	public static final String KEY_TOPIC = "topic";
	public static final String KEY_CLUSTER = "cluster";
	public static final String KEY_CONSUMER_GROUP = "consumer_group";

	public static final String ACCESS_TYPE_READ = "consume";
	public static final String ACCESS_TYPE_WRITE = "publish";
	public static final String ACCESS_TYPE_CREATE = "create";
	public static final String ACCESS_TYPE_DELETE = "delete";
	public static final String ACCESS_TYPE_CONFIGURE = "configure";
	public static final String ACCESS_TYPE_DESCRIBE = "describe";
	public static final String ACCESS_TYPE_KAFKA_ADMIN = "kafka_admin";

	private static volatile RangerBasePlugin rangerPlugin = null;

	public RangerKafkaAuthorizer() {
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see kafka.security.auth.Authorizer#configure(Map<String, Object>)
	 */
	@Override
	public void configure(Map<String, ?> configs) {
		RangerBasePlugin me = rangerPlugin;
		if (me == null) {
			synchronized(RangerKafkaAuthorizer.class) {
				me = rangerPlugin;
				if (me == null) {
					try {
						LoginManager loginManager = LoginManager.acquireLoginManager(LoginType.SERVER, true, configs);
						Subject subject = loginManager.subject();
						UserGroupInformation ugi = MiscUtil
								.createUGIFromSubject(subject);
						if (ugi != null) {
							MiscUtil.setUGILoginUser(ugi, subject);
						}
						logger.info("LoginUser=" + MiscUtil.getUGILoginUser());
					} catch (Throwable t) {
						logger.error("Error getting principal.", t);
					}
					me = rangerPlugin = new RangerBasePlugin("kafka", "kafka");
				}
			}
		}
		logger.info("Calling plugin.init()");
		rangerPlugin.init();
		RangerDefaultAuditHandler auditHandler = new RangerDefaultAuditHandler();
		rangerPlugin.setResultProcessor(auditHandler);
	}

	@Override
	public void close() {
		logger.info("close() called on authorizer.");
		try {
			if (rangerPlugin != null) {
				rangerPlugin.cleanup();
			}
		} catch (Throwable t) {
			logger.error("Error closing RangerPlugin.", t);
		}
	}

	@Override
	public boolean authorize(Session session, Operation operation,
			Resource resource) {

		if (rangerPlugin == null) {
			MiscUtil.logErrorMessageByInterval(logger,
					"Authorizer is still not initialized");
			return false;
		}

		// TODO: If resource type is consumer group, then allow it by default
		if (resource.resourceType().equals(Group$.MODULE$)) {
			if (logger.isDebugEnabled()) {
				logger.debug("If resource type is consumer group, then we allow it by default!  Returning true");
			}
			return true;
		}

		String userName = null;
		if (session.principal() != null) {
			userName = session.principal().getName();
		}
		java.util.Set<String> userGroups = MiscUtil
				.getGroupsForRequestUser(userName);
		String ip = session.clientAddress().getHostAddress();
{'fraction_non_alphanumeric': 0.09881825590872045, 'fraction_numerical': 0.0012224938875305623, 'mean_word_length': 4.505888951205833, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2684427', 'n_tokens_mistral': 3159, 'n_tokens_neox': 2831, 'n_words': 782}