History

openapi: per-user OAuth connections pane in EditOpenApiSource

- Edit page gains a Connections section with one row per OAuth2 auth, showing per-user connection status (secretStatusAtom), connect (startOpenApiOAuth) and disconnect (removeSecret) actions so different users in the same org can manage their own tokens independently. - Add page sends deterministic ${slug}_access_token/_refresh_token ids in startOAuth, renders the copyable redirect URL, exports the shared OAuth constants, and swaps to the CreatableSecretPicker.

Rhys Sullivan committed 6 months ago

Commit 1a925861 parent fe5f1b15 files · +391 −12Browse files

Unified · Split

5 files
  1. packages/plugins/openapi/src/react/AddOpenApiSource.tsx +29 −6
  2. packages/plugins/openapi/src/react/EditOpenApiSource.tsx +339 −4
  3. packages/plugins/openapi/src/sdk/invoke.ts +7 −2
  4. packages/plugins/openapi/src/sdk/store.ts +3 −0
  5. packages/plugins/openapi/src/sdk/types.ts +13 −0
packages/plugins/openapi/src/react/AddOpenApiSource.tsx+29−6
@@ -4,12 +4,12 @@ import { Option } from "effect"; · 3 unmodified lines
44
55 import { openOAuthPopup, type OAuthPopupResult } from "@executor/plugin-oauth2/react";
66
7−import { SecretPicker } from "@executor/react/plugins/secret-picker";
87 import { useScope } from "@executor/react/api/scope-context";
98 import { sourceWriteKeys } from "@executor/react/api/reactivity-keys";
109 import { usePendingSources } from "@executor/react/api/optimistic";
1110 import { HeadersList } from "@executor/react/plugins/headers-list";
1211 import {
12+ CreatableSecretPicker,
1313 matchPresetKey,
1414 type HeaderState,
1515 } from "@executor/react/plugins/secret-header-auth";
@@ -20,6 +20,7 @@ import { · 4 unmodified lines
2020 } from "@executor/react/plugins/source-identity";
2121 import { useSecretPickerSecrets } from "@executor/react/plugins/use-secret-picker-secrets";
2222 import { Button } from "@executor/react/components/button";
23+import { CopyButton } from "@executor/react/components/copy-button";
2324 import {
2425 CardStack,
2526 CardStackContent,
@@ -56,8 +57,9 @@ import { · 30 unmodified lines
5657 type ServerVariable,
5758 } from "../sdk/types";
5859
59−const OPENAPI_OAUTH_CHANNEL = "executor:openapi-oauth-result";
60−const OPENAPI_OAUTH_POPUP_NAME = "openapi-oauth";
60+export const OPENAPI_OAUTH_CHANNEL = "executor:openapi-oauth-result";
61+export const OPENAPI_OAUTH_POPUP_NAME = "openapi-oauth";
62+export const OPENAPI_OAUTH_CALLBACK_PATH = "/api/openapi/oauth/callback";
6163
6264 // Stable secret ids for the access/refresh tokens a given OAuth2 security
6365 // scheme on a given source mints. The same ids must be passed into
@@ -259,6 +261,10 @@ export default function AddOpenApiSource(props: { · 195 unmodified lines
259261 const customHeadersValid = customHeaders.every((ch) => ch.name.trim() && ch.secretId);
260262
261263 const oauth2Presets: readonly OAuth2Preset[] = preview?.oauth2Presets ?? [];
264+ const oauth2RedirectUrl =
265+ typeof window !== "undefined"
266+ ? `${window.location.origin}${OPENAPI_OAUTH_CALLBACK_PATH}`
267+ : OPENAPI_OAUTH_CALLBACK_PATH;
262268 const selectedOAuth2Preset: OAuth2Preset | null =
263269 strategy.kind === "oauth2" ? (oauth2Presets[strategy.presetIndex] ?? null) : null;
264270
@@ -391,7 +397,7 @@ export default function AddOpenApiSource(props: { · 126 unmodified lines
391397 flow: "authorizationCode",
392398 authorizationUrl: Option.getOrElse(selectedOAuth2Preset.authorizationUrl, () => ""),
393399 tokenUrl: selectedOAuth2Preset.tokenUrl,
394− redirectUrl: `${window.location.origin}/api/openapi/oauth/callback`,
400+ redirectUrl: oauth2RedirectUrl,
395401 clientIdSecretId: oauth2ClientIdSecretId,
396402 clientSecretSecretId: oauth2ClientSecretSecretId,
397403 scopes: [...oauth2SelectedScopes],
@@ -453,6 +459,7 @@ export default function AddOpenApiSource(props: { · 55 unmodified lines
453459 oauth2ClientIdSecretId,
454460 oauth2ClientSecretSecretId,
455461 oauth2SelectedScopes,
462+ oauth2RedirectUrl,
456463 preview,
457464 doStartOAuth,
458465 scopeId,
@@ -819,15 +826,29 @@ export default function AddOpenApiSource(props: { · 360 unmodified lines
819826 {/* OAuth2 configuration */}
820827 {selectedOAuth2Preset && (
821828 <div className="space-y-3 rounded-lg border border-border/60 bg-muted/10 p-3">
829+ <div className="space-y-1.5">
830+ <FieldLabel className="text-[11px]">
831+ Redirect URL{" "}
832+ <span className="text-muted-foreground">
833+ · add this to your OAuth app's allowed redirects
834+ </span>
835+ </FieldLabel>
836+ <div className="flex items-center gap-1 rounded-md border border-border bg-background/50 px-2.5 py-1.5 font-mono text-[11px]">
837+ <span className="truncate flex-1 text-foreground">{oauth2RedirectUrl}</span>
838+ <CopyButton value={oauth2RedirectUrl} />
839+ </div>
840+ </div>
822841 <div className="space-y-1.5">
823842 <FieldLabel className="text-[11px]">Client ID secret</FieldLabel>
824− <SecretPicker
843+ <CreatableSecretPicker
825844 value={oauth2ClientIdSecretId}
826845 onSelect={(id: string) => {
827846 setOauth2ClientIdSecretId(id);
828847 setOauth2Auth(null);
829848 }}
830849 secrets={secretList}
850+ sourceName={identity.name}
851+ secretLabel="Client ID"
831852 />
832853 </div>
833854 <div className="space-y-1.5">
@@ -837,13 +858,15 @@ export default function AddOpenApiSource(props: { · 3 unmodified lines
837858 · optional for public clients with PKCE
838859 </span>
839860 </FieldLabel>
840− <SecretPicker
861+ <CreatableSecretPicker
841862 value={oauth2ClientSecretSecretId}
842863 onSelect={(id: string) => {
843864 setOauth2ClientSecretSecretId(id);
844865 setOauth2Auth(null);
845866 }}
846867 secrets={secretList}
868+ sourceName={identity.name}
869+ secretLabel="Client Secret"
847870 />
848871 </div>
849872 <div className="space-y-1.5">
packages/plugins/openapi/src/react/EditOpenApiSource.tsx+339−4
@@ -1,8 +1,30 @@
1−import { useState } from "react";
2−import { useAtomValue, useAtomSet, Result } from "@effect-atom/atom-react";
3−import { openApiSourceAtom, updateOpenApiSource } from "./atoms";
1+import { useCallback, useEffect, useRef, useState } from "react";
2+import {
3+ useAtomValue,
4+ useAtomSet,
5+ useAtomRefresh,
6+ Result,
7+} from "@effect-atom/atom-react";
8+import { Option } from "effect";
9+
10+import { SecretId } from "@executor/sdk";
11+import { openOAuthPopup, type OAuthPopupResult } from "@executor/plugin-oauth2/react";
12+
13+import {
14+ openApiSourceAtom,
15+ previewOpenApiSpec,
16+ startOpenApiOAuth,
17+ updateOpenApiSource,
18+} from "./atoms";
419 import { useScope } from "@executor/react/api/scope-context";
5−import { sourceWriteKeys } from "@executor/react/api/reactivity-keys";
20+import {
21+ secretStatusAtom,
22+ removeSecret,
23+} from "@executor/react/api/atoms";
24+import {
25+ secretWriteKeys,
26+ sourceWriteKeys,
27+} from "@executor/react/api/reactivity-keys";
628 import { useSecretPickerSecrets } from "@executor/react/plugins/use-secret-picker-secrets";
729 import {
830 headerValueToState,
@@ -23,8 +45,306 @@ import { · 14 unmodified lines
2345 import { FieldLabel } from "@executor/react/components/field";
2446 import { Input } from "@executor/react/components/input";
2547 import { Badge } from "@executor/react/components/badge";
48+import { Spinner } from "@executor/react/components/spinner";
49+import {
50+ OPENAPI_OAUTH_CALLBACK_PATH,
51+ OPENAPI_OAUTH_CHANNEL,
52+ OPENAPI_OAUTH_POPUP_NAME,
53+} from "./AddOpenApiSource";
54+import type { SpecPreview, OAuth2Preset } from "../sdk/preview";
55+import { OAuth2Auth } from "../sdk/types";
2656 import type { StoredSourceSchemaType } from "../sdk/store";
2757
58+// ---------------------------------------------------------------------------
59+// Connections — one row per OAuth2Auth on the source
60+// ---------------------------------------------------------------------------
61+
62+/**
63+ * Single OAuth2Auth connection row. Each org member sees the status of
64+ * their own tokens (access/refresh secrets resolve via per-user scope
65+ * fall-through) and can trigger the same OAuth flow another member used
66+ * when first onboarding the source.
67+ */
68+function ConnectionRow(props: {
69+ readonly auth: OAuth2Auth;
70+ readonly sourceName: string;
71+ readonly preset: OAuth2Preset | null;
72+ readonly previewError: string | null;
73+}) {
74+ const scopeId = useScope();
75+ const { auth, preset } = props;
76+
77+ const statusAtom = secretStatusAtom(
78+ scopeId,
79+ SecretId.make(auth.accessTokenSecretId),
80+ );
81+ const accessStatus = useAtomValue(statusAtom);
82+ const refreshStatus = useAtomRefresh(statusAtom);
83+ const isConnected =
84+ Result.isSuccess(accessStatus) && accessStatus.value.status === "resolved";
85+
86+ const doStartOAuth = useAtomSet(startOpenApiOAuth, { mode: "promise" });
87+ const doRemoveSecret = useAtomSet(removeSecret, { mode: "promise" });
88+
89+ const [busy, setBusy] = useState(false);
90+ const [error, setError] = useState<string | null>(null);
91+ const cleanupRef = useRef<(() => void) | null>(null);
92+
93+ useEffect(() => () => cleanupRef.current?.(), []);
94+
95+ const redirectUrl =
96+ typeof window !== "undefined"
97+ ? `${window.location.origin}${OPENAPI_OAUTH_CALLBACK_PATH}`
98+ : OPENAPI_OAUTH_CALLBACK_PATH;
99+
100+ const handleConnect = useCallback(async () => {
101+ if (!preset) return;
102+ cleanupRef.current?.();
103+ cleanupRef.current = null;
104+ setBusy(true);
105+ setError(null);
106+ try {
107+ const response = await doStartOAuth({
108+ path: { scopeId },
109+ payload: {
110+ displayName: props.sourceName || auth.securitySchemeName,
111+ securitySchemeName: auth.securitySchemeName,
112+ flow: "authorizationCode",
113+ authorizationUrl: Option.getOrElse(preset.authorizationUrl, () => ""),
114+ tokenUrl: auth.tokenUrl,
115+ redirectUrl,
116+ clientIdSecretId: auth.clientIdSecretId,
117+ clientSecretSecretId: auth.clientSecretSecretId,
118+ // Reuse the source-wide scopes granted at onboarding time —
119+ // per-member connects should land the same capabilities.
120+ scopes: [...auth.scopes],
121+ // Reuse the same secret ids the source already references.
122+ // On completeOAuth the plugin writes tokens at the innermost
123+ // (per-user) scope by default; same id + inner scope shadows
124+ // any org-level fallback so each member's bearer is theirs.
125+ accessTokenSecretId: auth.accessTokenSecretId,
126+ refreshTokenSecretId: auth.refreshTokenSecretId,
127+ },
128+ });
129+
130+ cleanupRef.current = openOAuthPopup<OAuth2Auth>({
131+ url: response.authorizationUrl,
132+ popupName: OPENAPI_OAUTH_POPUP_NAME,
133+ channelName: OPENAPI_OAUTH_CHANNEL,
134+ onResult: (result: OAuthPopupResult<OAuth2Auth>) => {
135+ cleanupRef.current = null;
136+ setBusy(false);
137+ if (result.ok) {
138+ setError(null);
139+ // completeOAuth ran server-side (inside the popup's callback
140+ // HTML handler) and wrote the access/refresh tokens via
141+ // ctx.secrets.set — that bypasses our atom-layer mutation,
142+ // so we refresh the status atom here to flip the badge.
143+ refreshStatus();
144+ } else {
145+ setError(result.error);
146+ }
147+ },
148+ onClosed: () => {
149+ cleanupRef.current = null;
150+ setBusy(false);
151+ setError("OAuth cancelled — popup was closed before completing the flow.");
152+ },
153+ onOpenFailed: () => {
154+ cleanupRef.current = null;
155+ setBusy(false);
156+ setError("OAuth popup was blocked by the browser");
157+ },
158+ });
159+ } catch (e) {
160+ setBusy(false);
161+ setError(e instanceof Error ? e.message : "Failed to start OAuth");
162+ }
163+ }, [
164+ preset,
165+ auth.securitySchemeName,
166+ auth.tokenUrl,
167+ auth.clientIdSecretId,
168+ auth.clientSecretSecretId,
169+ auth.accessTokenSecretId,
170+ auth.refreshTokenSecretId,
171+ auth.scopes,
172+ doStartOAuth,
173+ redirectUrl,
174+ scopeId,
175+ props.sourceName,
176+ refreshStatus,
177+ ]);
178+
179+ const handleDisconnect = useCallback(async () => {
180+ setBusy(true);
181+ setError(null);
182+ try {
183+ await doRemoveSecret({
184+ path: {
185+ scopeId,
186+ secretId: SecretId.make(auth.accessTokenSecretId),
187+ },
188+ reactivityKeys: secretWriteKeys,
189+ });
190+ if (auth.refreshTokenSecretId) {
191+ await doRemoveSecret({
192+ path: {
193+ scopeId,
194+ secretId: SecretId.make(auth.refreshTokenSecretId),
195+ },
196+ reactivityKeys: secretWriteKeys,
197+ }).catch(() => {
198+ // The refresh secret may not exist for this user — ignore.
199+ });
200+ }
201+ } catch (e) {
202+ setError(e instanceof Error ? e.message : "Failed to disconnect");
203+ } finally {
204+ setBusy(false);
205+ }
206+ }, [
207+ doRemoveSecret,
208+ scopeId,
209+ auth.accessTokenSecretId,
210+ auth.refreshTokenSecretId,
211+ ]);
212+
213+ const canConnect = preset !== null && Option.isSome(preset.authorizationUrl);
214+
215+ return (
216+ <div className="flex flex-col gap-2 rounded-lg border border-border/60 bg-background/40 p-3">
217+ <div className="flex items-center justify-between gap-3">
218+ <div className="min-w-0 flex-1">
219+ <div className="text-xs font-medium text-foreground">
220+ {auth.securitySchemeName}
221+ </div>
222+ <div className="mt-0.5 text-[10px] text-muted-foreground">
223+ {auth.scopes.length} scope{auth.scopes.length === 1 ? "" : "s"}
224+ </div>
225+ </div>
226+ {isConnected ? (
227+ <Badge
228+ variant="outline"
229+ className="border-green-500/30 bg-green-500/5 text-green-700 dark:text-green-400"
230+ >
231+ Connected
232+ </Badge>
233+ ) : (
234+ <Badge variant="outline" className="text-muted-foreground">
235+ Not connected
236+ </Badge>
237+ )}
238+ </div>
239+
240+ <div className="flex items-center justify-end gap-2">
241+ {isConnected ? (
242+ <Button
243+ variant="ghost"
244+ size="sm"
245+ onClick={handleDisconnect}
246+ disabled={busy}
247+ >
248+ {busy && <Spinner className="size-3.5" />}
249+ Disconnect
250+ </Button>
251+ ) : (
252+ <Button
253+ variant="secondary"
254+ size="sm"
255+ onClick={handleConnect}
256+ disabled={busy || !canConnect}
257+ >
258+ {busy && <Spinner className="size-3.5" />}
259+ Connect
260+ </Button>
261+ )}
262+ </div>
263+
264+ {!canConnect && props.previewError && (
265+ <p className="text-[11px] text-amber-600 dark:text-amber-400">
266+ {props.previewError}
267+ </p>
268+ )}
269+ {!canConnect && !props.previewError && preset === null && (
270+ <p className="text-[11px] text-muted-foreground">
271+ Loading OAuth configuration…
272+ </p>
273+ )}
274+ {error && (
275+ <div className="rounded-md border border-destructive/30 bg-destructive/5 px-2.5 py-1.5">
276+ <p className="text-[11px] text-destructive">{error}</p>
277+ </div>
278+ )}
279+ </div>
280+ );
281+}
282+
283+function ConnectionsSection(props: {
284+ readonly sourceName: string;
285+ readonly spec: string;
286+ readonly oauth2Entries: readonly OAuth2Auth[];
287+}) {
288+ const scopeId = useScope();
289+ const doPreview = useAtomSet(previewOpenApiSpec, { mode: "promise" });
290+ const [preview, setPreview] = useState<SpecPreview | null>(null);
291+ const [previewError, setPreviewError] = useState<string | null>(null);
292+
293+ useEffect(() => {
294+ let cancelled = false;
295+ doPreview({ path: { scopeId }, payload: { spec: props.spec } })
296+ .then((result) => {
297+ if (!cancelled) setPreview(result);
298+ })
299+ .catch((e: unknown) => {
300+ if (!cancelled) {
301+ setPreviewError(
302+ e instanceof Error
303+ ? `Couldn't load OAuth config from spec: ${e.message}`
304+ : "Couldn't load OAuth config from spec",
305+ );
306+ }
307+ });
308+ return () => {
309+ cancelled = true;
310+ };
311+ }, [doPreview, scopeId, props.spec]);
312+
313+ const presetFor = (securitySchemeName: string): OAuth2Preset | null => {
314+ if (!preview) return null;
315+ return (
316+ preview.oauth2Presets.find(
317+ (p) =>
318+ p.securitySchemeName === securitySchemeName &&
319+ p.flow === "authorizationCode",
320+ ) ?? null
321+ );
322+ };
323+
324+ return (
325+ <section className="space-y-2.5">
326+ <div>
327+ <FieldLabel>Connections</FieldLabel>
328+ <p className="mt-1 text-[11px] text-muted-foreground">
329+ Each member of this organization connects with their own OAuth
330+ credentials.
331+ </p>
332+ </div>
333+ <div className="space-y-2">
334+ {props.oauth2Entries.map((auth) => (
335+ <ConnectionRow
336+ key={auth.securitySchemeName}
337+ auth={auth}
338+ sourceName={props.sourceName}
339+ preset={presetFor(auth.securitySchemeName)}
340+ previewError={previewError}
341+ />
342+ ))}
343+ </div>
344+ </section>
345+ );
346+}
347+
28348 // ---------------------------------------------------------------------------
29349 // Edit form
30350 // ---------------------------------------------------------------------------
@@ -54,6 +374,13 @@ function EditForm(props: { · 23 unmodified lines
54374
55375 const identityDirty = identity.name.trim() !== props.initial.name.trim();
56376
377+ // A source may have zero or one stored OAuth2Auth today, but the
378+ // "Connections" section is written to iterate so future multi-scheme
379+ // specs surface without another pass.
380+ const oauth2Entries: readonly OAuth2Auth[] = props.initial.config.oauth2
381+ ? [props.initial.config.oauth2]
382+ : [];
383+
57384 const handleHeadersChange = (next: HeaderState[]) => {
58385 setHeaders(next);
59386 setDirty(true);
@@ -127,6 +454,14 @@ function EditForm(props: { · 67 unmodified lines
127454 />
128455 </section>
129456
457+ {oauth2Entries.length > 0 && (
458+ <ConnectionsSection
459+ sourceName={props.initial.name}
460+ spec={props.initial.config.spec}
461+ oauth2Entries={oauth2Entries}
462+ />
463+ )}
464+
130465 {error && (
131466 <div className="rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2">
132467 <p className="text-sm text-destructive">{error}</p>
packages/plugins/openapi/src/sdk/invoke.ts+7−2
@@ -302,13 +302,18 @@ export const invokeWithLayer = ( · 301 unmodified lines
302302 // Derive annotations from HTTP method
303303 // ---------------------------------------------------------------------------
304304
305−const SAFE_METHODS = new Set(["get", "head", "options"]);
305+const DEFAULT_REQUIRE_APPROVAL = new Set(["post", "put", "patch", "delete"]);
306306
307307 export const annotationsForOperation = (
308308 method: string,
309309 pathTemplate: string,
310+ policy?: { readonly requireApprovalFor?: readonly string[] },
310311 ): { requiresApproval?: boolean; approvalDescription?: string } => {
311− if (SAFE_METHODS.has(method.toLowerCase())) return {};
312+ const m = method.toLowerCase();
313+ const requireSet = policy?.requireApprovalFor
314+ ? new Set(policy.requireApprovalFor.map((v) => v.toLowerCase()))
315+ : DEFAULT_REQUIRE_APPROVAL;
316+ if (!requireSet.has(m)) return {};
312317 return {
313318 requiresApproval: true,
314319 approvalDescription: `${method.toUpperCase()} ${pathTemplate}`,
packages/plugins/openapi/src/sdk/store.ts+3−0
@@ -7,6 +7,7 @@ import { · 6 unmodified lines
77 } from "@executor/sdk";
88
99 import {
10+ AnnotationPolicy,
1011 HeaderValue,
1112 InvocationConfig,
1213 OAuth2Auth,
@@ -31,6 +32,7 @@ export const openapiSchema = defineSchema({ · 18 unmodified lines
3132 base_url: { type: "string", required: false },
3233 headers: { type: "json", required: false },
3334 oauth2: { type: "json", required: false },
35+ annotation_policy: { type: "json", required: false },
3436 invocation_config: { type: "json", required: true },
3537 },
3638 },
@@ -64,6 +66,7 @@ export interface SourceConfig { · 27 unmodified lines
6466 readonly namespace?: string;
6567 readonly headers?: Record<string, HeaderValue>;
6668 readonly oauth2?: OAuth2Auth;
69+ readonly annotationPolicy?: AnnotationPolicy;
6770 }
6871
6972 export interface StoredSource {
packages/plugins/openapi/src/sdk/types.ts+13−0
@@ -139,6 +139,19 @@ export class OAuth2Auth extends Schema.Class<OAuth2Auth>("OpenApiOAuth2Auth")({ · 138 unmodified lines
139139 scopes: Schema.Array(Schema.String),
140140 }) {}
141141
142+// ---------------------------------------------------------------------------
143+// Annotation policy — per-source override of the HTTP-method-based default
144+// for `requiresApproval`. If `requireApprovalFor` is set, it replaces the
145+// default set ({POST, PUT, PATCH, DELETE}) wholesale: any method present
146+// requires approval, any method absent does not.
147+// ---------------------------------------------------------------------------
148+
149+export class AnnotationPolicy extends Schema.Class<AnnotationPolicy>(
150+ "OpenApiAnnotationPolicy",
151+)({
152+ requireApprovalFor: Schema.optional(Schema.Array(HttpMethod)),
153+}) {}
154+
142155 export class InvocationConfig extends Schema.Class<InvocationConfig>("InvocationConfig")({
143156 baseUrl: Schema.String,
144157 /** Headers applied to every request. Values can reference secrets. */

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t