pax_global_header00006660000000000000000000000064145100024450014505gustar00rootroot0000000000000052 comment=660f3d811b4108d0b6259046afd25b3b3b06be9d git-credential-oauth-0.11.0/000077500000000000000000000000001451000244500155755ustar00rootroot00000000000000git-credential-oauth-0.11.0/.github/000077500000000000000000000000001451000244500171355ustar00rootroot00000000000000git-credential-oauth-0.11.0/.github/FUNDING.yml000066400000000000000000000000211451000244500207430ustar00rootroot00000000000000github: hickford git-credential-oauth-0.11.0/.github/workflows/000077500000000000000000000000001451000244500211725ustar00rootroot00000000000000git-credential-oauth-0.11.0/.github/workflows/go.yml000066400000000000000000000005511451000244500223230ustar00rootroot00000000000000name: Go on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Go uses: actions/setup-go@v3 with: go-version: 1.19 - name: Build run: go build -v ./... - name: Test run: go test -v ./... git-credential-oauth-0.11.0/.gitignore000066400000000000000000000004511451000244500175650ustar00rootroot00000000000000# Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib git-credential-oauth # Test binary, built with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Dependency directories (remove the comment below to include it) # vendor/ dist/ git-credential-oauth-0.11.0/.goreleaser.yaml000066400000000000000000000004051451000244500206660ustar00rootroot00000000000000before: hooks: - go mod tidy builds: - env: - CGO_ENABLED=0 archives: # modelines, feel free to remove those if you don't want/use them: # yaml-language-server: $schema=https://goreleaser.com/static/schema.json # vim: set ts=2 sw=2 tw=0 fo=cnqoj git-credential-oauth-0.11.0/CONTRIBUTING.md000066400000000000000000000021111451000244500200210ustar00rootroot00000000000000# How to Contribute We'd love to accept your patches and contributions to this project. There are just a few small guidelines you need to follow. ## Contributor License Agreement Contributions to this project must be accompanied by a Contributor License Agreement. You (or your employer) retain the copyright to your contribution; this simply gives us permission to use and redistribute your contributions as part of the project. Head over to to see your current agreements on file or to sign a new one. You generally only need to submit a CLA once, so if you've already submitted one (even if it was for a different project), you probably don't need to do it again. ## Code Reviews All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. Consult [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more information on using pull requests. ## Community Guidelines This project follows [Google's Open Source Community Guidelines](https://opensource.google/conduct/). git-credential-oauth-0.11.0/LICENSE.txt000066400000000000000000000261361451000244500174300ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. git-credential-oauth-0.11.0/README.md000066400000000000000000000207101451000244500170540ustar00rootroot00000000000000git-credential-oauth ==================== *No more passwords! No more personal access tokens! No more SSH keys!* git-credential-oauth is a Git credential helper that securely authenticates to GitHub, GitLab, BitBucket and Gerrit using [OAuth](https://datatracker.ietf.org/wg/oauth/about/). The first time you authenticate, the helper opens a browser window to the host. Subsequent authentication within storage lifetime is non interactive. ## Motivation Git assumes users can type a password from memory, but hosts such as GitHub no longer accept passwords without two-factor authentication. Personal access tokens are easy enough to copy and paste but awkward to store securely. [git-credential-cache](https://git-scm.com/docs/git-credential-cache) works well for passwords but not personal access tokens because the token is lost when the cache expires. All in all, the usability is so poor that the [most popular advice on StackOverflow](https://stackoverflow.com/a/35942890/284795) is to insecurely save credentials in plaintext! OAuth has multiple advantages over personal access tokens or SSH: | Advantage | OAuth | Personal access token | SSH | |--------------------------------------------|-------|-----------------------|-----| | Clone public repo without setup | ✓ | ✓ | 🗙 | | Authenticate to popular hosts without setup| ✓ | 🗙 | 🗙 | | Server authenticity verified automatically | ✓ | ✓ | 🗙 | | Protections against token theft[^1] | [✓](https://www.ietf.org/archive/id/draft-ietf-oauth-security-topics-22.html#name-refresh-token-protection) | 🗙 | *only if key has passphrase* | [^1]: Scenario: an old disk backup is leaked. ## Installation **Download** binary from https://github.com/hickford/git-credential-oauth/releases. Then test that Git can find the application: git credential-oauth If you have problems, make sure that the binary is [located in the path](https://superuser.com/a/284351/62691) and [is executable](https://askubuntu.com/a/229592/18504). ### Linux [Several Linux distributions](https://repology.org/project/git-credential-oauth/versions) include a git-credential-oauth package including [Fedora](https://packages.fedoraproject.org/pkgs/git-credential-oauth/git-credential-oauth/), [Debian](https://tracker.debian.org/pkg/git-credential-oauth) and [Ubuntu](https://packages.ubuntu.com/lunar/git-credential-oauth). [![Packaging status](https://repology.org/badge/vertical-allrepos/git-credential-oauth.svg?exclude_unsupported=1&header=)](https://repology.org/project/git-credential-oauth/versions) ### macOS #### Homebrew macOS users can install from [Homebrew](https://formulae.brew.sh/formula/git-credential-oauth#default): brew install git-credential-oauth #### MacPorts macOS users can alternatively install via [MacPorts](https://ports.macports.org/port/git-credential-oauth/): sudo port install git-credential-oauth ### Go users Go users can install the latest release to `~/go/bin` with: go install github.com/hickford/git-credential-oauth@latest ## Configuration As a convenience, you can run: ```sh git credential-oauth configure ``` This uses the recommended config below. ### How it works Git is cleverly designed to [support multiple credential helpers](https://git-scm.com/docs/gitcredentials#_custom_helpers). To fill credentials, Git calls each helper in turn until it has the information it needs. git-credential-oauth is a read-only credential-generating helper, designed to be configured in combination with a storage helper. To configure together with [git-credential-cache](https://git-scm.com/docs/git-credential-cache): ```sh git config --global --unset-all credential.helper git config --global --add credential.helper "cache --timeout 7200" # two hours git config --global --add credential.helper oauth ``` You may choose a different storage helper such as `osxkeychain`, `wincred` or `libsecret`, but git-credential-oauth must be configured last. This ensures Git checks for *stored* credentials before generating *new* credentials. **Windows users** must use storage helper `wincred` because [git-credential-cache isn't available on Windows](https://github.com/git-for-windows/git/issues/3892). ### Manual config Edit your [global git config](https://git-scm.com/docs/git-config#FILES) `~/.gitconfig` to include the following lines: ```ini [credential] helper = cache --timeout 7200 # two hours helper = oauth ``` ### Browserless systems On systems without a web browser, set the `-device` flag to authenticate on another device using [OAuth device flow](https://www.rfc-editor.org/rfc/rfc8628). Currently only GitHub supports this flow. ```ini [credential] helper = cache --timeout 7200 # two hours helper = oauth -device ``` ### Unconfiguration Edit `~/.gitconfig` manually, or run: git config --global --unset-all credential.helper oauth ## Custom hosts To use with a custom host, eg. `gitlab.example.com`: 1. Register an OAuth application on the host. The [GitLab instructions](https://docs.gitlab.com/ee/integration/oauth_provider.html#user-owned-applications) are typical. * Specify name `git-credential-oauth` * Specify redirect URI `http://127.0.0.1`. * Select scopes for read and write Git operations. 2. Adjust the config commands below with the generated client id and *space-separated* scopes. 3. Share the config commands with colleagues so they can skip the registration step. ```sh git config --global credential.https://gitlab.example.com.oauthClientId git config --global credential.https://gitlab.example.com.oauthScopes read_repository write_repository git config --global credential.https://gitlab.example.com.oauthAuthURL /oauth/authorize git config --global credential.https://gitlab.example.com.oauthTokenURL /oauth/token ``` Would you like to see universal GitLab support? *Vote for [GitLab issue #374172](https://gitlab.com/gitlab-org/gitlab/-/issues/374172). ## Philosophy * Do one thing well, namely OAuth authentication. * Interoperate with other credential helpers. * [Contribute upstream](https://lore.kernel.org/git/?q=f%3Ahickford+s%3Acredential) to improve the ecosystem. ## Comparison with Git Credential Manager [Git Credential Manager](https://github.com/GitCredentialManager/git-credential-manager) (GCM) is an excellent credential helper with broader functionality. However because it's developed in .NET, GCM is [prohibitively difficult for Linux distributions to package](https://github.com/dotnet/source-build/discussions/2960). | | Git Credential Manager | git-credential-oauth | |----------------|------------------------|----------------------| | Cross platform | ✓ | ✓ | | Linux arm64 support | 🗙 | ✓ | | Packaged in Linux distributions | 🗙 | ✓ ([many](https://repology.org/project/git-credential-oauth/versions)) | | Installation size (Linux) | [82 MB](https://github.com/git-ecosystem/git-credential-manager/issues/1212#issuecomment-1530304873) | 5 MB | | Installation size (Windows) | 4 MB | 5 MB | | Ships with Git for Windows | ✓ | 🗙 | | Credential storage | In built | Used together with any storage helper | | Development | .NET | Go | | Lines of code | 40,000 | 400 | | Minimum HTTP requests | 1 | 0 | | Authentication to Azure DevOps | ✓ | 🗙 (try [git-credential-azure](https://github.com/hickford/git-credential-azure)) | | Hosts with default config | 4 | 12 | The maintainer personally uses GCM on Windows and git-credential-oauth on Linux. ## Development Install locally with `go install .`. ### Debugging Use the `-verbose` flag to print more details: ```sh git config --global --unset-all credential.helper oauth git config --global --add credential.helper "oauth -verbose" ``` You can also test git-credential-oauth in isolation: ``` echo host=gitlab.com\nprotocol=https | git-credential-oauth -verbose get ``` You can test configured helpers in combination with `git credential fill`, eg. ``` echo url=https://gitlab.com | git credential fill ``` To see which helpers Git calls, set `export GIT_TRACE=1`. ## See also * [git-credential-azure](https://github.com/hickford/git-credential-azure): a Git credential manager that authenticates to Azure Repos * [Git Credential Manager](https://github.com/git-ecosystem/git-credential-manager) git-credential-oauth-0.11.0/git-credential-oauth.1000066400000000000000000000015511451000244500216720ustar00rootroot00000000000000.\" Automatically generated by Pandoc 3.1.7 .\" .TH "GIT-CREDENTIAL-OAUTH" "1" "" "2023-08-12" "" .SH NAME git-credential-oauth - Git credential helper that authenticates to GitHub and other forges using OAuth .SH SYNOPSIS \f[CR]git-credential-oauth [] \f[R] .SH DESCRIPTION A read-only Git credential helper that authenticates to GitHub and other forges using OAuth. .PP Example configuration for Git: .IP .EX git config --global --unset-all credential.helper git config --global --add credential.helper \[dq]cache --timeout 7200\[dq] # two hours git config --global --add credential.helper oauth .EE .PP To unconfigure: .IP .EX git config --global --unset-all credential.helper oauth .EE .SH OPTIONS Run \f[CR]git-credential-oauth -help\f[R] for more details. .SH REPORTING BUGS Please report any bugs at https://github.com/hickford/git-credential-oauth git-credential-oauth-0.11.0/go.mod000066400000000000000000000003721451000244500167050ustar00rootroot00000000000000module github.com/hickford/git-credential-oauth go 1.19 require golang.org/x/oauth2 v0.13.0 require ( github.com/golang/protobuf v1.5.3 // indirect google.golang.org/appengine v1.6.8 // indirect google.golang.org/protobuf v1.31.0 // indirect ) git-credential-oauth-0.11.0/go.sum000066400000000000000000000072551451000244500167410ustar00rootroot00000000000000github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/oauth2 v0.13.0 h1:jDDenyj+WgFtmV3zYVoi8aE2BwtXFLWOA67ZfNWftiY= golang.org/x/oauth2 v0.13.0/go.mod h1:/JMhi4ZRXAf4HG9LiNmxvk+45+96RUlVThiH8FzNBn0= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= git-credential-oauth-0.11.0/main.go000066400000000000000000000377451451000244500170700ustar00rootroot00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "context" "flag" "fmt" "io" "log" "net" "net/http" "net/http/httptest" "net/url" "os" "os/exec" "runtime" "runtime/debug" "strings" "golang.org/x/oauth2" "golang.org/x/oauth2/endpoints" ) // configByHost lists default config for several public hosts. var configByHost = map[string]oauth2.Config{ // https://github.com/settings/applications/2017944 "github.com": { ClientID: "b895675a4e2cf54d5c6c", // IMPORTANT: The client "secret" below is non confidential. // This is expected for OAuth native apps which (unlike web apps) are public clients // "incapable of maintaining the confidentiality of their credentials" // "It is assumed that any client authentication credentials included in the application can be extracted" // https://datatracker.ietf.org/doc/html/rfc6749#section-2.1 ClientSecret: "2b746eea028711749c5062b9fe626fed78d03cc0", Endpoint: endpoints.GitHub, Scopes: []string{"repo", "gist", "workflow"}}, // https://gitlab.com/oauth/applications/232663 "gitlab.com": { ClientID: "10bfbbf46e5b760b55ce772a262d7a0205eacc417816eb84d37d0fb02c89bb97", Endpoint: endpoints.GitLab, Scopes: []string{"read_repository", "write_repository"}}, // https://gitlab.freedesktop.org/oauth/applications/68 "gitlab.freedesktop.org": { ClientID: "ba28f287f465c03c629941bca9de965923c561f8e967ce02673a0cd937a94b6f", Endpoint: replaceHost(endpoints.GitLab, "gitlab.freedesktop.org"), Scopes: []string{"read_repository", "write_repository"}}, // https://gitlab.gnome.org/oauth/applications/112 "gitlab.gnome.org": { ClientID: "9719f147e6117ef0ee9954516bd7fe292176343a7fd24a8bcd5a686e8ef1ec71", Endpoint: replaceHost(endpoints.GitLab, "gitlab.gnome.org"), Scopes: []string{"read_repository", "write_repository"}}, // https://code.videolan.org/oauth/applications/109 "code.videolan.org": { ClientID: "a6d235d8ebc7a7eacc52be6dba0b5bc31a6d013be85e2d15f0fc9006b4c6e9ff", Endpoint: replaceHost(endpoints.GitLab, "code.videolan.org"), Scopes: []string{"read_repository", "write_repository"}}, // https://salsa.debian.org/oauth/applications/95 "salsa.debian.org": { ClientID: "0ae3637439058e4f261db17a001a7ec9235e1fda88b6d9221222a57c14ed830d", Endpoint: replaceHost(endpoints.GitLab, "salsa.debian.org"), Scopes: []string{"read_repository", "write_repository"}}, // https://gitlab.haskell.org/oauth/applications/3 "gitlab.haskell.org": { ClientID: "078baa23982db8d6e179fb7da816b92e6a761268b8b35a7aa1e7ee7a3891a426", Endpoint: replaceHost(endpoints.GitLab, "gitlab.haskell.org"), Scopes: []string{"read_repository", "write_repository"}}, // https://gitlab.alpinelinux.org/oauth/applications/7 "gitlab.alpinelinux.org": { ClientID: "6e1363d5730bd1068bc908d6eda9f4f7e72352147dbe15f441a2f9e2ce5aebee", Endpoint: replaceHost(endpoints.GitLab, "gitlab.alpinelinux.org"), Scopes: []string{"read_repository", "write_repository"}}, // https://gitea.com/user/settings/applications/oauth2/218 "gitea.com": { ClientID: "e13f8ebc-398d-4091-9481-5a37a76b51f6", Endpoint: oauth2.Endpoint{AuthURL: "https://gitea.com/login/oauth/authorize", TokenURL: "https://gitea.com/login/oauth/access_token"}}, // https://codeberg.org/user/settings/applications/oauth2/223 "codeberg.org": { ClientID: "246ca3e8-e974-430c-b9ec-3d4e2b54ad28", Endpoint: oauth2.Endpoint{AuthURL: "https://codeberg.org/login/oauth/authorize", TokenURL: "https://codeberg.org/login/oauth/access_token"}}, // https://bitbucket.org/hickford/workspace/settings/oauth-consumers/983448/edit "bitbucket.org": { ClientID: "abET6ywGmTknNRvAMT", ClientSecret: "df8rsnkAxuHCgZrSgu5ykJQjrbGVzT9m", Endpoint: endpoints.Bitbucket, Scopes: []string{"repository", "repository:write"}}, "android.googlesource.com": { ClientID: "897755559425-di05p489vpt7iv09thbf5a1ombcbs5v0.apps.googleusercontent.com", ClientSecret: "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", Endpoint: endpoints.Google, Scopes: []string{"https://www.googleapis.com/auth/gerritcodereview"}}, } var ( verbose bool // populated by GoReleaser https://goreleaser.com/cookbooks/using-main.version version = "dev" ) func getVersion() string { info, ok := debug.ReadBuildInfo() if ok && version == "dev" { version = info.Main.Version } return version } func printVersion() { if verbose { fmt.Fprintf(os.Stderr, "git-credential-oauth %s\n", getVersion()) } } func parse(input string) map[string]string { lines := strings.Split(string(input), "\n") pairs := map[string]string{} for _, line := range lines { parts := strings.SplitN(line, "=", 2) if len(parts) >= 2 { pairs[parts[0]] = parts[1] } } return pairs } func main() { flag.BoolVar(&verbose, "verbose", false, "log debug information to stderr") var device bool flag.BoolVar(&device, "device", false, "instead of opening a web browser locally, print a code to enter on another device") flag.Usage = func() { printVersion() fmt.Fprintln(os.Stderr, "usage: git credential-oauth [] ") fmt.Fprintln(os.Stderr, "") fmt.Fprintln(os.Stderr, "Options:") flag.PrintDefaults() fmt.Fprintln(os.Stderr, "") fmt.Fprintln(os.Stderr, "Actions:") fmt.Fprintln(os.Stderr, " get Generate credential [called by Git]") fmt.Fprintln(os.Stderr, " configure Configure as Git credential helper") fmt.Fprintln(os.Stderr, " unconfigure Unconfigure as Git credential helper") fmt.Fprintln(os.Stderr, "") fmt.Fprintln(os.Stderr, "See also https://github.com/hickford/git-credential-oauth") } flag.Parse() if device { c := configByHost["android.googlesource.com"] c.ClientID = "897755559425-82ha835rqnprtctvm8shjc2p86bk0eru.apps.googleusercontent.com" c.ClientSecret = "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" configByHost["android.googlesource.com"] = c } args := flag.Args() if len(args) != 1 { flag.Usage() os.Exit(2) } switch args[0] { case "get": printVersion() input, err := io.ReadAll(os.Stdin) if err != nil { log.Fatalln(err) } pairs := parse(string(input)) if verbose { fmt.Fprintln(os.Stderr, "input:", pairs) } host := pairs["host"] looksLikeGitLab := strings.HasPrefix(host, "gitlab.") || strings.Contains(pairs["wwwauth[]"], `Realm="GitLab"`) looksLikeGitea := strings.Contains(pairs["wwwauth[]"], `realm="Gitea"`) looksLikeGitHub := strings.HasPrefix(host, "github.") || strings.Contains(pairs["wwwauth[]"], `realm="GitHub"`) urll := fmt.Sprintf("%s://%s", pairs["protocol"], host) c, found := configByHost[host] if !found && strings.HasSuffix(host, ".googlesource.com") { c = configByHost["android.googlesource.com"] } if !found && looksLikeGitLab { // TODO: universal GitLab support with constant client id // https://gitlab.com/gitlab-org/gitlab/-/issues/374172 // c.ClientID = ... // assumes GitLab installed at domain root c.Endpoint = oauth2.Endpoint{ AuthURL: fmt.Sprintf("%s/oauth/authorize", urll), TokenURL: fmt.Sprintf("%s/oauth/token", urll), } c.Scopes = configByHost["gitlab.com"].Scopes } if !found && looksLikeGitea { c.ClientID = "a4792ccc-144e-407e-86c9-5e7d8d9c3269" c.Endpoint = oauth2.Endpoint{ AuthURL: fmt.Sprintf("%s/login/oauth/authorize", urll), TokenURL: fmt.Sprintf("%s/login/oauth/access_token", urll), } c.Scopes = configByHost["gitea.com"].Scopes } if !found && looksLikeGitHub { c.Endpoint = oauth2.Endpoint{ AuthURL: fmt.Sprintf("%s/login/oauth/authorize", urll), TokenURL: fmt.Sprintf("%s/login/oauth/access_token", urll), DeviceAuthURL: fmt.Sprintf("%s/login/device/code", urll), } c.Scopes = configByHost["github.com"].Scopes } gitPath, err := exec.LookPath("git") if err == nil { cmd := exec.Command(gitPath, "config", "--get-urlmatch", "credential.oauthClientId", urll) bytes, err := cmd.Output() if err == nil { c.ClientID = strings.TrimSpace(string(bytes)) } bytes, err = exec.Command(gitPath, "config", "--get-urlmatch", "credential.oauthClientSecret", urll).Output() if err == nil { c.ClientSecret = strings.TrimSpace(string(bytes)) } bytes, err = exec.Command(gitPath, "config", "--get-urlmatch", "credential.oauthScopes", urll).Output() if err == nil { c.Scopes = []string{strings.TrimSpace(string(bytes))} } bytes, err = exec.Command(gitPath, "config", "--get-urlmatch", "credential.oauthAuthURL", urll).Output() if err == nil { c.Endpoint.AuthURL, err = urlResolveReference(urll, strings.TrimSpace(string(bytes))) if err != nil { log.Fatalln(err) } } bytes, err = exec.Command(gitPath, "config", "--get-urlmatch", "credential.oauthTokenURL", urll).Output() if err == nil { c.Endpoint.TokenURL, err = urlResolveReference(urll, strings.TrimSpace(string(bytes))) if err != nil { log.Fatalln(err) } } bytes, err = exec.Command(gitPath, "config", "--get-urlmatch", "credential.oauthRedirectURL", urll).Output() if err == nil { c.RedirectURL = strings.TrimSpace(string(bytes)) } } if c.ClientID == "" || c.Endpoint.AuthURL == "" || c.Endpoint.TokenURL == "" { if looksLikeGitLab { fmt.Fprintf(os.Stderr, "It looks like you're authenticating to a GitLab instance! To configure git-credential-oauth for host %s, follow the instructions at https://github.com/hickford/git-credential-oauth/issues/18. You may need to register an OAuth application at https://%s/-/profile/applications\n", host, host) } return } var token *oauth2.Token if pairs["oauth_refresh_token"] != "" { // Try refresh token (fast, doesn't open browser) if verbose { fmt.Fprintln(os.Stderr, "refreshing token...") } token, err = c.TokenSource(context.Background(), &oauth2.Token{RefreshToken: pairs["oauth_refresh_token"]}).Token() if err != nil { fmt.Fprintln(os.Stderr, "error during OAuth token refresh", err) } } if token == nil { // Generate new token (opens browser, may require user input) if device { token, err = getDeviceToken(c) } else { token, err = getToken(c) } if err != nil { log.Fatalln(err) } } if verbose { fmt.Fprintln(os.Stderr, "token:", token) } var username string if host == "bitbucket.org" { // https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud/#Cloning-a-repository-with-an-access-token username = "x-token-auth" } else if looksLikeGitLab { // https://docs.gitlab.com/ee/api/oauth2.html#access-git-over-https-with-access-token username = "oauth2" } else if pairs["username"] == "" { username = "oauth2" } output := map[string]string{ "password": token.AccessToken, } if username != "" { output["username"] = username } if !token.Expiry.IsZero() { output["password_expiry_utc"] = fmt.Sprintf("%d", token.Expiry.UTC().Unix()) } if token.RefreshToken != "" { output["oauth_refresh_token"] = token.RefreshToken } if verbose { fmt.Fprintln(os.Stderr, "output:", output) } for key, v := range output { fmt.Printf("%s=%s\n", key, v) } case "configure", "unconfigure": gitPath, err := exec.LookPath("git") if err != nil { log.Fatalln(err) } var commands []*exec.Cmd if args[0] == "configure" { var storage string switch runtime.GOOS { case "windows": storage = "wincred" case "darwin": storage = "osxkeychain" default: storage = "cache --timeout 7200" } commands = []*exec.Cmd{exec.Command(gitPath, "config", "--global", "--unset-all", "credential.helper"), exec.Command(gitPath, "config", "--global", "--add", "credential.helper", storage), exec.Command(gitPath, "config", "--global", "--add", "credential.helper", "oauth")} } else if args[0] == "unconfigure" { commands = []*exec.Cmd{exec.Command(gitPath, "config", "--global", "--unset-all", "credential.helper", "oauth")} } for _, cmd := range commands { cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout if verbose { fmt.Fprintln(os.Stderr, cmd) } err := cmd.Run() // ignore exit status 5 "you try to unset an option which does not exist" https://git-scm.com/docs/git-config#_description if err != nil && cmd.ProcessState.ExitCode() != 5 { log.Fatalln(err) } } fmt.Fprintf(os.Stderr, "%sd successfully\n", args[0]) } } var template string = ` Git authentication

