1use std::collections::BTreeMap;
8
9pub use ai6::wire::pools::{AddStation, BoardClaim, BoardLoginRequest};
10use ai6::{AccountRef, AccountState, AuditRecord};
11use ai6_diptel::OperationId;
12use axum::Json;
13use axum::extract::{Path, State};
14use axum::http::{HeaderMap, StatusCode};
15use serde::Serialize;
16use uuid::Uuid;
17
18use crate::{
19 ApiError, Gateway, GatewayError, authorize_operation_action, authorize_resource_action, bearer,
20 resolve_user, unix_timestamp,
21};
22
23#[non_exhaustive]
25#[derive(Debug, Clone, PartialEq, Serialize)]
26pub struct BoardWindow {
27 pub name: String,
29 pub used_permille: Option<u16>,
31 pub resets_at: Option<f64>,
33 pub status: Option<String>,
35 pub models: Vec<String>,
37 pub observed_at: f64,
39}
40
41#[non_exhaustive]
43#[derive(Debug, Clone, PartialEq, Serialize)]
44pub struct BoardUsageRead {
45 pub requested_at: f64,
47 pub answered_at: Option<f64>,
49 pub result: Option<String>,
51}
52
53#[non_exhaustive]
55#[derive(Debug, Clone, PartialEq, Serialize)]
56pub struct BoardLogin {
57 pub stations: Vec<String>,
59 pub expires_at: Option<f64>,
61 pub renewed_at: Option<f64>,
63 pub renewal_held_by: Option<String>,
65 pub renewal_held_until: Option<f64>,
67 pub last_result: Option<String>,
69 pub last_attempt_at: Option<f64>,
71 pub failures: u32,
73 pub needs_person: Option<String>,
75 pub needs_person_command: Option<String>,
77 pub requests: Vec<BoardLoginRequest>,
79}
80
81fn board_login(
83 login: Option<&ai6::LoginState>,
84 sealed: bool,
85 account: &AccountRef,
86 handler: &str,
87 now: f64,
88) -> Option<BoardLogin> {
89 let fix = || ai6::directorates::q::login_standing::add_login_command(account, handler);
90 let Some(login) = login else {
91 return sealed.then(|| BoardLogin {
92 stations: Vec::new(),
93 expires_at: None,
94 renewed_at: None,
95 renewal_held_by: None,
96 renewal_held_until: None,
97 last_result: None,
98 last_attempt_at: None,
99 failures: 0,
100 needs_person: Some("no login is kept for this account".to_owned()),
101 needs_person_command: Some(fix()),
102 requests: Vec::new(),
103 });
104 };
105 let lease = login.leased_at(now);
106 Some(BoardLogin {
107 stations: login.stations.clone(),
108 expires_at: login.expires_at,
109 renewed_at: login.renewed_at,
110 renewal_held_by: lease.map(|lease| lease.station.clone()),
111 renewal_held_until: lease.map(|lease| lease.until),
112 last_result: login.last_result.clone(),
113 last_attempt_at: login.last_attempt_at,
114 failures: login.failures,
115 needs_person: login.needs_person.clone(),
116 needs_person_command: login.needs_person.is_some().then(fix),
117 requests: login
118 .requests
119 .iter()
120 .map(|asked| {
121 let (action, station) = match &asked.action {
122 ai6::LoginRequestAction::AddStation { station } => {
123 ("add_station", Some(station.clone()))
124 }
125 ai6::LoginRequestAction::RemoveStation { station } => {
126 ("remove_station", Some(station.clone()))
127 }
128 ai6::LoginRequestAction::SignOutAndForget => ("sign_out_and_forget", None),
129 _ => ("change", None),
130 };
131 BoardLoginRequest {
132 action: action.to_owned(),
133 station,
134 by: asked.by.clone(),
135 at: asked.at,
136 }
137 })
138 .collect(),
139 })
140}
141
142#[non_exhaustive]
144#[derive(Debug, Clone, PartialEq, Serialize)]
145pub struct BoardAccount {
146 pub pool: String,
148 pub account: String,
150 pub handler: String,
152 pub kind: String,
154 pub priority: i64,
156 pub max_concurrent: Option<usize>,
158 pub labels: BTreeMap<String, String>,
160 pub active: Vec<BoardClaim>,
162 pub other_runs: usize,
164 pub windows: Vec<BoardWindow>,
166 pub limited_until: Option<f64>,
168 pub last_used: Option<f64>,
170 pub tokens_today: u64,
172 pub login: Option<BoardLogin>,
174 pub usage_read: Option<BoardUsageRead>,
176}
177
178#[non_exhaustive]
180#[derive(Debug, Clone, PartialEq, Serialize)]
181pub struct PoolBoard {
182 pub operation_id: String,
184 pub accounts: Vec<BoardAccount>,
186}
187
188fn board_account(state: AccountState, operation: &str, now: f64) -> Option<BoardAccount> {
190 let profile = state.profile()?;
191 if !profile.operations.iter().any(|id| id == operation) {
192 return None;
193 }
194 Some(entry(state, Some(profile), Some(operation), now))
195}
196
197fn assistant_account(state: AccountState, now: f64) -> Option<BoardAccount> {
201 let profile = state.profile();
202 if profile.as_ref().is_some_and(|p| !p.operations.is_empty()) {
203 return None;
204 }
205 let limited = state.limited_until.is_some_and(|until| until > now);
206 if !limited && state.windows.is_empty() {
207 return None;
208 }
209 Some(entry(state, profile, None, now))
210}
211
212fn entry(
214 state: AccountState,
215 profile: Option<ai6::AccountProfile>,
216 operation: Option<&str>,
217 now: f64,
218) -> BoardAccount {
219 let sealed = profile.as_ref().is_some_and(|p| p.sealed_login);
220 let (handler, kind) = profile
221 .as_ref()
222 .map_or_else(Default::default, |p| (p.handler.clone(), p.kind.clone()));
223 let (own, others): (Vec<_>, Vec<_>) = state
224 .live_claims(now)
225 .partition(|claim| claim.operation.as_deref() == operation);
226 let login = board_login(state.login.as_ref(), sealed, &state.account, &handler, now);
227 BoardAccount {
228 login,
229 usage_read: state.usage_request.as_ref().map(|ask| BoardUsageRead {
230 requested_at: ask.at,
231 answered_at: ask.done_at,
232 result: ask.result.clone(),
233 }),
234 tokens_today: state.tokens_on_day(now as i64),
235 active: own
236 .into_iter()
237 .map(|claim| BoardClaim {
238 station_id: claim.station.clone(),
239 mission_id: claim.mission.clone(),
240 since: claim.since,
241 })
242 .collect(),
243 other_runs: others.len(),
244 windows: state
245 .windows
246 .iter()
247 .map(|window| BoardWindow {
248 name: window.name.clone(),
249 used_permille: window.used_permille,
250 resets_at: window.resets_at,
251 status: window.status.clone(),
252 models: window.models.clone(),
253 observed_at: window.observed_at,
254 })
255 .collect(),
256 limited_until: state.limited_until.filter(|until| *until > now),
257 last_used: state.last_used,
258 pool: state.account.pool,
259 account: state.account.account,
260 handler,
261 kind,
262 priority: profile.as_ref().map_or(0, |p| p.priority),
263 max_concurrent: profile.as_ref().and_then(|p| p.max_concurrent),
264 labels: profile.map(|p| p.labels).unwrap_or_default(),
265 }
266}
267
268const ASSISTANT_RESOURCE: &str = "config:assistant";
270
271pub(crate) async fn assistant_pools(
274 State(gateway): State<Gateway>,
275 headers: HeaderMap,
276) -> Result<Json<PoolBoard>, ApiError> {
277 let person = resolve_user(&gateway, bearer(&headers)?).await?;
278 authorize_resource_action(
279 &gateway,
280 person,
281 ASSISTANT_RESOURCE.to_owned(),
282 "config.read",
283 )
284 .await?;
285 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
286 let now = unix_timestamp()?;
287 let states = tokio::task::spawn_blocking(move || registry.accounts())
288 .await
289 .map_err(|_| ApiError::internal())?
290 .map_err(|_| ApiError::internal())?;
291 Ok(Json(PoolBoard {
292 accounts: states
293 .into_iter()
294 .filter_map(|state| assistant_account(state, now))
295 .collect(),
296 operation_id: String::new(),
297 }))
298}
299
300pub(crate) async fn clear_assistant_limit(
304 State(gateway): State<Gateway>,
305 headers: HeaderMap,
306 Path((pool, account)): Path<(String, String)>,
307) -> Result<StatusCode, ApiError> {
308 let person = resolve_user(&gateway, bearer(&headers)?).await?;
309 let account = AccountRef::new(pool, account);
310 authorize_resource_action(
311 &gateway,
312 person.clone(),
313 ASSISTANT_RESOURCE.to_owned(),
314 "config.manage",
315 )
316 .await?;
317 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
318 let target = account.clone();
319 tokio::task::spawn_blocking(move || {
320 let belongs_to_none = registry
321 .accounts()
322 .map_err(|_| ApiError::internal())?
323 .into_iter()
324 .find(|state| state.account == target)
325 .is_some_and(|state| state.profile().is_none_or(|p| p.operations.is_empty()));
326 if !belongs_to_none {
327 return Err(ApiError::from(GatewayError::NotFound));
328 }
329 registry
330 .clear_account_limit(&target)
331 .map(|_| ())
332 .map_err(|_| ApiError::bad_request())
333 })
334 .await
335 .map_err(|_| ApiError::internal())??;
336 let audit = AuditRecord {
337 id: Uuid::new_v4().to_string(),
338 actor: crate::actor_of(&person),
339 action: "pool.limit.clear".to_owned(),
340 operation: String::new(),
341 resource: Some(ASSISTANT_RESOURCE.to_owned()),
342 target: account.to_string(),
343 at: unix_timestamp()?,
344 };
345 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
346 tokio::task::spawn_blocking(move || registry.record_audit(&audit))
347 .await
348 .map_err(|_| ApiError::internal())?
349 .map_err(|_| ApiError::internal())?;
350 Ok(StatusCode::NO_CONTENT)
351}
352
353pub(crate) async fn operation_pools(
355 State(gateway): State<Gateway>,
356 headers: HeaderMap,
357 Path(operation_id): Path<String>,
358) -> Result<Json<PoolBoard>, ApiError> {
359 let person = resolve_user(&gateway, bearer(&headers)?).await?;
360 let operation = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
361 authorize_operation_action(&gateway, person, &operation, "pool.read").await?;
362 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
363 let now = unix_timestamp()?;
364 let operation = operation.to_string();
365 let states = tokio::task::spawn_blocking(move || registry.accounts())
366 .await
367 .map_err(|_| ApiError::internal())?
368 .map_err(|_| ApiError::internal())?;
369 Ok(Json(PoolBoard {
370 accounts: states
371 .into_iter()
372 .filter_map(|state| board_account(state, &operation, now))
373 .collect(),
374 operation_id: operation,
375 }))
376}
377
378const USAGE_WAIT: std::time::Duration =
381 std::time::Duration::from_millis(if cfg!(test) { 1_500 } else { 20_000 });
382const USAGE_POLL: std::time::Duration = std::time::Duration::from_millis(200);
384
385pub(crate) async fn read_usage(
392 State(gateway): State<Gateway>,
393 headers: HeaderMap,
394 Path((operation_id, pool, account)): Path<(String, String, String)>,
395) -> Result<(StatusCode, Json<BoardAccount>), ApiError> {
396 let person = resolve_user(&gateway, bearer(&headers)?).await?;
397 let operation = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
398 let account = AccountRef::new(pool, account);
399 authorize_operation_action(&gateway, person.clone(), &operation, "pool.read").await?;
400 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
401 let (name, by, now) = (
402 operation.to_string(),
403 crate::actor_of(&person),
404 unix_timestamp()?,
405 );
406 let target = account.clone();
407 let asking = registry.clone();
408 let asked = tokio::task::spawn_blocking(move || {
409 let declared = asking
410 .accounts()
411 .map_err(|_| ApiError::internal())?
412 .into_iter()
413 .find(|state| state.account == target)
414 .and_then(|state| state.profile())
415 .is_some_and(|profile| profile.operations.contains(&name));
416 if !declared {
417 return Err(ApiError::from(GatewayError::NotFound));
418 }
419 ai6::directorates::q::usage_standing::request(asking.as_ref(), &target, &by, now)
420 .map_err(|_| ApiError::internal())
421 })
422 .await
423 .map_err(|_| ApiError::internal())??;
424 let deadline = std::time::Instant::now() + USAGE_WAIT;
425 loop {
426 let (looking, target) = (registry.clone(), account.clone());
427 let states = tokio::task::spawn_blocking(move || looking.accounts())
428 .await
429 .map_err(|_| ApiError::internal())?
430 .map_err(|_| ApiError::internal())?;
431 let state = states
432 .into_iter()
433 .find(|state| state.account == target)
434 .ok_or_else(|| ApiError::from(GatewayError::NotFound))?;
435 let answered = state
438 .usage_request
439 .as_ref()
440 .is_some_and(|ask| ask.at >= asked.at - 0.001 && !ask.waits());
441 if answered || std::time::Instant::now() >= deadline {
442 let status = if answered {
443 StatusCode::OK
444 } else {
445 StatusCode::ACCEPTED
446 };
447 let entry = board_account(state, &operation.to_string(), unix_timestamp()?)
448 .ok_or_else(|| ApiError::from(GatewayError::NotFound))?;
449 return Ok((status, Json(entry)));
450 }
451 tokio::time::sleep(USAGE_POLL).await;
452 }
453}
454
455pub(crate) async fn clear_limit(
459 State(gateway): State<Gateway>,
460 headers: HeaderMap,
461 Path((operation_id, pool, account)): Path<(String, String, String)>,
462) -> Result<StatusCode, ApiError> {
463 let person = resolve_user(&gateway, bearer(&headers)?).await?;
464 let operation = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
465 let account = AccountRef::new(pool, account);
466 authorize_operation_action(&gateway, person.clone(), &operation, "pool.manage").await?;
467 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
468 let operation_name = operation.to_string();
469 let target = account.clone();
470 tokio::task::spawn_blocking(move || {
471 let declared = registry
472 .accounts()
473 .map_err(|_| ApiError::internal())?
474 .into_iter()
475 .find(|state| state.account == target)
476 .and_then(|state| state.profile())
477 .is_some_and(|profile| profile.operations.contains(&operation_name));
478 if !declared {
479 return Err(ApiError::from(GatewayError::NotFound));
480 }
481 registry
482 .clear_account_limit(&target)
483 .map(|_| ())
484 .map_err(|_| ApiError::bad_request())
485 })
486 .await
487 .map_err(|_| ApiError::internal())??;
488 let audit = AuditRecord {
489 id: Uuid::new_v4().to_string(),
490 actor: crate::actor_of(&person),
491 action: "pool.limit.clear".to_owned(),
492 operation: operation.to_string(),
493 resource: None,
494 target: account.to_string(),
495 at: unix_timestamp()?,
496 };
497 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
498 tokio::task::spawn_blocking(move || registry.record_audit(&audit))
499 .await
500 .map_err(|_| ApiError::internal())?
501 .map_err(|_| ApiError::internal())?;
502 Ok(StatusCode::NO_CONTENT)
503}
504
505async fn manageable(
507 gateway: &Gateway,
508 headers: &HeaderMap,
509 operation_id: String,
510 pool: String,
511 account: String,
512) -> Result<(ai6::Person, OperationId, AccountRef), ApiError> {
513 let person = resolve_user(gateway, bearer(headers)?).await?;
514 let operation = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
515 let account = AccountRef::new(pool, account);
516 authorize_operation_action(gateway, person.clone(), &operation, "pool.manage").await?;
517 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
518 let (name, target) = (operation.to_string(), account.clone());
519 let declared = tokio::task::spawn_blocking(move || {
520 registry.accounts().map(|states| {
521 states
522 .into_iter()
523 .find(|state| state.account == target)
524 .and_then(|state| state.profile())
525 .is_some_and(|profile| profile.operations.contains(&name))
526 })
527 })
528 .await
529 .map_err(|_| ApiError::internal())?
530 .map_err(|_| ApiError::internal())?;
531 if !declared {
532 return Err(ApiError::from(GatewayError::NotFound));
533 }
534 Ok((person, operation, account))
535}
536
537async fn require_login(gateway: &Gateway, account: &AccountRef) -> Result<(), ApiError> {
539 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
540 let target = account.clone();
541 let held = tokio::task::spawn_blocking(move || {
542 ai6::directorates::q::login_standing::holds_login(registry.as_ref(), &target)
543 })
544 .await
545 .map_err(|_| ApiError::internal())?
546 .map_err(|_| ApiError::internal())?;
547 if held {
548 Ok(())
549 } else {
550 Err(ApiError::from(GatewayError::NotFound))
551 }
552}
553
554async fn audit_login_change(
556 gateway: &Gateway,
557 person: &ai6::Person,
558 operation: &OperationId,
559 action: &str,
560 target: String,
561) -> Result<(), ApiError> {
562 let audit = AuditRecord {
563 id: Uuid::new_v4().to_string(),
564 actor: crate::actor_of(person),
565 action: action.to_owned(),
566 operation: operation.to_string(),
567 resource: None,
568 target,
569 at: unix_timestamp()?,
570 };
571 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
572 tokio::task::spawn_blocking(move || registry.record_audit(&audit))
573 .await
574 .map_err(|_| ApiError::internal())?
575 .map_err(|_| ApiError::internal())
576}
577
578async fn queue_login_change(
580 gateway: &Gateway,
581 person: &ai6::Person,
582 account: AccountRef,
583 action: ai6::LoginRequestAction,
584) -> Result<StatusCode, ApiError> {
585 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
586 let (by, now) = (crate::actor_of(person), unix_timestamp()?);
587 tokio::task::spawn_blocking(move || {
588 ai6::directorates::q::login_standing::request(registry.as_ref(), &account, action, &by, now)
589 })
590 .await
591 .map_err(|_| ApiError::internal())?
592 .map_err(|_| ApiError::internal())?
593 .then_some(StatusCode::ACCEPTED)
594 .ok_or_else(|| ApiError::from(GatewayError::NotFound))
595}
596
597fn station_name(station: String) -> Result<String, ApiError> {
599 if station.is_empty() || station.contains(char::is_control) {
600 return Err(ApiError::bad_request());
601 }
602 Ok(station)
603}
604
605pub(crate) async fn add_login_station(
610 State(gateway): State<Gateway>,
611 headers: HeaderMap,
612 Path((operation_id, pool, account)): Path<(String, String, String)>,
613 Json(body): Json<AddStation>,
614) -> Result<StatusCode, ApiError> {
615 let station = station_name(body.station)?;
616 let (person, operation, account) =
617 manageable(&gateway, &headers, operation_id, pool, account).await?;
618 require_login(&gateway, &account).await?;
619 audit_login_change(
620 &gateway,
621 &person,
622 &operation,
623 "pool.login.station.add",
624 format!("{account} {station}"),
625 )
626 .await?;
627 queue_login_change(
628 &gateway,
629 &person,
630 account,
631 ai6::LoginRequestAction::AddStation { station },
632 )
633 .await
634}
635
636pub(crate) async fn remove_login_station(
640 State(gateway): State<Gateway>,
641 headers: HeaderMap,
642 Path((operation_id, pool, account, station)): Path<(String, String, String, String)>,
643) -> Result<StatusCode, ApiError> {
644 let station = station_name(station)?;
645 let (person, operation, account) =
646 manageable(&gateway, &headers, operation_id, pool, account).await?;
647 require_login(&gateway, &account).await?;
648 audit_login_change(
649 &gateway,
650 &person,
651 &operation,
652 "pool.login.station.remove",
653 format!("{account} {station}"),
654 )
655 .await?;
656 queue_login_change(
657 &gateway,
658 &person,
659 account,
660 ai6::LoginRequestAction::RemoveStation { station },
661 )
662 .await
663}
664
665#[derive(serde::Deserialize)]
667#[serde(deny_unknown_fields)]
668pub(crate) struct ForgetLogin {
669 #[serde(default)]
670 sign_out: bool,
671}
672
673pub(crate) async fn forget_login(
679 State(gateway): State<Gateway>,
680 headers: HeaderMap,
681 Path((operation_id, pool, account)): Path<(String, String, String)>,
682 axum::extract::Query(query): axum::extract::Query<ForgetLogin>,
683) -> Result<StatusCode, ApiError> {
684 let (person, operation, account) =
685 manageable(&gateway, &headers, operation_id, pool, account).await?;
686 require_login(&gateway, &account).await?;
687 if query.sign_out {
688 audit_login_change(
689 &gateway,
690 &person,
691 &operation,
692 "pool.login.sign_out",
693 account.to_string(),
694 )
695 .await?;
696 return queue_login_change(
697 &gateway,
698 &person,
699 account,
700 ai6::LoginRequestAction::SignOutAndForget,
701 )
702 .await;
703 }
704 audit_login_change(
705 &gateway,
706 &person,
707 &operation,
708 "pool.login.forget",
709 account.to_string(),
710 )
711 .await?;
712 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
713 tokio::task::spawn_blocking(move || {
714 ai6::directorates::q::login_standing::forget(registry.as_ref(), &account)
715 })
716 .await
717 .map_err(|_| ApiError::internal())?
718 .map_err(|_| ApiError::internal())?
719 .then_some(StatusCode::NO_CONTENT)
720 .ok_or_else(|| ApiError::from(GatewayError::NotFound))
721}
722
723#[cfg(test)]
724mod tests {
725 use std::time::Duration;
726
727 use ai6::directorates::registry::backend::*;
728 use ai6::{
729 Account, AccountClaimRequest, AccountKind, AccountPool, AccountProfile, AccountRef,
730 QuotaWindow,
731 };
732 use axum::http::StatusCode;
733
734 use crate::controls::tests::{Served, served_with};
735
736 const ROLES: &str = r#"
737 [role.pools]
738 actions = ["pool.read"]
739
740 [[rule]]
741 subject = "person:viewer-007"
742 scope = "operation:G"
743 role = "pools"
744
745 [role.pool-managers]
746 actions = ["pool.read", "pool.manage"]
747
748 [[rule]]
749 subject = "person:operator-007"
750 scope = "operation:G"
751 role = "pool-managers"
752 "#;
753
754 fn declare(served: &Served) -> AccountPool {
756 let pool = AccountPool::new("team", "claude")
757 .account(
758 Account::new("alpha", AccountKind::ClaudeOauthToken)
759 .secret("SECRET-NAME")
760 .max_concurrent(2),
761 )
762 .account(Account::new("beta", AccountKind::ConfigDir).dir("/SECRET-DIR"));
763 for (name, operations) in [("alpha", vec!["G"]), ("beta", vec!["L"])] {
764 served
765 .registry
766 .declare_account(
767 &AccountRef::new("team", name),
768 "worker",
769 &AccountProfile::of(
770 &pool,
771 name,
772 operations.into_iter().map(Into::into).collect(),
773 )
774 .unwrap(),
775 )
776 .unwrap();
777 }
778 pool
779 }
780
781 #[tokio::test]
782 async fn the_board_shows_a_login_s_standing_and_nothing_of_the_login() {
783 use std::sync::Arc;
784
785 use ai6::directorates::q::logins::add_login;
786 use ai6::directorates::q::sealing::{Recipient, SealingKey, Vault};
787 use ai6::directorates::registry::sealed::StationSealingKey;
788
789 const PLANTED: &str = "planted-refresh-0451";
790 let served = served_with(ROLES).await;
791 let pool = AccountPool::new("free", "acp")
792 .account(Account::new("shared", AccountKind::HarnessLogin).files([".fake/auth.json"]));
793 let account = AccountRef::new("free", "shared");
794 served
795 .registry
796 .declare_account(
797 &account,
798 "worker",
799 &AccountProfile::of(&pool, "shared", vec!["G".to_owned()]).unwrap(),
800 )
801 .unwrap();
802 let key = Arc::new(SealingKey::generate());
803 served
804 .registry
805 .publish_sealing_key(&StationSealingKey::new(
806 "worker",
807 key.public_key().to_text(),
808 ))
809 .unwrap();
810 let vault = Vault::new(
811 Arc::new(ai6::FileRegistry::open(served.registry.root())),
812 "worker",
813 key,
814 )
815 .with_trust(ai6::directorates::q::sealing::Trust::unsigned());
816 let dir = tempfile::tempdir().unwrap();
817 std::fs::create_dir_all(dir.path().join(".fake")).unwrap();
818 std::fs::write(
819 dir.path().join(".fake/auth.json"),
820 format!(r#"{{"refresh_token":"{PLANTED}","expires_at":1890000000}}"#),
821 )
822 .unwrap();
823 add_login(
824 &vault,
825 &account,
826 dir.path(),
827 &[".fake/auth.json".to_owned()],
828 &[Recipient::named("worker")],
829 1_790_000_000.0,
830 )
831 .unwrap();
832
833 let response = board(&served, &served.viewer, "G").await;
834 assert_eq!(response.status(), StatusCode::OK);
835 let text = response.text().await.unwrap();
836 assert!(!text.contains(PLANTED), "{text}");
837 assert!(!text.contains("auth.json"), "{text}");
838 let body: serde_json::Value = serde_json::from_str(&text).unwrap();
839 let login = &body["accounts"][0]["login"];
840 assert_eq!(login["stations"], serde_json::json!(["worker"]));
841 assert_eq!(login["expires_at"], 1_890_000_000.0);
842 assert_eq!(login["renewed_at"], 1_790_000_000.0);
843 assert_eq!(login["renewal_held_by"], serde_json::Value::Null);
844 assert_eq!(login["needs_person"], serde_json::Value::Null);
845 }
846
847 async fn board(served: &Served, token: &str, operation: &str) -> reqwest::Response {
848 reqwest::Client::new()
849 .get(format!(
850 "{}/v1/user/operations/{operation}/pools",
851 served.base
852 ))
853 .bearer_auth(token)
854 .send()
855 .await
856 .unwrap()
857 }
858
859 #[tokio::test]
860 async fn the_board_shows_an_operations_accounts_and_never_a_credential() {
861 let served = served_with(ROLES).await;
862 let now = std::time::SystemTime::now()
863 .duration_since(std::time::UNIX_EPOCH)
864 .unwrap()
865 .as_secs_f64()
866 .floor();
868 let pool = declare(&served);
869 let alpha = AccountRef::new("team", "alpha");
870 for (mission, operation) in [("mission-g", "G"), ("SECRET-MISSION-L", "L")] {
871 served
872 .registry
873 .claim_account(
874 &AccountClaimRequest::new(&pool, "worker", mission, Duration::from_secs(60))
875 .operation(Some(operation.to_owned()))
876 .only("alpha"),
877 now,
878 )
879 .unwrap()
880 .unwrap();
881 }
882 served
883 .registry
884 .report_quota(
885 &alpha,
886 &[QuotaWindow::new("five_hour", now)
887 .used_permille(640)
888 .resets_at(now + 600.0)],
889 )
890 .unwrap();
891 served.registry.limit_account(&alpha, now + 600.0).unwrap();
892 served
893 .registry
894 .record_account_usage(&alpha, 1_234, now as i64)
895 .unwrap();
896
897 let response = board(&served, &served.viewer, "G").await;
898 assert_eq!(response.status(), StatusCode::OK);
899 let shown: serde_json::Value = response.json().await.unwrap();
900 let text = shown.to_string();
901 assert!(!text.contains("SECRET"), "{text}");
902 assert_eq!(shown["operation_id"], "G");
903 let accounts = shown["accounts"].as_array().unwrap();
904 assert_eq!(accounts.len(), 1, "beta is not open to G");
905 let alpha = &accounts[0];
906 assert_eq!(alpha["pool"], "team");
907 assert_eq!(alpha["account"], "alpha");
908 assert_eq!(alpha["kind"], "claude-oauth-token");
909 assert_eq!(alpha["max_concurrent"], 2);
910 assert_eq!(alpha["active"].as_array().unwrap().len(), 1);
911 assert_eq!(alpha["active"][0]["mission_id"], "mission-g");
912 assert_eq!(alpha["active"][0]["station_id"], "worker");
913 assert_eq!(
914 alpha["other_runs"], 1,
915 "another Operation's Run is only counted"
916 );
917 assert_eq!(alpha["windows"][0]["used_permille"], 640);
918 assert_eq!(alpha["windows"][0]["observed_at"], now);
919 assert_eq!(alpha["windows"][0]["models"], serde_json::json!([]));
920 assert_eq!(alpha["limited_until"], now + 600.0);
921 assert_eq!(alpha["tokens_today"], 1_234);
922 let mut keys = alpha
924 .as_object()
925 .unwrap()
926 .keys()
927 .cloned()
928 .collect::<Vec<_>>();
929 keys.sort();
930 assert_eq!(
931 keys,
932 [
933 "account",
934 "active",
935 "handler",
936 "kind",
937 "labels",
938 "last_used",
939 "limited_until",
940 "login",
941 "max_concurrent",
942 "other_runs",
943 "pool",
944 "priority",
945 "tokens_today",
946 "usage_read",
947 "windows",
948 ],
949 "no field carries a secret name or a login directory"
950 );
951 }
952
953 async fn ask_usage(
955 served: &Served,
956 token: &str,
957 account: &str,
958 ) -> (StatusCode, serde_json::Value) {
959 let response = reqwest::Client::new()
960 .post(format!(
961 "{}/v1/user/operations/G/pools/team/{account}/usage",
962 served.base
963 ))
964 .bearer_auth(token)
965 .send()
966 .await
967 .unwrap();
968 let status = response.status();
969 (status, response.json().await.unwrap_or_default())
970 }
971
972 #[tokio::test]
973 async fn asking_for_usage_needs_pool_read_and_a_station_answers_it_through_the_registry() {
974 let served = served_with(ROLES).await;
975 declare(&served);
976 let alpha = AccountRef::new("team", "alpha");
977 assert_eq!(
978 ask_usage(&served, "not-a-token", "alpha").await.0,
979 StatusCode::UNAUTHORIZED
980 );
981 assert_eq!(
982 ask_usage(&served, &served.viewer, "beta").await.0,
983 StatusCode::NOT_FOUND,
984 "beta is not declared for G"
985 );
986 let (status, waiting) = ask_usage(&served, &served.viewer, "alpha").await;
988 assert_eq!(status, StatusCode::ACCEPTED, "{waiting}");
989 assert!(
990 waiting["usage_read"]["requested_at"].is_number(),
991 "{waiting}"
992 );
993 assert!(waiting["usage_read"]["answered_at"].is_null(), "{waiting}");
994 let held = served
995 .registry
996 .accounts()
997 .unwrap()
998 .into_iter()
999 .find(|state| state.account == alpha)
1000 .unwrap();
1001 assert!(held.usage_request.unwrap().waits());
1002 let station = ai6::FileRegistry::open(served.registry.root());
1004 let answering = alpha.clone();
1005 let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1006 let stopping = stop.clone();
1007 let answered = std::thread::spawn(move || {
1008 let mut answers = 0;
1009 while !stopping.load(std::sync::atomic::Ordering::SeqCst) {
1010 let asked = station
1011 .accounts()
1012 .unwrap()
1013 .into_iter()
1014 .find(|state| state.account == answering)
1015 .and_then(|state| state.usage_request)
1016 .filter(|ask| ask.waits());
1017 if let Some(ask) = asked {
1018 station
1019 .report_quota(
1020 &answering,
1021 &[QuotaWindow::new("five_hour", ask.at + 1.0).used_permille(420)],
1022 )
1023 .unwrap();
1024 ai6::directorates::q::usage_standing::answer(
1025 &station,
1026 &answering,
1027 ask.at,
1028 ask.at + 1.0,
1029 "read",
1030 )
1031 .unwrap();
1032 answers += 1;
1033 }
1034 std::thread::sleep(Duration::from_millis(20));
1035 }
1036 answers
1037 });
1038 let (status, entry) = ask_usage(&served, &served.viewer, "alpha").await;
1039 stop.store(true, std::sync::atomic::Ordering::SeqCst);
1040 assert!(answered.join().unwrap() >= 1, "the Station saw the ask");
1041 assert_eq!(status, StatusCode::OK, "{entry}");
1042 assert_eq!(entry["usage_read"]["result"], "read");
1043 assert!(entry["usage_read"]["answered_at"].is_number());
1044 assert_eq!(entry["windows"][0]["used_permille"], 420);
1045 let text = entry.to_string();
1046 assert!(
1047 !text.contains("SECRET-NAME") && !text.contains("SECRET-DIR"),
1048 "{text}"
1049 );
1050 let board: serde_json::Value = board(&served, &served.viewer, "G")
1052 .await
1053 .json()
1054 .await
1055 .unwrap();
1056 assert_eq!(board["accounts"][0]["usage_read"]["result"], "read");
1057 }
1058
1059 #[tokio::test]
1060 async fn clearing_a_limit_needs_pool_manage_and_is_audited() {
1061 let served = served_with(ROLES).await;
1062 declare(&served);
1063 let alpha = AccountRef::new("team", "alpha");
1064 served
1065 .registry
1066 .limit_account(&alpha, 4_000_000_000.0)
1067 .unwrap();
1068 let clear = |token: String, account: &'static str| {
1069 let base = served.base.clone();
1070 async move {
1071 reqwest::Client::new()
1072 .post(format!(
1073 "{base}/v1/user/operations/G/pools/team/{account}/clear-limit"
1074 ))
1075 .bearer_auth(token)
1076 .send()
1077 .await
1078 .unwrap()
1079 .status()
1080 }
1081 };
1082 assert_eq!(
1083 clear(served.viewer.clone(), "alpha").await,
1084 StatusCode::FORBIDDEN,
1085 "pool.read is not enough"
1086 );
1087 assert_eq!(
1088 clear(served.operator.clone(), "beta").await,
1089 StatusCode::NOT_FOUND,
1090 "beta is not declared for G"
1091 );
1092 assert_eq!(
1093 clear(served.operator.clone(), "alpha").await,
1094 StatusCode::NO_CONTENT
1095 );
1096 let state = served
1097 .registry
1098 .accounts()
1099 .unwrap()
1100 .into_iter()
1101 .find(|state| state.account == alpha)
1102 .unwrap();
1103 assert_eq!(state.limited_until, None);
1104 let audit = served.registry.audit_records().unwrap();
1105 assert!(
1106 audit
1107 .iter()
1108 .any(|record| record.action == "pool.limit.clear"
1109 && record.target == "team/alpha"
1110 && record.actor == "operator-007"
1111 && record.operation == "G")
1112 );
1113 }
1114
1115 fn declare_login(served: &Served) -> AccountRef {
1117 let pool = AccountPool::new("free", "acp")
1118 .account(Account::new("shared", AccountKind::HarnessLogin).files([".fake/auth.json"]))
1119 .account(Account::new("other", AccountKind::HarnessLogin).files([".fake/auth.json"]));
1120 for (name, operation) in [("shared", "G"), ("other", "L")] {
1121 served
1122 .registry
1123 .declare_account(
1124 &AccountRef::new("free", name),
1125 "worker",
1126 &AccountProfile::of(&pool, name, vec![operation.to_owned()]).unwrap(),
1127 )
1128 .unwrap();
1129 }
1130 AccountRef::new("free", "shared")
1131 }
1132
1133 fn login_state(served: &Served, account: &AccountRef) -> Option<ai6::LoginState> {
1134 served
1135 .registry
1136 .accounts()
1137 .unwrap()
1138 .into_iter()
1139 .find(|state| state.account == *account)
1140 .and_then(|state| state.login)
1141 }
1142
1143 fn give_login(served: &Served, account: &AccountRef, change: impl Fn(&mut ai6::LoginState)) {
1145 served
1146 .registry
1147 .change_login(account, &mut |state| {
1148 let mut login = ai6::LoginState::default();
1149 login.stations = vec!["worker".to_owned()];
1150 login.revision = 1;
1151 change(&mut login);
1152 *state = Some(login);
1153 })
1154 .unwrap();
1155 }
1156
1157 #[tokio::test]
1158 async fn the_board_says_when_a_login_needs_a_person_and_what_to_run() {
1159 let served = served_with(ROLES).await;
1160 let account = declare_login(&served);
1161 let response = board(&served, &served.viewer, "G").await;
1163 let body: serde_json::Value = response.json().await.unwrap();
1164 let login = &body["accounts"][0]["login"];
1165 assert_eq!(login["stations"], serde_json::json!([]));
1166 assert_eq!(login["needs_person"], "no login is kept for this account");
1167 assert_eq!(
1168 login["needs_person_command"],
1169 "ai6 pools add-login free shared --handler acp --replace"
1170 );
1171
1172 let now = std::time::SystemTime::now()
1173 .duration_since(std::time::UNIX_EPOCH)
1174 .unwrap()
1175 .as_secs_f64()
1176 .floor();
1177 give_login(&served, &account, |login| {
1178 login.expires_at = Some(now + 600.0);
1179 login.renewed_at = Some(now - 60.0);
1180 login.last_result = Some("failed: its harness removed its login file".to_owned());
1181 login.last_attempt_at = Some(now - 30.0);
1182 login.failures = 3;
1183 login.needs_person = Some("3 renewals failed in a row".to_owned());
1184 login.lease = Some(
1185 serde_json::from_value(
1186 serde_json::json!({"station": "worker", "until": now + 120.0}),
1187 )
1188 .unwrap(),
1189 );
1190 });
1191 let body: serde_json::Value = board(&served, &served.viewer, "G")
1192 .await
1193 .json()
1194 .await
1195 .unwrap();
1196 let login = &body["accounts"][0]["login"];
1197 assert_eq!(login["stations"], serde_json::json!(["worker"]));
1198 assert_eq!(login["renewal_held_by"], "worker");
1199 assert_eq!(login["renewal_held_until"], now + 120.0);
1200 assert_eq!(login["last_attempt_at"], now - 30.0);
1201 assert!(
1202 login["last_result"]
1203 .as_str()
1204 .unwrap()
1205 .starts_with("failed: ")
1206 );
1207 assert_eq!(login["failures"], 3);
1208 assert_eq!(login["needs_person"], "3 renewals failed in a row");
1209 assert_eq!(
1210 login["needs_person_command"],
1211 "ai6 pools add-login free shared --handler acp --replace"
1212 );
1213
1214 give_login(&served, &account, |login| {
1216 login.last_result = Some("renewed".to_owned());
1217 });
1218 let body: serde_json::Value = board(&served, &served.viewer, "G")
1219 .await
1220 .json()
1221 .await
1222 .unwrap();
1223 let login = &body["accounts"][0]["login"];
1224 assert_eq!(login["needs_person"], serde_json::Value::Null);
1225 assert_eq!(login["needs_person_command"], serde_json::Value::Null);
1226 }
1227
1228 async fn change(
1229 served: &Served,
1230 token: &str,
1231 method: reqwest::Method,
1232 path: &str,
1233 body: Option<serde_json::Value>,
1234 ) -> StatusCode {
1235 let mut request = reqwest::Client::new()
1236 .request(method, format!("{}/v1/user/operations/{path}", served.base))
1237 .bearer_auth(token);
1238 if let Some(body) = body {
1239 request = request.json(&body);
1240 }
1241 request.send().await.unwrap().status()
1242 }
1243
1244 #[tokio::test]
1245 async fn stations_and_the_login_are_changed_with_pool_manage_and_audited_first() {
1246 use reqwest::Method;
1247 let served = served_with(ROLES).await;
1248 let account = declare_login(&served);
1249 let stations = "G/pools/free/shared/login/stations";
1250 let add = || serde_json::json!({"station": "host-b"});
1251
1252 assert_eq!(
1253 change(&served, &served.viewer, Method::POST, stations, Some(add())).await,
1254 StatusCode::FORBIDDEN,
1255 "pool.read is not enough"
1256 );
1257 assert_eq!(
1258 change(
1259 &served,
1260 &served.operator,
1261 Method::POST,
1262 "G/pools/free/other/login/stations",
1263 Some(add())
1264 )
1265 .await,
1266 StatusCode::NOT_FOUND,
1267 "free/other is not declared for G"
1268 );
1269 assert_eq!(
1270 change(
1271 &served,
1272 &served.operator,
1273 Method::POST,
1274 stations,
1275 Some(add())
1276 )
1277 .await,
1278 StatusCode::NOT_FOUND,
1279 "there is no login to change"
1280 );
1281 assert!(
1282 served
1283 .registry
1284 .audit_records()
1285 .unwrap()
1286 .iter()
1287 .all(|record| !record.action.starts_with("pool.login")),
1288 "a refused request leaves no trace beyond the refusal"
1289 );
1290
1291 give_login(&served, &account, |_| {});
1292 assert_eq!(
1293 change(
1294 &served,
1295 &served.operator,
1296 Method::POST,
1297 stations,
1298 Some(add())
1299 )
1300 .await,
1301 StatusCode::ACCEPTED
1302 );
1303 assert_eq!(
1304 change(
1305 &served,
1306 &served.operator,
1307 Method::DELETE,
1308 &format!("{stations}/worker"),
1309 None
1310 )
1311 .await,
1312 StatusCode::ACCEPTED
1313 );
1314 let login = login_state(&served, &account).unwrap();
1315 let asked: Vec<_> = login.requests.iter().map(|asked| &asked.action).collect();
1316 assert_eq!(
1317 asked,
1318 [
1319 &ai6::LoginRequestAction::AddStation {
1320 station: "host-b".to_owned()
1321 },
1322 &ai6::LoginRequestAction::RemoveStation {
1323 station: "worker".to_owned()
1324 },
1325 ]
1326 );
1327 assert_eq!(
1328 login.stations,
1329 ["worker"],
1330 "a Station with the key makes it"
1331 );
1332 let body: serde_json::Value = board(&served, &served.viewer, "G")
1333 .await
1334 .json()
1335 .await
1336 .unwrap();
1337 assert_eq!(
1338 body["accounts"][0]["login"]["requests"][0],
1339 serde_json::json!({"action": "add_station", "station": "host-b",
1340 "by": "operator-007", "at": body["accounts"][0]["login"]["requests"][0]["at"]})
1341 );
1342
1343 assert_eq!(
1345 change(
1346 &served,
1347 &served.operator,
1348 Method::DELETE,
1349 "G/pools/free/shared/login?sign_out=true",
1350 None
1351 )
1352 .await,
1353 StatusCode::ACCEPTED
1354 );
1355 assert!(login_state(&served, &account).is_some());
1356 assert_eq!(
1357 change(
1358 &served,
1359 &served.operator,
1360 Method::DELETE,
1361 "G/pools/free/shared/login",
1362 None
1363 )
1364 .await,
1365 StatusCode::NO_CONTENT
1366 );
1367 assert!(login_state(&served, &account).is_none());
1368 assert_eq!(
1369 change(
1370 &served,
1371 &served.operator,
1372 Method::DELETE,
1373 "G/pools/free/shared/login",
1374 None
1375 )
1376 .await,
1377 StatusCode::NOT_FOUND,
1378 "it holds none now"
1379 );
1380 let mut made: Vec<(String, String)> = served
1381 .registry
1382 .audit_records()
1383 .unwrap()
1384 .into_iter()
1385 .filter(|record| record.action.starts_with("pool.login"))
1386 .inspect(|record| {
1387 assert_eq!(record.actor, "operator-007");
1388 assert_eq!(record.operation, "G");
1389 })
1390 .map(|record| (record.action, record.target))
1391 .collect();
1392 made.sort();
1393 assert_eq!(
1394 made,
1395 [
1396 ("pool.login.forget".to_owned(), "free/shared".to_owned()),
1397 ("pool.login.sign_out".to_owned(), "free/shared".to_owned()),
1398 (
1399 "pool.login.station.add".to_owned(),
1400 "free/shared host-b".to_owned()
1401 ),
1402 (
1403 "pool.login.station.remove".to_owned(),
1404 "free/shared worker".to_owned()
1405 ),
1406 ]
1407 );
1408 }
1409
1410 #[tokio::test]
1411 async fn a_refused_audit_refuses_the_change() {
1412 use reqwest::Method;
1413 let served = served_with(ROLES).await;
1414 let account = declare_login(&served);
1415 give_login(&served, &account, |_| {});
1416 let audit = served.registry.root().join("audit");
1418 let _ = std::fs::remove_dir_all(&audit);
1419 std::fs::write(&audit, b"not a directory").unwrap();
1420 for (method, path, body) in [
1421 (
1422 Method::POST,
1423 "G/pools/free/shared/login/stations",
1424 Some(serde_json::json!({"station": "host-b"})),
1425 ),
1426 (
1427 Method::DELETE,
1428 "G/pools/free/shared/login/stations/worker",
1429 None,
1430 ),
1431 (
1432 Method::DELETE,
1433 "G/pools/free/shared/login?sign_out=true",
1434 None,
1435 ),
1436 (Method::DELETE, "G/pools/free/shared/login", None),
1437 ] {
1438 let status = change(&served, &served.operator, method, path, body).await;
1439 assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{path}");
1440 }
1441 let login = login_state(&served, &account).expect("the login was not forgotten");
1442 assert!(login.requests.is_empty(), "nothing was queued");
1443 }
1444
1445 #[tokio::test]
1446 async fn the_board_needs_pool_read_on_the_operation() {
1447 let served = served_with(ROLES).await;
1448 assert_eq!(
1449 board(&served, &served.viewer, "L").await.status(),
1450 StatusCode::FORBIDDEN
1451 );
1452 assert_eq!(
1453 board(&served, &served.operator, "L").await.status(),
1454 StatusCode::FORBIDDEN,
1455 "the operator has no pool.read in L"
1456 );
1457 let anonymous = reqwest::Client::new()
1458 .get(format!("{}/v1/user/operations/G/pools", served.base))
1459 .send()
1460 .await
1461 .unwrap();
1462 assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
1463 }
1464}