跳至主内容

MLflow 身份验证

Experimental Feature

此功能仍处于实验阶段,未来版本可能会在不另行通知的情况下进行增强。

MLflow Authentication 通过 HTTP 基本身份验证为实验和已注册模型提供安全的访问控制。启用后,用户在访问 Tracking Server 上的任何资源之前必须进行身份验证。

快速开始

安装与设置

安装 MLflow 和身份验证依赖项:

pip install mlflow[auth]

设置服务器密钥并启动经过身份验证的服务器:

export MLFLOW_FLASK_SERVER_SECRET_KEY="my-secret-key"
mlflow server --app-name basic-auth
Important

秘密密钥必须在多个服务器之间保持一致,以防止验证错误。

默认管理员访问

MLflow 在第一次启动时会创建一个默认的管理员用户:

用户名密码
adminpassword1234
Security Recommendation

在首次登录后立即使用 /api/2.0/mlflow/users/update-password 端点更新默认管理员密码。

核心概念

权限级别

MLflow 使用分层权限系统,包含四个级别:

权限读取更新删除管理
读取
编辑
管理
NO_PERMISSIONS

默认情况下,所有用户的权限为 READ,可在 auth 配置文件中配置。

资源类型

权限在两种主要资源类型上授予:

  • 实验 - 控制对实验数据和运行的访问
  • 已注册模型 - 控制对模型注册表操作的访问

身份验证方法

使用 mlflow.login() 进行引导式身份验证设置:

import mlflow

# Interactive login with prompts
mlflow.login()

# Login to Databricks (currently the only supported backend)
mlflow.login(backend="databricks", interactive=True)

# Non-interactive mode (requires existing credentials)
mlflow.login(backend="databricks", interactive=False)

# After login, start using MLflow normally
with mlflow.start_run():
mlflow.log_metric("accuracy", 0.95)
Interactive Experience

mlflow.login() 如果未找到凭据,会提示您输入凭据并自动将其保存以便将来使用。对于 Databricks,它会保存到 ~/.databrickscfg

环境变量

在你的环境中设置认证凭证:

export MLFLOW_TRACKING_USERNAME=your_username
export MLFLOW_TRACKING_PASSWORD=your_password

import os

os.environ["MLFLOW_TRACKING_USERNAME"] = "your_username"
os.environ["MLFLOW_TRACKING_PASSWORD"] = "your_password"

并使用它们来对跟踪服务器进行身份验证:

import mlflow

mlflow.set_tracking_uri("https://your-mlflow-server.com")
with mlflow.start_run():
# Your authenticated MLflow operations
mlflow.log_metric("accuracy", 0.95)

凭据文件

将凭证存储在 ~/.mlflow/credentials(受文件系统权限保护):

[mlflow]
mlflow_tracking_username = your_username
mlflow_tracking_password = your_password
Credential Priority

环境变量优先于凭证文件。这使得在不同环境中可以轻松进行覆盖。

高级身份验证选项

MLflow 支持额外的身份验证方法和安全配置:

基于令牌的认证

import os

os.environ["MLFLOW_TRACKING_TOKEN"] = "your_api_token"

AWS SigV4 身份验证

import os

os.environ["MLFLOW_TRACKING_AWS_SIGV4"] = "true"

自定义身份验证头

import os

os.environ["MLFLOW_TRACKING_AUTH"] = "custom_auth_header_value"

TLS/SSL 配置

import os

# Disable TLS verification (not recommended for production)
os.environ["MLFLOW_TRACKING_INSECURE_TLS"] = "true"

# Custom client certificate
os.environ["MLFLOW_TRACKING_CLIENT_CERT_PATH"] = "/path/to/client.crt"

# Custom server certificate
os.environ["MLFLOW_TRACKING_SERVER_CERT_PATH"] = "/path/to/server.crt"
Security Note

只在开发环境中禁用 TLS 验证。生产环境中始终使用适当的证书。

用户管理

创建用户

使用 Web 界面

导航到 /signup 以访问用户创建表单。

使用 Python 客户端

from mlflow.server import get_app_client

# Authenticate as admin
auth_client = get_app_client("basic-auth", tracking_uri="https://your-server.com")
user = auth_client.create_user(username="newuser", password="secure_password")

print(f"Created user: {user.username} (ID: {user.id})")

使用 REST API

import requests

response = requests.post(
"https://your-server.com/api/2.0/mlflow/users/create",
json={"username": "newuser", "password": "secure_password"},
auth=("admin", "password1234"),
)

管理员状态管理

只有现有的管理员可以将用户提升为管理员:

# Promote user to admin
auth_client.update_user_admin(username="newuser", is_admin=True)

# Remove admin privileges
auth_client.update_user_admin(username="newuser", is_admin=False)

权限管理

实验权限

授予用户对实验的特定权限:

from mlflow import MlflowClient

# Create experiment and grant permissions
client = MlflowClient(tracking_uri="https://your-server.com")
experiment_id = client.create_experiment("my_experiment")

# Grant MANAGE permission to user
auth_client.create_experiment_permission(
experiment_id=experiment_id, username="data_scientist", permission="MANAGE"
)

# Update existing permission
auth_client.update_experiment_permission(
experiment_id=experiment_id, username="data_scientist", permission="EDIT"
)

# Check current permission
permission = auth_client.get_experiment_permission(
experiment_id=experiment_id, username="data_scientist"
)
print(f"User permission: {permission.permission}")

已注册模型权限

控制对模型注册表操作的访问:

# Create model with automatic MANAGE permission for creator
model = client.create_registered_model("my_model")

