Fix merge conflicts

This commit is contained in:
Tuan Dang
2023-11-23 15:37:14 +07:00
28 changed files with 1607 additions and 937 deletions

View File

@@ -306,12 +306,77 @@
},
"/api/v1/workspace/{workspaceId}/audit-logs": {
"get": {
"description": "",
"summary": "Return audit logs",
"description": "Return audit logs",
"parameters": [
{
"name": "workspaceId",
"in": "path",
"required": true,
"schema": {
"type": "string"
},
"description": "ID of the workspace where to get folders from"
},
{
"name": "offset",
"description": "Number of logs to skip before starting to return logs for pagination",
"required": false,
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "limit",
"description": "Maximum number of logs to return for pagination",
"required": false,
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "startDate",
"description": "Filter logs from this date in ISO-8601 format",
"required": false,
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "endDate",
"description": "Filter logs till this date in ISO-8601 format",
"required": false,
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "eventType",
"description": "Filter by type of event such as get-secrets, get-secret, create-secret, update-secret, delete-secret, etc.",
"required": false,
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "userAgentType",
"description": "Filter by type of user agent such as web, cli, k8-operator, or other",
"required": false,
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "actor",
"description": "Filter by actor such as user or service",
"required": false,
"in": "query",
"schema": {
"type": "string"
}
@@ -319,9 +384,30 @@
],
"responses": {
"200": {
"description": "OK"
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"auditLogs": {
"type": "array",
"items": {
"$ref": "#/components/schemas/AuditLog"
},
"description": "List of audit log"
}
}
}
}
}
}
}
},
"security": [
{
"apiKeyAuth": []
}
]
}
},
"/api/v1/workspace/{workspaceId}/audit-logs/filters/actors": {
@@ -1132,6 +1218,43 @@
}
}
},
"/api/v1/admin/config": {
"get": {
"description": "",
"responses": {
"200": {
"description": "OK"
}
}
},
"patch": {
"description": "",
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/admin/signup": {
"post": {
"description": "",
"parameters": [
{
"name": "user-agent",
"in": "header",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/bot/{workspaceId}": {
"get": {
"description": "",
@@ -4560,65 +4683,6 @@
}
}
}
},
"get": {
"summary": "Get all accessible environments of a workspace",
"description": "Fetch all environments that the user has access to in a specified workspace",
"parameters": [
{
"name": "workspaceId",
"in": "path",
"required": true,
"schema": {
"type": "string"
},
"description": "ID of the workspace"
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"accessibleEnvironments": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"example": "Development"
},
"slug": {
"type": "string",
"example": "development"
},
"isWriteDenied": {
"type": "boolean",
"example": false
},
"isReadDenied": {
"type": "boolean",
"example": false
}
}
}
}
},
"description": "List of environments the user has access to in the specified workspace"
}
}
}
}
},
"security": [
{
"apiKeyAuth": []
}
]
}
},
"/api/v2/workspace/{workspaceId}/tags": {
@@ -6864,6 +6928,61 @@
"example": "2023-01-13T14:16:12.210Z"
}
}
},
"AuditLog": {
"type": "object",
"properties": {
"actor": {
"type": "object",
"properties": {
"type": {
"type": "string",
"example": ""
},
"metadata": {
"type": "object",
"properties": {}
}
}
},
"organization": {
"type": "string",
"example": ""
},
"workspace": {
"type": "string",
"example": ""
},
"ipAddress": {
"type": "string",
"example": ""
},
"event": {
"type": "object",
"properties": {
"type": {
"type": "string",
"example": ""
},
"metadata": {
"type": "object",
"properties": {}
}
}
},
"userAgent": {
"type": "string",
"example": ""
},
"userAgentType": {
"type": "string",
"example": ""
},
"expiresAt": {
"type": "string",
"example": ""
}
}
}
},
"securitySchemes": {

View File

@@ -578,6 +578,82 @@ export const rollbackWorkspaceSecretSnapshot = async (req: Request, res: Respons
* @param res
*/
export const getWorkspaceAuditLogs = async (req: Request, res: Response) => {
/*
#swagger.summary = 'Return audit logs'
#swagger.description = 'Return audit logs'
#swagger.security = [{
"apiKeyAuth": []
}]
#swagger.parameters['workspaceId'] = {
"description": "ID of the workspace where to get folders from",
"required": true,
"type": "string",
"in": "path"
}
#swagger.parameters['offset'] = {
"description": "Number of logs to skip before starting to return logs for pagination",
"required": false,
"type": "string"
}
#swagger.parameters['limit'] = {
"description": "Maximum number of logs to return for pagination",
"required": false,
"type": "string"
}
#swagger.parameters['startDate'] = {
"description": "Filter logs from this date in ISO-8601 format",
"required": false,
"type": "string"
}
#swagger.parameters['endDate'] = {
"description": "Filter logs till this date in ISO-8601 format",
"required": false,
"type": "string"
}
#swagger.parameters['eventType'] = {
"description": "Filter by type of event such as get-secrets, get-secret, create-secret, update-secret, delete-secret, etc.",
"required": false,
"type": "string",
}
#swagger.parameters['userAgentType'] = {
"description": "Filter by type of user agent such as web, cli, k8-operator, or other",
"required": false,
"type": "string",
}
#swagger.parameters['actor'] = {
"description": "Filter by actor such as user or service",
"required": false,
"type": "string"
}
#swagger.responses[200] = {
content: {
"application/json": {
schema: {
"type": "object",
"properties": {
"auditLogs": {
"type": "array",
"items": {
$ref: "#/components/schemas/AuditLog",
},
"description": "List of audit log"
},
}
}
}
}
}
*/
const {
query: { limit, offset, endDate, eventType, startDate, userAgentType, actor },
params: { workspaceId }
@@ -592,7 +668,7 @@ export const getWorkspaceAuditLogs = async (req: Request, res: Response) => {
ProjectPermissionActions.Read,
ProjectPermissionSub.AuditLogs
);
const query = {
workspace: new Types.ObjectId(workspaceId),
...(eventType
@@ -626,14 +702,9 @@ export const getWorkspaceAuditLogs = async (req: Request, res: Response) => {
}
: {})
};
const auditLogs = await AuditLog.find(query).sort({ createdAt: -1 }).skip(offset).limit(limit);
const totalCount = await AuditLog.countDocuments(query);
return res.status(200).send({
auditLogs,
totalCount
auditLogs
});
};
@@ -685,7 +756,7 @@ export const getWorkspaceAuditLogActorFilterOpts = async (req: Request, res: Res
name: serviceTokenData.name
}
}));
const serviceV3Actors: ServiceActorV3[] = (
await ServiceTokenDataV3.find({
workspace: new Types.ObjectId(workspaceId)
@@ -697,12 +768,8 @@ export const getWorkspaceAuditLogActorFilterOpts = async (req: Request, res: Res
name: serviceTokenData.name
}
}));
const actors = [
...userActors,
...serviceActors,
...serviceV3Actors
];
const actors = [...userActors, ...serviceActors, ...serviceV3Actors];
return res.status(200).send({
actors

View File

@@ -1,76 +1,70 @@
import { Schema, Types, model } from "mongoose";
import {
ActorType,
EventType,
UserAgentType
} from "./enums";
import {
Actor,
Event
} from "./types";
import { ActorType, EventType, UserAgentType } from "./enums";
import { Actor, Event } from "./types";
export interface IAuditLog {
actor: Actor;
organization: Types.ObjectId;
workspace: Types.ObjectId;
ipAddress: string;
event: Event;
userAgent: string;
userAgentType: UserAgentType;
expiresAt: Date;
actor: Actor;
organization: Types.ObjectId;
workspace: Types.ObjectId;
ipAddress: string;
event: Event;
userAgent: string;
userAgentType: UserAgentType;
expiresAt: Date;
}
const auditLogSchema = new Schema<IAuditLog>(
{
actor: {
type: {
type: String,
enum: ActorType,
required: true
},
metadata: {
type: Schema.Types.Mixed
}
},
organization: {
type: Schema.Types.ObjectId,
required: false
},
workspace: {
type: Schema.Types.ObjectId,
required: false
},
ipAddress: {
type: String,
required: true
},
event: {
type: {
type: String,
enum: EventType,
required: true
},
metadata: {
type: Schema.Types.Mixed
}
},
userAgent: {
type: String,
required: true
},
userAgentType: {
type: String,
enum: UserAgentType,
required: true
},
expiresAt: {
type: Date,
expires: 0
}
{
actor: {
type: {
type: String,
enum: ActorType,
required: true
},
metadata: {
type: Schema.Types.Mixed
}
},
{
timestamps: true
organization: {
type: Schema.Types.ObjectId,
required: false
},
workspace: {
type: Schema.Types.ObjectId,
required: false,
index: true
},
ipAddress: {
type: String,
required: true
},
event: {
type: {
type: String,
enum: EventType,
required: true
},
metadata: {
type: Schema.Types.Mixed
}
},
userAgent: {
type: String,
required: true
},
userAgentType: {
type: String,
enum: UserAgentType,
required: true
},
expiresAt: {
type: Date,
expires: 0
}
},
{
timestamps: true
}
);
export const AuditLog = model<IAuditLog>("AuditLog", auditLogSchema);
export const AuditLog = model<IAuditLog>("AuditLog", auditLogSchema);

View File

@@ -10,6 +10,8 @@ import {
INTEGRATION_CIRCLECI_API_URL,
INTEGRATION_CLOUDFLARE_PAGES,
INTEGRATION_CLOUDFLARE_PAGES_API_URL,
INTEGRATION_CLOUDFLARE_WORKERS,
INTEGRATION_CLOUDFLARE_WORKERS_API_URL,
INTEGRATION_CLOUD_66,
INTEGRATION_CLOUD_66_API_URL,
INTEGRATION_CODEFRESH,
@@ -186,6 +188,12 @@ const getApps = async ({
accountId: accessId
});
break;
case INTEGRATION_CLOUDFLARE_WORKERS:
apps = await getAppsCloudflareWorkers({
accessToken,
accountId: accessId
});
break;
case INTEGRATION_NORTHFLANK:
apps = await getAppsNorthflank({
accessToken
@@ -968,6 +976,40 @@ const getAppsCloudflarePages = async ({
return apps;
};
/**
* Return list of projects for the Cloudflare Workers integration
* @param {Object} obj
* @param {String} obj.accessToken - api key for the Cloudflare API
* @returns {Object[]} apps - Cloudflare Workers projects
* @returns {String} apps.id - Id of Cloudflare Workers project
* @returns {String} apps.name - Id of Cloudflare Workers project (Cloudflare workers API does not return the name)
*/
const getAppsCloudflareWorkers = async ({
accessToken,
accountId
}: {
accessToken: string;
accountId?: string;
}) => {
const { data } = await standardRequest.get(
`${INTEGRATION_CLOUDFLARE_WORKERS_API_URL}/client/v4/accounts/${accountId}/workers/services`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json"
}
}
);
const apps = data.result.map((a: any) => {
return {
name: a.id,
appId: a.id
};
});
return apps;
};
/**
* Return list of repositories for the BitBucket integration based on provided BitBucket workspace
* @param {Object} obj

View File

@@ -18,6 +18,8 @@ import {
INTEGRATION_CIRCLECI_API_URL,
INTEGRATION_CLOUDFLARE_PAGES,
INTEGRATION_CLOUDFLARE_PAGES_API_URL,
INTEGRATION_CLOUDFLARE_WORKERS,
INTEGRATION_CLOUDFLARE_WORKERS_API_URL,
INTEGRATION_CLOUD_66,
INTEGRATION_CLOUD_66_API_URL,
INTEGRATION_CODEFRESH,
@@ -262,6 +264,14 @@ const syncSecrets = async ({
accessToken
});
break;
case INTEGRATION_CLOUDFLARE_WORKERS:
await syncSecretsCloudflareWorkers({
integration,
secrets,
accessId,
accessToken
});
break;
case INTEGRATION_CODEFRESH:
await syncSecretsCodefresh({
integration,
@@ -2746,6 +2756,98 @@ const syncSecretsCloudflarePages = async ({
);
};
/**
* Sync/push [secrets] to Cloudflare Workers project with name [integration.app]
* @param {Object} obj
* @param {IIntegration} obj.integration - integration details
* @param {Object} obj.secrets - secrets to push to integration (object where keys are secret keys and values are secret values)
* @param {String} obj.accessToken - API token for Cloudflare workers
*/
const syncSecretsCloudflareWorkers = async ({
integration,
secrets,
accessId,
accessToken
}: {
integration: IIntegration;
secrets: Record<string, { value: string; comment?: string }>;
accessId: string | null;
accessToken: string;
}) => {
// get secrets from cloudflare workers
const getSecretsRes = (
await standardRequest.get(
`${INTEGRATION_CLOUDFLARE_WORKERS_API_URL}/client/v4/accounts/${accessId}/workers/scripts/${integration.app}/secrets`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json"
}
}
)
).data.result;
const secretsObj: any = getSecretKeyValuePair(secrets);
for (const [key, val] of Object.entries(secretsObj)) {
secretsObj[key] = { type: "secret_text", value: val };
}
// get deleted secrets list
const deletedSecretKeys: string[] = [];
if (getSecretsRes) {
getSecretsRes.forEach((secretRes: any) => {
if (!(Object.keys(secrets).includes(secretRes.name))) {
deletedSecretKeys.push(secretRes.name);
}
})
}
deletedSecretKeys.forEach(async (secretKey) => {
await standardRequest.delete(
`${INTEGRATION_CLOUDFLARE_WORKERS_API_URL}/client/v4/accounts/${accessId}/workers/scripts/${integration.app}/secrets/${secretKey}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json"
}
}
);
});
interface ConvertedSecret {
name: string;
text: string;
type: string;
}
interface SecretsObj {
[key: string]: {
type: string;
value: string;
};
}
const data: ConvertedSecret[] = Object.entries(secretsObj as SecretsObj).map(([name, secret]) => ({
name,
text: secret.value,
type: "secret_text"
}));
data.forEach(async (secret) => {
await standardRequest.put(
`${INTEGRATION_CLOUDFLARE_WORKERS_API_URL}/client/v4/accounts/${accessId}/workers/scripts/${integration.app}/secrets`,
secret,
{
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json"
}
}
);
})
};
/**
* Sync/push [secrets] to BitBucket repo with name [integration.app]
* @param {Object} obj

View File

@@ -6,6 +6,7 @@ import {
INTEGRATION_CHECKLY,
INTEGRATION_CIRCLECI,
INTEGRATION_CLOUDFLARE_PAGES,
INTEGRATION_CLOUDFLARE_WORKERS,
INTEGRATION_CLOUD_66,
INTEGRATION_CODEFRESH,
INTEGRATION_DIGITAL_OCEAN_APP_PLATFORM,
@@ -71,6 +72,7 @@ export interface IIntegration {
| "teamcity"
| "hashicorp-vault"
| "cloudflare-pages"
| "cloudflare-workers"
| "bitbucket"
| "codefresh"
| "digital-ocean-app-platform"
@@ -179,6 +181,7 @@ const integrationSchema = new Schema<IIntegration>(
INTEGRATION_TEAMCITY,
INTEGRATION_HASHICORP_VAULT,
INTEGRATION_CLOUDFLARE_PAGES,
INTEGRATION_CLOUDFLARE_WORKERS,
INTEGRATION_CODEFRESH,
INTEGRATION_WINDMILL,
INTEGRATION_BITBUCKET,

View File

@@ -8,6 +8,7 @@ import {
INTEGRATION_BITBUCKET,
INTEGRATION_CIRCLECI,
INTEGRATION_CLOUDFLARE_PAGES,
INTEGRATION_CLOUDFLARE_WORKERS,
INTEGRATION_CLOUD_66,
INTEGRATION_CODEFRESH,
INTEGRATION_DIGITAL_OCEAN_APP_PLATFORM,
@@ -55,6 +56,7 @@ export interface IIntegrationAuth extends Document {
| "checkly"
| "qovery"
| "cloudflare-pages"
| "cloudflare-workers"
| "codefresh"
| "digital-ocean-app-platform"
| "bitbucket"
@@ -113,6 +115,7 @@ const integrationAuthSchema = new Schema<IIntegrationAuth>(
INTEGRATION_TERRAFORM_CLOUD,
INTEGRATION_HASHICORP_VAULT,
INTEGRATION_CLOUDFLARE_PAGES,
INTEGRATION_CLOUDFLARE_WORKERS,
INTEGRATION_CODEFRESH,
INTEGRATION_WINDMILL,
INTEGRATION_BITBUCKET,

View File

@@ -59,7 +59,7 @@ export const validateClientForWorkspace = async ({
environment,
requiredPermissions
});
return { membership, workspace};
return { membership, workspace };
case ActorType.SERVICE_V3:
throw UnauthorizedRequestError({
message: "Failed service token authorization for organization"
@@ -122,8 +122,8 @@ export const GetWorkspaceAuditLogsV1 = z.object({
userAgentType: z.nativeEnum(UserAgentType).nullable().optional(),
startDate: z.string().datetime().nullable().optional(),
endDate: z.string().datetime().nullable().optional(),
offset: z.coerce.number(),
limit: z.coerce.number(),
offset: z.coerce.number().default(0),
limit: z.coerce.number().default(20),
actor: z.string().nullish().optional()
})
});
@@ -327,4 +327,4 @@ export const NameWorkspaceSecretsV3 = z.object({
})
.array()
})
});
});

View File

@@ -32,6 +32,7 @@ export const INTEGRATION_QOVERY = "qovery";
export const INTEGRATION_TERRAFORM_CLOUD = "terraform-cloud";
export const INTEGRATION_HASHICORP_VAULT = "hashicorp-vault";
export const INTEGRATION_CLOUDFLARE_PAGES = "cloudflare-pages";
export const INTEGRATION_CLOUDFLARE_WORKERS = "cloudflare-workers";
export const INTEGRATION_BITBUCKET = "bitbucket";
export const INTEGRATION_CODEFRESH = "codefresh";
export const INTEGRATION_WINDMILL = "windmill";
@@ -59,6 +60,7 @@ export const INTEGRATION_SET = new Set([
INTEGRATION_TERRAFORM_CLOUD,
INTEGRATION_HASHICORP_VAULT,
INTEGRATION_CLOUDFLARE_PAGES,
INTEGRATION_CLOUDFLARE_WORKERS,
INTEGRATION_CODEFRESH,
INTEGRATION_WINDMILL,
INTEGRATION_BITBUCKET,
@@ -101,6 +103,7 @@ export const INTEGRATION_CHECKLY_API_URL = "https://api.checklyhq.com";
export const INTEGRATION_QOVERY_API_URL = "https://api.qovery.com";
export const INTEGRATION_TERRAFORM_CLOUD_API_URL = "https://app.terraform.io";
export const INTEGRATION_CLOUDFLARE_PAGES_API_URL = "https://api.cloudflare.com";
export const INTEGRATION_CLOUDFLARE_WORKERS_API_URL = "https://api.cloudflare.com";
export const INTEGRATION_BITBUCKET_API_URL = "https://api.bitbucket.org";
export const INTEGRATION_CODEFRESH_API_URL = "https://g.codefresh.io/api";
export const INTEGRATION_WINDMILL_API_URL = "https://app.windmill.dev/api";
@@ -316,6 +319,15 @@ export const getIntegrationOptions = async () => {
clientId: "",
docsLink: ""
},
{
name: "Cloudflare Workers",
slug: "cloudflare-workers",
image: "Cloudflare.png",
isAvailable: true,
type: "pat",
clientId: "",
docsLink: ""
},
{
name: "BitBucket",
slug: "bitbucket",

View File

@@ -12,32 +12,32 @@ const generateOpenAPISpec = async () => {
const doc = {
info: {
title: "Infisical API",
description: "List of all available APIs that can be consumed",
description: "List of all available APIs that can be consumed"
},
host: ["https://infisical.com"],
servers: [
{
url: "https://app.infisical.com",
description: "Production server",
description: "Production server"
},
{
url: "http://localhost:8080",
description: "Local server",
},
description: "Local server"
}
],
securityDefinitions: {
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
description: "A service token in Infisical",
description: "A service token in Infisical"
},
apiKeyAuth: {
type: "apiKey",
in: "header",
name: "X-API-Key",
description: "An API Key in Infisical",
},
description: "An API Key in Infisical"
}
},
definitions: {
CurrentUser: {
@@ -50,7 +50,7 @@ const generateOpenAPISpec = async () => {
iv: "iv_of_enc_nacl_private_key",
tag: "tag_of_enc_nacl_private_key",
updatedAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z"
},
Membership: {
user: {
@@ -60,10 +60,10 @@ const generateOpenAPISpec = async () => {
lastName: "Doe",
publicKey: "johns_nacl_public_key",
updatedAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z"
},
workspace: "",
role: "admin",
role: "admin"
},
MembershipOrg: {
user: {
@@ -73,33 +73,35 @@ const generateOpenAPISpec = async () => {
lastName: "Doe",
publicKey: "johns_nacl_public_key",
updatedAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z"
},
organization: "",
role: "owner",
status: "accepted",
status: "accepted"
},
Organization: {
_id: "",
name: "Acme Corp.",
customerId: "",
customerId: ""
},
Project: {
name: "My Project",
organization: "",
environments: [{
name: "development",
slug: "dev",
}],
environments: [
{
name: "development",
slug: "dev"
}
]
},
ProjectKey: {
encryptedkey: "",
nonce: "",
sender: {
publicKey: "senders_nacl_public_key",
publicKey: "senders_nacl_public_key"
},
receiver: "",
workspace: "",
workspace: ""
},
CreateSecret: {
type: "shared",
@@ -111,7 +113,7 @@ const generateOpenAPISpec = async () => {
secretValueTag: "",
secretCommentCiphertext: "",
secretCommentIV: "",
secretCommentTag: "",
secretCommentTag: ""
},
UpdateSecret: {
id: "",
@@ -123,12 +125,12 @@ const generateOpenAPISpec = async () => {
secretValueTag: "",
secretCommentCiphertext: "",
secretCommentIV: "",
secretCommentTag: "",
secretCommentTag: ""
},
Secret: {
_id: "",
version: 1,
workspace : "",
workspace: "",
type: "shared",
user: null,
secretKeyCiphertext: "",
@@ -141,7 +143,7 @@ const generateOpenAPISpec = async () => {
secretCommentIV: "",
secretCommentTag: "",
updatedAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z"
},
RawSecret: {
_id: "abc123",
@@ -167,12 +169,10 @@ const generateOpenAPISpec = async () => {
_id: "",
email: "johndoe@gmail.com",
firstName: "John",
lastName: "Doe",
lastName: "Doe"
},
workspace: "",
actionNames: [
"addSecrets",
],
actionNames: ["addSecrets"],
actions: [
{
name: "addSecrets",
@@ -181,24 +181,24 @@ const generateOpenAPISpec = async () => {
payload: [
{
oldSecretVersion: "",
newSecretVersion: "",
},
],
},
newSecretVersion: ""
}
]
}
],
channel: "cli",
ipAddress: "192.168.0.1",
updatedAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z"
},
SecretSnapshot: {
workspace: "",
version: 1,
secretVersions: [
{
_id: "",
},
],
_id: ""
}
]
},
SecretVersion: {
_id: "",
@@ -214,7 +214,7 @@ const generateOpenAPISpec = async () => {
secretKeyTag: "",
secretValueCiphertext: "",
secretValueIV: "",
secretValueTag: "",
secretValueTag: ""
},
ServiceTokenData: {
_id: "",
@@ -224,16 +224,32 @@ const generateOpenAPISpec = async () => {
user: {
_id: "",
firstName: "",
lastName: "",
lastName: ""
},
expiresAt: "2023-01-13T14:16:12.210Z",
encryptedKey: "",
iv: "",
tag: "",
updatedAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z",
createdAt: "2023-01-13T14:16:12.210Z"
},
},
AuditLog: {
actor: {
type: "",
metadata: {}
},
organization: "",
workspace: "",
ipAddress: "",
event: {
type: "",
metadata: {}
},
userAgent: "",
userAgentType: "",
expiresAt: ""
}
}
};
const outputJSONFile = "../spec.json";
@@ -243,6 +259,6 @@ const generateOpenAPISpec = async () => {
const spec = await swaggerAutogen(outputJSONFile, endpointsFiles, doc);
await fs.writeFile(outputYAMLFile, yaml.dump(spec.data));
}
};
generateOpenAPISpec();
generateOpenAPISpec();

View File

@@ -0,0 +1,4 @@
---
title: "Export"
openapi: "GET /api/v1/workspace/{workspaceId}/audit-logs"
---

View File

@@ -1,4 +1,4 @@
---
title: "Create"
openapi: "POST /api/v2/workspace/{workspaceId}/environments"
---
openapi: "POST /api/v1/workspace/{workspaceId}/environments"
---

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 287 KiB

View File

@@ -0,0 +1,43 @@
---
title: "Cloudflare Workers"
description: "How to sync secrets from Infisical to Cloudflare Workers"
---
Prerequisites:
- Set up and add envars to [Infisical Cloud](https://app.infisical.com)
## Navigate to your project's integrations tab
![integrations](../../images/integrations.png)
## Authorize Infisical for Cloudflare Workers
Obtain a Cloudflare [API token](https://dash.cloudflare.com/profile/api-tokens) and [Account ID](https://developers.cloudflare.com/fundamentals/get-started/basic-tasks/find-account-and-zone-ids/):
1. Create a new [API token](https://dash.cloudflare.com/profile/api-tokens) in My Profile > API Tokens
![integrations cloudflare credentials 1](../../images/integrations/cloudflare/integrations-cloudflare-credentials-1.png)
![integrations cloudflare credentials 2](../../images/integrations/cloudflare/integrations-cloudflare-credentials-2.png)
![integrations cloudflare credentials 3](../../images/integrations/cloudflare/integrations-cloudflare-credentials-3.png)
2. Copy your [Account ID](https://developers.cloudflare.com/fundamentals/get-started/basic-tasks/find-account-and-zone-ids/) from Account > Workers & Pages > Overview
![integrations cloudflare credentials 4](../../images/integrations/cloudflare/integrations-cloudflare-credentials-4.png)
Press on the Cloudflare Workers tile and input your Cloudflare API token and account ID to grant Infisical access to your Cloudflare Workers.
![integrations cloudflare authorization](../../images/integrations/cloudflare/integration-cloudflare-workers-connect.png)
<Info>
If this is your project's first cloud integration, then you'll have to grant
Infisical access to your project's environment variables. Although this step
breaks E2EE, it's necessary for Infisical to sync the environment variables to
the cloud platform.
</Info>
## Start integration
Select which Infisical environment secrets you want to sync to Cloudflare Workers and press create integration to start syncing secrets.
![integrations cloudflare](../../images/integrations/cloudflare/integration-cloudflare-workers-create.png)

View File

@@ -26,6 +26,7 @@ Missing an integration? [Throw in a request](https://github.com/Infisical/infisi
| [Supabase](/integrations/cloud/supabase) | Cloud | Available |
| [Northflank](/integrations/cloud/northflank) | Cloud | Available |
| [Cloudflare Pages](/integrations/cloud/cloudflare-pages) | Cloud | Available |
| [Cloudflare Workers](/integrations/cloud/cloudflare-workers) | Cloud | Available |
| [Checkly](/integrations/cloud/checkly) | Cloud | Available |
| [Qovery](/integrations/cloud/qovery) | Cloud | Available |
| [HashiCorp Vault](/integrations/cloud/hashicorp-vault) | Cloud | Available |

View File

@@ -242,6 +242,7 @@
"integrations/cloud/hasura-cloud",
"integrations/cloud/terraform-cloud",
"integrations/cloud/cloudflare-pages",
"integrations/cloud/cloudflare-workers",
"integrations/cloud/qovery",
"integrations/cloud/hashicorp-vault",
"integrations/cloud/azure-key-vault",
@@ -380,6 +381,10 @@
{
"group": "Service Tokens",
"pages": ["api-reference/endpoints/service-tokens/get"]
},
{
"group": "Audit Logs",
"pages": ["api-reference/endpoints/audit-logs/export-audit-log"]
}
]
},

View File

@@ -192,16 +192,74 @@ paths:
description: Version of secret snapshot to roll back to
/api/v1/workspace/{workspaceId}/audit-logs:
get:
description: ''
summary: Return audit logs
description: Return audit logs
parameters:
- name: workspaceId
in: path
required: true
schema:
type: string
description: ID of the workspace where to get folders from
- name: offset
description: Number of logs to skip before starting to return logs for pagination
required: false
in: query
schema:
type: string
- name: limit
description: Maximum number of logs to return for pagination
required: false
in: query
schema:
type: string
- name: startDate
description: Filter logs from this date in ISO-8601 format
required: false
in: query
schema:
type: string
- name: endDate
description: Filter logs till this date in ISO-8601 format
required: false
in: query
schema:
type: string
- name: eventType
description: >-
Filter by type of event such as get-secrets, get-secret,
create-secret, update-secret, delete-secret, etc.
required: false
in: query
schema:
type: string
- name: userAgentType
description: Filter by type of user agent such as web, cli, k8-operator, or other
required: false
in: query
schema:
type: string
- name: actor
description: Filter by actor such as user or service
required: false
in: query
schema:
type: string
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
auditLogs:
type: array
items:
$ref: '#/components/schemas/AuditLog'
description: List of audit log
security:
- apiKeyAuth: []
/api/v1/workspace/{workspaceId}/audit-logs/filters/actors:
get:
description: ''
@@ -691,6 +749,28 @@ paths:
responses:
'200':
description: OK
/api/v1/admin/config:
get:
description: ''
responses:
'200':
description: OK
patch:
description: ''
responses:
'200':
description: OK
/api/v1/admin/signup:
post:
description: ''
parameters:
- name: user-agent
in: header
schema:
type: string
responses:
'200':
description: OK
/api/v1/bot/{workspaceId}:
get:
description: ''
@@ -2834,48 +2914,6 @@ paths:
example: dev
required:
- environmentSlug
get:
summary: Get all accessible environments of a workspace
description: >-
Fetch all environments that the user has access to in a specified
workspace
parameters:
- name: workspaceId
in: path
required: true
schema:
type: string
description: ID of the workspace
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
accessibleEnvironments:
type: array
items:
type: object
properties:
name:
type: string
example: Development
slug:
type: string
example: development
isWriteDenied:
type: boolean
example: false
isReadDenied:
type: boolean
example: false
description: >-
List of environments the user has access to in the specified
workspace
security:
- apiKeyAuth: []
/api/v2/workspace/{workspaceId}/tags:
get:
description: ''
@@ -4342,6 +4380,45 @@ components:
createdAt:
type: string
example: '2023-01-13T14:16:12.210Z'
AuditLog:
type: object
properties:
actor:
type: object
properties:
type:
type: string
example: ''
metadata:
type: object
properties: {}
organization:
type: string
example: ''
workspace:
type: string
example: ''
ipAddress:
type: string
example: ''
event:
type: object
properties:
type:
type: string
example: ''
metadata:
type: object
properties: {}
userAgent:
type: string
example: ''
userAgentType:
type: string
example: ''
expiresAt:
type: string
example: ''
securitySchemes:
bearerAuth:
type: http

View File

@@ -24,6 +24,7 @@ const integrationSlugNameMapping: Mapping = {
teamcity: "TeamCity",
"hashicorp-vault": "Vault",
"cloudflare-pages": "Cloudflare Pages",
"cloudflare-workers": "Cloudflare Workers",
codefresh: "Codefresh",
"digital-ocean-app-platform": "Digital Ocean App Platform",
bitbucket: "BitBucket",

View File

@@ -1,59 +1,46 @@
import { useQuery } from "@tanstack/react-query";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import {
Actor,
AuditLog,
AuditLogFilters
} from "./types";
import { Actor, AuditLog, AuditLogFilters } from "./types";
export const workspaceKeys = {
getAuditLogs: (workspaceId: string, filters: AuditLogFilters) => [{ workspaceId, filters }, "audit-logs"] as const,
getAuditLogActorFilterOpts: (workspaceId: string) => [{ workspaceId }, "audit-log-actor-filters"] as const
}
getAuditLogs: (workspaceId: string, filters: AuditLogFilters) =>
[{ workspaceId, filters }, "audit-logs"] as const,
getAuditLogActorFilterOpts: (workspaceId: string) =>
[{ workspaceId }, "audit-log-actor-filters"] as const
};
export const useGetAuditLogs = (workspaceId: string, filters: AuditLogFilters) => {
return useQuery({
queryKey: workspaceKeys.getAuditLogs(workspaceId, filters),
queryFn: async () => {
const params = new URLSearchParams();
if (filters.eventType) {
params.append("eventType", filters.eventType);
}
if (filters.userAgentType) {
params.append("userAgentType", filters.userAgentType);
}
if (filters.actor) {
params.append("actor", filters.actor);
}
if (filters.startDate) {
params.append("startDate", filters.startDate.toISOString());
}
if (filters.endDate) {
params.append("endDate", filters.endDate.toISOString());
}
params.append("offset", String(filters.offset));
params.append("limit", String(filters.limit));
const { data } = await apiRequest.get<{ auditLogs: AuditLog[], totalCount: number }>(`/api/v1/workspace/${workspaceId}/audit-logs`, { params });
return data;
return useInfiniteQuery({
queryKey: workspaceKeys.getAuditLogs(workspaceId, filters),
queryFn: async ({ pageParam }) => {
const { data } = await apiRequest.get<{ auditLogs: AuditLog[] }>(
`/api/v1/workspace/${workspaceId}/audit-logs`,
{
params: {
...filters,
offset: pageParam,
startDate: filters?.startDate?.toISOString(),
endDate: filters?.endDate?.toISOString()
}
}
});
}
);
return data.auditLogs;
},
getNextPageParam: (lastPage, pages) =>
lastPage.length !== 0 ? pages.length * filters.limit : undefined
});
};
export const useGetAuditLogActorFilterOpts = (workspaceId: string) => {
return useQuery({
queryKey: workspaceKeys.getAuditLogActorFilterOpts(workspaceId),
queryFn: async () => {
const { data } = await apiRequest.get<{ actors: Actor[] }>(`/api/v1/workspace/${workspaceId}/audit-logs/filters/actors`);
return data.actors;
}
});
}
return useQuery({
queryKey: workspaceKeys.getAuditLogActorFilterOpts(workspaceId),
queryFn: async () => {
const { data } = await apiRequest.get<{ actors: Actor[] }>(
`/api/v1/workspace/${workspaceId}/audit-logs/filters/actors`
);
return data.actors;
}
});
};

View File

@@ -1,8 +1,4 @@
import {
ActorType,
EventType,
UserAgentType
} from "./enums";
import { ActorType, EventType, UserAgentType } from "./enums";
interface UserActorMetadata {
userId: string;
@@ -25,174 +21,171 @@ export interface ServiceActor {
}
export interface ServiceActorV3 {
type: ActorType.SERVICE_V3;
metadata: ServiceActorMetadata;
type: ActorType.SERVICE_V3;
metadata: ServiceActorMetadata;
}
export type Actor =
| UserActor
| ServiceActor
| ServiceActorV3;
export type Actor = UserActor | ServiceActor | ServiceActorV3;
interface GetSecretsEvent {
type: EventType.GET_SECRETS;
metadata: {
environment: string;
secretPath: string;
numberOfSecrets: number;
};
type: EventType.GET_SECRETS;
metadata: {
environment: string;
secretPath: string;
numberOfSecrets: number;
};
}
interface GetSecretEvent {
type: EventType.GET_SECRET;
metadata: {
environment: string;
secretPath: string;
secretId: string;
secretKey: string;
secretVersion: number;
};
type: EventType.GET_SECRET;
metadata: {
environment: string;
secretPath: string;
secretId: string;
secretKey: string;
secretVersion: number;
};
}
interface CreateSecretEvent {
type: EventType.CREATE_SECRET;
metadata: {
environment: string;
secretPath: string;
secretId: string;
secretKey: string;
secretVersion: number;
}
type: EventType.CREATE_SECRET;
metadata: {
environment: string;
secretPath: string;
secretId: string;
secretKey: string;
secretVersion: number;
};
}
interface UpdateSecretEvent {
type: EventType.UPDATE_SECRET;
metadata: {
environment: string;
secretPath: string;
secretId: string;
secretKey: string;
secretVersion: number;
}
type: EventType.UPDATE_SECRET;
metadata: {
environment: string;
secretPath: string;
secretId: string;
secretKey: string;
secretVersion: number;
};
}
interface DeleteSecretEvent {
type: EventType.DELETE_SECRET;
metadata: {
environment: string;
secretPath: string;
secretId: string;
secretKey: string;
secretVersion: number;
}
type: EventType.DELETE_SECRET;
metadata: {
environment: string;
secretPath: string;
secretId: string;
secretKey: string;
secretVersion: number;
};
}
interface GetWorkspaceKeyEvent {
type: EventType.GET_WORKSPACE_KEY,
metadata: {
keyId: string;
}
type: EventType.GET_WORKSPACE_KEY;
metadata: {
keyId: string;
};
}
interface AuthorizeIntegrationEvent {
type: EventType.AUTHORIZE_INTEGRATION;
metadata: {
integration: string;
}
type: EventType.AUTHORIZE_INTEGRATION;
metadata: {
integration: string;
};
}
interface UnauthorizeIntegrationEvent {
type: EventType.UNAUTHORIZE_INTEGRATION;
metadata: {
integration: string;
}
type: EventType.UNAUTHORIZE_INTEGRATION;
metadata: {
integration: string;
};
}
interface CreateIntegrationEvent {
type: EventType.CREATE_INTEGRATION;
metadata: {
integrationId: string;
integration: string;
environment: string;
secretPath: string;
url?: string;
app?: string;
appId?: string;
targetEnvironment?: string;
targetEnvironmentId?: string;
targetService?: string;
targetServiceId?: string;
path?: string;
region?: string;
}
type: EventType.CREATE_INTEGRATION;
metadata: {
integrationId: string;
integration: string;
environment: string;
secretPath: string;
url?: string;
app?: string;
appId?: string;
targetEnvironment?: string;
targetEnvironmentId?: string;
targetService?: string;
targetServiceId?: string;
path?: string;
region?: string;
};
}
interface DeleteIntegrationEvent {
type: EventType.DELETE_INTEGRATION;
metadata: {
integrationId: string;
integration: string;
environment: string;
secretPath: string;
url?: string;
app?: string;
appId?: string;
targetEnvironment?: string;
targetEnvironmentId?: string;
targetService?: string;
targetServiceId?: string;
path?: string;
region?: string;
}
type: EventType.DELETE_INTEGRATION;
metadata: {
integrationId: string;
integration: string;
environment: string;
secretPath: string;
url?: string;
app?: string;
appId?: string;
targetEnvironment?: string;
targetEnvironmentId?: string;
targetService?: string;
targetServiceId?: string;
path?: string;
region?: string;
};
}
interface AddTrustedIPEvent {
type: EventType.ADD_TRUSTED_IP;
metadata: {
trustedIpId: string;
ipAddress: string;
prefix?: number;
}
type: EventType.ADD_TRUSTED_IP;
metadata: {
trustedIpId: string;
ipAddress: string;
prefix?: number;
};
}
interface UpdateTrustedIPEvent {
type: EventType.UPDATE_TRUSTED_IP;
metadata: {
trustedIpId: string;
ipAddress: string;
prefix?: number;
}
type: EventType.UPDATE_TRUSTED_IP;
metadata: {
trustedIpId: string;
ipAddress: string;
prefix?: number;
};
}
interface DeleteTrustedIPEvent {
type: EventType.DELETE_TRUSTED_IP;
metadata: {
trustedIpId: string;
ipAddress: string;
prefix?: number;
}
type: EventType.DELETE_TRUSTED_IP;
metadata: {
trustedIpId: string;
ipAddress: string;
prefix?: number;
};
}
interface CreateServiceTokenEvent {
type: EventType.CREATE_SERVICE_TOKEN;
metadata: {
name: string;
scopes: Array<{
environment: string;
secretPath: string;
}>;
}
type: EventType.CREATE_SERVICE_TOKEN;
metadata: {
name: string;
scopes: Array<{
environment: string;
secretPath: string;
}>;
};
}
interface DeleteServiceTokenEvent {
type: EventType.DELETE_SERVICE_TOKEN;
metadata: {
name: string;
scopes: Array<{
environment: string;
secretPath: string;
}>;
}
type: EventType.DELETE_SERVICE_TOKEN;
metadata: {
name: string;
scopes: Array<{
environment: string;
secretPath: string;
}>;
};
}
interface CreateServiceTokenV3Event {
@@ -226,227 +219,226 @@ interface DeleteServiceTokenV3Event {
}
interface CreateEnvironmentEvent {
type: EventType.CREATE_ENVIRONMENT;
metadata: {
name: string;
slug: string;
}
type: EventType.CREATE_ENVIRONMENT;
metadata: {
name: string;
slug: string;
};
}
interface UpdateEnvironmentEvent {
type: EventType.UPDATE_ENVIRONMENT;
metadata: {
oldName: string;
newName: string;
oldSlug: string;
newSlug: string;
}
type: EventType.UPDATE_ENVIRONMENT;
metadata: {
oldName: string;
newName: string;
oldSlug: string;
newSlug: string;
};
}
interface DeleteEnvironmentEvent {
type: EventType.DELETE_ENVIRONMENT;
metadata: {
name: string;
slug: string;
}
type: EventType.DELETE_ENVIRONMENT;
metadata: {
name: string;
slug: string;
};
}
interface AddWorkspaceMemberEvent {
type: EventType.ADD_WORKSPACE_MEMBER;
metadata: {
userId: string;
email: string;
}
type: EventType.ADD_WORKSPACE_MEMBER;
metadata: {
userId: string;
email: string;
};
}
interface RemoveWorkspaceMemberEvent {
type: EventType.REMOVE_WORKSPACE_MEMBER;
metadata: {
userId: string;
email: string;
}
type: EventType.REMOVE_WORKSPACE_MEMBER;
metadata: {
userId: string;
email: string;
};
}
interface CreateFolderEvent {
type: EventType.CREATE_FOLDER;
metadata: {
environment: string;
folderId: string;
folderName: string;
folderPath: string;
}
type: EventType.CREATE_FOLDER;
metadata: {
environment: string;
folderId: string;
folderName: string;
folderPath: string;
};
}
interface UpdateFolderEvent {
type: EventType.UPDATE_FOLDER;
metadata: {
environment: string;
folderId: string;
oldFolderName: string;
newFolderName: string;
folderPath: string;
}
type: EventType.UPDATE_FOLDER;
metadata: {
environment: string;
folderId: string;
oldFolderName: string;
newFolderName: string;
folderPath: string;
};
}
interface DeleteFolderEvent {
type: EventType.DELETE_FOLDER;
metadata: {
environment: string;
folderId: string;
folderName: string;
folderPath: string;
}
type: EventType.DELETE_FOLDER;
metadata: {
environment: string;
folderId: string;
folderName: string;
folderPath: string;
};
}
interface CreateWebhookEvent {
type: EventType.CREATE_WEBHOOK,
metadata: {
webhookId: string;
environment: string;
secretPath: string;
webhookUrl: string;
isDisabled: boolean;
}
type: EventType.CREATE_WEBHOOK;
metadata: {
webhookId: string;
environment: string;
secretPath: string;
webhookUrl: string;
isDisabled: boolean;
};
}
interface UpdateWebhookStatusEvent {
type: EventType.UPDATE_WEBHOOK_STATUS,
metadata: {
webhookId: string;
environment: string;
secretPath: string;
webhookUrl: string;
isDisabled: boolean;
}
type: EventType.UPDATE_WEBHOOK_STATUS;
metadata: {
webhookId: string;
environment: string;
secretPath: string;
webhookUrl: string;
isDisabled: boolean;
};
}
interface DeleteWebhookEvent {
type: EventType.DELETE_WEBHOOK,
metadata: {
webhookId: string;
environment: string;
secretPath: string;
webhookUrl: string;
isDisabled: boolean;
}
type: EventType.DELETE_WEBHOOK;
metadata: {
webhookId: string;
environment: string;
secretPath: string;
webhookUrl: string;
isDisabled: boolean;
};
}
interface GetSecretImportsEvent {
type: EventType.GET_SECRET_IMPORTS,
metadata: {
environment: string;
secretImportId: string;
folderId: string;
numberOfImports: number;
}
type: EventType.GET_SECRET_IMPORTS;
metadata: {
environment: string;
secretImportId: string;
folderId: string;
numberOfImports: number;
};
}
interface CreateSecretImportEvent {
type: EventType.CREATE_SECRET_IMPORT,
metadata: {
secretImportId: string;
folderId: string;
importFromEnvironment: string;
importFromSecretPath: string;
importToEnvironment: string;
importToSecretPath: string;
}
type: EventType.CREATE_SECRET_IMPORT;
metadata: {
secretImportId: string;
folderId: string;
importFromEnvironment: string;
importFromSecretPath: string;
importToEnvironment: string;
importToSecretPath: string;
};
}
interface UpdateSecretImportEvent {
type: EventType.UPDATE_SECRET_IMPORT,
metadata: {
secretImportId: string;
folderId: string;
importToEnvironment: string;
importToSecretPath: string;
orderBefore: {
environment: string;
secretPath: string;
}[],
orderAfter: {
environment: string;
secretPath: string;
}[]
}
type: EventType.UPDATE_SECRET_IMPORT;
metadata: {
secretImportId: string;
folderId: string;
importToEnvironment: string;
importToSecretPath: string;
orderBefore: {
environment: string;
secretPath: string;
}[];
orderAfter: {
environment: string;
secretPath: string;
}[];
};
}
interface DeleteSecretImportEvent {
type: EventType.DELETE_SECRET_IMPORT,
metadata: {
secretImportId: string;
folderId: string;
importFromEnvironment: string;
importFromSecretPath: string;
importToEnvironment: string;
importToSecretPath: string;
}
type: EventType.DELETE_SECRET_IMPORT;
metadata: {
secretImportId: string;
folderId: string;
importFromEnvironment: string;
importFromSecretPath: string;
importToEnvironment: string;
importToSecretPath: string;
};
}
interface UpdateUserRole {
type: EventType.UPDATE_USER_WORKSPACE_ROLE,
metadata: {
userId: string;
email: string;
oldRole: string;
newRole: string;
}
type: EventType.UPDATE_USER_WORKSPACE_ROLE;
metadata: {
userId: string;
email: string;
oldRole: string;
newRole: string;
};
}
interface UpdateUserDeniedPermissions {
type: EventType.UPDATE_USER_WORKSPACE_DENIED_PERMISSIONS,
metadata: {
userId: string;
email: string;
deniedPermissions: {
environmentSlug: string;
ability: string;
}[]
}
type: EventType.UPDATE_USER_WORKSPACE_DENIED_PERMISSIONS;
metadata: {
userId: string;
email: string;
deniedPermissions: {
environmentSlug: string;
ability: string;
}[];
};
}
export type Event =
| GetSecretsEvent
| GetSecretEvent
| CreateSecretEvent
| UpdateSecretEvent
| DeleteSecretEvent
| GetWorkspaceKeyEvent
| AuthorizeIntegrationEvent
| UnauthorizeIntegrationEvent
| CreateIntegrationEvent
| DeleteIntegrationEvent
| AddTrustedIPEvent
| UpdateTrustedIPEvent
| DeleteTrustedIPEvent
| CreateServiceTokenEvent
| DeleteServiceTokenEvent
| CreateServiceTokenV3Event
| UpdateServiceTokenV3Event
| DeleteServiceTokenV3Event
| CreateEnvironmentEvent
| UpdateEnvironmentEvent
| DeleteEnvironmentEvent
| AddWorkspaceMemberEvent
| RemoveWorkspaceMemberEvent
| CreateFolderEvent
| UpdateFolderEvent
| DeleteFolderEvent
| CreateWebhookEvent
| UpdateWebhookStatusEvent
| DeleteWebhookEvent
| GetSecretImportsEvent
| CreateSecretImportEvent
| UpdateSecretImportEvent
| DeleteSecretImportEvent
| UpdateUserRole
| UpdateUserDeniedPermissions;
export type Event =
| GetSecretsEvent
| GetSecretEvent
| CreateSecretEvent
| UpdateSecretEvent
| DeleteSecretEvent
| GetWorkspaceKeyEvent
| AuthorizeIntegrationEvent
| UnauthorizeIntegrationEvent
| CreateIntegrationEvent
| DeleteIntegrationEvent
| AddTrustedIPEvent
| UpdateTrustedIPEvent
| DeleteTrustedIPEvent
| CreateServiceTokenEvent
| DeleteServiceTokenEvent
| CreateServiceTokenV3Event
| UpdateServiceTokenV3Event
| DeleteServiceTokenV3Event
| CreateEnvironmentEvent
| UpdateEnvironmentEvent
| DeleteEnvironmentEvent
| AddWorkspaceMemberEvent
| RemoveWorkspaceMemberEvent
| CreateFolderEvent
| UpdateFolderEvent
| DeleteFolderEvent
| CreateWebhookEvent
| UpdateWebhookStatusEvent
| DeleteWebhookEvent
| GetSecretImportsEvent
| CreateSecretImportEvent
| UpdateSecretImportEvent
| DeleteSecretImportEvent
| UpdateUserRole
| UpdateUserDeniedPermissions;
export type AuditLog = {
_id: string;
actor: Actor;
organization: string;
organization: string;
workspace: string;
ipAddress: string;
event: Event;
@@ -454,14 +446,13 @@ export type AuditLog = {
userAgentType: UserAgentType;
createdAt: string;
updatedAt: string;
}
};
export type AuditLogFilters = {
eventType?: EventType;
userAgentType?: UserAgentType;
actor?: string;
offset: number;
limit: number;
startDate?: Date;
endDate?: Date;
}
eventType?: EventType;
userAgentType?: UserAgentType;
actor?: string;
limit: number;
startDate?: Date;
endDate?: Date;
};

View File

@@ -0,0 +1,92 @@
import { useState } from "react";
import { useRouter } from "next/router";
import {
useSaveIntegrationAccessToken
} from "@app/hooks/api";
import { Button,Card, CardTitle, FormControl, Input } from "../../../components/v2";
export default function CloudflareWorkersIntegrationPage() {
const router = useRouter();
const { mutateAsync } = useSaveIntegrationAccessToken();
const [accessKey, setAccessKey] = useState("");
const [accessKeyErrorText, setAccessKeyErrorText] = useState("");
const [accountId, setAccountId] = useState("");
const [accountIdErrorText, setAccountIdErrorText] = useState("");
const [isLoading, setIsLoading] = useState(false);
const handleButtonClick = async () => {
try {
setAccessKeyErrorText("");
setAccountIdErrorText("");
if (accessKey.length === 0 || accountId.length === 0) {
if (accessKey.length === 0) setAccessKeyErrorText("API token cannot be blank!");
if (accountId.length === 0) setAccountIdErrorText("Account ID cannot be blank!");
return;
}
setIsLoading(true);
const integrationAuth = await mutateAsync({
workspaceId: localStorage.getItem("projectData.id"),
integration: "cloudflare-workers",
accessId: accountId,
accessToken: accessKey
});
setAccessKey("");
setAccountId("");
setIsLoading(false);
router.push(`/integrations/cloudflare-workers/create?integrationAuthId=${integrationAuth._id}`);
} catch (err) {
console.error(err);
}
}
return (
<div className="flex h-full w-full items-center justify-center">
<Card className="max-w-lg rounded-md border border-mineshaft-600 mb-12">
<CardTitle className="text-left px-6" subTitle="After adding your API-key, you will be prompted to set up an integration for a particular Infisical project and environment.">Cloudflare Workers Integration</CardTitle>
<FormControl
label="Cloudflare Workers API token"
errorText={accessKeyErrorText}
isError={accessKeyErrorText !== "" ?? false}
className="mx-6"
>
<Input
placeholder=""
value={accessKey}
onChange={(e) => setAccessKey(e.target.value)}
/>
</FormControl>
<FormControl
label="Cloudflare Workers Account ID"
errorText={accountIdErrorText}
isError={accountIdErrorText !== "" ?? false}
className="mx-6"
>
<Input
placeholder=""
value={accountId}
onChange={(e) => setAccountId(e.target.value)}
/>
</FormControl>
<Button
onClick={handleButtonClick}
color="mineshaft"
variant="outline_bg"
className="mb-6 mt-2 ml-auto mr-6 w-min"
isFullWidth={false}
isLoading={isLoading}
>
Connect to Cloudflare Workers
</Button>
</Card>
</div>
);
}
CloudflareWorkersIntegrationPage.requireAuth = true;

View File

@@ -0,0 +1,133 @@
import { useEffect,useState } from "react";
import { useRouter } from "next/router";
import queryString from "query-string";
import {
useCreateIntegration
, useGetWorkspaceById } from "@app/hooks/api";
import { Button, Card, CardTitle, FormControl, Select, SelectItem } from "../../../components/v2";
import { useGetIntegrationAuthApps, useGetIntegrationAuthById } from "../../../hooks/api/integrationAuth";
export default function CloudflareWorkersIntegrationPage() {
const router = useRouter();
const { mutateAsync } = useCreateIntegration();
const { integrationAuthId } = queryString.parse(router.asPath.split("?")[1]);
const { data: workspace } = useGetWorkspaceById(localStorage.getItem("projectData.id") ?? "");
const { data: integrationAuth } = useGetIntegrationAuthById((integrationAuthId as string) ?? "");
const { data: integrationAuthApps } = useGetIntegrationAuthApps({
integrationAuthId: (integrationAuthId as string) ?? ""
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState("");
const [targetApp, setTargetApp] = useState("");
const [targetAppId, setTargetAppId] = useState("");
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (workspace) {
setSelectedSourceEnvironment(workspace.environments[0].slug);
}
}, [workspace]);
useEffect(() => {
if (integrationAuthApps) {
if (integrationAuthApps.length > 0) {
setTargetApp(integrationAuthApps[0].name);
setTargetAppId(String(integrationAuthApps[0].appId));
} else {
setTargetApp("none");
}
}
}, [integrationAuthApps]);
const handleButtonClick = async () => {
try {
if (!integrationAuth?._id) return;
setIsLoading(true);
await mutateAsync({
integrationAuthId: integrationAuth?._id,
isActive: true,
app: targetApp,
appId: targetAppId,
sourceEnvironment: selectedSourceEnvironment,
secretPath: "/",
});
setIsLoading(false);
router.push(`/integrations/${localStorage.getItem("projectData.id")}`);
} catch(err) {
console.error(err);
}
}
return integrationAuth &&
workspace &&
selectedSourceEnvironment &&
integrationAuthApps &&
targetApp ? (
<div className="flex h-full w-full items-center justify-center bg-gradient-to-tr from-mineshaft-900 to-bunker-900">
<Card className="max-w-lg rounded-md p-0 border border-mineshaft-600">
<CardTitle className="text-left px-6" subTitle="Choose which environment in Infisical you want to sync with your Cloudflare Workers project.">Cloudflare Workers Integration</CardTitle>
<FormControl label="Infisical Project Environment" className="mt-2 px-6">
<Select
value={selectedSourceEnvironment}
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
{workspace?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
>
{sourceEnvironment.name}
</SelectItem>
))}
</Select>
</FormControl>
<FormControl label="Cloudflare Workers Project" className="mt-4 px-6">
<Select
value={targetApp}
onValueChange={(val) => setTargetApp(val)}
className="w-full border border-mineshaft-500"
isDisabled={integrationAuthApps.length === 0}
>
{integrationAuthApps.length > 0 ? (
integrationAuthApps.map((integrationAuthApp) => (
<SelectItem
value={integrationAuthApp.name}
key={`target-app-${integrationAuthApp.name}`}
>
{integrationAuthApp.name}
</SelectItem>
))
) : (
<SelectItem value="none" key="target-app-none">
No apps found
</SelectItem>
)}
</Select>
</FormControl>
<Button
onClick={handleButtonClick}
color="mineshaft"
variant="outline_bg"
className="mt-2 mb-6 ml-auto mr-6"
isFullWidth={false}
isLoading={isLoading}
>
Create Integration
</Button>
</Card>
</div>
) : (
<div />
);
}
CloudflareWorkersIntegrationPage.requireAuth = true;

View File

@@ -101,6 +101,9 @@ export const redirectForProviderAuth = (integrationOption: TCloudIntegration) =>
case "cloudflare-pages":
link = `${window.location.origin}/integrations/cloudflare-pages/authorize`;
break;
case "cloudflare-workers":
link = `${window.location.origin}/integrations/cloudflare-workers/authorize`;
break;
case "bitbucket":
link = `https://bitbucket.org/site/oauth2/authorize?client_id=${integrationOption.clientId}&response_type=code&redirect_uri=${window.location.origin}/integrations/bitbucket/oauth2/callback&state=${state}`;
break;

View File

@@ -8,7 +8,7 @@ export const AuditLogsPage = withProjectPermission(
return (
<div className="flex justify-center bg-bunker-800 text-white w-full h-full">
<div className="max-w-7xl px-6 w-full">
<div className="my-6">
<div className="py-6 sticky top-0 z-10 bg-bunker-800">
<p className="text-3xl font-semibold text-gray-200">Audit Logs</p>
<div />
</div>

View File

@@ -3,13 +3,7 @@ import { Control, Controller, UseFormReset } from "react-hook-form";
import { faFilterCircleXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
Button,
DatePicker,
FormControl,
Select,
SelectItem
} from "@app/components/v2";
import { Button, DatePicker, FormControl, Select, SelectItem } from "@app/components/v2";
import { useWorkspace } from "@app/context";
import { useGetAuditLogActorFilterOpts } from "@app/hooks/api";
import { eventToNameMap, userAgentTTypeoNameMap } from "@app/hooks/api/auditLogs/constants";
@@ -19,201 +13,207 @@ import { Actor } from "@app/hooks/api/auditLogs/types";
import { AuditLogFilterFormData } from "./types";
const eventTypes = Object.entries(eventToNameMap).map(([value, label]) => ({ label, value }));
const userAgentTypes = Object.entries(userAgentTTypeoNameMap).map(([value, label]) => ({ label, value }));
const userAgentTypes = Object.entries(userAgentTTypeoNameMap).map(([value, label]) => ({
label,
value
}));
type Props = {
control: Control<AuditLogFilterFormData>;
reset: UseFormReset<AuditLogFilterFormData>;
}
control: Control<AuditLogFilterFormData>;
reset: UseFormReset<AuditLogFilterFormData>;
};
export const LogsFilter = ({
control,
reset
}: Props) => {
const [isStartDatePickerOpen, setIsStartDatePickerOpen] = useState(false);
const [isEndDatePickerOpen, setIsEndDatePickerOpen] = useState(false);
export const LogsFilter = ({ control, reset }: Props) => {
const [isStartDatePickerOpen, setIsStartDatePickerOpen] = useState(false);
const [isEndDatePickerOpen, setIsEndDatePickerOpen] = useState(false);
const { currentWorkspace } = useWorkspace();
const { data, isLoading } = useGetAuditLogActorFilterOpts(currentWorkspace?._id ?? "");
const renderActorSelectItem = (actor: Actor) => {
switch (actor.type) {
case ActorType.USER:
return (
<SelectItem value={`${actor.type}-${actor.metadata.userId}`} key={`user-actor-filter-${actor.metadata.userId}`}>
{actor.metadata.email}
</SelectItem>
);
case ActorType.SERVICE:
return (
<SelectItem value={`${actor.type}-${actor.metadata.serviceId}`} key={`service-actor-filter-${actor.metadata.serviceId}`}>
{actor.metadata.name}
</SelectItem>
);
case ActorType.SERVICE_V3:
return (
<SelectItem value={`${actor.type}-${actor.metadata.serviceId}`} key={`service-actor-v3-filter-${actor.metadata.serviceId}`}>
{actor.metadata.name}
</SelectItem>
);
default:
return (
<SelectItem value="actor-none" key="actor-none">
N/A
</SelectItem>
);
}
const { currentWorkspace } = useWorkspace();
const { data, isLoading } = useGetAuditLogActorFilterOpts(currentWorkspace?._id ?? "");
const renderActorSelectItem = (actor: Actor) => {
switch (actor.type) {
case ActorType.USER:
return (
<SelectItem
value={`${actor.type}-${actor.metadata.userId}`}
key={`user-actor-filter-${actor.metadata.userId}`}
>
{actor.metadata.email}
</SelectItem>
);
case ActorType.SERVICE:
return (
<SelectItem
value={`${actor.type}-${actor.metadata.serviceId}`}
key={`service-actor-filter-${actor.metadata.serviceId}`}
>
{actor.metadata.name}
</SelectItem>
);
case ActorType.SERVICE_V3:
return (
<SelectItem
value={`${actor.type}-${actor.metadata.serviceId}`}
key={`service-actor-v3-filter-${actor.metadata.serviceId}`}
>
{actor.metadata.name}
</SelectItem>
);
default:
return (
<SelectItem value="actor-none" key="actor-none">
N/A
</SelectItem>
);
}
};
return (
<div className="flex justify-between items-center">
<div className="flex items-center">
<Controller
control={control}
name="eventType"
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
label="Event"
errorText={error?.message}
isError={Boolean(error)}
className="w-40 mr-4"
>
<Select
{...(field.value ? { value: field.value } : { placeholder: "Select" })}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full bg-mineshaft-700 border border-mineshaft-500 text-mineshaft-100"
>
{eventTypes.map(({ label, value }) => (
<SelectItem value={String(value || "")} key={label}>
{label}
</SelectItem>
))}
</Select>
</FormControl>
)}
/>
{!isLoading && data && data.length > 0 && (
<Controller
control={control}
name="actor"
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
label="Actor"
errorText={error?.message}
isError={Boolean(error)}
className="w-40 mr-4"
>
<Select
{...(field.value ? { value: field.value } : { placeholder: "Select" })}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full bg-mineshaft-700 border border-mineshaft-500 text-mineshaft-100"
>
{data.map((actor) => renderActorSelectItem(actor))}
</Select>
</FormControl>
)}
/>
)}
<Controller
control={control}
name="userAgentType"
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
label="Source"
errorText={error?.message}
isError={Boolean(error)}
className="w-40 mr-4"
>
<Select
{...(field.value ? { value: field.value } : { placeholder: "Select" })}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full bg-mineshaft-700 border border-mineshaft-500 text-mineshaft-100"
>
{userAgentTypes.map(({ label, value }) => (
<SelectItem value={String(value || "")} key={label}>
{label}
</SelectItem>
))}
</Select>
</FormControl>
)}
/>
<Controller
name="startDate"
control={control}
render={({ field: { onChange, ...field }, fieldState: { error } }) => {
return (
<FormControl
label="Start date"
errorText={error?.message}
isError={Boolean(error)}
className="mr-4"
>
<DatePicker
value={field.value || undefined}
onChange={date => {
onChange(date);
setIsStartDatePickerOpen(false);
}}
popUpProps={{
open: isStartDatePickerOpen,
onOpenChange: setIsStartDatePickerOpen
}}
popUpContentProps={{}}
/>
</FormControl>
);
}}
/>
<Controller
name="endDate"
control={control}
render={({ field: { onChange, ...field }, fieldState: { error } }) => {
return (
<FormControl
label="End date"
errorText={error?.message}
isError={Boolean(error)}
>
<DatePicker
value={field.value || undefined}
onChange={date => {
onChange(date);
setIsEndDatePickerOpen(false);
}}
popUpProps={{
open: isEndDatePickerOpen,
onOpenChange: setIsEndDatePickerOpen
}}
popUpContentProps={{}}
/>
</FormControl>
);
}}
/>
</div>
<div>
<Button
isLoading={false}
colorSchema="primary"
variant="outline_bg"
type="submit"
leftIcon={<FontAwesomeIcon icon={faFilterCircleXmark} className="mr-2" />}
onClick={() => reset({
eventType: undefined,
actor: undefined,
userAgentType: undefined,
startDate: undefined,
endDate: undefined
})}
return (
<div className="flex justify-between items-center sticky top-20 z-10 bg-bunker-800">
<div className="flex items-center">
<Controller
control={control}
name="eventType"
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
label="Event"
errorText={error?.message}
isError={Boolean(error)}
className="w-40 mr-4"
>
<Select
{...(field.value ? { value: field.value } : { placeholder: "Select" })}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full bg-mineshaft-700 border border-mineshaft-500 text-mineshaft-100"
>
{eventTypes.map(({ label, value }) => (
<SelectItem value={String(value || "")} key={label}>
{label}
</SelectItem>
))}
</Select>
</FormControl>
)}
/>
{!isLoading && data && data.length > 0 && (
<Controller
control={control}
name="actor"
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
label="Actor"
errorText={error?.message}
isError={Boolean(error)}
className="w-40 mr-4"
>
<Select
{...(field.value ? { value: field.value } : { placeholder: "Select" })}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full bg-mineshaft-700 border border-mineshaft-500 text-mineshaft-100"
>
Clear filters
</Button>
</div>
</div>
);
}
{data.map((actor) => renderActorSelectItem(actor))}
</Select>
</FormControl>
)}
/>
)}
<Controller
control={control}
name="userAgentType"
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
label="Source"
errorText={error?.message}
isError={Boolean(error)}
className="w-40 mr-4"
>
<Select
{...(field.value ? { value: field.value } : { placeholder: "Select" })}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full bg-mineshaft-700 border border-mineshaft-500 text-mineshaft-100"
>
{userAgentTypes.map(({ label, value }) => (
<SelectItem value={String(value || "")} key={label}>
{label}
</SelectItem>
))}
</Select>
</FormControl>
)}
/>
<Controller
name="startDate"
control={control}
render={({ field: { onChange, ...field }, fieldState: { error } }) => {
return (
<FormControl
label="Start date"
errorText={error?.message}
isError={Boolean(error)}
className="mr-4"
>
<DatePicker
value={field.value || undefined}
onChange={(date) => {
onChange(date);
setIsStartDatePickerOpen(false);
}}
popUpProps={{
open: isStartDatePickerOpen,
onOpenChange: setIsStartDatePickerOpen
}}
popUpContentProps={{}}
/>
</FormControl>
);
}}
/>
<Controller
name="endDate"
control={control}
render={({ field: { onChange, ...field }, fieldState: { error } }) => {
return (
<FormControl label="End date" errorText={error?.message} isError={Boolean(error)}>
<DatePicker
value={field.value || undefined}
onChange={(date) => {
onChange(date);
setIsEndDatePickerOpen(false);
}}
popUpProps={{
open: isEndDatePickerOpen,
onOpenChange: setIsEndDatePickerOpen
}}
popUpContentProps={{}}
/>
</FormControl>
);
}}
/>
</div>
<div>
<Button
isLoading={false}
colorSchema="primary"
variant="outline_bg"
type="submit"
leftIcon={<FontAwesomeIcon icon={faFilterCircleXmark} className="mr-2" />}
onClick={() =>
reset({
eventType: undefined,
actor: undefined,
userAgentType: undefined,
startDate: undefined,
endDate: undefined
})
}
>
Clear filters
</Button>
</div>
</div>
);
};

