Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix: address the review findings on the platform test PR

Claudead4f1ec83b96
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index f98c8fba64..f2a3bb2fe5 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -71,7 +71,8 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
actorType: req.permission.type,
actorAuthMethod: req.permission.authMethod,
directAddress: req.body.directAddress,
- name: req.body.name
+ name: req.body.name,
+ tokenVersion: req.auth.authMode === AuthMode.GATEWAY_ACCESS_TOKEN ? req.auth.token.tokenVersion : undefined
});
await server.services.auditLog.createAuditLog({
diff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.ts
index 92a5cb3427..14682fec94 100644
--- a/backend/src/ee/routes/v3/gateway-router.ts
+++ b/backend/src/ee/routes/v3/gateway-router.ts
@@ -908,7 +908,8 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorType: req.permission.type,
relayName: req.body.relayName,
- directAddress: req.body.directAddress
+ directAddress: req.body.directAddress,
+ tokenVersion: req.auth.authMode === AuthMode.GATEWAY_ACCESS_TOKEN ? req.auth.token.tokenVersion : undefined
});
await server.services.auditLog.createAuditLog({
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index ee8ebd8d28..39f1a22d45 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -2307,7 +2307,7 @@ interface InviteOrgMembersEvent {
metadata: {
inviteeEmails: string[];
organizationRoleSlug: string;
- projectIds?: string[];
+ projects?: { id: string; name: string }[];
};
}
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index e82036b9e2..3e55eee746 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -3,13 +3,19 @@ import net from "node:net";
import { ForbiddenError } from "@casl/ability";
import * as x509 from "@peculiar/x509";
-import { OrganizationActionScope, OrgMembershipRole, OrgMembershipStatus, TRelays } from "@app/db/schemas";
+import {
+ OrganizationActionScope,
+ OrgMembershipRole,
+ OrgMembershipStatus,
+ TGatewaysV2Update,
+ TRelays
+} from "@app/db/schemas";
import { assertHostNotInfisicalInfrastructure } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
import { PgSqlLock } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { DatabaseErrorCode } from "@app/lib/error-codes";
-import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, DatabaseError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn";
import { getGatewayLoadTracker } from "@app/lib/gateway-v2/gateway-load-tracker";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
@@ -781,6 +787,24 @@ export const gatewayV2ServiceFactory = ({
};
};
+ // Revoking clears a gateway's transports and bumps its token version. A connect authenticated just
+ // before the revoke would otherwise write them back after it, so the write only lands while the
+ // version the request authenticated with is still current.
+ const $writeAgentTransports = async (
+ gatewayId: string,
+ tokenVersion: number | undefined,
+ transports: Pick<TGatewaysV2Update, "directAddress" | "directHeartbeat" | "heartbeat" | "relayId">
+ ) => {
+ if (tokenVersion === undefined) {
+ throw new UnauthorizedError({ message: "Gateway token has been revoked" });
+ }
+ const [updated] = await gatewayV2DAL.update({ id: gatewayId, tokenVersion }, transports);
+ if (!updated) {
+ throw new UnauthorizedError({ message: "Gateway token has been revoked" });
+ }
+ return updated;
+ };
+
const registerGateway = async ({
orgId,
actorId,
@@ -788,7 +812,8 @@ export const gatewayV2ServiceFactory = ({
actorAuthMethod,
relayName,
directAddress,
- name
+ name,
+ tokenVersion
}: {
orgId: string;
actorId: string;
@@ -797,6 +822,8 @@ export const gatewayV2ServiceFactory = ({
relayName?: string;
directAddress?: string;
name?: string;
+ /** The gateway access token's version, when a gateway agent is the actor. */
+ tokenVersion?: number;
}) => {
if (directAddress) {
if (getConfig().isCloud) {
@@ -829,7 +856,7 @@ export const gatewayV2ServiceFactory = ({
}
// The gateway declares its full transport set every call, so an omitted transport is removed.
- const registeredGateway = await gatewayV2DAL.updateById(gateway.id, {
+ const registeredGateway = await $writeAgentTransports(gateway.id, tokenVersion, {
directAddress: directAddress ?? null,
directHeartbeat: directAddress === gateway.directAddress ? gateway.directHeartbeat : null,
heartbeat: resolvedRelay?.id === gateway.relayId ? gateway.heartbeat : null,
@@ -1503,13 +1530,16 @@ export const gatewayV2ServiceFactory = ({
actorId,
actorType,
relayName,
- directAddress
+ directAddress,
+ tokenVersion
}: {
orgId: string;
actorId: string;
actorType: ActorType;
relayName?: string;
directAddress?: string;
+ /** The gateway access token's version the request authenticated with. */
+ tokenVersion?: number;
}) => {
if (directAddress) {
if (getConfig().isCloud) {
@@ -1540,7 +1570,7 @@ export const gatewayV2ServiceFactory = ({
}
// The gateway declares its full transport set every call, so an omitted transport is removed.
- const registeredGateway = await gatewayV2DAL.updateById(gateway.id, {
+ const registeredGateway = await $writeAgentTransports(gateway.id, tokenVersion, {
directAddress: directAddress ?? null,
directHeartbeat: directAddress === gateway.directAddress ? gateway.directHeartbeat : null,
heartbeat: resolvedRelay?.id === gateway.relayId ? gateway.heartbeat : null,
diff --git a/backend/src/server/routes/v1/invite-org-router.ts b/backend/src/server/routes/v1/invite-org-router.ts
index 080ff934c9..29f963ab99 100644
--- a/backend/src/server/routes/v1/invite-org-router.ts
+++ b/backend/src/server/routes/v1/invite-org-router.ts
@@ -79,6 +79,12 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {
}
});
+ const projects = req.body.projectIds?.length
+ ? await server.services.project.getProjectNamesByIds({
+ orgId: req.permission.orgId,
+ projectIds: req.body.projectIds
+ })
+ : undefined;
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
@@ -87,7 +93,7 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {
metadata: {
inviteeEmails: req.body.inviteeEmails,
organizationRoleSlug: req.body.organizationRoleSlug,
- projectIds: req.body.projectIds
+ projects
}
}
});
diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts
index cd42dd06e0..70588f45e3 100644
--- a/backend/src/server/routes/v1/sso-router.ts
+++ b/backend/src/server/routes/v1/sso-router.ts
@@ -596,7 +596,11 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
hide: true,
operationId: "googleLoginCallback",
querystring: z
- .object({ code: z.string().optional(), state: z.string().optional(), error: z.string().optional() })
+ .object({
+ code: z.string().trim().max(4096).optional(),
+ state: z.string().trim().max(4096).optional(),
+ error: z.string().trim().max(256).optional()
+ })
.passthrough()
},
preValidation: [
@@ -702,7 +706,11 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
hide: true,
operationId: "githubLoginCallback",
querystring: z
- .object({ code: z.string().optional(), state: z.string().optional(), error: z.string().optional() })
+ .object({
+ code: z.string().trim().max(4096).optional(),
+ state: z.string().trim().max(4096).optional(),
+ error: z.string().trim().max(256).optional()
+ })
.passthrough()
},
preValidation: [
@@ -781,7 +789,11 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
hide: true,
operationId: "gitlabLoginCallback",
querystring: z
- .object({ code: z.string().optional(), state: z.string().optional(), error: z.string().optional() })
+ .object({
+ code: z.string().trim().max(4096).optional(),
+ state: z.string().trim().max(4096).optional(),
+ error: z.string().trim().max(256).optional()
+ })
.passthrough()
},
preValidation: [
diff --git a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts
index 5a9a5ca5d2..38d14a2ae2 100644
--- a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts
+++ b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts
@@ -20,6 +20,7 @@ import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
+import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
@@ -178,8 +179,14 @@ export const identityJwtAuthServiceFactory = ({
}
});
}
+ // The fetch error can carry network details or the endpoint's response body, and this
+ // route is unauthenticated, so the caller gets a fixed message and the detail is logged.
+ logger.error(
+ { error, identityId: identity.id, jwksUrl: identityJwtAuth.jwksUrl, kid },
+ `JWT auth signing key retrieval failed [identityId=${identity.id}] [kid=${kid}]`
+ );
throw new UnauthorizedError({
- message: `Access denied: Failed to retrieve signing key from the JWKS endpoint: ${error instanceof Error ? error.message : String(error)}`,
+ message: "Access denied: Failed to retrieve the signing key from the configured JWKS endpoint.",
detail: {
reasonCode: "signing_key_retrieval_failed",
identityId: identity.id,
diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts
index 0e0c656431..b22b6430c8 100644
--- a/backend/src/services/project/project-service.ts
+++ b/backend/src/services/project/project-service.ts
@@ -2369,9 +2369,18 @@ export const projectServiceFactory = ({
const getSecretBlindIndexMigrationStatus = async (dto: TEnableSecretBlindIndexDTO) =>
secretValueTrackingService.getProjectStatus(dto);
+ // Labels for audit metadata only, so no permission check. Scoped to the org, so an id from
+ // another org resolves to nothing.
+ const getProjectNamesByIds = async ({ orgId, projectIds }: { orgId: string; projectIds: string[] }) => {
+ if (!projectIds.length) return [];
+ const projects = await projectDAL.find({ orgId, $in: { id: projectIds } });
+ return projects.map(({ id, name }) => ({ id, name }));
+ };
+
return {
createProject,
deleteProject,
+ getProjectNamesByIds,
getProjects,
getAccessibleProjectsWithSubOrgs,
updateProject,
diff --git a/tests/suites/auditlog/actor_test.go b/tests/suites/auditlog/actor_test.go
index f772cc5c4c..00f3ba15b4 100644
--- a/tests/suites/auditlog/actor_test.go
+++ b/tests/suites/auditlog/actor_test.go
@@ -235,6 +235,30 @@ func TestAuditLog_OrgInvite(t *testing.T) {
})
require.Equal(t, "member", event.Metadata["organizationRoleSlug"])
})
+
+ t.Run("should name each project the invitation grants access to", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ invitee := tn.Email("invitee")
+
+ // Action
+ res, err := tn.Admin.API.InviteUsersToOrganizationWithResponse(t.Context(), api.InviteUsersToOrganizationJSONRequestBody{
+ InviteeEmails: []openapi_types.Email{openapi_types.Email(invitee)},
+ OrganizationId: tn.OrgID.String(),
+ ProjectIds: &[]string{proj.ID},
+ })
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ event := waitForEvent(t, tn.Admin, "invite-org-members", func(e entry) bool {
+ return strings.Contains(strings.ToLower(jsonString(t, e.Metadata)), invitee)
+ })
+ require.Equal(t, []any{map[string]any{"id": proj.ID, "name": proj.Name}}, event.Metadata["projects"])
+ })
}
func selectionsBy(user *harness.Principal) filter {
diff --git a/tests/suites/gateway/connect_test.go b/tests/suites/gateway/connect_test.go
index 6d21f569b6..4c96c9bfaa 100644
--- a/tests/suites/gateway/connect_test.go
+++ b/tests/suites/gateway/connect_test.go
@@ -3,6 +3,7 @@ package gateway_test
import (
"crypto/x509"
"net/http"
+ "sync"
"testing"
"time"
@@ -226,3 +227,44 @@ func connectedRoot(t *testing.T, tn *harness.Tenant, res *api.ConnectGatewayResp
require.Equal(t, []string{tn.OrgID.String()}, root.Subject.Organization)
return root
}
+
+// concurrentFirstUses is how many agents make an organization's first connect at once: enough
+// that, without the re-check under the advisory lock, more than one would create the CA.
+const concurrentFirstUses = 6
+
+func TestGatewayConnect_ConcurrentFirstConnect(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should create one gateway CA when an organization's first gateways connect at once", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ relay := newRelay(t, tn)
+ agents := make([]agent, concurrentFirstUses)
+ for i := range agents {
+ agents[i] = enrollGateway(t, tn, newGateway(t, tn).ID)
+ }
+
+ // Action
+ results := make([]*api.ConnectGatewayResponse, len(agents))
+ errs := make([]error, len(agents))
+ var wg sync.WaitGroup
+ for i, a := range agents {
+ wg.Go(func() {
+ results[i], errs[i] = a.API.ConnectGatewayWithResponse(t.Context(), api.ConnectGatewayJSONRequestBody{RelayName: &relay.Name})
+ })
+ }
+ wg.Wait()
+
+ // Assert
+ roots := map[string]bool{}
+ for i, res := range results {
+ require.NoError(t, errs[i])
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ roots[string(connectedRoot(t, tn, res).SubjectKeyId)] = true
+ }
+ require.Len(t, roots, 1, "the concurrent connects were issued certificates under different root CAs")
+ })
+}
diff --git a/tests/suites/gateway/relay_test.go b/tests/suites/gateway/relay_test.go
index 0d9e251bbd..08d7994df1 100644
--- a/tests/suites/gateway/relay_test.go
+++ b/tests/suites/gateway/relay_test.go
@@ -2,6 +2,7 @@ package gateway_test
import (
"net/http"
+ "sync"
"testing"
"time"
@@ -283,3 +284,37 @@ func TestRelay_MemberPermission(t *testing.T) {
requireStatus(t, http.StatusOK, connect.StatusCode(), connect.Body)
})
}
+
+func TestRelay_ConcurrentFirstConnect(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should create one relay CA when an organization's first relays connect at once", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ agents := make([]agent, concurrentFirstUses)
+ for i := range agents {
+ agents[i] = enrollRelay(t, tn, newRelay(t, tn).ID)
+ }
+
+ // Action
+ results := make([]*api.ConnectRelayResponse, len(agents))
+ errs := make([]error, len(agents))
+ var wg sync.WaitGroup
+ for i, a := range agents {
+ wg.Go(func() { results[i], errs[i] = a.API.ConnectRelayWithResponse(t.Context()) })
+ }
+ wg.Wait()
+
+ // Assert
+ issuers := map[string]bool{}
+ for i, res := range results {
+ require.NoError(t, errs[i])
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ issuers[string(parseCert(t, res.JSON200.Pki.ServerCertificate).AuthorityKeyId)] = true
+ }
+ require.Len(t, issuers, 1, "the concurrent connects were issued certificates under different relay CAs")
+ })
+}
diff --git a/tests/suites/machineidentity/accesstoken_test.go b/tests/suites/machineidentity/accesstoken_test.go
index 10488e4411..7fcfdd2c55 100644
--- a/tests/suites/machineidentity/accesstoken_test.go
+++ b/tests/suites/machineidentity/accesstoken_test.go
@@ -154,7 +154,7 @@ func TestAccessToken_TTL(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTTL: new(2), AccessTokenMaxTTL: new(10)}).login(t, tn)
+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTTL: new(5), AccessTokenMaxTTL: new(20)}).login(t, tn)
c := tn.Client(t, token)
// Action
@@ -190,8 +190,8 @@ func TestAccessToken_TTL(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- const maxTTL = 4
- token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTTL: new(2), AccessTokenMaxTTL: new(maxTTL)}).login(t, tn)
+ const maxTTL = 10
+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTTL: new(5), AccessTokenMaxTTL: new(maxTTL)}).login(t, tn)
deadline := int64(claims(t, token)["creationEpoch"].(float64)) + maxTTL
var exps []int64
@@ -224,7 +224,7 @@ func TestAccessToken_TTL(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- const ttl, maxTTL = 4, 6
+ const ttl, maxTTL = 8, 12
token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTTL: new(ttl), AccessTokenMaxTTL: new(maxTTL)}).login(t, tn)
deadline := claims(t, token)["creationEpoch"].(float64) + maxTTL
@@ -248,7 +248,7 @@ func TestAccessToken_TTL(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- const period, maxTTL = 2, 3
+ const period, maxTTL = 5, 6
token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{
AccessTokenTTL: new(period), AccessTokenMaxTTL: new(maxTTL), AccessTokenPeriod: new(period),
}).login(t, tn)
@@ -264,7 +264,7 @@ func TestAccessToken_TTL(t *testing.T) {
token = res.JSON200.AccessToken
expiresIn = append(expiresIn, res.JSON200.ExpiresIn)
return struct{}{}, time.Since(start) > 2*maxTTL*time.Second, nil
- }, wait.Interval(500*time.Millisecond), wait.Timeout(15*time.Second))
+ }, wait.Interval(time.Second), wait.Timeout(30*time.Second))
// Assert
require.NoError(t, err)