"""Which credentials does boto3 pick when several are available? Local only: reads fake files, never calls AWS."""
import os, tempfile, textwrap, boto3

home = tempfile.mkdtemp()
os.makedirs(f"{home}/.aws")
open(f"{home}/.aws/credentials", "w").write(textwrap.dedent("""\
    [default]
    aws_access_key_id = AKIAZ7LABFAKEKEY4TEST
    aws_secret_access_key = wJk3Lab9FakeSecretValueForTestingOnly0123456
    """))
open(f"{home}/.aws/config", "w").write(textwrap.dedent("""\
    [profile app-role]
    role_arn = arn:aws:iam::123456789012:role/app-role
    source_profile = default
    """))

def who(label, profile=None, env=None):
    for k in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE"): os.environ.pop(k, None)
    os.environ["HOME"] = home
    os.environ["AWS_SHARED_CREDENTIALS_FILE"] = f"{home}/.aws/credentials"
    os.environ["AWS_CONFIG_FILE"] = f"{home}/.aws/config"
    os.environ["AWS_EC2_METADATA_DISABLED"] = "true"
    os.environ.update(env or {})
    c = boto3.Session(profile_name=profile).get_credentials()
    print(f"{label:<58} -> picked: {c.method}")

who("A. only a static key in the credentials file")
who("B. same file, PLUS old static key left in an env var", env={"AWS_ACCESS_KEY_ID": "AKIAZ7LABOLDENVKEY00", "AWS_SECRET_ACCESS_KEY": "fake"})
who("C. profile that assumes a role, nothing else set", profile="app-role")
who("D. role profile, but an old static key is still in env", profile="app-role", env={"AWS_ACCESS_KEY_ID": "AKIAZ7LABOLDENVKEY00", "AWS_SECRET_ACCESS_KEY": "fake"})
