smooai-smooth-operator-server 1.2.0

Reference WebSocket service for smooth-operator — speaks the schema-driven protocol over a smooth-operator KnowledgeChatRuntime.
Documentation
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Integration tests for the admin **write** API (Phase 12, increment 3).
//!
//! Connector-config CRUD, settings, and the trigger-an-indexing-run endpoint.
//! Drives the real axum router in-process via `tower::ServiceExt::oneshot` — no
//! live gateway or network. Auth runs through the **real** [`JwtVerifier`] with
//! HS256 tokens signed in-test, so the RBAC gates and org-scoping are exercised
//! end to end.
//!
//! The `/index` endpoint is exercised **offline** two ways:
//!   1. a `web`/`file`-kind connector pointed at a local temp file (no network),
//!      which runs a real `IndexingService::run_once` and lands a run in the
//!      `IndexingStore`; and
//!   2. a `github`-kind connector with an **unresolvable `auth_ref`**, which must
//!      return a clean 400 *before* any GitHub call (no panic, no network).

use std::sync::Arc;

use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use serde_json::{json, Value};
use tower::ServiceExt;

use smooth_operator::auth::JwtVerifier;
use smooth_operator_server::config::ServerConfig;
use smooth_operator_server::{build_state, router};

const SECRET: &[u8] = b"admin-write-test-secret";
const ORG: &str = "org-acme";
const OTHER_ORG: &str = "org-other";

fn test_config() -> ServerConfig {
    ServerConfig {
        bind: "127.0.0.1".into(),
        port: 0,
        gateway_url: "https://example.test/v1".into(),
        gateway_key: None,
        model: "m".into(),
        seed_kb: false,
        max_iterations: 4,
        max_tokens: 128,
        storage: smooth_operator_server::config::StorageBackend::Memory,
        widget_auth_strict: false,
    }
}

/// App with the real HS256 JwtVerifier (default in-memory stores).
fn app() -> axum::Router {
    let state =
        build_state(test_config()).with_auth(Arc::new(JwtVerifier::hs256(SECRET, None, None)));
    router(state)
}

