A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: add secrets in db confiugration (#4522)
Myles Scolnick834844c8f4c6
diff --git a/frontend/src/components/editor/chrome/panels/secrets-panel.tsx b/frontend/src/components/editor/chrome/panels/secrets-panel.tsxindex f24f645688..5e6df9483d 100644--- a/frontend/src/components/editor/chrome/panels/secrets-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/secrets-panel.tsx@@ -18,146 +18,8 @@ import { copyToClipboard } from "@/utils/copy";import { cn } from "@/utils/cn";import { SECRETS_REGISTRY } from "@/core/secrets/request-registry";import { Badge } from "@/components/ui/badge";-import type { ListSecretKeysResponse } from "@/core/network/types";-import { Button } from "@/components/ui/button";import { useImperativeModal } from "@/components/modal/ImperativeModal";-import {- DialogContent,- DialogHeader,- DialogTitle,- DialogDescription,- DialogFooter,-} from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import { writeSecret } from "@/core/network/requests";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import { FormDescription } from "@/components/ui/field";-import { ExternalLink } from "@/components/ui/links";--// dotenv providers should be at the top-function sortProviders(providers: ListSecretKeysResponse["keys"]) {- return providers.sort((a, b) => {- if (a.provider === "env") {- return 1;- }- if (b.provider === "env") {- return -1;- }- return 0;- });-}--const WriteSecretModal: React.FC<{- providerNames: string[];- onClose: () => void;- onSuccess: () => void;-}> = ({ providerNames, onClose, onSuccess }) => {- const [key, setKey] = React.useState("");- const [value, setValue] = React.useState("");- const [location, setLocation] = React.useState(providerNames[0] || ".env");- // Only dotenv is supported for now- const provider = "dotenv";-- const handleSubmit = async (e: React.FormEvent) => {- e.preventDefault();- try {- await writeSecret({- key,- value,- provider,- name: location,- });- toast({- title: "Secret created",- description: "The secret has been created successfully.",- });- onSuccess();- } catch {- toast({- title: "Error",- description: "Failed to create secret. Please try again.",- variant: "danger",- });- }- };-- return (- <DialogContent>- <form onSubmit={handleSubmit}>- <DialogHeader>- <DialogTitle>Add Secret</DialogTitle>- <DialogDescription>- Add a new secret to your environment variables.- </DialogDescription>- </DialogHeader>- <div className="grid gap-4 py-4">- <div className="grid gap-2">- <Label htmlFor="key">Key</Label>- <Input- id="key"- value={key}- onChange={(e) => {- // Remove any whitespace from the input- setKey(e.target.value.replaceAll(/\s+/g, "_"));- }}- placeholder="MY_SECRET_KEY"- required={true}- />- </div>- <div className="grid gap-2">- <Label htmlFor="value">Value</Label>- <Input- id="value"- type="text"- value={value}- onChange={(e) => setValue(e.target.value)}- required={true}- autoComplete="off"- />- </div>- <div className="grid gap-2">- <Label htmlFor="location">Location</Label>- <Select- value={location}- onValueChange={(value) => setLocation(value)}- >- <SelectTrigger>- <SelectValue placeholder="Select a provider" />- </SelectTrigger>- <SelectContent>- {providerNames.map((name) => (- <SelectItem key={name} value={name}>- {name}- </SelectItem>- ))}- </SelectContent>- </Select>- <FormDescription>- You can configure the location by setting the{" "}- <ExternalLink href="https://links.marimo.app/dotenv">- dotenv configuration- </ExternalLink>- .- </FormDescription>- </div>- </div>- <DialogFooter>- <Button type="button" variant="outline" onClick={onClose}>- Cancel- </Button>- <Button type="submit">Add Secret</Button>- </DialogFooter>- </form>- </DialogContent>- );-};+import { sortProviders, WriteSecretModal } from "./write-secret-modal";export const SecretsPanel: React.FC = () => {const { openModal, closeModal } = useImperativeModal();diff --git a/frontend/src/components/editor/chrome/panels/write-secret-modal.tsx b/frontend/src/components/editor/chrome/panels/write-secret-modal.tsxnew file mode 100644index 0000000000..5154efa8e5--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/write-secret-modal.tsx@@ -0,0 +1,145 @@+/* Copyright 2024 Marimo. All rights reserved. */+import React from "react";+import { toast } from "@/components/ui/use-toast";+import { Button } from "@/components/ui/button";+import {+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { writeSecret } from "@/core/network/requests";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { FormDescription } from "@/components/ui/field";+import { ExternalLink } from "@/components/ui/links";+import type { ListSecretKeysResponse } from "@/core/network/types";++// dotenv providers should be at the top+export function sortProviders(providers: ListSecretKeysResponse["keys"]) {+ return providers.sort((a, b) => {+ if (a.provider === "env") {+ return 1;+ }+ if (b.provider === "env") {+ return -1;+ }+ return 0;+ });+}++/**+ * A modal component that allows users to add a new secret+ */+export const WriteSecretModal: React.FC<{+ providerNames: string[];+ onClose: () => void;+ onSuccess: (secretName: string) => void;+}> = ({ providerNames, onClose, onSuccess }) => {+ const [key, setKey] = React.useState("");+ const [value, setValue] = React.useState("");+ const [location, setLocation] = React.useState(providerNames[0] || ".env");+ // Only dotenv is supported for now+ const provider = "dotenv";++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ try {+ await writeSecret({+ key,+ value,+ provider,+ name: location,+ });+ toast({+ title: "Secret created",+ description: "The secret has been created successfully.",+ });+ onSuccess(key);+ } catch {+ toast({+ title: "Error",+ description: "Failed to create secret. Please try again.",+ variant: "danger",+ });+ }+ };++ return (+ <DialogContent>+ <form onSubmit={handleSubmit}>+ <DialogHeader>+ <DialogTitle>Add Secret</DialogTitle>+ <DialogDescription>+ Add a new secret to your environment variables.+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4 py-4">+ <div className="grid gap-2">+ <Label htmlFor="key">Key</Label>+ <Input+ id="key"+ value={key}+ onChange={(e) => {+ // Remove any whitespace from the input+ setKey(e.target.value.replaceAll(/\s+/g, "_"));+ }}+ placeholder="MY_SECRET_KEY"+ required={true}+ />+ </div>+ <div className="grid gap-2">+ <Label htmlFor="value">Value</Label>+ <Input+ id="value"+ type="text"+ value={value}+ onChange={(e) => setValue(e.target.value)}+ required={true}+ autoComplete="off"+ />+ </div>+ <div className="grid gap-2">+ <Label htmlFor="location">Location</Label>+ <Select+ value={location}+ onValueChange={(value) => setLocation(value)}+ >+ <SelectTrigger>+ <SelectValue placeholder="Select a provider" />+ </SelectTrigger>+ <SelectContent>+ {providerNames.map((name) => (+ <SelectItem key={name} value={name}>+ {name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ You can configure the location by setting the{" "}+ <ExternalLink href="https://links.marimo.app/dotenv">+ dotenv configuration+ </ExternalLink>+ .+ </FormDescription>+ </div>+ </div>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={onClose}>+ Cancel+ </Button>+ <Button type="submit">Add Secret</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ );+};diff --git a/frontend/src/components/editor/database/form-renderers.tsx b/frontend/src/components/editor/database/form-renderers.tsxindex bafbc0b477..860eadf252 100644--- a/frontend/src/components/editor/database/form-renderers.tsx+++ b/frontend/src/components/editor/database/form-renderers.tsx@@ -12,11 +12,13 @@ import {} from "@/components/ui/form";import { Input } from "@/components/ui/input";import { SECRETS_REGISTRY } from "@/core/secrets/request-registry";-import { KeyIcon } from "lucide-react";+import { KeyIcon, PlusCircleIcon } from "lucide-react";import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { Button } from "@/components/ui/button";@@ -28,8 +30,15 @@ import { createContext, useContext, type ReactNode } from "react";import { Functions } from "@/utils/functions";import { NumberField } from "@/components/ui/number-field";import { displaySecret, isSecret, prefixSecret } from "./secrets";+import { partition } from "lodash-es";+import { useImperativeModal } from "@/components/modal/ImperativeModal";+import {+ sortProviders,+ WriteSecretModal,+} from "../chrome/panels/write-secret-modal";interface SecretsContextType {+ providerNames: string[];secretKeys: string[];loading: boolean;error: Error | undefined;@@ -37,6 +46,7 @@ interface SecretsContextType {}const SecretsContext = createContext<SecretsContextType>({+ providerNames: [],secretKeys: [],loading: false,error: undefined,@@ -50,19 +60,28 @@ interface SecretsProviderProps {}export const SecretsProvider = ({ children }: SecretsProviderProps) => {- const {- data: secretKeys = [],- loading,- error,- reload,- } = useAsyncData(async () => {+ const { data, loading, error, reload } = useAsyncData(async () => {const result = await SECRETS_REGISTRY.request({});- return result.secrets.flatMap((secret) => secret.keys).sort();+ // Provider names without 'env' provider+ const providerNames = sortProviders(result.secrets)+ .filter((provider) => provider.provider !== "env")+ .map((provider) => provider.name);++ return {+ secretKeys: result.secrets.flatMap((secret) => secret.keys).sort(),+ providerNames: providerNames,+ };}, []);return (<SecretsContext.Provider- value={{ secretKeys, loading, error, refreshSecrets: reload }}+ value={{+ secretKeys: data?.secretKeys || [],+ providerNames: data?.providerNames || [],+ loading,+ error,+ refreshSecrets: reload,+ }}>{children}</SecretsContext.Provider>@@ -80,7 +99,8 @@ export const ENV_RENDERER: FormRenderer<z.ZodString | z.ZodNumber> = {return false;},Component: ({ schema, form, path }) => {- const { secretKeys } = useSecrets();+ const { secretKeys, providerNames, refreshSecrets } = useSecrets();+ const { openModal, closeModal } = useImperativeModal();const {label,@@ -88,7 +108,7 @@ export const ENV_RENDERER: FormRenderer<z.ZodString | z.ZodNumber> = {optionRegex = "",} = FieldOptions.parse(schema._def.description || "");- const filteredSecretKeys = secretKeys.filter((key) =>+ const [recommendedKeys, otherKeys] = partition(secretKeys, (key) =>new RegExp(optionRegex, "i").test(key),);@@ -117,34 +137,65 @@ export const ENV_RENDERER: FormRenderer<z.ZodString | z.ZodNumber> = {className="flex-1"/>)}- {filteredSecretKeys.length > 0 && (- <DropdownMenu>- <DropdownMenuTrigger asChild={true}>- <Button- variant="outline"- size="icon"- className={cn(- isSecret(field.value as string) && "bg-accent",- )}- >- <KeyIcon className="h-3 w-3" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent- align="end"- className="max-h-60 overflow-y-auto"+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>+ <Button+ variant="outline"+ size="icon"+ className={cn(+ isSecret(field.value as string) && "bg-accent",+ )}>- {filteredSecretKeys.map((key) => (- <DropdownMenuItem- key={key}- onSelect={() => field.onChange(prefixSecret(key))}- >- {displaySecret(key)}- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- )}+ <KeyIcon className="h-3 w-3" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="max-h-60 overflow-y-auto"+ >+ <DropdownMenuItem+ onSelect={() => {+ openModal(+ <WriteSecretModal+ providerNames={providerNames}+ onSuccess={(secretKey) => {+ refreshSecrets();+ field.onChange(prefixSecret(secretKey));+ closeModal();+ }}+ onClose={closeModal}+ />,+ );+ }}+ >+ <PlusCircleIcon className="mr-2 h-3.5 w-3.5" />+ Create a new secret+ </DropdownMenuItem>+ {recommendedKeys.length > 0 && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuLabel>Recommended</DropdownMenuLabel>+ </>+ )}+ {recommendedKeys.map((key) => (+ <DropdownMenuItem+ key={key}+ onSelect={() => field.onChange(prefixSecret(key))}+ >+ {displaySecret(key)}+ </DropdownMenuItem>+ ))}+ {otherKeys.length > 0 && <DropdownMenuSeparator />}+ {otherKeys.map((key) => (+ <DropdownMenuItem+ key={key}+ onSelect={() => field.onChange(prefixSecret(key))}+ >+ {displaySecret(key)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu></div></FormControl><FormMessage />diff --git a/pyproject.toml b/pyproject.tomlindex 8ae2af6a18..3900caa7b8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -522,7 +522,7 @@ dataframes = "rich"watcher_on_save = "autorun"output_max_bytes = 10_000_000std_stream_max_bytes = 2_000_000-dotenv = [".env.testing"]+dotenv = [".env"][tool.marimo.keymap]vimrc = "configs/.vimrc"