File size: 9,464 Bytes
c91c7db
 
 
b998e5a
 
 
c91c7db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b998e5a
 
 
 
 
 
 
 
ac630d5
 
 
 
b998e5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c91c7db
 
 
 
 
 
 
 
 
 
 
 
3493993
 
1fed801
c91c7db
 
 
 
 
b998e5a
c91c7db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b998e5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c91c7db
 
 
 
 
 
 
b998e5a
c91c7db
 
3493993
 
 
 
c91c7db
 
 
 
 
 
 
 
b998e5a
 
c91c7db
 
 
 
 
 
 
 
 
 
b998e5a
 
c91c7db
 
 
 
 
 
 
 
 
 
b998e5a
 
c91c7db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b998e5a
 
c91c7db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b998e5a
 
c91c7db
 
 
 
 
 
 
 
 
 
 
 
b998e5a
 
c91c7db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b998e5a
 
 
 
 
 
 
 
 
 
 
 
 
c91c7db
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
from __future__ import annotations

from fastapi import APIRouter, HTTPException, Query, Request, Response, status
from sqlalchemy import func, select

from app.security.models import APIKey, APIKeyPrincipal, AuditLog

from app.security.errors import APIKeyConflictError, APIKeyNotFoundError
from app.security.schemas import (
    APIKeyCreate,
    APIKeyCreated,
    APIKeyList,
    APIKeyPatch,
    APIKeyRotate,
    APIKeyView,
    AuthContextView,
    AuditLogView,
)
from app.security.scopes import ALL_SCOPES

router = APIRouter(prefix="/v1", tags=["authentication"])


def _view(record: object) -> APIKeyView:
    return APIKeyView.model_validate(record)


def _not_found() -> HTTPException:
    return HTTPException(status_code=404, detail="API key was not found")


def _require_workspace_key_admin(request: Request):
    """Require a resolved user membership with workspace owner/admin authority."""
    context = getattr(request.state, "auth", None)
    if (
        context is None
        or not context.workspace_id
        or not context.user_id
        or (context.membership_role or "").strip().lower() not in {"owner", "admin"}
        or (
            getattr(request.state, "studio_identity_verified", False) is not True
            and "admin" not in context.scopes
        )
    ):
        raise HTTPException(status_code=403, detail="Workspace owner or admin membership is required")
    return context


async def _require_key_in_workspace(request: Request, key_id: str, context) -> None:
    session_factory = request.app.state.container.security_database.session
    async with session_factory() as session:
        principal = await session.scalar(
            select(APIKeyPrincipal).where(
                APIKeyPrincipal.api_key_id == key_id,
                APIKeyPrincipal.workspace_id == context.workspace_id,
                APIKeyPrincipal.status == "active",
            )
        )
    if principal is None:
        # Do not disclose whether another workspace owns the identifier.
        raise _not_found()


@router.get("/auth/context", response_model=AuthContextView)
async def current_auth_context(request: Request) -> AuthContextView:
    """Validate a key and return only its safe, non-secret authorization context."""
    context = request.state.auth
    return AuthContextView(
        id=context.api_key_id,
        name=context.key_name,
        key_prefix=context.key_prefix,
        environment=context.environment,
        role=context.role,
        scopes=sorted(context.scopes),
        expires_at=context.expires_at,
        workspace_id=context.workspace_id,
        user_id=context.user_id,
        membership_role=context.membership_role,
    )


@router.get("/api-keys/capabilities")
async def api_key_capabilities(request: Request) -> dict[str, object]:
    _require_workspace_key_admin(request)
    container = request.app.state.container
    return {
        "scopes": sorted(ALL_SCOPES),
        "roles": {
            role: sorted(scopes)
            for role, scopes in container.api_keys.roles.items()
        },
        "defaults": {
            "requests_per_minute": container.settings.auth_default_requests_per_minute,
            "concurrent_jobs": container.settings.auth_default_concurrent_jobs,
            "uploads_per_hour": container.settings.auth_default_uploads_per_hour,
            "processing_bytes_per_day": (
                container.settings.auth_default_processing_bytes_per_day
            ),
        },
    }


@router.get("/api-keys", response_model=APIKeyList)
async def list_api_keys(
    request: Request,
    offset: int = Query(default=0, ge=0),
    limit: int = Query(default=100, ge=1, le=500),
) -> APIKeyList:
    context = _require_workspace_key_admin(request)
    await request.app.state.container.api_keys._finalize_expired_rotations()
    async with request.app.state.container.security_database.session() as session:
        base = (
            select(APIKey)
            .join(APIKeyPrincipal, APIKeyPrincipal.api_key_id == APIKey.id)
            .where(
                APIKeyPrincipal.workspace_id == context.workspace_id,
                APIKeyPrincipal.status == "active",
            )
        )
        total = int(await session.scalar(select(func.count()).select_from(base.subquery())) or 0)
        records = list((await session.scalars(
            base.order_by(APIKey.created_at.desc()).offset(offset).limit(limit)
        )).all())
    return APIKeyList(items=[_view(record) for record in records], total=total)


