chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { grafanaUpdateAlertRuleContract } from '@/lib/api/contracts/tools/grafana'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import {
|
||||
secureFetchWithPinnedIP,
|
||||
validateUrlWithDNS,
|
||||
} from '@/lib/core/security/input-validation.server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { mapAlertRule } from '@/tools/grafana/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('GrafanaUpdateAlertRuleAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
||||
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(
|
||||
`[${requestId}] Unauthorized Grafana update alert rule attempt: ${authResult.error}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
grafanaUpdateAlertRuleContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const baseUrl = params.baseUrl.replace(/\/$/, '')
|
||||
|
||||
const getHeaders: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
}
|
||||
if (params.organizationId) {
|
||||
getHeaders['X-Grafana-Org-Id'] = params.organizationId
|
||||
}
|
||||
|
||||
const getUrl = `${baseUrl}/api/v1/provisioning/alert-rules/${params.alertRuleUid.trim()}`
|
||||
const getValidation = await validateUrlWithDNS(getUrl, 'baseUrl')
|
||||
if (!getValidation.isValid || !getValidation.resolvedIP) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Invalid Grafana baseUrl: ${getValidation.error}`,
|
||||
})
|
||||
}
|
||||
|
||||
const getResponse = await secureFetchWithPinnedIP(getUrl, getValidation.resolvedIP, {
|
||||
method: 'GET',
|
||||
headers: getHeaders,
|
||||
})
|
||||
|
||||
if (!getResponse.ok) {
|
||||
const errorText = await getResponse.text()
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Failed to fetch existing alert rule: ${errorText}`,
|
||||
})
|
||||
}
|
||||
|
||||
const existingRule = (await getResponse.json()) as any
|
||||
|
||||
if (!existingRule || !existingRule.uid) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: 'Failed to fetch existing alert rule',
|
||||
})
|
||||
}
|
||||
|
||||
const updatedRule: Record<string, unknown> = {
|
||||
...existingRule,
|
||||
}
|
||||
|
||||
if (params.title) updatedRule.title = params.title
|
||||
if (params.folderUid) updatedRule.folderUID = params.folderUid
|
||||
if (params.ruleGroup) updatedRule.ruleGroup = params.ruleGroup
|
||||
if (params.condition) updatedRule.condition = params.condition
|
||||
if (params.forDuration) updatedRule.for = params.forDuration
|
||||
if (params.noDataState) updatedRule.noDataState = params.noDataState
|
||||
if (params.execErrState) updatedRule.execErrState = params.execErrState
|
||||
if (params.isPaused !== undefined) updatedRule.isPaused = params.isPaused
|
||||
if (params.keepFiringFor) updatedRule.keep_firing_for = params.keepFiringFor
|
||||
if (params.missingSeriesEvalsToResolve !== undefined) {
|
||||
updatedRule.missingSeriesEvalsToResolve = params.missingSeriesEvalsToResolve
|
||||
}
|
||||
|
||||
if (params.notificationSettings) {
|
||||
try {
|
||||
updatedRule.notification_settings = JSON.parse(params.notificationSettings)
|
||||
} catch {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: 'Invalid JSON for notificationSettings parameter',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (params.record) {
|
||||
try {
|
||||
updatedRule.record = JSON.parse(params.record)
|
||||
} catch {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: 'Invalid JSON for record parameter',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (params.data) {
|
||||
try {
|
||||
updatedRule.data = JSON.parse(params.data)
|
||||
} catch {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: 'Invalid JSON for data parameter',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (params.annotations) {
|
||||
try {
|
||||
updatedRule.annotations = {
|
||||
...(existingRule.annotations || {}),
|
||||
...JSON.parse(params.annotations),
|
||||
}
|
||||
} catch {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: 'Invalid JSON for annotations parameter',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (params.labels) {
|
||||
try {
|
||||
updatedRule.labels = {
|
||||
...(existingRule.labels || {}),
|
||||
...JSON.parse(params.labels),
|
||||
}
|
||||
} catch {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: 'Invalid JSON for labels parameter',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
}
|
||||
if (params.organizationId) {
|
||||
headers['X-Grafana-Org-Id'] = params.organizationId
|
||||
}
|
||||
if (params.disableProvenance) {
|
||||
headers['X-Disable-Provenance'] = 'true'
|
||||
}
|
||||
|
||||
const updateUrl = `${baseUrl}/api/v1/provisioning/alert-rules/${params.alertRuleUid.trim()}`
|
||||
const urlValidation = await validateUrlWithDNS(updateUrl, 'baseUrl')
|
||||
if (!urlValidation.isValid || !urlValidation.resolvedIP) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Invalid Grafana baseUrl: ${urlValidation.error}`,
|
||||
})
|
||||
}
|
||||
|
||||
const updateResponse = await secureFetchWithPinnedIP(updateUrl, urlValidation.resolvedIP, {
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: JSON.stringify(updatedRule),
|
||||
})
|
||||
|
||||
if (!updateResponse.ok) {
|
||||
const errorText = await updateResponse.text()
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Failed to update alert rule: ${errorText}`,
|
||||
})
|
||||
}
|
||||
|
||||
const data = (await updateResponse.json()) as Record<string, unknown>
|
||||
return NextResponse.json({ success: true, output: mapAlertRule(data) })
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error updating Grafana alert rule:`, error)
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: getErrorMessage(error),
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,208 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { grafanaUpdateDashboardContract } from '@/lib/api/contracts/tools/grafana'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import {
|
||||
secureFetchWithPinnedIP,
|
||||
validateUrlWithDNS,
|
||||
} from '@/lib/core/security/input-validation.server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('GrafanaUpdateDashboardAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
||||
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(
|
||||
`[${requestId}] Unauthorized Grafana update dashboard attempt: ${authResult.error}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
grafanaUpdateDashboardContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const baseUrl = params.baseUrl.replace(/\/$/, '')
|
||||
|
||||
const getHeaders: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
}
|
||||
if (params.organizationId) {
|
||||
getHeaders['X-Grafana-Org-Id'] = params.organizationId
|
||||
}
|
||||
|
||||
const getUrl = `${baseUrl}/api/dashboards/uid/${params.dashboardUid.trim()}`
|
||||
const getValidation = await validateUrlWithDNS(getUrl, 'baseUrl')
|
||||
if (!getValidation.isValid || !getValidation.resolvedIP) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Invalid Grafana baseUrl: ${getValidation.error}`,
|
||||
})
|
||||
}
|
||||
|
||||
const getResponse = await secureFetchWithPinnedIP(getUrl, getValidation.resolvedIP, {
|
||||
method: 'GET',
|
||||
headers: getHeaders,
|
||||
})
|
||||
|
||||
if (!getResponse.ok) {
|
||||
const errorText = await getResponse.text()
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Failed to fetch existing dashboard: ${errorText}`,
|
||||
})
|
||||
}
|
||||
|
||||
const existing = (await getResponse.json()) as any
|
||||
const existingDashboard = existing.dashboard
|
||||
const existingMeta = existing.meta
|
||||
|
||||
if (!existingDashboard || !existingDashboard.uid) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: 'Failed to fetch existing dashboard',
|
||||
})
|
||||
}
|
||||
|
||||
const updatedDashboard: Record<string, any> = {
|
||||
...existingDashboard,
|
||||
}
|
||||
|
||||
if (params.title) updatedDashboard.title = params.title
|
||||
if (params.timezone) updatedDashboard.timezone = params.timezone
|
||||
if (params.refresh) updatedDashboard.refresh = params.refresh
|
||||
|
||||
if (params.tags) {
|
||||
updatedDashboard.tags = params.tags
|
||||
.split(',')
|
||||
.map((t) => t.trim())
|
||||
.filter((t) => t)
|
||||
}
|
||||
|
||||
if (params.panels) {
|
||||
try {
|
||||
updatedDashboard.panels = JSON.parse(params.panels)
|
||||
} catch {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: 'Invalid JSON for panels parameter',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (existingDashboard.version) {
|
||||
updatedDashboard.version = existingDashboard.version
|
||||
}
|
||||
|
||||
const body: Record<string, any> = {
|
||||
dashboard: updatedDashboard,
|
||||
overwrite: params.overwrite === true,
|
||||
}
|
||||
|
||||
if (params.folderUid) {
|
||||
body.folderUid = params.folderUid
|
||||
} else if (existingMeta?.folderUid) {
|
||||
body.folderUid = existingMeta.folderUid
|
||||
}
|
||||
|
||||
if (params.message) {
|
||||
body.message = params.message
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
}
|
||||
if (params.organizationId) {
|
||||
headers['X-Grafana-Org-Id'] = params.organizationId
|
||||
}
|
||||
|
||||
const updateUrl = `${baseUrl}/api/dashboards/db`
|
||||
const urlValidation = await validateUrlWithDNS(updateUrl, 'baseUrl')
|
||||
if (!urlValidation.isValid || !urlValidation.resolvedIP) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Invalid Grafana baseUrl: ${urlValidation.error}`,
|
||||
})
|
||||
}
|
||||
|
||||
const updateResponse = await secureFetchWithPinnedIP(updateUrl, urlValidation.resolvedIP, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!updateResponse.ok) {
|
||||
const errorText = await updateResponse.text()
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Failed to update dashboard: ${errorText}`,
|
||||
})
|
||||
}
|
||||
|
||||
const data = (await updateResponse.json()) as {
|
||||
id?: number
|
||||
uid?: string
|
||||
url?: string
|
||||
status?: string
|
||||
version?: number
|
||||
slug?: string
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
id: data.id,
|
||||
uid: data.uid,
|
||||
url: data.url,
|
||||
status: data.status,
|
||||
version: data.version,
|
||||
slug: data.slug,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error updating Grafana dashboard:`, error)
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: getErrorMessage(error),
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,148 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { grafanaUpdateFolderContract } from '@/lib/api/contracts/tools/grafana'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import {
|
||||
secureFetchWithPinnedIP,
|
||||
validateUrlWithDNS,
|
||||
} from '@/lib/core/security/input-validation.server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('GrafanaUpdateFolderAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
||||
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized Grafana update folder attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
grafanaUpdateFolderContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const baseUrl = params.baseUrl.replace(/\/$/, '')
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
}
|
||||
if (params.organizationId) {
|
||||
headers['X-Grafana-Org-Id'] = params.organizationId
|
||||
}
|
||||
|
||||
const folderUrl = `${baseUrl}/api/folders/${params.folderUid.trim()}`
|
||||
const urlValidation = await validateUrlWithDNS(folderUrl, 'baseUrl')
|
||||
if (!urlValidation.isValid || !urlValidation.resolvedIP) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Invalid Grafana baseUrl: ${urlValidation.error}`,
|
||||
})
|
||||
}
|
||||
|
||||
const getResponse = await secureFetchWithPinnedIP(folderUrl, urlValidation.resolvedIP, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
})
|
||||
|
||||
if (!getResponse.ok) {
|
||||
const errorText = await getResponse.text()
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Failed to fetch existing folder: ${errorText}`,
|
||||
})
|
||||
}
|
||||
|
||||
const existingFolder = (await getResponse.json()) as any
|
||||
|
||||
if (!existingFolder || !existingFolder.uid) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: 'Failed to fetch existing folder',
|
||||
})
|
||||
}
|
||||
|
||||
const body: Record<string, unknown> = {
|
||||
title: params.title ?? existingFolder.title,
|
||||
version: existingFolder.version,
|
||||
overwrite: true,
|
||||
}
|
||||
|
||||
const updateResponse = await secureFetchWithPinnedIP(folderUrl, urlValidation.resolvedIP, {
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!updateResponse.ok) {
|
||||
const errorText = await updateResponse.text()
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: `Failed to update folder: ${errorText}`,
|
||||
})
|
||||
}
|
||||
|
||||
const data = (await updateResponse.json()) as Record<string, unknown>
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
id: (data.id as number) ?? null,
|
||||
uid: (data.uid as string) ?? null,
|
||||
title: (data.title as string) ?? null,
|
||||
url: (data.url as string) ?? null,
|
||||
parentUid: (data.parentUid as string) ?? null,
|
||||
parents: (data.parents as { uid: string; title: string; url: string }[]) ?? [],
|
||||
hasAcl: (data.hasAcl as boolean) ?? null,
|
||||
canSave: (data.canSave as boolean) ?? null,
|
||||
canEdit: (data.canEdit as boolean) ?? null,
|
||||
canAdmin: (data.canAdmin as boolean) ?? null,
|
||||
createdBy: (data.createdBy as string) ?? null,
|
||||
created: (data.created as string) ?? null,
|
||||
updatedBy: (data.updatedBy as string) ?? null,
|
||||
updated: (data.updated as string) ?? null,
|
||||
version: (data.version as number) ?? null,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error updating Grafana folder:`, error)
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: {},
|
||||
error: getErrorMessage(error),
|
||||
})
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user