Skip to content

Instantly share code, notes, and snippets.

@gregalia
Last active February 20, 2025 17:58
Show Gist options
  • Save gregalia/6c190a46b2f6daf730e46789fda8bc57 to your computer and use it in GitHub Desktop.
Save gregalia/6c190a46b2f6daf730e46789fda8bc57 to your computer and use it in GitHub Desktop.
Code Snippets

Code Snippets

Mac Stuff

Plist Looping/Get Mac Default URL Handler

#!/usr/bin/env bash

# Other types of handlers, e.g. file extensions
# LSHandlerContentType
# LSHandlerPreferredVersions

get_url_handler() (
  url_scheme_wanted="${1}"
  prefs_file=~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist
  hash -p /usr/libexec/PlistBuddy PlistBuddy
  i=0
  while PlistBuddy -c "print LSHandlers:${i}" "${prefs_file}" &>/dev/null; do
    url_scheme_found="$(
      PlistBuddy \
        -c "print LSHandlers:${i}:LSHandlerURLScheme" \
        "${prefs_file}" \
        2>/dev/null
    )"
    if [[ "${url_scheme_found}" == "${url_scheme_wanted}" ]]; then
      default_handler="$(
        PlistBuddy \
          -c "print LSHandlers:${i}:LSHandlerRoleAll" \
          "${prefs_file}" \
          2>/dev/null
      )"
      echo "${default_handler}"
    fi
    ((i++))
  done
)

get_url_handler https

Docker stuff

Attach VS Code Debugger to Pytest in a Container

compose.yaml

---
services:
  service-name:
    ports:
      - name: debugpy
        published: 5678
        target: 5678
    build:
      context: .
      dockerfile: path-to/Dockerfile
      target: test-image
      tags:
        - service-name:test-image
      ssh:
        - default=${SSH_AUTH_SOCK}
    stdin_open: true
    tty: true
    volumes:
      - type: bind
        source: .ignore/docker-pytest-cache
        target: /path/to/.pytest_cache
    environment:
      PYTHONBREAKPOINT: debugpy.breakpoint()
    entrypoint: "\
      sh -c 'pip install debugpy && python -Xfrozen_modules=off -m \
      debugpy --wait-for-client --listen 0.0.0.0:5678 -m \
      pytest \
      tests/test_file.py\
      ::\
      ClassName\
      ::\
      method_name\
      '"

.vscode/tasks.json

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "docker compose up",
      "type": "shell",
      "command": "docker compose up --build",
      "isBackground": true
  ]
}

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "debugpy docker pytest",
      "preLaunchTask": "docker compose up",
      "type": "debugpy",
      "request": "attach",
      "connect": {
        "host": "localhost",
        "port": 5678
      },
      // Adjust this if the debugger reports that it can't find the source file
      "pathMappings": [
        {
          "localRoot": "${workspaceFolder}",
          "remoteRoot": "."
        }
      ]
    }
  ]
}

Procedure

  1. In VS Code Command Palette: 'Debug: Select and Start Debugging'
  2. Select 'debugpy docker tests'
  3. Wait for task to finish
  4. When you see the task manager complain that The task can't be tracked
    1. Enable 'Remember my choice for this task'
    2. Select 'Debug Anyway'

GitHub Actions Stuff

Delete Docker Build Cache

gh cache list --json key --jq '.[] | select(.key | contains("buildkit")) | .key' | xargs -L 1 gh cache delete

Unix Stuff

Simple Netcat Web Server

port='80'
header='HTTP/1.1 200 OK'
body='<!DOCTYPE html>
<html>
  <body>
    <h1>Example</h1>
    <p>
      This is a simple webserver running with <b>nc</b>
    </p>
  </body>
</html>'

printf -v response "%s\n\n%s\n" "${header}" "${body}"

while true; do
  /usr/bin/nc -l "${port}" <<<"${response}"
done

GCP SDK Using Federated AWS Auth

from boto3 import Session as BotoSession
from botocore.credentials import Credentials as BotoCredentials
from botocore.exceptions import NoCredentialsError
from google.auth import _helpers
from google.auth.aws import AwsSecurityCredentials, AwsSecurityCredentialsSupplier
from google.auth.aws import Credentials as AwsFederatedGcpCredentials
from google.auth.external_account import SupplierContext
from google.auth.transport import Request


class BotoCredentialsSupplier(AwsSecurityCredentialsSupplier):
    """
    Use boto to resolve the current session's AWS credentials rather than using
    the GCP SDK defaults: exposing them to the environment or using a metadata
    service
    """

    def __init__(self, aws_region: str, boto_session=None) -> None:
        self.aws_region = aws_region
        self.boto_session = boto_session

    @_helpers.copy_docstring(AwsSecurityCredentialsSupplier)
    def get_aws_security_credentials(
        self,
        context: SupplierContext,
        request: Request,
    ) -> AwsSecurityCredentials:
        boto_session = self.boto_session if self.boto_session else BotoSession(region_name=self.aws_region)
        boto_credentials: BotoCredentials | None = boto_session.get_credentials()
        if boto_credentials is None:
            raise NoCredentialsError
        frozen_credentials = boto_credentials.get_frozen_credentials()
        return AwsSecurityCredentials(
            frozen_credentials.access_key,
            frozen_credentials.secret_key,
            frozen_credentials.token,
        )

    @_helpers.copy_docstring(AwsSecurityCredentialsSupplier)
    def get_aws_region(
        self,
        context: SupplierContext,
        request: Request,
    ) -> str:
        return self.aws_region


def get_aws_federated_gcp_creds(
    aws_region: str,
    project_number: str | int,
    pool_id: str,
    org_uuid: str,
    service_account_email: str,
) -> AwsFederatedGcpCredentials:
    """
    If AWS is properly federated as an identity provider in GCP, GCP
    session credentials can be obtained with AWS credentials.
    """
    provider_id = org_uuid.replace("-", "")
    boto_credentials_supplier = BotoCredentialsSupplier(aws_region=aws_region)
    return AwsFederatedGcpCredentials(
        audience=(
            f"//iam.googleapis.com/projects/{project_number}/locations/global"
            f"/workloadIdentityPools/{pool_id}/providers/{provider_id}"
        ),
        subject_token_type="urn:ietf:params:aws:token-type:aws4_request",
        service_account_impersonation_url=(
            "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts"
            f"/{service_account_email}:generateAccessToken"
        ),
        aws_security_credentials_supplier=boto_credentials_supplier,
    )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment