python_code
stringlengths
0
290k
repo_name
stringclasses
30 values
file_path
stringlengths
6
125
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression _has_s3fs = importlib.util.find_spec("s3fs") is not None if _has_s3fs: from .s3filesystem import S3FileSystem # noqa: F401 COMPRESSION_FILESYSTEMS: List[compression.BaseCompressedFileFileSystem] = [ compression.Bz2FileSystem, compression.GzipFileSystem, compression.Lz4FileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(f"A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.") fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def extract_path_from_uri(dataset_path: str) -> str: """ Preprocesses `dataset_path` and removes remote filesystem (e.g. removing `s3://`). Args: dataset_path (`str`): Path (e.g. `dataset/train`) or remote uri (e.g. `s3://my-bucket/dataset/train`) of the dataset directory. """ if "://" in dataset_path: dataset_path = dataset_path.split("://")[1] return dataset_path def is_remote_filesystem(fs: fsspec.AbstractFileSystem) -> bool: """ Validates if filesystem has remote protocol. Args: fs (`fsspec.spec.AbstractFileSystem`): An abstract super-class for pythonic file-systems, e.g. `fsspec.filesystem(\'file\')` or [`datasets.filesystems.S3FileSystem`]. """ if fs is not None and fs.protocol != "file": return True else: return False def rename(fs: fsspec.AbstractFileSystem, src: str, dst: str): """ Renames the file `src` in `fs` to `dst`. """ is_local = not is_remote_filesystem(fs) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(src), fs._strip_protocol(dst)) else: fs.mv(src, dst, recursive=True) def _reset_fsspec_lock() -> None: """ Clear reference to the loop and thread. This is necessary otherwise HTTPFileSystem hangs in the ML training loop. Only required for fsspec >= 0.9.0 See https://github.com/fsspec/gcsfs/issues/379 """ if hasattr(fsspec.asyn, "reset_lock"): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: fsspec.asyn.iothread[0] = None fsspec.asyn.loop[0] = None fsspec.asyn.lock = threading.Lock()
datasets-main
src/datasets/filesystems/__init__.py
import s3fs from ..utils.deprecation_utils import deprecated @deprecated("Use s3fs.S3FileSystem instead.") class S3FileSystem(s3fs.S3FileSystem): """ `datasets.filesystems.S3FileSystem` is a subclass of [`s3fs.S3FileSystem`](https://s3fs.readthedocs.io/en/latest/api.html). Users can use this class to access S3 as if it were a file system. It exposes a filesystem-like API (ls, cp, open, etc.) on top of S3 storage. Provide credentials either explicitly (`key=`, `secret=`) or with boto's credential methods. See botocore documentation for more information. If no credentials are available, use `anon=True`. Args: anon (`bool`, default to `False`): Whether to use anonymous connection (public buckets only). If `False`, uses the key/secret given, or boto's credential resolver (client_kwargs, environment, variables, config files, EC2 IAM server, in that order). key (`str`): If not anonymous, use this access key ID, if specified. secret (`str`): If not anonymous, use this secret access key, if specified. token (`str`): If not anonymous, use this security token, if specified. use_ssl (`bool`, defaults to `True`): Whether to use SSL in connections to S3; may be faster without, but insecure. If `use_ssl` is also set in `client_kwargs`, the value set in `client_kwargs` will take priority. s3_additional_kwargs (`dict`): Parameters that are used when calling S3 API methods. Typically used for things like ServerSideEncryption. client_kwargs (`dict`): Parameters for the botocore client. requester_pays (`bool`, defaults to `False`): Whether `RequesterPays` buckets are supported. default_block_size (`int`): If given, the default block size value used for `open()`, if no specific value is given at all time. The built-in default is 5MB. default_fill_cache (`bool`, defaults to `True`): Whether to use cache filling with open by default. Refer to `S3File.open`. default_cache_type (`str`, defaults to `bytes`): If given, the default `cache_type` value used for `open()`. Set to `none` if no caching is desired. See fsspec's documentation for other available `cache_type` values. version_aware (`bool`, defaults to `False`): Whether to support bucket versioning. If enable this will require the user to have the necessary IAM permissions for dealing with versioned objects. cache_regions (`bool`, defaults to `False`): Whether to cache bucket regions. Whenever a new bucket is used, it will first find out which region it belongs to and then use the client for that region. asynchronous (`bool`, defaults to `False`): Whether this instance is to be used from inside coroutines. config_kwargs (`dict`): Parameters passed to `botocore.client.Config`. **kwargs: Other parameters for core session. session (`aiobotocore.session.AioSession`): Session to be used for all connections. This session will be used inplace of creating a new session inside S3FileSystem. For example: `aiobotocore.session.AioSession(profile='test_user')`. skip_instance_cache (`bool`): Control reuse of instances. Passed on to `fsspec`. use_listings_cache (`bool`): Control reuse of directory listings. Passed on to `fsspec`. listings_expiry_time (`int` or `float`): Control reuse of directory listings. Passed on to `fsspec`. max_paths (`int`): Control reuse of directory listings. Passed on to `fsspec`. Examples: Listing files from public S3 bucket. ```py >>> import datasets >>> s3 = datasets.filesystems.S3FileSystem(anon=True) # doctest: +SKIP >>> s3.ls('public-datasets/imdb/train') # doctest: +SKIP ['dataset_info.json.json','dataset.arrow','state.json'] ``` Listing files from private S3 bucket using `aws_access_key_id` and `aws_secret_access_key`. ```py >>> import datasets >>> s3 = datasets.filesystems.S3FileSystem(key=aws_access_key_id, secret=aws_secret_access_key) # doctest: +SKIP >>> s3.ls('my-private-datasets/imdb/train') # doctest: +SKIP ['dataset_info.json.json','dataset.arrow','state.json'] ``` Using `S3Filesystem` with `botocore.session.Session` and custom `aws_profile`. ```py >>> import botocore >>> from datasets.filesystems import S3Filesystem >>> s3_session = botocore.session.Session(profile_name='my_profile_name') >>> s3 = S3FileSystem(session=s3_session) # doctest: +SKIP ``` Loading dataset from S3 using `S3Filesystem` and [`load_from_disk`]. ```py >>> from datasets import load_from_disk >>> from datasets.filesystems import S3Filesystem >>> s3 = S3FileSystem(key=aws_access_key_id, secret=aws_secret_access_key) # doctest: +SKIP >>> dataset = load_from_disk('s3://my-private-datasets/imdb/train', storage_options=s3.storage_options) # doctest: +SKIP >>> print(len(dataset)) 25000 ``` Saving dataset to S3 using `S3Filesystem` and [`Dataset.save_to_disk`]. ```py >>> from datasets import load_dataset >>> from datasets.filesystems import S3Filesystem >>> dataset = load_dataset("imdb") >>> s3 = S3FileSystem(key=aws_access_key_id, secret=aws_secret_access_key) # doctest: +SKIP >>> dataset.save_to_disk('s3://my-private-datasets/imdb/train', storage_options=s3.storage_options) # doctest: +SKIP ``` """
datasets-main
src/datasets/filesystems/s3filesystem.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from typing import Callable from fastapi import FastAPI from app.db.tasks import close_db_connection, connect_to_db def create_start_app_handler(app: FastAPI) -> Callable: async def start_app() -> None: await connect_to_db(app) return start_app def create_stop_app_handler(app: FastAPI) -> Callable: async def stop_app() -> None: await close_db_connection(app) return stop_app
collaborative-training-auth-main
backend/app/core/tasks.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from databases import DatabaseURL from starlette.config import Config from starlette.datastructures import Secret config = Config(".env") PROJECT_NAME = "whitelist" VERSION = "1.0.0" API_PREFIX = "/api" SECRET_KEY = config("SECRET_KEY", cast=Secret) POSTGRES_USER = config("POSTGRES_USER", cast=str) POSTGRES_PASSWORD = config("POSTGRES_PASSWORD", cast=Secret) POSTGRES_SERVER = config("POSTGRES_SERVER", cast=str, default="db") POSTGRES_PORT = config("POSTGRES_PORT", cast=str, default="5432") POSTGRES_DB = config("POSTGRES_DB", cast=str) DATABASE_URL = config( "DATABASE_URL", cast=DatabaseURL, default=f"postgresql://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_SERVER}:{POSTGRES_PORT}/{POSTGRES_DB}", ) EXPIRATION_MINUTES = 60 * 6
collaborative-training-auth-main
backend/app/core/config.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# import datetime from typing import Optional from pydantic import IPvAnyAddress, validator from app.models.core import CoreModel class HivemindAccess(CoreModel): username: str peer_public_key: bytes expiration_time: datetime.datetime signature: bytes class ExperimentJoinInput(CoreModel): """ All common characteristics of our Experiment resource """ peer_public_key: Optional[bytes] # bytes class ExperimentJoinOutput(CoreModel): """ All common characteristics of our Experiment resource """ coordinator_ip: Optional[IPvAnyAddress] coordinator_port: Optional[int] hivemind_access: HivemindAccess auth_server_public_key: bytes @validator("coordinator_port") def validate_port(cls, port): if port is None: return port if int(port) > 2 ** 16: raise ValueError("port overflow") return port
collaborative-training-auth-main
backend/app/models/experiment_join.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.#
collaborative-training-auth-main
backend/app/models/__init__.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from datetime import datetime from typing import Optional from pydantic import BaseModel, validator class CoreModel(BaseModel): """ Any common logic to be shared by all models goes here. """ pass class DateTimeModelMixin(BaseModel): created_at: Optional[datetime] updated_at: Optional[datetime] @validator("created_at", "updated_at", pre=True) def default_datetime(cls, value: datetime) -> datetime: return value or datetime.datetime.now() class IDModelMixin(BaseModel): id: int
collaborative-training-auth-main
backend/app/models/core.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from typing import Optional from pydantic import IPvAnyAddress, validator from app.models.core import CoreModel, DateTimeModelMixin, IDModelMixin class ExperimentBase(CoreModel): """ All common characteristics of our Experiment resource """ organization_name: Optional[str] model_name: Optional[str] coordinator_ip: Optional[IPvAnyAddress] coordinator_port: Optional[int] @validator("coordinator_port") def validate_port(cls, port): if port is None: return port if int(port) > 2 ** 16: raise ValueError("port overflow") return port class ExperimentCreatePublic(ExperimentBase): organization_name: str model_name: str class ExperimentCreate(ExperimentBase): organization_name: str model_name: str auth_server_public_key: Optional[bytes] auth_server_private_key: Optional[bytes] class ExperimentUpdate(ExperimentBase): pass class ExperimentInDB(IDModelMixin, DateTimeModelMixin, ExperimentBase): organization_name: str model_name: str creator: str auth_server_public_key: Optional[bytes] auth_server_private_key: Optional[bytes] class ExperimentPublic(IDModelMixin, DateTimeModelMixin, ExperimentBase): organization_name: str model_name: str creator: str coordinator_ip: Optional[IPvAnyAddress] coordinator_port: Optional[int] class DeletedExperimentPublic(IDModelMixin, CoreModel): pass
collaborative-training-auth-main
backend/app/models/experiment.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# import logging import os from databases import Database from fastapi import FastAPI from app.core.config import DATABASE_URL logger = logging.getLogger(__name__) async def connect_to_db(app: FastAPI) -> None: DB_URL = f"{DATABASE_URL}_test" if os.environ.get("TESTING") else DATABASE_URL database = Database(DB_URL, min_size=2, max_size=10) try: await database.connect() app.state._db = database except Exception as e: logger.warn("--- DB CONNECTION ERROR ---") logger.warn(e) logger.warn("--- DB CONNECTION ERROR ---") async def close_db_connection(app: FastAPI) -> None: try: await app.state._db.disconnect() except Exception as e: logger.warn("--- DB DISCONNECT ERROR ---") logger.warn(e) logger.warn("--- DB DISCONNECT ERROR ---")
collaborative-training-auth-main
backend/app/db/tasks.py
from typing import Tuple from sqlalchemy import TIMESTAMP, Column, Integer, LargeBinary, MetaData, Table, Text, UniqueConstraint, func from sqlalchemy_utils import IPAddressType metadata = MetaData() def timestamps(indexed: bool = False) -> Tuple[Column, Column]: return ( Column( "created_at", TIMESTAMP(timezone=True), server_default=func.now(), nullable=False, index=indexed, ), Column( "updated_at", TIMESTAMP(timezone=True), server_default=func.now(), nullable=False, index=indexed, ), ) experiments_table = Table( "experiments", metadata, Column("id", Integer, primary_key=True), Column("organization_name", Text, nullable=False, index=True), Column("model_name", Text, nullable=False, index=True), Column("creator", Text, nullable=False, index=True), Column("coordinator_ip", IPAddressType), Column("coordinator_port", Integer), Column("auth_server_public_key", LargeBinary), Column("auth_server_private_key", LargeBinary), *timestamps(), UniqueConstraint("organization_name", "model_name", name="uix_1"), )
collaborative-training-auth-main
backend/app/db/models.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.#
collaborative-training-auth-main
backend/app/db/__init__.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# import logging import os import pathlib import sys from logging.config import fileConfig import alembic from psycopg2 import DatabaseError from sqlalchemy import create_engine, engine_from_config, pool # we're appending the app directory to our path here so that we can import config easily sys.path.append(str(pathlib.Path(__file__).resolve().parents[3])) from app.core.config import DATABASE_URL, POSTGRES_DB # noqa from app.db.models import metadata # noqa # add your model's MetaData object here # for 'autogenerate' support target_metadata = metadata # Alembic Config object, which provides access to values within the .ini file config = alembic.context.config # Interpret the config file for logging fileConfig(config.config_file_name) logger = logging.getLogger("alembic.env") def run_migrations_online() -> None: """ Run migrations in 'online' mode """ DB_URL = f"{DATABASE_URL}_test" if os.environ.get("TESTING") else str(DATABASE_URL) # handle testing config for migrations if os.environ.get("TESTING"): # connect to primary db default_engine = create_engine(str(DATABASE_URL), isolation_level="AUTOCOMMIT") # drop testing db if it exists and create a fresh one with default_engine.connect() as default_conn: default_conn.execute(f"DROP DATABASE IF EXISTS {POSTGRES_DB}_test") default_conn.execute(f"CREATE DATABASE {POSTGRES_DB}_test") connectable = config.attributes.get("connection", None) config.set_main_option("sqlalchemy.url", DB_URL) if connectable is None: connectable = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: alembic.context.configure(connection=connection, target_metadata=target_metadata) with alembic.context.begin_transaction(): alembic.context.run_migrations() def run_migrations_offline() -> None: """ Run migrations in 'offline' mode. """ if os.environ.get("TESTING"): raise DatabaseError("Running testing migrations offline currently not permitted.") alembic.context.configure(url=str(DATABASE_URL), target_metadata=target_metadata) with alembic.context.begin_transaction(): alembic.context.run_migrations() if alembic.context.is_offline_mode(): logger.info("Running migrations offline") run_migrations_offline() else: logger.info("Running migrations online") run_migrations_online()
collaborative-training-auth-main
backend/app/db/migrations/env.py
"""init table Revision ID: a7841c3b04d0 Revises: 1ff5763812c1 Create Date: 2021-11-15 18:16:30.192984 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic revision = "a7841c3b04d0" down_revision = "1ff5763812c1" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_index("ix_users_username", table_name="users") op.drop_table("users") op.drop_index("ix_experiments_name", table_name="experiments") op.drop_index("ix_experiments_owner", table_name="experiments") op.drop_table("experiments") op.drop_index("ix_whitelist_experiment_id", table_name="whitelist") op.drop_table("whitelist") op.drop_table("collaborators") # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.create_table( "collaborators", sa.Column("id", sa.INTEGER(), autoincrement=True, nullable=False), sa.Column("peer_public_key", postgresql.BYTEA(), autoincrement=False, nullable=False), sa.Column("user_id", sa.INTEGER(), autoincrement=False, nullable=False), sa.Column("whitelist_item_id", sa.INTEGER(), autoincrement=False, nullable=False), sa.Column( "created_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=False, ), sa.Column( "updated_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=False, ), sa.PrimaryKeyConstraint("id", name="collaborators_pkey"), ) op.create_table( "whitelist", sa.Column("id", sa.INTEGER(), autoincrement=True, nullable=False), sa.Column("experiment_id", sa.INTEGER(), autoincrement=False, nullable=False), sa.Column("user_id", sa.INTEGER(), autoincrement=False, nullable=False), sa.Column( "created_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=False, ), sa.Column( "updated_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=False, ), sa.PrimaryKeyConstraint("id", name="whitelist_pkey"), ) op.create_index("ix_whitelist_experiment_id", "whitelist", ["experiment_id"], unique=False) op.create_table( "experiments", sa.Column("id", sa.INTEGER(), autoincrement=True, nullable=False), sa.Column("name", sa.TEXT(), autoincrement=False, nullable=False), sa.Column("owner", sa.TEXT(), autoincrement=False, nullable=False), sa.Column( "created_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=False, ), sa.Column( "updated_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=False, ), sa.Column("coordinator_ip", sa.VARCHAR(length=50), autoincrement=False, nullable=True), sa.Column("coordinator_port", sa.INTEGER(), autoincrement=False, nullable=True), sa.Column("auth_server_public_key", postgresql.BYTEA(), autoincrement=False, nullable=True), sa.Column("auth_server_private_key", postgresql.BYTEA(), autoincrement=False, nullable=True), sa.PrimaryKeyConstraint("id", name="experiments_pkey"), ) op.create_index("ix_experiments_owner", "experiments", ["owner"], unique=False) op.create_index("ix_experiments_name", "experiments", ["name"], unique=False) op.create_table( "users", sa.Column("id", sa.INTEGER(), autoincrement=True, nullable=False), sa.Column("username", sa.TEXT(), autoincrement=False, nullable=True), sa.Column( "created_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=False, ), sa.Column( "updated_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=False, ), sa.PrimaryKeyConstraint("id", name="users_pkey"), ) op.create_index("ix_users_username", "users", ["username"], unique=True) # ### end Alembic commands ###
collaborative-training-auth-main
backend/app/db/migrations/versions/a7841c3b04d0_drop_everything.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# """create_main_tables Revision ID: 2dc2179b353f Revises: Create Date: 2021-04-28 07:54:49.181680 """ # noqa from typing import Tuple import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic revision = "2dc2179b353f" down_revision = None branch_labels = None depends_on = None def create_updated_at_trigger() -> None: op.execute( """ CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ language 'plpgsql'; """ ) def timestamps(indexed: bool = False) -> Tuple[sa.Column, sa.Column]: return ( sa.Column( "created_at", sa.TIMESTAMP(timezone=True), server_default=sa.func.now(), nullable=False, index=indexed, ), sa.Column( "updated_at", sa.TIMESTAMP(timezone=True), server_default=sa.func.now(), nullable=False, index=indexed, ), ) def create_experiments_table() -> None: op.create_table( "experiments", sa.Column("id", sa.Integer, primary_key=True), sa.Column("name", sa.Text, nullable=False, index=True), sa.Column("owner", sa.Text, nullable=False, index=True), *timestamps(), ) op.execute( """ CREATE TRIGGER update_experiments_modtime BEFORE UPDATE ON experiments FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); """ ) def create_whitelist_table() -> None: op.create_table( "whitelist", sa.Column("id", sa.Integer, primary_key=True), sa.Column("experiment_id", sa.Integer, nullable=False, index=True), sa.Column("user_id", sa.Integer, nullable=False, index=False), *timestamps(), ) op.execute( """ CREATE TRIGGER update_whitelist_modtime BEFORE UPDATE ON whitelist FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); """ ) def create_users_table() -> None: op.create_table( "users", sa.Column("id", sa.Integer, primary_key=True), sa.Column("username", sa.Text, unique=True, nullable=True, index=True), *timestamps(), ) op.execute( """ CREATE TRIGGER update_user_modtime BEFORE UPDATE ON users FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); """ ) def upgrade() -> None: create_updated_at_trigger() create_experiments_table() create_whitelist_table() create_users_table() def downgrade() -> None: op.drop_table("users") op.drop_table("experiments") op.drop_table("whitelist") op.execute("DROP FUNCTION update_updated_at_column")
collaborative-training-auth-main
backend/app/db/migrations/versions/2dc2179b353f_create_main_tables.py
"""create experiments table Revision ID: 97659da4900e Revises: a7841c3b04d0 Create Date: 2021-11-15 18:18:47.732081 """ import sqlalchemy as sa import sqlalchemy_utils from alembic import op # revision identifiers, used by Alembic revision = "97659da4900e" down_revision = "a7841c3b04d0" branch_labels = None depends_on = None def create_updated_at_trigger() -> None: op.execute( """ CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ language 'plpgsql'; """ ) def upgrade() -> None: create_updated_at_trigger() # ### commands auto generated by Alembic - please adjust! ### op.create_table( "experiments", sa.Column("id", sa.Integer(), nullable=False), sa.Column("organization_name", sa.Text(), nullable=False), sa.Column("model_name", sa.Text(), nullable=False), sa.Column("creator", sa.Text(), nullable=False), sa.Column("coordinator_ip", sqlalchemy_utils.types.ip_address.IPAddressType(length=50), nullable=True), sa.Column("coordinator_port", sa.Integer(), nullable=True), sa.Column("auth_server_public_key", sa.LargeBinary(), nullable=True), sa.Column("auth_server_private_key", sa.LargeBinary(), nullable=True), sa.Column("created_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False), sa.Column("updated_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_index(op.f("ix_experiments_model_name"), "experiments", ["model_name"], unique=False) op.create_index(op.f("ix_experiments_organization_name"), "experiments", ["organization_name"], unique=False) op.execute( """ CREATE TRIGGER update_experiments_modtime BEFORE UPDATE ON experiments FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); """ ) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f("ix_experiments_organization_name"), table_name="experiments") op.drop_index(op.f("ix_experiments_model_name"), table_name="experiments") op.drop_index(op.f("ix_experiments_creator"), table_name="experiments") op.drop_table("experiments") op.execute("DROP FUNCTION update_updated_at_column") # ### end Alembic commands ###
collaborative-training-auth-main
backend/app/db/migrations/versions/97659da4900e_create_experiments_table.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# """add coordinator ip and port Revision ID: abc051ececd5 Revises: 2dc2179b353f Create Date: 2021-04-30 14:23:44.114294 """ import sqlalchemy as sa from alembic import op from sqlalchemy_utils import IPAddressType # revision identifiers, used by Alembic revision = "abc051ececd5" down_revision = "2dc2179b353f" branch_labels = None depends_on = None def upgrade() -> None: op.add_column("experiments", sa.Column("coordinator_ip", IPAddressType)) op.add_column("experiments", sa.Column("coordinator_port", sa.Integer)) def downgrade() -> None: op.drop_column("experiments", "coordinator_ip") op.drop_column("experiments", "coordinator_port")
collaborative-training-auth-main
backend/app/db/migrations/versions/abc051ececd5_add_coordinator_ip_and_port.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# """add_keys Revision ID: ba788d7c81bf Revises: abc051ececd5 Create Date: 2021-05-03 15:29:01.414138 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic revision = "ba788d7c81bf" down_revision = "abc051ececd5" branch_labels = None depends_on = None def upgrade() -> None: op.add_column("whitelist", sa.Column("peer_public_key", sa.Text)) op.add_column("experiments", sa.Column("auth_server_public_key", sa.LargeBinary)) op.add_column("experiments", sa.Column("auth_server_private_key", sa.LargeBinary)) def downgrade() -> None: op.drop_column("whitelist", "peer_public_key") op.drop_column("experiments", "auth_server_public_key") op.drop_column("experiments", "auth_server_private_key")
collaborative-training-auth-main
backend/app/db/migrations/versions/ba788d7c81bf_add_keys.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# """create_collaborator Revision ID: 1ff5763812c1 Revises: ba788d7c81bf Create Date: 2021-05-04 19:04:16.294453 """ from typing import Tuple import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic revision = "1ff5763812c1" down_revision = "ba788d7c81bf" branch_labels = None depends_on = None def timestamps(indexed: bool = False) -> Tuple[sa.Column, sa.Column]: return ( sa.Column( "created_at", sa.TIMESTAMP(timezone=True), server_default=sa.func.now(), nullable=False, index=indexed, ), sa.Column( "updated_at", sa.TIMESTAMP(timezone=True), server_default=sa.func.now(), nullable=False, index=indexed, ), ) def create_collaborators_table() -> None: op.create_table( "collaborators", sa.Column("id", sa.Integer, primary_key=True), sa.Column("peer_public_key", sa.LargeBinary, nullable=False, index=False), sa.Column("user_id", sa.Integer, nullable=False, index=False), sa.Column("whitelist_item_id", sa.Integer, nullable=False, index=False), *timestamps(), ) op.execute( """ CREATE TRIGGER update_collaborators_modtime BEFORE UPDATE ON collaborators FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); """ ) def upgrade() -> None: op.drop_column("whitelist", "peer_public_key") create_collaborators_table() def downgrade() -> None: op.add_column("whitelist", sa.Column("peer_public_key", sa.Text)) op.drop_table("collaborators")
collaborative-training-auth-main
backend/app/db/migrations/versions/1ff5763812c1_create_collaborator.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.#
collaborative-training-auth-main
backend/app/db/repositories/__init__.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from ipaddress import IPv4Address, IPv6Address from typing import List from fastapi import HTTPException from starlette.status import HTTP_400_BAD_REQUEST from app.db.repositories.base import BaseRepository from app.models.experiment import ExperimentCreate, ExperimentInDB, ExperimentUpdate from app.services.authentication import MoonlandingUser COLUMNS = "id, organization_name, model_name, creator, coordinator_ip, coordinator_port, auth_server_public_key, auth_server_private_key, created_at, updated_at" CREATE_EXPERIMENT_QUERY = """ INSERT INTO experiments (organization_name, model_name, creator, coordinator_ip, coordinator_port, auth_server_public_key, auth_server_private_key) VALUES (:organization_name, :model_name, :creator, :coordinator_ip, :coordinator_port, :auth_server_public_key, :auth_server_private_key) RETURNING id, organization_name, model_name, creator, coordinator_ip, coordinator_port, auth_server_public_key, auth_server_private_key, created_at, updated_at; """ GET_EXPERIMENT_BY_ID_QUERY = """ SELECT id, organization_name, model_name, creator, coordinator_ip, coordinator_port, auth_server_public_key, auth_server_private_key, created_at, updated_at FROM experiments WHERE id = :id; """ GET_EXPERIMENT_BY_ORGANIZATON_AND_MODEL_NAME_QUERY = """ SELECT id, organization_name, model_name, creator, coordinator_ip, coordinator_port, auth_server_public_key, auth_server_private_key, created_at, updated_at FROM experiments WHERE model_name = :model_name AND organization_name = :organization_name; """ LIST_ALL_USER_EXPERIMENTS_QUERY = """ SELECT id, organization_name, model_name, creator, coordinator_ip, coordinator_port, auth_server_public_key, auth_server_private_key, created_at, updated_at FROM experiments WHERE creator = :creator; """ UPDATE_EXPERIMENT_BY_ID_QUERY = """ UPDATE experiments SET organization_name = :organization_name, model_name = :model_name, coordinator_ip = :coordinator_ip, coordinator_port = :coordinator_port, creator = :creator WHERE id = :id RETURNING id, organization_name, model_name, creator, coordinator_ip, coordinator_port, auth_server_public_key, auth_server_private_key, created_at, updated_at; """ DELETE_EXPERIMENT_BY_ID_QUERY = """ DELETE FROM experiments WHERE id = :id RETURNING id; """ class ExperimentsRepository(BaseRepository): """ " All database actions associated with the Experiment resource """ async def create_experiment( self, *, new_experiment: ExperimentCreate, requesting_user: MoonlandingUser ) -> ExperimentInDB: new_experiment_table = {**new_experiment.dict(), "creator": requesting_user.username} if "coordinator_ip" in new_experiment_table.keys() and ( isinstance(new_experiment_table["coordinator_ip"], IPv4Address) or isinstance(new_experiment_table["coordinator_ip"], IPv6Address) ): new_experiment_table["coordinator_ip"] = str(new_experiment_table["coordinator_ip"]) experiment = await self.db.fetch_one(query=CREATE_EXPERIMENT_QUERY, values=new_experiment_table) return ExperimentInDB(**experiment) async def get_experiment_by_organization_and_model_name( self, *, organization_name: str, model_name: str ) -> ExperimentInDB: experiment = await self.db.fetch_one( query=GET_EXPERIMENT_BY_ORGANIZATON_AND_MODEL_NAME_QUERY, values={"organization_name": organization_name, "model_name": model_name}, ) if not experiment: return None return ExperimentInDB(**experiment) async def get_experiment_by_id(self, *, id: int) -> ExperimentInDB: experiment = await self.db.fetch_one(query=GET_EXPERIMENT_BY_ID_QUERY, values={"id": id}) if not experiment: return None return ExperimentInDB(**experiment) async def list_all_user_experiments(self, requesting_user: MoonlandingUser) -> List[ExperimentInDB]: experiment_records = await self.db.fetch_all( query=LIST_ALL_USER_EXPERIMENTS_QUERY, values={"creator": requesting_user.username} ) return [ExperimentInDB(**exp) for exp in experiment_records] async def update_experiment_by_id(self, *, id_exp: int, experiment_update: ExperimentUpdate) -> ExperimentInDB: experiment = await self.get_experiment_by_id(id=id_exp) if not experiment: return None experiment_update_params = experiment.copy(update=experiment_update.dict(exclude_unset=True)) values = { **experiment_update_params.dict( exclude={ "auth_server_public_key", "auth_server_private_key", "created_at", "updated_at", } ) } if "coordinator_ip" in values.keys() and ( isinstance(values["coordinator_ip"], IPv4Address) or isinstance(values["coordinator_ip"], IPv6Address) ): values["coordinator_ip"] = str(values["coordinator_ip"]) try: updated_experiment = await self.db.fetch_one(query=UPDATE_EXPERIMENT_BY_ID_QUERY, values=values) except Exception as e: print(e) raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="Invalid update params.") return ExperimentInDB(**updated_experiment) async def delete_experiment_by_id(self, *, id: int) -> int: experiment = await self.get_experiment_by_id(id=id) if not experiment: return None deleted_id = await self.db.execute(query=DELETE_EXPERIMENT_BY_ID_QUERY, values={"id": id}) return deleted_id
collaborative-training-auth-main
backend/app/db/repositories/experiments.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from databases import Database class BaseRepository: def __init__(self, db: Database) -> None: self.db = db
collaborative-training-auth-main
backend/app/db/repositories/base.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.api.routes import router as api_router from app.core import config, tasks def get_application(): app = FastAPI(title=config.PROJECT_NAME, version=config.VERSION) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_event_handler("startup", tasks.create_start_app_handler(app)) app.add_event_handler("shutdown", tasks.create_stop_app_handler(app)) app.include_router(api_router, prefix="/api") return app app = get_application()
collaborative-training-auth-main
backend/app/api/server.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.#
collaborative-training-auth-main
backend/app/api/__init__.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from typing import Callable, Type from databases import Database from fastapi import Depends from starlette.requests import Request from app.db.repositories.base import BaseRepository def get_database(request: Request) -> Database: return request.app.state._db def get_repository(Repo_type: Type[BaseRepository]) -> Callable: def get_repo(db: Database = Depends(get_database)) -> Type[BaseRepository]: return Repo_type(db) return get_repo
collaborative-training-auth-main
backend/app/api/dependencies/database.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.#
collaborative-training-auth-main
backend/app/api/dependencies/__init__.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# import base64 import datetime from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding from app.core.config import EXPIRATION_MINUTES, SECRET_KEY from app.models.experiment_join import HivemindAccess PADDING = padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH) HASH_ALGORITHM = hashes.SHA256() def save_private_key(private_key): pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.BestAvailableEncryption(f"{SECRET_KEY}".encode()), ) return pem def save_public_key(public_key): pem = public_key.public_bytes( encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH, ) return pem def load_private_key(string_in_db): private_key = serialization.load_pem_private_key(string_in_db, f"{SECRET_KEY}".encode()) return private_key def load_public_key(string_in_db): public_key = serialization.load_ssh_public_key(string_in_db) return public_key def create_hivemind_access(peer_public_key: bytes, auth_server_private_key: bytes, username: str): current_time = datetime.datetime.utcnow() expiration_time = current_time + datetime.timedelta(minutes=EXPIRATION_MINUTES) private_key = load_private_key(auth_server_private_key) signature = private_key.sign( f"{username} {peer_public_key} {expiration_time}".encode(), PADDING, HASH_ALGORITHM, ) signature = base64.b64encode(signature) hivemind_access = HivemindAccess( username=username, peer_public_key=peer_public_key, expiration_time=expiration_time, signature=signature, ) return hivemind_access
collaborative-training-auth-main
backend/app/api/dependencies/crypto.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from fastapi import APIRouter, Depends from app.api.routes.experiments import router as experiments_router from app.services.authentication import authenticate router = APIRouter() router.include_router( experiments_router, prefix="/experiments", tags=["experiments"], dependencies=[Depends(authenticate)] )
collaborative-training-auth-main
backend/app/api/routes/__init__.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from cryptography.hazmat.primitives.asymmetric import rsa from fastapi import APIRouter, Body, Depends, HTTPException, Path from starlette.status import HTTP_201_CREATED, HTTP_401_UNAUTHORIZED, HTTP_404_NOT_FOUND from app.api.dependencies import crypto from app.api.dependencies.database import get_repository from app.db.repositories.experiments import ExperimentsRepository from app.models.experiment import ( ExperimentCreate, ExperimentCreatePublic, ExperimentInDB, ExperimentPublic, ExperimentUpdate, ) from app.models.experiment_join import ExperimentJoinInput, ExperimentJoinOutput from app.services.authentication import MoonlandingUser, RepoRole, authenticate router = APIRouter() @router.post("/", response_model=ExperimentPublic, name="experiments:create-experiment", status_code=HTTP_201_CREATED) async def create_new_experiment( new_experiment: ExperimentCreatePublic = Body(..., embed=True), experiments_repo: ExperimentsRepository = Depends(get_repository(ExperimentsRepository)), user: MoonlandingUser = Depends(authenticate), ) -> ExperimentPublic: # collaborators_list = new_experiment.collaborators if new_experiment.organization_name not in [org.name for org in user.orgs if org.role_in_org == RepoRole.admin]: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=f"You need to be an admin of the organization {new_experiment.organization_name} to create a collaborative experiment for the model {new_experiment.model_name}", ) experiment = await experiments_repo.get_experiment_by_organization_and_model_name( organization_name=new_experiment.organization_name, model_name=new_experiment.model_name ) if experiment is not None: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=f"An experiment already exist for the organization {new_experiment.organization_name} and the model {new_experiment.model_name}", ) private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) public_key = private_key.public_key() new_experiment = new_experiment.dict() new_experiment_item = ExperimentCreate( **new_experiment, auth_server_private_key=crypto.save_private_key(private_key), auth_server_public_key=crypto.save_public_key(public_key), ) created_experiment_item = await experiments_repo.create_experiment( new_experiment=new_experiment_item, requesting_user=user ) created_experiment_item = await get_experiment_by_id( id=created_experiment_item.id, experiments_repo=experiments_repo, user=user, ) return created_experiment_item @router.get("/", response_model=ExperimentPublic, name="experiments:get-experiment-by-organization-and-model-name") async def get_experiment_by_organization_and_model_name( organization_name: str, model_name: str, experiments_repo: ExperimentsRepository = Depends(get_repository(ExperimentsRepository)), user: MoonlandingUser = Depends(authenticate), ) -> ExperimentPublic: experiment = await experiments_repo.get_experiment_by_organization_and_model_name( organization_name=organization_name, model_name=model_name ) if not experiment: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="You need to be an admin of the organization to get the collaborative experiment for the model", ) if experiment.organization_name not in [org.name for org in user.orgs if org.role_in_org == RepoRole.admin]: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=f"You need to be an admin of the organization {experiment.organization_name} to get the collaborative experiment for the model {experiment.model_name}", ) experiment_public = ExperimentPublic(**experiment.dict()) return experiment_public @router.get("/{id}/", response_model=ExperimentPublic, name="experiments:get-experiment-by-id") async def get_experiment_by_id( id: int, experiments_repo: ExperimentsRepository = Depends(get_repository(ExperimentsRepository)), user: MoonlandingUser = Depends(authenticate), ) -> ExperimentPublic: experiment = await experiments_repo.get_experiment_by_id(id=id) if not experiment: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="You need to be an admin of the organization to get the collaborative experiment for the model", ) if experiment.organization_name not in [org.name for org in user.orgs if org.role_in_org == RepoRole.admin]: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=f"You need to be an admin of the organization {experiment.organization_name} to get the collaborative experiment for the model {experiment.model_name}", ) experiment_public = ExperimentPublic(**experiment.dict()) return experiment_public @router.put("/{id}/", response_model=ExperimentPublic, name="experiments:update-experiment-by-id") async def update_experiment_by_id( id: int = Path(..., ge=1, title="The ID of the experiment to update."), experiment_update: ExperimentUpdate = Body(..., embed=True), experiments_repo: ExperimentsRepository = Depends(get_repository(ExperimentsRepository)), user: MoonlandingUser = Depends(authenticate), ) -> ExperimentPublic: experiment = await experiments_repo.get_experiment_by_id(id=id) if not experiment: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="You need to be an admin of the organization to update the collaborative experiment for the model", ) if experiment.organization_name not in [org.name for org in user.orgs if org.role_in_org == RepoRole.admin]: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=f"You need to be an admin of the organization {experiment.organization_name} to update the collaborative experiment for the model {experiment.model_name}", ) if not experiment: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No experiment found with that id.") updated_public_experiment = await update_experiment(experiment, experiment_update, user, experiments_repo) return updated_public_experiment async def update_experiment( experiment: ExperimentInDB, experiment_update: ExperimentUpdate, user: MoonlandingUser, experiments_repo: ExperimentsRepository, ): experiment_update = ExperimentUpdate(**experiment_update.dict(exclude_unset=True)) experiment = await experiments_repo.update_experiment_by_id( id_exp=experiment.id, experiment_update=experiment_update ) updated_public_experiment = await get_experiment_by_id( id=experiment.id, experiments_repo=experiments_repo, user=user, ) return updated_public_experiment @router.delete("/{id}/", response_model=ExperimentPublic, name="experiments:delete-experiment-by-id") async def delete_experiment_by_id( id: int = Path(..., ge=1, title="The ID of the experiment to delete."), experiments_repo: ExperimentsRepository = Depends(get_repository(ExperimentsRepository)), user: MoonlandingUser = Depends(authenticate), ) -> ExperimentPublic: experiment = await experiments_repo.get_experiment_by_id(id=id) if not experiment: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="You need to be an admin of the organization to update the collaborative experiment for the model", ) if experiment.organization_name not in [org.name for org in user.orgs if org.role_in_org == RepoRole.admin]: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=f"You need to be an admin of the organization {experiment.organization_name} to delete the collaborative experiment for the model {experiment.model_name}", ) deleted_public_experiment = await delete_experiment(experiment, user, experiments_repo) return deleted_public_experiment async def delete_experiment( experiment: ExperimentInDB, user: MoonlandingUser, experiments_repo: ExperimentsRepository ): deleted_id = await experiments_repo.delete_experiment_by_id(id=experiment.id) if not deleted_id: raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail=f"No experiment found with the id {experiment.id} for the collaborative experiment of the model {experiment.model_name} of the organization {experiment.organization_name}.", ) deleted_exp = ExperimentPublic(**experiment.dict()) return deleted_exp @router.put( "/join", response_model=ExperimentJoinOutput, name="experiments:join-experiment-by-organization-and-model-name", ) async def join_experiment_by_organization_and_model_name( organization_name: str, model_name: str, experiment_join_input: ExperimentJoinInput = Body(..., embed=True), experiments_repo: ExperimentsRepository = Depends(get_repository(ExperimentsRepository)), user: MoonlandingUser = Depends(authenticate), ) -> ExperimentJoinOutput: experiment = await experiments_repo.get_experiment_by_organization_and_model_name( organization_name=organization_name, model_name=model_name ) if not experiment: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="You need to be at least a reader of the organization to join the collaborative experiment for the model", ) if experiment.organization_name not in [org.name for org in user.orgs]: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Access to the experiment denied.", ) exp_pass = await join_experiment(experiment, user, experiment_join_input) return exp_pass @router.put("/join/{id}/", response_model=ExperimentJoinOutput, name="experiments:join-experiment-by-id") async def join_experiment_by_id( id: int = Path(..., ge=1, title="The ID of the experiment the user wants to join."), experiment_join_input: ExperimentJoinInput = Body(..., embed=True), experiments_repo: ExperimentsRepository = Depends(get_repository(ExperimentsRepository)), user: MoonlandingUser = Depends(authenticate), ) -> ExperimentJoinOutput: experiment = await experiments_repo.get_experiment_by_id(id=id) if not experiment: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="You need to be at least a reader of the organization to join the collaborative experiment for the model", ) if experiment.organization_name not in [org.name for org in user.orgs]: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Access to the experiment denied.", ) exp_pass = await join_experiment(experiment, user, experiment_join_input) return exp_pass async def join_experiment( experiment: ExperimentInDB, user: MoonlandingUser, experiment_join_input: ExperimentJoinInput ): if not experiment: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No experiment found with that id.") hivemind_access = crypto.create_hivemind_access( peer_public_key=experiment_join_input.peer_public_key, auth_server_private_key=experiment.auth_server_private_key, username=user.username, ) exp_pass = ExperimentJoinOutput(**experiment.dict(), hivemind_access=hivemind_access) return exp_pass
collaborative-training-auth-main
backend/app/api/routes/experiments.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.#
collaborative-training-auth-main
backend/app/services/__init__.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# from enum import Enum from functools import partial from typing import List, Optional import requests from fastapi import Depends, HTTPException from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase from pydantic import BaseModel from requests import ConnectionError, HTTPError from starlette.status import HTTP_401_UNAUTHORIZED HF_API = "https://huggingface.co/api" class RepoRole(Enum): read = 1 write = 2 admin = 3 class Organization(BaseModel): name: str role_in_org: RepoRole class MoonlandingUser(BaseModel): """Dataclass holding a user info""" username: str email: Optional[str] orgs: Optional[List[Organization]] UnauthenticatedError = partial( HTTPException, status_code=HTTP_401_UNAUTHORIZED, headers={"WWW-Authenticate": 'Bearer realm="Access to the API"'}, ) api_key = HTTPBase(scheme="bearer", auto_error=False) async def authenticate(credentials: Optional[HTTPAuthorizationCredentials] = Depends(api_key)) -> MoonlandingUser: if credentials is None: raise UnauthenticatedError(detail="Not authenticated") if credentials.scheme.lower() != "bearer": raise UnauthenticatedError(detail="Not authenticated") token = credentials.credentials try: user_identity = moonlanding_auth(token) except HTTPError as exc: if exc.response.status_code == 401: raise UnauthenticatedError(detail="Invalid credentials") else: raise UnauthenticatedError(detail="Error when authenticating") except ConnectionError: raise UnauthenticatedError(detail="Authentication backend could not be reached") username = user_identity["name"] email = user_identity["email"] if user_identity["type"] != "user": raise UnauthenticatedError(detail="Invalid credentials. You should use the credentials from a user.") orgs = [Organization(name=org["name"], role_in_org=RepoRole[org["roleInOrg"]]) for org in user_identity["orgs"]] return MoonlandingUser(username=username, email=email, orgs=orgs) def moonlanding_auth(token: str) -> dict: """Validate token with Moon Landing TODO: cache requests to avoid flooding Moon Landing """ auth_repsonse = requests.get(HF_API + "/whoami-v2", headers={"Authorization": f"Bearer {token}"}, timeout=3) auth_repsonse.raise_for_status() return auth_repsonse.json()
collaborative-training-auth-main
backend/app/services/authentication.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# import os import warnings from typing import Tuple import alembic import pytest from alembic.config import Config from asgi_lifespan import LifespanManager from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from databases import Database from fastapi import FastAPI from httpx import AsyncClient from app.api.routes.experiments import create_new_experiment, update_experiment_by_id from app.db.repositories.experiments import ExperimentsRepository from app.models.experiment import ExperimentCreatePublic, ExperimentPublic, ExperimentUpdate from app.models.experiment_join import ExperimentJoinInput from app.services.authentication import MoonlandingUser, Organization, RepoRole # Apply migrations at beginning and end of testing session @pytest.fixture(scope="session") def apply_migrations(): warnings.filterwarnings("ignore", category=DeprecationWarning) os.environ["TESTING"] = "1" config = Config("alembic.ini") alembic.command.upgrade(config, "head") yield alembic.command.downgrade(config, "base") # Create a new application for testing @pytest.fixture def app(apply_migrations: None) -> FastAPI: from app.api.server import get_application app = get_application() return app # Grab a reference to our database when needed @pytest.fixture def db(app: FastAPI) -> Database: return app.state._db # Make requests in our tests @pytest.fixture async def client(app: FastAPI) -> AsyncClient: async with LifespanManager(app): async with AsyncClient( app=app, base_url="http://testserver", headers={"Content-Type": "application/json"} ) as client: yield client # Fixtures for authenticated User1 # Create an organization @pytest.fixture def organization_1_admin(): return Organization(name="org_1", role_in_org=RepoRole.admin) @pytest.fixture def organization_3_admin(): return Organization(name="org_3", role_in_org=RepoRole.admin) @pytest.fixture def organization_a_admin(): return Organization(name="organization_a", role_in_org=RepoRole.admin) @pytest.fixture def Organization_a_admin(): return Organization(name="Organization_a", role_in_org=RepoRole.admin) @pytest.fixture def organization_1_read(): return Organization(name="org_1", role_in_org=RepoRole.read) @pytest.fixture def organization_2_read(): return Organization(name="org_2", role_in_org=RepoRole.read) # Create a user for testing @pytest.fixture def moonlanding_user_1( organization_1_admin, Organization_a_admin, organization_a_admin, organization_2_read ) -> MoonlandingUser: moonlanding_user_1 = MoonlandingUser( username="User1", email="user1@test.co", orgs=[organization_1_admin, Organization_a_admin, organization_a_admin, organization_2_read], ) return moonlanding_user_1 # Make requests in our tests @pytest.fixture async def client_wt_auth_user_1(app: FastAPI, moonlanding_user_1: MoonlandingUser) -> AsyncClient: from app.services.authentication import authenticate app.dependency_overrides[authenticate] = lambda: moonlanding_user_1 async with LifespanManager(app): async with AsyncClient( app=app, base_url="http://testserver", headers={"Content-Type": "application/json"} ) as client: yield client @pytest.fixture async def test_experiment_1_created_by_user_1(db: Database, moonlanding_user_1: MoonlandingUser) -> ExperimentPublic: experiments_repo = ExperimentsRepository(db) organization_name = "org_1" model_name = "model_1" experiment = await experiments_repo.get_experiment_by_organization_and_model_name( organization_name=organization_name, model_name=model_name ) if experiment: return experiment new_experiment = ExperimentCreatePublic(organization_name=organization_name, model_name=model_name) new_exp = await create_new_experiment( new_experiment=new_experiment, experiments_repo=experiments_repo, user=moonlanding_user_1, ) return new_exp @pytest.fixture async def test_experiment_2_created_by_user_1_for_updates_tests( db: Database, moonlanding_user_1: MoonlandingUser ) -> ExperimentPublic: experiments_repo = ExperimentsRepository(db) organization_name = "organization_a" model_name = "model_1" experiment = await experiments_repo.get_experiment_by_organization_and_model_name( organization_name=organization_name, model_name=model_name ) if experiment: return experiment new_experiment = ExperimentCreatePublic(organization_name=organization_name, model_name=model_name) new_exp = await create_new_experiment( new_experiment=new_experiment, experiments_repo=experiments_repo, user=moonlanding_user_1, ) return new_exp @pytest.fixture async def test_experiment_join_input_1_by_user_2() -> Tuple[ExperimentJoinInput, rsa.RSAPrivateKey]: private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) serialized_public_key = private_key.public_key().public_bytes( encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH ) return ExperimentJoinInput(peer_public_key=serialized_public_key), private_key @pytest.fixture async def test_experiment_join_input_2_by_user_2() -> Tuple[ExperimentJoinInput, rsa.RSAPrivateKey]: private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) serialized_public_key = private_key.public_key().public_bytes( encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH ) return ExperimentJoinInput(peer_public_key=serialized_public_key), private_key # Fixtures for authenticated User2 # Create a user for testing @pytest.fixture def moonlanding_user_2(organization_3_admin, organization_1_read) -> MoonlandingUser: moonlanding_user_2 = MoonlandingUser( username="User2", email="user2@test.co", orgs=[organization_1_read, organization_3_admin] ) return moonlanding_user_2 @pytest.fixture async def client_wt_auth_user_2(app: FastAPI, moonlanding_user_2: MoonlandingUser) -> AsyncClient: from app.services.authentication import authenticate app.dependency_overrides[authenticate] = lambda: moonlanding_user_2 async with LifespanManager(app): async with AsyncClient( app=app, base_url="http://testserver", headers={"Content-Type": "application/json"} ) as client: yield client @pytest.fixture async def test_experiment_1_created_by_user_2(db: Database, moonlanding_user_2: MoonlandingUser) -> ExperimentPublic: experiments_repo = ExperimentsRepository(db) organization_name = "org_3" model_name = "model_1" experiment = await experiments_repo.get_experiment_by_organization_and_model_name( organization_name=organization_name, model_name=model_name ) if experiment: return experiment new_experiment = ExperimentCreatePublic(organization_name=organization_name, model_name=model_name) experiment = await create_new_experiment( new_experiment=new_experiment, experiments_repo=experiments_repo, user=moonlanding_user_2, ) exp = await update_experiment_by_id( id=experiment.id, experiment_update=ExperimentUpdate(coordinator_ip="192.0.2.0", coordinator_port=80), experiments_repo=experiments_repo, user=moonlanding_user_2, ) return exp
collaborative-training-auth-main
backend/tests/conftest.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.#
collaborative-training-auth-main
backend/tests/__init__.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# import asyncio import os import unittest from typing import Any, Dict from unittest.mock import patch from fastapi.exceptions import HTTPException from fastapi.security.http import HTTPAuthorizationCredentials from requests import ConnectionError from requests.models import HTTPError from starlette.responses import Response from starlette.status import HTTP_401_UNAUTHORIZED from app.services.authentication import authenticate class AsyncTestCase(unittest.TestCase): """Utility to run async tests""" def __init__(self, methodName="runTest", loop=None): self.loop = loop or asyncio.get_event_loop() self._function_cache = {} super().__init__(methodName=methodName) def coroutine_function_decorator(self, func): def wrapper(*args, **kw): return self.loop.run_until_complete(func(*args, **kw)) return wrapper def __getattribute__(self, item): attr = object.__getattribute__(self, item) if asyncio.iscoroutinefunction(attr): if item not in self._function_cache: self._function_cache[item] = self.coroutine_function_decorator(attr) return self._function_cache[item] return attr class TestAuthenticate(AsyncTestCase): def setUp(self): super().setUp() self.moonlanding_mock = patch("app.services.authentication.moonlanding_auth").start() getenv_mock = patch("os.getenv").start() getenv_mock.side_effect = lambda name: os.getenv(name) if name != "PRODUCTION" else "1" self.addCleanup(patch.stopall) self.base_scope = {"type": "http", "path": "/", "headers": []} def set_moonlanding_response( self, ): # TODO non-user resp: Dict[str, Any] = {"type": "user", "name": "autotest", "email": "auto@test.co", "orgs": []} self.moonlanding_mock.return_value = resp async def test_validation(self): # Invalid credentials creds = None with self.assertRaises(HTTPException) as exc_info: await authenticate(creds) self.assertEqual(exc_info.exception.status_code, HTTP_401_UNAUTHORIZED) # Wrong prefix creds = HTTPAuthorizationCredentials(scheme="wrong", credentials="api_fake") with self.assertRaises(HTTPException) as exc_info: await authenticate(creds) self.assertEqual(exc_info.exception.status_code, HTTP_401_UNAUTHORIZED) async def test_moonlanding_error(self): creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials="api_fake") # Connection error self.moonlanding_mock.side_effect = ConnectionError() with self.assertRaises(HTTPException) as err_ctx: await authenticate(creds) self.assertEqual(err_ctx.exception.status_code, HTTP_401_UNAUTHORIZED) self.assertIn("Authentication backend could not be reached", err_ctx.exception.detail) # Invalid credentials self.moonlanding_mock.side_effect = HTTPError(response=Response(status_code=401)) with self.assertRaises(HTTPException) as err_ctx: await authenticate(creds) self.assertEqual(err_ctx.exception.status_code, HTTP_401_UNAUTHORIZED) self.assertIn("Invalid credentials", err_ctx.exception.detail) # Other error codes for err_code in [500, 403, 404]: with self.subTest("Error code: " + str(err_code)): self.moonlanding_mock.side_effect = HTTPError(response=Response(status_code=err_code)) with self.assertRaises(HTTPException) as err_ctx: await authenticate(creds) self.assertEqual(err_ctx.exception.status_code, HTTP_401_UNAUTHORIZED) self.assertIn("Error when authenticating", err_ctx.exception.detail) async def test_auth_guards_user(self): creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials="api_faketoken") self.set_moonlanding_response() await authenticate(creds)
collaborative-training-auth-main
backend/tests/test_authentication.py
# # Copyright (c) 2021 the Hugging Face team. # # 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.# import base64 import datetime from ipaddress import IPv4Address, IPv6Address from typing import List import pytest from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey from fastapi import FastAPI, status from httpx import AsyncClient from app.api.dependencies import crypto from app.models.experiment import ExperimentCreate, ExperimentCreatePublic, ExperimentPublic, ExperimentUpdate from app.models.experiment_join import ExperimentJoinInput, ExperimentJoinOutput # decorate all tests with @pytest.mark.asyncio pytestmark = pytest.mark.asyncio @pytest.fixture def new_experiment(): return ExperimentCreatePublic(organization_name="organization_a", model_name="model-a") def encrypt_msg(msg: str, public_key: RSAPublicKey): ciphertext = public_key.encrypt( msg.encode(), padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None) ) return ciphertext def decrypt_msg(ciphertext: str, private_key: RSAPrivateKey): plaintext = private_key.decrypt( ciphertext, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None) ) return plaintext.decode() class TestExperimentsRoutes: async def test_routes_exist(self, app: FastAPI, client_wt_auth_user_1: AsyncClient) -> None: res = await client_wt_auth_user_1.post(app.url_path_for("experiments:create-experiment"), json={}) assert res.status_code != status.HTTP_404_NOT_FOUND async def test_invalid_input_raises_error(self, app: FastAPI, client_wt_auth_user_1: AsyncClient) -> None: res = await client_wt_auth_user_1.post(app.url_path_for("experiments:create-experiment"), json={}) assert res.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY class TestCreateExperiment: @pytest.mark.parametrize( "new_experiment", ( (ExperimentCreatePublic(organization_name="organization_a", model_name="model-a")), (ExperimentCreatePublic(organization_name="Organization_a", model_name="modelA")), (ExperimentCreatePublic(organization_name="org_1", model_name="modelA")), ), ) async def test_valid_input( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, moonlanding_user_1, new_experiment: ExperimentCreatePublic, ) -> None: res = await client_wt_auth_user_1.post( app.url_path_for("experiments:create-experiment"), json={"new_experiment": new_experiment.dict()}, ) assert res.status_code == status.HTTP_201_CREATED created_experiment = ExperimentPublic(**res.json()) assert created_experiment.organization_name == new_experiment.organization_name assert created_experiment.model_name == new_experiment.model_name assert created_experiment.creator == moonlanding_user_1.username @pytest.mark.parametrize( "invalid_payload, status_code", ( (None, 422), ({}, 422), ), ) async def test_invalid_input_raises_error( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, invalid_payload: dict, status_code: int ) -> None: res = await client_wt_auth_user_1.post( app.url_path_for("experiments:create-experiment"), json={"new_experiment": invalid_payload} ) assert res.status_code == status_code @pytest.mark.parametrize( "new_experiment, status_code", ( (ExperimentCreatePublic(organization_name="org_2", model_name="model-a"), 401), (ExperimentCreatePublic(organization_name="fake_org", model_name="model-a"), 401), ), ) async def test_not_admin_raises_error( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, new_experiment: ExperimentCreatePublic, status_code: int, ) -> None: res = await client_wt_auth_user_1.post( app.url_path_for("experiments:create-experiment"), json={"new_experiment": new_experiment.dict()} ) assert res.status_code == status_code async def test_unauthenticated_user_unable_to_create_experiment( self, app: FastAPI, client: AsyncClient, new_experiment: ExperimentCreate ) -> None: res = await client.post( app.url_path_for("experiments:create-experiment"), json={"new_experiment": new_experiment.dict()}, ) assert res.status_code == status.HTTP_401_UNAUTHORIZED class TestGetExperimentById: async def test_get_experiment_by_id_valid_query_by_user_1( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_1_created_by_user_1: ExperimentPublic, ) -> None: res = await client_wt_auth_user_1.get( app.url_path_for("experiments:get-experiment-by-id", id=test_experiment_1_created_by_user_1.id) ) assert res.status_code == status.HTTP_200_OK experiment = ExperimentPublic(**res.json()) assert experiment == test_experiment_1_created_by_user_1 async def test_get_experiment_by_id_unvalid_query_by_user_1( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_1_created_by_user_2: ExperimentPublic, ) -> None: res = await client_wt_auth_user_1.get( app.url_path_for("experiments:get-experiment-by-id", id=test_experiment_1_created_by_user_2.id) ) assert res.status_code == status.HTTP_401_UNAUTHORIZED @pytest.mark.parametrize( "id, status_code", ( (500, 401), (-1, 401), (None, 422), ), ) async def test_wrong_id_returns_error( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, id: int, status_code: int ) -> None: res = await client_wt_auth_user_1.get(app.url_path_for("experiments:get-experiment-by-id", id=id)) assert res.status_code == status_code class TestGetExperimentByOrgAndModelName: async def test_get_experiment_by_org_and_model_name_valid_query_by_user_1( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_1_created_by_user_1: ExperimentPublic, ) -> None: res = await client_wt_auth_user_1.get( app.url_path_for("experiments:get-experiment-by-organization-and-model-name"), params={ "organization_name": test_experiment_1_created_by_user_1.organization_name, "model_name": test_experiment_1_created_by_user_1.model_name, }, ) assert res.status_code == status.HTTP_200_OK experiment = ExperimentPublic(**res.json()) assert experiment.organization_name == test_experiment_1_created_by_user_1.organization_name assert experiment.model_name == test_experiment_1_created_by_user_1.model_name assert experiment.id == test_experiment_1_created_by_user_1.id assert experiment.coordinator_ip == test_experiment_1_created_by_user_1.coordinator_ip assert experiment.coordinator_port == test_experiment_1_created_by_user_1.coordinator_port assert experiment.creator == test_experiment_1_created_by_user_1.creator async def test_get_experiment_by_id_unvalid_query_by_user_1( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_1_created_by_user_2: ExperimentPublic, ) -> None: res = await client_wt_auth_user_1.get( app.url_path_for("experiments:get-experiment-by-organization-and-model-name"), params={ "organization_name": test_experiment_1_created_by_user_2.organization_name, "model_name": test_experiment_1_created_by_user_2.model_name, }, ) assert res.status_code == status.HTTP_401_UNAUTHORIZED @pytest.mark.parametrize( "organization_name, model_name, status_code", ( (500, 500, 401), (-1, 500, 401), (None, 500, 401), (500, 500, 401), (500, -1, 401), (500, None, 401), ), ) async def test_wrong_id_returns_error( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, organization_name: int, model_name: int, status_code: int, ) -> None: res = await client_wt_auth_user_1.get( app.url_path_for("experiments:get-experiment-by-organization-and-model-name"), params={ "organization_name": organization_name, "model_name": model_name, }, ) assert res.status_code == status_code class TestUpdateExperiment: @pytest.mark.parametrize( "attrs_to_change, values", ( (["coordinator_ip"], ["192.0.2.0"]), (["coordinator_ip"], ["684D:1111:222:3333:4444:5555:6:77"]), (["coordinator_port"], [400]), ( [ "coordinator_ip", "coordinator_port", ], [ "0.0.0.0", 80, ], ), ( [ "model_name", "coordinator_ip", "coordinator_port", ], [ "model_4", "1.0.0.0", 890, ], ), ( [ "organization_name", "model_name", "coordinator_ip", "coordinator_port", ], [ "Organization_a", "model_4", "2.0.0.0", 880, ], ), ), ) async def test_update_experiment_with_valid_input( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_2_created_by_user_1_for_updates_tests: ExperimentPublic, attrs_to_change: List[str], values: List[str], ) -> None: _ = ExperimentUpdate(**{attrs_to_change[i]: values[i] for i in range(len(attrs_to_change))}) experiment_update = {"experiment_update": {attrs_to_change[i]: values[i] for i in range(len(attrs_to_change))}} res = await client_wt_auth_user_1.put( app.url_path_for( "experiments:update-experiment-by-id", id=test_experiment_2_created_by_user_1_for_updates_tests.id ), json=experiment_update, ) assert res.status_code == status.HTTP_200_OK updated_experiment = ExperimentPublic(**res.json()) assert ( updated_experiment.id == test_experiment_2_created_by_user_1_for_updates_tests.id ) # make sure it's the same experiment # make sure that any attribute we updated has changed to the correct value for attr_to_change, value in zip(attrs_to_change, values): # Beware, this can raise an error if someone ask to removed user not whitelisted (and it isn't an error) assert getattr(updated_experiment, attr_to_change) != getattr( test_experiment_2_created_by_user_1_for_updates_tests, attr_to_change ) final_value = getattr(updated_experiment, attr_to_change) if isinstance(final_value, IPv4Address): assert final_value == IPv4Address(value) elif isinstance(final_value, IPv6Address): assert final_value == IPv6Address(value) else: assert final_value == value # make sure that no other attributes' values have changed for attr, value in updated_experiment.dict().items(): if attr not in attrs_to_change and attr != "updated_at": final_value = getattr(test_experiment_2_created_by_user_1_for_updates_tests, attr) if isinstance(final_value, IPv4Address): assert final_value == IPv4Address(value) elif isinstance(final_value, IPv6Address): assert final_value == IPv6Address(value) else: assert final_value == value if attr == "updated_at": assert getattr(test_experiment_2_created_by_user_1_for_updates_tests, attr) != value @pytest.mark.parametrize( "id, payload, status_code", ( (-1, {"organization_name": "test"}, 422), (0, {"organization_name": "test2"}, 422), (500, {}, 401), (500, {"organization_name": "test3"}, 401), ), ) async def test_update_experiment_with_invalid_input_throws_error( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, id: int, payload: dict, status_code: int, ) -> None: experiment_full_update = {"experiment_update": payload} res = await client_wt_auth_user_1.put( app.url_path_for("experiments:update-experiment-by-id", id=id), json=experiment_full_update, ) assert res.status_code == status_code class TestDeleteExperiment: async def test_can_delete_experiment_successfully( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_1_created_by_user_1: ExperimentPublic, ) -> None: # delete the experiment res = await client_wt_auth_user_1.delete( app.url_path_for("experiments:delete-experiment-by-id", id=test_experiment_1_created_by_user_1.id) ) assert res.status_code == status.HTTP_200_OK # ensure that the experiment no longer exists res = await client_wt_auth_user_1.get( app.url_path_for("experiments:get-experiment-by-id", id=test_experiment_1_created_by_user_1.id) ) assert res.status_code == status.HTTP_401_UNAUTHORIZED async def test_cant_delete_other_user_experiment( self, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_1_created_by_user_2: ExperimentPublic, ) -> None: # delete the experiment res = await client_wt_auth_user_1.delete( app.url_path_for("experiments:delete-experiment-by-id", id=test_experiment_1_created_by_user_2.id) ) assert res.status_code == status.HTTP_401_UNAUTHORIZED @pytest.mark.parametrize( "id, status_code", ( (500, 401), (0, 422), (-1, 422), (None, 422), ), ) async def test_can_delete_experiment_unsuccessfully( self, moonlanding_user_1, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_1_created_by_user_1: ExperimentPublic, id: int, status_code: int, ) -> None: res = await client_wt_auth_user_1.delete(app.url_path_for("experiments:delete-experiment-by-id", id=id)) assert res.status_code == status_code class TestJoinExperimentById: async def test_can_join_experiment_successfully( self, moonlanding_user_1, moonlanding_user_2, app: FastAPI, client_wt_auth_user_2: AsyncClient, # client_wt_auth_user_2: AsyncClient, test_experiment_1_created_by_user_1: ExperimentPublic, test_experiment_join_input_1_by_user_2: ExperimentJoinInput, test_experiment_join_input_2_by_user_2: ExperimentJoinInput, ) -> None: join_input_1, private_key_input_1 = test_experiment_join_input_1_by_user_2 values = join_input_1.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_2.put( app.url_path_for("experiments:join-experiment-by-id", id=test_experiment_1_created_by_user_1.id), json={"experiment_join_input": values}, ) assert res.status_code == status.HTTP_200_OK, res.content exp_pass = ExperimentJoinOutput(**res.json()) assert getattr(exp_pass, "coordinator_ip") == test_experiment_1_created_by_user_1.coordinator_ip assert getattr(exp_pass, "coordinator_port") == test_experiment_1_created_by_user_1.coordinator_port hivemind_access = getattr(exp_pass, "hivemind_access") assert getattr(hivemind_access, "peer_public_key") == join_input_1.peer_public_key signature = base64.b64decode(getattr(hivemind_access, "signature")) auth_server_public_key = getattr(exp_pass, "auth_server_public_key") auth_server_public_key = crypto.load_public_key(auth_server_public_key) verif = auth_server_public_key.verify( signature, f"{hivemind_access.username} {hivemind_access.peer_public_key} {hivemind_access.expiration_time}".encode(), crypto.PADDING, crypto.HASH_ALGORITHM, ) assert verif is None # verify() returns None iff the signature is correct assert hivemind_access.expiration_time > datetime.datetime.utcnow() assert hivemind_access.username == moonlanding_user_2.username # Now the same user try to join a second time with another public key join_input_2, private_key_input_2 = test_experiment_join_input_2_by_user_2 values = join_input_2.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_2.put( app.url_path_for("experiments:join-experiment-by-id", id=test_experiment_1_created_by_user_1.id), json={"experiment_join_input": values}, ) assert res.status_code == status.HTTP_200_OK, res.content exp_pass = ExperimentJoinOutput(**res.json()) assert getattr(exp_pass, "coordinator_ip") == test_experiment_1_created_by_user_1.coordinator_ip assert getattr(exp_pass, "coordinator_port") == test_experiment_1_created_by_user_1.coordinator_port hivemind_access = getattr(exp_pass, "hivemind_access") peer_public_key = getattr(hivemind_access, "peer_public_key") assert peer_public_key == join_input_2.peer_public_key signature = base64.b64decode(getattr(hivemind_access, "signature")) auth_server_public_key = getattr(exp_pass, "auth_server_public_key") auth_server_public_key = crypto.load_public_key(auth_server_public_key) verif = auth_server_public_key.verify( signature, f"{hivemind_access.username} {hivemind_access.peer_public_key} {hivemind_access.expiration_time}".encode(), crypto.PADDING, crypto.HASH_ALGORITHM, ) assert verif is None # verify() returns None iff the signature is correct assert hivemind_access.expiration_time > datetime.datetime.utcnow() assert hivemind_access.username == moonlanding_user_2.username msg = "this is a test" ciphertext = encrypt_msg(msg, crypto.load_public_key(peer_public_key)) plaintext = decrypt_msg(ciphertext, private_key_input_2) assert plaintext == msg with pytest.raises(Exception): plaintext = decrypt_msg(ciphertext, private_key_input_1) async def test_can_join_experiment_successfully_2_times_with_same_public_key( self, moonlanding_user_1, moonlanding_user_2, app: FastAPI, client_wt_auth_user_2: AsyncClient, # client_wt_auth_user_2: AsyncClient, test_experiment_1_created_by_user_1: ExperimentPublic, test_experiment_join_input_1_by_user_2: ExperimentJoinInput, test_experiment_join_input_2_by_user_2: ExperimentJoinInput, ) -> None: join_input_1, private_key_input_1 = test_experiment_join_input_1_by_user_2 values = join_input_1.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_2.put( app.url_path_for("experiments:join-experiment-by-id", id=test_experiment_1_created_by_user_1.id), json={"experiment_join_input": values}, ) assert res.status_code == status.HTTP_200_OK, res.content exp_pass = ExperimentJoinOutput(**res.json()) assert getattr(exp_pass, "coordinator_ip") == test_experiment_1_created_by_user_1.coordinator_ip assert getattr(exp_pass, "coordinator_port") == test_experiment_1_created_by_user_1.coordinator_port hivemind_access = getattr(exp_pass, "hivemind_access") assert getattr(hivemind_access, "peer_public_key") == join_input_1.peer_public_key signature = base64.b64decode(getattr(hivemind_access, "signature")) auth_server_public_key = getattr(exp_pass, "auth_server_public_key") auth_server_public_key = crypto.load_public_key(auth_server_public_key) verif = auth_server_public_key.verify( signature, f"{hivemind_access.username} {hivemind_access.peer_public_key} {hivemind_access.expiration_time}".encode(), crypto.PADDING, crypto.HASH_ALGORITHM, ) assert verif is None # verify() returns None iff the signature is correct assert hivemind_access.expiration_time > datetime.datetime.utcnow() assert hivemind_access.username == moonlanding_user_2.username # Now the same user try to join a second time with the same public key join_input_1, private_key_input_1 = test_experiment_join_input_1_by_user_2 values = join_input_1.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_2.put( app.url_path_for("experiments:join-experiment-by-id", id=test_experiment_1_created_by_user_1.id), json={"experiment_join_input": values}, ) assert res.status_code == status.HTTP_200_OK, res.content exp_pass = ExperimentJoinOutput(**res.json()) assert getattr(exp_pass, "coordinator_ip") == test_experiment_1_created_by_user_1.coordinator_ip assert getattr(exp_pass, "coordinator_port") == test_experiment_1_created_by_user_1.coordinator_port hivemind_access = getattr(exp_pass, "hivemind_access") assert getattr(hivemind_access, "peer_public_key") == join_input_1.peer_public_key signature = base64.b64decode(getattr(hivemind_access, "signature")) auth_server_public_key = getattr(exp_pass, "auth_server_public_key") auth_server_public_key = crypto.load_public_key(auth_server_public_key) verif = auth_server_public_key.verify( signature, f"{hivemind_access.username} {hivemind_access.peer_public_key} {hivemind_access.expiration_time}".encode(), crypto.PADDING, crypto.HASH_ALGORITHM, ) assert verif is None # verify() returns None iff the signature is correct assert hivemind_access.expiration_time > datetime.datetime.utcnow() assert hivemind_access.username == moonlanding_user_2.username async def test_cant_join_experiment_successfully_user_not_allowlisted( self, moonlanding_user_1, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_1_created_by_user_2: ExperimentPublic, test_experiment_join_input_1_by_user_2: ExperimentJoinInput, ): join_input_1, private_key_input_1 = test_experiment_join_input_1_by_user_2 values = join_input_1.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_1.put( app.url_path_for("experiments:join-experiment-by-id", id=test_experiment_1_created_by_user_2.id), json={"experiment_join_input": values}, ) assert res.status_code == status.HTTP_401_UNAUTHORIZED, res.content class TestJoinExperimentByOrgAndModelName: async def test_can_join_experiment_successfully( self, moonlanding_user_2, app: FastAPI, client_wt_auth_user_2: AsyncClient, # client_wt_auth_user_2: AsyncClient, test_experiment_1_created_by_user_1: ExperimentPublic, test_experiment_join_input_1_by_user_2: ExperimentJoinInput, test_experiment_join_input_2_by_user_2: ExperimentJoinInput, ) -> None: join_input_1, private_key_input_1 = test_experiment_join_input_1_by_user_2 values = join_input_1.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_2.put( app.url_path_for( "experiments:join-experiment-by-organization-and-model-name", ), json={"experiment_join_input": values}, params={ "organization_name": test_experiment_1_created_by_user_1.organization_name, "model_name": test_experiment_1_created_by_user_1.model_name, }, ) assert res.status_code == status.HTTP_200_OK, res.content exp_pass = ExperimentJoinOutput(**res.json()) assert getattr(exp_pass, "coordinator_ip") == test_experiment_1_created_by_user_1.coordinator_ip assert getattr(exp_pass, "coordinator_port") == test_experiment_1_created_by_user_1.coordinator_port hivemind_access = getattr(exp_pass, "hivemind_access") assert getattr(hivemind_access, "peer_public_key") == join_input_1.peer_public_key signature = base64.b64decode(getattr(hivemind_access, "signature")) auth_server_public_key = getattr(exp_pass, "auth_server_public_key") auth_server_public_key = crypto.load_public_key(auth_server_public_key) verif = auth_server_public_key.verify( signature, f"{hivemind_access.username} {hivemind_access.peer_public_key} {hivemind_access.expiration_time}".encode(), crypto.PADDING, crypto.HASH_ALGORITHM, ) assert verif is None # verify() returns None iff the signature is correct assert hivemind_access.expiration_time > datetime.datetime.utcnow() assert hivemind_access.username == moonlanding_user_2.username # Now the same user try to join a second time with another public key join_input_2, private_key_input_2 = test_experiment_join_input_2_by_user_2 values = join_input_2.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_2.put( app.url_path_for( "experiments:join-experiment-by-organization-and-model-name", ), json={"experiment_join_input": values}, params={ "organization_name": test_experiment_1_created_by_user_1.organization_name, "model_name": test_experiment_1_created_by_user_1.model_name, }, ) assert res.status_code == status.HTTP_200_OK, res.content exp_pass = ExperimentJoinOutput(**res.json()) assert getattr(exp_pass, "coordinator_ip") == test_experiment_1_created_by_user_1.coordinator_ip assert getattr(exp_pass, "coordinator_port") == test_experiment_1_created_by_user_1.coordinator_port hivemind_access = getattr(exp_pass, "hivemind_access") peer_public_key = getattr(hivemind_access, "peer_public_key") assert peer_public_key == join_input_2.peer_public_key signature = base64.b64decode(getattr(hivemind_access, "signature")) auth_server_public_key = getattr(exp_pass, "auth_server_public_key") auth_server_public_key = crypto.load_public_key(auth_server_public_key) verif = auth_server_public_key.verify( signature, f"{hivemind_access.username} {hivemind_access.peer_public_key} {hivemind_access.expiration_time}".encode(), crypto.PADDING, crypto.HASH_ALGORITHM, ) assert verif is None # verify() returns None iff the signature is correct assert hivemind_access.expiration_time > datetime.datetime.utcnow() assert hivemind_access.username == moonlanding_user_2.username msg = "this is a test" ciphertext = encrypt_msg(msg, crypto.load_public_key(peer_public_key)) plaintext = decrypt_msg(ciphertext, private_key_input_2) assert plaintext == msg with pytest.raises(Exception): plaintext = decrypt_msg(ciphertext, private_key_input_1) async def test_can_join_experiment_successfully_2_times_with_same_public_key( self, moonlanding_user_1, moonlanding_user_2, app: FastAPI, client_wt_auth_user_2: AsyncClient, # client_wt_auth_user_2: AsyncClient, test_experiment_1_created_by_user_1: ExperimentPublic, test_experiment_join_input_1_by_user_2: ExperimentJoinInput, test_experiment_join_input_2_by_user_2: ExperimentJoinInput, ) -> None: join_input_1, private_key_input_1 = test_experiment_join_input_1_by_user_2 values = join_input_1.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_2.put( app.url_path_for( "experiments:join-experiment-by-organization-and-model-name", ), json={"experiment_join_input": values}, params={ "organization_name": test_experiment_1_created_by_user_1.organization_name, "model_name": test_experiment_1_created_by_user_1.model_name, }, ) assert res.status_code == status.HTTP_200_OK, res.content exp_pass = ExperimentJoinOutput(**res.json()) assert getattr(exp_pass, "coordinator_ip") == test_experiment_1_created_by_user_1.coordinator_ip assert getattr(exp_pass, "coordinator_port") == test_experiment_1_created_by_user_1.coordinator_port hivemind_access = getattr(exp_pass, "hivemind_access") assert getattr(hivemind_access, "peer_public_key") == join_input_1.peer_public_key signature = base64.b64decode(getattr(hivemind_access, "signature")) auth_server_public_key = getattr(exp_pass, "auth_server_public_key") auth_server_public_key = crypto.load_public_key(auth_server_public_key) verif = auth_server_public_key.verify( signature, f"{hivemind_access.username} {hivemind_access.peer_public_key} {hivemind_access.expiration_time}".encode(), crypto.PADDING, crypto.HASH_ALGORITHM, ) assert verif is None # verify() returns None iff the signature is correct assert hivemind_access.expiration_time > datetime.datetime.utcnow() assert hivemind_access.username == moonlanding_user_2.username # Now the same user try to join a second time with the same public key join_input_1, private_key_input_1 = test_experiment_join_input_1_by_user_2 values = join_input_1.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_2.put( app.url_path_for( "experiments:join-experiment-by-organization-and-model-name", ), json={"experiment_join_input": values}, params={ "organization_name": test_experiment_1_created_by_user_1.organization_name, "model_name": test_experiment_1_created_by_user_1.model_name, }, ) assert res.status_code == status.HTTP_200_OK, res.content exp_pass = ExperimentJoinOutput(**res.json()) assert getattr(exp_pass, "coordinator_ip") == test_experiment_1_created_by_user_1.coordinator_ip assert getattr(exp_pass, "coordinator_port") == test_experiment_1_created_by_user_1.coordinator_port hivemind_access = getattr(exp_pass, "hivemind_access") assert getattr(hivemind_access, "peer_public_key") == join_input_1.peer_public_key signature = base64.b64decode(getattr(hivemind_access, "signature")) auth_server_public_key = getattr(exp_pass, "auth_server_public_key") auth_server_public_key = crypto.load_public_key(auth_server_public_key) verif = auth_server_public_key.verify( signature, f"{hivemind_access.username} {hivemind_access.peer_public_key} {hivemind_access.expiration_time}".encode(), crypto.PADDING, crypto.HASH_ALGORITHM, ) assert verif is None # verify() returns None iff the signature is correct assert hivemind_access.expiration_time > datetime.datetime.utcnow() assert hivemind_access.username == moonlanding_user_2.username async def test_cant_join_experiment_successfully_user_not_allowlisted( self, moonlanding_user_1, app: FastAPI, client_wt_auth_user_1: AsyncClient, test_experiment_1_created_by_user_2: ExperimentPublic, test_experiment_join_input_1_by_user_2: ExperimentJoinInput, ): join_input_1, private_key_input_1 = test_experiment_join_input_1_by_user_2 values = join_input_1.dict() # Make the values JSON serializable values["peer_public_key"] = values["peer_public_key"].decode("utf-8") res = await client_wt_auth_user_1.put( app.url_path_for( "experiments:join-experiment-by-organization-and-model-name", ), json={"experiment_join_input": values}, params={ "organization_name": test_experiment_1_created_by_user_2.organization_name, "model_name": test_experiment_1_created_by_user_2.model_name, }, ) assert res.status_code == status.HTTP_401_UNAUTHORIZED, res.content
collaborative-training-auth-main
backend/tests/test_experiments.py