/// Sign an HS256 token for `(user, role)` in `org`.
fn token_in(org: &str, user: &str, role: &str) -> String {
    let exp = (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp();
    let claims = json!({ "sub": user, "org": org, "role": role, "exp": exp });
    encode(
        &Header::new(Algorithm::HS256),
        &claims,
        &EncodingKey::from_secret(SECRET),
    )
    .expect("sign")
}

fn token(user: &str, role: &str) -> String {
    token_in(ORG, user, role)
}

/// Issue an HTTP request with method/path/optional-bearer/optional-json-body.
async fn req(
    app: &axum::Router,
    method: &str,
    path: &str,
    bearer: Option<&str>,
    body: Option<Value>,
) -> (StatusCode, Value) {
    let mut b = Request::builder().method(method).uri(path);
    if let Some(t) = bearer {
        b = b.header("Authorization", format!("Bearer {t}"));
    }
    let request = if let Some(json) = body {
        b.header("Content-Type", "application/json")
            .body(Body::from(serde_json::to_vec(&json).unwrap()))
            .unwrap()
    } else {
        b.body(Body::empty()).unwrap()
    };
    let resp = app.clone().oneshot(request).await.expect("oneshot");
    let status = resp.status();
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let value: Value = if bytes.is_empty() {
        Value::Null
    } else {
        serde_json::from_slice(&bytes).unwrap_or(Value::Null)
    };
    (status, value)
}

// ---------------------------------------------------------------------------
// Connector CRUD + RBAC
// ---------------------------------------------------------------------------

#[tokio::test]
async fn admin_creates_connector_then_it_is_listed() {
    let app = app();
    let create = json!({
        "name": "Docs repo",
        "kind": "web",
        "config": { "url": "https://example.test/page" },
        "enabled": true
    });
    let (status, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("a", "admin")),
        Some(create),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "create: {body:?}");
    let id = body["connector"]["id"].as_str().expect("id").to_string();
    assert_eq!(body["connector"]["name"], "Docs repo");
    assert_eq!(body["connector"]["kind"], "web");

    // Curator can list and sees it (org-scoped).
    let (status, body) = req(
        &app,
        "GET",
        "/admin/connectors",
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let conns = body["connectors"].as_array().expect("array");
    assert_eq!(conns.len(), 1);
    assert_eq!(conns[0]["id"], id);

    // GET by id (Curator).
    let (status, body) = req(
        &app,
        "GET",
        &format!("/admin/connectors/{id}"),
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["connector"]["id"], id);
}

#[tokio::test]
async fn basic_is_forbidden_to_create_update_delete() {
    let app = app();
    let create = json!({ "name": "x", "kind": "web", "config": { "url": "https://e.test" } });

    let (status, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("u", "basic")),
        Some(create.clone()),
    )
    .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
    assert_eq!(body["error"]["code"], "FORBIDDEN");

    let (status, _) = req(
        &app,
        "PUT",
        "/admin/connectors/whatever",
        Some(&token("u", "basic")),
        Some(create),
    )
    .await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    let (status, _) = req(
        &app,
        "DELETE",
        "/admin/connectors/whatever",
        Some(&token("u", "basic")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn curator_can_list_but_not_create() {
    let app = app();
    // Curator CAN list (read).
    let (status, _) = req(
        &app,
        "GET",
        "/admin/connectors",
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    // Curator CANNOT create (Admin-only write).
    let create = json!({ "name": "x", "kind": "web", "config": { "url": "https://e.test" } });
    let (status, _) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("c", "curator")),
        Some(create),
    )
    .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn cross_org_get_and_delete_are_404() {
    let app = app();
    // Admin in ORG creates a connector.
    let create = json!({ "name": "x", "kind": "web", "config": { "url": "https://e.test" } });
    let (status, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("a", "admin")),
        Some(create),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let id = body["connector"]["id"].as_str().unwrap().to_string();

    // Admin in OTHER_ORG cannot see it (404, not 403 — don't leak existence).
    let other = token_in(OTHER_ORG, "a2", "admin");
    let (status, b) = req(
        &app,
        "GET",
        &format!("/admin/connectors/{id}"),
        Some(&other),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND, "{b:?}");

    // Cross-org delete is also a 404.
    let (status, _) = req(
        &app,
        "DELETE",
        &format!("/admin/connectors/{id}"),
        Some(&other),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);

    // The original org still has it.
    let (status, body) = req(
        &app,
        "GET",
        "/admin/connectors",
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["connectors"].as_array().unwrap().len(), 1);
}

#[tokio::test]
async fn put_updates_and_delete_removes() {
    let app = app();
    let create = json!({ "name": "before", "kind": "web", "config": { "url": "https://e.test" }, "enabled": true });
    let (_, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("a", "admin")),
        Some(create),
    )
    .await;
    let id = body["connector"]["id"].as_str().unwrap().to_string();

    // PUT updates name + enabled.
    let update = json!({ "name": "after", "kind": "web", "config": { "url": "https://e2.test" }, "enabled": false });
    let (status, body) = req(
        &app,
        "PUT",
        &format!("/admin/connectors/{id}"),
        Some(&token("a", "admin")),
        Some(update),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "{body:?}");
    assert_eq!(body["connector"]["name"], "after");
    assert_eq!(body["connector"]["enabled"], false);
    assert_eq!(body["connector"]["id"], id, "id preserved across update");

    // GET reflects it.
    let (_, body) = req(
        &app,
        "GET",
        &format!("/admin/connectors/{id}"),
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(body["connector"]["name"], "after");

    // DELETE removes it.
    let (status, _) = req(
        &app,
        "DELETE",
        &format!("/admin/connectors/{id}"),
        Some(&token("a", "admin")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::NO_CONTENT);

    let (status, _) = req(
        &app,
        "GET",
        &format!("/admin/connectors/{id}"),
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);

    // A second delete 404s.
    let (status, _) = req(
        &app,
        "DELETE",
        &format!("/admin/connectors/{id}"),
        Some(&token("a", "admin")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn unknown_kind_is_rejected_with_400() {
    let app = app();
    let create = json!({ "name": "x", "kind": "slack", "config": {} });
    let (status, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("a", "admin")),
        Some(create),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["error"]["code"], "VALIDATION_ERROR");
    assert!(
        body["error"]["message"].as_str().unwrap().contains("slack"),
        "message names the bad kind: {body:?}"
    );
}

#[tokio::test]
async fn malformed_config_is_rejected_with_400() {
    let app = app();
    // web kind requires a `url`.
    let create = json!({ "name": "x", "kind": "web", "config": { "not_url": "y" } });
    let (status, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("a", "admin")),
        Some(create),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body:?}");
    assert_eq!(body["error"]["code"], "VALIDATION_ERROR");
}

// ---------------------------------------------------------------------------
// No-secret-leak
// ---------------------------------------------------------------------------

#[tokio::test]
async fn auth_ref_is_stored_but_token_never_returned() {
    let app = app();
    // Create a github connector carrying an auth_ref (a NAME, not a token).
    let create = json!({
        "name": "private repo",
        "kind": "github",
        "config": { "owner": "smooai", "repo": "secret", "auth_ref": "GITHUB_TOKEN", "visibility": "private" },
        "enabled": true
    });
    let (status, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("a", "admin")),
        Some(create),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let id = body["connector"]["id"].as_str().unwrap().to_string();

    // The create response echoes the auth_ref NAME but never a token value.
    let create_text = serde_json::to_string(&body).unwrap();
    assert!(
        create_text.contains("GITHUB_TOKEN"),
        "auth_ref name is fine to echo"
    );
    assert!(
        !create_text.to_lowercase().contains("ghp_"),
        "no PAT in response"
    );

    // GET by id + list: never any token material, only the ref name.
    for path in [
        format!("/admin/connectors/{id}"),
        "/admin/connectors".to_string(),
    ] {
        let (_, body) = req(&app, "GET", &path, Some(&token("c", "curator")), None).await;
        let text = serde_json::to_string(&body).unwrap();
        assert!(
            !text.to_lowercase().contains("ghp_"),
            "no token leaked in {path}: {text}"
        );
    }
}

// ---------------------------------------------------------------------------
// Trigger an indexing run
// ---------------------------------------------------------------------------

#[tokio::test]
async fn index_runs_offline_connector_and_appears_in_runs() {
    // A temp file the `file` connector ingests with no network.
    let dir = std::env::temp_dir().join(format!("smooth-index-{}", uuid::Uuid::new_v4()));
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("note.md");
    std::fs::write(
        &file,
        "SmooAI offline indexing smoke document. Returns are accepted within 17 days.",
    )
    .unwrap();

    let app = app();
    let create = json!({
        "name": "local docs",
        "kind": "file",
        "config": { "path": file.to_string_lossy() },
        "enabled": true
    });
    let (status, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("a", "admin")),
        Some(create),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let id = body["connector"]["id"].as_str().unwrap().to_string();

    // Curator triggers an index run.
    let (status, body) = req(
        &app,
        "POST",
        &format!("/admin/connectors/{id}/index"),
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK, "index: {body:?}");
    assert_eq!(body["run"]["status"], "succeeded", "{body:?}");
    assert_eq!(body["run"]["connectorName"], "local docs");
    assert!(body["run"]["documentsSeen"].as_u64().unwrap() >= 1);
    assert!(body["run"]["chunksIndexed"].as_u64().unwrap() >= 1);

    // The run now appears in GET /admin/indexing/runs (reuses the IndexingStore).
    let (status, body) = req(
        &app,
        "GET",
        "/admin/indexing/runs",
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let runs = body["runs"].as_array().expect("runs");
    assert!(
        runs.iter()
            .any(|r| r["connectorName"] == "local docs" && r["status"] == "succeeded"),
        "the triggered run is listed: {body:?}"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn index_github_without_token_is_clean_400_no_network() {
    let app = app();
    // github connector with an auth_ref pointing at an UNSET env var.
    let unset = format!("SMOOTH_TEST_MISSING_{}", uuid::Uuid::new_v4().simple());
    let create = json!({
        "name": "needs token",
        "kind": "github",
        "config": { "owner": "smooai", "repo": "private", "auth_ref": unset, "visibility": "private" },
        "enabled": true
    });
    let (_, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("a", "admin")),
        Some(create),
    )
    .await;
    let id = body["connector"]["id"].as_str().unwrap().to_string();

    // Triggering index must 400 cleanly (token unresolvable) — no panic, no GitHub call.
    let (status, body) = req(
        &app,
        "POST",
        &format!("/admin/connectors/{id}/index"),
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body:?}");
    assert_eq!(body["error"]["code"], "VALIDATION_ERROR");
    let msg = body["error"]["message"].as_str().unwrap();
    assert!(
        msg.contains("auth_ref") || msg.to_lowercase().contains("token"),
        "explains the missing secret: {msg}"
    );
}

#[tokio::test]
async fn index_requires_curator() {
    let app = app();
    let create = json!({ "name": "x", "kind": "web", "config": { "url": "https://e.test" } });
    let (_, body) = req(
        &app,
        "POST",
        "/admin/connectors",
        Some(&token("a", "admin")),
        Some(create),
    )
    .await;
    let id = body["connector"]["id"].as_str().unwrap().to_string();

    // Basic is forbidden from triggering an index.
    let (status, _) = req(
        &app,
        "POST",
        &format!("/admin/connectors/{id}/index"),
        Some(&token("u", "basic")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn index_unknown_connector_is_404() {
    let app = app();
    let (status, _) = req(
        &app,
        "POST",
        "/admin/connectors/missing/index",
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ---------------------------------------------------------------------------
// Settings
// ---------------------------------------------------------------------------

#[tokio::test]
async fn settings_get_returns_defaults_then_put_reflects() {
    let app = app();
    // Default GET (Curator can read).
    let (status, body) = req(
        &app,
        "GET",
        "/admin/settings",
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK, "{body:?}");
    assert_eq!(body["settings"]["orgId"], ORG);
    assert!(body["settings"]["model"].as_str().is_some());

    // Admin PUTs new settings.
    let update = json!({
        "model": "claude-test",
        "systemPrompt": "be terse",
        "defaultTools": ["knowledge_search"]
    });
    let (status, body) = req(
        &app,
        "PUT",
        "/admin/settings",
        Some(&token("a", "admin")),
        Some(update),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "{body:?}");
    assert_eq!(body["settings"]["model"], "claude-test");

    // GET reflects the change.
    let (_, body) = req(
        &app,
        "GET",
        "/admin/settings",
        Some(&token("c", "curator")),
        None,
    )
    .await;
    assert_eq!(body["settings"]["model"], "claude-test");
    assert_eq!(body["settings"]["systemPrompt"], "be terse");
    assert_eq!(body["settings"]["defaultTools"][0], "knowledge_search");
}

#[tokio::test]
async fn settings_put_requires_admin() {
    let app = app();
    let update = json!({ "model": "x", "systemPrompt": "y", "defaultTools": [] });
    // Basic is forbidden.
    let (status, _) = req(
        &app,
        "PUT",
        "/admin/settings",
        Some(&token("u", "basic")),
        Some(update.clone()),
    )
    .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
    // Curator is also forbidden (write is Admin-only).
    let (status, _) = req(
        &app,
        "PUT",
        "/admin/settings",
        Some(&token("c", "curator")),
        Some(update),
    )
    .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn settings_put_is_org_scoped() {
    let app = app();
    // Admin in ORG sets a model.
    let update = json!({ "model": "org-acme-model", "systemPrompt": "p", "defaultTools": [] });
    let (status, _) = req(
        &app,
        "PUT",
        "/admin/settings",
        Some(&token("a", "admin")),
        Some(update),
    )
    .await;
    assert_eq!(status, StatusCode::OK);

    // Admin in OTHER_ORG still sees defaults (not ORG's value).
    let (_, body) = req(
        &app,
        "GET",
        "/admin/settings",
        Some(&token_in(OTHER_ORG, "a2", "admin")),
        None,
    )
    .await;
    assert_ne!(body["settings"]["model"], "org-acme-model");
    assert_eq!(body["settings"]["orgId"], OTHER_ORG);
}