Added a confirmation dialog for clearing a Trust Anchor.
[moonshot-ui.git] / src / moonshot-identity-dialog.vala
1 /*
2  * Copyright (c) 2016, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31 */
32
33 using Gee;
34 using Gtk;
35
36
37 // Defined here as workaround for emacs vala-mode indentation failure.
38 #if VALA_0_12
39 static const string CANCEL = Stock.CANCEL;
40 #else
41 static const string CANCEL = STOCK_CANCEL;
42 #endif
43
44
45 // For use when exporting certificates.
46 static string export_directory = null;
47
48 class IdentityDialog : Dialog
49 {
50     private static Gdk.Color white = make_color(65535, 65535, 65535);
51     private static Gdk.Color selected_color = make_color(0xd9 << 8, 0xf7 << 8, 65535);
52
53     private static MoonshotLogger logger = get_logger("IdentityDialog");
54
55     static const string displayname_labeltext = _("Display Name");
56     static const string realm_labeltext = _("Realm");
57     static const string username_labeltext = _("Username");
58     static const string password_labeltext = _("Password");
59
60     private Entry displayname_entry;
61     private Label displayname_label;
62     private Entry realm_entry;
63     private Label realm_label;
64     private Entry username_entry;
65     private Label username_label;
66     private Entry password_entry;
67     private Label password_label;
68     private CheckButton remember_checkbutton;
69     private Label message_label;
70     public bool complete;
71     private IdCard card;
72
73     private Label selected_item = null;
74
75     // Whether to clear the card's TrustAnchor after the user selects OK
76     internal bool clear_trust_anchor = false;
77
78     public string display_name {
79         get { return displayname_entry.get_text(); }
80     }
81
82     public string issuer {
83         get { return realm_entry.get_text(); }
84     }
85
86     public string username {
87         get { return username_entry.get_text(); }
88     }
89
90     public string password {
91         get { return password_entry.get_text(); }
92     }
93
94     public bool store_password {
95         get { return remember_checkbutton.active; }
96     }
97
98     /**
99      * Don't leave passwords in memory longer than necessary.
100      * This may not actually erase the password data bytes, but it seems to be the best we can do.
101      */
102     public void clear_password() {
103         clear_password_entry(password_entry);
104     }
105
106     internal ArrayList<string> get_services()
107     {
108         return card.services;
109     }
110
111     public IdentityDialog(IdentityManagerView parent)
112     {
113         this.with_idcard(null, _("Add ID Card"), parent);
114     }
115
116     public IdentityDialog.with_idcard(IdCard? a_card, string title, IdentityManagerView parent)
117     {
118         bool is_new_card = false;
119         if (a_card == null)
120         {
121             is_new_card = true;
122         }
123
124         card = a_card ?? new IdCard();
125         this.set_title(title);
126         this.set_modal(true);
127         this.set_transient_for(parent);
128
129         this.add_buttons(CANCEL, ResponseType.CANCEL, _("OK"), ResponseType.OK);
130         Box content_area = (Box) this.get_content_area();
131
132         displayname_label = new Label(@"$displayname_labeltext:");
133         displayname_label.set_alignment(0, (float) 0.5);
134         displayname_entry = new Entry();
135         displayname_entry.set_text(card.display_name);
136         displayname_entry.set_width_chars(40);
137
138         realm_label = new Label(@"$realm_labeltext:");
139         realm_label.set_alignment(0, (float) 0.5);
140         realm_entry = new Entry();
141         realm_entry.set_text(card.issuer);
142         realm_entry.set_width_chars(60);
143
144         username_label = new Label(@"$username_labeltext:");
145         username_label.set_alignment(0, (float) 0.5);
146         username_entry = new Entry();
147         username_entry.set_text(card.username);
148         username_entry.set_width_chars(40);
149
150         password_label = new Label(@"$password_labeltext:");
151         password_label.set_alignment(0, (float) 0.5);
152
153         remember_checkbutton = new CheckButton.with_label(_("Remember password"));
154         remember_checkbutton.active = card.store_password;
155
156         password_entry = new Entry();
157         password_entry.set_invisible_char('*');
158         password_entry.set_visibility(false);
159         password_entry.set_width_chars(40);
160         password_entry.set_text(card.password);
161
162         message_label = new Label("");
163         message_label.set_visible(false);
164
165         set_atk_relation(displayname_label, displayname_entry, Atk.RelationType.LABEL_FOR);
166         set_atk_relation(realm_label, realm_entry, Atk.RelationType.LABEL_FOR);
167         set_atk_relation(username_label, username_entry, Atk.RelationType.LABEL_FOR);
168         set_atk_relation(password_label, password_entry, Atk.RelationType.LABEL_FOR);
169
170         content_area.pack_start(message_label, false, false, 6);
171         add_as_vbox(content_area, displayname_label, displayname_entry);
172         add_as_vbox(content_area, username_label, username_entry);
173         add_as_vbox(content_area, realm_label, realm_entry);
174         add_as_vbox(content_area, password_label, password_entry);
175
176         var remember_hbox = new HBox(false, 40);
177         remember_hbox.pack_start(new HBox(false, 0), false, false, 0);
178         remember_hbox.pack_start(remember_checkbutton, false, false, 0);
179         content_area.pack_start(remember_hbox, false, false, 2);
180
181         this.response.connect(on_response);
182         content_area.set_border_width(6);
183
184         if (!is_new_card)
185         {
186             Widget trust_anchor_box = make_trust_anchor_box(card);
187             content_area.pack_start(trust_anchor_box, false, false, 15);
188
189             var services_vbox = make_services_vbox();
190             content_area.pack_start(services_vbox);
191             var services_vbox_bottom_spacer = new Alignment(0, 0, 0, 0);
192             services_vbox_bottom_spacer.set_size_request(0, 12);
193             content_area.pack_start(services_vbox_bottom_spacer, false, false, 0);
194         }
195
196         if (card.is_no_identity())
197         {
198             displayname_entry.set_sensitive(false);
199             realm_entry.set_sensitive(false);
200             username_entry.set_sensitive(false);
201             password_entry.set_sensitive(false);
202             remember_checkbutton.set_sensitive(false);
203         }
204
205         this.destroy.connect(() => {
206                 logger.trace("Destroying IdentityDialog; clearing its password.");
207                 this.clear_password();
208             });
209
210
211         this.set_border_width(6);
212         this.set_resizable(false);
213         set_bg_color(this);
214         this.show_all();
215     }
216
217     private Widget make_trust_anchor_box(IdCard id)
218     {
219
220         int nrows = 7;
221         int ncolumns = 2;
222         string ta_label_prefix = _("Trust anchor: ");
223         string none = _("None");
224
225         HBox trust_anchor_box = new HBox(false, 0);
226
227         Label ta_label = new Label(ta_label_prefix
228                                    + (id.trust_anchor.is_empty() ? none : _("Enterprise provisioned")));
229         ta_label.set_alignment(0, 0.5f);
230
231         if (id.trust_anchor.is_empty()) {
232             trust_anchor_box.pack_start(ta_label, false, false, 0);
233             return trust_anchor_box;
234         }
235
236
237         AttachOptions fill_and_expand = AttachOptions.EXPAND | AttachOptions.FILL;
238         AttachOptions fill = AttachOptions.FILL;
239
240         Table ta_table = new Table(nrows, ncolumns, false);
241         int row = 0;
242
243         var ta_clear_button = new Button.with_label(_("Clear Trust Anchor"));
244         ta_clear_button.clicked.connect((w) => {
245                 var result = WarningDialog.confirm(this,
246                                                    Markup.printf_escaped(
247                                                        "<span font-weight='heavy'>" 
248                                                        + _("You are about to clear the trust anchor fingerprint for '%s'.") 
249                                                        + "</span>",
250                                                        id.display_name)
251                                                    + _("\n\nAre you sure you want to do this?"),
252                                                    "clear_trust_anchor");
253
254                 if (result)
255                 {
256                     clear_trust_anchor = true;
257
258                     // Clearing the trust_anchor_box's children, and then re-packing
259                     // a label into it, doesn't seem to work. Instead, let's clear out
260                     // the table's children, and then re-insert a label into it.
261                     var children = ta_table.get_children();
262                     foreach (var child in children) {
263                         ta_table.remove(child);
264                     }
265
266                     ta_table.resize(1, ncolumns);
267                     ta_label.set_text(ta_label_prefix + none);
268                     ta_table.attach(ta_label, 0, 1, 0, 1, 
269                                     fill_and_expand, fill_and_expand, 0, 0);
270
271                 }
272             }
273             );
274
275         ta_table.attach(ta_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 0, 0);
276         ta_table.attach(ta_clear_button, 1, 2, row, row + 1, fill, fill, 0, 0);
277         row++;
278
279         Label added_label = new Label(_("Added: " + id.trust_anchor.datetime_added));
280         added_label.set_alignment(0, 0.5f);
281         ta_table.attach(added_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 20, 5);
282         row++;
283
284         if (id.trust_anchor.get_anchor_type() == TrustAnchor.TrustAnchorType.SERVER_CERT) {
285             Widget fingerprint = make_ta_fingerprint_widget(id.trust_anchor.server_cert);
286             ta_table.attach(fingerprint, 0, 2, row, row + 2, fill_and_expand, fill_and_expand, 5, 5);
287         }
288         else {
289             Label ca_cert_label = new Label(_("CA Certificate:"));
290             ca_cert_label.set_alignment(0, 0.5f);
291             var export_button = new Button.with_label(_("Export Certificate"));
292             export_button.clicked.connect((w) => {export_certificate(id);});
293
294             ta_table.attach(ca_cert_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 20, 0);
295             ta_table.attach(export_button, 1, 2, row, row + 1, fill, fill, 0, 0);
296             row++;
297
298             if (id.trust_anchor.subject != "") {
299                 Label subject_label = new Label(_("Subject: ") + id.trust_anchor.subject);
300                 subject_label.set_alignment(0, 0.5f);
301                 ta_table.attach(subject_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 40, 5);
302                 row++;
303             }
304
305             if (id.trust_anchor.subject_alt != "") {
306                 Label subject_alt_label = new Label(_("Subject-Alt: ") + id.trust_anchor.subject_alt);
307                 subject_alt_label.set_alignment(0, 0.5f);
308                 ta_table.attach(subject_alt_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 40, 5);
309                 row++;
310             }
311
312             Label expiration_label = new Label(_("Expiration date: ") + id.trust_anchor.get_expiration_date());
313             expiration_label.set_alignment(0, 0.5f);
314             ta_table.attach(expiration_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 40, 5);
315             row++;
316
317             //!!TODO: What goes here?
318             Label constraint_label = new Label(_("Constraint: "));
319             constraint_label.set_alignment(0, 0.5f);
320             ta_table.attach(constraint_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 20, 0);
321             row++;
322         }
323
324         trust_anchor_box.pack_start(ta_table, false, false, 0);
325         return trust_anchor_box;
326     }
327
328     private static void add_as_vbox(Box content_area, Label label, Entry entry)
329     {
330         VBox vbox = new VBox(false, 2);
331
332         vbox.pack_start(label, false, false, 0);
333         vbox.pack_start(entry, false, false, 0);
334
335         // Hack to prevent the text entries from stretching horizontally
336         HBox hbox = new HBox(false, 0);
337         hbox.pack_start(vbox, false, false, 0);
338         content_area.pack_start(hbox, false, false, 6);
339     }
340
341     private static string update_preamble(string preamble)
342     {
343         if (preamble == "")
344             return _("Missing required field: ");
345         return _("Missing required fields: ");
346     }
347
348     private static string update_message(string old_message, string new_item)
349     {
350         string message;
351         if (old_message == "")
352             message = new_item;
353         else
354             message = old_message + ", " + new_item;
355         return message;
356     }
357
358     private static void check_field(string field, Label label, string fieldname, ref string preamble, ref string message)
359     {
360         if (field != "") {
361             label.set_markup(@"$fieldname:");
362             return;
363         }
364         label.set_markup(@"<span foreground=\"red\">$fieldname:</span>");
365         preamble = update_preamble(preamble);
366         message = update_message(message, fieldname);
367     }
368
369     private bool check_fields()
370     {
371         string preamble = "";
372         string message = "";
373         string password_test = store_password ? password : "not required";
374         if (!card.is_no_identity())
375         {
376             check_field(display_name, displayname_label, displayname_labeltext, ref preamble, ref message);
377             check_field(username, username_label, username_labeltext, ref preamble, ref message);
378             check_field(issuer, realm_label, realm_labeltext, ref preamble, ref message);
379             check_field(password_test, password_label, password_labeltext, ref preamble, ref message);
380         }
381         if (message != "") {
382             message_label.set_visible(true);
383             message_label.set_markup(@"<span foreground=\"red\">$preamble$message</span>");
384             return false;
385         }
386         return true;
387     }
388
389     private void on_response(Dialog source, int response_id)
390     {
391         switch (response_id) {
392         case ResponseType.OK:
393             complete = check_fields();
394             break;
395         case ResponseType.CANCEL:
396             complete = true;
397             break;
398         }
399     }
400
401     private VBox make_services_vbox()
402     {
403         logger.trace("make_services_vbox");
404
405         var services_vbox_alignment = new Alignment(0, 0, 1, 0);
406         var services_vscroll = new ScrolledWindow(null, null);
407         services_vscroll.set_policy(PolicyType.NEVER, PolicyType.AUTOMATIC);
408         services_vscroll.set_shadow_type(ShadowType.IN);
409         services_vscroll.set_size_request(0, 60);
410         services_vscroll.add_with_viewport(services_vbox_alignment);
411
412 #if VALA_0_12
413         var remove_button = new Button.from_stock(Stock.REMOVE);
414 #else
415         var remove_button = new Button.from_stock(STOCK_REMOVE);
416 #endif
417         remove_button.set_sensitive(false);
418
419
420         var services_table = new Table(card.services.size, 1, false);
421         services_table.set_row_spacings(1);
422         services_table.set_col_spacings(0);
423         set_bg_color(services_table);
424
425         var table_button_hbox = new HBox(false, 6);
426         table_button_hbox.pack_start(services_vscroll, true, true, 4);
427
428         // Hack to prevent the button from growing vertically
429         VBox fixed_height = new VBox(false, 0);
430         fixed_height.pack_start(remove_button, false, false, 0);
431         table_button_hbox.pack_start(fixed_height, false, false, 0);
432
433         // A table doesn't have a background color, so put it in an EventBox, and
434         // set the EventBox's background color instead.
435         EventBox table_bg = new EventBox();
436         set_bg_color(table_bg);
437         table_bg.add(services_table);
438         services_vbox_alignment.add(table_bg);
439
440         var services_vbox_title = new Label(_("Services:"));
441         services_vbox_title.set_alignment(0, 0.5f);
442
443         var services_vbox = new VBox(false, 6);
444         services_vbox.pack_start(services_vbox_title, false, false, 0);
445         services_vbox.pack_start(table_button_hbox, true, true, 0);
446
447         int i = 0;
448         foreach (string service in card.services)
449         {
450             var label = new Label(service);
451             label.set_alignment((float) 0, (float) 0);
452             label.xpad = 3;
453
454             EventBox event_box = new EventBox();
455             event_box.modify_bg(StateType.NORMAL, white);
456             event_box.add(label);
457             event_box.button_press_event.connect(() =>
458                 {
459                     var state = label.get_state();
460                     logger.trace("button_press_callback: Label state=" + state.to_string() + " setting bg to " + white.to_string());
461
462                     if (selected_item == label)
463                     {
464                         // Deselect
465                         selected_item.parent.modify_bg(state, white);
466                         selected_item = null;
467                         remove_button.set_sensitive(false);
468                     }
469                     else
470                     {
471                         if (selected_item != null)
472                         {
473                             // Deselect
474                             selected_item.parent.modify_bg(state, white);
475                             selected_item = null;
476                         }
477
478                         // Select
479                         selected_item = label;
480                         selected_item.parent.modify_bg(state, selected_color);
481                         remove_button.set_sensitive(true);
482                     }
483                     return false;
484                 });
485
486             services_table.attach_defaults(event_box, 0, 1, i, i+1);
487             i++;
488         }
489
490         remove_button.clicked.connect((remove_button) =>
491             {
492                 var result = WarningDialog.confirm(this,
493                                                    Markup.printf_escaped(
494                                                        "<span font-weight='heavy'>"
495                                                        + _("You are about to remove the service\n'%s'.") 
496                                                        + "</span>",
497                                                        selected_item.label)
498                                                    + _("\n\nAre you sure you want to do this?"),
499                                                    "delete_service");
500
501                 if (result)
502                 {
503                     if (card != null) {
504                         card.services.remove(selected_item.label);
505                         services_table.remove(selected_item.parent);
506                         selected_item = null;
507                         remove_button.set_sensitive(false);
508                     }
509                 }
510
511             });
512
513         return services_vbox;
514     }
515
516     private void export_certificate(IdCard id) 
517     {
518         var dialog = new FileChooserDialog("Save File",
519                                            this,
520                                            FileChooserAction.SAVE,
521                                            _("Cancel"),ResponseType.CANCEL,
522                                            _("Save"), ResponseType.ACCEPT,
523                                            null);
524         dialog.set_do_overwrite_confirmation(true);
525         if (export_directory != null) {
526             dialog.set_current_folder(export_directory);
527         }
528         // Remove slashes from the default filename.
529         string default_filename = 
530             (id.display_name + ".pem").replace(Path.DIR_SEPARATOR_S, "_");
531         dialog.set_current_name(default_filename);
532         if (dialog.run() == ResponseType.ACCEPT)
533         {
534             // Export the certificate in PEM format.
535
536             const string CERT_HEADER = "-----BEGIN CERTIFICATE-----\n";
537             const string CERT_FOOTER = "\n-----END CERTIFICATE-----\n";
538
539             // Strip any embedded newlines in the certificate...
540             string cert = id.trust_anchor.ca_cert.replace("\n", "");
541
542             // Re-embed newlines every 64 chars.
543             string newcert = CERT_HEADER;
544             while (cert.length > 63) {
545                 newcert += cert[0:64];
546                 newcert += "\n";
547                 cert = cert[64:cert.length];
548             }
549             if (cert.length > 0) {
550                 newcert += cert;
551             }
552             newcert += CERT_FOOTER;
553
554             string filename = dialog.get_filename();
555             var file  = File.new_for_path(filename);
556             var stream = file.replace(null, false, FileCreateFlags.PRIVATE);
557             stream.write(newcert.data);
558
559             // Save the parent directory to use as default for next save
560             export_directory = file.get_parent().get_path();
561         }
562         dialog.destroy();
563     }
564 }