From 28a998e518ef02373878b47832743594f22b757a Mon Sep 17 00:00:00 2001 From: bergatco <129839305+bergatco@users.noreply.github.com> Date: Thu, 13 Jun 2024 13:57:10 +0200 Subject: [PATCH] BC-6453 - Add authorization service client module (#5050) --- .../.openapi-generator-ignore | 38 ++ .../.openapi-generator/FILES | 11 + .../.openapi-generator/VERSION | 1 + .../authorization-api-client/api.ts | 18 + .../api/authorization-api.ts | 159 +++++++++ .../authorization-api-client/base.ts | 86 +++++ .../authorization-api-client/common.ts | 150 ++++++++ .../authorization-api-client/configuration.ts | 110 ++++++ .../authorization-api-client/index.ts | 18 + .../authorization-api-client/models/action.ts | 31 ++ .../models/authorization-body-params.ts | 62 ++++ .../models/authorization-context-params.ts | 44 +++ .../models/authorized-reponse.ts | 36 ++ .../authorization-api-client/models/index.ts | 4 + .../authorization-client.adapter.spec.ts | 327 ++++++++++++++++++ .../authorization-client.adapter.ts | 67 ++++ .../authorization-client.module.ts | 29 ++ ...orization-error.loggable-exception.spec.ts | 88 +++++ .../authorization-error.loggable-exception.ts | 27 ++ ...ation-forbidden.loggable-exception.spec.ts | 41 +++ ...horization-forbidden.loggable-exception.ts | 25 ++ .../infra/authorization-client/error/index.ts | 2 + .../src/infra/authorization-client/index.ts | 2 + .../src/shared/controller/swagger.spec.ts | 6 +- apps/server/src/shared/controller/swagger.ts | 4 +- package.json | 1 + scripts/generate-client.js | 12 +- sonar-project.properties | 4 +- src/swagger.js | 4 +- 29 files changed, 1396 insertions(+), 11 deletions(-) create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator-ignore create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator/FILES create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator/VERSION create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/api.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/api/authorization-api.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/base.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/common.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/configuration.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/index.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/models/action.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/models/authorization-body-params.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/models/authorization-context-params.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/models/authorized-reponse.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-api-client/models/index.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-client.adapter.spec.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-client.adapter.ts create mode 100644 apps/server/src/infra/authorization-client/authorization-client.module.ts create mode 100644 apps/server/src/infra/authorization-client/error/authorization-error.loggable-exception.spec.ts create mode 100644 apps/server/src/infra/authorization-client/error/authorization-error.loggable-exception.ts create mode 100644 apps/server/src/infra/authorization-client/error/authorization-forbidden.loggable-exception.spec.ts create mode 100644 apps/server/src/infra/authorization-client/error/authorization-forbidden.loggable-exception.ts create mode 100644 apps/server/src/infra/authorization-client/error/index.ts create mode 100644 apps/server/src/infra/authorization-client/index.ts diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator-ignore b/apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator-ignore new file mode 100644 index 00000000000..bbc533d699f --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator-ignore @@ -0,0 +1,38 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md + +# ignore some general files +.gitignore +.npmignore +git_push.sh + +# ignore all files in the "models" folder +models/* + +# list of allowed files in the "models" folder +!models/action.ts +!models/authorization-body-params.ts +!models/authorization-context-params.ts +!models/authorized-reponse.ts +!models/index.ts \ No newline at end of file diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator/FILES b/apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator/FILES new file mode 100644 index 00000000000..b0b81500e3f --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator/FILES @@ -0,0 +1,11 @@ +api.ts +api/authorization-api.ts +base.ts +common.ts +configuration.ts +index.ts +models/action.ts +models/authorization-body-params.ts +models/authorization-context-params.ts +models/authorized-reponse.ts +models/index.ts diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator/VERSION b/apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator/VERSION new file mode 100644 index 00000000000..93c8ddab9fe --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.6.0 diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/api.ts b/apps/server/src/infra/authorization-client/authorization-api-client/api.ts new file mode 100644 index 00000000000..fc2c3721af2 --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/api.ts @@ -0,0 +1,18 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +export * from './api/authorization-api'; + diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/api/authorization-api.ts b/apps/server/src/infra/authorization-client/authorization-api-client/api/authorization-api.ts new file mode 100644 index 00000000000..73e22786fca --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/api/authorization-api.ts @@ -0,0 +1,159 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from '../configuration'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; +import globalAxios from 'axios'; +// Some imports not used depending on template conditions +// @ts-ignore +import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../common'; +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS, type RequestArgs, BaseAPI, RequiredError, operationServerMap } from '../base'; +// @ts-ignore +import type { ApiValidationError } from '../models'; +// @ts-ignore +import type { AuthorizationBodyParams } from '../models'; +// @ts-ignore +import type { AuthorizedReponse } from '../models'; +/** + * AuthorizationApi - axios parameter creator + * @export + */ +export const AuthorizationApiAxiosParamCreator = function (configuration?: Configuration) { + return { + /** + * + * @summary Checks if user is authorized to perform the given operation. + * @param {AuthorizationBodyParams} authorizationBodyParams + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + authorizationReferenceControllerAuthorizeByReference: async (authorizationBodyParams: AuthorizationBodyParams, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'authorizationBodyParams' is not null or undefined + assertParamExists('authorizationReferenceControllerAuthorizeByReference', 'authorizationBodyParams', authorizationBodyParams) + const localVarPath = `/authorization/by-reference`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication bearer required + // http bearer authentication required + await setBearerAuthToObject(localVarHeaderParameter, configuration) + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(authorizationBodyParams, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * AuthorizationApi - functional programming interface + * @export + */ +export const AuthorizationApiFp = function(configuration?: Configuration) { + const localVarAxiosParamCreator = AuthorizationApiAxiosParamCreator(configuration) + return { + /** + * + * @summary Checks if user is authorized to perform the given operation. + * @param {AuthorizationBodyParams} authorizationBodyParams + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams: AuthorizationBodyParams, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['AuthorizationApi.authorizationReferenceControllerAuthorizeByReference']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + } +}; + +/** + * AuthorizationApi - factory interface + * @export + */ +export const AuthorizationApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { + const localVarFp = AuthorizationApiFp(configuration) + return { + /** + * + * @summary Checks if user is authorized to perform the given operation. + * @param {AuthorizationBodyParams} authorizationBodyParams + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams: AuthorizationBodyParams, options?: any): AxiosPromise { + return localVarFp.authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams, options).then((request) => request(axios, basePath)); + }, + }; +}; + +/** + * AuthorizationApi - interface + * @export + * @interface AuthorizationApi + */ +export interface AuthorizationApiInterface { + /** + * + * @summary Checks if user is authorized to perform the given operation. + * @param {AuthorizationBodyParams} authorizationBodyParams + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof AuthorizationApiInterface + */ + authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams: AuthorizationBodyParams, options?: RawAxiosRequestConfig): AxiosPromise; + +} + +/** + * AuthorizationApi - object-oriented interface + * @export + * @class AuthorizationApi + * @extends {BaseAPI} + */ +export class AuthorizationApi extends BaseAPI implements AuthorizationApiInterface { + /** + * + * @summary Checks if user is authorized to perform the given operation. + * @param {AuthorizationBodyParams} authorizationBodyParams + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof AuthorizationApi + */ + public authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams: AuthorizationBodyParams, options?: RawAxiosRequestConfig) { + return AuthorizationApiFp(this.configuration).authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams, options).then((request) => request(this.axios, this.basePath)); + } +} + diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/base.ts b/apps/server/src/infra/authorization-client/authorization-api-client/base.ts new file mode 100644 index 00000000000..5bcf014a72f --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/base.ts @@ -0,0 +1,86 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from './configuration'; +// Some imports not used depending on template conditions +// @ts-ignore +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; +import globalAxios from 'axios'; + +export const BASE_PATH = "http://localhost:3030/api/v3".replace(/\/+$/, ""); + +/** + * + * @export + */ +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +/** + * + * @export + * @interface RequestArgs + */ +export interface RequestArgs { + url: string; + options: RawAxiosRequestConfig; +} + +/** + * + * @export + * @class BaseAPI + */ +export class BaseAPI { + protected configuration: Configuration | undefined; + + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { + if (configuration) { + this.configuration = configuration; + this.basePath = configuration.basePath ?? basePath; + } + } +}; + +/** + * + * @export + * @class RequiredError + * @extends {Error} + */ +export class RequiredError extends Error { + constructor(public field: string, msg?: string) { + super(msg); + this.name = "RequiredError" + } +} + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/common.ts b/apps/server/src/infra/authorization-client/authorization-api-client/common.ts new file mode 100644 index 00000000000..6c119efb60d --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/common.ts @@ -0,0 +1,150 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from "./configuration"; +import type { RequestArgs } from "./base"; +import type { AxiosInstance, AxiosResponse } from 'axios'; +import { RequiredError } from "./base"; + +/** + * + * @export + */ +export const DUMMY_BASE_URL = 'https://example.com' + +/** + * + * @throws {RequiredError} + * @export + */ +export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) { + if (paramValue === null || paramValue === undefined) { + throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`); + } +} + +/** + * + * @export + */ +export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) { + if (configuration && configuration.apiKey) { + const localVarApiKeyValue = typeof configuration.apiKey === 'function' + ? await configuration.apiKey(keyParamName) + : await configuration.apiKey; + object[keyParamName] = localVarApiKeyValue; + } +} + +/** + * + * @export + */ +export const setBasicAuthToObject = function (object: any, configuration?: Configuration) { + if (configuration && (configuration.username || configuration.password)) { + object["auth"] = { username: configuration.username, password: configuration.password }; + } +} + +/** + * + * @export + */ +export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const accessToken = typeof configuration.accessToken === 'function' + ? await configuration.accessToken() + : await configuration.accessToken; + object["Authorization"] = "Bearer " + accessToken; + } +} + +/** + * + * @export + */ +export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? await configuration.accessToken(name, scopes) + : await configuration.accessToken; + object["Authorization"] = "Bearer " + localVarAccessTokenValue; + } +} + +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (parameter == null) return; + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + +/** + * + * @export + */ +export const setSearchParams = function (url: URL, ...objects: any[]) { + const searchParams = new URLSearchParams(url.search); + setFlattenedQueryParams(searchParams, objects); + url.search = searchParams.toString(); +} + +/** + * + * @export + */ +export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) { + const nonString = typeof value !== 'string'; + const needsSerialization = nonString && configuration && configuration.isJsonMime + ? configuration.isJsonMime(requestOptions.headers['Content-Type']) + : nonString; + return needsSerialization + ? JSON.stringify(value !== undefined ? value : {}) + : (value || ""); +} + +/** + * + * @export + */ +export const toPathString = function (url: URL) { + return url.pathname + url.search + url.hash +} + +/** + * + * @export + */ +export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { + return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; + return axios.request(axiosRequestArgs); + }; +} diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/configuration.ts b/apps/server/src/infra/authorization-client/authorization-api-client/configuration.ts new file mode 100644 index 00000000000..8c97d307cf4 --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/configuration.ts @@ -0,0 +1,110 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface ConfigurationParameters { + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + username?: string; + password?: string; + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + basePath?: string; + serverIndex?: number; + baseOptions?: any; + formDataCtor?: new () => any; +} + +export class Configuration { + /** + * parameter for apiKey security + * @param name security name + * @memberof Configuration + */ + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + username?: string; + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + password?: string; + /** + * parameter for oauth2 security + * @param name security name + * @param scopes oauth2 scope + * @memberof Configuration + */ + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + /** + * override base path + * + * @type {string} + * @memberof Configuration + */ + basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; + /** + * base options for axios calls + * + * @type {any} + * @memberof Configuration + */ + baseOptions?: any; + /** + * The FormData constructor that will be used to create multipart form data + * requests. You can inject this here so that execution environments that + * do not support the FormData class can still run the generated client. + * + * @type {new () => FormData} + */ + formDataCtor?: new () => any; + + constructor(param: ConfigurationParameters = {}) { + this.apiKey = param.apiKey; + this.username = param.username; + this.password = param.password; + this.accessToken = param.accessToken; + this.basePath = param.basePath; + this.serverIndex = param.serverIndex; + this.baseOptions = param.baseOptions; + this.formDataCtor = param.formDataCtor; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } +} diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/index.ts b/apps/server/src/infra/authorization-client/authorization-api-client/index.ts new file mode 100644 index 00000000000..8b762df664e --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/index.ts @@ -0,0 +1,18 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export * from "./api"; +export * from "./configuration"; +export * from "./models"; diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/models/action.ts b/apps/server/src/infra/authorization-client/authorization-api-client/models/action.ts new file mode 100644 index 00000000000..c74334d322b --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/models/action.ts @@ -0,0 +1,31 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +/** + * + * @export + * @enum {string} + */ + +export const Action = { + READ: 'read', + WRITE: 'write' +} as const; + +export type Action = typeof Action[keyof typeof Action]; + + + diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/models/authorization-body-params.ts b/apps/server/src/infra/authorization-client/authorization-api-client/models/authorization-body-params.ts new file mode 100644 index 00000000000..1bf892fbe0f --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/models/authorization-body-params.ts @@ -0,0 +1,62 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +// May contain unused imports in some cases +// @ts-ignore +import type { AuthorizationContextParams } from './authorization-context-params'; + +/** + * + * @export + * @interface AuthorizationBodyParams + */ +export interface AuthorizationBodyParams { + /** + * + * @type {AuthorizationContextParams} + * @memberof AuthorizationBodyParams + */ + 'context': AuthorizationContextParams; + /** + * The entity or domain object the operation should be performed on. + * @type {string} + * @memberof AuthorizationBodyParams + */ + 'referenceType': AuthorizationBodyParamsReferenceType; + /** + * The id of the entity/domain object of the defined referenceType. + * @type {string} + * @memberof AuthorizationBodyParams + */ + 'referenceId': string; +} + +export const AuthorizationBodyParamsReferenceType = { + USERS: 'users', + SCHOOLS: 'schools', + COURSES: 'courses', + COURSEGROUPS: 'coursegroups', + TASKS: 'tasks', + LESSONS: 'lessons', + TEAMS: 'teams', + SUBMISSIONS: 'submissions', + SCHOOL_EXTERNAL_TOOLS: 'school-external-tools', + BOARDNODES: 'boardnodes', + CONTEXT_EXTERNAL_TOOLS: 'context-external-tools' +} as const; + +export type AuthorizationBodyParamsReferenceType = typeof AuthorizationBodyParamsReferenceType[keyof typeof AuthorizationBodyParamsReferenceType]; + + diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/models/authorization-context-params.ts b/apps/server/src/infra/authorization-client/authorization-api-client/models/authorization-context-params.ts new file mode 100644 index 00000000000..055adfae85a --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/models/authorization-context-params.ts @@ -0,0 +1,44 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +// May contain unused imports in some cases +// @ts-ignore +import type { Action } from './action'; +// May contain unused imports in some cases +// @ts-ignore +import type { Permission } from './permission'; + +/** + * + * @export + * @interface AuthorizationContextParams + */ +export interface AuthorizationContextParams { + /** + * + * @type {Action} + * @memberof AuthorizationContextParams + */ + 'action': Action; + /** + * User permissions that are needed to execute the operation. + * @type {Array} + * @memberof AuthorizationContextParams + */ + 'requiredPermissions': Array; +} + + + diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/models/authorized-reponse.ts b/apps/server/src/infra/authorization-client/authorization-api-client/models/authorized-reponse.ts new file mode 100644 index 00000000000..b69c757a07a --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/models/authorized-reponse.ts @@ -0,0 +1,36 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +/** + * + * @export + * @interface AuthorizedReponse + */ +export interface AuthorizedReponse { + /** + * + * @type {string} + * @memberof AuthorizedReponse + */ + 'userId': string; + /** + * + * @type {boolean} + * @memberof AuthorizedReponse + */ + 'isAuthorized': boolean; +} + diff --git a/apps/server/src/infra/authorization-client/authorization-api-client/models/index.ts b/apps/server/src/infra/authorization-client/authorization-api-client/models/index.ts new file mode 100644 index 00000000000..59dfc03282f --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-api-client/models/index.ts @@ -0,0 +1,4 @@ +export * from './action'; +export * from './authorization-body-params'; +export * from './authorization-context-params'; +export * from './authorized-reponse'; diff --git a/apps/server/src/infra/authorization-client/authorization-client.adapter.spec.ts b/apps/server/src/infra/authorization-client/authorization-client.adapter.spec.ts new file mode 100644 index 00000000000..35d08e38221 --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-client.adapter.spec.ts @@ -0,0 +1,327 @@ +import { createMock, DeepMocked } from '@golevelup/ts-jest'; +import { REQUEST } from '@nestjs/core'; +import { Test, TestingModule } from '@nestjs/testing'; +import { AxiosResponse } from 'axios'; +import { Request } from 'express'; +import { + Action, + AuthorizationApi, + AuthorizationBodyParamsReferenceType, + AuthorizedReponse, +} from './authorization-api-client'; +import { AuthorizationClientAdapter } from './authorization-client.adapter'; +import { AuthorizationErrorLoggableException, AuthorizationForbiddenLoggableException } from './error'; + +const jwtToken = 'someJwtToken'; +const requiredPermissions = ['somePermissionA', 'somePermissionB']; + +describe(AuthorizationClientAdapter.name, () => { + let module: TestingModule; + let service: AuthorizationClientAdapter; + let authorizationApi: DeepMocked; + + beforeAll(async () => { + module = await Test.createTestingModule({ + providers: [ + AuthorizationClientAdapter, + { + provide: AuthorizationApi, + useValue: createMock(), + }, + { + provide: REQUEST, + useValue: createMock({ + headers: { + authorization: `Bearer ${jwtToken}`, + }, + }), + }, + ], + }).compile(); + + service = module.get(AuthorizationClientAdapter); + authorizationApi = module.get(AuthorizationApi); + }); + + afterAll(async () => { + await module.close(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); + + describe('checkPermissionsByReference', () => { + describe('when authorizationReferenceControllerAuthorizeByReference resolves successful', () => { + const setup = (props: { isAuthorized: boolean }) => { + const params = { + context: { + action: Action.READ, + requiredPermissions, + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const response = createMock>({ + data: { + isAuthorized: props.isAuthorized, + userId: 'userId', + }, + }); + authorizationApi.authorizationReferenceControllerAuthorizeByReference.mockResolvedValueOnce(response); + + return { params }; + }; + + it('should call authorizationReferenceControllerAuthorizeByReference with correct params', async () => { + const { params } = setup({ isAuthorized: true }); + + const expectedOptions = { headers: { authorization: `Bearer ${jwtToken}` } }; + + await service.checkPermissionsByReference(params); + + expect(authorizationApi.authorizationReferenceControllerAuthorizeByReference).toHaveBeenCalledWith( + params, + expectedOptions + ); + }); + + describe('when permission is granted', () => { + it('should resolve', async () => { + const { params } = setup({ isAuthorized: true }); + + await expect(service.checkPermissionsByReference(params)).resolves.toBeUndefined(); + }); + }); + + describe('when permission is denied', () => { + it('should throw AuthorizationForbiddenLoggableException', async () => { + const { params } = setup({ isAuthorized: false }); + + const expectedError = new AuthorizationForbiddenLoggableException(params); + + await expect(service.checkPermissionsByReference(params)).rejects.toThrowError(expectedError); + }); + }); + }); + + describe('when authorizationReferenceControllerAuthorizeByReference returns error', () => { + const setup = () => { + const params = { + context: { + action: Action.READ, + requiredPermissions, + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const error = new Error('testError'); + authorizationApi.authorizationReferenceControllerAuthorizeByReference.mockRejectedValueOnce(error); + + return { params, error }; + }; + + it('should throw AuthorizationErrorLoggableException', async () => { + const { params, error } = setup(); + + const expectedError = new AuthorizationErrorLoggableException(error, params); + + await expect(service.checkPermissionsByReference(params)).rejects.toThrowError(expectedError); + }); + }); + }); + + describe('hasPermissionsByReference', () => { + describe('when authorizationReferenceControllerAuthorizeByReference resolves successful', () => { + const setup = () => { + const params = { + context: { + action: Action.READ, + requiredPermissions, + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const response = createMock>({ + data: { + isAuthorized: true, + userId: 'userId', + }, + }); + authorizationApi.authorizationReferenceControllerAuthorizeByReference.mockResolvedValueOnce(response); + + return { params, response }; + }; + + it('should call authorizationReferenceControllerAuthorizeByReference with the correct params', async () => { + const { params } = setup(); + + const expectedOptions = { headers: { authorization: `Bearer ${jwtToken}` } }; + + await service.hasPermissionsByReference(params); + + expect(authorizationApi.authorizationReferenceControllerAuthorizeByReference).toHaveBeenCalledWith( + params, + expectedOptions + ); + }); + + it('should return isAuthorized', async () => { + const { params, response } = setup(); + + const result = await service.hasPermissionsByReference(params); + + expect(result).toEqual(response.data.isAuthorized); + }); + }); + + describe('when cookie header contains JWT token', () => { + const setup = () => { + const params = { + context: { + action: Action.READ, + requiredPermissions, + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const response = createMock>({ + data: { + isAuthorized: true, + userId: 'userId', + }, + }); + authorizationApi.authorizationReferenceControllerAuthorizeByReference.mockResolvedValueOnce(response); + + const request = createMock({ + headers: { + cookie: `jwt=${jwtToken}`, + }, + }); + const adapter = new AuthorizationClientAdapter(authorizationApi, request); + + return { params, adapter }; + }; + + it('should forward the JWT as bearer token', async () => { + const { params, adapter } = setup(); + + const expectedOptions = { headers: { authorization: `Bearer ${jwtToken}` } }; + + await adapter.hasPermissionsByReference(params); + + expect(authorizationApi.authorizationReferenceControllerAuthorizeByReference).toHaveBeenCalledWith( + params, + expectedOptions + ); + }); + }); + + describe('when authorization header is without "Bearer " at the start', () => { + const setup = () => { + const params = { + context: { + action: Action.READ, + requiredPermissions, + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const response = createMock>({ + data: { + isAuthorized: true, + userId: 'userId', + }, + }); + authorizationApi.authorizationReferenceControllerAuthorizeByReference.mockResolvedValueOnce(response); + + const request = createMock({ + headers: { + authorization: jwtToken, + }, + }); + const adapter = new AuthorizationClientAdapter(authorizationApi, request); + + return { params, adapter }; + }; + + it('should forward the JWT as bearer token', async () => { + const { params, adapter } = setup(); + + const expectedOptions = { headers: { authorization: `Bearer ${jwtToken}` } }; + + await adapter.hasPermissionsByReference(params); + + expect(authorizationApi.authorizationReferenceControllerAuthorizeByReference).toHaveBeenCalledWith( + params, + expectedOptions + ); + }); + }); + + describe('when no JWT token is found', () => { + const setup = () => { + const params = { + context: { + action: Action.READ, + requiredPermissions, + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const request = createMock({ + headers: {}, + }); + const adapter = new AuthorizationClientAdapter(authorizationApi, request); + + const error = new Error('Authentication is required.'); + + return { params, adapter, error }; + }; + + it('should throw an AuthorizationErrorLoggableException', async () => { + const { params, adapter, error } = setup(); + + const expectedError = new AuthorizationErrorLoggableException(error, params); + + await expect(adapter.hasPermissionsByReference(params)).rejects.toThrowError(expectedError); + }); + }); + + describe('when authorizationReferenceControllerAuthorizeByReference returns error', () => { + const setup = () => { + const params = { + context: { + action: Action.READ, + requiredPermissions, + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const error = new Error('testError'); + authorizationApi.authorizationReferenceControllerAuthorizeByReference.mockRejectedValueOnce(error); + + return { params, error }; + }; + + it('should throw AuthorizationErrorLoggableException', async () => { + const { params, error } = setup(); + + const expectedError = new AuthorizationErrorLoggableException(error, params); + + await expect(service.hasPermissionsByReference(params)).rejects.toThrowError(expectedError); + }); + }); + }); +}); diff --git a/apps/server/src/infra/authorization-client/authorization-client.adapter.ts b/apps/server/src/infra/authorization-client/authorization-client.adapter.ts new file mode 100644 index 00000000000..daf155fdf14 --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-client.adapter.ts @@ -0,0 +1,67 @@ +import { Inject, Injectable } from '@nestjs/common'; +import { REQUEST } from '@nestjs/core'; +import { RawAxiosRequestConfig } from 'axios'; +import cookie from 'cookie'; +import { Request } from 'express'; +import { ExtractJwt, JwtFromRequestFunction } from 'passport-jwt'; +import { AuthorizationApi, AuthorizationBodyParams } from './authorization-api-client'; +import { AuthorizationErrorLoggableException, AuthorizationForbiddenLoggableException } from './error'; + +@Injectable() +export class AuthorizationClientAdapter { + constructor(private readonly authorizationApi: AuthorizationApi, @Inject(REQUEST) private request: Request) {} + + public async checkPermissionsByReference(params: AuthorizationBodyParams): Promise { + const hasPermission = await this.hasPermissionsByReference(params); + if (!hasPermission) { + throw new AuthorizationForbiddenLoggableException(params); + } + } + + public async hasPermissionsByReference(params: AuthorizationBodyParams): Promise { + const options = this.createOptionParams(params); + + try { + const response = await this.authorizationApi.authorizationReferenceControllerAuthorizeByReference( + params, + options + ); + const hasPermission = response.data.isAuthorized; + + return hasPermission; + } catch (error) { + throw new AuthorizationErrorLoggableException(error, params); + } + } + + private createOptionParams(params: AuthorizationBodyParams): RawAxiosRequestConfig { + const jwt = this.getJWT(params); + const options: RawAxiosRequestConfig = { headers: { authorization: `Bearer ${jwt}` } }; + + return options; + } + + private getJWT(params: AuthorizationBodyParams): string { + const getJWT = ExtractJwt.fromExtractors([ExtractJwt.fromAuthHeaderAsBearerToken(), this.fromCookie('jwt')]); + const jwt = getJWT(this.request) || this.request.headers.authorization; + + if (!jwt) { + const error = new Error('Authentication is required.'); + throw new AuthorizationErrorLoggableException(error, params); + } + + return jwt; + } + + private fromCookie(name: string): JwtFromRequestFunction { + return (request: Request) => { + let token: string | null = null; + const cookies = cookie.parse(request.headers.cookie || ''); + if (cookies && cookies[name]) { + token = cookies[name]; + } + + return token; + }; + } +} diff --git a/apps/server/src/infra/authorization-client/authorization-client.module.ts b/apps/server/src/infra/authorization-client/authorization-client.module.ts new file mode 100644 index 00000000000..fdd6beebaaf --- /dev/null +++ b/apps/server/src/infra/authorization-client/authorization-client.module.ts @@ -0,0 +1,29 @@ +import { DynamicModule, Module } from '@nestjs/common'; +import { AuthorizationApi, Configuration, ConfigurationParameters } from './authorization-api-client'; +import { AuthorizationClientAdapter } from './authorization-client.adapter'; + +export interface AuthorizationClientConfig extends ConfigurationParameters { + basePath?: string; +} + +@Module({}) +export class AuthorizationClientModule { + static register(config: AuthorizationClientConfig): DynamicModule { + const providers = [ + AuthorizationClientAdapter, + { + provide: AuthorizationApi, + useFactory: () => { + const configuration = new Configuration(config); + return new AuthorizationApi(configuration); + }, + }, + ]; + + return { + module: AuthorizationClientModule, + providers, + exports: [AuthorizationClientAdapter], + }; + } +} diff --git a/apps/server/src/infra/authorization-client/error/authorization-error.loggable-exception.spec.ts b/apps/server/src/infra/authorization-client/error/authorization-error.loggable-exception.spec.ts new file mode 100644 index 00000000000..601cad990fc --- /dev/null +++ b/apps/server/src/infra/authorization-client/error/authorization-error.loggable-exception.spec.ts @@ -0,0 +1,88 @@ +import { Action, AuthorizationBodyParamsReferenceType } from '../authorization-api-client'; +import { AuthorizationErrorLoggableException } from './authorization-error.loggable-exception'; + +describe('AuthorizationErrorLoggableException', () => { + describe('when error is instance of Error', () => { + describe('getLogMessage', () => { + const setup = () => { + const params = { + context: { + action: Action.READ, + requiredPermissions: [], + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const error = new Error('testError'); + const exception = new AuthorizationErrorLoggableException(error, params); + + return { + params, + error, + exception, + }; + }; + + it('should log the correct message', () => { + const { params, error, exception } = setup(); + + const result = exception.getLogMessage(); + + expect(result).toEqual({ + type: 'INTERNAL_SERVER_ERROR', + error, + stack: expect.any(String), + data: { + action: params.context.action, + referenceId: params.referenceId, + referenceType: params.referenceType, + requiredPermissions: params.context.requiredPermissions.join(','), + }, + }); + }); + }); + }); + + describe('when error is NOT instance of Error', () => { + describe('getLogMessage', () => { + const setup = () => { + const params = { + context: { + action: Action.READ, + requiredPermissions: [], + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const error = { code: '123', message: 'testError' }; + const exception = new AuthorizationErrorLoggableException(error, params); + + return { + params, + error, + exception, + }; + }; + + it('should log the correct message', () => { + const { params, error, exception } = setup(); + + const result = exception.getLogMessage(); + + expect(result).toEqual({ + type: 'INTERNAL_SERVER_ERROR', + error: new Error(JSON.stringify(error)), + stack: expect.any(String), + data: { + action: params.context.action, + referenceId: params.referenceId, + referenceType: params.referenceType, + requiredPermissions: params.context.requiredPermissions.join(','), + }, + }); + }); + }); + }); +}); diff --git a/apps/server/src/infra/authorization-client/error/authorization-error.loggable-exception.ts b/apps/server/src/infra/authorization-client/error/authorization-error.loggable-exception.ts new file mode 100644 index 00000000000..2d35d90f7dc --- /dev/null +++ b/apps/server/src/infra/authorization-client/error/authorization-error.loggable-exception.ts @@ -0,0 +1,27 @@ +import { ForbiddenException } from '@nestjs/common'; +import { Loggable } from '@src/core/logger/interfaces'; +import { ErrorLogMessage } from '@src/core/logger/types'; +import { AuthorizationBodyParams } from '../authorization-api-client'; + +export class AuthorizationErrorLoggableException extends ForbiddenException implements Loggable { + constructor(private readonly error: unknown, private readonly params: AuthorizationBodyParams) { + super(); + } + + getLogMessage(): ErrorLogMessage { + const error = this.error instanceof Error ? this.error : new Error(JSON.stringify(this.error)); + const message: ErrorLogMessage = { + type: 'INTERNAL_SERVER_ERROR', + error, + stack: this.stack, + data: { + action: this.params.context.action, + referenceId: this.params.referenceId, + referenceType: this.params.referenceType, + requiredPermissions: this.params.context.requiredPermissions.join(','), + }, + }; + + return message; + } +} diff --git a/apps/server/src/infra/authorization-client/error/authorization-forbidden.loggable-exception.spec.ts b/apps/server/src/infra/authorization-client/error/authorization-forbidden.loggable-exception.spec.ts new file mode 100644 index 00000000000..75b19806969 --- /dev/null +++ b/apps/server/src/infra/authorization-client/error/authorization-forbidden.loggable-exception.spec.ts @@ -0,0 +1,41 @@ +import { AuthorizationForbiddenLoggableException } from './authorization-forbidden.loggable-exception'; +import { Action, AuthorizationBodyParamsReferenceType } from '../authorization-api-client'; + +describe('AuthorizationForbiddenLoggableException', () => { + describe('getLogMessage', () => { + const setup = () => { + const params = { + context: { + action: Action.READ, + requiredPermissions: [], + }, + referenceType: AuthorizationBodyParamsReferenceType.COURSES, + referenceId: 'someReferenceId', + }; + + const exception = new AuthorizationForbiddenLoggableException(params); + + return { + exception, + params, + }; + }; + + it('should log the correct message', () => { + const { exception, params } = setup(); + + const result = exception.getLogMessage(); + + expect(result).toEqual({ + type: 'FORBIDDEN_EXCEPTION', + stack: expect.any(String), + data: { + action: params.context.action, + referenceId: params.referenceId, + referenceType: params.referenceType, + requiredPermissions: params.context.requiredPermissions.join(','), + }, + }); + }); + }); +}); diff --git a/apps/server/src/infra/authorization-client/error/authorization-forbidden.loggable-exception.ts b/apps/server/src/infra/authorization-client/error/authorization-forbidden.loggable-exception.ts new file mode 100644 index 00000000000..ffd44125976 --- /dev/null +++ b/apps/server/src/infra/authorization-client/error/authorization-forbidden.loggable-exception.ts @@ -0,0 +1,25 @@ +import { ForbiddenException } from '@nestjs/common'; +import { Loggable } from '@src/core/logger/interfaces'; +import { ErrorLogMessage } from '@src/core/logger/types'; +import { AuthorizationBodyParams } from '../authorization-api-client'; + +export class AuthorizationForbiddenLoggableException extends ForbiddenException implements Loggable { + constructor(private readonly params: AuthorizationBodyParams) { + super(); + } + + getLogMessage(): ErrorLogMessage { + const message: ErrorLogMessage = { + type: 'FORBIDDEN_EXCEPTION', + stack: this.stack, + data: { + action: this.params.context.action, + referenceId: this.params.referenceId, + referenceType: this.params.referenceType, + requiredPermissions: this.params.context.requiredPermissions.join(','), + }, + }; + + return message; + } +} diff --git a/apps/server/src/infra/authorization-client/error/index.ts b/apps/server/src/infra/authorization-client/error/index.ts new file mode 100644 index 00000000000..439c65fe445 --- /dev/null +++ b/apps/server/src/infra/authorization-client/error/index.ts @@ -0,0 +1,2 @@ +export * from './authorization-error.loggable-exception'; +export * from './authorization-forbidden.loggable-exception'; diff --git a/apps/server/src/infra/authorization-client/index.ts b/apps/server/src/infra/authorization-client/index.ts new file mode 100644 index 00000000000..d67234adb75 --- /dev/null +++ b/apps/server/src/infra/authorization-client/index.ts @@ -0,0 +1,2 @@ +export { AuthorizationClientAdapter } from './authorization-client.adapter'; +export { AuthorizationClientModule } from './authorization-client.module'; diff --git a/apps/server/src/shared/controller/swagger.spec.ts b/apps/server/src/shared/controller/swagger.spec.ts index 413a3fa3a9c..9b8e23f3108 100644 --- a/apps/server/src/shared/controller/swagger.spec.ts +++ b/apps/server/src/shared/controller/swagger.spec.ts @@ -1,6 +1,6 @@ +import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; -import { ServerTestModule } from '@modules/server'; import request from 'supertest'; import { enableOpenApiDocs } from './swagger'; @@ -33,8 +33,8 @@ describe('swagger setup', () => { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access expect(response.body.info).toEqual({ contact: {}, - description: 'This is v3 of HPI Schul-Cloud Server. Checkout /docs for v1.', - title: 'HPI Schul-Cloud Server API', + description: 'This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1.', + title: 'Schulcloud-Verbund-Software Server API', // care about api changes when version changes version: '3.0', }); diff --git a/apps/server/src/shared/controller/swagger.ts b/apps/server/src/shared/controller/swagger.ts index e27605b23d5..8207598976e 100644 --- a/apps/server/src/shared/controller/swagger.ts +++ b/apps/server/src/shared/controller/swagger.ts @@ -13,8 +13,8 @@ import { DocumentBuilder, SwaggerDocumentOptions, SwaggerModule } from '@nestjs/ // DTO's and Entity properties have to use @ApiProperty decorator to add their properties const config = new DocumentBuilder() .addServer('/api/v3/') // add default path as server to have correct urls ald let 'try out' work - .setTitle('HPI Schul-Cloud Server API') - .setDescription('This is v3 of HPI Schul-Cloud Server. Checkout /docs for v1.') + .setTitle('Schulcloud-Verbund-Software Server API') + .setDescription('This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1.') .setVersion('3.0') /** set authentication for all routes enabled by default */ .addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }) diff --git a/package.json b/package.json index 55f490ed236..2b67a87f720 100644 --- a/package.json +++ b/package.json @@ -120,6 +120,7 @@ "ensureIndexes": "npm run nest:start:console -- database sync-indexes", "schoolExport": "node ./scripts/schoolExport.js", "schoolImport": "node ./scripts/schoolImport.js", + "generate-client:authorization": "node ./scripts/generate-client.js -u 'http://localhost:3030/api/v3/docs-json/' -p 'apps/server/src/infra/authorization-client/authorization-api-client' -c 'openapitools-config.json' -f 'operationId:AuthorizationReferenceController_authorizeByReference'", "generate-client:etherpad": "node ./scripts/generate-client.js -u 'http://localhost:9001/api/openapi.json' -p 'apps/server/src/infra/etherpad-client/etherpad-api-client' -c 'openapitools-config.json'" }, "dependencies": { diff --git a/scripts/generate-client.js b/scripts/generate-client.js index 1c33627238f..c9605d9463d 100644 --- a/scripts/generate-client.js +++ b/scripts/generate-client.js @@ -17,6 +17,9 @@ const args = arg( '--config': String, '-c': '--config', + + '--filter': String, + '-f': '--filter', }, { argv: process.argv.slice(2), @@ -30,6 +33,7 @@ OPTIONS: --path (-p) Path to the newly created client's directory. --url (-u) URL/path to the spec file in yml/json format. --config (-c) path to the additional-properties config file in yml/json format + --filter (-f) filter to apply to the openapi spec before generating the client `); process.exit(0); } @@ -41,15 +45,19 @@ const params = { path: args._[1] || args['--path'], config: args._[2] || args['--config'] || '', + + + filter: args._[3] || args['--filter'] || '', }; const errorMessageContains = (includedString, error) => error && error.message && typeof error.message === 'string' && error.message.includes(includedString); const getOpenApiCommand = (params) => { - const { url, path, config } = params; + const { url, path, config, filter } = params; const configFile = config ? `-c ${config}` : ''; - const command = `openapi-generator-cli generate -i ${url} -g typescript-axios -o ${path} ${configFile} --skip-validate-spec`; + const filterString = filter ? `--openapi-normalizer FILTER="${filter}"` : ''; + const command = `openapi-generator-cli generate -i ${url} -g typescript-axios -o ${path} ${configFile} --skip-validate-spec ${filterString}`; return command; }; diff --git a/sonar-project.properties b/sonar-project.properties index 18a0ed51fb0..b7be9f713c3 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -3,8 +3,8 @@ sonar.projectKey=hpi-schul-cloud_schulcloud-server sonar.sources=. sonar.tests=. sonar.test.inclusions=**/*.spec.ts -sonar.exclusions=**/*.js,jest.config.ts,globalSetup.ts,globalTeardown.ts,**/*.app.ts,**/seed-data/*.ts,**/migrations/mikro-orm/*.ts,**/etherpad-api-client/**/*.ts -sonar.coverage.exclusions=**/board-management.uc.ts,**/*.module.ts,**/*.factory.ts,**/migrations/mikro-orm/*.ts,**/globalSetup.ts,**/globalTeardown.ts,**/etherpad-api-client/**/*.ts +sonar.exclusions=**/*.js,jest.config.ts,globalSetup.ts,globalTeardown.ts,**/*.app.ts,**/seed-data/*.ts,**/migrations/mikro-orm/*.ts,**/etherpad-api-client/**/*.ts,**/authorization-api-client/**/*.ts +sonar.coverage.exclusions=**/board-management.uc.ts,**/*.module.ts,**/*.factory.ts,**/migrations/mikro-orm/*.ts,**/globalSetup.ts,**/globalTeardown.ts,**/etherpad-api-client/**/*.ts,**/authorization-api-client/**/*.ts sonar.cpd.exclusions=**/controller/dto/*.ts sonar.javascript.lcov.reportPaths=merged-lcov.info sonar.typescript.tsconfigPaths=tsconfig.json,src/apps/server/tsconfig.app.json diff --git a/src/swagger.js b/src/swagger.js index c81cc1af3c0..9f96009881f 100644 --- a/src/swagger.js +++ b/src/swagger.js @@ -11,8 +11,8 @@ module.exports = function swaggerSetup(app) { security: [{ jwtBearer: [] }], schemes: ['http', 'https'], info: { - title: 'HPI Schul-Cloud API', - description: 'This is the HPI Schul-Cloud API.', + title: 'Schulcloud-Verbund-Software API', + description: 'This is the Schulcloud-Verbund-Software API.', termsOfServiceUrl: 'https://github.com/hpi-schul-cloud/schulcloud-server/blob/master/LICENSE', contact: { name: 'support',