You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@syncope.apache.org by il...@apache.org on 2025/03/04 13:06:50 UTC
(syncope) branch master updated: [SYNCOPE-1834] OpenFGA extension (#998)
This is an automated email from the ASF dual-hosted git repository.
ilgrosso pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/syncope.git
The following commit(s) were added to refs/heads/master by this push:
new ab5bd7341b [SYNCOPE-1834] OpenFGA extension (#998)
ab5bd7341b is described below
commit ab5bd7341b71e63b8f02cf46f249f4536229def2
Author: Francesco Chicchiriccò <il...@users.noreply.github.com>
AuthorDate: Tue Mar 4 14:06:45 2025 +0100
[SYNCOPE-1834] OpenFGA extension (#998)
---
.github/workflows/crosschecks.yml | 1 +
.github/workflows/fit_WA_OIDCC4UI.yml | 2 +-
.../{fit_WA_OIDCC4UI.yml => fit_WA_OpenFGA.yml} | 10 +-
.../common/lib/policy/OpenFGAAccessPolicyConf.java | 86 +
.../apache/syncope/core/logic/AnyTypeLogic.java | 30 +-
.../syncope/core/logic/IdRepoLogicContext.java | 11 +-
.../syncope/core/logic/RelationshipTypeLogic.java | 23 +-
.../persistence/api/dao/RelationshipTypeDAO.java | 2 +
.../jpa/dao/repo/RelationshipTypeRepoExt.java | 3 +
.../jpa/dao/repo/RelationshipTypeRepoExtImpl.java | 10 +
.../neo4j/dao/repo/RelationshipTypeRepoExt.java | 3 +
.../dao/repo/RelationshipTypeRepoExtImpl.java | 11 +
.../neo4j/entity/Neo4jRelationshipType.java | 4 +-
.../client/ElasticsearchClientContext.java | 3 +-
ext/openfga/client-openfga/pom.xml | 120 +
.../syncope/ext/openfga/client/OpenFGAClient.java | 117 +
.../ext/openfga/client/OpenFGAClientContext.java | 79 +
.../ext/openfga/client/OpenFGAClientFactory.java | 114 +
.../ext/openfga/client/OpenFGAHealthIndicator.java | 72 +
.../ext/openfga/client/OpenFGAProperties.java | 97 +
.../ext/openfga/client/OpenFGAStoreManager.java | 315 ++
...rk.boot.autoconfigure.AutoConfiguration.imports | 17 +
.../client-openfga/src/main/resources/openfga.yaml | 3277 ++++++++++++++++++++
.../ext/openfga/client/OpenFGAClientTest.java | 258 ++
.../openfga/client/OpenFGAClientTestContext.java | 66 +
.../src/test/resources/core-test.properties | 18 +
.../src/test/resources/simplelogger.properties | 24 +
ext/openfga/pom.xml | 45 +
ext/openfga/provisioning-java/pom.xml | 62 +
.../core/provisioning/java/job/OpenFGAReinit.java | 142 +
ext/pom.xml | 1 +
fit/core-reference/pom.xml | 8 +-
.../fit/core/reference/ITImplementationLookup.java | 1 +
fit/wa-reference/pom.xml | 24 +-
.../org/apache/syncope/fit/AbstractITCase.java | 11 +
.../apache/syncope/fit/sra/AbstractOIDCITCase.java | 2 +-
.../apache/syncope/fit/sra/AbstractSRAITCase.java | 5 +-
.../org/apache/syncope/fit/ui/OIDCC4UIITCase.java | 2 +-
.../org/apache/syncope/fit/ui/OpenFGAUIITCase.java | 157 +
pom.xml | 10 +-
.../reference-guide/concepts/extensions.adoc | 24 +
.../reference-guide/concepts/policies.adoc | 9 +
.../reference-guide/usage/customization.adoc | 54 +
.../mapping/DefaultAttrReleaseMapper.java | 44 +-
.../syncope/wa/starter/config/WAContext.java | 7 +
.../wa/starter/mapping/OpenFGAAccessMapper.java | 49 +
46 files changed, 5380 insertions(+), 50 deletions(-)
diff --git a/.github/workflows/crosschecks.yml b/.github/workflows/crosschecks.yml
index 1474e9d4ef..cd9e72a432 100644
--- a/.github/workflows/crosschecks.yml
+++ b/.github/workflows/crosschecks.yml
@@ -57,6 +57,7 @@ jobs:
- name: Build
run: mvn -U -T 1C -P 'skipTests,all'
- name: Validate
+ if: runner.os == 'Linux'
run: mvn -T 1C checkstyle:check tools:verify-legal-files modernizer:modernizer apache-rat:check
- name: Test
run: mvn -T 1C clean test '-Dinvoker.streamLogs=true' '-Dmodernizer.skip=true' '-Dianal.phase=none' '-Drat.skip=true' '-Dcheckstyle.skip=true' '-Dsass.skip=true'
diff --git a/.github/workflows/fit_WA_OIDCC4UI.yml b/.github/workflows/fit_WA_OIDCC4UI.yml
index 9b079f6490..fc045e60f4 100644
--- a/.github/workflows/fit_WA_OIDCC4UI.yml
+++ b/.github/workflows/fit_WA_OIDCC4UI.yml
@@ -50,4 +50,4 @@ jobs:
- name: Build
run: mvn -U -T 1C -P 'skipTests,all'
- name: 'WA / OIDCC4UI'
- run: mkdir -p fit/core-reference/target/test-classes && cp fit/core-reference/src/test/resources/saml.keystore.jks fit/core-reference/target/test-classes && mvn -f fit/wa-reference/pom.xml verify -Dinvoker.streamLogs=true -Dmodernizer.skip=true -Drat.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true -Dit.test=OIDCC4UIITCase
+ run: mvn -f fit/wa-reference/pom.xml verify -Dinvoker.streamLogs=true -Dmodernizer.skip=true -Drat.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true -Dit.test=OIDCC4UIITCase
diff --git a/.github/workflows/fit_WA_OIDCC4UI.yml b/.github/workflows/fit_WA_OpenFGA.yml
similarity index 76%
copy from .github/workflows/fit_WA_OIDCC4UI.yml
copy to .github/workflows/fit_WA_OpenFGA.yml
index 9b079f6490..56680e70c0 100644
--- a/.github/workflows/fit_WA_OIDCC4UI.yml
+++ b/.github/workflows/fit_WA_OpenFGA.yml
@@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License
-name: "FIT WA OIDCC4UI"
+name: "FIT WA OpenFGA"
on:
push:
@@ -26,7 +26,7 @@ on:
- cron: '0 13 * * 4'
jobs:
- fit_WA_OIDCC4UI:
+ fit_WA_OpenFGA:
runs-on: ubuntu-latest
steps:
@@ -49,5 +49,7 @@ jobs:
${{ runner.os }}-maven-
- name: Build
run: mvn -U -T 1C -P 'skipTests,all'
- - name: 'WA / OIDCC4UI'
- run: mkdir -p fit/core-reference/target/test-classes && cp fit/core-reference/src/test/resources/saml.keystore.jks fit/core-reference/target/test-classes && mvn -f fit/wa-reference/pom.xml verify -Dinvoker.streamLogs=true -Dmodernizer.skip=true -Drat.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true -Dit.test=OIDCC4UIITCase
+ - name: 'Unit Tests: OpenFGA'
+ run: mvn -f ext/openfga/client-openfga/pom.xml -P openfga -Dinvoker.streamLogs=true -Dmodernizer.skip=true -Dianal.phase=none -Drat.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true
+ - name: 'WA / OpenFGA'
+ run: mvn -f fit/wa-reference/pom.xml verify -Dinvoker.streamLogs=true -Dmodernizer.skip=true -Drat.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true -Dit.test=OpenFGAUIITCase
diff --git a/common/am/lib/src/main/java/org/apache/syncope/common/lib/policy/OpenFGAAccessPolicyConf.java b/common/am/lib/src/main/java/org/apache/syncope/common/lib/policy/OpenFGAAccessPolicyConf.java
new file mode 100644
index 0000000000..88b61540fa
--- /dev/null
+++ b/common/am/lib/src/main/java/org/apache/syncope/common/lib/policy/OpenFGAAccessPolicyConf.java
@@ -0,0 +1,86 @@
+/*
+ * 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.syncope.common.lib.policy;
+
+import org.apache.syncope.common.lib.types.AnyTypeKind;
+
+public class OpenFGAAccessPolicyConf implements AccessPolicyConf {
+
+ private static final long serialVersionUID = -6037828132577267304L;
+
+ private String apiUrl;
+
+ private String token;
+
+ private String storeId;
+
+ private String userType = AnyTypeKind.USER.name();
+
+ private String relation;
+
+ private String object;
+
+ public String getApiUrl() {
+ return apiUrl;
+ }
+
+ public void setApiUrl(final String apiUrl) {
+ this.apiUrl = apiUrl;
+ }
+
+ public String getToken() {
+ return token;
+ }
+
+ public void setToken(final String token) {
+ this.token = token;
+ }
+
+ public String getStoreId() {
+ return storeId;
+ }
+
+ public void setStoreId(final String storeId) {
+ this.storeId = storeId;
+ }
+
+ public String getUserType() {
+ return userType;
+ }
+
+ public void setUserType(final String userType) {
+ this.userType = userType;
+ }
+
+ public String getRelation() {
+ return relation;
+ }
+
+ public void setRelation(final String relation) {
+ this.relation = relation;
+ }
+
+ public String getObject() {
+ return object;
+ }
+
+ public void setObject(final String object) {
+ this.object = object;
+ }
+}
diff --git a/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/AnyTypeLogic.java b/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/AnyTypeLogic.java
index 8592dbaa52..f2a99c911f 100644
--- a/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/AnyTypeLogic.java
+++ b/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/AnyTypeLogic.java
@@ -32,6 +32,10 @@ import org.apache.syncope.core.persistence.api.dao.DuplicateException;
import org.apache.syncope.core.persistence.api.dao.NotFoundException;
import org.apache.syncope.core.persistence.api.entity.AnyType;
import org.apache.syncope.core.provisioning.api.data.AnyTypeDataBinder;
+import org.apache.syncope.core.provisioning.api.event.EntityLifecycleEvent;
+import org.apache.syncope.core.spring.security.AuthContextUtils;
+import org.identityconnectors.framework.common.objects.SyncDeltaType;
+import org.springframework.context.ApplicationEventPublisher;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
@@ -44,14 +48,18 @@ public class AnyTypeLogic extends AbstractTransactionalLogic<AnyTypeTO> {
protected final AnyObjectDAO anyObjectDAO;
+ protected final ApplicationEventPublisher publisher;
+
public AnyTypeLogic(
final AnyTypeDataBinder binder,
final AnyTypeDAO anyTypeDAO,
- final AnyObjectDAO anyObjectDAO) {
+ final AnyObjectDAO anyObjectDAO,
+ final ApplicationEventPublisher publisher) {
this.binder = binder;
this.anyTypeDAO = anyTypeDAO;
this.anyObjectDAO = anyObjectDAO;
+ this.publisher = publisher;
}
@PreAuthorize("hasRole('" + IdRepoEntitlement.ANYTYPE_READ + "')")
@@ -80,7 +88,12 @@ public class AnyTypeLogic extends AbstractTransactionalLogic<AnyTypeTO> {
throw new DuplicateException(anyTypeTO.getKey());
}
- return binder.getAnyTypeTO(anyTypeDAO.save(binder.create(anyTypeTO)));
+ AnyType anyType = anyTypeDAO.save(binder.create(anyTypeTO));
+
+ publisher.publishEvent(
+ new EntityLifecycleEvent<>(this, SyncDeltaType.CREATE, anyType, AuthContextUtils.getDomain()));
+
+ return binder.getAnyTypeTO(anyType);
}
@PreAuthorize("hasRole('" + IdRepoEntitlement.ANYTYPE_UPDATE + "')")
@@ -89,7 +102,11 @@ public class AnyTypeLogic extends AbstractTransactionalLogic<AnyTypeTO> {
orElseThrow(() -> new NotFoundException("AnyType " + anyTypeTO.getKey()));
binder.update(anyType, anyTypeTO);
- anyTypeDAO.save(anyType);
+
+ anyType = anyTypeDAO.save(anyType);
+
+ publisher.publishEvent(
+ new EntityLifecycleEvent<>(this, SyncDeltaType.UPDATE, anyType, AuthContextUtils.getDomain()));
}
@PreAuthorize("hasRole('" + IdRepoEntitlement.ANYTYPE_DELETE + "')")
@@ -107,7 +124,12 @@ public class AnyTypeLogic extends AbstractTransactionalLogic<AnyTypeTO> {
}
try {
- return binder.delete(anyType);
+ AnyTypeTO deleted = binder.delete(anyType);
+
+ publisher.publishEvent(
+ new EntityLifecycleEvent<>(this, SyncDeltaType.DELETE, anyType, AuthContextUtils.getDomain()));
+
+ return deleted;
} catch (IllegalArgumentException | InvalidDataAccessApiUsageException e) {
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidRequest);
sce.getElements().add(e.getMessage());
diff --git a/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/IdRepoLogicContext.java b/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/IdRepoLogicContext.java
index ccea3ee257..7e2893e1bf 100644
--- a/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/IdRepoLogicContext.java
+++ b/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/IdRepoLogicContext.java
@@ -99,6 +99,7 @@ import org.apache.syncope.core.spring.security.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@@ -188,9 +189,10 @@ public class IdRepoLogicContext {
public AnyTypeLogic anyTypeLogic(
final AnyTypeDataBinder binder,
final AnyTypeDAO anyTypeDAO,
- final AnyObjectDAO anyObjectDAO) {
+ final AnyObjectDAO anyObjectDAO,
+ final ApplicationEventPublisher publisher) {
- return new AnyTypeLogic(binder, anyTypeDAO, anyObjectDAO);
+ return new AnyTypeLogic(binder, anyTypeDAO, anyObjectDAO, publisher);
}
@ConditionalOnMissingBean
@@ -375,9 +377,10 @@ public class IdRepoLogicContext {
@Bean
public RelationshipTypeLogic relationshipTypeLogic(
final RelationshipTypeDataBinder binder,
- final RelationshipTypeDAO relationshipTypeDAO) {
+ final RelationshipTypeDAO relationshipTypeDAO,
+ final ApplicationEventPublisher publisher) {
- return new RelationshipTypeLogic(binder, relationshipTypeDAO);
+ return new RelationshipTypeLogic(binder, relationshipTypeDAO, publisher);
}
@ConditionalOnMissingBean
diff --git a/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/RelationshipTypeLogic.java b/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/RelationshipTypeLogic.java
index 854b251dc2..9a27fcf629 100644
--- a/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/RelationshipTypeLogic.java
+++ b/core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/RelationshipTypeLogic.java
@@ -28,6 +28,10 @@ import org.apache.syncope.core.persistence.api.dao.NotFoundException;
import org.apache.syncope.core.persistence.api.dao.RelationshipTypeDAO;
import org.apache.syncope.core.persistence.api.entity.RelationshipType;
import org.apache.syncope.core.provisioning.api.data.RelationshipTypeDataBinder;
+import org.apache.syncope.core.provisioning.api.event.EntityLifecycleEvent;
+import org.apache.syncope.core.spring.security.AuthContextUtils;
+import org.identityconnectors.framework.common.objects.SyncDeltaType;
+import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
@@ -37,12 +41,16 @@ public class RelationshipTypeLogic extends AbstractTransactionalLogic<Relationsh
protected final RelationshipTypeDAO relationshipTypeDAO;
+ protected final ApplicationEventPublisher publisher;
+
public RelationshipTypeLogic(
final RelationshipTypeDataBinder binder,
- final RelationshipTypeDAO relationshipTypeDAO) {
+ final RelationshipTypeDAO relationshipTypeDAO,
+ final ApplicationEventPublisher publisher) {
this.binder = binder;
this.relationshipTypeDAO = relationshipTypeDAO;
+ this.publisher = publisher;
}
@PreAuthorize("hasRole('" + IdRepoEntitlement.RELATIONSHIPTYPE_READ + "')")
@@ -62,7 +70,12 @@ public class RelationshipTypeLogic extends AbstractTransactionalLogic<Relationsh
@PreAuthorize("hasRole('" + IdRepoEntitlement.RELATIONSHIPTYPE_CREATE + "')")
public RelationshipTypeTO create(final RelationshipTypeTO relationshipTypeTO) {
- return binder.getRelationshipTypeTO(relationshipTypeDAO.save(binder.create(relationshipTypeTO)));
+ RelationshipType relationshipType = relationshipTypeDAO.save(binder.create(relationshipTypeTO));
+
+ publisher.publishEvent(
+ new EntityLifecycleEvent<>(this, SyncDeltaType.CREATE, relationshipType, AuthContextUtils.getDomain()));
+
+ return binder.getRelationshipTypeTO(relationshipType);
}
@PreAuthorize("hasRole('" + IdRepoEntitlement.RELATIONSHIPTYPE_UPDATE + "')")
@@ -73,6 +86,9 @@ public class RelationshipTypeLogic extends AbstractTransactionalLogic<Relationsh
binder.update(relationshipType, relationshipTypeTO);
relationshipType = relationshipTypeDAO.save(relationshipType);
+ publisher.publishEvent(
+ new EntityLifecycleEvent<>(this, SyncDeltaType.UPDATE, relationshipType, AuthContextUtils.getDomain()));
+
return binder.getRelationshipTypeTO(relationshipType);
}
@@ -85,6 +101,9 @@ public class RelationshipTypeLogic extends AbstractTransactionalLogic<Relationsh
relationshipTypeDAO.deleteById(key);
+ publisher.publishEvent(
+ new EntityLifecycleEvent<>(this, SyncDeltaType.DELETE, relationshipType, AuthContextUtils.getDomain()));
+
return deleted;
}
diff --git a/core/persistence-api/src/main/java/org/apache/syncope/core/persistence/api/dao/RelationshipTypeDAO.java b/core/persistence-api/src/main/java/org/apache/syncope/core/persistence/api/dao/RelationshipTypeDAO.java
index 43f7f353c6..602d293246 100644
--- a/core/persistence-api/src/main/java/org/apache/syncope/core/persistence/api/dao/RelationshipTypeDAO.java
+++ b/core/persistence-api/src/main/java/org/apache/syncope/core/persistence/api/dao/RelationshipTypeDAO.java
@@ -25,4 +25,6 @@ import org.apache.syncope.core.persistence.api.entity.RelationshipType;
public interface RelationshipTypeDAO extends DAO<RelationshipType> {
List<String> findByEndAnyType(AnyType anyType);
+
+ List<? extends RelationshipType> findByLeftEndAnyType(AnyType anyType);
}
diff --git a/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/dao/repo/RelationshipTypeRepoExt.java b/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/dao/repo/RelationshipTypeRepoExt.java
index 391437ecfa..d64357b227 100644
--- a/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/dao/repo/RelationshipTypeRepoExt.java
+++ b/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/dao/repo/RelationshipTypeRepoExt.java
@@ -20,10 +20,13 @@ package org.apache.syncope.core.persistence.jpa.dao.repo;
import java.util.List;
import org.apache.syncope.core.persistence.api.entity.AnyType;
+import org.apache.syncope.core.persistence.api.entity.RelationshipType;
public interface RelationshipTypeRepoExt {
List<String> findByEndAnyType(AnyType anyType);
+ List<? extends RelationshipType> findByLeftEndAnyType(AnyType anyType);
+
void deleteById(String key);
}
diff --git a/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/dao/repo/RelationshipTypeRepoExtImpl.java b/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/dao/repo/RelationshipTypeRepoExtImpl.java
index b67a4a6ae9..e00c77dae2 100644
--- a/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/dao/repo/RelationshipTypeRepoExtImpl.java
+++ b/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/dao/repo/RelationshipTypeRepoExtImpl.java
@@ -52,6 +52,16 @@ public class RelationshipTypeRepoExtImpl implements RelationshipTypeRepoExt {
return query.getResultList().stream().map(RelationshipType::getKey).toList();
}
+ @Override
+ public List<? extends RelationshipType> findByLeftEndAnyType(final AnyType anyType) {
+ TypedQuery<RelationshipType> query = entityManager.createQuery(
+ "SELECT DISTINCT e FROM " + JPARelationshipType.class.getSimpleName() + " e "
+ + "WHERE e.leftEndAnyType=:anyType",
+ RelationshipType.class);
+ query.setParameter("anyType", anyType);
+ return query.getResultList();
+ }
+
protected Collection<? extends Relationship<?, ?>> findRelationshipsByType(final RelationshipType type) {
TypedQuery<ARelationship> aquery = entityManager.createQuery(
"SELECT e FROM " + JPAARelationship.class.getSimpleName() + " e WHERE e.type=:type",
diff --git a/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/dao/repo/RelationshipTypeRepoExt.java b/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/dao/repo/RelationshipTypeRepoExt.java
index 13d07cff6b..b839b09204 100644
--- a/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/dao/repo/RelationshipTypeRepoExt.java
+++ b/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/dao/repo/RelationshipTypeRepoExt.java
@@ -20,10 +20,13 @@ package org.apache.syncope.core.persistence.neo4j.dao.repo;
import java.util.List;
import org.apache.syncope.core.persistence.api.entity.AnyType;
+import org.apache.syncope.core.persistence.api.entity.RelationshipType;
public interface RelationshipTypeRepoExt {
List<String> findByEndAnyType(AnyType anyType);
+ List<? extends RelationshipType> findByLeftEndAnyType(AnyType anyType);
+
void deleteById(String key);
}
diff --git a/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/dao/repo/RelationshipTypeRepoExtImpl.java b/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/dao/repo/RelationshipTypeRepoExtImpl.java
index 56c5ba21d3..741e7c8e31 100644
--- a/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/dao/repo/RelationshipTypeRepoExtImpl.java
+++ b/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/dao/repo/RelationshipTypeRepoExtImpl.java
@@ -49,6 +49,17 @@ public class RelationshipTypeRepoExtImpl extends AbstractDAO implements Relation
return result.stream().map(RelationshipType::getKey).distinct().toList();
}
+ @Override
+ public List<? extends RelationshipType> findByLeftEndAnyType(final AnyType anyType) {
+ return findByRelationship(
+ Neo4jRelationshipType.NODE,
+ Neo4jAnyType.NODE,
+ anyType.getKey(),
+ Neo4jRelationshipType.LEFT_END_ANYTYPE,
+ Neo4jRelationshipType.class,
+ null);
+ }
+
protected Collection<? extends Relationship<?, ?>> findRelationshipsByType(final RelationshipType type) {
List<Relationship<?, ?>> result = new ArrayList<>();
diff --git a/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/entity/Neo4jRelationshipType.java b/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/entity/Neo4jRelationshipType.java
index 826d445bde..033aaba943 100644
--- a/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/entity/Neo4jRelationshipType.java
+++ b/core/persistence-neo4j/src/main/java/org/apache/syncope/core/persistence/neo4j/entity/Neo4jRelationshipType.java
@@ -33,9 +33,9 @@ public class Neo4jRelationshipType extends AbstractProvidedKeyNode implements Re
public static final String NODE = "RelationshipType";
- private static final String LEFT_END_ANYTYPE = "RELATIONSHIPTYPE_LEFT_END_ANYTYPE";
+ public static final String LEFT_END_ANYTYPE = "RELATIONSHIPTYPE_LEFT_END_ANYTYPE";
- private static final String RIGHT_END_ANYTYPE = "RELATIONSHIPTYPE_RIGHT_END_ANYTYPE";
+ public static final String RIGHT_END_ANYTYPE = "RELATIONSHIPTYPE_RIGHT_END_ANYTYPE";
private String description;
diff --git a/ext/elasticsearch/client-elasticsearch/src/main/java/org/apache/syncope/ext/elasticsearch/client/ElasticsearchClientContext.java b/ext/elasticsearch/client-elasticsearch/src/main/java/org/apache/syncope/ext/elasticsearch/client/ElasticsearchClientContext.java
index ede274672a..77664ccb03 100644
--- a/ext/elasticsearch/client-elasticsearch/src/main/java/org/apache/syncope/ext/elasticsearch/client/ElasticsearchClientContext.java
+++ b/ext/elasticsearch/client-elasticsearch/src/main/java/org/apache/syncope/ext/elasticsearch/client/ElasticsearchClientContext.java
@@ -39,8 +39,7 @@ public class ElasticsearchClientContext {
@Bean
public ElasticsearchClientFactoryBean elasticsearchClientFactoryBean(final ElasticsearchProperties props) {
return new ElasticsearchClientFactoryBean(
- CollectionUtil.nullAsEmpty(props.getHosts()).stream().
- map(HttpHost::create).toList());
+ CollectionUtil.nullAsEmpty(props.getHosts()).stream().map(HttpHost::create).toList());
}
@ConditionalOnMissingBean
diff --git a/ext/openfga/client-openfga/pom.xml b/ext/openfga/client-openfga/pom.xml
new file mode 100644
index 0000000000..23bd555a21
--- /dev/null
+++ b/ext/openfga/client-openfga/pom.xml
@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.syncope.ext</groupId>
+ <artifactId>syncope-ext-openfga</artifactId>
+ <version>4.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Apache Syncope Ext: OpenFGA Client</name>
+ <description>Apache Syncope Ext: OpenFGA Client</description>
+ <groupId>org.apache.syncope.ext.openfga</groupId>
+ <artifactId>syncope-ext-openfga-client</artifactId>
+ <packaging>jar</packaging>
+
+ <properties>
+ <skipTests>true</skipTests>
+ <rootpom.basedir>${basedir}/../../..</rootpom.basedir>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.syncope.core</groupId>
+ <artifactId>syncope-core-provisioning-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-actuator</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.testcontainers</groupId>
+ <artifactId>openfga</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.openapitools</groupId>
+ <artifactId>openapi-generator-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>generate</goal>
+ </goals>
+ <configuration>
+ <inputSpec>${project.basedir}/src/main/resources/openfga.yaml</inputSpec>
+ <generatorName>java</generatorName>
+ <apiPackage>org.apache.syncope.ext.openfga.client.api</apiPackage>
+ <modelPackage>org.apache.syncope.ext.openfga.client.model</modelPackage>
+ <generateApiTests>false</generateApiTests>
+ <generateModelTests>false</generateModelTests>
+ <configOptions>
+ <library>native</library>
+ <useJakartaEe>true</useJakartaEe>
+ <openApiNullable>false</openApiNullable>
+ <sourceFolder>/</sourceFolder>
+ </configOptions>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <sourceDirectories>
+ <sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
+ <sourceDirectory>${project.build.testSourceDirectory}</sourceDirectory>
+ </sourceDirectories>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <profiles>
+ <profile>
+ <id>openfga</id>
+
+ <properties>
+ <skipTests>false</skipTests>
+ </properties>
+ </profile>
+ </profiles>
+</project>
diff --git a/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClient.java b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClient.java
new file mode 100644
index 0000000000..d32e9bfdd8
--- /dev/null
+++ b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClient.java
@@ -0,0 +1,117 @@
+/*
+ * 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.syncope.ext.openfga.client;
+
+import org.apache.syncope.ext.openfga.client.api.AuthorizationModelsApi;
+import org.apache.syncope.ext.openfga.client.api.RelationshipQueriesApi;
+import org.apache.syncope.ext.openfga.client.api.RelationshipTuplesApi;
+import org.apache.syncope.ext.openfga.client.api.StoresApi;
+import org.apache.syncope.ext.openfga.client.model.AuthorizationModel;
+import org.apache.syncope.ext.openfga.client.model.CheckRequest;
+import org.apache.syncope.ext.openfga.client.model.CheckResponse;
+import org.apache.syncope.ext.openfga.client.model.CreateStoreRequest;
+import org.apache.syncope.ext.openfga.client.model.CreateStoreResponse;
+import org.apache.syncope.ext.openfga.client.model.GetStoreResponse;
+import org.apache.syncope.ext.openfga.client.model.ListStoresResponse;
+import org.apache.syncope.ext.openfga.client.model.ReadAuthorizationModelsResponse;
+import org.apache.syncope.ext.openfga.client.model.ReadRequest;
+import org.apache.syncope.ext.openfga.client.model.ReadResponse;
+import org.apache.syncope.ext.openfga.client.model.WriteAuthorizationModelRequest;
+import org.apache.syncope.ext.openfga.client.model.WriteAuthorizationModelResponse;
+import org.apache.syncope.ext.openfga.client.model.WriteRequest;
+
+public class OpenFGAClient {
+
+ protected final StoresApi storesApi;
+
+ protected final AuthorizationModelsApi authorizationModelsApi;
+
+ protected final RelationshipTuplesApi relationshipTuplesApi;
+
+ protected final RelationshipQueriesApi relationshipQueriesApi;
+
+ protected String storeId;
+
+ protected String authorizationModelId;
+
+ public OpenFGAClient(final ApiClient apiClient) {
+ this.storesApi = new StoresApi(apiClient);
+ this.authorizationModelsApi = new AuthorizationModelsApi(apiClient);
+ this.relationshipTuplesApi = new RelationshipTuplesApi(apiClient);
+ this.relationshipQueriesApi = new RelationshipQueriesApi(apiClient);
+ }
+
+ public String getStoreId() {
+ return storeId;
+ }
+
+ public void setStoreId(final String storeId) {
+ this.storeId = storeId;
+ }
+
+ public String getAuthorizationModelId() {
+ return authorizationModelId;
+ }
+
+ public void setAuthorizationModelId(final String authorizationModelId) {
+ this.authorizationModelId = authorizationModelId;
+ }
+
+ public GetStoreResponse getStore() throws ApiException {
+ return storesApi.getStore(storeId);
+ }
+
+ public ListStoresResponse listStores() throws ApiException {
+ return storesApi.listStores(null, null, null);
+ }
+
+ public ApiResponse<ListStoresResponse> listStoresWithHttpInfo() throws ApiException {
+ return storesApi.listStoresWithHttpInfo(null, null, null);
+ }
+
+ public CreateStoreResponse createStore(final CreateStoreRequest request) throws ApiException {
+ return storesApi.createStore(request);
+ }
+
+ public WriteAuthorizationModelResponse writeAuthorizationModel(
+ final WriteAuthorizationModelRequest request) throws ApiException {
+
+ return authorizationModelsApi.writeAuthorizationModel(storeId, request);
+ }
+
+ public ReadAuthorizationModelsResponse readAuthorizationModels() throws ApiException {
+ return authorizationModelsApi.readAuthorizationModels(storeId, null, null);
+ }
+
+ public AuthorizationModel readLatestAuthorizationModel() throws ApiException {
+ return readAuthorizationModels().getAuthorizationModels().get(0);
+ }
+
+ public ReadResponse read(final ReadRequest request) throws ApiException {
+ return relationshipTuplesApi.read(storeId, request);
+ }
+
+ public void write(final WriteRequest request) throws ApiException {
+ relationshipTuplesApi.write(storeId, request);
+ }
+
+ public CheckResponse check(final CheckRequest request) throws ApiException {
+ return relationshipQueriesApi.check(storeId, request);
+ }
+}
diff --git a/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClientContext.java b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClientContext.java
new file mode 100644
index 0000000000..7f9e94f5c2
--- /dev/null
+++ b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClientContext.java
@@ -0,0 +1,79 @@
+/*
+ * 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.syncope.ext.openfga.client;
+
+import jakarta.ws.rs.core.HttpHeaders;
+import java.net.http.HttpClient;
+import java.util.Optional;
+import org.apache.syncope.core.persistence.api.DomainHolder;
+import org.apache.syncope.core.persistence.api.dao.RelationshipTypeDAO;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@EnableConfigurationProperties(OpenFGAProperties.class)
+@Configuration(proxyBeanMethods = false)
+@ConditionalOnProperty(prefix = "openfga", name = "api-url")
+public class OpenFGAClientContext {
+
+ @ConditionalOnMissingBean
+ @Bean
+ public ApiClient openFgaApiClient(final OpenFGAProperties props) {
+ HttpClient.Builder httpClientBuilder = ApiClient.createDefaultHttpClientBuilder();
+
+ ApiClient apiClient = new ApiClient(
+ httpClientBuilder,
+ ApiClient.createDefaultObjectMapper(),
+ props.getApiUrl());
+ apiClient.setConnectTimeout(props.getConnectTimeout());
+ apiClient.setReadTimeout(props.getReadTimeout());
+
+ Optional.ofNullable(props.getApiToken()).
+ ifPresent(apiToken -> apiClient.setRequestInterceptor(builder -> builder.
+ header(HttpHeaders.AUTHORIZATION, "Bearer " + apiToken)));
+
+ return apiClient;
+ }
+
+ @ConditionalOnMissingBean
+ @Bean
+ public OpenFGAClientFactory openFgaClientFactory(final ApiClient openFgaApiClient, final OpenFGAProperties props) {
+ return new OpenFGAClientFactory(openFgaApiClient, props);
+ }
+
+ @ConditionalOnMissingBean
+ @Bean
+ public OpenFGAStoreManager openFgaStoreManager(
+ final OpenFGAClientFactory clientFactory,
+ final RelationshipTypeDAO relationshipTypeDAO) {
+
+ return new OpenFGAStoreManager(clientFactory, relationshipTypeDAO);
+ }
+
+ @ConditionalOnMissingBean
+ @Bean
+ public OpenFGAHealthIndicator openFgaHealthIndicator(
+ final DomainHolder<?> domainHolder,
+ final OpenFGAClientFactory clientFactory) {
+
+ return new OpenFGAHealthIndicator(domainHolder, clientFactory);
+ }
+}
diff --git a/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClientFactory.java b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClientFactory.java
new file mode 100644
index 0000000000..dbc6e832e2
--- /dev/null
+++ b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClientFactory.java
@@ -0,0 +1,114 @@
+/*
+ * 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.syncope.ext.openfga.client;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.syncope.common.lib.types.AnyTypeKind;
+import org.apache.syncope.ext.openfga.client.model.AuthorizationModel;
+import org.apache.syncope.ext.openfga.client.model.CreateStoreRequest;
+import org.apache.syncope.ext.openfga.client.model.Metadata;
+import org.apache.syncope.ext.openfga.client.model.RelationMetadata;
+import org.apache.syncope.ext.openfga.client.model.RelationReference;
+import org.apache.syncope.ext.openfga.client.model.Store;
+import org.apache.syncope.ext.openfga.client.model.TypeDefinition;
+import org.apache.syncope.ext.openfga.client.model.Userset;
+import org.apache.syncope.ext.openfga.client.model.WriteAuthorizationModelRequest;
+
+public class OpenFGAClientFactory {
+
+ public static final String MEMBERSHIP_RELATION = "member";
+
+ public static final String SCHEMA_VERSION = "1.1";
+
+ protected static String storeId(final String domain) {
+ return StringUtils.rightPad(domain.toUpperCase(), 26, '0');
+ }
+
+ protected final ApiClient apiClient;
+
+ protected final OpenFGAProperties properties;
+
+ public OpenFGAClientFactory(final ApiClient openFgaApiClient, final OpenFGAProperties properties) {
+ this.apiClient = openFgaApiClient;
+ this.properties = properties;
+ }
+
+ public String getBaseUri() {
+ return apiClient.getBaseUri();
+ }
+
+ protected final Map<String, OpenFGAClient> clients = new ConcurrentHashMap<>();
+
+ public void initAuthorizationModel(
+ final OpenFGAClient client,
+ final String domain,
+ final boolean force) throws Exception {
+
+ String storeId = client.listStores().getStores().stream().
+ filter(store -> domain.equals(store.getName())).findFirst().
+ map(Store::getId).orElse(null);
+ if (storeId == null) {
+ storeId = client.createStore(new CreateStoreRequest().name(domain)).getId();
+ }
+ client.setStoreId(storeId);
+
+ WriteAuthorizationModelRequest request = new WriteAuthorizationModelRequest().
+ schemaVersion(SCHEMA_VERSION).
+ addTypeDefinitionsItem(
+ new TypeDefinition().type(AnyTypeKind.USER.name()).relations(Map.of())).
+ addTypeDefinitionsItem(new TypeDefinition().type(AnyTypeKind.GROUP.name()).
+ putRelationsItem(MEMBERSHIP_RELATION, new Userset()._this(Map.of())).
+ metadata(new Metadata().putRelationsItem(
+ MEMBERSHIP_RELATION,
+ new RelationMetadata().addDirectlyRelatedUserTypesItem(
+ new RelationReference().type(AnyTypeKind.USER.name())))));
+ if (force) {
+ client.setAuthorizationModelId(
+ client.writeAuthorizationModel(request).getAuthorizationModelId());
+ } else {
+ List<AuthorizationModel> models = client.readAuthorizationModels().getAuthorizationModels();
+ if (models.isEmpty()) {
+ client.setAuthorizationModelId(client.writeAuthorizationModel(request).getAuthorizationModelId());
+ } else {
+ client.setAuthorizationModelId(models.get(0).getId());
+ }
+ }
+ }
+
+ public OpenFGAClient get(final String domain) {
+ return clients.computeIfAbsent(domain, d -> {
+ try {
+ OpenFGAClient client = new OpenFGAClient(apiClient);
+
+ initAuthorizationModel(client, domain, false);
+
+ return client;
+ } catch (Exception e) {
+ throw new IllegalStateException("Could not init OpenFga client for domain " + d, e);
+ }
+ });
+ }
+
+ public void remove(final String domain) {
+ clients.remove(domain);
+ }
+}
diff --git a/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAHealthIndicator.java b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAHealthIndicator.java
new file mode 100644
index 0000000000..cb768cd4e1
--- /dev/null
+++ b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAHealthIndicator.java
@@ -0,0 +1,72 @@
+/*
+ * 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.syncope.ext.openfga.client;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.syncope.core.persistence.api.DomainHolder;
+import org.apache.syncope.ext.openfga.client.model.ListStoresResponse;
+import org.springframework.boot.actuate.health.Health;
+import org.springframework.boot.actuate.health.HealthIndicator;
+import org.springframework.boot.actuate.health.Status;
+
+public class OpenFGAHealthIndicator implements HealthIndicator {
+
+ protected final DomainHolder<?> domainHolder;
+
+ protected final OpenFGAClientFactory clientFactory;
+
+ public OpenFGAHealthIndicator(
+ final DomainHolder<?> domainHolder,
+ final OpenFGAClientFactory clientFactory) {
+
+ this.domainHolder = domainHolder;
+ this.clientFactory = clientFactory;
+ }
+
+ @Override
+ public Health health() {
+ Health.Builder builder = new Health.Builder();
+ builder.withDetail("baseUri", clientFactory.getBaseUri());
+
+ AtomicReference<Boolean> anyDown = new AtomicReference<>(Boolean.FALSE);
+
+ domainHolder.getDomains().keySet().forEach(domain -> {
+ try {
+ OpenFGAClient client = clientFactory.get(domain);
+ ApiResponse<ListStoresResponse> response = client.listStoresWithHttpInfo();
+ if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) {
+ builder.withDetail(domain, Map.of(
+ "storeId", client.getStoreId(),
+ "status", Status.UP.getCode()));
+ } else {
+ builder.withDetail(domain, Status.DOWN);
+ anyDown.set(true);
+ }
+ } catch (Exception e) {
+ builder.withDetail(domain, Status.DOWN).withException(e);
+ anyDown.set(true);
+ }
+ });
+
+ builder.status(anyDown.get() ? Status.DOWN : Status.UP);
+
+ return builder.build();
+ }
+}
diff --git a/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAProperties.java b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAProperties.java
new file mode 100644
index 0000000000..e22d77c6e0
--- /dev/null
+++ b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAProperties.java
@@ -0,0 +1,97 @@
+/*
+ * 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.syncope.ext.openfga.client;
+
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.boot.convert.DurationUnit;
+
+@ConfigurationProperties("openfga")
+public class OpenFGAProperties implements InitializingBean {
+
+ private static void assertPositive(final Duration duration, final String fieldName) {
+ if (duration != null && duration.isNegative()) {
+ throw new IllegalStateException("%s must be positive".formatted(fieldName));
+ }
+ }
+
+ /**
+ * URL to OpenFGA instance.
+ * If configured, beans will be initialized.
+ */
+ private String apiUrl;
+
+ /**
+ * API token for authenticating requests.
+ * If null, anonymous requests will be sent out.
+ */
+ private String apiToken;
+
+ /**
+ * The read timeout for request.
+ */
+ @DurationUnit(ChronoUnit.SECONDS)
+ private Duration readTimeout = Duration.ofSeconds(10);
+
+ /**
+ * The connect timeout for requests.
+ */
+ @DurationUnit(ChronoUnit.SECONDS)
+ private Duration connectTimeout = Duration.ofSeconds(10);
+
+ public String getApiUrl() {
+ return apiUrl;
+ }
+
+ public void setApiUrl(final String apiUrl) {
+ this.apiUrl = apiUrl;
+ }
+
+ public String getApiToken() {
+ return apiToken;
+ }
+
+ public void setApiToken(final String apiToken) {
+ this.apiToken = apiToken;
+ }
+
+ public Duration getReadTimeout() {
+ return readTimeout;
+ }
+
+ public void setReadTimeout(final Duration readTimeout) {
+ this.readTimeout = readTimeout;
+ }
+
+ public Duration getConnectTimeout() {
+ return connectTimeout;
+ }
+
+ public void setConnectTimeout(final Duration connectTimeout) {
+ this.connectTimeout = connectTimeout;
+ }
+
+ @Override
+ public void afterPropertiesSet() {
+ assertPositive(readTimeout, "readTimeout");
+ assertPositive(connectTimeout, "connectTimeout");
+ }
+}
diff --git a/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAStoreManager.java b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAStoreManager.java
new file mode 100644
index 0000000000..c856624fd9
--- /dev/null
+++ b/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAStoreManager.java
@@ -0,0 +1,315 @@
+/*
+ * 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.syncope.ext.openfga.client;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.apache.syncope.common.lib.types.AnyTypeKind;
+import org.apache.syncope.core.persistence.api.dao.RelationshipTypeDAO;
+import org.apache.syncope.core.persistence.api.entity.Any;
+import org.apache.syncope.core.persistence.api.entity.AnyType;
+import org.apache.syncope.core.persistence.api.entity.Entity;
+import org.apache.syncope.core.persistence.api.entity.Groupable;
+import org.apache.syncope.core.persistence.api.entity.Relatable;
+import org.apache.syncope.core.persistence.api.entity.RelationshipType;
+import org.apache.syncope.core.persistence.api.entity.group.Group;
+import org.apache.syncope.core.persistence.api.entity.user.User;
+import org.apache.syncope.core.provisioning.api.event.EntityLifecycleEvent;
+import org.apache.syncope.ext.openfga.client.model.AuthorizationModel;
+import org.apache.syncope.ext.openfga.client.model.Metadata;
+import org.apache.syncope.ext.openfga.client.model.ReadRequest;
+import org.apache.syncope.ext.openfga.client.model.ReadRequestTupleKey;
+import org.apache.syncope.ext.openfga.client.model.RelationMetadata;
+import org.apache.syncope.ext.openfga.client.model.RelationReference;
+import org.apache.syncope.ext.openfga.client.model.Tuple;
+import org.apache.syncope.ext.openfga.client.model.TupleKey;
+import org.apache.syncope.ext.openfga.client.model.TupleKeyWithoutCondition;
+import org.apache.syncope.ext.openfga.client.model.TypeDefinition;
+import org.apache.syncope.ext.openfga.client.model.Userset;
+import org.apache.syncope.ext.openfga.client.model.WriteAuthorizationModelRequest;
+import org.apache.syncope.ext.openfga.client.model.WriteAuthorizationModelResponse;
+import org.apache.syncope.ext.openfga.client.model.WriteRequest;
+import org.apache.syncope.ext.openfga.client.model.WriteRequestDeletes;
+import org.apache.syncope.ext.openfga.client.model.WriteRequestWrites;
+import org.identityconnectors.framework.common.objects.SyncDeltaType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.event.TransactionalEventListener;
+
+public class OpenFGAStoreManager {
+
+ protected static final Logger LOG = LoggerFactory.getLogger(OpenFGAStoreManager.class);
+
+ protected static String anyMembership(final AnyType anyType) {
+ return anyType.getKey() + "_" + OpenFGAClientFactory.MEMBERSHIP_RELATION;
+ }
+
+ protected static String type(final String anyType) {
+ return anyType + ":";
+ }
+
+ protected static String type(final AnyType anyType) {
+ return type(anyType.getKey());
+ }
+
+ protected static String id(final Any any) {
+ return type(any.getType())
+ + (any instanceof User user
+ ? user.getUsername()
+ : any instanceof Group group
+ ? group.getName()
+ : any.getKey());
+ }
+
+ protected final OpenFGAClientFactory clientFactory;
+
+ protected final RelationshipTypeDAO relationshipTypeDAO;
+
+ public OpenFGAStoreManager(
+ final OpenFGAClientFactory clientFactory,
+ final RelationshipTypeDAO relationshipTypeDAO) {
+
+ this.clientFactory = clientFactory;
+ this.relationshipTypeDAO = relationshipTypeDAO;
+ }
+
+ public void handle(
+ final OpenFGAClient openfgaClient,
+ final SyncDeltaType eventType,
+ final AnyType anyType) throws ApiException {
+
+ AuthorizationModel authModel = openfgaClient.readLatestAuthorizationModel();
+ openfgaClient.setAuthorizationModelId(authModel.getId());
+
+ Optional<TypeDefinition> group = authModel.getTypeDefinitions().stream().
+ filter(type -> AnyTypeKind.GROUP.name().equals(type.getType())).
+ findFirst();
+
+ boolean changed = false;
+ switch (eventType) {
+ case CREATE:
+ changed = authModel.getTypeDefinitions().
+ add(new TypeDefinition().type(anyType.getKey()).relations(Map.of()));
+ if (changed) {
+ group.ifPresent(g -> {
+ g.putRelationsItem(anyMembership(anyType), new Userset()._this(Map.of()));
+ g.getMetadata().putRelationsItem(
+ anyMembership(anyType),
+ new RelationMetadata().addDirectlyRelatedUserTypesItem(
+ new RelationReference().type(anyType.getKey())));
+ });
+ }
+ break;
+
+ case DELETE:
+ changed = authModel.getTypeDefinitions().
+ removeIf(typeDefinition -> anyType.getKey().equals(typeDefinition.getType()));
+ if (changed) {
+ group.ifPresent(g -> {
+ g.getRelations().remove(anyMembership(anyType));
+ g.getMetadata().getRelations().remove(anyMembership(anyType));
+ });
+ }
+ break;
+
+ default:
+ }
+
+ if (changed) {
+ LOG.debug("Authorization Model is to update on {} {}", eventType, anyType);
+
+ WriteAuthorizationModelResponse response = openfgaClient.writeAuthorizationModel(
+ new WriteAuthorizationModelRequest().
+ schemaVersion(authModel.getSchemaVersion()).
+ typeDefinitions(authModel.getTypeDefinitions()).
+ conditions(authModel.getConditions()));
+ openfgaClient.setAuthorizationModelId(response.getAuthorizationModelId());
+ } else {
+ LOG.debug("Authorization Model not to update on {} {}", eventType, anyType);
+ }
+ }
+
+ public void handle(
+ final OpenFGAClient openfgaClient,
+ final SyncDeltaType eventType,
+ final RelationshipType relationshipType) throws ApiException {
+
+ // skip self relationships, not supported by OpenFGA
+ if (relationshipType.getLeftEndAnyType().equals(relationshipType.getRightEndAnyType())) {
+ return;
+ }
+
+ AuthorizationModel authModel = openfgaClient.readLatestAuthorizationModel();
+ openfgaClient.setAuthorizationModelId(authModel.getId());
+
+ TypeDefinition left = authModel.getTypeDefinitions().stream().
+ filter(type -> relationshipType.getLeftEndAnyType().getKey().equals(type.getType())).
+ findFirst().
+ orElseGet(() -> new TypeDefinition().type(relationshipType.getLeftEndAnyType().getKey()));
+ TypeDefinition right = authModel.getTypeDefinitions().stream().
+ filter(type -> relationshipType.getRightEndAnyType().getKey().equals(type.getType())).
+ findFirst().
+ orElseGet(() -> new TypeDefinition().type(relationshipType.getRightEndAnyType().getKey()));
+
+ authModel.getTypeDefinitions().removeIf(
+ type -> left.getType().equals(type.getType()) || right.getType().equals(type.getType()));
+
+ authModel.addTypeDefinitionsItem(left);
+ authModel.addTypeDefinitionsItem(right);
+
+ boolean changed = false;
+ switch (eventType) {
+ case CREATE:
+ right.putRelationsItem(relationshipType.getKey(), new Userset()._this(Map.of()));
+ right.metadata(new Metadata().putRelationsItem(
+ relationshipType.getKey(),
+ new RelationMetadata().addDirectlyRelatedUserTypesItem(
+ new RelationReference().type(left.getType()))));
+ changed = true;
+ break;
+
+ case DELETE:
+ changed = right.getRelations().remove(relationshipType.getKey()) != null
+ && right.getMetadata().getRelations().remove(relationshipType.getKey()) != null;
+ break;
+
+ default:
+ }
+
+ if (changed) {
+ LOG.debug("Authorization Model is to update on {} {}", eventType, relationshipType);
+
+ WriteAuthorizationModelResponse response = openfgaClient.writeAuthorizationModel(
+ new WriteAuthorizationModelRequest().
+ schemaVersion(authModel.getSchemaVersion()).
+ typeDefinitions(authModel.getTypeDefinitions()).
+ conditions(authModel.getConditions()));
+ openfgaClient.setAuthorizationModelId(response.getAuthorizationModelId());
+ } else {
+ LOG.debug("Authorization Model not to update on {} {}", eventType, relationshipType);
+ }
+ }
+
+ public void handle(
+ final OpenFGAClient openfgaClient,
+ final SyncDeltaType eventType,
+ final Any any) throws ApiException {
+
+ List<ReadRequest> readRequests = new ArrayList<>();
+ if (any instanceof Groupable) {
+ ReadRequest request = new ReadRequest();
+ request.setTupleKey(new ReadRequestTupleKey().
+ user(id(any))._object(type(AnyTypeKind.GROUP.name())));
+ readRequests.add(request);
+ }
+ for (RelationshipType relationshipType : relationshipTypeDAO.findByLeftEndAnyType(any.getType())) {
+ ReadRequest request = new ReadRequest();
+ request.setTupleKey(new ReadRequestTupleKey().
+ user(id(any))._object(type(relationshipType.getRightEndAnyType())));
+ readRequests.add(request);
+ }
+
+ List<TupleKey> current = new ArrayList<>();
+ for (ReadRequest request : readRequests) {
+ current.addAll(openfgaClient.read(request).getTuples().stream().map(Tuple::getKey).toList());
+ }
+
+ List<TupleKey> next;
+ if (eventType == SyncDeltaType.DELETE) {
+ next = List.of();
+ } else {
+ next = new ArrayList<>();
+ if (any instanceof Groupable<?, ?, ?, ?> groupable) {
+ next.addAll(groupable.getMemberships().stream().map(m -> new TupleKey().
+ user(id(groupable)).
+ relation(OpenFGAClientFactory.MEMBERSHIP_RELATION).
+ _object(id(m.getRightEnd()))).
+ toList());
+ }
+ if (any instanceof Relatable<?, ?, ?> relatable) {
+ next.addAll(relatable.getRelationships().stream().
+ filter(r -> !r.getType().getRightEndAnyType().equals(any.getType())).
+ map(r -> new TupleKey().
+ user(id(relatable)).
+ relation(r.getType().getKey()).
+ _object(id(r.getRightEnd()))).
+ toList());
+ }
+ }
+
+ List<TupleKey> toWrite = next.stream().
+ filter(tk -> !current.contains(tk)).
+ map(tk -> new TupleKey().
+ user(tk.getUser()).
+ relation(tk.getRelation())
+ ._object(tk.getObject())).
+ toList();
+ List<TupleKeyWithoutCondition> toDelete = current.stream().
+ filter(tk -> !next.contains(tk)).
+ map(tk -> new TupleKeyWithoutCondition().
+ user(tk.getUser()).
+ relation(tk.getRelation())
+ ._object(tk.getObject())).
+ toList();
+
+ if (!toWrite.isEmpty() || !toDelete.isEmpty()) {
+ LOG.debug("Tuples are to update on {} {}", eventType, any);
+
+ AuthorizationModel authModel = openfgaClient.readLatestAuthorizationModel();
+ openfgaClient.setAuthorizationModelId(authModel.getId());
+
+ WriteRequest request = new WriteRequest();
+ if (!toWrite.isEmpty()) {
+ request.writes(new WriteRequestWrites().tupleKeys(toWrite));
+ }
+ if (!toDelete.isEmpty()) {
+ request.deletes(new WriteRequestDeletes().tupleKeys(toDelete));
+ }
+
+ openfgaClient.write(request);
+ } else {
+ LOG.debug("Tuples not to update on {} {}", eventType, any);
+ }
+ }
+
+ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
+ @TransactionalEventListener
+ public void entity(final EntityLifecycleEvent<Entity> event) throws IOException {
+ LOG.debug("About to handle {}", event);
+
+ OpenFGAClient openfgaClient = clientFactory.get(event.getDomain());
+
+ try {
+ if (event.getEntity() instanceof final AnyType anyType && anyType.getKind() == AnyTypeKind.ANY_OBJECT) {
+ handle(openfgaClient, event.getType(), anyType);
+ } else if (event.getEntity() instanceof final RelationshipType relationshipType) {
+ handle(openfgaClient, event.getType(), relationshipType);
+ } else if (event.getEntity() instanceof final Any any) {
+ handle(openfgaClient, event.getType(), any);
+ }
+ } catch (Exception e) {
+ LOG.error("While handling event {}", event, e);
+ }
+ }
+}
diff --git a/ext/openfga/client-openfga/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/ext/openfga/client-openfga/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 0000000000..99a87975da
--- /dev/null
+++ b/ext/openfga/client-openfga/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1,17 @@
+# 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.
+org.apache.syncope.ext.openfga.client.OpenFGAClientContext
diff --git a/ext/openfga/client-openfga/src/main/resources/openfga.yaml b/ext/openfga/client-openfga/src/main/resources/openfga.yaml
new file mode 100644
index 0000000000..18160447cc
--- /dev/null
+++ b/ext/openfga/client-openfga/src/main/resources/openfga.yaml
@@ -0,0 +1,3277 @@
+#
+# Copyright (C) OpenFGA https://openfga.dev/
+#
+# 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.
+#
+# Copied from https://raw.githubusercontent.com/openfga/api/main/docs/openapiv2/apidocs.swagger.json
+#
+swagger: '2.0'
+info:
+ title: OpenFGA
+ description: >-
+ A high performance and flexible authorization/permission engine built for
+ developers and inspired by Google Zanzibar.
+ version: 1.x
+ contact:
+ name: OpenFGA
+ url: https://openfga.dev
+ email: community@openfga.dev
+ license:
+ name: Apache-2.0
+ url: https://github.com/openfga/openfga/blob/main/LICENSE
+tags:
+ - name: OpenFGAService
+schemes:
+ - https
+consumes:
+ - application/json
+produces:
+ - application/json
+paths:
+ /stores:
+ get:
+ summary: List all stores
+ description: >
+ Returns a paginated list of OpenFGA stores and a continuation token to
+ get additional stores.
+
+ The continuation token will be empty if there are no more stores.
+ operationId: ListStores
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/ListStoresResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: page_size
+ in: query
+ required: false
+ type: integer
+ format: int32
+ - name: continuation_token
+ in: query
+ required: false
+ type: string
+ - name: name
+ description: >-
+ The name parameter instructs the API to only include results that
+ match that name.Multiple results may be returned. Only exact matches
+ will be returned; substring matches and regexes will not be
+ evaluated
+ in: query
+ required: false
+ type: string
+ tags:
+ - Stores
+ post:
+ summary: Create a store
+ description: >-
+ Create a unique OpenFGA store which will be used to store authorization
+ models and relationship tuples.
+ operationId: CreateStore
+ responses:
+ '201':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/CreateStoreResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: body
+ in: body
+ required: true
+ schema:
+ $ref: '#/definitions/CreateStoreRequest'
+ tags:
+ - Stores
+ /stores/{store_id}:
+ get:
+ summary: Get a store
+ description: Returns an OpenFGA store by its identifier
+ operationId: GetStore
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/GetStoreResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ tags:
+ - Stores
+ delete:
+ summary: Delete a store
+ description: >-
+ Delete an OpenFGA store. This does not delete the data associated with
+ the store, like tuples or authorization models.
+ operationId: DeleteStore
+ responses:
+ '204':
+ description: A successful response.
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ tags:
+ - Stores
+ /stores/{store_id}/assertions/{authorization_model_id}:
+ get:
+ summary: Read assertions for an authorization model ID
+ description: >-
+ The ReadAssertions API will return, for a given authorization model id,
+ all the assertions stored for it.
+ operationId: ReadAssertions
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/ReadAssertionsResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: authorization_model_id
+ in: path
+ required: true
+ type: string
+ tags:
+ - Assertions
+ put:
+ summary: Upsert assertions for an authorization model ID
+ description: >-
+ The WriteAssertions API will upsert new assertions for an authorization
+ model id, or overwrite the existing ones. An assertion is an object that
+ contains a tuple key, the expectation of whether a call to the Check API
+ of that tuple key will return true or false, and optionally a list of
+ contextual tuples.
+ operationId: WriteAssertions
+ responses:
+ '204':
+ description: A successful response.
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: authorization_model_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ assertions:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/Assertion'
+ maxItems: 100
+ required:
+ - assertions
+ tags:
+ - Assertions
+ /stores/{store_id}/authorization-models:
+ get:
+ summary: Return all the authorization models for a particular store
+ description: >
+ The ReadAuthorizationModels API will return all the authorization models
+ for a certain store.
+
+ OpenFGA's response will contain an array of all authorization models,
+ sorted in descending order of creation.
+
+
+ ## Example
+
+ Assume that a store's authorization model has been configured twice. To
+ get all the authorization models that have been created in this store,
+ call GET authorization-models. The API will return a response that looks
+ like:
+
+ ```json
+
+ {
+ "authorization_models": [
+ {
+ "id": "01G50QVV17PECNVAHX1GG4Y5NC",
+ "type_definitions": [...]
+ },
+ {
+ "id": "01G4ZW8F4A07AKQ8RHSVG9RW04",
+ "type_definitions": [...]
+ },
+ ],
+ "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="
+ }
+
+ ```
+
+ If there are no more authorization models available, the
+ `continuation_token` field will be empty
+
+ ```json
+
+ {
+ "authorization_models": [
+ {
+ "id": "01G50QVV17PECNVAHX1GG4Y5NC",
+ "type_definitions": [...]
+ },
+ {
+ "id": "01G4ZW8F4A07AKQ8RHSVG9RW04",
+ "type_definitions": [...]
+ },
+ ],
+ "continuation_token": ""
+ }
+
+ ```
+ operationId: ReadAuthorizationModels
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/ReadAuthorizationModelsResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: page_size
+ in: query
+ required: false
+ type: integer
+ format: int32
+ - name: continuation_token
+ in: query
+ required: false
+ type: string
+ tags:
+ - Authorization Models
+ post:
+ summary: Create a new authorization model
+ description: >
+ The WriteAuthorizationModel API will add a new authorization model to a
+ store.
+
+ Each item in the `type_definitions` array is a type definition as
+ specified in the field `type_definition`.
+
+ The response will return the authorization model's ID in the `id` field.
+
+
+ ## Example
+
+ To add an authorization model with `user` and `document` type
+ definitions, call POST authorization-models API with the body:
+
+ ```json
+
+ {
+ "type_definitions":[
+ {
+ "type":"user"
+ },
+ {
+ "type":"document",
+ "relations":{
+ "reader":{
+ "union":{
+ "child":[
+ {
+ "this":{}
+ },
+ {
+ "computedUserset":{
+ "object":"",
+ "relation":"writer"
+ }
+ }
+ ]
+ }
+ },
+ "writer":{
+ "this":{}
+ }
+ }
+ }
+ ]
+ }
+
+ ```
+
+ OpenFGA's response will include the version id for this authorization
+ model, which will look like
+
+ ```
+
+ {"authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC"}
+
+ ```
+ operationId: WriteAuthorizationModel
+ responses:
+ '201':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/WriteAuthorizationModelResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ type_definitions:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/TypeDefinition'
+ minItems: 1
+ schema_version:
+ type: string
+ conditions:
+ type: object
+ additionalProperties:
+ $ref: '#/definitions/Condition'
+ required:
+ - type_definitions
+ - schema_version
+ tags:
+ - Authorization Models
+ /stores/{store_id}/authorization-models/{id}:
+ get:
+ summary: Return a particular version of an authorization model
+ description: >-
+ The ReadAuthorizationModel API returns an authorization model by its
+ identifier.
+
+ The response will return the authorization model for the particular
+ version.
+
+
+ ## Example
+
+ To retrieve the authorization model with ID `01G5JAVJ41T49E9TT3SKVS7X1J`
+ for the store, call the GET authorization-models by ID API with
+ `01G5JAVJ41T49E9TT3SKVS7X1J` as the `id` path parameter. The API will
+ return:
+
+ ```json
+
+ {
+ "authorization_model":{
+ "id":"01G5JAVJ41T49E9TT3SKVS7X1J",
+ "type_definitions":[
+ {
+ "type":"user"
+ },
+ {
+ "type":"document",
+ "relations":{
+ "reader":{
+ "union":{
+ "child":[
+ {
+ "this":{}
+ },
+ {
+ "computedUserset":{
+ "object":"",
+ "relation":"writer"
+ }
+ }
+ ]
+ }
+ },
+ "writer":{
+ "this":{}
+ }
+ }
+ }
+ ]
+ }
+ }
+
+ ```
+
+ In the above example, there are 2 types (`user` and `document`). The
+ `document` type has 2 relations (`writer` and `reader`).
+ operationId: ReadAuthorizationModel
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/ReadAuthorizationModelResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: id
+ in: path
+ required: true
+ type: string
+ tags:
+ - Authorization Models
+ /stores/{store_id}/batch-check:
+ post:
+ summary: Send a list of `check` operations in a single request
+ description: >
+ The `BatchCheck` API functions nearly identically to `Check`, but
+ instead of checking a single user-object relationship BatchCheck accepts
+ a list of relationships to check and returns a map containing
+ `BatchCheckItem` response for each check it received.
+
+
+ An associated `correlation_id` is required for each check in the batch.
+ This ID is used to correlate a check to the appropriate response. It is
+ a string consisting of only alphanumeric characters or hyphens with a
+ maximum length of 36 characters. This `correlation_id` is used to map
+ the result of each check to the item which was checked, so it must be
+ unique for each item in the batch. We recommend using a UUID or ULID as
+ the `correlation_id`, but you can use whatever unique identifier you
+ need as long as it matches this regex pattern: `^[\w\d-]{1,36}$`
+
+
+ For more details on how `Check` functions, see the docs for `/check`.
+
+
+ ### Examples
+
+ #### A BatchCheckRequest
+
+ ```json
+
+ {
+ "checks": [
+ {
+ "tuple_key": {
+ "object": "document:2021-budget"
+ "relation": "reader",
+ "user": "user:anne",
+ },
+ "contextual_tuples": {...}
+ "context": {}
+ "correlation_id": "01JA8PM3QM7VBPGB8KMPK8SBD5"
+ },
+ {
+ "tuple_key": {
+ "object": "document:2021-budget"
+ "relation": "reader",
+ "user": "user:bob",
+ },
+ "contextual_tuples": {...}
+ "context": {}
+ "correlation_id": "01JA8PMM6A90NV5ET0F28CYSZQ"
+ }
+ ]
+ }
+
+ ```
+
+
+ Below is a possible response to the above request. Note that the result
+ map's keys are the `correlation_id` values from the checked items in the
+ request:
+
+ ```json
+
+ {
+ "result": {
+ "01JA8PMM6A90NV5ET0F28CYSZQ": {
+ "allowed": false,
+ "error": {"message": ""}
+ },
+ "01JA8PM3QM7VBPGB8KMPK8SBD5": {
+ "allowed": true,
+ "error": {"message": ""}
+ }
+ }
+
+ ```
+ operationId: BatchCheck
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/BatchCheckResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ checks:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/BatchCheckItem'
+ minItems: 1
+ authorization_model_id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ consistency:
+ $ref: '#/definitions/ConsistencyPreference'
+ required:
+ - checks
+ tags:
+ - Relationship Queries
+ /stores/{store_id}/changes:
+ get:
+ summary: Return a list of all the tuple changes
+ description: >
+ The ReadChanges API will return a paginated list of tuple changes
+ (additions and deletions) that occurred in a given store, sorted by
+ ascending time. The response will include a continuation token that is
+ used to get the next set of changes. If there are no changes after the
+ provided continuation token, the same token will be returned in order
+ for it to be used when new changes are recorded. If the store never had
+ any tuples added or removed, this token will be empty.
+
+ You can use the `type` parameter to only get the list of tuple changes
+ that affect objects of that type.
+
+ When reading a write tuple change, if it was conditioned, the condition
+ will be returned.
+
+ When reading a delete tuple change, the condition will NOT be returned
+ regardless of whether it was originally conditioned or not.
+ operationId: ReadChanges
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/ReadChangesResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: type
+ in: query
+ required: false
+ type: string
+ - name: page_size
+ in: query
+ required: false
+ type: integer
+ format: int32
+ - name: continuation_token
+ in: query
+ required: false
+ type: string
+ - name: start_time
+ description: >-
+ Start date and time of changes to read.
+
+ Format: ISO 8601 timestamp (e.g., 2022-01-01T00:00:00Z)
+
+ If a continuation_token is provided along side start_time, the
+ continuation_token will take precedence over start_time.
+ in: query
+ required: false
+ type: string
+ format: date-time
+ tags:
+ - Relationship Tuples
+ /stores/{store_id}/check:
+ post:
+ summary: Check whether a user is authorized to access an object
+ description: >
+ The Check API returns whether a given user has a relationship with a
+ given object in a given store.
+
+ The `user` field of the request can be a specific target, such as
+ `user:anne`, or a userset (set of users) such as
+ `group:marketing#member` or a type-bound public access `user:*`.
+
+ To arrive at a result, the API uses: an authorization model, explicit
+ tuples written through the Write API, contextual tuples present in the
+ request, and implicit tuples that exist by virtue of applying set theory
+ (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the
+ set of users who are viewers of `document:2021-budget` are the set of
+ users who are the viewers of `document:2021-budget`).
+
+ A `contextual_tuples` object may also be included in the body of the
+ request. This object contains one field `tuple_keys`, which is an array
+ of tuple keys. Each of these tuples may have an associated `condition`.
+
+ You may also provide an `authorization_model_id` in the body. This will
+ be used to assert that the input `tuple_key` is valid for the model
+ specified. If not specified, the assertion will be made against the
+ latest authorization model ID. It is strongly recommended to specify
+ authorization model id for better performance.
+
+ You may also provide a `context` object that will be used to evaluate
+ the conditioned tuples in the system. It is strongly recommended to
+ provide a value for all the input parameters of all the conditions, to
+ ensure that all tuples be evaluated correctly.
+
+ By default, the Check API caches results for a short time to optimize
+ performance. You may specify a value of `HIGHER_CONSISTENCY` for the
+ optional `consistency` parameter in the body to inform the server that
+ higher conisistency is preferred at the expense of increased latency.
+ Consideration should be given to the increased latency if requesting
+ higher consistency.
+
+ The response will return whether the relationship exists in the field
+ `allowed`.
+
+
+ Some exceptions apply, but in general, if a Check API responds with
+ `{allowed: true}`, then you can expect the equivalent ListObjects query
+ to return the object, and viceversa.
+
+ For example, if `Check(user:anne, reader, document:2021-budget)`
+ responds with `{allowed: true}`, then `ListObjects(user:anne, reader,
+ document)` may include `document:2021-budget` in the response.
+
+ ## Examples
+
+ ### Querying with contextual tuples
+
+ In order to check if user `user:anne` of type `user` has a `reader`
+ relationship with object `document:2021-budget` given the following
+ contextual tuple
+
+ ```json
+
+ {
+ "user": "user:anne",
+ "relation": "member",
+ "object": "time_slot:office_hours"
+ }
+
+ ```
+
+ the Check API can be used with the following request body:
+
+ ```json
+
+ {
+ "tuple_key": {
+ "user": "user:anne",
+ "relation": "reader",
+ "object": "document:2021-budget"
+ },
+ "contextual_tuples": {
+ "tuple_keys": [
+ {
+ "user": "user:anne",
+ "relation": "member",
+ "object": "time_slot:office_hours"
+ }
+ ]
+ },
+ "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC"
+ }
+
+ ```
+
+ ### Querying usersets
+
+ Some Checks will always return `true`, even without any tuples. For
+ example, for the following authorization model
+
+ ```python
+
+ model
+ schema 1.1
+ type user
+
+ type document
+ relations
+ define reader: [user]
+ ```
+
+ the following query
+
+ ```json
+
+ {
+ "tuple_key": {
+ "user": "document:2021-budget#reader",
+ "relation": "reader",
+ "object": "document:2021-budget"
+ }
+ }
+
+ ```
+
+ will always return `{ "allowed": true }`. This is because usersets are
+ self-defining: the userset `document:2021-budget#reader` will always
+ have the `reader` relation with `document:2021-budget`.
+
+ ### Querying usersets with difference in the model
+
+ A Check for a userset can yield results that must be treated carefully
+ if the model involves difference. For example, for the following
+ authorization model
+
+ ```python
+
+ model
+ schema 1.1
+ type user
+
+ type group
+ relations
+ define member: [user]
+ type document
+ relations
+ define blocked: [user]
+ define reader: [group#member] but not blocked
+ ```
+
+ the following query
+
+ ```json
+
+ {
+ "tuple_key": {
+ "user": "group:finance#member",
+ "relation": "reader",
+ "object": "document:2021-budget"
+ },
+ "contextual_tuples": {
+ "tuple_keys": [
+ {
+ "user": "user:anne",
+ "relation": "member",
+ "object": "group:finance"
+ },
+ {
+ "user": "group:finance#member",
+ "relation": "reader",
+ "object": "document:2021-budget"
+ },
+ {
+ "user": "user:anne",
+ "relation": "blocked",
+ "object": "document:2021-budget"
+ }
+ ]
+ },
+ }
+
+ ```
+
+ will return `{ "allowed": true }`, even though a specific user of the
+ userset `group:finance#member` does not have the `reader` relationship
+ with the given object.
+
+ ### Requesting higher consistency
+
+ By default, the Check API caches results for a short time to optimize
+ performance. You may request higher consistency to inform the server
+ that higher consistency should be preferred at the expense of increased
+ latency. Care should be taken when requesting higher consistency due to
+ the increased latency.
+
+ ```json
+
+ {
+ "tuple_key": {
+ "user": "group:finance#member",
+ "relation": "reader",
+ "object": "document:2021-budget"
+ },
+ "consistency": "HIGHER_CONSISTENCY"
+ }
+
+ ```
+ operationId: Check
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/CheckResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ tuple_key:
+ $ref: '#/definitions/CheckRequestTupleKey'
+ contextual_tuples:
+ $ref: '#/definitions/ContextualTupleKeys'
+ authorization_model_id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ trace:
+ type: boolean
+ example: false
+ description: >-
+ Defaults to false. Making it true has performance
+ implications.
+ readOnly: true
+ context:
+ type: object
+ description: >-
+ Additional request context that will be used to evaluate any
+ ABAC conditions encountered
+
+ in the query evaluation.
+ consistency:
+ $ref: '#/definitions/ConsistencyPreference'
+ description: >-
+ Controls the consistency preference for this request. Default
+ value is UNSPECIFIED, which will have the same behavior as
+ MINIMIZE_LATENCY.
+ required:
+ - tuple_key
+ tags:
+ - Relationship Queries
+ /stores/{store_id}/expand:
+ post:
+ summary: >-
+ Expand all relationships in userset tree format, and following userset
+ rewrite rules. Useful to reason about and debug a certain relationship
+ description: >
+ The Expand API will return all users and usersets that have certain
+ relationship with an object in a certain store.
+
+ This is different from the `/stores/{store_id}/read` API in that both
+ users and computed usersets are returned.
+
+ Body parameters `tuple_key.object` and `tuple_key.relation` are all
+ required.
+
+ A `contextual_tuples` object may also be included in the body of the
+ request. This object contains one field `tuple_keys`, which is an array
+ of tuple keys. Each of these tuples may have an associated `condition`.
+
+ The response will return a tree whose leaves are the specific users and
+ usersets. Union, intersection and difference operator are located in the
+ intermediate nodes.
+
+
+ ## Example
+
+ To expand all users that have the `reader` relationship with object
+ `document:2021-budget`, use the Expand API with the following request
+ body
+
+ ```json
+
+ {
+ "tuple_key": {
+ "object": "document:2021-budget",
+ "relation": "reader"
+ },
+ "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC"
+ }
+
+ ```
+
+ OpenFGA's response will be a userset tree of the users and usersets that
+ have read access to the document.
+
+ ```json
+
+ {
+ "tree":{
+ "root":{
+ "type":"document:2021-budget#reader",
+ "union":{
+ "nodes":[
+ {
+ "type":"document:2021-budget#reader",
+ "leaf":{
+ "users":{
+ "users":[
+ "user:bob"
+ ]
+ }
+ }
+ },
+ {
+ "type":"document:2021-budget#reader",
+ "leaf":{
+ "computed":{
+ "userset":"document:2021-budget#writer"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+
+ ```
+
+ The caller can then call expand API for the `writer` relationship for
+ the `document:2021-budget`.
+
+ ### Expand Request with Contextual Tuples
+
+
+ Given the model
+
+ ```python
+
+ model
+ schema 1.1
+
+ type user
+
+
+ type folder
+ relations
+ define owner: [user]
+
+ type document
+ relations
+ define parent: [folder]
+ define viewer: [user] or writer
+ define writer: [user] or owner from parent
+ ```
+
+ and the initial tuples
+
+ ```json
+
+ [{
+ "user": "user:bob",
+ "relation": "owner",
+ "object": "folder:1"
+ }]
+
+ ```
+
+
+ To expand all `writers` of `document:1` when `document:1` is put in
+ `folder:1`, the first call could be
+
+
+ ```json
+
+ {
+ "tuple_key": {
+ "object": "document:1",
+ "relation": "writer"
+ },
+ "contextual_tuples": {
+ "tuple_keys": [
+ {
+ "user": "folder:1",
+ "relation": "parent",
+ "object": "document:1"
+ }
+ ]
+ }
+ }
+
+ ```
+
+ this returns:
+
+ ```json
+
+ {
+ "tree": {
+ "root": {
+ "name": "document:1#writer",
+ "union": {
+ "nodes": [
+ {
+ "name": "document:1#writer",
+ "leaf": {
+ "users": {
+ "users": []
+ }
+ }
+ },
+ {
+ "name": "document:1#writer",
+ "leaf": {
+ "tupleToUserset": {
+ "tupleset": "document:1#parent",
+ "computed": [
+ {
+ "userset": "folder:1#owner"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+
+ ```
+
+ This tells us that the `owner` of `folder:1` may also be a writer. So
+ our next call could be to find the `owners` of `folder:1`
+
+ ```json
+
+ {
+ "tuple_key": {
+ "object": "folder:1",
+ "relation": "owner"
+ }
+ }
+
+ ```
+
+ which gives
+
+ ```json
+
+ {
+ "tree": {
+ "root": {
+ "name": "folder:1#owner",
+ "leaf": {
+ "users": {
+ "users": [
+ "user:bob"
+ ]
+ }
+ }
+ }
+ }
+ }
+
+ ```
+ operationId: Expand
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/ExpandResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ tuple_key:
+ $ref: '#/definitions/ExpandRequestTupleKey'
+ authorization_model_id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ consistency:
+ $ref: '#/definitions/ConsistencyPreference'
+ description: >-
+ Controls the consistency preference for this request. Default
+ value is UNSPECIFIED, which will have the same behavior as
+ MINIMIZE_LATENCY.
+ contextual_tuples:
+ $ref: '#/definitions/ContextualTupleKeys'
+ required:
+ - tuple_key
+ tags:
+ - Relationship Queries
+ /stores/{store_id}/list-objects:
+ post:
+ summary: List all objects of the given type that the user has a relation with
+ description: >-
+ The ListObjects API returns a list of all the objects of the given type
+ that the user has a relation with.
+ To arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).
+ An `authorization_model_id` may be specified in the body. If it is not
+ specified, the latest authorization model ID will be used. It is
+ strongly recommended to specify authorization model id for better
+ performance.
+
+ You may also specify `contextual_tuples` that will be treated as regular
+ tuples. Each of these tuples may have an associated `condition`.
+
+ You may also provide a `context` object that will be used to evaluate
+ the conditioned tuples in the system. It is strongly recommended to
+ provide a value for all the input parameters of all the conditions, to
+ ensure that all tuples be evaluated correctly.
+
+ By default, the Check API caches results for a short time to optimize
+ performance. You may specify a value of `HIGHER_CONSISTENCY` for the
+ optional `consistency` parameter in the body to inform the server that
+ higher conisistency is preferred at the expense of increased latency.
+ Consideration should be given to the increased latency if requesting
+ higher consistency.
+
+ The response will contain the related objects in an array in the
+ "objects" field of the response and they will be strings in the object
+ format `<type>:<id>` (e.g. "document:roadmap").
+
+ The number of objects in the response array will be limited by the
+ execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE
+ and by the upper bound specified in the flag
+ OPENFGA_LIST_OBJECTS_MAX_RESULTS, whichever is hit first.
+
+ The objects given will not be sorted, and therefore two identical calls
+ can give a given different set of objects.
+ operationId: ListObjects
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/ListObjectsResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ authorization_model_id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ type:
+ type: string
+ example: document
+ relation:
+ type: string
+ example: reader
+ user:
+ type: string
+ example: user:anne
+ maxLength: 512
+ minLength: 1
+ contextual_tuples:
+ $ref: '#/definitions/ContextualTupleKeys'
+ context:
+ type: object
+ description: >-
+ Additional request context that will be used to evaluate any
+ ABAC conditions encountered
+
+ in the query evaluation.
+ consistency:
+ $ref: '#/definitions/ConsistencyPreference'
+ description: >-
+ Controls the consistency preference for this request. Default
+ value is UNSPECIFIED, which will have the same behavior as
+ MINIMIZE_LATENCY.
+ required:
+ - type
+ - relation
+ - user
+ tags:
+ - Relationship Queries
+ /stores/{store_id}/list-users:
+ post:
+ summary: >-
+ List the users matching the provided filter who have a certain relation
+ to a particular type.
+ description: >-
+ The ListUsers API returns a list of all the users of a specific type
+ that have a relation to a given object.
+ To arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).
+ An `authorization_model_id` may be specified in the body. If it is not
+ specified, the latest authorization model ID will be used. It is
+ strongly recommended to specify authorization model id for better
+ performance.
+
+ You may also specify `contextual_tuples` that will be treated as regular
+ tuples. Each of these tuples may have an associated `condition`.
+
+ You may also provide a `context` object that will be used to evaluate
+ the conditioned tuples in the system. It is strongly recommended to
+ provide a value for all the input parameters of all the conditions, to
+ ensure that all tuples be evaluated correctly.
+
+ The response will contain the related users in an array in the "users"
+ field of the response. These results may include specific objects,
+ usersets
+
+ or type-bound public access. Each of these types of results is encoded
+ in its own type and not represented as a string.In cases where a
+ type-bound public access result is returned (e.g. `user:*`), it cannot
+ be inferred that all subjects
+
+ of that type have a relation to the object; it is possible that
+ negations exist and checks should still be queried
+
+ on individual subjects to ensure access to that document.The number of
+ users in the response array will be limited by the execution timeout
+ specified in the flag OPENFGA_LIST_USERS_DEADLINE and by the upper bound
+ specified in the flag OPENFGA_LIST_USERS_MAX_RESULTS, whichever is hit
+ first.
+
+ The returned users will not be sorted, and therefore two identical calls
+ may yield different sets of users.
+ operationId: ListUsers
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/ListUsersResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ authorization_model_id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ object:
+ $ref: '#/definitions/Object'
+ example: document:example
+ relation:
+ type: string
+ example: reader
+ user_filters:
+ type: array
+ example:
+ - type: user
+ - type: group
+ relation: member
+ items:
+ type: object
+ $ref: '#/definitions/UserTypeFilter'
+ description: The type of results returned. Only accepts exactly one value.
+ maxItems: 1
+ minItems: 1
+ contextual_tuples:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/TupleKey'
+ maxItems: 100
+ context:
+ type: object
+ description: >-
+ Additional request context that will be used to evaluate any
+ ABAC conditions encountered
+
+ in the query evaluation.
+ consistency:
+ $ref: '#/definitions/ConsistencyPreference'
+ description: >-
+ Controls the consistency preference for this request. Default
+ value is UNSPECIFIED, which will have the same behavior as
+ MINIMIZE_LATENCY.
+ required:
+ - object
+ - relation
+ - user_filters
+ tags:
+ - Relationship Queries
+ /stores/{store_id}/read:
+ post:
+ summary: >-
+ Get tuples from the store that matches a query, without following
+ userset rewrite rules
+ description: >
+ The Read API will return the tuples for a certain store that match a
+ query filter specified in the body of the request.
+
+ The API doesn't guarantee order by any field.
+
+ It is different from the `/stores/{store_id}/expand` API in that it only
+ returns relationship tuples that are stored in the system and satisfy
+ the query.
+
+ In the body:
+
+ 1. `tuple_key` is optional. If not specified, it will return all tuples
+ in the store.
+
+ 2. `tuple_key.object` is mandatory if `tuple_key` is specified. It can
+ be a full object (e.g., `type:object_id`) or type only (e.g., `type:`).
+
+ 3. `tuple_key.user` is mandatory if tuple_key is specified in the case
+ the `tuple_key.object` is a type only. If tuple_key.user is specified,
+ it needs to be a full object (e.g., `type:user_id`).
+
+ ## Examples
+
+ ### Query for all objects in a type definition
+
+ To query for all objects that `user:bob` has `reader` relationship in
+ the `document` type definition, call read API with body of
+
+ ```json
+
+ {
+ "tuple_key": {
+ "user": "user:bob",
+ "relation": "reader",
+ "object": "document:"
+ }
+ }
+
+ ```
+
+ The API will return tuples and a continuation token, something like
+
+ ```json
+
+ {
+ "tuples": [
+ {
+ "key": {
+ "user": "user:bob",
+ "relation": "reader",
+ "object": "document:2021-budget"
+ },
+ "timestamp": "2021-10-06T15:32:11.128Z"
+ }
+ ],
+ "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="
+ }
+
+ ```
+
+ This means that `user:bob` has a `reader` relationship with 1 document
+ `document:2021-budget`. Note that this API, unlike the List Objects API,
+ does not evaluate the tuples in the store.
+
+ The continuation token will be empty if there are no more tuples to
+ query.
+
+ ### Query for all stored relationship tuples that have a particular
+ relation and object
+
+ To query for all users that have `reader` relationship with
+ `document:2021-budget`, call read API with body of
+
+ ```json
+
+ {
+ "tuple_key": {
+ "object": "document:2021-budget",
+ "relation": "reader"
+ }
+ }
+
+ ```
+
+ The API will return something like
+
+ ```json
+
+ {
+ "tuples": [
+ {
+ "key": {
+ "user": "user:bob",
+ "relation": "reader",
+ "object": "document:2021-budget"
+ },
+ "timestamp": "2021-10-06T15:32:11.128Z"
+ }
+ ],
+ "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="
+ }
+
+ ```
+
+ This means that `document:2021-budget` has 1 `reader` (`user:bob`).
+ Note that, even if the model said that all `writers` are also `readers`,
+ the API will not return writers such as `user:anne` because it only
+ returns tuples and does not evaluate them.
+
+ ### Query for all users with all relationships for a particular document
+
+ To query for all users that have any relationship with
+ `document:2021-budget`, call read API with body of
+
+ ```json
+
+ {
+ "tuple_key": {
+ "object": "document:2021-budget"
+ }
+ }
+
+ ```
+
+ The API will return something like
+
+ ```json
+
+ {
+ "tuples": [
+ {
+ "key": {
+ "user": "user:anne",
+ "relation": "writer",
+ "object": "document:2021-budget"
+ },
+ "timestamp": "2021-10-05T13:42:12.356Z"
+ },
+ {
+ "key": {
+ "user": "user:bob",
+ "relation": "reader",
+ "object": "document:2021-budget"
+ },
+ "timestamp": "2021-10-06T15:32:11.128Z"
+ }
+ ],
+ "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="
+ }
+
+ ```
+
+ This means that `document:2021-budget` has 1 `reader` (`user:bob`) and 1
+ `writer` (`user:anne`).
+ operationId: Read
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/ReadResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ tuple_key:
+ $ref: '#/definitions/ReadRequestTupleKey'
+ page_size:
+ type: integer
+ format: int32
+ example: 50
+ maximum: 100
+ minimum: 1
+ continuation_token:
+ type: string
+ example: >-
+ eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==
+ consistency:
+ $ref: '#/definitions/ConsistencyPreference'
+ description: >-
+ Controls the consistency preference for this request. Default
+ value is UNSPECIFIED, which will have the same behavior as
+ MINIMIZE_LATENCY.
+ tags:
+ - Relationship Tuples
+ /stores/{store_id}/streamed-list-objects:
+ post:
+ summary: Stream all objects of the given type that the user has a relation with
+ description: >
+ The Streamed ListObjects API is very similar to the the ListObjects API,
+ with two differences:
+
+ 1. Instead of collecting all objects before returning a response, it
+ streams them to the client as they are collected.
+
+ 2. The number of results returned is only limited by the execution
+ timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE.
+ operationId: StreamedListObjects
+ responses:
+ '200':
+ description: A successful response.(streaming responses)
+ schema:
+ type: object
+ properties:
+ result:
+ $ref: '#/definitions/StreamedListObjectsResponse'
+ error:
+ $ref: '#/definitions/Status'
+ title: Stream result of StreamedListObjectsResponse
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ authorization_model_id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ type:
+ type: string
+ example: document
+ relation:
+ type: string
+ example: reader
+ user:
+ type: string
+ example: user:anne
+ maxLength: 512
+ minLength: 1
+ contextual_tuples:
+ $ref: '#/definitions/ContextualTupleKeys'
+ context:
+ type: object
+ description: >-
+ Additional request context that will be used to evaluate any
+ ABAC conditions encountered
+
+ in the query evaluation.
+ consistency:
+ $ref: '#/definitions/ConsistencyPreference'
+ description: >-
+ Controls the consistency preference for this request. Default
+ value is UNSPECIFIED, which will have the same behavior as
+ MINIMIZE_LATENCY.
+ required:
+ - type
+ - relation
+ - user
+ tags:
+ - Relationship Queries
+ /stores/{store_id}/write:
+ post:
+ summary: Add or delete tuples from the store
+ description: >
+ The Write API will transactionally update the tuples for a certain
+ store. Tuples and type definitions allow OpenFGA to determine whether a
+ relationship exists between an object and an user.
+
+ In the body, `writes` adds new tuples and `deletes` removes existing
+ tuples. When deleting a tuple, any `condition` specified with it is
+ ignored.
+
+ The API is not idempotent: if, later on, you try to add the same tuple
+ key (even if the `condition` is different), or if you try to delete a
+ non-existing tuple, it will throw an error.
+
+ The API will not allow you to write tuples such as
+ `document:2021-budget#viewer@document:2021-budget#viewer`, because they
+ are implicit.
+
+ An `authorization_model_id` may be specified in the body. If it is, it
+ will be used to assert that each written tuple (not deleted) is valid
+ for the model specified. If it is not specified, the latest
+ authorization model ID will be used.
+
+ ## Example
+
+ ### Adding relationships
+
+ To add `user:anne` as a `writer` for `document:2021-budget`, call write
+ API with the following
+
+ ```json
+
+ {
+ "writes": {
+ "tuple_keys": [
+ {
+ "user": "user:anne",
+ "relation": "writer",
+ "object": "document:2021-budget"
+ }
+ ]
+ },
+ "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC"
+ }
+
+ ```
+
+ ### Removing relationships
+
+ To remove `user:bob` as a `reader` for `document:2021-budget`, call
+ write API with the following
+
+ ```json
+
+ {
+ "deletes": {
+ "tuple_keys": [
+ {
+ "user": "user:bob",
+ "relation": "reader",
+ "object": "document:2021-budget"
+ }
+ ]
+ }
+ }
+
+ ```
+ operationId: Write
+ responses:
+ '200':
+ description: A successful response.
+ schema:
+ $ref: '#/definitions/WriteResponse'
+ '400':
+ description: Request failed due to invalid input.
+ schema:
+ $ref: '#/definitions/ValidationErrorMessageResponse'
+ '401':
+ description: Not authenticated.
+ schema:
+ $ref: '#/definitions/UnauthenticatedResponse'
+ '403':
+ description: Forbidden.
+ schema:
+ $ref: '#/definitions/ForbiddenResponse'
+ '404':
+ description: Request failed due to incorrect path.
+ schema:
+ $ref: '#/definitions/PathUnknownErrorMessageResponse'
+ '409':
+ description: Request was aborted due a transaction conflict.
+ schema:
+ $ref: '#/definitions/AbortedMessageResponse'
+ '422':
+ description: Request timed out due to excessive request throttling.
+ schema:
+ $ref: '#/definitions/UnprocessableContentMessageResponse'
+ '500':
+ description: Request failed due to internal server error.
+ schema:
+ $ref: '#/definitions/InternalErrorMessageResponse'
+ parameters:
+ - name: store_id
+ in: path
+ required: true
+ type: string
+ - name: body
+ in: body
+ required: true
+ schema:
+ type: object
+ properties:
+ writes:
+ $ref: '#/definitions/WriteRequestWrites'
+ deletes:
+ $ref: '#/definitions/WriteRequestDeletes'
+ authorization_model_id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ tags:
+ - Relationship Tuples
+definitions:
+ AbortedMessageResponse:
+ type: object
+ example:
+ code: '10'
+ message: transaction conflict
+ properties:
+ code:
+ type: string
+ message:
+ type: string
+ Any:
+ type: object
+ properties:
+ '@type':
+ type: string
+ additionalProperties: {}
+ Assertion:
+ type: object
+ properties:
+ tuple_key:
+ $ref: '#/definitions/AssertionTupleKey'
+ expectation:
+ type: boolean
+ contextual_tuples:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/TupleKey'
+ maxItems: 20
+ context:
+ type: object
+ example:
+ view_count: 100
+ description: >-
+ Additional request context that will be used to evaluate any ABAC
+ conditions encountered
+
+ in the query evaluation.
+ required:
+ - tuple_key
+ - expectation
+ AssertionTupleKey:
+ type: object
+ properties:
+ object:
+ type: string
+ example: document:2021-budget
+ maxLength: 256
+ relation:
+ type: string
+ example: reader
+ maxLength: 50
+ user:
+ type: string
+ example: user:anne
+ maxLength: 512
+ required:
+ - object
+ - relation
+ - user
+ AuthErrorCode:
+ type: string
+ enum:
+ - no_auth_error
+ - auth_failed_invalid_subject
+ - auth_failed_invalid_audience
+ - auth_failed_invalid_issuer
+ - invalid_claims
+ - auth_failed_invalid_bearer_token
+ - bearer_token_missing
+ - unauthenticated
+ - forbidden
+ default: no_auth_error
+ AuthorizationModel:
+ type: object
+ properties:
+ id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ schema_version:
+ type: string
+ type_definitions:
+ type: array
+ example:
+ - type: user
+ - type: document
+ relations:
+ reader:
+ union:
+ child:
+ - this: {}
+ - computedUserset:
+ object: ''
+ relation: writer
+ writer:
+ this: {}
+ metadata:
+ relations:
+ reader:
+ directly_related_user_types:
+ - type: user
+ writer:
+ directly_related_user_types:
+ - type: user
+ items:
+ type: object
+ $ref: '#/definitions/TypeDefinition'
+ conditions:
+ type: object
+ additionalProperties:
+ $ref: '#/definitions/Condition'
+ required:
+ - id
+ - schema_version
+ - type_definitions
+ BatchCheckItem:
+ type: object
+ properties:
+ tuple_key:
+ $ref: '#/definitions/CheckRequestTupleKey'
+ contextual_tuples:
+ $ref: '#/definitions/ContextualTupleKeys'
+ context:
+ type: object
+ correlation_id:
+ type: string
+ example: 1cd93d8c-8e45-43c6-9a15-cbb3c7f394bc
+ description: >-
+ correlation_id must be a string containing only letters, numbers, or
+ hyphens, with length ≤ 36 characters.
+ required:
+ - tuple_key
+ - correlation_id
+ BatchCheckResponse:
+ type: object
+ properties:
+ result:
+ type: object
+ example:
+ 1cd93d8c-8e45-43c6-9a15-cbb3c7f394bc:
+ allowed: true
+ error:
+ message: ''
+ additionalProperties:
+ $ref: '#/definitions/BatchCheckSingleResult'
+ description: >-
+ map keys are the correlation_id values from the BatchCheckItems in the
+ request
+ BatchCheckSingleResult:
+ type: object
+ properties:
+ allowed:
+ type: boolean
+ error:
+ $ref: '#/definitions/CheckError'
+ CheckError:
+ type: object
+ properties:
+ input_error:
+ $ref: '#/definitions/ErrorCode'
+ internal_error:
+ $ref: '#/definitions/InternalErrorCode'
+ message:
+ type: string
+ CheckRequestTupleKey:
+ type: object
+ properties:
+ user:
+ type: string
+ example: user:anne
+ maxLength: 512
+ relation:
+ type: string
+ example: reader
+ maxLength: 50
+ object:
+ type: string
+ example: document:2021-budget
+ maxLength: 256
+ required:
+ - user
+ - relation
+ - object
+ CheckResponse:
+ type: object
+ properties:
+ allowed:
+ type: boolean
+ example: true
+ resolution:
+ type: string
+ description: For internal use only.
+ Computed:
+ type: object
+ properties:
+ userset:
+ type: string
+ required:
+ - userset
+ Condition:
+ type: object
+ properties:
+ name:
+ type: string
+ title: A unique name for the condition
+ expression:
+ type: string
+ description: A Google CEL expression, expressed as a string.
+ parameters:
+ type: object
+ additionalProperties:
+ $ref: '#/definitions/ConditionParamTypeRef'
+ description: A map of parameter names to the parameter's defined type reference.
+ metadata:
+ $ref: '#/definitions/ConditionMetadata'
+ required:
+ - name
+ - expression
+ ConditionMetadata:
+ type: object
+ properties:
+ module:
+ type: string
+ source_info:
+ $ref: '#/definitions/SourceInfo'
+ ConditionParamTypeRef:
+ type: object
+ properties:
+ type_name:
+ $ref: '#/definitions/TypeName'
+ generic_types:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/ConditionParamTypeRef'
+ required:
+ - type_name
+ ConsistencyPreference:
+ type: string
+ enum:
+ - UNSPECIFIED
+ - MINIMIZE_LATENCY
+ - HIGHER_CONSISTENCY
+ default: UNSPECIFIED
+ description: |-
+ Controls the consistency preferences when calling the query APIs.
+
+ - UNSPECIFIED: Default if not set. Behavior will be the same as MINIMIZE_LATENCY.
+ - MINIMIZE_LATENCY: Minimize latency at the potential expense of lower consistency.
+ - HIGHER_CONSISTENCY: Prefer higher consistency, at the potential expense of increased latency.
+ example: MINIMIZE_LATENCY
+ ContextualTupleKeys:
+ type: object
+ properties:
+ tuple_keys:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/TupleKey'
+ maxItems: 100
+ required:
+ - tuple_keys
+ CreateStoreRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ example: my-store-name
+ required:
+ - name
+ CreateStoreResponse:
+ type: object
+ properties:
+ id:
+ type: string
+ example: 01YCP46JKYM8FJCQ37NMBYHE5X
+ name:
+ type: string
+ created_at:
+ type: string
+ format: date-time
+ updated_at:
+ type: string
+ format: date-time
+ required:
+ - id
+ - name
+ - created_at
+ - updated_at
+ DeleteStoreResponse:
+ type: object
+ DirectUserset:
+ type: object
+ description: |-
+ A DirectUserset is a sentinel message for referencing
+ the direct members specified by an object/relation mapping.
+ ErrorCode:
+ type: string
+ enum:
+ - no_error
+ - validation_error
+ - authorization_model_not_found
+ - authorization_model_resolution_too_complex
+ - invalid_write_input
+ - cannot_allow_duplicate_tuples_in_one_request
+ - cannot_allow_duplicate_types_in_one_request
+ - cannot_allow_multiple_references_to_one_relation
+ - invalid_continuation_token
+ - invalid_tuple_set
+ - invalid_check_input
+ - invalid_expand_input
+ - unsupported_user_set
+ - invalid_object_format
+ - write_failed_due_to_invalid_input
+ - authorization_model_assertions_not_found
+ - latest_authorization_model_not_found
+ - type_not_found
+ - relation_not_found
+ - empty_relation_definition
+ - invalid_user
+ - invalid_tuple
+ - unknown_relation
+ - store_id_invalid_length
+ - assertions_too_many_items
+ - id_too_long
+ - authorization_model_id_too_long
+ - tuple_key_value_not_specified
+ - tuple_keys_too_many_or_too_few_items
+ - page_size_invalid
+ - param_missing_value
+ - difference_base_missing_value
+ - subtract_base_missing_value
+ - object_too_long
+ - relation_too_long
+ - type_definitions_too_few_items
+ - type_invalid_length
+ - type_invalid_pattern
+ - relations_too_few_items
+ - relations_too_long
+ - relations_invalid_pattern
+ - object_invalid_pattern
+ - query_string_type_continuation_token_mismatch
+ - exceeded_entity_limit
+ - invalid_contextual_tuple
+ - duplicate_contextual_tuple
+ - invalid_authorization_model
+ - unsupported_schema_version
+ - cancelled
+ - invalid_start_time
+ default: no_error
+ ExpandRequestTupleKey:
+ type: object
+ properties:
+ relation:
+ type: string
+ example: reader
+ maxLength: 50
+ object:
+ type: string
+ example: document:2021-budget
+ maxLength: 256
+ required:
+ - relation
+ - object
+ ExpandResponse:
+ type: object
+ properties:
+ tree:
+ $ref: '#/definitions/UsersetTree'
+ ForbiddenResponse:
+ type: object
+ example:
+ code: forbidden
+ message: the principal is not authorized to perform the action
+ properties:
+ code:
+ $ref: '#/definitions/AuthErrorCode'
+ message:
+ type: string
+ GetStoreResponse:
+ type: object
+ properties:
+ id:
+ type: string
+ example: 01YCP46JKYM8FJCQ37NMBYHE5X
+ name:
+ type: string
+ created_at:
+ type: string
+ format: date-time
+ updated_at:
+ type: string
+ format: date-time
+ deleted_at:
+ type: string
+ format: date-time
+ required:
+ - id
+ - name
+ - created_at
+ - updated_at
+ InternalErrorCode:
+ type: string
+ enum:
+ - no_internal_error
+ - internal_error
+ - deadline_exceeded
+ - already_exists
+ - resource_exhausted
+ - failed_precondition
+ - aborted
+ - out_of_range
+ - unavailable
+ - data_loss
+ default: no_internal_error
+ InternalErrorMessageResponse:
+ type: object
+ example:
+ code: internal_error
+ message: Internal Server Error
+ properties:
+ code:
+ $ref: '#/definitions/InternalErrorCode'
+ message:
+ type: string
+ Leaf:
+ type: object
+ properties:
+ users:
+ $ref: '#/definitions/Users'
+ computed:
+ $ref: '#/definitions/Computed'
+ tupleToUserset:
+ $ref: '#/definitions/UsersetTree.TupleToUserset'
+ description: |-
+ A leaf node contains either
+ - a set of users (which may be individual users, or usersets
+ referencing other relations)
+ - a computed node, which is the result of a computed userset
+ value in the authorization model
+ - a tupleToUserset nodes, containing the result of expanding
+ a tupleToUserset value in a authorization model.
+ ListObjectsResponse:
+ type: object
+ properties:
+ objects:
+ type: array
+ example:
+ - document:roadmap
+ - document:planning
+ items:
+ type: string
+ required:
+ - objects
+ ListStoresResponse:
+ type: object
+ properties:
+ stores:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/Store'
+ continuation_token:
+ type: string
+ example: >-
+ eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==
+ description: The continuation token will be empty if there are no more stores.
+ required:
+ - stores
+ - continuation_token
+ ListUsersResponse:
+ type: object
+ properties:
+ users:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/User'
+ required:
+ - users
+ Metadata:
+ type: object
+ properties:
+ relations:
+ type: object
+ additionalProperties:
+ $ref: '#/definitions/RelationMetadata'
+ module:
+ type: string
+ source_info:
+ $ref: '#/definitions/SourceInfo'
+ Node:
+ type: object
+ properties:
+ name:
+ type: string
+ leaf:
+ $ref: '#/definitions/Leaf'
+ difference:
+ $ref: '#/definitions/UsersetTree.Difference'
+ union:
+ $ref: '#/definitions/Nodes'
+ intersection:
+ $ref: '#/definitions/Nodes'
+ required:
+ - name
+ Nodes:
+ type: object
+ properties:
+ nodes:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/Node'
+ required:
+ - nodes
+ NotFoundErrorCode:
+ type: string
+ enum:
+ - no_not_found_error
+ - undefined_endpoint
+ - store_id_not_found
+ - unimplemented
+ default: no_not_found_error
+ NullValue:
+ type: string
+ enum:
+ - NULL_VALUE
+ default: NULL_VALUE
+ description: |-
+ `NullValue` is a singleton enumeration to represent the null value for the
+ `Value` type union.
+
+ The JSON representation for `NullValue` is JSON `null`.
+
+ - NULL_VALUE: Null value.
+ Object:
+ type: object
+ properties:
+ type:
+ type: string
+ example: document
+ id:
+ type: string
+ example: 0bcdf6fa-a6aa-4730-a8eb-9cf172ff16d9
+ description: |-
+ Object represents an OpenFGA Object.
+
+ An Object is composed of a type and identifier (e.g. 'document:1')
+
+ See https://openfga.dev/docs/concepts#what-is-an-object
+ required:
+ - type
+ - id
+ ObjectRelation:
+ type: object
+ properties:
+ object:
+ type: string
+ relation:
+ type: string
+ PathUnknownErrorMessageResponse:
+ type: object
+ example:
+ code: undefined_endpoint
+ message: Endpoint not enabled
+ properties:
+ code:
+ $ref: '#/definitions/NotFoundErrorCode'
+ message:
+ type: string
+ ReadAssertionsResponse:
+ type: object
+ properties:
+ authorization_model_id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ assertions:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/Assertion'
+ required:
+ - authorization_model_id
+ ReadAuthorizationModelResponse:
+ type: object
+ properties:
+ authorization_model:
+ $ref: '#/definitions/AuthorizationModel'
+ ReadAuthorizationModelsResponse:
+ type: object
+ properties:
+ authorization_models:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/AuthorizationModel'
+ continuation_token:
+ type: string
+ example: >-
+ eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==
+ description: The continuation token will be empty if there are no more models.
+ required:
+ - authorization_models
+ ReadChangesResponse:
+ type: object
+ properties:
+ changes:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/TupleChange'
+ continuation_token:
+ type: string
+ example: >-
+ eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==
+ description: The continuation token will be identical if there are no new changes.
+ required:
+ - changes
+ ReadRequestTupleKey:
+ type: object
+ properties:
+ user:
+ type: string
+ example: user:anne
+ maxLength: 512
+ relation:
+ type: string
+ example: reader
+ maxLength: 50
+ object:
+ type: string
+ example: document:2021-budget
+ maxLength: 256
+ ReadResponse:
+ type: object
+ properties:
+ tuples:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/Tuple'
+ continuation_token:
+ type: string
+ example: >-
+ eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==
+ description: The continuation token will be empty if there are no more tuples.
+ required:
+ - tuples
+ - continuation_token
+ RelationMetadata:
+ type: object
+ properties:
+ directly_related_user_types:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/RelationReference'
+ module:
+ type: string
+ source_info:
+ $ref: '#/definitions/SourceInfo'
+ RelationReference:
+ type: object
+ properties:
+ type:
+ type: string
+ example: group
+ relation:
+ type: string
+ example: member
+ wildcard:
+ $ref: '#/definitions/Wildcard'
+ condition:
+ type: string
+ description: The name of a condition that is enforced over the allowed relation.
+ description: >-
+ RelationReference represents a relation of a particular object type (e.g.
+ 'document#viewer').
+ required:
+ - type
+ RelationshipCondition:
+ type: object
+ properties:
+ name:
+ type: string
+ example: condition1
+ description: >-
+ A reference (by name) of the relationship condition defined in the
+ authorization model.
+ maxLength: 256
+ context:
+ type: object
+ description: >-
+ Additional context/data to persist along with the condition.
+
+ The keys must match the parameters defined by the condition, and the
+ value types must
+
+ match the parameter type definitions.
+ required:
+ - name
+ SourceInfo:
+ type: object
+ properties:
+ file:
+ type: string
+ Status:
+ type: object
+ properties:
+ code:
+ type: integer
+ format: int32
+ message:
+ type: string
+ details:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/Any'
+ Store:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ created_at:
+ type: string
+ format: date-time
+ updated_at:
+ type: string
+ format: date-time
+ deleted_at:
+ type: string
+ format: date-time
+ required:
+ - id
+ - name
+ - created_at
+ - updated_at
+ StreamedListObjectsResponse:
+ type: object
+ properties:
+ object:
+ type: string
+ example: document:roadmap
+ description: The response for a StreamedListObjects RPC.
+ required:
+ - object
+ Tuple:
+ type: object
+ properties:
+ key:
+ $ref: '#/definitions/TupleKey'
+ timestamp:
+ type: string
+ format: date-time
+ required:
+ - key
+ - timestamp
+ TupleChange:
+ type: object
+ properties:
+ tuple_key:
+ $ref: '#/definitions/TupleKey'
+ operation:
+ $ref: '#/definitions/TupleOperation'
+ timestamp:
+ type: string
+ format: date-time
+ required:
+ - tuple_key
+ - operation
+ - timestamp
+ TupleKey:
+ type: object
+ properties:
+ user:
+ type: string
+ example: user:anne
+ maxLength: 512
+ relation:
+ type: string
+ example: reader
+ maxLength: 50
+ object:
+ type: string
+ example: document:2021-budget
+ maxLength: 256
+ condition:
+ $ref: '#/definitions/RelationshipCondition'
+ required:
+ - user
+ - relation
+ - object
+ TupleKeyWithoutCondition:
+ type: object
+ properties:
+ user:
+ type: string
+ example: user:anne
+ maxLength: 512
+ relation:
+ type: string
+ example: reader
+ maxLength: 50
+ object:
+ type: string
+ example: document:2021-budget
+ maxLength: 256
+ required:
+ - user
+ - relation
+ - object
+ TupleOperation:
+ type: string
+ enum:
+ - TUPLE_OPERATION_WRITE
+ - TUPLE_OPERATION_DELETE
+ default: TUPLE_OPERATION_WRITE
+ title: buf:lint:ignore ENUM_ZERO_VALUE_SUFFIX
+ TypeDefinition:
+ type: object
+ properties:
+ type:
+ type: string
+ example: document
+ relations:
+ type: object
+ example:
+ reader:
+ union:
+ child:
+ - this: {}
+ - computedUserset:
+ object: ''
+ relation: writer
+ writer:
+ this: {}
+ additionalProperties:
+ $ref: '#/definitions/Userset'
+ metadata:
+ $ref: '#/definitions/Metadata'
+ description: >-
+ A map whose keys are the name of the relation and whose value is the
+ Metadata for that relation.
+
+ It also holds information around the module name and source file if
+ this model was constructed
+
+ from a modular model.
+ required:
+ - type
+ TypeName:
+ type: string
+ enum:
+ - TYPE_NAME_UNSPECIFIED
+ - TYPE_NAME_ANY
+ - TYPE_NAME_BOOL
+ - TYPE_NAME_STRING
+ - TYPE_NAME_INT
+ - TYPE_NAME_UINT
+ - TYPE_NAME_DOUBLE
+ - TYPE_NAME_DURATION
+ - TYPE_NAME_TIMESTAMP
+ - TYPE_NAME_MAP
+ - TYPE_NAME_LIST
+ - TYPE_NAME_IPADDRESS
+ default: TYPE_NAME_UNSPECIFIED
+ TypedWildcard:
+ type: object
+ properties:
+ type:
+ type: string
+ example: employee
+ description: >-
+ Type bound public access.
+
+
+ Normally represented using the `<type>:*` syntax
+
+
+ `employee:*` represents every object of type `employee`, including those
+ not currently present in the system
+
+
+ See https://openfga.dev/docs/concepts#what-is-type-bound-public-access
+ required:
+ - type
+ UnauthenticatedResponse:
+ type: object
+ example:
+ code: unauthenticated
+ message: unauthenticated
+ properties:
+ code:
+ $ref: '#/definitions/ErrorCode'
+ message:
+ type: string
+ UnprocessableContentErrorCode:
+ type: string
+ enum:
+ - no_throttled_error_code
+ - throttled_timeout_error
+ default: no_throttled_error_code
+ UnprocessableContentMessageResponse:
+ type: object
+ example:
+ code: throttled_timeout_error
+ message: timeout due to throttling on complex request
+ properties:
+ code:
+ $ref: '#/definitions/UnprocessableContentErrorCode'
+ message:
+ type: string
+ User:
+ type: object
+ properties:
+ object:
+ $ref: '#/definitions/Object'
+ userset:
+ $ref: '#/definitions/UsersetUser'
+ wildcard:
+ $ref: '#/definitions/TypedWildcard'
+ description: >-
+ User.
+
+
+ Represents any possible value for a user (subject or principal). Can be a:
+
+ - Specific user object e.g.: 'user:will', 'folder:marketing',
+ 'org:contoso', ...)
+
+ - Specific userset (e.g. 'group:engineering#member')
+
+ - Public-typed wildcard (e.g. 'user:*')
+
+
+ See https://openfga.dev/docs/concepts#what-is-a-user
+ UserTypeFilter:
+ type: object
+ properties:
+ type:
+ type: string
+ example: group
+ relation:
+ type: string
+ example: member
+ required:
+ - type
+ Users:
+ type: object
+ properties:
+ users:
+ type: array
+ items:
+ type: string
+ required:
+ - users
+ Userset:
+ type: object
+ properties:
+ this:
+ $ref: '#/definitions/DirectUserset'
+ computedUserset:
+ $ref: '#/definitions/ObjectRelation'
+ tupleToUserset:
+ $ref: '#/definitions/v1.TupleToUserset'
+ union:
+ $ref: '#/definitions/Usersets'
+ intersection:
+ $ref: '#/definitions/Usersets'
+ difference:
+ $ref: '#/definitions/v1.Difference'
+ UsersetTree:
+ type: object
+ properties:
+ root:
+ $ref: '#/definitions/Node'
+ description: A UsersetTree contains the result of an Expansion.
+ UsersetTree.Difference:
+ type: object
+ properties:
+ base:
+ $ref: '#/definitions/Node'
+ subtract:
+ $ref: '#/definitions/Node'
+ required:
+ - base
+ - subtract
+ UsersetTree.TupleToUserset:
+ type: object
+ properties:
+ tupleset:
+ type: string
+ computed:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/Computed'
+ required:
+ - tupleset
+ - computed
+ UsersetUser:
+ type: object
+ properties:
+ type:
+ type: string
+ example: group
+ id:
+ type: string
+ example: fga
+ relation:
+ type: string
+ example: member
+ description: >-
+ Userset.
+
+
+ A set or group of users, represented in the `<type>:<id>#<relation>`
+ format
+
+
+ `group:fga#member` represents all members of group FGA, not to be confused
+ by `group:fga` which represents the group itself as a specific object.
+
+
+ See:
+ https://openfga.dev/docs/modeling/building-blocks/usersets#what-is-a-userset
+ required:
+ - type
+ - id
+ - relation
+ Usersets:
+ type: object
+ properties:
+ child:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/Userset'
+ required:
+ - child
+ ValidationErrorMessageResponse:
+ type: object
+ example:
+ code: validation_error
+ message: Generic validation error
+ properties:
+ code:
+ $ref: '#/definitions/ErrorCode'
+ message:
+ type: string
+ Wildcard:
+ type: object
+ WriteAssertionsResponse:
+ type: object
+ WriteAuthorizationModelResponse:
+ type: object
+ properties:
+ authorization_model_id:
+ type: string
+ example: 01G5JAVJ41T49E9TT3SKVS7X1J
+ required:
+ - authorization_model_id
+ WriteRequestDeletes:
+ type: object
+ properties:
+ tuple_keys:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/TupleKeyWithoutCondition'
+ minItems: 1
+ required:
+ - tuple_keys
+ WriteRequestWrites:
+ type: object
+ properties:
+ tuple_keys:
+ type: array
+ items:
+ type: object
+ $ref: '#/definitions/TupleKey'
+ minItems: 1
+ required:
+ - tuple_keys
+ WriteResponse:
+ type: object
+ v1.Difference:
+ type: object
+ properties:
+ base:
+ $ref: '#/definitions/Userset'
+ subtract:
+ $ref: '#/definitions/Userset'
+ required:
+ - base
+ - subtract
+ v1.TupleToUserset:
+ type: object
+ properties:
+ tupleset:
+ $ref: '#/definitions/ObjectRelation'
+ title: The target object/relation
+ computedUserset:
+ $ref: '#/definitions/ObjectRelation'
+ required:
+ - tupleset
+ - computedUserset
diff --git a/ext/openfga/client-openfga/src/test/java/org/apache/syncope/ext/openfga/client/OpenFGAClientTest.java b/ext/openfga/client-openfga/src/test/java/org/apache/syncope/ext/openfga/client/OpenFGAClientTest.java
new file mode 100644
index 0000000000..8300f86cb4
--- /dev/null
+++ b/ext/openfga/client-openfga/src/test/java/org/apache/syncope/ext/openfga/client/OpenFGAClientTest.java
@@ -0,0 +1,258 @@
+/*
+ * 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.syncope.ext.openfga.client;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testcontainers.shaded.org.awaitility.Awaitility.await;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import org.apache.syncope.common.lib.SyncopeConstants;
+import org.apache.syncope.common.lib.types.AnyTypeKind;
+import org.apache.syncope.core.persistence.api.entity.AnyType;
+import org.apache.syncope.core.persistence.api.entity.Entity;
+import org.apache.syncope.core.persistence.api.entity.RelationshipType;
+import org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject;
+import org.apache.syncope.core.persistence.api.entity.group.GRelationship;
+import org.apache.syncope.core.persistence.api.entity.group.Group;
+import org.apache.syncope.core.provisioning.api.event.EntityLifecycleEvent;
+import org.apache.syncope.ext.openfga.client.model.AuthorizationModel;
+import org.apache.syncope.ext.openfga.client.model.CheckRequest;
+import org.apache.syncope.ext.openfga.client.model.CheckRequestTupleKey;
+import org.apache.syncope.ext.openfga.client.model.ReadRequest;
+import org.apache.syncope.ext.openfga.client.model.ReadRequestTupleKey;
+import org.apache.syncope.ext.openfga.client.model.Tuple;
+import org.identityconnectors.framework.common.objects.SyncDeltaType;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
+import org.testcontainers.openfga.OpenFGAContainer;
+
+@SpringJUnitConfig(classes = OpenFGAClientTestContext.class)
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class OpenFGAClientTest {
+
+ static final OpenFGAContainer OPENFGA_CONTAINER = new OpenFGAContainer("openfga/openfga:v1");
+
+ static {
+ OPENFGA_CONTAINER.start();
+ }
+
+ @DynamicPropertySource
+ static void configureProperties(final DynamicPropertyRegistry registry) {
+ registry.add("OPENFGA_API_URL", () -> OPENFGA_CONTAINER.getHttpEndpoint());
+ }
+
+ protected static AnyType mockAnyType() {
+ AnyType anyType = mock(AnyType.class);
+ when(anyType.getKind()).thenReturn(AnyTypeKind.ANY_OBJECT);
+ when(anyType.getKey()).thenReturn(OpenFGAClientTestContext.NEW_TYPE_KEY);
+ return anyType;
+ }
+
+ protected static EntityLifecycleEvent<Entity> mockNewAnyTypeEvent() {
+ @SuppressWarnings("unchecked")
+ EntityLifecycleEvent<Entity> event = mock(EntityLifecycleEvent.class);
+ when(event.getEntity()).thenAnswer(ic -> mockAnyType());
+ when(event.getDomain()).thenReturn(SyncopeConstants.MASTER_DOMAIN);
+ when(event.getType()).thenReturn(SyncDeltaType.CREATE);
+ return event;
+ }
+
+ protected static RelationshipType mockRelationshipType() {
+ RelationshipType relType = mock(RelationshipType.class);
+ when(relType.getKey()).thenReturn("newrelationship");
+
+ when(relType.getLeftEndAnyType()).thenAnswer(ic -> {
+ AnyType anyType = mock(AnyType.class);
+ when(anyType.getKind()).thenReturn(AnyTypeKind.GROUP);
+ when(anyType.getKey()).thenReturn(AnyTypeKind.GROUP.name());
+ return anyType;
+ });
+
+ when(relType.getRightEndAnyType()).thenAnswer(ic -> mockAnyType());
+
+ return relType;
+ }
+
+ protected static EntityLifecycleEvent<Entity> mockNewRelationshipTypeEvent() {
+ @SuppressWarnings("unchecked")
+ EntityLifecycleEvent<Entity> event = mock(EntityLifecycleEvent.class);
+ when(event.getEntity()).thenAnswer(ic -> mockRelationshipType());
+ when(event.getDomain()).thenReturn(SyncopeConstants.MASTER_DOMAIN);
+ when(event.getType()).thenReturn(SyncDeltaType.CREATE);
+ return event;
+ }
+
+ @Autowired
+ private OpenFGAClientFactory clientFactory;
+
+ @Autowired
+ private OpenFGAStoreManager storeManager;
+
+ @Test
+ @Order(1)
+ void predefined() throws Exception {
+ OpenFGAClient client = clientFactory.get(SyncopeConstants.MASTER_DOMAIN);
+
+ String store = client.getStore().getName();
+ assertEquals(SyncopeConstants.MASTER_DOMAIN, store);
+
+ AuthorizationModel authorizationModel = client.readLatestAuthorizationModel();
+ assertNotNull(authorizationModel.getId());
+ assertEquals(2, authorizationModel.getTypeDefinitions().size());
+ }
+
+ @Test
+ @Order(2)
+ void anyTypeCRUD() throws Exception {
+ EntityLifecycleEvent<Entity> event = mockNewAnyTypeEvent();
+
+ storeManager.entity(event);
+
+ await().atMost(Duration.ofSeconds(5L)).pollInterval(Duration.ofSeconds(1L)).until(() -> {
+ AuthorizationModel authorizationModel = clientFactory.get(SyncopeConstants.MASTER_DOMAIN).
+ readLatestAuthorizationModel();
+ return authorizationModel.getTypeDefinitions().size() == 3;
+ });
+
+ when(event.getType()).thenReturn(SyncDeltaType.DELETE);
+
+ storeManager.entity(event);
+
+ await().atMost(Duration.ofSeconds(5L)).pollInterval(Duration.ofSeconds(1L)).until(() -> {
+ AuthorizationModel authorizationModel = clientFactory.get(SyncopeConstants.MASTER_DOMAIN).
+ readLatestAuthorizationModel();
+ return authorizationModel.getTypeDefinitions().size() == 2;
+ });
+ }
+
+ @Test
+ @Order(3)
+ void relationshipTypeCRUD() throws IOException {
+ storeManager.entity(mockNewAnyTypeEvent());
+
+ EntityLifecycleEvent<Entity> event = mockNewRelationshipTypeEvent();
+
+ storeManager.entity(event);
+
+ await().atMost(Duration.ofSeconds(5L)).pollInterval(Duration.ofSeconds(1L)).until(() -> {
+ AuthorizationModel authorizationModel = clientFactory.get(SyncopeConstants.MASTER_DOMAIN).
+ readLatestAuthorizationModel();
+
+ return authorizationModel.getTypeDefinitions().stream().
+ anyMatch(type -> OpenFGAClientTestContext.NEW_TYPE_KEY.equals(type.getType())
+ && !type.getRelations().isEmpty());
+ });
+
+ when(event.getType()).thenReturn(SyncDeltaType.DELETE);
+
+ storeManager.entity(event);
+
+ await().atMost(Duration.ofSeconds(5L)).pollInterval(Duration.ofSeconds(1L)).until(() -> {
+ AuthorizationModel authorizationModel = clientFactory.get(SyncopeConstants.MASTER_DOMAIN).
+ readLatestAuthorizationModel();
+
+ return authorizationModel.getTypeDefinitions().stream().
+ anyMatch(type -> OpenFGAClientTestContext.NEW_TYPE_KEY.equals(type.getType())
+ && type.getRelations().isEmpty());
+ });
+ }
+
+ @Test
+ @Order(4)
+ void relatable() throws Exception {
+ storeManager.entity(mockNewAnyTypeEvent());
+
+ storeManager.entity(mockNewRelationshipTypeEvent());
+
+ @SuppressWarnings("unchecked")
+ EntityLifecycleEvent<Entity> event = mock(EntityLifecycleEvent.class);
+ when(event.getEntity()).thenAnswer(ic -> {
+ AnyObject anyObject = mock(AnyObject.class);
+ when(anyObject.getType()).thenAnswer(ic2 -> {
+ AnyType anyType = mock(AnyType.class);
+ when(anyType.getKey()).thenReturn(OpenFGAClientTestContext.NEW_TYPE_KEY);
+ return anyType;
+ });
+ when(anyObject.getKey()).thenReturn("anyObjectKey");
+
+ Group group = mock(Group.class);
+ when(group.getType()).thenAnswer(ic2 -> {
+ AnyType anyType = mock(AnyType.class);
+ when(anyType.getKey()).thenReturn(AnyTypeKind.GROUP.name());
+ return anyType;
+ });
+ when(group.getName()).thenReturn("groupKey");
+ when(group.getRelationships()).thenAnswer(ic2 -> {
+ GRelationship relationship = mock(GRelationship.class);
+ when(relationship.getKey()).thenReturn("newrelationship");
+ when(relationship.getRightEnd()).thenReturn(anyObject);
+ when(relationship.getType()).thenAnswer(ic3 -> mockRelationshipType());
+
+ return List.of(relationship);
+ });
+
+ return group;
+ });
+ when(event.getDomain()).thenReturn(SyncopeConstants.MASTER_DOMAIN);
+ when(event.getType()).thenReturn(SyncDeltaType.CREATE);
+
+ storeManager.entity(event);
+
+ OpenFGAClient client = clientFactory.get(SyncopeConstants.MASTER_DOMAIN);
+
+ // the tuple was created
+ List<Tuple> tuples = await().atMost(Duration.ofSeconds(5L)).pollInterval(Duration.ofSeconds(1L)).
+ until(() -> {
+ ReadRequest request = new ReadRequest();
+ request.setTupleKey(new ReadRequestTupleKey().
+ user("GROUP:groupKey").
+ _object(OpenFGAClientTestContext.NEW_TYPE_KEY + ":"));
+ try {
+ return client.read(request).getTuples();
+ } catch (Exception e) {
+ return List.<Tuple>of();
+ }
+ }, list -> !list.isEmpty());
+
+ assertEquals(1, tuples.size());
+ assertEquals("GROUP:groupKey", tuples.get(0).getKey().getUser());
+ assertEquals("newrelationship", tuples.get(0).getKey().getRelation());
+ assertEquals("NEWTYPE:anyObjectKey", tuples.get(0).getKey().getObject());
+ assertNull(tuples.get(0).getKey().getCondition());
+
+ // check is succssful
+ assertTrue(client.check(new CheckRequest().tupleKey(new CheckRequestTupleKey().
+ user(tuples.get(0).getKey().getUser()).
+ relation(tuples.get(0).getKey().getRelation()).
+ _object(tuples.get(0).getKey().getObject()))).getAllowed());
+ }
+}
diff --git a/ext/openfga/client-openfga/src/test/java/org/apache/syncope/ext/openfga/client/OpenFGAClientTestContext.java b/ext/openfga/client-openfga/src/test/java/org/apache/syncope/ext/openfga/client/OpenFGAClientTestContext.java
new file mode 100644
index 0000000000..63695e604e
--- /dev/null
+++ b/ext/openfga/client-openfga/src/test/java/org/apache/syncope/ext/openfga/client/OpenFGAClientTestContext.java
@@ -0,0 +1,66 @@
+/*
+ * 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.syncope.ext.openfga.client;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.syncope.common.lib.SyncopeConstants;
+import org.apache.syncope.core.persistence.api.DomainHolder;
+import org.apache.syncope.core.persistence.api.dao.RelationshipTypeDAO;
+import org.apache.syncope.core.persistence.api.entity.AnyType;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.PropertySource;
+
+@PropertySource("classpath:core-test.properties")
+@Import(OpenFGAClientContext.class)
+@Configuration(proxyBeanMethods = false)
+public class OpenFGAClientTestContext {
+
+ public static final String NEW_TYPE_KEY = "NEWTYPE";
+
+ @Bean
+ public DomainHolder<?> domainHolder() {
+ return new DomainHolder<Object>() {
+
+ @Override
+ public Map<String, Object> getDomains() {
+ return Map.of(SyncopeConstants.MASTER_DOMAIN, new Object());
+ }
+
+ @Override
+ public Map<String, Boolean> getHealthInfo() {
+ return Map.of(SyncopeConstants.MASTER_DOMAIN, true);
+ }
+ };
+ }
+
+ @Bean
+ public RelationshipTypeDAO relationshipTypeDAO() {
+ RelationshipTypeDAO relationshipTypeDAO = mock(RelationshipTypeDAO.class);
+ when(relationshipTypeDAO.findByLeftEndAnyType(any(AnyType.class))).
+ thenAnswer(ic -> List.of(OpenFGAClientTest.mockRelationshipType()));
+ return relationshipTypeDAO;
+ }
+}
diff --git a/ext/openfga/client-openfga/src/test/resources/core-test.properties b/ext/openfga/client-openfga/src/test/resources/core-test.properties
new file mode 100644
index 0000000000..8bf29c30aa
--- /dev/null
+++ b/ext/openfga/client-openfga/src/test/resources/core-test.properties
@@ -0,0 +1,18 @@
+# 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.
+
+openfga.api-url=${OPENFGA_API_URL}
diff --git a/ext/openfga/client-openfga/src/test/resources/simplelogger.properties b/ext/openfga/client-openfga/src/test/resources/simplelogger.properties
new file mode 100644
index 0000000000..82ce05c41d
--- /dev/null
+++ b/ext/openfga/client-openfga/src/test/resources/simplelogger.properties
@@ -0,0 +1,24 @@
+# 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.
+
+# See http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html
+# Possible values: "trace", "debug", "info", "warn", or "error"
+org.slf4j.simpleLogger.showDateTime=true
+org.slf4j.simpleLogger.dateTimeFormat=YYYY-mm-dd HH:mm:ss.SSS
+org.slf4j.simpleLogger.defaultLogLevel=debug
+org.slf4j.simpleLogger.log.com.github.dockerjava.zerodep.shaded=error
+org.slf4j.simpleLogger.log.org.testcontainers=error
diff --git a/ext/openfga/pom.xml b/ext/openfga/pom.xml
new file mode 100644
index 0000000000..f750e08e57
--- /dev/null
+++ b/ext/openfga/pom.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.syncope</groupId>
+ <artifactId>syncope-ext</artifactId>
+ <version>4.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Apache Syncope Ext: OpenFGA</name>
+ <description>Apache Syncope Ext: OpenFGA</description>
+ <groupId>org.apache.syncope.ext</groupId>
+ <artifactId>syncope-ext-openfga</artifactId>
+ <packaging>pom</packaging>
+
+ <properties>
+ <rootpom.basedir>${basedir}/../..</rootpom.basedir>
+ </properties>
+
+ <modules>
+ <module>client-openfga</module>
+ <module>provisioning-java</module>
+ </modules>
+
+</project>
diff --git a/ext/openfga/provisioning-java/pom.xml b/ext/openfga/provisioning-java/pom.xml
new file mode 100644
index 0000000000..97dda27511
--- /dev/null
+++ b/ext/openfga/provisioning-java/pom.xml
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.syncope.ext</groupId>
+ <artifactId>syncope-ext-openfga</artifactId>
+ <version>4.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Apache Syncope Ext: OpenFGA Provisioning Java</name>
+ <description>Apache Syncope Ext: OpenFGA Provisioning Java</description>
+ <groupId>org.apache.syncope.ext.openfga</groupId>
+ <artifactId>syncope-ext-openfga-provisioning-java</artifactId>
+ <packaging>jar</packaging>
+
+ <properties>
+ <rootpom.basedir>${basedir}/../../..</rootpom.basedir>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.syncope.core</groupId>
+ <artifactId>syncope-core-provisioning-java</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.syncope.ext.openfga</groupId>
+ <artifactId>syncope-ext-openfga-client</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/ext/openfga/provisioning-java/src/main/java/org/apache/syncope/core/provisioning/java/job/OpenFGAReinit.java b/ext/openfga/provisioning-java/src/main/java/org/apache/syncope/core/provisioning/java/job/OpenFGAReinit.java
new file mode 100644
index 0000000000..c8f890cc93
--- /dev/null
+++ b/ext/openfga/provisioning-java/src/main/java/org/apache/syncope/core/provisioning/java/job/OpenFGAReinit.java
@@ -0,0 +1,142 @@
+/*
+ * 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.syncope.core.provisioning.java.job;
+
+import java.util.List;
+import org.apache.syncope.common.lib.types.AnyTypeKind;
+import org.apache.syncope.core.persistence.api.dao.AnyDAO;
+import org.apache.syncope.core.persistence.api.dao.AnyObjectDAO;
+import org.apache.syncope.core.persistence.api.dao.AnyTypeDAO;
+import org.apache.syncope.core.persistence.api.dao.DAO;
+import org.apache.syncope.core.persistence.api.dao.GroupDAO;
+import org.apache.syncope.core.persistence.api.dao.RelationshipTypeDAO;
+import org.apache.syncope.core.persistence.api.dao.UserDAO;
+import org.apache.syncope.core.persistence.api.entity.AnyType;
+import org.apache.syncope.core.persistence.api.entity.RelationshipType;
+import org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject;
+import org.apache.syncope.core.persistence.api.entity.group.Group;
+import org.apache.syncope.core.persistence.api.entity.task.SchedTask;
+import org.apache.syncope.core.persistence.api.entity.task.TaskExec;
+import org.apache.syncope.core.persistence.api.entity.user.User;
+import org.apache.syncope.core.provisioning.api.job.JobExecutionContext;
+import org.apache.syncope.core.provisioning.api.job.JobExecutionException;
+import org.apache.syncope.core.spring.security.AuthContextUtils;
+import org.apache.syncope.ext.openfga.client.OpenFGAClient;
+import org.apache.syncope.ext.openfga.client.OpenFGAClientFactory;
+import org.apache.syncope.ext.openfga.client.OpenFGAStoreManager;
+import org.identityconnectors.framework.common.objects.SyncDeltaType;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+
+/**
+ * Replace the authorization model and creates new tuples with information from existing
+ * any types, relationship types, users, groups and any objects.
+ */
+public class OpenFGAReinit extends AbstractSchedTaskJobDelegate<SchedTask> {
+
+ @Autowired
+ protected OpenFGAStoreManager storeManager;
+
+ @Autowired
+ protected OpenFGAClientFactory clientFactory;
+
+ @Autowired
+ protected AnyTypeDAO anyTypeDAO;
+
+ @Autowired
+ protected RelationshipTypeDAO relationshipTypeDAO;
+
+ @Autowired
+ protected UserDAO userDAO;
+
+ @Autowired
+ protected GroupDAO groupDAO;
+
+ @Autowired
+ protected AnyObjectDAO anyObjectDAO;
+
+ @Override
+ protected String doExecute(final JobExecutionContext context) throws JobExecutionException {
+ if (!context.isDryRun()) {
+ setStatus("Start rebuilding OpenFGA authorization model and tuples");
+
+ try {
+ OpenFGAClient client = clientFactory.get(AuthContextUtils.getDomain());
+
+ // replace the current authorization model
+ clientFactory.initAuthorizationModel(client, AuthContextUtils.getDomain(), true);
+
+ List<? extends AnyType> anyTypes = anyTypeDAO.findAll().stream().
+ filter(anyType -> anyType.getKind() == AnyTypeKind.ANY_OBJECT).toList();
+ for (AnyType anyType : anyTypes) {
+ storeManager.handle(client, SyncDeltaType.CREATE, anyType);
+ }
+
+ List<? extends RelationshipType> relationshipTypes = relationshipTypeDAO.findAll();
+ for (RelationshipType relationshipType : relationshipTypes) {
+ storeManager.handle(client, SyncDeltaType.CREATE, relationshipType);
+ }
+
+ // replace tuples
+ long users = userDAO.count();
+ for (int page = 0; page <= (users / AnyDAO.DEFAULT_PAGE_SIZE); page++) {
+ Pageable pageable = PageRequest.of(page, AnyDAO.DEFAULT_PAGE_SIZE, DAO.DEFAULT_SORT);
+ for (User user : userDAO.findAll(pageable)) {
+ storeManager.handle(client, SyncDeltaType.CREATE, user);
+ }
+ }
+
+ long groups = groupDAO.count();
+ for (int page = 0; page <= (groups / AnyDAO.DEFAULT_PAGE_SIZE); page++) {
+ Pageable pageable = PageRequest.of(page, AnyDAO.DEFAULT_PAGE_SIZE, DAO.DEFAULT_SORT);
+ for (Group group : groupDAO.findAll(pageable)) {
+ storeManager.handle(client, SyncDeltaType.CREATE, group);
+ }
+ }
+
+ long anyObjects = anyObjectDAO.count();
+ for (int page = 0; page <= (anyObjects / AnyDAO.DEFAULT_PAGE_SIZE); page++) {
+ Pageable pageable = PageRequest.of(page, AnyDAO.DEFAULT_PAGE_SIZE, DAO.DEFAULT_SORT);
+ for (AnyObject anyObject : anyObjectDAO.findAll(pageable)) {
+ storeManager.handle(client, SyncDeltaType.CREATE, anyObject);
+ }
+ }
+
+ setStatus("Rebuild for domain " + AuthContextUtils.getDomain() + " successfully completed");
+
+ return "Authorization model replaced with USER, GROUP, " + anyTypes.size() + " AnyTypes, Memberships "
+ + "and " + relationshipTypes.size() + " RelationshipTypes\n"
+ + "Tuples:\n"
+ + " * " + users + " Users\n"
+ + " * " + groups + " Groups\n"
+ + " * " + anyObjects + " AnyObjects";
+ } catch (Exception e) {
+ throw new JobExecutionException("While rebuilding for domain " + AuthContextUtils.getDomain(), e);
+ }
+ }
+
+ return "SUCCESS";
+ }
+
+ @Override
+ protected boolean hasToBeRegistered(final TaskExec<?> execution) {
+ return true;
+ }
+}
diff --git a/ext/pom.xml b/ext/pom.xml
index b8c3b1e9c6..f32d5ac6c8 100644
--- a/ext/pom.xml
+++ b/ext/pom.xml
@@ -83,6 +83,7 @@ under the License.
<module>elasticsearch</module>
<module>opensearch</module>
<module>scimv2</module>
+ <module>openfga</module>
</modules>
</project>
diff --git a/fit/core-reference/pom.xml b/fit/core-reference/pom.xml
index b15e9d8e66..d5d8d413f5 100644
--- a/fit/core-reference/pom.xml
+++ b/fit/core-reference/pom.xml
@@ -1501,8 +1501,14 @@ under the License.
<artifactId>syncope-ext-scimv2-scim-rest-cxf</artifactId>
<version>${project.version}</version>
</dependency>
+
+ <dependency>
+ <groupId>org.apache.syncope.ext.openfga</groupId>
+ <artifactId>syncope-ext-openfga-provisioning-java</artifactId>
+ <version>${project.version}</version>
+ </dependency>
</dependencies>
-
+
<build>
<plugins>
<!-- Adds Flowable custom classes -->
diff --git a/fit/core-reference/src/main/java/org/apache/syncope/fit/core/reference/ITImplementationLookup.java b/fit/core-reference/src/main/java/org/apache/syncope/fit/core/reference/ITImplementationLookup.java
index a091e1b995..5d03ef94e4 100644
--- a/fit/core-reference/src/main/java/org/apache/syncope/fit/core/reference/ITImplementationLookup.java
+++ b/fit/core-reference/src/main/java/org/apache/syncope/fit/core/reference/ITImplementationLookup.java
@@ -141,6 +141,7 @@ public class ITImplementationLookup implements ImplementationLookup {
classNames.add(LiveSyncJobDelegate.class.getName());
classNames.add(PullJobDelegate.class.getName());
classNames.add(PushJobDelegate.class.getName());
+ classNames.add(PushJobDelegate.class.getName());
put(IdRepoImplementationType.TASKJOB_DELEGATE, classNames);
classNames = new HashSet<>();
diff --git a/fit/wa-reference/pom.xml b/fit/wa-reference/pom.xml
index a52f6a39dd..6173c96502 100644
--- a/fit/wa-reference/pom.xml
+++ b/fit/wa-reference/pom.xml
@@ -173,7 +173,6 @@ under the License.
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<configuration>
- <skip>${skipTests}</skip>
<images>
<image>
<name>kennethreitz/httpbin</name>
@@ -183,23 +182,36 @@ under the License.
</ports>
</run>
</image>
+ <image>
+ <alias>openfga</alias>
+ <name>openfga/openfga:${docker.openfga.version}</name>
+ <run>
+ <cmd>run</cmd>
+ </run>
+ </image>
</images>
</configuration>
<executions>
<execution>
- <id>start-httpbin</id>
+ <id>start-docker-images</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
+ <configuration>
+ <skip>${skipTests}</skip>
+ </configuration>
</execution>
<execution>
- <id>stop-httpbin</id>
+ <id>stop-docker-images</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
<goal>remove</goal>
</goals>
+ <configuration>
+ <skip>${skipTests}</skip>
+ </configuration>
</execution>
</executions>
</plugin>
@@ -236,6 +248,7 @@ under the License.
<properties>
<cargo.jvmargs>
-Dspring.profiles.active=embedded,https,all
+ -Dopenfga.api-url=http://${docker.container.openfga.ip}:8080
-Xmx1024m -Xms512m</cargo.jvmargs>
<cargo.servlet.port>9443</cargo.servlet.port>
@@ -395,8 +408,8 @@ under the License.
</properties>
<build>
- <defaultGoal>clean verify cargo:run</defaultGoal>
-
+ <defaultGoal>clean verify io.fabric8:docker-maven-plugin:start cargo:run</defaultGoal>
+
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
@@ -407,6 +420,7 @@ under the License.
<properties>
<cargo.jvmargs>
-Dspring.profiles.active=embedded,https,all
+ -Dopenfga.api-url=http://${docker.container.openfga.ip}:8080
-Dwicket.core.settings.general.configuration-type=development
-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
-XX:+UseG1GC -Xmx1024m -Xms512m</cargo.jvmargs>
diff --git a/fit/wa-reference/src/test/java/org/apache/syncope/fit/AbstractITCase.java b/fit/wa-reference/src/test/java/org/apache/syncope/fit/AbstractITCase.java
index e0ec2b2f69..aeabf35fda 100644
--- a/fit/wa-reference/src/test/java/org/apache/syncope/fit/AbstractITCase.java
+++ b/fit/wa-reference/src/test/java/org/apache/syncope/fit/AbstractITCase.java
@@ -22,6 +22,7 @@ import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import com.fasterxml.jackson.databind.json.JsonMapper;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import java.io.IOException;
@@ -42,11 +43,13 @@ import org.apache.http.message.BasicNameValuePair;
import org.apache.syncope.client.lib.SyncopeClient;
import org.apache.syncope.client.lib.SyncopeClientFactoryBean;
import org.apache.syncope.common.rest.api.service.ClientAppService;
+import org.apache.syncope.common.rest.api.service.ImplementationService;
import org.apache.syncope.common.rest.api.service.OIDCC4UIProviderService;
import org.apache.syncope.common.rest.api.service.PolicyService;
import org.apache.syncope.common.rest.api.service.SAML2IdPEntityService;
import org.apache.syncope.common.rest.api.service.SAML2SP4UIIdPService;
import org.apache.syncope.common.rest.api.service.SRARouteService;
+import org.apache.syncope.common.rest.api.service.TaskService;
import org.apache.syncope.common.rest.api.service.UserService;
import org.apache.syncope.common.rest.api.service.wa.WAConfigService;
import org.apereo.cas.oidc.OidcConstants;
@@ -61,6 +64,8 @@ public abstract class AbstractITCase {
protected static final Logger LOG = LoggerFactory.getLogger(AbstractITCase.class);
+ protected static final JsonMapper MAPPER = JsonMapper.builder().findAndAddModules().build();
+
protected static final String ADMIN_UNAME = "admin";
protected static final String ADMIN_PWD = "password";
@@ -83,6 +88,10 @@ public abstract class AbstractITCase {
protected static SyncopeClient ADMIN_CLIENT;
+ protected static ImplementationService IMPLEMENTATION_SERVICE;
+
+ protected static TaskService TASK_SERVICE;
+
protected static UserService USER_SERVICE;
protected static PolicyService POLICY_SERVICE;
@@ -102,6 +111,8 @@ public abstract class AbstractITCase {
CLIENT_FACTORY = new SyncopeClientFactoryBean().setAddress(CORE_ADDRESS);
ADMIN_CLIENT = CLIENT_FACTORY.create(ADMIN_UNAME, ADMIN_PWD);
+ IMPLEMENTATION_SERVICE = ADMIN_CLIENT.getService(ImplementationService.class);
+ TASK_SERVICE = ADMIN_CLIENT.getService(TaskService.class);
USER_SERVICE = ADMIN_CLIENT.getService(UserService.class);
POLICY_SERVICE = ADMIN_CLIENT.getService(PolicyService.class);
CLIENT_APP_SERVICE = ADMIN_CLIENT.getService(ClientAppService.class);
diff --git a/fit/wa-reference/src/test/java/org/apache/syncope/fit/sra/AbstractOIDCITCase.java b/fit/wa-reference/src/test/java/org/apache/syncope/fit/sra/AbstractOIDCITCase.java
index c01f6087a0..25d4db6b1a 100644
--- a/fit/wa-reference/src/test/java/org/apache/syncope/fit/sra/AbstractOIDCITCase.java
+++ b/fit/wa-reference/src/test/java/org/apache/syncope/fit/sra/AbstractOIDCITCase.java
@@ -105,7 +105,7 @@ abstract class AbstractOIDCITCase extends AbstractSRAITCase {
Response response = POLICY_SERVICE.create(PolicyType.ATTR_RELEASE, policy);
if (response.getStatusInfo().getStatusCode() != Response.Status.CREATED.getStatusCode()) {
- fail("Could not create Test Attr Release Policy");
+ fail("Could not create " + description);
}
return POLICY_SERVICE.read(
diff --git a/fit/wa-reference/src/test/java/org/apache/syncope/fit/sra/AbstractSRAITCase.java b/fit/wa-reference/src/test/java/org/apache/syncope/fit/sra/AbstractSRAITCase.java
index bb7c74c6e4..814aa97efd 100644
--- a/fit/wa-reference/src/test/java/org/apache/syncope/fit/sra/AbstractSRAITCase.java
+++ b/fit/wa-reference/src/test/java/org/apache/syncope/fit/sra/AbstractSRAITCase.java
@@ -28,7 +28,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.ws.rs.core.HttpHeaders;
@@ -65,8 +64,6 @@ import org.junit.jupiter.api.BeforeAll;
abstract class AbstractSRAITCase extends AbstractITCase {
- protected static final JsonMapper MAPPER = JsonMapper.builder().findAndAddModules().build();
-
protected static final String SRA_ADDRESS = "http://127.0.0.1:8080";
protected static final String QUERY_STRING =
@@ -232,7 +229,7 @@ abstract class AbstractSRAITCase extends AbstractITCase {
Response response = POLICY_SERVICE.create(PolicyType.AUTH, policy);
if (response.getStatusInfo().getStatusCode() != Response.Status.CREATED.getStatusCode()) {
- fail("Could not create Syncope Auth Policy");
+ fail("Could not create " + description);
}
return POLICY_SERVICE.read(PolicyType.AUTH, response.getHeaderString(RESTHeaders.RESOURCE_KEY));
diff --git a/fit/wa-reference/src/test/java/org/apache/syncope/fit/ui/OIDCC4UIITCase.java b/fit/wa-reference/src/test/java/org/apache/syncope/fit/ui/OIDCC4UIITCase.java
index e5d4158dc8..841804acb1 100644
--- a/fit/wa-reference/src/test/java/org/apache/syncope/fit/ui/OIDCC4UIITCase.java
+++ b/fit/wa-reference/src/test/java/org/apache/syncope/fit/ui/OIDCC4UIITCase.java
@@ -123,7 +123,7 @@ public class OIDCC4UIITCase extends AbstractUIITCase {
WA_CONFIG_SERVICE.pushToWA(WAConfigService.PushSubject.clientApps, List.of());
}
- private static String getAppName(final String address) {
+ protected static String getAppName(final String address) {
return CONSOLE_ADDRESS.equals(address)
? OIDCC4UIITCase.class.getName() + "_Console"
: OIDCC4UIITCase.class.getName() + "_Enduser";
diff --git a/fit/wa-reference/src/test/java/org/apache/syncope/fit/ui/OpenFGAUIITCase.java b/fit/wa-reference/src/test/java/org/apache/syncope/fit/ui/OpenFGAUIITCase.java
new file mode 100644
index 0000000000..c32fb432c8
--- /dev/null
+++ b/fit/wa-reference/src/test/java/org/apache/syncope/fit/ui/OpenFGAUIITCase.java
@@ -0,0 +1,157 @@
+/*
+ * 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.syncope.fit.ui;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import jakarta.ws.rs.core.Response;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.syncope.common.lib.SyncopeClientException;
+import org.apache.syncope.common.lib.SyncopeConstants;
+import org.apache.syncope.common.lib.policy.AccessPolicyTO;
+import org.apache.syncope.common.lib.policy.OpenFGAAccessPolicyConf;
+import org.apache.syncope.common.lib.to.ClientAppTO;
+import org.apache.syncope.common.lib.to.ImplementationTO;
+import org.apache.syncope.common.lib.to.SchedTaskTO;
+import org.apache.syncope.common.lib.types.ClientAppType;
+import org.apache.syncope.common.lib.types.IdRepoImplementationType;
+import org.apache.syncope.common.lib.types.ImplementationEngine;
+import org.apache.syncope.common.lib.types.PolicyType;
+import org.apache.syncope.common.lib.types.TaskType;
+import org.apache.syncope.common.rest.api.RESTHeaders;
+import org.apache.syncope.common.rest.api.beans.ExecSpecs;
+import org.apache.syncope.common.rest.api.service.wa.WAConfigService;
+import org.junit.jupiter.api.BeforeAll;
+
+public class OpenFGAUIITCase extends OIDCC4UIITCase {
+
+ private static final String OPENFGA_REINIT = "org.apache.syncope.core.provisioning.java.job.OpenFGAReinit";
+
+ @BeforeAll
+ public static void initOpenFga() {
+ ImplementationTO delegate = null;
+ try {
+ delegate = IMPLEMENTATION_SERVICE.read(IdRepoImplementationType.TASKJOB_DELEGATE, OPENFGA_REINIT);
+ } catch (SyncopeClientException e) {
+ if (e.getType().getResponseStatus() == Response.Status.NOT_FOUND) {
+ delegate = new ImplementationTO();
+ delegate.setKey(OPENFGA_REINIT);
+ delegate.setEngine(ImplementationEngine.JAVA);
+ delegate.setType(IdRepoImplementationType.TASKJOB_DELEGATE);
+ delegate.setBody(OPENFGA_REINIT);
+ Response response = IMPLEMENTATION_SERVICE.create(delegate);
+ delegate = IMPLEMENTATION_SERVICE.read(
+ delegate.getType(), response.getHeaderString(RESTHeaders.RESOURCE_KEY));
+ assertNotNull(delegate);
+ }
+ }
+ assertNotNull(delegate);
+
+ String taskKey = null;
+ try {
+ SchedTaskTO schedTask = new SchedTaskTO();
+ schedTask.setJobDelegate(delegate.getKey());
+ schedTask.setName(OPENFGA_REINIT);
+ Response response = TASK_SERVICE.create(TaskType.SCHEDULED, schedTask);
+ taskKey = response.getHeaderString(RESTHeaders.RESOURCE_KEY);
+ } catch (SyncopeClientException e) {
+ // ignore
+ }
+
+ if (taskKey == null) {
+ return;
+ }
+
+ ExecSpecs execSpecs = new ExecSpecs.Builder().key(taskKey).build();
+ TASK_SERVICE.execute(execSpecs);
+
+ await().atMost(30, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> {
+ try {
+ return !TASK_SERVICE.read(TaskType.SCHEDULED, execSpecs.getKey(), true).getExecutions().isEmpty();
+ } catch (Exception e) {
+ return false;
+ }
+ });
+ }
+
+ private static AccessPolicyTO getAccessPolicy() throws JsonProcessingException {
+ JsonNode health = MAPPER.readTree(WebClient.create(
+ StringUtils.substringBefore(CORE_ADDRESS, "/rest") + "/actuator/health",
+ ANONYMOUS_USER, ANONYMOUS_KEY, null).
+ get().readEntity(String.class));
+ JsonNode openfga = health.get("components").get("openFga").get("details");
+ String baseUri = openfga.get("baseUri").asText();
+ String storeId = openfga.get(SyncopeConstants.MASTER_DOMAIN).get("storeId").asText();
+
+ String description = "OpenFGA access policy";
+
+ return POLICY_SERVICE.list(PolicyType.ACCESS).stream().
+ map(AccessPolicyTO.class::cast).
+ filter(policy -> description.equals(policy.getName())
+ && policy.getConf() instanceof OpenFGAAccessPolicyConf).
+ findFirst().
+ orElseGet(() -> {
+ OpenFGAAccessPolicyConf policyConf = new OpenFGAAccessPolicyConf();
+ policyConf.setApiUrl(baseUri);
+ policyConf.setStoreId(storeId);
+ policyConf.setRelation("member");
+ policyConf.setObject("GROUP:managingDirector");
+
+ AccessPolicyTO policy = new AccessPolicyTO();
+ policy.setName(description);
+ policy.setConf(policyConf);
+
+ Response response = POLICY_SERVICE.create(PolicyType.ACCESS, policy);
+ if (response.getStatusInfo().getStatusCode() != Response.Status.CREATED.getStatusCode()) {
+ fail("Could not create " + description);
+ }
+
+ return POLICY_SERVICE.read(
+ PolicyType.ACCESS,
+ response.getHeaderString(RESTHeaders.RESOURCE_KEY));
+ });
+ }
+
+ @BeforeAll
+ public static void consoleOpenFGASetup() throws JsonProcessingException {
+ ClientAppTO clientApp = CLIENT_APP_SERVICE.list(ClientAppType.OIDCRP).stream().
+ filter(app -> getAppName(CONSOLE_ADDRESS).equals(app.getName())).
+ findFirst().orElseThrow();
+
+ clientApp.setAccessPolicy(getAccessPolicy().getKey());
+
+ CLIENT_APP_SERVICE.update(ClientAppType.OIDCRP, clientApp);
+
+ WA_CONFIG_SERVICE.pushToWA(WAConfigService.PushSubject.clientApps, List.of());
+ }
+
+ @Override
+ public void createUnmatching() throws IOException {
+ assumeFalse(true);
+ }
+}
diff --git a/pom.xml b/pom.xml
index 02b95b32af..eb4e61126e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -432,13 +432,15 @@ under the License.
<opensearch.version>2.19.1</opensearch.version>
<opensearch-java.version>2.21.0</opensearch-java.version>
+ <docker.openfga.version>v1</docker.openfga.version>
+
<commons-lang3.version>3.17.0</commons-lang3.version>
<commons-jexl.version>3.4.0</commons-jexl.version>
<commons-text.version>1.13.0</commons-text.version>
<pac4j.version>6.1.1</pac4j.version>
- <cas.version>7.2.0-RC5</cas.version>
+ <cas.version>7.2.0-SNAPSHOT</cas.version>
<cas-client.version>4.0.4</cas-client.version>
<swagger-core.version>2.2.28</swagger-core.version>
@@ -1612,6 +1614,12 @@ under the License.
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.openapitools</groupId>
+ <artifactId>openapi-generator-maven-plugin</artifactId>
+ <version>7.11.0</version>
+ </plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
diff --git a/src/main/asciidoc/reference-guide/concepts/extensions.adoc b/src/main/asciidoc/reference-guide/concepts/extensions.adoc
index 716fab5812..77c789c34b 100644
--- a/src/main/asciidoc/reference-guide/concepts/extensions.adoc
+++ b/src/main/asciidoc/reference-guide/concepts/extensions.adoc
@@ -170,3 +170,27 @@ https://github.com/apache/syncope/tree/master/ext/scimv2[source tree^]
endif::[]
.
====
+
+==== OpenFGA
+
+This extension provides seamless integration with an https://openfga.dev/[OpenFGA^] server.
+
+When this extension is enabled:
+
+* all <<anytype>> and <<relationshiptype>> instances are transparently mirrored to
+OpenFGA's https://openfga.dev/docs/concepts#what-is-an-authorization-model[authorization model^]
+* all <<users-groups-and-any-objects>> and their <<memberships-relationships>> are transparently mirrored as
+OpenFGA's https://openfga.dev/docs/concepts#what-is-a-relationship-tuple[tuple^] objects
+
+[NOTE]
+.Extension Sources
+====
+The source code of this extension is available from the Apache Syncope
+ifeval::["{snapshotOrRelease}" == "release"]
+https://github.com/apache/syncope/tree/syncope-{docVersion}/ext/openfga[source tree^]
+endif::[]
+ifeval::["{snapshotOrRelease}" == "snapshot"]
+https://github.com/apache/syncope/tree/master/ext/openfga[source tree^]
+endif::[]
+.
+====
diff --git a/src/main/asciidoc/reference-guide/concepts/policies.adoc b/src/main/asciidoc/reference-guide/concepts/policies.adoc
index 576f5ef7ec..ee2d78316c 100644
--- a/src/main/asciidoc/reference-guide/concepts/policies.adoc
+++ b/src/main/asciidoc/reference-guide/concepts/policies.adoc
@@ -296,6 +296,15 @@ https://github.com/apache/syncope/blob/master/common/am/lib/src/main/java/org/ap
endif::[]
| Make access decisions based on HTTP request properties as client IP address and user-agent.
+|
+ifeval::["{snapshotOrRelease}" == "release"]
+https://github.com/apache/syncope/blob/syncope-{docVersion}/common/am/lib/src/main/java/org/apache/syncope/common/lib/policy/OpenFGAAccessPolicyConf.java[OpenFGAAccessPolicyConf^]
+endif::[]
+ifeval::["{snapshotOrRelease}" == "snapshot"]
+https://github.com/apache/syncope/blob/master/common/am/lib/src/main/java/org/apache/syncope/common/lib/policy/OpenFGAAccessPolicyConf.java[OpenFGAAccessPolicyConf^]
+endif::[]
+| Builds an authorization request and submits it to https://openfga.dev/[OpenFGA^]'s `check` API endpoint.
+
|
ifeval::["{snapshotOrRelease}" == "release"]
https://github.com/apache/syncope/blob/syncope-{docVersion}/common/am/lib/src/main/java/org/apache/syncope/common/lib/policy/RemoteEndpointAccessPolicyConf.java[RemoteEndpointAccessPolicyConf^]
diff --git a/src/main/asciidoc/reference-guide/usage/customization.adoc b/src/main/asciidoc/reference-guide/usage/customization.adoc
index 97ee5ed005..9a975dcb9f 100644
--- a/src/main/asciidoc/reference-guide/usage/customization.adoc
+++ b/src/main/asciidoc/reference-guide/usage/customization.adoc
@@ -476,6 +476,60 @@ Add the following dependencies to `core/pom.xml`:
</dependency>
----
+[discrete]
+===== Enable the <<OpenFGA>> extension
+
+Add the following dependency to `core/pom.xml`:
+
+[source,xml,subs="verbatim,attributes"]
+----
+<dependency>
+ <groupId>org.apache.syncope.ext.openfga</groupId>
+ <artifactId>syncope-ext-openfga-provisioning-java</artifactId>
+ <version>${syncope.version}</version>
+</dependency>
+----
+
+Create
+
+[source]
+....
+openfga.api-url=http://localhost:8080
+....
+
+as `core/src/main/resources/core-openfga.properties`. +
+More properties are available, as you can read from
+ifeval::["{snapshotOrRelease}" == "release"]
+https://github.com/apache/syncope/blob/syncope-{docVersion}/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAProperties.java[OpenFGAProperties^]
+endif::[]
+ifeval::["{snapshotOrRelease}" == "snapshot"]
+https://github.com/apache/syncope/blob/master/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAProperties.java[OpenFGAProperties^]
+endif::[]
+.
+
+Do not forget to include `openfga` as
+https://docs.spring.io/spring-boot/3.4/reference/features/profiles.html#features.profiles.adding-active-profiles[Spring Boot profile^]
+for the Core application.
+
+If needed, customize the `@Bean` declarations from
+ifeval::["{snapshotOrRelease}" == "release"]
+https://github.com/apache/syncope/blob/syncope-{docVersion}/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClientContext.java[OpenFGAClientContext^]
+endif::[]
+ifeval::["{snapshotOrRelease}" == "snapshot"]
+https://github.com/apache/syncope/blob/master/ext/openfga/client-openfga/src/main/java/org/apache/syncope/ext/openfga/client/OpenFGAClientContext.java[OpenFGAClientContext^]
+endif::[]
+as explained <<extending-configuration,above>>.
+
+It is also required to initialize the OpenFGA authorization model: add a new Java <<implementations,implementation>> for
+`TASKJOB_DELEGATE` and use `org.apache.syncope.core.provisioning.java.job.OpenFGAReinit` as class. +
+Then, create a new <<tasks-scheduled, scheduled task>>, select the implementation just created as job delegate and execute it.
+
+[TIP]
+The `org.apache.syncope.core.provisioning.java.job.OpenFGAReinit` task created above is not meant for
+scheduled execution; rather, it can be run every time you want to blank and re-create the OpenFGA authorization model
+starting from Syncope's internal storage.
+
+
[discrete]
===== New REST endpoints
Adding a new REST endpoint involves several operations:
diff --git a/wa/bootstrap/src/main/java/org/apache/syncope/wa/bootstrap/mapping/DefaultAttrReleaseMapper.java b/wa/bootstrap/src/main/java/org/apache/syncope/wa/bootstrap/mapping/DefaultAttrReleaseMapper.java
index 07cb261d3e..46d94ac1c3 100644
--- a/wa/bootstrap/src/main/java/org/apache/syncope/wa/bootstrap/mapping/DefaultAttrReleaseMapper.java
+++ b/wa/bootstrap/src/main/java/org/apache/syncope/wa/bootstrap/mapping/DefaultAttrReleaseMapper.java
@@ -126,6 +126,21 @@ public class DefaultAttrReleaseMapper implements AttrReleaseMapper {
return policies;
}
+ protected void setPrincipalAttributesRepository(
+ final DefaultAttrReleasePolicyConf.PrincipalAttrRepoConf parc,
+ final AbstractRegisteredServiceAttributeReleasePolicy policy) {
+
+ AbstractPrincipalAttributesRepository par = parc.getExpiration() > 0
+ ? new CachingPrincipalAttributesRepository(parc.getTimeUnit().name(), parc.getExpiration())
+ : new DefaultPrincipalAttributesRepository();
+
+ par.setMergingStrategy(MergingStrategyTypes.valueOf(parc.getMergingStrategy().name()));
+ par.setIgnoreResolvedAttributes(par.isIgnoreResolvedAttributes());
+ par.setAttributeRepositoryIds(new HashSet<>(parc.getAttrRepos()));
+
+ policy.setPrincipalAttributesRepository(par);
+ }
+
protected Optional<DefaultRegisteredServiceConsentPolicy> buildConsentPolicy(
final AttrReleasePolicyTO policy,
final DefaultAttrReleasePolicyConf conf) {
@@ -188,36 +203,29 @@ public class DefaultAttrReleaseMapper implements AttrReleaseMapper {
Optional<DefaultRegisteredServiceConsentPolicy> consentPolicy = buildConsentPolicy(policy, conf);
if (!chain.getPolicies().isEmpty()) {
+ Optional.ofNullable(conf.getPrincipalAttrRepoConf()).
+ ifPresent(parc -> chain.setMergingPolicy(
+ MergingStrategyTypes.valueOf(parc.getMergingStrategy().name())));
+
chain.getPolicies().stream().
filter(AbstractRegisteredServiceAttributeReleasePolicy.class::isInstance).
map(AbstractRegisteredServiceAttributeReleasePolicy.class::cast).
forEach(p -> {
consentPolicy.ifPresent(p::setConsentPolicy);
Optional.ofNullable(conf.getPrincipalIdAttr()).ifPresent(p::setPrincipalIdAttribute);
- });
- if (conf.getPrincipalAttrRepoConf() != null && !conf.getPrincipalAttrRepoConf().getAttrRepos().isEmpty()) {
- DefaultAttrReleasePolicyConf.PrincipalAttrRepoConf parc = conf.getPrincipalAttrRepoConf();
- chain.setMergingPolicy(MergingStrategyTypes.valueOf(parc.getMergingStrategy().name()));
- }
+ Optional.ofNullable(conf.getPrincipalAttrRepoConf()).
+ filter(parc -> !parc.getAttrRepos().isEmpty()).
+ ifPresent(parc -> setPrincipalAttributesRepository(parc, p));
+ });
}
Optional.ofNullable(single).ifPresent(p -> {
consentPolicy.ifPresent(p::setConsentPolicy);
Optional.ofNullable(conf.getPrincipalIdAttr()).ifPresent(p::setPrincipalIdAttribute);
- if (conf.getPrincipalAttrRepoConf() != null && !conf.getPrincipalAttrRepoConf().getAttrRepos().isEmpty()) {
- DefaultAttrReleasePolicyConf.PrincipalAttrRepoConf parc = conf.getPrincipalAttrRepoConf();
-
- AbstractPrincipalAttributesRepository par = parc.getExpiration() > 0
- ? new CachingPrincipalAttributesRepository(parc.getTimeUnit().name(), parc.getExpiration())
- : new DefaultPrincipalAttributesRepository();
-
- par.setMergingStrategy(MergingStrategyTypes.valueOf(parc.getMergingStrategy().name()));
- par.setIgnoreResolvedAttributes(par.isIgnoreResolvedAttributes());
- par.setAttributeRepositoryIds(new HashSet<>(parc.getAttrRepos()));
-
- p.setPrincipalAttributesRepository(par);
- }
+ Optional.ofNullable(conf.getPrincipalAttrRepoConf()).
+ filter(parc -> !parc.getAttrRepos().isEmpty()).
+ ifPresent(parc -> setPrincipalAttributesRepository(parc, p));
});
return single == null ? chain : single;
diff --git a/wa/starter/src/main/java/org/apache/syncope/wa/starter/config/WAContext.java b/wa/starter/src/main/java/org/apache/syncope/wa/starter/config/WAContext.java
index 885f9944af..e7e831c3e8 100644
--- a/wa/starter/src/main/java/org/apache/syncope/wa/starter/config/WAContext.java
+++ b/wa/starter/src/main/java/org/apache/syncope/wa/starter/config/WAContext.java
@@ -51,6 +51,7 @@ import org.apache.syncope.wa.starter.mapping.DefaultAuthMapper;
import org.apache.syncope.wa.starter.mapping.DefaultTicketExpirationMapper;
import org.apache.syncope.wa.starter.mapping.HttpRequestAccessMapper;
import org.apache.syncope.wa.starter.mapping.OIDCRPClientAppTOMapper;
+import org.apache.syncope.wa.starter.mapping.OpenFGAAccessMapper;
import org.apache.syncope.wa.starter.mapping.RegisteredServiceMapper;
import org.apache.syncope.wa.starter.mapping.RemoteEndpointAccessMapper;
import org.apache.syncope.wa.starter.mapping.SAML2SPClientAppTOMapper;
@@ -158,6 +159,12 @@ public class WAContext {
return new TimeBasedAccessMapper();
}
+ @ConditionalOnMissingBean
+ @Bean
+ public OpenFGAAccessMapper openFGAAccessMapper() {
+ return new OpenFGAAccessMapper();
+ }
+
@ConditionalOnMissingBean
@Bean
public AuthMapper authMapper() {
diff --git a/wa/starter/src/main/java/org/apache/syncope/wa/starter/mapping/OpenFGAAccessMapper.java b/wa/starter/src/main/java/org/apache/syncope/wa/starter/mapping/OpenFGAAccessMapper.java
new file mode 100644
index 0000000000..a47cfe819a
--- /dev/null
+++ b/wa/starter/src/main/java/org/apache/syncope/wa/starter/mapping/OpenFGAAccessMapper.java
@@ -0,0 +1,49 @@
+/*
+ * 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.syncope.wa.starter.mapping;
+
+import org.apache.syncope.common.lib.policy.AccessPolicyConf;
+import org.apache.syncope.common.lib.policy.AccessPolicyTO;
+import org.apache.syncope.common.lib.policy.OpenFGAAccessPolicyConf;
+import org.apereo.cas.services.OpenFGARegisteredServiceAccessStrategy;
+import org.apereo.cas.services.RegisteredServiceAccessStrategy;
+
+public class OpenFGAAccessMapper implements AccessMapper {
+
+ @Override
+ public boolean supports(final AccessPolicyConf conf) {
+ return OpenFGAAccessPolicyConf.class.equals(conf.getClass());
+ }
+
+ @Override
+ public RegisteredServiceAccessStrategy build(final AccessPolicyTO policy) {
+ OpenFGAAccessPolicyConf conf = (OpenFGAAccessPolicyConf) policy.getConf();
+
+ OpenFGARegisteredServiceAccessStrategy accessStrategy = new OpenFGARegisteredServiceAccessStrategy();
+
+ accessStrategy.setApiUrl(conf.getApiUrl());
+ accessStrategy.setToken(conf.getToken());
+ accessStrategy.setStoreId(conf.getStoreId());
+ accessStrategy.setUserType(conf.getUserType());
+ accessStrategy.setRelation(conf.getRelation());
+ accessStrategy.setObject(conf.getObject());
+
+ return accessStrategy;
+ }
+}