Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🎉 Source Gitlab: add OAuth2.0 authentication support #7506

Merged
merged 45 commits into from
Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
e1cea7e
added support of oauth2.0
bazarnov Oct 29, 2021
6934a2d
added OAuthFlow.java part
bazarnov Oct 31, 2021
ac6dd9e
bumped version of the Dockerfile
bazarnov Oct 31, 2021
37af9c0
corrected SAT
bazarnov Oct 31, 2021
5ecff85
added unit_test for Oauth java part, added integration-test for java …
bazarnov Oct 31, 2021
26612c4
added changelog
bazarnov Oct 31, 2021
98e03ec
fix java part test
bazarnov Oct 31, 2021
af49c77
updated after review
bazarnov Nov 1, 2021
bd67cec
Merge remote-tracking branch 'origin/master' into bazarnov/7480-gitla…
bazarnov Nov 1, 2021
ec26576
updated spec.json
bazarnov Nov 3, 2021
ee22f2b
Merge remote-tracking branch 'origin/master' into bazarnov/7480-gitla…
bazarnov Nov 4, 2021
ac15b82
updated after review
bazarnov Nov 5, 2021
8ede858
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 4, 2022
3ab2f00
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 4, 2022
a06e575
#7480 source gitlab: rm empty files
davydov-d Dec 4, 2022
2f31254
#7480 source gitlab: add single use refresh token authenticator
davydov-d Dec 6, 2022
6840a23
#7480 source gitlab: upd oauth implementation
davydov-d Dec 6, 2022
b119ccb
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 6, 2022
fc458a2
#7480 source gitlab: refactor auth
davydov-d Dec 7, 2022
5551985
Merge branch 'master' into bazarnov/7480-gitlab-oauth
alafanechere Dec 7, 2022
853c2b7
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 7, 2022
fad195e
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 8, 2022
8f17e3e
#7480 fix oauth: java
davydov-d Dec 8, 2022
da55d45
Merge branch 'bazarnov/7480-gitlab-oauth' of github.com:airbytehq/air…
davydov-d Dec 8, 2022
39bf3d3
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 9, 2022
c2cb032
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 9, 2022
229e3c0
#7480 source gitlab: review fixes
davydov-d Dec 9, 2022
52439df
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 11, 2022
266eb98
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 13, 2022
ae5b0bc
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 15, 2022
4be38bc
#7480 source gitlab: upd release stage
davydov-d Dec 15, 2022
880cbfa
#7480 source gitlab: fix unit tests
davydov-d Dec 15, 2022
4d1a6d1
#7480 source gitlab: update expected records
davydov-d Dec 15, 2022
1515ab2
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Dec 16, 2022
0b494f1
#7480 source gitlab: upd sats
davydov-d Dec 16, 2022
5000dfb
#7480 source gitlab: upd expected records
davydov-d Dec 16, 2022
67209d4
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Jan 10, 2023
41f06cb
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Jan 11, 2023
c3dfe00
#7480 source Gitlab: use SingleUseRefreshTokenOauth as is
davydov-d Jan 12, 2023
59b3637
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Jan 12, 2023
d13c5d1
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Jan 12, 2023
0da8ab6
#7480 sourcte gitlab: upd expected records
davydov-d Jan 18, 2023
7052aed
Merge branch 'bazarnov/7480-gitlab-oauth' of github.com:airbytehq/air…
davydov-d Jan 18, 2023
550f5ad
auto-bump connector version
octavia-squidington-iii Jan 18, 2023
9df8fa1
Merge branch 'master' into bazarnov/7480-gitlab-oauth
davydov-d Jan 18, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/publish-command.yml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ jobs:
FILE_SECURE_HTTPS_TEST_CREDS: ${{ secrets.FILE_SECURE_HTTPS_TEST_CREDS }}
FRESHDESK_TEST_CREDS: ${{ secrets.FRESHDESK_TEST_CREDS }}
GITLAB_INTEGRATION_TEST_CREDS: ${{ secrets.GITLAB_INTEGRATION_TEST_CREDS }}
GITLAB_INTEGRATION_TEST_OAUTH_CREDS: ${{ secrets.GITLAB_INTEGRATION_TEST_OAUTH_CREDS }}
GH_NATIVE_INTEGRATION_TEST_CREDS: ${{ secrets.GH_NATIVE_INTEGRATION_TEST_CREDS }}
GOOGLE_ADS_TEST_CREDS: ${{ secrets.GOOGLE_ADS_TEST_CREDS }}
GOOGLE_ANALYTICS_V4_TEST_CREDS: ${{ secrets.GOOGLE_ANALYTICS_V4_TEST_CREDS }}
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/test-command.yml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ jobs:
FILE_SECURE_HTTPS_TEST_CREDS: ${{ secrets.FILE_SECURE_HTTPS_TEST_CREDS }}
FRESHDESK_TEST_CREDS: ${{ secrets.FRESHDESK_TEST_CREDS }}
GITLAB_INTEGRATION_TEST_CREDS: ${{ secrets.GITLAB_INTEGRATION_TEST_CREDS }}
GITLAB_INTEGRATION_TEST_OAUTH_CREDS: ${{ secrets.GITLAB_INTEGRATION_TEST_OAUTH_CREDS }}
GH_NATIVE_INTEGRATION_TEST_CREDS: ${{ secrets.GH_NATIVE_INTEGRATION_TEST_CREDS }}
GOOGLE_ADS_TEST_CREDS: ${{ secrets.GOOGLE_ADS_TEST_CREDS }}
GOOGLE_ANALYTICS_V4_TEST_CREDS: ${{ secrets.GOOGLE_ANALYTICS_V4_TEST_CREDS }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
"sourceDefinitionId": "5e6175e5-68e1-4c17-bff9-56103bbb0d80",
"name": "Gitlab",
"dockerRepository": "airbyte/source-gitlab",
"dockerImageTag": "0.1.2",
"dockerImageTag": "0.1.3",
"documentationUrl": "https://docs.airbyte.io/integrations/sources/gitlab"
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@
- name: Gitlab
sourceDefinitionId: 5e6175e5-68e1-4c17-bff9-56103bbb0d80
dockerRepository: airbyte/source-gitlab
dockerImageTag: 0.1.2
dockerImageTag: 0.1.3
documentationUrl: https://docs.airbyte.io/integrations/sources/gitlab
sourceType: api
- name: Google Ads
Expand Down
2 changes: 1 addition & 1 deletion airbyte-integrations/connectors/source-gitlab/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ RUN pip install .

ENTRYPOINT ["python", "/airbyte/integration_code/main.py"]

LABEL io.airbyte.version=0.1.2
LABEL io.airbyte.version=0.1.3
LABEL io.airbyte.name=airbyte/source-gitlab
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@ tests:
connection:
- config_path: "secrets/config.json"
status: "succeed"
- config_path: "secrets/config_oauth.json"
status: "succeed"
- config_path: "integration_tests/invalid_config.json"
status: "failed"
discovery:
- config_path: "secrets/config.json"
- config_path: "secrets/config_oauth.json"
basic_read:
# test read with old config
- config_path: "secrets/config.json"
configured_catalog_path: "integration_tests/configured_catalog.json"
# test read with OAuth2.0
- config_path: "secrets/config_oauth.json"
configured_catalog_path: "integration_tests/configured_catalog.json"
# We cannot use these tests for testing Incremental, since for Gitlab the State is saved for each Project separately,
# and the Acceptance Tests at this stage do not support this functionality.
# Therefore, we hardcode the cursor_paths for our config.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
{
"api_url": "gitlab.com",
"private_token": "private_token-fake",
"groups": "new-group",
"projects": "new-ci-test",
"start_date": "2021-01-01T00:00:00Z"
}
"start_date": "2021-01-01T00:00:00Z",
"groups": "new-group-airbute",
"projects": "new-group-airbute/new-ci-test-project",
"credentials": {
"credentials": "access_token",
"access_token": "migrated_from_old_config"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#


from typing import Any, List, Mapping, Tuple
from typing import Any, Dict, List, Mapping, Tuple

from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources import AbstractSource
Expand Down Expand Up @@ -37,6 +37,21 @@
)


class GitlabAuthenticator(TokenAuthenticator):
def __init__(self, config: Dict):
self.config = config

def get_auth(self) -> TokenAuthenticator:
private_token = self.config.get("private_token")
oauth_token = self.config.get("credentials")
if private_token:
# support of old config
return TokenAuthenticator(token=private_token)
if oauth_token:
# support of new config with oauth2.0
return TokenAuthenticator(token=oauth_token["access_token"])


class SourceGitlab(AbstractSource):
def _generate_main_streams(self, config: Mapping[str, Any]) -> Tuple[GitlabStream, GitlabStream]:
gids = list(filter(None, config["groups"].split(" ")))
Expand All @@ -45,7 +60,7 @@ def _generate_main_streams(self, config: Mapping[str, Any]) -> Tuple[GitlabStrea
if not pids and not gids:
raise Exception("Either groups or projects need to be provided for connect to Gitlab API")

auth = TokenAuthenticator(token=config["private_token"])
auth = GitlabAuthenticator(config).get_auth()
auth_params = dict(authenticator=auth, api_url=config["api_url"])
groups = Groups(group_ids=gids, **auth_params)
if gids:
Expand All @@ -65,7 +80,7 @@ def check_connection(self, logger, config) -> Tuple[bool, any]:
return False, f"Unable to connect to Gitlab API with the provided credentials - {repr(error)}"

def streams(self, config: Mapping[str, Any]) -> List[Stream]:
auth = TokenAuthenticator(token=config["private_token"])
auth = GitlabAuthenticator(config).get_auth()
auth_params = dict(authenticator=auth, api_url=config["api_url"])

groups, projects = self._generate_main_streams(config)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,100 @@
"documentationUrl": "https://docs.airbyte.io/integrations/sources/gitlab",
"connectionSpecification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Source Gitlab Singer Spec",
"title": "Source Gitlab Spec",
"type": "object",
"required": ["api_url", "private_token", "start_date"],
"additionalProperties": false,
"required": ["api_url", "start_date"],
"additionalProperties": true,
"properties": {
"api_url": {
"type": "string",
"title": "API URL",
"examples": ["gitlab.com"],
"default": "gitlab.com",
"description": "Please enter your basic URL from Gitlab instance"
},
"private_token": {
"type": "string",
"description": "Log into your Gitlab account and then generate a personal Access Token.",
"airbyte_secret": true
},
"groups": {
"type": "string",
"title": "Groups",
"examples": ["airbyte.io"],
"description": "Space-delimited list of groups. e.g. airbyte.io"
},
"projects": {
"type": "string",
"title": "Projects",
"examples": ["airbyte.io/documentation"],
"description": "Space-delimited list of projects. e.g. airbyte.io/documentation meltano/tap-gitlab"
},
"start_date": {
"type": "string",
"title": "Start Date",
"description": "The date from which you'd like to replicate data for Gitlab API, in the format YYYY-MM-DDT00:00:00Z. All data generated after this date will be replicated.",
"examples": ["2021-03-01T00:00:00Z"],
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$"
},
"credentials": {
"title": "Authorization Method",
"type": "object",
"oneOf": [
{
"type": "object",
"title": "OAuth2.0",
"required": ["client_id", "client_secret", "access_token"],
"properties": {
"credentials": {
"type": "string",
"const": "oauth2.0"
},
"client_id": {
"type": "string",
"description": "The API ID of the Gitlab developer application.",
"airbyte_secret": true
},
"client_secret": {
"type": "string",
"description": "The API Secret the Gitlab developer application.",
"airbyte_secret": true
},
"access_token": {
"type": "string",
"description": "Access Token for making authenticated requests.",
"airbyte_secret": true
},
"refresh_token": {
"type": "string",
"description": "The key to refresh the expired access_token.",
"airbyte_secret": true
}
}
},
{
"title": "Private Token",
"type": "object",
"required": ["access_token"],
"properties": {
"credentials": {
"type": "string",
"const": "access_token"
},
"access_token": {
"type": "string",
"title": "Private Token",
"description": "Log into your Gitlab account and then generate a personal Access Token.",
"airbyte_secret": true
}
}
}
]
}
}
},
"authSpecification": {
"auth_type": "oauth2.0",
"oauth2Specification": {
"rootObject": ["credentials", "0"],
"oauthFlowInitParameters": [["client_id"], ["client_secret"]],
"oauthFlowOutputParameters": [["access_token"], ["refresh_token"]]
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import io.airbyte.config.persistence.ConfigRepository;
import io.airbyte.oauth.flows.AsanaOAuthFlow;
import io.airbyte.oauth.flows.GithubOAuthFlow;
import io.airbyte.oauth.flows.GitlabOAuthFlow;
import io.airbyte.oauth.flows.SalesforceOAuthFlow;
import io.airbyte.oauth.flows.SurveymonkeyOAuthFlow;
import io.airbyte.oauth.flows.TrelloOAuthFlow;
Expand Down Expand Up @@ -39,6 +40,7 @@ public OAuthImplementationFactory(final ConfigRepository configRepository) {
.put("airbyte/source-salesforce", new SalesforceOAuthFlow(configRepository))
.put("airbyte/source-surveymonkey", new SurveymonkeyOAuthFlow(configRepository))
.put("airbyte/source-trello", new TrelloOAuthFlow(configRepository))
.put("airbyte/source-gitlab", new GitlabOAuthFlow(configRepository))
.build();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* Copyright (c) 2021 Airbyte, Inc., all rights reserved.
*/

package io.airbyte.oauth.flows;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import io.airbyte.config.persistence.ConfigRepository;
import io.airbyte.oauth.BaseOAuthFlow;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.function.Supplier;
import org.apache.http.client.utils.URIBuilder;

/**
* Following docs from https://docs.gitlab.com/ee/api/oauth2.html#authorization-code-flow
*/
public class GitlabOAuthFlow extends BaseOAuthFlow {

private static final String ACCESS_TOKEN_URL = "https://gitlab.com/oauth/token";

public GitlabOAuthFlow(ConfigRepository configRepository) {
super(configRepository);
}

@VisibleForTesting
GitlabOAuthFlow(ConfigRepository configRepository, HttpClient httpClient, Supplier<String> stateSupplier) {
super(configRepository, httpClient, stateSupplier);
}

@Override
protected String formatConsentUrl(UUID definitionId, String clientId, String redirectUrl) throws IOException {
final URIBuilder builder = new URIBuilder()
.setScheme("https")
.setHost("gitlab.com")
.setPath("oauth/authorize")
.addParameter("client_id", clientId)
.addParameter("redirect_uri", redirectUrl)
.addParameter("state", getState())
.addParameter("response_type", "code")
.addParameter("scope", "read_api");
try {
return builder.build().toString();
} catch (URISyntaxException e) {
throw new IOException("Failed to format Consent URL for OAuth flow", e);
}
}

@Override
protected String extractCodeParameter(Map<String, Object> queryParams) throws IOException {
if (queryParams.containsKey("code")) {
return (String) queryParams.get("code");
} else {
throw new IOException("Undefined 'code' from consent redirected url.");
}
}

@Override
protected String getClientIdUnsafe(JsonNode config) {
// the config object containing client ID is nested inside the "credentials" object
Preconditions.checkArgument(config.hasNonNull("credentials"));
return super.getClientIdUnsafe(config.get("credentials"));
}

@Override
protected String getClientSecretUnsafe(JsonNode config) {
// the config object containing client SECRET is nested inside the "credentials" object
Preconditions.checkArgument(config.hasNonNull("credentials"));
return super.getClientSecretUnsafe(config.get("credentials"));
}

@Override
protected String getAccessTokenUrl() {
return ACCESS_TOKEN_URL;
}

@Override
protected Map<String, String> getAccessTokenQueryParameters(String clientId, String clientSecret, String authCode, String redirectUrl) {
return ImmutableMap.<String, String>builder()
.put("client_id", clientId)
.put("client_secret", clientSecret)
.put("code", authCode)
.put("grant_type", "authorization_code")
.put("redirect_uri", redirectUrl)
.build();
}

@Override
protected Map<String, Object> extractRefreshToken(final JsonNode data, String accessTokenUrl) throws IOException {
final Map<String, Object> result = new HashMap<>();
// check for refresh_token after successful authentication
if (data.has("refresh_token")) {
result.put("refresh_token", data.get("refresh_token").asText());
} else {
throw new IOException(String.format("Missing 'refresh_token' in query params from %s", accessTokenUrl));
}
// check for access_token after successful authentication
if (data.has("access_token")) {
result.put("access_token", data.get("access_token").asText());
} else {
throw new IOException(String.format("Missing 'access_token' in query params from %s", accessTokenUrl));
}
// return result as mapping
return Map.of("credentials", result);
}

}
Loading