Victor Dibia fe1feb3906
Enable Auth in AGS (#5928)
<!-- Thank you for your contribution! Please review
https://microsoft.github.io/autogen/docs/Contribute before opening a
pull request. -->

<!-- Please add a reviewer to the assignee section when you create a PR.
If you don't have the access to it, we will shortly find a reviewer and
assign them to your PR. -->

## Why are these changes needed?


https://github.com/user-attachments/assets/b649053b-c377-40c7-aa51-ee64af766fc2

<img width="100%" alt="image"
src="https://github.com/user-attachments/assets/03ba1df5-c9a2-4734-b6a2-0eb97ec0b0e0"
/>


## Authentication

This PR implements an experimental authentication feature to enable
personalized experiences (multiple users). Currently, only GitHub
authentication is supported. You can extend the base authentication
class to add support for other authentication methods.

By default authenticatio is disabled and only enabled when you pass in
the `--auth-config` argument when running the application.

### Enable GitHub Authentication

To enable GitHub authentication, create a `auth.yaml` file in your app
directory:

```yaml
type: github
jwt_secret: "your-secret-key"
token_expiry_minutes: 60
github:
  client_id: "your-github-client-id"
  client_secret: "your-github-client-secret"
  callback_url: "http://localhost:8081/api/auth/callback"
  scopes: ["user:email"]
```

Please see the documentation on [GitHub
OAuth](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authenticating-to-the-rest-api-with-an-oauth-app)
for more details on obtaining the `client_id` and `client_secret`.

To pass in this configuration you can use the `--auth-config` argument
when running the application:

```bash
autogenstudio ui --auth-config /path/to/auth.yaml
```

Or set the environment variable:

```bash
export AUTOGENSTUDIO_AUTH_CONFIG="/path/to/auth.yaml"
```

```{note}
- Authentication is currently experimental and may change in future releases
- User data is stored in your configured database
- When enabled, all API endpoints require authentication except for the authentication endpoints
- WebSocket connections require the token to be passed as a query parameter (`?token=your-jwt-token`)

```

## Related issue number

<!-- For example: "Closes #1234" -->
Closes #4350  

## Checks

- [ ] I've included any doc changes needed for
<https://microsoft.github.io/autogen/>. See
<https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to
build and test documentation locally.
- [ ] I've added tests (if relevant) corresponding to the changes
introduced in this PR.
- [ ] I've made sure all auto checks have passed.

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2025-03-14 15:02:05 -07:00

140 lines
4.2 KiB
Python

import os
import tempfile
import warnings
from typing import Optional
import typer
import uvicorn
from typing_extensions import Annotated
from .version import VERSION
app = typer.Typer()
# Ignore deprecation warnings from websockets
warnings.filterwarnings("ignore", message="websockets.legacy is deprecated*")
warnings.filterwarnings("ignore", message="websockets.server.WebSocketServerProtocol is deprecated*")
def get_env_file_path():
app_dir = os.path.join(os.path.expanduser("~"), ".autogenstudio")
if not os.path.exists(app_dir):
os.makedirs(app_dir, exist_ok=True)
return os.path.join(app_dir, "temp_env_vars.env")
@app.command()
def ui(
host: str = "127.0.0.1",
port: int = 8081,
workers: int = 1,
reload: Annotated[bool, typer.Option("--reload")] = False,
docs: bool = True,
appdir: str | None = None,
database_uri: Optional[str] = None,
auth_config: Optional[str] = None,
upgrade_database: bool = False,
):
"""
Run the AutoGen Studio UI.
Args:
host (str, optional): Host to run the UI on. Defaults to 127.0.0.1 (localhost).
port (int, optional): Port to run the UI on. Defaults to 8081.
workers (int, optional): Number of workers to run the UI with. Defaults to 1.
reload (bool, optional): Whether to reload the UI on code changes. Defaults to False.
docs (bool, optional): Whether to generate API docs. Defaults to False.
appdir (str, optional): Path to the AutoGen Studio app directory. Defaults to None.
database_uri (str, optional): Database URI to connect to. Defaults to None.
auth_config (str, optional): Path to authentication configuration YAML. Defaults to None.
upgrade_database (bool, optional): Whether to upgrade the database. Defaults to False.
"""
# Write configuration
env_vars = {
"AUTOGENSTUDIO_HOST": host,
"AUTOGENSTUDIO_PORT": port,
"AUTOGENSTUDIO_API_DOCS": str(docs),
}
if appdir:
env_vars["AUTOGENSTUDIO_APPDIR"] = appdir
if database_uri:
env_vars["AUTOGENSTUDIO_DATABASE_URI"] = database_uri
if auth_config:
if not os.path.exists(auth_config):
typer.echo(f"Error: Auth config file not found: {auth_config}", err=True)
raise typer.Exit(1)
env_vars["AUTOGENSTUDIO_AUTH_CONFIG"] = auth_config
if upgrade_database:
env_vars["AUTOGENSTUDIO_UPGRADE_DATABASE"] = "1"
# Create temporary env file to share configuration with uvicorn workers
env_file_path = get_env_file_path()
with open(env_file_path, "w") as temp_env:
for key, value in env_vars.items():
temp_env.write(f"{key}={value}\n")
uvicorn.run(
"autogenstudio.web.app:app",
host=host,
port=port,
workers=workers,
reload=reload,
reload_excludes=["**/alembic/*", "**/alembic.ini", "**/versions/*"] if reload else None,
env_file=env_file_path,
)
@app.command()
def serve(
team: str = "",
host: str = "127.0.0.1",
port: int = 8084,
workers: int = 1,
docs: bool = False,
):
"""
Serve an API Endpoint based on an AutoGen Studio workflow json file.
Args:
team (str): Path to the team json file.
host (str, optional): Host to run the UI on. Defaults to 127.0.0.1 (localhost).
port (int, optional): Port to run the UI on. Defaults to 8084
workers (int, optional): Number of workers to run the UI with. Defaults to 1.
reload (bool, optional): Whether to reload the UI on code changes. Defaults to False.
docs (bool, optional): Whether to generate API docs. Defaults to False.
"""
os.environ["AUTOGENSTUDIO_API_DOCS"] = str(docs)
os.environ["AUTOGENSTUDIO_TEAM_FILE"] = team
# validate the team file
if not os.path.exists(team):
raise ValueError(f"Team file not found: {team}")
uvicorn.run(
"autogenstudio.web.serve:app",
host=host,
port=port,
workers=workers,
reload=False,
)
@app.command()
def version():
"""
Print the version of the AutoGen Studio UI CLI.
"""
typer.echo(f"AutoGen Studio CLI version: {VERSION}")
def run():
app()
if __name__ == "__main__":
app()