Using GitHub private repositories as composer dependencies

Sometimes your workflow requires using private GitHub repositories as composer dependencies. One solution is to use Packagist paid account or Satis. Another option is to add the GitHub repositories to your composer.json file and configure ssh key for each repository.

GitHub forbids you to add one key for multiple repositories for some weird security reason. So you have to configure a dedicated key for each repository.

When you need these dependencies in your clients server, it makes total sense to add ssh key for each client. Just in case your business relation ends with particular client.

Generating a ssh key

You can generate n+1 ssh keys with ssh-keygen command. Make sure you do this in the server!

➜  ~ cd ~/.ssh
➜  .ssh ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa): repo1
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in repo1.
Your public key has been saved in repo1.pub.
The key fingerprint is:
SHA256:EPc79FoaidfN0/PAsjSAZdomex2J1b/4zUR6Oj7IV2o user@laptop
The key's randomart image is:
+---[RSA 2048]----+
|      . . o ..   |
|       o B o ..  |
|      . + B o  . |
|       . * B = .o|
|        S B O B+o|
|         o B =.+*|
|          o....Bo|
|            o E.o|
|             +.o |
+----[SHA256]-----+

After using the ssh-keygen command you will be prompted for the filename and passphrase. You need a key for each private repository you're going to use as composer dependency. In this example the repo1 is the filename.

Make sure you leave the passphrase and confirmation empty.

Configuring the ssh to pick up the correct key

In servers ~/.ssh/config file you can assign an alias for each GitHub repository. Otherwise composer tries to use the default id_rsa.

Host repo1
    HostName github.com
    User git
    IdentityFile ~/.ssh/repo1
    IdentitiesOnly yes

Host repo2
    HostName github.com
    User git
    IdentityFile ~/.ssh/repo2
    IdentitiesOnly yes

Configuring Composer

In projects composer.json file you need to add the repositories you want as dependencies:

"repositories": [
    {
        "type": "vcs",
        "url": "repo1:YourAccount/repo1.git"
    },
    {
        "type": "vcs",
        "url": "repo2:YourAccount/repo2.git"
    }
],

repo1 and repo2 are the aliases you created in ~/ssh/config file. The full GitHub ssh url for repo1 would be:

git@github.com:YourAccount/repo1.git

And now you should be set for good. You can now require your dependencies:

:code-markup composer require youraccount/repo1 -n composer require youraccount/repo2 -n

:

NB! When using GitHub repositories as composer dependencies you always need to add -n to each composer command.