diff --git a/Dockerfile b/Dockerfile index 3841ed935..d42d1dd18 100644 --- a/Dockerfile +++ b/Dockerfile @@ -24,7 +24,7 @@ ENV appname=sheepdog RUN pip install --upgrade pip poetry RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential libffi-dev musl-dev gcc libxml2-dev libxslt-dev \ - curl bash git vim + curl bash git vim postgresql-client RUN mkdir -p /var/www/$appname \ && mkdir -p /var/www/.cache/Python-Eggs/ \ diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..67de100f5 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,2 @@ +[![Creative Commons License](https://i.creativecommons.org/l/by-nc/4.0/88x31.png)](http://creativecommons.org/licenses/by-nc/4.0/) +This work is licensed under a [Creative Commons Attribution-NonCommercial 4.0 International License](http://creativecommons.org/licenses/by-nc/4.0/). diff --git a/sheepdog/api.py b/sheepdog/api.py index 79352c74b..02263f388 100644 --- a/sheepdog/api.py +++ b/sheepdog/api.py @@ -1,5 +1,6 @@ import os import sys +import importlib import logging import traceback @@ -166,6 +167,23 @@ def app_init(app): app.auth = ArboristClient() + app.node_authz_entity_name = os.environ.get("AUTHZ_ENTITY_NAME", None) + app.node_authz_entity = None + app.subject_entity = None + if app.node_authz_entity_name: + full_module_name = "datamodelutils.models" + mymodule = importlib.import_module(full_module_name) + for i in dir(mymodule): + app.logger.warn(i) + if i.lower() == "person": + attribute = getattr(mymodule, i) + app.subject_entity = attribute + if i.lower() == app.node_authz_entity_name.lower(): + attribute = getattr(mymodule, i) + app.node_authz_entity = attribute + + + app = Flask(__name__) diff --git a/sheepdog/auth/__init__.py b/sheepdog/auth/__init__.py index bad753153..bd81faf70 100644 --- a/sheepdog/auth/__init__.py +++ b/sheepdog/auth/__init__.py @@ -15,6 +15,7 @@ import flask from sheepdog.errors import AuthNError, AuthZError +from sheepdog.globals import ROLES logger = get_logger(__name__) @@ -110,20 +111,53 @@ def authorize_and_call(*args, **kwargs): return authorize_and_call -def authorize(program, project, roles): +def authorize(program, project, roles, resource_list=None): resource = "/programs/{}/projects/{}".format(program, project) + + resources = [] + if resource_list: + for res in resource_list: + resources.append(resource + res) + else: + resources = [resource] + jwt = get_jwt_from_header() authz = flask.current_app.auth.auth_request( - jwt=jwt, service="sheepdog", methods=roles, resources=[resource] + jwt=jwt, service="sheepdog", methods=roles, resources=resources ) + if not authz: raise AuthZError("user is unauthorized") -def create_resource(program, project=None): +def create_resource(program, project=None, data=None): resource = "/programs/{}".format(program) + if project: resource += "/projects/{}".format(project) + + if isinstance(data, list): + for d in data: + get_and_create_resource_values(resource, d) + else: + get_and_create_resource_values(resource, data) + + +def get_and_create_resource_values(resource, data): + stop_node = flask.current_app.node_authz_entity + person_node = flask.current_app.subject_entity + if data and data["type"] == person_node.label: + resource += "/persons/{}".format(data["submitter_id"]) + elif data and data["type"] == stop_node.label: + person = None + if isinstance(data["persons"], list): + person = data["persons"][0] + else: + person = data["persons"] + resource += "/persons/{}/subjects/{}".format(person["submitter_id"], data["submitter_id"]) + logger.warn(resource) + + logger.info("Creating arborist resource {}".format(resource)) json_data = { @@ -139,3 +173,73 @@ def create_resource(program, project=None): resp.error.code, resp.error.message ) ) + + +def check_resource_access(program, project, nodes): + subject_submitter_ids = [] + stop_node = flask.current_app.node_authz_entity_name + + for node in nodes: + if node.label == stop_node: + subject_submitter_ids.append({"id": node.node_id, "submitter_id": node.props.get("submitter_id", None)}) + else: + for link in node._pg_links: + tmp_dads = getattr(node, link, None) + if tmp_dads: + tmp_dad = tmp_dads[0] + nodeType = link + path_tmp = nodeType + tmp = node._pg_links[link]["dst_type"] + while tmp.label != stop_node and tmp.label != "program": + # assuming ony one parents + nodeType = list(tmp._pg_links.keys())[0] + path_tmp = path_tmp + "." + nodeType + tmp = tmp._pg_links[nodeType]["dst_type"] + # TODO double check this with deeper relationship > 2 nodes under project + tmp_dad = getattr(tmp_dad, nodeType)[0] + + if tmp.label == stop_node: + subject_submitter_ids.append({"id": tmp_dad.node_id, "submitter_id": tmp_dad.props.get("submitter_id", None)}) + else: + logger.warn("resource not found " + node.label) + logger.warn(node) + + try: + resources = [ + "/{}s/{}".format(stop_node, node["submitter_id"]) + for node in subject_submitter_ids + ] + authorize(program, project, [ROLES["READ"]], resources) + except AuthZError: + return "You do not have read permission on project {} for one or more of the subjects requested" + + +# TEST BUT YOU NEED TO ADD ACTUAL ID LIST NOT ONLY THE ONE LISTED IN THE DB +def get_authorized_ids(program, project): + try: + mapping = flask.current_app.auth.auth_mapping(current_user.username) + except AuthZError as e: + logger.warn( + "Unable to retrieve auth mapping for user `{}`: {}".format(current_user.username, e) + ) + mapping = {} + + base_resource_path = "/programs/{}/projects/{}".format(program, project) + result = [resource_path for resource_path, permissions in mapping.items() if base_resource_path in resource_path] + ids = [] + + for path in result: + parts = path.strip("/").split("/") + if path != "/" and parts[0] != "programs": + continue + + if len(parts) > 6 or (len(parts) > 2 and parts[2] != "projects") or (len(parts) > 4 and (flask.current_app.node_authz_entity_name is None or flask.current_app.node_authz_entity is None or parts[4] != (flask.current_app.node_authz_entity_name + "s"))): + continue + + if len(parts) < 6: + return(None) + else: + ids.append(parts[5]) + + return(ids) + diff --git a/sheepdog/blueprint/routes/views/program/project.py b/sheepdog/blueprint/routes/views/program/project.py index 288e5b134..4c9d568e9 100644 --- a/sheepdog/blueprint/routes/views/program/project.py +++ b/sheepdog/blueprint/routes/views/program/project.py @@ -242,7 +242,6 @@ def get_project_dictionary_entry(program, project, entry): @utils.assert_program_exists -@auth.authorize_for_project(ROLES["READ"]) def get_entities_by_id(program, project, entity_id_string): """ Retrieve existing GDC entities by ID. @@ -276,9 +275,20 @@ def get_entities_by_id(program, project, entity_id_string): :reqheader X-Auth-Token: |reqheader_X-Auth-Token| :resheader Content-Type: |resheader_Content-Type| """ + entity_ids = entity_id_string.split(",") with flask.current_app.db.session_scope(): - nodes = flask.current_app.db.nodes().ids(entity_ids).all() + dictionary_nodes = flask.current_app.db.nodes().ids(entity_ids).props(project_id = program + "-" + project).all() + project_nodes = flask.current_app.db.nodes(models.Project).ids(entity_ids).all() + program_nodes = flask.current_app.db.nodes(models.Program).ids(entity_ids).all() + + nodes = [] + nodes.extend(dictionary_nodes) + nodes.extend(project_nodes) + nodes.extend(program_nodes) + + auth.check_resource_access(program, project, nodes) + entities = {n.node_id: n for n in nodes} missing_entities = set(entity_ids) - set(entities.keys()) if missing_entities: @@ -354,7 +364,6 @@ def delete_entities(program, project, ids, to_delete=None): return delete_entities -@auth.authorize_for_project(ROLES["READ"]) def export_entities(program, project): """ Return a file with the requested entities as an attachment. diff --git a/sheepdog/transactions/upload/__init__.py b/sheepdog/transactions/upload/__init__.py index d0453a403..b0fa34f73 100644 --- a/sheepdog/transactions/upload/__init__.py +++ b/sheepdog/transactions/upload/__init__.py @@ -139,9 +139,17 @@ def handle_single_transaction(role, program, project, **tx_kwargs): flask.current_app.async_pool.schedule( single_transaction_worker, transaction, *doc_args ) + + # create the resource in arborist + auth.create_resource(program, project, doc_args[3]) + return flask.jsonify(response) else: response, code = single_transaction_worker(transaction, *doc_args) + + # create the resource in arborist + auth.create_resource(program, project, doc_args[3]) + return flask.jsonify(response), code diff --git a/sheepdog/utils/transforms/graph_to_doc.py b/sheepdog/utils/transforms/graph_to_doc.py index 0efb1a78b..58c271a66 100644 --- a/sheepdog/utils/transforms/graph_to_doc.py +++ b/sheepdog/utils/transforms/graph_to_doc.py @@ -15,6 +15,9 @@ import flask import psqlgraph +from sqlalchemy.orm import aliased + +from sheepdog import auth from sheepdog import dictionary from sheepdog.errors import ( InternalError, @@ -493,6 +496,7 @@ def get_nodes(self, ids, with_children, without_id): .props(project_id=self.project_id) .all() ) + auth.check_resource_access(self.program, self.project, self.nodes) found_ids = {node.node_id for node in self.nodes} if not found_ids: raise NotFoundError("Unable to find {}".format(", ".join(ids))) @@ -811,19 +815,56 @@ def export_all(node_label, project_id, file_format, db, without_id): # This is used to look up the classes for the linked nodes. # Now, fill out the properties lists from the titles. cls = psqlgraph.Node.get_subclass(node_label) + + # Create alias if joining on itself + recursive_node = '_TimingPartOfTiming_out' + edge = None + node_timing_dst = None + for link in cls._pg_links.values(): + if link["edge_out"] == recursive_node: + titles_linked = [a for a in titles_linked if 'timings.' not in a] + edge = psqlgraph.Edge.get_unique_subclass("timing", "part_of", "timing") + # node_timing_dst = aliased(link["dst_type"]) + # edges = psqlgraph.Edge.get_subclasses() + # edge = psqlgraph.Edge.get_subclass("timingpartoftiming") + # edge = psqlgraph.Edge.get_subclass(link["edge_out"]) + # edge = psqlgraph.Edge.get_unique_subclass("timing", "part_of", "timing") + # print(edge) + # node_timing_dst = aliased(link["dst_type"]) + # userSkillI = aliased(UserSkill) + # join(userSkillF, User.skills).\ + # join(userSkillI, User.skills).\ + node_timing_dst = aliased(link["dst_type"], name='node_timing_1') + linked_props = make_linked_props(cls, titles_linked) + - # Bui ld up the query. The query will contain, firstly, the node class, + # Build up the query. The query will contain, firstly, the node class, # and secondly, all the relevant properties in linked nodes. query_args = [cls] + linked_props + query_args.extend([getattr(node_timing_dst, 'node_id'), getattr(node_timing_dst, 'submitter_id')] if node_timing_dst is not None else []) query = session.query(*query_args).prop("project_id", project_id) + + #add filter by id the user is authorized to access + auth_ids = auth.get_authorized_ids(project_id.split('-')[0], project_id.split('-')[1]) + if auth_ids: + query = query.prop_in('submitter_id', auth_ids) + # Join the related node tables using the links. for link in cls._pg_links.values(): - query = ( - query.outerjoin(link["edge_out"]) - .outerjoin(link["dst_type"]) - .order_by("src_id") - ) + if link["edge_out"] != recursive_node: + query = ( + query.outerjoin(link["edge_out"]) + .outerjoin(link["dst_type"]) + .order_by("src_id") + ) + else: + query = ( + query.outerjoin(edge, cls.node_id==edge.src_id) + .outerjoin(node_timing_dst, node_timing_dst.node_id==edge.dst_id) + .order_by("src_id") + ) + # The result from the query should look like this (header just for # example): # diff --git a/tests/integration/api.py b/tests/integration/api.py index ca040fdb7..988061d99 100644 --- a/tests/integration/api.py +++ b/tests/integration/api.py @@ -7,6 +7,8 @@ import sqlite3 import sys +import os +import importlib from cdispyutils.log import get_handler from flask import Flask, jsonify @@ -72,6 +74,21 @@ def app_init(app): except (ValueError, AssertionError): app.logger.info("Blueprint is already registered!!!") + app.node_authz_entity_name = os.environ.get("AUTHZ_ENTITY_NAME", None) + app.node_authz_entity = None + app.subject_entity = None + if app.node_authz_entity_name: + full_module_name = "datamodelutils.models" + mymodule = importlib.import_module(full_module_name) + for i in dir(mymodule): + app.logger.warn(i) + if i.lower() == "person": + attribute = getattr(mymodule, i) + app.subject_entity = attribute + if i.lower() == app.node_authz_entity_name.lower(): + attribute = getattr(mymodule, i) + app.node_authz_entity = attribute + app = Flask(__name__) diff --git a/tests/integration/datadict/api.py b/tests/integration/datadict/api.py new file mode 100644 index 000000000..382d07f27 --- /dev/null +++ b/tests/integration/datadict/api.py @@ -0,0 +1,266 @@ +# pylint: disable=superfluous-parens +# pylint: disable=redefined-outer-name +"""tests.api + +Complimentary to conftest.py it sets up certain functionality +""" + +import sqlite3 +import sys +import os +import importlib + +import cdis_oauth2client +from cdis_oauth2client import OAuth2Client, OAuth2Error +from cdispyutils.log import get_handler +from flask import Flask, jsonify +from flask_sqlalchemy_session import flask_scoped_session +from indexclient.client import IndexClient +from indexd.index.drivers.alchemy import SQLAlchemyIndexDriver +from indexd.alias.drivers.alchemy import SQLAlchemyAliasDriver +from indexd.auth.drivers.alchemy import SQLAlchemyAuthDriver +from psqlgraph import PsqlGraphDriver +from datamodelutils import models, validators, postgres_admin + +import sheepdog +from sheepdog.errors import APIError, setup_default_handlers, UnhealthyCheck +from sheepdog.version_data import VERSION, COMMIT +from sheepdog.globals import dictionary_version, dictionary_commit + +# recursion depth is increased for complex graph traversals +sys.setrecursionlimit(10000) +DEFAULT_ASYNC_WORKERS = 8 + + +def app_register_blueprints(app): + # TODO: (jsm) deprecate the index endpoints on the root path, + # these are currently duplicated under /index (the ultimate + # path) for migration + v0 = "/v0" + app.url_map.strict_slashes = False + + app.register_blueprint(cdis_oauth2client.blueprint, url_prefix=v0 + "/oauth2") + + +def db_init(app): + app.logger.info("Initializing PsqlGraph driver") + app.db = PsqlGraphDriver( + host=app.config["PSQLGRAPH"]["host"], + user=app.config["PSQLGRAPH"]["user"], + password=app.config["PSQLGRAPH"]["password"], + database=app.config["PSQLGRAPH"]["database"], + set_flush_timestamps=True, + ) + + app.oauth2 = OAuth2Client(**app.config["OAUTH2"]) + + app.logger.info("Initializing Indexd driver") + app.index_client = IndexClient( + app.config["INDEX_CLIENT"]["host"], + version=app.config["INDEX_CLIENT"]["version"], + auth=app.config["INDEX_CLIENT"]["auth"], + ) + + +def app_init(app): + # Register duplicates only at runtime + app.logger.info("Initializing app") + + app.config["REQUIRE_FILE_INDEX_EXISTS"] = ( + # If True, enforce indexd record exists before file node registration + app.config.get("REQUIRE_FILE_INDEX_EXISTS", False) + ) + + app_register_blueprints(app) + db_init(app) + # exclude es init as it's not used yet + # es_init(app) + try: + app.secret_key = app.config["FLASK_SECRET_KEY"] + except KeyError: + app.logger.error("Secret key not set in config! Authentication will not work") + sheepdog_blueprint = sheepdog.create_blueprint("submission") + + try: + app.register_blueprint(sheepdog_blueprint, url_prefix="/v0/submission") + except AssertionError: + app.logger.info("Blueprint is already registered!!!") + + app.node_authz_entity_name = os.environ.get("AUTHZ_ENTITY_NAME", None) + app.node_authz_entity = None + app.subject_entity = None + if app.node_authz_entity_name: + full_module_name = "datamodelutils.models" + mymodule = importlib.import_module(full_module_name) + for i in dir(mymodule): + app.logger.warn(i) + if i.lower() == "person": + attribute = getattr(mymodule, i) + app.subject_entity = attribute + if i.lower() == app.node_authz_entity_name.lower(): + attribute = getattr(mymodule, i) + app.node_authz_entity = attribute + + +app = Flask(__name__) + +# Setup logger +app.logger.addHandler(get_handler()) + +setup_default_handlers(app) + + +@app.route("/_status", methods=["GET"]) +def health_check(): + with app.db.session_scope() as session: + try: + session.execute("SELECT 1") + except Exception: + raise UnhealthyCheck("Unhealthy") + + return "Healthy", 200 + + +@app.route("/_version", methods=["GET"]) +def version(): + dictver = {"version": dictionary_version(), "commit": dictionary_commit()} + base = {"version": VERSION, "commit": COMMIT, "dictionary": dictver} + + return jsonify(base), 200 + + +def _log_and_jsonify_exception(e): + """ + Log an exception and return the jsonified version along with the code. + + This is the error handling mechanism for ``APIErrors`` and + ``OAuth2Errors``. + """ + app.logger.exception(e) + if hasattr(e, "json") and e.json: + return jsonify(**e.json), e.code + return jsonify(message=e.message), e.code + + +app.register_error_handler(APIError, _log_and_jsonify_exception) + +app.register_error_handler(APIError, _log_and_jsonify_exception) +app.register_error_handler(OAuth2Error, _log_and_jsonify_exception) + +OLD_SQLITE = sqlite3.sqlite_version_info < (3, 7, 16) + +INDEX_HOST = "index.sq3" +ALIAS_HOST = "alias.sq3" + + +INDEX_TABLES = { + "index_record": [ + (0, "did", "VARCHAR", 1, None, 1), + (1, "rev", "VARCHAR", 0, None, 0), + (2, "form", "VARCHAR", 0, None, 0), + (3, "size", "INTEGER", 0, None, 0), + ], + "index_record_hash": [ + (0, "did", "VARCHAR", 1, None, 1), + (1, "hash_type", "VARCHAR", 1, None, 1 if OLD_SQLITE else 2), + (2, "hash_value", "VARCHAR", 0, None, 0), + ], + "index_record_url": [ + (0, "did", "VARCHAR", 1, None, 1), + (1, "url", "VARCHAR", 1, None, 1 if OLD_SQLITE else 2), + ], +} + + +# pulled from indexd/tests/test_setup.py +ALIAS_TABLES = { + "alias_record": [ + (0, "name", "VARCHAR", 1, None, 1), + (1, "rev", "VARCHAR", 0, None, 0), + (2, "size", "INTEGER", 0, None, 0), + (3, "release", "VARCHAR", 0, None, 0), + (4, "metastring", "VARCHAR", 0, None, 0), + (5, "keeper_authority", "VARCHAR", 0, None, 0), + ], + "alias_record_hash": [ + (0, "name", "VARCHAR", 1, None, 1), + (1, "hash_type", "VARCHAR", 1, None, 1 if OLD_SQLITE else 2), + (2, "hash_value", "VARCHAR", 0, None, 0), + ], + "alias_record_host_authority": [ + (0, "name", "VARCHAR", 1, None, 1), + (1, "host", "VARCHAR", 1, None, 1 if OLD_SQLITE else 2), + ], +} + + +def setup_sqlite3_index_tables(): + """Setup the SQLite3 index database.""" + + SQLAlchemyIndexDriver("sqlite:///index.sq3") + + with sqlite3.connect(INDEX_HOST) as conn: + connection = conn.execute( + """ + SELECT name FROM sqlite_master WHERE type = 'table' + """ + ) + + tables = [i[0] for i in connection] + + for table in INDEX_TABLES: + assert table in tables, "{table} not created".format(table=table) + + for table, _ in INDEX_TABLES.items(): + # NOTE PRAGMA's don't work with parameters... + connection = conn.execute( + """ + PRAGMA table_info ('{table}') + """.format( + table=table + ) + ) + + +def setup_sqlite3_alias_tables(): + """Setup the SQLite3 alias database.""" + + SQLAlchemyAliasDriver("sqlite:///alias.sq3") + + with sqlite3.connect(ALIAS_HOST) as conn: + connection = conn.execute( + """ + SELECT name FROM sqlite_master WHERE type = 'table' + """ + ) + + tables = [i[0] for i in connection] + + for table in ALIAS_TABLES: + assert table in tables, "{table} not created".format(table=table) + + for table, _ in ALIAS_TABLES.items(): + # NOTE PRAGMA's don't work with parameters... + connection = conn.execute( + """ + PRAGMA table_info ('{table}') + """.format( + table=table + ) + ) + + +def setup_sqlite3_auth_tables(username, password): + """Setup the SQLite3 auth database.""" + auth_driver = SQLAlchemyAuthDriver("sqlite:///auth.sq3") + try: + auth_driver.add(username, password) + except Exception as error: + print("Unable to create auth tables") + print(error) + + +def indexd_init(username, password): + setup_sqlite3_index_tables() + setup_sqlite3_alias_tables() + setup_sqlite3_auth_tables(username, password)