-
Notifications
You must be signed in to change notification settings - Fork 6
Undo the Codebuild Pull Request Regex hack #107
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
Open
unlox775-code-dot-org
wants to merge
3
commits into
main
Choose a base branch
from
dave2/new-pr-cicd-authorize-event-flow
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import os | ||
import json | ||
import boto3 | ||
from urllib import request | ||
|
||
# Lambda handler for PR authorizer | ||
# Fetches GitHub token from Secrets Manager, checks PR author permission, | ||
# and starts CodeBuild if writer/maintainer/admin. | ||
|
||
def handler(event, context): | ||
# Load env vars | ||
secret_arn = os.environ['GITHUB_TOKEN_SECRET_ARN'] | ||
owner = os.environ['GitHubOwner'] | ||
repo = os.environ['GitHubRepo'] | ||
branch = os.environ['GitHubBranch'] | ||
project = os.environ['CODEBUILD_PROJECT'] | ||
|
||
# Fetch GitHub PAT from Secrets Manager | ||
sm = boto3.client('secretsmanager') | ||
secret = sm.get_secret_value(SecretId=secret_arn) | ||
token = json.loads(secret['SecretString'])['token'] | ||
|
||
# Extract PR event details | ||
detail = event.get('detail', {}) | ||
pr = detail.get('pull_request', {}) | ||
|
||
# Only handle events on the configured branch | ||
if pr.get('base', {}).get('ref') != branch: | ||
return | ||
|
||
login = pr.get('user', {}).get('login') | ||
if not login: | ||
return | ||
|
||
# Build GitHub API URL for collaborator permission | ||
url = f"https://api.github.com/repos/{owner}/{repo}/collaborators/{login}/permission" | ||
req = request.Request( | ||
url, | ||
headers={ | ||
'Authorization': f'token {token}', | ||
'Accept': 'application/vnd.github.v3+json' | ||
} | ||
) | ||
# Call GitHub | ||
with request.urlopen(req) as resp: | ||
data = json.loads(resp.read().decode()) | ||
|
||
# Only allow write/maintain/admin | ||
if data.get('permission') in ['write', 'maintain', 'admin']: | ||
cb = boto3.client('codebuild') | ||
cb.start_build(projectName=project) |
106 changes: 106 additions & 0 deletions
106
cicd/2-cicd/authorizer/tests/test_authorizer_integration.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
import os | ||
import json | ||
import boto3 | ||
import pytest | ||
from moto import mock_secretsmanager, mock_codebuild | ||
from authorizer.authorizer import handler | ||
from urllib.error import URLError | ||
|
||
# Simulated HTTP response for GitHub API | ||
class DummyResponse: | ||
def __init__(self, data): | ||
self._data = data | ||
def read(self): | ||
return json.dumps(self._data).encode('utf-8') | ||
def __enter__(self): | ||
return self | ||
def __exit__(self, exc_type, exc_val, exc_tb): | ||
pass | ||
|
||
@pytest.fixture(autouse=True) | ||
def set_env_vars(monkeypatch): | ||
monkeypatch.setenv('GITHUB_TOKEN_SECRET_ARN', 'arn:aws:secretsmanager:us-east-1:123456:secret:githtoken') | ||
monkeypatch.setenv('GitHubOwner', 'code-dot-org') | ||
monkeypatch.setenv('GitHubRepo', 'aiproxy') | ||
monkeypatch.setenv('GitHubBranch', 'main') | ||
monkeypatch.setenv('CODEBUILD_PROJECT', 'pr-build-project') | ||
|
||
@mock_secretsmanager | ||
@mock_codebuild | ||
def test_integration_starts_codebuild(monkeypatch): | ||
# Setup SecretsManager | ||
sm = boto3.client('secretsmanager', region_name='us-east-1') | ||
sm.create_secret(Name='githtoken', SecretString=json.dumps({'token':'fakepat'})) | ||
|
||
# Create CodeBuild project | ||
cb = boto3.client('codebuild', region_name='us-east-1') | ||
cb.create_project( | ||
name='pr-build-project', | ||
source={'type':'CODEPIPELINE'}, | ||
artifacts={'type':'NO_ARTIFACTS'}, | ||
environment={'type':'LINUX_CONTAINER','computeType':'BUILD_GENERAL1_SMALL','image':'aws/codebuild/amazonlinux2-x86_64-standard:5.0'} | ||
) | ||
|
||
# Stub urlopen to return write permission | ||
def fake_urlopen(req): | ||
return DummyResponse({'permission':'maintain'}) | ||
monkeypatch.setattr('authorizer.authorizer.request.urlopen', fake_urlopen) | ||
|
||
# Simulate event | ||
event = { 'detail': { 'pull_request': { 'base': { 'ref': 'main' }, 'user': { 'login': 'octocat' } } } } | ||
handler(event, None) | ||
|
||
# List builds to confirm start | ||
builds = cb.list_builds_for_project(projectName='pr-build-project')['ids'] | ||
assert len(builds) == 1 | ||
|
||
@mock_secretsmanager | ||
@mock_codebuild | ||
def test_integration_no_start_on_bad_permission(monkeypatch): | ||
# Setup SecretsManager | ||
sm = boto3.client('secretsmanager', region_name='us-east-1') | ||
sm.create_secret(Name='githtoken', SecretString=json.dumps({'token':'fakepat'})) | ||
|
||
# Create CodeBuild project | ||
cb = boto3.client('codebuild', region_name='us-east-1') | ||
cb.create_project( | ||
name='pr-build-project', | ||
source={'type':'CODEPIPELINE'}, | ||
artifacts={'type':'NO_ARTIFACTS'}, | ||
environment={'type':'LINUX_CONTAINER','computeType':'BUILD_GENERAL1_SMALL','image':'aws/codebuild/amazonlinux2-x86_64-standard:5.0'} | ||
) | ||
|
||
# Stub urlopen to return read permission | ||
def fake_urlopen(req): | ||
return DummyResponse({'permission':'read'}) | ||
monkeypatch.setattr('authorizer.authorizer.request.urlopen', fake_urlopen) | ||
|
||
event = { 'detail': { 'pull_request': { 'base': { 'ref': 'main' }, 'user': { 'login': 'octocat' } } } } | ||
handler(event, None) | ||
|
||
builds = cb.list_builds_for_project(projectName='pr-build-project')['ids'] | ||
assert len(builds) == 0 | ||
|
||
@mock_secretsmanager | ||
@mock_codebuild | ||
def test_integration_no_start_on_wrong_branch(monkeypatch): | ||
# Setup SecretsManager and CodeBuild | ||
sm = boto3.client('secretsmanager', region_name='us-east-1') | ||
sm.create_secret(Name='githtoken', SecretString=json.dumps({'token':'fakepat'})) | ||
cb = boto3.client('codebuild', region_name='us-east-1') | ||
cb.create_project( | ||
name='pr-build-project', | ||
source={'type':'CODEPIPELINE'}, | ||
artifacts={'type':'NO_ARTIFACTS'}, | ||
environment={'type':'LINUX_CONTAINER','computeType':'BUILD_GENERAL1_SMALL','image':'aws/codebuild/amazonlinux2-x86_64-standard:5.0'} | ||
) | ||
|
||
# Stub urlopen | ||
monkeypatch.setattr('authorizer.authorizer.request.urlopen', lambda req: DummyResponse({'permission':'admin'})) | ||
|
||
# Wrong branch | ||
event = { 'detail': { 'pull_request': { 'base': { 'ref': 'feature' }, 'user': { 'login': 'octocat' } } } } | ||
handler(event, None) | ||
|
||
builds = cb.list_builds_for_project(projectName='pr-build-project')['ids'] | ||
assert len(builds) == 0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
import os | ||
import json | ||
import pytest | ||
from unittest.mock import patch, MagicMock | ||
from authorizer.authorizer import handler | ||
|
||
# Helper to build a minimal PR event | ||
def make_event(login, ref="main"): | ||
return { | ||
"detail": { | ||
"pull_request": { | ||
"base": {"ref": ref}, | ||
"user": {"login": login} | ||
} | ||
} | ||
} | ||
|
||
@pytest.fixture(autouse=True) | ||
def set_env_vars(monkeypatch): | ||
monkeypatch.setenv('GITHUB_TOKEN_SECRET_ARN', 'arn:aws:secretsmanager:us-east-1:123:secret:test') | ||
monkeypatch.setenv('GitHubOwner', 'code-dot-org') | ||
monkeypatch.setenv('GitHubRepo', 'aiproxy') | ||
monkeypatch.setenv('GitHubBranch', 'main') | ||
monkeypatch.setenv('CODEBUILD_PROJECT', 'pr-build-project') | ||
|
||
@patch('authorizer.authorizer.boto3') | ||
@patch('authorizer.authorizer.request.urlopen') | ||
def test_handler_auth_start_build(mock_urlopen, mock_boto3): | ||
# Mock SecretsManager get_secret_value | ||
sm = MagicMock() | ||
sm.get_secret_value.return_value = {'SecretString': json.dumps({'token': 'fake'})} | ||
# Mock CodeBuild client | ||
cb = MagicMock() | ||
# Configure boto3.client side effects | ||
def client_factory(name, **kwargs): | ||
if name == 'secretsmanager': | ||
return sm | ||
if name == 'codebuild': | ||
return cb | ||
raise ValueError(f"Unexpected client {name}") | ||
mock_boto3.client.side_effect = client_factory | ||
|
||
# Mock GitHub API response: permission = write | ||
response = MagicMock() | ||
response.read.return_value = json.dumps({'permission': 'write'}).encode() | ||
mock_urlopen.return_value.__enter__.return_value = response | ||
|
||
# Invoke handler | ||
evt = make_event(login='octocat', ref='main') | ||
handler(evt, None) | ||
|
||
# Assert start_build was called | ||
cb.start_build.assert_called_once_with(projectName='pr-build-project') | ||
|
||
@patch('authorizer.authorizer.boto3') | ||
@patch('authorizer.authorizer.request.urlopen') | ||
def test_handler_no_build_on_wrong_branch(mock_urlopen, mock_boto3): | ||
# Wrong branch: should not call build | ||
cb = MagicMock() | ||
sm = MagicMock() | ||
mock_boto3.client.side_effect = lambda name, **kwargs: sm if name=='secretsmanager' else cb | ||
|
||
evt = make_event(login='octocat', ref='feature') | ||
handler(evt, None) | ||
cb.start_build.assert_not_called() | ||
|
||
@patch('authorizer.authorizer.boto3') | ||
@patch('authorizer.authorizer.request.urlopen') | ||
def test_handler_no_build_on_insufficient_permission(mock_urlopen, mock_boto3): | ||
# Insufficient GitHub permission: read only | ||
sm = MagicMock() | ||
sm.get_secret_value.return_value = {'SecretString': json.dumps({'token': 'fake'})} | ||
cb = MagicMock() | ||
mock_boto3.client.side_effect = lambda name, **kwargs: sm if name=='secretsmanager' else cb | ||
|
||
# Mock GitHub API permission read | ||
resp = MagicMock() | ||
resp.read.return_value = json.dumps({'permission': 'read'}).encode() | ||
mock_urlopen.return_value.__enter__.return_value = resp | ||
|
||
evt = make_event(login='octocat', ref='main') | ||
handler(evt, None) | ||
cb.start_build.assert_not_called() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this a duplicate of "cicd/2-cicd/authorizer.py"? Should we be loading that file instead of inlining it here?