Skip to content
pi-c Artifact [e4764ffad3]
Login

Artifact [e4764ffad3]

Artifact e4764ffad3e648e29e80acd6c19b024013edc9b0ec15055b9484816aec28b814:


#!/bin/sh
# Stands in for the keystore (PIC_TEST_KEYCHAIN), so no test touches the real login Keychain or
# keyring. It speaks the part of macOS's security that pic uses (-i with add-generic-password on
# stdin, find-generic-password -w, delete-generic-password) and of secret-tool (store with the
# secret on stdin, lookup, clear). Items are files under $FAKE_KEYCHAIN_DIR/items; every argv is
# appended to $FAKE_KEYCHAIN_DIR/argv.log. While $FAKE_KEYCHAIN_DIR/locked exists it refuses, as
# a locked Keychain does over ssh (security -i still exits 0, as the real one does).
D=${FAKE_KEYCHAIN_DIR:?set FAKE_KEYCHAIN_DIR}
mkdir -p "$D/items"
printf '%s\n' "$*" >> "$D/argv.log"
locked() { [ -e "$D/locked" ]; }
item() { printf '%s/items/%s' "$D" "$(printf '%s|%s' "$1" "$2" | od -An -tx1 | tr -d ' \n')"; }

# security's commands; S, A and W are parsed from -s, -a and -w.
security_cmd() {
    cmd=$1
    shift
    S= A= W=
    while [ $# -gt 0 ]; do
        case $1 in
        -s) S=$2; shift ;;
        -a) A=$2; shift ;;
        -l) shift ;;
        -w) if [ $# -gt 1 ]; then W=$2; shift; else W=-; fi ;;
        esac
        shift
    done
    case $cmd in
    add-generic-password)
        if locked; then echo "User interaction is not allowed." >&2; return 36; fi
        printf '%s' "$W" > "$(item "$S" "$A")" ;;
    find-generic-password)
        if locked; then echo "User interaction is not allowed." >&2; return 36; fi
        f=$(item "$S" "$A")
        [ -f "$f" ] || { echo "The specified item could not be found in the keychain." >&2; return 44; }
        cat "$f"; echo ;;
    delete-generic-password)
        f=$(item "$S" "$A")
        [ -f "$f" ] || return 44
        rm -f "$f" ;;
    *) echo "fake_keychain: unknown command $cmd" >&2; return 1 ;;
    esac
}

# secret-tool's: attribute pairs after the command.
secret_attrs() {
    S= A=
    while [ $# -gt 0 ]; do
        case $1 in
        service) S=$2; shift ;;
        account) A=$2; shift ;;
        esac
        shift
    done
}

case $1 in
-i)
    while IFS= read -r line; do
        printf 'stdin: %s\n' "${line%% *}" >> "$D/argv.log"
        eval "set -- $line"
        security_cmd "$@" || :
    done
    exit 0 ;;
add-generic-password | find-generic-password | delete-generic-password)
    security_cmd "$@"; exit $? ;;
store)
    shift
    secret_attrs "$@"
    if locked; then cat > /dev/null; echo "Cannot create an item in a locked collection" >&2; exit 1; fi
    cat > "$(item "$S" "$A")" ;;
lookup)
    shift
    secret_attrs "$@"
    if locked; then exit 1; fi
    f=$(item "$S" "$A")
    [ -f "$f" ] || exit 1
    cat "$f" ;;
clear)
    shift
    secret_attrs "$@"
    rm -f "$(item "$S" "$A")" ;;
*) echo "fake_keychain: unknown command $1" >&2; exit 1 ;;
esac