credential: add a field for pre-encoded credentials
[alt-git.git] / credential.c
blobc521822e5a6eddc786a230d7c49c3c23e55e0882
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "config.h"
4 #include "credential.h"
5 #include "gettext.h"
6 #include "string-list.h"
7 #include "run-command.h"
8 #include "url.h"
9 #include "prompt.h"
10 #include "sigchain.h"
11 #include "strbuf.h"
12 #include "urlmatch.h"
13 #include "git-compat-util.h"
15 void credential_init(struct credential *c)
17 struct credential blank = CREDENTIAL_INIT;
18 memcpy(c, &blank, sizeof(*c));
21 void credential_clear(struct credential *c)
23 free(c->protocol);
24 free(c->host);
25 free(c->path);
26 free(c->username);
27 free(c->password);
28 free(c->credential);
29 free(c->oauth_refresh_token);
30 free(c->authtype);
31 string_list_clear(&c->helpers, 0);
32 strvec_clear(&c->wwwauth_headers);
34 credential_init(c);
37 int credential_match(const struct credential *want,
38 const struct credential *have, int match_password)
40 #define CHECK(x) (!want->x || (have->x && !strcmp(want->x, have->x)))
41 return CHECK(protocol) &&
42 CHECK(host) &&
43 CHECK(path) &&
44 CHECK(username) &&
45 (!match_password || CHECK(password));
46 #undef CHECK
50 static int credential_from_potentially_partial_url(struct credential *c,
51 const char *url);
53 static int credential_config_callback(const char *var, const char *value,
54 const struct config_context *ctx UNUSED,
55 void *data)
57 struct credential *c = data;
58 const char *key;
60 if (!skip_prefix(var, "credential.", &key))
61 return 0;
63 if (!value)
64 return config_error_nonbool(var);
66 if (!strcmp(key, "helper")) {
67 if (*value)
68 string_list_append(&c->helpers, value);
69 else
70 string_list_clear(&c->helpers, 0);
71 } else if (!strcmp(key, "username")) {
72 if (!c->username_from_proto) {
73 free(c->username);
74 c->username = xstrdup(value);
77 else if (!strcmp(key, "usehttppath"))
78 c->use_http_path = git_config_bool(var, value);
80 return 0;
83 static int proto_is_http(const char *s)
85 if (!s)
86 return 0;
87 return !strcmp(s, "https") || !strcmp(s, "http");
90 static void credential_describe(struct credential *c, struct strbuf *out);
91 static void credential_format(struct credential *c, struct strbuf *out);
93 static int select_all(const struct urlmatch_item *a UNUSED,
94 const struct urlmatch_item *b UNUSED)
96 return 0;
99 static int match_partial_url(const char *url, void *cb)
101 struct credential *c = cb;
102 struct credential want = CREDENTIAL_INIT;
103 int matches = 0;
105 if (credential_from_potentially_partial_url(&want, url) < 0)
106 warning(_("skipping credential lookup for key: credential.%s"),
107 url);
108 else
109 matches = credential_match(&want, c, 0);
110 credential_clear(&want);
112 return matches;
115 static void credential_apply_config(struct credential *c)
117 char *normalized_url;
118 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
119 struct strbuf url = STRBUF_INIT;
121 if (!c->host)
122 die(_("refusing to work with credential missing host field"));
123 if (!c->protocol)
124 die(_("refusing to work with credential missing protocol field"));
126 if (c->configured)
127 return;
129 config.section = "credential";
130 config.key = NULL;
131 config.collect_fn = credential_config_callback;
132 config.cascade_fn = NULL;
133 config.select_fn = select_all;
134 config.fallback_match_fn = match_partial_url;
135 config.cb = c;
137 credential_format(c, &url);
138 normalized_url = url_normalize(url.buf, &config.url);
140 git_config(urlmatch_config_entry, &config);
141 string_list_clear(&config.vars, 1);
142 free(normalized_url);
143 urlmatch_config_release(&config);
144 strbuf_release(&url);
146 c->configured = 1;
148 if (!c->use_http_path && proto_is_http(c->protocol)) {
149 FREE_AND_NULL(c->path);
153 static void credential_describe(struct credential *c, struct strbuf *out)
155 if (!c->protocol)
156 return;
157 strbuf_addf(out, "%s://", c->protocol);
158 if (c->username && *c->username)
159 strbuf_addf(out, "%s@", c->username);
160 if (c->host)
161 strbuf_addstr(out, c->host);
162 if (c->path)
163 strbuf_addf(out, "/%s", c->path);
166 static void credential_format(struct credential *c, struct strbuf *out)
168 if (!c->protocol)
169 return;
170 strbuf_addf(out, "%s://", c->protocol);
171 if (c->username && *c->username) {
172 strbuf_add_percentencode(out, c->username, STRBUF_ENCODE_SLASH);
173 strbuf_addch(out, '@');
175 if (c->host)
176 strbuf_addstr(out, c->host);
177 if (c->path) {
178 strbuf_addch(out, '/');
179 strbuf_add_percentencode(out, c->path, 0);
183 static char *credential_ask_one(const char *what, struct credential *c,
184 int flags)
186 struct strbuf desc = STRBUF_INIT;
187 struct strbuf prompt = STRBUF_INIT;
188 char *r;
190 credential_describe(c, &desc);
191 if (desc.len)
192 strbuf_addf(&prompt, "%s for '%s': ", what, desc.buf);
193 else
194 strbuf_addf(&prompt, "%s: ", what);
196 r = git_prompt(prompt.buf, flags);
198 strbuf_release(&desc);
199 strbuf_release(&prompt);
200 return xstrdup(r);
203 static void credential_getpass(struct credential *c)
205 if (!c->username)
206 c->username = credential_ask_one("Username", c,
207 PROMPT_ASKPASS|PROMPT_ECHO);
208 if (!c->password)
209 c->password = credential_ask_one("Password", c,
210 PROMPT_ASKPASS);
213 int credential_read(struct credential *c, FILE *fp)
215 struct strbuf line = STRBUF_INIT;
217 while (strbuf_getline(&line, fp) != EOF) {
218 char *key = line.buf;
219 char *value = strchr(key, '=');
221 if (!line.len)
222 break;
224 if (!value) {
225 warning("invalid credential line: %s", key);
226 strbuf_release(&line);
227 return -1;
229 *value++ = '\0';
231 if (!strcmp(key, "username")) {
232 free(c->username);
233 c->username = xstrdup(value);
234 c->username_from_proto = 1;
235 } else if (!strcmp(key, "password")) {
236 free(c->password);
237 c->password = xstrdup(value);
238 } else if (!strcmp(key, "credential")) {
239 free(c->credential);
240 c->credential = xstrdup(value);
241 } else if (!strcmp(key, "protocol")) {
242 free(c->protocol);
243 c->protocol = xstrdup(value);
244 } else if (!strcmp(key, "host")) {
245 free(c->host);
246 c->host = xstrdup(value);
247 } else if (!strcmp(key, "path")) {
248 free(c->path);
249 c->path = xstrdup(value);
250 } else if (!strcmp(key, "wwwauth[]")) {
251 strvec_push(&c->wwwauth_headers, value);
252 } else if (!strcmp(key, "password_expiry_utc")) {
253 errno = 0;
254 c->password_expiry_utc = parse_timestamp(value, NULL, 10);
255 if (c->password_expiry_utc == 0 || errno == ERANGE)
256 c->password_expiry_utc = TIME_MAX;
257 } else if (!strcmp(key, "oauth_refresh_token")) {
258 free(c->oauth_refresh_token);
259 c->oauth_refresh_token = xstrdup(value);
260 } else if (!strcmp(key, "authtype")) {
261 free(c->authtype);
262 c->authtype = xstrdup(value);
263 } else if (!strcmp(key, "url")) {
264 credential_from_url(c, value);
265 } else if (!strcmp(key, "quit")) {
266 c->quit = !!git_config_bool("quit", value);
269 * Ignore other lines; we don't know what they mean, but
270 * this future-proofs us when later versions of git do
271 * learn new lines, and the helpers are updated to match.
275 strbuf_release(&line);
276 return 0;
279 static void credential_write_item(FILE *fp, const char *key, const char *value,
280 int required)
282 if (!value && required)
283 BUG("credential value for %s is missing", key);
284 if (!value)
285 return;
286 if (strchr(value, '\n'))
287 die("credential value for %s contains newline", key);
288 fprintf(fp, "%s=%s\n", key, value);
291 void credential_write(const struct credential *c, FILE *fp)
293 credential_write_item(fp, "protocol", c->protocol, 1);
294 credential_write_item(fp, "host", c->host, 1);
295 credential_write_item(fp, "path", c->path, 0);
296 credential_write_item(fp, "username", c->username, 0);
297 credential_write_item(fp, "password", c->password, 0);
298 credential_write_item(fp, "credential", c->credential, 0);
299 credential_write_item(fp, "oauth_refresh_token", c->oauth_refresh_token, 0);
300 if (c->password_expiry_utc != TIME_MAX) {
301 char *s = xstrfmt("%"PRItime, c->password_expiry_utc);
302 credential_write_item(fp, "password_expiry_utc", s, 0);
303 free(s);
305 for (size_t i = 0; i < c->wwwauth_headers.nr; i++)
306 credential_write_item(fp, "wwwauth[]", c->wwwauth_headers.v[i], 0);
307 credential_write_item(fp, "authtype", c->authtype, 0);
310 static int run_credential_helper(struct credential *c,
311 const char *cmd,
312 int want_output)
314 struct child_process helper = CHILD_PROCESS_INIT;
315 FILE *fp;
317 strvec_push(&helper.args, cmd);
318 helper.use_shell = 1;
319 helper.in = -1;
320 if (want_output)
321 helper.out = -1;
322 else
323 helper.no_stdout = 1;
325 if (start_command(&helper) < 0)
326 return -1;
328 fp = xfdopen(helper.in, "w");
329 sigchain_push(SIGPIPE, SIG_IGN);
330 credential_write(c, fp);
331 fclose(fp);
332 sigchain_pop(SIGPIPE);
334 if (want_output) {
335 int r;
336 fp = xfdopen(helper.out, "r");
337 r = credential_read(c, fp);
338 fclose(fp);
339 if (r < 0) {
340 finish_command(&helper);
341 return -1;
345 if (finish_command(&helper))
346 return -1;
347 return 0;
350 static int credential_do(struct credential *c, const char *helper,
351 const char *operation)
353 struct strbuf cmd = STRBUF_INIT;
354 int r;
356 if (helper[0] == '!')
357 strbuf_addstr(&cmd, helper + 1);
358 else if (is_absolute_path(helper))
359 strbuf_addstr(&cmd, helper);
360 else
361 strbuf_addf(&cmd, "git credential-%s", helper);
363 strbuf_addf(&cmd, " %s", operation);
364 r = run_credential_helper(c, cmd.buf, !strcmp(operation, "get"));
366 strbuf_release(&cmd);
367 return r;
370 void credential_fill(struct credential *c)
372 int i;
374 if ((c->username && c->password) || c->credential)
375 return;
377 credential_apply_config(c);
379 for (i = 0; i < c->helpers.nr; i++) {
380 credential_do(c, c->helpers.items[i].string, "get");
381 if (c->password_expiry_utc < time(NULL)) {
382 /* Discard expired password */
383 FREE_AND_NULL(c->password);
384 /* Reset expiry to maintain consistency */
385 c->password_expiry_utc = TIME_MAX;
387 if ((c->username && c->password) || c->credential)
388 return;
389 if (c->quit)
390 die("credential helper '%s' told us to quit",
391 c->helpers.items[i].string);
394 credential_getpass(c);
395 if (!c->username && !c->password && !c->credential)
396 die("unable to get password from user");
399 void credential_approve(struct credential *c)
401 int i;
403 if (c->approved)
404 return;
405 if (((!c->username || !c->password) && !c->credential) || c->password_expiry_utc < time(NULL))
406 return;
408 credential_apply_config(c);
410 for (i = 0; i < c->helpers.nr; i++)
411 credential_do(c, c->helpers.items[i].string, "store");
412 c->approved = 1;
415 void credential_reject(struct credential *c)
417 int i;
419 credential_apply_config(c);
421 for (i = 0; i < c->helpers.nr; i++)
422 credential_do(c, c->helpers.items[i].string, "erase");
424 FREE_AND_NULL(c->username);
425 FREE_AND_NULL(c->password);
426 FREE_AND_NULL(c->credential);
427 FREE_AND_NULL(c->oauth_refresh_token);
428 c->password_expiry_utc = TIME_MAX;
429 c->approved = 0;
432 static int check_url_component(const char *url, int quiet,
433 const char *name, const char *value)
435 if (!value)
436 return 0;
437 if (!strchr(value, '\n'))
438 return 0;
440 if (!quiet)
441 warning(_("url contains a newline in its %s component: %s"),
442 name, url);
443 return -1;
447 * Potentially-partial URLs can, but do not have to, contain
449 * - a protocol (or scheme) of the form "<protocol>://"
451 * - a host name (the part after the protocol and before the first slash after
452 * that, if any)
454 * - a user name and potentially a password (as "<user>[:<password>]@" part of
455 * the host name)
457 * - a path (the part after the host name, if any, starting with the slash)
459 * Missing parts will be left unset in `struct credential`. Thus, `https://`
460 * will have only the `protocol` set, `example.com` only the host name, and
461 * `/git` only the path.
463 * Note that an empty host name in an otherwise fully-qualified URL (e.g.
464 * `cert:///path/to/cert.pem`) will be treated as unset if we expect the URL to
465 * be potentially partial, and only then (otherwise, the empty string is used).
467 * The credential_from_url() function does not allow partial URLs.
469 static int credential_from_url_1(struct credential *c, const char *url,
470 int allow_partial_url, int quiet)
472 const char *at, *colon, *cp, *slash, *host, *proto_end;
474 credential_clear(c);
477 * Match one of:
478 * (1) proto://<host>/...
479 * (2) proto://<user>@<host>/...
480 * (3) proto://<user>:<pass>@<host>/...
482 proto_end = strstr(url, "://");
483 if (!allow_partial_url && (!proto_end || proto_end == url)) {
484 if (!quiet)
485 warning(_("url has no scheme: %s"), url);
486 return -1;
488 cp = proto_end ? proto_end + 3 : url;
489 at = strchr(cp, '@');
490 colon = strchr(cp, ':');
493 * A query or fragment marker before the slash ends the host portion.
494 * We'll just continue to call this "slash" for simplicity. Notably our
495 * "trim leading slashes" part won't skip over this part of the path,
496 * but that's what we'd want.
498 slash = cp + strcspn(cp, "/?#");
500 if (!at || slash <= at) {
501 /* Case (1) */
502 host = cp;
504 else if (!colon || at <= colon) {
505 /* Case (2) */
506 c->username = url_decode_mem(cp, at - cp);
507 if (c->username && *c->username)
508 c->username_from_proto = 1;
509 host = at + 1;
510 } else {
511 /* Case (3) */
512 c->username = url_decode_mem(cp, colon - cp);
513 if (c->username && *c->username)
514 c->username_from_proto = 1;
515 c->password = url_decode_mem(colon + 1, at - (colon + 1));
516 host = at + 1;
519 if (proto_end && proto_end - url > 0)
520 c->protocol = xmemdupz(url, proto_end - url);
521 if (!allow_partial_url || slash - host > 0)
522 c->host = url_decode_mem(host, slash - host);
523 /* Trim leading and trailing slashes from path */
524 while (*slash == '/')
525 slash++;
526 if (*slash) {
527 char *p;
528 c->path = url_decode(slash);
529 p = c->path + strlen(c->path) - 1;
530 while (p > c->path && *p == '/')
531 *p-- = '\0';
534 if (check_url_component(url, quiet, "username", c->username) < 0 ||
535 check_url_component(url, quiet, "password", c->password) < 0 ||
536 check_url_component(url, quiet, "protocol", c->protocol) < 0 ||
537 check_url_component(url, quiet, "host", c->host) < 0 ||
538 check_url_component(url, quiet, "path", c->path) < 0)
539 return -1;
541 return 0;
544 static int credential_from_potentially_partial_url(struct credential *c,
545 const char *url)
547 return credential_from_url_1(c, url, 1, 0);
550 int credential_from_url_gently(struct credential *c, const char *url, int quiet)
552 return credential_from_url_1(c, url, 0, quiet);
555 void credential_from_url(struct credential *c, const char *url)
557 if (credential_from_url_gently(c, url, 0) < 0)
558 die(_("credential url cannot be parsed: %s"), url);