File size: 5,132 Bytes
9f6a4bd
e99df76
691dc7c
2415446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
2415446
f7872b8
2415446
 
 
 
f7872b8
2415446
f7872b8
2415446
 
 
 
691dc7c
2415446
 
 
f7872b8
2415446
 
 
 
 
 
 
c7221ec
abe1c43
2415446
 
c7221ec
 
 
 
 
 
 
 
e99df76
c7221ec
 
 
 
0a54372
 
c7221ec
0a54372
 
c7221ec
691dc7c
e99df76
2415446
 
 
 
 
8e438ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7b8ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e438ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
from __future__ import annotations
"""FastAPI dependencies for the explicit runtime service boundary."""

import secrets

from fastapi import Depends, HTTPException, Request
from loguru import logger

from free_claude_code.application.errors import UnknownProviderError
from free_claude_code.application.ports import ProviderPort, RequestRuntimeLease
from free_claude_code.config.settings import Settings

from .ports import ApiServices


def get_services(request: Request) -> ApiServices:
    """Return the complete services supplied when the app was constructed."""
    return request.app.state.services


def get_settings(services: ApiServices = Depends(get_services)) -> Settings:
    """Return the current request-runtime settings snapshot."""
    return services.requests.current_settings()


async def resolve_provider(
    provider_type: str,
    api_key_number: int = 1,
    *,
    lease: RequestRuntimeLease,
) -> ProviderPort:
    """Resolve a provider through one retained generation."""
    should_log_init = not lease.is_provider_cached(provider_type, api_key_number)
    try:
        provider = await lease.resolve_provider(provider_type, api_key_number)
    except UnknownProviderError:
        logger.error(
            "Unknown provider_type: '{}'. Supported: {}",
            provider_type,
            ", ".join(f"'{key}'" for key in lease.settings.provider_ids),
        )
        raise
    if should_log_init:
        logger.info("Provider initialized: {} Key {}", provider_type, api_key_number)
    return provider


def require_proxy_auth(
    request: Request,
    settings: Settings = Depends(get_settings),
) -> None:
    """Require the configured proxy token as HTTP bearer authorization or x-api-key."""
    if not settings.proxy_auth_enabled:
        return

    token: str | None = None
    authorization = request.headers.get("authorization") or request.headers.get("proxy-authorization")
    if authorization:
        parts = authorization.strip().split(maxsplit=1)
        if len(parts) == 2 and parts[0].casefold() == "bearer":
            token = parts[1].strip()
        else:
            token = authorization.strip()

    if not token:
        token = request.headers.get("x-api-key")

    if not token:
        raise HTTPException(
            status_code=401,
            detail="Missing proxy authentication token",
        )

    if not secrets.compare_digest(
        token.encode("utf-8"),
        settings.proxy_auth_token.encode("utf-8"),
    ):
        raise HTTPException(
            status_code=401,
            detail="Invalid proxy authentication token",
        )


def require_anthropic_proxy_auth(
    request: Request,
    settings: Settings = Depends(get_settings),
) -> None:
    """Require Bearer or Anthropic ``x-api-key`` proxy authentication."""
    if not settings.proxy_auth_enabled:
        return

    authorization = request.headers.get("authorization")
    if authorization is not None:
        if _proxy_token_matches(
            authorization,
            settings.proxy_auth_token,
            require_bearer=True,
        ):
            return
        raise HTTPException(
            status_code=401,
            detail="Invalid proxy authentication token",
        )

    x_api_key = request.headers.get("x-api-key")
    if x_api_key is None:
        raise HTTPException(
            status_code=401,
            detail="Missing proxy authentication token",
        )

    if not _proxy_token_matches(
        x_api_key,
        settings.proxy_auth_token,
        require_bearer=False,
    ):
        raise HTTPException(
            status_code=401,
            detail="Invalid proxy authentication token",
        )


def require_gemini_proxy_auth(
    request: Request,
    settings: Settings = Depends(get_settings),
) -> None:
    keys = request.query_params.getlist("key")
    if len(keys) > 1:
        raise HTTPException(
            status_code=400, detail="Repeated key query credentials are unsupported"
        )
    if not settings.proxy_auth_enabled:
        return
    credential = request.headers.get("authorization")
    bearer = credential is not None
    if credential is None:
        credential = request.headers.get("x-goog-api-key")
    if credential is None:
        credential = keys[0] if keys else None
    if credential is None:
        raise HTTPException(
            status_code=401, detail="Missing proxy authentication token"
        )
    if not _proxy_token_matches(
        credential, settings.proxy_auth_token, require_bearer=bearer
    ):
        raise HTTPException(
            status_code=401, detail="Invalid proxy authentication token"
        )


def _proxy_token_matches(
    credential: str,
    configured_token: str,
    *,
    require_bearer: bool,
) -> bool:
    token = credential.strip()
    if require_bearer:
        parts = token.split(maxsplit=1)
        if len(parts) != 2 or parts[0].casefold() != "bearer":
            return False
        token = parts[1].strip()

    return bool(token) and secrets.compare_digest(
        token.encode("utf-8"),
        configured_token.encode("utf-8"),
    )