Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions knox-agent/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,18 @@
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/**
* 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.knox;

import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
import org.apache.ranger.plugin.policyengine.RangerAccessResource;
import org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* @generated by Cursor
* @description <Unit Test for KnoxRangerPlugin class>
*/
@ExtendWith(MockitoExtension.class)
@TestMethodOrder(MethodOrderer.MethodName.class)
public class TestKnoxRangerPlugin {
@Test
public void test01_init_setsResultProcessorOnce() {
KnoxRangerPlugin plugin = new KnoxRangerPlugin();

Assertions.assertNull(plugin.getResultProcessor());
plugin.init();
Assertions.assertNotNull(plugin.getResultProcessor());

// second init should not reset and should not throw
plugin.init();
Assertions.assertNotNull(plugin.getResultProcessor());
}

@Test
public void test02_requestBuilder_verifyBuildable_throwsOnMissing() {
KnoxRangerPlugin.RequestBuilder b = new KnoxRangerPlugin.RequestBuilder();
Assertions.assertThrows(IllegalStateException.class, b::verifyBuildable);

b.service("svc");
Assertions.assertThrows(IllegalStateException.class, b::verifyBuildable);

b.topology("top");
Assertions.assertThrows(IllegalStateException.class, b::verifyBuildable);

b.user("u");
// no exception now
b.verifyBuildable();
}

@Test
public void test03_requestBuilder_build_setsAllFields() {
Set<String> groups = new HashSet<>(Arrays.asList("g1", "g2"));
List<String> fwd = Arrays.asList("1.1.1.1", "2.2.2.2");

KnoxRangerPlugin.RequestBuilder b = new KnoxRangerPlugin.RequestBuilder()
.service("svc")
.topology("top")
.user("user")
.groups(groups)
.clientIp("10.0.0.1")
.remoteIp("10.0.0.1")
.forwardedAddresses(fwd);

RangerAccessRequest req = b.build();
Assertions.assertEquals("user", req.getUser());
Assertions.assertEquals("allow", req.getAction());
Assertions.assertEquals("allow", req.getAccessType());
Assertions.assertEquals("10.0.0.1", req.getClientIPAddress());
Assertions.assertEquals(groups, req.getUserGroups());
Assertions.assertEquals(fwd, req.getForwardedAddresses());

RangerAccessResource res = req.getResource();
Assertions.assertTrue(res instanceof RangerAccessResourceImpl);
Assertions.assertEquals("svc", ((RangerAccessResourceImpl) res).getValue(KnoxRangerPlugin.KnoxConstants.ResourceName.Service));
Assertions.assertEquals("top", ((RangerAccessResourceImpl) res).getValue(KnoxRangerPlugin.KnoxConstants.ResourceName.Topology));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
/**
* 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.knox;

import org.apache.knox.gateway.filter.AbstractGatewayFilter;
import org.apache.knox.gateway.security.GroupPrincipal;
import org.apache.knox.gateway.security.ImpersonatedPrincipal;
import org.apache.knox.gateway.security.PrimaryPrincipal;
import org.apache.ranger.audit.provider.MiscUtil;
import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
import org.apache.ranger.plugin.policyengine.RangerAccessResult;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

import javax.security.auth.Subject;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.List;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
* @generated by Cursor
* @description <Unit Test for RangerPDPKnoxFilter class>
*/
@ExtendWith(MockitoExtension.class)
@TestMethodOrder(MethodOrderer.MethodName.class)
public class TestRangerPDPKnoxFilter {
@Test
public void test01_init_initializesPluginOnce() {
RangerPDPKnoxFilter filter = new RangerPDPKnoxFilter();
FilterConfig cfg = mock(FilterConfig.class);
when(cfg.getInitParameter("resource.role"))
.thenReturn("WEBHDFS");

try (MockedStatic<MiscUtil> mu = Mockito.mockStatic(MiscUtil.class)) {
filter.init(cfg);
// second init call should reuse existing plugin and not throw
filter.init(cfg);
}
}

@Test
public void test02_doFilter_accessAllowed_callsChain() throws Exception {
RangerPDPKnoxFilter filter = new RangerPDPKnoxFilter();

// prepare Subject with principals
Subject subject = new Subject();
subject.getPrincipals().add(new PrimaryPrincipal("primary"));
subject.getPrincipals().add(new ImpersonatedPrincipal("impersonated"));
subject.getPrincipals().add(new GroupPrincipal("g1"));
subject.getPrincipals().add(new GroupPrincipal("g2"));

ServletRequest req = mock(HttpServletRequest.class);
ServletResponse res = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);

when(req.getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME))
.thenReturn("/cluster/top1/path");
when(req.getRemoteAddr()).thenReturn("10.0.0.1");

// mock plugin
KnoxRangerPlugin plugin = Mockito.mock(KnoxRangerPlugin.class);
Field f = RangerPDPKnoxFilter.class.getDeclaredField("plugin");
f.setAccessible(true);
f.set(null, plugin);

RangerAccessResult allow = Mockito.mock(RangerAccessResult.class);
when(allow.getIsAllowed()).thenReturn(true);
when(plugin.isAccessAllowed(Mockito.any(RangerAccessRequest.class))).thenReturn(allow);

Subject.doAs(subject, (PrivilegedExceptionAction<Void>) () -> {
filter.doFilter(req, res, chain);
return null;
});
verify(chain, times(1)).doFilter(req, res);
}

@Test
public void test03_doFilter_accessDenied_sendsForbidden() throws Exception {
RangerPDPKnoxFilter filter = new RangerPDPKnoxFilter();
Subject subject = new Subject();
subject.getPrincipals().add(new PrimaryPrincipal("primary"));
ServletRequest req = mock(HttpServletRequest.class);
HttpServletResponse res = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);

when(req.getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME))
.thenReturn("/cluster/top1/path");
when(req.getRemoteAddr()).thenReturn("10.0.0.1");

