Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SecretSourceInput.tsx

327 lines12.3 KB

1import {
2 SecretReference,
3 type EnvironmentId,
4 type SecretProviderConfig,
5 type SecretProviderId,
6 type SecretProviderKind,
7} from "@t3tools/contracts";
8import { builtInSecretProviderDefinitions } from "@t3tools/secret-provider-definitions/registry";
9import { useAtomValue } from "@effect/atom-react";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import { AlertTriangleIcon, CheckIcon, KeyRoundIcon, RefreshCwIcon, TypeIcon } from "lucide-react";
13import { useState, type ComponentProps, type ComponentType, type ReactNode } from "react";
14​
15import { isSecretsFeatureEnabled } from "../../env";
16import { useEnvironmentSettings } from "../../hooks/useSettings";
17import { OnePasswordIcon } from "../Icons";
18import { serverEnvironment } from "../../state/server";
19import { useAtomCommand } from "../../state/use-atom-command";
20import { Button } from "../ui/button";
21import { DraftInput } from "../ui/draft-input";
22import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
23import { Spinner } from "../ui/spinner";
24import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
25import { SecretInput } from "./SecretInput";
26import { classifySecretProvider } from "./SecretProviderDialog.logic";
27​
28export interface SecretSource {
29 readonly id: SecretProviderId;
30 readonly kind: SecretProviderKind;
31 readonly label: string;
33​
34const NO_SECRET_SOURCES: ReadonlyArray<SecretSource> = [];
35const STORED_VALUE = "__stored__";
36const decodeSecretReference = Schema.decodeUnknownOption(SecretReference);
37​
38/** Secret providers a setting can point at; empty when the environment cannot read references. */
39export function useSecretSources(environmentId: EnvironmentId): ReadonlyArray<SecretSource> {
40 const providers = useEnvironmentSettings(environmentId, (settings) => settings.secretProviders);
41 const supported = useAtomValue(
42 serverEnvironment.configValueAtom(environmentId),
43 (config) => config?.secretReferences === true,
44 );
45 if (!isSecretsFeatureEnabled || !supported) return NO_SECRET_SOURCES;
46 return (Object.entries(providers) as Array<[SecretProviderId, SecretProviderConfig]>)
47 .filter(([, config]) => classifySecretProvider(config).kind !== "unsupported")
48 .map(([id, config]) => ({ id, kind: config.kind, label: config.label }));
50​
51function SourceIcon(props: { readonly icon: ComponentType<{ readonly className?: string }> }) {
52 return <props.icon className="size-3.5 shrink-0" />;
54​
55function SourceLabel(props: {
56 readonly icon: ComponentType<{ readonly className?: string }>;
57 readonly label: string;
58}) {
59 return (
60 <span className="flex min-w-0 items-center gap-1.5">
61 <props.icon className="size-3.5 shrink-0" />
62 <span className="truncate">{props.label}</span>
63 </span>
64 );
66​
67/** Picks Value (`null`) or one of `sources`; a `value` no longer among them stays listed. */
68export function SecretSourceSelect(props: {
69 readonly value: SecretProviderId | null;
70 readonly sources: ReadonlyArray<Pick<SecretSource, "id" | "label">>;
71 readonly label: string;
72 readonly disabled?: boolean;
73 readonly onValueChange: (provider: SecretProviderId | null) => void;
74}) {
75 const { value, sources } = props;
76 const known = value === null || sources.some((source) => source.id === value);
77 const title =
78 value === null ? "Value" : (sources.find((source) => source.id === value)?.label ?? value);
79 return (
80 <Select
81 value={value ?? STORED_VALUE}
82 onValueChange={(next) =>
83 props.onValueChange(
84 next === STORED_VALUE || next === null ? null : (next as SecretProviderId),
85 )
86 }
87 {...(props.disabled === undefined ? {} : { disabled: props.disabled })}
88 >
89 <SelectTrigger
90 size="sm"
91 className="w-auto min-w-0 shrink-0"
92 aria-label={`${props.label} source`}
93 title={title}
94 >
95 <SelectValue>
96 <SourceIcon icon={value === null ? TypeIcon : known ? OnePasswordIcon : KeyRoundIcon} />
97 </SelectValue>
98 </SelectTrigger>
99 <SelectPopup align="start" alignItemWithTrigger={false}>
100 <SelectItem value={STORED_VALUE}>
101 <SourceLabel icon={TypeIcon} label="Value" />
102 </SelectItem>
103 {sources.map((source) => (
104 <SelectItem key={source.id} value={source.id}>
105 <SourceLabel icon={OnePasswordIcon} label={source.label} />
106 </SelectItem>
107 ))}
108 {known ? null : (
109 <SelectItem value={value}>
110 <SourceLabel icon={KeyRoundIcon} label={value} />
111 </SelectItem>
112 )}
113 </SelectPopup>
114 </Select>
115 );
117​
118type SecretCheck =
119 | { readonly status: "checking" }
120 | { readonly status: "resolved" }
121 | { readonly status: "failed"; readonly detail: string };
122​
123/** Asks the server to resolve the committed reference, so a typo shows here and not at provider start. */
124function SecretCheckButton(props: {
125 readonly environmentId: EnvironmentId;
126 readonly secret: SecretReference;
127 readonly label: string;
128 readonly disabled?: boolean | undefined;
129}) {
130 const { environmentId, secret } = props;
131 const supported = useAtomValue(
132 serverEnvironment.configValueAtom(environmentId),
133 (config) => config?.environment.capabilities.secretSourceCheck === true,
134 );
135 const canCheck = useAtomValue(serverEnvironment.checkSecretSource.permissionAtom(environmentId));
136 const checkSecretSource = useAtomCommand(serverEnvironment.checkSecretSource);
137 const secretKey = `${secret.provider}\u0000${secret.reference}`;
138 const [check, setCheck] = useState<{
139 readonly secretKey: string;
140 readonly state: SecretCheck;
141 } | null>(null);
142 const state = check?.secretKey === secretKey ? check.state : undefined;
143​
144 const run = async () => {
145 setCheck({ secretKey, state: { status: "checking" } });
146 const response = await checkSecretSource({ environmentId, input: { source: secret } });
147 const next: SecretCheck =
148 response._tag !== "Success"
149 ? { status: "failed", detail: "Could not reach the server" }
150 : response.value._tag === "Resolved"
151 ? { status: "resolved" }
152 : { status: "failed", detail: response.value.detail };
153 setCheck((previous) =>
154 previous?.secretKey === secretKey ? { secretKey, state: next } : previous,
155 );
156 };
157​
158 if (!supported) return null;
159 const description = !canCheck
160 ? "You cannot check secrets on this environment"
161 : state === undefined
162 ? "Check that the secret resolves"
163 : state.status === "checking"
164 ? "Checking the secret"
165 : state.status === "resolved"
166 ? "Secret resolved"
167 : state.detail;
168 return (
169 <Tooltip>
170 <TooltipTrigger
171 render={
172 <span className="inline-flex">
173 <Button
174 type="button"
175 size="icon-micro"
176 variant="ghost-muted"
177 disabled={props.disabled === true || !canCheck || state?.status === "checking"}
178 onClick={() => void run()}
179 aria-label={
180 state?.status === "failed"
181 ? `${props.label} failed: ${state.detail}`
182 : state?.status === "resolved"
183 ? `${props.label} resolved`
184 : props.label
185 }
186 >
187 {state?.status === "checking" ? (
188 <Spinner />
189 ) : state?.status === "resolved" ? (
190 <CheckIcon className="text-success-foreground" />
191 ) : state?.status === "failed" ? (
192 <AlertTriangleIcon className="text-destructive" />
193 ) : (
194 <RefreshCwIcon />
195 )}
196 </Button>
197 </span>
198 }
199 />
200 <TooltipPopup side="top">{description}</TooltipPopup>
201 </Tooltip>
202 );
204​
205type SecretSourceInputProps = Omit<ComponentProps<typeof SecretInput>, "value" | "children"> & {
206 readonly value: string | SecretReference;
207 /** Offers a check of the committed reference on this environment. */
208 readonly environmentId?: EnvironmentId | undefined;
209 readonly sources: ReadonlyArray<SecretSource>;
210 readonly onSecretChange: (secret: SecretReference | undefined) => void;
211 /** Whether the selected source and committed field can be saved or used. */
212 readonly onValidityChange?: (valid: boolean) => void;
213 /** Places the parts in the caller's layout; `source` is null when there is nothing to pick. */
214 readonly children?: (parts: {
215 readonly source: ReactNode;
216 readonly value: ReactNode;
217 }) => ReactNode;
218};
219​
220/** A secret entered here, or read from a secret provider when one is configured. */
221export function SecretSourceInput({
222 value,
223 environmentId,
224 sources,
225 onSecretChange,
226 onValidityChange,
227 children,
228 ...rest
229}: SecretSourceInputProps) {
230 // A provider picked here applies once a reference for it is committed.
231 const [pendingProvider, setPendingProvider] = useState<SecretProviderId | null>(null);
232 const [rejectedReference, setRejectedReference] = useState<string | null>(null);
233 const secret = typeof value === "string" ? undefined : value;
234 const input = { ...rest, value: typeof value === "string" ? value : "" };
235 const provider = pendingProvider ?? secret?.provider ?? null;
236 const reference = secret !== undefined && secret.provider === provider ? secret.reference : "";
237 const providerSource = sources.find((source) => source.id === provider);
238 const definition = providerSource && builtInSecretProviderDefinitions.find(providerSource.kind);
239 const label = input["aria-label"] ?? "Secret";
240 const source =
241 sources.length === 0 && provider === null ? null : (
242 <SecretSourceSelect
243 value={provider}
244 sources={sources}
245 label={label}
246 onValueChange={(next) => {
247 setRejectedReference(null);
248 if (next === null) {
249 setPendingProvider(null);
250 onValidityChange?.(true);
251 if (secret !== undefined) onSecretChange(undefined);
252 return;
253 }
254 onValidityChange?.(next === secret?.provider);
255 setPendingProvider(next === secret?.provider ? null : next);
256 }}
257 />
258 );
259​
260 const valueField =
261 provider === null ? (
262 <SecretInput {...input} />
263 ) : (
264 <div className="flex min-w-0 flex-1 flex-col gap-1">
265 <div className="flex min-w-0 items-center gap-1.5">
266 <DraftInput
267 {...(input.id !== undefined ? { id: input.id } : {})}
268 size="sm"
269 font="mono"
270 className="min-w-0 flex-1"
271 value={rejectedReference ?? reference}
272 onCommit={(next) => {
273 if (next.trim().length === 0) {
274 setRejectedReference(null);
275 onValidityChange?.(pendingProvider === null && secret !== undefined);
276 if (pendingProvider === null && secret !== undefined) onSecretChange(undefined);
277 return;
278 }
279 const decoded = decodeSecretReference({ provider, reference: next });
280 if (
281 Option.isNone(decoded) ||
282 definition?.isReference(decoded.value.reference) === false
283 ) {
284 setRejectedReference(next);
285 onValidityChange?.(false);
286 return;
287 }
288 setRejectedReference(null);
289 setPendingProvider(null);
290 onValidityChange?.(true);
291 onSecretChange(decoded.value);
292 }}
293 autoComplete="off"
294 placeholder={definition?.referencePlaceholder}
295 spellCheck={false}
296 aria-label={`${label} reference`}
297 aria-invalid={rejectedReference !== null}
298 />
299 {environmentId !== undefined &&
300 secret !== undefined &&
301 pendingProvider === null &&
302 rejectedReference === null ? (
303 <SecretCheckButton
304 environmentId={environmentId}
305 secret={secret}
306 label={`Check ${label}`}
307 disabled={input.disabled}
308 />
309 ) : null}
310 </div>
311 {rejectedReference !== null ? (
312 <p className="text-2xs text-destructive">
313 {definition?.invalidReferenceMessage ?? "Enter a valid secret reference."}
314 </p>
315 ) : null}
316 </div>
317 );
318​
319 if (children !== undefined) return children({ source, value: valueField });
320 if (source === null) return valueField;
321 return (
322 <div className="flex min-w-0 flex-1 items-start gap-1.5">
323 {source}
324 {valueField}
325 </div>
326 );