tailscale-mcp 1.2.1

MCP server for Tailscale: the local node through the CLI, the tailnet through the control-plane API
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//! The devices in the tailnet, as the control plane sees them.
//!
//! The first tailnet toolset, so it settles a few things the rest follow.
//!
//! **Identifiers.** Every device endpoint takes a `device_id`, and the API
//! accepts either the node id (`n1234567CNTRL`, which the listing calls
//! `nodeId`) or the numeric `id`. Both are passed through as the caller wrote
//! them; nothing here converts one to the other, because either is valid and
//! guessing wrong would be a call to the wrong device.
//!
//! **Answers.** ADR-0004 has Tailscale's bodies come back in Tailscale's shape,
//! so a listing answers with `{"devices": [...]}` and a device with the device.
//! The one thing added is on the endpoints that answer with nothing: a caller
//! that asked for a deletion gets a small report saying what was deleted rather
//! than `null`, because `null` is indistinguishable from a bug.
//!
//! **Severing.** Six of these can cut this node off from the tailnet it is
//! being reached over — deleting it, expiring its key, de-authorising it,
//! moving its address, retagging it, or dropping the routes it carries. None
//! is marked self-severing here, because nothing yet recognises *this* node
//! among the arguments: ticket 21 builds that, and marking them before it
//! exists would put a claim in the annotations that the server cannot keep.

use rmcp::schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tailscale_rest::models::device::DEVICE_FIELDS;

use crate::context::ToolContext;
use crate::error::{ToolError, ToolResult};
use crate::tools::common::{
    Done, SelfConfirmation, answered_or, not_at_ourselves, one_of, path_segment, report,
    require_destructive,
};

crate::tools! {
    /// List the devices in the tailnet. Answers with the control plane's own
    /// `{"devices": [...]}`, or with a `window` beside it when `limit` or
    /// `offset` narrowed the list here.
    ///
    /// The endpoint has no pagination, so a large tailnet answers whole and
    /// may exceed this server's result cap. `filters` is what asks the control
    /// plane for less, and so the only one of these that can rescue such a
    /// listing; `limit` and `offset` are applied to an answer that has already
    /// arrived. `fields: "all"` adds the costlier fields — posture identity,
    /// client connectivity — that `default` leaves out, and `fields:
    /// "default"` is the smaller answer.
    tailnet_device_list => DeviceListParams, device_list,
        toolset: TailnetDevices, tier: Read, idempotent: true;

    /// Read one device, by any of the names or identifiers it answers to.
    tailnet_device_get => DeviceGetParams, device_get,
        toolset: TailnetDevices, tier: Read, idempotent: true;

    /// Remove a device from the tailnet permanently. The machine has to
    /// re-authenticate to come back, as a new device with a new address.
    ///
    /// Only devices belonging to this tailnet can be deleted; a device shared
    /// in from another tailnet is refused by the control plane.
    tailnet_device_delete => SeveringDeviceParams, device_delete,
        toolset: TailnetDevices, tier: Destructive, idempotent: true, severs_local: true;

    /// Expire a device's node key, which disconnects it until someone
    /// re-authenticates the machine. The device itself is kept.
    tailnet_device_expire => SeveringDeviceParams, device_expire,
        toolset: TailnetDevices, tier: Destructive, severs_local: true;

    /// Authorise a device, or revoke its authorisation.
    ///
    /// Only meaningful on a tailnet that requires device approval. Authorising
    /// is a write; revoking disconnects the device until it is authorised
    /// again, and needs the destructive tier.
    tailnet_device_authorize => DeviceAuthorizeParams, device_authorize,
        toolset: TailnetDevices, tier: Write, idempotent: true, severs_local: true,
        varying: true;

    /// Rename a device. Its old MagicDNS names stop resolving, so anything
    /// addressing it by name has to be updated.
    tailnet_device_rename => DeviceRenameParams, device_rename,
        toolset: TailnetDevices, tier: Write, idempotent: true, severs_local: true;

    /// Replace a device's tags. Tags must already be defined in the tailnet
    /// policy file, and the credential's own tags limit what it may assign.
    ///
    /// This replaces the whole set: tags not listed are removed, and removing
    /// a tag can remove the access a policy rule granted through it.
    tailnet_device_tags_set => DeviceTagsParams, device_tags_set,
        toolset: TailnetDevices, tier: Write, idempotent: true, severs_local: true;

    /// Turn a device's key expiry off, so it stays connected without
    /// re-authenticating, or back on.
    tailnet_device_key_expiry_set => DeviceKeyExpiryParams, device_key_expiry_set,
        toolset: TailnetDevices, tier: Write, idempotent: true;

    /// Move a device to a different Tailscale IPv4 address.
    ///
    /// Existing connections to the old address break. The address has to come
    /// from the tailnet's own range.
    tailnet_device_ip_set => DeviceIpParams, device_ip_set,
        toolset: TailnetDevices, tier: Write, idempotent: true, severs_local: true;

    /// Read the routes a device advertises and the subset that is enabled.
    tailnet_device_routes_get => DeviceParams, device_routes_get,
        toolset: TailnetDevices, tier: Read, idempotent: true;

    /// Replace the set of advertised routes that are enabled for a device.
    ///
    /// Only the enabled set can be set here; what a device advertises is the
    /// device's own configuration. Enabling a route the device does not
    /// advertise has no effect until it does.
    tailnet_device_routes_set => DeviceRoutesParams, device_routes_set,
        toolset: TailnetDevices, tier: Write, idempotent: true, severs_local: true;

    /// Read the custom posture attributes set on a device, and when each
    /// expires.
    tailnet_device_attributes_get => DeviceParams, device_attributes_get,
        toolset: TailnetDevices, tier: Read, idempotent: true;

    /// Set one custom posture attribute on one device.
    ///
    /// The key must begin `custom:`. The value's type — string, number or
    /// boolean — is fixed by the first write and a later write of a different
    /// type is refused by the control plane.
    tailnet_device_attribute_set => AttributeSetParams, device_attribute_set,
        toolset: TailnetDevices, tier: Write, idempotent: true;

    /// Delete one custom posture attribute from one device. Only `custom:`
    /// attributes can be deleted; the ones Tailscale sets are read-only.
    tailnet_device_attribute_delete => AttributeParams, device_attribute_delete,
        toolset: TailnetDevices, tier: Destructive, idempotent: true;

    /// Set custom posture attributes on many devices in one call.
    ///
    /// A merge: a device the map does not mention is left alone, an attribute
    /// it does not mention is left alone, and an attribute given `null` is
    /// deleted. Each value is a string, a number, a boolean, `null`, or an
    /// object `{"value": ..., "expiry": "<RFC 3339>"}` to set an expiry too.
    tailnet_device_attributes_update => AttributesBatchParams, device_attributes_update,
        toolset: TailnetDevices, tier: Write, idempotent: true;
}

