def test_link_host_with_uuid_unauthorized( mocker: MockerFixture, uuid: UUID, ) -> None: response = Response() response.status_code = 403 response._content = ( b'{"title": "You do not have the permission for agent pairing.", "status": 403}' ) mocker.patch( "agent_receiver.checkmk_rest_api._forward_put", return_value=response, ) with pytest.raises(HTTPException) as excpt_info: link_host_with_uuid( HTTPBasicCredentials( username="******", password="******", ), "some_host", uuid, ) assert excpt_info.value.status_code == 403 assert excpt_info.value.detail == "You do not have the permission for agent pairing."
def test_can_not_authenticate_with_wrong_password(monkeypatch): monkeypatch.setattr("config.AUTH_USERS", {"abc": "def"}) credentials = HTTPBasicCredentials(username="******", password="******") with pytest.raises(HTTPException) as exception: authenticate(credentials) assert exception.value.status_code == 401
def test_can_not_authenticate_when_no_users_provided(monkeypatch): monkeypatch.setattr("config.AUTH_USERS", {}) credentials = HTTPBasicCredentials(username="******", password="******") with pytest.raises(HTTPException) as exception: authenticate(credentials) assert exception.value.status_code == 401
async def __call__(self, request: Request) -> Optional[HTTPBasicCredentials]: client_id: Optional[str] = request.query_params.get('client_id') client_secret: Optional[str] = request.query_params.get( 'client_secret') if not client_id or not client_secret: if self.auto_error: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") else: return None return HTTPBasicCredentials(username=client_id, password=client_secret)
async def robinhood_has_access(token: HTTPBasicCredentials = Depends( security)) -> None: """Validates the token if mentioned as a dependency. Args: token: Takes the authorization header token as an argument. """ auth = token.dict().get('credentials') if auth.startswith('\\'): auth = bytes(auth, "utf-8").decode(encoding="unicode_escape") if auth == env.robinhood_endpoint_auth: return raise APIResponse(status_code=HTTPStatus.UNAUTHORIZED.real, detail=HTTPStatus.UNAUTHORIZED.__dict__['phrase'])
async def __call__(self, request: Request) -> Optional[HTTPBasicCredentials]: try: request_json = await request.json() client_id: Optional[str] = request_json.get('client_id') client_secret: Optional[str] = request_json.get('client_secret') except ValueError: client_id = None client_secret = None if not client_id or not client_secret: if self.auto_error: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") else: return None return HTTPBasicCredentials(username=client_id, password=client_secret)
def test_link_host_with_uuid_ok( mocker: MockerFixture, uuid: UUID, ) -> None: response = Response() response.status_code = 204 mocker.patch( "agent_receiver.checkmk_rest_api._forward_put", return_value=response, ) link_host_with_uuid( HTTPBasicCredentials( username="******", password="******", ), "some_host", uuid, )
def test_that_user_route_works_with_auth_configured(): cred = HTTPBasicCredentials(username="******", password="******") security = FastAPISecurity() security.init_basic_auth([cred]) app = ProdAPI().with_user_routes(security) with TestClient(app) as c: resp = c.get("/users/me") assert resp.status_code == 200 data = resp.json() assert data["auth"]["auth_method"] == "none" with TestClient(app) as c: resp = c.get("/users/me", auth=("johndoe", "123")) assert resp.status_code == 200 data = resp.json() assert data["auth"]["auth_method"] == "basic_auth" assert data["auth"]["subject"] == "johndoe"
def test_that_user_with_permission_is_granted_access(): cred = HTTPBasicCredentials(username="******", password="******") security = FastAPISecurity() security.init_basic_auth([cred]) security.add_permission_overrides({"johndoe": ["products:create"]}) app = ProdAPI() create_product_perm = security.user_permission("products:create") @app.post("/products") def create_product( user: User = Depends( security.user_holding(create_product_perm)), ): return {"ok": True} with TestClient(app) as c: resp = c.post("/products", auth=("johndoe", "123")) assert resp.status_code == 200 assert resp.json() == {"ok": True}
def test_that_user_without_permission_is_denied_access(): cred = HTTPBasicCredentials(username="******", password="******") security = FastAPISecurity() security.init_basic_auth([cred]) app = ProdAPI() create_product_perm = security.user_permission("products:create") @app.post("/products") def create_product( user: User = Depends( security.user_holding(create_product_perm)), ): return {} with TestClient(app) as c: resp = c.post("/products", auth=("johndoe", "123")) assert resp.status_code == 403 assert resp.json() == { "detail": "Missing required permission products:create" }
def test_that_user_route_includes_user_permissions(): cred = HTTPBasicCredentials(username="******", password="******") security = FastAPISecurity() security.init_basic_auth([cred]) security.add_permission_overrides({"johndoe": "*"}) security.user_permission("products:create") security.user_permission("products:delete") app = ProdAPI().with_user_routes(security) with TestClient(app) as c: resp = c.get("/users/me") assert resp.status_code == 200 data = resp.json() assert data["auth"]["auth_method"] == "none" with TestClient(app) as c: resp = c.get("/users/me", auth=("johndoe", "123")) data = resp.json() assert data["auth"]["permissions"] == [ "products:create", "products:delete" ]
def test_cred_check(tmp_database): auth = HTTPBasicCredentials(username='******', password='******') assert cred_check(auth) == auth
def test_can_authenticate(monkeypatch): monkeypatch.setattr("config.AUTH_USERS", {"my_user": "******"}) credentials = HTTPBasicCredentials(username="******", password="******") assert authenticate(credentials) is True