Debian Codegraph @

pkg/systemd/overview-cards/realmd.jsx

raw
1 /*
2 * Copyright (C) 2021 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import React, { useState, useEffect } from 'react';
7
8 import { Alert, AlertActionLink } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
9 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
10 import { CodeBlockCode } from "@patternfly/react-core/dist/esm/components/CodeBlock/index.js";
11 import { DescriptionList, DescriptionListDescription, DescriptionListGroup, DescriptionListTerm } from "@patternfly/react-core/dist/esm/components/DescriptionList/index.js";
12 import { ExpandableSection } from "@patternfly/react-core/dist/esm/components/ExpandableSection/index.js";
13 import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
14 import {
15 Modal, ModalBody, ModalFooter, ModalHeader
16 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
17 import { TextInput } from "@patternfly/react-core/dist/esm/components/TextInput/index.js";
18 import { CheckIcon, ExclamationCircleIcon, InProgressIcon } from "@patternfly/react-icons";
19
20 import cockpit from "cockpit";
21 import { Privileged } from "cockpit-components-privileged";
22 import { superuser } from "superuser";
23 import { useEvent } from "hooks.js";
24 import { FormHelper } from "cockpit-components-form-helper";
25 import { install_dialog } from "cockpit-components-install-dialog.jsx";
26 import { useDialogs } from "dialogs.jsx";
27 import { getPackageManager } from 'packagemanager';
28
29 import "./realmd.scss";
30
31 const _ = cockpit.gettext;
32
33 const MANAGER = "/org/freedesktop/realmd";
34 const PROVIDER = "org.freedesktop.realmd.Provider";
35 const KERBEROS = "org.freedesktop.realmd.Kerberos";
36 const KERBEROS_MEMBERSHIP = "org.freedesktop.realmd.KerberosMembership";
37 const REALM = "org.freedesktop.realmd.Realm";
38
39 export class RealmdClient {
40 constructor() {
41 this.onClose = this.onClose.bind(this);
42 this.onRealmsChanged = this.onRealmsChanged.bind(this);
43 this.joined = [];
44 this.detected = null;
45 this.error = null;
46 this.install_realmd = false;
47 this.callSerial = 1;
48
49 cockpit.event_target(this);
50 this.initProxy();
51 superuser.addEventListener("changed", () => this.initProxy());
52 }
53
54 onClose(ev, options) {
55 if (options.problem === "not-found") {
56 // see if we can install it
57 getPackageManager().then(() => {
58 this.error = _("Joining a domain requires installation of realmd");
59 this.install_realmd = true;
60 this.dispatchEvent("changed");
61 }).catch(exc => {
62 this.error = _("Cannot join a domain because realmd is not available on this system");
63 this.dispatchEvent("changed");
64 });
65 } else {
66 this.error = cockpit.message(options);
67 this.dispatchEvent("changed");
68 }
69 this.dbus_realmd.removeEventListener("close", this.onClose);
70 this.dbus_realmd.close();
71 this.dbus_realmd = null;
72 }
73
74 onRealmsChanged() {
75 this.joined = [];
76 for (const path in this.realms) {
77 const realm = this.realms[path];
78 if (realm.Configured)
79 this.joined.push(realm);
80 }
81
82 this.dispatchEvent("changed");
83 }
84
85 initProxy() {
86 // Ignore intermediate states of superuser.allowed to
87 // avoid initializing the proxy twice during page
88 // load. This is less wasteful and helps the tests avoid
89 // race conditions. We are guaranteed to see a real "true"
90 // or "false" value eventually.
91 //
92 if (superuser.allowed === null)
93 return;
94
95 if (this.dbus_realmd) {
96 this.dbus_realmd.removeEventListener("close", this.onClose);
97 this.dbus_realmd.close();
98 }
99
100 this.error = null;
101 this.dbus_realmd = cockpit.dbus("org.freedesktop.realmd", { superuser: "try" });
102 this.dbus_realmd.watch(MANAGER);
103 this.dbus_realmd.addEventListener("close", this.onClose);
104
105 this.realms = this.dbus_realmd.proxies(REALM, MANAGER);
106 this.realms.addEventListener("changed", this.onRealmsChanged);
107 }
108
109 checkRealm(name) {
110 return this.dbus_realmd.call(MANAGER, PROVIDER, "Discover", [name, {}])
111 .then(([relevance, realms]) => {
112 if (realms.length == 0)
113 return { result: false };
114
115 // the first realm
116 const path = realms[0];
117 const realm = this.dbus_realmd.proxy(REALM, path);
118 const kerberos_membership = this.dbus_realmd.proxy(KERBEROS_MEMBERSHIP, path);
119 return Promise.allSettled([realm.wait(), kerberos_membership.wait()])
120 .then(() => { return { result: true, realm, kerberos_membership } });
121 });
122 }
123
124 join(realm, kerberosMembership, user, password) {
125 const id = "cockpit-" + this.callSerial;
126 this.callSerial += 1;
127 let diagnostics = "";
128
129 const options = { operation: cockpit.variant('s', id) };
130 const diagnostics_sub = this.dbus_realmd.subscribe({ member: "Diagnostics" }, (path, iface, signal, args) => {
131 if (args[1] === id) {
132 diagnostics += args[0];
133 }
134 });
135
136 if (kerberosMembership.valid) {
137 const credentials = ["password", "administrator", cockpit.variant('(ss)', [user, password])];
138 return kerberosMembership.call("Join", [credentials, options])
139 .then(() => this.installWSCredentials(realm, user, password))
140 .catch(ex => {
141 if (ex.name == "org.freedesktop.realmd.Error.Cancelled")
142 return Promise.resolve();
143 ex.diagnostics = diagnostics;
144 return Promise.reject(ex);
145 })
146 .finally(() => diagnostics_sub.remove());
147 } else {
148 return Promise.reject(new Error(_("Joining this domain is not supported")));
149 }
150 }
151
152 leave(realm) {
153 return this.cleanupWSCredentials(realm)
154 .then(() => realm.Deconfigure({ operation: cockpit.variant('s', "cockpit-leave-domain") }));
155 }
156
157 installWSCredentials(realm, user, password) {
158 // skip this on remote ssh hosts, only set up ws hosts
159 if (cockpit.transport.host !== "localhost")
160 return true;
161
162 const server_sw = find_detail(realm, "server-software");
163 if (server_sw !== "ipa") {
164 console.log("installing ws credentials not supported for server software", server_sw);
165 return true;
166 }
167
168 const kerberos = this.dbus_realmd.proxy(KERBEROS, realm.path);
169 return kerberos.wait()
170 .then(() => {
171 const helper = cockpit.manifests.system.libexecdir + "/cockpit-certificate-helper";
172 const proc = cockpit.spawn([helper, "ipa", "request", kerberos.RealmName, user],
173 { superuser: "require", err: "message" });
174 proc.input(password);
175 proc.catch(ex => console.warn("Failed to run", helper, "ipa request:", ex.toString()));
176 return proc;
177 })
178 .catch(() => true); // no Kerberos domain? nevermind then
179 }
180
181 cleanupWSCredentials(realm) {
182 // skip this on remote ssh hosts, only set up ws hosts
183 if (cockpit.transport.host !== "localhost")
184 return Promise.resolve();
185
186 const server_sw = find_detail(realm, "server-software");
187 if (server_sw !== "ipa") {
188 console.log("cleaning up ws credentials not supported for server software", server_sw);
189 return Promise.resolve();
190 }
191
192 const kerberos = this.dbus_realmd.proxy(KERBEROS, realm.path);
193 return kerberos.wait()
194 .then(() => {
195 const helper = cockpit.manifests.system.libexecdir + "/cockpit-certificate-helper";
196 return cockpit.spawn([helper, "ipa", "cleanup", kerberos.RealmName],
197 { superuser: "require", err: "message" })
198 .catch(ex => {
199 console.log("Failed to clean up SPN from /etc/cockpit/krb5.keytab:", JSON.stringify(ex));
200 return true;
201 });
202 })
203 .catch(() => true); // no Kerberos domain? nevermind then
204 }
205
206 allowHostnameChange() {
207 return this.joined.length === 0;
208 }
209
210 installPackage() {
211 if (this.install_realmd) {
212 return install_dialog("realmd")
213 .then(() => {
214 this.install_realmd = false;
215 this.initProxy();
216 return true;
217 })
218 .catch(() => false); // dialog cancelled
219 }
220
221 return null;
222 }
223 }
224
225 /*
226 * The realmd dbus interface has an a(ss) Details
227 * property. Lookup the right value for the given
228 * field key.
229 */
230 function find_detail(realm, field) {
231 let result = null;
232 if (realm && realm.Details) {
233 realm.Details.forEach(value => {
234 if (value[0] === field)
235 result = value[1];
236 });
237 }
238 return result;
239 }
240
241 const LeaveDialog = ({ realmd_client }) => {
242 const Dialogs = useDialogs();
243 const [expanded, setExpanded] = useState(false);
244 const [pending, setPending] = useState(false);
245 const [error, setError] = useState(null);
246 const realm = realmd_client.joined[0];
247
248 const onLeave = () => {
249 setPending(true);
250 realmd_client.leave(realm)
251 .then(Dialogs.close)
252 .catch(err => {
253 console.warn("Failed to leave domain:", err.toString());
254 setPending(false);
255 setError(err);
256 });
257 };
258
259 return (
260 <Modal id="realms-leave-dialog" isOpen position="top" variant="medium"
261 onClose={Dialogs.close}
262 >
263 <ModalHeader title={ _("dialog-title", "Domain") } />
264 <ModalBody>
265 <DescriptionList isHorizontal>
266 <DescriptionListGroup>
267 <DescriptionListTerm>{ _("Domain") }</DescriptionListTerm>
268 <DescriptionListDescription id="realms-op-info-domain">
269 { realm && realm.Name }
270 </DescriptionListDescription>
271 </DescriptionListGroup>
272 <DescriptionListGroup>
273 <DescriptionListTerm>{ _("Login format") }</DescriptionListTerm>
274 <DescriptionListDescription id="realms-op-info-login-format">{
275 realm && realm.LoginFormats && realm.LoginFormats.length > 0
276 ? realm.LoginFormats[0].replace("%U", "username")
277 : null
278 }</DescriptionListDescription>
279 </DescriptionListGroup>
280 <DescriptionListGroup>
281 <DescriptionListTerm>{ _("Server software") }</DescriptionListTerm>
282 <DescriptionListDescription id="realms-op-info-server-sw">
283 { find_detail(realm, "server-software") }
284 </DescriptionListDescription>
285 </DescriptionListGroup>
286 <DescriptionListGroup>
287 <DescriptionListTerm>{ _("Client software") }</DescriptionListTerm>
288 <DescriptionListDescription id="realms-op-info-client-sw">
289 { find_detail(realm, "client-software") }
290 </DescriptionListDescription>
291 </DescriptionListGroup>
292 </DescriptionList>
293
294 <ExpandableSection toggleText={ _("Leave domain") } isExpanded={expanded}
295 onToggle={ e => setExpanded(e) }>
296 <Alert variant="warning" isInline
297 title={ realm && realm.Name ? cockpit.format(_("Leave $0"), realm.Name) : _("Leave domain") }
298 actionLinks={
299 <Button variant="danger" id="realms-op-leave" isDisabled={pending} onClick={onLeave}>{ _("Leave domain") }</Button>
300 }>
301 { _("After leaving the domain, only users with local credentials will be able to log into this machine. This may also affect other services as DNS resolution settings and the list of trusted CAs may change.") }
302 </Alert>
303 </ExpandableSection>
304 </ModalBody>
305 <ModalFooter>
306 { error && <Alert variant="danger" isInline className="realms-op-error" title={error.toString()} /> }
307 <Button variant="secondary" isDisabled={pending} onClick={Dialogs.close}>{ _("Close") }</Button>
308 </ModalFooter>
309 </Modal>);
310 };
311
312 let domainValidateTimeout;
313
314 const JoinDialog = ({ realmd_client }) => {
315 const Dialogs = useDialogs();
316 const [pending, setPending] = useState(false);
317 const [address, setAddress] = useState("");
318 const [addressValid, setAddressValid] = useState(null); // success, error, unsupported, default (for pending check)
319 const [admin, setAdmin] = useState("");
320 const [adminPassword, setAdminPassword] = useState("");
321 const [realm, setRealm] = useState(null);
322 const [kerberosMembership, setKerberosMembership] = useState(null);
323 const [error, setError] = useState(null);
324 const [diagnosticsExpanded, setDiagnosticsExpanded] = useState(false);
325
326 const checkAddress = name => {
327 setAddressValid("default");
328
329 realmd_client.checkRealm(name)
330 .then(reply => {
331 if (reply.result) {
332 setRealm(reply.realm);
333
334 // handle initial auto-detection
335 if (name == "") {
336 if (!address)
337 setAddress(reply.realm.Name);
338 }
339
340 if (reply.kerberos_membership && reply.kerberos_membership.valid) {
341 setAddressValid("success");
342 if (!admin && reply.kerberos_membership.SuggestedAdministrator)
343 setAdmin(reply.kerberos_membership.SuggestedAdministrator);
344 setKerberosMembership(reply.kerberos_membership);
345 } else {
346 setAddressValid("unsupported");
347 }
348 } else {
349 // error_detect will not show the validation error, but trigger data-discover=done
350 setAddressValid(name ? "error" : "error_detect");
351 }
352 })
353 .catch(err => console.error("checkRealm failed", JSON.stringify(err)));
354 };
355
356 const validateAddress = value => {
357 setAddress(value);
358 setAddressValid(null);
359 window.clearTimeout(domainValidateTimeout);
360 if (value)
361 domainValidateTimeout = window.setTimeout(() => checkAddress(value), 1000);
362 };
363
364 const onJoin = () => {
365 setError(null);
366 setDiagnosticsExpanded(null);
367 setPending(true);
368 realmd_client.join(realm, kerberosMembership, admin, adminPassword)
369 .then(Dialogs.close)
370 .catch(err => {
371 setPending(false);
372 setError(err);
373 });
374 };
375
376 // initial auto-detection of domain name
377 useEffect(() => checkAddress(""), []); // eslint-disable-line react-hooks/exhaustive-deps
378
379 const join_disabled = pending || addressValid !== "success" || !admin || !kerberosMembership;
380
381 const DOMAIN_VALID_HELPER_TEXT = {
382 default: _("Validating address"),
383 success: _("Contacted domain"),
384 error: _("Domain could not be contacted"),
385 unsupported: _("Domain is not supported"),
386 };
387
388 const DOMAIN_VALID_HELPER_ICON = {
389 default: <InProgressIcon />,
390 success: <CheckIcon />,
391 error: <ExclamationCircleIcon />,
392 unsupported: <ExclamationCircleIcon />,
393 };
394
395 const domainHelperText = DOMAIN_VALID_HELPER_TEXT[addressValid];
396 const domainHelperIcon = DOMAIN_VALID_HELPER_ICON[addressValid];
397
398 let errorAlert;
399 if (error) {
400 const details = (error.diagnostics && diagnosticsExpanded)
401 ? <CodeBlockCode className="realms-op-diagnostics">{error.diagnostics}</CodeBlockCode>
402 : null;
403 const actionLink = (error.diagnostics && !diagnosticsExpanded)
404 ? <AlertActionLink onClick={ () => setDiagnosticsExpanded(true) }>{ _("Details") }</AlertActionLink>
405 : null;
406 errorAlert = <Alert variant="danger" isInline className="realms-op-error" actionLinks={actionLink} title={error.toString()}>{details}</Alert>;
407 }
408
409 return (
410 <Modal id="realms-join-dialog" isOpen position="top" variant="medium"
411 onClose={Dialogs.close}
412 >
413 <ModalHeader title={ _("dialog-title", "Join a domain") } />
414 <ModalBody>
415 <Form isHorizontal onSubmit={onJoin}>
416 <FormGroup label={ _("Domain address") } fieldId="realms-op-address" validated={addressValid}>
417 <TextInput id="realms-op-address" placeholder="domain.example.com"
418 data-discover={ (!addressValid || addressValid == "default") ? null : "done" }
419 autoComplete="url"
420 value={address} onChange={(_event, value) => validateAddress(value)} isDisabled={pending} />
421 </FormGroup>
422
423 <FormGroup label={ _("Domain administrator name") } fieldId="realms-op-admin">
424 <TextInput id="realms-op-admin" placeholder="admin" value={admin} autoComplete="username" onChange={(_event, value) => setAdmin(value)} isDisabled={pending} />
425 </FormGroup>
426 <FormGroup label={ _("Domain administrator password") } fieldId="realms-op-admin-password">
427 <TextInput id="realms-op-admin-password" type="password" value={adminPassword} autoComplete="current-password" onChange={(_event, value) => setAdminPassword(value)} isDisabled={pending} />
428 </FormGroup>
429 <FormHelper fieldId="realms-op-address" helperText={domainHelperText} helperTextInvalid={addressValid == "error" && domainHelperText} icon={domainHelperIcon} />
430 </Form>
431 </ModalBody>
432 <ModalFooter>
433 { errorAlert }
434 <Button variant="primary"
435 isDisabled={join_disabled}
436 onClick={onJoin}
437 isLoading={pending}
438 spinnerAriaValueText={ pending ? _("Joining") : null }>
439 { _("Join") }
440 </Button>
441 <Button variant="link" isDisabled={pending} onClick={Dialogs.close}>{ _("Cancel") }</Button>
442 { pending && <span className="realms-op-wait-message">{ _("This may take a while") }</span> }
443 </ModalFooter>
444 </Modal>);
445 };
446
447 export const RealmButton = ({ realmd_client }) => {
448 const Dialogs = useDialogs();
449 useEvent(realmd_client, "changed");
450 useEvent(superuser, "changed");
451
452 const buttonTooltip = superuser.allowed ? realmd_client.error : _("Not permitted to configure realms");
453 const buttonText = !realmd_client.install_realmd ? (realmd_client.joined.length ? realmd_client.joined.map(r => r.Name).join(", ") : _("Join domain")) : _("Install realmd support");
454 const buttonDisabled = !superuser.allowed || (realmd_client.error && !realmd_client.install_realmd);
455
456 const onClicked = () => {
457 // handle on-demand realmd package install
458 const install_promise = realmd_client.installPackage();
459 if (install_promise) {
460 // after installation, proceed to join dialog
461 install_promise.then(success => success && onClicked());
462 return null;
463 }
464 realmd_client.joined.length > 0
465 ? Dialogs.show(<LeaveDialog realmd_client={realmd_client} />)
466 : Dialogs.show(<JoinDialog realmd_client={realmd_client} />);
467 };
468
469 return (
470 <Privileged allowed={ superuser.allowed && !realmd_client.error }
471 tooltipId="system_information_domain_tooltip"
472 excuse={ buttonTooltip }>
473 <Button id="system_information_domain_button" variant="link"
474 onClick={onClicked}
475 isInline isDisabled={buttonDisabled} aria-label={buttonText}>
476 { buttonText }
477 </Button>
478 </Privileged>);
479 };