Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
adityachoudhari26 committed Jan 3, 2025
1 parent 2f2c926 commit 84e8d21
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 84 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ export const convertManagedClusterToResource = (
return null;
}

const appUrl = cluster.azurePortalFqdn ?? "";

return {
workspaceId,
providerId,
Expand All @@ -46,7 +44,9 @@ export const convertManagedClusterToResource = (
},
},
metadata: omitNullUndefined({
[ReservedMetadataKey.Links]: JSON.stringify({ "Azure Portal": appUrl }),
[ReservedMetadataKey.Links]: cluster.azurePortalFqdn
? JSON.stringify({ "Azure Portal": cluster.azurePortalFqdn })
: undefined,
[ReservedMetadataKey.ExternalId]: cluster.id ?? "",
[ReservedMetadataKey.KubernetesFlavor]: "aks",
[ReservedMetadataKey.KubernetesVersion]: cluster.currentKubernetesVersion,
Expand Down
18 changes: 9 additions & 9 deletions apps/event-worker/src/resource-scan/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const removeResourceJob = (job: Job) =>
? resourceScanQueue.removeRepeatableByKey(job.repeatJobKey)
: null;

const getResource = async (rp: any) => {
const getResources = async (rp: any) => {
if (rp.resource_provider_google != null) {
const [gkeResources, vpcResources] = await Promise.all([
getGkeResources(rp.workspace, rp.resource_provider_google),
Expand Down Expand Up @@ -91,18 +91,18 @@ export const createResourceScanWorker = () =>
);

try {
const resources = await getResource(rp);
log.info(
`Upserting ${resources.length} resources for provider ${rp.resource_provider.id}`,
);

if (resources.length > 0) {
await upsertResources(db, resources);
} else {
const resources = await getResources(rp);
if (resources.length === 0) {
log.info(
`No resources found for provider ${rp.resource_provider.id}, skipping upsert.`,
);
return;
}

log.info(
`Upserting ${resources.length} resources for provider ${rp.resource_provider.id}`,
);
await upsertResources(db, resources);
} catch (error: any) {
log.error(
`Error scanning/upserting resources for provider ${rp.resource_provider.id}: ${error.message}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,29 +68,29 @@ const ManagedProviderBadge: React.FC<{
<Badge
variant="secondary"
className={cn(
"flex h-6 w-fit rounded-full px-2 py-0 text-xs",
provider.googleConfig != null && "bg-red-400/20",
provider.awsConfig != null && "bg-orange-400/20",
provider.azureConfig != null && "bg-blue-400/20",
"flex h-6 w-fit items-center gap-1 rounded-full px-2 py-0 text-xs",
provider.googleConfig != null && "bg-red-400/20 text-red-400",
provider.awsConfig != null && "bg-orange-400/20 text-orange-400",
provider.azureConfig != null && "bg-blue-400/20 text-blue-400",
)}
>
{provider.googleConfig != null && (
<div className="flex items-center gap-1 text-red-400">
<>
<SiGooglecloud className="h-3 w-3" />
Google
</div>
</>
)}
{provider.awsConfig != null && (
<div className="flex items-center gap-1 text-orange-400">
<>
<SiAmazon className="h-3 w-3" />
AWS
</div>
</>
)}
{provider.azureConfig != null && (
<div className="flex items-center gap-1 text-blue-400">
<>
<IconBrandAzure className="h-3 w-3" />
Azure
</div>
</>
)}
</Badge>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import ms from "ms";
import { eq, takeFirstOrNull } from "@ctrlplane/db";
import { db } from "@ctrlplane/db/client";
import * as SCHEMA from "@ctrlplane/db/schema";
import { logger } from "@ctrlplane/logger";
import { Channel } from "@ctrlplane/validators/events";

import { env } from "~/env";
Expand All @@ -30,76 +31,78 @@ const resourceScanQueue = new Queue<ResourceScanEvent>(Channel.ResourceScan, {

export const GET = async (_: never, { params }: { params: Params }) => {
const { workspaceId, tenantId, subscriptionId, name } = params;
return db.transaction(async (db) => {
const workspace = await db
.select()
.from(SCHEMA.workspace)
.where(eq(SCHEMA.workspace.id, workspaceId))
.then(takeFirstOrNull);

const workspace = await db
.select()
.from(SCHEMA.workspace)
.where(eq(SCHEMA.workspace.id, workspaceId))
.then(takeFirstOrNull);
if (workspace == null)
return NextResponse.json(
{ error: "Workspace not found" },
{ status: NOT_FOUND },
);

if (workspace == null)
return NextResponse.json(
{ error: "Workspace not found" },
{ status: NOT_FOUND },
);
const tenant = await db
.select()
.from(SCHEMA.azureTenant)
.where(eq(SCHEMA.azureTenant.tenantId, tenantId))
.then(takeFirstOrNull);

const tenant = await db
.select()
.from(SCHEMA.azureTenant)
.where(eq(SCHEMA.azureTenant.tenantId, tenantId))
.then(takeFirstOrNull);
if (tenant == null) {
const state = randomUUID();
const config = { workspaceId, tenantId, subscriptionId, name };
const configJSON = JSON.stringify(config);
await redis.set(`azure_consent_state:${state}`, configJSON, "EX", 900);
const redirectUrl = `${baseUrl}/api/azure/consent?state=${state}`;
const consentUrl = `https://login.microsoftonline.com/${tenantId}/adminconsent?client_id=${clientId}&redirect_uri=${redirectUrl}`;
return NextResponse.redirect(consentUrl);
}

if (tenant == null) {
const state = randomUUID();
const config = { workspaceId, tenantId, subscriptionId, name };
const configJSON = JSON.stringify(config);
await redis.set(`azure_consent_state:${state}`, configJSON, "EX", 900);
const redirectUrl = `${baseUrl}/api/azure/consent?state=${state}`;
const consentUrl = `https://login.microsoftonline.com/${tenantId}/adminconsent?client_id=${clientId}&redirect_uri=${redirectUrl}`;
return NextResponse.redirect(consentUrl);
}
if (tenant.workspaceId !== workspaceId)
return NextResponse.json(
{ error: "Tenant does not belong to this workspace" },
{ status: FORBIDDEN },
);

if (tenant.workspaceId !== workspaceId)
return NextResponse.json(
{ error: "Tenant does not belong to this workspace" },
{ status: FORBIDDEN },
);
const resourceProvider = await db
.insert(SCHEMA.resourceProvider)
.values({
workspaceId,
name,
})
.returning()
.then(takeFirstOrNull);

const resourceProvider = await db
.insert(SCHEMA.resourceProvider)
.values({
workspaceId,
name,
})
.returning()
.then(takeFirstOrNull);
if (resourceProvider == null)
return NextResponse.json(
{ error: "Failed to create resource provider" },
{ status: INTERNAL_SERVER_ERROR },
);

if (resourceProvider == null)
return NextResponse.json(
{ error: "Failed to create resource provider" },
{ status: INTERNAL_SERVER_ERROR },
);
try {
await db.insert(SCHEMA.resourceProviderAzure).values({
resourceProviderId: resourceProvider.id,
tenantId: tenant.id,
subscriptionId,
});

db.insert(SCHEMA.resourceProviderAzure)
.values({
resourceProviderId: resourceProvider.id,
tenantId: tenant.id,
subscriptionId,
})
.then(() =>
resourceScanQueue.add(
await resourceScanQueue.add(
resourceProvider.id,
{ resourceProviderId: resourceProvider.id },
{ repeat: { every: ms("10m"), immediately: true } },
),
)
.then(() =>
NextResponse.redirect(`${baseUrl}/${workspace.slug}/resource-providers`),
)
.catch(() =>
NextResponse.json(
{ error: "Failed to create resource provider" },
);
} catch (error) {
logger.error(error);
return NextResponse.json(
{ error: "Failed to create resource provider Azure" },
{ status: INTERNAL_SERVER_ERROR },
),
);
}

return NextResponse.redirect(
`${baseUrl}/${workspace.slug}/resource-providers`,
);
});
};
9 changes: 6 additions & 3 deletions apps/webservice/src/app/api/azure/consent/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,17 @@ export const GET = async (req: NextRequest) => {
const { searchParams } = new URL(req.url);
const state = searchParams.get("state");

if (!state) return NextResponse.json({ status: BAD_REQUEST });
if (!state)
return NextResponse.json({ error: "Bad request" }, { status: BAD_REQUEST });

const configJSON = await redis.get(`azure_consent_state:${state}`);
if (configJSON == null) return NextResponse.json({ status: BAD_REQUEST });
if (configJSON == null)
return NextResponse.json({ error: "Bad request" }, { status: BAD_REQUEST });

const config = JSON.parse(configJSON);
const parsedConfig = configSchema.safeParse(config);
if (!parsedConfig.success) return NextResponse.json({ status: BAD_REQUEST });
if (!parsedConfig.success)
return NextResponse.json({ error: "Bad request" }, { status: BAD_REQUEST });

const { workspaceId, tenantId, subscriptionId, name } = parsedConfig.data;

Expand Down

0 comments on commit 84e8d21

Please sign in to comment.