feat(platform-api): multi-audience JWT + Partner CRUD + tenant lifecycle (O.2)
JwtAuthGuard now accepts a comma-separated AUTHENTIK_AUDIENCE
('dezky-portal,dezky-operator'). jose.jwtVerify takes an array and succeeds
on any match — both customer-portal and operator-portal tokens validate
against this service. Per-endpoint guards restrict further.
New OperatorGuard enforces operator-only mutations:
1. JWT audience claim includes 'dezky-operator' (proof from the token
alone that this is a privileged session)
2. ActorService-resolved User has platformAdmin=true (DB check so
revocation works without waiting for the token to expire)
Both required; either alone is insufficient.
Partner module:
- Partner schema: slug, name, domain, status, marginPct, contactInfo,
billingInfo. marginPct is one number per partner (decided in grilling)
- CRUD endpoints under @UseGuards(JwtAuthGuard, OperatorGuard) — every
partner mutation requires operator scope
- GET /partners returns each row with a computed customers count from
aggregating Tenant.partnerId. MRR aggregation deferred until
Subscription gains a price column
- GET /partners/:slug/tenants for the partner detail view
- DELETE soft-terminates (status='terminated') — never hard-delete
because tenants may still reference the partner
Tenant changes:
- partnerId?: Types.ObjectId (ref Partner, indexed sparse) added to
Tenant schema
- UpdateTenantDto accepts partnerId so PATCH can attach/detach
- POST /tenants/:slug/suspend and /resume — operator-only via
OperatorGuard. PATCH already covers plan/domains/partnerId changes
Smoke test: customer-portal session sends POST /api/partners through the
portal proxy → 403 "This endpoint requires an operator-scoped token". The
positive test (operator-token → 200) waits for O.3 when there's an
operator app to mint the right token.
apps/portal/server/api/partners/index.post.ts is a temporary verification
proxy — delete once the operator portal exists.
This commit is contained in:
@@ -3,10 +3,11 @@ import { MongooseModule } from '@nestjs/mongoose'
|
||||
import { User, UserSchema } from '../schemas/user.schema.js'
|
||||
import { ActorService } from './actor.service.js'
|
||||
import { JwtAuthGuard } from './jwt-auth.guard.js'
|
||||
import { OperatorGuard } from './operator.guard.js'
|
||||
|
||||
@Module({
|
||||
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
|
||||
providers: [JwtAuthGuard, ActorService],
|
||||
exports: [JwtAuthGuard, ActorService],
|
||||
providers: [JwtAuthGuard, OperatorGuard, ActorService],
|
||||
exports: [JwtAuthGuard, OperatorGuard, ActorService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
@@ -14,12 +14,19 @@ export class JwtAuthGuard implements CanActivate {
|
||||
private readonly logger = new Logger(JwtAuthGuard.name)
|
||||
private jwks: ReturnType<typeof createRemoteJWKSet> | null = null
|
||||
private readonly issuer: string
|
||||
private readonly audience: string
|
||||
// AUTHENTIK_AUDIENCE is comma-separated to accept tokens from multiple
|
||||
// OAuth clients (customer portal + operator portal + future surfaces).
|
||||
// jose.jwtVerify with an array succeeds if the token's aud matches any.
|
||||
private readonly audiences: string[]
|
||||
private readonly jwksUri: string
|
||||
|
||||
constructor(config: ConfigService) {
|
||||
this.issuer = config.getOrThrow<string>('AUTHENTIK_ISSUER')
|
||||
this.audience = config.getOrThrow<string>('AUTHENTIK_AUDIENCE')
|
||||
this.audiences = config
|
||||
.getOrThrow<string>('AUTHENTIK_AUDIENCE')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
this.jwksUri = config.getOrThrow<string>('AUTHENTIK_JWKS_URI')
|
||||
}
|
||||
|
||||
@@ -52,7 +59,7 @@ export class JwtAuthGuard implements CanActivate {
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, this.getJwks(), {
|
||||
issuer: this.issuer,
|
||||
audience: this.audience,
|
||||
audience: this.audiences,
|
||||
})
|
||||
req.user = payload as unknown as AuthentikJwtPayload
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common'
|
||||
import { ActorService } from './actor.service.js'
|
||||
import type { AuthentikJwtPayload } from './jwt-payload.interface.js'
|
||||
|
||||
// Applied AFTER JwtAuthGuard. Enforces that the request is coming from an
|
||||
// operator session — both proofs required:
|
||||
// 1. Token audience is 'dezky-operator' (the operator OAuth client)
|
||||
// 2. The DB-resolved User has platformAdmin=true
|
||||
//
|
||||
// Either proof alone is insufficient. The token claim makes "is this a
|
||||
// privileged session" derivable from the JWT alone; the DB check ensures
|
||||
// revocation works without waiting for the token to expire.
|
||||
@Injectable()
|
||||
export class OperatorGuard implements CanActivate {
|
||||
constructor(private readonly actor: ActorService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest<{ user?: AuthentikJwtPayload }>()
|
||||
const jwt = req.user
|
||||
if (!jwt) {
|
||||
throw new ForbiddenException('Authentication required (JwtAuthGuard must run first)')
|
||||
}
|
||||
|
||||
const aud = Array.isArray(jwt.aud) ? jwt.aud : [jwt.aud]
|
||||
if (!aud.includes('dezky-operator')) {
|
||||
throw new ForbiddenException('This endpoint requires an operator-scoped token')
|
||||
}
|
||||
|
||||
const actor = await this.actor.resolve(jwt)
|
||||
if (!actor.platformAdmin) {
|
||||
throw new ForbiddenException('platformAdmin role required')
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user