# Grant READ permission to another user
auth_client.create_registered_model_permission(
name="my_model", username="ml_engineer", permission="READ"
)

# Update to EDIT permission
auth_client.update_registered_model_permission(
name="my_model", username="ml_engineer", permission="EDIT"
)

API 参考

核心端点

用户管理

端点方法描述所需权限
/api/2.0/mlflow/users/createPOSTCreate new userAdmin only
/api/2.0/mlflow/users/getGETGet user infoSelf only
/api/2.0/mlflow/users/update-passwordPATCHUpdate passwordSelf only
/api/2.0/mlflow/users/update-adminPATCHUpdate admin statusAdmin only
/api/2.0/mlflow/users/deleteDELETEDelete userAdmin only

实验权限

端点方法所需权限
/api/2.0/mlflow/experiments/permissions/createPOSTcan_manage
/api/2.0/mlflow/experiments/permissions/getGETcan_manage
/api/2.0/mlflow/experiments/permissions/updatePATCHcan_manage
/api/2.0/mlflow/experiments/permissions/deleteDELETEcan_manage

模型注册表权限

端点方法所需权限
/api/2.0/mlflow/registered-models/permissions/createPOSTcan_manage
/api/2.0/mlflow/registered-models/permissions/getGETcan_manage
/api/2.0/mlflow/registered-models/permissions/updatePATCHcan_manage
/api/2.0/mlflow/registered-models/permissions/deleteDELETEcan_manage

增强行为

当启用身份验证时,某些 APIs 会根据用户权限自动过滤结果:

  • 搜索实验 - 只返回用户可以读取的实验
  • 搜索运行 - 仅返回来自可读取实验的运行
  • Search Registered Models - 仅返回用户可读取的模型
  • 创建操作 - 自动授予 MANAGE 权限给创建者

配置

数据库配置

MLflow 默认使用 SQLite,但支持用于多节点部署的集中式数据库:

# /path/to/auth_config.ini
[mlflow]
database_uri = postgresql://username:password@hostname:port/database
default_permission = READ
admin_username = admin
admin_password = password1234
authorization_function = mlflow.server.auth:authenticate_request_basic_auth

使用自定义配置启动服务器:

MLFLOW_AUTH_CONFIG_PATH=/path/to/auth_config.ini mlflow server --app-name basic-auth

数据库迁移

在需要时运行数据库迁移:

python -m mlflow.server.auth db upgrade --url <database_url>

高级主题

自定义身份验证

MLflow 支持通过可插拔函数实现自定义身份验证方法:

# custom_auth.py
from werkzeug.datastructures import Authorization
from flask import Response


def custom_authenticate() -> Union[Authorization, Response]:
# Your custom authentication logic
# Return Authorization object if authenticated
# Return Response object (401) if not authenticated
pass

更新配置以使用您的自定义函数:

[mlflow]
authorization_function = custom_auth:custom_authenticate

插件开发

创建可安装的身份验证插件:

# my_auth_plugin/__init__.py
from flask import Flask
from mlflow.server import app


def create_app(my_app: Flask = app):
# Extend MLflow app with custom auth logic
my_app.add_url_rule(...)
return my_app


class MyAuthClient:
# Custom client for managing permissions
pass

注册您的插件:

# setup.py
setup(
entry_points={
"mlflow.app": ["my-auth=my_auth_plugin:create_app"],
"mlflow.app.client": ["my-auth=my_auth_plugin:MyAuthClient"],
}
)

安全最佳实践

密码安全

  • 使用强密码(至少12个字符)
  • 定期轮换凭证
  • 使用环境变量或安全的凭证文件安全地存储凭证

网络安全

  • 在生产环境中使用 HTTPS
  • 配置适当的防火墙规则
  • 考虑使用带有额外安全头的反向代理

数据库安全

  • 使用加密连接到您的数据库
  • 定期备份身份验证数据
  • 实施适当的数据库访问控制

监控

  • 监控身份验证日志以发现可疑活动
  • 为身份验证失败的尝试设置警报
  • 定期审计用户权限

故障排除

常见问题

密钥错误

Solution: Ensure MLFLOW_FLASK_SERVER_SECRET_KEY is set and consistent across all servers

权限被拒绝 (403)

Solution: Check user permissions using get_experiment_permission or get_registered_model_permission

身份验证失败 (401)

Solution: Verify username/password and ensure user exists in the system

数据库连接问题

Solution: Verify database_uri in configuration and ensure database is accessible

调试技巧

  1. 启用调试日志记录

    export MLFLOW_LOGGING_LEVEL=DEBUG
  2. 检查用户权限

    # 验证当前用户权限
    user = auth_client.get_user("username")
    print(f"Is admin: {user.is_admin}")

    permission = auth_client.get_experiment_permission("exp_id", "username")
    print(f"Experiment permission: {permission.permission}")
  3. 数据库检查

    # 检查数据库表
    sqlite3 basic_auth.db ".tables"
    sqlite3 basic_auth.db "SELECT * FROM users;"

迁移指南

在现有服务器上启用身份验证

  1. 备份你的数据 在启用身份验证之前
  2. 安装认证依赖: pip install mlflow[auth]
  3. 设置密钥: export MLFLOW_FLASK_SERVER_SECRET_KEY="your-key"
  4. 重启服务器: mlflow server --app-name basic-auth
  5. 更新管理员密码 在首次登录后立即

禁用身份验证

要禁用身份验证,只需在不带 --app-name basic-auth 标志的情况下重新启动服务器。用户数据和权限将被保留,以便将来重新启用。


需要帮助? 请查看 MLflow Authentication API Reference 以获取详细的函数文档。