summaryrefslogtreecommitdiff
path: root/cmd/authelia-gen/cmd_docs_jsonschema.go
blob: 93e9d7df5fd2edebc40ed3baec66be59f3b985a6 (plain)
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
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"strings"

	"github.com/authelia/jsonschema"
	"github.com/spf13/cobra"

	"github.com/authelia/authelia/v4/internal/authentication"
	"github.com/authelia/authelia/v4/internal/configuration/schema"
	"github.com/authelia/authelia/v4/internal/model"
	"github.com/authelia/authelia/v4/internal/utils"
)

func newDocsJSONSchemaCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   pathJSONSchema,
		Short: "Generate docs JSON schema",
		RunE:  rootSubCommandsRunE,

		DisableAutoGenTag: true,
	}

	cmd.AddCommand(newDocsJSONSchemaConfigurationCmd(), newDocsJSONSchemaUserDatabaseCmd(), newDocsJSONSchemaExportsCmd())

	return cmd
}

func newDocsJSONSchemaExportsCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "exports",
		Short: "Generate docs JSON schema for the various exports",
		RunE:  rootSubCommandsRunE,

		DisableAutoGenTag: true,
	}

	cmd.AddCommand(newDocsJSONSchemaExportsTOTPCmd(), newDocsJSONSchemaExportsWebAuthnCmd(), newDocsJSONSchemaExportsIdentifiersCmd())

	return cmd
}

func newDocsJSONSchemaExportsTOTPCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "totp",
		Short: "Generate docs JSON schema for the TOTP exports",
		RunE:  docsJSONSchemaExportsTOTPRunE,

		DisableAutoGenTag: true,
	}

	return cmd
}

func newDocsJSONSchemaExportsWebAuthnCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "webauthn",
		Short: "Generate docs JSON schema for the WebAuthn exports",
		RunE:  docsJSONSchemaExportsWebAuthnRunE,

		DisableAutoGenTag: true,
	}

	return cmd
}

func newDocsJSONSchemaExportsIdentifiersCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "identifiers",
		Short: "Generate docs JSON schema for the identifiers exports",
		RunE:  docsJSONSchemaExportsIdentifiersRunE,

		DisableAutoGenTag: true,
	}

	return cmd
}

func newDocsJSONSchemaConfigurationCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "configuration",
		Short: "Generate docs JSON schema for the configuration",
		RunE:  docsJSONSchemaConfigurationRunE,

		DisableAutoGenTag: true,
	}

	return cmd
}

func newDocsJSONSchemaUserDatabaseCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "user-database",
		Short: "Generate docs JSON schema for the user database",
		RunE:  docsJSONSchemaUserDatabaseRunE,

		DisableAutoGenTag: true,
	}

	return cmd
}

func docsJSONSchemaExportsTOTPRunE(cmd *cobra.Command, args []string) (err error) {
	var version *model.SemanticVersion

	if version, err = readVersion(cmd); err != nil {
		return err
	}

	var (
		dir, file, schemaDir string
	)

	if schemaDir, err = getPFlagPath(cmd.Flags(), cmdFlagRoot, cmdFlagDirSchema); err != nil {
		return err
	}

	if dir, file, err = getJSONSchemaOutputPath(cmd, cmdFlagDocsStaticJSONSchemaExportsTOTP); err != nil {
		return err
	}

	return docsJSONSchemaGenerateRunE(cmd, args, version, schemaDir, &model.TOTPConfigurationDataExport{}, dir, file, nil)
}

func docsJSONSchemaExportsWebAuthnRunE(cmd *cobra.Command, args []string) (err error) {
	var version *model.SemanticVersion

	if version, err = readVersion(cmd); err != nil {
		return err
	}

	var (
		dir, file, schemaDir string
	)

	if schemaDir, err = getPFlagPath(cmd.Flags(), cmdFlagRoot, cmdFlagDirSchema); err != nil {
		return err
	}

	if dir, file, err = getJSONSchemaOutputPath(cmd, cmdFlagDocsStaticJSONSchemaExportsWebAuthn); err != nil {
		return err
	}

	return docsJSONSchemaGenerateRunE(cmd, args, version, schemaDir, &model.WebAuthnCredentialDataExport{}, dir, file, nil)
}

func docsJSONSchemaExportsIdentifiersRunE(cmd *cobra.Command, args []string) (err error) {
	var version *model.SemanticVersion

	if version, err = readVersion(cmd); err != nil {
		return err
	}

	var (
		dir, file, schemaDir string
	)

	if schemaDir, err = getPFlagPath(cmd.Flags(), cmdFlagRoot, cmdFlagDirSchema); err != nil {
		return err
	}

	if dir, file, err = getJSONSchemaOutputPath(cmd, cmdFlagDocsStaticJSONSchemaExportsIdentifiers); err != nil {
		return err
	}

	return docsJSONSchemaGenerateRunE(cmd, args, version, schemaDir, &model.UserOpaqueIdentifiersExport{}, dir, file, nil)
}

