ztnet 0.1.20

ZTNet CLI — manage ZeroTier networks via ZTNet
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
use reqwest::Method;
use serde_json::Value;

use crate::cli::{GlobalOpts, OrgCommand, OrgRole, OutputFormat};
use crate::context::resolve_effective_config;
use crate::error::CliError;
use crate::http::{ClientUi, HttpClient};
use crate::output;

use super::common::{load_config_store, print_human_or_machine};
use super::resolve::resolve_org_id;
use super::trpc_client::{require_cookie_from_effective, TrpcClient};
use super::trpc_resolve::resolve_org_id as resolve_org_id_trpc;

pub(super) async fn run(global: &GlobalOpts, command: OrgCommand) -> Result<(), CliError> {
	let (_config_path, cfg) = load_config_store()?;
	let effective = resolve_effective_config(global, &cfg)?;

	let client = HttpClient::new(
		&effective.host,
		effective.token.clone(),
		effective.timeout,
		effective.retries,
		global.dry_run,
		ClientUi::from_context(global, &effective),
	)?;

	match command {
		OrgCommand::List(args) => {
			let mut response = client
				.request_json(Method::GET, "/api/v1/org", None, Default::default(), true)
				.await?;

			if args.details {
				let Some(orgs) = response.as_array() else {
					return Err(CliError::InvalidArgument("expected array response".to_string()));
				};

				let mut detailed = Vec::with_capacity(orgs.len());
				for org in orgs {
					let Some(id) = org.get("id").and_then(|v| v.as_str()) else {
						continue;
					};
					let detail = client
						.request_json(
							Method::GET,
							&format!("/api/v1/org/{id}"),
							None,
							Default::default(),
							true,
						)
						.await?;
					detailed.push(detail);
				}
				response = Value::Array(detailed);
			}

			if args.ids_only {
				let ids = response
					.as_array()
					.map(|arr| {
						arr.iter()
							.filter_map(|o| o.get("id").and_then(|v| v.as_str()).map(str::to_string))
							.collect::<Vec<_>>()
					})
					.unwrap_or_default();

				if matches!(effective.output, OutputFormat::Table) {
					for id in ids {
						println!("{id}");
					}
					return Ok(());
				}

				let value = Value::Array(ids.into_iter().map(Value::String).collect());
				output::print_value(&value, effective.output, global.no_color)?;
				return Ok(());
			}

			output::print_value(&response, effective.output, global.no_color)?;
			Ok(())
		}
		OrgCommand::Get(args) => {
			let org_id = resolve_org_id(&client, &args.org).await?;
			let response = client
				.request_json(
					Method::GET,
					&format!("/api/v1/org/{org_id}"),
					None,
					Default::default(),
					true,
				)
				.await?;
			print_human_or_machine(&response, effective.output, global.no_color)?;
			Ok(())
		}
		OrgCommand::Users { command } => match command {
			crate::cli::OrgUsersCommand::List(args) => {
				let org_id = resolve_org_id(&client, &args.org).await?;
				let response = client
					.request_json(
						Method::GET,
						&format!("/api/v1/org/{org_id}/user"),
						None,
						Default::default(),
						true,
					)
					.await?;
				output::print_value(&response, effective.output, global.no_color)?;
				Ok(())
			}
			crate::cli::OrgUsersCommand::Add(args) => {
				let trpc = trpc_authed(global, &effective)?;
				let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;

				let users = trpc
					.query(
						"org.getPlatformUsers",
						serde_json::json!({ "organizationId": &org_id }),
					)
					.await?;
				let Some(users) = users.as_array() else {
					return Err(CliError::InvalidArgument(
						"failed to list platform users".to_string(),
					));
				};

				let mut matches = Vec::new();
				for u in users {
					let email = u.get("email").and_then(|v| v.as_str()).unwrap_or("");
					if email.eq_ignore_ascii_case(&args.email) {
						matches.push(u.clone());
					}
				}

				let user = match matches.len() {
					0 => {
						return Err(CliError::InvalidArgument(format!(
							"user '{}' not found",
							args.email
						)));
					}
					1 => matches.remove(0),
					_ => {
						return Err(CliError::InvalidArgument(format!(
							"multiple users match '{}'",
							args.email
						)));
					}
				};

				let user_id = user
					.get("id")
					.and_then(|v| v.as_str())
					.ok_or_else(|| CliError::InvalidArgument("user missing id".to_string()))?
					.to_string();
				let user_name = user
					.get("name")
					.and_then(|v| v.as_str())
					.unwrap_or(&args.email)
					.to_string();

				let role = role_to_string(args.role);
				let response = trpc
					.call(
						"org.addUser",
						serde_json::json!({
							"organizationId": &org_id,
							"userId": user_id,
							"userName": user_name,
							"organizationRole": role,
						}),
					)
					.await?;

				print_human_or_machine(&response, effective.output, global.no_color)?;
				Ok(())
			}
			crate::cli::OrgUsersCommand::Role(args) => {
				let trpc = trpc_authed(global, &effective)?;
				let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;

				let user_id = if args.user.contains('@') {
					let users = trpc
						.query("org.getOrgUsers", serde_json::json!({ "organizationId": &org_id }))
						.await?;
					let Some(users) = users.as_array() else {
						return Err(CliError::InvalidArgument(
							"failed to list org users".to_string(),
						));
					};

					let mut matches = Vec::new();
					for u in users {
						let email = u.get("email").and_then(|v| v.as_str()).unwrap_or("");
						if email.eq_ignore_ascii_case(&args.user) {
							matches.push(u.clone());
						}
					}

					let user = match matches.len() {
						0 => {
							return Err(CliError::InvalidArgument(format!(
								"user '{}' not found in org",
								args.user
							)));
						}
						1 => matches.remove(0),
						_ => {
							return Err(CliError::InvalidArgument(format!(
								"multiple org users match '{}'",
								args.user
							)));
						}
					};

					user.get("id")
						.and_then(|v| v.as_str())
						.ok_or_else(|| CliError::InvalidArgument("user missing id".to_string()))?
						.to_string()
				} else {
					args.user.clone()
				};

				let response = trpc
					.call(
						"org.changeUserRole",
						serde_json::json!({
							"organizationId": &org_id,
							"userId": user_id,
							"role": role_to_string(args.role),
						}),
					)
					.await?;

				print_human_or_machine(&response, effective.output, global.no_color)?;
				Ok(())
			}
		},
		OrgCommand::Invite { command } => {
			let trpc = trpc_authed(global, &effective)?;
			match command {
				crate::cli::OrgInviteCommand::Create(args) => {
					let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
					let response = trpc
						.call(
							"org.generateInviteLink",
							serde_json::json!({
								"organizationId": org_id,
								"role": role_to_string(args.role),
								"email": args.email,
							}),
						)
						.await?;
					print_human_or_machine(&response, effective.output, global.no_color)?;
					Ok(())
				}
				crate::cli::OrgInviteCommand::List(args) => {
					let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
					let response = trpc
						.query("org.getInvites", serde_json::json!({ "organizationId": org_id }))
						.await?;
					output::print_value(&response, effective.output, global.no_color)?;
					Ok(())
				}
				crate::cli::OrgInviteCommand::Delete(args) => {
					let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
					let response = trpc
						.call(
							"org.deleteInvite",
							serde_json::json!({
								"organizationId": org_id,
								"invitationId": args.invite,
							}),
						)
						.await?;
					print_human_or_machine(&response, effective.output, global.no_color)?;
					Ok(())
				}
				crate::cli::OrgInviteCommand::Send(args) => {
					let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
					let response = trpc
						.call(
							"org.inviteUserByMail",
							serde_json::json!({
								"organizationId": org_id,
								"role": role_to_string(args.role),
								"email": args.email,
							}),
						)
						.await?;
					print_human_or_machine(&response, effective.output, global.no_color)?;
					Ok(())
				}
			}
		}
		OrgCommand::Settings { command } => {
			let trpc = trpc_authed(global, &effective)?;
			match command {
				crate::cli::OrgSettingsCommand::Get(args) => {
					let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
					let response = trpc
						.query(
							"org.getOrganizationSettings",
							serde_json::json!({ "organizationId": org_id }),
						)
						.await?;
					print_human_or_machine(&response, effective.output, global.no_color)?;
					Ok(())
				}
				crate::cli::OrgSettingsCommand::Update(args) => {
					let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
					let rename = if args.rename_node_globally {
						Some(true)
					} else if args.no_rename_node_globally {
						Some(false)
					} else {
						None
					}
					.ok_or_else(|| {
						CliError::InvalidArgument(
							"no update fields provided (use --rename-node-globally or --no-rename-node-globally)"
								.to_string(),
						)
					})?;

					let response = trpc
						.call(
							"org.updateOrganizationSettings",
							serde_json::json!({
								"organizationId": org_id,
								"renameNodeGlobally": rename,
							}),
						)
						.await?;

					print_human_or_machine(&response, effective.output, global.no_color)?;
					Ok(())
				}
			}
		}
		OrgCommand::Webhooks { command } => {
			let trpc = trpc_authed(global, &effective)?;
			match command {
				crate::cli::OrgWebhooksCommand::List(args) => {
					let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
					let response = trpc
						.query("org.getOrgWebhooks", serde_json::json!({ "organizationId": org_id }))
						.await?;
					output::print_value(&response, effective.output, global.no_color)?;
					Ok(())
				}
				crate::cli::OrgWebhooksCommand::Add(args) => {
					if args.event.is_empty() {
						return Err(CliError::InvalidArgument(
							"webhook add requires at least one --event".to_string(),
						));
					}

					let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
					let response = trpc
						.call(
							"org.addOrgWebhooks",
							serde_json::json!({
								"organizationId": org_id,
								"webhookUrl": args.url,
								"webhookName": args.name,
								"hookType": args.event,
							}),
						)
						.await?;
					print_human_or_machine(&response, effective.output, global.no_color)?;
					Ok(())
				}
				crate::cli::OrgWebhooksCommand::Delete(args) => {
					let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
					let response = trpc
						.call(
							"org.deleteOrgWebhooks",
							serde_json::json!({
								"organizationId": org_id,
								"webhookId": args.webhook,
							}),
						)
						.await?;
					print_human_or_machine(&response, effective.output, global.no_color)?;
					Ok(())
				}
			}
		}
		OrgCommand::Logs(args) => {
			let trpc = trpc_authed(global, &effective)?;
			let org_id = resolve_org_id_trpc(&trpc, &args.org).await?;
			let response = trpc
				.query("org.getLogs", serde_json::json!({ "organizationId": org_id }))
				.await?;
			output::print_value(&response, effective.output, global.no_color)?;
			Ok(())
		}
	}
}

fn role_to_string(role: OrgRole) -> &'static str {
	match role {
		OrgRole::ReadOnly => "READ_ONLY",
		OrgRole::User => "USER",
		OrgRole::Admin => "ADMIN",
	}
}

fn trpc_authed(global: &GlobalOpts, effective: &crate::context::EffectiveConfig) -> Result<TrpcClient, CliError> {
	let cookie = require_cookie_from_effective(effective)?;
	Ok(TrpcClient::new(
		&effective.host,
		effective.timeout,
		effective.retries,
		global.dry_run,
		ClientUi::from_context(global, effective),
	)?
	.with_cookie(Some(cookie)))
}