File: gitg-credentials-manager.vala

package info (click to toggle)
gitg 41-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 18,876 kB
  • sloc: ansic: 1,636; ruby: 1,445; sh: 314; python: 261; xml: 57; makefile: 15
file content (320 lines) | stat: -rw-r--r-- 7,575 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/*
 * This file is part of gitg
 *
 * Copyright (C) 2014 - Jesse van den Kieboom
 *
 * gitg is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * gitg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gitg. If not, see <http://www.gnu.org/licenses/>.
 */

namespace Gitg
{

public errordomain CredentialsError
{
	CANCELLED
}

public class CredentialsManager
{
	private Ggit.Config? d_config;
	private Gtk.Window d_window;
	private Gee.HashMap<string, string>? d_usermap;
	private bool d_save_user_in_config;
	private string d_last_user;
	private Gee.HashMap<string, Ggit.Credtype> d_auth_tried;

	private static Secret.Schema s_secret_schema;
	private static Regex s_ssh_short_form;

	static construct
	{
		s_secret_schema = new Secret.Schema(Gitg.Config.APPLICATION_ID + ".Credentials",
		                                    Secret.SchemaFlags.NONE,
		                                    "scheme", Secret.SchemaAttributeType.STRING,
		                                    "host", Secret.SchemaAttributeType.STRING,
		                                    "user", Secret.SchemaAttributeType.STRING);

		try
		{
			s_ssh_short_form = new Regex("^(?:[^: /@]+)@(?P<host>[^:]+)");
		} catch (Error e) { stderr.printf("regex err: %s\n", e.message); }
	}

	public CredentialsManager(Ggit.Config? config, Gtk.Window window, bool save_user_in_config)
	{
		d_config = config;
		d_save_user_in_config = save_user_in_config;
		d_auth_tried = new Gee.HashMap<string, Ggit.Credtype>();
		d_window = window;
	}

	private string? lookup_user(string host)
	{
		if (d_usermap == null)
		{
			d_usermap = new Gee.HashMap<string, string?>();

			if (d_config != null)
			{
				try
				{
					var r = new Regex("credential\\.(.*)\\.username");

					d_config.snapshot().match_foreach(r, (info, value) => {
						d_usermap[info.fetch(1)] = value;
						return 0;
					});
				}
				catch (Error e)
				{
					stderr.printf("Could not get username from git config: %s\n", e.message);
				}
			}
		}

		return d_usermap[host];
	}

	private Ggit.Cred? user_pass_dialog(string url, string scheme, string host, string? username) throws Error
	{
		var mutex = Mutex();
		mutex.lock();

		var cond = Cond();

		Gtk.ResponseType response = Gtk.ResponseType.CANCEL;

		string password = "";
		string newusername = "";
		AuthenticationLifeTime lifetime = AuthenticationLifeTime.FORGET;

		Idle.add(() => {
			// Skip SSH_KEY in terms of tried since that might just fail if
			// there is no key and that's not informative to the user
			var tried = d_auth_tried[username] & ~Ggit.Credtype.SSH_KEY;

			var d = new AuthenticationDialog(url, username, tried != 0);
			d.set_transient_for(d_window);

			response = (Gtk.ResponseType)d.run();

			if (response == Gtk.ResponseType.OK)
			{
				newusername = d.username;
				password = d.password;
				lifetime = d.life_time;
			}

			d.destroy();

			mutex.lock();
			cond.signal();
			mutex.unlock();

			return false;
		});

		cond.wait(mutex);
		mutex.unlock();

		if (response != Gtk.ResponseType.OK)
		{
			throw new CredentialsError.CANCELLED("cancelled by user");
		}

		d_last_user = newusername;

		// Save username in config
		if (username == null || newusername != username && d_config != null && d_save_user_in_config)
		{
			if (d_usermap == null)
			{
				d_usermap = new Gee.HashMap<string, string?>();
			}

			try
			{
				var hid = @"$(scheme)://$(host)";

				d_config.set_string(@"credential.$(hid).username", newusername);
				d_usermap[hid] = newusername;
			}
			catch (Error e)
			{
				stderr.printf("Failed to store username in config: %s\n", e.message);
			}
		}

		var attributes = new HashTable<string, string>(str_hash, str_equal);
		attributes["scheme"] = scheme;
		attributes["host"] = host;
		attributes["user"] = newusername;

		// Save secret
		if (lifetime != AuthenticationLifeTime.FORGET)
		{
			string? collection = null;

			if (lifetime == AuthenticationLifeTime.SESSION)
			{
				collection = Secret.COLLECTION_SESSION;
			}

			Secret.password_storev.begin(s_secret_schema,
			                             attributes,
			                             collection,
			                             @"$(scheme)://$(host)",
			                             password,
			                             null,
			                             (obj, res) => {
				try
				{
					Secret.password_storev.end(res);
				}
				catch (Error e)
				{
					stderr.printf("Failed to store secret in keyring: %s\n", e.message);
				}
			});
		}
		else
		{
			Secret.password_clearv.begin(s_secret_schema, attributes, null, (obj, res) => {
				try
				{
					Secret.password_clearv.end(res);
				}
				catch (Error e)
				{
					stderr.printf("Failed to clear secret from keyring: %s\n", e.message);
				}
			});
		}

		d_auth_tried[newusername] |= Ggit.Credtype.USERPASS_PLAINTEXT;
		return new Ggit.CredPlaintext(newusername, password);
	}

