Files
speckle-server/packages/server/modules/shared/services/auth.ts
T
Chuck Driesler b195df37d6 feat(sso): active user sso information (#3432)
* feat(workspaces): add workspace sso feature flag

* feat(workspaceSso): wip validate sso

* feat(workspaces): validate and add sso provider to the workspace with user sso sessions

* feat(workspaces): validate and add sso provider to the workspace with user sso sessions

* WIP

* fix(sso): restructure to handle all branches at end of flow

* fix(sso): add and validate emails used for sso

* fix(sso): park progress

* chore(workspaces): review sso login/valdate

* fix(sso): adjust validate url

* chore(sso): auth header puzzle

* fix(sso): happy-path config

* chore(gql): gqlgen

* fix(sso): almost almost

* fix(sso): auth endpoint

* a lil more terse

* fix(sso): light at the end of the tunnel

* fix(sso): improve catch block error messages

* fix(sso): session lifespan => validUntil

* fix(sso): I think we've got it

* feat(sso): limited workspace values for public sso login

* fix(sso): use factory functions

* fix(sso): til decrypt is single-use

* fix(sso): correct usage of access codes

* fix(sso): use finalize middleware in all routes

* chore(sso): cheeky tweak

* fix(sso): move some types around

* fix(sso): stencil final shape I'm sleepy

* fix(sso): more factories more factories

* fix(sso): on to final boss of factories

* fix(sso): needs a haircut but she works

* fix(sso): init rest w function, not side-effects

* fix(sso): /authn => /sso

* chore(sso): errors

* chore(sso): test test test

* chore(sso): test all the corners

* feat(sso): list workspace sso memberships

* chore(sso): tests, expose in rest

* fix(sso): sketch active user auth

* fix(sso): expose search via gql

* fix(sso): active user session information

* chore(sso): sso session test utils

* chore(sso): test sso session repo/services

* chore(sso): gqlgen

* fix(sso): simplify gql resolver structure

* chore(sso): gqlgen

---------

Co-authored-by: Gergő Jedlicska <gergo@jedlicska.com>
Co-authored-by: Mike Tasset <mike.tasset@gmail.com>
2024-11-05 12:27:46 +00:00

122 lines
3.7 KiB
TypeScript

import { GetStream } from '@/modules/core/domain/streams/operations'
import {
isResourceAllowed,
RoleResourceTargets,
roleResourceTypeToTokenResourceType
} from '@/modules/core/helpers/token'
import {
AuthorizeResolver,
GetUserAclRole,
GetUserServerRole,
ValidateScopes
} from '@/modules/shared/domain/operations'
import { GetRoles } from '@/modules/shared/domain/rolesAndScopes/operations'
import { ForbiddenError } from '@/modules/shared/errors'
import { adminOverrideEnabled } from '@/modules/shared/helpers/envHelper'
import { EventBusEmit } from '@/modules/shared/services/eventBus'
import { isNullOrUndefined, Roles } from '@speckle/shared'
/**
* Validates the scope against a list of scopes of the current session.
*/
export const validateScopesFactory = (): ValidateScopes => async (scopes, scope) => {
const errMsg = `Your auth token does not have the required scope${
scope?.length ? ': ' + scope + '.' : '.'
}`
if (!scopes) throw new ForbiddenError(errMsg, { info: { scope } })
if (scopes.indexOf(scope) === -1 && scopes.indexOf('*') === -1)
throw new ForbiddenError(errMsg, { info: { scope } })
}
/**
* Checks the userId against the resource's acl.
*/
export const authorizeResolverFactory =
(deps: {
getRoles: GetRoles
adminOverrideEnabled: typeof adminOverrideEnabled
getUserServerRole: GetUserServerRole
getStream: GetStream
getUserAclRole: GetUserAclRole
emitWorkspaceEvent: EventBusEmit
}): AuthorizeResolver =>
async (userId, resourceId, requiredRole, userResourceAccessLimits) => {
userId = userId || null
const roles = await deps.getRoles()
// TODO: Cache these results with a TTL of 1 mins or so, it's pointless to query the db every time we get a ping.
const role = roles.find((r) => r.name === requiredRole)
if (!role) throw new ForbiddenError('Unknown role: ' + requiredRole)
const resourceRuleType = roleResourceTypeToTokenResourceType(role.resourceTarget)
const isResourceLimited =
resourceRuleType &&
!isResourceAllowed({
resourceId,
resourceType: resourceRuleType,
resourceAccessRules: userResourceAccessLimits
})
if (isResourceLimited) {
throw new ForbiddenError('You are not authorized to access this resource.')
}
if (deps.adminOverrideEnabled() && userId) {
const serverRole = await deps.getUserServerRole({ userId })
if (serverRole === Roles.Server.Admin) return
}
let targetWorkspaceId: string | null = null
if (role.resourceTarget === RoleResourceTargets.Streams) {
const stream = await deps.getStream({
userId: userId || undefined,
streamId: resourceId
})
if (!stream) {
throw new ForbiddenError(
`Resource of type ${role.resourceTarget} with ${resourceId} not found`
)
}
targetWorkspaceId = stream.workspaceId
const isPublic = !!stream?.isPublic
if (isPublic && role.weight < 200) return
}
if (role.resourceTarget === RoleResourceTargets.Workspaces) {
targetWorkspaceId = resourceId
}
const userAclRole = userId
? await deps.getUserAclRole({
aclTableName: role.aclTableName,
userId,
resourceId
})
: null
if (!userAclRole) {
throw new ForbiddenError('You are not authorized to access this resource.')
}
const fullRole = roles.find((r) => r.name === userAclRole)
if (fullRole && fullRole.weight < role.weight) {
throw new ForbiddenError('You are not authorized.')
}
if (!isNullOrUndefined(targetWorkspaceId)) {
await deps.emitWorkspaceEvent({
eventName: 'workspace.authorized',
payload: {
workspaceId: targetWorkspaceId,
userId
}
})
}
}