| 1 | use axum::extract::{DefaultBodyLimit, State}; |
| 2 | use axum::http::{HeaderValue, header}; |
| 3 | use axum::middleware::{self, Next}; |
| 4 | use axum::response::{IntoResponse, Response}; |
| 5 | use axum::routing::{delete, get, post}; |
| 6 | use axum::{Json, Router}; |
| 7 | use codewhale_account_cli::{AccountClient, AccountStatus}; |
| 8 | use codewhale_secrets::account::AccountAuthBundle; |
| 9 | use serde::Deserialize; |
| 10 | use serde_json::{Value, json}; |
| 11 | |
| 12 | use super::{ApiError, RuntimeApiState, auth}; |
| 13 | |
| 14 | pub(super) fn routes(state: &RuntimeApiState) -> Router<RuntimeApiState> { |
| 15 | Router::new() |
| 16 | .route("/v1/account/status", get(status)) |
| 17 | .route("/v1/account/lease", post(lease)) |
| 18 | .route("/v1/account/import", post(import)) |
| 19 | .route("/v1/account/session", delete(logout)) |
| 20 | .route("/v1/account/claim", post(claim).delete(cancel_claim)) |
| 21 | .layer(DefaultBodyLimit::max(256 * 1024)) |
| 22 | .route_layer(middleware::from_fn_with_state( |
| 23 | state.clone(), |
| 24 | auth::require_host_token, |
| 25 | )) |
| 26 | .layer(middleware::from_fn(no_store)) |
| 27 | } |
| 28 | |
| 29 | async fn no_store(request: axum::extract::Request, next: Next) -> Response { |
| 30 | let mut response = next.run(request).await; |
| 31 | response.headers_mut().insert( |
| 32 | header::CACHE_CONTROL, |
| 33 | HeaderValue::from_static("private, no-store"), |
| 34 | ); |
| 35 | response |
| 36 | } |
| 37 | |
| 38 | pub(super) fn client(state: &RuntimeApiState) -> Result<AccountClient, ApiError> { |
| 39 | AccountClient::new( |
| 40 | state.config_profile.as_deref(), |
| 41 | Some(&codewhale_engine::profile_constitution::runtime_account_api_base()), |
| 42 | ) |
| 43 | .map_err(|_| ApiError::internal("Codewhale account storage is unavailable")) |
| 44 | } |
| 45 | |
| 46 | fn receipt(status: AccountStatus) -> Value { |
| 47 | let display_name = status |
| 48 | .user |
| 49 | .as_ref() |
| 50 | .map(|user| { |
| 51 | if user.display_name.trim().is_empty() { |
| 52 | user.id.as_str() |
| 53 | } else { |
| 54 | user.display_name.as_str() |
| 55 | } |
| 56 | }) |
| 57 | .map(|name| name.chars().take(120).collect::<String>()); |
| 58 | json!({ |
| 59 | "apiBase": status.api_base, |
| 60 | "profile": status.profile, |
| 61 | "state": status.account.state, |
| 62 | "revision": status.revision, |
| 63 | "accountId": status.account.account_id, |
| 64 | "sessionId": status.account.session_id, |
| 65 | "expiresAt": status.account.expires_at, |
| 66 | "displayName": display_name, |
| 67 | "importAllowed": status.import_allowed, |
| 68 | }) |
| 69 | } |
| 70 | |
| 71 | fn read_status(client: &AccountClient) -> Result<Value, ApiError> { |
| 72 | client |
| 73 | .status() |
| 74 | .map(receipt) |
| 75 | .map_err(|_| ApiError::internal("Codewhale account storage could not be read")) |
| 76 | } |
| 77 | |
| 78 | async fn blocking( |
| 79 | operation: impl FnOnce() -> Result<Value, ApiError> + Send + 'static, |
| 80 | ) -> Result<Response, ApiError> { |
| 81 | tokio::task::spawn_blocking(operation) |
| 82 | .await |
| 83 | .map_err(|_| ApiError::internal("Codewhale account operation failed"))? |
| 84 | .map(|body| Json(body).into_response()) |
| 85 | } |
| 86 | |
| 87 | pub(super) async fn status_receipt(state: RuntimeApiState) -> Result<Value, ApiError> { |
| 88 | tokio::task::spawn_blocking(move || read_status(&client(&state)?)) |
| 89 | .await |
| 90 | .map_err(|_| ApiError::internal("Codewhale account operation failed"))? |
| 91 | } |
| 92 | |
| 93 | async fn status(State(state): State<RuntimeApiState>) -> Result<Response, ApiError> { |
| 94 | Ok(Json(status_receipt(state).await?).into_response()) |
| 95 | } |
| 96 | |
| 97 | #[derive(Deserialize)] |
| 98 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 99 | struct LeaseRequest { |
| 100 | rejected_access_token: Option<String>, |
| 101 | } |
| 102 | |
| 103 | async fn lease( |
| 104 | State(state): State<RuntimeApiState>, |
| 105 | Json(request): Json<LeaseRequest>, |
| 106 | ) -> Result<Response, ApiError> { |
| 107 | if request |
| 108 | .rejected_access_token |
| 109 | .as_ref() |
| 110 | .is_some_and(|token| token.len() > 64 * 1024) |
| 111 | { |
| 112 | return Err(ApiError::bad_request("Invalid rejected account credential")); |
| 113 | } |
| 114 | blocking(move || { |
| 115 | let client = client(&state)?; |
| 116 | let lease = client |
| 117 | .fresh_auth(request.rejected_access_token.as_deref()) |
| 118 | .map_err(|_| ApiError::conflict("Reconnect your Codewhale account and try again"))?; |
| 119 | let mut status = read_status(&client)?; |
| 120 | if let Some(lease) = lease { |
| 121 | if status["revision"].as_str() != Some(lease.snapshot.fingerprint().as_str()) |
| 122 | || status["accountId"].as_str() |
| 123 | != lease.bundle.user.as_ref().map(|user| user.id.as_str()) |
| 124 | || status["sessionId"].as_str() |
| 125 | != lease |
| 126 | .bundle |
| 127 | .session |
| 128 | .as_ref() |
| 129 | .map(|session| session.id.as_str()) |
| 130 | || status["accountId"].as_str().is_none() |
| 131 | || status["sessionId"].as_str().is_none() |
| 132 | { |
| 133 | return Err(ApiError::conflict( |
| 134 | "The Codewhale account changed; try again", |
| 135 | )); |
| 136 | } |
| 137 | status["accessToken"] = json!(lease.bundle.access_token); |
| 138 | } |
| 139 | Ok(status) |
| 140 | }) |
| 141 | .await |
| 142 | } |
| 143 | |
| 144 | #[derive(Deserialize)] |
| 145 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 146 | struct ImportRequest { |
| 147 | expected_revision: String, |
| 148 | auth: AccountAuthBundle, |
| 149 | #[serde(default)] |
| 150 | replace_existing: bool, |
| 151 | } |
| 152 | |
| 153 | async fn import( |
| 154 | State(state): State<RuntimeApiState>, |
| 155 | Json(request): Json<ImportRequest>, |
| 156 | ) -> Result<Response, ApiError> { |
| 157 | blocking(move || { |
| 158 | let client = client(&state)?; |
| 159 | let committed = client |
| 160 | .import_with_receipt( |
| 161 | request.auth, |
| 162 | &request.expected_revision, |
| 163 | request.replace_existing, |
| 164 | ) |
| 165 | .map_err(|_| { |
| 166 | ApiError::internal("The account connection could not be confirmed; try again") |
| 167 | })? |
| 168 | .ok_or_else(|| { |
| 169 | ApiError::conflict("The Codewhale account changed; try again") |
| 170 | .with_code("account_import_superseded") |
| 171 | })?; |
| 172 | let stored = committed |
| 173 | .load() |
| 174 | .map_err(|_| ApiError::internal("The account connection could not be confirmed"))? |
| 175 | .ok_or_else(|| ApiError::internal("The account connection could not be confirmed"))?; |
| 176 | let revision = committed.fingerprint(); |
| 177 | let mut status = receipt(AccountStatus { |
| 178 | profile: codewhale_secrets::account::normalize_account_profile( |
| 179 | state.config_profile.as_deref(), |
| 180 | ), |
| 181 | api_base: stored.api_base, |
| 182 | account: committed |
| 183 | .runtime_info_at(chrono::Utc::now()) |
| 184 | .map_err(|_| ApiError::internal("The account connection could not be confirmed"))?, |
| 185 | user: stored.bundle.user, |
| 186 | revision: revision.clone(), |
| 187 | import_allowed: false, |
| 188 | }); |
| 189 | status["committedRevision"] = json!(revision); |
| 190 | state.provider_connect.forget_claude_org_availability(); |
| 191 | Ok(status) |
| 192 | }) |
| 193 | .await |
| 194 | } |
| 195 | |
| 196 | async fn claim( |
| 197 | State(state): State<RuntimeApiState>, |
| 198 | Json(request): Json<CancelClaimRequest>, |
| 199 | ) -> Result<Response, ApiError> { |
| 200 | blocking(move || { |
| 201 | let client = client(&state)?; |
| 202 | let claimed = client |
| 203 | .claim_if_unchanged(&request.expected_revision) |
| 204 | .map_err(|_| ApiError::internal("The account connection could not be started"))? |
| 205 | .ok_or_else(|| ApiError::conflict("The Codewhale account changed; try again"))?; |
| 206 | let status = read_status(&client)?; |
| 207 | if status["revision"].as_str() != Some(claimed.fingerprint().as_str()) { |
| 208 | return Err(ApiError::conflict( |
| 209 | "The Codewhale account changed; try again", |
| 210 | )); |
| 211 | } |
| 212 | state.provider_connect.forget_claude_org_availability(); |
| 213 | Ok(status) |
| 214 | }) |
| 215 | .await |
| 216 | } |
| 217 | |
| 218 | #[derive(Deserialize)] |
| 219 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 220 | struct CancelClaimRequest { |
| 221 | expected_revision: String, |
| 222 | } |
| 223 | |
| 224 | async fn cancel_claim( |
| 225 | State(state): State<RuntimeApiState>, |
| 226 | Json(request): Json<CancelClaimRequest>, |
| 227 | ) -> Result<Response, ApiError> { |
| 228 | blocking(move || { |
| 229 | let client = client(&state)?; |
| 230 | let cancelled = client |
| 231 | .cancel_claim(&request.expected_revision) |
| 232 | .map_err(|_| ApiError::internal("The account connection could not be cancelled"))?; |
| 233 | let mut status = read_status(&client)?; |
| 234 | status["cancelled"] = json!(cancelled); |
| 235 | Ok(status) |
| 236 | }) |
| 237 | .await |
| 238 | } |
| 239 | |
| 240 | async fn logout( |
| 241 | State(state): State<RuntimeApiState>, |
| 242 | Json(request): Json<CancelClaimRequest>, |
| 243 | ) -> Result<Response, ApiError> { |
| 244 | blocking(move || { |
| 245 | let client = client(&state)?; |
| 246 | let expected = client |
| 247 | .snapshot() |
| 248 | .map_err(|_| ApiError::internal("Codewhale account storage could not be read"))?; |
| 249 | if expected.fingerprint() != request.expected_revision { |
| 250 | return Err(ApiError::conflict( |
| 251 | "The Codewhale account changed; try again", |
| 252 | )); |
| 253 | } |
| 254 | let expected_session = expected |
| 255 | .load() |
| 256 | .ok() |
| 257 | .flatten() |
| 258 | .and_then(|stored| stored.bundle.session) |
| 259 | .map(|session| session.id); |
| 260 | let expected_profile = |
| 261 | codewhale_secrets::account::normalize_account_profile(state.config_profile.as_deref()); |
| 262 | let revoked = client |
| 263 | .logout_if_unchanged(&expected) |
| 264 | .map_err(|_| ApiError::internal("The Codewhale account could not be signed out"))?; |
| 265 | { |
| 266 | let config = state.config.read(); |
| 267 | let mut access = config.account_model_access.write(); |
| 268 | if access.as_ref().is_some_and(|access| { |
| 269 | expected_session.as_deref() == Some(access.session_id.as_str()) |
| 270 | && codewhale_secrets::account::normalize_account_profile( |
| 271 | access.profile.as_deref(), |
| 272 | ) == expected_profile |
| 273 | }) { |
| 274 | access.take(); |
| 275 | } |
| 276 | } |
| 277 | state.provider_connect.forget_claude_org_availability(); |
| 278 | let mut status = read_status(&client)?; |
| 279 | status["remoteRevoked"] = json!(revoked); |
| 280 | Ok(status) |
| 281 | }) |
| 282 | .await |
| 283 | } |
| 284 |