Why does go module ssh custom private repo (non-github) config still request https fetch? - go

I am using Go modules.
In order to use module version, I cannot use local module. For example:
replace locakpkg => ../localpkg v0.1.0
The above will fail because replacement local path cannot have version so far (go 1.15).
Thus, to make the module version work, I decided to use a private ssh repo.
I did search how to make private ssh repo work for two days.
By following many online articles, I did
git config --global url.user#private.com:.insteadOf https://private.com/
go env -w GOPRIVATE=private.com
I found out go get will always do https fetch to check ssl credential. So I configured a https server properly too.
But in the end, I still get an error message:
unrecognized import path "private.com/foo": reading https://private.com/foo?go-get=1: 404 Not Found
I did google this error and found out this spec https://golang.org/ref/mod#vcs-find which says I have to let the server reply with <meta name="go-import" content="root-path vcs repo-url"> for https fetch request.
If there is a way to use git tag versioning in local module packages, I am OK to use local replace in go.mod instead of configuring a private ssh repo.
If the above point is not possible, how to avoid https fetch when I configure a private ssh repo? I think ssh repo has nothing to do with https protocol.

(I am using go 1.15 at linux. The latest stable version while posting this answer)
I solved the problem and posting here, hopefully, this will help other people one day. I don't find any correct answer by my search online.
In short, the answer is to use .git suffix in all places. Without .git suffix, go mod tidy and go get will use https instead of ssh (git).
At Client:
The file ~/.gitconfig (at linux) if you use /repopath/foo.git path at server:
[url "ssh://user#private.com"]
insteadOf = https://private.com
The file ~/.gitconfig (at linux) if you use ~/repopath/foo.git path at server:
[url "user#private.com:"]
insteadOf = https://private.com/
Execute the following to update ~/.config/go/env at linux:
go env -w GOPRIVATE=private.com
In go.mod, it should use
require private.com/repopath/foo.git v0.1.0
In file.go, it should be
import private.com/repopath/foo.git
At SSH Server
in foo.git/go.mod at private server should have:
module private.com/repopath/foo.git
And make sure the git repo at server has tag version v0.1.0. Don't forget to use git push --tags at client to update the tag version to the server. Without --tags, tag version will not be pushed.
After adding .git suffix to all the required places, go mod tidy and go get will no longer send https request.

Related

How does golang import github private library dependencies [duplicate]

