Repository navigation
Expand file tree
/
Copy pathtools.go
More file actions
778 lines (724 loc) · 27.8 KB
/
Copy pathtools.go
File metadata and controls
778 lines (724 loc) · 27.8 KB
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
package pluginsdk
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"regexp"
"slices"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
// Toolset is an optional Source extension for plugins that let Marmot tasks
// read and change the systems they catalogue. Tools are what a task may do
// through the plugin, and only a task run may ask for one: every request
// names its run in Origin. Tools are typed and allow-listed: the manifest
// Tools returns is the whole of what the plugin can do, a caller only
// picks one and fills its declared parameters, and there is never a
// free-form command.
//
// Tools runs once, when Serve starts, and must return the same manifest on
// every call: hosts pin it by ManifestDigest, so a manifest that varied with
// config or time would never match what was approved.
//
// PlanTool is a dry run and must have no side effects for any input: hosts
// plan before deciding whether the caller may act at all. It returns what
// would change and a Precondition naming the exact state it looked at.
// ExecuteTool must refuse when that state has moved on, so what runs is
// what was previewed.
//
// Serve checks every request against the manifest (ValidateParams, the
// origin and identity stamps, a precondition on execute) before either
// method sees it, so a plugin cannot forget to. Plugins whose Source
// implements Toolset are surfaced via Meta.SupportsTools.
type Toolset interface {
Tools() []ToolSpec
PlanTool(ctx context.Context, config RawConfig, req ToolRequest) (*ToolPlan, error)
ExecuteTool(ctx context.Context, config RawConfig, req ToolRequest) (*ToolResult, error)
}
// TargetKind names the kind of object a tool changes, as
// "<technology>/<kind>" in lower case, such as "kubernetes/deployment", so
// policy can scope tools by what they touch without knowing the plugin.
type TargetKind string
// Reversibility says whether a tool's effect can be taken back.
type Reversibility string
const (
// ReversibilityReversible tools have an Inverse that restores the
// previous state, and ExecuteTool returns it filled in as Undo.
ReversibilityReversible Reversibility = "reversible"
// ReversibilitySelfHealing tools disturb a system that returns to
// the same steady state by itself, such as restarting a workload.
ReversibilitySelfHealing Reversibility = "self_healing"
// ReversibilityIrreversible tools cannot be undone.
ReversibilityIrreversible Reversibility = "irreversible"
// ReversibilityReadOnly tools change nothing: they read the system
// and return what they saw in ToolResult.Output. They are always
// RiskRead, and the two are valid only together, so a host gating on
// either cannot be told one thing by the risk and another by the
// reversibility.
ReversibilityReadOnly Reversibility = "read_only"
)
// RiskTier ranks how much harm a tool can do, for policy to gate on.
type RiskTier int
const (
// RiskRead changes nothing. A read tool has no plan and needs no
// precondition: ExecuteTool is the read, and its output is capped at
// MaxReadOutputBytes.
RiskRead RiskTier = 0
// RiskBounded is reversible and limited in effect.
RiskBounded RiskTier = 1
// RiskCostly is irreversible, or reversible but able to cause an
// outage or spend money, such as scaling to zero or to many replicas.
RiskCostly RiskTier = 2
// RiskDestructive can destroy production state.
RiskDestructive RiskTier = 3
)
// ParamType is the type of one tool parameter. There is deliberately no
// object, list or free text type: every value is a scalar the manifest bounds.
type ParamType string
const (
ParamString ParamType = "string"
ParamInt ParamType = "int"
ParamBool ParamType = "bool"
ParamEnum ParamType = "enum"
// ParamEnumList and ParamStringList are lists of distinct values, for
// trigger parameters only, such as the kinds or namespaces a trigger
// watches. Tools take scalars alone, so a tool's parameters
// never grow into a batch. A list takes MaxItems, and its elements
// the bounds of the matching scalar type.
ParamEnumList ParamType = "enum_list"
ParamStringList ParamType = "string_list"
)
// MaxListParamItems caps every list parameter, whatever its MaxItems.
const MaxListParamItems = 64
// MaxReadOutputBytes caps the JSON encoding of a read tool's result.
// Serve refuses a larger one rather than truncate it, so a read cannot
// flood the host and a host never mistakes a cut-off answer for a whole one.
const MaxReadOutputBytes = 256 << 10
// MaxStringParamLength caps every string tool parameter, whatever its
// MaxLength, so no parameter can carry a payload.
const MaxStringParamLength = 1024
// MaxTriggerStringParamLength caps a string trigger parameter, which may
// hold an expression the runner's operator wrote, such as a CEL condition.
const MaxTriggerStringParamLength = 4096
// ToolSpec declares one tool. Every field is part of the manifest digest,
// so a field added here must be omitempty or every existing digest changes.
type ToolSpec struct {
// Name is the tool's identifier, snake_case, such as "scale".
Name string `json:"name"`
// Version is bumped whenever the tool's meaning changes, so a policy
// written against one version does not silently cover the next.
Version int `json:"version"`
Title string `json:"title"`
Description string `json:"description"`
// Targets lists every kind of object the tool can change.
Targets []TargetKind `json:"targets"`
Params []ToolParam `json:"params,omitempty"`
Reversibility Reversibility `json:"reversibility"`
Risk RiskTier `json:"risk"`
// Inverse names the tool that undoes this one, and is set exactly
// when Reversibility is ReversibilityReversible.
Inverse string `json:"inverse,omitempty"`
}
// ToolParam declares one typed, bounded parameter. An int needs Min and
// Max, a string needs MaxLength and may set Pattern, which must match the
// whole value, and an enum needs Enum.
type ToolParam struct {
Name string `json:"name"`
Description string `json:"description"`
Type ParamType `json:"type"`
Required bool `json:"required,omitempty"`
Min int64 `json:"min,omitempty"`
Max int64 `json:"max,omitempty"`
MaxLength int `json:"max_length,omitempty"`
Pattern string `json:"pattern,omitempty"`
Enum []string `json:"enum,omitempty"`
// MaxItems bounds a list parameter and is set only on one.
MaxItems int `json:"max_items,omitempty"`
// Multiline lets a tool's string parameter hold line breaks and tabs,
// for text a plugin writes into a file and shows as a diff in its plan
// before anything changes. No other control character is accepted,
// carriage returns included, and MaxLength still bounds it. It is part
// of the manifest, so a runner that pinned a manifest notices a plugin
// that starts accepting it.
Multiline bool `json:"multiline,omitempty"`
}
// ToolRequest asks a plugin to plan or execute one tool.
type ToolRequest struct {
Tool string `json:"tool"`
Params map[string]any `json:"params,omitempty"`
// Identity is the acting principal's audit subject, such as
// "user:alice@example.com".
Identity string `json:"identity"`
// Origin is the task run that asked for the tool, as
// TaskRunOrigin followed by the run's id, such as "task_run:<uuid>".
// The plugin stamps it on every change and call it makes, so a change
// in the target system can be traced back to the run that made it.
Origin string `json:"origin"`
// Precondition is the token from the ToolPlan being executed.
// ExecuteTool refuses to run without one, and the plugin refuses
// when the target's state no longer matches it.
Precondition string `json:"precondition,omitempty"`
// DryRun is set by Serve: true for PlanTool and false for
// ExecuteTool, whatever the caller sent, so a plugin sharing code
// between the two can branch on it. ExecuteTool refuses a request
// that asks for a dry run rather than quietly running it for real.
DryRun bool `json:"dry_run,omitempty"`
}
// ToolPlan is what a tool would do. Before and After hold only the
// fields that change, Diff renders the same change for people, and
// Precondition binds a later execution to the state this plan looked at.
type ToolPlan struct {
// Target identifies the object, such as "deployment/payments/api".
Target string `json:"target"`
TargetKind TargetKind `json:"target_kind"`
Summary string `json:"summary"`
Before json.RawMessage `json:"before,omitempty"`
After json.RawMessage `json:"after,omitempty"`
Diff string `json:"diff,omitempty"`
// Precondition is opaque to the host, such as a resourceVersion.
Precondition string `json:"precondition"`
Warnings []string `json:"warnings,omitempty"`
}
// ToolResult is what an executed tool did. Undo is the inverse tool
// with its parameters filled in, ready to plan, or nil when the tool is not
// reversible; it carries no identity, origin or precondition, which whoever
// undoes it supplies.
type ToolResult struct {
Target string `json:"target"`
TargetKind TargetKind `json:"target_kind"`
Summary string `json:"summary"`
Before json.RawMessage `json:"before,omitempty"`
After json.RawMessage `json:"after,omitempty"`
Undo *ToolRequest `json:"undo,omitempty"`
Warnings []string `json:"warnings,omitempty"`
// Output is a read tool's answer as JSON, and empty for any other.
Output json.RawMessage `json:"output,omitempty"`
// Untrusted says Output carries text that people or programs in the
// target system can write, such as log lines or event messages. A host
// shows it as data and never follows instructions found in it.
Untrusted bool `json:"untrusted,omitempty"`
}
// StringParam returns a string or enum parameter, or "" when it is absent.
func (r ToolRequest) StringParam(name string) string {
s, _ := r.Params[name].(string)
return s
}
// IntParam returns an int parameter and whether it was set.
func (r ToolRequest) IntParam(name string) (int64, bool) {
n, err := toInt(r.Params[name])
return n, err == nil
}
// BoolParam returns a bool parameter, or false when it is absent.
func (r ToolRequest) BoolParam(name string) bool {
b, _ := r.Params[name].(bool)
return b
}
var (
// identifierPattern is the shape of tool and parameter names: they
// end up in policy files, audit logs and annotations.
identifierPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,62}$`)
targetKindPattern = regexp.MustCompile(`^[a-z0-9]+/[a-z0-9]+$`)
)
// maxStampLength bounds Identity, Origin and Precondition.
const maxStampLength = 256
// ReadOnly reports whether the tool only reads.
func (s ToolSpec) ReadOnly() bool {
return s.Reversibility == ReversibilityReadOnly && s.Risk == RiskRead
}
// ValidateManifest checks a plugin's tool manifest: unique, well-formed
// names, valid reversibility and risk, an inverse exactly for reversible
// tools that names a tool in the same manifest, risk 0 exactly for
// read_only tools, and every parameter a typed, bounded scalar. Serve
// refuses to start a plugin whose manifest fails.
func ValidateManifest(specs []ToolSpec) error {
names := make(map[string]bool, len(specs))
for _, spec := range specs {
if !identifierPattern.MatchString(spec.Name) {
return fmt.Errorf("tool name %q must be snake_case, at most 63 characters", spec.Name)
}
if names[spec.Name] {
return fmt.Errorf("tool %q is declared twice", spec.Name)
}
names[spec.Name] = true
}
for _, spec := range specs {
if err := validateSpec(spec, names); err != nil {
return fmt.Errorf("tool %q: %w", spec.Name, err)
}
}
// An inverse that only reads would leave the change in place while
// reporting it undone.
for _, spec := range specs {
i := slices.IndexFunc(specs, func(s ToolSpec) bool { return s.Name == spec.Inverse })
if spec.Inverse != "" && i >= 0 && specs[i].ReadOnly() {
return fmt.Errorf("tool %q: its inverse %q only reads", spec.Name, spec.Inverse)
}
}
return nil
}
func validateSpec(spec ToolSpec, names map[string]bool) error {
if spec.Version < 1 {
return fmt.Errorf("version must be at least 1")
}
if spec.Title == "" || spec.Description == "" {
return fmt.Errorf("title and description are required")
}
if len(spec.Targets) == 0 {
return fmt.Errorf("at least one target kind is required")
}
for _, t := range spec.Targets {
if !targetKindPattern.MatchString(string(t)) {
return fmt.Errorf("target kind %q must look like \"kubernetes/deployment\"", t)
}
}
if spec.Risk < RiskRead || spec.Risk > RiskDestructive {
return fmt.Errorf("risk must be 0, 1, 2 or 3")
}
// Risk 0 and read_only mean the same thing and are only valid
// together, so neither can be used to pass a write off as a read.
if (spec.Risk == RiskRead) != (spec.Reversibility == ReversibilityReadOnly) {
return fmt.Errorf("risk 0 and reversibility read_only are only valid together")
}
switch spec.Reversibility {
case ReversibilityReadOnly:
if spec.Inverse != "" {
return fmt.Errorf("a read tool changes nothing, so it has no inverse")
}
case ReversibilityReversible:
if spec.Inverse == "" {
return fmt.Errorf("a reversible tool must name its inverse")
}
if !names[spec.Inverse] {
return fmt.Errorf("inverse %q is not in the manifest", spec.Inverse)
}
case ReversibilitySelfHealing, ReversibilityIrreversible:
if spec.Inverse != "" {
return fmt.Errorf("only a reversible tool has an inverse")
}
// Something that cannot be taken back is never the lowest tier.
if spec.Reversibility == ReversibilityIrreversible && spec.Risk < RiskCostly {
return fmt.Errorf("an irreversible tool must be risk 2 or higher")
}
default:
return fmt.Errorf("reversibility %q is not one of reversible, self_healing, irreversible, read_only", spec.Reversibility)
}
return validateParamSpecs(spec.Params, false)
}
// validateParamSpecs checks declared parameters. Lists, and strings up to
// MaxTriggerStringParamLength, are allowed only when trigger is set: a
// trigger's parameters come from the runner's own policy, never from
// Marmot, and one may carry an expression the operator wrote.
func validateParamSpecs(params []ToolParam, trigger bool) error {
seen := make(map[string]bool, len(params))
for _, p := range params {
if !trigger && (p.Type == ParamEnumList || p.Type == ParamStringList) {
return fmt.Errorf("parameter %q: a tool takes scalar parameters only", p.Name)
}
if !trigger && p.MaxLength > MaxStringParamLength {
return fmt.Errorf("parameter %q: max_length must be between 1 and %d", p.Name, MaxStringParamLength)
}
if p.Multiline && (trigger || p.Type != ParamString) {
return fmt.Errorf("parameter %q: only a tool's string parameter may be multiline", p.Name)
}
if !identifierPattern.MatchString(p.Name) {
return fmt.Errorf("parameter name %q must be snake_case, at most 63 characters", p.Name)
}
if seen[p.Name] {
return fmt.Errorf("parameter %q is declared twice", p.Name)
}
seen[p.Name] = true
if err := validateParamSpec(p); err != nil {
return fmt.Errorf("parameter %q: %w", p.Name, err)
}
}
return nil
}
func validateParamSpec(p ToolParam) error {
if p.Description == "" {
return fmt.Errorf("description is required")
}
isList := p.Type == ParamEnumList || p.Type == ParamStringList
if isList {
if p.MaxItems < 1 || p.MaxItems > MaxListParamItems {
return fmt.Errorf("max_items must be between 1 and %d", MaxListParamItems)
}
// A list is checked as its element type, which takes the rest
// of the bounds.
elem := p
elem.MaxItems = 0
elem.Type = ParamEnum
if p.Type == ParamStringList {
elem.Type = ParamString
}
return validateParamSpec(elem)
}
if p.MaxItems != 0 {
return fmt.Errorf("max_items applies to list parameters only")
}
// Each type takes only its own bounds, so a manifest never declares a
// bound that ValidateParams silently ignores.
stringBounds := p.MaxLength != 0 || p.Pattern != ""
intBounds := p.Min != 0 || p.Max != 0
switch p.Type {
case ParamString:
if intBounds || len(p.Enum) > 0 {
return fmt.Errorf("a string takes max_length and pattern only")
}
if p.MaxLength < 1 || p.MaxLength > MaxTriggerStringParamLength {
return fmt.Errorf("max_length must be between 1 and %d", MaxStringParamLength)
}
if p.Pattern != "" {
if _, err := regexp.Compile(p.Pattern); err != nil {
return fmt.Errorf("pattern does not compile: %w", err)
}
}
case ParamInt:
if stringBounds || len(p.Enum) > 0 {
return fmt.Errorf("an int takes min and max only")
}
if p.Min > p.Max {
return fmt.Errorf("min %d is above max %d", p.Min, p.Max)
}
// Hosts and plugins pass parameters as JSON, whose numbers are
// float64 to most decoders.
if p.Min < -maxSafeInt || p.Max > maxSafeInt {
return fmt.Errorf("bounds must fit in a float64 exactly")
}
case ParamBool:
if stringBounds || intBounds || len(p.Enum) > 0 {
return fmt.Errorf("a bool takes no bounds")
}
case ParamEnum:
if stringBounds || intBounds {
return fmt.Errorf("an enum takes enum values only")
}
if len(p.Enum) == 0 {
return fmt.Errorf("an enum needs at least one value")
}
for i, v := range p.Enum {
if v == "" || len(v) > MaxStringParamLength || hasControl(v) {
return fmt.Errorf("enum value %q is empty, too long or has control characters", v)
}
if slices.Contains(p.Enum[:i], v) {
return fmt.Errorf("enum value %q is listed twice", v)
}
}
default:
return fmt.Errorf("type %q is not one of string, int, bool, enum, enum_list, string_list", p.Type)
}
return nil
}
// maxSafeInt is the largest integer a float64 holds exactly.
const maxSafeInt = 1<<53 - 1
// ValidateParams checks params against a tool's declared parameters:
// every required one present, nothing undeclared, each value of its declared
// type and within its bounds. Hosts call it before asking for a plan and
// Serve calls it again in the plugin, so neither side trusts the other.
func ValidateParams(spec ToolSpec, params map[string]any) error {
return validateParams(spec.Name, spec.Params, params)
}
func validateParams(owner string, specs []ToolParam, params map[string]any) error {
var errs []ValidationError
declared := make(map[string]ToolParam, len(specs))
for _, p := range specs {
declared[p.Name] = p
}
unknown := make([]string, 0)
for name := range params {
if _, ok := declared[name]; !ok {
unknown = append(unknown, name)
}
}
slices.Sort(unknown)
for _, name := range unknown {
errs = append(errs, ValidationError{Field: name, Message: "is not a parameter of " + owner})
}
for _, p := range specs {
v, present := params[p.Name]
if !present {
if p.Required {
errs = append(errs, ValidationError{Field: p.Name, Message: "is required"})
}
continue
}
if err := checkParam(p, v); err != nil {
errs = append(errs, ValidationError{Field: p.Name, Message: err.Error()})
}
}
if len(errs) > 0 {
return ValidationErrors{Errors: errs}
}
return nil
}
func checkParam(p ToolParam, v any) error {
switch p.Type {
case ParamEnumList, ParamStringList:
items, ok := listItems(v)
if !ok {
return fmt.Errorf("must be a list")
}
if len(items) > p.MaxItems {
return fmt.Errorf("must have at most %d items", p.MaxItems)
}
elem := p
elem.Type = ParamEnum
if p.Type == ParamStringList {
elem.Type = ParamString
}
for i, item := range items {
if err := checkParam(elem, item); err != nil {
return fmt.Errorf("item %d %w", i, err)
}
if slices.Contains(items[:i], item) {
return fmt.Errorf("item %d is listed twice", i)
}
}
case ParamString:
s, ok := v.(string)
if !ok {
return fmt.Errorf("must be a string")
}
if len(s) > p.MaxLength {
return fmt.Errorf("must be at most %d bytes", p.MaxLength)
}
if p.Multiline {
if !utf8.ValidString(s) || hasControlBesides(s, "\n\t") || hasHiddenLayout(s) {
return fmt.Errorf("must be valid UTF-8 without control characters other than line breaks and tabs")
}
} else if !utf8.ValidString(s) || hasControl(s) {
return fmt.Errorf("must be valid UTF-8 without control characters")
}
if p.Pattern != "" {
// Anchored here rather than trusted to the author, so a
// pattern written as "[a-z]+" cannot pass "ok; rm -rf".
re, err := regexp.Compile(`^(?:` + p.Pattern + `)$`)
if err != nil {
return fmt.Errorf("pattern does not compile: %w", err)
}
if !re.MatchString(s) {
return fmt.Errorf("must match %s", p.Pattern)
}
}
case ParamEnum:
s, ok := v.(string)
if !ok || !slices.Contains(p.Enum, s) {
return fmt.Errorf("must be one of %s", strings.Join(p.Enum, ", "))
}
case ParamBool:
if _, ok := v.(bool); !ok {
return fmt.Errorf("must be a bool")
}
case ParamInt:
n, err := toInt(v)
if err != nil {
return err
}
if n < p.Min || n > p.Max {
return fmt.Errorf("must be between %d and %d", p.Min, p.Max)
}
default:
return fmt.Errorf("has undeclared type %q", p.Type)
}
return nil
}
// listItems accepts the shapes a list of strings takes after a JSON or
// YAML round trip.
func listItems(v any) ([]any, bool) {
switch l := v.(type) {
case []any:
return l, true
case []string:
out := make([]any, len(l))
for i, s := range l {
out[i] = s
}
return out, true
}
return nil, false
}
// toInt accepts the shapes an integer takes after a JSON round trip, and
// refuses fractions and strings rather than truncating or parsing them.
func toInt(v any) (int64, error) {
switch n := v.(type) {
case int:
return int64(n), nil
case int32:
return int64(n), nil
case int64:
return n, nil
case float64:
if n != math.Trunc(n) || math.Abs(n) > maxSafeInt {
return 0, fmt.Errorf("must be a whole number")
}
return int64(n), nil
case json.Number:
i, err := strconv.ParseInt(string(n), 10, 64)
if err != nil {
return 0, fmt.Errorf("must be a whole number")
}
return i, nil
default:
return 0, fmt.Errorf("must be a whole number")
}
}
// normalizeParams rewrites ints to int64 after ValidateParams has passed, so
// a plugin sees one type whatever decoder the host used.
func normalizeParams(spec ToolSpec, params map[string]any) map[string]any {
return normalize(spec.Params, params)
}
func normalize(specs []ToolParam, params map[string]any) map[string]any {
out := make(map[string]any, len(params))
for _, p := range specs {
v, ok := params[p.Name]
if !ok {
continue
}
switch p.Type {
case ParamInt:
v, _ = toInt(v)
case ParamEnumList, ParamStringList:
items, _ := listItems(v)
list := make([]string, 0, len(items))
for _, item := range items {
list = append(list, item.(string))
}
v = list
}
out[p.Name] = v
}
return out
}
func hasControl(s string) bool {
return strings.IndexFunc(s, unicode.IsControl) >= 0
}
// hasHiddenLayout reports bidirectional controls and Unicode line and
// paragraph separators, which make text read differently from what it is,
// so a multiline value cannot hide what it writes from the diff an approver
// reads.
func hasHiddenLayout(s string) bool {
return strings.IndexFunc(s, func(r rune) bool {
return unicode.Is(unicode.Bidi_Control, r) || unicode.In(r, unicode.Zl, unicode.Zp)
}) >= 0
}
// hasControlBesides is hasControl allowing the characters in allowed.
func hasControlBesides(s, allowed string) bool {
return strings.IndexFunc(s, func(r rune) bool { return unicode.IsControl(r) && !strings.ContainsRune(allowed, r) }) >= 0
}
// checkStamp bounds the values a plugin writes into audit trails, headers
// and annotations: printable ASCII with no spaces, so none can split a
// header or a log line.
func checkStamp(field, v string, required bool) error {
if v == "" {
if required {
return fmt.Errorf("%s is required", field)
}
return nil
}
if len(v) > maxStampLength {
return fmt.Errorf("%s must be at most %d characters", field, maxStampLength)
}
for i := 0; i < len(v); i++ {
if v[i] < 0x21 || v[i] > 0x7e {
return fmt.Errorf("%s must be printable ASCII without spaces", field)
}
}
return nil
}
// TaskRunOrigin prefixes the Origin of every tool request: tools are
// only ever asked for by a task run.
const TaskRunOrigin = "task_run:"
// CheckToolRequest is everything Serve checks before a plugin sees a
// request: the tool is in the manifest, its parameters validate, and it
// carries an identity and a task run origin. Executing a write also needs a
// precondition and must not ask for a dry run. A read is never planned,
// since it has nothing to preview, and needs no precondition, since it
// changes no state that one could bind. Hosts can call it to refuse early.
func CheckToolRequest(specs []ToolSpec, req ToolRequest, execute bool) (ToolSpec, error) {
i := slices.IndexFunc(specs, func(s ToolSpec) bool { return s.Name == req.Tool })
if i < 0 {
return ToolSpec{}, fmt.Errorf("tool %q is not in the plugin's manifest", req.Tool)
}
spec := specs[i]
if err := checkStamp("identity", req.Identity, true); err != nil {
return spec, err
}
if err := checkStamp("origin", req.Origin, true); err != nil {
return spec, err
}
if !strings.HasPrefix(req.Origin, TaskRunOrigin) || len(req.Origin) == len(TaskRunOrigin) {
return spec, fmt.Errorf("origin %q is not a task run: tools are only run by tasks, as %s<id>", req.Origin, TaskRunOrigin)
}
if !execute && spec.ReadOnly() {
return spec, fmt.Errorf("%s only reads: execute it directly, there is nothing to plan", spec.Name)
}
if err := checkStamp("precondition", req.Precondition, execute && !spec.ReadOnly()); err != nil {
return spec, err
}
if execute && req.DryRun {
return spec, fmt.Errorf("execute was asked for a dry run: plan the tool instead")
}
if err := ValidateParams(spec, req.Params); err != nil {
return spec, fmt.Errorf("parameters of %s: %w", spec.Name, err)
}
return spec, nil
}
// checkUndo vets the Undo a plugin returned, after the tool has already
// run. A bad one is dropped with a warning rather than failing the call,
// which would report a change that happened as one that did not.
func checkUndo(specs []ToolSpec, spec ToolSpec, result *ToolResult) {
if spec.Reversibility != ReversibilityReversible {
if result.Undo != nil {
result.Undo = nil
result.Warnings = append(result.Warnings, "the plugin returned an undo for a tool it declares not reversible; it was dropped")
}
return
}
if result.Undo == nil {
result.Warnings = append(result.Warnings, "the plugin returned no undo for a reversible tool")
return
}
undo := ToolRequest{Tool: result.Undo.Tool, Params: result.Undo.Params}
inverse := slices.IndexFunc(specs, func(s ToolSpec) bool { return s.Name == undo.Tool })
if undo.Tool != spec.Inverse || inverse < 0 {
result.Undo = nil
result.Warnings = append(result.Warnings, fmt.Sprintf("the plugin's undo was not the declared inverse %q; it was dropped", spec.Inverse))
return
}
if err := ValidateParams(specs[inverse], undo.Params); err != nil {
result.Undo = nil
result.Warnings = append(result.Warnings, fmt.Sprintf("the plugin's undo had invalid parameters and was dropped: %v", err))
return
}
undo.Params = normalizeParams(specs[inverse], undo.Params)
result.Undo = &undo
}
// manifestFormat versions the canonical encoding ManifestDigest hashes, so a
// change to that encoding is a visible change of digest rather than a
// silent collision with an old one.
const manifestFormat = 1
// ManifestDigest returns "sha256:<hex>" over a canonical JSON encoding of the
// manifest, sorted by tool name, so a runner can pin the exact set of
// tools it approved and notice any change to them, down to one bound.
func ManifestDigest(specs []ToolSpec) string {
sorted := slices.Clone(specs)
slices.SortFunc(sorted, func(a, b ToolSpec) int { return strings.Compare(a.Name, b.Name) })
if sorted == nil {
sorted = []ToolSpec{}
}
// encoding/json writes struct fields in declaration order and these
// types hold no maps, so the encoding is stable.
data, err := json.Marshal(struct {
Format int `json:"format"`
Tools []ToolSpec `json:"tools"`
}{manifestFormat, sorted})
if err != nil {
panic(fmt.Sprintf("encoding a tool manifest: %v", err))
}
sum := sha256.Sum256(data)
return "sha256:" + hex.EncodeToString(sum[:])
}