KnoxRangerPlugin plugin = Mockito.mock(KnoxRangerPlugin.class);
Field f = RangerPDPKnoxFilter.class.getDeclaredField("plugin");
f.setAccessible(true);
f.set(null, plugin);

RangerAccessResult deny = Mockito.mock(RangerAccessResult.class);
when(deny.getIsAllowed()).thenReturn(false);
when(plugin.isAccessAllowed(Mockito.any(RangerAccessRequest.class))).thenReturn(deny);

Subject.doAs(subject, (PrivilegedExceptionAction<Void>) () -> {
filter.doFilter(req, res, chain);
return null;
});
verify(res, times(1)).sendError(403);
}

@Test
public void test04_getInitParameter_lowercasesName() {
RangerPDPKnoxFilter filter = new RangerPDPKnoxFilter();
FilterConfig cfg = mock(FilterConfig.class);
when(cfg.getInitParameter("resource.role")).thenReturn("WEBHDFS");
Assertions.assertEquals("WEBHDFS", invokeGetInitParameter(filter, cfg, "RESOURCE.ROLE"));
}

@Test
public void test05_getForwardedAddresses_parsesHeader() {
RangerPDPKnoxFilter filter = new RangerPDPKnoxFilter();
HttpServletRequest req = mock(HttpServletRequest.class);
when(req.getHeader("X-Forwarded-For")).thenReturn("1.1.1.1,2.2.2.2");
List<String> addrs = invokeGetForwardedAddresses(filter, req);
Assertions.assertEquals(Arrays.asList("1.1.1.1", "2.2.2.2"), addrs);

when(req.getHeader("X-Forwarded-For")).thenReturn(null);
Assertions.assertNull(invokeGetForwardedAddresses(filter, req));
}

@Test
public void test06_getTopologyName_extractsThirdTokenOrNull() {
RangerPDPKnoxFilter filter = new RangerPDPKnoxFilter();
Assertions.assertNull(invokeGetTopologyName(filter, null));
Assertions.assertNull(invokeGetTopologyName(filter, "/one"));
Assertions.assertEquals("two", invokeGetTopologyName(filter, "/one/two/three"));
}

private String invokeGetInitParameter(RangerPDPKnoxFilter filter, FilterConfig cfg, String name) {
try {
Method m = RangerPDPKnoxFilter.class.getDeclaredMethod("getInitParameter", FilterConfig.class, String.class);
m.setAccessible(true);
return (String) m.invoke(filter, cfg, name);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private List<String> invokeGetForwardedAddresses(RangerPDPKnoxFilter filter, ServletRequest req) {
try {
Method m = RangerPDPKnoxFilter.class.getDeclaredMethod("getForwardedAddresses", ServletRequest.class);
m.setAccessible(true);
@SuppressWarnings("unchecked")
List<String> ret = (List<String>) m.invoke(filter, req);
return ret;
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private String invokeGetTopologyName(RangerPDPKnoxFilter filter, String url) {
try {
Method m = RangerPDPKnoxFilter.class.getDeclaredMethod("getTopologyName", String.class);
m.setAccessible(true);
return (String) m.invoke(filter, url);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Loading
Loading