Revert "Merge branch 'jc/patch-id' into maint-2.46"
[git/gitster.git] / credential.c
blob4b1a2b94feff73d31d5682b44ce4bfd14f88594e
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 credential_clear_secrets(c);
24 free(c->protocol);
25 free(c->host);
26 free(c->path);
27 free(c->username);
28 free(c->oauth_refresh_token);
29 free(c->authtype);
30 string_list_clear(&c->helpers, 0);
31 strvec_clear(&c->wwwauth_headers);
32 strvec_clear(&c->state_headers);
33 strvec_clear(&c->state_headers_to_send);
35 credential_init(c);
38 void credential_next_state(struct credential *c)
40 strvec_clear(&c->state_headers_to_send);
41 SWAP(c->state_headers, c->state_headers_to_send);
44 void credential_clear_secrets(struct credential *c)
46 FREE_AND_NULL(c->password);
47 FREE_AND_NULL(c->credential);
50 static void credential_set_capability(struct credential_capability *capa,
51 enum credential_op_type op_type)
53 switch (op_type) {
54 case CREDENTIAL_OP_INITIAL:
55 capa->request_initial = 1;
56 break;
57 case CREDENTIAL_OP_HELPER:
58 capa->request_helper = 1;
59 break;
60 case CREDENTIAL_OP_RESPONSE:
61 capa->response = 1;
62 break;
67 void credential_set_all_capabilities(struct credential *c,
68 enum credential_op_type op_type)
70 credential_set_capability(&c->capa_authtype, op_type);
71 credential_set_capability(&c->capa_state, op_type);
74 static void announce_one(struct credential_capability *cc, const char *name, FILE *fp) {
75 if (cc->request_initial)
76 fprintf(fp, "capability %s\n", name);
79 void credential_announce_capabilities(struct credential *c, FILE *fp) {
80 fprintf(fp, "version 0\n");
81 announce_one(&c->capa_authtype, "authtype", fp);
82 announce_one(&c->capa_state, "state", fp);
85 int credential_match(const struct credential *want,
86 const struct credential *have, int match_password)
88 #define CHECK(x) (!want->x || (have->x && !strcmp(want->x, have->x)))
89 return CHECK(protocol) &&
90 CHECK(host) &&
91 CHECK(path) &&
92 CHECK(username) &&
93 (!match_password || CHECK(password)) &&
94 (!match_password || CHECK(credential));
95 #undef CHECK
99 static int credential_from_potentially_partial_url(struct credential *c,
100 const char *url);
102 static int credential_config_callback(const char *var, const char *value,
103 const struct config_context *ctx UNUSED,
104 void *data)
106 struct credential *c = data;
107 const char *key;
109 if (!skip_prefix(var, "credential.", &key))
110 return 0;
112 if (!value)
113 return config_error_nonbool(var);
115 if (!strcmp(key, "helper")) {
116 if (*value)
117 string_list_append(&c->helpers, value);
118 else
119 string_list_clear(&c->helpers, 0);
120 } else if (!strcmp(key, "username")) {
121 if (!c->username_from_proto) {
122 free(c->username);
123 c->username = xstrdup(value);
126 else if (!strcmp(key, "usehttppath"))
127 c->use_http_path = git_config_bool(var, value);
129 return 0;
132 static int proto_is_http(const char *s)
134 if (!s)
135 return 0;
136 return !strcmp(s, "https") || !strcmp(s, "http");
139 static void credential_describe(struct credential *c, struct strbuf *out);
140 static void credential_format(struct credential *c, struct strbuf *out);
142 static int select_all(const struct urlmatch_item *a UNUSED,
143 const struct urlmatch_item *b UNUSED)
145 return 0;
148 static int match_partial_url(const char *url, void *cb)
150 struct credential *c = cb;
151 struct credential want = CREDENTIAL_INIT;
152 int matches = 0;
154 if (credential_from_potentially_partial_url(&want, url) < 0)
155 warning(_("skipping credential lookup for key: credential.%s"),
156 url);
157 else
158 matches = credential_match(&want, c, 0);
159 credential_clear(&want);
161 return matches;
164 static void credential_apply_config(struct credential *c)
166 char *normalized_url;
167 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
168 struct strbuf url = STRBUF_INIT;
170 if (!c->host)
171 die(_("refusing to work with credential missing host field"));
172 if (!c->protocol)
173 die(_("refusing to work with credential missing protocol field"));
175 if (c->configured)
176 return;
178 config.section = "credential";
179 config.key = NULL;
180 config.collect_fn = credential_config_callback;
181 config.cascade_fn = NULL;
182 config.select_fn = select_all;
183 config.fallback_match_fn = match_partial_url;
184 config.cb = c;
186 credential_format(c, &url);
187 normalized_url = url_normalize(url.buf, &config.url);
189 git_config(urlmatch_config_entry, &config);
190 string_list_clear(&config.vars, 1);
191 free(normalized_url);
192 urlmatch_config_release(&config);
193 strbuf_release(&url);
195 c->configured = 1;
197 if (!c->use_http_path && proto_is_http(c->protocol)) {
198 FREE_AND_NULL(c->path);
202 static void credential_describe(struct credential *c, struct strbuf *out)
204 if (!c->protocol)
205 return;
206 strbuf_addf(out, "%s://", c->protocol);
207 if (c->username && *c->username)
208 strbuf_addf(out, "%s@", c->username);
209 if (c->host)
210 strbuf_addstr(out, c->host);
211 if (c->path)
212 strbuf_addf(out, "/%s", c->path);
215 static void credential_format(struct credential *c, struct strbuf *out)
217 if (!c->protocol)
218 return;
219 strbuf_addf(out, "%s://", c->protocol);
220 if (c->username && *c->username) {
221 strbuf_add_percentencode(out, c->username, STRBUF_ENCODE_SLASH);
222 strbuf_addch(out, '@');
224 if (c->host)
225 strbuf_addstr(out, c->host);
226 if (c->path) {
227 strbuf_addch(out, '/');
228 strbuf_add_percentencode(out, c->path, 0);
232 static char *credential_ask_one(const char *what, struct credential *c,
233 int flags)
235 struct strbuf desc = STRBUF_INIT;
236 struct strbuf prompt = STRBUF_INIT;
237 char *r;
239 credential_describe(c, &desc);
240 if (desc.len)
241 strbuf_addf(&prompt, "%s for '%s': ", what, desc.buf);
242 else
243 strbuf_addf(&prompt, "%s: ", what);
245 r = git_prompt(prompt.buf, flags);
247 strbuf_release(&desc);
248 strbuf_release(&prompt);
249 return xstrdup(r);
252 static void credential_getpass(struct credential *c)
254 if (!c->username)
255 c->username = credential_ask_one("Username", c,
256 PROMPT_ASKPASS|PROMPT_ECHO);
257 if (!c->password)
258 c->password = credential_ask_one("Password", c,
259 PROMPT_ASKPASS);
262 int credential_has_capability(const struct credential_capability *capa,
263 enum credential_op_type op_type)
266 * We're checking here if each previous step indicated that we had the
267 * capability. If it did, then we want to pass it along; conversely, if
268 * it did not, we don't want to report that to our caller.
270 switch (op_type) {
271 case CREDENTIAL_OP_HELPER:
272 return capa->request_initial;
273 case CREDENTIAL_OP_RESPONSE:
274 return capa->request_initial && capa->request_helper;
275 default:
276 return 0;
280 int credential_read(struct credential *c, FILE *fp,
281 enum credential_op_type op_type)
283 struct strbuf line = STRBUF_INIT;
285 while (strbuf_getline(&line, fp) != EOF) {
286 char *key = line.buf;
287 char *value = strchr(key, '=');
289 if (!line.len)
290 break;
292 if (!value) {
293 warning("invalid credential line: %s", key);
294 strbuf_release(&line);
295 return -1;
297 *value++ = '\0';
299 if (!strcmp(key, "username")) {
300 free(c->username);
301 c->username = xstrdup(value);
302 c->username_from_proto = 1;
303 } else if (!strcmp(key, "password")) {
304 free(c->password);
305 c->password = xstrdup(value);
306 } else if (!strcmp(key, "credential")) {
307 free(c->credential);
308 c->credential = xstrdup(value);
309 } else if (!strcmp(key, "protocol")) {
310 free(c->protocol);
311 c->protocol = xstrdup(value);
312 } else if (!strcmp(key, "host")) {
313 free(c->host);
314 c->host = xstrdup(value);
315 } else if (!strcmp(key, "path")) {
316 free(c->path);
317 c->path = xstrdup(value);
318 } else if (!strcmp(key, "ephemeral")) {
319 c->ephemeral = !!git_config_bool("ephemeral", value);
320 } else if (!strcmp(key, "wwwauth[]")) {
321 strvec_push(&c->wwwauth_headers, value);
322 } else if (!strcmp(key, "state[]")) {
323 strvec_push(&c->state_headers, value);
324 } else if (!strcmp(key, "capability[]")) {
325 if (!strcmp(value, "authtype"))
326 credential_set_capability(&c->capa_authtype, op_type);
327 else if (!strcmp(value, "state"))
328 credential_set_capability(&c->capa_state, op_type);
329 } else if (!strcmp(key, "continue")) {
330 c->multistage = !!git_config_bool("continue", value);
331 } else if (!strcmp(key, "password_expiry_utc")) {
332 errno = 0;
333 c->password_expiry_utc = parse_timestamp(value, NULL, 10);
334 if (c->password_expiry_utc == 0 || errno == ERANGE)
335 c->password_expiry_utc = TIME_MAX;
336 } else if (!strcmp(key, "oauth_refresh_token")) {
337 free(c->oauth_refresh_token);
338 c->oauth_refresh_token = xstrdup(value);
339 } else if (!strcmp(key, "authtype")) {
340 free(c->authtype);
341 c->authtype = xstrdup(value);
342 } else if (!strcmp(key, "url")) {
343 credential_from_url(c, value);
344 } else if (!strcmp(key, "quit")) {
345 c->quit = !!git_config_bool("quit", value);
348 * Ignore other lines; we don't know what they mean, but
349 * this future-proofs us when later versions of git do
350 * learn new lines, and the helpers are updated to match.
354 strbuf_release(&line);
355 return 0;
358 static void credential_write_item(FILE *fp, const char *key, const char *value,
359 int required)
361 if (!value && required)
362 BUG("credential value for %s is missing", key);
363 if (!value)
364 return;
365 if (strchr(value, '\n'))
366 die("credential value for %s contains newline", key);
367 fprintf(fp, "%s=%s\n", key, value);
370 void credential_write(const struct credential *c, FILE *fp,
371 enum credential_op_type op_type)
373 if (credential_has_capability(&c->capa_authtype, op_type))
374 credential_write_item(fp, "capability[]", "authtype", 0);
375 if (credential_has_capability(&c->capa_state, op_type))
376 credential_write_item(fp, "capability[]", "state", 0);
378 if (credential_has_capability(&c->capa_authtype, op_type)) {
379 credential_write_item(fp, "authtype", c->authtype, 0);
380 credential_write_item(fp, "credential", c->credential, 0);
381 if (c->ephemeral)
382 credential_write_item(fp, "ephemeral", "1", 0);
384 credential_write_item(fp, "protocol", c->protocol, 1);
385 credential_write_item(fp, "host", c->host, 1);
386 credential_write_item(fp, "path", c->path, 0);
387 credential_write_item(fp, "username", c->username, 0);
388 credential_write_item(fp, "password", c->password, 0);
389 credential_write_item(fp, "oauth_refresh_token", c->oauth_refresh_token, 0);
390 if (c->password_expiry_utc != TIME_MAX) {
391 char *s = xstrfmt("%"PRItime, c->password_expiry_utc);
392 credential_write_item(fp, "password_expiry_utc", s, 0);
393 free(s);
395 for (size_t i = 0; i < c->wwwauth_headers.nr; i++)
396 credential_write_item(fp, "wwwauth[]", c->wwwauth_headers.v[i], 0);
397 if (credential_has_capability(&c->capa_state, op_type)) {
398 if (c->multistage)
399 credential_write_item(fp, "continue", "1", 0);
400 for (size_t i = 0; i < c->state_headers_to_send.nr; i++)
401 credential_write_item(fp, "state[]", c->state_headers_to_send.v[i], 0);
405 static int run_credential_helper(struct credential *c,
406 const char *cmd,
407 int want_output)
409 struct child_process helper = CHILD_PROCESS_INIT;
410 FILE *fp;
412 strvec_push(&helper.args, cmd);
413 helper.use_shell = 1;
414 helper.in = -1;
415 if (want_output)
416 helper.out = -1;
417 else
418 helper.no_stdout = 1;
420 if (start_command(&helper) < 0)
421 return -1;
423 fp = xfdopen(helper.in, "w");
424 sigchain_push(SIGPIPE, SIG_IGN);
425 credential_write(c, fp, want_output ? CREDENTIAL_OP_HELPER : CREDENTIAL_OP_RESPONSE);
426 fclose(fp);
427 sigchain_pop(SIGPIPE);
429 if (want_output) {
430 int r;
431 fp = xfdopen(helper.out, "r");
432 r = credential_read(c, fp, CREDENTIAL_OP_HELPER);
433 fclose(fp);
434 if (r < 0) {
435 finish_command(&helper);
436 return -1;
440 if (finish_command(&helper))
441 return -1;
442 return 0;
445 static int credential_do(struct credential *c, const char *helper,
446 const char *operation)
448 struct strbuf cmd = STRBUF_INIT;
449 int r;
451 if (helper[0] == '!')
452 strbuf_addstr(&cmd, helper + 1);
453 else if (is_absolute_path(helper))
454 strbuf_addstr(&cmd, helper);
455 else
456 strbuf_addf(&cmd, "git credential-%s", helper);
458 strbuf_addf(&cmd, " %s", operation);
459 r = run_credential_helper(c, cmd.buf, !strcmp(operation, "get"));
461 strbuf_release(&cmd);
462 return r;
465 void credential_fill(struct credential *c, int all_capabilities)
467 int i;
469 if ((c->username && c->password) || c->credential)
470 return;
472 credential_next_state(c);
473 c->multistage = 0;
475 credential_apply_config(c);
476 if (all_capabilities)
477 credential_set_all_capabilities(c, CREDENTIAL_OP_INITIAL);
479 for (i = 0; i < c->helpers.nr; i++) {
480 credential_do(c, c->helpers.items[i].string, "get");
482 if (c->password_expiry_utc < time(NULL)) {
484 * Don't use credential_clear() here: callers such as
485 * cmd_credential() expect to still be able to call
486 * credential_write() on a struct credential whose
487 * secrets have expired.
489 credential_clear_secrets(c);
490 /* Reset expiry to maintain consistency */
491 c->password_expiry_utc = TIME_MAX;
493 if ((c->username && c->password) || c->credential) {
494 strvec_clear(&c->wwwauth_headers);
495 return;
497 if (c->quit)
498 die("credential helper '%s' told us to quit",
499 c->helpers.items[i].string);
502 credential_getpass(c);
503 if (!c->username && !c->password && !c->credential)
504 die("unable to get password from user");
507 void credential_approve(struct credential *c)
509 int i;
511 if (c->approved)
512 return;
513 if (((!c->username || !c->password) && !c->credential) || c->password_expiry_utc < time(NULL))
514 return;
516 credential_next_state(c);
518 credential_apply_config(c);
520 for (i = 0; i < c->helpers.nr; i++)
521 credential_do(c, c->helpers.items[i].string, "store");
522 c->approved = 1;
525 void credential_reject(struct credential *c)
527 int i;
529 credential_next_state(c);
531 credential_apply_config(c);
533 for (i = 0; i < c->helpers.nr; i++)
534 credential_do(c, c->helpers.items[i].string, "erase");
536 credential_clear_secrets(c);
537 FREE_AND_NULL(c->username);
538 FREE_AND_NULL(c->oauth_refresh_token);
539 c->password_expiry_utc = TIME_MAX;
540 c->approved = 0;
543 static int check_url_component(const char *url, int quiet,
544 const char *name, const char *value)
546 if (!value)
547 return 0;
548 if (!strchr(value, '\n'))
549 return 0;
551 if (!quiet)
552 warning(_("url contains a newline in its %s component: %s"),
553 name, url);
554 return -1;
558 * Potentially-partial URLs can, but do not have to, contain
560 * - a protocol (or scheme) of the form "<protocol>://"
562 * - a host name (the part after the protocol and before the first slash after
563 * that, if any)
565 * - a user name and potentially a password (as "<user>[:<password>]@" part of
566 * the host name)
568 * - a path (the part after the host name, if any, starting with the slash)
570 * Missing parts will be left unset in `struct credential`. Thus, `https://`
571 * will have only the `protocol` set, `example.com` only the host name, and
572 * `/git` only the path.
574 * Note that an empty host name in an otherwise fully-qualified URL (e.g.
575 * `cert:///path/to/cert.pem`) will be treated as unset if we expect the URL to
576 * be potentially partial, and only then (otherwise, the empty string is used).
578 * The credential_from_url() function does not allow partial URLs.
580 static int credential_from_url_1(struct credential *c, const char *url,
581 int allow_partial_url, int quiet)
583 const char *at, *colon, *cp, *slash, *host, *proto_end;
585 credential_clear(c);
588 * Match one of:
589 * (1) proto://<host>/...
590 * (2) proto://<user>@<host>/...
591 * (3) proto://<user>:<pass>@<host>/...
593 proto_end = strstr(url, "://");
594 if (!allow_partial_url && (!proto_end || proto_end == url)) {
595 if (!quiet)
596 warning(_("url has no scheme: %s"), url);
597 return -1;
599 cp = proto_end ? proto_end + 3 : url;
600 at = strchr(cp, '@');
601 colon = strchr(cp, ':');
604 * A query or fragment marker before the slash ends the host portion.
605 * We'll just continue to call this "slash" for simplicity. Notably our
606 * "trim leading slashes" part won't skip over this part of the path,
607 * but that's what we'd want.
609 slash = cp + strcspn(cp, "/?#");
611 if (!at || slash <= at) {
612 /* Case (1) */
613 host = cp;
615 else if (!colon || at <= colon) {
616 /* Case (2) */
617 c->username = url_decode_mem(cp, at - cp);
618 if (c->username && *c->username)
619 c->username_from_proto = 1;
620 host = at + 1;
621 } else {
622 /* Case (3) */
623 c->username = url_decode_mem(cp, colon - cp);
624 if (c->username && *c->username)
625 c->username_from_proto = 1;
626 c->password = url_decode_mem(colon + 1, at - (colon + 1));
627 host = at + 1;
630 if (proto_end && proto_end - url > 0)
631 c->protocol = xmemdupz(url, proto_end - url);
632 if (!allow_partial_url || slash - host > 0)
633 c->host = url_decode_mem(host, slash - host);
634 /* Trim leading and trailing slashes from path */
635 while (*slash == '/')
636 slash++;
637 if (*slash) {
638 char *p;
639 c->path = url_decode(slash);
640 p = c->path + strlen(c->path) - 1;
641 while (p > c->path && *p == '/')
642 *p-- = '\0';
645 if (check_url_component(url, quiet, "username", c->username) < 0 ||
646 check_url_component(url, quiet, "password", c->password) < 0 ||
647 check_url_component(url, quiet, "protocol", c->protocol) < 0 ||
648 check_url_component(url, quiet, "host", c->host) < 0 ||
649 check_url_component(url, quiet, "path", c->path) < 0)
650 return -1;
652 return 0;
655 static int credential_from_potentially_partial_url(struct credential *c,
656 const char *url)
658 return credential_from_url_1(c, url, 1, 0);
661 int credential_from_url_gently(struct credential *c, const char *url, int quiet)
663 return credential_from_url_1(c, url, 0, quiet);
666 void credential_from_url(struct credential *c, const char *url)
668 if (credential_from_url_gently(c, url, 0) < 0)
669 die(_("credential url cannot be parsed: %s"), url);