diff --git a/CHANGELOG.md b/CHANGELOG.md index 196a8292b20918926df4a66fb1081651f0ede66e..4dafc0aa2ec89300f9e0f94260aa038f20ba319b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,10 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -This is an important security update. - ### Added +* Implementation for the ACM GRPC-API +* Implementation for the EntityACL GRPC-API + ### Changed ### Deprecated @@ -19,6 +20,12 @@ This is an important security update. ### Fixed +* Wrong serialization of date time values in the GRPC-API (resulting in + org.caosdb.server.datatime@12347abcd or similar). +* Missing serialization of file descriptors in the GRPC-API during retrievals. +* [caosdb-server#131](https://gitlab.com/caosdb/caosdb-server/-/issues/131) + Query: AND does not work with sub-properties + ### Security diff --git a/README_SETUP.md b/README_SETUP.md index 5065e3383c4ac2f2d549bfedb15687d0b4124ec0..d46722d26458757a53f081dd1ce9af3db2688283 100644 --- a/README_SETUP.md +++ b/README_SETUP.md @@ -58,12 +58,14 @@ libpam0g-dev`. Then try again. After a fresh clone of the repository, this is what you need to setup the server: -1. Compile the server with `make compile`. This may take a while and there +1. Install the `proto` submodule (and submodules for those extensions you want, see above): + `git submodule update --init caosdb-proto` +2. Compile the server with `make compile`. This may take a while and there needs to be an internet connection as packages are downloaded to be integrated in the java file. 1. It is recommended to run the unit tests with `make test`. It may take a while. -2. Create an SSL certificate somewhere with a `Java Key Store` file. For +3. Create an SSL certificate somewhere with a `Java Key Store` file. For self-signed certificates (not recommended for production use) you can do: - `mkdir certificates; cd certificates` - `keytool -genkey -keyalg RSA -alias selfsigned -keystore caosdb.jks -validity 375 -keysize 2048 -ext san=dns:localhost` @@ -77,11 +79,11 @@ server: Alternatively, you can create a keystore from certificate files that you already have: - `openssl pkcs12 -export -inkey privkey.pem -in fullchain.pem -out all-certs.pkcs12` - `keytool -importkeystore -srckeystore all-certs.pkcs12 -srcstoretype PKCS12 -deststoretype pkcs12 -destkeystore caosdb.jks` -3. Install/configure the MySQL back-end: see the `README_SETUP.md` of the +4. Install/configure the MySQL back-end: see the `README_SETUP.md` of the `caosdb-mysqlbackend` repository -4. Create an authtoken config (e.g. copy `conf/core/authtoken.example.yaml` to +5. Create an authtoken config (e.g. copy `conf/core/authtoken.example.yaml` to `conf/ext/authtoken.yml` and change it) -5. Copy `conf/core/server.conf` to `conf/ext/server.conf` and change it +6. Copy `conf/core/server.conf` to `conf/ext/server.conf` and change it appropriately: * Setup for MySQL back-end: specify the fields `MYSQL_USER_NAME`, `MYSQL_USER_PASSWORD`, @@ -94,7 +96,7 @@ server: `CERTIFICATES_KEY_STORE_PATH`, and `CERTIFICATES_KEY_STORE_PASSWORD`. Make sure that the conf file is not readable by other users because the certificate passwords are stored in plaintext. - - Set the path to the authtoken config (see step 4) + * Set the path to the authtoken config (see step 4) * Set the file system paths: - `FILE_SYSTEM_ROOT`: The root for all the files managed by CaosDB. - `DROP_OFF_BOX`: Files can be put here for insertion into CaosDB. @@ -112,8 +114,8 @@ server: - `INSERT_FILES_IN_DIR_ALLOWED_DIRS`: add mounted filesystems here that shall be accessible by CaosDB * Maybe set another `SESSION_TIMEOUT_MS`. - * See also [CONFIGURATION.rst](src/doc/administration/configuration.rst) -6. Copy `conf/core/usersources.ini.template` to `conf/ext/usersources.ini`. + * See also [CONFIGURATION.rst](src/doc/administration/configuration.rst) +7. Copy `conf/core/usersources.ini.template` to `conf/ext/usersources.ini`. * You can skip this if you do not want to use an external authentication. Local users (CaosDB realm) are always available. * Define the users/groups who you want to include/exclude. @@ -128,7 +130,7 @@ server: Especially that there are no `properties` (aka `keys`) without a `value`. An emtpy value can be represented by `""`. Comments are everything from `#` or `;` to the end of the line. -7. Possibly install the PAM caller in `misc/pam_authentication/` if you have +8. Possibly install the PAM caller in `misc/pam_authentication/` if you have not do so already. See above. Done! diff --git a/caosdb-proto b/caosdb-proto index 533c8e7341d0659e3cc43d834793a7a965703f55..02e56997f29ee3bfc2c079c9776f66659379c58a 160000 --- a/caosdb-proto +++ b/caosdb-proto @@ -1 +1 @@ -Subproject commit 533c8e7341d0659e3cc43d834793a7a965703f55 +Subproject commit 02e56997f29ee3bfc2c079c9776f66659379c58a diff --git a/src/doc/index.rst b/src/doc/index.rst index 4f63fe07f37a4432a442040ff2f614f01c959472..b5ce9f3235277b613b357dca5dfc3334d80aeb3f 100644 --- a/src/doc/index.rst +++ b/src/doc/index.rst @@ -10,6 +10,7 @@ Welcome to caosdb-server's documentation! Getting started <README_SETUP> Concepts <concepts> + tutorials Query Language <CaosDB-Query-Language> administration Development <development/devel> diff --git a/src/doc/tutorials.rst b/src/doc/tutorials.rst new file mode 100644 index 0000000000000000000000000000000000000000..27aacfb3eb9a4f04ab261b12f904e652c4daf3d3 --- /dev/null +++ b/src/doc/tutorials.rst @@ -0,0 +1,10 @@ +Tutorials +============== + +.. toctree:: + :maxdepth: 1 + :glob: + + tutorials/* + + diff --git a/src/doc/tutorials/setup_state_model.py b/src/doc/tutorials/setup_state_model.py new file mode 100755 index 0000000000000000000000000000000000000000..0a1a7daa3b14d7c3e7a5b8eac093857bddfad330 --- /dev/null +++ b/src/doc/tutorials/setup_state_model.py @@ -0,0 +1,379 @@ +#!/usr/bin/env python3 +# encoding: utf-8 +# +# This file is a part of the CaosDB Project. +# +# Copyright (C) 2021 Indiscale GmbH <info@indiscale.com> +# Copyright (C) 2021 Henrik tom Wörden <h.tomwoerden@indiscale.com> +# Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <https://www.gnu.org/licenses/>. +# +""" +This is a utility script to setup a publication process in LinkAhead using +states. + +If you start from scratch you should perform the following actions in that +order: + +1. setup_roles +2. setup_state_data_model +4. setup_model_publication_cycle +""" +from argparse import ArgumentParser, RawDescriptionHelpFormatter + +import caosdb as db +from caosdb.common.administration import generate_password + + +def teardown(args): + """fully clears the database""" + + if "yes" != input( + "Are you really sure that you want to delete ALL " + "ENTITIES in LinkAhead? [yes/No]" + ): + + print("Nothing done.") + + return + d = db.execute_query("FIND ENTITY WITH ID > 99") + + if len(d) > 0: + d.delete(flags={"forceFinalState": "true"}) + + +def soft_teardown(args): + """ allows to remove state data only """ + recs = db.execute_query("FIND Entity WITH State") + + for rec in recs: + rec.state = None + recs.update(flags={"forceFinalState": "true"}) + db.execute_query("FIND StateModel").delete() + db.execute_query("FIND Transition").delete() + db.execute_query("FIND State").delete() + db.execute_query( + "FIND Property WITH name=from or name=to or name=initial or name=final or name=color").delete() + + +def setup_user(args): + """Creates a user with given username and adds the given role. + + If the user exists, it is deleted first. A random password is generated + and printed in clear text in the console output. + + """ + + username, role = args.username, args.role + try: + db.administration._delete_user(name=username) + except Exception: + pass + + password = generate_password(10) + print("new password for {}:\n{}".format(username, password)) + db.administration._insert_user( + name=username, password=password, status="ACTIVE") + db.administration._set_roles(username=username, roles=[role]) + + +def remove_user(args): + """deletes the given user""" + db.administration._delete_user(name=args.username) + + +def setup_role_permissions(): + """ + Adds the appropriate permissions to the 'normal' and 'publisher' role. + + The permissions are such that they suit the publication life cycle. + """ + db.administration._set_permissions( + role="normal", + permission_rules=[ + db.administration.PermissionRule("Grant", "TRANSACTION:*"), + db.administration.PermissionRule( + "Grant", "ACM:USER:UPDATE_PASSWORD:?REALM?:?USERNAME?" + ), + db.administration.PermissionRule("Grant", "STATE:TRANSITION:Edit"), + db.administration.PermissionRule("Grant", "UPDATE:PROPERTY:ADD"), + db.administration.PermissionRule( + "Grant", "UPDATE:PROPERTY:REMOVE"), + db.administration.PermissionRule( + "Grant", "STATE:TRANSITION:Start Review"), + db.administration.PermissionRule( + "Grant", "STATE:ASSIGN:Publish Life-cycle" + ), + ], + ) + + db.administration._set_permissions( + role="publisher", + permission_rules=[ + db.administration.PermissionRule( + "Grant", "ACM:USER:UPDATE_PASSWORD:?REALM?:?USERNAME?" + ), + db.administration.PermissionRule("Grant", "TRANSACTION:*"), + db.administration.PermissionRule("Grant", "UPDATE:PROPERTY:ADD"), + db.administration.PermissionRule( + "Grant", "UPDATE:PROPERTY:REMOVE"), + db.administration.PermissionRule("Grant", "STATE:*"), + ], + ) + + +def setup_roles(args): + """Creates 'publisher' and 'normla' roles and assigns appropriate + permissions + + If those roles exist they are deleted first. + """ + + for role in ["publisher", "normal"]: + try: + db.administration._delete_role(name=role) + except Exception: + print("Could not delete role {}".format(role)) + + for role in ["publisher", "normal"]: + db.administration._insert_role(name=role, description="") + + setup_role_permissions() + + +def setup_state_data_model(args): + """Creates the data model for using states + + RecordTypes: State, StateModel, Transition + Properties: from, to, initial, final, color + """ + cont = db.Container().extend( + [ + db.RecordType("State"), + db.RecordType("StateModel"), + db.RecordType("Transition"), + db.Property(name="from", datatype="State"), + db.Property(name="to", datatype="State"), + db.Property(name="initial", datatype="State"), + db.Property(name="final", datatype="State"), + db.Property(name="color", datatype=db.TEXT), + ] + ) + cont.insert() + + +def setup_model_publication_cycle(args): + """Creates States and Transitions for the Publication Life Cycle""" + unpublished_acl = db.ACL() + unpublished_acl.grant(role="publisher", permission="*") + unpublished_acl.grant(role="normal", permission="UPDATE:*") + unpublished_acl.grant(role="normal", permission="RETRIEVE:ENTITY") + unpublished_acl = db.State.create_state_acl(unpublished_acl) + + unpublished_state = ( + db.Record( + "Unpublished", + description="Unpublished entries are only visible to the team " + "and may be edited by any team member.", + ) + .add_parent("State") + .add_property("color", "#5bc0de") + ) + unpublished_state.acl = unpublished_acl + unpublished_state.insert() + + review_acl = db.ACL() + review_acl.grant(role="publisher", permission="*") + review_acl.grant(role="normal", permission="RETRIEVE:ENTITY") + + review_state = ( + db.Record( + "Under Review", + description="Entries under review are not publicly available yet, " + "but they can only be edited by the members of the publisher " + "group.", + ) + .add_parent("State") + .add_property("color", "#FFCC33") + ) + review_state.acl = db.State.create_state_acl(review_acl) + review_state.insert() + + published_acl = db.ACL() + published_acl.grant(role="guest", permission="RETRIEVE:ENTITY") + + published_state = ( + db.Record( + "Published", + description="Published entries are publicly available and " + "cannot be edited unless they are unpublished again.", + ) + .add_parent("State") + .add_property("color", "#333333") + ) + published_state.acl = db.State.create_state_acl(published_acl) + published_state.insert() + + # 1->2 + ( + db.Record( + "Start Review", + description="This transitions denies the permissions to edit an " + "entry for anyone but the members of the publisher group. " + "However, the entry is not yet publicly available.", + ) + .add_parent("Transition") + .add_property("from", "unpublished") + .add_property("to", "under review") + .add_property("color", "#FFCC33") + .insert() + ) + + # 2->3 + ( + db.Record( + "Publish", + description="Published entries are visible for the public and " + "cannot be changed unless they are unpublished again. Only members" + " of the publisher group can publish or unpublish entries.", + ) + .add_parent("Transition") + .add_property("from", "under review") + .add_property("to", "published") + .add_property("color", "red") + .insert() + ) + + # 3->1 + ( + db.Record( + "Unpublish", + description="Unpublish this entry to hide it from " + "the public. Unpublished entries can be edited by any team " + "member.", + ) + .add_parent("Transition") + .add_property("from", "published") + .add_property("to", "unpublished") + .insert() + ) + + # 2->1 + ( + db.Record( + "Reject", + description="Reject the publishing of this entity. Afterwards, " + "the entity is editable for any team member again.", + ) + .add_parent("Transition") + .add_property("from", "under review") + .add_property("to", "unpublished") + .insert() + ) + + # 1->1 + ( + db.Record( + "Edit", + description="Edit this entity. The changes are not publicly " + "available until this entity will have been reviewed and " + "published.", + ) + .add_parent( + "Transition", + ) + .add_property("from", "unpublished") + .add_property("to", "unpublished") + .insert() + ) + + ( + db.Record( + "Publish Life-cycle", + description="The publish life-cycle is a quality assurance tool. " + "Database entries can be edited without being publicly available " + "until the changes have been reviewed and explicitely published by" + " an eligible user.", + ) + .add_parent("StateModel") + .add_property( + "Transition", + datatype=db.LIST("Transition"), + value=[ + "Edit", + "Start Review", + "Reject", + "Publish", + "Unpublish", + ], + ) + .add_property("initial", "Unpublished") + .add_property("final", "Unpublished") + .insert() + ) + + +def parse_args(): + parser = ArgumentParser( + description=__doc__, formatter_class=RawDescriptionHelpFormatter + ) + subparsers = parser.add_subparsers( + title="action", + metavar="ACTION", + description=( + "You can perform the following actions. " + "Print the detailed help for each command with " + "#> setup_state_model ACTION -h" + ), + ) + + subparser = subparsers.add_parser( + "setup_state_data_model", help=setup_state_data_model.__doc__ + ) + subparser.set_defaults(call=setup_state_data_model) + + subparser = subparsers.add_parser( + "setup_model_publication_cycle", help=setup_model_publication_cycle.__doc__ + ) + subparser.set_defaults(call=setup_model_publication_cycle) + + subparser = subparsers.add_parser("setup_roles", help=setup_roles.__doc__) + subparser.set_defaults(call=setup_roles) + + subparser = subparsers.add_parser("remove_user", help=remove_user.__doc__) + subparser.set_defaults(call=remove_user) + subparser.add_argument("username") + + subparser = subparsers.add_parser("setup_user", help=setup_user.__doc__) + subparser.set_defaults(call=setup_user) + subparser.add_argument("username") + subparser.add_argument("role") + + subparser = subparsers.add_parser( + "teardown", help="Removes ALL ENTITIES from LinkAhead!" + ) + subparser.set_defaults(call=teardown) + + subparser = subparsers.add_parser( + "soft_teardown", help=soft_teardown.__doc__ + ) + subparser.set_defaults(call=soft_teardown) + + return parser.parse_args() + + +if __name__ == "__main__": + args = parse_args() + args.call(args) diff --git a/src/doc/tutorials/statemachine.rst b/src/doc/tutorials/statemachine.rst new file mode 100644 index 0000000000000000000000000000000000000000..317620423e6221ccaf29297fc1f71f0c008f78a0 --- /dev/null +++ b/src/doc/tutorials/statemachine.rst @@ -0,0 +1,34 @@ + +State Machine +============= + +Prerequisites +------------- + +In order to use the state machine functionality you have to set the +corresponding server setting: ``EXT_ENTITY_STATE=ENABLED``. + +Also, a few RecordTypes and Properties are required. You can use the +script `setup_state_model.py <https://gitlab.com/caosdb/caosdb-server/-/blob/dev/src/doc/tutorials/setup_state_model.py>`_ +to create those or you may have a look at it to see what is needed (``setup_state_data_model`` function). + +Defining the State Machine +-------------------------- + +Now you are setup to create your own state machine. You can define States and Transitions +and bundle it all to a StateModel. The above mentioned ``setup_state_model.py`` script defines +a publication cycle with the state "Unpublished", "UnderReview" and "Published". +Again, the ``setup_state_model.py`` script provides orientation on how this +can be setup (``setup_model_publication_cycle`` function). + +Note, that you can provide ACL to the state definition which will be applied to an entity once +the state is reached. This is for example useful to change the visibility depending on a state change. + +If you assign a state to a RecordType, this state will be the initial state +of Records that have that parent. For example by executing: + +.. code-block:: Python + + rt = db.RecordType("Article").retrieve() + rt.state = db.State(name="UnPublished", model="Publish Life-cycle")`` + rt.update() diff --git a/src/main/java/org/caosdb/datetime/DateTimeFactory2.java b/src/main/java/org/caosdb/datetime/DateTimeFactory2.java index 103359c7b4ff6f995996866e2283bab47562699c..14088ea5d1033771d8835352b61e5bf430c4ff5f 100644 --- a/src/main/java/org/caosdb/datetime/DateTimeFactory2.java +++ b/src/main/java/org/caosdb/datetime/DateTimeFactory2.java @@ -30,6 +30,11 @@ import org.antlr.v4.runtime.CommonTokenStream; import org.caosdb.server.query.CQLParsingErrorListener; import org.caosdb.server.query.CQLParsingErrorListener.ParsingError; +/** + * Factory which parses string into CaosDB's DATETIME values. + * + * @author tf + */ public class DateTimeFactory2 implements DateTimeFactoryInterface { private Long millis = null; @@ -51,6 +56,14 @@ public class DateTimeFactory2 implements DateTimeFactoryInterface { private Integer nanosecond = null; private TimeZone timeZone = TimeZone.getDefault(); + public DateTimeFactory2(TimeZone timeZone) { + this.timeZone = timeZone; + } + + public DateTimeFactory2() { + this(TimeZone.getDefault()); + } + @Override public void setDate(final String string) { this.date = Integer.valueOf(string); @@ -220,6 +233,16 @@ public class DateTimeFactory2 implements DateTimeFactoryInterface { } public static DateTimeInterface valueOf(final String str) { + return valueOf(str, TimeZone.getDefault()); + } + + public static DateTimeInterface valueOf(final String str, TimeZone timeZone) { + final DateTimeFactory2 dtf = new DateTimeFactory2(timeZone); + + return dtf.parse(str); + } + + public DateTimeInterface parse(String str) { final DateTimeLexer lexer = new DateTimeLexer(CharStreams.fromString(str)); final CommonTokenStream tokens = new CommonTokenStream(lexer); @@ -230,9 +253,7 @@ public class DateTimeFactory2 implements DateTimeFactoryInterface { final CQLParsingErrorListener el = new CQLParsingErrorListener(DateTimeLexer.UNKNOWN_CHAR); parser.addErrorListener(el); - final DateTimeFactory2 dtf = new DateTimeFactory2(); - - parser.datetime(dtf); + parser.datetime(this); if (el.hasErrors()) { final StringBuilder sb = new StringBuilder(); @@ -243,7 +264,7 @@ public class DateTimeFactory2 implements DateTimeFactoryInterface { "Parsing DateTime finished with errors. \n" + sb.toString()); } - return dtf.getDateTime(); + return getDateTime(); } @Override diff --git a/src/main/java/org/caosdb/server/CaosDBServer.java b/src/main/java/org/caosdb/server/CaosDBServer.java index b445749d68fafaeac74cc398912769acd6841a8b..fab783b765cb8af3c5ffdd1dda8ab2eb5dd0086b 100644 --- a/src/main/java/org/caosdb/server/CaosDBServer.java +++ b/src/main/java/org/caosdb/server/CaosDBServer.java @@ -60,6 +60,8 @@ import org.caosdb.server.entity.EntityInterface; import org.caosdb.server.entity.Role; import org.caosdb.server.entity.container.Container; import org.caosdb.server.grpc.GRPCServer; +import org.caosdb.server.jobs.core.AccessControl; +import org.caosdb.server.jobs.core.CheckStateTransition; import org.caosdb.server.logging.RequestErrorLogMessage; import org.caosdb.server.resource.AuthenticationResource; import org.caosdb.server.resource.DefaultResource; @@ -81,6 +83,7 @@ import org.caosdb.server.resource.Webinterface; import org.caosdb.server.resource.WebinterfaceBuildNumber; import org.caosdb.server.resource.transaction.EntityNamesResource; import org.caosdb.server.resource.transaction.EntityResource; +import org.caosdb.server.scripting.ScriptingPermissions; import org.caosdb.server.transaction.ChecksumUpdater; import org.caosdb.server.utils.FileUtils; import org.caosdb.server.utils.Initialization; @@ -280,6 +283,16 @@ public class CaosDBServer extends Application { // init Shiro (user authentication/authorization and session management) final Ini config = getShiroConfig(); initShiro(config); + + // Init ACMPermissions.ALL - the whole point is to fill all these + // permissions into ACMPermissions.ALL for retrieval by clients. If we don't + // do this, every work, but the list of known permissions grows over time + // (as soon as these classes are used for the first time) + logger.debug("Register permissions: ", ScriptingPermissions.PERMISSION_EXECUTION("*")); + logger.debug("Register permissions: ", CheckStateTransition.STATE_PERMISSIONS.toString()); + logger.debug( + "Register permissions: ", CheckStateTransition.PERMISSION_STATE_FORCE_FINAL.toString()); + logger.debug("Register permissions: ", AccessControl.TRANSACTION_PERMISSIONS.toString()); } public static Ini getShiroConfig() { diff --git a/src/main/java/org/caosdb/server/accessControl/ACMPermissions.java b/src/main/java/org/caosdb/server/accessControl/ACMPermissions.java index 84844e892297e68d2ad22cbf5dad935612d1c4f4..854fc07f9ed93eda28e8aca99c1ea1983c73f4fe 100644 --- a/src/main/java/org/caosdb/server/accessControl/ACMPermissions.java +++ b/src/main/java/org/caosdb/server/accessControl/ACMPermissions.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -17,79 +18,257 @@ * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. - * - * ** end header */ package org.caosdb.server.accessControl; -public class ACMPermissions { +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ACMPermissions implements Comparable<ACMPermissions> { + + private static Logger LOGGER = LoggerFactory.getLogger(ACMPermissions.class); + public static final String USER_PARAMETER = "?USER?"; + public static final String REALM_PARAMETER = "?REALM?"; + public static final String ROLE_PARAMETER = "?ROLE?"; + public static Set<ACMPermissions> ALL = new HashSet<>(); + public static final ACMPermissions GENERIC_ACM_PERMISSION = + new ACMPermissions( + "ACM:*", + "Permissions to administrate the access controll management system. That includes managing users, roles, and assigning permissions to roles and roles to users."); + + protected final String permission; + protected final String description; + + public ACMPermissions(String permission, String description) { + if (permission == null) { + throw new NullPointerException("Permission must no be null"); + } + this.permission = permission; + this.description = description; + ALL.add(this); + } + + @Override + public final boolean equals(Object obj) { + if (obj instanceof ACMPermissions) { + ACMPermissions that = (ACMPermissions) obj; + return this.permission.equals(that.permission); + } + return false; + } + + @Override + public final int hashCode() { + return permission.hashCode(); + } + + @Override + public final String toString() { + return this.permission; + } + + public final String getDescription() { + return description; + } + + public static final class UserPermission extends ACMPermissions { + + public static final ACMPermissions GENERIC_USER_PERMISSION = + new ACMPermissions( + "ACM:USER:*", + "Permissions to manage users, i.e. create, retrieve, update and delete users."); + + public UserPermission(String permission, String description) { + super(permission, description); + } + + public String toString(String realm) { + return toString().replace(REALM_PARAMETER, realm); + } + + public String toString(String realm, String user) { + return toString(realm).replace(USER_PARAMETER, user); + } + } + + public static final class RolePermission extends ACMPermissions { + + public static final ACMPermissions GENERIC_ROLE_PERMISSION = + new ACMPermissions( + "ACM:ROLE:*", + "Permissions to manage roles, i.e. create, retrieve, update and delete roles and assign them to users."); + + public RolePermission(String permission, String description) { + super(permission, description); + } - public static final String PERMISSION_ACCESS_SERVER_PROPERTIES = "ACCESS_SERVER_PROPERTIES"; - public static final String PERMISSION_RETRIEVE_SERVERLOGS = "SERVERLOGS:RETRIEVE"; + public String toString(String role) { + return toString().replace(ROLE_PARAMETER, role); + } + } + + public static final String PERMISSION_ACCESS_SERVER_PROPERTIES = + new ACMPermissions("ACCESS_SERVER_PROPERTIES", "Permission to read the server properties.") + .toString(); + + @Deprecated + public static final String PERMISSION_RETRIEVE_SERVERLOGS = + new ACMPermissions("SERVERLOGS:RETRIEVE", "Permission to read the server logs. (DEPRECATED)") + .toString(); + + private static UserPermission retrieve_user_roles = + new UserPermission( + "ACM:USER:RETRIEVE:ROLES:" + REALM_PARAMETER + ":" + USER_PARAMETER, + "Permission to retrieve the roles of a user"); public static final String PERMISSION_RETRIEVE_USER_ROLES( final String realm, final String username) { - return "ACM:USER:RETRIEVE:ROLES:" + realm + ":" + username; + return retrieve_user_roles.toString(realm, username); } + private static UserPermission retrieve_user_info = + new UserPermission( + "ACM:USER:RETRIEVE:INFO:" + REALM_PARAMETER + ":" + USER_PARAMETER, + "Permission to retrieve the user info (email, entity, status)"); + public static final String PERMISSION_RETRIEVE_USER_INFO( final String realm, final String username) { - return "ACM:USER:RETRIEVE:INFO:" + realm + ":" + username; + return retrieve_user_info.toString(realm, username); } + private static UserPermission delete_user = + new UserPermission( + "ACM:USER:DELETE:" + REALM_PARAMETER + ":" + USER_PARAMETER, + "Permission to delete a user"); + public static String PERMISSION_DELETE_USER(final String realm, final String username) { - return "ACM:USER:DELETE:" + realm + ":" + username; + return delete_user.toString(realm, username); } + private static final UserPermission insert_user = + new UserPermission( + "ACM:USER:INSERT:" + REALM_PARAMETER, "Permission to create a user in the given realm"); + public static String PERMISSION_INSERT_USER(final String realm) { - return "ACM:USER:INSERT:" + realm; + return insert_user.toString(realm); } + private static final UserPermission update_user_password = + new UserPermission( + "ACM:USER:UPDATE_PASSWORD:" + REALM_PARAMETER + ":" + USER_PARAMETER, + "Permission to set the password of a user."); + public static String PERMISSION_UPDATE_USER_PASSWORD(final String realm, final String username) { - return "ACM:USER:UPDATE_PASSWORD:" + realm + ":" + username; + return update_user_password.toString(realm, username); } + private static final UserPermission update_user_email = + new UserPermission( + "ACM:USER:UPDATE:EMAIL:" + REALM_PARAMETER + ":" + USER_PARAMETER, + "Permission to update the email address of a user."); + public static String PERMISSION_UPDATE_USER_EMAIL(final String realm, final String username) { - return "ACM:USER:UPDATE:EMAIL:" + realm + ":" + username; + return update_user_email.toString(realm, username); } + private static final UserPermission update_user_status = + new UserPermission( + "ACM:USER:UPDATE:STATUS:" + REALM_PARAMETER + ":" + USER_PARAMETER, + "Permission to update the status of a user, i.e. marking them as ACTIVE or INACTIVE."); + public static String PERMISSION_UPDATE_USER_STATUS(final String realm, final String username) { - return "ACM:USER:UPDATE:STATUS:" + realm + ":" + username; + return update_user_status.toString(realm, username); } + private static final UserPermission update_user_entity = + new UserPermission( + "ACM:USER:UPDATE:ENTITY:" + REALM_PARAMETER + ":" + USER_PARAMETER, + "Permission to set the entity which is associated with a user."); + public static String PERMISSION_UPDATE_USER_ENTITY(final String realm, final String username) { - return "ACM:USER:UPDATE:ENTITY:" + realm + ":" + username; + return update_user_entity.toString(realm, username); } + private static final UserPermission update_user_roles = + new UserPermission( + "ACM:USER:UPDATE:ROLES:" + REALM_PARAMETER + ":" + USER_PARAMETER, + "Permission to change the roles of a user."); + public static String PERMISSION_UPDATE_USER_ROLES(final String realm, final String username) { - return "ACM:USER:UPDATE:ROLES:" + realm + ":" + username; + return update_user_roles.toString(realm, username); } + private static final RolePermission insert_role = + new RolePermission("ACM:ROLE:INSERT", "Permission to create a new role."); + public static String PERMISSION_INSERT_ROLE() { - return "ACM:ROLE:INSERT"; + return insert_role.toString(); } + private static final RolePermission update_role_description = + new RolePermission( + "ACM:ROLE:UPDATE:DESCRIPTION:" + ROLE_PARAMETER, + "Permission to update the description of a role."); + public static String PERMISSION_UPDATE_ROLE_DESCRIPTION(final String role) { - return "ACM:ROLE:UPDATE:DESCRIPTION:" + role; + return update_role_description.toString(role); } + private static final RolePermission retrieve_role_description = + new RolePermission( + "ACM:ROLE:RETRIEVE:DESCRIPTION:" + ROLE_PARAMETER, + "Permission to retrieve the description of a role."); + public static String PERMISSION_RETRIEVE_ROLE_DESCRIPTION(final String role) { - return "ACM:ROLE:RETRIEVE:DESCRIPTION:" + role; + return retrieve_role_description.toString(role); } + private static final RolePermission delete_role = + new RolePermission("ACM:ROLE:DELETE:" + ROLE_PARAMETER, "Permission to delete a role."); + public static String PERMISSION_DELETE_ROLE(final String role) { - return "ACM:ROLE:DELETE:" + role; + return delete_role.toString(role); } + private static final RolePermission update_role_permissions = + new RolePermission( + "ACM:ROLE:UPDATE:PERMISSIONS:" + ROLE_PARAMETER, + "Permission to set the permissions of a role."); + public static String PERMISSION_UPDATE_ROLE_PERMISSIONS(final String role) { - return "ACM:ROLE:UPDATE:PERMISSIONS:" + role; + return update_role_permissions.toString(role); } + private static final RolePermission retrieve_role_permissions = + new RolePermission( + "ACM:ROLE:RETRIEVE:PERMISSIONS:" + ROLE_PARAMETER, + "Permission to read the permissions of a role."); + public static String PERMISSION_RETRIEVE_ROLE_PERMISSIONS(final String role) { - return "ACM:ROLE:RETRIEVE:PERMISSIONS:" + role; + return retrieve_role_permissions.toString(role); } + private static final RolePermission assign_role = + new RolePermission( + "ACM:ROLE:ASSIGN:" + ROLE_PARAMETER, "Permission to assign a role (to a user)."); + public static String PERMISSION_ASSIGN_ROLE(final String role) { - return "ACM:ROLE:ASSIGN:" + role; + return assign_role.toString(role); + } + + @Override + public int compareTo(ACMPermissions that) { + return this.toString().compareToIgnoreCase(that.toString()); + } + + public static List<ACMPermissions> getAll() { + LinkedList<ACMPermissions> result = new LinkedList<>(ALL); + Collections.sort(result); + return result; } } diff --git a/src/main/java/org/caosdb/server/accessControl/AnonymousRealm.java b/src/main/java/org/caosdb/server/accessControl/AnonymousRealm.java index 006400bf649619390d5eaa642642a73b6a94f337..92b37c0ec15b110670a55ea46b6efa1a418bb597 100644 --- a/src/main/java/org/caosdb/server/accessControl/AnonymousRealm.java +++ b/src/main/java/org/caosdb/server/accessControl/AnonymousRealm.java @@ -27,12 +27,19 @@ import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher; import org.apache.shiro.realm.AuthenticatingRealm; +import org.caosdb.server.CaosDBServer; +import org.caosdb.server.ServerProperties; public class AnonymousRealm extends AuthenticatingRealm { @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) { - return new SimpleAuthenticationInfo(token.getPrincipal(), null, getName()); + + if (CaosDBServer.getServerProperty(ServerProperties.KEY_AUTH_OPTIONAL) + .equalsIgnoreCase("true")) { + return new SimpleAuthenticationInfo(token.getPrincipal(), null, getName()); + } + return null; } public AnonymousRealm() { diff --git a/src/main/java/org/caosdb/server/accessControl/AuthenticationUtils.java b/src/main/java/org/caosdb/server/accessControl/AuthenticationUtils.java index e6907f40b57b5ef44dc9c4772327ddf8920df173..dc40e72e44ffdd6fca21824c6f3dd036f0b6f9ed 100644 --- a/src/main/java/org/caosdb/server/accessControl/AuthenticationUtils.java +++ b/src/main/java/org/caosdb/server/accessControl/AuthenticationUtils.java @@ -29,6 +29,7 @@ import static org.caosdb.server.utils.Utils.URLDecodeWithUTF8; import java.sql.Timestamp; import java.util.Collection; import java.util.LinkedList; +import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.subject.Subject; import org.caosdb.server.CaosDBServer; import org.caosdb.server.ServerProperties; @@ -199,4 +200,8 @@ public class AuthenticationUtils { .getRealm() .equals(OneTimeAuthenticationToken.REALM_NAME); } + + public static AuthorizationInfo getAuthorizationInfo(Subject user) { + return new CaosDBAuthorizingRealm().doGetAuthorizationInfo(user.getPrincipals()); + } } diff --git a/src/main/java/org/caosdb/server/accessControl/CaosDBAuthorizingRealm.java b/src/main/java/org/caosdb/server/accessControl/CaosDBAuthorizingRealm.java index e10a0b29b38b2e246bde8c89c43a8b82a9307b7e..52f8d3db87f9748a254f7a6f60fc00100a1bef0e 100644 --- a/src/main/java/org/caosdb/server/accessControl/CaosDBAuthorizingRealm.java +++ b/src/main/java/org/caosdb/server/accessControl/CaosDBAuthorizingRealm.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,8 +19,8 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.accessControl; import java.util.Collection; @@ -63,7 +64,7 @@ public class CaosDBAuthorizingRealm extends AuthorizingRealm { // Find all roles which are associated with this principal in this realm. final Set<String> principalRoles = - UserSources.resolve((Principal) principals.getPrimaryPrincipal()); + UserSources.resolveRoles((Principal) principals.getPrimaryPrincipal()); if (principalRoles != null) { authzInfo.addRoles(principalRoles); } diff --git a/src/main/java/org/caosdb/server/accessControl/CaosDBRolePermissionResolver.java b/src/main/java/org/caosdb/server/accessControl/CaosDBRolePermissionResolver.java index 17637b010a1ddcd7ed88e3ba448e3fa68b894b43..5bc711e17b60309f851e55bf249a22beeec56d61 100644 --- a/src/main/java/org/caosdb/server/accessControl/CaosDBRolePermissionResolver.java +++ b/src/main/java/org/caosdb/server/accessControl/CaosDBRolePermissionResolver.java @@ -49,6 +49,7 @@ public class CaosDBRolePermissionResolver { throw new AuthenticationException(e); } } + return new CaosPermission(rules); } } diff --git a/src/main/java/org/caosdb/server/accessControl/Principal.java b/src/main/java/org/caosdb/server/accessControl/Principal.java index fc96fb99670b51d0a128710722e2c10effed152a..7d4144557d89ddf90ec99edb190abb66ec0119aa 100644 --- a/src/main/java/org/caosdb/server/accessControl/Principal.java +++ b/src/main/java/org/caosdb/server/accessControl/Principal.java @@ -88,6 +88,6 @@ public class Principal implements ResponsibleAgent { @Override public String toString() { - return "[[" + this.realm + "]]" + this.username; + return this.username + REALM_SEPARATOR + this.realm; } } diff --git a/src/main/java/org/caosdb/server/accessControl/Role.java b/src/main/java/org/caosdb/server/accessControl/Role.java index 1a34b49974804ae202ceaf4044ff1f620eaa5d12..d1b04918e76ecbe6c94db8b00c6bb50f1c9a351c 100644 --- a/src/main/java/org/caosdb/server/accessControl/Role.java +++ b/src/main/java/org/caosdb/server/accessControl/Role.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,18 +19,23 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.accessControl; import java.io.Serializable; +import java.util.LinkedList; +import org.caosdb.server.database.proto.ProtoUser; +import org.caosdb.server.permissions.PermissionRule; import org.jdom2.Element; public class Role implements Serializable { - private static final long serialVersionUID = 8968219504349206982L; + private static final long serialVersionUID = -243913823L; public String name = null; public String description = null; + public LinkedList<PermissionRule> permission_rules = null; + public LinkedList<ProtoUser> users = null; public Element toElement() { final Element ret = new Element("Role"); diff --git a/src/main/java/org/caosdb/server/accessControl/SessionTokenRealm.java b/src/main/java/org/caosdb/server/accessControl/SessionTokenRealm.java index d78ffb405a8470a005da54736e25fbd69340b7e5..270565be3dd8fc25408a1d7992638ef24bcfaa1c 100644 --- a/src/main/java/org/caosdb/server/accessControl/SessionTokenRealm.java +++ b/src/main/java/org/caosdb/server/accessControl/SessionTokenRealm.java @@ -36,7 +36,7 @@ public class SessionTokenRealm extends AuthenticatingRealm { final SelfValidatingAuthenticationToken sessionToken = (SelfValidatingAuthenticationToken) token; - if (sessionToken.isValid()) { + if (sessionToken.isValid() && UserSources.isActive(sessionToken)) { return new SimpleAuthenticationInfo(sessionToken, null, getName()); } return null; diff --git a/src/main/java/org/caosdb/server/accessControl/SinglePermissionSubject.java b/src/main/java/org/caosdb/server/accessControl/SinglePermissionSubject.java new file mode 100644 index 0000000000000000000000000000000000000000..2c3a3479420c5f0642e0d42bf53b717ab0219571 --- /dev/null +++ b/src/main/java/org/caosdb/server/accessControl/SinglePermissionSubject.java @@ -0,0 +1,210 @@ +package org.caosdb.server.accessControl; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.Callable; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authz.AuthorizationException; +import org.apache.shiro.authz.Permission; +import org.apache.shiro.authz.permission.WildcardPermission; +import org.apache.shiro.session.Session; +import org.apache.shiro.subject.ExecutionException; +import org.apache.shiro.subject.PrincipalCollection; +import org.apache.shiro.subject.Subject; + +public class SinglePermissionSubject implements Subject { + + private WildcardPermission permission; + + public SinglePermissionSubject(String permission) { + this.permission = new WildcardPermission(permission); + } + + @Override + public Object getPrincipal() { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public PrincipalCollection getPrincipals() { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public boolean isPermitted(String permission) { + return this.permission.implies(new WildcardPermission(permission)); + } + + @Override + public boolean isPermitted(Permission permission) { + return this.permission.implies(permission); + } + + @Override + public boolean[] isPermitted(String... permissions) { + boolean[] result = new boolean[permissions.length]; + for (int i = 0; i < result.length; i++) { + result[i] = this.permission.implies(new WildcardPermission(permissions[i])); + } + return result; + } + + @Override + public boolean[] isPermitted(List<Permission> permissions) { + boolean[] result = new boolean[permissions.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = this.permission.implies(permissions.get(i)); + } + return result; + } + + @Override + public boolean isPermittedAll(String... permissions) { + boolean result = true; + for (int i = 0; i < permissions.length; i++) { + result &= this.permission.implies(new WildcardPermission(permissions[i])); + } + return result; + } + + @Override + public boolean isPermittedAll(Collection<Permission> permissions) { + Boolean result = true; + Iterator<Permission> iterator = permissions.iterator(); + while (iterator.hasNext()) { + result &= this.permission.implies(iterator.next()); + } + return result; + } + + @Override + public void checkPermission(String permission) throws AuthorizationException { + if (!isPermitted(permission)) { + throw new AuthenticationException("Not permitted: " + permission); + } + } + + @Override + public void checkPermission(Permission permission) throws AuthorizationException { + if (!isPermitted(permission)) { + throw new AuthenticationException("Not permitted: " + permission.toString()); + } + } + + @Override + public void checkPermissions(String... permissions) throws AuthorizationException { + if (!isPermittedAll(permissions)) { + throw new AuthenticationException("Not permitted: " + permissions.toString()); + } + } + + @Override + public void checkPermissions(Collection<Permission> permissions) throws AuthorizationException { + if (!isPermittedAll(permissions)) { + throw new AuthenticationException("Not permitted: " + permissions.toString()); + } + } + + @Override + public boolean hasRole(String roleIdentifier) { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public boolean[] hasRoles(List<String> roleIdentifiers) { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public boolean hasAllRoles(Collection<String> roleIdentifiers) { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public void checkRole(String roleIdentifier) throws AuthorizationException { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public void checkRoles(Collection<String> roleIdentifiers) throws AuthorizationException { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public void checkRoles(String... roleIdentifiers) throws AuthorizationException { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public void login(AuthenticationToken token) throws AuthenticationException { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public boolean isAuthenticated() { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public boolean isRemembered() { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public Session getSession() { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public Session getSession(boolean create) { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public void logout() { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public <V> V execute(Callable<V> callable) throws ExecutionException { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public void execute(Runnable runnable) { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public <V> Callable<V> associateWith(Callable<V> callable) { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public Runnable associateWith(Runnable runnable) { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public void runAs(PrincipalCollection principals) + throws NullPointerException, IllegalStateException { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public boolean isRunAs() { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public PrincipalCollection getPreviousPrincipals() { + throw new UnsupportedOperationException("This method should never be called"); + } + + @Override + public PrincipalCollection releaseRunAs() { + throw new UnsupportedOperationException("This method should never be called"); + } +} diff --git a/src/main/java/org/caosdb/server/accessControl/UserSources.java b/src/main/java/org/caosdb/server/accessControl/UserSources.java index a7abd1405f3d566bb672befc86b853dcf2a17357..04c2ecab9fee23c62b042657c69911e2d69846a0 100644 --- a/src/main/java/org/caosdb/server/accessControl/UserSources.java +++ b/src/main/java/org/caosdb/server/accessControl/UserSources.java @@ -1,11 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen - * Copyright (C) 2020 Indiscale GmbH <info@indiscale.com> - * Copyright (C) 2020 Timm Fitschen <t.fitschen@indiscale.com> + * Copyright (C) 2020-2021 Indiscale GmbH <info@indiscale.com> + * Copyright (C) 2020-2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -20,22 +19,26 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.accessControl; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.config.Ini; +import org.apache.shiro.subject.Subject; import org.caosdb.server.CaosDBServer; import org.caosdb.server.ServerProperties; import org.caosdb.server.entity.Message; import org.caosdb.server.permissions.Role; +import org.caosdb.server.transaction.LogUserVisitTransaction; import org.caosdb.server.transaction.RetrieveRoleTransaction; import org.caosdb.server.transaction.RetrieveUserTransaction; import org.caosdb.server.utils.ServerMessages; @@ -69,6 +72,8 @@ import org.slf4j.LoggerFactory; */ public class UserSources extends HashMap<String, UserSource> { + public static final String USERNAME_PASSWORD_AUTHENTICATION = "USERNAME_PASSWORD_AUTHENTICATION"; + private static final Subject transactor = new SinglePermissionSubject("ACM:*:RETRIEVE:*"); private static final Logger logger = LoggerFactory.getLogger(UserSources.class); public static final String KEY_DEFAULT_REALM = "defaultRealm"; public static final String KEY_REALMS = "realms"; @@ -86,6 +91,14 @@ public class UserSources extends HashMap<String, UserSource> { * @return true iff the user identified by the given {@link Principal} exists. */ public static boolean isUserExisting(final Principal principal) { + if (principal.getRealm().equals(OneTimeAuthenticationToken.REALM_NAME)) { + return true; + } + if (principal.toString().equals(AnonymousAuthenticationToken.PRINCIPAL.toString()) + && CaosDBServer.getServerProperty(ServerProperties.KEY_AUTH_OPTIONAL) + .equalsIgnoreCase("true")) { + return true; + } UserSource userSource = instance.get(principal.getRealm()); if (userSource != null) { return userSource.isUserExisting(principal.getUsername()); @@ -164,18 +177,23 @@ public class UserSources extends HashMap<String, UserSource> { * @return A set of user roles. */ public static Set<String> resolveRoles(String realm, final String username) { + if (AnonymousAuthenticationToken.PRINCIPAL.getRealm().equals(realm) + && AnonymousAuthenticationToken.PRINCIPAL.getUsername().equals(username)) { + return Collections.singleton(Role.ANONYMOUS_ROLE.toString()); + } if (realm == null) { realm = guessRealm(username); } - UserSource userSource = instance.get(realm); - if (userSource == null) { - return null; + RetrieveUserTransaction t = new RetrieveUserTransaction(realm, username, transactor); + try { + t.execute(); + if (t.getUser() != null) return t.getRoles(); + } catch (Exception e) { + throw new AuthorizationException("Could not resolve roles for " + username + "@" + realm); } - // find all roles that are associated with this principal in this realm - final Set<String> ret = userSource.resolveRolesForUsername(username); - return ret; + return null; } public static String guessRealm(final String username) { @@ -206,20 +224,28 @@ public class UserSources extends HashMap<String, UserSource> { return instance.map.getSectionProperty(Ini.DEFAULT_SECTION_NAME, KEY_DEFAULT_REALM, "CaosDB"); } - // @todo Refactor name: resolveRoles(...)? - public static Set<String> resolve(final Principal principal) { + /** + * Return the roles of a given user. + * + * @param principal + * @return A set of role names. + */ + public static Set<String> resolveRoles(final Principal principal) { if (AnonymousAuthenticationToken.PRINCIPAL == principal) { // anymous has one role Set<String> roles = new HashSet<>(); roles.add(Role.ANONYMOUS_ROLE.toString()); return roles; } + if (principal instanceof OneTimeAuthenticationToken) { + return new HashSet<>(((OneTimeAuthenticationToken) principal).getRoles()); + } return resolveRoles(principal.getRealm(), principal.getUsername()); } public static boolean isRoleExisting(final String role) { - final RetrieveRoleTransaction t = new RetrieveRoleTransaction(role); + final RetrieveRoleTransaction t = new RetrieveRoleTransaction(role, transactor); try { t.execute(); return true; @@ -233,12 +259,20 @@ public class UserSources extends HashMap<String, UserSource> { } } + public static UserStatus getDefaultUserStatus(final String realm, String username) { + return instance.get(realm).getDefaultUserStatus(username); + } + public static UserStatus getDefaultUserStatus(final Principal p) { - return instance.get(p.getRealm()).getDefaultUserStatus(p.getUsername()); + return getDefaultUserStatus(p.getRealm(), p.getUsername()); } public static String getDefaultUserEmail(final Principal p) { - return instance.get(p.getRealm()).getDefaultUserEmail(p.getUsername()); + return getDefaultUserEmail(p.getRealm(), p.getUsername()); + } + + public static String getDefaultUserEmail(String realm, String username) { + return instance.get(realm).getDefaultUserEmail(username); } public static UserSource getInternalRealm() { @@ -251,16 +285,60 @@ public class UserSources extends HashMap<String, UserSource> { } final boolean isValid = instance.get(realm).isValid(username, password); - return isValid && isActive(realm, username); + + if (isValid && isActive(realm, username)) { + logUserVisit(realm, username, USERNAME_PASSWORD_AUTHENTICATION); + return true; + } + return false; + } + + /** Log the current time as the user's last visit. */ + public static void logUserVisit(String realm, String username, String type) { + try { + LogUserVisitTransaction t = + new LogUserVisitTransaction(System.currentTimeMillis(), realm, username, type); + t.execute(); + } catch (final Exception e) { + throw new AuthenticationException(e); + } } private static boolean isActive(final String realm, final String username) { - final RetrieveUserTransaction t = new RetrieveUserTransaction(realm, username); + final RetrieveUserTransaction t = new RetrieveUserTransaction(realm, username, transactor); try { t.execute(); - return t.isActive(); + if (t.getUser() != null) { + return t.getUser().status == UserStatus.ACTIVE; + } else { + return instance.get(realm).getDefaultUserStatus(username) == UserStatus.ACTIVE; + } } catch (final Exception e) { throw new AuthenticationException(e); } } + + public static boolean isActive(Principal principal) { + if (principal.getRealm().equals(OneTimeAuthenticationToken.REALM_NAME)) { + return true; + } + if (principal.getUsername().equals(AnonymousAuthenticationToken.PRINCIPAL.getUsername()) + && principal.getRealm().equals(AnonymousAuthenticationToken.PRINCIPAL.getRealm()) + && CaosDBServer.getServerProperty(ServerProperties.KEY_AUTH_OPTIONAL) + .equalsIgnoreCase("true")) { + return true; + } + return isActive(principal.getRealm(), principal.getUsername()); + } + + public static Set<String> getDefaultRoles(String realm, String username) { + UserSource userSource = instance.get(realm); + if (userSource == null) { + return null; + } + // find all roles that are associated with this principal in this realm + final Set<String> ret = userSource.resolveRolesForUsername(username); + + return ret; + } } diff --git a/src/main/java/org/caosdb/server/database/BackendTransaction.java b/src/main/java/org/caosdb/server/database/BackendTransaction.java index 7c26db1ed05e76c30f9d30f0c3d9965ed0c59b6b..5addf3f3f3e34a8e3e6a9152b9511046fe4b6a23 100644 --- a/src/main/java/org/caosdb/server/database/BackendTransaction.java +++ b/src/main/java/org/caosdb/server/database/BackendTransaction.java @@ -44,10 +44,14 @@ import org.caosdb.server.database.backend.implementation.MySQL.MySQLInsertRole; import org.caosdb.server.database.backend.implementation.MySQL.MySQLInsertSparseEntity; import org.caosdb.server.database.backend.implementation.MySQL.MySQLInsertTransactionHistory; import org.caosdb.server.database.backend.implementation.MySQL.MySQLIsSubType; +import org.caosdb.server.database.backend.implementation.MySQL.MySQLListRoles; +import org.caosdb.server.database.backend.implementation.MySQL.MySQLListUsers; +import org.caosdb.server.database.backend.implementation.MySQL.MySQLLogUserVisit; import org.caosdb.server.database.backend.implementation.MySQL.MySQLRegisterSubDomain; import org.caosdb.server.database.backend.implementation.MySQL.MySQLRetrieveAll; import org.caosdb.server.database.backend.implementation.MySQL.MySQLRetrieveAllUncheckedFiles; import org.caosdb.server.database.backend.implementation.MySQL.MySQLRetrieveDatatypes; +import org.caosdb.server.database.backend.implementation.MySQL.MySQLRetrieveEntityACL; import org.caosdb.server.database.backend.implementation.MySQL.MySQLRetrieveLogRecord; import org.caosdb.server.database.backend.implementation.MySQL.MySQLRetrieveParents; import org.caosdb.server.database.backend.implementation.MySQL.MySQLRetrievePasswordValidator; @@ -99,10 +103,14 @@ import org.caosdb.server.database.backend.interfaces.InsertRoleImpl; import org.caosdb.server.database.backend.interfaces.InsertSparseEntityImpl; import org.caosdb.server.database.backend.interfaces.InsertTransactionHistoryImpl; import org.caosdb.server.database.backend.interfaces.IsSubTypeImpl; +import org.caosdb.server.database.backend.interfaces.ListRolesImpl; +import org.caosdb.server.database.backend.interfaces.ListUsersImpl; +import org.caosdb.server.database.backend.interfaces.LogUserVisitImpl; import org.caosdb.server.database.backend.interfaces.RegisterSubDomainImpl; import org.caosdb.server.database.backend.interfaces.RetrieveAllImpl; import org.caosdb.server.database.backend.interfaces.RetrieveAllUncheckedFilesImpl; import org.caosdb.server.database.backend.interfaces.RetrieveDatatypesImpl; +import org.caosdb.server.database.backend.interfaces.RetrieveEntityACLImpl; import org.caosdb.server.database.backend.interfaces.RetrieveLogRecordImpl; import org.caosdb.server.database.backend.interfaces.RetrieveParentsImpl; import org.caosdb.server.database.backend.interfaces.RetrievePasswordValidatorImpl; @@ -192,6 +200,7 @@ public abstract class BackendTransaction implements Undoable { setImpl(FileCheckSize.class, UnixFileSystemCheckSize.class); setImpl(InsertRoleImpl.class, MySQLInsertRole.class); setImpl(RetrieveRoleImpl.class, MySQLRetrieveRole.class); + setImpl(ListRolesImpl.class, MySQLListRoles.class); setImpl(DeleteRoleImpl.class, MySQLDeleteRole.class); setImpl(SetPermissionRulesImpl.class, MySQLSetPermissionRules.class); setImpl(RetrievePermissionRulesImpl.class, MySQLRetrievePermissionRules.class); @@ -204,6 +213,9 @@ public abstract class BackendTransaction implements Undoable { setImpl(InsertEntityDatatypeImpl.class, MySQLInsertEntityDatatype.class); setImpl(RetrieveVersionHistoryImpl.class, MySQLRetrieveVersionHistory.class); setImpl(SetFileChecksumImpl.class, MySQLSetFileChecksum.class); + setImpl(ListUsersImpl.class, MySQLListUsers.class); + setImpl(LogUserVisitImpl.class, MySQLLogUserVisit.class); + setImpl(RetrieveEntityACLImpl.class, MySQLRetrieveEntityACL.class); } } diff --git a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLDeleteRole.java b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLDeleteRole.java index 8fd8d35fda6b99f7d79b245a10ace4ed9521e0ce..b0faa45f96e04e6957ff1d288d034ca9e96cb6d7 100644 --- a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLDeleteRole.java +++ b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLDeleteRole.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,15 +19,17 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.database.backend.implementation.MySQL; import java.sql.PreparedStatement; import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; import org.caosdb.server.database.access.Access; import org.caosdb.server.database.backend.interfaces.DeleteRoleImpl; import org.caosdb.server.database.exceptions.TransactionException; +import org.caosdb.server.utils.ServerMessages; public class MySQLDeleteRole extends MySQLTransaction implements DeleteRoleImpl { @@ -42,6 +45,8 @@ public class MySQLDeleteRole extends MySQLTransaction implements DeleteRoleImpl final PreparedStatement stmt = prepareStatement(STMT_DELETE_ROLE); stmt.setString(1, role); stmt.execute(); + } catch (final SQLIntegrityConstraintViolationException e) { + throw new TransactionException(ServerMessages.ROLE_CANNOT_BE_DELETED); } catch (final SQLException e) { throw new TransactionException(e); } catch (final ConnectionException e) { diff --git a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLHelper.java b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLHelper.java index b1f445e2b8ad2d79b756e1dd662296d8e6c9a49c..568e0e53a7b80a76c533229e13c6700c4c4ff47f 100644 --- a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLHelper.java +++ b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLHelper.java @@ -35,7 +35,7 @@ import org.caosdb.server.accessControl.Principal; import org.caosdb.server.database.misc.DBHelper; import org.caosdb.server.transaction.ChecksumUpdater; import org.caosdb.server.transaction.TransactionInterface; -import org.caosdb.server.transaction.WriteTransaction; +import org.caosdb.server.transaction.WriteTransactionInterface; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,7 +55,7 @@ public class MySQLHelper implements DBHelper { * * <p>In the database, this adds a row to the transaction table with SRID, user and timestamp. */ - public void initTransaction(Connection connection, WriteTransaction transaction) + public void initTransaction(Connection connection, WriteTransactionInterface transaction) throws SQLException { try (CallableStatement call = connection.prepareCall("CALL set_transaction(?,?,?,?,?)")) { @@ -86,10 +86,10 @@ public class MySQLHelper implements DBHelper { if (transaction instanceof ChecksumUpdater) { connection.setReadOnly(false); connection.setAutoCommit(false); - } else if (transaction instanceof WriteTransaction) { + } else if (transaction instanceof WriteTransactionInterface) { connection.setReadOnly(false); connection.setAutoCommit(false); - initTransaction(connection, (WriteTransaction) transaction); + initTransaction(connection, (WriteTransactionInterface) transaction); } else { connection.setReadOnly(false); connection.setAutoCommit(true); diff --git a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLListRoles.java b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLListRoles.java new file mode 100644 index 0000000000000000000000000000000000000000..69ac524eae823d06fdbd4346056979ea15307437 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLListRoles.java @@ -0,0 +1,65 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.implementation.MySQL; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.LinkedList; +import java.util.List; +import org.caosdb.server.accessControl.Role; +import org.caosdb.server.database.access.Access; +import org.caosdb.server.database.backend.interfaces.ListRolesImpl; +import org.caosdb.server.database.exceptions.TransactionException; + +public class MySQLListRoles extends MySQLTransaction implements ListRolesImpl { + + public MySQLListRoles(Access access) { + super(access); + } + + public static final String STMT_LIST_ROLES = "SELECT name, description FROM roles"; + + @Override + public List<Role> execute() { + List<Role> roles = new LinkedList<>(); + try { + final PreparedStatement stmt = prepareStatement(STMT_LIST_ROLES); + final ResultSet rs = stmt.executeQuery(); + try { + while (rs.next()) { + final Role role = new Role(); + role.name = rs.getString("name"); + role.description = rs.getString("description"); + roles.add(role); + } + } finally { + rs.close(); + } + } catch (final SQLException e) { + throw new TransactionException(e); + } catch (final ConnectionException e) { + throw new TransactionException(e); + } + return roles; + } +} diff --git a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLListUsers.java b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLListUsers.java new file mode 100644 index 0000000000000000000000000000000000000000..83ebffe679e6625da720fd2933a5d8defb7264c3 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLListUsers.java @@ -0,0 +1,73 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.implementation.MySQL; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.LinkedList; +import java.util.List; +import org.caosdb.server.accessControl.UserStatus; +import org.caosdb.server.database.access.Access; +import org.caosdb.server.database.backend.interfaces.ListUsersImpl; +import org.caosdb.server.database.exceptions.TransactionException; +import org.caosdb.server.database.proto.ProtoUser; + +public class MySQLListUsers extends MySQLTransaction implements ListUsersImpl { + + public MySQLListUsers(Access access) { + super(access); + } + + public static final String STMT_LIST_USERS = + "SELECT status, realm, name, email, entity FROM user_info"; + + @Override + public List<ProtoUser> execute() { + List<ProtoUser> users = new LinkedList<>(); + try { + final PreparedStatement stmt = prepareStatement(STMT_LIST_USERS); + final ResultSet rs = stmt.executeQuery(); + try { + while (rs.next()) { + final ProtoUser user = new ProtoUser(); + user.name = rs.getString("name"); + user.realm = rs.getString("realm"); + user.email = rs.getString("email"); + user.entity = rs.getInt("entity"); + if (user.entity == 0) { + user.entity = null; + } + user.status = UserStatus.valueOf(rs.getString("status")); + users.add(user); + } + } finally { + rs.close(); + } + } catch (final SQLException e) { + throw new TransactionException(e); + } catch (final ConnectionException e) { + throw new TransactionException(e); + } + return users; + } +} diff --git a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLLogUserVisit.java b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLLogUserVisit.java new file mode 100644 index 0000000000000000000000000000000000000000..23050da87e324026be1eefa02690959d0a0590cc --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLLogUserVisit.java @@ -0,0 +1,59 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.implementation.MySQL; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import org.caosdb.server.database.access.Access; +import org.caosdb.server.database.backend.interfaces.LogUserVisitImpl; +import org.caosdb.server.database.exceptions.TransactionException; + +public class MySQLLogUserVisit extends MySQLTransaction implements LogUserVisitImpl { + + public MySQLLogUserVisit(Access access) { + super(access); + } + + public static final String LOG_USER_VISIT = + "SELECT status FROM user_info WHERE realm = ? AND name = ?"; + // TODO Replace by "UPDATE user_info SET last_seen = ?"; + + /** Return true if this is not the first visit of this user. */ + @Override + public boolean logUserReturnIsKnown(long timestamp, String realm, String username, String type) { + try (final PreparedStatement stmt = prepareStatement(LOG_USER_VISIT)) { + stmt.setString(1, realm); + stmt.setString(2, username); + ResultSet executeQuery = stmt.executeQuery(); + if (!executeQuery.next()) { + // first login of this user + return false; + } + } catch (final SQLException e) { + throw new TransactionException(e); + } catch (final ConnectionException e) { + throw new TransactionException(e); + } + return true; + } +} diff --git a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLRetrieveEntityACL.java b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLRetrieveEntityACL.java new file mode 100644 index 0000000000000000000000000000000000000000..5db8ed7597b1c0d357273848fb7c36febdcfed13 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLRetrieveEntityACL.java @@ -0,0 +1,57 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.implementation.MySQL; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import org.caosdb.server.database.access.Access; +import org.caosdb.server.database.backend.interfaces.RetrieveEntityACLImpl; +import org.caosdb.server.database.exceptions.TransactionException; +import org.caosdb.server.database.proto.VerySparseEntity; + +public class MySQLRetrieveEntityACL extends MySQLTransaction implements RetrieveEntityACLImpl { + + public MySQLRetrieveEntityACL(Access access) { + super(access); + } + + public static final String STMT = + "SELECT a.acl FROM entities AS e LEFT JOIN entity_acl AS a ON (a.id = e.acl) WHERE e.id = ? LIMIT 1"; + + @Override + public VerySparseEntity execute(Integer id) { + try (PreparedStatement stmt = prepareStatement(STMT)) { + stmt.setInt(1, id); + ResultSet rs = stmt.executeQuery(); + if (rs.next()) { + VerySparseEntity result = new VerySparseEntity(); + result.id = id; + result.acl = rs.getString(1); + return result; + } + } catch (SQLException | ConnectionException e) { + throw new TransactionException(e); + } + return null; + } +} diff --git a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLRetrieveRole.java b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLRetrieveRole.java index f0219040c47bc09fe2052d8e95a3ea83637e6aae..e9ee37c9a55bc07c79abc8b73d8f9bef2a5cde8c 100644 --- a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLRetrieveRole.java +++ b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLRetrieveRole.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,17 +19,22 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.database.backend.implementation.MySQL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.LinkedList; +import java.util.Map; import org.caosdb.server.accessControl.Role; import org.caosdb.server.database.access.Access; import org.caosdb.server.database.backend.interfaces.RetrieveRoleImpl; import org.caosdb.server.database.exceptions.TransactionException; +import org.caosdb.server.database.proto.ProtoUser; +import org.caosdb.server.permissions.PermissionRule; +import org.eclipse.jetty.util.ajax.JSON; public class MySQLRetrieveRole extends MySQLTransaction implements RetrieveRoleImpl { @@ -36,30 +42,66 @@ public class MySQLRetrieveRole extends MySQLTransaction implements RetrieveRoleI super(access); } - public static final String STMT_RETRIEVE_ROLE = "SELECT description FROM roles WHERE name=?"; + public static final String STMT_RETRIEVE_ROLE = + "SELECT r.description AS description, p.permissions AS permissions FROM roles AS r LEFT JOIN permissions AS p ON (r.name = p.role) WHERE r.name=?"; + public static final String STMT_RETRIEVE_USERS = + "SELECT u.realm, u.user FROM user_roles AS u WHERE u.role = ?"; @Override public Role retrieve(final String role) throws TransactionException { - try { - final PreparedStatement stmt = prepareStatement(STMT_RETRIEVE_ROLE); + Role ret = null; + try (final PreparedStatement stmt = prepareStatement(STMT_RETRIEVE_ROLE)) { stmt.setString(1, role); final ResultSet rs = stmt.executeQuery(); - try { - if (rs.next()) { - final Role ret = new Role(); - ret.name = role; - ret.description = rs.getString("description"); - return ret; - } else { - return null; + if (rs.next()) { + ret = new Role(); + ret.name = role; + ret.description = rs.getString("description"); + ret.permission_rules = parse(rs.getString("permissions")); + } else { + return null; + } + } catch (final SQLException e) { + throw new TransactionException(e); + } catch (final ConnectionException e) { + throw new TransactionException(e); + } + + try (final PreparedStatement stmt = prepareStatement(STMT_RETRIEVE_USERS)) { + stmt.setString(1, role); + final ResultSet rs = stmt.executeQuery(); + if (rs.next()) { + ret.users = new LinkedList<>(); + + ret.users.add(nextUser(rs)); + while (rs.next()) { + ret.users.add(nextUser(rs)); } - } finally { - rs.close(); } } catch (final SQLException e) { throw new TransactionException(e); } catch (final ConnectionException e) { throw new TransactionException(e); } + return ret; + } + + private ProtoUser nextUser(ResultSet rs) throws SQLException { + ProtoUser nextUser = new ProtoUser(); + nextUser.realm = rs.getString("realm"); + nextUser.name = rs.getString("user"); + return nextUser; + } + + @SuppressWarnings("unchecked") + private LinkedList<PermissionRule> parse(String string) { + if (string == null) return null; + final Object[] maps = (Object[]) JSON.parse(string); + final LinkedList<PermissionRule> ret = new LinkedList<>(); + for (final Object map : maps) { + ret.add(PermissionRule.parse((Map<String, String>) map)); + } + + return ret; } } diff --git a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLUpdateUserRoles.java b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLUpdateUserRoles.java index 62cb68bf58fc8269cc365fa167929ff79726499b..6a52ab9d0e7d606d5f92038239be0ccacd03bda6 100644 --- a/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLUpdateUserRoles.java +++ b/src/main/java/org/caosdb/server/database/backend/implementation/MySQL/MySQLUpdateUserRoles.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,13 +19,12 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ package org.caosdb.server.database.backend.implementation.MySQL; import java.sql.PreparedStatement; import java.sql.SQLException; -import java.util.HashSet; +import java.util.Set; import org.caosdb.server.database.access.Access; import org.caosdb.server.database.backend.interfaces.UpdateUserRolesImpl; import org.caosdb.server.database.exceptions.TransactionException; @@ -41,7 +41,7 @@ public class MySQLUpdateUserRoles extends MySQLTransaction implements UpdateUser "INSERT INTO user_roles (realm, user, role) VALUES (?,?,?);"; @Override - public void updateUserRoles(final String realm, final String user, final HashSet<String> roles) + public void updateUserRoles(final String realm, final String user, final Set<String> roles) throws TransactionException { try { final PreparedStatement delete_stmt = prepareStatement(STMT_DELETE_USER_ROLES); diff --git a/src/main/java/org/caosdb/server/database/backend/interfaces/ListRolesImpl.java b/src/main/java/org/caosdb/server/database/backend/interfaces/ListRolesImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..aab9041ae0f4e02d4b601e97d042dff591fbbf85 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/interfaces/ListRolesImpl.java @@ -0,0 +1,30 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.interfaces; + +import java.util.List; +import org.caosdb.server.accessControl.Role; + +public interface ListRolesImpl extends BackendTransactionImpl { + + public List<Role> execute(); +} diff --git a/src/main/java/org/caosdb/server/database/backend/interfaces/ListUsersImpl.java b/src/main/java/org/caosdb/server/database/backend/interfaces/ListUsersImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..6bdfda92f2b5a78b8b2dfc8b6f20aac3b68c08a9 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/interfaces/ListUsersImpl.java @@ -0,0 +1,30 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.interfaces; + +import java.util.List; +import org.caosdb.server.database.proto.ProtoUser; + +public interface ListUsersImpl extends BackendTransactionImpl { + + List<ProtoUser> execute(); +} diff --git a/src/main/java/org/caosdb/server/database/backend/interfaces/LogUserVisitImpl.java b/src/main/java/org/caosdb/server/database/backend/interfaces/LogUserVisitImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..38c253e2e76075c83a7874d581f8b97d25a382f5 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/interfaces/LogUserVisitImpl.java @@ -0,0 +1,26 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ +package org.caosdb.server.database.backend.interfaces; + +public interface LogUserVisitImpl extends BackendTransactionImpl { + + /** Return true if this is not the first visit of this user. */ + boolean logUserReturnIsKnown(long timestamp, String realm, String username, String type); +} diff --git a/src/main/java/org/caosdb/server/database/backend/interfaces/RetrieveEntityACLImpl.java b/src/main/java/org/caosdb/server/database/backend/interfaces/RetrieveEntityACLImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..230d4d34103603d5499532a7dc1a941cf82068e7 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/interfaces/RetrieveEntityACLImpl.java @@ -0,0 +1,29 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.interfaces; + +import org.caosdb.server.database.proto.VerySparseEntity; + +public interface RetrieveEntityACLImpl extends BackendTransactionImpl { + + public VerySparseEntity execute(Integer id); +} diff --git a/src/main/java/org/caosdb/server/database/backend/interfaces/UpdateUserRolesImpl.java b/src/main/java/org/caosdb/server/database/backend/interfaces/UpdateUserRolesImpl.java index f2abfbe3cb7846f16e21d8f9a719ad708884841c..891df301e992f42c38f7c52d867353a65cddd1b2 100644 --- a/src/main/java/org/caosdb/server/database/backend/interfaces/UpdateUserRolesImpl.java +++ b/src/main/java/org/caosdb/server/database/backend/interfaces/UpdateUserRolesImpl.java @@ -22,11 +22,11 @@ */ package org.caosdb.server.database.backend.interfaces; -import java.util.HashSet; +import java.util.Set; import org.caosdb.server.database.exceptions.TransactionException; public interface UpdateUserRolesImpl extends BackendTransactionImpl { - public void updateUserRoles(String realm, String user, HashSet<String> roles) + public void updateUserRoles(String realm, String user, Set<String> roles) throws TransactionException; } diff --git a/src/main/java/org/caosdb/server/database/backend/transaction/ListRoles.java b/src/main/java/org/caosdb/server/database/backend/transaction/ListRoles.java new file mode 100644 index 0000000000000000000000000000000000000000..75792475c4c5a6ae9091f89c8de1b4ef157aa11f --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/transaction/ListRoles.java @@ -0,0 +1,42 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.transaction; + +import java.util.List; +import org.caosdb.server.accessControl.Role; +import org.caosdb.server.database.BackendTransaction; +import org.caosdb.server.database.backend.interfaces.ListRolesImpl; + +public class ListRoles extends BackendTransaction { + + private List<Role> roles; + + @Override + protected void execute() { + ListRolesImpl t = getImplementation(ListRolesImpl.class); + roles = t.execute(); + } + + public List<Role> getRoles() { + return roles; + } +} diff --git a/src/main/java/org/caosdb/server/database/backend/transaction/ListUsers.java b/src/main/java/org/caosdb/server/database/backend/transaction/ListUsers.java new file mode 100644 index 0000000000000000000000000000000000000000..9f29a3c5888104140eb6e2c29b83370fc1c56401 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/transaction/ListUsers.java @@ -0,0 +1,42 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.transaction; + +import java.util.List; +import org.caosdb.server.database.BackendTransaction; +import org.caosdb.server.database.backend.interfaces.ListUsersImpl; +import org.caosdb.server.database.proto.ProtoUser; + +public class ListUsers extends BackendTransaction { + + private List<ProtoUser> users; + + @Override + protected void execute() { + ListUsersImpl t = getImplementation(ListUsersImpl.class); + users = t.execute(); + } + + public List<ProtoUser> getUsers() { + return users; + } +} diff --git a/src/main/java/org/caosdb/server/database/backend/transaction/LogUserVisit.java b/src/main/java/org/caosdb/server/database/backend/transaction/LogUserVisit.java new file mode 100644 index 0000000000000000000000000000000000000000..43fd87495c4e7489e7f15ec8674ce01cb674dd90 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/transaction/LogUserVisit.java @@ -0,0 +1,66 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.transaction; + +import java.util.HashSet; +import org.caosdb.server.accessControl.UserSources; +import org.caosdb.server.database.BackendTransaction; +import org.caosdb.server.database.backend.interfaces.LogUserVisitImpl; +import org.caosdb.server.database.backend.interfaces.UpdateUserImpl; +import org.caosdb.server.database.backend.interfaces.UpdateUserRolesImpl; +import org.caosdb.server.database.exceptions.TransactionException; +import org.caosdb.server.database.proto.ProtoUser; + +public class LogUserVisit extends BackendTransaction { + + private String realm; + private String username; + private String type; + private long timestamp; + + public LogUserVisit(long timestamp, String realm, String username, String type) { + this.timestamp = timestamp; + this.realm = realm; + this.username = username; + this.type = type; + } + + @Override + protected void execute() throws TransactionException { + final LogUserVisitImpl t = getImplementation(LogUserVisitImpl.class); + if (!t.logUserReturnIsKnown(timestamp, realm, username, type)) { + // User is unknown. Make it known + ProtoUser user = new ProtoUser(); + user.realm = realm; + user.name = username; + user.email = UserSources.getDefaultUserEmail(realm, username); + user.status = UserSources.getDefaultUserStatus(realm, username); + user.roles = new HashSet<>(UserSources.getDefaultRoles(realm, username)); + + UpdateUserImpl insertUser = getImplementation(UpdateUserImpl.class); + insertUser.execute(user); + UpdateUserRolesImpl setRoles = getImplementation(UpdateUserRolesImpl.class); + setRoles.updateUserRoles(user.realm, user.name, user.roles); + t.logUserReturnIsKnown(timestamp, realm, username, type); + } + } +} diff --git a/src/main/java/org/caosdb/server/database/backend/transaction/RetrieveEntityACLTransaction.java b/src/main/java/org/caosdb/server/database/backend/transaction/RetrieveEntityACLTransaction.java new file mode 100644 index 0000000000000000000000000000000000000000..9cb96112532fe249fd81c3e8d10d85ca900293d9 --- /dev/null +++ b/src/main/java/org/caosdb/server/database/backend/transaction/RetrieveEntityACLTransaction.java @@ -0,0 +1,71 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.database.backend.transaction; + +import org.caosdb.server.database.CacheableBackendTransaction; +import org.caosdb.server.database.backend.interfaces.RetrieveEntityACLImpl; +import org.caosdb.server.database.exceptions.TransactionException; +import org.caosdb.server.database.proto.VerySparseEntity; +import org.caosdb.server.permissions.EntityACL; + +public class RetrieveEntityACLTransaction + extends CacheableBackendTransaction<Integer, VerySparseEntity> { + + private Integer id; + private EntityACL entityAcl; + + public RetrieveEntityACLTransaction(Integer id) { + // TODO + super(null); + this.id = id; + } + + @Override + public VerySparseEntity executeNoCache() throws TransactionException { + RetrieveEntityACLImpl t = getImplementation(RetrieveEntityACLImpl.class); + return t.execute(getKey()); + } + + @Override + protected void process(VerySparseEntity t) throws TransactionException { + this.entityAcl = EntityACL.fromJSON(t.acl); + } + + @Override + protected Integer getKey() { + return id; + } + + public EntityACL getEntityAcl() { + return entityAcl; + } + + public RetrieveEntityACLTransaction reuse(Integer id) { + this.id = id; + this.entityAcl = null; + return this; + } + + public static void removeCached(Integer id) { + // TODO + } +} diff --git a/src/main/java/org/caosdb/server/database/backend/transaction/RetrieveRole.java b/src/main/java/org/caosdb/server/database/backend/transaction/RetrieveRole.java index 1e855663590d85610860fcee246a4f1ed78a31b2..f4059832095acc38d3c65b828412c09cc58b3194 100644 --- a/src/main/java/org/caosdb/server/database/backend/transaction/RetrieveRole.java +++ b/src/main/java/org/caosdb/server/database/backend/transaction/RetrieveRole.java @@ -24,6 +24,7 @@ */ package org.caosdb.server.database.backend.transaction; +import java.util.Set; import org.apache.commons.jcs.access.behavior.ICacheAccess; import org.caosdb.server.accessControl.Role; import org.caosdb.server.caching.Cache; @@ -66,4 +67,8 @@ public class RetrieveRole extends CacheableBackendTransaction<String, Role> { public static void removeCached(final String name) { cache.remove(name); } + + public static void removeCached(Set<String> roles) { + roles.forEach(RetrieveRole::removeCached); + } } diff --git a/src/main/java/org/caosdb/server/database/backend/transaction/UpdateSparseEntity.java b/src/main/java/org/caosdb/server/database/backend/transaction/UpdateSparseEntity.java index 8548fb0477de9d8b52b18b8132af15295dbc9353..837f64b32ca4cd6f035b74d13ee116205c7e82bc 100644 --- a/src/main/java/org/caosdb/server/database/backend/transaction/UpdateSparseEntity.java +++ b/src/main/java/org/caosdb/server/database/backend/transaction/UpdateSparseEntity.java @@ -4,8 +4,8 @@ * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen - * Copyright (C) 2019 IndiScale GmbH - * Copyright (C) 2019 Timm Fitschen (t.fitschen@indiscale.com) + * Copyright (C) 2019, 2021 IndiScale GmbH + * Copyright (C) 2019, 2021 Timm Fitschen (t.fitschen@indiscale.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -41,6 +41,7 @@ public class UpdateSparseEntity extends BackendTransaction { @Override public void execute() throws TransactionException { + RetrieveEntityACLTransaction.removeCached(this.entity.getId()); RetrieveSparseEntity.removeCached(this.entity); if (entity.hasFileProperties()) { GetFileRecordByPath.removeCached(this.entity.getFileProperties().getPath()); diff --git a/src/main/java/org/caosdb/server/database/backend/transaction/UpdateUserRoles.java b/src/main/java/org/caosdb/server/database/backend/transaction/UpdateUserRoles.java index 66b3cb8e6f03c3abde0ccaa051a1228057d973f7..bbd23aa95d3eb1bed4f2bafc78fa12d112a02169 100644 --- a/src/main/java/org/caosdb/server/database/backend/transaction/UpdateUserRoles.java +++ b/src/main/java/org/caosdb/server/database/backend/transaction/UpdateUserRoles.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,11 +19,11 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.database.backend.transaction; -import java.util.HashSet; +import java.util.Set; import org.caosdb.server.accessControl.Principal; import org.caosdb.server.database.BackendTransaction; import org.caosdb.server.database.backend.interfaces.UpdateUserRolesImpl; @@ -31,10 +32,10 @@ import org.caosdb.server.database.exceptions.TransactionException; public class UpdateUserRoles extends BackendTransaction { private final String user; - private final HashSet<String> roles; + private final Set<String> roles; private final String realm; - public UpdateUserRoles(final String realm, final String user, final HashSet<String> roles) { + public UpdateUserRoles(final String realm, final String user, final Set<String> roles) { this.realm = realm; this.user = user; this.roles = roles; diff --git a/src/main/java/org/caosdb/server/database/proto/ProtoUser.java b/src/main/java/org/caosdb/server/database/proto/ProtoUser.java index cafa32d2580c8a09a97e1cd3ee48c2ec59a454cf..643f4250216c7829c8218113a8842ff139b313ec 100644 --- a/src/main/java/org/caosdb/server/database/proto/ProtoUser.java +++ b/src/main/java/org/caosdb/server/database/proto/ProtoUser.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,24 +19,24 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.database.proto; import java.io.Serializable; -import java.util.Set; +import java.util.HashSet; import org.caosdb.server.accessControl.UserStatus; public class ProtoUser implements Serializable { public ProtoUser() {} - private static final long serialVersionUID = -2704114543883567439L; + private static final long serialVersionUID = 5381234723597234L; public UserStatus status = null; public String name = null; public String email = null; public Integer entity = null; public String realm = null; - public Set<String> roles = null; + public HashSet<String> roles = null; } diff --git a/src/main/java/org/caosdb/server/entity/Message.java b/src/main/java/org/caosdb/server/entity/Message.java index 4c89e1ee23839483f7bed1099c52e8c24a56a6a2..fca6024561ede97c1b5520bc6a07f08f30f7a76a 100644 --- a/src/main/java/org/caosdb/server/entity/Message.java +++ b/src/main/java/org/caosdb/server/entity/Message.java @@ -19,6 +19,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ + package org.caosdb.server.entity; import java.util.HashMap; @@ -35,6 +36,11 @@ public class Message extends Exception implements Comparable<Message>, ToElement private final String description; private final String body; + @Override + public String getMessage() { + return description; + } + @Deprecated private static final Map<String, String> legacy_codes_mapping = new HashMap<>(); static void init() { diff --git a/src/main/java/org/caosdb/server/grpc/AccessControlManagementServiceImpl.java b/src/main/java/org/caosdb/server/grpc/AccessControlManagementServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..88429828f27ac843903cfcfc801847c35eedb607 --- /dev/null +++ b/src/main/java/org/caosdb/server/grpc/AccessControlManagementServiceImpl.java @@ -0,0 +1,602 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.grpc; + +import io.grpc.Status; +import io.grpc.StatusException; +import io.grpc.stub.StreamObserver; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authz.UnauthorizedException; +import org.apache.shiro.subject.Subject; +import org.caosdb.api.acm.v1alpha1.AccessControlManagementServiceGrpc.AccessControlManagementServiceImplBase; +import org.caosdb.api.acm.v1alpha1.CreateSingleRoleRequest; +import org.caosdb.api.acm.v1alpha1.CreateSingleRoleResponse; +import org.caosdb.api.acm.v1alpha1.CreateSingleUserRequest; +import org.caosdb.api.acm.v1alpha1.CreateSingleUserResponse; +import org.caosdb.api.acm.v1alpha1.DeleteSingleRoleRequest; +import org.caosdb.api.acm.v1alpha1.DeleteSingleRoleResponse; +import org.caosdb.api.acm.v1alpha1.DeleteSingleUserRequest; +import org.caosdb.api.acm.v1alpha1.DeleteSingleUserResponse; +import org.caosdb.api.acm.v1alpha1.EmailSetting; +import org.caosdb.api.acm.v1alpha1.EntitySetting; +import org.caosdb.api.acm.v1alpha1.ListKnownPermissionsRequest; +import org.caosdb.api.acm.v1alpha1.ListKnownPermissionsResponse; +import org.caosdb.api.acm.v1alpha1.ListRoleItem; +import org.caosdb.api.acm.v1alpha1.ListRolesRequest; +import org.caosdb.api.acm.v1alpha1.ListRolesResponse; +import org.caosdb.api.acm.v1alpha1.ListUsersRequest; +import org.caosdb.api.acm.v1alpha1.ListUsersResponse; +import org.caosdb.api.acm.v1alpha1.PermissionDescription; +import org.caosdb.api.acm.v1alpha1.PermissionRule; +import org.caosdb.api.acm.v1alpha1.RetrieveSingleRoleRequest; +import org.caosdb.api.acm.v1alpha1.RetrieveSingleRoleResponse; +import org.caosdb.api.acm.v1alpha1.RetrieveSingleUserRequest; +import org.caosdb.api.acm.v1alpha1.RetrieveSingleUserResponse; +import org.caosdb.api.acm.v1alpha1.RoleCapabilities; +import org.caosdb.api.acm.v1alpha1.RolePermissions; +import org.caosdb.api.acm.v1alpha1.UpdateSingleRoleRequest; +import org.caosdb.api.acm.v1alpha1.UpdateSingleRoleResponse; +import org.caosdb.api.acm.v1alpha1.UpdateSingleUserRequest; +import org.caosdb.api.acm.v1alpha1.UpdateSingleUserResponse; +import org.caosdb.api.acm.v1alpha1.User; +import org.caosdb.api.acm.v1alpha1.UserCapabilities; +import org.caosdb.api.acm.v1alpha1.UserPermissions; +import org.caosdb.api.acm.v1alpha1.UserStatus; +import org.caosdb.server.accessControl.ACMPermissions; +import org.caosdb.server.accessControl.AuthenticationUtils; +import org.caosdb.server.accessControl.Role; +import org.caosdb.server.accessControl.UserSources; +import org.caosdb.server.database.proto.ProtoUser; +import org.caosdb.server.transaction.DeleteRoleTransaction; +import org.caosdb.server.transaction.DeleteUserTransaction; +import org.caosdb.server.transaction.InsertRoleTransaction; +import org.caosdb.server.transaction.InsertUserTransaction; +import org.caosdb.server.transaction.ListRolesTransaction; +import org.caosdb.server.transaction.ListUsersTransaction; +import org.caosdb.server.transaction.RetrieveRoleTransaction; +import org.caosdb.server.transaction.RetrieveUserTransaction; +import org.caosdb.server.transaction.UpdateRoleTransaction; +import org.caosdb.server.transaction.UpdateUserTransaction; +import org.caosdb.server.utils.ServerMessages; + +public class AccessControlManagementServiceImpl extends AccessControlManagementServiceImplBase { + + /////////////////////////////////// CONVERTERS + + private ProtoUser convert(User user) { + ProtoUser result = new ProtoUser(); + result.realm = user.getRealm(); + result.name = user.getName(); + result.email = user.hasEmailSetting() ? user.getEmailSetting().getEmail() : null; + result.status = convert(user.getStatus()); + result.roles = new HashSet<String>(); + if (user.getRolesCount() >= 0) { + user.getRolesList().forEach(result.roles::add); + } + return result; + } + + private org.caosdb.server.accessControl.UserStatus convert(UserStatus status) { + switch (status) { + case USER_STATUS_ACTIVE: + return org.caosdb.server.accessControl.UserStatus.ACTIVE; + case USER_STATUS_INACTIVE: + return org.caosdb.server.accessControl.UserStatus.INACTIVE; + default: + break; + } + return org.caosdb.server.accessControl.UserStatus.INACTIVE; + } + + private ListUsersResponse convertUsers(List<ProtoUser> users) { + ListUsersResponse.Builder response = ListUsersResponse.newBuilder(); + users.forEach( + user -> { + response.addUsers(convert(user)); + }); + + return response.build(); + } + + private User.Builder convert(ProtoUser user) { + User.Builder result = User.newBuilder(); + result.setRealm(user.realm); + result.setName(user.name); + if (user.status != null) result.setStatus(convert(user.status)); + if (user.email != null) { + result.setEmailSetting(EmailSetting.newBuilder().setEmail(user.email)); + } + if (user.entity != null) { + result.setEntitySetting( + EntitySetting.newBuilder().setEntityId(Integer.toString(user.entity))); + } + if (user.roles != null && !user.roles.isEmpty()) { + result.addAllRoles(user.roles); + } + return result; + } + + private UserStatus convert(org.caosdb.server.accessControl.UserStatus status) { + switch (status) { + case ACTIVE: + return UserStatus.USER_STATUS_ACTIVE; + case INACTIVE: + return UserStatus.USER_STATUS_INACTIVE; + default: + return UserStatus.USER_STATUS_UNSPECIFIED; + } + } + + private Role convert(org.caosdb.api.acm.v1alpha1.Role role) { + Role result = new Role(); + + result.name = role.getName(); + result.description = role.getDescription(); + result.permission_rules = convertPermissionRules(role.getPermissionRulesList()); + return result; + } + + private LinkedList<org.caosdb.server.permissions.PermissionRule> convertPermissionRules( + List<PermissionRule> permissionRulesList) { + LinkedList<org.caosdb.server.permissions.PermissionRule> result = new LinkedList<>(); + permissionRulesList.forEach((r) -> result.add(convert(r))); + return result; + } + + private org.caosdb.server.permissions.PermissionRule convert(PermissionRule r) { + boolean grant = r.getGrant(); + boolean priority = r.getPriority(); + String permission = r.getPermission(); + return new org.caosdb.server.permissions.PermissionRule(grant, priority, permission); + } + + private ListRolesResponse convert(List<Role> roles) { + ListRolesResponse.Builder response = ListRolesResponse.newBuilder(); + roles.forEach( + role -> { + response.addRoles(convert(role, getRolePermissions(role), getRoleCapabilities(role))); + }); + + return response.build(); + } + + private ListRoleItem convert( + Role role, + Iterable<? extends RolePermissions> rolePermissions, + Iterable<? extends RoleCapabilities> roleCapabilities) { + return ListRoleItem.newBuilder() + .setRole(convert(role)) + .addAllCapabilities(roleCapabilities) + .addAllPermissions(rolePermissions) + .build(); + } + + private org.caosdb.api.acm.v1alpha1.Role.Builder convert(Role role) { + org.caosdb.api.acm.v1alpha1.Role.Builder result = org.caosdb.api.acm.v1alpha1.Role.newBuilder(); + result.setDescription(role.description); + result.setName(role.name); + if (role.permission_rules != null) result.addAllPermissionRules(convert(role.permission_rules)); + return result; + } + + private PermissionRule convert(org.caosdb.server.permissions.PermissionRule rule) { + PermissionRule.Builder result = PermissionRule.newBuilder(); + result.setGrant(rule.isGrant()); + result.setPriority(rule.isPriority()); + result.setPermission(rule.getPermission()); + return result.build(); + } + + private Iterable<PermissionRule> convert( + LinkedList<org.caosdb.server.permissions.PermissionRule> permission_rules) { + + List<PermissionRule> result = new LinkedList<>(); + permission_rules.forEach( + (rule) -> { + result.add(convert(rule)); + }); + return result; + } + + ////////////////////////////////////// RPC Methods (Implementation) + + private ListKnownPermissionsResponse listKnownPermissions(ListKnownPermissionsRequest request) { + ListKnownPermissionsResponse.Builder builder = ListKnownPermissionsResponse.newBuilder(); + builder.addAllPermissions(listKnownPermissions()); + return builder.build(); + } + + private Iterable<PermissionDescription> listKnownPermissions() { + List<PermissionDescription> result = new LinkedList<>(); + for (ACMPermissions p : ACMPermissions.getAll()) { + result.add( + PermissionDescription.newBuilder() + .setPermission(p.toString()) + .setDescription(p.getDescription()) + .build()); + } + return result; + } + + ////////////////// ... for roles + + private ListRolesResponse listRolesTransaction(ListRolesRequest request) throws Exception { + ListRolesTransaction transaction = new ListRolesTransaction(); + transaction.execute(); + List<Role> roles = transaction.getRoles(); + + return convert(roles); + } + + private CreateSingleRoleResponse createSingleRoleTransaction(CreateSingleRoleRequest request) + throws Exception { + Role role = convert(request.getRole()); + InsertRoleTransaction transaction = new InsertRoleTransaction(role); + transaction.execute(); + + return CreateSingleRoleResponse.newBuilder().build(); + } + + private RetrieveSingleRoleResponse retrieveSingleRoleTransaction( + RetrieveSingleRoleRequest request) throws Exception { + RetrieveRoleTransaction transaction = new RetrieveRoleTransaction(request.getName()); + transaction.execute(); + + Role role = transaction.getRole(); + RetrieveSingleRoleResponse.Builder builder = + RetrieveSingleRoleResponse.newBuilder().setRole(convert(transaction.getRole())); + if (role.users != null && !role.users.isEmpty()) + role.users.forEach( + (u) -> { + builder.addUsers(convert(u)); + }); + return builder + .addAllPermissions(getRolePermissions(role)) + .addAllCapabilities(getRoleCapabilities(role)) + .build(); + } + + /** What can be done with this role. */ + private Iterable<? extends RoleCapabilities> getRoleCapabilities(Role role) { + List<RoleCapabilities> result = new LinkedList<>(); + if (org.caosdb.server.permissions.Role.ADMINISTRATION.toString().equals(role.name)) { + // administration cannot be deleted and the permissions cannot be changed (from *) + result.add(RoleCapabilities.ROLE_CAPABILITIES_ASSIGN); + } else if (org.caosdb.server.permissions.Role.ANONYMOUS_ROLE.toString().equals(role.name)) { + // anonymous cannot be deleted or assigned to any user + result.add(RoleCapabilities.ROLE_CAPABILITIES_UPDATE_PERMISSION_RULES); + } else { + result.add(RoleCapabilities.ROLE_CAPABILITIES_ASSIGN); + result.add(RoleCapabilities.ROLE_CAPABILITIES_DELETE); + result.add(RoleCapabilities.ROLE_CAPABILITIES_UPDATE_PERMISSION_RULES); + } + return result; + } + + /** The permissions of the current user w.r.t. this role. */ + private Iterable<? extends RolePermissions> getRolePermissions(Role role) { + List<RolePermissions> result = new LinkedList<>(); + Subject current_user = SecurityUtils.getSubject(); + if (current_user.isPermitted(ACMPermissions.PERMISSION_DELETE_ROLE(role.name))) { + result.add(RolePermissions.ROLE_PERMISSIONS_DELETE); + } + if (current_user.isPermitted(ACMPermissions.PERMISSION_UPDATE_ROLE_DESCRIPTION(role.name))) { + result.add(RolePermissions.ROLE_PERMISSIONS_UPDATE_DESCRIPTION); + } + if (current_user.isPermitted(ACMPermissions.PERMISSION_UPDATE_ROLE_PERMISSIONS(role.name))) { + result.add(RolePermissions.ROLE_PERMISSIONS_UPDATE_PERMISSION_RULES); + } + if (current_user.isPermitted(ACMPermissions.PERMISSION_ASSIGN_ROLE(role.name))) { + result.add(RolePermissions.ROLE_PERMISSIONS_ASSIGN); + } + return result; + } + + private DeleteSingleRoleResponse deleteSingleRoleTransaction(DeleteSingleRoleRequest request) + throws Exception { + DeleteRoleTransaction transaction = new DeleteRoleTransaction(request.getName()); + transaction.execute(); + + return DeleteSingleRoleResponse.newBuilder().build(); + } + + private UpdateSingleRoleResponse updateSingleRoleTransaction(UpdateSingleRoleRequest request) + throws Exception { + Role role = convert(request.getRole()); + UpdateRoleTransaction transaction = new UpdateRoleTransaction(role); + transaction.execute(); + return UpdateSingleRoleResponse.newBuilder().build(); + } + + ////////////////// ... for users + + private ListUsersResponse listUsersTransaction(ListUsersRequest request) throws Exception { + ListUsersTransaction transaction = new ListUsersTransaction(); + transaction.execute(); + List<ProtoUser> users = transaction.getUsers(); + return convertUsers(users); + } + + private CreateSingleUserResponse createSingleUserTransaction(CreateSingleUserRequest request) + throws Exception { + ProtoUser user = convert(request.getUser()); + InsertUserTransaction transaction = + new InsertUserTransaction( + user, request.hasPasswordSetting() ? request.getPasswordSetting().getPassword() : null); + transaction.execute(); + + return CreateSingleUserResponse.newBuilder().build(); + } + + private UpdateSingleUserResponse updateSingleUserTransaction(UpdateSingleUserRequest request) + throws Exception { + ProtoUser user = convert(request.getUser()); + UpdateUserTransaction transaction = + new UpdateUserTransaction( + user, request.hasPasswordSetting() ? request.getPasswordSetting().getPassword() : null); + transaction.execute(); + + return UpdateSingleUserResponse.newBuilder().build(); + } + + private RetrieveSingleUserResponse retrieveSingleUserTransaction( + RetrieveSingleUserRequest request) throws Exception { + RetrieveUserTransaction transaction = + new RetrieveUserTransaction(request.getRealm(), request.getName()); + transaction.execute(); + ProtoUser user = transaction.getUser(); + + return RetrieveSingleUserResponse.newBuilder() + .setUser(convert(user)) + .addAllPermissions(getUserPermissions(user.realm, user.name)) + .addAllCapabilities(getUserCapabilities(user)) + .build(); + } + + private Iterable<? extends UserCapabilities> getUserCapabilities(ProtoUser user) { + LinkedList<UserCapabilities> result = new LinkedList<>(); + if (user.realm.equals(UserSources.getInternalRealm().getName())) { + result.add(UserCapabilities.USER_CAPABILITIES_DELETE); + result.add(UserCapabilities.USER_CAPABILITIES_UPDATE_PASSWORD); + } + return result; + } + + private Iterable<? extends UserPermissions> getUserPermissions(String realm, String name) { + LinkedList<UserPermissions> result = new LinkedList<>(); + Subject current_user = SecurityUtils.getSubject(); + if (current_user.isPermitted(ACMPermissions.PERMISSION_DELETE_USER(realm, name))) { + result.add(UserPermissions.USER_PERMISSIONS_DELETE); + } + if (current_user.isPermitted(ACMPermissions.PERMISSION_UPDATE_USER_EMAIL(realm, name))) { + result.add(UserPermissions.USER_PERMISSIONS_UPDATE_EMAIL); + } + if (current_user.isPermitted(ACMPermissions.PERMISSION_UPDATE_USER_STATUS(realm, name))) { + result.add(UserPermissions.USER_PERMISSIONS_UPDATE_STATUS); + } + if (current_user.isPermitted(ACMPermissions.PERMISSION_UPDATE_USER_ROLES(realm, name))) { + result.add(UserPermissions.USER_PERMISSIONS_UPDATE_ROLES); + } + if (current_user.isPermitted(ACMPermissions.PERMISSION_UPDATE_USER_PASSWORD(realm, name))) { + result.add(UserPermissions.USER_PERMISSIONS_UPDATE_PASSWORD); + } + return result; + } + + private DeleteSingleUserResponse deleteSingleUserTransaction(DeleteSingleUserRequest request) + throws Exception { + DeleteUserTransaction transaction = + new DeleteUserTransaction(request.getRealm(), request.getName()); + transaction.execute(); + + return DeleteSingleUserResponse.newBuilder().build(); + } + + ///////////////////////////////////// RPC Methods (API) + + @Override + public void listUsers( + ListUsersRequest request, StreamObserver<ListUsersResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final ListUsersResponse response = listUsersTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void listRoles( + ListRolesRequest request, StreamObserver<ListRolesResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final ListRolesResponse response = listRolesTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void createSingleRole( + CreateSingleRoleRequest request, StreamObserver<CreateSingleRoleResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final CreateSingleRoleResponse response = createSingleRoleTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void retrieveSingleRole( + RetrieveSingleRoleRequest request, + StreamObserver<RetrieveSingleRoleResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final RetrieveSingleRoleResponse response = retrieveSingleRoleTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void createSingleUser( + CreateSingleUserRequest request, StreamObserver<CreateSingleUserResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final CreateSingleUserResponse response = createSingleUserTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void updateSingleUser( + UpdateSingleUserRequest request, StreamObserver<UpdateSingleUserResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final UpdateSingleUserResponse response = updateSingleUserTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void retrieveSingleUser( + RetrieveSingleUserRequest request, + StreamObserver<RetrieveSingleUserResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final RetrieveSingleUserResponse response = retrieveSingleUserTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void deleteSingleUser( + DeleteSingleUserRequest request, StreamObserver<DeleteSingleUserResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final DeleteSingleUserResponse response = deleteSingleUserTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void deleteSingleRole( + DeleteSingleRoleRequest request, StreamObserver<DeleteSingleRoleResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final DeleteSingleRoleResponse response = deleteSingleRoleTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void updateSingleRole( + UpdateSingleRoleRequest request, StreamObserver<UpdateSingleRoleResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final UpdateSingleRoleResponse response = updateSingleRoleTransaction(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + @Override + public void listKnownPermissions( + ListKnownPermissionsRequest request, + StreamObserver<ListKnownPermissionsResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final ListKnownPermissionsResponse response = listKnownPermissions(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + handleException(responseObserver, e); + } + } + + public static void handleException(StreamObserver<?> responseObserver, Exception e) { + String description = e.getMessage(); + if (description == null || description.isBlank()) { + description = "Unknown Error. Please Report!"; + } + if (e instanceof UnauthorizedException) { + Subject subject = SecurityUtils.getSubject(); + if (AuthenticationUtils.isAnonymous(subject)) { + responseObserver.onError(new StatusException(AuthInterceptor.PLEASE_LOG_IN)); + return; + } else { + responseObserver.onError( + new StatusException( + Status.PERMISSION_DENIED.withCause(e).withDescription(description))); + return; + } + } else if (e == ServerMessages.ROLE_DOES_NOT_EXIST + || e == ServerMessages.ACCOUNT_DOES_NOT_EXIST) { + responseObserver.onError( + new StatusException(Status.NOT_FOUND.withDescription(description).withCause(e))); + return; + } + e.printStackTrace(); + responseObserver.onError( + new StatusException(Status.UNKNOWN.withDescription(description).withCause(e))); + } +} diff --git a/src/main/java/org/caosdb/server/grpc/AuthInterceptor.java b/src/main/java/org/caosdb/server/grpc/AuthInterceptor.java index 0b359835c293a9b1ad95b296f1301de93a6fbbfa..ce8a62210d3c8e849397600fc112cd3103f15df4 100644 --- a/src/main/java/org/caosdb/server/grpc/AuthInterceptor.java +++ b/src/main/java/org/caosdb/server/grpc/AuthInterceptor.java @@ -1,7 +1,31 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + package org.caosdb.server.grpc; +import static org.caosdb.server.utils.Utils.URLDecodeWithUTF8; + import io.grpc.Context; import io.grpc.Contexts; +import io.grpc.ForwardingServerCall; import io.grpc.Metadata; import io.grpc.Metadata.Key; import io.grpc.ServerCall; @@ -10,14 +34,22 @@ import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.Status; import java.util.Base64; +import java.util.function.Predicate; +import java.util.regex.Pattern; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.subject.Subject; +import org.apache.shiro.util.ThreadContext; import org.caosdb.server.CaosDBServer; import org.caosdb.server.ServerProperties; import org.caosdb.server.accessControl.AnonymousAuthenticationToken; +import org.caosdb.server.accessControl.AuthenticationUtils; import org.caosdb.server.accessControl.RealmUsernamePasswordToken; +import org.caosdb.server.accessControl.SelfValidatingAuthenticationToken; +import org.caosdb.server.accessControl.SessionToken; import org.caosdb.server.accessControl.UserSources; +import org.caosdb.server.utils.Utils; +import org.restlet.data.CookieSetting; /** * ServerInterceptor for Authentication. If the authentication succeeds or if the caller is @@ -26,12 +58,35 @@ import org.caosdb.server.accessControl.UserSources; * * @author Timm Fitschen <t.fitschen@indiscale.com> */ -class AuthInterceptor implements ServerInterceptor { +public class AuthInterceptor implements ServerInterceptor { - private static final Key<String> AUTHENTICATION_HEADER = + public static final Status PLEASE_LOG_IN = + Status.UNAUTHENTICATED.withDescription("Please log in!"); + public static final Key<String> AUTHENTICATION_HEADER = Key.of("authentication", Metadata.ASCII_STRING_MARSHALLER); - private static final Context.Key<Subject> SUBJECT_KEY = Context.key("subject"); - private static final String BASIC_SCHEME_PREFIX = "Basic "; + public static final Key<String> AUTHORIZATION_HEADER = + Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER); + public static final Key<String> COOKIE_HEADER = + Key.of("Cookie", Metadata.ASCII_STRING_MARSHALLER); + public static final Context.Key<Subject> SUBJECT_KEY = Context.key("subject"); + public static final String BASIC_SCHEME_PREFIX = "Basic "; + public static final Pattern SESSION_TOKEN_COOKIE_PREFIX_PATTERN = + Pattern.compile("^\\s*" + AuthenticationUtils.SESSION_TOKEN_COOKIE + "\\s*=\\s*"); + public static final Predicate<String> SESSION_TOKEN_COOKIE_PREFIX_PREDICATE = + SESSION_TOKEN_COOKIE_PREFIX_PATTERN.asPredicate(); + + @SuppressWarnings("unused") + public static Subject bindSubject() { + Subject subject = (Subject) SUBJECT_KEY.get(); + ThreadContext.bind(subject); + return subject; + } + + public final Metadata expiredSessionMetadata() { + Metadata metadata = new Metadata(); + metadata.put(CookieSetter.SET_COOKIE, CookieSetter.EXPIRED_SESSION_COOKIE); + return metadata; + } /** * A no-op listener. This class is used for failed authentications. We couldn't return a null * instead because the documentation of the {@link ServerInterceptor} explicitely forbids it. @@ -56,8 +111,9 @@ class AuthInterceptor implements ServerInterceptor { final String username = split[0]; final String password = split[1]; final RealmUsernamePasswordToken token = - new RealmUsernamePasswordToken(UserSources.getDefaultRealm(), username, password); - final org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject(); + new RealmUsernamePasswordToken( + UserSources.guessRealm(username, UserSources.getDefaultRealm()), username, password); + final Subject subject = SecurityUtils.getSubject(); subject.login(token); return subject; } @@ -67,25 +123,75 @@ class AuthInterceptor implements ServerInterceptor { final ServerCall<ReqT, RespT> call, final Metadata headers, final ServerCallHandler<ReqT, RespT> next) { - final String authentication = headers.get(AUTHENTICATION_HEADER); + ThreadContext.remove(); + + String authentication = headers.get(AUTHENTICATION_HEADER); + if (authentication == null) { + authentication = headers.get(AUTHORIZATION_HEADER); + } + if (authentication == null) { + authentication = getSessionToken(headers.get(COOKIE_HEADER)); + } Status status = Status.UNKNOWN.withDescription( "An unknown error occured during authentication. Please report a bug."); if (authentication == null && isAuthOptional()) { return anonymous(call, headers, next); } else if (authentication == null) { - status = Status.UNAUTHENTICATED.withDescription("Please login."); + status = PLEASE_LOG_IN; } else if (authentication.startsWith(BASIC_SCHEME_PREFIX)) { return basicAuth(authentication.substring(BASIC_SCHEME_PREFIX.length()), call, headers, next); + } else if (SESSION_TOKEN_COOKIE_PREFIX_PREDICATE.test(authentication)) { + return sessionTokenAuth( + SESSION_TOKEN_COOKIE_PREFIX_PATTERN.split(authentication, 2)[1], call, headers, next); } else { - status = - Status.UNAUTHENTICATED.withDescription( - "Unsupported authentication scheme: " + authentication.split(" ", 2)[0]); + status = Status.UNAUTHENTICATED.withDescription("Unsupported authentication scheme."); } - call.close(status, new Metadata()); + call.close(status, expiredSessionMetadata()); return new NoOpListener<ReqT>(); } + private String getSessionToken(String cookies) { + if (cookies != null) + for (String cookie : cookies.split("\\s*;\\s*")) { + if (SESSION_TOKEN_COOKIE_PREFIX_PREDICATE.test(cookie)) { + return cookie; + } + } + return null; + } + + /** + * Login via AuthenticationToken and add the resulting subject to the call context. + * + * @see #updateContext(Subject, ServerCall, Metadata, ServerCallHandler) for more information. + */ + private <ReqT, RespT> Listener<ReqT> sessionTokenAuth( + String sessionTokenCookie, + ServerCall<ReqT, RespT> call, + Metadata headers, + ServerCallHandler<ReqT, RespT> next) { + try { + final String tokenString = URLDecodeWithUTF8(sessionTokenCookie.split(";")[0]); + + final Subject subject = sessionTokenAuth(tokenString); + return updateContext(subject, call, headers, next, "sessionToken: " + tokenString); + } catch (final AuthenticationException e) { + final Status status = + Status.UNAUTHENTICATED.withDescription( + "Authentication failed. SessionToken was invalid."); + call.close(status, expiredSessionMetadata()); + return new NoOpListener<ReqT>(); + } + } + + /** Login via AuthenticationToken and return the logged-in subject. */ + private Subject sessionTokenAuth(String tokenString) { + Subject subject = SecurityUtils.getSubject(); + subject.login(SelfValidatingAuthenticationToken.parse(tokenString)); + return subject; + } + /** * Login via username and password with the basic authentication scheme and add the resulting * subject to the call context. @@ -99,12 +205,17 @@ class AuthInterceptor implements ServerInterceptor { final ServerCallHandler<ReqT, RespT> next) { try { final Subject subject = basicAuth(base64); - return updateContext(subject, call, headers, next); + return updateContext( + subject, + call, + headers, + next, + "basic: " + base64 + " thread: " + Thread.currentThread().getName()); } catch (final AuthenticationException e) { final Status status = Status.UNAUTHENTICATED.withDescription( "Authentication failed. Username or password wrong."); - call.close(status, new Metadata()); + call.close(status, expiredSessionMetadata()); return new NoOpListener<ReqT>(); } } @@ -119,7 +230,7 @@ class AuthInterceptor implements ServerInterceptor { final Metadata headers, final ServerCallHandler<ReqT, RespT> next) { final Subject subject = anonymous(); - return updateContext(subject, call, headers, next); + return updateContext(subject, call, headers, next, "anonymous"); } /** Login as anonymous. */ @@ -137,9 +248,66 @@ class AuthInterceptor implements ServerInterceptor { final Subject subject, final ServerCall<ReqT, RespT> call, final Metadata headers, - final ServerCallHandler<ReqT, RespT> next) { - final Context context = Context.current(); - context.withValue(SUBJECT_KEY, subject); - return Contexts.interceptCall(Context.current(), call, headers, next); + final ServerCallHandler<ReqT, RespT> next, + final String tag) { + final Context context = Context.current().withValue(SUBJECT_KEY, subject); + ServerCall<ReqT, RespT> cookieSetter = new CookieSetter<>(call, subject, tag); + return Contexts.interceptCall(context, cookieSetter, headers, next); + } +} + +final class CookieSetter<ReqT, RespT> + extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> { + public static final String EXPIRED_SESSION_COOKIE = + AuthenticationUtils.SESSION_TOKEN_COOKIE + + "=expired; Path=/; HttpOnly; SameSite=Strict; Max-Age=0"; + public static final Key<String> SET_COOKIE = + Key.of("Set-Cookie", Metadata.ASCII_STRING_MARSHALLER); + private Subject subject; + + protected CookieSetter(ServerCall<ReqT, RespT> delegate, Subject subject, String tag) { + super(delegate); + this.subject = subject; + } + + String getSessionTimeoutSeconds() { + int ms = + Integer.parseInt(CaosDBServer.getServerProperty(ServerProperties.KEY_SESSION_TIMEOUT_MS)); + int seconds = (int) Math.floor(ms / 1000); + return Integer.toString(seconds); + } + + @Override + public void sendHeaders(Metadata headers) { + setSessionCookies(headers); + super.sendHeaders(headers); + }; + + private void setSessionCookies(Metadata headers) { + // if authenticated as a normal user: generate and set session cookie. + if (subject.isAuthenticated() + && !AnonymousAuthenticationToken.PRINCIPAL.equals(subject.getPrincipal())) { + final SessionToken sessionToken = SessionToken.generate(subject); + if (sessionToken != null && sessionToken.isValid()) { + + final CookieSetting sessionTokenCookie = + AuthenticationUtils.createSessionTokenCookie(sessionToken); + if (sessionTokenCookie != null) { + // TODO add "Secure;" to cookie setting + headers.put( + SET_COOKIE, + AuthenticationUtils.SESSION_TOKEN_COOKIE + + "=" + + Utils.URLEncodeWithUTF8(sessionToken.toString()) + + "; Path=/; HttpOnly; SameSite=Strict; Max-Age=" + + getSessionTimeoutSeconds()); + } + } + } else if (AnonymousAuthenticationToken.PRINCIPAL.equals(subject.getPrincipal())) { + // this is anonymous, do nothing + headers.toString(); + } else { + headers.put(SET_COOKIE, EXPIRED_SESSION_COOKIE); + } } } diff --git a/src/main/java/org/caosdb/server/grpc/CaosDBToGrpcConverters.java b/src/main/java/org/caosdb/server/grpc/CaosDBToGrpcConverters.java index aa6a260dfb52b5e36520d130219632d26095b0d1..d9ac193c104c9cb643897a0cabc97ff2f42cbb9a 100644 --- a/src/main/java/org/caosdb/server/grpc/CaosDBToGrpcConverters.java +++ b/src/main/java/org/caosdb/server/grpc/CaosDBToGrpcConverters.java @@ -1,15 +1,42 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + package org.caosdb.server.grpc; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.TimeZone; import org.caosdb.api.entity.v1.AtomicDataType; import org.caosdb.api.entity.v1.CollectionValues; import org.caosdb.api.entity.v1.DataType; import org.caosdb.api.entity.v1.Entity; import org.caosdb.api.entity.v1.Entity.Builder; +import org.caosdb.api.entity.v1.EntityACL; +import org.caosdb.api.entity.v1.EntityAclPermission; +import org.caosdb.api.entity.v1.EntityPermissionRule; +import org.caosdb.api.entity.v1.EntityPermissionRuleCapability; import org.caosdb.api.entity.v1.EntityResponse; import org.caosdb.api.entity.v1.EntityRole; +import org.caosdb.api.entity.v1.FileDescriptor; import org.caosdb.api.entity.v1.Importance; import org.caosdb.api.entity.v1.ListDataType; import org.caosdb.api.entity.v1.MessageCode; @@ -36,6 +63,7 @@ import org.caosdb.server.datatype.ReferenceValue; import org.caosdb.server.datatype.TextDatatype; import org.caosdb.server.datatype.Value; import org.caosdb.server.entity.EntityInterface; +import org.caosdb.server.entity.FileProperties; import org.caosdb.server.entity.MagicTypes; import org.caosdb.server.entity.Message; import org.caosdb.server.entity.Role; @@ -43,9 +71,17 @@ import org.caosdb.server.entity.StatementStatus; import org.caosdb.server.entity.container.ParentContainer; import org.caosdb.server.entity.container.PropertyContainer; import org.caosdb.server.entity.wrapper.Property; +import org.caosdb.server.permissions.EntityACI; +import org.caosdb.server.permissions.EntityPermission; public class CaosDBToGrpcConverters { + private TimeZone timeZone; + + public CaosDBToGrpcConverters(TimeZone timeZone) { + this.timeZone = timeZone; + } + /** Get the unit as string. */ public String getStringUnit(final EntityInterface entity) { final Iterator<Property> iterator = entity.getProperties().iterator(); @@ -98,6 +134,9 @@ public class CaosDBToGrpcConverters { if (from.hasParents()) { entityBuilder.addAllParents(convert(from.getParents())); } + if (from.hasFileProperties()) { + entityBuilder.setFileDescriptor(convert(from.getFileProperties())); + } final EntityResponse.Builder responseBuilder = EntityResponse.newBuilder(); responseBuilder.setEntity(entityBuilder); @@ -107,6 +146,13 @@ public class CaosDBToGrpcConverters { return responseBuilder; } + private FileDescriptor.Builder convert(FileProperties fileProperties) { + FileDescriptor.Builder result = FileDescriptor.newBuilder(); + result.setPath(fileProperties.getPath()); + result.setSize(fileProperties.getSize()); + return result; + } + private EntityRole convert(final Role role) { switch (role) { case RecordType: @@ -210,7 +256,7 @@ public class CaosDBToGrpcConverters { return builder; } - private ScalarValue.Builder convertScalarValue(final Value value) { + protected ScalarValue.Builder convertScalarValue(final Value value) { if (value instanceof BooleanValue) { return convertBooleanValue((BooleanValue) value); @@ -234,20 +280,20 @@ public class CaosDBToGrpcConverters { } else if (wrappedValue instanceof Integer) { return ScalarValue.newBuilder().setIntegerValue((Integer) wrappedValue); } else { - return convertStringValue(value); + return convertStringValue(value.toString()); } } - private org.caosdb.api.entity.v1.ScalarValue.Builder convertStringValue(final Value value) { - if (value.toString().isEmpty()) { + private org.caosdb.api.entity.v1.ScalarValue.Builder convertStringValue(final String value) { + if (value.isEmpty()) { return ScalarValue.newBuilder().setSpecialValue(SpecialValue.SPECIAL_VALUE_EMPTY_STRING); } - return ScalarValue.newBuilder().setStringValue(value.toString()); + return ScalarValue.newBuilder().setStringValue(value); } private org.caosdb.api.entity.v1.ScalarValue.Builder convertDateTimeInterface( final DateTimeInterface value) { - return convertStringValue(value); + return convertStringValue(value.toDateTimeString(timeZone)); } private org.caosdb.api.entity.v1.ScalarValue.Builder convertBooleanValue( @@ -256,7 +302,7 @@ public class CaosDBToGrpcConverters { } private ScalarValue.Builder convertReferenceValue(final ReferenceValue value) { - return convertStringValue(value); + return convertStringValue(value.toString()); } private org.caosdb.api.entity.v1.Value.Builder convertCollectionValue( @@ -274,6 +320,11 @@ public class CaosDBToGrpcConverters { } private ScalarValue convertScalarValue(final IndexedSingleValue v) { + if (v == null || v.getWrapped() == null) { + return ScalarValue.newBuilder() + .setSpecialValue(SpecialValue.SPECIAL_VALUE_UNSPECIFIED) + .build(); + } return convertScalarValue(v.getWrapped()).build(); } @@ -438,4 +489,56 @@ public class CaosDBToGrpcConverters { builder.addAllInfos(convert(from.getMessages(Message.MessageType.Info.toString()))); } } + + public EntityACL convertACL(EntityInterface e) { + EntityACL.Builder builder = EntityACL.newBuilder(); + builder.setId(e.getId().toString()); + if (e.hasEntityACL()) { + builder.addAllRules(convert(e.getEntityACL(), true)); + } + builder.addAllRules(convert(org.caosdb.server.permissions.EntityACL.GLOBAL_PERMISSIONS, false)); + EntityAclPermission entityAclPermission = getCurrentACLPermission(e); + if (entityAclPermission != null) { + builder.setPermission(entityAclPermission); + } + return builder.build(); + } + + private org.caosdb.api.entity.v1.EntityAclPermission getCurrentACLPermission(EntityInterface e) { + if (e.hasPermission(EntityPermission.EDIT_PRIORITY_ACL)) { + return EntityAclPermission.ENTITY_ACL_PERMISSION_EDIT_PRIORITY_ACL; + } + if (e.hasPermission(EntityPermission.EDIT_ACL)) { + return EntityAclPermission.ENTITY_ACL_PERMISSION_EDIT_ACL; + } + return null; + } + + private Iterable<? extends EntityPermissionRule> convert( + org.caosdb.server.permissions.EntityACL entityACL, boolean deletable) { + List<EntityPermissionRule> result = new LinkedList<>(); + for (EntityACI aci : entityACL.getRules()) { + EntityPermissionRule.Builder builder = + EntityPermissionRule.newBuilder() + .setGrant(aci.isGrant()) + .setPriority(aci.isPriority()) + .setRole(aci.getResponsibleAgent().toString()) + .addAllPermissions(convert(aci)); + if (deletable) { + builder.addCapabilities( + EntityPermissionRuleCapability.ENTITY_PERMISSION_RULE_CAPABILITY_DELETE); + } + result.add(builder.build()); + } + return result; + } + + private Iterable<org.caosdb.api.entity.v1.EntityPermission> convert(EntityACI aci) { + List<org.caosdb.api.entity.v1.EntityPermission> result = new LinkedList<>(); + + for (EntityPermission p : aci.getPermission()) { + result.add(p.getMapping()); + } + return result; + } } diff --git a/src/main/java/org/caosdb/server/grpc/EntityTransactionServiceImpl.java b/src/main/java/org/caosdb/server/grpc/EntityTransactionServiceImpl.java index 7062defe36121177976d43bc58355f87f235ff8a..c234e61048ba7af730dd7928d0b64ff587c005cc 100644 --- a/src/main/java/org/caosdb/server/grpc/EntityTransactionServiceImpl.java +++ b/src/main/java/org/caosdb/server/grpc/EntityTransactionServiceImpl.java @@ -1,7 +1,29 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + package org.caosdb.server.grpc; import io.grpc.stub.StreamObserver; import java.util.HashMap; +import java.util.TimeZone; import java.util.UUID; import org.apache.shiro.SecurityUtils; import org.caosdb.api.entity.v1.DeleteRequest; @@ -13,8 +35,12 @@ import org.caosdb.api.entity.v1.EntityTransactionServiceGrpc.EntityTransactionSe import org.caosdb.api.entity.v1.IdResponse; import org.caosdb.api.entity.v1.InsertRequest; import org.caosdb.api.entity.v1.InsertResponse; +import org.caosdb.api.entity.v1.MultiRetrieveEntityACLRequest; +import org.caosdb.api.entity.v1.MultiRetrieveEntityACLResponse; import org.caosdb.api.entity.v1.MultiTransactionRequest; import org.caosdb.api.entity.v1.MultiTransactionResponse; +import org.caosdb.api.entity.v1.MultiUpdateEntityACLRequest; +import org.caosdb.api.entity.v1.MultiUpdateEntityACLResponse; import org.caosdb.api.entity.v1.RetrieveResponse; import org.caosdb.api.entity.v1.TransactionRequest; import org.caosdb.api.entity.v1.TransactionRequest.WrappedRequestsCase; @@ -31,12 +57,16 @@ import org.caosdb.server.entity.UpdateEntity; import org.caosdb.server.entity.container.RetrieveContainer; import org.caosdb.server.entity.container.WritableContainer; import org.caosdb.server.transaction.Retrieve; +import org.caosdb.server.transaction.RetrieveACL; +import org.caosdb.server.transaction.UpdateACL; import org.caosdb.server.transaction.WriteTransaction; import org.caosdb.server.utils.ServerMessages; public class EntityTransactionServiceImpl extends EntityTransactionServiceImplBase { - private final CaosDBToGrpcConverters caosdbToGrpc = new CaosDBToGrpcConverters(); + // TODO(tf) let the clients define the time zone of the date time values which are being returned. + private final CaosDBToGrpcConverters caosdbToGrpc = + new CaosDBToGrpcConverters(TimeZone.getDefault()); private final GrpcToCaosDBConverters grpcToCaosdb = new GrpcToCaosDBConverters(); private final FileTransmissionServiceImpl fileTransmissionService; @@ -359,18 +389,67 @@ public class EntityTransactionServiceImpl extends EntityTransactionServiceImplBa } } + private MultiRetrieveEntityACLResponse multiRetrieveEntityACL( + MultiRetrieveEntityACLRequest request) throws Exception { + MultiRetrieveEntityACLResponse.Builder builder = MultiRetrieveEntityACLResponse.newBuilder(); + RetrieveACL transaction = new RetrieveACL(request.getIdList()); + transaction.execute(); + for (EntityInterface e : transaction.getContainer()) { + builder.addAcls(caosdbToGrpc.convertACL(e)); + } + return builder.build(); + } + + private MultiUpdateEntityACLResponse multiUpdateEntityACL(MultiUpdateEntityACLRequest request) + throws Exception { + MultiUpdateEntityACLResponse.Builder builder = MultiUpdateEntityACLResponse.newBuilder(); + UpdateACL transaction = new UpdateACL(grpcToCaosdb.convertAcls(request.getAclsList())); + transaction.execute(); + return builder.build(); + } + @Override public void multiTransaction( final MultiTransactionRequest request, final StreamObserver<MultiTransactionResponse> responseObserver) { try { + AuthInterceptor.bindSubject(); final MultiTransactionResponse response = transaction(request); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (final Exception e) { - e.printStackTrace(); - responseObserver.onError(e); + AccessControlManagementServiceImpl.handleException(responseObserver, e); + } + } + + @Override + public void multiRetrieveEntityACL( + MultiRetrieveEntityACLRequest request, + StreamObserver<MultiRetrieveEntityACLResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final MultiRetrieveEntityACLResponse response = multiRetrieveEntityACL(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + AccessControlManagementServiceImpl.handleException(responseObserver, e); + } + } + + @Override + public void multiUpdateEntityACL( + MultiUpdateEntityACLRequest request, + StreamObserver<MultiUpdateEntityACLResponse> responseObserver) { + try { + AuthInterceptor.bindSubject(); + final MultiUpdateEntityACLResponse response = multiUpdateEntityACL(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + AccessControlManagementServiceImpl.handleException(responseObserver, e); } } } diff --git a/src/main/java/org/caosdb/server/grpc/FileTransmissionServiceImpl.java b/src/main/java/org/caosdb/server/grpc/FileTransmissionServiceImpl.java index 0b0c4b50e0851f3298a61c02c5e38e08c29b2601..1f549b37a33f26c2f4ecdc5efc1258a3bb602d50 100644 --- a/src/main/java/org/caosdb/server/grpc/FileTransmissionServiceImpl.java +++ b/src/main/java/org/caosdb/server/grpc/FileTransmissionServiceImpl.java @@ -45,6 +45,7 @@ public class FileTransmissionServiceImpl extends FileTransmissionServiceImplBase @Override public void onNext(final FileUploadRequest request) { + AuthInterceptor.bindSubject(); final FileChunk chunk = request.getChunk(); if (chunk.hasFileTransmissionId()) { fileUpload = @@ -104,6 +105,7 @@ public class FileTransmissionServiceImpl extends FileTransmissionServiceImplBase final RegisterFileUploadRequest request, final StreamObserver<RegisterFileUploadResponse> responseObserver) { try { + AuthInterceptor.bindSubject(); final FileTransmission result = fileUploadRegistration.registerFileUpload(); final Builder builder = RegisterFileUploadResponse.newBuilder(); builder.setStatus(result.getRegistrationStatus()); @@ -133,6 +135,7 @@ public class FileTransmissionServiceImpl extends FileTransmissionServiceImplBase final FileDownloadRequest request, final StreamObserver<FileDownloadResponse> responseObserver) { try { + AuthInterceptor.bindSubject(); FileDownloadResponse response = fileDownloadRegistration.downloadNextChunk(request.getFileTransmissionId()); responseObserver.onNext(response); diff --git a/src/main/java/org/caosdb/server/grpc/GRPCServer.java b/src/main/java/org/caosdb/server/grpc/GRPCServer.java index 469e4b1048b6139c58d41a46b36c738603e536cf..73356140b85fb09af93bdca034a69685ce8cd4eb 100644 --- a/src/main/java/org/caosdb/server/grpc/GRPCServer.java +++ b/src/main/java/org/caosdb/server/grpc/GRPCServer.java @@ -17,6 +17,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ + package org.caosdb.server.grpc; import io.grpc.Server; @@ -115,6 +116,12 @@ public class GRPCServer { private List<ServerServiceDefinition> getEnabledServices() { final List<ServerServiceDefinition> services = new LinkedList<>(); + final AccessControlManagementServiceImpl accessControlManagementService = + new AccessControlManagementServiceImpl(); + services.add( + ServerInterceptors.intercept( + accessControlManagementService, loggingInterceptor, authInterceptor)); + final GeneralInfoServiceImpl generalInfoService = new GeneralInfoServiceImpl(); services.add( ServerInterceptors.intercept(generalInfoService, loggingInterceptor, authInterceptor)); @@ -197,6 +204,7 @@ public class GRPCServer { CaosDBServer.addPreShutdownHook(new ServerStopper(server)); server.start(); logger.info("Started GRPC (HTTP) on port {}", port_http); + } else if (!started) { logger.warn( "No GRPC Server has been started. Please configure {} or {} to do so.", diff --git a/src/main/java/org/caosdb/server/grpc/GeneralInfoServiceImpl.java b/src/main/java/org/caosdb/server/grpc/GeneralInfoServiceImpl.java index 17d9f4c8e17886f66bc73096487f0b194b350fe8..e47bda9c1783fd9a82703626ad8017c26dbea1fe 100644 --- a/src/main/java/org/caosdb/server/grpc/GeneralInfoServiceImpl.java +++ b/src/main/java/org/caosdb/server/grpc/GeneralInfoServiceImpl.java @@ -17,15 +17,27 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ + package org.caosdb.server.grpc; import io.grpc.stub.StreamObserver; +import java.util.Collection; +import java.util.LinkedList; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.Permission; +import org.apache.shiro.subject.Subject; import org.caosdb.api.info.v1.GeneralInfoServiceGrpc.GeneralInfoServiceImplBase; +import org.caosdb.api.info.v1.GetSessionInfoRequest; +import org.caosdb.api.info.v1.GetSessionInfoResponse; import org.caosdb.api.info.v1.GetVersionInfoRequest; import org.caosdb.api.info.v1.GetVersionInfoResponse; import org.caosdb.api.info.v1.VersionInfo; import org.caosdb.server.CaosDBServer; import org.caosdb.server.ServerProperties; +import org.caosdb.server.accessControl.AuthenticationUtils; +import org.caosdb.server.accessControl.Principal; +import org.caosdb.server.permissions.CaosPermission; /** * Implementation of the GeneralInfoService. @@ -38,10 +50,7 @@ import org.caosdb.server.ServerProperties; */ public class GeneralInfoServiceImpl extends GeneralInfoServiceImplBase { - @Override - public void getVersionInfo( - final GetVersionInfoRequest request, - final StreamObserver<GetVersionInfoResponse> responseObserver) { + private GetVersionInfoResponse getVersionInfo(GetVersionInfoRequest request) { final String version[] = CaosDBServer.getServerProperty(ServerProperties.KEY_PROJECT_VERSION).split("[\\.-]", 4); @@ -59,10 +68,74 @@ public class GeneralInfoServiceImpl extends GeneralInfoServiceImplBase { .setPreRelease(pre_release) .setBuild(build) .build(); - final GetVersionInfoResponse response = - GetVersionInfoResponse.newBuilder().setVersionInfo(versionInfo).build(); + return GetVersionInfoResponse.newBuilder().setVersionInfo(versionInfo).build(); + } + + @Override + public void getVersionInfo( + final GetVersionInfoRequest request, + final StreamObserver<GetVersionInfoResponse> responseObserver) { + + try { + AuthInterceptor.bindSubject(); + GetVersionInfoResponse response = getVersionInfo(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); + + } catch (final Exception e) { + AccessControlManagementServiceImpl.handleException(responseObserver, e); + } + } + + private GetSessionInfoResponse getSessionInfo(GetSessionInfoRequest request) { + Subject subject = SecurityUtils.getSubject(); + GetSessionInfoResponse.Builder response = GetSessionInfoResponse.newBuilder(); + + Principal principal = (Principal) subject.getPrincipal(); + + response.setUsername(principal.getUsername()); + response.setRealm(principal.getRealm()); + + AuthorizationInfo authorizationInfo = AuthenticationUtils.getAuthorizationInfo(subject); + Collection<String> roles = authorizationInfo.getRoles(); + if (roles != null && !roles.isEmpty()) { + response.addAllRoles(roles); + } + + Collection<String> permissions = new LinkedList<>(); + + Collection<String> stringPermissions = authorizationInfo.getStringPermissions(); + if (stringPermissions != null && !stringPermissions.isEmpty()) { + permissions.addAll(stringPermissions); + } + + for (Permission p : authorizationInfo.getObjectPermissions()) { + if (p instanceof CaosPermission) { + permissions.addAll(((CaosPermission) p).getStringPermissions(subject)); + } else { + permissions.add(p.toString()); + } + } + + if (permissions != null && !permissions.isEmpty()) { + response.addAllPermissions(permissions); + } + + return response.build(); + } + + @Override + public void getSessionInfo( + GetSessionInfoRequest request, StreamObserver<GetSessionInfoResponse> responseObserver) { + + try { + AuthInterceptor.bindSubject(); + final GetSessionInfoResponse response = getSessionInfo(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + } catch (final Exception e) { + AccessControlManagementServiceImpl.handleException(responseObserver, e); + } } } diff --git a/src/main/java/org/caosdb/server/grpc/GrpcToCaosDBConverters.java b/src/main/java/org/caosdb/server/grpc/GrpcToCaosDBConverters.java index c2007bebd52f29ce8d1a02fe9e0fcd913a8df798..d7c515a433cfa82f0bea046a1856dd9fb309b915 100644 --- a/src/main/java/org/caosdb/server/grpc/GrpcToCaosDBConverters.java +++ b/src/main/java/org/caosdb/server/grpc/GrpcToCaosDBConverters.java @@ -1,12 +1,39 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + package org.caosdb.server.grpc; +import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; +import java.util.UUID; +import org.apache.shiro.SecurityUtils; import org.caosdb.api.entity.v1.AtomicDataType; import org.caosdb.api.entity.v1.CollectionValues; import org.caosdb.api.entity.v1.DataType; import org.caosdb.api.entity.v1.Entity; +import org.caosdb.api.entity.v1.EntityACL; +import org.caosdb.api.entity.v1.EntityPermission; +import org.caosdb.api.entity.v1.EntityPermissionRule; import org.caosdb.api.entity.v1.EntityRole; import org.caosdb.api.entity.v1.FileDescriptor; import org.caosdb.api.entity.v1.Importance; @@ -28,7 +55,10 @@ import org.caosdb.server.entity.FileProperties; import org.caosdb.server.entity.MagicTypes; import org.caosdb.server.entity.Role; import org.caosdb.server.entity.StatementStatus; +import org.caosdb.server.entity.UpdateEntity; +import org.caosdb.server.entity.container.TransactionContainer; import org.caosdb.server.entity.wrapper.Property; +import org.caosdb.server.permissions.EntityACLFactory; import org.caosdb.server.utils.EntityStatus; import org.caosdb.server.utils.ServerMessages; @@ -95,7 +125,7 @@ public class GrpcToCaosDBConverters { if (from.getParentsCount() > 0) { entity.getParents().addAll(convertParents(from.getParentsList())); } - if (from.hasFileDescriptor()) { + if (entity.getRole() == Role.File && from.hasFileDescriptor()) { entity.setFileProperties(convert(from.getFileDescriptor())); } return entity; @@ -289,4 +319,58 @@ public class GrpcToCaosDBConverters { result.setName(e.getName().isBlank() ? null : e.getName()); return result; } + + public TransactionContainer convertAcls(List<EntityACL> aclsList) { + TransactionContainer result = + new TransactionContainer( + SecurityUtils.getSubject(), System.currentTimeMillis(), UUID.randomUUID().toString()); + + aclsList.forEach( + acl -> { + result.add(convert(acl)); + }); + return result; + } + + private EntityInterface convert(EntityACL acl) { + try { + Integer id = getId(acl.getId()); + UpdateEntity result = new UpdateEntity(id, null); + result.setEntityACL(convertAcl(acl)); + return result; + } catch (NumberFormatException exc) { + UpdateEntity result = new UpdateEntity(null, null); + result.addError(ServerMessages.ENTITY_DOES_NOT_EXIST); + return result; + } + } + + private org.caosdb.server.permissions.EntityACL convertAcl(EntityACL acl) { + EntityACLFactory fac = new EntityACLFactory(); + for (EntityPermissionRule rule : acl.getRulesList()) { + if (rule.getGrant()) { + fac.grant( + org.caosdb.server.permissions.Role.create(rule.getRole()), + rule.getPriority(), + convert(rule.getPermissionsList())); + } else { + fac.deny( + org.caosdb.server.permissions.Role.create(rule.getRole()), + rule.getPriority(), + convert(rule.getPermissionsList())); + } + } + return fac.remove(org.caosdb.server.permissions.EntityACL.GLOBAL_PERMISSIONS).create(); + } + + private org.caosdb.server.permissions.EntityPermission[] convert( + List<EntityPermission> permissionsList) { + ArrayList<org.caosdb.server.permissions.EntityPermission> result = + new ArrayList<>(permissionsList.size()); + permissionsList.forEach( + (p) -> { + result.add(org.caosdb.server.permissions.EntityPermission.getEntityPermission(p)); + }); + return result.toArray(new org.caosdb.server.permissions.EntityPermission[0]); + } } diff --git a/src/main/java/org/caosdb/server/jobs/Job.java b/src/main/java/org/caosdb/server/jobs/Job.java index 9bca9eb2e1b9a78e9e73a79b5f31161b345f2dc1..675686aa797cd2a00cf7a921a29e81ce144db179 100644 --- a/src/main/java/org/caosdb/server/jobs/Job.java +++ b/src/main/java/org/caosdb/server/jobs/Job.java @@ -27,8 +27,6 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; -import org.apache.shiro.authz.AuthorizationException; -import org.apache.shiro.authz.Permission; import org.apache.shiro.subject.Subject; import org.caosdb.server.CaosDBException; import org.caosdb.server.database.BackendTransaction; @@ -300,11 +298,6 @@ public abstract class Job { return entity; } - protected final void checkPermission(final EntityInterface entity, final Permission permission) - throws AuthorizationException { - entity.checkPermission(permission); - } - /** * Create a Job object with the given parameters. * diff --git a/src/main/java/org/caosdb/server/jobs/Schedule.java b/src/main/java/org/caosdb/server/jobs/Schedule.java index f33400099a951aa8fbcf1975208988085813a8b8..57474da515418745ed0457962596dfce233bff48 100644 --- a/src/main/java/org/caosdb/server/jobs/Schedule.java +++ b/src/main/java/org/caosdb/server/jobs/Schedule.java @@ -97,8 +97,8 @@ public class Schedule { ? this.jobLists.get(jobclass.getAnnotation(JobAnnotation.class).stage().ordinal()) : this.jobLists.get(TransactionStage.CHECK.ordinal()); for (final ScheduledJob scheduledJob : jobs) { - if (jobclass.isInstance(scheduledJob.job)) { - if (scheduledJob.job.getEntity() == entity) { + if (jobclass.isInstance(scheduledJob.getJob())) { + if (scheduledJob.getJob().getEntity() == entity) { runJob(scheduledJob); } } diff --git a/src/main/java/org/caosdb/server/jobs/ScheduledJob.java b/src/main/java/org/caosdb/server/jobs/ScheduledJob.java index 3affdfd21421961edc4721c25d80f392d914d1bb..0ef0ac143428eaddaf857f063b7953a620f47ee6 100644 --- a/src/main/java/org/caosdb/server/jobs/ScheduledJob.java +++ b/src/main/java/org/caosdb/server/jobs/ScheduledJob.java @@ -31,11 +31,14 @@ package org.caosdb.server.jobs; public class ScheduledJob { long runtime = 0; - final Job job; + private final Job job; private long startTime = -1; - ScheduledJob(final Job j) { - this.job = j; + ScheduledJob(final Job job) { + if (job == null) { + throw new NullPointerException("job was null."); + } + this.job = job; } void run() { @@ -85,4 +88,8 @@ public class ScheduledJob { public boolean skip() { return this.job.getTarget().skipJob(); } + + public Job getJob() { + return job; + } } diff --git a/src/main/java/org/caosdb/server/jobs/core/AccessControl.java b/src/main/java/org/caosdb/server/jobs/core/AccessControl.java index 408384f416e1249501d5383ea1028ced56914ded..724dd89844097dad5bd1a6fbf2102c8f2c4ceb8c 100644 --- a/src/main/java/org/caosdb/server/jobs/core/AccessControl.java +++ b/src/main/java/org/caosdb/server/jobs/core/AccessControl.java @@ -24,6 +24,7 @@ package org.caosdb.server.jobs.core; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; +import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.database.backend.transaction.RetrieveSparseEntity; import org.caosdb.server.entity.EntityInterface; import org.caosdb.server.entity.wrapper.Parent; @@ -37,12 +38,51 @@ import org.caosdb.server.utils.ServerMessages; @JobAnnotation(stage = TransactionStage.INIT) public class AccessControl extends ContainerJob { + public static class TransactionPermission extends ACMPermissions { + + public static final String ENTITY_ROLE_PARAMETER = "?ENTITY_ROLE?"; + + public TransactionPermission(String permission, String description) { + super(permission, description); + } + + public final String toString(String entityRole) { + return toString().replace(ENTITY_ROLE_PARAMETER, entityRole); + } + + public final String toString(String transaction, String entityRole) { + return "TRANSACTION:" + transaction + (entityRole != null ? (":" + entityRole) : ""); + } + + public static String init() { + return TransactionPermission.class.getSimpleName(); + } + } + + public static final TransactionPermission TRANSACTION_PERMISSIONS = + new TransactionPermission( + "TRANSACTION:*", + "Permission to execute any writable transaction. This permission only allows to execute these transactions in general. The necessary entities permissions are not implied."); + public static final TransactionPermission UPDATE = + new TransactionPermission( + "TRANSACTION:UPDATE:" + TransactionPermission.ENTITY_ROLE_PARAMETER, + "Permission to update entities of a given role (e.g. Record, File, RecordType, or Property)."); + public static final TransactionPermission DELETE = + new TransactionPermission( + "TRANSACTION:DELETE:" + TransactionPermission.ENTITY_ROLE_PARAMETER, + "Permission to delete entities of a given role (e.g. Record, File, RecordType, or Property)."); + public static final TransactionPermission INSERT = + new TransactionPermission( + "TRANSACTION:INSERT:" + TransactionPermission.ENTITY_ROLE_PARAMETER, + "Permission to insert entities of a given role (e.g. Record, File, RecordType, or Property)."); + @Override protected void run() { final Subject subject = SecurityUtils.getSubject(); // subject has complete permissions for this kind of transaction - if (subject.isPermitted("TRANSACTION:" + getTransaction().getClass().getSimpleName())) { + if (subject.isPermitted( + TRANSACTION_PERMISSIONS.toString(getTransaction().getClass().getSimpleName(), null))) { return; } @@ -54,10 +94,8 @@ public class AccessControl extends ContainerJob { // per role permission if (subject.isPermitted( - "TRANSACTION:" - + getTransaction().getClass().getSimpleName() - + ":" - + e.getRole().toString())) { + TRANSACTION_PERMISSIONS.toString( + getTransaction().getClass().getSimpleName(), e.getRole().toString()))) { continue; } diff --git a/src/main/java/org/caosdb/server/jobs/core/CheckStateTransition.java b/src/main/java/org/caosdb/server/jobs/core/CheckStateTransition.java index 1a159910044a079baba3b64c62176883ad31b8ef..a43face9ae14f3fac57890ccb8617e5637c95c16 100644 --- a/src/main/java/org/caosdb/server/jobs/core/CheckStateTransition.java +++ b/src/main/java/org/caosdb/server/jobs/core/CheckStateTransition.java @@ -22,6 +22,7 @@ package org.caosdb.server.jobs.core; import java.util.Map; import org.apache.shiro.authz.AuthorizationException; +import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.entity.DeleteEntity; import org.caosdb.server.entity.Message; import org.caosdb.server.entity.Message.MessageType; @@ -42,9 +43,35 @@ import org.caosdb.server.utils.ServerMessages; @JobAnnotation(stage = TransactionStage.POST_CHECK, transaction = WriteTransaction.class) public class CheckStateTransition extends EntityStateJob { - private static final String PERMISSION_STATE_FORCE_FINAL = "STATE:FORCE:FINAL"; - private static final String PERMISSION_STATE_UNASSIGN = "STATE:UNASSIGN:"; - private static final String PERMISSION_STATE_ASSIGN = "STATE:ASSIGN:"; + public static final class StateModelPermission extends ACMPermissions { + + public static final String STATE_MODEL_PARAMETER = "?STATE_MODEL?"; + + public StateModelPermission(String permission, String description) { + super(permission, description); + } + + public final String toString(String state_model) { + return toString().replace(STATE_MODEL_PARAMETER, state_model); + } + + public static String init() { + return StateModelPermission.class.getSimpleName(); + } + } + + public static final StateModelPermission PERMISSION_STATE_FORCE_FINAL = + new StateModelPermission( + "STATE:FORCE:FINAL", + "Permission to force to leave a state models specified life-cycle even though the currrent state isn't a final state in the that model."); + public static final StateModelPermission PERMISSION_STATE_UNASSIGN = + new StateModelPermission( + "STATE:UNASSIGN:" + StateModelPermission.STATE_MODEL_PARAMETER, + "Permission to unassign a state model."); + public static final StateModelPermission PERMISSION_STATE_ASSIGN = + new StateModelPermission( + "STATE:ASSIGN:" + StateModelPermission.STATE_MODEL_PARAMETER, + "Permission to assign a state model."); private static final Message TRANSITION_NOT_ALLOWED = new Message(MessageType.Error, "Transition not allowed."); private static final Message INITIAL_STATE_NOT_ALLOWED = @@ -167,12 +194,12 @@ public class CheckStateTransition extends EntityStateJob { private void checkFinalState(State oldState) throws Message { if (!oldState.isFinal()) { if (isForceFinal()) { - getUser().checkPermission(PERMISSION_STATE_FORCE_FINAL); + getUser().checkPermission(PERMISSION_STATE_FORCE_FINAL.toString()); } else { throw FINAL_STATE_NOT_ALLOWED; } } - getUser().checkPermission(PERMISSION_STATE_UNASSIGN + oldState.getStateModelName()); + getUser().checkPermission(PERMISSION_STATE_UNASSIGN.toString(oldState.getStateModelName())); } /** @@ -185,7 +212,7 @@ public class CheckStateTransition extends EntityStateJob { if (!newState.isInitial()) { throw INITIAL_STATE_NOT_ALLOWED; } - getUser().checkPermission(PERMISSION_STATE_ASSIGN + newState.getStateModelName()); + getUser().checkPermission(PERMISSION_STATE_ASSIGN.toString(newState.getStateModelName())); } private boolean isForceFinal() { diff --git a/src/main/java/org/caosdb/server/jobs/core/EntityStateJob.java b/src/main/java/org/caosdb/server/jobs/core/EntityStateJob.java index e2f59a8827a682df508a26176a45a9fc1a874b4e..16fe593654aad760edc2b8efc2e6889222bfa78e 100644 --- a/src/main/java/org/caosdb/server/jobs/core/EntityStateJob.java +++ b/src/main/java/org/caosdb/server/jobs/core/EntityStateJob.java @@ -33,6 +33,7 @@ import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import org.apache.shiro.subject.Subject; +import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.database.exceptions.EntityDoesNotExistException; import org.caosdb.server.datatype.AbstractCollectionDatatype; import org.caosdb.server.datatype.CollectionValue; @@ -82,6 +83,19 @@ import org.jdom2.Element; */ public abstract class EntityStateJob extends EntityJob { + public static final class TransitionPermission extends ACMPermissions { + + public static final String TRANSITION_PARAMETER = "?TRANSITION?"; + + public TransitionPermission(String permission, String description) { + super(permission, description); + } + + public final String toString(String transition) { + return toString().replace(TRANSITION_PARAMETER, transition); + } + } + protected static final String SERVER_PROPERTY_EXT_ENTITY_STATE = "EXT_ENTITY_STATE"; public static final String TO_STATE_PROPERTY_NAME = "to"; @@ -102,7 +116,13 @@ public abstract class EntityStateJob extends EntityJob { public static final String STATE_ATTRIBUTE_DESCRIPTION = "description"; public static final String STATE_ATTRIBUTE_ID = "id"; public static final String ENTITY_STATE_ROLE_MARKER = "?STATE?"; - public static final String PERMISSION_STATE_TRANSION = "STATE:TRANSITION:"; + public static final ACMPermissions STATE_PERMISSIONS = + new ACMPermissions( + "STATE:*", "Permissions to manage state models and the states of entities."); + public static final TransitionPermission PERMISSION_STATE_TRANSION = + new TransitionPermission( + "STATE:TRANSITION:" + TransitionPermission.TRANSITION_PARAMETER, + "Permission to initiate a transition."); public static final Message STATE_MODEL_NOT_FOUND = new Message(MessageType.Error, "StateModel not found."); @@ -253,7 +273,7 @@ public abstract class EntityStateJob extends EntityJob { } public boolean isPermitted(Subject user) { - return user.isPermitted(PERMISSION_STATE_TRANSION + this.name); + return user.isPermitted(PERMISSION_STATE_TRANSION.toString(this.name)); } } diff --git a/src/main/java/org/caosdb/server/permissions/CaosPermission.java b/src/main/java/org/caosdb/server/permissions/CaosPermission.java index bfbb7eb2e8515f71bb2d611d4fd75916cfae50e7..615b4d1a9c26c1addb955506ab1debddb729db9c 100644 --- a/src/main/java/org/caosdb/server/permissions/CaosPermission.java +++ b/src/main/java/org/caosdb/server/permissions/CaosPermission.java @@ -22,12 +22,11 @@ */ package org.caosdb.server.permissions; +import java.util.Collection; import java.util.HashSet; -import java.util.Map; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.Permission; import org.apache.shiro.subject.Subject; -import org.eclipse.jetty.util.ajax.JSON; public class CaosPermission extends HashSet<PermissionRule> implements Permission { @@ -35,16 +34,33 @@ public class CaosPermission extends HashSet<PermissionRule> implements Permissio super(rules); } - public CaosPermission() {} + public Collection<String> getStringPermissions(Subject subject) { + HashSet<String> grant = new HashSet<>(); + HashSet<String> prio_grant = new HashSet<>(); + HashSet<String> deny = new HashSet<>(); + HashSet<String> prio_deny = new HashSet<>(); - public static CaosPermission parseJSON(final String json) { - final CaosPermission ret = new CaosPermission(); - @SuppressWarnings("unchecked") - final Map<String, String>[] rules = (Map<String, String>[]) JSON.parse(json); - for (final Map<String, String> rule : rules) { - ret.add(PermissionRule.parse(rule)); + for (PermissionRule r : this) { + String p = subject == null ? r.getPermission() : r.getPermission(subject).toString(); + if (r.isGrant()) { + if (r.isPriority()) { + prio_grant.add(p); + } else { + grant.add(p); + } + } else { + if (r.isPriority()) { + prio_deny.add(p); + } else { + deny.add(p); + } + } } - return ret; + + grant.removeAll(deny); + grant.addAll(prio_grant); + grant.removeAll(prio_deny); + return grant; } private static final long serialVersionUID = 2136265443788256009L; diff --git a/src/main/java/org/caosdb/server/permissions/EntityACL.java b/src/main/java/org/caosdb/server/permissions/EntityACL.java index ce76cf5283847ad0e17886daa80b06548541c030..f959ba89bd08cd5996af18540a484292a5046f94 100644 --- a/src/main/java/org/caosdb/server/permissions/EntityACL.java +++ b/src/main/java/org/caosdb/server/permissions/EntityACL.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,8 +19,8 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.permissions; import static org.caosdb.server.permissions.Role.OTHER_ROLE; @@ -152,6 +153,7 @@ public class EntityACL { } } if (acl.isEmpty()) { + // There haven't been any rules which apply to this subject. Thus the rules for ?OTHER? apply. acl.addAll(forOthers); } return getPermissionsFromBitSet(getResultingACL(acl)); @@ -360,10 +362,6 @@ public class EntityACL { return new EntityACL(newACL); } - public static final void normalize(final Collection<EntityACI> acl) { - // every priority denial removes all other items - } - public EntityACL getPriorityEntityACL() { return getPriorityEntityACL(this); } diff --git a/src/main/java/org/caosdb/server/permissions/EntityPermission.java b/src/main/java/org/caosdb/server/permissions/EntityPermission.java index 1f84dce34a611f3b25bea5ddaab0d40c9723a280..f8f21a354ef68403f852a1f426e28afed857278d 100644 --- a/src/main/java/org/caosdb/server/permissions/EntityPermission.java +++ b/src/main/java/org/caosdb/server/permissions/EntityPermission.java @@ -37,6 +37,11 @@ public class EntityPermission extends Permission { private static final long serialVersionUID = -8935713878537140286L; private static List<EntityPermission> instances = new ArrayList<>(); private final int bitNumber; + private final org.caosdb.api.entity.v1.EntityPermission mapping; + public static final Permission EDIT_PRIORITY_ACL = + new Permission( + "ADMIN:ENTITY:EDIT:PRIORITY_ACL", + "The permission to edit (add/delete) the prioritized rules of an acl of an entity."); public static ToElementable getAllEntityPermissions() { final Element entityPermissionsElement = new Element("EntityPermissions"); @@ -57,9 +62,14 @@ public class EntityPermission extends Permission { }; } - private EntityPermission(final String shortName, final String description, final int bitNumber) { + private EntityPermission( + final String shortName, + final String description, + final int bitNumber, + org.caosdb.api.entity.v1.EntityPermission mapping) { super(shortName, description); this.bitNumber = bitNumber; + this.mapping = mapping; if (bitNumber > 61) { throw new CaosDBException( "This bitNumber is too big. This implementation only handles bitNumbers up to 61."); @@ -102,6 +112,16 @@ public class EntityPermission extends Permission { throw new IllegalArgumentException("Permission is not defined."); } + public static EntityPermission getEntityPermission( + final org.caosdb.api.entity.v1.EntityPermission permission) { + for (final EntityPermission p : instances) { + if (p.getMapping() == permission) { + return p; + } + } + throw new IllegalArgumentException("Permission not found." + permission.name()); + } + public long getBitSet() { return (long) Math.pow(2, getBitNumber()); } @@ -116,78 +136,153 @@ public class EntityPermission extends Permission { return ret; } + public org.caosdb.api.entity.v1.EntityPermission getMapping() { + return mapping; + } + public static final EntityPermission RETRIEVE_ENTITY = new EntityPermission( "RETRIEVE:ENTITY", "Permission to retrieve the full entity (name, description, data type, ...) with all parents and properties (unless prohibited by another rule on the property level).", - 4); + 4, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_ENTITY); public static final EntityPermission RETRIEVE_ACL = new EntityPermission( - "RETRIEVE:ACL", "Permission to retrieve the full and final ACL of this entity.", 5); + "RETRIEVE:ACL", + "Permission to retrieve the full and final ACL of this entity.", + 5, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_ACL); public static final EntityPermission RETRIEVE_HISTORY = new EntityPermission( - "RETRIEVE:HISTORY", "Permission to retrieve the history of this entity.", 6); + "RETRIEVE:HISTORY", + "Permission to retrieve the history of this entity.", + 6, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_HISTORY); public static final EntityPermission RETRIEVE_OWNER = new EntityPermission( - "RETRIEVE:OWNER", "Permission to retrieve the owner(s) of this entity.", 9); + "RETRIEVE:OWNER", + "Permission to retrieve the owner(s) of this entity.", + 9, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_OWNER); public static final EntityPermission RETRIEVE_FILE = new EntityPermission( - "RETRIEVE:FILE", "Permission to download the file belonging to this entity.", 10); + "RETRIEVE:FILE", + "Permission to download the file belonging to this entity.", + 10, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_FILE); public static final EntityPermission DELETE = - new EntityPermission("DELETE", "Permission to delete an entity.", 1); + new EntityPermission( + "DELETE", + "Permission to delete an entity.", + 1, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_DELETE); public static final EntityPermission EDIT_ACL = new EntityPermission( "EDIT:ACL", "Permission to change the user-specified part of this entity's ACL. Roles with this Permission are called 'Owners'.", - 0); + 0, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_EDIT_ACL); public static final EntityPermission UPDATE_DESCRIPTION = new EntityPermission( - "UPDATE:DESCRIPTION", "Permission to change the value of this entity.", 11); + "UPDATE:DESCRIPTION", + "Permission to change the value of this entity.", + 11, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_DESCRIPTION); public static final EntityPermission UPDATE_VALUE = - new EntityPermission("UPDATE:VALUE", "Permission to change the value of this entity.", 12); + new EntityPermission( + "UPDATE:VALUE", + "Permission to change the value of this entity.", + 12, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_VALUE); public static final EntityPermission UPDATE_ROLE = - new EntityPermission("UPDATE:ROLE", "Permission to change the role of this entity.", 13); + new EntityPermission( + "UPDATE:ROLE", + "Permission to change the role of this entity.", + 13, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_ROLE); public static final EntityPermission UPDATE_REMOVE_PARENT = new EntityPermission( - "UPDATE:PARENT:REMOVE", "Permission to remove parents from this entity.", 14); + "UPDATE:PARENT:REMOVE", + "Permission to remove parents from this entity.", + 14, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_REMOVE_PARENT); public static final EntityPermission UPDATE_ADD_PARENT = - new EntityPermission("UPDATE:PARENT:ADD", "Permission to add a parent to this entity.", 15); + new EntityPermission( + "UPDATE:PARENT:ADD", + "Permission to add a parent to this entity.", + 15, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_ADD_PARENT); public static final EntityPermission UPDATE_REMOVE_PROPERTY = new EntityPermission( - "UPDATE:PROPERTY:REMOVE", "Permission to remove properties from this entity.", 16); + "UPDATE:PROPERTY:REMOVE", + "Permission to remove properties from this entity.", + 16, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_REMOVE_PROPERTY); public static final EntityPermission UPDATE_ADD_PROPERTY = new EntityPermission( - "UPDATE:PROPERTY:ADD", "Permission to add a property to this entity.", 17); + "UPDATE:PROPERTY:ADD", + "Permission to add a property to this entity.", + 17, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_ADD_PROPERTY); public static final EntityPermission UPDATE_NAME = - new EntityPermission("UPDATE:NAME", "Permission to change the name of this entity.", 19); + new EntityPermission( + "UPDATE:NAME", + "Permission to change the name of this entity.", + 19, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_NAME); public static final EntityPermission UPDATE_DATA_TYPE = new EntityPermission( - "UPDATE:DATA_TYPE", "Permission to change the data type of this entity.", 20); + "UPDATE:DATA_TYPE", + "Permission to change the data type of this entity.", + 20, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_DATA_TYPE); public static final EntityPermission UPDATE_REMOVE_FILE = new EntityPermission( - "UPDATE:FILE:REMOVE", "Permission to delete the file of this entity.", 21); + "UPDATE:FILE:REMOVE", + "Permission to delete the file of this entity.", + 21, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_REMOVE_FILE); public static final EntityPermission UPDATE_ADD_FILE = - new EntityPermission("UPDATE:FILE:ADD", "Permission to set a file for this entity.", 22); + new EntityPermission( + "UPDATE:FILE:ADD", + "Permission to set a file for this entity.", + 22, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_ADD_FILE); public static final EntityPermission UPDATE_MOVE_FILE = new EntityPermission( - "UPDATE:FILE:MOVE", "Permission to move an existing file to a new location.", 23); + "UPDATE:FILE:MOVE", + "Permission to move an existing file to a new location.", + 23, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_MOVE_FILE); public static final EntityPermission USE_AS_REFERENCE = new EntityPermission( - "USE:AS_REFERENCE", "Permission to refer to this entity via a reference property.", 24); + "USE:AS_REFERENCE", + "Permission to refer to this entity via a reference property.", + 24, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_USE_AS_REFERENCE); public static final EntityPermission USE_AS_PROPERTY = new EntityPermission( - "USE:AS_PROPERTY", "Permission to implement this entity as a property.", 25); + "USE:AS_PROPERTY", + "Permission to implement this entity as a property.", + 25, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_USE_AS_PROPERTY); public static final EntityPermission USE_AS_PARENT = new EntityPermission( - "USE:AS_PARENT", "Permission to use this entity as a super type for other entities.", 26); + "USE:AS_PARENT", + "Permission to use this entity as a super type for other entities.", + 26, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_USE_AS_PARENT); public static final EntityPermission USE_AS_DATA_TYPE = new EntityPermission( "USE:AS_DATA_TYPE", "Permission to use this entity as a data type for reference properties.", - 27); + 27, + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_USE_AS_DATA_TYPE); public static final EntityPermission UPDATE_QUERY_TEMPLATE_DEFINITION = new EntityPermission( "UPDATE:QUERY_TEMPLATE_DEFINITION", "Permission to update the query template definition of this QueryTemplate", - 28); + 28, + org.caosdb.api.entity.v1.EntityPermission + .ENTITY_PERMISSION_UPDATE_QUERY_TEMPLATE_DEFINITION); } diff --git a/src/main/java/org/caosdb/server/permissions/Permission.java b/src/main/java/org/caosdb/server/permissions/Permission.java index 44eee1c68a073c405233195aee491bcf10fcd38c..e8f33a3ae3f9eb0956bae6bc7c7eceefdc5663b7 100644 --- a/src/main/java/org/caosdb/server/permissions/Permission.java +++ b/src/main/java/org/caosdb/server/permissions/Permission.java @@ -28,11 +28,6 @@ public class Permission extends WildcardPermission { private static final long serialVersionUID = -7471830472441416012L; - public static final org.apache.shiro.authz.Permission EDIT_PRIORITY_ACL = - new Permission( - "ADMIN:ENTITY:EDIT:PRIORITY_ACL", - "The permission to edit (add/delete) the prioritized rules of an acl of an entity."); - private final String description; private final String shortName; diff --git a/src/main/java/org/caosdb/server/permissions/PermissionRule.java b/src/main/java/org/caosdb/server/permissions/PermissionRule.java index 85d3b62834a67a4fc46ea9b3c38d19e4b8261d74..2e8b6984509761d649acb27b5482c8df7bff9933 100644 --- a/src/main/java/org/caosdb/server/permissions/PermissionRule.java +++ b/src/main/java/org/caosdb/server/permissions/PermissionRule.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,8 +19,8 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.permissions; import java.util.HashMap; @@ -43,6 +44,9 @@ public class PermissionRule { public PermissionRule(final boolean grant, final boolean priority, final String permission) { this.grant = grant; this.priority = priority; + if (permission == null) { + throw new NullPointerException("permission cannot be null"); + } this.permission = permission; } @@ -54,6 +58,10 @@ public class PermissionRule { return this.priority; } + public String getPermission() { + return permission; + } + public Permission getPermission(String realm, String username) { return new WildcardPermission( permission.replaceAll("\\?REALM\\?", realm).replaceAll("\\?USERNAME\\?", username)); @@ -72,6 +80,31 @@ public class PermissionRule { return ret; } + @Override + public String toString() { + return "PermissionRule(" + + (priority ? "[P]" : "") + + (grant ? "GRANT" : "DENY") + + permission + + ")"; + } + + @Override + public int hashCode() { + return permission.hashCode() + (grant ? 3 : 0) - (priority ? 5 : 0); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof PermissionRule) { + PermissionRule that = (PermissionRule) obj; + return this.grant == that.grant + && this.priority == that.priority + && this.permission.equals(that.permission); + } + return false; + } + public static PermissionRule parse(final Element e) { return new PermissionRule( e.getName().equalsIgnoreCase("Grant"), diff --git a/src/main/java/org/caosdb/server/permissions/Role.java b/src/main/java/org/caosdb/server/permissions/Role.java index 54afefc664c330dfc4465285347a1463d9df0d5e..f7f4e55e195d72ba3a42a8b909d2c87944bcbf81 100644 --- a/src/main/java/org/caosdb/server/permissions/Role.java +++ b/src/main/java/org/caosdb/server/permissions/Role.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,8 +19,8 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.permissions; import java.util.HashMap; @@ -31,6 +32,7 @@ public class Role implements ResponsibleAgent { public static final Role OWNER_ROLE = new Role("?OWNER?"); public static final Role OTHER_ROLE = new Role("?OTHER?"); public static final Role ANONYMOUS_ROLE = new Role("anonymous"); + public static final Role ADMINISTRATION = new Role("administration"); private final String role; diff --git a/src/main/java/org/caosdb/server/query/CQLParser.g4 b/src/main/java/org/caosdb/server/query/CQLParser.g4 index c4311ac1cbe03f490b79456e091cc0e73b94c506..f8c2a3b5ea4e7c34f3cc8fd07cdc77c912a5cc7b 100644 --- a/src/main/java/org/caosdb/server/query/CQLParser.g4 +++ b/src/main/java/org/caosdb/server/query/CQLParser.g4 @@ -287,15 +287,36 @@ pov returns [POV filter] locals [Query.Pattern p, String o, String v, String a] ; -subproperty returns [SubProperty subp] locals [String p] +subproperty returns [SubProperty subp] @init{ - $p = null; $subp = null; } : - entity_filter {$subp = new SubProperty($entity_filter.filter);} + subproperty_filter {$subp = new SubProperty($subproperty_filter.filter);} ; +subproperty_filter returns [EntityFilterInterface filter] + @init{ + $filter = null; + } +: + which_exp + ( + ( + LPAREN WHITE_SPACE? + ( + filter_expression {$filter = $filter_expression.efi;} + | conjunction {$filter = $conjunction.c;} + | disjunction {$filter = $disjunction.d;} + ) + RPAREN + ) | ( + filter_expression {$filter = $filter_expression.efi;} + ) + )? +; + + backreference returns [Backreference ref] locals [Query.Pattern e, Query.Pattern p] @init{ $e = null; @@ -328,7 +349,7 @@ storedat returns [StoredAt filter] locals [String loc] WHITE_SPACE? ; -conjunction returns [Conjunction c] locals [Conjunction dummy] +conjunction returns [Conjunction c] @init{ $c = new Conjunction(); } @@ -493,7 +514,7 @@ number_with_unit unit : - (~(WHITE_SPACE | WHICH | HAS_A | WITH | WHERE | DOT | AND | OR )) + (~(WHITE_SPACE | WHICH | HAS_A | WITH | WHERE | DOT | AND | OR | RPAREN )) (~(WHITE_SPACE))* | NUM SLASH (~(WHITE_SPACE))+ @@ -510,7 +531,7 @@ atom returns [Query.Pattern ep] : double_quoted {$ep = $double_quoted.ep;} | single_quoted {$ep = $single_quoted.ep;} - | (~(WHITE_SPACE | DOT ))+ {$ep = new Query.Pattern($text, Query.Pattern.TYPE_NORMAL);} + | (~(WHITE_SPACE | DOT | RPAREN | LPAREN ))+ {$ep = new Query.Pattern($text, Query.Pattern.TYPE_NORMAL);} ; single_quoted returns [Query.Pattern ep] locals [StringBuffer sb, int patternType] diff --git a/src/main/java/org/caosdb/server/query/Query.java b/src/main/java/org/caosdb/server/query/Query.java index 95f853d607edffa29b69e4f84657560ba3a52a48..07a165a352ba9a07a345018e7d287cd961f4a00b 100644 --- a/src/main/java/org/caosdb/server/query/Query.java +++ b/src/main/java/org/caosdb/server/query/Query.java @@ -47,6 +47,7 @@ import org.antlr.v4.runtime.CommonTokenStream; import org.apache.commons.jcs.access.behavior.ICacheAccess; import org.apache.shiro.subject.Subject; import org.caosdb.api.entity.v1.MessageCode; +import org.caosdb.datetime.UTCDateTime; import org.caosdb.server.CaosDBServer; import org.caosdb.server.ServerProperties; import org.caosdb.server.caching.Cache; @@ -1047,4 +1048,9 @@ public class Query implements QueryInterface, ToElementable, TransactionInterfac return -1; } } + + @Override + public UTCDateTime getTimestamp() { + return null; + } } diff --git a/src/main/java/org/caosdb/server/resource/AbstractCaosDBServerResource.java b/src/main/java/org/caosdb/server/resource/AbstractCaosDBServerResource.java index 876b43a160f673b96a7220a746c9a7dcd4951388..44ebfa22d08c975031f5bf5bfca325d6b706af24 100644 --- a/src/main/java/org/caosdb/server/resource/AbstractCaosDBServerResource.java +++ b/src/main/java/org/caosdb/server/resource/AbstractCaosDBServerResource.java @@ -251,6 +251,7 @@ public abstract class AbstractCaosDBServerResource extends ServerResource { try { return httpPostInChildClass(entity); } catch (final Throwable t) { + t.printStackTrace(); return handleThrowable(t); } } @@ -388,6 +389,7 @@ public abstract class AbstractCaosDBServerResource extends ServerResource { public Representation handleThrowable(final Throwable t) { try { getRequest().getAttributes().put("THROWN", t); + t.printStackTrace(); throw t; } catch (final AuthenticationException e) { return error(ServerMessages.UNAUTHENTICATED, Status.CLIENT_ERROR_UNAUTHORIZED); diff --git a/src/main/java/org/caosdb/server/resource/RolesResource.java b/src/main/java/org/caosdb/server/resource/RolesResource.java index a89a731950d09a7edbce0a5f67a3e81287c07b2a..ad1544da3a326f1c16e0b01238985d10e93b0581 100644 --- a/src/main/java/org/caosdb/server/resource/RolesResource.java +++ b/src/main/java/org/caosdb/server/resource/RolesResource.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import org.caosdb.server.CaosDBException; -import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.accessControl.Role; import org.caosdb.server.database.backend.implementation.MySQL.ConnectionException; import org.caosdb.server.entity.Message; @@ -55,7 +54,6 @@ public class RolesResource extends AbstractCaosDBServerResource { if (getRequestedItems().length > 0) { final String name = getRequestedItems()[0]; if (name != null) { - getUser().checkPermission(ACMPermissions.PERMISSION_RETRIEVE_ROLE_DESCRIPTION(name)); final RetrieveRoleTransaction t = new RetrieveRoleTransaction(name); try { t.execute(); diff --git a/src/main/java/org/caosdb/server/resource/Webinterface.java b/src/main/java/org/caosdb/server/resource/Webinterface.java index adba714a96e5bbb4bc3ea13b8d72ec69a88cb33b..95901260937a5364a68ed3e9e6849210bd67d6b3 100644 --- a/src/main/java/org/caosdb/server/resource/Webinterface.java +++ b/src/main/java/org/caosdb/server/resource/Webinterface.java @@ -81,7 +81,9 @@ public class Webinterface extends ServerResource { ? MediaType.IMAGE_PNG : path.endsWith(".html") ? MediaType.TEXT_HTML - : path.endsWith(".yaml") ? MediaType.TEXT_YAML : MediaType.TEXT_XML; + : path.endsWith(".yaml") + ? MediaType.TEXT_YAML + : path.endsWith(".xml") ? MediaType.TEXT_XML : MediaType.ALL; final FileRepresentation ret = new FileRepresentation(file, mt); diff --git a/src/main/java/org/caosdb/server/scripting/ScriptingPermissions.java b/src/main/java/org/caosdb/server/scripting/ScriptingPermissions.java index 78ad99d77d06b681838e455ad391c62e7ce85ca6..0af49e9faf6ec8ad9a4107d72554a44744184661 100644 --- a/src/main/java/org/caosdb/server/scripting/ScriptingPermissions.java +++ b/src/main/java/org/caosdb/server/scripting/ScriptingPermissions.java @@ -1,11 +1,29 @@ package org.caosdb.server.scripting; -public class ScriptingPermissions { +import org.caosdb.server.accessControl.ACMPermissions; + +public class ScriptingPermissions extends ACMPermissions { + + public static final String PATH_PARAMETER = "?PATH?"; + + public ScriptingPermissions(String permission, String description) { + super(permission, description); + } + + public String toString(String path) { + return toString().replace(PATH_PARAMETER, path.replace("/", ":")); + } + + private static final ScriptingPermissions execution = + new ScriptingPermissions( + "SCRIPTING:EXECUTE:" + PATH_PARAMETER, + "Permission to execute a server-side script under the given path. Note that, for utilizing the wild cards feature, you have to use ':' as path separator. E.g. 'SCRIPTING:EXECUTE:my_scripts:*' would be the permission to execute all executables below the my_scripts directory."); public static final String PERMISSION_EXECUTION(final String call) { - StringBuilder ret = new StringBuilder(18 + call.length()); - ret.append("SCRIPTING:EXECUTE:"); - ret.append(call.replace("/", ":")); - return ret.toString(); + return execution.toString(call); + } + + public static String init() { + return ScriptingPermissions.class.getSimpleName(); } } diff --git a/src/main/java/org/caosdb/server/transaction/AccessControlTransaction.java b/src/main/java/org/caosdb/server/transaction/AccessControlTransaction.java index 4897cd65620577e36a98f2db5e5530a42b3f43d0..1cf9f8f70df2eaa384e4074cc3b80a4816a88142 100644 --- a/src/main/java/org/caosdb/server/transaction/AccessControlTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/AccessControlTransaction.java @@ -22,6 +22,7 @@ */ package org.caosdb.server.transaction; +import org.caosdb.datetime.UTCDateTime; import org.caosdb.server.database.DatabaseAccessManager; import org.caosdb.server.database.access.Access; import org.caosdb.server.database.misc.RollBackHandler; @@ -30,9 +31,11 @@ import org.caosdb.server.entity.Message; public abstract class AccessControlTransaction implements TransactionInterface { private Access access; + private UTCDateTime timestamp; @Override public final void execute() throws Exception { + this.timestamp = UTCDateTime.SystemMillisToUTCDateTime(System.currentTimeMillis()); this.access = DatabaseAccessManager.getAccountAccess(this); try { @@ -54,4 +57,9 @@ public abstract class AccessControlTransaction implements TransactionInterface { } protected abstract void transaction() throws Exception; + + @Override + public UTCDateTime getTimestamp() { + return timestamp; + } } diff --git a/src/main/java/org/caosdb/server/transaction/DeleteRoleTransaction.java b/src/main/java/org/caosdb/server/transaction/DeleteRoleTransaction.java index ad9a9925f8bed2ef03a1bcf9cd6b8c79adca6345..2e7e5b2a5ad4354b517dc7020f44f5ece459cc35 100644 --- a/src/main/java/org/caosdb/server/transaction/DeleteRoleTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/DeleteRoleTransaction.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,8 +19,8 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.transaction; import org.apache.shiro.SecurityUtils; @@ -27,6 +28,8 @@ import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.database.backend.transaction.DeleteRole; import org.caosdb.server.database.backend.transaction.RetrieveRole; import org.caosdb.server.database.backend.transaction.SetPermissionRules; +import org.caosdb.server.database.exceptions.TransactionException; +import org.caosdb.server.entity.Message; import org.caosdb.server.utils.ServerMessages; public class DeleteRoleTransaction extends AccessControlTransaction { @@ -41,10 +44,19 @@ public class DeleteRoleTransaction extends AccessControlTransaction { protected void transaction() throws Exception { SecurityUtils.getSubject().checkPermission(ACMPermissions.PERMISSION_DELETE_ROLE(this.name)); + if (this.name == "administration" || this.name == "anonymous") { + throw ServerMessages.SPECIAL_ROLE_CANNOT_BE_DELETED; + } if (execute(new RetrieveRole(this.name), getAccess()).getRole() == null) { throw ServerMessages.ROLE_DOES_NOT_EXIST; } execute(new SetPermissionRules(this.name, null), getAccess()); - execute(new DeleteRole(this.name), getAccess()); + try { + execute(new DeleteRole(this.name), getAccess()); + } catch (TransactionException e) { + if (e.getCause() == ServerMessages.ROLE_CANNOT_BE_DELETED) { + throw (Message) e.getCause(); + } + } } } diff --git a/src/main/java/org/caosdb/server/transaction/DeleteUserTransaction.java b/src/main/java/org/caosdb/server/transaction/DeleteUserTransaction.java index dc935adc9ea0236ce3c8d54b498ed5f6b15a8c42..24aac16b9c529130520518822e6bf3a6a3e8b72d 100644 --- a/src/main/java/org/caosdb/server/transaction/DeleteUserTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/DeleteUserTransaction.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,13 +19,15 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.transaction; import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.accessControl.CredentialsValidator; +import org.caosdb.server.accessControl.Principal; import org.caosdb.server.accessControl.UserSources; import org.caosdb.server.database.backend.transaction.DeletePassword; import org.caosdb.server.database.backend.transaction.DeleteUser; @@ -35,34 +38,41 @@ import org.jdom2.Element; public class DeleteUserTransaction extends AccessControlTransaction { - private final String user; + private final String name; private final String realm; - public DeleteUserTransaction(final String user) { - this.realm = UserSources.getInternalRealm().getName(); - this.user = user; + public DeleteUserTransaction(final String name) { + this(UserSources.getInternalRealm().getName(), name); + } + + public DeleteUserTransaction(final String realm, final String name) { + this.realm = realm; + this.name = name; } @Override protected void transaction() throws Exception { - SecurityUtils.getSubject() - .checkPermission(ACMPermissions.PERMISSION_DELETE_USER(this.realm, this.user)); + Subject subject = SecurityUtils.getSubject(); + if (subject.getPrincipal().equals(new Principal(realm, name))) { + throw ServerMessages.CANNOT_DELETE_YOURSELF(); + } + subject.checkPermission(ACMPermissions.PERMISSION_DELETE_USER(this.realm, this.name)); final CredentialsValidator<String> validator = - execute(new RetrievePasswordValidator(this.user), getAccess()).getValidator(); + execute(new RetrievePasswordValidator(this.name), getAccess()).getValidator(); if (validator == null) { throw ServerMessages.ACCOUNT_DOES_NOT_EXIST; } - execute(new DeletePassword(this.user), getAccess()); - execute(new DeleteUser(this.realm, this.user), getAccess()); + execute(new DeletePassword(this.name), getAccess()); + execute(new DeleteUser(this.realm, this.name), getAccess()); } public Element getUserElement() { final Element ret = new Element("User"); ret.setAttribute("realm", this.realm); - ret.setAttribute("name", this.user); + ret.setAttribute("name", this.name); ret.addContent(new Message("This user has been deleted.").toElement()); return ret; } diff --git a/src/main/java/org/caosdb/server/transaction/FileStorageConsistencyCheck.java b/src/main/java/org/caosdb/server/transaction/FileStorageConsistencyCheck.java index e066feb3028eb6dcb9bf645070cadefa9cc45047..1ce1aa566ad28d048a36f91d50bb297b1a709d14 100644 --- a/src/main/java/org/caosdb/server/transaction/FileStorageConsistencyCheck.java +++ b/src/main/java/org/caosdb/server/transaction/FileStorageConsistencyCheck.java @@ -53,6 +53,7 @@ public class FileStorageConsistencyCheck extends Thread private Runnable finishRunnable = null; private final String location; private Long ts = null; + private UTCDateTime timestamp = null; public Exception getException() { return this.exception; @@ -60,6 +61,7 @@ public class FileStorageConsistencyCheck extends Thread public FileStorageConsistencyCheck(final String location) { setDaemon(true); + this.timestamp = UTCDateTime.SystemMillisToUTCDateTime(System.currentTimeMillis()); this.location = location.startsWith("/") ? location.replaceFirst("^/", "") : location; } @@ -245,4 +247,9 @@ public class FileStorageConsistencyCheck extends Thread public void execute() throws Exception { run(); } + + @Override + public UTCDateTime getTimestamp() { + return timestamp; + } } diff --git a/src/main/java/org/caosdb/server/transaction/InsertLogRecordTransaction.java b/src/main/java/org/caosdb/server/transaction/InsertLogRecordTransaction.java index c1128135b8620ebfe08328cd4901e9c0e6062053..950d9b8d25688e47833b60c01335f8dd525a0630 100644 --- a/src/main/java/org/caosdb/server/transaction/InsertLogRecordTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/InsertLogRecordTransaction.java @@ -24,6 +24,7 @@ package org.caosdb.server.transaction; import java.util.List; import java.util.logging.LogRecord; +import org.caosdb.datetime.UTCDateTime; import org.caosdb.server.database.DatabaseAccessManager; import org.caosdb.server.database.access.Access; import org.caosdb.server.database.backend.transaction.InsertLogRecord; @@ -31,8 +32,10 @@ import org.caosdb.server.database.backend.transaction.InsertLogRecord; public class InsertLogRecordTransaction implements TransactionInterface { private final List<LogRecord> toBeFlushed; + private UTCDateTime timestamp; public InsertLogRecordTransaction(final List<LogRecord> toBeFlushed) { + this.timestamp = UTCDateTime.SystemMillisToUTCDateTime(System.currentTimeMillis()); this.toBeFlushed = toBeFlushed; } @@ -45,4 +48,9 @@ public class InsertLogRecordTransaction implements TransactionInterface { access.release(); } } + + @Override + public UTCDateTime getTimestamp() { + return timestamp; + } } diff --git a/src/main/java/org/caosdb/server/transaction/InsertRoleTransaction.java b/src/main/java/org/caosdb/server/transaction/InsertRoleTransaction.java index b70e2bd71259645a8f619cb25d36998579e3dca7..44288af5888c2dacbf9e97c235a76e0d9992a969 100644 --- a/src/main/java/org/caosdb/server/transaction/InsertRoleTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/InsertRoleTransaction.java @@ -22,11 +22,14 @@ */ package org.caosdb.server.transaction; +import java.util.Set; import org.apache.shiro.SecurityUtils; import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.accessControl.Role; import org.caosdb.server.database.backend.transaction.InsertRole; import org.caosdb.server.database.backend.transaction.RetrieveRole; +import org.caosdb.server.database.backend.transaction.SetPermissionRules; +import org.caosdb.server.entity.Message; import org.caosdb.server.utils.ServerMessages; public class InsertRoleTransaction extends AccessControlTransaction { @@ -37,14 +40,24 @@ public class InsertRoleTransaction extends AccessControlTransaction { this.role = role; } - @Override - protected void transaction() throws Exception { + private void checkPermissions() throws Message { SecurityUtils.getSubject().checkPermission(ACMPermissions.PERMISSION_INSERT_ROLE()); if (execute(new RetrieveRole(this.role.name), getAccess()).getRole() != null) { throw ServerMessages.ROLE_NAME_IS_NOT_UNIQUE; } + } + + @Override + protected void transaction() throws Exception { + checkPermissions(); execute(new InsertRole(this.role), getAccess()); + if (this.role.permission_rules != null) { + execute( + new SetPermissionRules(this.role.name, Set.copyOf(this.role.permission_rules)), + getAccess()); + } + RetrieveRole.removeCached(this.role.name); } } diff --git a/src/main/java/org/caosdb/server/transaction/InsertUserTransaction.java b/src/main/java/org/caosdb/server/transaction/InsertUserTransaction.java index b91b1aa6b31911822ed9df4c1eaffa87374ede82..09d59e8d84659037da66e11f7b4c0da556d8aa50 100644 --- a/src/main/java/org/caosdb/server/transaction/InsertUserTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/InsertUserTransaction.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,25 +19,27 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.transaction; import org.apache.shiro.SecurityUtils; import org.caosdb.server.accessControl.ACMPermissions; +import org.caosdb.server.accessControl.Principal; import org.caosdb.server.accessControl.UserSources; import org.caosdb.server.accessControl.UserStatus; -import org.caosdb.server.database.backend.transaction.RetrievePasswordValidator; import org.caosdb.server.database.backend.transaction.SetPassword; import org.caosdb.server.database.backend.transaction.UpdateUser; +import org.caosdb.server.database.backend.transaction.UpdateUserRoles; import org.caosdb.server.database.proto.ProtoUser; +import org.caosdb.server.entity.Message; import org.caosdb.server.utils.ServerMessages; import org.caosdb.server.utils.Utils; import org.jdom2.Element; public class InsertUserTransaction extends AccessControlTransaction { - ProtoUser user = new ProtoUser(); + private final ProtoUser user; private final String password; public InsertUserTransaction( @@ -45,11 +48,16 @@ public class InsertUserTransaction extends AccessControlTransaction { final String email, final UserStatus status, final Integer entity) { + this(new ProtoUser(), password); this.user.realm = UserSources.getInternalRealm().getName(); this.user.name = username; this.user.email = email; this.user.status = status; this.user.entity = entity; + } + + public InsertUserTransaction(ProtoUser user, String password) { + this.user = user; this.password = password; } @@ -58,6 +66,8 @@ public class InsertUserTransaction extends AccessControlTransaction { SecurityUtils.getSubject() .checkPermission(ACMPermissions.PERMISSION_INSERT_USER(this.user.realm)); + checkUserName(this.user.name); + if (this.user.email != null && !Utils.isRFC822Compliant(this.user.email)) { throw ServerMessages.EMAIL_NOT_WELL_FORMED; } @@ -66,15 +76,31 @@ public class InsertUserTransaction extends AccessControlTransaction { UpdateUserTransaction.checkEntityExists(this.user.entity); } - if (execute(new RetrievePasswordValidator(this.user.name), getAccess()).getValidator() - == null) { - if (this.password != null) { - Utils.checkPasswordStrength(this.password); - } + if (this.password != null) { + Utils.checkPasswordStrength(this.password); + } + + execute(new SetPassword(this.user.name, this.password), getAccess()); + execute(new UpdateUser(this.user), getAccess()); + execute(new UpdateUserRoles(this.user.realm, this.user.name, this.user.roles), getAccess()); + } + + /* + * Names should have at least a length of 1, a maximum length of 32 and match + * ^[a-zA-Z_][a-zA-Z0-9_-]*$. + */ + private void checkUserName(String name) throws Message { + // Make this configurable? + final boolean length = name.length() >= 1 && name.length() <= 32; + final boolean match = + name.matches("^[\\p{Lower}\\p{Upper}_][\\p{Lower}\\p{Upper}\\p{Digit}_-]*$"); + + if (!(length && match)) { + throw ServerMessages.INVALID_USER_NAME( + "User names must have a length from 1 to 32 characters, begin with a latin letter a-z (upper case or lower case) or an underscore (_), and all other characters must be latin letters, arabic numbers, hyphens (-) or undescores (_)."); + } - execute(new SetPassword(this.user.name, this.password), getAccess()); - execute(new UpdateUser(this.user), getAccess()); - } else { + if (UserSources.isUserExisting(new Principal(this.user.realm, this.user.name))) { throw ServerMessages.ACCOUNT_NAME_NOT_UNIQUE; } } diff --git a/src/main/java/org/caosdb/server/transaction/ListRolesTransaction.java b/src/main/java/org/caosdb/server/transaction/ListRolesTransaction.java new file mode 100644 index 0000000000000000000000000000000000000000..ed3cd3cc5a154e82946e76f9934ee8608fe6980c --- /dev/null +++ b/src/main/java/org/caosdb/server/transaction/ListRolesTransaction.java @@ -0,0 +1,69 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.transaction; + +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; +import org.caosdb.server.accessControl.ACMPermissions; +import org.caosdb.server.accessControl.Role; +import org.caosdb.server.database.backend.transaction.ListRoles; +import org.caosdb.server.database.proto.ProtoUser; + +public class ListRolesTransaction extends AccessControlTransaction { + + private List<Role> roles = null; + + @Override + protected void transaction() throws Exception { + Subject currentUser = SecurityUtils.getSubject(); + roles = + execute(new ListRoles(), getAccess()) + .getRoles() + .stream() + .filter( + role -> + currentUser.isPermitted( + ACMPermissions.PERMISSION_RETRIEVE_ROLE_DESCRIPTION(role.name))) + .collect(Collectors.toList()); + + // remove users. the list will only contain name and description. + for (Role role : roles) { + if (role.users != null) { + Iterator<ProtoUser> iterator = role.users.iterator(); + while (iterator.hasNext()) { + ProtoUser user = iterator.next(); + if (!currentUser.isPermitted( + ACMPermissions.PERMISSION_RETRIEVE_USER_ROLES(user.realm, user.name))) { + iterator.remove(); + } + } + } + } + } + + public List<Role> getRoles() { + return roles; + } +} diff --git a/src/main/java/org/caosdb/server/transaction/ListUsersTransaction.java b/src/main/java/org/caosdb/server/transaction/ListUsersTransaction.java new file mode 100644 index 0000000000000000000000000000000000000000..2ade4e8595f159d1fc6996c1e04913f4195ecd97 --- /dev/null +++ b/src/main/java/org/caosdb/server/transaction/ListUsersTransaction.java @@ -0,0 +1,63 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.transaction; + +import java.util.List; +import java.util.stream.Collectors; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; +import org.caosdb.server.accessControl.ACMPermissions; +import org.caosdb.server.database.backend.transaction.ListUsers; +import org.caosdb.server.database.proto.ProtoUser; + +public class ListUsersTransaction extends AccessControlTransaction { + + private List<ProtoUser> users = null; + + @Override + protected void transaction() throws Exception { + Subject currentUser = SecurityUtils.getSubject(); + users = + execute(new ListUsers(), getAccess()) + .getUsers() + .stream() + .filter( + user -> + currentUser.isPermitted( + ACMPermissions.PERMISSION_RETRIEVE_USER_INFO(user.realm, user.name))) + .collect(Collectors.toList()); + + // remove roles + for (ProtoUser user : users) { + if (user.roles != null) { + if (!currentUser.isPermitted( + ACMPermissions.PERMISSION_RETRIEVE_USER_ROLES(user.realm, user.name))) { + user.roles = null; + } + } + } + } + + public List<ProtoUser> getUsers() { + return users; + } +} diff --git a/src/main/java/org/caosdb/server/transaction/LogUserVisitTransaction.java b/src/main/java/org/caosdb/server/transaction/LogUserVisitTransaction.java new file mode 100644 index 0000000000000000000000000000000000000000..dff0d34fed5bab445bfd761817aecc474def6025 --- /dev/null +++ b/src/main/java/org/caosdb/server/transaction/LogUserVisitTransaction.java @@ -0,0 +1,42 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ +package org.caosdb.server.transaction; + +import org.caosdb.server.database.backend.transaction.LogUserVisit; + +public class LogUserVisitTransaction extends AccessControlTransaction { + + private String realm; + private String username; + private String type; + private long timestamp; + + public LogUserVisitTransaction(long timestamp, String realm, String username, String type) { + this.timestamp = timestamp; + this.realm = realm; + this.username = username; + this.type = type; + } + + @Override + protected void transaction() throws Exception { + execute(new LogUserVisit(timestamp, realm, username, type), getAccess()); + } +} diff --git a/src/main/java/org/caosdb/server/transaction/RetrieveACL.java b/src/main/java/org/caosdb/server/transaction/RetrieveACL.java new file mode 100644 index 0000000000000000000000000000000000000000..cd9c5c0841557da579c3581f876a1180ecd06f8d --- /dev/null +++ b/src/main/java/org/caosdb/server/transaction/RetrieveACL.java @@ -0,0 +1,89 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.transaction; + +import com.google.protobuf.ProtocolStringList; +import java.util.UUID; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authz.AuthorizationException; +import org.caosdb.server.database.backend.transaction.RetrieveEntityACLTransaction; +import org.caosdb.server.entity.Entity; +import org.caosdb.server.entity.EntityInterface; +import org.caosdb.server.entity.container.TransactionContainer; +import org.caosdb.server.permissions.EntityACL; +import org.caosdb.server.permissions.EntityPermission; + +public class RetrieveACL extends Transaction<TransactionContainer> { + + public RetrieveACL(ProtocolStringList idList) { + super( + new TransactionContainer( + SecurityUtils.getSubject(), System.currentTimeMillis(), UUID.randomUUID().toString())); + for (String strId : idList) { + getContainer().add(new Entity(Integer.parseInt(strId))); + } + } + + @Override + public boolean logHistory() { + return false; + } + + @Override + protected void init() throws Exception { + // acquire weak access + setAccess(getAccessManager().acquireReadAccess(this)); + } + + @Override + protected void preCheck() throws InterruptedException, Exception {} + + @Override + protected void postCheck() {} + + @Override + protected void preTransaction() throws InterruptedException {} + + @Override + protected void transaction() throws Exception { + RetrieveEntityACLTransaction t = new RetrieveEntityACLTransaction(null); + for (EntityInterface e : getContainer()) { + EntityACL acl = execute(t.reuse(e.getId()), getAccess()).getEntityAcl(); + if (acl != null && acl.isPermitted(getTransactor(), EntityPermission.RETRIEVE_ACL)) { + e.setEntityACL(acl); + } else if (acl != null + && acl.isPermitted(getTransactor(), EntityPermission.RETRIEVE_ENTITY)) { + throw new AuthorizationException("You are not permitted to update this entity's ACL."); + } else { + e.addError(org.caosdb.server.utils.ServerMessages.ENTITY_DOES_NOT_EXIST); + } + } + } + + @Override + protected void postTransaction() throws Exception {} + + @Override + protected void cleanUp() { + getAccess().release(); + } +} diff --git a/src/main/java/org/caosdb/server/transaction/RetrieveLogRecordTransaction.java b/src/main/java/org/caosdb/server/transaction/RetrieveLogRecordTransaction.java index 7e6c527865566795c397377409b1fc63020ca1dd..2f6cafd6e4e55ab868f69f1d3414a2196f0a4fea 100644 --- a/src/main/java/org/caosdb/server/transaction/RetrieveLogRecordTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/RetrieveLogRecordTransaction.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.logging.Level; import java.util.logging.LogRecord; import org.apache.shiro.SecurityUtils; +import org.caosdb.datetime.UTCDateTime; import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.database.DatabaseAccessManager; import org.caosdb.server.database.access.Access; @@ -37,10 +38,12 @@ public class RetrieveLogRecordTransaction implements TransactionInterface { private final String logger; private final Level level; private final String message; + private UTCDateTime timestamp; public RetrieveLogRecordTransaction( final String logger, final Level level, final String message) { this.level = level; + this.timestamp = UTCDateTime.SystemMillisToUTCDateTime(System.currentTimeMillis()); if (message != null && message.isEmpty()) { this.message = null; } else if (message != null) { @@ -73,4 +76,9 @@ public class RetrieveLogRecordTransaction implements TransactionInterface { public List<LogRecord> getLogRecords() { return this.logRecords; } + + @Override + public UTCDateTime getTimestamp() { + return timestamp; + } } diff --git a/src/main/java/org/caosdb/server/transaction/RetrieveRoleTransaction.java b/src/main/java/org/caosdb/server/transaction/RetrieveRoleTransaction.java index c7c251ba9847fe29f84589297f846f436f2a1309..8e92a347f869b2a6a3e6f2be58d9124e6a9442d7 100644 --- a/src/main/java/org/caosdb/server/transaction/RetrieveRoleTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/RetrieveRoleTransaction.java @@ -22,25 +22,50 @@ */ package org.caosdb.server.transaction; +import java.util.Iterator; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authz.AuthorizationException; +import org.apache.shiro.subject.Subject; +import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.accessControl.Role; import org.caosdb.server.database.backend.transaction.RetrieveRole; +import org.caosdb.server.database.proto.ProtoUser; import org.caosdb.server.utils.ServerMessages; public class RetrieveRoleTransaction extends AccessControlTransaction { private final String name; private Role role; + private Subject transactor; - public RetrieveRoleTransaction(final String name) { + public RetrieveRoleTransaction(final String name, Subject transactor) { + this.transactor = transactor; this.name = name; } + public RetrieveRoleTransaction(final String name) { + this(name, SecurityUtils.getSubject()); + } + @Override protected void transaction() throws Exception { + if (!transactor.isPermitted(ACMPermissions.PERMISSION_RETRIEVE_ROLE_DESCRIPTION(this.name))) { + throw new AuthorizationException("You are not permitted to retrieve this role"); + } this.role = execute(new RetrieveRole(this.name), getAccess()).getRole(); if (this.role == null) { throw ServerMessages.ROLE_DOES_NOT_EXIST; } + if (this.role.users != null) { + Iterator<ProtoUser> iterator = this.role.users.iterator(); + while (iterator.hasNext()) { + ProtoUser user = iterator.next(); + if (!transactor.isPermitted( + ACMPermissions.PERMISSION_RETRIEVE_USER_ROLES(user.realm, user.name))) { + iterator.remove(); + } + } + } } public Role getRole() { diff --git a/src/main/java/org/caosdb/server/transaction/RetrieveUserRolesTransaction.java b/src/main/java/org/caosdb/server/transaction/RetrieveUserRolesTransaction.java index 97e518d06ac9ad5766b3801be8b1f1403cf8af3f..e26e29830a6e3c5f135b467f4622febda195da89 100644 --- a/src/main/java/org/caosdb/server/transaction/RetrieveUserRolesTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/RetrieveUserRolesTransaction.java @@ -23,6 +23,7 @@ package org.caosdb.server.transaction; import java.util.Set; +import org.caosdb.datetime.UTCDateTime; import org.caosdb.server.accessControl.Principal; import org.caosdb.server.accessControl.UserSources; import org.caosdb.server.utils.ServerMessages; @@ -33,8 +34,10 @@ public class RetrieveUserRolesTransaction implements TransactionInterface { private final String user; private Set<String> roles; private final String realm; + private UTCDateTime timestamp; public RetrieveUserRolesTransaction(final String realm, final String user) { + this.timestamp = UTCDateTime.SystemMillisToUTCDateTime(System.currentTimeMillis()); this.realm = realm; this.user = user; } @@ -67,4 +70,9 @@ public class RetrieveUserRolesTransaction implements TransactionInterface { public Set<String> getRoles() { return this.roles; } + + @Override + public UTCDateTime getTimestamp() { + return timestamp; + } } diff --git a/src/main/java/org/caosdb/server/transaction/RetrieveUserTransaction.java b/src/main/java/org/caosdb/server/transaction/RetrieveUserTransaction.java index 228b1585233ae71d3b7130196f68c3b9f83f5ed2..eb24fb24db4f1b6a50a279cfcd9e158003a70948 100644 --- a/src/main/java/org/caosdb/server/transaction/RetrieveUserTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/RetrieveUserTransaction.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,14 +19,16 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.transaction; import java.util.Set; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; +import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.accessControl.Principal; import org.caosdb.server.accessControl.UserSources; -import org.caosdb.server.accessControl.UserStatus; import org.caosdb.server.database.backend.transaction.RetrieveUser; import org.caosdb.server.database.proto.ProtoUser; import org.caosdb.server.utils.ServerMessages; @@ -35,28 +38,32 @@ public class RetrieveUserTransaction extends AccessControlTransaction { private final Principal principal; private ProtoUser user; + private final Subject currentUser; public RetrieveUserTransaction(final String realm, final String name) { - this.principal = new Principal(realm, name); + this(realm, name, SecurityUtils.getSubject()); + } + + public RetrieveUserTransaction(String realm, String username, Subject transactor) { + currentUser = transactor; + this.principal = new Principal(realm, username); } @Override protected void transaction() throws Exception { - if (!UserSources.isUserExisting(this.principal)) { + if (!UserSources.isUserExisting(this.principal) + || !currentUser.isPermitted( + ACMPermissions.PERMISSION_RETRIEVE_USER_INFO( + this.principal.getRealm(), this.principal.getUsername()))) { throw ServerMessages.ACCOUNT_DOES_NOT_EXIST; } this.user = execute(new RetrieveUser(this.principal), getAccess()).getUser(); - if (this.user == null) { - this.user = new ProtoUser(); - this.user.name = this.principal.getUsername(); - this.user.realm = this.principal.getRealm(); - } - if (this.user.status == null) { - this.user.status = UserSources.getDefaultUserStatus(this.principal); - } - if (this.user.email == null) { - this.user.email = UserSources.getDefaultUserEmail(this.principal); + if (user != null && user.roles != null) { + if (!currentUser.isPermitted( + ACMPermissions.PERMISSION_RETRIEVE_USER_ROLES(user.realm, user.name))) { + user.roles = null; + } } } @@ -86,7 +93,7 @@ public class RetrieveUserTransaction extends AccessControlTransaction { return this.user.roles; } - public boolean isActive() { - return this.user.status == UserStatus.ACTIVE; + public ProtoUser getUser() { + return user; } } diff --git a/src/main/java/org/caosdb/server/transaction/TransactionInterface.java b/src/main/java/org/caosdb/server/transaction/TransactionInterface.java index d56407ca854c756a956fe11d9bc98a72f05a4b50..8e01c7d9b407927ebdb6a0528f7dcbc6d5bea40d 100644 --- a/src/main/java/org/caosdb/server/transaction/TransactionInterface.java +++ b/src/main/java/org/caosdb/server/transaction/TransactionInterface.java @@ -22,6 +22,7 @@ */ package org.caosdb.server.transaction; +import org.caosdb.datetime.UTCDateTime; import org.caosdb.server.database.BackendTransaction; import org.caosdb.server.database.access.Access; import org.caosdb.server.database.misc.RollBackHandler; @@ -48,4 +49,6 @@ public interface TransactionInterface { t.executeTransaction(); return t; } + + public UTCDateTime getTimestamp(); } diff --git a/src/main/java/org/caosdb/server/transaction/UpdateACL.java b/src/main/java/org/caosdb/server/transaction/UpdateACL.java new file mode 100644 index 0000000000000000000000000000000000000000..84c73080550d8899f4f1a5156bebb2a44c39df6a --- /dev/null +++ b/src/main/java/org/caosdb/server/transaction/UpdateACL.java @@ -0,0 +1,146 @@ +/* + * This file is a part of the CaosDB Project. + * + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + */ + +package org.caosdb.server.transaction; + +import static org.caosdb.server.query.Query.clearCache; + +import org.apache.shiro.authz.AuthorizationException; +import org.caosdb.server.database.backend.transaction.RetrieveFullEntityTransaction; +import org.caosdb.server.database.backend.transaction.UpdateEntityTransaction; +import org.caosdb.server.entity.EntityInterface; +import org.caosdb.server.entity.UpdateEntity; +import org.caosdb.server.entity.container.TransactionContainer; +import org.caosdb.server.jobs.Job; +import org.caosdb.server.jobs.core.CheckEntityACLRoles; +import org.caosdb.server.jobs.core.JobFailureSeverity; +import org.caosdb.server.permissions.EntityACL; +import org.caosdb.server.permissions.EntityPermission; +import org.caosdb.server.utils.EntityStatus; + +public class UpdateACL extends Transaction<TransactionContainer> + implements WriteTransactionInterface { + + public UpdateACL(TransactionContainer t) { + super(t); + } + + @Override + public boolean logHistory() { + return false; + } + + @Override + protected void init() throws Exception { + getSchedule() + .add( + Job.getJob( + CheckEntityACLRoles.class.getSimpleName(), JobFailureSeverity.ERROR, null, this)); + // reserve write access. Other thread may read until the write access is + // actually acquired. + setAccess(getAccessManager().reserveWriteAccess(this)); + } + + @Override + protected void preCheck() throws InterruptedException, Exception { + TransactionContainer oldContainer = new TransactionContainer(); + + for (EntityInterface e : getContainer()) { + oldContainer.add(new UpdateEntity(e.getId(), null)); + } + + RetrieveFullEntityTransaction t = new RetrieveFullEntityTransaction(oldContainer); + execute(t, getAccess()); + + // the entities in this container only have an id and an ACL. -> Replace + // with full entity and move ACL to full entity if permissions are + // sufficient, otherwise add an error. + getContainer() + .replaceAll( + (e) -> { + EntityInterface result = oldContainer.getEntityById(e.getId()); + + // Check ACL update is permitted (against the old ACL) and set the new ACL afterwards. + EntityACL oldAcl = result.getEntityACL(); + EntityACL newAcl = e.getEntityACL(); + if (oldAcl != null + && oldAcl.isPermitted(getTransactor(), EntityPermission.EDIT_ACL)) { + if (oldAcl.equals(newAcl)) { + // nothing to be done + result.setEntityStatus(EntityStatus.IGNORE); + } else { + if (!oldAcl.getPriorityEntityACL().equals(newAcl.getPriorityEntityACL()) + && !oldAcl.isPermitted(getTransactor(), EntityPermission.EDIT_PRIORITY_ACL)) { + throw new AuthorizationException( + "You are not permitted to change prioritized permission rules of this entity."); + } + + // we're good to go. set new entity acl + result.setEntityACL(newAcl); + result.setEntityStatus(EntityStatus.QUALIFIED); + } + } else if (oldAcl != null + && oldAcl.isPermitted(getTransactor(), EntityPermission.RETRIEVE_ENTITY)) { + // the user knows that this entity exists + throw new AuthorizationException( + "You are not permitted to change permission rules of this entity."); + } else { + // we pretend this entity doesn't exist + result.addError(org.caosdb.server.utils.ServerMessages.ENTITY_DOES_NOT_EXIST); + } + return result; + }); + } + + @Override + protected void postCheck() {} + + @Override + protected void preTransaction() throws InterruptedException { + + setAccess(getAccessManager().acquireWriteAccess(this)); + } + + @Override + protected void transaction() throws Exception { + UpdateEntityTransaction t = new UpdateEntityTransaction(getContainer()); + execute(t, getAccess()); + } + + @Override + protected void postTransaction() throws Exception {} + + @Override + protected void cleanUp() { + getAccess().release(); + } + + @Override + protected void commit() throws Exception { + getAccess().commit(); + clearCache(); + } + + @Override + public String getSRID() { + return getContainer().getRequestId(); + } +} diff --git a/src/main/java/org/caosdb/server/transaction/UpdateRoleTransaction.java b/src/main/java/org/caosdb/server/transaction/UpdateRoleTransaction.java index 7e1632f8a0a9252c6e400d352bb63e133f6ae9e6..a62aff5bb6e90120e6cfd6651acde231cf3519b1 100644 --- a/src/main/java/org/caosdb/server/transaction/UpdateRoleTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/UpdateRoleTransaction.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,36 +19,62 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.transaction; +import java.util.Set; import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.accessControl.Role; -import org.caosdb.server.accessControl.UserSources; import org.caosdb.server.database.backend.transaction.InsertRole; import org.caosdb.server.database.backend.transaction.RetrieveRole; +import org.caosdb.server.database.backend.transaction.SetPermissionRules; +import org.caosdb.server.entity.Message; +import org.caosdb.server.permissions.PermissionRule; import org.caosdb.server.utils.ServerMessages; public class UpdateRoleTransaction extends AccessControlTransaction { private final Role role; + private Set<PermissionRule> newPermissionRules = null; public UpdateRoleTransaction(final Role role) { this.role = role; } - @Override - protected void transaction() throws Exception { - SecurityUtils.getSubject() - .checkPermission(ACMPermissions.PERMISSION_UPDATE_ROLE_DESCRIPTION(this.role.name)); + private void checkPermissions() throws Message { - if (!UserSources.isRoleExisting(this.role.name)) { + Subject subject = SecurityUtils.getSubject(); + subject.checkPermission(ACMPermissions.PERMISSION_UPDATE_ROLE_DESCRIPTION(this.role.name)); + + Role oldRole = execute(new RetrieveRole(this.role.name), getAccess()).getRole(); + if (oldRole == null) { throw ServerMessages.ROLE_DOES_NOT_EXIST; } + if (this.role.permission_rules != null) { + Set<PermissionRule> oldPermissions = Set.copyOf(oldRole.permission_rules); + Set<PermissionRule> newPermissions = Set.copyOf(role.permission_rules); + if (!oldPermissions.equals(newPermissions)) { + if (org.caosdb.server.permissions.Role.ADMINISTRATION.toString().equals(this.role.name)) { + throw ServerMessages.SPECIAL_ROLE_PERMISSIONS_CANNOT_BE_CHANGED(); + } + subject.checkPermission(ACMPermissions.PERMISSION_UPDATE_ROLE_PERMISSIONS(this.role.name)); + this.newPermissionRules = newPermissions; + } + } + } + + @Override + protected void transaction() throws Exception { + checkPermissions(); + execute(new InsertRole(this.role), getAccess()); + if (this.newPermissionRules != null) { + execute(new SetPermissionRules(this.role.name, newPermissionRules), getAccess()); + } RetrieveRole.removeCached(this.role.name); } } diff --git a/src/main/java/org/caosdb/server/transaction/UpdateUserTransaction.java b/src/main/java/org/caosdb/server/transaction/UpdateUserTransaction.java index 330ce5907f601b4b4345c26b1d483029f7d049b1..6e945118c9b0eef7460f41b5062ccb308b0fd956 100644 --- a/src/main/java/org/caosdb/server/transaction/UpdateUserTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/UpdateUserTransaction.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,21 +19,27 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.transaction; +import java.util.HashSet; +import java.util.Set; import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; import org.caosdb.server.accessControl.ACMPermissions; import org.caosdb.server.accessControl.Principal; import org.caosdb.server.accessControl.UserSources; import org.caosdb.server.accessControl.UserStatus; +import org.caosdb.server.database.backend.transaction.RetrieveRole; import org.caosdb.server.database.backend.transaction.RetrieveUser; import org.caosdb.server.database.backend.transaction.SetPassword; import org.caosdb.server.database.backend.transaction.UpdateUser; +import org.caosdb.server.database.backend.transaction.UpdateUserRoles; import org.caosdb.server.database.exceptions.TransactionException; import org.caosdb.server.database.proto.ProtoUser; import org.caosdb.server.entity.Entity; +import org.caosdb.server.entity.Message; import org.caosdb.server.entity.RetrieveEntity; import org.caosdb.server.entity.container.RetrieveContainer; import org.caosdb.server.utils.EntityStatus; @@ -40,10 +47,15 @@ import org.caosdb.server.utils.ServerMessages; import org.caosdb.server.utils.Utils; import org.jdom2.Element; +/** + * This transaction also checks if the current user has sufficient permissions to make the update. + */ public class UpdateUserTransaction extends AccessControlTransaction { private final String password; - private final ProtoUser user = new ProtoUser(); + private final ProtoUser user; + private HashSet<String> newRoles; + private Set<String> oldRoles; public UpdateUserTransaction( final String realm, @@ -52,6 +64,7 @@ public class UpdateUserTransaction extends AccessControlTransaction { final String email, final Integer entity, final String password) { + this.user = new ProtoUser(); this.user.realm = (realm == null ? UserSources.guessRealm(username, UserSources.getInternalRealm().getName()) @@ -63,9 +76,19 @@ public class UpdateUserTransaction extends AccessControlTransaction { this.password = password; } - @Override - protected void transaction() throws Exception { - if (!UserSources.isUserExisting(new Principal(this.user.realm, this.user.name))) { + public UpdateUserTransaction(ProtoUser user, String password) { + this.user = user; + if (this.user.realm == null) { + this.user.realm = + UserSources.guessRealm(this.user.name, UserSources.getInternalRealm().getName()); + } + this.password = password; + } + + private void checkPermissions() throws Message { + Principal principal = new Principal(this.user.realm, this.user.name); + ProtoUser oldUser = execute(new RetrieveUser(principal), getAccess()).getUser(); + if (oldUser == null) { throw ServerMessages.ACCOUNT_DOES_NOT_EXIST; } @@ -94,29 +117,51 @@ public class UpdateUserTransaction extends AccessControlTransaction { } } + if (this.user.roles != null) { + Set<String> oldRoles = oldUser.roles; + if (!this.user.roles.equals(oldRoles)) { + SecurityUtils.getSubject() + .checkPermission( + ACMPermissions.PERMISSION_UPDATE_USER_ROLES(this.user.realm, this.user.name)); + } + this.oldRoles = oldRoles; + this.newRoles = this.user.roles; + } + } + + @Override + protected void transaction() throws Exception { + checkPermissions(); + if (isToBeUpdated()) { execute(new UpdateUser(this.user), getAccess()); } + if (this.newRoles != null) { + execute(new UpdateUserRoles(this.user.realm, this.user.name, this.user.roles), getAccess()); + RetrieveRole.removeCached(newRoles); + if (this.oldRoles != null) { + RetrieveRole.removeCached(oldRoles); + } + } } private boolean isToBeUpdated() throws Exception { + Subject current_user = SecurityUtils.getSubject(); boolean isToBeUpdated = false; final ProtoUser validUser = execute(new RetrieveUser(new Principal(this.user.realm, this.user.name)), getAccess()) .getUser(); if (this.user.status != null && (validUser == null || this.user.status != validUser.status)) { - SecurityUtils.getSubject() - .checkPermission( - ACMPermissions.PERMISSION_UPDATE_USER_STATUS(this.user.realm, this.user.name)); + current_user.checkPermission( + ACMPermissions.PERMISSION_UPDATE_USER_STATUS(this.user.realm, this.user.name)); isToBeUpdated = true; } else if (validUser != null) { this.user.status = validUser.status; } if (this.user.email != null && (validUser == null || !this.user.email.equals(validUser.email))) { - SecurityUtils.getSubject() - .checkPermission( - ACMPermissions.PERMISSION_UPDATE_USER_EMAIL(this.user.realm, this.user.name)); + current_user.checkPermission( + ACMPermissions.PERMISSION_UPDATE_USER_EMAIL(this.user.realm, this.user.name)); if (!Utils.isRFC822Compliant(this.user.email)) { throw ServerMessages.EMAIL_NOT_WELL_FORMED; } @@ -127,9 +172,8 @@ public class UpdateUserTransaction extends AccessControlTransaction { } if (this.user.entity != null && (validUser == null || !this.user.entity.equals(validUser.entity))) { - SecurityUtils.getSubject() - .checkPermission( - ACMPermissions.PERMISSION_UPDATE_USER_ENTITY(this.user.realm, this.user.name)); + current_user.checkPermission( + ACMPermissions.PERMISSION_UPDATE_USER_ENTITY(this.user.realm, this.user.name)); isToBeUpdated = true; if (this.user.entity.equals(0)) { diff --git a/src/main/java/org/caosdb/server/transaction/WriteTransaction.java b/src/main/java/org/caosdb/server/transaction/WriteTransaction.java index 5c730a19ee0cc7e09278a3e7c184884cb4ff1c3e..334e408a82ddc343ed634979dc76e0b11f33a94b 100644 --- a/src/main/java/org/caosdb/server/transaction/WriteTransaction.java +++ b/src/main/java/org/caosdb/server/transaction/WriteTransaction.java @@ -377,7 +377,7 @@ public class WriteTransaction extends Transaction<WritableContainer> .getPriorityEntityACL() .equals(oldEntity.getEntityACL().getPriorityEntityACL())) { // priority acl is to be changed? - oldEntity.checkPermission(Permission.EDIT_PRIORITY_ACL); + oldEntity.checkPermission(EntityPermission.EDIT_PRIORITY_ACL); } updatetable = true; } else if (!newEntity.hasEntityACL()) { @@ -578,6 +578,7 @@ public class WriteTransaction extends Transaction<WritableContainer> return null; } + @Override public String getSRID() { return getContainer().getRequestId(); } diff --git a/src/main/java/org/caosdb/server/transaction/WriteTransactionInterface.java b/src/main/java/org/caosdb/server/transaction/WriteTransactionInterface.java index 165acb408776a720c6887d31b550cf57e3d6fa0c..4e2938e18d061cbd1a7575baa59322356731859a 100644 --- a/src/main/java/org/caosdb/server/transaction/WriteTransactionInterface.java +++ b/src/main/java/org/caosdb/server/transaction/WriteTransactionInterface.java @@ -1,8 +1,13 @@ package org.caosdb.server.transaction; +import org.apache.shiro.subject.Subject; import org.caosdb.server.database.access.Access; public interface WriteTransactionInterface extends TransactionInterface { public Access getAccess(); + + public Subject getTransactor(); + + public String getSRID(); } diff --git a/src/main/java/org/caosdb/server/utils/Info.java b/src/main/java/org/caosdb/server/utils/Info.java index 18ee09828006c0394dec315ca77483f8298ba86b..644239fc662c1b6a05dc1aac37af1bfe26e7972e 100644 --- a/src/main/java/org/caosdb/server/utils/Info.java +++ b/src/main/java/org/caosdb/server/utils/Info.java @@ -28,6 +28,7 @@ import java.sql.SQLException; import java.util.LinkedList; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.caosdb.datetime.UTCDateTime; import org.caosdb.server.CaosDBServer; import org.caosdb.server.FileSystem; import org.caosdb.server.database.DatabaseAccessManager; @@ -46,6 +47,7 @@ public class Info extends AbstractObservable implements Observer, TransactionInt public static final String SYNC_DATABASE_EVENT = "SyncDatabaseEvent"; private final Access access; public Logger logger = LogManager.getLogger(getClass()); + private UTCDateTime timestamp; @Override public boolean notifyObserver(final String e, final Observable o) { @@ -58,6 +60,7 @@ public class Info extends AbstractObservable implements Observer, TransactionInt } private Info() { + this.timestamp = UTCDateTime.SystemMillisToUTCDateTime(System.currentTimeMillis()); this.access = DatabaseAccessManager.getInfoAccess(this); try { syncDatabase(); @@ -246,4 +249,9 @@ public class Info extends AbstractObservable implements Observer, TransactionInt public void execute() throws Exception { syncDatabase(); } + + @Override + public UTCDateTime getTimestamp() { + return timestamp; + } } diff --git a/src/main/java/org/caosdb/server/utils/Initialization.java b/src/main/java/org/caosdb/server/utils/Initialization.java index cb1a36307928a72b9da95b48737196e569c43346..4f28f206bd5f272887fb78b661c6dc46d5cff6bc 100644 --- a/src/main/java/org/caosdb/server/utils/Initialization.java +++ b/src/main/java/org/caosdb/server/utils/Initialization.java @@ -24,6 +24,7 @@ */ package org.caosdb.server.utils; +import org.caosdb.datetime.UTCDateTime; import org.caosdb.server.database.DatabaseAccessManager; import org.caosdb.server.database.access.Access; import org.caosdb.server.transaction.TransactionInterface; @@ -31,9 +32,11 @@ import org.caosdb.server.transaction.TransactionInterface; public final class Initialization implements TransactionInterface, AutoCloseable { private Access access; + private UTCDateTime timestamp; private static final Initialization instance = new Initialization(); private Initialization() { + this.timestamp = UTCDateTime.SystemMillisToUTCDateTime(System.currentTimeMillis()); this.access = DatabaseAccessManager.getInitAccess(this); } @@ -55,4 +58,9 @@ public final class Initialization implements TransactionInterface, AutoCloseable this.access = null; } } + + @Override + public UTCDateTime getTimestamp() { + return timestamp; + } } diff --git a/src/main/java/org/caosdb/server/utils/ServerMessages.java b/src/main/java/org/caosdb/server/utils/ServerMessages.java index 4197f2cf78cedb3fcf9dc0ea6648b6c3335a9da8..151f55face7edbfab793606474f183a65f0468be 100644 --- a/src/main/java/org/caosdb/server/utils/ServerMessages.java +++ b/src/main/java/org/caosdb/server/utils/ServerMessages.java @@ -1,22 +1,26 @@ /* - * ** header v3.0 This file is a part of the CaosDB Project. + * This file is a part of the CaosDB Project. * - * Copyright (C) 2018 Research Group Biomedical Physics, Max-Planck-Institute for Dynamics and - * Self-Organization Göttingen + * Copyright (C) 2018 Research Group Biomedical Physics, Max-Planck-Institute + * for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * - * This program is free software: you can redistribute it and/or modify it under the terms of the - * GNU Affero General Public License as published by the Free Software Foundation, either version 3 - * of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without - * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Affero General Public License for more details. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. * - * You should have received a copy of the GNU Affero General Public License along with this program. - * If not, see <https://www.gnu.org/licenses/>. + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.utils; import org.caosdb.api.entity.v1.MessageCode; @@ -267,6 +271,25 @@ public class ServerMessages { MessageCode.MESSAGE_CODE_UNKNOWN, "Role name is already in use. Choose a different name."); + public static final Message ROLE_CANNOT_BE_DELETED = + new Message( + MessageType.Error, + MessageCode.MESSAGE_CODE_UNKNOWN, + "Role cannot be deleted because there are still users with this role."); + + public static final Message SPECIAL_ROLE_CANNOT_BE_DELETED = + new Message( + MessageType.Error, + MessageCode.MESSAGE_CODE_UNKNOWN, + "This special role cannot be deleted. Ever."); + + public static final Message SPECIAL_ROLE_PERMISSIONS_CANNOT_BE_CHANGED() { + return new Message( + MessageType.Error, + MessageCode.MESSAGE_CODE_UNKNOWN, + "This special role's permissions cannot be changed. Ever."); + } + public static final Message QUERY_EXCEPTION = new Message( MessageType.Error, @@ -336,7 +359,9 @@ public class ServerMessages { public static final Message AUTHORIZATION_ERROR = new Message( - MessageType.Error, MessageCode.MESSAGE_CODE_UNKNOWN, "You are not allowed to do this."); + MessageType.Error, + MessageCode.MESSAGE_CODE_AUTHORIZATION_ERROR, + "You are not allowed to do this."); public static final Message REFERENCE_IS_NOT_ALLOWED_BY_DATATYPE = new Message( @@ -579,4 +604,16 @@ public class ServerMessages { MessageType.Error, MessageCode.MESSAGE_CODE_INTEGRITY_VIOLATION, "This entity caused an unexpected integrity violation. This is a strong indicator for a server bug. Please report."); + + public static final Message INVALID_USER_NAME(String policy) { + return new Message( + MessageType.Error, + MessageCode.MESSAGE_CODE_UNKNOWN, + "The user name does not comply with the policies for user names: " + policy); + } + + public static final Message CANNOT_DELETE_YOURSELF() { + return new Message( + MessageType.Error, MessageCode.MESSAGE_CODE_UNKNOWN, "You cannot delete yourself."); + } } diff --git a/src/test/java/org/caosdb/server/authentication/AuthTokenTest.java b/src/test/java/org/caosdb/server/authentication/AuthTokenTest.java index ca19603230bf6aa989c495fbadabd0989c2a9790..0b19b414517769ee1d6c3882658e870d50193225 100644 --- a/src/test/java/org/caosdb/server/authentication/AuthTokenTest.java +++ b/src/test/java/org/caosdb/server/authentication/AuthTokenTest.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,12 +19,13 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.authentication; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; @@ -53,10 +55,11 @@ import org.caosdb.server.database.backend.interfaces.RetrievePasswordValidatorIm import org.caosdb.server.database.backend.interfaces.RetrievePermissionRulesImpl; import org.caosdb.server.database.backend.interfaces.RetrieveRoleImpl; import org.caosdb.server.database.backend.interfaces.RetrieveUserImpl; +import org.caosdb.server.grpc.AuthInterceptor; import org.caosdb.server.resource.TestScriptingResource.RetrievePasswordValidator; import org.caosdb.server.resource.TestScriptingResource.RetrievePermissionRules; -import org.caosdb.server.resource.TestScriptingResource.RetrieveRole; -import org.caosdb.server.resource.TestScriptingResource.RetrieveUser; +import org.caosdb.server.resource.TestScriptingResource.RetrieveRoleMockup; +import org.caosdb.server.resource.TestScriptingResource.RetrieveUserMockUp; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; @@ -71,9 +74,9 @@ public class AuthTokenTest { @BeforeClass public static void setupShiro() throws IOException { - BackendTransaction.setImpl(RetrieveRoleImpl.class, RetrieveRole.class); + BackendTransaction.setImpl(RetrieveRoleImpl.class, RetrieveRoleMockup.class); BackendTransaction.setImpl(RetrievePermissionRulesImpl.class, RetrievePermissionRules.class); - BackendTransaction.setImpl(RetrieveUserImpl.class, RetrieveUser.class); + BackendTransaction.setImpl(RetrieveUserImpl.class, RetrieveUserMockUp.class); BackendTransaction.setImpl( RetrievePasswordValidatorImpl.class, RetrievePasswordValidator.class); @@ -393,6 +396,7 @@ public class AuthTokenTest { OneTimeAuthenticationToken.initConfig(new CharSequenceInputStream(testYaml, "utf-8")); Subject anonymous = SecurityUtils.getSubject(); + CaosDBServer.setProperty(ServerProperties.KEY_AUTH_OPTIONAL, "true"); anonymous.login(AnonymousAuthenticationToken.getInstance()); OneTimeAuthenticationToken token = @@ -448,4 +452,10 @@ public class AuthTokenTest { assertEquals(9223372036854775000L, config.getExpiresAfter()); assertEquals(922337203685477000L, config.getReplayTimeout()); } + + @Test + public void testSessionTokenCookiePattern() { + String cookie = "SessionToken=%5B%22S%22%22%5D"; + assertTrue(AuthInterceptor.SESSION_TOKEN_COOKIE_PREFIX_PATTERN.matcher(cookie).find()); + } } diff --git a/src/test/java/org/caosdb/server/grpc/CaosDBToGrpcConvertersTest.java b/src/test/java/org/caosdb/server/grpc/CaosDBToGrpcConvertersTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6b21c9b1a5aa4afbe4b018029bf938ae2edd997e --- /dev/null +++ b/src/test/java/org/caosdb/server/grpc/CaosDBToGrpcConvertersTest.java @@ -0,0 +1,56 @@ +package org.caosdb.server.grpc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.TimeZone; +import org.caosdb.datetime.DateTimeFactory2; +import org.caosdb.server.datatype.Value; +import org.caosdb.server.entity.FileProperties; +import org.caosdb.server.entity.RetrieveEntity; +import org.junit.Test; + +public class CaosDBToGrpcConvertersTest { + + @Test + public void testConvertScalarValue_Datetime() { + TimeZone timeZone = TimeZone.getTimeZone("UTC"); + DateTimeFactory2 factory = new DateTimeFactory2(timeZone); + CaosDBToGrpcConverters converters = new CaosDBToGrpcConverters(timeZone); + Value value = null; + assertNull(converters.convertScalarValue(value)); + value = factory.parse("2022"); + assertEquals(converters.convertScalarValue(value).toString(), "string_value: \"2022\"\n"); + value = factory.parse("2022-12"); + assertEquals(converters.convertScalarValue(value).toString(), "string_value: \"2022-12\"\n"); + value = factory.parse("2022-12-24"); + assertEquals(converters.convertScalarValue(value).toString(), "string_value: \"2022-12-24\"\n"); + value = factory.parse("2022-12-24T18:15:00"); + assertEquals( + converters.convertScalarValue(value).toString(), + "string_value: \"2022-12-24T18:15:00+0000\"\n"); + value = factory.parse("2022-12-24T18:15:00.999999"); + assertEquals( + converters.convertScalarValue(value).toString(), + "string_value: \"2022-12-24T18:15:00.999999+0000\"\n"); + value = factory.parse("2022-12-24T18:15:00.999999UTC"); + assertEquals( + converters.convertScalarValue(value).toString(), + "string_value: \"2022-12-24T18:15:00.999999+0000\"\n"); + value = factory.parse("2022-12-24T18:15:00.999999+0200"); + assertEquals( + converters.convertScalarValue(value).toString(), + "string_value: \"2022-12-24T16:15:00.999999+0000\"\n"); + } + + @Test + public void testConvertEntity_FileDescriptor() { + RetrieveEntity entity = new RetrieveEntity(null); + CaosDBToGrpcConverters converters = new CaosDBToGrpcConverters(null); + assertEquals(converters.convert(entity).toString(), "entity {\n}\n"); + entity.setFileProperties(new FileProperties("checksum1234", "the/path", 1024L)); + assertEquals( + converters.convert(entity).toString(), + "entity {\n file_descriptor {\n path: \"the/path\"\n size: 1024\n }\n}\n"); + } +} diff --git a/src/test/java/org/caosdb/server/permissions/EntityACLTest.java b/src/test/java/org/caosdb/server/permissions/EntityACLTest.java index 28b4322333f771a3480e4d386b7e77fb2977590b..30c0cd992573c0c083d863a6d60750dd77d6e035 100644 --- a/src/test/java/org/caosdb/server/permissions/EntityACLTest.java +++ b/src/test/java/org/caosdb/server/permissions/EntityACLTest.java @@ -35,17 +35,23 @@ import java.util.Set; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.caosdb.server.CaosDBServer; +import org.caosdb.server.ServerProperties; import org.caosdb.server.accessControl.AnonymousAuthenticationToken; import org.caosdb.server.accessControl.AuthenticationUtils; import org.caosdb.server.accessControl.Config; +import org.caosdb.server.accessControl.CredentialsValidator; import org.caosdb.server.accessControl.OneTimeAuthenticationToken; +import org.caosdb.server.accessControl.Principal; import org.caosdb.server.accessControl.Role; import org.caosdb.server.database.BackendTransaction; import org.caosdb.server.database.access.Access; +import org.caosdb.server.database.backend.interfaces.RetrievePasswordValidatorImpl; import org.caosdb.server.database.backend.interfaces.RetrievePermissionRulesImpl; import org.caosdb.server.database.backend.interfaces.RetrieveRoleImpl; +import org.caosdb.server.database.backend.interfaces.RetrieveUserImpl; import org.caosdb.server.database.exceptions.TransactionException; import org.caosdb.server.database.misc.TransactionBenchmark; +import org.caosdb.server.database.proto.ProtoUser; import org.caosdb.server.resource.AbstractCaosDBServerResource; import org.caosdb.server.resource.AbstractCaosDBServerResource.XMLParser; import org.caosdb.server.utils.Utils; @@ -103,6 +109,54 @@ public class EntityACLTest { } } + public static class RetrievePasswordValidatorMockup implements RetrievePasswordValidatorImpl { + + public RetrievePasswordValidatorMockup(Access a) {} + + @Override + public void setTransactionBenchmark(TransactionBenchmark b) {} + + @Override + public TransactionBenchmark getBenchmark() { + return null; + } + + @Override + public CredentialsValidator<String> execute(String name) throws TransactionException { + if (name.equals("anonymous")) { + return new CredentialsValidator<String>() { + + @Override + public boolean isValid(String credential) { + return false; + } + }; + } + return null; + } + } + + public static class RetrieveUserMockup implements RetrieveUserImpl { + + public RetrieveUserMockup(Access a) {} + + @Override + public void setTransactionBenchmark(TransactionBenchmark b) {} + + @Override + public TransactionBenchmark getBenchmark() { + return null; + } + + @Override + public ProtoUser execute(Principal principal) throws TransactionException { + if (principal.getUsername().equals("anonymous")) { + return new ProtoUser(); + } + return null; + } + } + @BeforeClass public static void init() throws IOException { CaosDBServer.initServerProperties(); @@ -112,6 +166,9 @@ public class EntityACLTest { BackendTransaction.setImpl( RetrievePermissionRulesImpl.class, RetrievePermissionRulesMockup.class); BackendTransaction.setImpl(RetrieveRoleImpl.class, RetrieveRoleMockup.class); + BackendTransaction.setImpl( + RetrievePasswordValidatorImpl.class, RetrievePasswordValidatorMockup.class); + BackendTransaction.setImpl(RetrieveUserImpl.class, RetrieveUserMockup.class); } @Test @@ -272,6 +329,7 @@ public class EntityACLTest { @Test public void testEntityACLForAnonymous() { Subject anonymous = SecurityUtils.getSubject(); + CaosDBServer.setProperty(ServerProperties.KEY_AUTH_OPTIONAL, "true"); anonymous.login(AnonymousAuthenticationToken.getInstance()); assertTrue(AuthenticationUtils.isAnonymous(anonymous)); EntityACL acl = EntityACL.getOwnerACLFor(anonymous); @@ -279,35 +337,6 @@ public class EntityACLTest { assertTrue(acl.getOwners().isEmpty()); } - // @Test - // public void testParseFromElement() throws JDOMException, IOException { - // Assert.assertEquals("[]", - // EntityACL.serialize(EntityACL.parseFromElement(stringToJdom("<ACL></ACL>")))); - // Assert.assertEquals("[]", EntityACL.serialize(EntityACL - // .parseFromElement(stringToJdom("<ACL><Grant></Grant></ACL>")))); - // Assert.assertEquals("[]", EntityACL.serialize(EntityACL - // .parseFromElement(stringToJdom("<ACL><Deny></Deny></ACL>")))); - // Assert.assertEquals("[]", EntityACL.serialize(EntityACL - // .parseFromElement(stringToJdom("<ACL><Grant role='bla'></Grant></ACL>")))); - // Assert.assertEquals("[]", EntityACL.serialize(EntityACL - // .parseFromElement(stringToJdom("<ACL><Deny role='bla'></Deny></ACL>")))); - // Assert.assertEquals( - // "{bla:2;}", - // EntityACL.serialize(EntityACL - // .parseFromElement(stringToJdom("<ACL><Grant role='bla'><Permission - // name='DELETE'/></Grant></ACL>")))); - // Assert.assertEquals( - // "{bla:" + (Long.MIN_VALUE + 2) + ";}", - // EntityACL.serialize(EntityACL - // .parseFromElement(stringToJdom("<ACL><Deny role='bla'><Permission name='DELETE' - // /></Deny></ACL>")))); - // Assert.assertEquals( - // "{bla:32;}", - // EntityACL.serialize(EntityACL - // .parseFromElement(stringToJdom("<ACL><Grant role='bla'><Permission name='RETRIEVE:ACL' - // /></Grant></ACL>")))); - // } - @Test public void testFactory() { final AbstractEntityACLFactory<EntityACL> f = new EntityACLFactory(); @@ -420,6 +449,7 @@ public class EntityACLTest { EntityACL acl = f.create(); Subject anonymous = SecurityUtils.getSubject(); + CaosDBServer.setProperty(ServerProperties.KEY_AUTH_OPTIONAL, "true"); anonymous.login(AnonymousAuthenticationToken.getInstance()); assertTrue(AuthenticationUtils.isAnonymous(anonymous)); diff --git a/src/test/java/org/caosdb/server/permissions/EntityPermissionTest.java b/src/test/java/org/caosdb/server/permissions/EntityPermissionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..fd7c3e8e7e9a66a8b99ac09487bfa02767497e22 --- /dev/null +++ b/src/test/java/org/caosdb/server/permissions/EntityPermissionTest.java @@ -0,0 +1,92 @@ +package org.caosdb.server.permissions; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class EntityPermissionTest { + + @Test + public void testGRPCMapping() { + assertEquals( + EntityPermission.EDIT_ACL.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_EDIT_ACL); + + assertEquals( + EntityPermission.DELETE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_DELETE); + + assertEquals( + EntityPermission.USE_AS_DATA_TYPE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_USE_AS_DATA_TYPE); + assertEquals( + EntityPermission.USE_AS_PARENT.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_USE_AS_PARENT); + assertEquals( + EntityPermission.USE_AS_PROPERTY.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_USE_AS_PROPERTY); + assertEquals( + EntityPermission.USE_AS_REFERENCE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_USE_AS_REFERENCE); + + assertEquals( + EntityPermission.RETRIEVE_ENTITY.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_ENTITY); + assertEquals( + EntityPermission.RETRIEVE_ACL.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_ACL); + assertEquals( + EntityPermission.RETRIEVE_OWNER.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_OWNER); + assertEquals( + EntityPermission.RETRIEVE_HISTORY.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_HISTORY); + assertEquals( + EntityPermission.RETRIEVE_FILE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_RETRIEVE_FILE); + + assertEquals( + EntityPermission.UPDATE_VALUE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_VALUE); + assertEquals( + EntityPermission.UPDATE_DESCRIPTION.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_DESCRIPTION); + assertEquals( + EntityPermission.UPDATE_DATA_TYPE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_DATA_TYPE); + assertEquals( + EntityPermission.UPDATE_NAME.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_NAME); + assertEquals( + EntityPermission.UPDATE_QUERY_TEMPLATE_DEFINITION.getMapping(), + org.caosdb.api.entity.v1.EntityPermission + .ENTITY_PERMISSION_UPDATE_QUERY_TEMPLATE_DEFINITION); + assertEquals( + EntityPermission.UPDATE_ROLE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_ROLE); + + assertEquals( + EntityPermission.UPDATE_ADD_PARENT.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_ADD_PARENT); + assertEquals( + EntityPermission.UPDATE_REMOVE_PARENT.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_REMOVE_PARENT); + + assertEquals( + EntityPermission.UPDATE_ADD_PROPERTY.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_ADD_PROPERTY); + assertEquals( + EntityPermission.UPDATE_REMOVE_PROPERTY.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_REMOVE_PROPERTY); + + assertEquals( + EntityPermission.UPDATE_ADD_FILE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_ADD_FILE); + assertEquals( + EntityPermission.UPDATE_REMOVE_FILE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_REMOVE_FILE); + assertEquals( + EntityPermission.UPDATE_MOVE_FILE.getMapping(), + org.caosdb.api.entity.v1.EntityPermission.ENTITY_PERMISSION_UPDATE_MOVE_FILE); + } +} diff --git a/src/test/java/org/caosdb/server/query/TestCQL.java b/src/test/java/org/caosdb/server/query/TestCQL.java index cf54bf71b69ea5f539744bd4bbe30fd1c37edcf4..ff1be776b041490aac7c434acdee73c96a9e88f9 100644 --- a/src/test/java/org/caosdb/server/query/TestCQL.java +++ b/src/test/java/org/caosdb/server/query/TestCQL.java @@ -264,6 +264,13 @@ public class TestCQL { String queryMR56 = "FIND ENTITY WITH ((p0 = v0 OR p1=v1) AND p2=v2)"; String versionedQuery1 = "FIND ANY VERSION OF ENTITY e1"; + // https://gitlab.com/caosdb/caosdb-server/-/issues/131 + String issue131a = "FIND ename WITH pname1.x AND pname2"; + String issue131b = "FIND ename WITH (pname1.x < 10) AND (pname1.x)"; + String issue131c = "FIND ename WITH pname2 AND pname1.x "; + String issue131d = "FIND ename WITH (pname1.x) AND pname2"; + String issue131e = "FIND ename WITH (pname1.pname2 > 30) AND (pname1.pname2 < 40)"; + String issue131f = "FIND ename WITH (pname1.pname2 > 30) AND pname1.pname2 < 40"; @Test public void testQuery1() @@ -4341,7 +4348,7 @@ public class TestCQL { assertEquals("THE GREATEST ID", conjunction.getChild(3).getText()); } - /** String query31 = "FIND PROPERTIES WHICH ARE INSERTED TODAY"; */ + /** String query31 = "FIND PROPERTIES WHICH WERE INSERTED TODAY"; */ @Test public void testQuery31() { CQLLexer lexer; @@ -6740,4 +6747,163 @@ public class TestCQL { // must not throw ParsingException new Query(this.queryIssue131).parse(); } + + /** String issue131a = "FIND ename WITH pname1.x AND pname2"; */ + @Test + public void testIssue131a() { + CQLLexer lexer; + lexer = new CQLLexer(CharStreams.fromString(this.issue131a)); + final CommonTokenStream tokens = new CommonTokenStream(lexer); + + final CQLParser parser = new CQLParser(tokens); + final CqContext sfq = parser.cq(); + + System.out.println(sfq.toStringTree(parser)); + + assertTrue(sfq.filter instanceof Conjunction); + LinkedList<EntityFilterInterface> filters = ((Conjunction) sfq.filter).getFilters(); + assertEquals(filters.size(), 2); + assertTrue(filters.get(0) instanceof POV); + assertTrue(filters.get(1) instanceof POV); + POV pov1 = ((POV) filters.get(0)); + POV pov2 = ((POV) filters.get(1)); + assertEquals("POV(pname1,null,null)", pov1.toString()); + assertEquals("POV(pname2,null,null)", pov2.toString()); + assertTrue(pov1.hasSubProperty()); + assertFalse(pov2.hasSubProperty()); + assertEquals("POV(x,null,null)", pov1.getSubProperty().getFilter().toString()); + } + + /** String issue131b = "FIND ename WITH (pname1.x < 10) AND (pname1.x)"; */ + @Test + public void testIssue131b() { + CQLLexer lexer; + lexer = new CQLLexer(CharStreams.fromString(this.issue131b)); + final CommonTokenStream tokens = new CommonTokenStream(lexer); + + final CQLParser parser = new CQLParser(tokens); + final CqContext sfq = parser.cq(); + + System.out.println(sfq.toStringTree(parser)); + + assertTrue(sfq.filter instanceof Conjunction); + LinkedList<EntityFilterInterface> filters = ((Conjunction) sfq.filter).getFilters(); + assertEquals(filters.size(), 2); + assertTrue(filters.get(0) instanceof POV); + assertTrue(filters.get(1) instanceof POV); + POV pov1 = ((POV) filters.get(0)); + POV pov2 = ((POV) filters.get(1)); + assertEquals("POV(pname1,null,null)", pov1.toString()); + assertEquals("POV(pname1,null,null)", pov2.toString()); + assertTrue(pov1.hasSubProperty()); + assertTrue(pov2.hasSubProperty()); + assertEquals("POV(x,<,10)", pov1.getSubProperty().getFilter().toString()); + assertEquals("POV(x,null,null)", pov2.getSubProperty().getFilter().toString()); + } + + /** String issue131c = "FIND ename WITH pname2 AND pname1.x "; */ + @Test + public void testIssue131c() { + CQLLexer lexer; + lexer = new CQLLexer(CharStreams.fromString(this.issue131c)); + final CommonTokenStream tokens = new CommonTokenStream(lexer); + + final CQLParser parser = new CQLParser(tokens); + final CqContext sfq = parser.cq(); + + System.out.println(sfq.toStringTree(parser)); + + assertTrue(sfq.filter instanceof Conjunction); + LinkedList<EntityFilterInterface> filters = ((Conjunction) sfq.filter).getFilters(); + assertEquals(filters.size(), 2); + assertTrue(filters.get(0) instanceof POV); + assertTrue(filters.get(1) instanceof POV); + POV pov1 = ((POV) filters.get(0)); + POV pov2 = ((POV) filters.get(1)); + assertEquals("POV(pname2,null,null)", pov1.toString()); + assertEquals("POV(pname1,null,null)", pov2.toString()); + assertFalse(pov1.hasSubProperty()); + assertTrue(pov2.hasSubProperty()); + assertEquals("POV(x,null,null)", pov2.getSubProperty().getFilter().toString()); + } + + /** String issue131d = "FIND ename WITH (pname1.x) AND pname2"; */ + @Test + public void testIssue131d() { + CQLLexer lexer; + lexer = new CQLLexer(CharStreams.fromString(this.issue131d)); + final CommonTokenStream tokens = new CommonTokenStream(lexer); + + final CQLParser parser = new CQLParser(tokens); + final CqContext sfq = parser.cq(); + + System.out.println(sfq.toStringTree(parser)); + + assertTrue(sfq.filter instanceof Conjunction); + LinkedList<EntityFilterInterface> filters = ((Conjunction) sfq.filter).getFilters(); + assertEquals(filters.size(), 2); + assertTrue(filters.get(0) instanceof POV); + assertTrue(filters.get(1) instanceof POV); + POV pov1 = ((POV) filters.get(0)); + POV pov2 = ((POV) filters.get(1)); + assertEquals("POV(pname1,null,null)", pov1.toString()); + assertEquals("POV(pname2,null,null)", pov2.toString()); + assertTrue(pov1.hasSubProperty()); + assertFalse(pov2.hasSubProperty()); + assertEquals("POV(x,null,null)", pov1.getSubProperty().getFilter().toString()); + } + + /** String issue131e = "FIND ename WITH (pname1.pname2 > 30) AND (pname1.pname2 < 40)"; */ + @Test + public void testIssue131e() { + CQLLexer lexer; + lexer = new CQLLexer(CharStreams.fromString(this.issue131e)); + final CommonTokenStream tokens = new CommonTokenStream(lexer); + + final CQLParser parser = new CQLParser(tokens); + final CqContext sfq = parser.cq(); + + System.out.println(sfq.toStringTree(parser)); + + assertTrue(sfq.filter instanceof Conjunction); + LinkedList<EntityFilterInterface> filters = ((Conjunction) sfq.filter).getFilters(); + assertEquals(filters.size(), 2); + assertTrue(filters.get(0) instanceof POV); + assertTrue(filters.get(1) instanceof POV); + POV pov1 = ((POV) filters.get(0)); + POV pov2 = ((POV) filters.get(1)); + assertEquals("POV(pname1,null,null)", pov1.toString()); + assertEquals("POV(pname1,null,null)", pov2.toString()); + assertTrue(pov1.hasSubProperty()); + assertTrue(pov2.hasSubProperty()); + assertEquals("POV(pname2,>,30)", pov1.getSubProperty().getFilter().toString()); + assertEquals("POV(pname2,<,40)", pov2.getSubProperty().getFilter().toString()); + } + + /** String issue131f = "FIND ename WITH (pname1.pname2 > 30) AND pname1.pname2 < 40"; */ + @Test + public void testIssue131f() { + CQLLexer lexer; + lexer = new CQLLexer(CharStreams.fromString(this.issue131f)); + final CommonTokenStream tokens = new CommonTokenStream(lexer); + + final CQLParser parser = new CQLParser(tokens); + final CqContext sfq = parser.cq(); + + System.out.println(sfq.toStringTree(parser)); + + assertTrue(sfq.filter instanceof Conjunction); + LinkedList<EntityFilterInterface> filters = ((Conjunction) sfq.filter).getFilters(); + assertEquals(filters.size(), 2); + assertTrue(filters.get(0) instanceof POV); + assertTrue(filters.get(1) instanceof POV); + POV pov1 = ((POV) filters.get(0)); + POV pov2 = ((POV) filters.get(1)); + assertEquals("POV(pname1,null,null)", pov1.toString()); + assertEquals("POV(pname1,null,null)", pov2.toString()); + assertTrue(pov1.hasSubProperty()); + assertTrue(pov2.hasSubProperty()); + assertEquals("POV(pname2,>,30)", pov1.getSubProperty().getFilter().toString()); + assertEquals("POV(pname2,<,40)", pov2.getSubProperty().getFilter().toString()); + } } diff --git a/src/test/java/org/caosdb/server/resource/TestAbstractCaosDBServerResource.java b/src/test/java/org/caosdb/server/resource/TestAbstractCaosDBServerResource.java index 5d81ca738d507bcfd75dbe137756135cede3989b..226c9aaac077a56fa96535480418762d30bbb6e9 100644 --- a/src/test/java/org/caosdb/server/resource/TestAbstractCaosDBServerResource.java +++ b/src/test/java/org/caosdb/server/resource/TestAbstractCaosDBServerResource.java @@ -89,6 +89,7 @@ public class TestAbstractCaosDBServerResource { @Test public void testReponseRootElement() throws IOException { final Subject user = new DelegatingSubject(new DefaultSecurityManager(new AnonymousRealm())); + CaosDBServer.setProperty(ServerProperties.KEY_AUTH_OPTIONAL, "true"); user.login(AnonymousAuthenticationToken.getInstance()); AbstractCaosDBServerResource s = new AbstractCaosDBServerResource() { diff --git a/src/test/java/org/caosdb/server/resource/TestScriptingResource.java b/src/test/java/org/caosdb/server/resource/TestScriptingResource.java index 7f7434528678dbd2e1886fade2116d0c9f766740..566c8a09ee301f628bfe9232dde75ad5a66c0207 100644 --- a/src/test/java/org/caosdb/server/resource/TestScriptingResource.java +++ b/src/test/java/org/caosdb/server/resource/TestScriptingResource.java @@ -1,9 +1,10 @@ /* - * ** header v3.0 * This file is a part of the CaosDB Project. * * Copyright (C) 2018 Research Group Biomedical Physics, * Max-Planck-Institute for Dynamics and Self-Organization Göttingen + * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com> + * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,8 +19,8 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * - * ** end header */ + package org.caosdb.server.resource; import static org.junit.Assert.assertEquals; @@ -31,6 +32,7 @@ import java.util.List; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.caosdb.server.CaosDBServer; +import org.caosdb.server.ServerProperties; import org.caosdb.server.accessControl.AnonymousAuthenticationToken; import org.caosdb.server.accessControl.CredentialsValidator; import org.caosdb.server.accessControl.Principal; @@ -64,9 +66,9 @@ import org.restlet.representation.StringRepresentation; public class TestScriptingResource { - public static class RetrieveRole implements RetrieveRoleImpl { + public static class RetrieveRoleMockup implements RetrieveRoleImpl { - public RetrieveRole(Access a) {} + public RetrieveRoleMockup(Access a) {} @Override public Role retrieve(String role) throws TransactionException { @@ -107,9 +109,9 @@ public class TestScriptingResource { public void setTransactionBenchmark(TransactionBenchmark b) {} } - public static class RetrieveUser implements RetrieveUserImpl { + public static class RetrieveUserMockUp implements RetrieveUserImpl { - public RetrieveUser(Access a) {} + public RetrieveUserMockUp(Access a) {} @Override public ProtoUser execute(Principal principal) throws TransactionException { @@ -154,9 +156,9 @@ public class TestScriptingResource { CaosDBServer.initServerProperties(); CaosDBServer.initShiro(); - BackendTransaction.setImpl(RetrieveRoleImpl.class, RetrieveRole.class); + BackendTransaction.setImpl(RetrieveRoleImpl.class, RetrieveRoleMockup.class); BackendTransaction.setImpl(RetrievePermissionRulesImpl.class, RetrievePermissionRules.class); - BackendTransaction.setImpl(RetrieveUserImpl.class, RetrieveUser.class); + BackendTransaction.setImpl(RetrieveUserImpl.class, RetrieveUserMockUp.class); BackendTransaction.setImpl( RetrievePasswordValidatorImpl.class, RetrievePasswordValidator.class); @@ -204,6 +206,7 @@ public class TestScriptingResource { @Test public void testAnonymousWithOutPermission() { Subject user = SecurityUtils.getSubject(); + CaosDBServer.setProperty(ServerProperties.KEY_AUTH_OPTIONAL, "true"); user.login(AnonymousAuthenticationToken.getInstance()); Form form = new Form("call=anonymous_no_permission"); Representation entity = form.getWebRepresentation(); @@ -221,6 +224,7 @@ public class TestScriptingResource { @Test public void testAnonymousWithPermission() { Subject user = SecurityUtils.getSubject(); + CaosDBServer.setProperty(ServerProperties.KEY_AUTH_OPTIONAL, "true"); user.login(AnonymousAuthenticationToken.getInstance()); Form form = new Form("call=anonymous_ok"); Representation entity = form.getWebRepresentation(); @@ -253,6 +257,7 @@ public class TestScriptingResource { @Test public void testHandleForm() throws Message, IOException { Subject user = SecurityUtils.getSubject(); + CaosDBServer.setProperty(ServerProperties.KEY_AUTH_OPTIONAL, "true"); user.login(AnonymousAuthenticationToken.getInstance()); Form form = new Form("call=anonymous_ok"); assertEquals(0, resource.handleForm(form)); diff --git a/src/test/java/org/caosdb/server/resource/TestSharedFileResource.java b/src/test/java/org/caosdb/server/resource/TestSharedFileResource.java index 8dbbd5b1ec25843c3a5b28d46a2fa784f169330d..bff03a45e908419bbaef3a8988df7d9d382a0e8a 100644 --- a/src/test/java/org/caosdb/server/resource/TestSharedFileResource.java +++ b/src/test/java/org/caosdb/server/resource/TestSharedFileResource.java @@ -122,16 +122,10 @@ public class TestSharedFileResource { provideUserSourcesFile(); final Subject user = new DelegatingSubject(new DefaultSecurityManager(new AnonymousRealm())); + CaosDBServer.setProperty(ServerProperties.KEY_AUTH_OPTIONAL, "true"); user.login(AnonymousAuthenticationToken.getInstance()); SharedFileResource resource = new SharedFileResource() { - // @Override - // protected Representation httpGetInChildClass() - // throws ConnectionException, IOException, SQLException, CaosDBException, - // NoSuchAlgorithmException, Exception { - // // TODO Auto-generated method stub - // return super.httpGetInChildClass(); - // } @Override public String getSRID() {