CurrentPermissionsWriter.java

/*
 * Copyright 2018 Global Crop Diversity Trust
 *
 * Licensed 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.genesys.blocks.security.serialization;

import org.genesys.blocks.security.SecurityContextUtil;
import org.genesys.blocks.security.model.AclAwareModel;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.fasterxml.jackson.annotation.JsonIgnoreType;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.fasterxml.jackson.databind.ser.VirtualBeanPropertyWriter;
import com.fasterxml.jackson.databind.util.Annotations;

import lombok.extern.slf4j.Slf4j;

/**
 * The <code>CurrentPermissionsWriter</code> is applied to {@link AclAwareModel} and it
 * instructs Jackson to include {@link Permissions} for current SID for every
 * ACL aware entity.
 * 
 * The serialization of {@code Permissions} as {@code "_permissions"} property is enabled
 * with the <code>@JsonAppend</code> annotation on <code>AclAwareModel</code>:
 * 
 * <pre>
 *  &#64;JsonAppend(props = { @JsonAppend.Prop(name="_permissions", value = CurrentPermissionsWriter.class, type=CurrentPermissions.class) })
 *  public interface AclAwareModel...
 * </pre>
 * 
 * To be able to access the current permissions of the current SID, this code
 * requires that an instance of
 * <code>org.genesys.blocks.util.CurrentApplicationContext</code> is
 * registered in the Spring application context.
 * <p>
 * Writer can be disabled with {@code @JsonView(CurrentPermissionsWriter.NoPermissions.class)}
 * (or a {@code JsonView} extending it):
 * 
 * <pre>
 *  static interface RootNoPermissions extends JsonViews.Root, CurrentPermissionsWriter.NoPermissions { }
 * </pre>
 * 
 * <b>or</b> by mix-in that ignores {@link Permissions} type:
 * 
 * <pre>
 *  {@code @JsonIgnoreType}
 *  public class MyMixInForIgnoreType {}
 *  ...
 *  mapper.addMixIn(Permissions.class, MyMixInForIgnoreType.class);
 * </pre>
 */
@Slf4j
public class CurrentPermissionsWriter extends VirtualBeanPropertyWriter {

	/**
	 * Use this JsonView to exclude permission checks!
	 */
	public static interface NoPermissions {
	}

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/**
	 * Writer can be disabled with <code>@JsonView(CurrentPermissionsWriter.NoPermissions.class)</code>
	 * or by mix-in that ignores <code>{@link Permissions}.class</code>:
	 * 
	 * <pre>
	 *  {@code @JsonIgnoreType}
	 *  public class MyMixInForIgnoreType {}
	 *  ...
	 *  mapper.addMixIn(Permissions.class, MyMixInForIgnoreType.class);
	 * </pre>
	 */
	private boolean enabled = true;

	private static final Permissions NO_PERMISSIONS = new Permissions().grantNone();

	/**
	 * Instantiates a new current permissions writer.
	 */
	public CurrentPermissionsWriter() {
		log.trace("CurrentPermissionsWriter");
	}

	/**
	 * Instantiates a new current permissions writer.
	 *
	 * @param propDef the prop def
	 * @param annotations the annotations
	 * @param type the type
	 */
	public CurrentPermissionsWriter(BeanPropertyDefinition propDef, Annotations annotations, JavaType type) {
		super(propDef, annotations, type);
		log.trace("CurrentPermissionsWriter {} {}", propDef, type);
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * com.fasterxml.jackson.databind.ser.VirtualBeanPropertyWriter#value(java.lang.
	 * Object, com.fasterxml.jackson.core.JsonGenerator,
	 * com.fasterxml.jackson.databind.SerializerProvider)
	 */
	@Override
	protected Object value(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
		if (!enabled) {
			// We are not enabled
			return null;
		}
		if (bean == null || !(bean instanceof AclAwareModel)) {
			// Skip nulls
			return null;
		}

		AclAwareModel aclAwareModel = (AclAwareModel) bean;

		if (aclAwareModel.getId() == null) {
			// Don't write permissions for non-persisted objects
			return null;
		}
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return NO_PERMISSIONS;
		}
		Permissions perms = new Permissions();
		try {
			perms.isPublic = SecurityContextUtil.anyoneHasPermission(aclAwareModel, "READ");
		} catch (Throwable e) {
			log.warn("Could not read public permissions {}", e.getMessage(), e);
			perms.isPublic = false;
		}

		if (SecurityContextUtil.hasRole("ADMINISTRATOR")) {
			perms.grantAll();
		} else {
			try {
				perms.create = SecurityContextUtil.hasPermission(authentication, aclAwareModel, BasePermission.CREATE);
				perms.read = SecurityContextUtil.hasPermission(authentication, aclAwareModel, BasePermission.READ);
				perms.write = SecurityContextUtil.hasPermission(authentication, aclAwareModel, BasePermission.WRITE);
				perms.delete = SecurityContextUtil.hasPermission(authentication, aclAwareModel, BasePermission.DELETE);
				perms.manage = SecurityContextUtil.hasPermission(authentication, aclAwareModel, BasePermission.ADMINISTRATION);
			} catch (Throwable e) {
				log.warn("Could not read current permissions {}", e.getMessage(), e);
			}
		}
		return perms;
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * com.fasterxml.jackson.databind.ser.VirtualBeanPropertyWriter#withConfig(com.
	 * fasterxml.jackson.databind.cfg.MapperConfig,
	 * com.fasterxml.jackson.databind.introspect.AnnotatedClass,
	 * com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition,
	 * com.fasterxml.jackson.databind.JavaType)
	 */
	@Override
	public VirtualBeanPropertyWriter withConfig(MapperConfig<?> config, AnnotatedClass declaringClass, BeanPropertyDefinition propDef, JavaType type) {
		var writer = new CurrentPermissionsWriter(propDef, declaringClass.getAnnotations(), type);

		var permissionsMixin = config.findMixInClassFor(Permissions.class);
		if (permissionsMixin != null) {
			var isIgnoredType = permissionsMixin.getAnnotation(JsonIgnoreType.class);
			log.warn("Mixin for {} has @JsonIgnoreType={}", Permissions.class, isIgnoredType);
			if (isIgnoredType != null) {
				log.debug("Permissions.class is @JsonIgnoreType({})", isIgnoredType.value());
				writer.enabled = ! isIgnoredType.value(); // Enable or disable checks
			}
		}

		var activeView = config.getActiveView();
		log.trace("Active JsonView {}", activeView);
		if (activeView != null && NoPermissions.class.isAssignableFrom(activeView)) {
			log.debug("Not computing permissions for @JsonView(CurrentPermissionWriter.NoPermissions.class)");
			writer.enabled = false;
		}

		return writer;
	}

}