Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PoC kotlin data classes #1662

Closed
wants to merge 2 commits into from
Closed
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
4 changes: 2 additions & 2 deletions languages/java/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ test: rust
cd oso && mvn $(MVN_FLAGS) clean test

package: rust
cd oso && mvn $(MVN_FLAGS) clean package
cd oso && mvn $(MVN_FLAGS) clean install
Copy link
Author

@wcurrie wcurrie Jan 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just so I could use the locally built 0.26.5-SNAPSHOT in other projects like a fork of #1655

I built using:

$ MVN_FLAGS=-Dgpg.skip make package


repl: rust
cd oso && mvn $(MVN_FLAGS) exec:java -Dexec.mainClass="com.osohq.oso.Oso" -Dexec.args="$(ARGS)"
Expand All @@ -27,4 +27,4 @@ fmt:
$(MAKE) -C ../.. fmt-java

clean:
cd oso && mvn clean
cd oso && mvn clean
34 changes: 30 additions & 4 deletions languages/java/oso/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

<groupId>com.osohq</groupId>
<artifactId>oso</artifactId>
<!-- oso_version --><version>0.26.4</version>
<!-- oso_version --><version>0.26.5-SNAPSHOT</version>

<distributionManagement>
<snapshotRepository>
Expand All @@ -38,8 +38,9 @@

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<kotlin.version>1.8.0</kotlin.version>
</properties>

<dependencies>
Expand All @@ -62,6 +63,12 @@
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
Expand Down Expand Up @@ -90,7 +97,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<version>3.4.1</version>
<executions>
<execution>
<phase>package</phase>
Expand Down Expand Up @@ -183,6 +190,25 @@
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>

<executions>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>

<pluginManagement> <!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
Expand Down
30 changes: 23 additions & 7 deletions languages/java/oso/src/main/java/com/osohq/oso/Query.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections4.IteratorUtils;
import org.json.JSONArray;
import org.json.JSONException;
Expand Down Expand Up @@ -114,13 +115,7 @@ private void handleCall(
}
result = method.invoke(instance, args.get().toArray());
} else {
// Look for a field with the given name.
try {
Field field = cls.getField(attrName);
result = field.get(instance);
} catch (NoSuchFieldException f) {
throw new Exceptions.InvalidAttributeError(cls.getName(), attrName);
}
result = getFromFieldOrRecordAccessor(attrName, instance, cls);
}
String term = host.toPolarTerm(result).toString();
ffiQuery.callResult(callId, term);
Expand All @@ -141,6 +136,27 @@ private void handleCall(
}
}

private Object getFromFieldOrRecordAccessor(String attrName, Object instance, Class<?> cls) throws IllegalAccessException {
// Look for a field with the given name.
try {
Field field = cls.getField(attrName);
return field.get(instance);
} catch (NoSuchFieldException ignored) {
}
// Assume record, try foo() for attrName=foo
try {
Method method = cls.getMethod(attrName);
return method.invoke(instance);
} catch (NoSuchMethodException | InvocationTargetException ignored) {
}
// For kotlin data classes, try getFoo() for attrName=foo
try {
return PropertyUtils.getProperty(instance, attrName);
} catch (NoSuchMethodException | InvocationTargetException ignored) {
}
throw new Exceptions.InvalidAttributeError(cls.getName(), attrName);
}

/** Helper for `NextExternal` query events */
private void handleNextExternal(long callId, JSONObject iterable) throws Exceptions.OsoException {
if (!calls.containsKey(callId)) {
Expand Down
155 changes: 155 additions & 0 deletions languages/java/oso/src/test/java/com/osohq/oso/OsoJavaRecordTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package com.osohq.oso;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.junit.jupiter.api.Assertions.*;

public class OsoJavaRecordTest {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy paste of the existing OsoTest with record User instead of class User

protected Oso o;

public record User(String name) {
public List<Company> companies() {
return List.of(new Company(1));
}
}

public record Widget(int id) {
}

public record Company(int id) {

public String role(User a) {
if (a.name.equals("president")) {
return "admin";
}

return "guest";
}
}

@BeforeEach
public void setUp() throws Exception {
try {
URL testOso = getClass().getClassLoader().getResource("test_oso.polar");

o = new Oso();
o.registerClass(User.class, "User");
o.registerClass(Widget.class, "Widget");
o.registerClass(Company.class, "Company");

o.loadFile(testOso.getPath());
} catch (Exception e) {
throw new Error(e);
}
}

@Test
public void testIsAllowed() throws Exception {
User guest = new User("guest");
Widget resource1 = new Widget(1);
assertTrue(o.isAllowed(guest, "get", resource1));

User president = new User("president");
Company company = new Company(1);
assertTrue(o.isAllowed(president, "create", company));
}

@Test
public void testFail() throws Exception {
User guest = new User("guest");
Widget widget = new Widget(1);
assertFalse(o.isAllowed(guest, "not_allowed", widget));
}

@Test
public void testInstanceFromExternalCall() throws Exception {
Company company = new Company(1);
User guest = new User("guest");
assertTrue(o.isAllowed(guest, "frob", company));

// if the guest user can do it, then the dict should
// create an instance of the user and be allowed
HashMap<String, String> userMap = new HashMap<String, String>();
userMap.put("username", "guest");
assertTrue(o.isAllowed(userMap, "frob", company));
}

@Test
public void testAllowModel() throws Exception {
User auditor = new User("auditor");

assertTrue(o.isAllowed(auditor, "list", Company.class));
assertFalse(o.isAllowed(auditor, "list", Widget.class));
}

@Test
public void testGetAllowedActions() throws Exception {

Oso o = new Oso();
o.registerClass(User.class, "User");
o.registerClass(Widget.class, "Widget");

o.loadStr(
"allow(_actor: User{name: \"sally\"}, action, _resource: Widget{id: 1})"
+ " if action in [\"CREATE\", \"READ\"];");

User actor = new User("sally");
Widget widget = new Widget(1);
HashSet<Object> actions = o.getAllowedActions(actor, widget);

assertEquals(actions.size(), 2);
assertTrue(actions.contains("CREATE"));
assertTrue(actions.contains("READ"));

o.clearRules();

o.loadStr(
"allow(_actor: User{name: \"fred\"}, action, _resource: Widget{id: 2})"
+ " if action in [1, 2, 3, 4];");

User actor2 = new User("fred");
Widget widget2 = new Widget(2);
HashSet<Object> actions2 = o.getAllowedActions(actor2, widget2);

assertEquals(actions2.size(), 4);
assertTrue(actions2.contains(1));
assertTrue(actions2.contains(2));
assertTrue(actions2.contains(3));
assertTrue(actions2.contains(4));

User actor3 = new User("doug");
Widget widget3 = new Widget(4);
assertTrue(o.getAllowedActions(actor3, widget3).isEmpty());
}

@Test
public void testGetAllowedActionsWildcard() throws Exception {
Oso o = new Oso();

o.registerClass(User.class, "User");
o.registerClass(Widget.class, "Widget");

o.loadStr("allow(_actor: User{name: \"John\"}, _action, _resource: Widget{id: 1});");

User actor = new User("John");
Widget widget = new Widget(1);

assertEquals(Set.of("*"), o.getAllowedActions(actor, widget, true));
assertThrows(Exceptions.OsoException.class, () -> o.getAllowedActions(actor, widget, false));
}

@Test
public void testNotEqualOperator() {
Oso oso = new Oso();
oso.registerClass(User.class, "User");
oso.loadStr("allow(actor: User, _action, _resource) if actor != nil;");
assertFalse(oso.isAllowed(null, "foo", "foo"));
}
}
Loading
Loading