	private Ggit.Cred? query_user_pass(string url, string? username) throws Error
	{
		string? user;

		string host = "local";
		string scheme = "file";

		if (!("://" in url))
		{
			MatchInfo minfo;

			if (s_ssh_short_form.match(url, 0, out minfo))
			{
				scheme = "ssh";
				host = minfo.fetch_named("host");
			}
		}
		else
		{
			var uri = GLib.Uri.parse(url, GLib.UriFlags.NONE);

			if (uri != null)
			{
				host = uri.get_host();

				if (uri.get_port() != -1)
				{
					host = @"$(host):$(uri.get_port())";
				}
		
				scheme = uri.get_scheme();
			}
		}

		if (username == null)
		{
			// Try to obtain username from config
			user = lookup_user(@"$scheme://$host");
		}
		else
		{
			user = username;
		}

		if (user != null)
		{
			var tried = d_auth_tried[user];

			if ((tried & Ggit.Credtype.USERPASS_PLAINTEXT) == 0)
			{
				string? secret = null;

				try
				{
					secret = Secret.password_lookup_sync(s_secret_schema, null,
					                                     "scheme", scheme,
					                                     "host", host,
					                                     "user", user);
				}
				catch {}

				if (secret == null)
				{
					return user_pass_dialog(url, scheme, host, user);
				}

				d_auth_tried[user] |= Ggit.Credtype.USERPASS_PLAINTEXT;

				try
				{
					return new Ggit.CredPlaintext(user, secret);
				}
				catch (Error e)
				{
					return user_pass_dialog(url, scheme, host, user);
				}
			}
			else
			{
				return user_pass_dialog(url, scheme, host, user);
			}
		}
		else
		{
			return user_pass_dialog(url, scheme, host, user);
		}
	}

	public Ggit.Cred? credentials(string        url,
	                              string?       username,
	                              Ggit.Credtype allowed_types) throws Error
	{
		var uslookup = username != null ? username : "";
		var tried = d_auth_tried[uslookup];

		var untried_allowed_types = allowed_types & ~tried;

		if ((untried_allowed_types & Ggit.Credtype.SSH_KEY) != 0)
		{
			d_auth_tried[uslookup] = tried | Ggit.Credtype.SSH_KEY;
			return new Ggit.CredSshKeyFromAgent(username);
		}
		else if ((allowed_types & Ggit.Credtype.USERPASS_PLAINTEXT) != 0)
		{
			return query_user_pass(url, username);
		}

		return null;
	}
}

}