@router.post(
    "/api-keys", response_model=APIKeyCreated, status_code=status.HTTP_201_CREATED
)
async def create_api_key(request: Request, payload: APIKeyCreate) -> APIKeyCreated:
    context = _require_workspace_key_admin(request)
    try:
        record, secret = await request.app.state.container.api_keys.create(
            payload,
            created_by=context.api_key_id,
            workspace_id=context.workspace_id,
            user_id=context.user_id,
        )
    except APIKeyConflictError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc
    return APIKeyCreated(**_view(record).model_dump(), api_key=secret)


@router.get("/api-keys/{key_id}", response_model=APIKeyView)
async def get_api_key(request: Request, key_id: str) -> APIKeyView:
    context = _require_workspace_key_admin(request)
    await _require_key_in_workspace(request, key_id, context)
    try:
        return _view(await request.app.state.container.api_keys.get(key_id))
    except APIKeyNotFoundError as exc:
        raise _not_found() from exc


@router.patch("/api-keys/{key_id}", response_model=APIKeyView)
async def patch_api_key(
    request: Request, key_id: str, payload: APIKeyPatch
) -> APIKeyView:
    context = _require_workspace_key_admin(request)
    await _require_key_in_workspace(request, key_id, context)
    try:
        return _view(await request.app.state.container.api_keys.patch(key_id, payload))
    except APIKeyNotFoundError as exc:
        raise _not_found() from exc
    except APIKeyConflictError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc


@router.delete("/api-keys/{key_id}", status_code=status.HTTP_204_NO_CONTENT)
async def revoke_api_key(request: Request, key_id: str) -> Response:
    context = _require_workspace_key_admin(request)
    await _require_key_in_workspace(request, key_id, context)
    try:
        await request.app.state.container.api_keys.set_status(key_id, "revoked")
    except APIKeyNotFoundError as exc:
        raise _not_found() from exc
    return Response(status_code=status.HTTP_204_NO_CONTENT)


@router.post(
    "/api-keys/{key_id}/rotate",
    response_model=APIKeyCreated,
    status_code=status.HTTP_201_CREATED,
)
async def rotate_api_key(
    request: Request, key_id: str, payload: APIKeyRotate
) -> APIKeyCreated:
    context = _require_workspace_key_admin(request)
    await _require_key_in_workspace(request, key_id, context)
    try:
        record, secret = await request.app.state.container.api_keys.rotate(
            key_id,
            payload.grace_period_seconds,
            created_by=request.state.auth.api_key_id,
        )
    except APIKeyNotFoundError as exc:
        raise _not_found() from exc
    except APIKeyConflictError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc
    return APIKeyCreated(**_view(record).model_dump(), api_key=secret)


@router.post("/api-keys/{key_id}/disable", response_model=APIKeyView)
async def disable_api_key(request: Request, key_id: str) -> APIKeyView:
    context = _require_workspace_key_admin(request)
    await _require_key_in_workspace(request, key_id, context)
    try:
        return _view(
            await request.app.state.container.api_keys.set_status(key_id, "disabled")
        )
    except APIKeyNotFoundError as exc:
        raise _not_found() from exc
    except APIKeyConflictError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc


@router.post("/api-keys/{key_id}/enable", response_model=APIKeyView)
async def enable_api_key(request: Request, key_id: str) -> APIKeyView:
    context = _require_workspace_key_admin(request)
    await _require_key_in_workspace(request, key_id, context)
    try:
        return _view(
            await request.app.state.container.api_keys.set_status(key_id, "active")
        )
    except APIKeyNotFoundError as exc:
        raise _not_found() from exc
    except APIKeyConflictError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc


@router.get("/audit-logs", response_model=list[AuditLogView])
async def list_audit_logs(
    request: Request,
    offset: int = Query(default=0, ge=0),
    limit: int = Query(default=100, ge=1, le=500),
) -> list[AuditLogView]:
    context = _require_workspace_key_admin(request)
    async with request.app.state.container.security_database.session() as session:
        records = list((await session.scalars(
            select(AuditLog)
            .join(APIKeyPrincipal, APIKeyPrincipal.api_key_id == AuditLog.api_key_id)
            .where(
                APIKeyPrincipal.workspace_id == context.workspace_id,
                APIKeyPrincipal.status == "active",
            )
            .order_by(AuditLog.created_at.desc())
            .offset(offset)
            .limit(limit)
        )).all())
    return [AuditLogView.model_validate(record) for record in records]