Repository navigation
Expand file tree
/
Copy pathengine.go
More file actions
1634 lines (1444 loc) · 58.1 KB
/
Copy pathengine.go
File metadata and controls
1634 lines (1444 loc) · 58.1 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
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package authsome provides a composable authentication engine for the Forge ecosystem.
//
// AuthSome v0.5.0 is an interface-driven, store-abstracted authentication engine
// with a type-cached plugin registry, global hook bus, strategy-based authentication,
// and optional bridges to forgery extensions (Chronicle, Warden, Keysmith, Relay).
package authsome
import (
"context"
"crypto/hmac"
"crypto/sha256"
"errors"
"fmt"
"os"
"slices"
"strings"
"time"
log "github.com/xraph/go-utils/log"
"github.com/xraph/forge"
"github.com/xraph/forge/extensions/auth"
"github.com/xraph/authsome/account"
"github.com/xraph/authsome/apikey"
"github.com/xraph/authsome/app"
"github.com/xraph/authsome/appclientconfig"
"github.com/xraph/authsome/appsessionconfig"
"github.com/xraph/authsome/authprovider"
"github.com/xraph/authsome/authz"
"github.com/xraph/authsome/bridge"
"github.com/xraph/authsome/bridge/ledgeradapter"
"github.com/xraph/authsome/ceremony"
"github.com/xraph/authsome/dpop"
"github.com/xraph/authsome/formconfig"
"github.com/xraph/authsome/hook"
"github.com/xraph/authsome/id"
"github.com/xraph/authsome/lockout"
"github.com/xraph/authsome/middleware"
"github.com/xraph/authsome/organization"
"github.com/xraph/authsome/plugin"
"github.com/xraph/authsome/principal"
"github.com/xraph/authsome/ratelimit"
"github.com/xraph/authsome/rbac"
"github.com/xraph/authsome/securityevent"
"github.com/xraph/authsome/session"
"github.com/xraph/authsome/settings"
"github.com/xraph/authsome/store"
"github.com/xraph/authsome/strategy"
"github.com/xraph/authsome/tokenformat"
"github.com/xraph/authsome/user"
"github.com/xraph/grove"
"github.com/xraph/keysmith"
xledger "github.com/xraph/ledger"
ledgerstore "github.com/xraph/ledger/store"
"github.com/xraph/warden"
wardenid "github.com/xraph/warden/id"
"github.com/xraph/warden/resourcetype"
)
// Engine is the core AuthSome orchestrator. It holds only interfaces —
// no concrete implementations — for maximum pluggability.
type Engine struct {
config Config
store store.Store
logger log.Logger
// Plugin system
plugins *plugin.Registry
hooks *hook.Bus
strategies *strategy.Registry
pendingPlugins []plugin.Plugin
pendingStrategies []pendingStrategy
pendingAppSessCfgs []*appsessionconfig.Config
// principalAuthGate scores machine callers (API keys, and any other
// credential that authenticates without a human sign-in) through the
// principal-auth hooks before a session is minted. Built once during
// NewEngine and exposed to plugins via PrincipalAuthGate, which
// implements plugin.PrincipalAuthGateProvider.
principalAuthGate *principalAuthGate
// principalAuthTTL controls how long an allow verdict is cached, keyed
// on credential and source IP together. Set via WithPrincipalAuthTTL;
// defaults to five minutes.
principalAuthTTL time.Duration
// First-class authorization engine (optional, replaces bridge for RBAC)
wardenEng *warden.Engine
// First-class key management engine (optional, replaces bridge for API keys)
keysmithEng *keysmith.Engine
// First-class billing engine (optional, provides store access for subscription plugin)
ledgerEng *xledger.Ledger
// Optional forgery bridges (injected, not required)
chronicle bridge.Chronicle
authorizer bridge.Authorizer
keyManager bridge.KeyManager
relay bridge.EventRelay
mailer bridge.Mailer
sms bridge.SMSSender
heraldBridge bridge.Herald
vault bridge.Vault
dispatcher bridge.Dispatcher
ledger bridge.Ledger
metrics bridge.MetricsCollector
// tokenEncryptor encrypts at-rest secrets such as third-party OAuth
// access/refresh tokens. Defaults to bridge.NoopEncryptor when no
// AUTHSOME_TOKEN_ENCRYPTION_KEY is configured (dev mode).
tokenEncryptor bridge.Encryptor
// Ceremony state store for multi-instance auth ceremonies
ceremonyStore ceremony.Store
// RFC 9449 DPoP: proof validator (always constructed), nonce signer
// (nil when no signing secret is derivable) and replay cache.
dpopValidator *dpop.Validator
dpopNonceSigner *dpop.NonceSigner
dpopReplayCache dpop.ReplayCache
// Token format (default: opaque; per-app overrides via AppSessionConfig.TokenFormat)
defaultTokenFormat tokenformat.Format
jwtFormats map[string]*tokenformat.JWT // keyed by app ID
// Security
rateLimiter ratelimit.Limiter
lockout lockout.Tracker
passwordHistory account.PasswordHistoryStore
securityEvents securityevent.Store
// Dynamic settings manager (optional).
settingsMgr *settings.Manager
// Bootstrap configuration (nil = disabled).
bootstrapCfg *BootstrapConfig
platformAppID id.AppID
// Database reference for plugins that need direct database access
// to create their own persistent stores.
db *grove.DB
// Cached auth middleware — built once during InitPlugins() with full
// capability detection (JWT + strategies + cookie bridge).
authMiddleware forge.Middleware
// Forge auth provider registry — plugins register their providers here.
authRegistry auth.Registry
pluginsInitialized bool
started bool
}
// NewEngine creates a new AuthSome engine with the given options.
func NewEngine(opts ...Option) (*Engine, error) {
e := &Engine{
config: DefaultConfig(),
logger: log.NewNoopLogger(),
}
for _, opt := range opts {
opt(e)
}
if e.store == nil {
return nil, errors.New("authsome: store is required")
}
if e.wardenEng == nil {
return nil, errors.New("authsome: warden engine is required (use WithWarden option)")
}
// Stamp session roles on the way to the store, before any subsystem below
// captures a reference to it. Sessions are created from six different
// paths and all of them end at store.CreateSession, so this is the one
// place that covers every one of them. See engine_session_roles.go.
e.store = newRoleStampingStore(e.store, e.sessionRoleSlugs, e.logger)
// Eagerly allocate the MFA ceremony store when none was configured, so it
// is never lazily created on a request goroutine (which would be a data
// race between concurrent MFA-gated logins and could drop tickets).
if e.ceremonyStore == nil {
e.ceremonyStore = ceremony.NewMemory()
}
// Initialize subsystems
e.plugins = plugin.NewRegistry(e.logger)
e.hooks = hook.NewBus(e.logger)
e.strategies = strategy.NewRegistry(e.logger)
// Wire the principal-auth gate. Static API-key traffic (and any other
// machine credential) reaches strategy.Authenticate directly, bypassing
// every sign-in hook, so this is what fires OnBeforePrincipalAuth /
// OnAfterPrincipalAuth for it instead. See plugin_principalauth.go.
if e.principalAuthTTL <= 0 {
e.principalAuthTTL = 5 * time.Minute
}
e.principalAuthGate = newPrincipalAuthGate(
e.plugins.EmitBeforePrincipalAuth,
func(ctx context.Context, a *principal.AuthAttempt, s *session.Session) {
e.plugins.EmitAfterPrincipalAuth(ctx, a, s)
e.hooks.Emit(ctx, &hook.Event{
Action: hook.ActionPrincipalAuth,
Resource: hook.ResourceSession,
ResourceID: s.ID.String(),
ActorID: a.Subject.ID,
Tenant: a.AppID.String(),
Metadata: map[string]string{
"principal_kind": string(a.Subject.Kind),
"credential_kind": a.CredentialKind,
"credential_id": a.CredentialID,
"ip": a.IPAddress,
},
})
},
e.principalAuthTTL,
e.logger,
)
// Initialize the dynamic settings manager.
e.settingsMgr = settings.NewManager(e.store, e.logger)
// Register core session settings.
if err := registerCoreSessionSettings(e.settingsMgr); err != nil {
return nil, fmt.Errorf("authsome: failed to register core session settings: %w", err)
}
// Register captcha settings (Phase 2B.2).
if err := registerCaptchaSettings(e.settingsMgr); err != nil {
return nil, fmt.Errorf("authsome: failed to register captcha settings: %w", err)
}
// Construct the RFC 9449 DPoP validator and, when a secret is
// derivable, the nonce signer. Settings and JWT formats (both consulted
// indirectly, the latter via NonceSecret) are established by this point.
e.initDPoP()
// Resolve token encryptor: WithTokenEncryptor wins, otherwise read env.
if e.tokenEncryptor == nil {
e.tokenEncryptor = resolveTokenEncryptor(e.logger)
}
// Register pending plugins
for _, p := range e.pendingPlugins {
e.plugins.Register(p)
}
e.pendingPlugins = nil
// Register pending strategies
for _, ps := range e.pendingStrategies {
e.strategies.Register(ps.strategy, ps.priority)
}
e.pendingStrategies = nil
return e, nil
}
// ErrNotStarted is returned when a service method is called before Start().
var ErrNotStarted = errors.New("authsome: engine not started, please wait for initialization to complete")
// EnsureMigrated runs store migrations (core + plugin groups) if not disabled.
// This is idempotent — safe to call multiple times. Use this to ensure tables
// exist before the engine is fully started (e.g. during extension init).
func (e *Engine) EnsureMigrated(ctx context.Context) error {
if e.config.DisableMigrate {
return nil
}
extraGroups := e.plugins.CollectMigrationGroups(e.config.DriverName)
return e.store.Migrate(ctx, extraGroups...)
}
// requireStarted returns ErrNotStarted if the engine has not been started.
func (e *Engine) requireStarted() error {
if !e.started {
return ErrNotStarted
}
return nil
}
// DPoPBindingConfig returns the RFC 9449 enforcement wiring, for every auth
// path that resolves a token and therefore has to honour a binding. The auth
// middleware is one such path and the registered session auth provider is
// another; anyone assembling their own chain gets the same config from here
// rather than reassembling one that drifts.
//
// The validator is always non-nil (initDPoP builds it unconditionally); the
// nonce signer is nil until a secret is derivable, which DPoPNonceRequiredForApp
// already accounts for by refusing to demand nonces it cannot mint.
func (e *Engine) DPoPBindingConfig() middleware.SessionBindingConfig {
return middleware.SessionBindingConfig{
DPoPValidator: e.DPoPValidator(),
DPoPNonceSigner: e.DPoPNonceSigner(),
DPoPNonceRequired: func(ctx context.Context, appID string) bool {
parsed, err := id.Parse(appID)
if err != nil {
return false
}
return e.DPoPNonceRequiredForApp(ctx, parsed)
},
DPoPAudit: func(ctx context.Context, action string, md map[string]string) {
severity := bridge.SeverityInfo
if action == hook.ActionDPoPProofReplayed {
severity = bridge.SeverityWarning
}
e.audit(ctx, severity, bridge.OutcomeFailure, action, "session",
md["session_id"], "", md["app_id"], "auth", md)
},
}
}
// buildAuthMiddleware constructs the fully-configured auth middleware with
// capability detection (JWT, strategies) and the cookie-to-header bridge.
// Called once during InitPlugins so both the extension and plugins share
// the same middleware instance.
//
// Strategy registration timing — IMPORTANT: this method runs DURING
// InitPlugins, BEFORE plugin OnInit hooks fire and BEFORE Engine.Start
// auto-registers plugin-provided strategies. So at build time
// `e.HasStrategies()` is always false and `e.Strategies()` returns an
// empty registry. We deliberately ignore HasStrategies as a switch
// guard and always pass the registry pointer into the middleware —
// the registry is allocated up front and the middleware reads it
// lazily on each request, so strategies registered AFTER this build
// are picked up automatically. Choosing the bare `AuthMiddleware`
// variant here would permanently strip strategy support from every
// request and turn every API-key call into a 401 with the unhelpful
// "no strategy ran" debug_reason.
func (e *Engine) buildAuthMiddleware() {
var inner forge.Middleware
bindCfg := e.DPoPBindingConfig()
bindCfg.CookieNameResolver = e.resolveSessionCookieName
bindCfg.JWTSessionChecker = e.jwtSessionChecker
bindCfg.ExpectedAudienceResolver = e.resolveExpectedAudience
bindCfg.PrincipalResolver = e.ResolvePrincipalByRef
if e.HasJWT() {
inner = middleware.AuthMiddlewareWithJWT(
e.ResolveSessionByToken,
e.ResolveUser,
e.Strategies(),
e,
e.Logger(),
bindCfg,
)
} else {
// Always pass the strategies registry — even when empty at
// build time it will be populated by Start before the first
// request lands. The registry pointer is stable; the
// middleware iterates it on each request.
inner = middleware.AuthMiddlewareWithStrategies(
e.ResolveSessionByToken,
e.ResolveUser,
e.Strategies(),
e.Logger(),
bindCfg,
)
}
// Wrap with cookie-to-header bridge: when no Authorization header is
// present, read the auth_token cookie (set during browser login) or
// the dynamic session cookie and inject it as a Bearer token.
//
// The bridge also records the value it wrote. Everything downstream still
// reads one credential shape, but RFC 9449 section 7.1 is a rule about the
// Authorization header, and a bound session presented by cookie needs a
// proof rather than a scheme it has no way to set. Losing that fact in here
// made every bound cookie session a permanent 401, which since sign-in
// started binding is every first-party sign-in under mode required.
e.authMiddleware = func(next forge.Handler) forge.Handler {
return func(ctx forge.Context) error {
r := ctx.Request()
if r.Header.Get("Authorization") == "" {
bridged := ""
if cookie, err := r.Cookie("auth_token"); err == nil && cookie.Value != "" {
bridged = cookie.Value
} else {
// Fall back to the dynamic session cookie name from settings.
cookieName := e.resolveSessionCookieName(ctx.Context())
if cookie, err := r.Cookie(cookieName); err == nil && cookie.Value != "" {
bridged = cookie.Value
}
}
if bridged != "" {
r.Header.Set("Authorization", "Bearer "+bridged)
ctx.WithContext(middleware.WithCookieBridgedToken(ctx.Context(), bridged))
}
}
return inner(next)(ctx)
}
}
}
// AuthMiddleware returns the engine's fully-configured non-blocking
// authentication middleware (cookie bridge + JWT + strategies). Populates
// user context when a valid token is present, passes through otherwise.
// Applied globally by the extension.
func (e *Engine) AuthMiddleware() forge.Middleware { return e.authMiddleware }
// AuthRegistry returns the forge auth provider registry. Plugins can register
// their own auth providers and create middleware via registry.Middleware().
func (e *Engine) AuthRegistry() auth.Registry { return e.authRegistry }
// SetAuthRegistry sets the forge auth provider registry. Called by the
// extension after obtaining the registry from the DI container.
func (e *Engine) SetAuthRegistry(r auth.Registry) { e.authRegistry = r }
// registerSessionAuthProvider registers the core "session" auth provider
// with the forge auth registry. This must be called before plugin OnInit
// so plugins can reference "session" in their auth declarations.
func (e *Engine) registerSessionAuthProvider() {
if e.authRegistry == nil {
e.logger.Debug("authsome: no auth registry available, skipping session provider registration")
return
}
provider := authprovider.
NewSessionProvider(e.ResolveSessionByToken, e.ResolveUser, e.logger, e.resolveSessionCookieName).
WithDPoP(e.DPoPBindingConfig())
if err := e.authRegistry.Register(provider); err != nil {
e.logger.Warn("authsome: failed to register session auth provider",
log.String("error", err.Error()),
)
} else {
e.logger.Info("authsome: registered 'session' auth provider with forge auth registry")
}
// The provider above accepts a bearer header or the session cookie, but
// one provider declares one security scheme, and its scheme says bearer.
// Registering the cookie half separately is what puts the browser flow
// into the OpenAPI document, and therefore into every generated client.
// Both delegate to the same Authenticate, so they cannot disagree about
// what a valid session is.
if err := e.authRegistry.Register(authprovider.NewCookieSessionProvider(provider)); err != nil {
e.logger.Warn("authsome: failed to register session-cookie auth provider",
log.String("error", err.Error()),
)
} else {
e.logger.Info("authsome: registered 'session-cookie' auth provider with forge auth registry")
}
}
// resolveSessionCookieName returns the session cookie name for the given
// context by reading from dynamic settings. Falls back to the default
// "authsome_session_token" when settings are unavailable or unset.
func (e *Engine) resolveSessionCookieName(ctx context.Context) string {
mgr := e.Settings()
if mgr == nil {
return "authsome_session_token"
}
opts := settings.ResolveOpts{}
if appID, ok := middleware.AppIDFrom(ctx); ok {
opts.AppID = appID.String()
}
name, err := settings.Get(ctx, mgr, SettingCookieName, opts)
if err != nil || name == "" {
return "authsome_session_token"
}
return name
}
// resolveExpectedAudience returns the resource identifiers this deployment
// answers to for the app that minted the presented token, or nil to disable
// the check.
//
// appID comes from the token itself (sess.AppID or claims.AppID), not from the
// request context. resolveSessionCookieName reads the request's app id because
// picking a cookie name is a property of the inbound call, but the audience
// check is a property of the credential. The request only carries an app id
// when PublishableKeyMiddleware ran and the caller sent X-Publishable-Key,
// both optional, so reading it here would let a caller disable the check by
// dropping a header.
//
// The fail-open on a settings error is deliberate. Failing closed would turn a
// settings outage into a total authentication outage across every app, and the
// audience check is a second line of defence sitting behind the token's own
// signature, which has already been verified by the time this runs. Do not
// "harden" this into a fail-closed check without understanding that trade.
func (e *Engine) resolveExpectedAudience(ctx context.Context, appID string) []string {
mgr := e.Settings()
if mgr == nil {
return nil
}
opts := settings.ResolveOpts{AppID: appID}
identifier, err := settings.Get(ctx, mgr, SettingResourceIdentifier, opts)
if err != nil || identifier == "" {
return nil
}
return []string{identifier}
}
// jwtSessionChecker checks whether a JWT's session ID still exists in the
// store. This enables JWT revocation — revoked sessions are rejected even if
// the JWT signature is valid. The SettingJWTRequireActiveSession setting
// controls whether this check is active; when disabled, a non-nil sentinel
// session is returned to skip binding checks.
func (e *Engine) jwtSessionChecker(sessionIDStr string) (*session.Session, error) {
ctx := context.Background()
// Check if the feature is enabled via dynamic settings.
mgr := e.Settings()
if mgr != nil {
enabled, _ := settings.Get(ctx, mgr, SettingJWTRequireActiveSession, settings.ResolveOpts{}) //nolint:errcheck // best-effort
if !enabled {
return nil, nil //nolint:nilnil // nil,nil signals "feature disabled, skip check"
}
}
sessID, err := id.ParseSessionID(sessionIDStr)
if err != nil {
return nil, fmt.Errorf("authsome: invalid session ID in JWT: %w", err)
}
return e.store.GetSession(ctx, sessID)
}
// ensureAuthRegistry creates a local in-memory auth registry if no external
// one was provided (e.g. forge auth extension not registered in the app).
// This ensures AuthRegistry() never returns nil and plugins can always
// register providers and create middleware.
func (e *Engine) ensureAuthRegistry() {
if e.authRegistry != nil {
return
}
e.authRegistry = auth.NewRegistry(nil, e.logger)
e.logger.Debug("authsome: created local auth registry (forge auth extension not available)")
}
// InitPlugins builds the auth middleware, registers the session auth provider,
// and calls OnInit on all registered plugins. Idempotent — safe to call
// multiple times. The extension calls this before route registration so
// plugins can set up dependencies that RegisterRoutes relies on.
// A plugin whose OnInit fails aborts initialization: pluginsInitialized stays
// false so a caller that recovers can retry, and the error propagates rather
// than leaving the engine running with that plugin's control absent.
func (e *Engine) InitPlugins(ctx context.Context) error {
if e.pluginsInitialized {
return nil
}
e.buildAuthMiddleware()
e.ensureAuthRegistry()
e.registerSessionAuthProvider()
if err := e.plugins.EmitOnInit(ctx, e); err != nil {
return fmt.Errorf("authsome: init plugins: %w", err)
}
e.pluginsInitialized = true
return nil
}
// Start initializes the engine, runs migrations, and starts plugins.
func (e *Engine) Start(ctx context.Context) error {
if e.started {
return nil
}
// Run store migrations (idempotent — may have been called earlier via EnsureMigrated).
if err := e.EnsureMigrated(ctx); err != nil {
return err
}
// Register webhook event catalog with relay (before bootstrap so
// events emitted during bootstrap are recognized).
if e.relay != nil {
if err := e.relay.RegisterEventTypes(ctx, bridge.WebhookEventCatalog()); err != nil {
e.logger.Warn("authsome: failed to register webhook event catalog",
log.String("error", err.Error()),
)
}
}
// Initialize plugins (idempotent — may have been called earlier by
// the extension before route registration).
if err := e.InitPlugins(ctx); err != nil {
return err
}
// Seed per-app session configs (from code options or YAML config).
for _, cfg := range e.pendingAppSessCfgs {
if err := e.store.SetAppSessionConfig(ctx, cfg); err != nil {
e.logger.Warn("authsome: failed to seed app session config",
log.String("app_id", cfg.AppID.String()),
log.String("error", err.Error()),
)
}
}
e.pendingAppSessCfgs = nil
// Bootstrap platform app (if configured).
if e.bootstrapCfg != nil {
if err := e.bootstrap(ctx); err != nil {
return err
}
}
// Register authsome resource types with Warden (idempotent).
// This must run AFTER bootstrap so that platformAppID is set and
// resource types are created with the correct tenant ID.
if e.wardenEng != nil {
e.registerWardenResourceTypes(ctx)
}
// Distribute the resolved app ID to plugins that need it.
// This must happen after bootstrap (which may create the platform app).
if appID := e.config.AppID; appID != "" {
for _, p := range e.plugins.Plugins() {
type appIDSetter interface {
SetAppID(string)
}
if s, ok := p.(appIDSetter); ok {
s.SetAppID(appID)
}
}
}
// Auto-register strategies from plugins implementing StrategyProvider.
for _, p := range e.plugins.Plugins() {
if sp, ok := p.(plugin.StrategyProvider); ok {
e.strategies.Register(sp.Strategy(), sp.StrategyPriority())
e.logger.Info("authsome: auto-registered strategy from plugin",
log.String("plugin", p.Name()),
log.String("strategy", sp.Strategy().Name()),
)
}
}
// Auto-register settings from plugins implementing SettingsProvider.
for _, p := range e.plugins.Plugins() {
if sp, ok := p.(plugin.SettingsProvider); ok {
if err := sp.DeclareSettings(e.settingsMgr); err != nil {
e.logger.Warn("authsome: failed to register plugin settings",
log.String("plugin", p.Name()),
log.String("error", err.Error()),
)
}
}
}
// Register metrics collector as a hook handler
if e.metrics != nil {
e.hooks.On("metrics", func(_ context.Context, event *hook.Event) error {
outcome := "success"
if event.Err != nil {
outcome = "failure"
}
e.metrics.RecordEvent(event.Action, event.Resource, outcome, event.Tenant, 0)
return nil
})
}
// Register security event recorder as a hook handler
if e.securityEvents != nil {
e.hooks.On("security_events", func(ctx context.Context, event *hook.Event) error {
outcome := "success"
if event.Err != nil {
outcome = "failure"
}
return e.securityEvents.RecordSecurityEvent(ctx, &securityevent.Event{
Action: event.Action,
Outcome: outcome,
Metadata: event.Metadata,
CreatedAt: event.Timestamp,
})
})
}
e.started = true
return nil
}
// Health checks the health of the engine by pinging its store.
func (e *Engine) Health(ctx context.Context) error {
return e.store.Ping(ctx)
}
// Stop gracefully shuts down the engine and all plugins.
func (e *Engine) Stop(ctx context.Context) error {
if !e.started {
return nil
}
e.plugins.EmitOnShutdown(ctx)
e.started = false
return nil
}
// registerWardenResourceTypes registers authsome's default resource type
// schemas with the Warden store. The operation is idempotent — duplicate
// errors are silently ignored.
func (e *Engine) registerWardenResourceTypes(ctx context.Context) {
tenantID := e.config.AppID
if !e.platformAppID.IsNil() {
tenantID = e.platformAppID.String()
}
for _, schema := range authz.DefaultSchemas() {
rt := &resourcetype.ResourceType{
ID: wardenid.NewResourceTypeID(),
TenantID: tenantID,
AppID: tenantID,
Name: schema.Name,
Description: schema.Description,
Relations: schema.Relations,
Permissions: schema.Permissions,
}
if err := e.wardenEng.Store().CreateResourceType(ctx, rt); err != nil {
// Idempotent — ignore duplicate/already-exists errors.
e.logger.Debug("authsome: resource type may already exist",
log.String("name", schema.Name),
log.String("error", err.Error()),
)
}
}
e.logger.Info("authsome: warden resource types registered",
log.Int("count", len(authz.DefaultSchemas())),
)
}
// ──────────────────────────────────────────────────
// Accessors
// ──────────────────────────────────────────────────
// Compile-time check: *Engine must satisfy plugin.Engine.
var _ plugin.Engine = (*Engine)(nil)
// Store returns the persistence backend.
func (e *Engine) Store() store.Store { return e.store }
// GetUser returns a user by ID. This method allows the Engine to satisfy
// narrow interfaces (e.g. notification plugin's userLookup) without
// exposing the full store.
func (e *Engine) GetUser(ctx context.Context, userID id.UserID) (*user.User, error) {
return e.store.GetUser(ctx, userID)
}
// GetUserByEmail looks up a user by any of their email addresses (primary or
// secondary) within an app. Returns store.ErrNotFound when no match exists.
func (e *Engine) GetUserByEmail(ctx context.Context, appID id.AppID, email string) (*user.User, error) {
return e.store.GetUserByAnyEmail(ctx, appID, id.Nil, email)
}
// Plugins returns the plugin registry.
func (e *Engine) Plugins() *plugin.Registry { return e.plugins }
// Plugin returns a registered plugin by name, or nil if not found.
func (e *Engine) Plugin(name string) plugin.Plugin { return e.plugins.Plugin(name) }
// Hooks returns the global event bus.
func (e *Engine) Hooks() *hook.Bus { return e.hooks }
// SwitchActiveOrg sets the active organization on an existing session.
// The session's user must be a member of newOrgID — verified via the
// organization plugin. When the user is not a member the org-plugin
// returns ErrOrgNotMember (or equivalent) and we propagate.
//
// Returns the updated session so callers (HTTP handlers) can re-issue
// the cookie / token with the new OrgID claim if appropriate.
//
// When newOrgID is empty the active org is cleared (legitimate use:
// "leave the current org and stay logged out of any org").
func (e *Engine) SwitchActiveOrg(ctx context.Context, sessionID id.SessionID, newOrgID id.OrgID) (*session.Session, error) {
sess, err := e.store.GetSession(ctx, sessionID)
if err != nil {
return nil, fmt.Errorf("authsome: get session: %w", err)
}
if !newOrgID.IsNil() {
// Membership check via the organization plugin. Plugin name is
// stable so the lookup is cheap; we tolerate the plugin not
// being registered (auth-only deployments without orgs) by
// returning a clear error rather than crashing on nil.
orgP, ok := e.plugins.Plugin("organization").(orgMembershipChecker)
if !ok || orgP == nil {
return nil, fmt.Errorf("authsome: organization plugin not registered; cannot switch org")
}
orgs, err := orgP.ListUserOrganizations(ctx, sess.UserID)
if err != nil {
return nil, fmt.Errorf("authsome: list user orgs for membership check: %w", err)
}
matched := false
for _, o := range orgs {
if o.ID == newOrgID {
matched = true
break
}
}
if !matched {
return nil, fmt.Errorf("authsome: user is not a member of org %s", newOrgID)
}
}
sess.OrgID = newOrgID
if err := e.store.UpdateSession(ctx, sess); err != nil {
return nil, fmt.Errorf("authsome: update session: %w", err)
}
e.hooks.Emit(ctx, &hook.Event{
Action: hook.ActionSessionCreate, // closest semantic action; bespoke ActionSessionSwitchOrg can be added later
Resource: hook.ResourceSession,
ResourceID: sess.ID.String(),
ActorID: sess.UserID.String(),
Tenant: newOrgID.String(),
Metadata: map[string]string{"event": "switch_active_org"},
})
return sess, nil
}
// orgMembershipChecker is the narrow contract SwitchActiveOrg needs
// from the organization plugin. Defined locally so the engine doesn't
// import plugins/organization (would create a cycle).
type orgMembershipChecker interface {
ListUserOrganizations(ctx context.Context, userID id.UserID) ([]*organization.Organization, error)
}
// DefaultAppID returns the configured app ID string.
func (e *Engine) DefaultAppID() string { return e.config.AppID }
// BasePath returns the URL prefix for auth routes.
func (e *Engine) BasePath() string { return e.config.BasePath }
// Strategies returns the strategy registry.
func (e *Engine) Strategies() *strategy.Registry { return e.strategies }
// HasStrategies returns true if any authentication strategies are registered.
func (e *Engine) HasStrategies() bool { return len(e.strategies.Strategies()) > 0 }
// Logger returns the engine logger.
func (e *Engine) Logger() log.Logger { return e.logger }
// Config returns the engine configuration.
func (e *Engine) Config() Config { return e.config }
// SessionConfigForApp returns the resolved session config for an app,
// applying per-app and optional per-environment overrides on top of the
// global defaults. Plugins should use this instead of hardcoding their
// own session config.
func (e *Engine) SessionConfigForApp(ctx context.Context, appID id.AppID, envIDs ...id.EnvironmentID) account.SessionConfig {
return e.sessionConfigForApp(ctx, appID, envIDs...)
}
// Chronicle returns the audit trail bridge (may be nil).
func (e *Engine) Chronicle() bridge.Chronicle { return e.chronicle }
// SetChronicle replaces the chronicle implementation. Intended for tests;
// not safe for concurrent use after Start.
func (e *Engine) SetChronicle(ch bridge.Chronicle) { e.chronicle = ch }
// Authorizer returns the authorization bridge (may be nil).
func (e *Engine) Authorizer() bridge.Authorizer { return e.authorizer }
// KeyManager returns the key management bridge (may be nil).
func (e *Engine) KeyManager() bridge.KeyManager { return e.keyManager }
// Relay returns the event relay bridge (may be nil).
func (e *Engine) Relay() bridge.EventRelay { return e.relay }
// Mailer returns the email bridge (may be nil).
func (e *Engine) Mailer() bridge.Mailer { return e.mailer }
// SMSSender returns the SMS bridge (may be nil).
func (e *Engine) SMSSender() bridge.SMSSender { return e.sms }
// Herald returns the Herald notification bridge (may be nil).
func (e *Engine) Herald() bridge.Herald { return e.heraldBridge }
// Vault returns the secrets/feature-flag/config bridge (may be nil).
func (e *Engine) Vault() bridge.Vault { return e.vault }
// TokenEncryptor returns the at-rest Encryptor used for sensitive opaque
// payloads such as third-party OAuth access/refresh tokens. Always non-nil
// after NewEngine — falls back to bridge.NoopEncryptor when no key is
// configured. Plugins that persist provider tokens should wrap their store
// using this encryptor (see plugins/social.NewEncryptedStore).
func (e *Engine) TokenEncryptor() bridge.Encryptor {
if e.tokenEncryptor == nil {
return bridge.NoopEncryptor{}
}
return e.tokenEncryptor
}
// Dispatcher returns the job queue bridge (may be nil).
func (e *Engine) Dispatcher() bridge.Dispatcher { return e.dispatcher }
// Ledger returns the billing/metering bridge (may be nil).
func (e *Engine) Ledger() bridge.Ledger { return e.ledger }
// LedgerEngine returns the first-class ledger billing engine (may be nil).
func (e *Engine) LedgerEngine() *xledger.Ledger { return e.ledgerEng }
// LedgerStore returns the underlying ledger store for direct query access
// (e.g. plan/feature/subscription listing). Returns nil if no ledger engine
// was provided via WithLedgerEngine.
func (e *Engine) LedgerStore() ledgerstore.Store {
if e.ledgerEng != nil {
return e.ledgerEng.Store()
}
return nil
}
// SetLedgerEngine wires a ledger engine into the authsome engine after
// construction. This is the late-binding counterpart to WithLedgerEngine,
// intended for hosts that cannot resolve the ledger at engine-build time
// (typical when both authsome and ledger live in a DI container whose
// registration order is not guaranteed).
//
// It also updates the bridge.Ledger adapter so hook-based consumers see a
// real ledger instead of the noop. Callers are still responsible for
// propagating the new ledger to plugins that captured their own reference
// during OnInit — see Engine.rebindLedgerOnPlugins.
func (e *Engine) SetLedgerEngine(l *xledger.Ledger) {
e.ledgerEng = l
if l != nil {
e.ledger = ledgeradapter.New(l)
}
}
// ledgerRebindable is the optional interface implemented by plugins that
// captured a ledger reference during OnInit and need to be notified when
// the engine's ledger is rebound after construction.
type ledgerRebindable interface {
SetLedger(*xledger.Ledger)
SetLedgerStore(ledgerstore.Store)
}
// RebindLedgerOnPlugins pushes the engine's current ledger engine and store
// into any plugin that implements SetLedger / SetLedgerStore. Safe to call
// multiple times; no-op when the engine has no ledger.
func (e *Engine) RebindLedgerOnPlugins() {
if e.ledgerEng == nil || e.plugins == nil {
return
}
ledgerStore := e.ledgerEng.Store()
for _, p := range e.plugins.Plugins() {
if rb, ok := p.(ledgerRebindable); ok {
rb.SetLedger(e.ledgerEng)
rb.SetLedgerStore(ledgerStore)
}
}
}
// MetricsCollector returns the metrics collector bridge (may be nil).
func (e *Engine) MetricsCollector() bridge.MetricsCollector { return e.metrics }
// CeremonyStore returns the ceremony state store for short-lived auth
// ceremony sessions. Returns an in-memory store if none was configured.
func (e *Engine) CeremonyStore() ceremony.Store {
if e.ceremonyStore != nil {
return e.ceremonyStore
}
return ceremony.NewMemory()
}
// RateLimiter returns the rate limiter (may be nil).
func (e *Engine) RateLimiter() ratelimit.Limiter { return e.rateLimiter }
// ProtectedResourceMetadataURL returns the configured RFC 9728 metadata URL.
func (e *Engine) ProtectedResourceMetadataURL() string {
return e.config.ProtectedResourceMetadataURL
}
// Lockout returns the account lockout tracker (may be nil).
func (e *Engine) Lockout() lockout.Tracker { return e.lockout }
// PasswordHistory returns the password history store (may be nil).
func (e *Engine) PasswordHistory() account.PasswordHistoryStore { return e.passwordHistory }
// SecurityEvents returns the security event store (may be nil).
func (e *Engine) SecurityEvents() securityevent.Store { return e.securityEvents }
// Warden returns the first-class authorization engine (may be nil).
func (e *Engine) Warden() *warden.Engine { return e.wardenEng }
// Keysmith returns the first-class key management engine (may be nil).
func (e *Engine) Keysmith() *keysmith.Engine { return e.keysmithEng }
// Settings returns the dynamic settings manager (may be nil).
func (e *Engine) Settings() *settings.Manager { return e.settingsMgr }
// DB returns the database handle so plugins can create their own persistent
// stores. Returns nil if not set.
func (e *Engine) DB() *grove.DB { return e.db }
// ──────────────────────────────────────────────────
// Client configuration types
// ──────────────────────────────────────────────────
// ClientConfigResponse is the public client-facing configuration returned
// by the /client-config endpoint. It tells the frontend SDK which auth
// methods are enabled, available providers, branding, etc.
type ClientConfigResponse struct {
Version string `json:"version"`
AppID string `json:"app_id"`
SignupEnabled bool `json:"signup_enabled"`
Branding *ClientConfigBranding `json:"branding,omitempty"`
Password *ClientConfigToggle `json:"password,omitempty"`
Social *ClientConfigSocial `json:"social,omitempty"`
Passkey *ClientConfigToggle `json:"passkey,omitempty"`
MFA *ClientConfigMFA `json:"mfa,omitempty"`
MagicLink *ClientConfigToggle `json:"magiclink,omitempty"`
SSO *ClientConfigSSO `json:"sso,omitempty"`
EmailVerification *ClientConfigEmailVerification `json:"email_verification,omitempty"`
DeviceAuthorization *ClientConfigToggle `json:"device_authorization,omitempty"`