View File

@@ -13,78 +13,54 @@ import { LogsTable } from "./LogsTable";
import { AuditLogFilterFormData, auditLogFilterFormSchema } from "./types";
export const LogsSection = () => {
const { subscription } = useSubscription();
const router = useRouter();
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
"upgradePlan"
] as const);
const {
control,
reset,
watch,
setValue,
} = useForm<AuditLogFilterFormData>({
resolver: yupResolver(auditLogFilterFormSchema),
defaultValues: {
page: 1,
perPage: 10
}
});
useEffect(() => {
if (subscription && !subscription.auditLogs) {
handlePopUpOpen("upgradePlan");
}
}, [subscription]);
const { subscription } = useSubscription();
const router = useRouter();
const eventType = watch("eventType") as EventType | undefined;
const userAgentType = watch("userAgentType") as UserAgentType | undefined;
const actor = watch("actor");
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan"] as const);
const startDate = watch("startDate");
const endDate = watch("endDate");
const { control, reset, watch } = useForm<AuditLogFilterFormData>({
resolver: yupResolver(auditLogFilterFormSchema),
defaultValues: {
page: 1,
perPage: 10
}
});
const page = watch("page") as number;
const perPage = watch("perPage") as number;
return (
<div
// className="p-4 bg-mineshaft-900 mb-6 rounded-lg border border-mineshaft-600"
>
{/* <div className="flex items-center mb-8">
<h2 className="text-xl font-semibold flex-1 text-white">
Audit Logs
</h2>
</div> */}
<LogsFilter
control={control}
reset={reset}
/>
<LogsTable
eventType={eventType}
userAgentType={userAgentType}
actor={actor}
startDate={startDate}
endDate={endDate}
page={page}
perPage={perPage}
setValue={setValue}
/>
<UpgradePlanModal
isOpen={popUp.upgradePlan.isOpen}
onOpenChange={(isOpen) => {
if (!isOpen) {
router.back();
return;
}
useEffect(() => {
if (subscription && !subscription.auditLogs) {
handlePopUpOpen("upgradePlan");
}
}, [subscription]);
handlePopUpToggle("upgradePlan", isOpen)
}}
text="You can use audit logs if you switch to a paid Infisical plan."
/>
</div>
);
}
const eventType = watch("eventType") as EventType | undefined;
const userAgentType = watch("userAgentType") as UserAgentType | undefined;
const actor = watch("actor");
const startDate = watch("startDate");
const endDate = watch("endDate");
return (
<div>
<LogsFilter control={control} reset={reset} />
<LogsTable
eventType={eventType}
userAgentType={userAgentType}
actor={actor}
startDate={startDate}
endDate={endDate}
/>
<UpgradePlanModal
isOpen={popUp.upgradePlan.isOpen}
onOpenChange={(isOpen) => {
if (!isOpen) {
router.back();
return;
}
handlePopUpToggle("upgradePlan", isOpen);
}}
text="You can use audit logs if you switch to a paid Infisical plan."
/>
</div>
);
};

