> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Codebuild project source repo url remediation

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Here’s how to remediate this using the AWS Console by removing credentials from the Bitbucket URL and using proper authentication.

        ***

        ## 1. Identify the misconfigured CodeBuild project

        1. Sign in to the **AWS Management Console**.
        2. Go to **CodeBuild**:\
           `Services` → search for **CodeBuild** → open **CodeBuild**.
        3. In the left menu, select **Build projects**.
        4. Click the **project name** that is using Bitbucket and has a URL like:\
           `https://username:password@bitbucket.org/workspace/repo.git`.

        ***

        ## 2. Edit the project source configuration

        1. In the project details page, click **Edit** (top right).
        2. In the **Source** section, verify:
           * **Source provider**: should be **Bitbucket** (not “Git” with a raw HTTPS URL).
        3. If **Source provider** is currently set to **Git**:
           * Change **Source provider** to **Bitbucket**.
           * In the **Repository** field, specify the repo using a **clean URL** (no credentials), e.g.:\
             `https://bitbucket.org/workspace/repo.git`\
             or, if it’s an option in the UI, just select the repository from the Bitbucket connection (recommended).

        ***

        ## 3. Connect CodeBuild to Bitbucket without embedding credentials in URL

        ### A. If Bitbucket OAuth / integration is available

        1. In the **Source** section (with provider = Bitbucket), look for an option like:
           * **Connect to Bitbucket**, **Connect using OAuth**, or **Connect to source provider**.
        2. Click that and follow the prompts:
           * You will be redirected to Bitbucket to authorize AWS CodeBuild.
           * Approve the permissions so AWS can clone the repo.
        3. Back in CodeBuild, select the Bitbucket repository from the list (if presented).
        4. Ensure the repository URL now shows **without** credentials.

        ### B. If you must use HTTPS with an app password/personal token

        Do **not** put the token in the URL. Use environment variables + Secrets Manager or SSM.

        1. In Bitbucket:
           * Create an **App Password** or personal access token with minimally required scopes.
        2. In AWS:
           * Go to **AWS Secrets Manager**.
           * Store the username and app password in a secret (e.g., `bitbucket/codebuild/creds`).
        3. Back in **CodeBuild project → Edit**:
           * Scroll to **Environment** section.
           * Add environment variables like:
             * `BITBUCKET_USERNAME` = (value from Secrets Manager, **as a secrets-managed variable**)
             * `BITBUCKET_APP_PASSWORD` = (also from Secrets Manager)
           * Use the “**Secrets Manager**” option for value type, and select your secret/JSON key.
        4. In your **buildspec.yml**, replace any direct `git clone https://user:pass@...` with something like:
           ```bash theme={null}
           git clone https://$BITBUCKET_USERNAME:$BITBUCKET_APP_PASSWORD@bitbucket.org/workspace/repo.git
           ```
           This way, the URL never contains literal credentials in the CodeBuild configuration.

        ***

        ## 4. Save the project

        1. After updating the source and/or environment configuration, scroll down and click **Update build project** (or **Save**).

        ***

        ## 5. Remove leaked credentials from Bitbucket URL and rotate them

        1. In Bitbucket, **revoke or delete**:
           * Any username/password or app password that was embedded in the URL.
        2. If that password is used elsewhere, **change/rotate** it.
        3. If the credential was committed into any repository:
           * Remove it from the code (commit a change that removes it).
           * Consider history rewriting and rotating the credential, depending on your security policy.

        ***

        ## 6. Verify

        1. In CodeBuild, start a **new build** of the edited project.
        2. Confirm:
           * The build successfully pulls from Bitbucket.
           * No credentials appear in the repository URL shown in the project settings.
           * Logs don’t print credentials (check any echo/print commands).

        This fully removes sign-in credentials from the Bitbucket repository URL used by CodeBuild while maintaining secure access.
      </Accordion>

      <Accordion title="Using CLI">
        Here’s how to remediate “Sign-in Credentials Should Not Be In Bitbucket Source Repository URL” for an AWS CodeBuild project using the AWS CLI.

        ### 0. Understand the problem

        Right now your CodeBuild project’s `source.location` likely looks like this:

        ```text theme={null}
        https://username:password@bitbucket.org/org/repo.git
        ```

        You must:

        1. Remove `username:password@` from the URL.
        2. Use a proper auth mechanism (CodeStar Connection or OAuth/source credentials).
        3. Rotate/revoke the exposed credentials.

        ***

        ## 1. Rotate/revoke exposed Bitbucket credentials

        Do this in Bitbucket first:

        * Revoke the username/password (or app password) that was embedded in the URL.
        * Create a new, properly scoped credential if still needed (e.g., app password or OAuth token).

        ***

        ## 2. Get current CodeBuild project config

        ```bash theme={null}
        PROJECT_NAME="your-codebuild-project-name"

        aws codebuild batch-get-projects \
          --names "$PROJECT_NAME" \
          --query 'projects[0]' \
          --output json > current-project.json
        ```

        You’ll edit a copy rather than hand‑construct the full JSON.

        ***

        ## 3. Decide on proper auth mechanism

        ### Option A (recommended): Use CodeStar Connections

        1. In the AWS Console:\
           Developer Tools → Connections → Create connection → Bitbucket\
           Get the connection ARN, e.g.:

           ```text theme={null}
           arn:aws:codestar-connections:us-east-1:123456789012:connection/abcdef12-3456-7890-abcd-ef1234567890
           ```

        2. In CodeBuild, you then use `GIT` as source and specify `sourceIdentifier` as this connection. However, with CLI, this is done via `source` configuration using `sourceType=BITBUCKET` + `auth` OR through “Git repository in CodeStar Connections” (varies by region/console). The more universal approach is to use **GIT + CodeStar connection** via environment variable for `CODEBUILD_SOURCE_REPO_URL` and connection in CodePipeline; but for *direct* CodeBuild project, you can do:

           Use `BITBUCKET` with `auth.type=OAUTH` or use CodePipeline + CodeStar connection as the frontend. If you already have a working CodePipeline+Connection, you can just change CodeBuild project to `CODEPIPELINE` source and let the pipeline handle Bitbucket auth.

        Given the complexity and current support, most people:

        * Use **CodePipeline + CodeStar Connections**, with CodeBuild’s `source.type=CODEPIPELINE`.

        ### Option B: Use CodeBuild source credentials (OAUTH / personal token)

        Create a Bitbucket app password or token and register it with CodeBuild:

        ```bash theme={null}
        aws codebuild import-source-credentials \
          --server-type BITBUCKET \
          --auth-type PERSONAL_ACCESS_TOKEN \
          --token "YOUR_BITBUCKET_APP_PASSWORD_OR_TOKEN"
        ```

        This returns a `arn:aws:codebuild:...:sourceCredential/...`.

        You then configure your CodeBuild project to use:

        * `source.type = BITBUCKET`
        * `source.location = https://bitbucket.org/org/repo.git` (no credentials)
        * `source.auth.type = PERSONAL_ACCESS_TOKEN` (or `OAUTH`)
        * `source.auth.resource = <source-credential-ARN>`

        ***

        ## 4. Edit the project JSON (remove credentials from URL and add auth)

        Open `current-project.json` and locate the `"source"` block. You’ll see something like:

        ```json theme={null}
        "source": {
          "type": "BITBUCKET",
          "location": "https://username:password@bitbucket.org/org/repo.git",
          "gitCloneDepth": 1,
          ...
        }
        ```

        Replace it with (example using imported source credentials):

        ```json theme={null}
        "source": {
          "type": "BITBUCKET",
          "location": "https://bitbucket.org/org/repo.git",
          "auth": {
            "type": "PERSONAL_ACCESS_TOKEN",
            "resource": "arn:aws:codebuild:us-east-1:123456789012:sourceCredential/abcd1234-ef56-..."
          },
          "gitCloneDepth": 1,
          "insecureSsl": false
        }
        ```

        Keep all other top-level fields (environment, artifacts, etc.) exactly as they were.

        Save this as `updated-project.json`.

        > Note: If you prefer OAuth, use `"type": "OAUTH"` in `auth` and set `"resource"` to the appropriate credential ARN returned by `import-source-credentials`.

        ***

        ## 5. Update the CodeBuild project via CLI

        Now run:

        ```bash theme={null}
        aws codebuild update-project \
          --name "$PROJECT_NAME" \
          --source "file://<(jq '.source' updated-project.json)" \
          >/dev/null
        ```

        If your shell doesn’t support process substitution easily, you can pull `source` into its own file:

        ```bash theme={null}
        jq '.source' updated-project.json > source-only.json

        aws codebuild update-project \
          --name "$PROJECT_NAME" \
          --source file://source-only.json
        ```

        `update-project` only needs the `--name` and the part(s) you’re modifying; here it’s just the `source`.

        ***

        ## 6. Confirm the URL no longer contains credentials

        ```bash theme={null}
        aws codebuild batch-get-projects \
          --names "$PROJECT_NAME" \
          --query 'projects[0].source' \
          --output json
        ```

        Check:

        * `location` is `https://bitbucket.org/org/repo.git` (no `username:password@`).
        * `auth` is present and correctly set.

        ***

        ## 7. (Optional) Clean up any stored plaintext credentials in configs

        * Check buildspecs and environment variables for embedded Bitbucket usernames/passwords.
        * Rotate any other secrets that may have been exposed the same way.

        If you clarify whether you’re using CodePipeline + CodeBuild or standalone CodeBuild, I can give an exact CLI snippet tailored to your setup (CodeStar Connection vs source credentials).
      </Accordion>

      <Accordion title="Using Python">
        You need to (1) stop using credential‑embedded Bitbucket URLs in CodeBuild, (2) rotate/revoke the exposed credentials, and (3) update the project to use a safe auth method. Below is how to do that with Python (boto3).

        ***

        ## 1. What’s wrong now

        Your CodeBuild project likely has a source like:

        ```json theme={null}
        "source": {
          "type": "BITBUCKET",
          "location": "https://username:password@bitbucket.org/workspace/repo.git",
          ...
        }
        ```

        Credentials in `location` is the misconfiguration.

        ***

        ## 2. Immediate security actions

        1. **Rotate/revoke the exposed Bitbucket credentials**
           * Log in to Bitbucket.
           * Go to **Personal settings → App passwords** (or wherever those credentials were created).
           * **Revoke the exposed password/token**.
           * Create a **new app password / token** with minimum required scopes.

        2. **Search for other leaks**
           * Search your CodeBuild buildspecs, environment variables, and parameter store for the same username/password or token and remove/rotate them too.

        ***

        ## 3. Fix the CodeBuild project configuration

        ### Option A (recommended when possible): Use CodeStar Connections via CodePipeline

        If you can use CodePipeline, the most secure way is:

        1. Create a **CodeStar Connection** to Bitbucket in the AWS Console (Developer Tools → Connections).
        2. Use that connection in **CodePipeline** as the source.
        3. Have CodePipeline trigger your CodeBuild project; then your CodeBuild `source` type is `CODEPIPELINE` (no URL, no credentials).

        This moves Bitbucket auth out of CodeBuild entirely.

        ***

        ### Option B: Use a clean URL and managed auth for BITBUCKET source

        If you must keep CodeBuild directly pulling from Bitbucket:

        * The **`location` must not contain credentials**.
        * Configure authentication using `source.auth` and store any tokens/credentials in a secure store (e.g., Secrets Manager), not in the URL.

        A safe `location` value:

        ```text theme={null}
        https://bitbucket.org/workspace/repo.git
        ```

        The exact way Bitbucket auth is wired for CodeBuild is usually done in the console via OAuth; programmatically you typically still ensure that `location` is clean and that no credentials are in environment variables or buildspecs.

        ***

        ## 4. Python (boto3) remediation script

        Below is an example Python script that:

        * Finds CodeBuild projects whose source URL contains `@` with credentials.
        * Rewrites `location` to remove the credential portion.
        * Leaves all other settings intact.
        * (You still must handle token/OAuth setup separately as above.)

        ```python theme={null}
        import re
        import boto3

        codebuild = boto3.client('codebuild')

        def strip_credentials_from_url(url: str) -> str:
            """
            Remove any 'user:pass@' or 'token@' portion from a Git URL.
            Example:
              https://user:pass@bitbucket.org/work/repo.git
              -> https://bitbucket.org/work/repo.git
            """
            # matches scheme://anything@rest
            return re.sub(r'^(https?://)[^/@]+@', r'\1', url)

        def remediate_project(project_name: str):
            proj = codebuild.batch_get_projects(names=[project_name])['projects'][0]
            src = proj['source']

            old_location = src.get('location', '')
            if '@' not in old_location:
                print(f"[SKIP] {project_name}: no credentials in location")
                return

            new_location = strip_credentials_from_url(old_location)
            if new_location == old_location:
                print(f"[SKIP] {project_name}: could not simplify URL safely")
                return

            src['location'] = new_location

            # Build the update payload. Use existing values for everything else.
            update_params = {
                'name': proj['name'],
                'source': src,
                'environment': proj['environment'],
                'serviceRole': proj['serviceRole'],
                'artifacts': proj['artifacts'],
            }

            # Optional fields if present
            for key in [
                'description', 'timeoutInMinutes', 'queuedTimeoutInMinutes',
                'encryptionKey', 'tags', 'logsConfig', 'vpcConfig',
                'badgeEnabled', 'buildTimeoutInMinutes', 'secondarySources',
                'secondaryArtifacts', 'fileSystemLocations', 'sourceVersion',
                'concurrentBuildLimit', 'projectVisibility'
            ]:
                if key in proj:
                    update_params[key] = proj[key]

            codebuild.update_project(**update_params)
            print(f"[FIXED] {project_name}: {old_location} -> {new_location}")

        def main():
            # 1. List all projects
            paginator = codebuild.get_paginator('list_projects')
            for page in paginator.paginate():
                for name in page['projects']:
                    try:
                        remediate_project(name)
                    except Exception as e:
                        print(f"[ERROR] {name}: {e}")

        if __name__ == "__main__":
            main()
        ```

        **What this script does:**

        * Ensures `source.location` no longer contains `username:password@` or `token@`.
        * Does **not** put any new secret into the URL.
        * Leaves room for you to configure proper Bitbucket auth via:
          * CodeStar Connections + CodePipeline (preferred), or
          * Console-based OAuth setup for BITBUCKET source and/or use of secrets (never hard-coded).

        ***

        ## 5. Final checklist

        1. Revoke old Bitbucket credentials and create new ones.
        2. Remove credentials from:
           * CodeBuild `source.location`
           * buildspec files
           * environment variables / Parameter Store values (if plaintext)
        3. Configure secure auth:
           * Prefer CodeStar Connections via CodePipeline, or
           * Use Bitbucket OAuth / tokens stored in Secrets Manager, never in URLs.
        4. Run the Python/boto3 script to clean all affected CodeBuild projects.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Bitbucket connection for OAuth-based access (create once per Bitbucket connection)
        resource "aws_codestarconnections_connection" "BITBUCKET_CONNECTION" {
          name          = "BITBUCKET_CONNECTION_NAME"   # replace with a descriptive name
          provider_type = "Bitbucket"
        }

        # CodeBuild project with Bitbucket source URL that does NOT contain credentials,
        # and auth configured to use OAuth via the CodeStar connection above.
        resource "aws_codebuild_project" "CODEBUILD_PROJECT" {
          name         = "CODEBUILD_PROJECT_NAME"       # replace with your project name
          service_role = "CODEBUILD_SERVICE_ROLE_ARN"   # replace with IAM role ARN

          artifacts {
            type = "NO_ARTIFACTS"
          }

          environment {
            compute_type                = "BUILD_GENERAL1_SMALL"
            image                       = "PUBLIC_ECR_OR_DOCKER_IMAGE"  # replace as needed
            type                        = "LINUX_CONTAINER"
            privileged_mode             = false
          }

          source {
            type            = "BITBUCKET"
            # IMPORTANT: no username/password or token embedded in this URL
            location        = "https://bitbucket.org/WORKSPACE/REPO_SLUG.git" # replace with your repo URL

            auth {
              # Use OAuth as required by the remediation
              type     = "OAUTH"
              resource = aws_codestarconnections_connection.BITBUCKET_CONNECTION.arn
            }

            # keep any other existing source settings here (buildspec, git_clone_depth, etc.)
            # buildspec       = "buildspec.yml"
            # git_clone_depth = 1
          }
        }
        ```

        Changing the `source.location` to remove embedded credentials and updating `source.auth` to `type = "OAUTH"` is an in-place update for `aws_codebuild_project` (no replacement of the project itself, but builds will use the new connection).

        To verify, `terraform plan` should show updates only to the `source.location` (removing credentials if previously present) and the `source.auth` block (setting `type = "OAUTH"` and pointing `resource` at the OAuth connection ARN), with no `-/+` replacement for `aws_codebuild_project.CODEBUILD_PROJECT`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
