1#![forbid(unsafe_code)]
4
5use std::collections::HashMap;
6use std::net::SocketAddr;
7use std::sync::Arc;
8
9use axum::body::Bytes;
10use axum::extract::{Path, Query, State};
11use axum::http::{HeaderMap, StatusCode};
12use axum::response::IntoResponse;
13use axum::routing::{get, post};
14use axum::{Json, Router};
15use serde::Deserialize;
16use serde_json::{json, Value};
17use sylphx_api_types::{
18 Deployment, Environment, ErrorDetail, ErrorEnvelope, HealthResponse, OrganizationRef, PageInfo,
19 PrincipalUser, Project, WhoAmIResponse,
20};
21use tokio::sync::Mutex;
22
23const VALID_TOKEN: &str = "svc_test";
24const VALID_APP_SECRET: &str = "sk_test_deadbeef";
25
26#[derive(Clone)]
27struct AppState {
28 kv: Arc<Mutex<HashMap<String, (Value, Option<f64>)>>>,
29 env_vars: Arc<Mutex<HashMap<String, Value>>>,
30 resources: Arc<Mutex<HashMap<String, Value>>>,
31 flags: Arc<Mutex<HashMap<String, Value>>>,
32 tasks: Arc<Mutex<HashMap<String, Value>>>,
33 objects: Arc<Mutex<HashMap<String, Vec<u8>>>>,
34}
35
36pub struct WireMockServer {
38 addr: SocketAddr,
39 shutdown: Option<tokio::sync::oneshot::Sender<()>>,
40 join: Option<tokio::task::JoinHandle<()>>,
41}
42
43impl WireMockServer {
44 pub async fn start() -> Self {
46 let state = AppState {
47 kv: Arc::new(Mutex::new(HashMap::new())),
48 env_vars: Arc::new(Mutex::new(HashMap::new())),
49 resources: Arc::new(Mutex::new(HashMap::new())),
50 flags: Arc::new(Mutex::new(HashMap::new())),
51 tasks: Arc::new(Mutex::new(HashMap::new())),
52 objects: Arc::new(Mutex::new(HashMap::new())),
53 };
54 let app = Router::new()
55 .route("/v1/health", get(health))
56 .route("/v1/whoami", get(whoami))
57 .route("/v1/secrets", get(list_secrets).post(set_secret).delete(delete_secret))
58 .route("/v1/projects", get(list_projects).post(create_project))
59 .route("/v1/projects/{id}", get(get_project))
60 .route("/v1/projects/{id}/status", get(project_status))
61 .route("/v1/projects/{id}/environments", get(list_environments))
62 .route(
63 "/v1/projects/{id}/environments/{env_id}",
64 get(get_environment),
65 )
66 .route("/v1/projects/{id}/deployments", get(list_deployments))
67 .route("/v1/projects/{id}/candidates", post(publish_candidate))
68 .route(
69 "/v1/projects/{id}/candidates/{candidate_id}",
70 get(get_candidate),
71 )
72 .route("/v1/projects/{id}/deploy", post(create_deploy))
73 .route("/v1/projects/{id}/logs", get(project_logs))
74 .route("/v1/environments/{env_id}/logs", get(env_logs))
75 .route("/v1/resources", get(list_resources).post(create_resource))
76 .route(
77 "/v1/resources/{id}",
78 get(get_resource).delete(delete_resource),
79 )
80 .route("/v1/resources/{id}/bindings", post(bind_resource))
81 .route("/v1/flags", get(list_flags).post(create_flag))
82 .route("/v1/kv", post(kv_set))
83 .route("/v1/kv/incr", post(kv_incr))
84 .route("/v1/kv/expire", post(kv_expire))
85 .route("/v1/kv/{key}/exists", get(kv_exists))
86 .route("/v1/kv/{key}", get(kv_get).delete(kv_delete))
87 .route("/v1/email/send", post(email_send))
89 .route("/v1/email/configured", get(email_configured))
90 .route("/v1/email/send-to-user", post(email_send_to_user))
91 .route("/v1/objects/buckets", get(objects_list_buckets).post(objects_create_bucket))
92 .route("/v1/objects", get(objects_list))
93 .route("/v1/objects/{*key}", get(objects_get).put(objects_put))
94 .route("/v1/sandboxes", get(sandbox_list).post(sandbox_create))
95 .route("/v1/sandboxes/{id}", get(sandbox_get))
96 .route("/v1/flags/evaluate", post(flags_evaluate))
97 .route("/v1/search/index", post(search_index))
98 .route("/v1/search/search", post(search_query))
99 .route("/v1/sdk/realtime/emit", post(realtime_emit))
100 .route("/v1/auth/login", post(auth_login))
101 .route(
102 "/.well-known/oauth-authorization-server",
103 get(oauth_authorization_server_metadata),
104 )
105 .route("/v1/auth/device", post(device_init))
106 .route("/v1/auth/device/poll", get(device_poll))
107 .route("/v1/oauth/token", post(oauth_token))
108 .route("/v1/oauth/revoke", post(oauth_revoke))
109 .route("/v1/auth/me", get(auth_me))
110 .route("/v1/webhooks/config", get(webhooks_config))
111 .route("/v1/analytics/track", post(analytics_track))
112 .route("/v1/notifications/send", post(notifications_send))
113 .route("/v1/consent", get(consent_get).post(consent_set))
114 .route("/v1/sdk/monitoring/exception", post(monitoring_exception))
115 .route("/v1/rate-limits/status", get(rate_limits_status))
116 .route("/v1/referrals/code", get(referrals_code))
117 .route("/v1/billing/usage", get(billing_usage))
118 .with_state(state);
119 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
120 let addr = listener.local_addr().unwrap();
121 let (tx, rx) = tokio::sync::oneshot::channel::<()>();
122 let join = tokio::spawn(async move {
123 axum::serve(listener, app)
124 .with_graceful_shutdown(async {
125 let _ = rx.await;
126 })
127 .await
128 .ok();
129 });
130 for _ in 0..100 {
131 if tokio::net::TcpStream::connect(addr).await.is_ok() {
132 break;
133 }
134 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
135 }
136 Self {
137 addr,
138 shutdown: Some(tx),
139 join: Some(join),
140 }
141 }
142
143 pub fn management_base_url(&self) -> String {
145 format!("http://{}/v1", self.addr)
146 }
147 pub fn baas_base_url(&self) -> String {
149 format!("http://{}/v1", self.addr)
150 }
151 pub async fn shutdown(mut self) {
153 if let Some(tx) = self.shutdown.take() {
154 let _ = tx.send(());
155 }
156 if let Some(join) = self.join.take() {
157 let _ = join.await;
158 }
159 }
160}
161
162fn unauthorized() -> impl IntoResponse {
163 (
164 StatusCode::UNAUTHORIZED,
165 Json(ErrorEnvelope {
166 error: ErrorDetail {
167 status: Some(sylphx_api_types::proto::google::rpc::Status {
168 code: 16,
169 message: "invalid credentials".into(),
170 details: vec![],
171 ..Default::default()
172 })
173 .into(),
174 code: "unauthenticated".into(),
175 ..Default::default()
176 }
177 .into(),
178 ..Default::default()
179 }),
180 )
181}
182
183fn not_found(msg: &str) -> impl IntoResponse {
184 (
185 StatusCode::NOT_FOUND,
186 Json(ErrorEnvelope {
187 error: ErrorDetail {
188 status: Some(sylphx_api_types::proto::google::rpc::Status {
189 code: 5,
190 message: msg.into(),
191 details: vec![],
192 ..Default::default()
193 })
194 .into(),
195 code: "not_found".into(),
196 ..Default::default()
197 }
198 .into(),
199 ..Default::default()
200 }),
201 )
202}
203
204fn require_bearer(headers: &HeaderMap) -> Result<(), ()> {
205 let auth = headers
206 .get(axum::http::header::AUTHORIZATION)
207 .and_then(|v| v.to_str().ok())
208 .unwrap_or("");
209 if auth == format!("Bearer {VALID_TOKEN}") {
210 Ok(())
211 } else {
212 Err(())
213 }
214}
215
216fn require_bearer_or_app(headers: &HeaderMap) -> Result<(), ()> {
217 if require_bearer(headers).is_ok() || require_app_secret(headers).is_ok() {
218 Ok(())
219 } else {
220 Err(())
221 }
222}
223
224fn require_app_secret(headers: &HeaderMap) -> Result<(), ()> {
225 let key = headers
226 .get("x-app-secret")
227 .and_then(|v| v.to_str().ok())
228 .unwrap_or("");
229 if key == VALID_APP_SECRET {
230 Ok(())
231 } else {
232 Err(())
233 }
234}
235
236fn demo_project() -> Project {
237 Project {
238 id: "prj_demo".into(),
239 slug: "demo".into(),
240 name: "Demo".into(),
241 description: Some("wire mock project".into()),
242 org_id: "org_1".into(),
243 is_active: true,
244 r#ref: Some("main".into()),
245 sdk_url: Some("https://demo.api.sylphx.com/v1".into()),
246 infra_status: Some("ready".into()),
247 domains: vec!["demo.example.com".into()],
248 build_machine_type: Some("standard".into()),
249 region: Some("fsn1".into()),
250 created_at: Default::default(),
251 updated_at: Default::default(),
252 preview_max_active: None,
253 preview_tier_policy: None,
254 webhook_url: None,
255 webhook_events: vec![],
256 enabled_oauth_providers: vec![],
257 environments: vec![],
258 ..Default::default()
259 }
260}
261
262fn demo_environment(project_id: &str) -> Environment {
263 Environment {
264 id: "env_prod".into(),
265 slug: "production".into(),
266 name: "Production".into(),
267 project_id: project_id.to_string(),
268 branch: Some("main".into()),
269 status: Some("ready".into()),
270 env_type: Some("production".into()),
271 is_active: Some(true),
272 lifecycle_state: Some("active".into()),
273 protection: Default::default(),
274 public_key: Default::default(),
275 public_networking: Some(true),
276 reconcile_status: None,
277 created_at: Default::default(),
278 updated_at: Default::default(),
279 github_branch: Some("main".into()),
280 github_repo: None,
281 default_from_email: None,
282 default_from_name: None,
283 allowed_origins: vec![],
284 custom_domains: vec![],
285 auto_deploy: Some(false),
286 ..Default::default()
287 }
288}
289
290async fn health() -> Json<HealthResponse> {
291 Json(HealthResponse {
292 status: "ok".into(),
293 version: Some("0.1.0".into()),
294 git_sha: Some("wiremock".into()),
295 draining: Some(false),
296 k8s_configured: Some(true),
297 release: Some("mock".into()),
298 services: Default::default(),
299 transport: Some("mock".into()),
300 uptime_ms: Some(0),
301 ..Default::default()
302 })
303}
304
305async fn whoami(headers: HeaderMap) -> impl IntoResponse {
306 if require_bearer(&headers).is_err() {
307 return unauthorized().into_response();
308 }
309 Json(WhoAmIResponse {
310 user: PrincipalUser {
311 id: "user_1".into(),
312 email: "dev@sylphx.com".into(),
313 name: Some("Dev".into()),
314 ..Default::default()
315 }
316 .into(),
317 orgs: vec![OrganizationRef {
318 id: "org_1".into(),
319 slug: "acme".into(),
320 name: "Acme".into(),
321 ..Default::default()
322 }],
323 ..Default::default()
324 })
325 .into_response()
326}
327
328#[derive(Debug, Deserialize)]
329struct ListQuery {
330 #[serde(rename = "pageToken")]
331 page_token: Option<String>,
332 #[serde(rename = "pageSize")]
333 page_size: Option<u32>,
334 kind: Option<String>,
335 #[serde(rename = "projectId")]
336 project_id: Option<String>,
337 #[serde(rename = "envType")]
338 env_type: Option<String>,
339 #[serde(rename = "envId")]
340 env_id: Option<String>,
341 #[serde(rename = "type")]
342 log_type: Option<String>,
343 limit: Option<u32>,
344 level: Option<String>,
345 service: Option<String>,
346 grep: Option<String>,
347}
348
349async fn list_projects(headers: HeaderMap, Query(q): Query<ListQuery>) -> impl IntoResponse {
350 if require_bearer(&headers).is_err() {
351 return unauthorized().into_response();
352 }
353 let _ = q.page_size;
354 Json(json!({
355 "object": "list",
356 "data": [demo_project()],
357 "page": PageInfo {
358 next_page_token: q.page_token.unwrap_or_default(),
359 total_size: Some(1),
360 ..Default::default()
361 }
362 }))
363 .into_response()
364}
365
366async fn create_project(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
367 if require_bearer(&headers).is_err() {
368 return unauthorized().into_response();
369 }
370 let name = body.get("name").and_then(|v| v.as_str()).unwrap_or("New");
371 let slug = body
372 .get("slug")
373 .and_then(|v| v.as_str())
374 .unwrap_or("new-project");
375 let mut p = demo_project();
376 p.id = "prj_new".into();
377 p.name = name.into();
378 p.slug = slug.into();
379 Json(p).into_response()
380}
381
382async fn get_project(headers: HeaderMap, Path(id): Path<String>) -> impl IntoResponse {
383 if require_bearer(&headers).is_err() {
384 return unauthorized().into_response();
385 }
386 let p = demo_project();
387 if id != p.id && id != p.slug {
388 return not_found("project not found").into_response();
389 }
390 Json(p).into_response()
391}
392
393async fn publish_candidate(
394 headers: HeaderMap,
395 Path(project_id): Path<String>,
396 Json(body): Json<Value>,
397) -> impl IntoResponse {
398 if require_bearer(&headers).is_err() {
399 return unauthorized().into_response();
400 }
401 let Some(content) = body.get("content") else {
402 return (
403 StatusCode::BAD_REQUEST,
404 Json(json!({"error": {"code": "candidate_content_required"}})),
405 )
406 .into_response();
407 };
408 if content.get("policy_profile_digest").is_some()
409 || content.get("work_item_id").and_then(Value::as_str) != Some("wi_demo")
410 || content.get("producer_attempt_id").and_then(Value::as_str) != Some("att_demo")
411 {
412 return (
413 StatusCode::BAD_REQUEST,
414 Json(json!({"error": {"code": "candidate_authority_invalid"}})),
415 )
416 .into_response();
417 }
418 Json(json!({
419 "id": "11111111-1111-4111-8111-111111111111",
420 "project_id": project_id,
421 "candidate_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
422 "source_revision": content.get("source_revision"),
423 "status": "proposed",
424 }))
425 .into_response()
426}
427
428async fn get_candidate(
429 headers: HeaderMap,
430 Path((project_id, candidate_id)): Path<(String, String)>,
431) -> impl IntoResponse {
432 if require_bearer(&headers).is_err() {
433 return unauthorized().into_response();
434 }
435 Json(json!({
436 "id": candidate_id,
437 "project_id": project_id,
438 "candidate_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
439 "source_revision": "dddddddddddddddddddddddddddddddddddddddd",
440 "status": "proposed",
441 }))
442 .into_response()
443}
444
445async fn project_status(headers: HeaderMap, Path(id): Path<String>) -> impl IntoResponse {
446 if require_bearer(&headers).is_err() {
447 return unauthorized().into_response();
448 }
449 let p = demo_project();
450 if id != p.id && id != p.slug {
451 return not_found("project not found").into_response();
452 }
453 Json(json!({
454 "projectId": p.id,
455 "status": "running",
456 "environmentId": "env_prod",
457 "deploymentId": "dep_1",
458 "message": "healthy"
459 }))
460 .into_response()
461}
462
463async fn list_environments(
464 headers: HeaderMap,
465 Path(id): Path<String>,
466 Query(q): Query<ListQuery>,
467) -> impl IntoResponse {
468 if require_bearer(&headers).is_err() {
469 return unauthorized().into_response();
470 }
471 let p = demo_project();
472 if id != p.id && id != p.slug {
473 return not_found("project not found").into_response();
474 }
475 let env = demo_environment(&p.id);
476 Json(json!({
477 "object": "list",
478 "data": [env],
479 "page": PageInfo {
480 next_page_token: q.page_token.unwrap_or_default(),
481 total_size: Some(1),
482 ..Default::default()
483 }
484 }))
485 .into_response()
486}
487
488async fn get_environment(
489 headers: HeaderMap,
490 Path((id, env_id)): Path<(String, String)>,
491) -> impl IntoResponse {
492 if require_bearer(&headers).is_err() {
493 return unauthorized().into_response();
494 }
495 let p = demo_project();
496 if id != p.id && id != p.slug {
497 return not_found("project not found").into_response();
498 }
499 let env = demo_environment(&p.id);
500 if env_id != env.id && env_id != env.slug {
501 return not_found("environment not found").into_response();
502 }
503 Json(env).into_response()
504}
505
506async fn list_deployments(
507 headers: HeaderMap,
508 Path(id): Path<String>,
509 Query(q): Query<ListQuery>,
510) -> impl IntoResponse {
511 if require_bearer(&headers).is_err() {
512 return unauthorized().into_response();
513 }
514 let p = demo_project();
515 if id != p.id && id != p.slug {
516 return not_found("project not found").into_response();
517 }
518 let dep = Deployment {
519 id: "dep_1".into(),
520 project_id: p.id.clone(),
521 environment_id: Some("env_prod".into()),
522 status: "ready".into(),
523 git_sha: Some("abc123".into()),
524 created_at: Default::default(),
525 git_commit: None,
526 git_branch: None,
527 image_digest: None,
528 triggered_by: None,
529 skip_reason: None,
530 started_at: Default::default(),
531 finished_at: Default::default(),
532 deploy_app_id: None,
533 ..Default::default()
534 };
535 Json(json!({
536 "object": "list",
537 "data": [dep],
538 "page": PageInfo {
539 next_page_token: q.page_token.unwrap_or_default(),
540 total_size: Some(1),
541 ..Default::default()
542 }
543 }))
544 .into_response()
545}
546
547async fn create_deploy(
548 headers: HeaderMap,
549 Path(id): Path<String>,
550 Json(body): Json<Value>,
551) -> impl IntoResponse {
552 if require_bearer(&headers).is_err() {
553 return unauthorized().into_response();
554 }
555 let p = demo_project();
556 if id != p.id && id != p.slug {
557 return not_found("project not found").into_response();
558 }
559 let _ = body;
560 Json(json!({
561 "id": "dep_new",
562 "status": "building",
563 "projectId": p.id,
564 "environmentId": "env_prod",
565 "message": "deploy started"
566 }))
567 .into_response()
568}
569
570
571async fn list_secrets(
572 headers: HeaderMap,
573 State(state): State<AppState>,
574 Query(q): Query<ListQuery>,
575) -> impl IntoResponse {
576 if require_bearer(&headers).is_err() {
577 return unauthorized().into_response();
578 }
579 let map = state.env_vars.lock().await;
580 let mut secrets: Vec<Value> = map
581 .iter()
582 .map(|(k, v)| {
583 json!({
584 "id": format!("sec_mock_{}", k),
585 "key": k,
586 "description": Value::Null,
587 "environment": v.get("environmentId").cloned().map(|eid| json!({"id": eid, "name": "production"})),
588 "isActive": true,
589 "version": "1",
590 })
591 })
592 .collect();
593 if secrets.is_empty() {
594 secrets.push(json!({
595 "id": "sec_mock_NODE_ENV",
596 "key": "NODE_ENV",
597 "description": Value::Null,
598 "environment": json!({"id": "env_mock", "name": "production"}),
599 "isActive": true,
600 "version": "1",
601 }));
602 }
603 Json(json!({"secrets": secrets})).into_response()
604}
605
606async fn set_secret(
607 headers: HeaderMap,
608 State(state): State<AppState>,
609 Json(body): Json<Value>,
610) -> impl IntoResponse {
611 if require_bearer(&headers).is_err() {
612 return unauthorized().into_response();
613 }
614 let key = body
615 .get("key")
616 .and_then(|v| v.as_str())
617 .unwrap_or("")
618 .to_string();
619 let value = body
620 .get("value")
621 .and_then(|v| v.as_str())
622 .unwrap_or("")
623 .to_string();
624 let environment_id = body.get("environmentId").cloned();
625 let mut map = state.env_vars.lock().await;
626 let created = !map.contains_key(&key);
627 map.insert(
628 key.clone(),
629 json!({
630 "key": key,
631 "value": value,
632 "secret": true,
633 "environmentId": environment_id,
634 }),
635 );
636 Json(json!({"id": format!("sec_mock_{}", key), "key": key, "created": created})).into_response()
637}
638
639async fn delete_secret(
640 headers: HeaderMap,
641 State(state): State<AppState>,
642 Json(body): Json<Value>,
643) -> impl IntoResponse {
644 if require_bearer(&headers).is_err() {
645 return unauthorized().into_response();
646 }
647 let id = body
648 .get("id")
649 .and_then(|v| v.as_str())
650 .unwrap_or("")
651 .to_string();
652 let key = id.strip_prefix("sec_mock_").unwrap_or(&id).to_string();
653 let mut map = state.env_vars.lock().await;
654 let deleted = map.remove(&key).is_some() || key == "NODE_ENV";
655 Json(json!({"deleted": deleted, "key": key})).into_response()
656}
657
658async fn project_logs(
659 headers: HeaderMap,
660 Path(id): Path<String>,
661 Query(q): Query<ListQuery>,
662) -> impl IntoResponse {
663 if require_bearer(&headers).is_err() {
664 return unauthorized().into_response();
665 }
666 let p = demo_project();
667 if id != p.id && id != p.slug {
668 return not_found("project not found").into_response();
669 }
670 let limit = q.limit.unwrap_or(100).min(100) as usize;
671 let src = q.log_type.unwrap_or_else(|| "build".into());
672 let lines: Vec<Value> = (0..limit.min(3))
673 .map(|i| {
674 json!({
675 "timestamp": format!("2026-07-15T00:00:0{i}Z"),
676 "message": format!("{src} log line {i}"),
677 "level": "info",
678 "source": src,
679 })
680 })
681 .collect();
682 Json(json!({"object": "list", "data": lines})).into_response()
683}
684
685async fn env_logs(
686 headers: HeaderMap,
687 Path(env_id): Path<String>,
688 Query(q): Query<ListQuery>,
689) -> impl IntoResponse {
690 if require_bearer(&headers).is_err() {
691 return unauthorized().into_response();
692 }
693 if env_id != "env_prod" && env_id != "production" {
694 return not_found("environment not found").into_response();
695 }
696 let limit = q.limit.unwrap_or(100).min(100) as usize;
697 let src = q.log_type.unwrap_or_else(|| "runtime".into());
698 let lines: Vec<Value> = (0..limit.min(3))
699 .map(|i| {
700 json!({
701 "timestamp": format!("2026-07-15T01:00:0{i}Z"),
702 "message": format!("{src} log line {i}"),
703 "level": q.level.clone().unwrap_or_else(|| "info".into()),
704 "service": q.service.clone().unwrap_or_else(|| "web".into()),
705 "source": src,
706 })
707 })
708 .collect();
709 Json(json!({"object": "list", "data": lines})).into_response()
710}
711
712async fn list_resources(
713 headers: HeaderMap,
714 State(state): State<AppState>,
715 Query(q): Query<ListQuery>,
716) -> impl IntoResponse {
717 if require_bearer(&headers).is_err() {
718 return unauthorized().into_response();
719 }
720 let map = state.resources.lock().await;
721 let mut data: Vec<Value> = map.values().cloned().collect();
722 if data.is_empty() {
723 data.push(json!({
724 "id": "res_db1",
725 "kind": "database",
726 "name": "primary",
727 "status": "ready",
728 "projectId": "prj_demo",
729 "tier": "standard",
730 "storageGb": 10
731 }));
732 }
733 if let Some(kind) = &q.kind {
734 data.retain(|r| r.get("kind").and_then(|v| v.as_str()) == Some(kind.as_str()));
735 }
736 Json(json!({
737 "object": "list",
738 "data": data,
739 "page": {"nextPageToken": "", "totalSize": data.len()}
740 }))
741 .into_response()
742}
743
744async fn create_resource(
745 headers: HeaderMap,
746 State(state): State<AppState>,
747 Json(body): Json<Value>,
748) -> impl IntoResponse {
749 if require_bearer(&headers).is_err() {
750 return unauthorized().into_response();
751 }
752 let kind = body
753 .get("kind")
754 .and_then(|v| v.as_str())
755 .unwrap_or("database");
756 let name = body.get("name").and_then(|v| v.as_str()).unwrap_or("db");
757 let id = format!("res_{name}");
758 let resource = json!({
759 "id": id,
760 "kind": kind,
761 "name": name,
762 "status": "provisioning",
763 "projectId": body.get("projectId").cloned().unwrap_or(json!("prj_demo")),
764 "tier": body.get("tier").cloned().unwrap_or(json!("standard")),
765 "storageGb": body.get("storageGb").cloned().unwrap_or(json!(10)),
766 "message": "Database provisioning started. Poll GET /resources/:id for status."
767 });
768 state
769 .resources
770 .lock()
771 .await
772 .insert(id.clone(), resource.clone());
773 Json(json!({
774 "operation": operation_json(json!({
775 "resource": resource,
776 "message": "provisioning started",
777 }))
778 }))
779 .into_response()
780}
781
782async fn get_resource(
783 headers: HeaderMap,
784 State(state): State<AppState>,
785 Path(id): Path<String>,
786) -> impl IntoResponse {
787 if require_bearer(&headers).is_err() {
788 return unauthorized().into_response();
789 }
790 let map = state.resources.lock().await;
791 if let Some(r) = map.get(&id) {
792 return Json(r.clone()).into_response();
793 }
794 if id == "res_db1" {
795 return Json(json!({
796 "id": "res_db1",
797 "kind": "database",
798 "name": "primary",
799 "status": "ready",
800 "projectId": "prj_demo",
801 "tier": "standard",
802 "storageGb": 10
803 }))
804 .into_response();
805 }
806 not_found("resource not found").into_response()
807}
808
809async fn delete_resource(
810 headers: HeaderMap,
811 State(state): State<AppState>,
812 Path(id): Path<String>,
813) -> impl IntoResponse {
814 if require_bearer(&headers).is_err() {
815 return unauthorized().into_response();
816 }
817 let mut map = state.resources.lock().await;
818 let deleted = map.remove(&id).is_some() || id == "res_db1";
819 Json(json!({
820 "operation": operation_json(json!({"deleted": deleted, "id": id}))
821 }))
822 .into_response()
823}
824
825async fn bind_resource(
826 headers: HeaderMap,
827 Path(id): Path<String>,
828 Json(body): Json<Value>,
829) -> impl IntoResponse {
830 if require_bearer(&headers).is_err() {
831 return unauthorized().into_response();
832 }
833 let env_id = body
834 .get("environmentId")
835 .and_then(|v| v.as_str())
836 .unwrap_or("env_prod");
837 Json(json!({
838 "operation": operation_json(json!({
839 "bound": true,
840 "resourceId": id,
841 "environmentId": env_id
842 }))
843 }))
844 .into_response()
845}
846
847
848
849
850
851async fn list_flags(
852 headers: HeaderMap,
853 State(state): State<AppState>,
854 Query(q): Query<ListQuery>,
855) -> impl IntoResponse {
856 if require_bearer(&headers).is_err() {
857 return unauthorized().into_response();
858 }
859 let _ = q.project_id;
860 let map = state.flags.lock().await;
861 let mut data: Vec<Value> = map.values().cloned().collect();
862 if data.is_empty() {
863 data.push(json!({"key": "checkout-v2", "enabled": false, "description": "new checkout", "projectId": "prj_demo"}));
864 }
865 Json(json!({"object": "list", "data": data})).into_response()
866}
867
868async fn create_flag(
869 headers: HeaderMap,
870 State(state): State<AppState>,
871 Json(body): Json<Value>,
872) -> impl IntoResponse {
873 if require_bearer(&headers).is_err() {
874 return unauthorized().into_response();
875 }
876 let key = body
877 .get("key")
878 .and_then(|v| v.as_str())
879 .unwrap_or("flag")
880 .to_string();
881 let flag = json!({
882 "key": key,
883 "enabled": body.get("enabled").and_then(|v| v.as_bool()).unwrap_or(false),
884 "description": body.get("description").cloned().unwrap_or(json!("")),
885 "projectId": body.get("projectId").cloned().unwrap_or(json!("prj_demo"))
886 });
887 state.flags.lock().await.insert(key, flag.clone());
888 Json(json!({"flag": flag})).into_response()
889}
890
891
892
893fn operation_json(result: Value) -> Value {
895 json!({
896 "name": "operations/mock-1",
897 "requestId": "mock-request",
898 "principal": "principals/projects/mock",
899 "target": "projects/mock/environments/prod/kv",
900 "mode": "OPERATION_MODE_APPLY",
901 "execution": "OPERATION_EXECUTION_CLASS_INLINE",
902 "state": "OPERATION_STATE_SUCCEEDED",
903 "phase": "succeeded",
904 "result": result,
905 "createTime": "2026-08-10T00:00:00Z",
906 "updateTime": "2026-08-10T00:00:00Z",
907 "endTime": "2026-08-10T00:00:01Z",
908 })
909}
910
911async fn kv_set(
914 headers: HeaderMap,
915 State(state): State<AppState>,
916 Json(body): Json<Value>,
917) -> impl IntoResponse {
918 if require_app_secret(&headers).is_err() {
919 return unauthorized().into_response();
920 }
921 let key = body
922 .get("key")
923 .and_then(|v| v.as_str())
924 .unwrap_or("")
925 .to_string();
926 let value = body.get("value").cloned().unwrap_or(Value::Null);
927 let ttl = body.get("ex").and_then(|v| v.as_f64());
928 let mut map = state.kv.lock().await;
929 let created = !map.contains_key(&key);
930 map.insert(key.clone(), (value, ttl));
931 Json(json!({"operation": operation_json(json!({ "key": key, "success": true, "created": created }))})).into_response()
932}
933
934async fn kv_get(
935 headers: HeaderMap,
936 State(state): State<AppState>,
937 Path(key): Path<String>,
938) -> impl IntoResponse {
939 if require_app_secret(&headers).is_err() {
940 return unauthorized().into_response();
941 }
942 let map = state.kv.lock().await;
943 match map.get(&key) {
944 Some((value, ttl)) => Json(json!({ "value": value, "ttl": ttl })).into_response(),
945 None => not_found("key not found").into_response(),
946 }
947}
948
949async fn kv_delete(
950 headers: HeaderMap,
951 State(state): State<AppState>,
952 Path(key): Path<String>,
953) -> impl IntoResponse {
954 if require_app_secret(&headers).is_err() {
955 return unauthorized().into_response();
956 }
957 let mut map = state.kv.lock().await;
958 let deleted = u32::from(map.remove(&key).is_some());
959 Json(json!({"operation": operation_json(json!({ "key": key, "deleted": deleted }))})).into_response()
960}
961
962async fn kv_incr(
963 headers: HeaderMap,
964 State(state): State<AppState>,
965 Json(body): Json<Value>,
966) -> impl IntoResponse {
967 if require_app_secret(&headers).is_err() {
968 return unauthorized().into_response();
969 }
970 let key = body
971 .get("key")
972 .and_then(|v| v.as_str())
973 .unwrap_or("")
974 .to_string();
975 if key.is_empty() {
976 return not_found("key required").into_response();
977 }
978 let by = body
979 .get("by")
980 .and_then(|v| v.as_i64())
981 .filter(|n| *n != 0)
982 .unwrap_or(1);
983 let mut map = state.kv.lock().await;
984 let current = map.get(&key).and_then(|(v, _)| v.as_i64()).unwrap_or(0);
985 let next = current + by;
986 map.insert(key.clone(), (json!(next), None));
987 Json(json!({"operation": operation_json(json!({ "key": key, "value": next }))})).into_response()
988}
989
990async fn kv_exists(
991 headers: HeaderMap,
992 State(state): State<AppState>,
993 Path(key): Path<String>,
994) -> impl IntoResponse {
995 if require_app_secret(&headers).is_err() {
996 return unauthorized().into_response();
997 }
998 let map = state.kv.lock().await;
999 Json(json!({ "exists": map.contains_key(&key) })).into_response()
1000}
1001
1002async fn kv_expire(
1003 headers: HeaderMap,
1004 State(state): State<AppState>,
1005 Json(body): Json<Value>,
1006) -> impl IntoResponse {
1007 if require_app_secret(&headers).is_err() {
1008 return unauthorized().into_response();
1009 }
1010 let key = body
1011 .get("key")
1012 .and_then(|v| v.as_str())
1013 .unwrap_or("")
1014 .to_string();
1015 let ex = body.get("ex").and_then(|v| v.as_f64());
1016 if key.is_empty() || ex.is_none() {
1017 return not_found("key and ex required").into_response();
1018 }
1019 let mut map = state.kv.lock().await;
1020 match map.get_mut(&key) {
1021 Some((_v, ttl)) => {
1022 *ttl = ex;
1023 Json(json!({"operation": operation_json(json!({ "key": key, "success": true }))})).into_response()
1024 }
1025 None => not_found("key not found").into_response(),
1026 }
1027}
1028
1029async fn email_send(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1032 if require_app_secret(&headers).is_err() {
1033 return unauthorized().into_response();
1034 }
1035 let to = body.get("to").and_then(|v| v.as_str()).unwrap_or("");
1036 if to.is_empty() {
1037 return not_found("to required").into_response();
1038 }
1039 Json(json!({
1040 "id": "eml_1",
1041 "status": "queued",
1042 "to": to,
1043 "subject": body.get("subject").and_then(|v| v.as_str()).unwrap_or(""),
1044 "fromEmail": body.get("fromEmail").and_then(|v| v.as_str()).unwrap_or(""),
1045 "html": body.get("html").and_then(|v| v.as_str()).unwrap_or(""),
1046 "text": body.get("text").and_then(|v| v.as_str()).unwrap_or(""),
1047 }))
1048 .into_response()
1049}
1050
1051async fn email_configured(headers: HeaderMap) -> impl IntoResponse {
1052 if require_app_secret(&headers).is_err() {
1053 return unauthorized().into_response();
1054 }
1055 Json(json!({ "configured": true, "ok": true })).into_response()
1056}
1057
1058async fn email_send_to_user(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1059 if require_app_secret(&headers).is_err() {
1060 return unauthorized().into_response();
1061 }
1062 let user_id = body.get("userId").and_then(|v| v.as_str()).unwrap_or("");
1063 if user_id.is_empty() {
1064 return not_found("userId required").into_response();
1065 }
1066 Json(json!({
1067 "id": "eml_user_1",
1068 "status": "queued",
1069 "userId": user_id,
1070 "subject": body.get("subject").and_then(|v| v.as_str()).unwrap_or(""),
1071 }))
1072 .into_response()
1073}
1074
1075#[derive(Deserialize)]
1076struct ObjectsListQuery {
1077 #[allow(dead_code)]
1078 bucket: Option<String>,
1079 prefix: Option<String>,
1080 limit: Option<u32>,
1081}
1082
1083async fn objects_list_buckets(headers: HeaderMap) -> impl IntoResponse {
1084 if require_app_secret(&headers).is_err() {
1085 return unauthorized().into_response();
1086 }
1087 Json(json!({
1088 "buckets": [{ "name": "demo", "id": "bkt_1" }],
1089 }))
1090 .into_response()
1091}
1092
1093async fn objects_create_bucket(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1094 if require_app_secret(&headers).is_err() {
1095 return unauthorized().into_response();
1096 }
1097 let name = body
1098 .get("name")
1099 .and_then(|v| v.as_str())
1100 .unwrap_or("demo");
1101 Json(json!({ "ok": true, "name": name })).into_response()
1102}
1103
1104async fn objects_list(
1105 headers: HeaderMap,
1106 State(state): State<AppState>,
1107 Query(q): Query<ObjectsListQuery>,
1108) -> impl IntoResponse {
1109 if require_app_secret(&headers).is_err() {
1110 return unauthorized().into_response();
1111 }
1112 let store = state.objects.lock().await;
1113 let prefix = q.prefix.unwrap_or_default();
1114 let mut entries: Vec<Value> = store
1115 .iter()
1116 .filter(|(key, _)| prefix.is_empty() || key.starts_with(&prefix))
1117 .map(|(key, bytes)| {
1118 json!({
1119 "key": key,
1120 "size_bytes": bytes.len(),
1121 })
1122 })
1123 .collect();
1124 entries.sort_by(|a, b| {
1125 a.get("key")
1126 .and_then(|v| v.as_str())
1127 .unwrap_or("")
1128 .cmp(b.get("key").and_then(|v| v.as_str()).unwrap_or(""))
1129 });
1130 if let Some(limit) = q.limit {
1131 entries.truncate(limit as usize);
1132 }
1133 let count = entries.len();
1134 Json(json!({
1135 "ok": true,
1136 "objects": entries,
1137 "data": entries,
1138 "count": count,
1139 "prefix": prefix,
1140 }))
1141 .into_response()
1142}
1143
1144async fn objects_put(
1145 headers: HeaderMap,
1146 State(state): State<AppState>,
1147 Path(key): Path<String>,
1148 Query(q): Query<ObjectsListQuery>,
1149 body: Bytes,
1150) -> impl IntoResponse {
1151 if require_app_secret(&headers).is_err() {
1152 return unauthorized().into_response();
1153 }
1154 let _ = q.bucket;
1155 let key = key.trim_start_matches('/').to_string();
1156 state.objects.lock().await.insert(key.clone(), body.to_vec());
1157 Json(json!({ "ok": true, "key": key })).into_response()
1158}
1159
1160async fn objects_get(
1161 headers: HeaderMap,
1162 State(state): State<AppState>,
1163 Path(key): Path<String>,
1164 Query(q): Query<ObjectsListQuery>,
1165) -> impl IntoResponse {
1166 if require_app_secret(&headers).is_err() {
1167 return unauthorized().into_response();
1168 }
1169 let _ = q.bucket;
1170 let key = key.trim_start_matches('/').to_string();
1171 match state.objects.lock().await.get(&key).cloned() {
1172 Some(bytes) => (StatusCode::OK, bytes).into_response(),
1173 None => not_found("object not found").into_response(),
1174 }
1175}
1176
1177async fn sandbox_get(headers: HeaderMap, Path(id): Path<String>) -> impl IntoResponse {
1178 if require_app_secret(&headers).is_err() {
1179 return unauthorized().into_response();
1180 }
1181 Json(json!({
1182 "id": id,
1183 "status": "running",
1184 "machineSize": "small",
1185 "endpoint": "https://exec.example.com/sbx",
1186 "token": "sbx_tok_1",
1187 }))
1188 .into_response()
1189}
1190
1191async fn sandbox_create(headers: HeaderMap, Json(_body): Json<Value>) -> impl IntoResponse {
1192 if require_app_secret(&headers).is_err() {
1193 return unauthorized().into_response();
1194 }
1195 Json(json!({
1196 "id": "sbx_1",
1197 "status": "running",
1198 "machineSize": "small",
1199 "endpoint": "https://exec.example.com/sbx",
1200 "token": "sbx_tok_1",
1201 }))
1202 .into_response()
1203}
1204
1205async fn flags_evaluate(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1206 if require_app_secret(&headers).is_err() {
1207 return unauthorized().into_response();
1208 }
1209 let mut keys: Vec<String> = Vec::new();
1211 if let Some(k) = body.get("key").and_then(|v| v.as_str()) {
1212 keys.push(k.to_string());
1213 }
1214 if let Some(arr) = body.get("keys").and_then(|v| v.as_array()) {
1215 for v in arr {
1216 if let Some(s) = v.as_str() {
1217 keys.push(s.to_string());
1218 }
1219 }
1220 }
1221 if keys.is_empty() {
1222 keys.push("flag".into());
1223 }
1224 let mut data = serde_json::Map::new();
1225 for key in &keys {
1226 data.insert(
1227 key.clone(),
1228 json!({
1229 "key": key,
1230 "enabled": true,
1231 "variant": "on",
1232 "reason": "rule_match",
1233 "payload": { "source": "wire-mock" },
1234 }),
1235 );
1236 }
1237 let first = keys[0].clone();
1239 Json(json!({
1240 "data": data,
1241 "key": first,
1242 "enabled": true,
1243 "variant": "on",
1244 "payload": { "source": "wire-mock" },
1245 }))
1246 .into_response()
1247}
1248
1249async fn search_index(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1250 if require_app_secret(&headers).is_err() {
1251 return unauthorized().into_response();
1252 }
1253 let id = body
1254 .get("id")
1255 .or_else(|| body.get("externalId"))
1256 .and_then(|v| v.as_str())
1257 .unwrap_or("doc_1");
1258 let collection = body
1259 .get("collection")
1260 .or_else(|| body.get("namespace"))
1261 .and_then(|v| v.as_str())
1262 .unwrap_or("default");
1263 Json(json!({
1264 "id": id,
1265 "collection": collection,
1266 "indexed": true,
1267 "success": true,
1268 }))
1269 .into_response()
1270}
1271
1272async fn search_query(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1273 if require_app_secret(&headers).is_err() {
1274 return unauthorized().into_response();
1275 }
1276 let q = body
1277 .get("q")
1278 .or_else(|| body.get("query"))
1279 .and_then(|v| v.as_str())
1280 .unwrap_or("");
1281 Json(json!({
1282 "hits": [{ "id": "doc_1", "score": 1.0, "document": { "title": "demo", "q": q } }],
1283 "results": [{ "id": "doc_1", "score": 1.0, "title": "demo" }],
1284 "found": 1,
1285 "page": 1,
1286 }))
1287 .into_response()
1288}
1289
1290async fn realtime_emit(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1291 if require_app_secret(&headers).is_err() {
1292 return unauthorized().into_response();
1293 }
1294 Json(json!({
1295 "ok": true,
1296 "channel": body.get("channel").and_then(|v| v.as_str()).unwrap_or("default"),
1297 "event": body.get("event").and_then(|v| v.as_str()).unwrap_or("message"),
1298 "id": "evt_1",
1299 }))
1300 .into_response()
1301}
1302
1303async fn auth_login(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1304 if require_app_secret(&headers).is_err() {
1305 return unauthorized().into_response();
1306 }
1307 let email = body.get("email").and_then(|v| v.as_str()).unwrap_or("");
1308 Json(json!({
1309 "accessToken": "at_demo",
1310 "refreshToken": "rt_demo",
1311 "user": { "id": "user_1", "email": email },
1312 "expiresIn": 3600,
1313 }))
1314 .into_response()
1315}
1316
1317async fn auth_me(headers: HeaderMap) -> impl IntoResponse {
1318 if require_app_secret(&headers).is_err() {
1319 return unauthorized().into_response();
1320 }
1321 Json(json!({
1322 "user": { "id": "user_1", "email": "demo@example.com" },
1323 "session": { "id": "sess_1", "active": true },
1324 }))
1325 .into_response()
1326}
1327
1328async fn webhooks_config(headers: HeaderMap) -> impl IntoResponse {
1329 if require_app_secret(&headers).is_err() {
1330 return unauthorized().into_response();
1331 }
1332 Json(json!({
1333 "url": "https://hooks.example.com/sylphx",
1334 "enabled": true,
1335 "events": ["deploy.succeeded", "user.created"],
1336 "secretSet": true,
1337 }))
1338 .into_response()
1339}
1340
1341async fn analytics_track(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1342 if require_app_secret(&headers).is_err() {
1343 return unauthorized().into_response();
1344 }
1345 Json(json!({
1346 "ok": true,
1347 "event": body.get("event").and_then(|v| v.as_str()).unwrap_or("unknown"),
1348 "received": true,
1349 }))
1350 .into_response()
1351}
1352
1353async fn notifications_send(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1354 if require_app_secret(&headers).is_err() {
1355 return unauthorized().into_response();
1356 }
1357 Json(json!({
1358 "id": "push_1",
1359 "status": "queued",
1360 "userId": body.get("userId").and_then(|v| v.as_str()).unwrap_or(""),
1361 "title": body.get("title").and_then(|v| v.as_str()).unwrap_or(""),
1362 }))
1363 .into_response()
1364}
1365
1366async fn consent_set(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1367 if require_app_secret(&headers).is_err() {
1368 return unauthorized().into_response();
1369 }
1370 Json(json!({
1371 "ok": true,
1372 "updated": true,
1373 "consents": body.get("consents").cloned().unwrap_or(json!([])),
1374 }))
1375 .into_response()
1376}
1377
1378async fn consent_get(headers: HeaderMap) -> impl IntoResponse {
1379 if require_app_secret(&headers).is_err() {
1380 return unauthorized().into_response();
1381 }
1382 Json(json!({
1383 "consents": [
1384 { "type": "necessary", "granted": true },
1385 { "type": "analytics", "granted": true },
1386 ],
1387 }))
1388 .into_response()
1389}
1390
1391async fn monitoring_exception(headers: HeaderMap, Json(body): Json<Value>) -> impl IntoResponse {
1392 if require_app_secret(&headers).is_err() {
1393 return unauthorized().into_response();
1394 }
1395 Json(json!({
1396 "id": "err_1",
1397 "eventId": "err_1",
1398 "message": body.get("message").and_then(|v| v.as_str()).unwrap_or(""),
1399 "level": "error",
1400 }))
1401 .into_response()
1402}
1403
1404async fn rate_limits_status(headers: HeaderMap) -> impl IntoResponse {
1405 if require_bearer_or_app(&headers).is_err() {
1406 return unauthorized().into_response();
1407 }
1408 Json(json!({
1409 "namespace": "default",
1410 "remaining": 100,
1411 "limit": 1000,
1412 "resetAt": "2099-01-01T00:00:00Z",
1413 }))
1414 .into_response()
1415}
1416
1417async fn referrals_code(headers: HeaderMap) -> impl IntoResponse {
1418 if require_app_secret(&headers).is_err() {
1419 return unauthorized().into_response();
1420 }
1421 Json(json!({
1422 "code": "FRIEND10",
1423 "url": "https://sylphx.com/r/FRIEND10",
1424 "redemptions": 3,
1425 }))
1426 .into_response()
1427}
1428
1429async fn sandbox_list(headers: HeaderMap) -> impl IntoResponse {
1430 if require_app_secret(&headers).is_err() {
1431 return unauthorized().into_response();
1432 }
1433 Json(json!({
1434 "sandboxes": [
1435 { "id": "sbx_1", "status": "running", "machineSize": "small" }
1436 ],
1437 }))
1438 .into_response()
1439}
1440
1441async fn billing_usage(headers: HeaderMap) -> impl IntoResponse {
1442 if require_app_secret(&headers).is_err() {
1443 return unauthorized().into_response();
1444 }
1445 Json(json!({
1446 "period": "2026-07",
1447 "usage": { "computeHours": 12.5, "storageGb": 3.2 },
1448 "currency": "USD",
1449 }))
1450 .into_response()
1451}
1452
1453async fn device_init(Json(body): Json<Value>) -> impl IntoResponse {
1454 let client_id = body
1455 .get("client_id")
1456 .or_else(|| body.get("clientId"))
1457 .and_then(|v| v.as_str())
1458 .unwrap_or("sylphx-cli");
1459 Json(json!({
1460 "device_code": "devcode_test_1",
1461 "user_code": "ABCD-EFGH",
1462 "verification_uri": "https://sylphx.com/device",
1463 "verification_uri_complete": format!("https://sylphx.com/device?user_code=ABCD-EFGH&client_id={client_id}"),
1464 "expires_in": 600,
1465 "interval": 1,
1466 }))
1467}
1468
1469async fn device_poll(
1470 Query(q): Query<std::collections::HashMap<String, String>>,
1471) -> impl IntoResponse {
1472 let code = q.get("device_code").cloned().unwrap_or_default();
1473 if code.is_empty() {
1474 return (
1475 StatusCode::BAD_REQUEST,
1476 Json(json!({"status": "error", "error": "missing device_code"})),
1477 )
1478 .into_response();
1479 }
1480 Json(json!({
1482 "status": "approved",
1483 "access_token": VALID_TOKEN,
1484 "token_type": "Bearer",
1485 "expires_in": 1,
1486 "refresh_token": "rt_test_1",
1487 }))
1488 .into_response()
1489}
1490
1491async fn oauth_authorization_server_metadata(headers: HeaderMap) -> impl IntoResponse {
1492 let host = headers
1493 .get(axum::http::header::HOST)
1494 .and_then(|value| value.to_str().ok())
1495 .unwrap_or("127.0.0.1");
1496 let issuer = format!("http://{host}");
1497 Json(json!({
1498 "issuer": issuer,
1499 "authorization_endpoint": format!("{issuer}/v1/oauth/authorize"),
1500 "token_endpoint": format!("{issuer}/v1/oauth/token"),
1501 "revocation_endpoint": format!("{issuer}/v1/oauth/revoke"),
1502 "device_authorization_endpoint": format!("{issuer}/v1/auth/device"),
1503 "grant_types_supported": [
1504 "authorization_code",
1505 "refresh_token",
1506 "urn:ietf:params:oauth:grant-type:device_code"
1507 ],
1508 "token_endpoint_auth_methods_supported": ["none"],
1509 }))
1510}
1511
1512async fn oauth_token(Json(body): Json<Value>) -> impl IntoResponse {
1513 let grant = body
1514 .get("grant_type")
1515 .and_then(Value::as_str)
1516 .unwrap_or_default();
1517 let refresh = body
1518 .get("refresh_token")
1519 .and_then(Value::as_str)
1520 .unwrap_or_default();
1521 if grant != "refresh_token" || !matches!(refresh, "rt_test_1" | "rt_test_2") {
1522 return (
1523 StatusCode::BAD_REQUEST,
1524 Json(json!({"error": "invalid_grant"})),
1525 )
1526 .into_response();
1527 }
1528 Json(json!({
1529 "access_token": VALID_TOKEN,
1530 "token_type": "Bearer",
1531 "expires_in": 3600,
1532 "refresh_token": "rt_test_2",
1533 "refresh_expires_at": "2099-01-01T00:00:00Z",
1534 "scope": "openid profile email offline_access",
1535 }))
1536 .into_response()
1537}
1538
1539async fn oauth_revoke(Json(body): Json<Value>) -> impl IntoResponse {
1540 if body
1541 .get("token")
1542 .and_then(Value::as_str)
1543 .is_none_or(str::is_empty)
1544 {
1545 return (
1546 StatusCode::BAD_REQUEST,
1547 Json(json!({"error": "invalid_request"})),
1548 )
1549 .into_response();
1550 }
1551 Json(json!({"revoked": true})).into_response()
1552}