// ---------------------------------------------------------------------------
// Paths
// ---------------------------------------------------------------------------

/// `/api/v2/device/<id>`, with whatever follows it.
///
/// Not a tailnet path: a device is addressed globally by its own id, and the
/// control plane resolves which tailnet it belongs to. Only the two
/// tailnet-wide endpoints — the listing and the batch attribute update — go
/// through [`tailscale_rest::Client::tailnet_path`].
/// Resolve the device, refusing first if either spelling names this node.
///
/// The guard runs twice on purpose. Against what the caller wrote it costs
/// nothing and asks no control plane, so severing this node stays refused even
/// when the listing is unreachable — which is the direction that matters, since
/// a missed match is how a session cuts itself off. Against what that resolved
/// to it catches the one spelling [`SelfIdentity::matches`] does not know: the
/// machine's own hostname, which is not any of the identifiers the API accepts.
///
/// [`SelfIdentity::matches`]: crate::context::SelfIdentity::matches
async fn resolve_not_ourselves(
    ctx: &ToolContext,
    what: &str,
    given: &str,
    confirmation: &crate::tools::common::SelfConfirmation,
) -> ToolResult<String> {
    // Before the lookup, not after: this check needs no control plane, and a
    // call that is about to sever the session it arrived on should be refused
    // without reaching for the network first.
    not_at_ourselves(ctx, what, given, confirmation).await?;
    let device = resolve(ctx, given).await?;
    if device != given.trim() {
        not_at_ourselves(ctx, what, &device, confirmation).await?;
    }
    Ok(device)
}