func docsJSONSchemaConfigurationRunE(cmd *cobra.Command, args []string) (err error) {
	var version *model.SemanticVersion

	if version, err = readVersion(cmd); err != nil {
		return err
	}

	var (
		dir, file, schemaDir string
	)

	if schemaDir, err = getPFlagPath(cmd.Flags(), cmdFlagRoot, cmdFlagDirSchema); err != nil {
		return err
	}

	if dir, file, err = getJSONSchemaOutputPath(cmd, cmdFlagDocsStaticJSONSchemaConfiguration); err != nil {
		return err
	}

	return docsJSONSchemaGenerateRunE(cmd, args, version, schemaDir, &schema.Configuration{}, dir, file, jsonschemaKoanfMapper)
}

func docsJSONSchemaUserDatabaseRunE(cmd *cobra.Command, args []string) (err error) {
	var version *model.SemanticVersion

	if version, err = readVersion(cmd); err != nil {
		return err
	}

	var (
		dir, file, schemaDir string
	)

	if schemaDir, err = getPFlagPath(cmd.Flags(), cmdFlagRoot, cmdFlagDirAuthentication); err != nil {
		return err
	}

	if dir, file, err = getJSONSchemaOutputPath(cmd, cmdFlagDocsStaticJSONSchemaUserDatabase); err != nil {
		return err
	}

	return docsJSONSchemaGenerateRunE(cmd, args, version, schemaDir, &authentication.FileUserDatabase{}, dir, file, jsonschemaKoanfMapper)
}

