-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.go
More file actions
518 lines (429 loc) · 21.4 KB
/
Copy pathplugin.go
File metadata and controls
518 lines (429 loc) · 21.4 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
// Package plugin defines the plugin system for AuthSome v0.5.0.
// Plugins implement the base Plugin interface and optionally implement
// any combination of lifecycle and event hook interfaces.
//
// The registry type-caches plugins at registration time so emit calls
// iterate only over plugins implementing the relevant hook.
package plugin
import (
"context"
log "github.com/xraph/go-utils/log"
"github.com/xraph/grove"
"github.com/xraph/forge"
"github.com/xraph/forge/extensions/auth"
"github.com/xraph/authsome/account"
"github.com/xraph/authsome/apikey"
"github.com/xraph/authsome/bridge"
"github.com/xraph/authsome/ceremony"
"github.com/xraph/authsome/dpop"
"github.com/xraph/authsome/hook"
"github.com/xraph/authsome/id"
"github.com/xraph/authsome/organization"
"github.com/xraph/authsome/principal"
"github.com/xraph/authsome/ratelimit"
"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/migrate"
)
// Plugin is the base interface that all plugins must implement.
type Plugin interface {
Name() string
}
// ──────────────────────────────────────────────────
// Engine interface
// ──────────────────────────────────────────────────
// Engine is the typed interface that plugins receive during OnInit. It
// exposes the engine's capabilities without importing the concrete
// authsome.Engine type (which would create an import cycle).
//
// All commonly-used methods are included here so plugins can call them
// directly instead of ad-hoc type assertions. For specialised
// capabilities that would cause import cycles (e.g. warden, keysmith,
// ledger engines), use the optional interfaces below.
type Engine interface {
// ── Persistence ──
// Store returns the aggregate persistence store.
Store() store.Store
// DB returns the raw database handle. Returns nil if not set.
DB() *grove.DB
// ── Plugin system ──
// Plugins returns the plugin registry.
Plugins() *Registry
// Plugin returns a registered plugin by name, or nil if not found.
Plugin(name string) Plugin
// Hooks returns the hook event bus.
Hooks() *hook.Bus
// ── Observability ──
// Logger returns the engine's logger.
Logger() log.Logger
// ── Dynamic settings ──
// Settings returns the dynamic settings manager.
Settings() *settings.Manager
// ── Bridges ──
Chronicle() bridge.Chronicle
Relay() bridge.EventRelay
Herald() bridge.Herald
Mailer() bridge.Mailer
SMSSender() bridge.SMSSender
Ledger() bridge.Ledger
// TokenEncryptor returns the at-rest Encryptor used for sensitive
// opaque payloads such as third-party OAuth access/refresh tokens.
// Always non-nil — falls back to bridge.NoopEncryptor when no key
// is configured (with a startup warning).
TokenEncryptor() bridge.Encryptor
// ── Session / token ──
// SessionConfigForApp resolves per-app (and optional per-environment)
// session configuration.
SessionConfigForApp(ctx context.Context, appID id.AppID, envIDs ...id.EnvironmentID) account.SessionConfig
// TokenFormatForApp returns the token format configured for an app.
TokenFormatForApp(appID string) tokenformat.Format
// CeremonyStore returns the store for short-lived ceremony state.
CeremonyStore() ceremony.Store
// APIKeyStore returns the API key store.
APIKeyStore() apikey.Store
// SecurityEvents returns the queryable security event store, or nil when
// the engine was built without one.
//
// Plugins write here directly rather than emitting a hook. The hook-bus
// bridge builds its Event from Action, Outcome, Metadata and CreatedAt
// only, never setting AppID, and securityevent.Query filters on AppID, so
// anything recorded that way is written but cannot be read back.
SecurityEvents() securityevent.Store
// DPoPValidator returns the RFC 9449 proof validator. Never nil.
DPoPValidator() *dpop.Validator
// DPoPNonceSigner returns the DPoP nonce signer, or nil when no signing
// secret could be derived.
DPoPNonceSigner() *dpop.NonceSigner
// DPoPModeForApp resolves an app's DPoP mode. Fold a per-client value in
// with dpop.MaxMode; a client value must never lower the app's.
DPoPModeForApp(ctx context.Context, appID id.AppID) dpop.Mode
// DPoPNonceRequiredForApp reports whether an app demands a nonce.
DPoPNonceRequiredForApp(ctx context.Context, appID id.AppID) bool
// ── User / session resolution ──
// ResolveSessionByToken resolves a session from its opaque token.
ResolveSessionByToken(token string) (*session.Session, error)
// ResolveUser resolves a user by ID string.
ResolveUser(userID string) (*user.User, error)
// GetUser fetches a user by typed ID.
GetUser(ctx context.Context, userID id.UserID) (*user.User, error)
// ── Role management ──
// EnsureDefaultRole assigns the default role to a user if none is set.
EnsureDefaultRole(ctx context.Context, appID id.AppID, userID id.UserID)
// ── Principals ──
// ResolvePrincipal resolves any caller, human or otherwise, by ref.
// Use this rather than ResolveUser when a plugin must work for agents and
// workloads as well as people.
ResolvePrincipal(ctx context.Context, ref principal.Ref) (*principal.Principal, error)
// PrincipalStore returns the principal and delegation store.
PrincipalStore() principal.Store
// Can is the chain-aware authorization check. Pass an empty chain for an
// ordinary single-subject check.
Can(ctx context.Context, subject principal.Ref, actors principal.Chain,
action, resource string) (bool, error)
// ── Auth ──
// AuthMiddleware returns the engine's non-blocking authentication
// middleware (cookie bridge + session resolver + JWT + strategies).
// Populates user context when a valid token is present but passes
// through unauthenticated requests. Applied globally by the extension.
AuthMiddleware() forge.Middleware
// AuthRegistry returns the forge auth provider registry. Plugins can:
// - Register custom auth providers (API keys, SSO, etc.) via Register()
// - Create blocking middleware via Middleware("session", "api-key")
// - Use forge.WithGroupAuth("session") for OpenAPI + enforcement
AuthRegistry() auth.Registry
// ── Rate limiting ──
// RateLimiter returns the engine's rate limiter. May be nil.
RateLimiter() ratelimit.Limiter
// ── Config accessors ──
// These expose commonly-needed config values without importing
// authsome.Config (which would create an import cycle).
// PlatformAppID returns the platform/bootstrap app ID.
PlatformAppID() id.AppID
// DefaultAppID returns the configured app ID string.
DefaultAppID() string
// BasePath returns the URL prefix for auth routes.
BasePath() string
}
// ──────────────────────────────────────────────────
// Optional engine capability interfaces
// ──────────────────────────────────────────────────
//
// Plugins that need specialised engine capabilities (not on the core
// Engine interface) can type-assert against these exported interfaces
// instead of defining private ad-hoc interfaces.
// PermissionChecker is optionally implemented by engines that support
// RBAC permission checking. Mirrors middleware.PermissionChecker to
// avoid importing the middleware package from the plugin package.
type PermissionChecker interface {
HasPermission(ctx context.Context, userID id.UserID, action, resource string) (bool, error)
}
// LedgerEngineProvider is optionally implemented by engines with a
// first-class billing/ledger engine.
type LedgerEngineProvider interface {
LedgerEngine() any
}
// LedgerStoreProvider is optionally implemented by engines with a
// ledger store for direct query access.
type LedgerStoreProvider interface {
LedgerStore() any
}
// SessionRevoker is optionally implemented by engines that can revoke a
// single session by ID. Revoking through this rather than deleting rows
// directly keeps the AfterSessionRevoke hooks, the hook bus and the outbound
// relay firing. *authsome.Engine already satisfies it.
type SessionRevoker interface {
RevokeSession(ctx context.Context, sessionID id.SessionID) error
}
// DispatcherProvider is optionally implemented by engines that expose a
// background job queue. A plugin that needs deferred work should fall back to
// its own goroutine when the host returns nil. *authsome.Engine already
// satisfies it.
type DispatcherProvider interface {
Dispatcher() bridge.Dispatcher
}
// PrincipalAuthGateProvider is optionally implemented by engines that score
// machine callers (API keys, and anything else authenticating without a
// human sign-in) through the principal-auth hooks before minting a session.
// Returns any, not a named gate type, so this package does not have to
// import a specific plugin's interface (which would create an import cycle
// with a plugin that itself needs the concrete authsome.Engine type, as the
// apikey plugin does). The consuming plugin type-asserts the result against
// its own narrow gate interface. *authsome.Engine satisfies it.
type PrincipalAuthGateProvider interface {
PrincipalAuthGate() any
}
// ──────────────────────────────────────────────────
// Lifecycle hooks
// ──────────────────────────────────────────────────
// OnInit is called during engine initialization. The engine parameter
// provides typed access to all engine capabilities.
type OnInit interface {
OnInit(ctx context.Context, engine Engine) error
}
// OnShutdown is called during engine shutdown.
type OnShutdown interface {
OnShutdown(ctx context.Context) error
}
// ──────────────────────────────────────────────────
// Auth event hooks (signup / signin / signout)
// ──────────────────────────────────────────────────
// BeforeSignUp is called before a new account is created.
type BeforeSignUp interface {
OnBeforeSignUp(ctx context.Context, req *account.SignUpRequest) error
}
// AfterSignUp is called after a new account is created.
type AfterSignUp interface {
OnAfterSignUp(ctx context.Context, u *user.User, s *session.Session) error
}
// BeforeSignIn is called before authentication.
type BeforeSignIn interface {
OnBeforeSignIn(ctx context.Context, req *account.SignInRequest) error
}
// AfterSignIn is called after successful authentication.
type AfterSignIn interface {
OnAfterSignIn(ctx context.Context, u *user.User, s *session.Session) error
}
// BeforeSignOut is called before session termination.
type BeforeSignOut interface {
OnBeforeSignOut(ctx context.Context, sessionID id.SessionID) error
}
// AfterSignOut is called after session termination.
type AfterSignOut interface {
OnAfterSignOut(ctx context.Context, sessionID id.SessionID) error
}
// ──────────────────────────────────────────────────
// Principal auth hooks (non-human callers)
// ──────────────────────────────────────────────────
// BeforePrincipalAuth is called before a credential becomes a session for a
// caller that did not go through sign-in: an API key, a token exchange, a
// workload JWT.
//
// Returning an error denies the authentication. This is the machine-side
// counterpart to BeforeSignIn, and it exists because static API key traffic
// reaches strategy.Authenticate and never fires the sign-in hooks, so every
// risk plugin was blind to it.
type BeforePrincipalAuth interface {
OnBeforePrincipalAuth(ctx context.Context, a *principal.AuthAttempt) error
}
// AfterPrincipalAuth is called once a non-human caller has a session. Errors
// are logged and do not fail the request, matching the other After hooks.
type AfterPrincipalAuth interface {
OnAfterPrincipalAuth(ctx context.Context, a *principal.AuthAttempt, s *session.Session) error
}
// ──────────────────────────────────────────────────
// User lifecycle hooks
// ──────────────────────────────────────────────────
// BeforeUserCreate is called before a user is created.
type BeforeUserCreate interface {
OnBeforeUserCreate(ctx context.Context, u *user.User) error
}
// AfterUserCreate is called after a user is created.
type AfterUserCreate interface {
OnAfterUserCreate(ctx context.Context, u *user.User) error
}
// BeforeUserUpdate is called before a user is updated.
type BeforeUserUpdate interface {
OnBeforeUserUpdate(ctx context.Context, u *user.User) error
}
// AfterUserUpdate is called after a user is updated.
type AfterUserUpdate interface {
OnAfterUserUpdate(ctx context.Context, u *user.User) error
}
// BeforeUserDelete is called before a user is deleted.
type BeforeUserDelete interface {
OnBeforeUserDelete(ctx context.Context, userID id.UserID) error
}
// AfterUserDelete is called after a user is deleted.
type AfterUserDelete interface {
OnAfterUserDelete(ctx context.Context, userID id.UserID) error
}
// ──────────────────────────────────────────────────
// Session lifecycle hooks
// ──────────────────────────────────────────────────
// BeforeSessionCreate is called before a session is created.
type BeforeSessionCreate interface {
OnBeforeSessionCreate(ctx context.Context, s *session.Session) error
}
// AfterSessionCreate is called after a session is created.
type AfterSessionCreate interface {
OnAfterSessionCreate(ctx context.Context, s *session.Session) error
}
// AfterSessionRefresh is called after a session token is refreshed.
type AfterSessionRefresh interface {
OnAfterSessionRefresh(ctx context.Context, s *session.Session) error
}
// AfterSessionRevoke is called after a session is revoked.
type AfterSessionRevoke interface {
OnAfterSessionRevoke(ctx context.Context, sessionID id.SessionID) error
}
// ──────────────────────────────────────────────────
// Organization lifecycle hooks
// ──────────────────────────────────────────────────
// AfterOrgCreate is called after an organization is created.
type AfterOrgCreate interface {
OnAfterOrgCreate(ctx context.Context, o *organization.Organization) error
}
// AfterOrgUpdate is called after an organization is updated.
type AfterOrgUpdate interface {
OnAfterOrgUpdate(ctx context.Context, o *organization.Organization) error
}
// AfterOrgDelete is called after an organization is deleted.
type AfterOrgDelete interface {
OnAfterOrgDelete(ctx context.Context, orgID id.OrgID) error
}
// AfterMemberAdd is called after a member is added to an organization.
type AfterMemberAdd interface {
OnAfterMemberAdd(ctx context.Context, m *organization.Member) error
}
// BeforeMemberRemove is called before a member is removed from an
// organization, while the member record can still be read. AfterMemberRemove
// carries only the id and fires after deletion, so a plugin that needs to know
// which user left which org has to use this hook.
type BeforeMemberRemove interface {
OnBeforeMemberRemove(ctx context.Context, m *organization.Member) error
}
// AfterMemberRemove is called after a member is removed from an organization.
type AfterMemberRemove interface {
OnAfterMemberRemove(ctx context.Context, memberID id.MemberID) error
}
// AfterMemberRoleChange is called after a member's role is changed.
type AfterMemberRoleChange interface {
OnAfterMemberRoleChange(ctx context.Context, m *organization.Member) error
}
// ──────────────────────────────────────────────────
// Account linking
// ──────────────────────────────────────────────────
// AuthMethod describes a single authentication method linked to a user account.
type AuthMethod struct {
Type string `json:"type"` // e.g. "password", "social:google", "passkey", "phone"
Provider string `json:"provider"` // e.g. "google", "github", "password", "phone"
Label string `json:"label"` // Human-readable label, e.g. "Google (user@gmail.com)"
LinkedAt string `json:"linked_at,omitempty"`
}
// AuthMethodContributor is implemented by plugins that can report which
// authentication methods are linked to a user. The engine aggregates these
// to provide a unified "list auth methods" API.
type AuthMethodContributor interface {
Plugin
ListUserAuthMethods(ctx context.Context, userID id.UserID) ([]*AuthMethod, error)
}
// AuthMethodUnlinker is optionally implemented by plugins that support
// unlinking an auth method from a user account.
type AuthMethodUnlinker interface {
Plugin
UnlinkAuthMethod(ctx context.Context, userID id.UserID, provider string) error
CanUnlink(ctx context.Context, userID id.UserID, provider string) bool
}
// ──────────────────────────────────────────────────
// Strategy and provider hooks
// ──────────────────────────────────────────────────
// RouteProvider allows a plugin to register additional HTTP routes.
type RouteProvider interface {
RegisterRoutes(router forge.Router) error
}
// RootRouteProvider is implemented by plugins that must serve routes at the
// origin root rather than under the extension's mount prefix. Well-known
// discovery documents are the only legitimate use: RFC 8414 and RFC 9728
// define their locations relative to the origin, so a prefixed copy is
// invisible to a client that only knows the host.
type RootRouteProvider interface {
RegisterRootRoutes(router forge.Router) error
}
// MigrationProvider allows a plugin to register its own grove migration
// groups. The engine collects these groups and passes them to Store.Migrate()
// so plugin tables are created alongside the core schema. The driverName
// parameter ("pg", "sqlite", "mongo") lets the plugin return driver-specific
// migration groups.
type MigrationProvider interface {
MigrationGroups(driverName string) []*migrate.Group
}
// Extensible allows a plugin to accept sub-plugins.
type Extensible interface {
RegisterSubPlugin(sub Plugin) error
}
// DataExportContributor allows a plugin to contribute data to the GDPR
// user export. The returned key names the data section (e.g. "organizations")
// and data is the payload that will be included in the export.
type DataExportContributor interface {
ExportUserData(ctx context.Context, userID id.UserID) (key string, data any, err error)
}
// SettingsProvider is implemented by plugins that declare configurable
// settings via the dynamic settings system. The engine calls DeclareSettings
// during initialization so the settings are registered before use.
type SettingsProvider interface {
DeclareSettings(m *settings.Manager) error
}
// StrategyProvider is implemented by plugins that contribute an authentication
// strategy to the strategy registry. The engine auto-registers these strategies
// during Start() so they participate in layered auth middleware evaluation.
type StrategyProvider interface {
Plugin
Strategy() strategy.Strategy
StrategyPriority() int
}
// ──────────────────────────────────────────────────
// Notification extensibility
// ──────────────────────────────────────────────────
// NotificationMapping describes a hook-to-notification template mapping
// contributed by an external plugin.
type NotificationMapping struct {
// Template is the Herald template slug (e.g. "billing.payment-failed").
Template string
// Channels lists the channels to send on (e.g. ["email", "inapp"]).
Channels []string
// Enabled controls whether this mapping is active.
Enabled bool
}
// NotificationMappingContributor is implemented by plugins that want to
// contribute notification template mappings. The notification plugin
// collects these during initialization to extend its default mappings.
// Plugin-contributed mappings do not override user-provided config mappings.
type NotificationMappingContributor interface {
Plugin
NotificationMappings() map[string]*NotificationMapping
}