Start SCIM functionality

This commit is contained in:
Tuan Dang
2024-02-08 15:54:20 -08:00
parent 70e083bae0
commit d5064fe75a
12 changed files with 300 additions and 3 deletions

View File

@@ -0,0 +1,24 @@
import { Knex } from "knex";
import { TableName } from "../schemas";
import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
export async function up(knex: Knex): Promise<void> {
if (!(await knex.schema.hasTable(TableName.ScimToken))) {
await knex.schema.createTable(TableName.ScimToken, (t) => {
t.string("id", 36).primary().defaultTo(knex.fn.uuid());
t.bigInteger("tokenTTL").defaultTo(15552000).notNullable(); // 180 days second
t.datetime("tokenLastUsedAt");
t.uuid("orgId").notNullable();
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
t.timestamps(true, true, true);
});
}
await createOnUpdateTrigger(knex, TableName.IdentityAccessToken);
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTableIfExists(TableName.ScimToken);
await dropOnUpdateTrigger(knex, TableName.ScimToken);
}

View File

@@ -40,6 +40,7 @@ export enum TableName {
IdentityUaClientSecret = "identity_ua_client_secrets",
IdentityOrgMembership = "identity_org_memberships",
IdentityProjectMembership = "identity_project_memberships",
ScimToken = "scim_tokens",
SecretApprovalPolicy = "secret_approval_policies",
SecretApprovalPolicyApprover = "secret_approval_policies_approvers",
SecretApprovalRequest = "secret_approval_requests",

View File

@@ -3,6 +3,7 @@ import { registerOrgRoleRouter } from "./org-role-router";
import { registerProjectRoleRouter } from "./project-role-router";
import { registerProjectRouter } from "./project-router";
import { registerSamlRouter } from "./saml-router";
import { registerScimRouter } from "./scim-router";
import { registerSecretApprovalPolicyRouter } from "./secret-approval-policy-router";
import { registerSecretApprovalRequestRouter } from "./secret-approval-request-router";
import { registerSecretRotationProviderRouter } from "./secret-rotation-provider-router";
@@ -33,6 +34,7 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
prefix: "/secret-rotation-providers"
});
await server.register(registerSamlRouter, { prefix: "/sso" });
await server.register(registerScimRouter, { prefix: "/scim" });
await server.register(registerSecretScanningRouter, { prefix: "/secret-scanning" });
await server.register(registerSecretRotationRouter, { prefix: "/secret-rotations" });
await server.register(registerSecretVersionRouter, { prefix: "/secret" });

View File

@@ -0,0 +1,111 @@
import jwt from "jsonwebtoken";
import { z } from "zod";
import { getConfig } from "@app/lib/config/env";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode, AuthTokenType } from "@app/services/auth/auth-type";
export const registerScimRouter = async (server: FastifyZodProvider) => {
server.route({
url: "/",
method: "GET",
schema: {
params: z.object({}),
response: {
200: z.object({})
}
},
// onRequest: verifyAuth([AuthMode.JWT]),
handler: async () => {
return {
hello: "world"
};
}
});
server.route({
url: "/Users",
method: "GET",
schema: {
params: z.object({}),
response: {
200: z.object({})
}
},
// onRequest: verifyAuth([]),
handler: async () => {
return {
hello: "world"
};
}
});
server.route({
url: "/tokens/organizations/:organizationId", // api/v1/scim/token/organizations/:organizationId
method: "POST",
onRequest: verifyAuth([AuthMode.JWT]),
schema: {
params: z.object({
organizationId: z.string().trim()
}),
body: z.object({
description: z.string().trim(),
ttl: z.number().min(0).default(0)
}),
response: {
200: z.object({
scimToken: z.string().trim()
})
}
},
handler: async () => {
// TODO: create SCIM token logic
// TODO: create SCIM token controller
const appCfg = getConfig();
const scimToken = jwt.sign(
{
authTokenType: AuthTokenType.SCIM_TOKEN
},
appCfg.AUTH_SECRET,
{
// expiresIn: identityAccessToken.accessTokenMaxTTL === 0 ? undefined : identityAccessToken.accessTokenMaxTTL
}
); // TODO: add expiration
return { scimToken };
}
});
server.route({
url: "/tokens/organizations/:organizationId", // api/v1/scim/token/organizations/:organizationId
method: "GET",
onRequest: verifyAuth([AuthMode.JWT]),
schema: {
params: z.object({
organizationId: z.string().trim()
}),
response: {
200: z.object({
scimToken: z.string().trim()
})
}
},
handler: async () => {
// TODO: put into service file
const appCfg = getConfig();
const scimToken = jwt.sign(
{
authTokenType: AuthTokenType.SCIM_TOKEN
},
appCfg.AUTH_SECRET,
{
// expiresIn: identityAccessToken.accessTokenMaxTTL === 0 ? undefined : identityAccessToken.accessTokenMaxTTL
}
); // TODO: add expiration
return { scimToken };
}
});
};