I'm searching for the way to get $ go get work with private repository, after many google try.
The first try:
$ go get -v gitlab.com/secmask/awserver-go
Fetching https://gitlab.com/secmask/awserver-go?go-get=1
https fetch failed.
Fetching http://gitlab.com/secmask/awserver-go?go-get=1
Parsing meta tags from http://gitlab.com/secmask/awserver-go?go-get=1 (status code 200)
import "gitlab.com/secmask/awserver-go": parse http://gitlab.com/secmask/awserver-go?go-get=1: no go-import meta tags
package gitlab.com/secmask/awserver-go: unrecognized import path "gitlab.com/secmask/awserver-go
Yep, it did not see the meta tags because I could not know how to provide login information.
The second try:
Follow https://gist.github.com/shurcooL/6927554. Add config to .gitconfig.
[url "ssh://git#gitlab.com/"]
insteadOf = https://gitlab.com/
$ go get -v gitlab.com/secmask/awserver-go --> not work
$ go get -v gitlab.com/secmask/awserver-go.git --> work but I got src/gitlab.com/secmask/awserer-go.git
Yes it work but with .git extension with my project name, I can rename it to original but do it everytime $ go get is not so good, is there an otherway?
You have one thing to configure. The example is based on GitHub but this shouldn't change the process:
$ git config --global url.git#github.com:.insteadOf https://github.com/
$ cat ~/.gitconfig
[url "git#github.com:"]
insteadOf = https://github.com/
$ go get github.com/private/repo
For Go modules to work (with Go 1.11 or newer), you'll also need to set the GOPRIVATE variable, to avoid using the public servers to fetch the code:
export GOPRIVATE=github.com/private/repo
The proper way is to manually put the repository in the right place. Once the repository is there, you can use go get -u to update the package and go install to install it. A package named
github.com/secmask/awserver-go
goes into
$GOPATH/src/github.com/secmask/awserver-go
The commands you type are:
cd $GOPATH/src/github.com/secmask
git clone git#github.com:secmask/awserver-go.git
I had a problem with go get using private repository on gitlab from our company.
I lost a few minutes trying to find a solution. And I did find this one:
You need to get a private token at:
https://gitlab.mycompany.com/profile/account
Configure you git to add extra header with your private token:
$ git config --global http.extraheader "PRIVATE-TOKEN: YOUR_PRIVATE_TOKEN"
Configure your git to convert requests from http to ssh:
$ git config --global url."git#gitlab.mycompany.com:".insteadOf "https://gitlab.mycompany.com/"
Finally you can use your go get normally:
$ go get gitlab.com/company/private_repo
For people using private GitLabs, here's a snippet that may help: https://gist.github.com/MicahParks/1ba2b19c39d1e5fccc3e892837b10e21
Also pasted below:
Problem
The go command line tool needs to be able to fetch dependencies from your private GitLab, but authenticaiton is required.
This assumes your private GitLab is hosted at privategitlab.company.com.
Environment variables
The following environment variables are recommended:
export GO111MODULE=on
export GOPRIVATE=privategitlab.company.com # this is comma delimited if using multiple private repos
The above lines might fit best in your shell startup, like a ~/.bashrc.
Explanation
GO111MODULE=on tells Golang command line tools you are using modules. I have not tested this with projects not using
Golang modules on a private GitLab.
GOPRIVATE=privategitlab.company.com tells Golang command line tools to not use public internet resources for the hostnames
listed (like the public module proxy).
Get a personal access token from your private GitLab
To future proof these instructions, please follow this guide from the GitLab docs.
I know that the read_api scope is required for Golang command line tools to work, and I may suspect read_repository as
well, but have not confirmed this.
Set up the ~/.netrc
In order for the Golang command line tools to authenticate to GitLab, a ~/.netrc file is best to use.
To create the file if it does not exist, run the following commands:
touch ~/.netrc
chmod 600 ~/.netrc
Now edit the contents of the file to match the following:
machine privategitlab.company.com login USERNAME_HERE password TOKEN_HERE
Where USERNAME_HERE is replaced with your GitLab username and TOKEN_HERE is replaced with the access token aquired in the
previous section.
Common mistakes
Do not set up a global git configuration with something along the lines of this:
git config --global url."git#privategitlab.company.com:".insteadOf "https://privategitlab.company.com"
I beleive at the time of writing this, the SSH git is not fully supported by Golang command line tools and this may cause
conflicts with the ~/.netrc.
Bonus: SSH config file
For regular use of the git tool, not the Golang command line tools, it's convient to have a ~/.ssh/config file set up.
In order to do this, run the following commands:
mkdir ~/.ssh
chmod 700 ~/.ssh
touch ~/.ssh/config
chmod 600 ~/.ssh/config
Please note the permissions on the files and directory above are essentail for SSH to work in it's default configuration on
most Linux systems.
Then, edit the ~/.ssh/config file to match the following:
Host privategitlab.company.com
Hostname privategitlab.company.com
User USERNAME_HERE
IdentityFile ~/.ssh/id_rsa
Please note the spacing in the above file matters and will invalidate the file if it is incorrect.
Where USERNAME_HERE is your GitLab username and ~/.ssh/id_rsa is the path to your SSH private key in your file system.
You've already uploaded its public key to GitLab. Here are some instructions.
All of the above did not work for me. Cloning the repo was working correctly but I was still getting an unrecognized import error.
As it stands for Go v1.13, I found in the doc that we should use the GOPRIVATE env variable like so:
$ GOPRIVATE=github.com/ORGANISATION_OR_USER_NAME go get -u github.com/ORGANISATION_OR_USER_NAME/REPO_NAME
Generate a github oauth token here and export your github token as an environment variable:
export GITHUB_TOKEN=123
Set git config to use the basic auth url:
git config --global url."https://$GITHUB_TOKEN:x-oauth-basic#github.com/".insteadOf "https://github.com/"
Now you can go get your private repo.
If you've already got git using SSH, this answer by Ammar Bandukwala is a simple workaround:
$ go get uses git internally. The following one liners will make git and consequently $ go get clone your package via SSH.
Github:
$ git config --global url."git#github.com:".insteadOf "https://github.com/"
BitBucket:
$ git config --global url."git#bitbucket.org:".insteadOf "https://bitbucket.org/"
I came across .netrc and found it relevant to this.
Create a file ~/.netrc with the following content:
machine github.com
login <github username>
password <github password or Personal access tokens >
Done!
Additionally, for latest GO versions, you might need to add this to the environment variables GOPRIVATE=github.com
(I've added it to my .zshrc)
netrc also makes my development environment setup better as my personal github access for HTTPS is been configured now to be used across the machine (just like my SSH configuration).
Generate GitHub personal access tokens: https://github.com/settings/tokens
See this answer for its use with Git on Windows specifically
Ref: netrc man page
If you want to stick with the SSH authentication, then mask the request to use ssh forcefully
git config --global url."git#github.com:".insteadOf "https://github.com/"
More methods for setting up git access: https://gist.github.com/technoweenie/1072829#gistcomment-2979908
That looks like the GitLab issue 5769.
In GitLab, since the repositories always end in .git, I must specify .git at the end of the repository name to make it work, for example:
import "example.org/myuser/mygorepo.git"
And:
$ go get example.org/myuser/mygorepo.git
Looks like GitHub solves this by appending ".git".
It is supposed to be resolved in “Added support for Go's repository retrieval. #5958”, provided the right meta tags are in place.
Although there is still an issue for Go itself: “cmd/go: go get cannot discover meta tag in HTML5 documents”.
After trying multiple solutions my problem still persisted. The final solution after setting up the ~/.netrc and SSH config file, was to add the following line to my ~/.bash_profile
export GOPRIVATE="github.com/[organization]"
I have created a user specific ssh-config, so my user automatically logs in with the correct credentials and key.
First I needed to generate an key-pair
ssh-keygen -t rsa -b 4096 -C "my#email.here"
and saved it to e.g ~/.ssh/id_my_domain. Note that this is also the keypair (private and public) I've connected to my Github account, so mine is stored in~/.ssh/id_github_com.
I have then created (or altered) a file called ~/.ssh/config with an entry:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_github_com
On another server, the "ssh-url" is admin#domain.com:username/private-repo.git and the entry for this server would have been:
Host domain.com
HostName domain.com
User admin
IdentityFile ~/.ssh/id_domain_com
Just to clarify that you need ensure that the User, Host and HostName is set correctly.
Now I can just browse into the go path and then go get <package>, e.g go get main where the file main/main.go includes the package (from last example above) domain.com:username/private-repo.git.
For me, the solutions offered by others still gave the following error during go get
git#gl.nimi24.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
What this solution required
As stated by others:
git config --global url."git#github.com:".insteadOf "https://github.com/"
Removing the passphrase from my ./ssh/id_rsa key which was used for authenticating the connection to the repository. This can be done by entering an empty password when prompted as a response to:
ssh-keygen -p
Why this works
This is not a pretty workaround as it is always better to have a passphrase on your private key, but it was causing issues somewhere inside OpenSSH.
go get uses internally git, which uses openssh to open the connection. OpenSSH takes the certs necessary for authentication from .ssh/id_rsa. When executing git commands from the command line an agent can take care of opening the id_rsa file for you so that you do not have to specify the passphrase every time, but when executed in the belly of go get, this did not work somewhy in my case. OpenSSH wants to prompt you then for a password but since it is not possible due to how it was called, it prints to its debug log:
read_passphrase: can't open /dev/tty: No such device or address
And just fails. If you remove the passphrase from the key file, OpenSSH will get to your key without that prompt and it works
This might be caused by Go fetching modules concurrently and opening multiple SSH connections to Github at the same time (as described in this article). This is somewhat supported by the fact that OpenSSH debug log showed the initial connection to the repository succeed, but later tried it again for some reason and this time opted to ask for a passphrase.
However the solution of using SSH connection multiplexing as put forward in the mentioned article did not work for me. For the record, the author suggested adding the collowing conf to the ssh config file for the affected host:
ControlMaster auto
ControlPersist 3600
ControlPath ~/.ssh/%r#%h:%p
But as stated, for me it did not work, maybe I did it wrong
After setting up GOPRIVATE and git config ...
People may still meeting problems like this when fetching private source:
https fetch: Get "https://private/user/repo?go-get=1": EOF
They can't use private repo without .git extension.
The reason is the go tool has no idea about the VCS protocol of this repo, git or svn or any other, unlike github.com or golang.org them are hardcoded into go's source.
Then the go tool will do a https query before fetching your private repo:
https://private/user/repo?go-get=1
If your private repo has no support for https request, please use replace to tell it directly :
require private/user/repo v1.0.0
...
replace private/user/repo => private.server/user/repo.git v1.0.0
https://golang.org/cmd/go/#hdr-Remote_import_paths
Make sure you remove your previous gitconfigs, I had the same issue.
Previously I executed gitconfig whose token was expired, when you execute the command next time with new token make sure to delete previous one.
first I tried
[url "ssh://git#github.com/"]
insteadOf = https://github.com/
but it didn't worked for my local.
I tried
ssh -t git#github.com
and it shows my ssh is fine.
finally, I fix the problem to tell the go get to consider all as private and use ssh instead of HTTPS.
adding export GOPRIVATE=*
For standalone/final repos, an as a quick fix, why don't just to name the module within the go.mod as a package using your company's domain ... ?
module go.yourcompany.tld/the_repo
go.yourcompany.tld don't even have to exist as a valid (sub)domain...
Also, in the same go.mod you can use replacement block/lines to use private repos previously cloned the same way (within a respective folder cloned also in $GOPATH/src/go.yourcompany.tld) (why do we have to depend too much in GitHub?)
Edit
Needless to say that a private repo usually shall be a private repo, typically a standard git repo, right? With that, why not just to git clone and then go get within the cloned folder?
It's Hard Code In Go Get. Not The Git Reason. So Modify Go Source.
Reason:
repoRootForImportDynamic Will Request: https://....go-get
// RepoRootForImportPath analyzes importPath to determine the
// version control system, and code repository to use.
func RepoRootForImportPath(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) {
rr, err := repoRootFromVCSPaths(importPath, security, vcsPaths)
if err == errUnknownSite {
rr, err = repoRootForImportDynamic(importPath, mod, security)
if err != nil {
err = importErrorf(importPath, "unrecognized import path %q: %v", importPath, err)
}
}
if err != nil {
rr1, err1 := repoRootFromVCSPaths(importPath, security, vcsPathsAfterDynamic)
if err1 == nil {
rr = rr1
err = nil
}
}
So add gitlab domain to vcsPaths will ok.
Download go source code:
vi ./src/cmd/go/internal/vcs/vcs.go
Look for code below:
var vcsPaths = []*vcsPath{
// GitHub
{
pathPrefix: "github.com",
regexp: lazyregexp.New(`^(?P<root>github\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`),
vcs: "git",
repo: "https://{root}",
check: noVCSSuffix,
},
add Code As Follow,XXXX Is Your Domain:
// GitLab
{
pathPrefix: "gitlab.xxxx.com",
regexp: lazyregexp.New(`^(?P<root>gitlab.xxxx\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`),
vcs: "git",
repo: "https://{root}",
check: noVCSSuffix,
},
compile and replace go.

Why does GO mod tidy not work with bitbucket

I'm attempting to use private repositories as go libraries.
Whenever i try to run go get og god mod tidy, i get this kind of error
>go get bitbucket.org/myworkspace/myRepo
go get bitbucket.org/myworkspace/myRepo: reading https://api.bitbucket.org/2.0/repositories/myworkspace/myRepo?fields=scm: 404 Not Found
I've found multiple suggestions to fix this, with git config insteadOf url reqriting, but it doesn't work, and it all seems to assume that go will clone the library repo via git, and not the api.
My colleague who is running Linux, tried this and it worked, and at no point does it appear to use api.bitbucket.org instead of just bitbucket.org.
I've tried calling https://api.bitbucket.org/2.0/repositories/myworkspace/myRepo?fields=scm via Insomnia, with credentials, and i get the repo back just fine.
Why does go use the bitbucket api on windows, and how can i have it use credentials, so it can find the repo ?
This is due to a change made by Bitbucket (rolling out from June 1st 2022):
Rolling out these changes will break previous versions of Go due to the fact that the go command relies on a 403 response to fetch repositories hosted on Bitbucket Cloud. This means that users who use older versions of Go with private repositories, for example CI/CD builds with Go dependencies, will run into 404 errors.
Go has been updated to support these changes; version 1.18 includes the change but if you are running an earlier version you may need to upgrade to a later minor revision (change is in 1.17.7 and 1.16.14). The relevant Go issue is here (the aim of the change is something different but it resolves the issue).
Why does go use the bitbucket api on windows...
Go was using the API to determine if the Bitbucket repo was using Git or Mercurial (Bitbucket is dropping support for Mercurial).
As mentioned in the comments I've found that the new Git Credential Manager removes the need for the workarounds previously required to access private Bitbuicket repos. Using the credential manager and setting GOPRIVATE was all that was needed..
You can first export the private repository with the command export GOPRIVATE=<remote module name>. Then you can run the command env GIT_TERMINAL_PROMPT=1 go get <remote module name> so that if the credentials are not configured, you get a prompt.

Auto Replace URL with Mirror URL

Due to company policy we cannot access GitHub directly from company network, it has to be done via a company mirror. This is very painful when we need to run codes that needs to download dependencies from GitHub.
Right now I have to go into the code files and replace line by line for every URL from "github.com/username/repo_name" to "company_mirror.com/username/repo_name" where company_mirror.com is our company mirror.
Just wondering is there a way I can change the setting somewhere so that whenever something tries to access github.com it will access company_mirror.com instead? Could this be achieved by adding a few lines in bashrc?
System: Ubuntu 20.04
You should be able to add one or more insteadOf rules to your configuration:
url.<base>.insteadOf
Any URL that starts with this value will be rewritten to start, instead, with <base>. In cases where some site serves a large number of repositories, and serves them with multiple access methods, and some users need to use different access methods, this feature allows people to specify any of the equivalent URLs and have Git automatically rewrite the URL to the best alternative for the particular user, even for a never-before-seen repository on the site. When more than one insteadOf strings match a given URL, the longest match is used.
In this example, something like this should work:
# Rewrite HTTPS requests to GitHub.com
git config --global url."https://company_mirror.com/".insteadOf "https://github.com/"
# Rewrite SSH requests to GitHub.com
git config --global url."git#company_mirror.com:".insteadOf "git#github.com:"
And the end result will be something like this in your ~/.gitconfig:
[url "https://company_mirror.com/"]
insteadOf = "https://github.com/"
[url "git#company_mirror.com:"]
insteadOf = "git#github.com:"

How to use local Go module inside a Go project

In our local network, we have a GitLab running. The IP is bind to gitlab.local. I have a go package http://gitlab.local/projectsmall/core, and it is being used by another Go project. Inside this project, when I try to run go mod tidy, I am getting this error:
go get gitlab.local/projectsmall/core:
unrecognized import path "gitlab.local/projectsmall/core"
(https fetch:
Get https://gitlab.local/projectsmall/core?go-get=1:
dial tcp 192.168.28.9:443:
connect: connection refused
)
I have added the id_rsa.pub contents to SSH Kyes. I tried to add this core project to go mod path like this: /Users/UserA/go/pkg/mod/gitlab.local/guxin/core. The import "gitlab.local/guxin/core" is still red using GoLand IDE. It seems the go mod project can't find this gitlab.local/guxin/core package. In go.mod file, inside require block, when I added this gitlab.local/guxin/core, the IDE alert: usage: require module/path.
I found out it is using https, but local gitlab is not using SSL. So I tried go get -v -insecure and it's working now.
I'm not sure, but it seems to me that the problem may be that you are using the ssh keys and you are connecting via the HTTPs protocol as you can see from the error text.
Try it: https://gist.github.com/dmitshur/6927554
$ ssh -A vm
$ git config --global url."git#gitlab.local:".insteadOf "https://gitlab.local/"
$ cat ~/.gitconfig
[url "git#gitlab.local:"]
insteadOf = https://gitlab.local/
$ go get gitlab.local/private/repo && echo Success!
Success!
And also:
What's the proper way to "go get" a private repository?
In GitLab, since the repositories always end in .git, I must specify
.git at the end of the repository name to make it work, for example:
import "example.org/myuser/mygorepo.git"
And:
$ go get example.org/myuser/mygorepo.git
Looks like GitHub solves
this by appending ".git".

go get -insecure on a corporate network

C:\Users\me
> go get -insecure github.com/denisenkom/go-mssqldb
# cd .; git clone https://github.com/denisenkom/go-mssqldb C:\Users\me\Projects\Go\src\github.com\denisenkom\go-mssqldb
Cloning into 'C:\Users\me\Projects\Go\src\github.com\denisenkom\go-mssqldb'...
fatal: unable to access 'https://github.com/denisenkom/go-mssqldb/': SSL certificate problem: unable to get local issuer certificate
package github.com/denisenkom/go-mssqldb: exit status 128
According to go help get this connection should drop down to http? Yes? Do I misunderstand? How do I get this to work w/o https?
PS: I'm not interested in trying to fix https (which on this Win10 image I have no control over anyway) - I already fought that battle with npm and lost...
Edit: I found a passable answer by fixing the global git config. I hate to do it, but needs must... atom.io/go-plus does not seem to pick up this config change, I will ping the author.
C:\Users\me
> git config --global http.sslVerify false
Update Q2 2021: with the newly released Go 1.17 (beta), you now have, for deprecations:
go get
The go get -insecure flag is deprecated and has been removed.
To permit the use of insecure schemes when fetching dependencies, please use the GOINSECURE environment variable.
The -insecure flag also bypassed module sum validation, use GOPRIVATE or GONOSUMDB if you need that functionality.
See go help environment for details.

Resources