//nolint:gocyclo
func docsJSONSchemaGenerateRunE(cmd *cobra.Command, _ []string, version *model.SemanticVersion, schemaDir string, v any, dir, file string, mapper func(reflect.Type) *jsonschema.Schema) (err error) {
	r := &jsonschema.Reflector{
		RequiredFromJSONSchemaTags: true,
		Mapper:                     mapper,
	}

	if runtime.GOOS == windows {
		mapComments := map[string]string{}

		if err = jsonschema.ExtractGoComments(goModuleBase, schemaDir, mapComments); err != nil {
			return err
		}

		if r.CommentMap == nil {
			r.CommentMap = map[string]string{}
		}

		for key, comment := range mapComments {
			r.CommentMap[strings.ReplaceAll(key, `\`, `/`)] = comment
		}
	} else {
		if err = r.AddGoComments(goModuleBase, schemaDir); err != nil {
			return err
		}
	}

	var (
		versions []string
	)

	versions, _ = cmd.Flags().GetStringSlice(cmdFlagVersions)

	if len(versions) == 0 {
		versions = []string{metaVersionNext, metaVersionLatest}
	}

	next := utils.IsStringInSlice(metaVersionNext, versions)

	if next && utils.IsStringInSlice(metaVersionCurrent, versions) {
		return fmt.Errorf("failed to generate: meta version next and current are mutually exclusive")
	}

	schema := r.Reflect(v)

	for _, versionName := range versions {
		var out string

		switch versionName {
		case metaVersionNext:
			out = fmt.Sprintf("v%d.%d", version.Major, version.Minor+1)
			schema.ID = jsonschema.ID(fmt.Sprintf(model.FormatJSONSchemaIdentifier, out, file))
		case metaVersionCurrent:
			out = fmt.Sprintf("v%d.%d", version.Major, version.Minor)
			schema.ID = jsonschema.ID(fmt.Sprintf(model.FormatJSONSchemaIdentifier, out, file))
		case metaVersionLatest:
			out = metaVersionLatest

			if next {
				schema.ID = jsonschema.ID(fmt.Sprintf(model.FormatJSONSchemaIdentifier, fmt.Sprintf("v%d.%d", version.Major, version.Minor+1), file))
			} else {
				schema.ID = jsonschema.ID(fmt.Sprintf(model.FormatJSONSchemaIdentifier, fmt.Sprintf("v%d.%d", version.Major, version.Minor), file))
			}
		default:
			var parsed *model.SemanticVersion

			if parsed, err = model.NewSemanticVersion(versionName); err != nil {
				return fmt.Errorf("failed to parse version: %w", err)
			}

			out = fmt.Sprintf("v%d.%d", parsed.Major, parsed.Minor)
			schema.ID = jsonschema.ID(fmt.Sprintf(model.FormatJSONSchemaIdentifier, fmt.Sprintf("v%d.%d", version.Major, version.Minor), file))
		}

		if err = writeJSONSchema(schema, dir, out, file); err != nil {
			return err
		}
	}

	return nil
}

func writeJSONSchema(schema *jsonschema.Schema, dir, version, file string) (err error) {
	var (
		data []byte
		f    *os.File
	)

	if data, err = json.MarshalIndent(schema, "", "  "); err != nil {
		return err
	}

	if _, err = os.Stat(filepath.Join(dir, version, pathJSONSchema)); err != nil && os.IsNotExist(err) {
		if err = os.MkdirAll(filepath.Join(dir, version, pathJSONSchema), 0755); err != nil {
			return err
		}
	}

	if f, err = os.Create(filepath.Join(dir, version, pathJSONSchema, file+extJSON)); err != nil {
		return err
	}

	if _, err = f.Write(data); err != nil {
		return err
	}

	return f.Close()
}

func getJSONSchemaOutputPath(cmd *cobra.Command, flag string) (dir, file string, err error) {
	if dir, err = getPFlagPath(cmd.Flags(), cmdFlagRoot, cmdFlagDocs, cmdFlagDocsStatic, cmdFlagDocsStaticJSONSchemas); err != nil {
		return "", "", err
	}

	if file, err = cmd.Flags().GetString(flag); err != nil {
		return "", "", err
	}

	return dir, file, nil
}

func jsonschemaKoanfMapper(t reflect.Type) *jsonschema.Schema {
	switch t.String() {
	case "regexp.Regexp", "*regexp.Regexp":
		return &jsonschema.Schema{
			Type:   jsonschema.TypeString,
			Format: jsonschema.FormatStringRegex,
		}
	case "time.Duration", "*time.Duration":
		return &jsonschema.Schema{
			OneOf: []*jsonschema.Schema{
				{
					Type:    jsonschema.TypeString,
					Pattern: `^\d+\s*(y|M|w|d|h|m|s|ms|((year|month|week|day|hour|minute|second|millisecond)s?))(\s*\d+\s*(y|M|w|d|h|m|s|ms|((year|month|week|day|hour|minute|second|millisecond)s?)))*$`,
				},
				{
					Type:        jsonschema.TypeInteger,
					Description: "The duration in seconds",
				},
			},
		}
	case "schema.CryptographicKey":
		return &jsonschema.Schema{
			Type:    jsonschema.TypeString,
			Pattern: `^-{5}BEGIN (((RSA|EC) )?(PRIVATE|PUBLIC) KEY|CERTIFICATE)-{5}\n([a-zA-Z0-9\/+]{1,64}\n)+([a-zA-Z0-9\/+]{1,64}[=]{0,2})\n-{5}END (((RSA|EC) )?(PRIVATE|PUBLIC) KEY|CERTIFICATE)-{5}\n?$`,
		}
	case "schema.CryptographicPrivateKey":
		return &jsonschema.Schema{
			Type:    jsonschema.TypeString,
			Pattern: `^-{5}BEGIN ((RSA|EC) )?PRIVATE KEY-{5}\n([a-zA-Z0-9\/+]{1,64}\n)+([a-zA-Z0-9\/+]{1,64}[=]{0,2})\n-{5}END ((RSA|EC) )?PRIVATE KEY-{5}\n?$`,
		}
	case "rsa.PrivateKey", "*rsa.PrivateKey":
		return &jsonschema.Schema{
			Type:    jsonschema.TypeString,
			Pattern: `^-{5}(BEGIN (RSA )?PRIVATE KEY-{5}\n([a-zA-Z0-9\/+]{1,64}\n)+([a-zA-Z0-9\/+]{1,64}[=]{0,2})\n-{5}END (RSA )?PRIVATE KEY-{5}\n?)+$`,
		}
	case "ecdsa.PrivateKey", "*.ecdsa.PrivateKey":
		return &jsonschema.Schema{
			Type:    jsonschema.TypeString,
			Pattern: `^-{5}(BEGIN ((EC )?PRIVATE KEY-{5}\n([a-zA-Z0-9\/+]{1,64}\n)+([a-zA-Z0-9\/+]{1,64}[=]{0,2})\n-{5}END (EC )?PRIVATE KEY-{5}\n?)+$`,
		}
	case "mail.Address", "*mail.Address":
		return &jsonschema.Schema{
			Type:   jsonschema.TypeString,
			Format: jsonschema.FormatStringEmail,
		}
	case "schema.CSPTemplate":
		return &jsonschema.Schema{
			Type:    jsonschema.TypeString,
			Default: buildCSP(codeCSPProductionDefaultSrc, codeCSPValuesCommon, codeCSPValuesProduction),
		}
	}

	return nil
}