-
-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathroot.go
More file actions
652 lines (594 loc) · 31.8 KB
/
root.go
File metadata and controls
652 lines (594 loc) · 31.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
package cmd
import (
"context"
"fmt"
"os"
"os/signal"
"strings"
"time"
"github.com/redis/go-redis/v9"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
"github.com/authorizerdev/authorizer/internal/audit"
"github.com/authorizerdev/authorizer/internal/authenticators"
"github.com/authorizerdev/authorizer/internal/authorization"
"github.com/authorizerdev/authorizer/internal/config"
"github.com/authorizerdev/authorizer/internal/constants"
"github.com/authorizerdev/authorizer/internal/email"
"github.com/authorizerdev/authorizer/internal/events"
"github.com/authorizerdev/authorizer/internal/graph/model"
"github.com/authorizerdev/authorizer/internal/http_handlers"
"github.com/authorizerdev/authorizer/internal/memory_store"
"github.com/authorizerdev/authorizer/internal/metrics"
"github.com/authorizerdev/authorizer/internal/oauth"
"github.com/authorizerdev/authorizer/internal/rate_limit"
"github.com/authorizerdev/authorizer/internal/server"
"github.com/authorizerdev/authorizer/internal/sms"
"github.com/authorizerdev/authorizer/internal/storage"
"github.com/authorizerdev/authorizer/internal/token"
)
// Default values for flags (single source of truth for init and applyFlagDefaults).
var (
defaultHost = "0.0.0.0"
defaultMetricsHost = "127.0.0.1"
defaultLogLevel = "debug"
defaultHTTPPort = 8080
defaultMetricsPort = 8081
defaultOrganizationLogo = "https://authorizer.dev/images/logo.png"
defaultOrganizationName = "Authorizer"
// defaultAdminSecret intentionally REMOVED. Admin secret must be supplied
// explicitly via --admin-secret. The startup check in runRoot rejects
// only the empty value; the strength of the supplied secret is the
// operator's responsibility.
defaultJWTRoleClaim = "role"
defaultMicrosoftTenantID = "common"
defaultAllowedOrigins = []string{"*"}
defaultRoles = []string{"user"}
defaultGoogleScopes = []string{"openid", "profile", "email"}
defaultGithubScopes = []string{"read:user", "user:email"}
defaultFacebookScopes = []string{"public_profile", "email"}
defaultMicrosoftScopes = []string{"openid", "profile", "email"}
defaultTwitchScopes = []string{"openid", "user:read:email"}
defaultLinkedinScopes = []string{"r_liteprofile", "r_emailaddress"}
defaultAppleScopes = []string{"email", "name"}
defaultDiscordScopes = []string{"identify", "email"}
defaultTwitterScopes = []string{"tweet.read", "users.read"}
defaultRobloxScopes = []string{"openid", "profile"}
// Default RPS cap per IP; raised from 10 to reduce false positives on busy UIs.
defaultRateLimitRPS = 30
defaultRateLimitBurst = 20
)
var (
RootCmd = cobra.Command{
Use: "authorizer",
Run: runRoot,
}
rootArgs struct {
logLevel string
config config.Config
server server.Config
}
)
// legacyDisabledObserved is set when the operator passes the now-removed
// authorization-enforcement=disabled value. runRoot emits a one-time INFO log
// after the logger is configured. We cannot log from applyFlagDefaults because
// it runs before the logger is ready.
var legacyDisabledObserved bool
// legacyTypoObserved is set when the operator passes an
// authorization-enforcement value that is neither empty, "permissive",
// "enforcing" (any case), nor the legacy "disabled". runRoot emits a warning
// after the logger is configured so operators notice fat-fingered flags
// instead of being silently demoted to "permissive".
var legacyTypoObserved bool
// rawAuthzEnforcement preserves the operator-supplied --authorization-enforcement
// value before normalization, so runRoot can echo it back in the typo warning.
var rawAuthzEnforcement string
func init() {
f := RootCmd.Flags()
// Server flags
f.StringVar(&rootArgs.server.Host, "host", defaultHost, "Host address to listen on")
f.IntVar(&rootArgs.server.HTTPPort, "http-port", defaultHTTPPort, "Port to serve HTTP requests on")
f.IntVar(&rootArgs.server.MetricsPort, "metrics-port", defaultMetricsPort, "Port for the dedicated /metrics listener (must differ from --http-port)")
f.StringVar(&rootArgs.server.MetricsHost, "metrics-host", defaultMetricsHost, "Bind address for the dedicated /metrics listener (default loopback; use 0.0.0.0 when Prometheus scrapes from another host/pod)")
// Logging flags
f.StringVar(&rootArgs.logLevel, "log-level", defaultLogLevel, "Log level to use")
// Env
f.StringVar(&rootArgs.config.Env, "env", "", "Environment of the authorizer instance")
// Http routes
f.BoolVar(&rootArgs.config.EnableLoginPage, "enable-login-page", true, "Enable login page")
f.BoolVar(&rootArgs.config.EnablePlayground, "enable-playground", true, "Enable playground")
f.BoolVar(&rootArgs.config.EnableGraphQLIntrospection, "enable-graphql-introspection", true, "Enable GraphQL introspection for the /graphql endpoint")
f.BoolVar(&rootArgs.config.EnableHSTS, "enable-hsts", false, "Enable Strict-Transport-Security response header (only enable behind TLS)")
f.BoolVar(&rootArgs.config.DisableCSP, "disable-csp", false, "Disable the default Content-Security-Policy response header")
f.IntVar(&rootArgs.config.GraphQLMaxComplexity, "graphql-max-complexity", 300, "Maximum total complexity score for a single GraphQL operation")
f.IntVar(&rootArgs.config.GraphQLMaxDepth, "graphql-max-depth", 15, "Maximum nesting depth of a GraphQL selection set")
f.IntVar(&rootArgs.config.GraphQLMaxAliases, "graphql-max-aliases", 30, "Maximum total number of aliased fields per GraphQL operation")
f.Int64Var(&rootArgs.config.GraphQLMaxBodyBytes, "graphql-max-body-bytes", 1<<20, "Maximum allowed GraphQL request body size in bytes (default 1MB)")
// Organization flags
f.StringVar(&rootArgs.config.OrganizationLogo, "organization-logo", defaultOrganizationLogo, "Logo of the organization")
f.StringVar(&rootArgs.config.OrganizationName, "organization-name", defaultOrganizationName, "Name of the organization")
// OAuth flags
f.StringVar(&rootArgs.config.ClientID, "client-id", "", "Client ID for the OAuth")
f.StringVar(&rootArgs.config.ClientSecret, "client-secret", "", "Client secret for the OAuth")
f.StringVar(&rootArgs.config.DefaultAuthorizeResponseMode, "default-authorize-response-mode", constants.ResponseModeQuery, "Default response mode for the authorize endpoint")
f.StringVar(&rootArgs.config.DefaultAuthorizeResponseType, "default-authorize-response-type", constants.ResponseTypeToken, "Default response type for the authorize endpoint")
// Admin flags
f.StringVar(&rootArgs.config.AdminSecret, "admin-secret", "", "Secret for the admin (REQUIRED, must not be empty)")
f.Int64Var(&rootArgs.config.RefreshTokenExpiresIn, "refresh-token-expires-in", 60*60*24*30, "Refresh token lifetime in seconds (default: 30 days = 2592000)")
// Allowed origins
f.StringSliceVar(&rootArgs.config.AllowedOrigins, "allowed-origins", defaultAllowedOrigins, "Allowed origins")
// Database flags
f.StringVar(&rootArgs.config.DatabaseType, "database-type", "", "Type of database to use")
f.StringVar(&rootArgs.config.DatabaseURL, "database-url", "", "URL of the database")
f.StringVar(&rootArgs.config.DatabaseName, "database-name", "", "Name of the database")
f.StringVar(&rootArgs.config.DatabaseUsername, "database-username", "", "Username for the database")
f.StringVar(&rootArgs.config.DatabasePassword, "database-password", "", "Password for the database")
f.StringVar(&rootArgs.config.DatabaseHost, "database-host", "", "Host for the database")
f.IntVar(&rootArgs.config.DatabasePort, "database-port", 0, "Port for the database")
f.StringVar(&rootArgs.config.DatabaseCert, "database-cert", "", "Certificate for the database")
f.StringVar(&rootArgs.config.DatabaseCACert, "database-ca-cert", "", "CA certificate for the database")
f.StringVar(&rootArgs.config.DatabaseCertKey, "database-cert-key", "", "Certificate key for the database")
f.StringVar(&rootArgs.config.CouchBaseBucket, "couchbase-bucket", "", "Bucket for the database")
f.StringVar(&rootArgs.config.CouchBaseRamQuota, "couchbase-ram-quota", "", "RAM quota for the database")
f.StringVar(&rootArgs.config.CouchBaseScope, "couchbase-scope", "", "Scope for the database")
f.StringVar(&rootArgs.config.AWSRegion, "aws-region", "", "Region for the dynamodb database")
f.StringVar(&rootArgs.config.AWSAccessKeyID, "aws-access-key-id", "", "Access key ID for the dynamodb database")
f.StringVar(&rootArgs.config.AWSSecretAccessKey, "aws-secret-access-key", "", "Secret access key for the dynamodb database")
// Memory store flags
f.StringVar(&rootArgs.config.RedisURL, "redis-url", "", "URL of the redis server")
// Email flags
f.StringVar(&rootArgs.config.SMTPHost, "smtp-host", "", "Host for the SMTP server")
f.IntVar(&rootArgs.config.SMTPPort, "smtp-port", 0, "Port for the SMTP server")
f.StringVar(&rootArgs.config.SMTPUsername, "smtp-username", "", "Username for the SMTP server")
f.StringVar(&rootArgs.config.SMTPPassword, "smtp-password", "", "Password for the SMTP server")
f.StringVar(&rootArgs.config.SMTPSenderEmail, "smtp-sender-email", "", "Sender email for the SMTP server")
f.StringVar(&rootArgs.config.SMTPSenderName, "smtp-sender-name", "", "Sender name for the SMTP server")
f.StringVar(&rootArgs.config.SMTPLocalName, "smtp-local-name", "", "Local name for the SMTP server")
f.BoolVar(&rootArgs.config.SMTPSkipTLSVerification, "smtp-skip-tls-verification", false, "Skip TLS verification for the SMTP server")
// Auth flags
f.StringSliceVar(&rootArgs.config.DefaultRoles, "default-roles", defaultRoles, "Default user roles to assign")
f.StringSliceVar(&rootArgs.config.Roles, "roles", defaultRoles, "Roles to assign")
f.StringSliceVar(&rootArgs.config.ProtectedRoles, "protected-roles", []string{}, "Roles that cannot be deleted")
f.BoolVar(&rootArgs.config.EnableStrongPassword, "enable-strong-password", true, "Enable strong password requirement")
f.BoolVar(&rootArgs.config.EnableTOTPLogin, "enable-totp-login", false, "Enable TOTP login")
f.BoolVar(&rootArgs.config.EnableBasicAuthentication, "enable-basic-authentication", true, "Enable basic authentication")
f.BoolVar(&rootArgs.config.EnableEmailVerification, "enable-email-verification", false, "Enable email verification")
f.BoolVar(&rootArgs.config.EnableMobileBasicAuthentication, "enable-mobile-basic-authentication", true, "Enable mobile basic authentication")
f.BoolVar(&rootArgs.config.EnablePhoneVerification, "enable-phone-verification", false, "Enable phone verification")
f.BoolVar(&rootArgs.config.EnableMagicLinkLogin, "enable-magic-link-login", false, "Enable magic link login")
f.BoolVar(&rootArgs.config.EnforceMFA, "enforce-mfa", true, "Enforce MFA for all users")
f.BoolVar(&rootArgs.config.EnableMFA, "enable-mfa", false, "Enable MFA for all users")
f.BoolVar(&rootArgs.config.EnableEmailOTP, "enable-email-otp", false, "Enable email OTP")
f.BoolVar(&rootArgs.config.EnableSMSOTP, "enable-sms-otp", false, "Enable SMS OTP")
f.BoolVar(&rootArgs.config.EnableSignup, "enable-signup", true, "Enable signup")
// Cookies flags
f.BoolVar(&rootArgs.config.AppCookieSecure, "app-cookie-secure", true, "Application secure cookie flag")
f.StringVar(&rootArgs.config.AppCookieSameSite, "app-cookie-same-site", "none", "SameSite attribute for session cookies (lax, strict, none)")
f.BoolVar(&rootArgs.config.AdminCookieSecure, "admin-cookie-secure", true, "Admin secure cookie flag")
f.BoolVar(&rootArgs.config.DisableAdminHeaderAuth, "disable-admin-header-auth", false, "Disable admin authentication via X-Authorizer-Admin-Secret header")
// Rate limiting flags
f.IntVar(&rootArgs.config.RateLimitRPS, "rate-limit-rps", defaultRateLimitRPS, "Maximum requests per second per IP for rate limiting")
f.IntVar(&rootArgs.config.RateLimitBurst, "rate-limit-burst", defaultRateLimitBurst, "Maximum burst size per IP for rate limiting")
f.BoolVar(&rootArgs.config.RateLimitFailClosed, "rate-limit-fail-closed", false, "On rate-limit backend errors, reject with 503 instead of allowing the request")
f.StringSliceVar(&rootArgs.config.TrustedProxies, "trusted-proxies", nil, "Comma-separated CIDRs of trusted reverse proxies. When set, gin uses X-Forwarded-For from these networks. Empty (default) trusts no proxies and uses RemoteAddr.")
// JWT flags
f.StringVar(&rootArgs.config.JWTType, "jwt-type", "", "Type of JWT to use")
f.StringVar(&rootArgs.config.JWTSecret, "jwt-secret", "", "Secret for the JWT")
f.StringVar(&rootArgs.config.JWTPrivateKey, "jwt-private-key", "", "Private key for the JWT")
f.StringVar(&rootArgs.config.JWTPublicKey, "jwt-public-key", "", "Public key for the JWT")
// JWT secondary key flags (for manual key rotation)
f.StringVar(&rootArgs.config.JWTSecondaryType, "jwt-secondary-type", "", "Algorithm of the optional secondary JWT key used for manual rotation. When set, JWKS publishes both keys and token validation accepts either. New tokens are always signed with the primary (--jwt-type) key.")
f.StringVar(&rootArgs.config.JWTSecondarySecret, "jwt-secondary-secret", "", "Secret for the secondary JWT key (HMAC only; never exposed via JWKS)")
f.StringVar(&rootArgs.config.JWTSecondaryPrivateKey, "jwt-secondary-private-key", "", "Private key for the secondary JWT key. Currently unused — verification only uses the public key; kept for symmetry with --jwt-private-key and for future primary/secondary swap automation.")
f.StringVar(&rootArgs.config.JWTSecondaryPublicKey, "jwt-secondary-public-key", "", "Public key for the secondary JWT key. Used to verify tokens signed with the secondary key during rotation.")
f.StringVar(&rootArgs.config.JWTRoleClaim, "jwt-role-claim", defaultJWTRoleClaim, "Role claim for the JWT")
f.StringVar(&rootArgs.config.CustomAccessTokenScript, "custom-access-token-script", "", "Custom access token script")
// Twilio flags
f.StringVar(&rootArgs.config.TwilioAccountSID, "twilio-account-sid", "", "Account SID for Twilio")
f.StringVar(&rootArgs.config.TwilioAPIKey, "twilio-api-key", "", "API key for Twilio")
f.StringVar(&rootArgs.config.TwilioAPISecret, "twilio-api-secret", "", "API secret for Twilio")
f.StringVar(&rootArgs.config.TwilioSender, "twilio-sender", "", "Sender for Twilio")
// Oauth provider flags
f.StringVar(&rootArgs.config.GoogleClientID, "google-client-id", "", "Client ID for Google")
f.StringVar(&rootArgs.config.GoogleClientSecret, "google-client-secret", "", "Client secret for Google")
f.StringSliceVar(&rootArgs.config.GoogleScopes, "google-scopes", defaultGoogleScopes, "Scopes for Google")
f.StringVar(&rootArgs.config.GithubClientID, "github-client-id", "", "Client ID for Github")
f.StringVar(&rootArgs.config.GithubClientSecret, "github-client-secret", "", "Client secret for Github")
f.StringSliceVar(&rootArgs.config.GithubScopes, "github-scopes", defaultGithubScopes, "Scopes for Github")
f.StringVar(&rootArgs.config.FacebookClientID, "facebook-client-id", "", "Client ID for Facebook")
f.StringVar(&rootArgs.config.FacebookClientSecret, "facebook-client-secret", "", "Client secret for Facebook")
f.StringSliceVar(&rootArgs.config.FacebookScopes, "facebook-scopes", defaultFacebookScopes, "Scopes for Facebook")
f.StringVar(&rootArgs.config.MicrosoftClientID, "microsoft-client-id", "", "Client ID for Microsoft")
f.StringVar(&rootArgs.config.MicrosoftClientSecret, "microsoft-client-secret", "", "Client secret for Microsoft")
f.StringVar(&rootArgs.config.MicrosoftTenantID, "microsoft-tenant-id", defaultMicrosoftTenantID, "Tenant ID for Microsoft")
f.StringSliceVar(&rootArgs.config.MicrosoftScopes, "microsoft-scopes", defaultMicrosoftScopes, "Scopes for Microsoft")
f.StringVar(&rootArgs.config.TwitchClientID, "twitch-client-id", "", "Client ID for Twitch")
f.StringVar(&rootArgs.config.TwitchClientSecret, "twitch-client-secret", "", "Client secret for Twitch")
f.StringSliceVar(&rootArgs.config.TwitchScopes, "twitch-scopes", defaultTwitchScopes, "Scopes for Twitch")
f.StringVar(&rootArgs.config.LinkedinClientID, "linkedin-client-id", "", "Client ID for Linkedin")
f.StringVar(&rootArgs.config.LinkedinClientSecret, "linkedin-client-secret", "", "Client secret for Linkedin")
f.StringSliceVar(&rootArgs.config.LinkedinScopes, "linkedin-scopes", defaultLinkedinScopes, "Scopes for Linkedin")
f.StringVar(&rootArgs.config.AppleClientID, "apple-client-id", "", "Client ID for Apple")
f.StringVar(&rootArgs.config.AppleClientSecret, "apple-client-secret", "", "Client secret for Apple")
f.StringSliceVar(&rootArgs.config.AppleScopes, "apple-scopes", defaultAppleScopes, "Scopes for Apple")
f.StringVar(&rootArgs.config.DiscordClientID, "discord-client-id", "", "Client ID for Discord")
f.StringVar(&rootArgs.config.DiscordClientSecret, "discord-client-secret", "", "Client secret for Discord")
f.StringSliceVar(&rootArgs.config.DiscordScopes, "discord-scopes", defaultDiscordScopes, "Scopes for Discord")
f.StringVar(&rootArgs.config.TwitterClientID, "twitter-client-id", "", "Client ID for Twitter")
f.StringVar(&rootArgs.config.TwitterClientSecret, "twitter-client-secret", "", "Client secret for Twitter")
f.StringSliceVar(&rootArgs.config.TwitterScopes, "twitter-scopes", defaultTwitterScopes, "Scopes for Twitter")
f.StringVar(&rootArgs.config.RobloxClientID, "roblox-client-id", "", "Client ID for Roblox")
f.StringVar(&rootArgs.config.RobloxClientSecret, "roblox-client-secret", "", "Client secret for Roblox")
f.StringSliceVar(&rootArgs.config.RobloxScopes, "roblox-scopes", defaultRobloxScopes, "Scopes for Roblox")
// URLs
f.StringVar(&rootArgs.config.ResetPasswordURL, "reset-password-url", "", "URL for reset password")
// Back-channel logout (OIDC BCL 1.0)
f.StringVar(&rootArgs.config.BackchannelLogoutURI, "backchannel-logout-uri", "", "URL to POST a signed logout_token to when users log out successfully. Leave empty (default) to disable back-channel logout notifications. See OIDC Back-Channel Logout 1.0.")
// Fine-grained authorization flags
f.StringVar(&rootArgs.config.AuthorizationEnforcement, "authorization-enforcement", "permissive", "Authorization enforcement mode: permissive (default) or enforcing")
f.Int64Var(&rootArgs.config.AuthorizationCacheTTL, "authorization-cache-ttl", 300, "Cache TTL in seconds for permission checks (0 to disable)")
f.BoolVar(&rootArgs.config.IncludePermissionsInToken, "include-permissions-in-token", false, "Include permissions in JWT access tokens")
f.BoolVar(&rootArgs.config.AuthorizationLogAllChecks, "authorization-log-all-checks", false, "Audit log all permission checks, not just denials")
// Deprecated flags
f.MarkDeprecated("database_url", "use --database-url instead")
f.MarkDeprecated("database_type", "use --database-type instead")
f.MarkDeprecated("env_file", "no more supported")
f.MarkDeprecated("log_level", "use --log-level instead")
f.MarkDeprecated("redis_url", "use --redis-url instead")
}
// applyFlagDefaults sets config and server fields to their flag defaults when the
// value is empty (e.g. when user passes --host="" we use the default from vars above).
func applyFlagDefaults() {
c := &rootArgs.config
s := &rootArgs.server
if s.HTTPPort == 0 {
s.HTTPPort = defaultHTTPPort
}
if s.MetricsPort == 0 {
s.MetricsPort = defaultMetricsPort
}
if strings.TrimSpace(s.MetricsHost) == "" {
s.MetricsHost = defaultMetricsHost
}
if strings.TrimSpace(rootArgs.logLevel) == "" {
rootArgs.logLevel = defaultLogLevel
}
if strings.TrimSpace(c.OrganizationLogo) == "" {
c.OrganizationLogo = defaultOrganizationLogo
}
if strings.TrimSpace(c.OrganizationName) == "" {
c.OrganizationName = defaultOrganizationName
}
if strings.TrimSpace(c.DefaultAuthorizeResponseMode) == "" {
c.DefaultAuthorizeResponseMode = constants.ResponseModeQuery
}
if strings.TrimSpace(c.DefaultAuthorizeResponseType) == "" {
c.DefaultAuthorizeResponseType = constants.ResponseTypeToken
}
// AdminSecret deliberately has NO default. The fatal check in runRoot
// rejects empty values at startup; secret strength is the operator's
// responsibility.
if len(c.AllowedOrigins) == 0 {
c.AllowedOrigins = append([]string(nil), defaultAllowedOrigins...)
}
if len(c.DefaultRoles) == 0 {
c.DefaultRoles = append([]string(nil), defaultRoles...)
}
if len(c.Roles) == 0 {
c.Roles = append([]string(nil), defaultRoles...)
}
if strings.TrimSpace(c.JWTRoleClaim) == "" {
c.JWTRoleClaim = defaultJWTRoleClaim
}
if strings.TrimSpace(c.MicrosoftTenantID) == "" {
c.MicrosoftTenantID = defaultMicrosoftTenantID
}
if len(c.GoogleScopes) == 0 {
c.GoogleScopes = append([]string(nil), defaultGoogleScopes...)
}
if len(c.GithubScopes) == 0 {
c.GithubScopes = append([]string(nil), defaultGithubScopes...)
}
if len(c.FacebookScopes) == 0 {
c.FacebookScopes = append([]string(nil), defaultFacebookScopes...)
}
if len(c.MicrosoftScopes) == 0 {
c.MicrosoftScopes = append([]string(nil), defaultMicrosoftScopes...)
}
if len(c.TwitchScopes) == 0 {
c.TwitchScopes = append([]string(nil), defaultTwitchScopes...)
}
if len(c.LinkedinScopes) == 0 {
c.LinkedinScopes = append([]string(nil), defaultLinkedinScopes...)
}
if len(c.AppleScopes) == 0 {
c.AppleScopes = append([]string(nil), defaultAppleScopes...)
}
if len(c.DiscordScopes) == 0 {
c.DiscordScopes = append([]string(nil), defaultDiscordScopes...)
}
if len(c.TwitterScopes) == 0 {
c.TwitterScopes = append([]string(nil), defaultTwitterScopes...)
}
if len(c.RobloxScopes) == 0 {
c.RobloxScopes = append([]string(nil), defaultRobloxScopes...)
}
rawEnforcement := c.AuthorizationEnforcement
rawAuthzEnforcement = rawEnforcement
c.AuthorizationEnforcement = NormalizeAuthzEnforcement(rawEnforcement)
trimmed := strings.TrimSpace(rawEnforcement)
switch {
case strings.EqualFold(trimmed, "disabled"):
// Remember the legacy input so runRoot can log the one-time migration
// notice after the logger is configured. We cannot log here because
// applyFlagDefaults runs before the logger is ready.
legacyDisabledObserved = true
case trimmed == "",
strings.EqualFold(trimmed, constants.AuthorizationEnforcementPermissive),
strings.EqualFold(trimmed, constants.AuthorizationEnforcementEnforcing):
// Canonical input (case-insensitive) or unset; nothing to flag.
default:
// Anything else is a typo or unknown value. Surface it as a warning
// in runRoot so operators see their fat-fingered flag instead of
// being silently demoted to permissive.
legacyTypoObserved = true
}
}
// NormalizeAuthzEnforcement returns the canonical enforcement mode for the given input.
// - "enforcing" (case-insensitive, whitespace-tolerant) maps to "enforcing".
// - "" (empty), "permissive" (any case), "disabled" (legacy), and any
// unrecognized value map to "permissive" — the new safe default.
//
// Callers (applyFlagDefaults / runRoot) are responsible for emitting the
// legacy-migration notice for "disabled" (via legacyDisabledObserved) and a
// typo warning for unrecognized input (via legacyTypoObserved) after the
// logger is configured.
func NormalizeAuthzEnforcement(v string) string {
trimmed := strings.TrimSpace(v)
if strings.EqualFold(trimmed, constants.AuthorizationEnforcementEnforcing) {
return constants.AuthorizationEnforcementEnforcing
}
return constants.AuthorizationEnforcementPermissive
}
// Run the service
func runRoot(c *cobra.Command, args []string) {
applyFlagDefaults()
if rootArgs.server.HTTPPort == rootArgs.server.MetricsPort {
fmt.Fprintf(os.Stderr, "invalid server ports: --http-port and --metrics-port must differ (metrics are always served on a dedicated listener)\n")
os.Exit(1)
}
// Refuse to start without an admin secret. The previous default of
// "password" was a publicly known credential — operators upgrading from
// older versions must now supply --admin-secret explicitly. The strength
// of the supplied value is the operator's responsibility; we only
// guarantee it is non-empty.
if strings.TrimSpace(rootArgs.config.AdminSecret) == "" {
fmt.Fprintln(os.Stderr, "FATAL: --admin-secret is required and must not be empty.")
os.Exit(1)
}
// Prepare logger
ctx := context.Background()
// Parse the log level
zeroLogLevel, err := zerolog.ParseLevel(rootArgs.logLevel)
if err != nil {
// If the log level is invalid, set it to debug
zeroLogLevel = zerolog.DebugLevel
}
// Create a new console writer
// consoleWriter := zerolog.New(os.Stdout)
// consoleWriter.NoColor = true
// consoleWriter.TimeFormat = time.RFC3339
// consoleWriter.TimeLocation = time.UTC
zerolog.TimestampFunc = func() time.Time {
return time.Now().UTC()
}
log := zerolog.New(os.Stdout).
Level(zeroLogLevel).
With().Timestamp().Logger()
// Warn if AllowedOrigins is the wildcard ["*"] — this is a development-
// friendly default but in production it pairs poorly with credentialed
// requests. Operators should set an explicit allowlist before deploying.
for _, o := range rootArgs.config.AllowedOrigins {
if o == "*" {
log.Warn().Msg("AllowedOrigins contains \"*\" — this is unsafe for production. Set --allowed-origins to an explicit list of trusted origins. CSRF middleware will fall back to same-origin enforcement for state-changing requests.")
break
}
}
// Initialize prometheus metrics
metrics.Init()
// Derive IsEmailServiceEnabled from SMTP config
rootArgs.config.IsEmailServiceEnabled = strings.TrimSpace(rootArgs.config.SMTPHost) != "" &&
rootArgs.config.SMTPPort > 0 &&
strings.TrimSpace(rootArgs.config.SMTPSenderEmail) != ""
// Derive IsSMSServiceEnabled from Twilio config
rootArgs.config.IsSMSServiceEnabled = strings.TrimSpace(rootArgs.config.TwilioAPIKey) != "" &&
strings.TrimSpace(rootArgs.config.TwilioAPISecret) != "" &&
strings.TrimSpace(rootArgs.config.TwilioAccountSID) != "" &&
strings.TrimSpace(rootArgs.config.TwilioSender) != ""
// Storage provider
storageProvider, err := storage.New(&rootArgs.config, &storage.Dependencies{
Log: &log,
})
if err != nil {
log.Fatal().Err(err).Msg("failed to create storage provider")
}
defer func() {
if err := storageProvider.Close(); err != nil {
log.Error().Err(err).Msg("failed to close storage provider")
}
}()
// Authenticator provider
authenticatorProvider, err := authenticators.New(&rootArgs.config, &authenticators.Dependencies{
Log: &log,
StorageProvider: storageProvider,
})
if err != nil {
log.Fatal().Err(err).Msg("failed to create authenticator provider")
}
// Email provider
emailProvider, err := email.New(&rootArgs.config, &email.Dependencies{
Log: &log,
StorageProvider: storageProvider,
})
if err != nil {
log.Fatal().Err(err).Msg("failed to create email provider")
}
// Events provider
eventsProvider, err := events.New(&rootArgs.config, &events.Dependencies{
Log: &log,
StorageProvider: storageProvider,
})
if err != nil {
log.Fatal().Err(err).Msg("failed to create events provider")
}
// Memory store provider
memoryStoreProvider, err := memory_store.New(&rootArgs.config, &memory_store.Dependencies{
Log: &log,
StorageProvider: storageProvider,
})
if err != nil {
log.Fatal().Err(err).Msg("failed to create memory store provider")
}
// Rate limit provider
rateLimitDeps := &rate_limit.Dependencies{
Log: &log,
}
// If memory store is Redis-backed, reuse its client for distributed rate limiting
type redisClientProvider interface {
Client() interface {
Eval(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd
}
}
if rcp, ok := memoryStoreProvider.(redisClientProvider); ok {
if client, ok := rcp.Client().(rate_limit.RedisClient); ok {
rateLimitDeps.RedisStore = client
}
}
rateLimitProvider, err := rate_limit.New(&rootArgs.config, rateLimitDeps)
if err != nil {
log.Fatal().Err(err).Msg("failed to create rate limit provider")
}
defer rateLimitProvider.Close()
// Authorization provider
authorizationProvider, err := authorization.New(
&authorization.Config{
Enforcement: rootArgs.config.AuthorizationEnforcement,
CacheTTL: rootArgs.config.AuthorizationCacheTTL,
},
&authorization.Dependencies{
Log: &log,
StorageProvider: storageProvider,
},
)
if err != nil {
log.Fatal().Err(err).Msg("failed to create authorization provider")
}
if legacyDisabledObserved {
log.Info().Msg("authz: 'disabled' is no longer a supported enforcement mode; migrated to 'permissive'. CheckPermission calls with no matching permission will return ALLOWED and log authz.unmatched=true. Set --authorization-enforcement=enforcing once permissions are seeded.")
}
switch rootArgs.config.AuthorizationEnforcement {
case constants.AuthorizationEnforcementEnforcing:
// Check once at startup whether any permissions exist. If zero, emit a
// loud warn so operators don't lock themselves out in prod. Bounded
// context prevents a hung DB at boot from blocking startup indefinitely.
probeCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_, pr, lerr := storageProvider.ListPermissions(probeCtx, &model.Pagination{Limit: 1, Page: 1})
cancel()
switch {
case lerr != nil:
log.Warn().Err(lerr).Msg("authz: failed to probe permission count at startup; enforcing mode active")
case pr != nil && pr.Total == 0:
log.Warn().Msg("authz mode=enforcing but 0 permissions configured — all check_permission calls will DENY. Seed permissions or switch to --authorization-enforcement=permissive.")
default:
log.Info().Msg("authz mode=enforcing: unmatched CheckPermission calls will be DENIED.")
}
default:
log.Info().Msg("authz mode=permissive: unmatched CheckPermission calls will be ALLOWED and logged with authz.unmatched=true.")
}
// SMS provider
smsProvider, err := sms.New(&rootArgs.config, &sms.Dependencies{
Log: &log,
})
if err != nil {
log.Fatal().Err(err).Msg("failed to create sms provider")
}
// Token provider
tokenProvider, err := token.New(&rootArgs.config, &token.Dependencies{
Log: &log,
MemoryStoreProvider: memoryStoreProvider,
})
if err != nil {
log.Fatal().Err(err).Msg("failed to create token provider")
}
// OAuth provider
oauthProvider, err := oauth.New(&rootArgs.config, &oauth.Dependencies{
Log: &log,
})
if err != nil {
log.Fatal().Err(err).Msg("failed to create oauth provider")
}
// Ensure client ID and secret are set for authorizer instance
if strings.TrimSpace(rootArgs.config.ClientID) == "" {
log.Fatal().Msg("client ID missing in rootArgs")
}
if strings.TrimSpace(rootArgs.config.ClientSecret) == "" {
log.Fatal().Msg("client secret missing in rootArgs")
}
auditProvider := audit.New(&audit.Dependencies{
Log: &log,
StorageProvider: storageProvider,
})
httpProvider, err := http_handlers.New(&rootArgs.config, &http_handlers.Dependencies{
Log: &log,
AuditProvider: auditProvider,
AuthenticatorProvider: authenticatorProvider,
EmailProvider: emailProvider,
EventsProvider: eventsProvider,
MemoryStoreProvider: memoryStoreProvider,
SMSProvider: smsProvider,
StorageProvider: storageProvider,
TokenProvider: tokenProvider,
OAuthProvider: oauthProvider,
RateLimitProvider: rateLimitProvider,
AuthorizationProvider: authorizationProvider,
})
if err != nil {
log.Fatal().Err(err).Msg("failed to create http provider")
}
// Prepare server
deps := &server.Dependencies{
Log: &log,
AppConfig: &rootArgs.config,
HTTPProvider: httpProvider,
}
// Create the server
svr, err := server.New(&rootArgs.server, deps)
if err != nil {
log.Fatal().Err(err).Msg("failed to create server")
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
return svr.Run(ctx)
})
// Setup signal handler to allow for graceful termination
sigCtx, stop := signal.NotifyContext(ctx, os.Interrupt)
// Wait for interrupt or failure in errgroup.
select {
case <-sigCtx.Done():
log.Info().Msg("Signal received, shutting down...")
// Unregister signal handlers.
// Next interrupt signal will kill us.
cancel()
stop()
case <-ctx.Done():
// Errgroup context canceled
}
// Wait for all routines to end
if err := g.Wait(); err != nil {
log.Fatal().Err(err).Msg("Application failed")
}
log.Info().Msg("Application terminated")
}