From 1c5a8cabe96fb0a8d374c61ca898be1ff37c0871 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard Date: Tue, 17 Sep 2024 22:53:51 +0400 Subject: [PATCH 1/9] feat: better api errors --- backend/src/server/plugins/error-handler.ts | 37 ++++++++++++ .../services/project-bot/project-bot-fns.ts | 5 +- .../secret-import/secret-import-service.ts | 6 +- backend/src/services/secret/secret-fns.ts | 12 +++- backend/src/services/secret/secret-service.ts | 57 +++++++++++++++---- 5 files changed, 103 insertions(+), 14 deletions(-) diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts index 3320c7d87..6b51f04f7 100644 --- a/backend/src/server/plugins/error-handler.ts +++ b/backend/src/server/plugins/error-handler.ts @@ -1,7 +1,9 @@ import { ForbiddenError } from "@casl/ability"; import fastifyPlugin from "fastify-plugin"; +import { JsonWebTokenError } from "jsonwebtoken"; import { ZodError } from "zod"; +import { UserAgentType } from "@app/ee/services/audit-log/audit-log-types"; import { BadRequestError, DatabaseError, @@ -11,6 +13,12 @@ import { UnauthorizedError } from "@app/lib/errors"; +enum JWTErrors { + JwtExpired = "jwt expired", + JwtMalformed = "jwt malformed", + InvalidAlgorithm = "invalid algorithm" +} + export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider) => { server.setErrorHandler((error, req, res) => { req.log.error(error); @@ -36,6 +44,35 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider status: error.status, detail: error.detail }); + // Handle JWT errors and make them more human-readable for the end-user. + } else if (error instanceof JsonWebTokenError) { + const isCliRequest = req.headers["user-agent"] === UserAgentType.CLI; + + const message = (() => { + if (error.message === JWTErrors.JwtExpired) { + return "Your token has expired. Please re-authenticate."; + } + if (error.message === JWTErrors.JwtMalformed) { + if (isCliRequest) { + return "The access token is malformed. Are you sure the token you are using is correct? Check the INFISICAL_TOKEN environment variable, or the --token flag. If you are using user-login, please run [infisical login] to re-authenticate."; + } + return "The access token is malformed. Please ensure that the token is in the correct format and try again."; + } + if (error.message === JWTErrors.InvalidAlgorithm) { + if (isCliRequest) { + return "Invalid algorithm. Are you sure you are using the correct authentication method? Make sure to check that you don't have the INFISICAL_TOKEN variable set in your environment variables. If you are intentionally using the INFISICAL_TOKEN variable, make sure you are using the correct token." as const; + } + return "The access token is signed with an invalid algorithm. Please ensure that the token is in the correct format and try again. We recommend obtaining a new token."; + } + + return error.message; + })(); + + void res.status(401).send({ + statusCode: 401, + error: "TokenError", + message + }); } else { void res.send(error); } diff --git a/backend/src/services/project-bot/project-bot-fns.ts b/backend/src/services/project-bot/project-bot-fns.ts index 9cdb52cff..4efcbb34b 100644 --- a/backend/src/services/project-bot/project-bot-fns.ts +++ b/backend/src/services/project-bot/project-bot-fns.ts @@ -26,7 +26,10 @@ export const getBotKeyFnFactory = ( ) => { const getBotKeyFn = async (projectId: string) => { const project = await projectDAL.findById(projectId); - if (!project) throw new BadRequestError({ message: "Project not found during bot lookup." }); + if (!project) + throw new BadRequestError({ + message: "Project not found during bot lookup. Are you sure you are using the correct project ID?" + }); if (project.version === 3) { return { project, shouldUseSecretV2Bridge: true }; diff --git a/backend/src/services/secret-import/secret-import-service.ts b/backend/src/services/secret-import/secret-import-service.ts index c3d1a6791..45cecf03d 100644 --- a/backend/src/services/secret-import/secret-import-service.ts +++ b/backend/src/services/secret-import/secret-import-service.ts @@ -512,7 +512,11 @@ export const secretImportServiceFactory = ({ return importedSecrets; } - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); const importedSecrets = await fnSecretsFromImports({ allowedImports, folderDAL, secretDAL, secretImportDAL }); return importedSecrets.map((el) => ({ diff --git a/backend/src/services/secret/secret-fns.ts b/backend/src/services/secret/secret-fns.ts index 7837b716b..e77972d37 100644 --- a/backend/src/services/secret/secret-fns.ts +++ b/backend/src/services/secret/secret-fns.ts @@ -832,7 +832,11 @@ export const createManySecretsRawFnFactory = ({ secretDAL }); - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); const inputSecrets = secrets.map((secret) => { const secretKeyEncrypted = encryptSymmetric128BitHexKeyUTF8(secret.secretName, botKey); const secretValueEncrypted = encryptSymmetric128BitHexKeyUTF8(secret.secretValue || "", botKey); @@ -993,7 +997,11 @@ export const updateManySecretsRawFnFactory = ({ return updatedSecrets; } - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId }); if (!blindIndexCfg) throw new BadRequestError({ message: "Blind index not found", name: "Update secret" }); diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts index e502f577a..124515c8b 100644 --- a/backend/src/services/secret/secret-service.ts +++ b/backend/src/services/secret/secret-service.ts @@ -985,7 +985,11 @@ export const secretServiceFactory = ({ return { secrets, imports }; } - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); const { secrets, imports } = await getSecrets({ actorId, @@ -1146,7 +1150,10 @@ export const secretServiceFactory = ({ }); if (!botKey) - throw new BadRequestError({ message: "Please upgrade your project first", name: "bot_not_found_error" }); + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); const decryptedSecret = decryptSecretRaw(encryptedSecret, botKey); if (expandSecretReferences) { @@ -1238,7 +1245,11 @@ export const secretServiceFactory = ({ return { secret, type: SecretProtectionType.Direct as const }; } - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); const secretKeyEncrypted = encryptSymmetric128BitHexKeyUTF8(secretName, botKey); const secretValueEncrypted = encryptSymmetric128BitHexKeyUTF8(secretValue || "", botKey); const secretCommentEncrypted = encryptSymmetric128BitHexKeyUTF8(secretComment || "", botKey); @@ -1376,7 +1387,11 @@ export const secretServiceFactory = ({ return { type: SecretProtectionType.Direct as const, secret }; } - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); const secretValueEncrypted = encryptSymmetric128BitHexKeyUTF8(secretValue || "", botKey); const secretCommentEncrypted = encryptSymmetric128BitHexKeyUTF8(secretComment || "", botKey); @@ -1498,7 +1513,11 @@ export const secretServiceFactory = ({ }); return { type: SecretProtectionType.Direct as const, secret }; } - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); if (policy) { const approval = await secretApprovalRequestService.generateSecretApprovalRequest({ policy, @@ -1598,7 +1617,11 @@ export const secretServiceFactory = ({ return { secrets, type: SecretProtectionType.Direct as const }; } - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); const sanitizedSecrets = inputSecrets.map( ({ secretComment, secretKey, metadata, tagIds, secretValue, skipMultilineEncoding }) => { const secretKeyEncrypted = encryptSymmetric128BitHexKeyUTF8(secretKey, botKey); @@ -1720,7 +1743,11 @@ export const secretServiceFactory = ({ return { type: SecretProtectionType.Direct as const, secrets }; } - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); const sanitizedSecrets = inputSecrets.map( ({ secretComment, @@ -1848,7 +1875,11 @@ export const secretServiceFactory = ({ return { type: SecretProtectionType.Direct as const, secrets }; } - if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + if (!botKey) + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); if (policy) { const approval = await secretApprovalRequestService.generateSecretApprovalRequest({ @@ -2182,7 +2213,10 @@ export const secretServiceFactory = ({ } if (!botKey) - throw new BadRequestError({ message: "Please upgrade your project first", name: "bot_not_found_error" }); + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); await secretDAL.transaction(async (tx) => { const secrets = await secretDAL.findAllProjectSecretValues(projectId, tx); @@ -2265,7 +2299,10 @@ export const secretServiceFactory = ({ const { botKey } = await projectBotService.getBotKey(project.id); if (!botKey) { - throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + throw new BadRequestError({ + message: "Project bot not found. Please upgrade your project.", + name: "bot_not_found_error" + }); } const sourceFolder = await folderDAL.findBySecretPath(project.id, sourceEnvironment, sourceSecretPath); From 9b2565e3870f10f97cbf6402b7d4728b6330805b Mon Sep 17 00:00:00 2001 From: Daniel Hougaard Date: Tue, 17 Sep 2024 22:57:43 +0400 Subject: [PATCH 2/9] Update error-handler.ts --- backend/src/server/plugins/error-handler.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts index 6b51f04f7..34766f79e 100644 --- a/backend/src/server/plugins/error-handler.ts +++ b/backend/src/server/plugins/error-handler.ts @@ -46,6 +46,7 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider }); // Handle JWT errors and make them more human-readable for the end-user. } else if (error instanceof JsonWebTokenError) { + // We wan't to return a slightly different message if the request is coming from the CLI. This is because we're able to provide more specific information to the user in that case. const isCliRequest = req.headers["user-agent"] === UserAgentType.CLI; const message = (() => { @@ -54,13 +55,13 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider } if (error.message === JWTErrors.JwtMalformed) { if (isCliRequest) { - return "The access token is malformed. Are you sure the token you are using is correct? Check the INFISICAL_TOKEN environment variable, or the --token flag. If you are using user-login, please run [infisical login] to re-authenticate."; + return "The access token is malformed. Are you sure the token you are using is correct? Check the INFISICAL_TOKEN environment variable, or the --token flag. If you are using user-login, please run [infisical login] to re-authenticate. Please ensure that the INFISICAL_TOKEN variable is not set, if you are not intentionally using it."; } return "The access token is malformed. Please ensure that the token is in the correct format and try again."; } if (error.message === JWTErrors.InvalidAlgorithm) { if (isCliRequest) { - return "Invalid algorithm. Are you sure you are using the correct authentication method? Make sure to check that you don't have the INFISICAL_TOKEN variable set in your environment variables. If you are intentionally using the INFISICAL_TOKEN variable, make sure you are using the correct token." as const; + return "Invalid algorithm. Are you sure you are using the correct authentication method? Make sure to check that you don't have the INFISICAL_TOKEN variable set in your environment variables. If you are intentionally using the INFISICAL_TOKEN variable, make sure you are using the correct token."; } return "The access token is signed with an invalid algorithm. Please ensure that the token is in the correct format and try again. We recommend obtaining a new token."; } From 3e79dbb3f568c01004efa9c5db2614a291b0da2b Mon Sep 17 00:00:00 2001 From: Daniel Hougaard Date: Wed, 18 Sep 2024 01:34:01 +0400 Subject: [PATCH 3/9] feat(cli): warning when logged in and using token at the same time --- cli/packages/cmd/export.go | 8 +++---- cli/packages/cmd/folder.go | 8 +++---- cli/packages/cmd/root.go | 3 +++ cli/packages/cmd/run.go | 8 +++---- cli/packages/cmd/secrets.go | 32 ++++++++++++++------------ cli/packages/config/config.go | 1 + cli/packages/models/cli.go | 5 ++-- cli/packages/util/auth.go | 43 +++++++++++++++++++++++++++++++++++ cli/packages/util/helper.go | 12 ++++++---- 9 files changed, 87 insertions(+), 33 deletions(-) diff --git a/cli/packages/cmd/export.go b/cli/packages/cmd/export.go index f6b028b7a..cac014834 100644 --- a/cli/packages/cmd/export.go +++ b/cli/packages/cmd/export.go @@ -94,9 +94,9 @@ var exportCmd = &cobra.Command{ IncludeImport: includeImports, } - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { request.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { request.UniversalAuthAccessToken = token.Token } @@ -141,9 +141,9 @@ var exportCmd = &cobra.Command{ authParams := models.ExpandSecretsAuthentication{} - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { authParams.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { authParams.UniversalAuthAccessToken = token.Token } diff --git a/cli/packages/cmd/folder.go b/cli/packages/cmd/folder.go index 538f1e2dc..a634abbeb 100644 --- a/cli/packages/cmd/folder.go +++ b/cli/packages/cmd/folder.go @@ -53,9 +53,9 @@ var getCmd = &cobra.Command{ FoldersPath: foldersPath, } - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { request.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { request.UniversalAuthAccessToken = token.Token } @@ -125,7 +125,7 @@ var createCmd = &cobra.Command{ WorkspaceId: projectId, } - if token != nil && (token.Type == util.SERVICE_TOKEN_IDENTIFIER || token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER) { + if util.ShouldUseInfisicalToken(token, nil) { params.InfisicalToken = token.Token } @@ -193,7 +193,7 @@ var deleteCmd = &cobra.Command{ FolderPath: folderPath, } - if token != nil && (token.Type == util.SERVICE_TOKEN_IDENTIFIER || token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER) { + if util.ShouldUseInfisicalToken(token, nil) { params.InfisicalToken = token.Token } diff --git a/cli/packages/cmd/root.go b/cli/packages/cmd/root.go index 482c6f78a..2f6b4cefc 100644 --- a/cli/packages/cmd/root.go +++ b/cli/packages/cmd/root.go @@ -44,6 +44,7 @@ func init() { rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) { silent, err := cmd.Flags().GetBool("silent") config.INFISICAL_URL = util.AppendAPIEndpoint(config.INFISICAL_URL) + if err != nil { util.HandleError(err) } @@ -51,6 +52,8 @@ func init() { if !util.IsRunningInDocker() && !silent { util.CheckForUpdate() } + + config.INFISICAL_SILENT_MODE = silent } // if config.INFISICAL_URL is set to the default value, check if INFISICAL_URL is set in the environment diff --git a/cli/packages/cmd/run.go b/cli/packages/cmd/run.go index fa5176d89..d33d3c2a8 100644 --- a/cli/packages/cmd/run.go +++ b/cli/packages/cmd/run.go @@ -439,9 +439,9 @@ func executeCommandWithWatchMode(commandFlag string, args []string, watchModeInt func fetchAndFormatSecretsForShell(request models.GetAllSecretsParameters, projectConfigDir string, secretOverriding bool, shouldExpandSecrets bool, token *models.TokenDetails) (models.InjectableEnvironmentResult, error) { - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { request.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { request.UniversalAuthAccessToken = token.Token } @@ -461,9 +461,9 @@ func fetchAndFormatSecretsForShell(request models.GetAllSecretsParameters, proje authParams := models.ExpandSecretsAuthentication{} - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { authParams.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { authParams.UniversalAuthAccessToken = token.Token } diff --git a/cli/packages/cmd/secrets.go b/cli/packages/cmd/secrets.go index c9ac36852..d0bbdb596 100644 --- a/cli/packages/cmd/secrets.go +++ b/cli/packages/cmd/secrets.go @@ -87,9 +87,9 @@ var secretsCmd = &cobra.Command{ Recursive: recursive, } - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { request.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { request.UniversalAuthAccessToken = token.Token } @@ -106,9 +106,10 @@ var secretsCmd = &cobra.Command{ if shouldExpandSecrets { authParams := models.ExpandSecretsAuthentication{} - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { authParams.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { authParams.UniversalAuthAccessToken = token.Token } @@ -160,19 +161,19 @@ var secretsSetCmd = &cobra.Command{ util.HandleError(err, "Unable to parse flag") } - if (token == nil) { + if token == nil { util.RequireLocalWorkspaceFile() } environmentName, _ := cmd.Flags().GetString("env") if !cmd.Flags().Changed("env") { - environmentFromWorkspace := util.GetEnvFromWorkspaceFile() + environmentFromWorkspace := util.GetEnvFromWorkspaceFile() if environmentFromWorkspace != "" { environmentName = environmentFromWorkspace } } - projectId, err := cmd.Flags().GetString("projectId") + projectId, err := cmd.Flags().GetString("projectId") if err != nil { util.HandleError(err, "Unable to parse flag") } @@ -188,7 +189,7 @@ var secretsSetCmd = &cobra.Command{ } var secretOperations []models.SecretSetOperation - if token != nil && (token.Type == util.SERVICE_TOKEN_IDENTIFIER || token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER) { + if util.ShouldUseInfisicalToken(token, nil) { if projectId == "" { util.PrintErrorMessageAndExit("When using service tokens or machine identities, you must set the --projectId flag") } @@ -282,7 +283,7 @@ var secretsDeleteCmd = &cobra.Command{ projectId = workspaceFile.WorkspaceId } - if token != nil && (token.Type == util.SERVICE_TOKEN_IDENTIFIER || token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER) { + if util.ShouldUseInfisicalToken(token, nil) { httpClient.SetAuthToken(token.Token) } else { util.RequireLogin() @@ -390,9 +391,9 @@ func getSecretsByNames(cmd *cobra.Command, args []string) { Recursive: recursive, } - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { request.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { request.UniversalAuthAccessToken = token.Token } @@ -409,9 +410,10 @@ func getSecretsByNames(cmd *cobra.Command, args []string) { if shouldExpand { authParams := models.ExpandSecretsAuthentication{} - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { authParams.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { authParams.UniversalAuthAccessToken = token.Token } @@ -485,9 +487,9 @@ func generateExampleEnv(cmd *cobra.Command, args []string) { IncludeImport: true, } - if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { + if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { request.InfisicalToken = token.Token - } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { + } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { request.UniversalAuthAccessToken = token.Token } diff --git a/cli/packages/config/config.go b/cli/packages/config/config.go index c5e162c92..a9640236e 100644 --- a/cli/packages/config/config.go +++ b/cli/packages/config/config.go @@ -1,5 +1,6 @@ package config +var INFISICAL_SILENT_MODE bool var INFISICAL_URL string var INFISICAL_URL_MANUAL_OVERRIDE string var INFISICAL_LOGIN_URL string diff --git a/cli/packages/models/cli.go b/cli/packages/models/cli.go index 1bad5e327..3a6484e89 100644 --- a/cli/packages/models/cli.go +++ b/cli/packages/models/cli.go @@ -63,8 +63,9 @@ type DynamicSecretLease struct { } type TokenDetails struct { - Type string - Token string + Type string + Token string + PassedAsFlag bool } type SingleFolder struct { diff --git a/cli/packages/util/auth.go b/cli/packages/util/auth.go index cdcd7b50a..8333d2427 100644 --- a/cli/packages/util/auth.go +++ b/cli/packages/util/auth.go @@ -1,5 +1,12 @@ package util +import ( + "fmt" + + "github.com/Infisical/infisical-merge/packages/config" + "github.com/Infisical/infisical-merge/packages/models" +) + type AuthStrategyType string var AuthStrategy = struct { @@ -43,3 +50,39 @@ func IsAuthMethodValid(authMethod string, allowUserAuth bool) (isValid bool, str } return false, "" } + +func ShouldUseInfisicalToken(token *models.TokenDetails, validTokenTypes []string) bool { + + if token == nil { + return false + } + + // If nil is passed, we assume both service and universal tokens are acceptable. + if validTokenTypes == nil { + validTokenTypes = []string{SERVICE_TOKEN_IDENTIFIER, UNIVERSAL_AUTH_TOKEN_IDENTIFIER} + } + + for _, tokenType := range validTokenTypes { + if token.Type != tokenType { + continue + } + + details, err := GetCurrentLoggedInUserDetails() + if err == nil && details.IsUserLoggedIn && !details.LoginExpired && !config.INFISICAL_SILENT_MODE { + + var usingFrom string + if token.PassedAsFlag { + usingFrom = "--token flag" + } else { + usingFrom = "INFISICAL_TOKEN environment variable" + } + PrintWarning(fmt.Sprintf("You are currently logged in, but the command will be using the token provided from the %s.", usingFrom)) + + } + + return true + } + + return false + +} diff --git a/cli/packages/util/helper.go b/cli/packages/util/helper.go index b758ebd9d..bcae127b5 100644 --- a/cli/packages/util/helper.go +++ b/cli/packages/util/helper.go @@ -87,6 +87,8 @@ func GetInfisicalToken(cmd *cobra.Command) (token *models.TokenDetails, err erro return nil, err } + passedAsFlag := infisicalToken != "" + if infisicalToken == "" { // If no flag is passed, we first check for the universal auth access token env variable. infisicalToken = os.Getenv(INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN_NAME) @@ -101,14 +103,16 @@ func GetInfisicalToken(cmd *cobra.Command) (token *models.TokenDetails, err erro if strings.HasPrefix(infisicalToken, "st.") { return &models.TokenDetails{ - Type: SERVICE_TOKEN_IDENTIFIER, - Token: infisicalToken, + Type: SERVICE_TOKEN_IDENTIFIER, + Token: infisicalToken, + PassedAsFlag: passedAsFlag, }, nil } return &models.TokenDetails{ - Type: UNIVERSAL_AUTH_TOKEN_IDENTIFIER, - Token: infisicalToken, + Type: UNIVERSAL_AUTH_TOKEN_IDENTIFIER, + Token: infisicalToken, + PassedAsFlag: passedAsFlag, }, nil } From e7278c4cd909cae97c04db50c1dcf1a7fceeb166 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard Date: Wed, 18 Sep 2024 01:35:01 +0400 Subject: [PATCH 4/9] Requested changes --- backend/src/server/plugins/error-handler.ts | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts index 34766f79e..871b071e7 100644 --- a/backend/src/server/plugins/error-handler.ts +++ b/backend/src/server/plugins/error-handler.ts @@ -3,7 +3,6 @@ import fastifyPlugin from "fastify-plugin"; import { JsonWebTokenError } from "jsonwebtoken"; import { ZodError } from "zod"; -import { UserAgentType } from "@app/ee/services/audit-log/audit-log-types"; import { BadRequestError, DatabaseError, @@ -46,24 +45,15 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider }); // Handle JWT errors and make them more human-readable for the end-user. } else if (error instanceof JsonWebTokenError) { - // We wan't to return a slightly different message if the request is coming from the CLI. This is because we're able to provide more specific information to the user in that case. - const isCliRequest = req.headers["user-agent"] === UserAgentType.CLI; - const message = (() => { if (error.message === JWTErrors.JwtExpired) { return "Your token has expired. Please re-authenticate."; } if (error.message === JWTErrors.JwtMalformed) { - if (isCliRequest) { - return "The access token is malformed. Are you sure the token you are using is correct? Check the INFISICAL_TOKEN environment variable, or the --token flag. If you are using user-login, please run [infisical login] to re-authenticate. Please ensure that the INFISICAL_TOKEN variable is not set, if you are not intentionally using it."; - } - return "The access token is malformed. Please ensure that the token is in the correct format and try again."; + return "The provided access token is malformed. Please use a valid token or generate a new one and try again."; } if (error.message === JWTErrors.InvalidAlgorithm) { - if (isCliRequest) { - return "Invalid algorithm. Are you sure you are using the correct authentication method? Make sure to check that you don't have the INFISICAL_TOKEN variable set in your environment variables. If you are intentionally using the INFISICAL_TOKEN variable, make sure you are using the correct token."; - } - return "The access token is signed with an invalid algorithm. Please ensure that the token is in the correct format and try again. We recommend obtaining a new token."; + return "The access token is signed with an invalid algorithm. Please provide a valid token and try again."; } return error.message; From 9234213c62ec0d6d9585f24c36cf0c5bfc9540e6 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard Date: Wed, 18 Sep 2024 12:50:28 +0400 Subject: [PATCH 5/9] Requested changes --- cli/packages/cmd/root.go | 25 ++++++++++++++++++++++--- cli/packages/config/config.go | 1 - cli/packages/util/auth.go | 23 ++--------------------- 3 files changed, 24 insertions(+), 25 deletions(-) diff --git a/cli/packages/cmd/root.go b/cli/packages/cmd/root.go index 2f6b4cefc..586c47e38 100644 --- a/cli/packages/cmd/root.go +++ b/cli/packages/cmd/root.go @@ -4,6 +4,7 @@ Copyright (c) 2023 Infisical Inc. package cmd import ( + "fmt" "os" "strings" @@ -43,17 +44,35 @@ func init() { rootCmd.PersistentFlags().Bool("silent", false, "Disable output of tip/info messages. Useful when running in scripts or CI/CD pipelines.") rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) { silent, err := cmd.Flags().GetBool("silent") - config.INFISICAL_URL = util.AppendAPIEndpoint(config.INFISICAL_URL) - if err != nil { util.HandleError(err) } + config.INFISICAL_URL = util.AppendAPIEndpoint(config.INFISICAL_URL) + if !util.IsRunningInDocker() && !silent { util.CheckForUpdate() } - config.INFISICAL_SILENT_MODE = silent + loggedInDetails, err := util.GetCurrentLoggedInUserDetails() + + // If the user is logged in and their session is not expired, then we check if token auth is also being used concurrently. + if err == nil && loggedInDetails.IsUserLoggedIn && !loggedInDetails.LoginExpired { + token, err := util.GetInfisicalToken(cmd) + + // If token auth is being used concurrently, we warn the user that the token will be used instead of the logged in user's credentials. + if err == nil && token != nil { + var usingFrom string + if token.PassedAsFlag { + usingFrom = "--token flag" + } else { + usingFrom = "INFISICAL_TOKEN environment variable" + } + util.PrintWarning(fmt.Sprintf("You are currently logged in, but the command will be using the token provided from the %s.", usingFrom)) + + } + } + } // if config.INFISICAL_URL is set to the default value, check if INFISICAL_URL is set in the environment diff --git a/cli/packages/config/config.go b/cli/packages/config/config.go index a9640236e..c5e162c92 100644 --- a/cli/packages/config/config.go +++ b/cli/packages/config/config.go @@ -1,6 +1,5 @@ package config -var INFISICAL_SILENT_MODE bool var INFISICAL_URL string var INFISICAL_URL_MANUAL_OVERRIDE string var INFISICAL_LOGIN_URL string diff --git a/cli/packages/util/auth.go b/cli/packages/util/auth.go index 8333d2427..257d647a3 100644 --- a/cli/packages/util/auth.go +++ b/cli/packages/util/auth.go @@ -1,9 +1,6 @@ package util import ( - "fmt" - - "github.com/Infisical/infisical-merge/packages/config" "github.com/Infisical/infisical-merge/packages/models" ) @@ -52,7 +49,6 @@ func IsAuthMethodValid(authMethod string, allowUserAuth bool) (isValid bool, str } func ShouldUseInfisicalToken(token *models.TokenDetails, validTokenTypes []string) bool { - if token == nil { return false } @@ -63,24 +59,9 @@ func ShouldUseInfisicalToken(token *models.TokenDetails, validTokenTypes []strin } for _, tokenType := range validTokenTypes { - if token.Type != tokenType { - continue + if token.Type == tokenType { + return true } - - details, err := GetCurrentLoggedInUserDetails() - if err == nil && details.IsUserLoggedIn && !details.LoginExpired && !config.INFISICAL_SILENT_MODE { - - var usingFrom string - if token.PassedAsFlag { - usingFrom = "--token flag" - } else { - usingFrom = "INFISICAL_TOKEN environment variable" - } - PrintWarning(fmt.Sprintf("You are currently logged in, but the command will be using the token provided from the %s.", usingFrom)) - - } - - return true } return false From 7f055450df24471cd5a24be485e8c6033d1682e1 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard Date: Wed, 18 Sep 2024 12:55:03 +0400 Subject: [PATCH 6/9] Update root.go --- cli/packages/cmd/root.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/packages/cmd/root.go b/cli/packages/cmd/root.go index 586c47e38..1b66d9279 100644 --- a/cli/packages/cmd/root.go +++ b/cli/packages/cmd/root.go @@ -57,7 +57,7 @@ func init() { loggedInDetails, err := util.GetCurrentLoggedInUserDetails() // If the user is logged in and their session is not expired, then we check if token auth is also being used concurrently. - if err == nil && loggedInDetails.IsUserLoggedIn && !loggedInDetails.LoginExpired { + if !silent && err == nil && loggedInDetails.IsUserLoggedIn && !loggedInDetails.LoginExpired { token, err := util.GetInfisicalToken(cmd) // If token auth is being used concurrently, we warn the user that the token will be used instead of the logged in user's credentials. From 788dcf2c73896e7b4e4d9882faa67313a1692c3d Mon Sep 17 00:00:00 2001 From: Maidul Islam Date: Wed, 18 Sep 2024 09:21:11 -0400 Subject: [PATCH 7/9] Update warning message --- cli/packages/cmd/root.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/packages/cmd/root.go b/cli/packages/cmd/root.go index 1b66d9279..8fb160ad8 100644 --- a/cli/packages/cmd/root.go +++ b/cli/packages/cmd/root.go @@ -68,7 +68,7 @@ func init() { } else { usingFrom = "INFISICAL_TOKEN environment variable" } - util.PrintWarning(fmt.Sprintf("You are currently logged in, but the command will be using the token provided from the %s.", usingFrom)) + util.PrintWarning(fmt.Sprintf("Your logged-in session is being overwritten by the token provided from the %s", usingFrom)) } } From a6497b844aead4df7db03010ec81f55b009fe207 Mon Sep 17 00:00:00 2001 From: Maidul Islam Date: Wed, 18 Sep 2024 09:22:58 -0400 Subject: [PATCH 8/9] remove unneeded comments --- cli/packages/cmd/root.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/cli/packages/cmd/root.go b/cli/packages/cmd/root.go index 8fb160ad8..d45492953 100644 --- a/cli/packages/cmd/root.go +++ b/cli/packages/cmd/root.go @@ -56,11 +56,9 @@ func init() { loggedInDetails, err := util.GetCurrentLoggedInUserDetails() - // If the user is logged in and their session is not expired, then we check if token auth is also being used concurrently. if !silent && err == nil && loggedInDetails.IsUserLoggedIn && !loggedInDetails.LoginExpired { token, err := util.GetInfisicalToken(cmd) - // If token auth is being used concurrently, we warn the user that the token will be used instead of the logged in user's credentials. if err == nil && token != nil { var usingFrom string if token.PassedAsFlag { From cee982754b189759eb5ba937dc8ba443fde7c641 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard Date: Wed, 18 Sep 2024 20:41:21 +0400 Subject: [PATCH 9/9] Requested changes --- cli/packages/cmd/export.go | 8 ++++---- cli/packages/cmd/folder.go | 8 ++++---- cli/packages/cmd/root.go | 9 +-------- cli/packages/cmd/run.go | 8 ++++---- cli/packages/cmd/secrets.go | 26 ++++++++++++-------------- cli/packages/models/cli.go | 6 +++--- cli/packages/util/auth.go | 24 ------------------------ cli/packages/util/helper.go | 16 +++++++++------- 8 files changed, 37 insertions(+), 68 deletions(-) diff --git a/cli/packages/cmd/export.go b/cli/packages/cmd/export.go index cac014834..f6b028b7a 100644 --- a/cli/packages/cmd/export.go +++ b/cli/packages/cmd/export.go @@ -94,9 +94,9 @@ var exportCmd = &cobra.Command{ IncludeImport: includeImports, } - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { request.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { request.UniversalAuthAccessToken = token.Token } @@ -141,9 +141,9 @@ var exportCmd = &cobra.Command{ authParams := models.ExpandSecretsAuthentication{} - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { authParams.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { authParams.UniversalAuthAccessToken = token.Token } diff --git a/cli/packages/cmd/folder.go b/cli/packages/cmd/folder.go index a634abbeb..538f1e2dc 100644 --- a/cli/packages/cmd/folder.go +++ b/cli/packages/cmd/folder.go @@ -53,9 +53,9 @@ var getCmd = &cobra.Command{ FoldersPath: foldersPath, } - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { request.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { request.UniversalAuthAccessToken = token.Token } @@ -125,7 +125,7 @@ var createCmd = &cobra.Command{ WorkspaceId: projectId, } - if util.ShouldUseInfisicalToken(token, nil) { + if token != nil && (token.Type == util.SERVICE_TOKEN_IDENTIFIER || token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER) { params.InfisicalToken = token.Token } @@ -193,7 +193,7 @@ var deleteCmd = &cobra.Command{ FolderPath: folderPath, } - if util.ShouldUseInfisicalToken(token, nil) { + if token != nil && (token.Type == util.SERVICE_TOKEN_IDENTIFIER || token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER) { params.InfisicalToken = token.Token } diff --git a/cli/packages/cmd/root.go b/cli/packages/cmd/root.go index d45492953..e40c07022 100644 --- a/cli/packages/cmd/root.go +++ b/cli/packages/cmd/root.go @@ -60,14 +60,7 @@ func init() { token, err := util.GetInfisicalToken(cmd) if err == nil && token != nil { - var usingFrom string - if token.PassedAsFlag { - usingFrom = "--token flag" - } else { - usingFrom = "INFISICAL_TOKEN environment variable" - } - util.PrintWarning(fmt.Sprintf("Your logged-in session is being overwritten by the token provided from the %s", usingFrom)) - + util.PrintWarning(fmt.Sprintf("Your logged-in session is being overwritten by the token provided from the %s.", token.Source)) } } diff --git a/cli/packages/cmd/run.go b/cli/packages/cmd/run.go index d33d3c2a8..fa5176d89 100644 --- a/cli/packages/cmd/run.go +++ b/cli/packages/cmd/run.go @@ -439,9 +439,9 @@ func executeCommandWithWatchMode(commandFlag string, args []string, watchModeInt func fetchAndFormatSecretsForShell(request models.GetAllSecretsParameters, projectConfigDir string, secretOverriding bool, shouldExpandSecrets bool, token *models.TokenDetails) (models.InjectableEnvironmentResult, error) { - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { request.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { request.UniversalAuthAccessToken = token.Token } @@ -461,9 +461,9 @@ func fetchAndFormatSecretsForShell(request models.GetAllSecretsParameters, proje authParams := models.ExpandSecretsAuthentication{} - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { authParams.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { authParams.UniversalAuthAccessToken = token.Token } diff --git a/cli/packages/cmd/secrets.go b/cli/packages/cmd/secrets.go index d0bbdb596..e2987cc7d 100644 --- a/cli/packages/cmd/secrets.go +++ b/cli/packages/cmd/secrets.go @@ -87,9 +87,9 @@ var secretsCmd = &cobra.Command{ Recursive: recursive, } - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { request.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { request.UniversalAuthAccessToken = token.Token } @@ -106,10 +106,9 @@ var secretsCmd = &cobra.Command{ if shouldExpandSecrets { authParams := models.ExpandSecretsAuthentication{} - - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { authParams.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { authParams.UniversalAuthAccessToken = token.Token } @@ -189,7 +188,7 @@ var secretsSetCmd = &cobra.Command{ } var secretOperations []models.SecretSetOperation - if util.ShouldUseInfisicalToken(token, nil) { + if token != nil && (token.Type == util.SERVICE_TOKEN_IDENTIFIER || token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER) { if projectId == "" { util.PrintErrorMessageAndExit("When using service tokens or machine identities, you must set the --projectId flag") } @@ -283,7 +282,7 @@ var secretsDeleteCmd = &cobra.Command{ projectId = workspaceFile.WorkspaceId } - if util.ShouldUseInfisicalToken(token, nil) { + if token != nil && (token.Type == util.SERVICE_TOKEN_IDENTIFIER || token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER) { httpClient.SetAuthToken(token.Token) } else { util.RequireLogin() @@ -391,9 +390,9 @@ func getSecretsByNames(cmd *cobra.Command, args []string) { Recursive: recursive, } - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { request.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { request.UniversalAuthAccessToken = token.Token } @@ -410,10 +409,9 @@ func getSecretsByNames(cmd *cobra.Command, args []string) { if shouldExpand { authParams := models.ExpandSecretsAuthentication{} - - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { authParams.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { authParams.UniversalAuthAccessToken = token.Token } @@ -487,9 +485,9 @@ func generateExampleEnv(cmd *cobra.Command, args []string) { IncludeImport: true, } - if util.ShouldUseInfisicalToken(token, []string{util.SERVICE_TOKEN_IDENTIFIER}) { + if token != nil && token.Type == util.SERVICE_TOKEN_IDENTIFIER { request.InfisicalToken = token.Token - } else if util.ShouldUseInfisicalToken(token, []string{util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER}) { + } else if token != nil && token.Type == util.UNIVERSAL_AUTH_TOKEN_IDENTIFIER { request.UniversalAuthAccessToken = token.Token } diff --git a/cli/packages/models/cli.go b/cli/packages/models/cli.go index 3a6484e89..62ff07190 100644 --- a/cli/packages/models/cli.go +++ b/cli/packages/models/cli.go @@ -63,9 +63,9 @@ type DynamicSecretLease struct { } type TokenDetails struct { - Type string - Token string - PassedAsFlag bool + Type string + Token string + Source string } type SingleFolder struct { diff --git a/cli/packages/util/auth.go b/cli/packages/util/auth.go index 257d647a3..cdcd7b50a 100644 --- a/cli/packages/util/auth.go +++ b/cli/packages/util/auth.go @@ -1,9 +1,5 @@ package util -import ( - "github.com/Infisical/infisical-merge/packages/models" -) - type AuthStrategyType string var AuthStrategy = struct { @@ -47,23 +43,3 @@ func IsAuthMethodValid(authMethod string, allowUserAuth bool) (isValid bool, str } return false, "" } - -func ShouldUseInfisicalToken(token *models.TokenDetails, validTokenTypes []string) bool { - if token == nil { - return false - } - - // If nil is passed, we assume both service and universal tokens are acceptable. - if validTokenTypes == nil { - validTokenTypes = []string{SERVICE_TOKEN_IDENTIFIER, UNIVERSAL_AUTH_TOKEN_IDENTIFIER} - } - - for _, tokenType := range validTokenTypes { - if token.Type == tokenType { - return true - } - } - - return false - -} diff --git a/cli/packages/util/helper.go b/cli/packages/util/helper.go index bcae127b5..11a1e3e0a 100644 --- a/cli/packages/util/helper.go +++ b/cli/packages/util/helper.go @@ -87,13 +87,15 @@ func GetInfisicalToken(cmd *cobra.Command) (token *models.TokenDetails, err erro return nil, err } - passedAsFlag := infisicalToken != "" + var source = "--token flag" if infisicalToken == "" { // If no flag is passed, we first check for the universal auth access token env variable. infisicalToken = os.Getenv(INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN_NAME) + source = fmt.Sprintf("%s environment variable", INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN_NAME) if infisicalToken == "" { // If it's still empty after the first env check, we check for the service token env variable. infisicalToken = os.Getenv(INFISICAL_TOKEN_NAME) + source = fmt.Sprintf("%s environment variable", INFISICAL_TOKEN_NAME) } } @@ -103,16 +105,16 @@ func GetInfisicalToken(cmd *cobra.Command) (token *models.TokenDetails, err erro if strings.HasPrefix(infisicalToken, "st.") { return &models.TokenDetails{ - Type: SERVICE_TOKEN_IDENTIFIER, - Token: infisicalToken, - PassedAsFlag: passedAsFlag, + Type: SERVICE_TOKEN_IDENTIFIER, + Token: infisicalToken, + Source: source, }, nil } return &models.TokenDetails{ - Type: UNIVERSAL_AUTH_TOKEN_IDENTIFIER, - Token: infisicalToken, - PassedAsFlag: passedAsFlag, + Type: UNIVERSAL_AUTH_TOKEN_IDENTIFIER, + Token: infisicalToken, + Source: source, }, nil }