View File

@@ -33,6 +33,10 @@ export type TAuthMode =
actor: ActorType.IDENTITY;
identityId: string;
identityName: string;
}
| {
authMode: AuthMode.SCIM_TOKEN;
actor: ActorType.SCIM_IDP;
};
const extractAuth = async (req: FastifyRequest, jwtSecret: string) => {
@@ -53,6 +57,7 @@ const extractAuth = async (req: FastifyRequest, jwtSecret: string) => {
}
const decodedToken = jwt.verify(authTokenValue, jwtSecret) as JwtPayload;
switch (decodedToken.authTokenType) {
case AuthTokenType.ACCESS_TOKEN:
return {
@@ -68,6 +73,12 @@ const extractAuth = async (req: FastifyRequest, jwtSecret: string) => {
token: decodedToken as TIdentityAccessTokenJwtPayload,
actor: ActorType.IDENTITY
} as const;
case AuthTokenType.SCIM_TOKEN:
return {
authMode: AuthMode.SCIM_TOKEN,
token: decodedToken,
actor: ActorType.SCIM_IDP
} as const;
default:
return { authMode: null, token: null } as const;
}
@@ -111,6 +122,10 @@ export const injectIdentity = fp(async (server: FastifyZodProvider) => {
req.auth = { authMode: AuthMode.API_KEY as const, userId: user.id, actor, user };
break;
}
case AuthMode.SCIM_TOKEN: {
req.auth = { authMode: AuthMode.SCIM_TOKEN, actor };
break;
}
default:
throw new UnauthorizedError({ name: "Unknown token strategy" });
}

View File

@@ -17,21 +17,24 @@ export enum AuthTokenType {
API_KEY = "apiKey",
SERVICE_ACCESS_TOKEN = "serviceAccessToken",
SERVICE_REFRESH_TOKEN = "serviceRefreshToken",
IDENTITY_ACCESS_TOKEN = "identityAccessToken"
IDENTITY_ACCESS_TOKEN = "identityAccessToken",
SCIM_TOKEN = "scimToken"
}
export enum AuthMode {
JWT = "jwt",
SERVICE_TOKEN = "serviceToken",
API_KEY = "apiKey",
IDENTITY_ACCESS_TOKEN = "identityAccessToken"
IDENTITY_ACCESS_TOKEN = "identityAccessToken",
SCIM_TOKEN = "scimToken"
}
export enum ActorType { // would extend to AWS, Azure, ...
USER = "user", // userIdentity
SERVICE = "service",
IDENTITY = "identity",
Machine = "machine"
Machine = "machine",
SCIM_IDP = "scimIdp"
}
export type AuthModeJwtTokenPayload = {

View File

@@ -10,6 +10,7 @@ export * from "./integrations";
export * from "./keys";
export * from "./organization";
export * from "./roles";
export * from "./scim";
export * from "./secretApproval";
export * from "./secretApprovalRequest";
export * from "./secretFolders";

View File

@@ -0,0 +1,3 @@
export {
useGetScimToken
} from "./queries";

View File

@@ -0,0 +1,24 @@
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { GetScimTokenRes } from "./types";
const scimKeys = {
getScimToken: (orgId: string) => [{ orgId }, "organization-scim-token"] as const,
};
export const useGetScimToken = (organizationId: string) => {
return useQuery({
queryKey: scimKeys.getScimToken(organizationId),
queryFn: async () => {
if (organizationId === "") {
return undefined;
}
const { data: { scimToken } } = await apiRequest.get<GetScimTokenRes>(`/api/v1/scim/token/organizations/${organizationId}`);
return scimToken;
},
enabled: true
});
};

View File

@@ -0,0 +1,3 @@
export type GetScimTokenRes = {
scimToken: string;
};

View File

@@ -1,6 +1,7 @@
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/context";
import { withPermission } from "@app/hoc";
import { OrgSCIMSection } from "./OrgSCIMSection";
import { OrgSSOSection } from "./OrgSSOSection";
export const OrgAuthTab = withPermission(
@@ -8,6 +9,7 @@ export const OrgAuthTab = withPermission(
return (
<div>
<OrgSSOSection />
<OrgSCIMSection />
</div>
);
},

View File

@@ -0,0 +1,108 @@
import { useState } from "react";
import { faCheck, faCopy } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
// import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
// import { OrgPermissionCan } from "@app/components/permissions";
import {
// Button,
IconButton,
Switch
} from "@app/components/v2";
import {
// OrgPermissionActions,
// OrgPermissionSubjects,
useOrganization,
// useSubscription
} from "@app/context";
import { useToggle } from "@app/hooks";
// import { usePopUp } from "@app/hooks/usePopUp";
import { useGetScimToken } from "@app/hooks/api";
// TODO: add permissioning for enteprise SCIM
export const OrgSCIMSection = () => {
const { currentOrg } = useOrganization();
// const { createNotification } = useNotificationContext();
// const { subscription } = useSubscription();
// const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
// "upgradePlan"
// ] as const);
const { data: scimToken } = useGetScimToken(currentOrg?.id ?? "");
const [scimEnabled, setScimEnabled] = useState(false); // sync this with backend
const [isAPIKeyCopied, setIsAPIKeyCopied] = useToggle(false);
// TODO: get SCIM stuf
const handleSCIMToggle = (value: boolean) => {
// TODO
try {
setScimEnabled(value);
} catch (err) {
console.error(err);
}
}
const copyTokenToClipboard = () => {
navigator.clipboard.writeText(scimToken ?? "");
setIsAPIKeyCopied.on();
};
return (
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
<h2 className="flex-1 text-xl font-semibold text-white mb-8">SCIM Configuration</h2>
<Switch
id="enable-scim"
onCheckedChange={(value) => handleSCIMToggle(value)}
isChecked={scimEnabled}
isDisabled={false}
>
Enable SCIM Provisioning
</Switch>
{scimEnabled && (
<div>
<div className="mt-8 mb-8">
<h3 className="text-sm text-mineshaft-400">SCIM URL</h3>
<p className="text-md text-gray-400">{`${window.origin}/api/v1/scim`}</p>
</div>
{/* <h3 className="mb-2 mt-8 text-sm text-mineshaft-400">SCIM URL</h3> */}
{/* <div className="mb-8 max-w-xl flex items-center justify-between rounded-md bg-white/[0.07] p-2 text-base text-gray-400">
<p className="mr-4 break-all">{`${window.origin}/api/v1/scim`}</p>
<IconButton
ariaLabel="copy icon"
colorSchema="secondary"
className="group relative"
onClick={copyTokenToClipboard}
>
<FontAwesomeIcon icon={isAPIKeyCopied ? faCheck : faCopy} />
<span className="absolute -left-8 -top-20 hidden w-28 translate-y-full rounded-md bg-bunker-800 py-2 pl-3 text-center text-sm text-gray-400 group-hover:flex group-hover:animate-fadeIn">
Click to copy
</span>
</IconButton>
</div> */}
{scimToken && (
<>
<h3 className="mb-2 text-sm text-mineshaft-400">SCIM Bearer Token</h3>
<div className="max-w-xl flex items-center justify-between rounded-md bg-white/[0.07] p-2 text-base text-gray-400">
<p className="mr-4 break-all">{scimToken}</p>
<IconButton
ariaLabel="copy icon"
colorSchema="secondary"
className="group relative"
onClick={copyTokenToClipboard}
>
<FontAwesomeIcon icon={isAPIKeyCopied ? faCheck : faCopy} />
<span className="absolute -left-8 -top-20 hidden w-28 translate-y-full rounded-md bg-bunker-800 py-2 pl-3 text-center text-sm text-gray-400 group-hover:flex group-hover:animate-fadeIn">
Click to copy
</span>
</IconButton>
</div>
</>
)}
</div>
)}
</div>
);
}