/// The same check, for the handlers that resolve before they know they need it.
///
/// `device_authorize` only guards one of its two directions and `device_routes_set`
/// has a paragraph to say first, so neither can be folded into the call above;
/// both still owe the caller the same two checks.
async fn neither_names_us(
    ctx: &ToolContext,
    what: &str,
    given: &str,
    resolved: &str,
    confirmation: &crate::tools::common::SelfConfirmation,
) -> ToolResult<()> {
    not_at_ourselves(ctx, what, given, confirmation).await?;
    if resolved != given.trim() {
        not_at_ourselves(ctx, what, resolved, confirmation).await?;
    }
    Ok(())
}

/// Whether a value is already an identifier the control plane will take.
///
/// The two accepted shapes are distinctive enough to recognise without asking
/// anybody: a node id is `n`, alphanumerics, then `CNTRL`, and the legacy id is
/// all digits. Everything else is a name, and gets resolved. Recognising rather
/// than resolving is what keeps every call that works today working byte for
/// byte, and keeps a mistyped node id reaching the control plane so the answer
/// comes from the authority on it.
#[must_use]
pub(crate) fn is_identifier(value: &str) -> bool {
    let value = value.trim();
    if value.is_empty() {
        return false;
    }
    let numeric = value.bytes().all(|byte| byte.is_ascii_digit());
    let node_id = value.len() > "nCNTRL".len()
        && value.starts_with('n')
        && value.ends_with("CNTRL")
        && value[1..value.len() - "CNTRL".len()]
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric());
    numeric || node_id
}

/// The identifier the control plane accepts for whatever the caller named.
///
/// The instructions promise a device can be named by its address or its
/// MagicDNS name, and on the local surface the CLI makes that true. Here it is
/// true because of this: anything that is not already an identifier is looked
/// up in the tailnet's own listing.
///
/// It refuses rather than guesses. Hostnames are not unique — two machines
/// called `macbook-air` is an ordinary state of affairs — and picking one of
/// them is how the wrong device gets deleted. A caller given the candidates can
/// retry unambiguously; a caller given a silent choice cannot.
pub(crate) async fn resolve(ctx: &ToolContext, given: &str) -> ToolResult<String> {
    if is_identifier(given) {
        return Ok(given.trim().to_owned());
    }
    let wanted = given.trim().to_ascii_lowercase();
    let devices = ctx.tailnet_devices().await?;
    let mut found = devices.iter().filter(|device| device.answers_to(&wanted));
    let Some(first) = found.next() else {
        return Err(ToolError::not_found(&format!(
            "no device in this tailnet is called `{given}`; the name, the hostname, the \
             MagicDNS name and the addresses were all checked"
        ))
        .with_hint("`tailnet_device_list` names every device this credential can see."));
    };
    let rest: Vec<&str> = found
        .map(|device| device.node_id.as_str())
        .take(4)
        .collect();
    if rest.is_empty() {
        return Ok(first.node_id.clone());
    }
    let mut named = vec![first.node_id.as_str()];
    named.extend(rest);
    Err(ToolError::invalid_args(format!(
        "`{given}` names more than one device in this tailnet: {}. Give one of those node \
         ids instead.",
        named.join(", ")
    )))
}

pub(crate) fn device_path(device: &str, rest: &str) -> ToolResult<String> {
    let id = device_id("device_id", device)?;
    Ok(format!("/api/v2/device/{id}{rest}"))
}

/// A device identifier, checked and trimmed.
///
/// Wraps [`path_segment`] under a name that fits both its uses: most of these
/// identifiers become a path segment, and the batch attribute update's become
/// keys in a body. The check wanted is the same either way — an identifier and
/// not something that reshapes what it is put into — and `what` names the
/// parameter it came from, so a refusal points at the caller's own argument.
fn device_id(what: &str, device: &str) -> ToolResult<String> {
    path_segment(what, device)
}

/// The same, for the one endpoint that also names an attribute.
fn attribute_path(device: &str, key: &str) -> ToolResult<String> {
    let key = path_segment("attribute_key", key)?;
    if !key.starts_with("custom:") {
        return Err(ToolError::invalid_args(format!(
            "`attribute_key` has to begin with `custom:`; `{key}` is one of Tailscale's own \
             attributes, which are read-only"
        ))
        .with_hint("Prefix the name with `custom:`, as in `custom:diskEncrypted`."));
    }
    device_path(device, &format!("/attributes/{key}"))
}

// ---------------------------------------------------------------------------
// Listing
// ---------------------------------------------------------------------------

