-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
335 lines (309 loc) · 11.2 KB
/
Copy pathconfig.go
File metadata and controls
335 lines (309 loc) · 11.2 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
package config
import (
"fmt"
"log"
"os"
"strings"
"gopkg.in/yaml.v3"
)
// Config is the top-level YAML config. See Shared Type Reference in the plan.
type Config struct {
Google GoogleConfig `yaml:"google"`
SnipeIT SnipeITConfig `yaml:"snipe_it"`
Sync SyncConfig `yaml:"sync"`
Licenses LicensesConfig `yaml:"licenses"`
}
type GoogleConfig struct {
CredentialsFile string `yaml:"credentials_file"`
ImpersonateSubject string `yaml:"impersonate_subject"`
CustomerID string `yaml:"customer_id"`
Projection string `yaml:"projection"`
OrgUnitPath string `yaml:"org_unit_path"`
Query string `yaml:"query"`
Scopes []string `yaml:"scopes"`
}
type SnipeITConfig struct {
URL string `yaml:"url"`
APIKey string `yaml:"api_key"`
DefaultStatusID int `yaml:"default_status_id"`
DefaultCategoryID int `yaml:"default_category_id"`
DefaultManufacturerID int `yaml:"default_manufacturer_id"`
CustomFieldsetID int `yaml:"custom_fieldset_id"`
StatusMap map[string]int `yaml:"status_map"`
ManufacturerIDs map[string]int `yaml:"manufacturer_ids"`
}
type SyncConfig struct {
DryRun bool `yaml:"dry_run"`
Force bool `yaml:"force"`
RateLimit RateLimitSetting `yaml:"rate_limit"`
UpdateOnly bool `yaml:"update_only"`
UseCache bool `yaml:"use_cache"`
CacheDir string `yaml:"cache_dir"`
SetName bool `yaml:"set_name"`
NameTemplate string `yaml:"name_template"`
StripModelVendor bool `yaml:"strip_model_vendor"`
AssetTag AssetTagConfig `yaml:"asset_tag"`
FieldMapping map[string]FieldMappingEntry `yaml:"field_mapping"`
Checkout CheckoutConfig `yaml:"checkout"`
Concurrency int `yaml:"concurrency"`
}
// RateLimitSetting names the Snipe-IT plan whose request budget the client
// should pace itself against. Snipe-IT Cloud publishes a per-minute allowance
// per plan, and the client tightens further from the X-Ratelimit-* headers the
// API returns on every response.
//
// Accepted values: "basic" (120/min), "small_business" (240/min), "dedicated"
// (unmetered). The legacy booleans still parse: true is small_business,
// false is dedicated (i.e. no client-side limiting).
type RateLimitSetting string
const (
RateLimitBasic RateLimitSetting = "basic"
RateLimitSmallBusiness RateLimitSetting = "small_business"
RateLimitDedicated RateLimitSetting = "dedicated"
)
// UnmarshalYAML accepts the plan names and the pre-preset booleans.
func (r *RateLimitSetting) UnmarshalYAML(value *yaml.Node) error {
raw := strings.TrimSpace(value.Value)
switch strings.ToLower(raw) {
case "true", "yes", "on":
*r = RateLimitSmallBusiness
return nil
case "false", "no", "off":
*r = RateLimitDedicated
return nil
case "":
*r = ""
return nil
}
*r = RateLimitSetting(strings.ToLower(strings.ReplaceAll(raw, "-", "_")))
return nil
}
type AssetTagConfig struct {
Template string `yaml:"template"`
}
// FieldMappingEntry accepts either a bare string (path only) or a
// {path, transform} mapping in YAML.
type FieldMappingEntry struct {
Path string `yaml:"path"`
Transform string `yaml:"transform"`
}
func (e *FieldMappingEntry) UnmarshalYAML(value *yaml.Node) error {
if value.Kind == yaml.ScalarNode {
e.Path = value.Value
return nil
}
type raw FieldMappingEntry
var r raw
if err := value.Decode(&r); err != nil {
return err
}
*e = FieldMappingEntry(r)
return nil
}
type CheckoutConfig struct {
Enabled bool `yaml:"enabled"`
UseAnnotatedUser bool `yaml:"use_annotated_user"`
FallbackToRecent bool `yaml:"fallback_to_recent"`
RecentUserDomain string `yaml:"recent_user_domain"`
MatchField string `yaml:"match_field"`
Mode string `yaml:"mode"`
}
type LicensesConfig struct {
Enabled bool `yaml:"enabled"`
DefaultLicenseCategoryID int `yaml:"default_license_category_id"`
OrgUnitPaths []string `yaml:"org_unit_paths"`
Chrome map[string]ChromeLicenseConfig `yaml:"chrome"`
Workspace WorkspaceLicenseConfig `yaml:"workspace"`
}
type ChromeLicenseConfig struct {
Name string `yaml:"name"`
Cost float64 `yaml:"cost"`
Reassignable *bool `yaml:"reassignable"`
TermMonths int `yaml:"term_months"`
}
type WorkspaceLicenseConfig struct {
CustomerID string `yaml:"customer_id"`
Products []string `yaml:"products"`
SKUCosts map[string]float64 `yaml:"sku_costs"`
}
// ChromePerpetual reports whether a ChromeOS deviceLicenseType is a perpetual
// (non-reassignable) upgrade. Recurring = fixed-term or annual.
func ChromePerpetual(deviceLicenseType string) bool {
if strings.Contains(strings.ToLower(deviceLicenseType), "fixedterm") {
return false
}
switch deviceLicenseType {
case "enterpriseUpgrade", "kioskUpgrade": // deprecated-annual / kiosk-annual
return false
}
return true
}
// KnownTransforms is the set of transform names accepted in field_mapping.
var KnownTransforms = map[string]bool{
"": true, "bytes_to_gb": true, "bytes_to_gib": true, "bytes_to_mb": true,
"bytes_to_tb": true, "mac_colons": true, "mac_dashes": true,
"bool_yes_no": true, "uppercase": true, "lowercase": true,
"comma_thousands": true, "unix_to_iso": true,
"date_only": true, "datetime": true,
}
// DefaultGoogleScopes are the OAuth scopes requested when google.scopes is not
// configured. The service-account JWT is minted with exactly these, so a scope
// missing here fails with ACCESS_TOKEN_SCOPE_INSUFFICIENT even when the
// domain-wide delegation grant allows it.
//
// This is the single source of truth: google.DefaultScopes returns it, and
// TestDefaultScopesMatchAdminConstants pins the strings to the Admin SDK's own
// constants.
func DefaultGoogleScopes() []string {
return []string{
"https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly",
"https://www.googleapis.com/auth/admin.directory.user.readonly",
}
}
// FullOnlyPaths are gjson path prefixes only populated under projection=full.
var FullOnlyPaths = map[string]bool{
"recentUsers": true, "activeTimeRanges": true, "cpuStatusReports": true,
"cpuInfo": true, "diskVolumeReports": true, "systemRamFreeReports": true,
"deviceFiles": true, "screenshotFiles": true, "lastKnownNetwork": true,
"backlightInfo": true, "fanInfo": true, "bluetoothAdapterInfo": true,
"diskSpaceUsage": true, "tpmVersionInfo": true,
}
// loadConfig reads, applies env overrides + defaults, and validates a config file.
// It does NOT check for the licenses category requirement.
func loadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read config: %w", err)
}
var cfg Config
if err := yaml.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}
cfg.applyEnv()
cfg.applyDefaults()
if err := cfg.Validate(); err != nil {
return nil, err
}
return &cfg, nil
}
// Load reads, validates, and returns the config. It additionally requires a
// license category id once license cost sync is enabled.
func Load(path string) (*Config, error) {
c, err := loadConfig(path)
if err != nil {
return nil, err
}
if c.Licenses.Enabled && c.Licenses.DefaultLicenseCategoryID == 0 {
return nil, fmt.Errorf("licenses.default_license_category_id is required when licenses.enabled")
}
return c, nil
}
// LoadForSetup is like Load but tolerates licenses.enabled without a category id,
// so `licenses setup` can run before that id is configured.
func LoadForSetup(path string) (*Config, error) {
return loadConfig(path)
}
func (c *Config) applyEnv() {
if v := os.Getenv("SNIPE_URL"); v != "" {
c.SnipeIT.URL = v
}
if v := os.Getenv("SNIPE_API_KEY"); v != "" {
c.SnipeIT.APIKey = v
}
if v := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"); v != "" && c.Google.CredentialsFile == "" {
c.Google.CredentialsFile = v
}
if v := os.Getenv("GOOGLE_IMPERSONATE_SUBJECT"); v != "" {
c.Google.ImpersonateSubject = v
}
if v := os.Getenv("GOOGLE_CUSTOMER_ID"); v != "" {
c.Google.CustomerID = v
}
}
func (c *Config) applyDefaults() {
if c.Google.CustomerID == "" {
c.Google.CustomerID = "my_customer"
}
if c.Google.Projection == "" {
c.Google.Projection = "full"
}
c.Google.Projection = strings.ToLower(c.Google.Projection)
if len(c.Google.Scopes) == 0 {
c.Google.Scopes = DefaultGoogleScopes()
}
if c.Sync.CacheDir == "" {
c.Sync.CacheDir = ".cache"
}
if c.Sync.AssetTag.Template == "" {
c.Sync.AssetTag.Template = "{annotatedAssetId}"
}
if c.Sync.Checkout.MatchField == "" {
c.Sync.Checkout.MatchField = "email"
}
if c.Sync.Checkout.Mode == "" {
c.Sync.Checkout.Mode = "assign"
}
if c.Sync.Concurrency == 0 {
c.Sync.Concurrency = 8
}
if c.Sync.RateLimit == "" {
c.Sync.RateLimit = RateLimitSmallBusiness
}
}
// Validate fails fast on missing required fields and bad enum values.
func (c *Config) Validate() error {
if c.Google.CredentialsFile == "" {
return fmt.Errorf("google.credentials_file (or GOOGLE_APPLICATION_CREDENTIALS) is required")
}
if c.Google.ImpersonateSubject == "" {
return fmt.Errorf("google.impersonate_subject is required for domain-wide delegation")
}
if c.Google.Projection != "full" && c.Google.Projection != "basic" {
return fmt.Errorf("google.projection must be full or basic, got %q", c.Google.Projection)
}
if c.SnipeIT.URL == "" {
return fmt.Errorf("snipe_it.url is required")
}
if c.SnipeIT.APIKey == "" {
return fmt.Errorf("snipe_it.api_key is required")
}
switch c.Sync.RateLimit {
case RateLimitBasic, RateLimitSmallBusiness, RateLimitDedicated:
default:
return fmt.Errorf("sync.rate_limit must be one of basic, small_business, dedicated, got %q", c.Sync.RateLimit)
}
if c.SnipeIT.DefaultStatusID == 0 {
return fmt.Errorf("snipe_it.default_status_id is required")
}
if c.SnipeIT.DefaultCategoryID == 0 {
return fmt.Errorf("snipe_it.default_category_id is required")
}
for col, e := range c.Sync.FieldMapping {
if e.Path == "" {
return fmt.Errorf("field_mapping[%s]: empty path", col)
}
if !KnownTransforms[e.Transform] {
return fmt.Errorf("field_mapping[%s]: unknown transform %q", col, e.Transform)
}
if c.Google.Projection == "basic" {
prefix := e.Path
if i := strings.IndexAny(prefix, ".#"); i >= 0 {
prefix = prefix[:i]
}
if FullOnlyPaths[prefix] {
log.Printf("warning: field_mapping[%s] path %q requires projection=full but projection=basic", col, e.Path)
}
}
}
switch c.Sync.Checkout.MatchField {
case "email", "username", "employee_num":
default:
return fmt.Errorf("checkout.match_field must be email|username|employee_num, got %q", c.Sync.Checkout.MatchField)
}
switch c.Sync.Checkout.Mode {
case "assign", "sync", "force":
default:
return fmt.Errorf("checkout.mode must be assign|sync|force, got %q", c.Sync.Checkout.Mode)
}
return nil
}