python_code
stringlengths 0
290k
| repo_name
stringclasses 30
values | file_path
stringlengths 6
125
|
---|---|---|
#
# 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="[email protected]",
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="[email protected]", 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": "[email protected]", "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 |