/// One filter value, or several for the same field.
///
/// The API ANDs repeated parameters — `tags=tag:prod&tags=tag:subnet` selects
/// devices carrying both — so a map of one value per field could not express
/// half of what the endpoint offers. Either spelling is accepted because the
/// single value is much the commoner and `["tag:prod"]` is a worse way to
/// write it.
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum Filter {
    One(String),
    Several(Vec<String>),
}

impl Filter {
    fn values(&self) -> &[String] {
        match self {
            Self::One(value) => std::slice::from_ref(value),
            Self::Several(values) => values,
        }
    }
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeviceListParams {
    /// Which fields each device carries: `default` for the common ones, `all`
    /// to add posture identity and client connectivity. Omit for `default`.
    #[serde(default)]
    pub fields: Option<String>,
    /// Server-side filters, as field name to value, combined with AND — for
    /// example `{"isEphemeral": "true", "tags": ["tag:prod", "tag:subnet"]}`
    /// selects ephemeral devices carrying both tags. The field names are
    /// Tailscale's own, as they appear in a device.
    #[serde(default)]
    pub filters: Option<std::collections::BTreeMap<String, Filter>>,
    /// Return at most this many devices. Applied here rather than by the
    /// control plane, which has no pagination: the whole listing is fetched
    /// and this limits what is passed on. It cannot rescue a listing too large
    /// for the result cap, which is applied to the answer as it arrives.
    #[serde(default)]
    pub limit: Option<usize>,
    /// Skip this many devices before `limit` applies.
    #[serde(default)]
    pub offset: Option<usize>,
}

/// What a windowed listing answers with.
///
/// Only a *windowed* one: without `limit` or `offset` the answer is the
/// control plane's own, forwarded whole (ADR-0004). The counts exist because
/// the API sends none, so without them a truncated list and a short tailnet
/// look identical (Q69).
#[derive(Debug, Serialize)]
struct DeviceListReport {
    devices: Vec<Value>,
    window: Window,
}

#[derive(Debug, Serialize)]
struct Window {
    /// How many the control plane sent, before the window.
    total: usize,
    /// How many are in `devices`.
    returned: usize,
    offset: usize,
    /// The limit asked for, so that an empty page is legible: `returned: 0`
    /// with a limit of zero is one thing and an offset past the end another.
    #[serde(skip_serializing_if = "Option::is_none")]
    limit: Option<usize>,
}

async fn device_list(ctx: &ToolContext, params: DeviceListParams) -> ToolResult<Value> {
    let client = ctx.tailnet()?;
    let fields = checked_fields(params.fields.as_deref())?;
    let mut request = client
        .get(client.tailnet_path(None, "/devices"))
        .maybe_query("fields", fields);
    for (name, filter) in params.filters.iter().flatten() {
        // The API's filters are `<field>=<value>` pairs alongside `fields`, so
        // a caller could shadow it by naming it here. That would be a filter
        // silently changing which fields came back, so it is refused.
        if name == "fields" {
            return Err(ToolError::invalid_args(
                "`fields` is its own parameter and cannot also be a filter",
            ));
        }
        for value in filter.values() {
            request = request.query(name, value);
        }
    }
    let answer = request.send_as::<Value>().await?;

    // Unwindowed, the answer is the control plane's, forwarded whole. Reading
    // `devices` out and rebuilding around it would drop any other key the
    // control plane sent and would report an empty tailnet for an answer whose
    // shape had changed, which is the opposite of what ADR-0004 asks for.
    match (params.limit, params.offset.unwrap_or(0)) {
        (None, 0) => Ok(answer),
        (limit, offset) => window(answer, limit, offset),
    }
}

/// Slice a listing, keeping its shape.
///
/// Refuses rather than guesses when the answer is not the shape the window
/// needs: a body with no `devices` array is one this build does not
/// understand, and windowing it would mean answering with an empty list.
fn window(answer: Value, limit: Option<usize>, offset: usize) -> ToolResult<Value> {
    let Some(all) = answer.get("devices").and_then(Value::as_array) else {
        return Err(ToolError::new(
            crate::error::ErrorCode::ApiError,
            "the control plane answered without a `devices` list, so there is nothing to window",
        )
        .with_hint("Call again without `limit` or `offset` to see the answer as it arrived."));
    };
    let total = all.len();
    let taken = all.iter().skip(offset);
    let devices: Vec<Value> = match limit {
        Some(limit) => taken.take(limit).cloned().collect(),
        None => taken.cloned().collect(),
    };
    report(DeviceListReport {
        window: Window {
            total,
            returned: devices.len(),
            offset,
            limit,
        },
        devices,
    })
}

/// `fields` is a documented string, so the value is checked against the list
/// beside the model rather than sent onward to be rejected.
fn checked_fields(fields: Option<&str>) -> ToolResult<Option<String>> {
    fields
        .map(|value| one_of("fields", value, DEVICE_FIELDS))
        .transpose()
}

// ---------------------------------------------------------------------------
// One device
// ---------------------------------------------------------------------------

/// A device, and nothing else.
///
/// Separate from [`DeviceGetParams`] rather than one type with an optional
/// `fields`, because a schema is a promise: a parameter a tool advertises and
/// never reads is a caller being told something works when it does nothing.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeviceParams {
    /// The device, by its node id (`n1234567CNTRL`, the `nodeId` in a
    /// listing), its numeric `id`, its MagicDNS name, the short name before
    /// the first dot of that, its hostname, or one of its addresses. A name
    /// matching more than one device is refused rather than guessed at.
    pub device_id: String,
}

