---
title: "Managing SSH and Git Credentials in R"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Managing SSH and Git Credentials in R}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

The `credentials` package contains tools for configuring and retrieving SSH and HTTPS credentials for use with `git` or other services. It helps users to setup their git installation, and also provides a back-end for packages to authenticate with existing user credentials.

## Two types of remotes

```{r, echo=FALSE}
delete_git_config_on_exit <- !file.exists('~/.gitconfig')
credentials:::set_default_cred_helper()

library <- function(package){
  withCallingHandlers(base::library(credentials), 
                      packageStartupMessage = function(e) {
                        cat(e$message)
                        invokeRestart("muffleMessage")
                      })
}  
```


```{r}
library(credentials)
```

Git supports two types of remotes: SSH and HTTPS. These two use completely distinct authentication systems. 


|         | SSH REMOTES      | HTTPS REMOTES          |
|---------|------------------|------------------------|
| __url__     | `git@server.com` | `https://server.com`   |
| __authentication__    | Personal SSH key          | Password or PAT         |
| __stored in__ | file `id_rsa` or `ssh-agent` | `git credential` store |

For HTTPS remotes, git authenticates with a username + password. With GitHub, instead of a password, you can also use a [Personal Access Token](https://github.com/settings/tokens) (PAT). PATs are preferred because they provide more granular control of permissions (via the PAT's scopes), you can have many of them for different purposes, you can give them informative names, and they can be selectively revoked. Note that, if you use 2FA with GitHub, you must authenticate with a PAT if you use the HTTPS protocol.

For SSH remotes, git shells out to `ssh` on your system, and lets `ssh` take care of authentication. This means you have to setup an ssh key (usually `~/.ssh/id_rsa`) which you then [add to your git profile](https://github.com/settings/ssh/new).

### Special note for Windows

Windows does not include a native `git` installation by default. We recommended to use the latest version of [Git for Windows](https://git-scm.com/download/win). This bundle also includes `ssh` and [git credential manager for windows](https://github.com/Microsoft/Git-Credential-Manager-for-Windows) which is all you need.

Important: ssh keys are stored in your home directory for example: `C:\Users\Jeroen\.ssh\id_rsa`, and __not in the Documents folder__ (which is what R treats as the home sometimes). The `ssh_home()` function shows the correct `.ssh` directory on all platforms.


## Part 1: Storing HTTPS credentials

HTTPS remotes do not always require authentication. You can clone from a public repository without providing any credentials. But for pushing, or private repositories, `git` will prompt for a username/password.

```
git clone https://github.com/jeroen/jsonlite
```

To save you from entering your password over and over, git includes a [credential helper](https://git-scm.com/docs/gitcredentials). It has two modes:

 - `cache`: Cache credentials in memory for a short period of time.
 - `store`: Store credentials permanently in your operating system password manager.
 
To see which helper is configured for a given repo, run:

```{r}
credential_helper_get()
```

Most `git` installations default to `store` if supported because it is more convenient and secure. However the look and policy of the git credential store for entering and retrieving passwords can vary by system, because it uses the OS native password manager.

### Accessing the HTTPS Credential Store from R

The `credentials` R package provides a wrapper around the `git credential` command line API for reading and saving credentials. The `git_credential_ask()` function looks up suitable credentials for a given URL from the store. If no credentials are available, it will attempt to prompt the user for credentials and return those instead.

```{r, echo=FALSE}
# This hack may not work on MacOS server where cred helper is osxkeychain 
# which always requires user interaction. Hence error=TRUE in the next block.
example <- list(protocol = "https", host = "example.com",
  username = "jeroen", password = "supersecret")
credential_approve(example)
```

```{r error=TRUE}
library(credentials)
git_credential_ask('https://example.com')
```

The function `git_credential_update()` looks similar but it behaves slightly different: it first removes existing credentials from the store (if any), then prompts the user for a new username/password, and saves these to the store.

```r
# This should always prompt for new credentials
git_credential_update('https://example.com')
```

In a terminal window this will result in an interactive password prompt. In Windows the user might see something like this (depending on the version of Windows and git configuration):

<img style="width:690px; padding:0;" src="wincred.png">

```{r, echo=FALSE}
credential_reject(list(protocol = "https", host = "example.com"))
```

### Setting your GITHUB_PAT

Automatically populate your `GITHUB_PAT` environment variable from the native git credential store. The credential manager will safely prompt the user for credentials when needed.

```r
credentials::set_github_pat()
## Using GITHUB_PAT from Jeroen Ooms (credential helper: osxkeychain)
```

Use this function in your `.Rprofile` if you want to automatically set `GITHUB_PAT` for each R session, without hardcoding your secrets in plain text, such as in your `.Renviron` file.

### Non-interactive use

Retrieving credentials is by definition interactive, because the user may be required to enter a password or unlock the system keychain. However, saving or deleting credentials can sometimes be done non-interactively, but this depends on which credential helper is used.

The manual page for `credential_approve` and `credential_reject` has more details about how to call the basic git credential api. 


## Part 2: Managing SSH Keys

```{r, echo = FALSE}
ssh_key_info <- function(){
  try({
    out <- credentials:::ssh_key_info(auto_keygen = FALSE)
    out$pubkey = paste(substring(out$pubkey, 1, 80), "...")
    out
  })
}
```

For SSH remotes, git does not handle authentication itself. Git simply shells out to `ssh` on your system and uses your standard user ssh configuration. Hence authenticating with SSH git remotes comes down to setting up your ssh keys and copying these to your profile.

The `credentials` package provides a few utility functions to make this easier. The `ssh_key_info()` function calls out to look up which key `ssh` uses to connect to a given server. This is usually `~/.ssh/id_rsa` unless you have a fancy custom ssh configuration.

```{r}
ssh_key_info()
```

The output shows both the path to your (private) key as well as the ssh pubkey string. The latter is what you have to enter in your [GitHub profile](https://github.com/settings/ssh/new) to associate this key with your user account. You will then be automatically authenticated when using GitHub SSH remotes.

### Generating a key

To use SSH you need a personal key, which is usually stored in `~/.ssh/id_rsa`. If you do not have a key yet, the `ssh_key_info()` function will automatically ask if you want to generate one.

<img style="width:690px; padding:0;" src="keygen.png">

You can also generate a key manually elsewhere using the `ssh_keygen()` function.

```{r echo=FALSE}
if(isTRUE(delete_git_config_on_exit))
  unlink("~/.gitconfig")
```
