├── .github ├── release-drafter.yml └── workflows │ ├── maven.yml │ └── release-drafter.yml ├── .gitignore ├── LICENSE ├── README.md ├── codecov.yml ├── pom.xml ├── release.sh ├── renovate.json ├── rewrite-testcontainers-gitserver ├── pom.xml └── src │ ├── main │ ├── java │ │ └── io │ │ │ └── github │ │ │ └── sparsick │ │ │ └── testcontainers │ │ │ └── gitserver │ │ │ └── rewrite │ │ │ └── recipe │ │ │ └── RenamePackageOfGitHttpServerContainer.java │ └── resources │ │ └── META-INF │ │ └── rewrite │ │ ├── classpath │ │ └── testcontainers-gitserver-0.4.0.jar │ │ └── rewrite.yml │ └── test │ └── java │ └── io │ └── github │ └── sparsick │ └── testcontainers │ └── gitserver │ └── rewrite │ └── recipe │ ├── RenamePackageOfGitHttpServerContainerTest.java │ └── SplitPackageTest.java ├── testcontainers-git-bom └── pom.xml └── testcontainers-gitserver ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── github │ │ └── sparsick │ │ └── testcontainers │ │ └── gitserver │ │ ├── GitServerVersions.java │ │ ├── http │ │ ├── BasicAuthenticationCredentials.java │ │ ├── GitHttpServerContainer.java │ │ └── HttpProxySetting.java │ │ └── plain │ │ ├── GitServerContainer.java │ │ ├── SshHostKey.java │ │ └── SshIdentity.java └── resources │ ├── http-config │ └── nginx.conf │ ├── id_client │ ├── id_client.pub │ └── sshd_config └── test ├── java └── com │ └── github │ └── sparsick │ └── testcontainers │ └── gitserver │ ├── http │ └── GitHttpServerContainerTest.java │ └── plain │ ├── GitServerContainerJUnit5IntegrationTest.java │ └── GitServerContainerTest.java └── resources ├── logback-test.xml └── sampleRepo └── testFile /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | categories: 2 | - title: '🚀 Features' 3 | label: 'feature' 4 | - title: '🐛 Bugfixes' 5 | label: 'bug' 6 | - title: '🧰 Maintenance' 7 | label: 'maintenance' 8 | - title: '📦 Dependencies' 9 | label: 'dependencies' 10 | - title: '✏️ Documentation' 11 | label: 'documentation' 12 | exclude-labels: 13 | - 'skip-changelog' 14 | 15 | template: | 16 | ## What's Changed 17 | 18 | $CHANGES 19 | -------------------------------------------------------------------------------- /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020 Reficio (TM) - Reestablish your software! All Rights Reserved. 2 | # 3 | # Licensed to the Apache Software Foundation (ASF) under one or more 4 | # contributor license agreements. See the NOTICE file distributed with 5 | # this work for additional information regarding copyright ownership. 6 | # The ASF licenses this file to You under the Apache License, Version 2.0 7 | # (the "License"); you may not use this file except in compliance with 8 | # the License. You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | # This workflow will build a Java project with Maven 19 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven 20 | 21 | name: Java CI with Maven 22 | 23 | on: 24 | push: 25 | branches: [ main ] 26 | pull_request: 27 | branches: [ main ] 28 | schedule: 29 | - cron: '0 6 1 * *' 30 | 31 | jobs: 32 | build: 33 | name: "JDK 21 Eclipse Temurin" 34 | runs-on: ubuntu-latest 35 | container: "maven:3.9.9-eclipse-temurin-21" 36 | steps: 37 | - uses: actions/checkout@v4 38 | - uses: actions/cache@v4 39 | with: 40 | path: ~/.m2/repository 41 | key: maven-jdk17-${{ hashFiles('**/pom.xml') }} 42 | restore-keys: maven-jdk17 43 | - name: 'Build' 44 | run: | 45 | mvn \ 46 | --show-version \ 47 | --fail-at-end \ 48 | --batch-mode \ 49 | --no-transfer-progress \ 50 | clean verify \ 51 | - uses: codecov/codecov-action@v3 52 | with: 53 | token: ${{ secrets.CODECOV_TOKEN }} 54 | files: ./rewrite-testcontainers-gitserver/target/site/jacoco/jacoco.xml, ./testcontainers-gitserver/target/site/jacoco/jacoco.xml 55 | fail_ci_if_error: true 56 | verbose: false -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | on: 3 | push: 4 | # branches to consider in the event; optional, defaults to all 5 | branches: 6 | - main 7 | # pull_request event is required only for autolabeler 8 | pull_request: 9 | # Only following types are handled by the action, but one can default to all as well 10 | types: [opened, reopened, synchronize] 11 | # pull_request_target event is required for autolabeler to support PRs from forks 12 | # pull_request_target: 13 | # types: [opened, reopened, synchronize] 14 | 15 | jobs: 16 | update_release_draft: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: release-drafter/release-drafter@v6.1.0 20 | # (Optional) specify config name to use, relative to .github/. Default: release-drafter.yml 21 | env: 22 | GITHUB_TOKEN: ${{ secrets.RENOVATE_TOKEN }} 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | !**/src/main/**/target/ 4 | !**/src/test/**/target/ 5 | 6 | ### IntelliJ IDEA ### 7 | .idea/modules.xml 8 | .idea/jarRepositories.xml 9 | .idea/compiler.xml 10 | .idea/libraries/ 11 | *.iws 12 | *.iml 13 | *.ipr 14 | 15 | ### Eclipse ### 16 | .apt_generated 17 | .classpath 18 | .factorypath 19 | .project 20 | .settings 21 | .springBeans 22 | .sts4-cache 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | build/ 31 | !**/src/main/**/build/ 32 | !**/src/test/**/build/ 33 | 34 | ### VS Code ### 35 | .vscode/ 36 | 37 | ### Mac OS ### 38 | .DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Sandra Parsick 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # testcontainers-git 2 | [![codecov](https://codecov.io/gh/sparsick/testcontainers-git/branch/main/graph/badge.svg?token=F9R60M53IL)](https://codecov.io/gh/sparsick/testcontainers-git) 3 | [![Java CI with Maven](https://github.com/sparsick/testcontainers-git/actions/workflows/maven.yml/badge.svg?branch=main)](https://github.com/sparsick/testcontainers-git/actions/workflows/maven.yml) 4 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.github.sparsick.testcontainers.gitserver/testcontainers-gitserver/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.github.sparsick.testcontainers.gitserver/testcontainers-gitserver) 5 | 6 | This project contains a [Testcontainers](https://www.testcontainers.org/) implementation for a plain git server based on the Docker image `rockstorm/git-server` ([Github Project](https://github.com/rockstorm101/git-server-docker)). 7 | 8 | It sets up the git server with a ready to use repository with the default name `testRepo`. 9 | The repository name can be overwritten. 10 | It exists two flavours for the git server (exposed by SSH or by HTTP) 11 | The port is set by testcontainers' mechanism. 12 | 13 | ## Add me as Dependency 14 | 15 | 16 | **Maven:** 17 | ```xml 18 | 19 | 20 | 21 | io.github.sparsick.testcontainers.gitserver 22 | testcontainers-git-bom 23 | 0.12.0 24 | test 25 | 26 | 27 | 28 | 29 | 30 | 31 | io.github.sparsick.testcontainers.gitserver 32 | testcontainers-gitserver 33 | test 34 | 35 | 36 | ``` 37 | 38 | **Gradle:** 39 | ```groovy 40 | dependencyManagement { 41 | imports { 42 | mavenBom("io.github.sparsick.testcontainers.gitserver:testcontainers-git-bom:0.12.0") 43 | } 44 | } 45 | 46 | 47 | dependencies { 48 | testImplementation 'io.github.sparsick.testcontainers.gitserver:testcontainers-gitserver' 49 | } 50 | ``` 51 | 52 | ## Getting started with a sample 53 | 54 | The following samples show how to use the git server container in a JUnit 5 test. 55 | Currently, there exists two flavour: 56 | - git server via ssh (`GitServerContainer`) 57 | - git server via http (`GitHttpServerContainer`) 58 | 59 | ### Git Server via SSH 60 | The following sample shows how to use the git server container via SSH in a JUnit 5 test: 61 | ````java 62 | import com.github.sparsick.testcontainers.gitserver.GitServerVersions; 63 | import com.github.sparsick.testcontainers.gitserver.plain.GitServerContainer; 64 | import com.github.sparsick.testcontainers.gitserver.plain.SshHostKey; 65 | import com.github.sparsick.testcontainers.gitserver.plain.SshIdentity; 66 | 67 | @Testcontainers 68 | public class GitServerContainerUsedInJUnit5Test { 69 | 70 | @Container 71 | private GitServerContainer containerUnderTest = 72 | new GitServerContainer(GitServerVersions.V2_43.getDockerImageName()) 73 | .withGitRepo("testRepo") // overwrite the default git repository name 74 | .withGitPassword("12345") // overwrite the default git password 75 | .withSshKeyAuth() // enabled public key authentication 76 | .withCopyExistingGitRepoToContainer("src/test/resources/sampleRepo"); // path to an already existing Git repository 77 | 78 | @Test 79 | void checkInteractWithTheContainer() { 80 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsSSH(); 81 | String gitPassword = containerUnderTest.getGitPassword(); 82 | 83 | SshIdentity sshIdentity = containerUnderTest.getSshClientIdentity(); 84 | byte[] privateKey = sshIdentity.getPrivateKey(); 85 | byte[] publicKey = sshIdentity.getPublicKey(); 86 | byte[] passphrase = sshIdentity.getPassphrase(); 87 | 88 | SshHostKey hostKey = containerUnderTest.getHostKey(); 89 | String host = hostKey.getHostname(); 90 | byte[] key = hostKey.getKey(); 91 | 92 | // check interaction 93 | 94 | } 95 | } 96 | ```` 97 | 98 | ### Git Server via HTTP 99 | The following sample shows how to use the git server container via HTTP without Basic Authentication in a JUnit 5 test: 100 | 101 | ````java 102 | import com.github.sparsick.testcontainers.gitserver.GitServerVersions; 103 | import com.github.sparsick.testcontainers.gitserver.http.GitHttpServerContainer; 104 | 105 | @Testcontainers 106 | public class GitHttpServerContainerUsedInJUnit5Test { 107 | 108 | @Container 109 | private GitHttpServerContainer containerUnderTest = 110 | new GitHttpServerContainer(GitServerVersions.V2_43.getDockerImageName()); 111 | 112 | @Test 113 | void checkInteractWithTheContainer() { 114 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsHttp(); 115 | 116 | // check interaction 117 | } 118 | } 119 | ```` 120 | #### HTTP with Basic Authentication 121 | The next sample shows how to use the git server container via HTTP with Basic Authentication in a JUnit 5 test: 122 | 123 | ````java 124 | import com.github.sparsick.testcontainers.gitserver.GitServerVersions; 125 | import com.github.sparsick.testcontainers.gitserver.http.BasicAuthenticationCredentials; 126 | import com.github.sparsick.testcontainers.gitserver.http.GitHttpServerContainer; 127 | 128 | @Testcontainers 129 | public class GitHttpServerContainerUsedInJUnit5Test { 130 | 131 | @Container 132 | private GitHttpServerContainer containerUnderTest = 133 | new GitHttpServerContainer(GitServerVersions.V2_43.getDockerImageName(), new BasicAuthenticationCredentials("testuser", "testPassword")); 134 | 135 | @Test 136 | void checkInteractWithTheContainer() { 137 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsHttp(); 138 | 139 | BasicAuthenticationCredentials basicAuthCredentials = containerUnderTest.getBasicAuthCredentials(); 140 | String username = basicAuthCredentials.getUsername(); 141 | String password = basicAuthCredentials.getPassword(); 142 | 143 | // check interaction 144 | } 145 | } 146 | ```` 147 | #### Enabling HTTP Proxy 148 | Since 0.9.0 it is possible to configure HTTP proxy, programmatically. 149 | 150 | ````java 151 | import com.github.sparsick.testcontainers.gitserver.GitServerVersions; 152 | import com.github.sparsick.testcontainers.gitserver.http.GitHttpServerContainer; 153 | 154 | @Testcontainers 155 | public class GitHttpServerContainerUsedInJUnit5Test { 156 | 157 | @Container 158 | private GitHttpServerContainer containerUnderTest = 159 | new GitHttpServerContainer(GitServerVersions.V2_43.getDockerImageName()) 160 | .withHttpProxySetting(new HttpProxySetting("http://proxy.example.com", "https://proxy.example.com", "")); 161 | 162 | @Test 163 | void hasHttpProxySetting() { 164 | assertThat(containerUnderTest.hasHttpProxy()).isTrue(); 165 | // check interaction 166 | } 167 | } 168 | ```` 169 | 170 | ## Migration Guide 171 | ### Migration from 0.4.x to 0.5.x 172 | 173 | In 0.5.x the package structure has changed. 174 | The package `com.github.sparsick.testcontainers.gitserver` is split in `com.github.sparsick.testcontainers.gitserver.plain` and `com.github.sparsick.testcontainers.gitserver.http`. 175 | Making this migration easier, an OpenRewrite recipe `io.github.sparsick.testcontainers.gitserver.rewrite.recipe.SplitPackage` is provided. 176 | 177 | ````shell 178 | mvn -U org.openrewrite.maven:rewrite-maven-plugin:run \ 179 | -Drewrite.recipeArtifactCoordinates=io.github.sparsick.testcontainers.gitserver:rewrite-testcontainers-gitserver:RELEASE \ 180 | -Drewrite.activeRecipes=io.github.sparsick.testcontainers.gitserver.rewrite.recipe.SplitPackage 181 | ```` 182 | 183 | ## License 184 | 185 | MIT License 186 | 187 | 188 | 189 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: 4 | default: 5 | target: 80% 6 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | io.github.sparsick.testcontainers.gitserver 8 | testcontainers-git-parent 9 | 0.13.0-SNAPSHOT 10 | 11 | pom 12 | 13 | Git Server for Testcontainers 14 | Testcontainers Wrapper for gitserver Container Image 15 | https://github.com/sparsick/testcontainers-git 16 | 17 | 18 | 19 | MIT License 20 | https://github.com/sparsick/testcontainers-git/blob/main/LICENSE 21 | repo 22 | 23 | 24 | 25 | 26 | 11 27 | 17 28 | UTF-8 29 | 7.2.1.202505142326-r 30 | 31 | 32 | 33 | testcontainers-gitserver 34 | rewrite-testcontainers-gitserver 35 | testcontainers-git-bom 36 | 37 | 38 | 39 | 40 | 41 | ch.qos.logback 42 | logback-classic 43 | 1.5.18 44 | provided 45 | 46 | 47 | org.slf4j 48 | slf4j-api 49 | 2.0.17 50 | 51 | 52 | org.assertj 53 | assertj-core 54 | 3.27.3 55 | 56 | 57 | org.testcontainers 58 | testcontainers-bom 59 | 1.21.1 60 | pom 61 | import 62 | 63 | 64 | org.junit 65 | junit-bom 66 | 5.13.0 67 | pom 68 | import 69 | 70 | 71 | org.openrewrite.recipe 72 | rewrite-recipe-bom 73 | 3.9.0 74 | pom 75 | import 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | org.jacoco 84 | jacoco-maven-plugin 85 | 86 | 87 | 88 | prepare-agent 89 | report 90 | 91 | 92 | 93 | 94 | 95 | org.apache.maven.plugins 96 | maven-surefire-plugin 97 | 3.5.3 98 | 99 | 100 | org.apache.maven.plugins 101 | maven-compiler-plugin 102 | 3.14.0 103 | 104 | 105 | org.apache.maven.plugins 106 | maven-resources-plugin 107 | 3.3.1 108 | 109 | 110 | 111 | 112 | 113 | org.jacoco 114 | jacoco-maven-plugin 115 | 0.8.13 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | release 124 | 125 | 126 | 127 | org.apache.maven.plugins 128 | maven-gpg-plugin 129 | 3.2.7 130 | 131 | 132 | sign-artifacts 133 | verify 134 | 135 | sign 136 | 137 | 138 | 139 | 140 | 141 | org.apache.maven.plugins 142 | maven-source-plugin 143 | 3.3.1 144 | 145 | 146 | 147 | jar-no-fork 148 | 149 | 150 | 151 | 152 | 153 | org.apache.maven.plugins 154 | maven-javadoc-plugin 155 | 3.11.2 156 | 157 | 158 | attach-javadocs 159 | 160 | jar 161 | 162 | 163 | 164 | 165 | 166 | org.cyclonedx 167 | cyclonedx-maven-plugin 168 | 2.9.1 169 | 170 | 171 | package 172 | 173 | makeAggregateBom 174 | 175 | 176 | ${project.artifactId}-${project.version}-cyclonedx 177 | 178 | 179 | 180 | 181 | 182 | org.sonatype.central 183 | central-publishing-maven-plugin 184 | 0.7.0 185 | true 186 | 187 | central 188 | true 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | sparsick 199 | Sandra Parsick 200 | mail (at) sandra-parsick.de 201 | https://www.sandra-parsick.de 202 | 203 | developer 204 | 205 | 206 | 207 | 208 | 209 | GitHub 210 | https://github.com/sparsick/maven-docker-extension/issues 211 | 212 | 213 | 214 | scm:git:git@github.com:sparsick/testcontainers-git.git 215 | scm:git:git@github.com:sparsick/testcontainers-git.git 216 | https://github.com/sparsick/testcontainers-git 217 | HEAD 218 | 219 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -eo pipefail 4 | 5 | # Trap not-normal exit signals: 1/HUP, 2/INT, 3/QUIT, 15/TERM 6 | trap catch_sig 1 2 3 15 7 | # Trap errors (simple commands exiting with a non-zero status) 8 | trap 'catch_err ${LINENO}' ERR 9 | 10 | if [ $# -ne 2 ]; then 11 | echo "Usage: release.sh " 12 | exit 1 13 | fi 14 | 15 | release_version=$1 16 | new_version=$2 17 | 18 | mvn versions:set "-DnewVersion=$release_version" -DgenerateBackupPoms=false 19 | 20 | git commit -a -m "$release_version release" 21 | git tag -a "$release_version" -a -m "$release_version release" 22 | 23 | mvn deploy -DskipTests -Prelease 24 | 25 | mvn versions:set "-DnewVersion=$new_version" -DgenerateBackupPoms=false 26 | git commit -a -m "Preparing $new_version iteration" 27 | 28 | git push 29 | git push origin "$release_version" 30 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ], 5 | "labels": ["dependencies"] 6 | } 7 | -------------------------------------------------------------------------------- /rewrite-testcontainers-gitserver/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | io.github.sparsick.testcontainers.gitserver 9 | testcontainers-git-parent 10 | 0.13.0-SNAPSHOT 11 | 12 | 13 | rewrite-testcontainers-gitserver 14 | Rewrite for Git Server for Testcontainers 15 | 16 | 17 | 18 | 19 | ch.qos.logback 20 | logback-classic 21 | 22 | 23 | org.slf4j 24 | slf4j-api 25 | 26 | 27 | org.openrewrite 28 | rewrite-java 29 | 30 | 31 | org.openrewrite 32 | rewrite-yaml 33 | 34 | 35 | 36 | org.openrewrite 37 | rewrite-java-11 38 | runtime 39 | 40 | 41 | org.openrewrite 42 | rewrite-java-17 43 | runtime 44 | 45 | 46 | org.openrewrite 47 | rewrite-java-21 48 | runtime 49 | 50 | 51 | 52 | org.junit.jupiter 53 | junit-jupiter 54 | test 55 | 56 | 57 | org.assertj 58 | assertj-core 59 | test 60 | 61 | 62 | org.openrewrite 63 | rewrite-test 64 | test 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /rewrite-testcontainers-gitserver/src/main/java/io/github/sparsick/testcontainers/gitserver/rewrite/recipe/RenamePackageOfGitHttpServerContainer.java: -------------------------------------------------------------------------------- 1 | package io.github.sparsick.testcontainers.gitserver.rewrite.recipe; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import org.openrewrite.ExecutionContext; 5 | import org.openrewrite.Preconditions; 6 | import org.openrewrite.Recipe; 7 | import org.openrewrite.TreeVisitor; 8 | import org.openrewrite.java.ChangeType; 9 | import org.openrewrite.java.JavaIsoVisitor; 10 | import org.openrewrite.java.search.FindImports; 11 | import org.openrewrite.java.search.UsesType; 12 | import org.openrewrite.java.tree.J; 13 | import org.openrewrite.java.tree.NameTree; 14 | 15 | import java.util.Set; 16 | 17 | /** 18 | * Rename import for GitHttpContainer. 19 | */ 20 | public class RenamePackageOfGitHttpServerContainer extends Recipe { 21 | 22 | /** 23 | * Default constructor. 24 | */ 25 | @JsonCreator 26 | public RenamePackageOfGitHttpServerContainer() { 27 | } 28 | 29 | @Override 30 | public String getDisplayName() { 31 | return "Rename import for GitHttpContainer"; 32 | } 33 | 34 | @Override 35 | public String getDescription() { 36 | return "Rename import for GitHttpContainer."; 37 | } 38 | 39 | @Override 40 | public TreeVisitor getVisitor() { 41 | return Preconditions.check(Preconditions.or( 42 | new UsesType<>("com.github.sparsick.testcontainers.gitserver.GitHttpServerContainer", false), 43 | new FindImports("com.github.sparsick.testcontainers.gitserver.GitHttpServerContainer", null).getVisitor() 44 | ), new RenamePackageOfGitHttpContainerVisitor()); 45 | 46 | } 47 | 48 | private class RenamePackageOfGitHttpContainerVisitor extends JavaIsoVisitor { 49 | 50 | 51 | @Override 52 | public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) { 53 | J.CompilationUnit compilationUnit = super.visitCompilationUnit(cu, ctx); 54 | Set nameTreeSet = compilationUnit.findType("com.github.sparsick.testcontainers.gitserver.GitHttpServerContainer"); 55 | if (!nameTreeSet.isEmpty()) { 56 | compilationUnit = (J.CompilationUnit) new ChangeType("com.github.sparsick.testcontainers.gitserver.GitHttpServerContainer", "com.github.sparsick.testcontainers.gitserver.http.GitHttpServerContainer", true) 57 | .getVisitor().visitNonNull(compilationUnit, ctx); 58 | } 59 | return compilationUnit; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /rewrite-testcontainers-gitserver/src/main/resources/META-INF/rewrite/classpath/testcontainers-gitserver-0.4.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sparsick/testcontainers-git/91e6c37dbfd70dc690fc6dc405e4209a09e3be08/rewrite-testcontainers-gitserver/src/main/resources/META-INF/rewrite/classpath/testcontainers-gitserver-0.4.0.jar -------------------------------------------------------------------------------- /rewrite-testcontainers-gitserver/src/main/resources/META-INF/rewrite/rewrite.yml: -------------------------------------------------------------------------------- 1 | --- 2 | type: specs.openrewrite.org/v1beta/recipe 3 | name: io.github.sparsick.testcontainers.gitserver.rewrite.recipe.RenamePackageOfBasicAuthenticationCredentials 4 | displayName: Rename package of BasicAuthenticationCredentials 5 | recipeList: 6 | - org.openrewrite.java.ChangeType: 7 | oldFullyQualifiedTypeName: com.github.sparsick.testcontainers.gitserver.BasicAuthenticationCredentials 8 | newFullyQualifiedTypeName: com.github.sparsick.testcontainers.gitserver.http.BasicAuthenticationCredentials 9 | ignoreDefinition: null 10 | 11 | --- 12 | type: specs.openrewrite.org/v1beta/recipe 13 | name: io.github.sparsick.testcontainers.gitserver.rewrite.recipe.RenamePackageOfGitServerContainer 14 | displayName: Rename package of GitServerContainer 15 | recipeList: 16 | - org.openrewrite.java.ChangeType: 17 | oldFullyQualifiedTypeName: com.github.sparsick.testcontainers.gitserver.GitServerContainer 18 | newFullyQualifiedTypeName: com.github.sparsick.testcontainers.gitserver.plain.GitServerContainer 19 | ignoreDefinition: null 20 | 21 | --- 22 | type: specs.openrewrite.org/v1beta/recipe 23 | name: io.github.sparsick.testcontainers.gitserver.rewrite.recipe.RenamePackageOfSshHostKey 24 | displayName: Rename package of SshHostKey 25 | recipeList: 26 | - org.openrewrite.java.ChangeType: 27 | oldFullyQualifiedTypeName: com.github.sparsick.testcontainers.gitserver.SshHostKey 28 | newFullyQualifiedTypeName: com.github.sparsick.testcontainers.gitserver.plain.SshHostKey 29 | ignoreDefinition: null 30 | 31 | --- 32 | type: specs.openrewrite.org/v1beta/recipe 33 | name: io.github.sparsick.testcontainers.gitserver.rewrite.recipe.RenamePackageOfSshIdentity 34 | displayName: Rename package of SshIdentity 35 | recipeList: 36 | - org.openrewrite.java.ChangeType: 37 | oldFullyQualifiedTypeName: com.github.sparsick.testcontainers.gitserver.SshIdentity 38 | newFullyQualifiedTypeName: com.github.sparsick.testcontainers.gitserver.plain.SshIdentity 39 | ignoreDefinition: null 40 | --- 41 | 42 | type: specs.openrewrite.org/v1beta/recipe 43 | name: io.github.sparsick.testcontainers.gitserver.rewrite.recipe.SplitPackage 44 | description: Splitting origin package into plain and http specific ones. 45 | displayName: Split package 46 | recipeList: 47 | - io.github.sparsick.testcontainers.gitserver.rewrite.recipe.RenamePackageOfSshIdentity 48 | - io.github.sparsick.testcontainers.gitserver.rewrite.recipe.RenamePackageOfSshHostKey 49 | - io.github.sparsick.testcontainers.gitserver.rewrite.recipe.RenamePackageOfGitServerContainer 50 | - io.github.sparsick.testcontainers.gitserver.rewrite.recipe.RenamePackageOfBasicAuthenticationCredentials 51 | - io.github.sparsick.testcontainers.gitserver.rewrite.recipe.RenamePackageOfGitHttpServerContainer -------------------------------------------------------------------------------- /rewrite-testcontainers-gitserver/src/test/java/io/github/sparsick/testcontainers/gitserver/rewrite/recipe/RenamePackageOfGitHttpServerContainerTest.java: -------------------------------------------------------------------------------- 1 | package io.github.sparsick.testcontainers.gitserver.rewrite.recipe; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.openrewrite.InMemoryExecutionContext; 5 | import org.openrewrite.java.JavaParser; 6 | import org.openrewrite.test.RecipeSpec; 7 | import org.openrewrite.test.RewriteTest; 8 | 9 | import static org.openrewrite.java.Assertions.java; 10 | 11 | public class RenamePackageOfGitHttpServerContainerTest implements RewriteTest { 12 | 13 | 14 | @Override 15 | public void defaults(RecipeSpec spec) { 16 | spec.recipe(new RenamePackageOfGitHttpServerContainer()); 17 | spec.parser(JavaParser.fromJavaVersion() 18 | .classpathFromResources(new InMemoryExecutionContext(), "testcontainers-gitserver-0.4.0")); 19 | } 20 | 21 | @Test 22 | void renameImport() { 23 | rewriteRun( 24 | java( 25 | """ 26 | import com.github.sparsick.testcontainers.gitserver.GitHttpServerContainer; 27 | 28 | class FooBar { 29 | 30 | private GitHttpServerContainer container = null; 31 | 32 | } 33 | """, 34 | """ 35 | import com.github.sparsick.testcontainers.gitserver.http.GitHttpServerContainer; 36 | 37 | class FooBar { 38 | 39 | private GitHttpServerContainer container = null; 40 | 41 | } 42 | """ 43 | ) 44 | ); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /rewrite-testcontainers-gitserver/src/test/java/io/github/sparsick/testcontainers/gitserver/rewrite/recipe/SplitPackageTest.java: -------------------------------------------------------------------------------- 1 | package io.github.sparsick.testcontainers.gitserver.rewrite.recipe; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.openrewrite.InMemoryExecutionContext; 5 | import org.openrewrite.java.JavaParser; 6 | import org.openrewrite.test.RecipeSpec; 7 | import org.openrewrite.test.RewriteTest; 8 | 9 | import static org.openrewrite.java.Assertions.java; 10 | 11 | public class SplitPackageTest implements RewriteTest { 12 | 13 | 14 | @Override 15 | public void defaults(RecipeSpec spec) { 16 | spec.recipe(SplitPackageTest.class.getResourceAsStream("/META-INF/rewrite/rewrite.yml"), "io.github.sparsick.testcontainers.gitserver.rewrite.recipe.SplitPackage"); 17 | spec.parser(JavaParser.fromJavaVersion() 18 | .classpathFromResources(new InMemoryExecutionContext(), "testcontainers-gitserver-0.4.0")); 19 | } 20 | 21 | @Test 22 | void renameImporst() { 23 | rewriteRun( 24 | java( 25 | """ 26 | import com.github.sparsick.testcontainers.gitserver.BasicAuthenticationCredentials; 27 | import com.github.sparsick.testcontainers.gitserver.GitHttpServerContainer; 28 | import com.github.sparsick.testcontainers.gitserver.GitServerContainer; 29 | import com.github.sparsick.testcontainers.gitserver.SshHostKey; 30 | import com.github.sparsick.testcontainers.gitserver.SshIdentity; 31 | 32 | class FooBar { 33 | 34 | private GitHttpServerContainer httpContainer = null; 35 | private BasicAuthenticationCredentials credentials = null; 36 | private GitServerContainer plainContainer = null; 37 | private SshIdentity identity = null; 38 | private SshHostKey hostkey = null; 39 | 40 | } 41 | """, 42 | """ 43 | import com.github.sparsick.testcontainers.gitserver.http.BasicAuthenticationCredentials; 44 | import com.github.sparsick.testcontainers.gitserver.http.GitHttpServerContainer; 45 | import com.github.sparsick.testcontainers.gitserver.plain.GitServerContainer; 46 | import com.github.sparsick.testcontainers.gitserver.plain.SshHostKey; 47 | import com.github.sparsick.testcontainers.gitserver.plain.SshIdentity; 48 | 49 | class FooBar { 50 | 51 | private GitHttpServerContainer httpContainer = null; 52 | private BasicAuthenticationCredentials credentials = null; 53 | private GitServerContainer plainContainer = null; 54 | private SshIdentity identity = null; 55 | private SshHostKey hostkey = null; 56 | 57 | } 58 | """ 59 | ) 60 | ); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /testcontainers-git-bom/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | io.github.sparsick.testcontainers.gitserver 8 | testcontainers-git-parent 9 | 0.13.0-SNAPSHOT 10 | 11 | 12 | testcontainers-git-bom 13 | pom 14 | BOM for Git Server for Testcontainers 15 | 16 | 17 | 18 | 19 | 20 | io.github.sparsick.testcontainers.gitserver 21 | rewrite-testcontainers-gitserver 22 | ${project.version} 23 | 24 | 25 | io.github.sparsick.testcontainers.gitserver 26 | testcontainers-gitserver 27 | 0.13.0-SNAPSHOT 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /testcontainers-gitserver/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | io.github.sparsick.testcontainers.gitserver 9 | testcontainers-git-parent 10 | 0.13.0-SNAPSHOT 11 | 12 | 13 | testcontainers-gitserver 14 | Git Server for Testcontainers 15 | 16 | 17 | 18 | org.testcontainers 19 | testcontainers 20 | 21 | 22 | ch.qos.logback 23 | logback-classic 24 | 25 | 26 | org.slf4j 27 | slf4j-api 28 | 29 | 30 | org.junit.jupiter 31 | junit-jupiter 32 | test 33 | 34 | 35 | org.assertj 36 | assertj-core 37 | test 38 | 39 | 40 | org.eclipse.jgit 41 | org.eclipse.jgit 42 | ${jgit.version} 43 | test 44 | 45 | 46 | org.eclipse.jgit 47 | org.eclipse.jgit.ssh.jsch 48 | ${jgit.version} 49 | test 50 | 51 | 52 | org.testcontainers 53 | junit-jupiter 54 | test 55 | 56 | 57 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/java/com/github/sparsick/testcontainers/gitserver/GitServerVersions.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver; 2 | 3 | import org.testcontainers.utility.DockerImageName; 4 | 5 | /** 6 | * List of supported Git server version based on the docker image "rockstorm/git-server" 7 | * 8 | */ 9 | public enum GitServerVersions { 10 | 11 | /** 12 | * rockstorm/git-server:2.49 13 | */ 14 | V2_49(DockerImageName.parse("rockstorm/git-server:2.49")), 15 | 16 | 17 | /** 18 | * rockstorm/git-server:2.47 19 | */ 20 | V2_47(DockerImageName.parse("rockstorm/git-server:2.47")), 21 | 22 | /** 23 | * rockstorm/git-server:2.45 24 | */ 25 | V2_45(DockerImageName.parse("rockstorm/git-server:2.45")), 26 | 27 | 28 | /** 29 | * rockstorm/git-server:2.43 30 | */ 31 | V2_43(DockerImageName.parse("rockstorm/git-server:2.43")), 32 | 33 | /** 34 | * rockstorm/git-server:2.40 35 | */ 36 | V2_40(DockerImageName.parse("rockstorm/git-server:2.40")), 37 | /** 38 | * rockstorm/git-server:2.38 39 | */ 40 | V2_38(DockerImageName.parse("rockstorm/git-server:2.38")), 41 | /** 42 | * rockstorm/git-server:2.36 43 | */ 44 | V2_36(DockerImageName.parse("rockstorm/git-server:2.36")), 45 | /** 46 | * rockstorm/git-server:2.34.2 47 | */ 48 | V2_34_2(DockerImageName.parse("rockstorm/git-server:2.34.2")), 49 | /** 50 | * rockstorm/git-server:2.34 51 | */ 52 | V2_34(DockerImageName.parse("rockstorm/git-server:2.34")); 53 | 54 | private final DockerImageName dockerImageName; 55 | 56 | GitServerVersions(DockerImageName dockerImageName) { 57 | this.dockerImageName = dockerImageName; 58 | } 59 | 60 | /** 61 | * 62 | * @return docker image name 63 | */ 64 | public DockerImageName getDockerImageName() { 65 | return dockerImageName; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/java/com/github/sparsick/testcontainers/gitserver/http/BasicAuthenticationCredentials.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver.http; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * Credentials for basic authentication 7 | */ 8 | public class BasicAuthenticationCredentials { 9 | 10 | private final String username; 11 | private final String password; 12 | 13 | /** 14 | * 15 | * @param username - username for basic authentication 16 | * @param password - password for basic authentication 17 | */ 18 | public BasicAuthenticationCredentials(String username, String password){ 19 | this.username = username; 20 | this.password = password; 21 | } 22 | 23 | /** 24 | * 25 | * @return username for basic authentication 26 | */ 27 | public String getUsername() { 28 | return username; 29 | } 30 | 31 | /** 32 | * 33 | * @return password for basic authentication 34 | */ 35 | public String getPassword() { 36 | return password; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/java/com/github/sparsick/testcontainers/gitserver/http/GitHttpServerContainer.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver.http; 2 | 3 | import com.github.dockerjava.api.command.InspectContainerResponse; 4 | import org.jetbrains.annotations.NotNull; 5 | import org.testcontainers.containers.GenericContainer; 6 | import org.testcontainers.containers.wait.strategy.Wait; 7 | import org.testcontainers.images.builder.ImageFromDockerfile; 8 | import org.testcontainers.images.builder.dockerfile.DockerfileBuilder; 9 | import org.testcontainers.utility.DockerImageName; 10 | 11 | import java.io.IOException; 12 | import java.net.URI; 13 | import java.util.function.Consumer; 14 | 15 | /** 16 | * Container for a plain Git HTTP Server based on the Docker image "rockstorm/git-server". 17 | */ 18 | public class GitHttpServerContainer extends GenericContainer { 19 | private final String gitRepoName = "testRepo"; 20 | 21 | private final static DockerImageName DEFAULT_DOCKER_IMAGE_NAME = DockerImageName.parse("rockstorm/git-server"); 22 | 23 | private final BasicAuthenticationCredentials basicAuthenticationCredentials; 24 | private HttpProxySetting httpProxySetting; 25 | private boolean httpProxyEnabled = false; 26 | 27 | 28 | /** 29 | * @param dockerImageName - name of the docker image 30 | */ 31 | public GitHttpServerContainer(DockerImageName dockerImageName) { 32 | this(dockerImageName, null); 33 | } 34 | 35 | /** 36 | * @param dockerImageName - name of the docker image 37 | * @param basicAuthenticationCredentials - credentials for basic authentication 38 | */ 39 | public GitHttpServerContainer(DockerImageName dockerImageName, BasicAuthenticationCredentials basicAuthenticationCredentials) { 40 | super(new ImageFromDockerfile() 41 | .withFileFromClasspath("http-config/nginx.conf", "http-config/nginx.conf") 42 | .withDockerfileFromBuilder(dockerfileBuilder(dockerImageName, basicAuthenticationCredentials))); 43 | dockerImageName.assertCompatibleWith(DEFAULT_DOCKER_IMAGE_NAME); 44 | 45 | if ("2.38".compareTo(dockerImageName.getVersionPart()) <= 0) { 46 | waitingFor(Wait.forLogMessage(".*Container configuration completed.*", 1)).addExposedPorts(80); 47 | } else { 48 | withExposedPorts(80); 49 | } 50 | this.basicAuthenticationCredentials = basicAuthenticationCredentials; 51 | } 52 | 53 | @NotNull 54 | private static Consumer dockerfileBuilder(DockerImageName dockerImageName, BasicAuthenticationCredentials basicAuthenticationCredentials) { 55 | return builder -> { 56 | var tempBuilder = builder 57 | .from(dockerImageName.toString()) 58 | .run("apk add --update nginx && " + 59 | checkUpdateGit(dockerImageName) + 60 | "apk add --update fcgiwrap && " + 61 | "apk add --update spawn-fcgi && " + 62 | checkIfOpensslIsNeeded(basicAuthenticationCredentials) + 63 | "rm -rf /var/cache/apk/*") 64 | .copy("./http-config/nginx.conf", "/etc/nginx/nginx.conf"); 65 | 66 | if (basicAuthenticationCredentials != null) { 67 | tempBuilder.run("sh", "-c", "echo \"" + basicAuthenticationCredentials.getUsername() + ":$(openssl passwd -apr1 " + basicAuthenticationCredentials.getPassword() + ")\" > /etc/nginx/.htpasswd"); 68 | tempBuilder.run("sh", "-c", "sed -i -e 's/#auth_basic/auth_basic/g' /etc/nginx/nginx.conf"); 69 | } 70 | 71 | tempBuilder.cmd("spawn-fcgi -s /run/fcgi.sock -- /usr/bin/fcgiwrap -f && " + 72 | " nginx -g \"daemon off;\"") 73 | .build(); 74 | 75 | }; 76 | 77 | } 78 | 79 | @NotNull 80 | private static String checkIfOpensslIsNeeded(BasicAuthenticationCredentials basicAuthenticationCredentials) { 81 | final String enableOpenssl; 82 | if (basicAuthenticationCredentials != null) { 83 | enableOpenssl = "apk add --update openssl && "; 84 | } else { 85 | enableOpenssl = ""; 86 | } 87 | return enableOpenssl; 88 | } 89 | 90 | @NotNull 91 | private static String checkUpdateGit(DockerImageName dockerImageName) { 92 | final String updateGit; 93 | if ("2.36".compareTo(dockerImageName.getVersionPart()) == 0) { 94 | updateGit = "apk add --update git=2.36.6-r0 git-daemon=2.36.6-r0 && "; 95 | } else if ("2.34".compareTo(dockerImageName.getVersionPart()) == 0) { 96 | updateGit = "apk add --update git=2.34.8-r0 git-daemon=2.34.8-r0 && "; 97 | } else { 98 | updateGit = "apk add --update git git-daemon && "; 99 | } 100 | return updateGit; 101 | } 102 | 103 | /** 104 | * Return the HTTP URI for git repo. 105 | * 106 | * @return HTTP URI 107 | */ 108 | public URI getGitRepoURIAsHttp() { 109 | return URI.create("http://" + getHost() + ":" + getMappedPort(80) + "/git/" + gitRepoName); 110 | } 111 | 112 | @Override 113 | protected void containerIsStarted(InspectContainerResponse containerInfo) { 114 | super.containerIsStarted(containerInfo); 115 | configureGitRepository(); 116 | } 117 | 118 | private void configureGitRepository() { 119 | try { 120 | String gitRepoPath = String.format("/srv/git/%s.git", gitRepoName); 121 | execInContainer("mkdir", "-p", gitRepoPath); 122 | execInContainer("git", "init", "--bare", gitRepoPath); 123 | execInContainer("sh", "-c", "echo '[http]' >> " + gitRepoPath + "/config"); 124 | execInContainer("sh", "-c", "echo ' receivepack = true' >> " + gitRepoPath + "/config"); 125 | } catch (IOException | InterruptedException e) { 126 | throw new RuntimeException("Configure Git repository failed", e); 127 | 128 | } 129 | } 130 | 131 | /** 132 | * Return credentials for basic authentication 133 | * 134 | * @return credentials for basic authentication 135 | */ 136 | public BasicAuthenticationCredentials getBasicAuthCredentials() { 137 | return basicAuthenticationCredentials; 138 | } 139 | 140 | public boolean hasHttpProxy() { 141 | return this.httpProxyEnabled; 142 | } 143 | 144 | public GitHttpServerContainer withHttpProxySetting(HttpProxySetting httpProxySetting) { 145 | withEnv("HTTP_PROXY", httpProxySetting.getHttpProxy()); 146 | withEnv("http_proxy", httpProxySetting.getHttpProxy()); 147 | 148 | withEnv("HTTPS_PROXY", httpProxySetting.getHttpsProxy()); 149 | withEnv("https_proxy", httpProxySetting.getHttpsProxy()); 150 | 151 | withEnv("NO_PROXY", httpProxySetting.getNoProxy()); 152 | withEnv("no_proxy", httpProxySetting.getNoProxy()); 153 | this.httpProxyEnabled = true; 154 | return this; 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/java/com/github/sparsick/testcontainers/gitserver/http/HttpProxySetting.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver.http; 2 | 3 | import java.util.Objects; 4 | 5 | public class HttpProxySetting { 6 | 7 | private String httpProxy; 8 | private String httpsProxy; 9 | private String noProxy; 10 | 11 | public HttpProxySetting(String httpProxy, String httpsProxy, String noProxy) { 12 | this.httpProxy = httpProxy; 13 | this.httpsProxy = httpsProxy; 14 | this.noProxy = noProxy; 15 | } 16 | 17 | public String getHttpProxy() { 18 | return httpProxy; 19 | } 20 | 21 | public String getHttpsProxy() { 22 | return httpsProxy; 23 | } 24 | 25 | public String getNoProxy() { 26 | return noProxy; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/java/com/github/sparsick/testcontainers/gitserver/plain/GitServerContainer.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver.plain; 2 | 3 | import com.github.dockerjava.api.command.InspectContainerResponse; 4 | import org.testcontainers.containers.BindMode; 5 | import org.testcontainers.containers.GenericContainer; 6 | import org.testcontainers.containers.wait.strategy.Wait; 7 | import org.testcontainers.utility.DockerImageName; 8 | import org.testcontainers.utility.MountableFile; 9 | 10 | import java.io.IOException; 11 | import java.net.URI; 12 | import java.util.Base64; 13 | 14 | /** 15 | * Container for a plain Git Server based on the Docker image "rockstorm/git-server". 16 | */ 17 | public class GitServerContainer extends GenericContainer { 18 | 19 | private static final String GIT_PASSWORD_KEY = "GIT_PASSWORD"; 20 | private static DockerImageName DEFAULT_DOCKER_IMAGE_NAME = DockerImageName.parse("rockstorm/git-server"); 21 | private String gitRepoName = "testRepo"; 22 | private String pathToExistingRepo; 23 | private SshIdentity sshClientIdentity; 24 | private SshHostKey hostKey; 25 | 26 | /** 27 | * @param dockerImageName - name of the docker image 28 | */ 29 | public GitServerContainer(DockerImageName dockerImageName) { 30 | super(dockerImageName); 31 | dockerImageName.assertCompatibleWith(DEFAULT_DOCKER_IMAGE_NAME); 32 | if ("2.38".compareTo(dockerImageName.getVersionPart()) <= 0) { 33 | waitingFor(Wait.forLogMessage(".*Container configuration completed.*", 1)) 34 | .waitingFor(Wait.forListeningPorts(22)) 35 | .addExposedPorts(22); 36 | } else { 37 | waitingFor(Wait.forListeningPorts(22)) 38 | .addExposedPorts(22); 39 | } 40 | withCommand("/usr/sbin/sshd", "-D", "-e"); 41 | } 42 | 43 | /** 44 | * Override the default git password. 45 | *