Success. You may close this page and return to Git.

git-credential-oauth %s

` func getToken(c oauth2.Config) (*oauth2.Token, error) { state := oauth2.GenerateVerifier() queries := make(chan url.Values) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // TODO: consider whether to show errors in browser or command line queries <- r.URL.Query() w.Header().Add("Content-Type", "text/html") html := fmt.Sprintf(template, getVersion()) w.Write([]byte(html)) }) var server *httptest.Server if c.RedirectURL == "" { server = httptest.NewServer(handler) c.RedirectURL = server.URL } else { server = httptest.NewUnstartedServer(handler) url, err := url.Parse(c.RedirectURL) if err != nil { log.Fatalln(err) } origHostname := url.Hostname() if url.Port() == "" { url.Host += ":0" } l, err := net.Listen("tcp", url.Host) if err != nil { log.Fatalln(err) } server.Listener = l server.Start() url.Host = l.Addr().String() if verbose { fmt.Fprintf(os.Stderr, "listening on %s", url.Host) } if url.Hostname() != origHostname { // restore original hostname such as 'localhost' url.Host = fmt.Sprintf("%s:%s", origHostname, url.Port()) } c.RedirectURL = url.String() } defer server.Close() verifier := oauth2.GenerateVerifier() authCodeURL := c.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier)) fmt.Fprintf(os.Stderr, "Please complete authentication in your browser...\n%s\n", authCodeURL) var open string switch runtime.GOOS { case "windows": open = "start" case "darwin": open = "open" default: open = "xdg-open" } // TODO: wait for server to start before opening browser if _, err := exec.LookPath(open); err == nil { err = exec.Command(open, authCodeURL).Run() if err != nil { return nil, err } } query := <-queries server.Close() if verbose { fmt.Fprintln(os.Stderr, "query:", query) } if query.Get("state") != state { return nil, fmt.Errorf("state mismatch") } code := query.Get("code") return c.Exchange(context.Background(), code, oauth2.VerifierOption(verifier)) } func getDeviceToken(c oauth2.Config) (*oauth2.Token, error) { deviceAuth, err := c.DeviceAuth(context.Background()) if err != nil { log.Fatalln(err) } if verbose { fmt.Fprintln(os.Stderr, deviceAuth) } fmt.Fprintf(os.Stderr, "Please enter code %s at %s\n", deviceAuth.UserCode, deviceAuth.VerificationURI) return c.DeviceAccessToken(context.Background(), deviceAuth) } func replaceHost(e oauth2.Endpoint, host string) oauth2.Endpoint { e.AuthURL = replaceHostInURL(e.AuthURL, host) e.TokenURL = replaceHostInURL(e.TokenURL, host) e.DeviceAuthURL = replaceHostInURL(e.DeviceAuthURL, host) return e } func replaceHostInURL(originalURL, host string) string { if originalURL == "" { return "" } u, err := url.Parse(originalURL) if err != nil { panic(err) } u.Host = host return u.String() } func urlResolveReference(base, ref string) (string, error) { base1, err := url.Parse(base) if err != nil { return "", err } ref1, err := url.Parse(ref) if err != nil { return "", err } return base1.ResolveReference(ref1).String(), nil } git-credential-oauth-0.11.0/main_test.go000066400000000000000000000006511451000244500201110ustar00rootroot00000000000000package main import ( "strings" "testing" ) func TestConfig(t *testing.T) { for key, c := range configByHost { if key == "android.googlesource.com" { continue } if !strings.Contains(c.Endpoint.AuthURL, key) { t.Errorf("bad auth url for key %s: %s", key, c.Endpoint.AuthURL) } if !strings.Contains(c.Endpoint.TokenURL, key) { t.Errorf("bad token url for key %s: %s", key, c.Endpoint.TokenURL) } } }