Debian Codegraph @

pkg/lib/superuser-dialogs.tsx

raw
1 /*
2 * Copyright (C) 2020 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7 import React, { useState } from "react";
8 import { useObject, useInit, useEvent } from "hooks";
9 import { useDialogs } from "dialogs.jsx";
10 import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
11 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
12 import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
13 import {
14 Modal, ModalBody, ModalFooter, ModalHeader
15 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
16 import { TextInput } from "@patternfly/react-core/dist/esm/components/TextInput/index.js";
17 import { FormSelect, FormSelectOption } from "@patternfly/react-core/dist/esm/components/FormSelect/index.js";
18 import { Stack, StackItem } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
19 import { ModalError } from 'cockpit-components-inline-notification.jsx';
20 import { LockIcon } from '@patternfly/react-icons';
21
22 const _ = cockpit.gettext;
23
24 export function host_superuser_storage_key(host: string | undefined) {
25 if (!host)
26 host = cockpit.transport.host;
27
28 const local_key = window.localStorage.getItem("superuser-key");
29 if (host == "localhost")
30 return local_key;
31 else if (host.indexOf("@") >= 0)
32 return "superuser:" + host;
33 else if (local_key)
34 return local_key + "@" + host;
35 else
36 return null;
37 }
38
39 function sudo_polish(msg: string): string;
40 function sudo_polish(msg: null): null;
41 function sudo_polish(msg: string | null): string | null {
42 if (!msg)
43 return msg;
44
45 msg = msg.replace(/^\[sudo(: authenticate)?] /, "");
46 msg = msg[0].toUpperCase() + msg.slice(1);
47
48 return msg;
49 }
50
51 interface Method {
52 v: { label: { v: string; } };
53 }
54
55 export interface SuperuserProxy extends cockpit.DBusProxy {
56 Current: string;
57 Bridges: string[];
58 Methods: Record<string, Method>;
59
60 Start(method: string): Promise<void>;
61 Stop(): Promise<void>;
62 Answer(val: string): Promise<void>;
63 }
64
65 export function superuser_proxy(bus?: cockpit.DBusClient) {
66 if (!bus)
67 bus = cockpit.dbus(null, { bus: "internal" });
68 return bus.proxy("cockpit.Superuser", "/superuser") as SuperuserProxy;
69 }
70
71 const UnlockDialog = ({
72 proxy,
73 host
74 } : {
75 proxy: SuperuserProxy,
76 host: string | undefined
77 }) => {
78 const D = useDialogs();
79 useInit(init, [proxy, host]);
80
81 const [methods, setMethods] = useState<string[] | null>(null);
82 const [method, setMethod] = useState<string | false>(false);
83 const [busy, setBusy] = useState(false);
84 const [cancel, setCancel] = useState(() => D.close);
85 const [prompt, setPrompt] = useState<{ message: string, prompt: string, echo: boolean } | null>(null);
86 const [message, setMessage] = useState<string | null>(null);
87 const [error, setError] = useState<string | null>(null);
88 const [errorVariant, setErrorVariant] = useState<"danger" | "warning" | null>(null);
89 const [value, setValue] = useState("");
90
91 function start(method: string) {
92 setBusy(true);
93 setCancel(() => () => {
94 proxy.Stop();
95 D.close();
96 });
97
98 let did_prompt = false;
99
100 const onprompt = (_event: Event, message: string, prompt: string, def: string, echo: boolean, error: string) => {
101 setBusy(false);
102 setPrompt({
103 message: sudo_polish(message),
104 prompt: sudo_polish(prompt),
105 echo
106 });
107 setValue(def);
108
109 if (error) {
110 setError(sudo_polish(error));
111 setErrorVariant(did_prompt ? 'danger' : 'warning');
112 }
113
114 did_prompt = true;
115 };
116
117 proxy.addEventListener("Prompt", onprompt);
118 proxy.Start(method)
119 .then(() => {
120 proxy.removeEventListener("Prompt", onprompt);
121
122 const key = host_superuser_storage_key(host);
123 if (key)
124 window.localStorage.setItem(key, method);
125 if (did_prompt) {
126 D.close();
127 } else {
128 setBusy(false);
129 setPrompt(null);
130 setMessage(_("You now have administrative access."));
131 setCancel(() => D.close);
132 }
133 })
134 .catch((err: cockpit.BasicError) => {
135 console.warn(err);
136 proxy.removeEventListener("Prompt", onprompt);
137 if (err && err.message != "cancelled") {
138 setBusy(false);
139 setPrompt(null);
140 setError(sudo_polish(err.toString()));
141 setCancel(() => D.close);
142 } else
143 D.close();
144 });
145 }
146
147 function init() {
148 return proxy.Stop().finally(() => {
149 if (proxy.Bridges.length === 0) {
150 setError(_("No methods to gain administrative access are available (sudo -A, pkexec)."));
151 } else if (proxy.Methods) {
152 const ids = Object.keys(proxy.Methods);
153 if (ids.length == 0)
154 start(proxy.Bridges[0]);
155 else if (ids.length == 1)
156 start(ids[0]);
157 else {
158 setMethods(ids);
159 setMethod(ids[0]);
160 }
161 } else
162 start(proxy.Bridges[0]);
163 });
164 }
165
166 const validated = errorVariant == "danger" ? "error" : errorVariant;
167
168 let title = null;
169 let title_icon: null | "danger" = null;
170 let body = null;
171 let footer = null;
172
173 if (prompt) {
174 if (!prompt.message && !prompt.prompt) {
175 prompt.message = _("Please authenticate to gain administrative access");
176 prompt.prompt = _("Password");
177 }
178
179 const apply = () => {
180 proxy.Answer(value);
181 setError(null);
182 setBusy(true);
183 };
184
185 title = _("Switch to administrative access");
186 body = (
187 <Form isHorizontal onSubmit={event => { apply(); event.preventDefault(); return false }}>
188 { error && <Alert variant={errorVariant || 'danger'} isInline title={error} /> }
189 { prompt.message && <span>{prompt.message}</span> }
190 <FormGroup
191 fieldId="switch-to-admin-access-password"
192 label={prompt.prompt}
193 >
194 <TextInput
195 autoFocus // eslint-disable-line jsx-a11y/no-autofocus
196 id="switch-to-admin-access-password"
197 isDisabled={busy}
198 onChange={(_event, value) => setValue(value)}
199 type={!prompt.echo ? 'password' : 'text'}
200 validated={!error ? "default" : validated || "error"}
201 value={value}
202 />
203 </FormGroup>
204 </Form>
205 );
206
207 footer = (
208 <>
209 <Button variant='primary' onClick={apply} isDisabled={busy} isLoading={busy}>
210 {_("Authenticate")}
211 </Button>
212 <Button variant='link' className='btn-cancel' onClick={cancel}>
213 {_("Cancel")}
214 </Button>
215 </>);
216 } else if (message) {
217 title = _("Administrative access");
218 body = <p>{message}</p>;
219 footer = (
220 <Button variant="secondary" className='btn-cancel' onClick={cancel}>
221 {_("Close")}
222 </Button>);
223 } else if (error) {
224 title_icon = "danger";
225 title = _("Problem becoming administrator");
226 body = <p>{error}</p>;
227 footer = (
228 <Button variant="secondary" className='btn-cancel' onClick={cancel}>
229 {_("Close")}
230 </Button>);
231 } else if (methods && method) {
232 title = _("Switch to administrative access");
233 body = (
234 <Form isHorizontal>
235 <FormGroup fieldId="switch-to-admin-access-bridge-select"
236 label={_("Method")}>
237 <FormSelect id="switch-to-admin-access-bridge-select" value={method} onChange={(_, method) => setMethod(method)} isDisabled={busy}>
238 { methods.map(m => <FormSelectOption value={m} key={m}
239 label={_(proxy.Methods[m].v.label.v)} />) }
240 </FormSelect>
241 </FormGroup>
242 </Form>);
243
244 footer = (
245 <>
246 <Button variant='primary' onClick={() => start(method)} isDisabled={busy} isLoading={busy}>
247 {_("Authenticate")}
248 </Button>
249 <Button variant='link' className='btn-cancel' onClick={cancel}>
250 {_("Cancel")}
251 </Button>
252 </>);
253 }
254
255 if (body === null)
256 return null;
257
258 return (
259 <Modal isOpen
260 position="top"
261 variant="medium"
262 onClose={cancel}>
263 <ModalHeader title={title}
264 {...title_icon && { titleIconVariant: title_icon }}
265 />
266 <ModalBody>
267 {body}
268 </ModalBody>
269 <ModalFooter>
270 {footer}
271 </ModalFooter>
272 </Modal>
273 );
274 };
275
276 const LockDialog = ({
277 proxy,
278 host
279 } : {
280 proxy: SuperuserProxy,
281 host: string | undefined
282 }) => {
283 const D = useDialogs();
284 const [error, setError] = useState<string | null>(null);
285
286 const apply = () => {
287 setError(null);
288 proxy.Stop()
289 .then(() => {
290 const key = host_superuser_storage_key(host);
291 if (key)
292 window.localStorage.setItem(key, "none");
293 D.close();
294 })
295 .catch(err => {
296 setError(err.toString());
297 });
298 };
299
300 const footer = (
301 <ModalFooter>
302 <Button variant='primary' onClick={apply}>
303 {_("Limit access")}
304 </Button>
305 <Button variant='link' className='btn-cancel' onClick={D.close}>
306 {_("Cancel")}
307 </Button>
308 </ModalFooter>
309 );
310
311 return (
312 <Modal isOpen
313 position="top" variant="medium"
314 onClose={D.close}>
315 <ModalHeader title={_("Switch to limited access")} />
316 <ModalBody>
317 <Stack hasGutter>
318 {error && <ModalError dialogError={error} />}
319 <StackItem>
320 <p>{_("Limited access mode restricts administrative privileges. Some parts of the web console will have reduced functionality.")}</p>
321 <p>{_("Your browser will remember your access level across sessions.")}</p>
322 </StackItem>
323 </Stack>
324 </ModalBody>
325 {footer}
326 </Modal>
327 );
328 };
329
330 const SuperuserDialogs = ({
331 superuser_proxy,
332 host = undefined,
333 create_trigger
334 } : {
335 superuser_proxy: SuperuserProxy;
336 host: string | undefined,
337 create_trigger: (unlocked: boolean, onclick: () => void) => React.ReactNode;
338 }) => {
339 const D = useDialogs();
340 useEvent(superuser_proxy, "changed",
341 () => {
342 const key = host_superuser_storage_key(host);
343 if (key) {
344 // Reset wanted state if we fail to gain admin privs.
345 // Failing to gain admin privs might take a noticeable
346 // time, and we don't want to suffer through the
347 // associated intermediate UI state on every login.
348 const want = window.localStorage.getItem(key);
349 if (superuser_proxy.Current == "none" && superuser_proxy.Current != want)
350 window.localStorage.setItem(key, superuser_proxy.Current);
351 }
352 });
353
354 const show = superuser_proxy.Current != "root" && superuser_proxy.Current != "init";
355 const unlocked = superuser_proxy.Current != "none";
356
357 function unlock() {
358 D.show(<UnlockDialog proxy={superuser_proxy} host={host} />);
359 }
360
361 function lock() {
362 D.show(<LockDialog proxy={superuser_proxy} host={host} />);
363 }
364
365 if (!show)
366 return null;
367
368 return create_trigger(unlocked, unlocked ? lock : unlock);
369 };
370
371 export const SuperuserIndicator = ({
372 proxy,
373 host
374 } : {
375 proxy: SuperuserProxy | null,
376 host?: string
377 }) => {
378 if (!proxy || !proxy.valid)
379 return null;
380
381 function create_trigger(unlocked: boolean, onclick: () => void) {
382 return (
383 <Button variant="link" onClick={onclick} className={unlocked ? "ct-unlocked" : "ct-locked"}>
384 <span className="ct-lock-wrapper">
385 {!unlocked && <LockIcon />}
386 {unlocked ? _("Administrative access") : _("Limited access")}
387 </span>
388 </Button>
389 );
390 }
391
392 return <SuperuserDialogs superuser_proxy={proxy}
393 host={host}
394 create_trigger={create_trigger} />;
395 };
396
397 export const SuperuserButton = () => {
398 const proxy = useObject(
399 () => superuser_proxy(),
400 null,
401 []);
402
403 const create_trigger = (unlocked: boolean, onclick: () => void) =>
404 <Button onClick={onclick}>
405 {unlocked ? _("Switch to limited access") : _("Turn on administrative access")}
406 </Button>;
407
408 return <SuperuserDialogs
409 superuser_proxy={proxy}
410 create_trigger={create_trigger}
411 host={undefined} />;
412 };