/// A device, for an operation that cuts this node off when the device is ours.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SeveringDeviceParams {
    /// The device, by its node id (`n1234567CNTRL`, the `nodeId` in a
    /// listing), its numeric `id`, its MagicDNS name, the short name before
    /// the first dot of that, its hostname, or one of its addresses. A name
    /// matching more than one device is refused rather than guessed at.
    pub device_id: String,
    #[serde(flatten)]
    pub confirmation: SelfConfirmation,
}

/// A device, and which of its fields to read.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeviceGetParams {
    /// The device, by its node id (`n1234567CNTRL`, the `nodeId` in a
    /// listing), its numeric `id`, its MagicDNS name, the short name before
    /// the first dot of that, its hostname, or one of its addresses. A name
    /// matching more than one device is refused rather than guessed at.
    pub device_id: String,
    /// Which fields to return: `default` for the common ones, `all` to add
    /// posture identity and client connectivity.
    #[serde(default)]
    pub fields: Option<String>,
}

async fn device_get(ctx: &ToolContext, params: DeviceGetParams) -> ToolResult<Value> {
    let device = resolve(ctx, &params.device_id).await?;
    let client = ctx.tailnet()?;
    let fields = checked_fields(params.fields.as_deref())?;
    Ok(client
        .get(device_path(&device, "")?)
        .maybe_query("fields", fields)
        .send_as::<Value>()
        .await?)
}

async fn device_delete(ctx: &ToolContext, params: SeveringDeviceParams) -> ToolResult<Value> {
    let device = resolve_not_ourselves(
        ctx,
        "removing it from the tailnet",
        &params.device_id,
        &params.confirmation,
    )
    .await?;
    let client = ctx.tailnet()?;
    client.delete(device_path(&device, "")?).send().await?;
    report(Done::new("deleted").about("device_id", params.device_id))
}

async fn device_expire(ctx: &ToolContext, params: SeveringDeviceParams) -> ToolResult<Value> {
    let device = resolve_not_ourselves(
        ctx,
        "expiring its node key",
        &params.device_id,
        &params.confirmation,
    )
    .await?;
    let client = ctx.tailnet()?;
    client.post(device_path(&device, "/expire")?).send().await?;
    report(Done::new("key expired").about("device_id", params.device_id))
}

// ---------------------------------------------------------------------------
// Changing a device
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeviceAuthorizeParams {
    /// The device, by node id, numeric id, MagicDNS name, short name,
    /// hostname or address.
    pub device_id: String,
    /// `true` to authorise, `false` to revoke an existing authorisation.
    pub authorized: bool,
    #[serde(flatten)]
    pub confirmation: SelfConfirmation,
}