46 | * Default password is 12345 47 | * 48 | * @param password - git password 49 | * @return instance of the git server container 50 | */ 51 | public GitServerContainer withGitPassword(String password) { 52 | withEnv(GIT_PASSWORD_KEY, password); 53 | return this; 54 | } 55 | 56 | 57 | /** 58 | * Override the default git repository name. 59 | *

60 | * Default name is "testRepo" 61 | * 62 | * @param gitRepoName - name of the git repository that is created by default 63 | * @return instance of the git server container 64 | */ 65 | public GitServerContainer withGitRepo(String gitRepoName) { 66 | this.gitRepoName = gitRepoName; 67 | return this; 68 | } 69 | 70 | /** 71 | * Enabled SSH public key authentication. 72 | * 73 | * @return instance of the git server container 74 | */ 75 | public GitServerContainer withSshKeyAuth() { 76 | try { 77 | sshClientIdentity = new SshIdentity( 78 | this.getClass().getClassLoader().getResourceAsStream("id_client").readAllBytes(), 79 | this.getClass().getClassLoader().getResourceAsStream("id_client.pub").readAllBytes(), 80 | new byte[0]); 81 | 82 | withClasspathResourceMapping("id_client.pub", "/home/git/.ssh/authorized_keys", BindMode.READ_ONLY); 83 | withClasspathResourceMapping("sshd_config", "/etc/ssh/sshd_config", BindMode.READ_ONLY); 84 | 85 | 86 | } catch (IOException e) { 87 | throw new RuntimeException(e); 88 | } 89 | return this; 90 | } 91 | 92 | /** 93 | * Copy an existing git repository to the container. 94 | *

95 | * The git repository is copied to the container and the git repository is initialized as bare repository. 96 | * 97 | * @param pathtoExistingRepo - path to the existing git repository. The path is relative to the project root. 98 | * @return instance of the git server container 99 | */ 100 | public GitServerContainer withCopyExistingGitRepoToContainer(String pathtoExistingRepo) { 101 | this.pathToExistingRepo = pathtoExistingRepo; 102 | return this; 103 | } 104 | 105 | /** 106 | * Return the SSH URI for git repo. 107 | * 108 | * @return SSH URI 109 | */ 110 | public URI getGitRepoURIAsSSH() { 111 | 112 | return URI.create("ssh://git@" + getHost() + ":" + getMappedPort(22) + "/srv/git/" + gitRepoName + ".git"); 113 | } 114 | 115 | @Override 116 | protected void containerIsStarted(InspectContainerResponse containerInfo) { 117 | super.containerIsStarted(containerInfo); 118 | configureGitRepository(); 119 | collectHostKeyInformation(); 120 | fixFilePermissions(); 121 | } 122 | 123 | /** 124 | * Wrong file permissions cause authentication to fail. 125 | */ 126 | private void fixFilePermissions() { 127 | try { 128 | execInContainer("chmod", "600", "/home/git/.ssh/authorized_keys"); 129 | } catch (IOException | InterruptedException e) { 130 | throw new RuntimeException("Could not fix file permissions on /home/git/.ssh/authorized_keys", e); 131 | } 132 | } 133 | 134 | private void collectHostKeyInformation() { 135 | try { 136 | ExecResult result = execInContainer("cat", "/etc/ssh/ssh_host_ecdsa_key.pub"); 137 | String[] catResult = result.getStdout().split(" "); 138 | hostKey = new SshHostKey(getHost(), Base64.getDecoder().decode(catResult[1])); 139 | } catch (IOException | InterruptedException e) { 140 | throw new RuntimeException("Could not collect host key information", e); 141 | } 142 | } 143 | 144 | private void configureGitRepository() { 145 | try { 146 | String gitRepoPath = String.format("/srv/git/%s.git", gitRepoName); 147 | if (pathToExistingRepo != null) { 148 | copyFileToContainer(MountableFile.forHostPath(pathToExistingRepo + "/.git"), gitRepoPath); 149 | execInContainer("git", "config", "--bool", "core.bare", "true", gitRepoPath); 150 | execInContainer("chown", "-R", "git:git", "/srv"); 151 | } else { 152 | execInContainer("mkdir", "-p", gitRepoPath); 153 | execInContainer("git", "init", "--bare", gitRepoPath); 154 | execInContainer("chown", "-R", "git:git", "/srv"); 155 | } 156 | } catch (IOException | InterruptedException e) { 157 | throw new RuntimeException("Configure Git repository failed",e); 158 | } 159 | } 160 | 161 | /** 162 | * Return the Git Password that was set with the method {@code withGitPassword}. 163 | *

164 | * If no password was set, the default "12345" is returned. 165 | * 166 | * @return the git password 167 | */ 168 | public String getGitPassword() { 169 | var password = getEnvMap().get(GIT_PASSWORD_KEY); 170 | return password != null ? password : "12345"; 171 | } 172 | 173 | /** 174 | * Return the identity information for public key authentication. 175 | *

176 | * If {@code withSshKeyAuth} was not called, then it returns null. 177 | * 178 | * @return identity information for a public key authentication 179 | */ 180 | public SshIdentity getSshClientIdentity() { 181 | return sshClientIdentity; 182 | } 183 | 184 | /** 185 | * Return the public host key information. 186 | * 187 | * @return public host key 188 | */ 189 | public SshHostKey getHostKey() { 190 | return hostKey; 191 | } 192 | 193 | } 194 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/java/com/github/sparsick/testcontainers/gitserver/plain/SshHostKey.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver.plain; 2 | 3 | import java.util.Objects; 4 | 5 | 6 | /** 7 | * Value object for SSH Host key information. 8 | */ 9 | public class SshHostKey { 10 | 11 | private String hostname; 12 | private byte[] key; 13 | 14 | /** 15 | * SSH Host Key information 16 | * @param hostname host 17 | * @param key keystring 18 | */ 19 | public SshHostKey(String hostname, byte[] key) { 20 | this.key = key; 21 | this.hostname = hostname; 22 | } 23 | 24 | /** 25 | * Public key of the host key. 26 | * 27 | * @return key string 28 | */ 29 | public byte[] getKey() { 30 | return key; 31 | } 32 | 33 | /** 34 | * Name of the host 35 | * 36 | * @return name of the host 37 | */ 38 | public String getHostname() { 39 | return hostname; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/java/com/github/sparsick/testcontainers/gitserver/plain/SshIdentity.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver.plain; 2 | 3 | /** 4 | * Value object for identity information for a public key authentication. 5 | */ 6 | public class SshIdentity { 7 | private byte[] privateKey; 8 | private byte[] publicKey; 9 | private byte[] passphrase; 10 | 11 | /** 12 | * Identity information for a public key authentication. 13 | * 14 | * @param privateKey SSH private key 15 | * @param publicKey SSH public key 16 | * @param passphrase password for private key 17 | */ 18 | public SshIdentity(byte[] privateKey, byte[] publicKey, byte[] passphrase) { 19 | this.privateKey = privateKey; 20 | this.publicKey = publicKey; 21 | this.passphrase = passphrase; 22 | } 23 | 24 | /** 25 | * SSH private key 26 | * 27 | * @return SSH private key 28 | */ 29 | public byte[] getPrivateKey() { 30 | return privateKey; 31 | } 32 | 33 | /** 34 | * SSH public key 35 | * 36 | * @return SSH public key 37 | */ 38 | public byte[] getPublicKey() { 39 | return publicKey; 40 | } 41 | 42 | /** 43 | * Password for the SSH private key 44 | * 45 | * @return Password for the SSH private key 46 | */ 47 | public byte[] getPassphrase() { 48 | return passphrase; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/resources/http-config/nginx.conf: -------------------------------------------------------------------------------- 1 | worker_processes 1; 2 | 3 | error_log /var/log/nginx/error.log; 4 | pid /run/nginx.pid; 5 | user root; 6 | 7 | events { 8 | worker_connections 1024; 9 | } 10 | 11 | http { 12 | server { 13 | listen *:80; 14 | 15 | root /www/empty/; 16 | index index.html; 17 | 18 | server_name $hostname; 19 | access_log /var/log/nginx/access.log; 20 | 21 | #error_page 404 /404.html; 22 | 23 | #auth_basic "Restricted"; 24 | #auth_basic_user_file /etc/nginx/.htpasswd; 25 | 26 | location ~ /git(/.*) { 27 | # Set chunks to unlimited, as the bodies can be huge 28 | client_max_body_size 0; 29 | 30 | fastcgi_param SCRIPT_FILENAME /usr/libexec/git-core/git-http-backend; 31 | include fastcgi_params; 32 | fastcgi_param GIT_HTTP_EXPORT_ALL ""; 33 | fastcgi_param GIT_PROJECT_ROOT /srv/git; 34 | fastcgi_param PATH_INFO $1; 35 | 36 | # Forward REMOTE_USER as we want to know when we are authenticated 37 | fastcgi_param REMOTE_USER $remote_user; 38 | fastcgi_pass unix:/run/fcgi.sock; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/resources/id_client: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MHcCAQEEIAv2zdBPnakBt4UCoTDRMLDKOrm0JiPc9CwRFqvcha5coAoGCCqGSM49 3 | AwEHoUQDQgAEKArvTWElvX1Erm/essBeGKQzsGrHPJjGJprwEOqV/MKjUPZ1jxl3 4 | iZL9m/PqZrKc94PGgpalIFdxOcdrgwTLMg== 5 | -----END EC PRIVATE KEY----- 6 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/resources/id_client.pub: -------------------------------------------------------------------------------- 1 | ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCgK701hJb19RK5v3rLAXhikM7BqxzyYxiaa8BDqlfzCo1D2dY8Zd4mS/Zvz6maynPeDxoKWpSBXcTnHa4MEyzI= sparsick@Thinkpad-T14 2 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/main/resources/sshd_config: -------------------------------------------------------------------------------- 1 | # $OpenBSD: sshd_config,v 1.104 2021/07/02 05:11:21 dtucker Exp $ 2 | 3 | # This is the sshd server system-wide configuration file. See 4 | # sshd_config(5) for more information. 5 | 6 | # This sshd was compiled with PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 7 | 8 | # The strategy used for options in the default sshd_config shipped with 9 | # OpenSSH is to specify options with their default value where 10 | # possible, but leave them commented. Uncommented options override the 11 | # default value. 12 | 13 | #Port 22 14 | #AddressFamily any 15 | #ListenAddress 0.0.0.0 16 | #ListenAddress :: 17 | 18 | #HostKey /etc/ssh/ssh_host_rsa_key 19 | #HostKey /etc/ssh/ssh_host_ecdsa_key 20 | #HostKey /etc/ssh/ssh_host_ed25519_key 21 | 22 | # Ciphers and keying 23 | #RekeyLimit default none 24 | 25 | # Logging 26 | #SyslogFacility AUTH 27 | #LogLevel DEBUG 28 | 29 | # Authentication: 30 | 31 | #LoginGraceTime 2m 32 | #PermitRootLogin prohibit-password 33 | #StrictModes yes 34 | #MaxAuthTries 6 35 | #MaxSessions 10 36 | 37 | #PubkeyAuthentication yes 38 | #PubkeyAcceptedAlgorithms ssh-rsa 39 | 40 | # The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2 41 | # but this is overridden so installations will only check .ssh/authorized_keys 42 | AuthorizedKeysFile .ssh/authorized_keys 43 | 44 | #AuthorizedPrincipalsFile none 45 | 46 | #AuthorizedKeysCommand none 47 | #AuthorizedKeysCommandUser nobody 48 | 49 | # For this to work you will also need host keys in /etc/ssh/ssh_known_hosts 50 | #HostbasedAuthentication no 51 | # Change to yes if you don't trust ~/.ssh/known_hosts for 52 | # HostbasedAuthentication 53 | #IgnoreUserKnownHosts no 54 | # Don't read the user's ~/.rhosts and ~/.shosts files 55 | #IgnoreRhosts yes 56 | 57 | # To disable tunneled clear text passwords, change to no here! 58 | #PasswordAuthentication yes 59 | #PermitEmptyPasswords no 60 | 61 | # Change to no to disable s/key passwords 62 | #KbdInteractiveAuthentication yes 63 | 64 | # Kerberos options 65 | #KerberosAuthentication no 66 | #KerberosOrLocalPasswd yes 67 | #KerberosTicketCleanup yes 68 | #KerberosGetAFSToken no 69 | 70 | # GSSAPI options 71 | #GSSAPIAuthentication no 72 | #GSSAPICleanupCredentials yes 73 | 74 | # Set this to 'yes' to enable PAM authentication, account processing, 75 | # and session processing. If this is enabled, PAM authentication will 76 | # be allowed through the KbdInteractiveAuthentication and 77 | # PasswordAuthentication. Depending on your PAM configuration, 78 | # PAM authentication via KbdInteractiveAuthentication may bypass 79 | # the setting of "PermitRootLogin without-password". 80 | # If you just want the PAM account and session checks to run without 81 | # PAM authentication, then enable this but set PasswordAuthentication 82 | # and KbdInteractiveAuthentication to 'no'. 83 | #UsePAM no 84 | 85 | #AllowAgentForwarding yes 86 | # Feel free to re-enable these if your use case requires them. 87 | AllowTcpForwarding no 88 | GatewayPorts no 89 | X11Forwarding no 90 | #X11DisplayOffset 10 91 | #X11UseLocalhost yes 92 | #PermitTTY yes 93 | #PrintMotd yes 94 | #PrintLastLog yes 95 | #TCPKeepAlive yes 96 | #PermitUserEnvironment no 97 | #Compression delayed 98 | #ClientAliveInterval 0 99 | #ClientAliveCountMax 3 100 | #UseDNS no 101 | #PidFile /run/sshd.pid 102 | #MaxStartups 10:30:100 103 | #PermitTunnel no 104 | #ChrootDirectory none 105 | #VersionAddendum none 106 | 107 | # no default banner path 108 | #Banner none 109 | 110 | # override default of no subsystems 111 | Subsystem sftp /usr/lib/ssh/sftp-server 112 | 113 | # Example of overriding settings on a per-user basis 114 | #Match User anoncvs 115 | # X11Forwarding no 116 | # AllowTcpForwarding no 117 | # PermitTTY no 118 | # ForceCommand cvs server -------------------------------------------------------------------------------- /testcontainers-gitserver/src/test/java/com/github/sparsick/testcontainers/gitserver/http/GitHttpServerContainerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver.http; 2 | 3 | import com.github.sparsick.testcontainers.gitserver.GitServerVersions; 4 | import org.assertj.core.api.ThrowableAssert; 5 | import org.eclipse.jgit.api.Git; 6 | import org.eclipse.jgit.api.errors.GitAPIException; 7 | import org.eclipse.jgit.api.errors.TransportException; 8 | import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; 9 | import org.junit.jupiter.api.Test; 10 | import org.junit.jupiter.api.io.CleanupMode; 11 | import org.junit.jupiter.api.io.TempDir; 12 | import org.junit.jupiter.params.ParameterizedTest; 13 | import org.junit.jupiter.params.provider.EnumSource; 14 | import org.testcontainers.utility.DockerImageName; 15 | 16 | import java.io.File; 17 | import java.io.IOException; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | import static org.assertj.core.api.Assertions.catchThrowableOfType; 21 | 22 | 23 | public class GitHttpServerContainerTest { 24 | 25 | private static final DockerImageName LATEST_GIT_SERVER_VERSION = GitServerVersions.V2_49.getDockerImageName(); 26 | 27 | @TempDir(cleanup = CleanupMode.NEVER) 28 | private File tempDir; 29 | 30 | @ParameterizedTest 31 | @EnumSource(GitServerVersions.class) 32 | void cloneWithoutAuthentication(GitServerVersions gitServerVersions) throws GitAPIException, IOException { 33 | GitHttpServerContainer containerUnderTest = new GitHttpServerContainer(gitServerVersions.getDockerImageName()); 34 | containerUnderTest.start(); 35 | 36 | Git git = Git.cloneRepository() 37 | .setURI(containerUnderTest.getGitRepoURIAsHttp().toString()) 38 | .setDirectory(tempDir) 39 | .call(); 40 | 41 | assertThat(new File(tempDir, ".git")).exists(); 42 | assertGitPull(git); 43 | } 44 | 45 | @ParameterizedTest 46 | @EnumSource(GitServerVersions.class) 47 | void cloneWithAuthenticationFailedWithoutCredential(GitServerVersions gitServerVersions) { 48 | GitHttpServerContainer containerUnderTest = new GitHttpServerContainer(gitServerVersions.getDockerImageName(), new BasicAuthenticationCredentials("testuser", "testPassword")); 49 | containerUnderTest.start(); 50 | 51 | 52 | ThrowableAssert.ThrowingCallable tryingClone = () -> Git.cloneRepository() 53 | .setURI(containerUnderTest.getGitRepoURIAsHttp().toString()) 54 | .setDirectory(tempDir) 55 | .call(); 56 | TransportException expectedException = catchThrowableOfType(tryingClone, TransportException.class); 57 | assertThat(expectedException).isNotNull(); 58 | assertThat(expectedException).hasMessageContaining("Authentication is required"); 59 | } 60 | 61 | @ParameterizedTest 62 | @EnumSource(GitServerVersions.class) 63 | void cloneWithAuthentication(GitServerVersions gitServerVersions) throws GitAPIException, IOException { 64 | GitHttpServerContainer containerUnderTest = new GitHttpServerContainer(gitServerVersions.getDockerImageName(),new BasicAuthenticationCredentials("testuser", "testPassword")); 65 | containerUnderTest.start(); 66 | 67 | UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(containerUnderTest.getBasicAuthCredentials().getUsername(), containerUnderTest.getBasicAuthCredentials().getPassword()); 68 | Git git = Git.cloneRepository() 69 | .setURI(containerUnderTest.getGitRepoURIAsHttp().toString()) 70 | .setDirectory(tempDir) 71 | .setCredentialsProvider(credentialsProvider) 72 | .call(); 73 | 74 | assertThat(new File(tempDir, ".git")).exists(); 75 | assertGitPull(git, credentialsProvider); 76 | } 77 | 78 | @Test 79 | void enableHttpProxySetting() throws GitAPIException, IOException { 80 | GitHttpServerContainer containerUnderTest = new GitHttpServerContainer(LATEST_GIT_SERVER_VERSION).withHttpProxySetting(new HttpProxySetting("http://proxy.example.com", "https://proxy.example.com", "")); 81 | containerUnderTest.start(); 82 | 83 | assertThat(containerUnderTest.hasHttpProxy()).isTrue(); 84 | 85 | 86 | } 87 | 88 | private void assertGitPull(Git git, UsernamePasswordCredentialsProvider credentialsProvider) throws IOException, GitAPIException { 89 | new File(tempDir, "test.txt").createNewFile(); 90 | git.add().addFilepattern(".").call(); 91 | git.commit().setMessage("test").call(); 92 | 93 | if (credentialsProvider == null) { 94 | git.push().call(); 95 | } else { 96 | git.push().setCredentialsProvider(credentialsProvider).call(); 97 | } 98 | } 99 | 100 | private void assertGitPull(Git git) throws IOException, GitAPIException { 101 | assertGitPull(git, null); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/test/java/com/github/sparsick/testcontainers/gitserver/plain/GitServerContainerJUnit5IntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver.plain; 2 | 3 | import com.jcraft.jsch.Session; 4 | import org.eclipse.jgit.api.Git; 5 | import org.eclipse.jgit.transport.SshTransport; 6 | import org.eclipse.jgit.transport.ssh.jsch.JschConfigSessionFactory; 7 | import org.eclipse.jgit.transport.ssh.jsch.OpenSshConfig; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.io.CleanupMode; 10 | import org.junit.jupiter.api.io.TempDir; 11 | import org.testcontainers.junit.jupiter.Container; 12 | import org.testcontainers.junit.jupiter.Testcontainers; 13 | import org.testcontainers.utility.DockerImageName; 14 | 15 | import java.io.File; 16 | import java.net.URI; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.assertj.core.api.Assertions.assertThatNoException; 20 | 21 | @Testcontainers 22 | public class GitServerContainerJUnit5IntegrationTest { 23 | 24 | @Container 25 | private GitServerContainer containerUnderTest = new GitServerContainer(DockerImageName.parse("rockstorm/git-server")); 26 | 27 | @TempDir(cleanup = CleanupMode.NEVER) 28 | private File tempDir; 29 | 30 | 31 | @Test 32 | void cloneGitRepo() { 33 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsSSH(); 34 | 35 | assertThatNoException().isThrownBy(() -> 36 | Git.cloneRepository() 37 | .setURI(gitRepoURI.toString()) 38 | .setDirectory(tempDir) 39 | .setBranch("main") 40 | .setTransportConfigCallback(transport -> { 41 | var sshTransport = (SshTransport) transport; 42 | sshTransport.setSshSessionFactory(new JschConfigSessionFactory() { 43 | @Override 44 | protected void configure(OpenSshConfig.Host hc, Session session) { 45 | session.setPassword(containerUnderTest.getGitPassword()); 46 | session.setConfig("StrictHostKeyChecking", "no"); 47 | } 48 | }); 49 | }) 50 | .call() 51 | ); 52 | assertThat(new File(tempDir, ".git")).exists(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/test/java/com/github/sparsick/testcontainers/gitserver/plain/GitServerContainerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.sparsick.testcontainers.gitserver.plain; 2 | 3 | import com.github.sparsick.testcontainers.gitserver.GitServerVersions; 4 | import com.jcraft.jsch.HostKey; 5 | import com.jcraft.jsch.JSch; 6 | import com.jcraft.jsch.JSchException; 7 | import com.jcraft.jsch.Session; 8 | import org.eclipse.jgit.api.Git; 9 | import org.eclipse.jgit.api.TransportConfigCallback; 10 | import org.eclipse.jgit.api.errors.GitAPIException; 11 | import org.eclipse.jgit.transport.SshTransport; 12 | import org.eclipse.jgit.transport.Transport; 13 | import org.eclipse.jgit.transport.ssh.jsch.JschConfigSessionFactory; 14 | import org.eclipse.jgit.transport.ssh.jsch.OpenSshConfig; 15 | import org.eclipse.jgit.util.FS; 16 | import org.jetbrains.annotations.NotNull; 17 | import org.junit.jupiter.api.Test; 18 | import org.junit.jupiter.api.io.CleanupMode; 19 | import org.junit.jupiter.api.io.TempDir; 20 | import org.junit.jupiter.params.ParameterizedTest; 21 | import org.junit.jupiter.params.provider.Arguments; 22 | import org.junit.jupiter.params.provider.EnumSource; 23 | import org.junit.jupiter.params.provider.MethodSource; 24 | import org.testcontainers.shaded.org.apache.commons.io.FileUtils; 25 | import org.testcontainers.utility.DockerImageName; 26 | 27 | import java.io.File; 28 | import java.io.IOException; 29 | import java.net.URI; 30 | import java.util.Arrays; 31 | import java.util.List; 32 | import java.util.Map; 33 | import java.util.stream.Stream; 34 | import java.util.stream.StreamSupport; 35 | 36 | import static org.assertj.core.api.Assertions.assertThatNoException; 37 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 38 | import static org.assertj.core.api.Assertions.assertThat; 39 | 40 | public class GitServerContainerTest { 41 | 42 | private static final DockerImageName LATEST_GIT_SERVER_VERSION = GitServerVersions.V2_47.getDockerImageName(); 43 | @TempDir(cleanup = CleanupMode.NEVER) 44 | private File tempDir; 45 | 46 | 47 | static Stream publicKeySupportedVersions () { 48 | return Arrays.stream(GitServerVersions.values()) 49 | .filter(v -> !(v == GitServerVersions.V2_36 || v == GitServerVersions.V2_34_2 || v == GitServerVersions.V2_34)) 50 | .map(Arguments::of); 51 | } 52 | 53 | @Test 54 | void validDockerImageName() { 55 | assertThatNoException().isThrownBy(() -> 56 | new GitServerContainer(LATEST_GIT_SERVER_VERSION) 57 | ); 58 | } 59 | 60 | @Test 61 | void invalidDockerImageName() { 62 | assertThatThrownBy(() -> 63 | new GitServerContainer(DockerImageName.parse("invalid/git-server")) 64 | ).isInstanceOf(IllegalStateException.class); 65 | } 66 | 67 | @Test 68 | void gitPasswordIsSet() { 69 | var containerUnderTest = new GitServerContainer(LATEST_GIT_SERVER_VERSION).withGitPassword("password"); 70 | 71 | Map envMap = containerUnderTest.getEnvMap(); 72 | 73 | assertThat(envMap).containsEntry("GIT_PASSWORD", "password"); 74 | } 75 | 76 | @Test 77 | void getGitPassword() { 78 | var containerUnderTest = new GitServerContainer(LATEST_GIT_SERVER_VERSION).withGitPassword("password"); 79 | 80 | String gitPassword = containerUnderTest.getGitPassword(); 81 | 82 | assertThat(gitPassword).isEqualTo("password"); 83 | } 84 | 85 | @Test 86 | void exposedPortIs22() { 87 | var containerUnderTest = new GitServerContainer(LATEST_GIT_SERVER_VERSION); 88 | 89 | List exposedPorts = containerUnderTest.getExposedPorts(); 90 | assertThat(exposedPorts).containsOnly(22); 91 | } 92 | 93 | @ParameterizedTest 94 | @EnumSource(GitServerVersions.class) 95 | void containerStarted(GitServerVersions gitServer) { 96 | var containerUnderTest = new GitServerContainer(gitServer.getDockerImageName()); 97 | 98 | containerUnderTest.start(); 99 | 100 | assertThat(containerUnderTest.isRunning()).isTrue(); 101 | } 102 | 103 | @Test 104 | void gitRepoURI() { 105 | var containerUnderTest = new GitServerContainer(LATEST_GIT_SERVER_VERSION).withGitRepo("testRepoName"); 106 | 107 | containerUnderTest.start(); 108 | 109 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsSSH(); 110 | var gitPort = containerUnderTest.getMappedPort(22); 111 | assertThat(gitRepoURI.toString()).isEqualTo("ssh://git@"+ containerUnderTest.getHost() + ":" + gitPort + "/srv/git/testRepoName.git"); 112 | } 113 | 114 | @Test 115 | void copyExistingGitRepo(@TempDir File sampleRepo) throws GitAPIException, IOException { 116 | initSampleRepo(sampleRepo, "src/test/resources/sampleRepo/testFile"); 117 | 118 | var containerUnderTest = new GitServerContainer(LATEST_GIT_SERVER_VERSION) 119 | .withCopyExistingGitRepoToContainer(sampleRepo.getAbsolutePath()); 120 | 121 | containerUnderTest.start(); 122 | 123 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsSSH(); 124 | 125 | assertThatNoException().isThrownBy(() -> 126 | Git.cloneRepository() 127 | .setURI(gitRepoURI.toString()) 128 | .setDirectory(tempDir) 129 | .setBranch("main") 130 | .setTransportConfigCallback(GitServerContainerTest::configureWithPasswordAndNoHostKeyChecking) 131 | .call() 132 | ); 133 | 134 | assertThat(new File(tempDir, "testFile")).exists(); 135 | } 136 | 137 | @Test 138 | void copyExistingGitRepoWithCustomRepoName(@TempDir File sampleRepo) throws IOException, GitAPIException { 139 | initSampleRepo(sampleRepo, "src/test/resources/sampleRepo/testFile"); 140 | 141 | var containerUnderTest = new GitServerContainer(LATEST_GIT_SERVER_VERSION) 142 | .withGitRepo("customRepoName") 143 | .withCopyExistingGitRepoToContainer(sampleRepo.getAbsolutePath()); 144 | containerUnderTest.start(); 145 | 146 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsSSH(); 147 | 148 | assertThatNoException().isThrownBy(() -> 149 | Git.cloneRepository() 150 | .setURI(gitRepoURI.toString()) 151 | .setDirectory(tempDir) 152 | .setBranch("main") 153 | .setTransportConfigCallback(GitServerContainerTest::configureWithPasswordAndNoHostKeyChecking) 154 | .call() 155 | ); 156 | 157 | assertThat(new File(tempDir, "testFile")).exists(); 158 | } 159 | 160 | @ParameterizedTest 161 | @EnumSource(GitServerVersions.class) 162 | void setupGitRepo(GitServerVersions gitServer) { 163 | var containerUnderTest = new GitServerContainer(gitServer.getDockerImageName()).withGitRepo("testRepoName"); 164 | 165 | containerUnderTest.start(); 166 | 167 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsSSH(); 168 | 169 | assertThatNoException().isThrownBy(() -> 170 | Git.cloneRepository() 171 | .setURI(gitRepoURI.toString()) 172 | .setDirectory(tempDir) 173 | .setBranch("main") 174 | .setTransportConfigCallback(GitServerContainerTest::configureWithPasswordAndNoHostKeyChecking) 175 | .call() 176 | ); 177 | } 178 | 179 | @ParameterizedTest 180 | @MethodSource("publicKeySupportedVersions") 181 | void pubKeyAuth(GitServerVersions gitServer) { 182 | var containerUnderTest = new GitServerContainer(gitServer.getDockerImageName()).withSshKeyAuth(); 183 | 184 | containerUnderTest.start(); 185 | 186 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsSSH(); 187 | 188 | assertThatNoException().isThrownBy(() -> 189 | Git.cloneRepository() 190 | .setURI(gitRepoURI.toString()) 191 | .setDirectory(tempDir) 192 | .setBranch("main") 193 | .setTransportConfigCallback(configureWithSshIdentityAndNoHostVerification(containerUnderTest.getSshClientIdentity())) 194 | .call() 195 | ); 196 | } 197 | 198 | 199 | 200 | @ParameterizedTest 201 | @MethodSource("publicKeySupportedVersions") 202 | void strictHostKeyVerifivation(GitServerVersions gitServer) { 203 | var containerUnderTest = new GitServerContainer(gitServer.getDockerImageName()).withSshKeyAuth(); 204 | 205 | containerUnderTest.start(); 206 | 207 | URI gitRepoURI = containerUnderTest.getGitRepoURIAsSSH(); 208 | 209 | assertThatNoException().isThrownBy(() -> 210 | Git.cloneRepository() 211 | .setURI(gitRepoURI.toString()) 212 | .setDirectory(tempDir) 213 | .setBranch("main") 214 | .setTransportConfigCallback(configureWithSshIdentityAndHostKey(containerUnderTest.getSshClientIdentity(), containerUnderTest.getHostKey())) 215 | .call() 216 | ); 217 | } 218 | 219 | @NotNull 220 | private TransportConfigCallback configureWithSshIdentityAndHostKey(SshIdentity sshIdentity, SshHostKey hostKey) { 221 | return transport -> { 222 | var sshTransport = (SshTransport) transport; 223 | sshTransport.setSshSessionFactory(new JschConfigSessionFactory() { 224 | 225 | @Override 226 | protected JSch createDefaultJSch(FS fs) throws JSchException { 227 | JSch defaultJSch = super.createDefaultJSch(fs); 228 | configureSshIdentity(defaultJSch, sshIdentity); 229 | configureHostKeyRepository(defaultJSch, hostKey); 230 | return defaultJSch; 231 | } 232 | }); 233 | }; 234 | } 235 | 236 | private void configureSshIdentity(JSch defaultJSch, SshIdentity sshIdentity) throws JSchException { 237 | byte[] privateKey = sshIdentity.getPrivateKey(); 238 | byte[] publicKey = sshIdentity.getPublicKey(); 239 | byte[] passphrase = sshIdentity.getPassphrase(); 240 | defaultJSch.addIdentity("git-server", privateKey, publicKey, passphrase); 241 | } 242 | 243 | private void configureHostKeyRepository(JSch defaultJSch, SshHostKey hostKey) throws JSchException { 244 | String host = hostKey.getHostname(); 245 | byte[] key = hostKey.getKey(); 246 | defaultJSch.getHostKeyRepository().add(new HostKey(host, key), null); 247 | } 248 | 249 | private void initSampleRepo(File sampleRepo, String repoContent) throws IOException, GitAPIException { 250 | FileUtils.copyFileToDirectory(new File(repoContent), sampleRepo); 251 | 252 | Git repo = Git.init().setDirectory(sampleRepo).setInitialBranch("main").call(); 253 | repo.add().addFilepattern("testFile").call(); 254 | repo.commit().setAuthor("Sandra Parsick", "sample@example.com").setMessage("init").call(); 255 | } 256 | 257 | private static void configureWithPasswordAndNoHostKeyChecking(Transport transport) { 258 | var sshTransport = (SshTransport) transport; 259 | sshTransport.setSshSessionFactory(new JschConfigSessionFactory() { 260 | @Override 261 | protected void configure(OpenSshConfig.Host hc, Session session) { 262 | session.setPassword("12345"); 263 | session.setConfig("StrictHostKeyChecking", "no"); 264 | } 265 | }); 266 | } 267 | 268 | @NotNull 269 | private TransportConfigCallback configureWithSshIdentityAndNoHostVerification(SshIdentity sshIdentity) { 270 | return transport -> { 271 | var sshTransport = (SshTransport) transport; 272 | sshTransport.setSshSessionFactory(new JschConfigSessionFactory() { 273 | 274 | @Override 275 | protected JSch createDefaultJSch(FS fs) throws JSchException { 276 | JSch defaultJSch = super.createDefaultJSch(fs); 277 | configureSshIdentity(defaultJSch, sshIdentity); 278 | return defaultJSch; 279 | } 280 | 281 | @Override 282 | protected void configure(OpenSshConfig.Host hc, Session session) { 283 | session.setConfig("StrictHostKeyChecking", "no"); 284 | } 285 | }); 286 | }; 287 | } 288 | } 289 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /testcontainers-gitserver/src/test/resources/sampleRepo/testFile: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sparsick/testcontainers-git/91e6c37dbfd70dc690fc6dc405e4209a09e3be08/testcontainers-gitserver/src/test/resources/sampleRepo/testFile --------------------------------------------------------------------------------