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
use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde::Serialize;
use tokio::sync::Mutex;
use super::auth::{ensure_readonly_credential, ReadonlyCredential};
use super::discovery::{parse_workspace_list, workspace_url, Discovery, KcpInfo, WorkspaceInfo};
use super::runner::Runner;
pub const PROTECTED_HOSTS: &[&str] = &["socialweb.computer", "hat-7", "hat-9"];
const DISCOVERY_TTL: Duration = Duration::from_secs(30);
const TOKEN_REFRESH_MARGIN: Duration = Duration::from_secs(180);
const DEFAULT_TOKEN_TTL_SECONDS: u64 = 900;
type DiscoveryCache = Option<(Instant, Vec<KcpInfo>, Vec<String>)>;
#[derive(Clone, Debug)]
struct CachedCredential {
credential: ReadonlyCredential,
expires_at: Instant,
}
pub struct KcpService {
discovery: Discovery,
runner: Runner,
allow_prod: bool,
token_ttl_seconds: u64,
kcps: Mutex<DiscoveryCache>,
credentials: Mutex<HashMap<String, CachedCredential>>,
}
#[derive(Clone)]
pub struct KcpServiceHandle(pub Arc<KcpService>);
impl KcpServiceHandle {
pub fn new(service: KcpService) -> Self {
Self(Arc::new(service))
}
}
impl std::ops::Deref for KcpServiceHandle {
type Target = KcpService;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl KcpService {
pub fn new(
runner: Runner,
roots: Vec<String>,
kubeconfigs: Vec<String>,
allow_prod: bool,
) -> Self {
let discovery = Discovery::new(runner.clone(), roots, kubeconfigs);
Self {
discovery,
runner,
allow_prod,
token_ttl_seconds: DEFAULT_TOKEN_TTL_SECONDS,
kcps: Mutex::new(None),
credentials: Mutex::new(HashMap::new()),
}
}
pub async fn discover(&self, refresh: bool) -> (Vec<KcpInfo>, Vec<String>) {
let mut cache = self.kcps.lock().await;
if !refresh {
if let Some((at, kcps, errors)) = cache.as_ref() {
if at.elapsed() < DISCOVERY_TTL {
return (kcps.clone(), errors.clone());
}
}
}
let (mut kcps, mut errors) = self.discovery.discover().await;
for kcp in &mut kcps {
let workspace = kcp.workspace.clone();
match self
.read(
kcp,
&workspace,
&["get".to_string(), "--raw=/livez".to_string()],
)
.await
{
Ok(output) => kcp.running = output.to_ascii_lowercase().contains("ok"),
Err(error) => {
kcp.running = false;
kcp.error = Some(error.clone());
errors.push(format!("{}: {error}", kcp.id));
}
}
}
*cache = Some((Instant::now(), kcps.clone(), errors.clone()));
(kcps, errors)
}
pub async fn kcps(&self, refresh: bool) -> Result<Vec<KcpInfo>, String> {
let (kcps, errors) = self.discover(refresh).await;
if kcps.is_empty() {
let detail = if errors.is_empty() {
"no kcp admin.kubeconfig was found under the configured roots; pass --kubeconfig or --root".to_string()
} else {
errors.join("; ")
};
return Err(format!("no running kcp was discovered: {detail}"));
}
Ok(kcps)
}
/// Resolves a kcp id or kubeconfig path. `None` picks the only discovered
/// kcp, and fails with the list of ids when there are several.
pub async fn resolve_kcp(&self, needle: Option<&str>) -> Result<KcpInfo, String> {
let Some(needle) = needle.filter(|needle| !needle.is_empty()) else {
let mut kcps = self.kcps(false).await?;
if kcps.is_empty() {
kcps = self.discover(true).await.0;
}
return match kcps.as_slice() {
[only] => Ok(only.clone()),
[] => Err("no kcp discovered; pass kcp=<id or kubeconfig path>".to_string()),
many => Err(format!(
"several kcps running; pass kcp=<id>, one of: {}",
many.iter()
.map(|kcp| kcp.id.as_str())
.collect::<Vec<_>>()
.join(", ")
)),
};
};
let mut kcps = self.kcps(false).await?;
if let Some(found) = find_kcp(&kcps, needle) {
return Ok(found.clone());
}
let (fresh, _) = self.discover(true).await;
kcps = fresh;
find_kcp(&kcps, needle).cloned().ok_or_else(|| {
format!(
"unknown kcp {needle:?}; known kcps: {}",
kcps.iter()
.map(|kcp| kcp.id.as_str())
.collect::<Vec<_>>()
.join(", ")
)
})
}
pub async fn list_workspaces(
&self,
kcp: &KcpInfo,
workspace: Option<&str>,
recursive: bool,
) -> Result<Vec<WorkspaceInfo>, String> {
self.ensure_allowed(kcp, "list workspaces")?;
let start = workspace.unwrap_or(&kcp.workspace).to_string();
let mut seen = BTreeSet::new();
let mut result = Vec::new();
let mut pending = vec![start];
while let Some(parent) = pending.pop() {
if !seen.insert(parent.clone()) {
continue;
}
let output = self
.read(
kcp,
&parent,
&[
"get".to_string(),
"workspaces".to_string(),
"-o".to_string(),
"json".to_string(),
],
)
.await?;
for workspace in parse_workspace_list(&output, &parent, &kcp.server)? {
if recursive {
pending.push(workspace.path.clone());
}
result.push(workspace);
}
}
result.sort_by(|left, right| left.path.cmp(&right.path));
Ok(result)
}
pub fn workspace_or_default(&self, kcp: &KcpInfo, workspace: Option<&str>) -> String {
workspace
.map(str::to_string)
.filter(|workspace| !workspace.is_empty())
.unwrap_or_else(|| kcp.workspace.clone())
}
pub fn workspace_url(&self, kcp: &KcpInfo, workspace: &str) -> String {
workspace_url(&kcp.server, workspace)
}
pub async fn read(
&self,
kcp: &KcpInfo,
workspace: &str,
args: &[String],
) -> Result<String, String> {
self.ensure_allowed(kcp, "read")?;
let credential = self.credential(kcp, workspace).await?;
let mut command = vec![
"--kubeconfig".to_string(),
credential.kubeconfig.clone(),
"--server".to_string(),
self.workspace_url(kcp, workspace),
"--request-timeout=30s".to_string(),
];
command.extend(args.iter().cloned());
self.runner.kubectl(&command, None).await
}
/// Starts a streaming read (`kubectl get -w`) with the read credential and
/// no request timeout; the caller owns the child.
pub async fn read_stream(
&self,
kcp: &KcpInfo,
workspace: &str,
args: &[String],
) -> Result<tokio::process::Child, String> {
self.ensure_allowed(kcp, "watch")?;
let credential = self.credential(kcp, workspace).await?;
let mut command = vec![
"--kubeconfig".to_string(),
credential.kubeconfig.clone(),
"--server".to_string(),
self.workspace_url(kcp, workspace),
"--request-timeout=0".to_string(),
];
command.extend(args.iter().cloned());
self.runner.spawn_kubectl_stream(&command)
}
pub async fn admin(
&self,
kcp: &KcpInfo,
workspace: &str,
args: &[String],
stdin: Option<&str>,
) -> Result<String, String> {
self.ensure_allowed(kcp, "write")?;
let mut command = vec![
"--kubeconfig".to_string(),
kcp.kubeconfig.clone(),
"--server".to_string(),
self.workspace_url(kcp, workspace),
"--request-timeout=30s".to_string(),
];
command.extend(args.iter().cloned());
self.runner.kubectl(&command, stdin).await
}
pub async fn readonly_credential_status(
&self,
kcp: &KcpInfo,
workspace: &str,
refresh: bool,
) -> Result<ReadonlyCredential, String> {
self.ensure_allowed(kcp, "mint a read-only token")?;
if refresh {
self.credentials
.lock()
.await
.remove(&cache_key(kcp, workspace));
}
self.credential(kcp, workspace).await
}
async fn credential(
&self,
kcp: &KcpInfo,
workspace: &str,
) -> Result<ReadonlyCredential, String> {
let key = cache_key(kcp, workspace);
{
let cache = self.credentials.lock().await;
if let Some(cached) = cache.get(&key) {
if cached.expires_at.saturating_duration_since(Instant::now())
> TOKEN_REFRESH_MARGIN
{
return Ok(cached.credential.clone());
}
}
}
let admin = self.discovery.admin_config(kcp).await?;
let credential = ensure_readonly_credential(
&self.runner,
kcp,
workspace,
&admin,
self.token_ttl_seconds,
)
.await?;
let expires_at = Instant::now() + Duration::from_secs(self.token_ttl_seconds);
self.credentials.lock().await.insert(
key,
CachedCredential {
credential: credential.clone(),
expires_at,
},
);
Ok(credential)
}
fn ensure_allowed(&self, kcp: &KcpInfo, operation: &str) -> Result<(), String> {
if self.allow_prod {
return Ok(());
}
if PROTECTED_HOSTS
.iter()
.any(|protected| kcp.host.contains(protected))
{
return Err(format!(
"refusing to {operation} on protected host {:?}; re-run with --allow-prod after confirming the target",
kcp.host
));
}
Ok(())
}
}
pub fn find_kcp<'a>(kcps: &'a [KcpInfo], needle: &str) -> Option<&'a KcpInfo> {
if let Some(exact) = kcps
.iter()
.find(|kcp| kcp.id == needle || kcp.kubeconfig == needle)
{
return Some(exact);
}
let matches = kcps
.iter()
.filter(|kcp| kcp.id.contains(needle) || kcp.kubeconfig.contains(needle))
.collect::<Vec<_>>();
if matches.len() == 1 {
matches.first().copied()
} else {
None
}
}
fn cache_key(kcp: &KcpInfo, workspace: &str) -> String {
format!("{}|{workspace}", kcp.id)
}
#[derive(Serialize)]
pub struct DiscoveryReport<'a> {
pub kcps: &'a [KcpInfo],
pub errors: &'a [String],
}
#[derive(Serialize)]
pub struct CredentialReport {
pub kcp: String,
pub host: String,
pub workspace: String,
pub token_kubeconfig: String,
pub token_expires_in_seconds: u64,
pub note: &'static str,
}