Merge remote-tracking branch 'origin/main' into misc/add-checks-for-helm-verification

This commit is contained in:
Sheen Capadngan
2025-06-05 21:24:46 +08:00
18 changed files with 486 additions and 113 deletions

View File

@@ -11,7 +11,7 @@ export const globalRateLimiterCfg = (): RateLimitPluginOptions => {
return {
errorResponseBuilder: (_, context) => {
throw new RateLimitError({
message: `Rate limit exceeded. Please try again in ${context.after}`
message: `Rate limit exceeded. Please try again in ${Math.ceil(context.ttl / 1000)} seconds`
});
},
timeWindow: 60 * 1000,
@@ -113,3 +113,12 @@ export const requestAccessLimit: RateLimitOptions = {
max: 10,
keyGenerator: (req) => req.realIp
};
export const smtpRateLimit = ({
keyGenerator = (req) => req.realIp
}: Pick<RateLimitOptions, "keyGenerator"> = {}): RateLimitOptions => ({
timeWindow: 40 * 1000,
hook: "preValidation",
max: 2,
keyGenerator
});

View File

@@ -1,7 +1,7 @@
import { z } from "zod";
import { OrgMembershipRole, ProjectMembershipRole, UsersSchema } from "@app/db/schemas";
import { inviteUserRateLimit } from "@app/server/config/rateLimiter";
import { inviteUserRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
@@ -11,7 +11,7 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {
server.route({
url: "/signup",
config: {
rateLimit: inviteUserRateLimit
rateLimit: smtpRateLimit()
},
method: "POST",
schema: {
@@ -81,7 +81,10 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {
server.route({
url: "/signup-resend",
config: {
rateLimit: inviteUserRateLimit
rateLimit: smtpRateLimit({
keyGenerator: (req) =>
(req.body as { membershipId?: string })?.membershipId?.trim().substring(0, 100) ?? req.realIp
})
},
method: "POST",
schema: {

View File

@@ -2,9 +2,9 @@ import { z } from "zod";
import { ProjectMembershipsSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { readLimit, smtpRateLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { SanitizedProjectSchema } from "../sanitizedSchemas";
@@ -47,7 +47,9 @@ export const registerOrgAdminRouter = async (server: FastifyZodProvider) => {
method: "POST",
url: "/projects/:projectId/grant-admin-access",
config: {
rateLimit: writeLimit
rateLimit: smtpRateLimit({
keyGenerator: (req) => (req.auth.actor === ActorType.USER ? req.auth.userId : req.realIp)
})
},
schema: {
params: z.object({

View File

@@ -2,10 +2,10 @@ import { z } from "zod";
import { BackupPrivateKeySchema, UsersSchema } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { authRateLimit } from "@app/server/config/rateLimiter";
import { authRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { validateSignUpAuthorization } from "@app/services/auth/auth-fns";
import { AuthMode } from "@app/services/auth/auth-type";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { UserEncryption } from "@app/services/user/user-types";
export const registerPasswordRouter = async (server: FastifyZodProvider) => {
@@ -80,7 +80,9 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
method: "POST",
url: "/email/password-reset",
config: {
rateLimit: authRateLimit
rateLimit: smtpRateLimit({
keyGenerator: (req) => (req.body as { email?: string })?.email?.trim().substring(0, 100) ?? req.realIp
})
},
schema: {
body: z.object({
@@ -224,7 +226,9 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
method: "POST",
url: "/email/password-setup",
config: {
rateLimit: authRateLimit
rateLimit: smtpRateLimit({
keyGenerator: (req) => (req.auth.actor === ActorType.USER ? req.auth.userId : req.realIp)
})
},
schema: {
response: {
@@ -233,6 +237,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
await server.services.password.sendPasswordSetupEmail(req.permission);
@@ -267,6 +272,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req, res) => {
await server.services.password.setupPassword(req.body, req.permission);

View File

@@ -2,7 +2,7 @@ import { z } from "zod";
import { AuthTokenSessionsSchema, UserEncryptionKeysSchema, UsersSchema } from "@app/db/schemas";
import { ApiKeysSchema } from "@app/db/schemas/api-keys";
import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { authRateLimit, readLimit, smtpRateLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMethod, AuthMode, MfaMethod } from "@app/services/auth/auth-type";
import { sanitizedOrganizationSchema } from "@app/services/org/org-schema";
@@ -12,7 +12,9 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
method: "POST",
url: "/me/emails/code",
config: {
rateLimit: authRateLimit
rateLimit: smtpRateLimit({
keyGenerator: (req) => (req.body as { username?: string })?.username?.trim().substring(0, 100) ?? req.realIp
})
},
schema: {
body: z.object({

View File

@@ -3,7 +3,7 @@ import { z } from "zod";
import { UsersSchema } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { ForbiddenRequestError } from "@app/lib/errors";
import { authRateLimit } from "@app/server/config/rateLimiter";
import { authRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";
import { GenericResourceNameSchema } from "@app/server/lib/schemas";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -13,7 +13,9 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
url: "/email/signup",
method: "POST",
config: {
rateLimit: authRateLimit
rateLimit: smtpRateLimit({
keyGenerator: (req) => (req.body as { email?: string })?.email?.trim().substring(0, 100) ?? req.realIp
})
},
schema: {
body: z.object({

View File

@@ -0,0 +1,177 @@
---
title: SPIFFE/SPIRE
description: "Learn how to authenticate SPIRE workloads with Infisical using OpenID Connect (OIDC)."
---
**OIDC Auth** is a platform-agnostic JWT-based authentication method that can be used to authenticate from any platform or environment using an identity provider with OpenID Connect.
## Diagram
The following sequence diagram illustrates the OIDC Auth workflow for authenticating SPIRE workloads with Infisical.
```mermaid
sequenceDiagram
participant Client as SPIRE Workload
participant Agent as SPIRE Agent
participant Server as SPIRE Server
participant Infis as Infisical
Client->>Agent: Step 1: Request JWT-SVID
Agent->>Server: Validate workload and fetch signing key
Server-->>Agent: Return signing material
Agent-->>Client: Return JWT-SVID with verifiable claims
Note over Client,Infis: Step 2: Login Operation
Client->>Infis: Send JWT-SVID to /api/v1/auth/oidc-auth/login
Note over Infis,Server: Step 3: Query verification
Infis->>Server: Request JWT public key using OIDC Discovery
Server-->>Infis: Return public key
Note over Infis: Step 4: JWT validation
Infis->>Client: Return short-lived access token
Note over Client,Infis: Step 5: Access Infisical API with Token
Client->>Infis: Make authenticated requests using the short-lived access token
```
## Concept
At a high-level, Infisical authenticates a SPIRE workload by verifying the JWT-SVID and checking that it meets specific requirements (e.g. it is issued by a trusted SPIRE server) at the `/api/v1/auth/oidc-auth/login` endpoint. If successful,
then Infisical returns a short-lived access token that can be used to make authenticated requests to the Infisical API.
To be more specific:
1. The SPIRE workload requests a JWT-SVID from the local SPIRE Agent.
2. The SPIRE Agent validates the workload's identity and requests signing material from the SPIRE Server.
3. The SPIRE Agent returns a JWT-SVID containing the workload's SPIFFE ID and other claims.
4. The JWT-SVID is sent to Infisical at the `/api/v1/auth/oidc-auth/login` endpoint.
5. Infisical fetches the public key that was used to sign the JWT-SVID from the SPIRE Server using OIDC Discovery.
6. Infisical validates the JWT-SVID using the public key provided by the SPIRE Server and checks that the subject, audience, and claims of the token matches with the set criteria.
7. If all is well, Infisical returns a short-lived access token that the workload can use to make authenticated requests to the Infisical API.
<Note>Infisical needs network-level access to the SPIRE Server's OIDC Discovery endpoint.</Note>
## Prerequisites
Before following this guide, ensure you have:
- A running SPIRE deployment with both SPIRE Server and SPIRE Agent configured
- OIDC Discovery Provider deployed alongside your SPIRE Server
- Workload registration entries created in SPIRE for the workloads that need to access Infisical
- Network connectivity between Infisical and your OIDC Discovery Provider endpoint
For detailed SPIRE setup instructions, refer to the [SPIRE documentation](https://spiffe.io/docs/latest/spire-about/).
## OIDC Discovery Provider Setup
To enable JWT-SVID verification with Infisical, you need to deploy the OIDC Discovery Provider alongside your SPIRE Server. The OIDC Discovery Provider runs as a separate service that exposes the necessary OIDC endpoints.
In Kubernetes deployments, this is typically done by adding an `oidc-discovery-provider` container to your SPIRE Server StatefulSet:
```yaml
- name: spire-oidc
image: ghcr.io/spiffe/oidc-discovery-provider:1.12.2
args:
- -config
- /run/spire/oidc/config/oidc-discovery-provider.conf
ports:
- containerPort: 443
name: spire-oidc-port
```
The OIDC Discovery Provider will expose the OIDC Discovery endpoint at `https://<spire-oidc-host>/.well-known/openid_configuration`, which Infisical will use to fetch the public keys for JWT-SVID verification.
<Note>For detailed setup instructions, refer to the [SPIRE OIDC Discovery Provider documentation](https://github.com/spiffe/spire/tree/main/support/oidc-discovery-provider).</Note>
## Guide
In the following steps, we explore how to create and use identities to access the Infisical API using the OIDC Auth authentication method with SPIFFE/SPIRE.
<Steps>
<Step title="Creating an identity">
To create an identity, head to your Organization Settings > Access Control > Identities and press **Create identity**.
![identities organization](/images/platform/identities/identities-org.png)
When creating an identity, you specify an organization level [role](/documentation/platform/role-based-access-controls) for it to assume; you can configure roles in Organization Settings > Access Control > Organization Roles.
![identities organization create](/images/platform/identities/identities-org-create.png)
Now input a few details for your new identity. Here's some guidance for each field:
- Name (required): A friendly name for the identity.
- Role (required): A role from the **Organization Roles** tab for the identity to assume. The organization role assigned will determine what organization level resources this identity can have access to.
Once you've created an identity, you'll be redirected to a page where you can manage the identity.
![identities page](/images/platform/identities/identities-page.png)
Since the identity has been configured with Universal Auth by default, you should re-configure it to use OIDC Auth instead. To do this, press to edit the **Authentication** section,
remove the existing Universal Auth configuration, and add a new OIDC Auth configuration onto the identity.
![identities page remove default auth](/images/platform/identities/identities-page-remove-default-auth.png)
![identities create oidc auth method](/images/platform/identities/identities-org-create-oidc-auth-method.png)
<Warning>Restrict access by configuring the Subject, Audiences, and Claims fields</Warning>
Here's some more guidance on each field:
- OIDC Discovery URL: The URL used to retrieve the OpenID Connect configuration from the SPIRE Server. This will be used to fetch the public key needed for verifying the provided JWT-SVID. This should be set to your SPIRE Server's OIDC Discovery endpoint, typically `https://<spire-server-host>:<port>/.well-known/openid_configuration`
- Issuer: The unique identifier of the SPIRE Server issuing the JWT-SVID. This value is used to verify the iss (issuer) claim in the JWT-SVID to ensure the token is issued by a trusted SPIRE Server. This should match your SPIRE Server's configured issuer, typically `https://<spire-server-host>:<port>`
- CA Certificate: The PEM-encoded CA certificate for establishing secure communication with the SPIRE Server endpoints. This should contain the CA certificate that signed your SPIRE Server's TLS certificate.
- Subject: The expected SPIFFE ID that is the subject of the JWT-SVID. The format of the sub field for SPIRE JWT-SVIDs follows the SPIFFE ID format: `spiffe://<trust-domain>/<workload-path>`. For example: `spiffe://example.org/workload/api-server`
- Audiences: A list of intended recipients for the JWT-SVID. This value is checked against the aud (audience) claim in the token. When workloads request JWT-SVIDs from SPIRE, they specify an audience (e.g., `infisical` or your service name). Configure this to match what your workloads use.
- Claims: Additional information or attributes that should be present in the JWT-SVID for it to be valid. Standard SPIRE JWT-SVID claims include `sub` (SPIFFE ID), `aud` (audience), `exp` (expiration), and `iat` (issued at). You can also configure custom claims if your SPIRE Server includes additional metadata.
- Access Token TTL (default is `2592000` equivalent to 30 days): The lifetime for an access token in seconds. This value will be referenced at renewal time.
- Access Token Max TTL (default is `2592000` equivalent to 30 days): The maximum lifetime for an access token in seconds. This value will be referenced at renewal time.
- Access Token Max Number of Uses (default is `0`): The maximum number of times that an access token can be used; a value of `0` implies infinite number of uses.
- Access Token Trusted IPs: The IPs or CIDR ranges that access tokens can be used from. By default, each token is given the `0.0.0.0/0`, allowing usage from any network address.
<Tip>SPIRE JWT-SVIDs contain standard claims like `sub` (SPIFFE ID), `aud` (audience), `exp`, and `iat`. The audience is typically specified when requesting the JWT-SVID (e.g., `spire-agent api fetch jwt -audience infisical`).</Tip>
<Info>The `subject`, `audiences`, and `claims` fields support glob pattern matching; however, we highly recommend using hardcoded SPIFFE IDs whenever possible for better security.</Info>
</Step>
<Step title="Adding an identity to a project">
To enable the identity to access project-level resources such as secrets within a specific project, you should add it to that project.
To do this, head over to the project you want to add the identity to and go to Project Settings > Access Control > Machine Identities and press **Add identity**.
Next, select the identity you want to add to the project and the project level role you want to allow it to assume. The project role assigned will determine what project level resources this identity can have access to.
![identities project](/images/platform/identities/identities-project.png)
![identities project create](/images/platform/identities/identities-project-create.png)
</Step>
<Step title="Using JWT-SVID to authenticate with Infisical">
Here's an example of how a workload can use its JWT-SVID to authenticate with Infisical and retrieve secrets:
```bash
#!/bin/bash
# Obtain JWT-SVID from SPIRE Agent
JWT_SVID=$(spire-agent api fetch jwt -audience infisical -socketPath /run/spire/sockets/agent.sock | grep -A1 "token(" | tail -1)
# Authenticate with Infisical using the JWT-SVID
ACCESS_TOKEN=$(curl -s -X POST \
-H "Content-Type: application/json" \
-d "{\"identityId\":\"<your-identity-id>\",\"jwt\":\"$JWT_SVID\"}" \
https://app.infisical.com/api/v1/auth/oidc-auth/login | jq -r '.accessToken')
# Use the access token to retrieve secrets
curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://app.infisical.com/api/v3/secrets/raw?workspaceSlug=<project-slug>&environment=<env-slug>&secretPath=/"
```
<Note>
Each identity access token has a time-to-live (TTL) which you can infer from the response of the login operation;
the default TTL is `7200` seconds which can be adjusted.
If an identity access token expires, it can no longer authenticate with the Infisical API. In this case,
a new access token should be obtained by performing another login operation.
</Note>
<Tip>
JWT-SVIDs from SPIRE have their own expiration time (typically short-lived). Ensure your application handles both JWT-SVID renewal from SPIRE and access token renewal from Infisical appropriately.
</Tip>
</Step>
</Steps>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 493 KiB

After

Width:  |  Height:  |  Size: 454 KiB

View File

@@ -343,7 +343,8 @@
"documentation/platform/identities/oidc-auth/github",
"documentation/platform/identities/oidc-auth/circleci",
"documentation/platform/identities/oidc-auth/gitlab",
"documentation/platform/identities/oidc-auth/terraform-cloud"
"documentation/platform/identities/oidc-auth/terraform-cloud",
"documentation/platform/identities/oidc-auth/spire"
]
},

View File

@@ -78,11 +78,14 @@ export default function CodeInputStep({
const resendVerificationEmail = async () => {
setIsResendingVerificationEmail(true);
setIsLoading(true);
await mutateAsync({ email });
setTimeout(() => {
setIsLoading(false);
setIsResendingVerificationEmail(false);
}, 2000);
try {
await mutateAsync({ email });
} finally {
setTimeout(() => {
setIsLoading(false);
setIsResendingVerificationEmail(false);
}, 1000);
}
};
return (

View File

@@ -8,6 +8,11 @@ export const formatReservedPaths = (secretPath: string) => {
return secretPath;
};
export const parsePathFromReplicatedPath = (secretPath: string) => {
const i = secretPath.indexOf(ReservedFolders.SecretReplication);
return secretPath.slice(0, i);
};
export const camelCaseToSpaces = (input: string) => {
return input.replace(/([a-z])([A-Z])/g, "$1 $2");
};

View File

@@ -22,8 +22,12 @@ export const VerifyEmailPage = () => {
*/
const sendVerificationEmail = async () => {
if (email) {
await mutateAsync({ email });
setStep(2);
try {
await mutateAsync({ email });
setStep(2);
} catch {
setLoading(false);
}
}
};

View File

@@ -159,6 +159,7 @@ export const AddOrgMemberModal = ({
text: "Failed to invite user to org",
type: "error"
});
return;
}
if (serverDetails?.emailConfigured) {

View File

@@ -1,8 +1,11 @@
import { useCallback, useMemo } from "react";
import { useCallback, useMemo, useState } from "react";
import {
faArrowDown,
faArrowUp,
faCheckCircle,
faChevronRight,
faEllipsis,
faFilter,
faMagnifyingGlass,
faSearch,
faUsers
@@ -19,7 +22,11 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
DropdownSubMenu,
DropdownSubMenuContent,
DropdownSubMenuTrigger,
EmptyState,
IconButton,
Input,
@@ -75,6 +82,10 @@ enum OrgMembersOrderBy {
Email = "email"
}
type Filter = {
roles: string[];
};
export const OrgMembersTable = ({ handlePopUpOpen, setCompleteInviteLinks }: Props) => {
const navigate = useNavigate();
const { subscription } = useSubscription();
@@ -184,17 +195,29 @@ export const OrgMembersTable = ({ handlePopUpOpen, setCompleteInviteLinks }: Pro
setUserTablePreference("orgMembersTable", PreferenceKey.PerPage, newPerPage);
};
const [filter, setFilter] = useState<Filter>({
roles: []
});
const filteredUsers = useMemo(
() =>
members
?.filter(
({ user: u, inviteEmail }) =>
?.filter(({ user: u, inviteEmail, role, roleId }) => {
if (
filter.roles.length &&
!filter.roles.includes(role === "custom" ? findRoleFromId(roleId)!.slug : role)
) {
return false;
}
return (
u?.firstName?.toLowerCase().includes(search.toLowerCase()) ||
u?.lastName?.toLowerCase().includes(search.toLowerCase()) ||
u?.username?.toLowerCase().includes(search.toLowerCase()) ||
u?.email?.toLowerCase().includes(search.toLowerCase()) ||
inviteEmail?.toLowerCase().includes(search.toLowerCase())
)
);
})
.sort((a, b) => {
const [memberOne, memberTwo] = orderDirection === OrderByDirection.ASC ? [a, b] : [b, a];
@@ -217,7 +240,7 @@ export const OrgMembersTable = ({ handlePopUpOpen, setCompleteInviteLinks }: Pro
return valueOne.toLowerCase().localeCompare(valueTwo.toLowerCase());
}),
[members, search, orderDirection, orderBy]
[members, search, orderDirection, orderBy, filter]
);
const handleSort = (column: OrgMembersOrderBy) => {
@@ -236,14 +259,81 @@ export const OrgMembersTable = ({ handlePopUpOpen, setCompleteInviteLinks }: Pro
setPage
});
const handleRoleToggle = useCallback(
(roleSlug: string) =>
setFilter((state) => {
const currentRoles = state.roles || [];
if (currentRoles.includes(roleSlug)) {
return { ...state, roles: currentRoles.filter((role) => role !== roleSlug) };
}
return { ...state, roles: [...currentRoles, roleSlug] };
}),
[]
);
const isTableFiltered = Boolean(filter.roles.length);
return (
<div>
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}
placeholder="Search members..."
/>
<div className="flex gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton
ariaLabel="Filter Users"
variant="plain"
size="sm"
className={twMerge(
"flex h-10 w-11 items-center justify-center overflow-hidden border border-mineshaft-600 bg-mineshaft-800 p-0 transition-all hover:border-primary/60 hover:bg-primary/10",
isTableFiltered && "border-primary/50 text-primary"
)}
>
<FontAwesomeIcon icon={faFilter} />
</IconButton>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="p-0">
<DropdownMenuLabel>Filter By</DropdownMenuLabel>
<DropdownSubMenu>
<DropdownSubMenuTrigger
iconPos="right"
icon={<FontAwesomeIcon icon={faChevronRight} size="sm" />}
>
Roles
</DropdownSubMenuTrigger>
<DropdownSubMenuContent className="thin-scrollbar max-h-[20rem] overflow-y-auto rounded-l-none">
<DropdownMenuLabel className="sticky top-0 bg-mineshaft-900">
Apply Roles to Filter Users
</DropdownMenuLabel>
{roles?.map(({ id, slug, name }) => (
<DropdownMenuItem
onClick={(evt) => {
evt.preventDefault();
handleRoleToggle(slug);
}}
key={id}
icon={filter.roles.includes(slug) && <FontAwesomeIcon icon={faCheckCircle} />}
iconPos="right"
>
<div className="flex items-center">
<div
className="mr-2 h-2 w-2 rounded-full"
style={{ background: "#bec2c8" }}
/>
{name}
</div>
</DropdownMenuItem>
))}
</DropdownSubMenuContent>
</DropdownSubMenu>
</DropdownMenuContent>
</DropdownMenu>
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}
placeholder="Search members..."
/>
</div>
<TableContainer className="mt-4">
<Table>
<THead>

View File

@@ -163,6 +163,7 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
text: "Failed to add user to project",
type: "error"
});
return;
}
handlePopUpToggle("addMember", false);
reset();

View File

@@ -224,8 +224,7 @@ export const SecretApprovalRequest = () => {
createdAt,
reviewers,
status,
committerUser,
isReplicated: isReplication
committerUser
} = secretApproval;
const isReviewed = reviewers.some(
({ status: reviewStatus, userId }) =>
@@ -244,13 +243,15 @@ export const SecretApprovalRequest = () => {
>
<div className="mb-1">
<FontAwesomeIcon icon={faCodeBranch} className="mr-2" />
{generateCommitText(commits)}
{secretApproval.isReplicated
? `${commits.length} secret pending import`
: generateCommitText(commits)}
<span className="text-xs text-bunker-300"> #{secretApproval.slug}</span>
</div>
<span className="text-xs text-gray-500">
Opened {formatDistance(new Date(createdAt), new Date())} ago by{" "}
{committerUser?.firstName || ""} {committerUser?.lastName || ""} (
{committerUser?.email}){isReplication && " via replication"}
{committerUser?.email})
{!isReviewed && status === "open" && " - Review required"}
</span>
</div>

View File

@@ -12,7 +12,7 @@ import {
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Tag, Tooltip } from "@app/components/v2";
import { SecretInput, Tag, Tooltip } from "@app/components/v2";
import { CommitType, SecretV3Raw, TSecretApprovalSecChange, WsTag } from "@app/hooks/api/types";
export type Props = {
@@ -86,10 +86,10 @@ export const SecretApprovalRequestChangeItem = ({
{op === CommitType.UPDATE || op === CommitType.DELETE ? (
<div className="flex w-full cursor-default flex-col rounded-md border border-red-600/60 bg-red-600/10 p-4 xl:w-1/2">
<div className="mb-4 flex flex-row justify-between">
<span className="text-md font-medium">Legacy Secret</span>
<span className="text-md font-medium">Previous Secret</span>
<div className="rounded-full bg-red px-2 pb-[0.14rem] pt-[0.2rem] text-xs font-medium">
<FontAwesomeIcon icon={faCircleXmark} className="pr-1 text-white" />
Deprecated
Previous
</div>
</div>
<div className="mb-2">
@@ -104,34 +104,29 @@ export const SecretApprovalRequestChangeItem = ({
Rotated Secret value will not be affected
</span>
) : (
<div
onClick={() => setIsOldSecretValueVisible(!isOldSecretValueVisible)}
className="flex flex-row items-center justify-between rounded-md border border-mineshaft-500 bg-mineshaft-900 pl-2"
>
<div className="relative">
<SecretInput
isReadOnly
isVisible={isOldSecretValueVisible}
value={secretVersion?.secretValue}
containerClassName="text-bunker-300 hover:border-primary-400/50 border border-mineshaft-600 bg-bunker-700 px-2 py-1.5"
/>
<div
className={`flex font-mono ${isOldSecretValueVisible || !secretVersion?.secretValue ? "text-md py-[0.55rem]" : "text-lg"}`}
className="absolute right-1 top-1"
onClick={() => setIsOldSecretValueVisible(!isOldSecretValueVisible)}
>
{isOldSecretValueVisible
? secretVersion?.secretValue || "EMPTY"
: secretVersion?.secretValue
? secretVersion?.secretValue?.split("").map(() => "•")
: "EMPTY"}{" "}
<FontAwesomeIcon
icon={isOldSecretValueVisible ? faEyeSlash : faEye}
className="cursor-pointer rounded-md border border-mineshaft-500 bg-mineshaft-800 p-1.5 text-mineshaft-300 hover:bg-mineshaft-700"
/>
</div>
{secretVersion?.secretValue && (
<div className="flex h-10 w-10 items-center justify-center">
<FontAwesomeIcon
icon={isOldSecretValueVisible ? faEyeSlash : faEye}
className="cursor-pointer rounded-md border border-mineshaft-500 bg-mineshaft-800 p-1.5 text-mineshaft-300 hover:bg-mineshaft-700"
/>
</div>
)}
</div>
)}
</div>
</div>
<div className="mb-2">
<div className="text-sm font-medium text-mineshaft-300">Comment</div>
<div className="text-sm">
<div className="max-h-[5rem] overflow-y-auto text-sm">
{secretVersion?.secretComment || (
<span className="text-sm text-mineshaft-300">-</span>
)}{" "}
@@ -191,8 +186,7 @@ export const SecretApprovalRequestChangeItem = ({
</div>
) : (
<div className="text-md flex w-full items-center justify-center rounded-md border border-mineshaft-600 bg-mineshaft-800 text-mineshaft-300 xl:w-1/2">
{" "}
Secret not existent in the previous version.
Secret did not exist in the previous version.
</div>
)}
{op === CommitType.UPDATE || op === CommitType.CREATE ? (
@@ -201,7 +195,7 @@ export const SecretApprovalRequestChangeItem = ({
<span className="text-md font-medium">New Secret</span>
<div className="rounded-full bg-green-600 px-2 pb-[0.14rem] pt-[0.2rem] text-xs font-medium">
<FontAwesomeIcon icon={faCircleXmark} className="pr-1 text-white" />
Current
New
</div>
</div>
<div className="mb-2">
@@ -216,34 +210,29 @@ export const SecretApprovalRequestChangeItem = ({
Rotated Secret value will not be affected
</span>
) : (
<div
onClick={() => setIsNewSecretValueVisible(!isNewSecretValueVisible)}
className="flex flex-row items-center justify-between rounded-md border border-mineshaft-500 bg-mineshaft-900 pl-2"
>
<div className="relative">
<SecretInput
isReadOnly
isVisible={isNewSecretValueVisible}
value={newVersion?.secretValue}
containerClassName="text-bunker-300 hover:border-primary-400/50 border border-mineshaft-600 bg-bunker-700 px-2 py-1.5"
/>
<div
className={`flex font-mono ${isNewSecretValueVisible || !newVersion?.secretValue ? "text-md py-[0.55rem]" : "text-lg"}`}
className="absolute right-1 top-1"
onClick={() => setIsNewSecretValueVisible(!isNewSecretValueVisible)}
>
{isNewSecretValueVisible
? newVersion?.secretValue || "EMPTY"
: newVersion?.secretValue
? newVersion?.secretValue?.split("").map(() => "•")
: "EMPTY"}{" "}
<FontAwesomeIcon
icon={isNewSecretValueVisible ? faEyeSlash : faEye}
className="cursor-pointer rounded-md border border-mineshaft-500 bg-mineshaft-800 p-1.5 text-mineshaft-300 hover:bg-mineshaft-700"
/>
</div>
{newVersion?.secretValue && (
<div className="flex h-10 w-10 items-center justify-center">
<FontAwesomeIcon
icon={isNewSecretValueVisible ? faEyeSlash : faEye}
className="cursor-pointer rounded-md border border-mineshaft-500 bg-mineshaft-800 p-1.5 text-mineshaft-300 hover:bg-mineshaft-700"
/>
</div>
)}
</div>
)}
</div>
</div>
<div className="mb-2">
<div className="text-sm font-medium text-mineshaft-300">Comment</div>
<div className="text-sm">
<div className="max-h-[5rem] overflow-y-auto text-sm">
{newVersion?.secretComment || (
<span className="text-sm text-mineshaft-300">-</span>
)}{" "}
@@ -302,7 +291,7 @@ export const SecretApprovalRequestChangeItem = ({
) : (
<div className="text-md flex w-full items-center justify-center rounded-md border border-mineshaft-600 bg-mineshaft-800 text-mineshaft-300 xl:w-1/2">
{" "}
Secret not existent in the new version.
Secret did not exist in the previous version.
</div>
)}
</div>

View File

@@ -30,19 +30,24 @@ import {
TextArea,
Tooltip
} from "@app/components/v2";
import { useUser } from "@app/context";
import { useUser, useWorkspace } from "@app/context";
import { usePopUp } from "@app/hooks";
import {
useGetSecretApprovalRequestDetails,
useGetSecretImports,
useUpdateSecretApprovalReviewStatus
} from "@app/hooks/api";
import { ApprovalStatus, CommitType } from "@app/hooks/api/types";
import { formatReservedPaths } from "@app/lib/fn/string";
import { formatReservedPaths, parsePathFromReplicatedPath } from "@app/lib/fn/string";
import { SecretApprovalRequestAction } from "./SecretApprovalRequestAction";
import { SecretApprovalRequestChangeItem } from "./SecretApprovalRequestChangeItem";
export const generateCommitText = (commits: { op: CommitType }[] = []) => {
export const generateCommitText = (commits: { op: CommitType }[] = [], isReplicated = false) => {
if (isReplicated) {
return <span>{commits.length} secret pending import</span>;
}
const score: Record<string, number> = {};
commits.forEach(({ op }) => {
score[op] = (score?.[op] || 0) + 1;
@@ -74,7 +79,6 @@ export const generateCommitText = (commits: { op: CommitType }[] = []) => {
<span style={{ color: "#F83030" }}> deleted</span>
</span>
);
return text;
};
@@ -105,6 +109,7 @@ export const SecretApprovalRequestChanges = ({
workspaceId
}: Props) => {
const { user: userSession } = useUser();
const { currentWorkspace } = useWorkspace();
const {
data: secretApprovalRequestDetails,
isSuccess: isSecretApprovalRequestSuccess,
@@ -112,6 +117,20 @@ export const SecretApprovalRequestChanges = ({
} = useGetSecretApprovalRequestDetails({
id: approvalRequestId
});
const approvalSecretPath = parsePathFromReplicatedPath(
secretApprovalRequestDetails?.secretPath || ""
);
const { data: secretImports } = useGetSecretImports({
environment: secretApprovalRequestDetails?.environment || "",
projectId: currentWorkspace.id,
path: approvalSecretPath
});
const replicatedImport = secretApprovalRequestDetails?.isReplicated
? secretImports?.find(
(el) => secretApprovalRequestDetails?.secretPath?.includes(el.id) && el.isReplication
)
: undefined;
const {
mutateAsync: updateSecretApprovalRequestStatus,
@@ -226,34 +245,16 @@ export const SecretApprovalRequestChanges = ({
: secretApprovalRequestDetails.status}
</span>
</div>
<div className="flex flex-grow flex-col">
<div className="text-lg">
{generateCommitText(secretApprovalRequestDetails.commits)}
{secretApprovalRequestDetails.isReplicated && (
<span className="text-sm text-bunker-300"> (replication)</span>
<div className="flex-grow flex-col">
<div className="text-xl">
{generateCommitText(
secretApprovalRequestDetails.commits,
secretApprovalRequestDetails.isReplicated
)}
</div>
<div className="text-sm text-bunker-300">
<p className="inline">
{secretApprovalRequestDetails?.committerUser?.firstName || ""}
{secretApprovalRequestDetails?.committerUser?.lastName || ""} (
{secretApprovalRequestDetails?.committerUser?.email}) wants to change{" "}
{secretApprovalRequestDetails.commits.length} secret values in
</p>
<p className="mx-1 inline rounded bg-primary-600/40 px-1 py-1 text-primary-300">
{secretApprovalRequestDetails.environment}
</p>
<div className="inline-flex w-min items-center rounded border border-mineshaft-500 pl-1 pr-2">
<p className="cursor-default border-r border-mineshaft-500 pr-1">
<FontAwesomeIcon icon={faFolder} className="text-primary" size="sm" />
</p>
<p
className="cursor-default truncate pb-0.5 pl-2 text-sm"
style={{ maxWidth: "10rem" }}
>
{formatReservedPaths(secretApprovalRequestDetails.secretPath)}
</p>
</div>
<div className="flex items-center space-x-2 text-xs text-gray-400">
By {secretApprovalRequestDetails?.committerUser?.firstName} (
{secretApprovalRequestDetails?.committerUser?.email})
</div>
</div>
{!hasMerged &&
@@ -367,6 +368,82 @@ export const SecretApprovalRequestChanges = ({
</DropdownMenu>
)}
</div>
<div className="mb-4 flex flex-col rounded-r border-l-2 border-l-primary bg-mineshaft-300/5 px-4 py-2.5">
<div>
{secretApprovalRequestDetails.isReplicated ? (
<div className="text-sm text-bunker-300">
A secret import in
<p
className="mx-1 inline rounded bg-primary-600/40 text-primary-300"
style={{ padding: "2px 4px" }}
>
{secretApprovalRequestDetails?.environment}
</p>
<div className="mr-2 inline-flex w-min items-center rounded border border-mineshaft-500 pl-1 pr-2">
<p className="cursor-default border-r border-mineshaft-500 pr-1">
<FontAwesomeIcon icon={faFolder} className="text-primary" size="sm" />
</p>
<Tooltip content={approvalSecretPath}>
<p
className="cursor-default truncate pb-0.5 pl-2 text-sm"
style={{ maxWidth: "15rem" }}
>
{approvalSecretPath}
</p>
</Tooltip>
</div>
has pending changes to be accepted from its source at{" "}
<p
className="mx-1 inline rounded bg-primary-600/40 text-primary-300"
style={{ padding: "2px 4px" }}
>
{replicatedImport?.importEnv?.slug}
</p>
<div className="inline-flex w-min items-center rounded border border-mineshaft-500 pl-1 pr-2">
<p className="cursor-default border-r border-mineshaft-500 pr-1">
<FontAwesomeIcon icon={faFolder} className="text-primary" size="sm" />
</p>
<Tooltip content={replicatedImport?.importPath}>
<p
className="cursor-default truncate pb-0.5 pl-2 text-sm"
style={{ maxWidth: "15rem" }}
>
{replicatedImport?.importPath}
</p>
</Tooltip>
</div>
. Approving these changes will add them to that import.
</div>
) : (
<div className="text-sm text-bunker-300">
<p className="inline">Secret(s) in</p>
<p
className="mx-1 inline rounded bg-primary-600/40 text-primary-300"
style={{ padding: "2px 4px" }}
>
{secretApprovalRequestDetails?.environment}
</p>
<div className="mr-1 inline-flex w-min items-center rounded border border-mineshaft-500 pl-1 pr-2">
<p className="cursor-default border-r border-mineshaft-500 pr-1">
<FontAwesomeIcon icon={faFolder} className="text-primary" size="sm" />
</p>
<Tooltip content={formatReservedPaths(secretApprovalRequestDetails.secretPath)}>
<p
className="cursor-default truncate pb-0.5 pl-2 text-sm"
style={{ maxWidth: "20rem" }}
>
{formatReservedPaths(secretApprovalRequestDetails.secretPath)}
</p>
</Tooltip>
</div>
<p className="inline">
have pending changes. Approving these changes will add them to that environment
and path.
</p>
</div>
)}
</div>
</div>
<div className="flex flex-col space-y-4">
{secretApprovalRequestDetails.commits.map(
({ op, secretVersion, secret, ...newVersion }, index) => (