updateResourceRule.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import { Request, Response, NextFunction } from "express";
  2. import { z } from "zod";
  3. import { db } from "@server/db";
  4. import { resourceRules, resources } from "@server/db/schema";
  5. import { eq } from "drizzle-orm";
  6. import response from "@server/lib/response";
  7. import HttpCode from "@server/types/HttpCode";
  8. import createHttpError from "http-errors";
  9. import logger from "@server/logger";
  10. import { fromError } from "zod-validation-error";
  11. import {
  12. isValidCIDR,
  13. isValidIP,
  14. isValidUrlGlobPattern
  15. } from "@server/lib/validators";
  16. // Define Zod schema for request parameters validation
  17. const updateResourceRuleParamsSchema = z
  18. .object({
  19. ruleId: z.string().transform(Number).pipe(z.number().int().positive()),
  20. resourceId: z
  21. .string()
  22. .transform(Number)
  23. .pipe(z.number().int().positive())
  24. })
  25. .strict();
  26. // Define Zod schema for request body validation
  27. const updateResourceRuleSchema = z
  28. .object({
  29. action: z.enum(["ACCEPT", "DROP"]).optional(),
  30. match: z.enum(["CIDR", "IP", "PATH"]).optional(),
  31. value: z.string().min(1).optional(),
  32. priority: z.number().int(),
  33. enabled: z.boolean().optional()
  34. })
  35. .strict()
  36. .refine((data) => Object.keys(data).length > 0, {
  37. message: "At least one field must be provided for update"
  38. });
  39. export async function updateResourceRule(
  40. req: Request,
  41. res: Response,
  42. next: NextFunction
  43. ): Promise<any> {
  44. try {
  45. // Validate path parameters
  46. const parsedParams = updateResourceRuleParamsSchema.safeParse(
  47. req.params
  48. );
  49. if (!parsedParams.success) {
  50. return next(
  51. createHttpError(
  52. HttpCode.BAD_REQUEST,
  53. fromError(parsedParams.error).toString()
  54. )
  55. );
  56. }
  57. // Validate request body
  58. const parsedBody = updateResourceRuleSchema.safeParse(req.body);
  59. if (!parsedBody.success) {
  60. return next(
  61. createHttpError(
  62. HttpCode.BAD_REQUEST,
  63. fromError(parsedBody.error).toString()
  64. )
  65. );
  66. }
  67. const { ruleId, resourceId } = parsedParams.data;
  68. const updateData = parsedBody.data;
  69. // Verify that the resource exists
  70. const [resource] = await db
  71. .select()
  72. .from(resources)
  73. .where(eq(resources.resourceId, resourceId))
  74. .limit(1);
  75. if (!resource) {
  76. return next(
  77. createHttpError(
  78. HttpCode.NOT_FOUND,
  79. `Resource with ID ${resourceId} not found`
  80. )
  81. );
  82. }
  83. if (!resource.http) {
  84. return next(
  85. createHttpError(
  86. HttpCode.BAD_REQUEST,
  87. "Cannot create rule for non-http resource"
  88. )
  89. );
  90. }
  91. // Verify that the rule exists and belongs to the specified resource
  92. const [existingRule] = await db
  93. .select()
  94. .from(resourceRules)
  95. .where(eq(resourceRules.ruleId, ruleId))
  96. .limit(1);
  97. if (!existingRule) {
  98. return next(
  99. createHttpError(
  100. HttpCode.NOT_FOUND,
  101. `Resource rule with ID ${ruleId} not found`
  102. )
  103. );
  104. }
  105. if (existingRule.resourceId !== resourceId) {
  106. return next(
  107. createHttpError(
  108. HttpCode.FORBIDDEN,
  109. `Resource rule ${ruleId} does not belong to resource ${resourceId}`
  110. )
  111. );
  112. }
  113. const match = updateData.match || existingRule.match;
  114. const { value } = updateData;
  115. if (value !== undefined) {
  116. if (match === "CIDR") {
  117. if (!isValidCIDR(value)) {
  118. return next(
  119. createHttpError(
  120. HttpCode.BAD_REQUEST,
  121. "Invalid CIDR provided"
  122. )
  123. );
  124. }
  125. } else if (match === "IP") {
  126. if (!isValidIP(value)) {
  127. return next(
  128. createHttpError(
  129. HttpCode.BAD_REQUEST,
  130. "Invalid IP provided"
  131. )
  132. );
  133. }
  134. } else if (match === "PATH") {
  135. if (!isValidUrlGlobPattern(value)) {
  136. return next(
  137. createHttpError(
  138. HttpCode.BAD_REQUEST,
  139. "Invalid URL glob pattern provided"
  140. )
  141. );
  142. }
  143. }
  144. }
  145. // Update the rule
  146. const [updatedRule] = await db
  147. .update(resourceRules)
  148. .set(updateData)
  149. .where(eq(resourceRules.ruleId, ruleId))
  150. .returning();
  151. return response(res, {
  152. data: updatedRule,
  153. success: true,
  154. error: false,
  155. message: "Resource rule updated successfully",
  156. status: HttpCode.OK
  157. });
  158. } catch (error) {
  159. logger.error(error);
  160. return next(
  161. createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
  162. );
  163. }
  164. }