async fn device_authorize(ctx: &ToolContext, params: DeviceAuthorizeParams) -> ToolResult<Value> {
    // The inventory classifies this endpoint WRITE and ticket 17 says
    // "de-authorisation are destructive". Both are right about different
    // calls, so the row carries the floor and the call decides (Q70) — the
    // same arrangement the passthrough uses, and what `varying: true` means.
    if !params.authorized {
        // The tier first: a session that may not do this at all should hear
        // that, not be asked to confirm something it would then be refused.
        require_destructive(ctx, "revoking a device's authorisation")?;
        // Only revoking can sever: authorising this node changes nothing about
        // the connection the caller is already using.
        not_at_ourselves(
            ctx,
            "revoking its authorisation",
            &params.device_id,
            &params.confirmation,
        )
        .await?;
    }
    let device = resolve(ctx, &params.device_id).await?;
    if !params.authorized {
        neither_names_us(
            ctx,
            "revoking its authorisation",
            &params.device_id,
            &device,
            &params.confirmation,
        )
        .await?;
    }
    let client = ctx.tailnet()?;
    client
        .post(device_path(&device, "/authorized")?)
        .json(&json!({"authorized": params.authorized}))
        .send()
        .await?;
    report(
        Done::new(if params.authorized {
            "authorized"
        } else {
            "authorization revoked"
        })
        .about("device_id", params.device_id),
    )
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeviceRenameParams {
    /// The device, by node id, numeric id, MagicDNS name, short name,
    /// hostname or address.
    pub device_id: String,
    /// The new name. The control plane derives the MagicDNS name from it.
    pub name: String,
    #[serde(flatten)]
    pub confirmation: SelfConfirmation,
}

async fn device_rename(ctx: &ToolContext, params: DeviceRenameParams) -> ToolResult<Value> {
    // A rename does not drop the connection the caller is on, but it does take
    // away the name it dialled: anything that reconnects by MagicDNS stops
    // finding this node. That is the same loss as an address change, arriving
    // one round-trip later (Q88).
    let device =
        resolve_not_ourselves(ctx, "renaming it", &params.device_id, &params.confirmation).await?;
    let client = ctx.tailnet()?;
    client
        .post(device_path(&device, "/name")?)
        .json(&json!({"name": params.name}))
        .send()
        .await?;
    report(Done::new("renamed").about("device_id", params.device_id))
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeviceTagsParams {
    /// The device, by node id, numeric id, MagicDNS name, short name,
    /// hostname or address.
    pub device_id: String,
    /// The complete set of tags, each `tag:` prefixed. An empty list removes
    /// every tag, which returns the device to its owner's identity.
    pub tags: Vec<String>,
    #[serde(flatten)]
    pub confirmation: SelfConfirmation,
}

async fn device_tags_set(ctx: &ToolContext, params: DeviceTagsParams) -> ToolResult<Value> {
    // Retagging replaces the whole set, and a policy rule that granted
    // this caller its route in through one of the old tags stops applying.
    let device = resolve_not_ourselves(
        ctx,
        "replacing its tags",
        &params.device_id,
        &params.confirmation,
    )
    .await?;
    let client = ctx.tailnet()?;
    client
        .post(device_path(&device, "/tags")?)
        .json(&json!({"tags": params.tags}))
        .send()
        .await?;
    report(Done::new("tags set").about("device_id", params.device_id))
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeviceKeyExpiryParams {
    /// The device, by node id, numeric id, MagicDNS name, short name,
    /// hostname or address.
    pub device_id: String,
    /// `true` to stop the device's key expiring, `false` to let it expire on
    /// the tailnet's schedule again.
    pub key_expiry_disabled: bool,
}

async fn device_key_expiry_set(
    ctx: &ToolContext,
    params: DeviceKeyExpiryParams,
) -> ToolResult<Value> {
    let device = resolve(ctx, &params.device_id).await?;
    let client = ctx.tailnet()?;
    client
        .post(device_path(&device, "/key")?)
        .json(&json!({"keyExpiryDisabled": params.key_expiry_disabled}))
        .send()
        .await?;
    report(
        Done::new(if params.key_expiry_disabled {
            "key expiry disabled"
        } else {
            "key expiry enabled"
        })
        .about("device_id", params.device_id),
    )
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeviceIpParams {
    /// The device, by node id, numeric id, MagicDNS name, short name,
    /// hostname or address.
    pub device_id: String,
    /// The new IPv4 address, from the tailnet's own range.
    pub ipv4: String,
    #[serde(flatten)]
    pub confirmation: SelfConfirmation,
}

async fn device_ip_set(ctx: &ToolContext, params: DeviceIpParams) -> ToolResult<Value> {
    let device = resolve_not_ourselves(
        ctx,
        "moving it to another address",
        &params.device_id,
        &params.confirmation,
    )
    .await?;
    let client = ctx.tailnet()?;
    client
        .post(device_path(&device, "/ip")?)
        .json(&json!({"ipv4": params.ipv4}))
        .send()
        .await?;
    report(Done::new("address set").about("device_id", params.device_id))
}

// ---------------------------------------------------------------------------
// Routes
// ---------------------------------------------------------------------------

async fn device_routes_get(ctx: &ToolContext, params: DeviceParams) -> ToolResult<Value> {
    let device = resolve(ctx, &params.device_id).await?;
    let client = ctx.tailnet()?;
    Ok(client
        .get(device_path(&device, "/routes")?)
        .send_as::<Value>()
        .await?)
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeviceRoutesParams {
    /// The device, by node id, numeric id, MagicDNS name, short name,
    /// hostname or address.
    pub device_id: String,
    /// The complete set of enabled routes, as CIDR blocks. An empty list
    /// disables every route the device advertises.
    pub routes: Vec<String>,
    #[serde(flatten)]
    pub confirmation: SelfConfirmation,
}

async fn device_routes_set(ctx: &ToolContext, params: DeviceRoutesParams) -> ToolResult<Value> {
    // A caller reached over a subnet this node advertises loses its route
    // in when the route stops being enabled.
    let device = resolve_not_ourselves(
        ctx,
        "changing which of its routes are enabled",
        &params.device_id,
        &params.confirmation,
    )
    .await?;
    let client = ctx.tailnet()?;
    // This one answers with the routes it settled on, which is worth more to a
    // caller than a report that it worked.
    Ok(client
        .post(device_path(&device, "/routes")?)
        .json(&json!({"routes": params.routes}))
        .send_as::<Value>()
        .await?)
}

// ---------------------------------------------------------------------------
// Posture attributes
// ---------------------------------------------------------------------------

async fn device_attributes_get(ctx: &ToolContext, params: DeviceParams) -> ToolResult<Value> {
    let device = resolve(ctx, &params.device_id).await?;
    let client = ctx.tailnet()?;
    Ok(client
        .get(device_path(&device, "/attributes")?)
        .send_as::<Value>()
        .await?)
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct AttributeParams {
    /// The device, by node id, numeric id, MagicDNS name, short name,
    /// hostname or address.
    pub device_id: String,
    /// The attribute's name, which has to begin `custom:`.
    pub attribute_key: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct AttributeSetParams {
    /// The device, by node id, numeric id, MagicDNS name, short name,
    /// hostname or address.
    pub device_id: String,
    /// The attribute's name, which has to begin `custom:`.
    pub attribute_key: String,
    /// The value: a string, a number or a boolean. The type is fixed by the
    /// first write to this key.
    pub value: Value,
    /// When the control plane should forget the attribute, as RFC 3339. Omit
    /// for one that does not expire.
    #[serde(default)]
    pub expiry: Option<String>,
    /// A note recorded with the change, which the audit log keeps.
    #[serde(default)]
    pub comment: Option<String>,
}

async fn device_attribute_set(ctx: &ToolContext, params: AttributeSetParams) -> ToolResult<Value> {
    let device = resolve(ctx, &params.device_id).await?;
    let client = ctx.tailnet()?;
    let path = attribute_path(&device, &params.attribute_key)?;
    let mut body = json!({"value": params.value});
    if let Some(expiry) = &params.expiry {
        body["expiry"] = json!(expiry);
    }
    if let Some(comment) = &params.comment {
        body["comment"] = json!(comment);
    }
    // The one write among these the description gives a body: a `200` holding
    // the device's attributes as they now stand. That is worth more to a
    // caller than a report that it worked, so it is forwarded — but the
    // control plane also answers this call with nothing at all, and `null` is
    // not an answer, so an empty body falls back to the report (Q67).
    let answer = client.post(path).json(&body).send().await?;
    answered_or(
        answer,
        Done::new("attribute set")
            .about("device_id", params.device_id)
            .about("attribute_key", params.attribute_key),
    )
}

async fn device_attribute_delete(ctx: &ToolContext, params: AttributeParams) -> ToolResult<Value> {
    let device = resolve(ctx, &params.device_id).await?;
    let client = ctx.tailnet()?;
    let path = attribute_path(&device, &params.attribute_key)?;
    client.delete(path).send().await?;
    report(
        Done::new("attribute deleted")
            .about("device_id", params.device_id)
            .about("attribute_key", params.attribute_key),
    )
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct AttributesBatchParams {
    /// Device id to attribute map. Each attribute name has to begin `custom:`;
    /// each value is a string, number, boolean, `null` to delete it, or
    /// `{"value": ..., "expiry": "<RFC 3339>"}`.
    pub nodes: std::collections::BTreeMap<String, std::collections::BTreeMap<String, Value>>,
    /// A note recorded with the change, which the audit log keeps.
    #[serde(default)]
    pub comment: Option<String>,
}

async fn device_attributes_update(
    ctx: &ToolContext,
    params: AttributesBatchParams,
) -> ToolResult<Value> {
    let client = ctx.tailnet()?;
    if params.nodes.is_empty() {
        return Err(ToolError::invalid_args(
            "`nodes` names no devices, so there is nothing to change",
        ));
    }
    // Checked before anything is sent, because the call is all-or-nothing: one
    // bad key among a hundred devices would fail the whole batch after it had
    // gone, and the refusal here names the device and the key. The checked
    // spelling is what is sent, so an id the caller padded is the id it meant.
    let mut nodes = std::collections::BTreeMap::new();
    let mut changed = 0usize;
    for (device, attributes) in &params.nodes {
        // Named the same way as everywhere else: a caller who may write
        // `laptop` for one device should not have to write a node id here
        // because there are several. One listing serves the whole batch.
        let device = device_id("nodes", &resolve(ctx, device).await?)?;
        for key in attributes.keys() {
            if !key.starts_with("custom:") {
                return Err(ToolError::invalid_args(format!(
                    "`{key}` on `{device}` does not begin with `custom:`; only custom attributes \
                     can be set"
                )));
            }
        }
        changed += attributes.len();
        nodes.insert(device, attributes);
    }
    let devices = nodes.len();
    let mut body = json!({"nodes": nodes});
    if let Some(comment) = &params.comment {
        body["comment"] = json!(comment);
    }
    client
        .patch(client.tailnet_path(None, "/device-attributes"))
        .json(&body)
        .send()
        .await?;
    report(
        Done::new("attributes updated")
            .about("devices", devices)
            .about("attributes", changed),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_device_is_addressed_globally_rather_than_through_a_tailnet() {
        // The path a device endpoint takes has no tailnet in it: the id is
        // unique across tailnets and the control plane resolves the rest.
        assert_eq!(
            device_path("n1234567CNTRL", "/routes").expect("a valid id"),
            "/api/v2/device/n1234567CNTRL/routes"
        );
        assert_eq!(
            device_path("123456789", "").expect("the numeric form is valid too"),
            "/api/v2/device/123456789"
        );
    }

    #[test]
    fn an_identifier_that_would_rewrite_the_path_is_refused() {
        // The reason `path_segment` exists. Escaping these would send a call
        // that fails somewhere less legible; refusing says which argument.
        for bad in [
            "n123/../tailnet/-/devices",
            "n123?fields=all",
            "n123 456",
            "",
        ] {
            let error = device_path(bad, "").expect_err("{bad} should be refused");
            assert_eq!(
                serde_json::to_value(&error).expect("reportable")["code"],
                json!("invalid_args"),
                "{bad}"
            );
        }
    }

    #[test]
    fn an_attribute_this_server_may_not_set_is_refused_before_the_call() {
        let error = attribute_path("n1", "node:os").expect_err("not a custom attribute");
        let reported = serde_json::to_value(&error).expect("reportable");
        assert_eq!(reported["code"], json!("invalid_args"));
        assert!(
            reported["message"]
                .as_str()
                .is_some_and(|m| m.contains("custom:")),
            "{reported:#?}"
        );
        assert_eq!(
            attribute_path("n1", "custom:diskEncrypted").expect("a custom one"),
            "/api/v2/device/n1/attributes/custom:diskEncrypted"
        );
    }

    #[test]
    fn the_field_selection_is_checked_against_the_list_beside_the_model() {
        assert_eq!(checked_fields(None).expect("absent is fine"), None);
        assert_eq!(
            checked_fields(Some("all"))
                .expect("a known value")
                .as_deref(),
            Some("all")
        );
        let error = checked_fields(Some("everything")).expect_err("not a known value");
        assert!(
            serde_json::to_value(&error).expect("reportable")["message"]
                .as_str()
                .is_some_and(|m| m.contains("all") && m.contains("default")),
            "the refusal should quote the values: {error:?}"
        );
    }
}