View File

@@ -1,96 +1,95 @@
import { Fragment } from "react";
import { faFile } from "@fortawesome/free-solid-svg-icons";
import {
EmptyState,
Pagination,
Table,
TableContainer,
TableSkeleton,
TBody,
Td,
Th,
THead,
Tr} from "@app/components/v2";
Button,
EmptyState,
Table,
TableContainer,
TableSkeleton,
TBody,
Td,
Th,
THead,
Tr
} from "@app/components/v2";
import { useWorkspace } from "@app/context";
import { useGetAuditLogs } from "@app/hooks/api";
import { EventType, UserAgentType } from "@app/hooks/api/auditLogs/enums";
import { LogsTableRow } from "./LogsTableRow";
import { SetValueType } from "./types";
type Props = {
eventType?: EventType;
userAgentType?: UserAgentType;
actor?: string;
startDate?: Date;
endDate?: Date;
page: number;
perPage: number;
setValue: SetValueType;
}
eventType?: EventType;
userAgentType?: UserAgentType;
actor?: string;
startDate?: Date;
endDate?: Date;
};
export const LogsTable = ({
eventType,
userAgentType,
actor,
startDate,
endDate,
page,
perPage,
setValue
}: Props) => {
const { currentWorkspace } = useWorkspace();
const { data, isLoading } = useGetAuditLogs(currentWorkspace?._id ?? "", {
eventType,
userAgentType,
actor,
startDate,
endDate,
offset: (page - 1) * perPage,
limit: perPage
});
return (
<TableContainer>
<Table>
<THead>
<Tr>
<Th>Timestamp</Th>
<Th>Event</Th>
<Th>Actor</Th>
<Th>Source</Th>
<Th>Metadata</Th>
</Tr>
</THead>
<TBody>
{!isLoading && data?.auditLogs && data?.auditLogs.map((auditLog) => (
<LogsTableRow
auditLog={auditLog}
key={`audit-log-${auditLog._id}`}
/>
))}
{isLoading && <TableSkeleton innerKey="logs-table" columns={5} key="logs" />}
{!isLoading && data?.auditLogs && data?.auditLogs.length === 0 && (
<Tr>
<Td colSpan={5}>
<EmptyState
title="No audit logs on file"
icon={faFile}
/>
</Td>
</Tr>
)}
</TBody>
</Table>
{!isLoading && data?.totalCount !== undefined && (
<Pagination
count={data?.totalCount}
page={page}
perPage={perPage}
onChangePage={(newPage) => setValue("page", newPage)}
onChangePerPage={(newPerPage) => setValue("perPage", newPerPage)}
/>
const AUDIT_LOG_LIMIT = 15;
export const LogsTable = ({ eventType, userAgentType, actor, startDate, endDate }: Props) => {
const { currentWorkspace } = useWorkspace();
const { data, isLoading, isFetchingNextPage, hasNextPage, fetchNextPage } = useGetAuditLogs(
currentWorkspace?._id ?? "",
{
eventType,
userAgentType,
actor,
startDate,
endDate,
limit: AUDIT_LOG_LIMIT
}
);
const isEmpty = !isLoading && !data?.pages?.[0].length;
return (
<div>
<TableContainer>
<Table>
<THead>
<Tr>
<Th>Timestamp</Th>
<Th>Event</Th>
<Th>Actor</Th>
<Th>Source</Th>
<Th>Metadata</Th>
</Tr>
</THead>
<TBody>
{!isLoading &&
data?.pages?.map((group, i) => (
<Fragment key={`auditlog-item-${i + 1}`}>
{group.map((auditLog) => (
<LogsTableRow auditLog={auditLog} key={`audit-log-${auditLog._id}`} />
))}
</Fragment>
))}
{isLoading && <TableSkeleton innerKey="logs-table" columns={5} key="logs" />}
{isEmpty && (
<Tr>
<Td colSpan={5}>
<EmptyState title="No audit logs on file" icon={faFile} />
</Td>
</Tr>
)}
</TableContainer>
);
}
</TBody>
</Table>
</TableContainer>
{!isEmpty && (
<Button
className="mt-4 mb-20 py-3 px-4 text-sm"
isFullWidth
variant="star"
isLoading={isFetchingNextPage}
isDisabled={isFetchingNextPage || !hasNextPage}
onClick={() => fetchNextPage()}
>
{hasNextPage ? "Load More" : "End of logs"}
</Button>
)}
</div>
);
};