mirror of
https://github.com/langgenius/dify.git
synced 2026-05-29 21:27:54 +08:00
Adds a CLI-friendly authorization flow so difyctl (and future
non-browser clients) can obtain user-scoped tokens without copy-
pasting cookies or raw API keys. Two grant paths share one device
flow surface:
1. Account branch — user signs in via the existing /signin
methods, /device page calls console-authed approve, mints a
dfoa_ token tied to (account_id, tenant).
2. External-SSO branch (EE) — /v1/oauth/device/sso-initiate signs
an SSOState envelope, hands off to Enterprise's external ACS,
receives a signed external-subject assertion, mints a dfoe_
token tied to (subject_email, subject_issuer).
API surface (all under /v1, EE-only endpoints 404 on CE):
POST /v1/oauth/device/code — RFC 8628 start
POST /v1/oauth/device/token — RFC 8628 poll
GET /v1/oauth/device/lookup — pre-validate user_code
GET /v1/oauth/device/sso-initiate — SSO branch entry
GET /v1/device/sso-complete — SSO callback sink
GET /v1/oauth/device/approval-context — /device cookie probe
POST /v1/oauth/device/approve-external — SSO approve
GET /v1/me — bearer subject lookup
DELETE /v1/oauth/authorizations/self — self-revoke
POST /console/api/oauth/device/approve — account approve
POST /console/api/oauth/device/deny — account deny
Core primitives:
- libs/oauth_bearer.py: prefix-keyed TokenKindRegistry +
BearerAuthenticator + validate_bearer decorator. Two-tier scope
(full vs apps:run) stamped from the registry, never from the DB.
- libs/jws.py: HS256 compact JWS keyed on the shared Dify
SECRET_KEY — same key-set verifies the SSOState envelope, the
external-subject assertion (minted by Enterprise), and the
approval-grant cookie.
- libs/device_flow_security.py: enterprise_only gate, approval-
grant cookie mint/verify/consume (Path=/v1/oauth/device,
HttpOnly, SameSite=Lax, Secure follows is_secure()), anti-
framing headers.
- libs/rate_limit.py: typed RateLimit / RateLimitScope dispatch
with composite-key buckets; both decorator + imperative form.
- services/oauth_device_flow.py: Redis state machine (PENDING ->
APPROVED|DENIED with atomic consume-on-poll), token mint via
partial unique index uq_oauth_active_per_device (rotates in
place), env-driven TTL policy.
Storage: oauth_access_tokens table with partial unique index on
(subject_email, subject_issuer, client_id, device_label) WHERE
revoked_at IS NULL. account_id NULL distinguishes external-SSO
rows. Hard-expire is CAS UPDATE (revoked_at + nullify token_hash)
so audit events keep their token_id. Retention pruner DELETEs
revoked + zombie-expired rows past OAUTH_ACCESS_TOKEN_RETENTION_DAYS.
Frontend: /device page with code-entry, chooser (account vs SSO),
authorize-account, authorize-sso views. SSO branch detaches from
the URL user_code and reads everything from the cookie via
/approval-context. Anti-framing headers on all responses.
Wiring: ENABLE_OAUTH_BEARER feature flag; ext_oauth_bearer binds
the authenticator at startup; clean_oauth_access_tokens_task
scheduled in ext_celery.
Spec: docs/specs/v1.0/server/{device-flow,tokens,middleware,security}.md
122 lines
5.5 KiB
Python
122 lines
5.5 KiB
Python
from datetime import datetime
|
|
from typing import Any, Optional
|
|
|
|
import sqlalchemy as sa
|
|
from sqlalchemy import func
|
|
from sqlalchemy.orm import Mapped, mapped_column
|
|
|
|
from libs.uuid_utils import uuidv7
|
|
|
|
from .base import TypeBase
|
|
from .types import AdjustedJSON, LongText, StringUUID
|
|
|
|
|
|
class DatasourceOauthParamConfig(TypeBase):
|
|
__tablename__ = "datasource_oauth_params"
|
|
__table_args__ = (
|
|
sa.PrimaryKeyConstraint("id", name="datasource_oauth_config_pkey"),
|
|
sa.UniqueConstraint("plugin_id", "provider", name="datasource_oauth_config_datasource_id_provider_idx"),
|
|
)
|
|
|
|
id: Mapped[str] = mapped_column(
|
|
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
|
)
|
|
plugin_id: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
|
provider: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
|
system_credentials: Mapped[dict[str, Any]] = mapped_column(AdjustedJSON, nullable=False)
|
|
|
|
|
|
class DatasourceProvider(TypeBase):
|
|
__tablename__ = "datasource_providers"
|
|
__table_args__ = (
|
|
sa.PrimaryKeyConstraint("id", name="datasource_provider_pkey"),
|
|
sa.UniqueConstraint("tenant_id", "plugin_id", "provider", "name", name="datasource_provider_unique_name"),
|
|
sa.Index("datasource_provider_auth_type_provider_idx", "tenant_id", "plugin_id", "provider"),
|
|
)
|
|
id: Mapped[str] = mapped_column(
|
|
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
|
)
|
|
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
|
name: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
|
provider: Mapped[str] = mapped_column(sa.String(128), nullable=False)
|
|
plugin_id: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
|
auth_type: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
|
encrypted_credentials: Mapped[dict[str, Any]] = mapped_column(AdjustedJSON, nullable=False)
|
|
avatar_url: Mapped[str] = mapped_column(LongText, nullable=True, default="default")
|
|
is_default: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"), default=False)
|
|
expires_at: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default="-1", default=-1)
|
|
|
|
created_at: Mapped[datetime] = mapped_column(
|
|
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
|
)
|
|
updated_at: Mapped[datetime] = mapped_column(
|
|
sa.DateTime,
|
|
nullable=False,
|
|
server_default=func.current_timestamp(),
|
|
onupdate=func.current_timestamp(),
|
|
init=False,
|
|
)
|
|
|
|
|
|
class DatasourceOauthTenantParamConfig(TypeBase):
|
|
__tablename__ = "datasource_oauth_tenant_params"
|
|
__table_args__ = (
|
|
sa.PrimaryKeyConstraint("id", name="datasource_oauth_tenant_config_pkey"),
|
|
sa.UniqueConstraint("tenant_id", "plugin_id", "provider", name="datasource_oauth_tenant_config_unique"),
|
|
)
|
|
|
|
id: Mapped[str] = mapped_column(
|
|
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
|
)
|
|
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
|
provider: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
|
plugin_id: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
|
client_params: Mapped[dict[str, Any]] = mapped_column(AdjustedJSON, nullable=False, default_factory=dict)
|
|
enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
|
|
|
created_at: Mapped[datetime] = mapped_column(
|
|
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
|
)
|
|
updated_at: Mapped[datetime] = mapped_column(
|
|
sa.DateTime,
|
|
nullable=False,
|
|
server_default=func.current_timestamp(),
|
|
onupdate=func.current_timestamp(),
|
|
init=False,
|
|
)
|
|
|
|
|
|
class OAuthAccessToken(TypeBase):
|
|
"""Device-flow bearer. account_id NOT NULL ⇒ dfoa_ (Dify account);
|
|
account_id NULL + subject_issuer ⇒ dfoe_ (external SSO, EE-only).
|
|
Partial unique index on (subject_email, subject_issuer, client_id,
|
|
device_label) WHERE revoked_at IS NULL lets re-login rotate in place.
|
|
"""
|
|
|
|
__tablename__ = "oauth_access_tokens"
|
|
__table_args__ = (
|
|
sa.PrimaryKeyConstraint("id", name="oauth_access_tokens_pkey"),
|
|
)
|
|
|
|
id: Mapped[str] = mapped_column(
|
|
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
|
)
|
|
subject_email: Mapped[str] = mapped_column(sa.Text, nullable=False)
|
|
client_id: Mapped[str] = mapped_column(sa.String(64), nullable=False)
|
|
device_label: Mapped[str] = mapped_column(sa.Text, nullable=False)
|
|
prefix: Mapped[str] = mapped_column(sa.String(8), nullable=False)
|
|
expires_at: Mapped[datetime] = mapped_column(sa.DateTime(timezone=True), nullable=False)
|
|
subject_issuer: Mapped[Optional[str]] = mapped_column(sa.Text, nullable=True, default=None)
|
|
account_id: Mapped[Optional[str]] = mapped_column(StringUUID, nullable=True, default=None)
|
|
token_hash: Mapped[Optional[str]] = mapped_column(sa.String(64), nullable=True, default=None)
|
|
last_used_at: Mapped[Optional[datetime]] = mapped_column(
|
|
sa.DateTime(timezone=True), nullable=True, default=None
|
|
)
|
|
revoked_at: Mapped[Optional[datetime]] = mapped_column(
|
|
sa.DateTime(timezone=True), nullable=True, default=None
|
|
)
|
|
|
|
created_at: Mapped[datetime] = mapped_column(
|
|
sa.DateTime(timezone=True), nullable=False, server_default=func.now(), init=False
|
|
)
|