Compare commits
212 Commits
projected_
...
maxgoedjen
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9baf6aa9ed | ||
|
|
595de41f03 | ||
|
|
d82f404166 | ||
|
|
a3bfcb316c | ||
|
|
bba4fb9e7c | ||
|
|
32a1a0bca9 | ||
|
|
bb0b6d8dc3 | ||
|
|
c63d87cbec | ||
|
|
65bc6c1a69 | ||
|
|
275b6ef9bb | ||
|
|
f13bc23991 | ||
|
|
3a67d59519 | ||
|
|
d9a3f0c813 | ||
|
|
84d5a56fb0 | ||
|
|
3bb0cc4a0e | ||
|
|
516e37fdde | ||
|
|
f9dc947b59 | ||
|
|
9c042d1956 | ||
|
|
08e0c4b63b | ||
|
|
f80cbdaf04 | ||
|
|
7a53a85615 | ||
|
|
1f74bd814f | ||
|
|
d9d93574f2 | ||
|
|
15e8ed1ec2 | ||
|
|
1df0c8e96b | ||
|
|
8213a8b451 | ||
|
|
af77fd4a21 | ||
|
|
85d0cab0f5 | ||
|
|
e8cdcdfb7f | ||
|
|
d7f8d5e56b | ||
|
|
3f247d628f | ||
|
|
dae9cead4e | ||
|
|
fe9f8613fa | ||
|
|
5d5ae5bab4 | ||
|
|
f76766a9d5 | ||
|
|
b308b10716 | ||
|
|
0e1e6813a1 | ||
|
|
27bf7c29e4 | ||
|
|
36b6c52979 | ||
|
|
67ec4fee12 | ||
|
|
21fc834fd9 | ||
|
|
726d0580d0 | ||
|
|
4f608ebbc6 | ||
|
|
6e7cf82618 | ||
|
|
96ef91df0c | ||
|
|
aa46d8fa48 | ||
|
|
cf7c6e9fbe | ||
|
|
7c7db56c1e | ||
|
|
cd12e4c828 | ||
|
|
a5b43ea046 | ||
|
|
8c516e128a | ||
|
|
6854c05763 | ||
|
|
5467474d88 | ||
|
|
5c2d039682 | ||
|
|
20e64604d6 | ||
|
|
c5a610d786 | ||
|
|
7d21e3983c | ||
|
|
2c38aaed6f | ||
|
|
63b42bd9df | ||
|
|
cf5ae49ebc | ||
|
|
61705af42f | ||
|
|
558ae15b2d | ||
|
|
902d5c4a1e | ||
|
|
e0c24917f2 | ||
|
|
3d5f0b45bd | ||
|
|
74f4f1c0b1 | ||
|
|
c8cf0db1c5 | ||
|
|
412687467b | ||
|
|
416a7d5f40 | ||
|
|
c4605fb60e | ||
|
|
61eed5987c | ||
|
|
cbef7c6181 | ||
|
|
63a09390b8 | ||
|
|
a4e1ab9eb6 | ||
|
|
147f4d9908 | ||
|
|
ddcb2a36ec | ||
|
|
6dc93806a8 | ||
|
|
99a6d48e53 | ||
|
|
935ac32ea2 | ||
|
|
a0a632f245 | ||
|
|
51fed9e593 | ||
|
|
f652d1d961 | ||
|
|
8aacd428b1 | ||
|
|
c2eb5ce1f6 | ||
|
|
fb4dec383b | ||
|
|
c5052dd457 | ||
|
|
d967c7de07 | ||
|
|
d5b6382dd0 | ||
|
|
e8fcb95db0 | ||
|
|
8ad2d60082 | ||
|
|
6ce0510f21 | ||
|
|
c52728a050 | ||
|
|
8f4d0b8eda | ||
|
|
c37d0c0cba | ||
|
|
6c607f065c | ||
|
|
cff1fde90e | ||
|
|
c32ceb6ad8 | ||
|
|
f0a6f2e43b | ||
|
|
828c61cb2f | ||
|
|
e8c5336888 | ||
|
|
b3bea27f40 | ||
|
|
3d3d123484 | ||
|
|
5b0135d694 | ||
|
|
5067f05558 | ||
|
|
b815c1e5ad | ||
|
|
75c9b5bb62 | ||
|
|
f259cf6bf3 | ||
|
|
2ba73ff680 | ||
|
|
e3938caecb | ||
|
|
bd096c3012 | ||
|
|
2355d3f989 | ||
|
|
45bcb03fef | ||
|
|
e86aa559a4 | ||
|
|
d36537b919 | ||
|
|
8adb4423ac | ||
|
|
8dbf992cce | ||
|
|
f382d72ee5 | ||
|
|
9749cd6f3e | ||
|
|
83ecc15332 | ||
|
|
ecd001a082 | ||
|
|
eeec2c3169 | ||
|
|
609adf04bf | ||
|
|
197f63d1eb | ||
|
|
efe5858ce1 | ||
|
|
ed2678a615 | ||
|
|
0e6b218f1f | ||
|
|
5cc62b628a | ||
|
|
feffdb4856 | ||
|
|
c7d28678e7 | ||
|
|
b5f2dfd153 | ||
|
|
ad56019901 | ||
|
|
5929137f20 | ||
|
|
35a7c99cba | ||
|
|
a543de0737 | ||
|
|
fc21018eb4 | ||
|
|
52cc08424e | ||
|
|
d13f4ee7ba | ||
|
|
6f4226f97a | ||
|
|
3315a4bfbc | ||
|
|
85a7a64bc9 | ||
|
|
409efa5f9f | ||
|
|
bb63ae8469 | ||
|
|
30c1d36974 | ||
|
|
de8d18f9e9 | ||
|
|
1ae0996e2c | ||
|
|
3d50a99430 | ||
|
|
45fc356f0f | ||
|
|
212678b94e | ||
|
|
2e1f4881a9 | ||
|
|
c2b80e3c7c | ||
|
|
15d2afd2cb | ||
|
|
2a4da36c4e | ||
|
|
1fc8fa25d9 | ||
|
|
5718ae6805 | ||
|
|
5af84583ab | ||
|
|
afc54c5e40 | ||
|
|
c80a6f1b0b | ||
|
|
8c67ea7c73 | ||
|
|
171981de9f | ||
|
|
cf58630065 | ||
|
|
7b0ccbcc16 | ||
|
|
dbaa57a05a | ||
|
|
6248ecc9db | ||
|
|
d82bb80e14 | ||
|
|
5bf5be6c25 | ||
|
|
1d4ef12546 | ||
|
|
df10fa3912 | ||
|
|
e04fe419ed | ||
|
|
0944d65ccb | ||
|
|
2ca8279187 | ||
|
|
be58ddd324 | ||
|
|
93e79470b7 | ||
|
|
43a9e287c3 | ||
|
|
f54b2a33bf | ||
|
|
3bd8e3b494 | ||
|
|
14b351abee | ||
|
|
480ef5392d | ||
|
|
8679ca3da0 | ||
|
|
f43571baa3 | ||
|
|
acdf0baf3a | ||
|
|
1a362ef955 | ||
|
|
3b254d33a5 | ||
|
|
382913cb99 | ||
|
|
20cbaac6f6 | ||
|
|
47d736cb0d | ||
|
|
fa0e81cd8e | ||
|
|
e31db0f4fa | ||
|
|
403709ac83 | ||
|
|
5f055efa18 | ||
|
|
e77812c06c | ||
|
|
8744313ba1 | ||
|
|
26d6ced9ee | ||
|
|
71b4780488 | ||
|
|
84dd9403c3 | ||
|
|
0af7b803bc | ||
|
|
a1009d0dac | ||
|
|
ae7394f771 | ||
|
|
6ea0a3ebd2 | ||
|
|
067f1526b0 | ||
|
|
f43dea0d0d | ||
|
|
db8833fa25 | ||
|
|
1409e9ac31 | ||
|
|
adabe801d3 | ||
|
|
19f9494492 | ||
|
|
c50d2feaf9 | ||
|
|
03d3cc9177 | ||
|
|
141cc03b60 | ||
|
|
07559bd7ef | ||
|
|
cb206a18c2 | ||
|
|
6cb3ff80d9 | ||
|
|
05c5aca9b6 | ||
|
|
5894bbca00 |
BIN
.github/readme/app-dark.png
vendored
Normal file
|
After Width: | Height: | Size: 668 KiB |
BIN
.github/readme/app-light.png
vendored
Normal file
|
After Width: | Height: | Size: 618 KiB |
BIN
.github/readme/app.png
vendored
|
Before Width: | Height: | Size: 456 KiB |
BIN
.github/readme/notification.png
vendored
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 47 KiB |
BIN
.github/readme/touchid.png
vendored
|
Before Width: | Height: | Size: 190 KiB After Width: | Height: | Size: 230 KiB |
16
.github/templates/release.md
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
Update description
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
|
||||||
|
## Fixes
|
||||||
|
|
||||||
|
|
||||||
|
## Minimum macOS Version
|
||||||
|
|
||||||
|
|
||||||
|
## Build
|
||||||
|
https://github.com/maxgoedjen/secretive/actions/runs/RUN_ID
|
||||||
|
|
||||||
|
## Attestation
|
||||||
|
https://github.com/maxgoedjen/secretive/attestations/ATTESTATION_ID
|
||||||
47
.github/workflows/codeql.yml
vendored
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
name: "CodeQL Advanced"
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ "main" ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ "main" ]
|
||||||
|
schedule:
|
||||||
|
- cron: '26 15 * * 3'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
name: Analyze (${{ matrix.language }})
|
||||||
|
runs-on: ${{ (matrix.language == 'swift' && 'macos-26') || 'ubuntu-latest' }}
|
||||||
|
permissions:
|
||||||
|
security-events: write
|
||||||
|
packages: read
|
||||||
|
actions: read
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- language: actions
|
||||||
|
build-mode: none
|
||||||
|
# Disable this until CodeQL supports Xcode 26 builds.
|
||||||
|
# - language: swift
|
||||||
|
# build-mode: manual
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Initialize CodeQL
|
||||||
|
uses: github/codeql-action/init@v3
|
||||||
|
with:
|
||||||
|
languages: ${{ matrix.language }}
|
||||||
|
build-mode: ${{ matrix.build-mode }}
|
||||||
|
- if: matrix.build-mode == 'manual'
|
||||||
|
name: "Select Xcode"
|
||||||
|
run: sudo xcrun xcode-select -s /Applications/Xcode_26.2.app
|
||||||
|
- if: matrix.build-mode == 'manual'
|
||||||
|
name: "Build"
|
||||||
|
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO
|
||||||
|
- name: Perform CodeQL Analysis
|
||||||
|
uses: github/codeql-action/analyze@v3
|
||||||
|
with:
|
||||||
|
category: "/language:${{matrix.language}}"
|
||||||
65
.github/workflows/nightly.yml
vendored
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
name: Nightly
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 8 * * *"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: macos-26
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
contents: write
|
||||||
|
attestations: write
|
||||||
|
actions: read
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
- name: Setup Signing
|
||||||
|
env:
|
||||||
|
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||||
|
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||||
|
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||||
|
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||||
|
APPLE_API_KEY_DATA: ${{ secrets.APPLE_API_KEY_DATA }}
|
||||||
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
|
run: ./.github/scripts/signing.sh
|
||||||
|
- name: Set Environment
|
||||||
|
run: sudo xcrun xcode-select -s /Applications/Xcode_26.2.app
|
||||||
|
- name: Update Build Number
|
||||||
|
env:
|
||||||
|
RUN_ID: ${{ github.run_id }}
|
||||||
|
run: |
|
||||||
|
DATE=$(date "+%Y-%m-%d")
|
||||||
|
sed -i '' -e "s/GITHUB_CI_VERSION/0.0.0_nightly-$DATE/g" Sources/Config/Config.xcconfig
|
||||||
|
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||||
|
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||||
|
- name: Build
|
||||||
|
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||||
|
- name: Move to Artifact Folder
|
||||||
|
run: mkdir Artifact; cp -r Archive.xcarchive/Products/Applications/Secretive.app Artifact
|
||||||
|
- name: Upload App to Artifacts
|
||||||
|
id: upload
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: Secretive
|
||||||
|
path: Artifact
|
||||||
|
- name: Download Zipped Artifact
|
||||||
|
id: download
|
||||||
|
env:
|
||||||
|
ZIP_ID: ${{ steps.upload.outputs.artifact-id }}
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
run: |
|
||||||
|
curl -L -H "Authorization: Bearer $GITHUB_TOKEN" -L \
|
||||||
|
https://api.github.com/repos/maxgoedjen/secretive/actions/artifacts/$ZIP_ID/zip > Secretive.zip
|
||||||
|
- name: Notarize
|
||||||
|
env:
|
||||||
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
|
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||||
|
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
|
||||||
|
- name: Attest
|
||||||
|
id: attest
|
||||||
|
uses: actions/attest-build-provenance@v2
|
||||||
|
with:
|
||||||
|
subject-name: "Secretive.zip"
|
||||||
|
subject-digest: sha256:${{ steps.upload.outputs.artifact-digest }}
|
||||||
64
.github/workflows/oneoff.yml
vendored
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
name: One-Off Build
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: macos-26
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
contents: write
|
||||||
|
attestations: write
|
||||||
|
actions: read
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
- name: Setup Signing
|
||||||
|
env:
|
||||||
|
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||||
|
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||||
|
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||||
|
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||||
|
APPLE_API_KEY_DATA: ${{ secrets.APPLE_API_KEY_DATA }}
|
||||||
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
|
run: ./.github/scripts/signing.sh
|
||||||
|
- name: Set Environment
|
||||||
|
run: sudo xcrun xcode-select -s /Applications/Xcode_26.2.app
|
||||||
|
- name: Update Build Number
|
||||||
|
env:
|
||||||
|
RUN_ID: ${{ github.run_id }}
|
||||||
|
run: |
|
||||||
|
DATE=$(date "+%Y-%m-%d")
|
||||||
|
sed -i '' -e "s/GITHUB_CI_VERSION/0.0.0_oneoff-$DATE/g" Sources/Config/Config.xcconfig
|
||||||
|
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||||
|
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||||
|
- name: Build
|
||||||
|
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||||
|
- name: Move to Artifact Folder
|
||||||
|
run: mkdir Artifact; cp -r Archive.xcarchive/Products/Applications/Secretive.app Artifact
|
||||||
|
- name: Upload App to Artifacts
|
||||||
|
id: upload
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: Secretive
|
||||||
|
path: Artifact
|
||||||
|
- name: Download Zipped Artifact
|
||||||
|
id: download
|
||||||
|
env:
|
||||||
|
ZIP_ID: ${{ steps.upload.outputs.artifact-id }}
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
run: |
|
||||||
|
curl -L -H "Authorization: Bearer $GITHUB_TOKEN" -L \
|
||||||
|
https://api.github.com/repos/maxgoedjen/secretive/actions/artifacts/$ZIP_ID/zip > Secretive.zip
|
||||||
|
- name: Notarize
|
||||||
|
env:
|
||||||
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
|
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||||
|
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
|
||||||
|
- name: Attest
|
||||||
|
id: attest
|
||||||
|
uses: actions/attest-build-provenance@v2
|
||||||
|
with:
|
||||||
|
subject-name: "Secretive.zip"
|
||||||
|
subject-digest: sha256:${{ steps.upload.outputs.artifact-digest }}
|
||||||
104
.github/workflows/release.yml
vendored
@@ -6,10 +6,12 @@ on:
|
|||||||
- '*'
|
- '*'
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: macos-11.0
|
permissions:
|
||||||
|
contents: read
|
||||||
|
runs-on: macos-26
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v5
|
||||||
- name: Setup Signing
|
- name: Setup Signing
|
||||||
env:
|
env:
|
||||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||||
@@ -20,17 +22,21 @@ jobs:
|
|||||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
run: ./.github/scripts/signing.sh
|
run: ./.github/scripts/signing.sh
|
||||||
- name: Set Environment
|
- name: Set Environment
|
||||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
run: sudo xcrun xcode-select -s /Applications/Xcode_26.2.app
|
||||||
- name: Test
|
- name: Test
|
||||||
run: |
|
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme PackageTests test
|
||||||
pushd Sources/Packages
|
# SPM doesn't seem to pick up on the tests currently?
|
||||||
swift test
|
# run: swift test --build-system swiftbuild --package-path Sources/Packages
|
||||||
popd
|
|
||||||
build:
|
build:
|
||||||
runs-on: macos-11.0
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
contents: write
|
||||||
|
attestations: write
|
||||||
|
actions: read
|
||||||
|
runs-on: macos-26
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v5
|
||||||
- name: Setup Signing
|
- name: Setup Signing
|
||||||
env:
|
env:
|
||||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||||
@@ -41,7 +47,7 @@ jobs:
|
|||||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
run: ./.github/scripts/signing.sh
|
run: ./.github/scripts/signing.sh
|
||||||
- name: Set Environment
|
- name: Set Environment
|
||||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
run: sudo xcrun xcode-select -s /Applications/Xcode_26.2.app
|
||||||
- name: Update Build Number
|
- name: Update Build Number
|
||||||
env:
|
env:
|
||||||
TAG_NAME: ${{ github.ref }}
|
TAG_NAME: ${{ github.ref }}
|
||||||
@@ -50,63 +56,43 @@ jobs:
|
|||||||
export CLEAN_TAG=$(echo $TAG_NAME | sed -e 's/refs\/tags\/v//')
|
export CLEAN_TAG=$(echo $TAG_NAME | sed -e 's/refs\/tags\/v//')
|
||||||
sed -i '' -e "s/GITHUB_CI_VERSION/$CLEAN_TAG/g" Sources/Config/Config.xcconfig
|
sed -i '' -e "s/GITHUB_CI_VERSION/$CLEAN_TAG/g" Sources/Config/Config.xcconfig
|
||||||
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Sources/Config/Config.xcconfig
|
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||||
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Secretive/Credits.rtf
|
sed -i '' -e "s/GITHUB_BUILD_URL/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||||
- name: Build
|
- name: Build
|
||||||
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||||
- name: Create ZIPs
|
- name: Move to Artifact Folder
|
||||||
|
run: mkdir Artifact; cp -r Archive.xcarchive/Products/Applications/Secretive.app Artifact
|
||||||
|
- name: Upload App to Artifacts
|
||||||
|
id: upload
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: Secretive.zip
|
||||||
|
path: Artifact
|
||||||
|
- name: Download Zipped Artifact
|
||||||
|
id: download
|
||||||
|
env:
|
||||||
|
ZIP_ID: ${{ steps.upload.outputs.artifact-id }}
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive/Products/Applications/Secretive.app ./Secretive.zip
|
curl -L -H "Authorization: Bearer $GITHUB_TOKEN" -L \
|
||||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive ./Archive.zip
|
https://api.github.com/repos/maxgoedjen/secretive/actions/artifacts/$ZIP_ID/zip > Secretive.zip
|
||||||
- name: Notarize
|
- name: Notarize
|
||||||
env:
|
env:
|
||||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||||
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
|
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
|
||||||
- name: Document SHAs
|
- name: Attest
|
||||||
run: |
|
id: attest
|
||||||
shasum -a 512 Secretive.zip
|
uses: actions/attest-build-provenance@v2
|
||||||
shasum -a 512 Archive.zip
|
with:
|
||||||
|
subject-path: "Secretive.zip"
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
id: create_release
|
|
||||||
uses: actions/create-release@v1
|
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
with:
|
TAG_NAME: ${{ github.ref }}
|
||||||
tag_name: ${{ github.ref }}
|
RUN_ID: ${{ github.run_id }}
|
||||||
release_name: ${{ github.ref }}
|
ATTESTATION_ID: ${{ steps.attest.outputs.attestation-id }}
|
||||||
body: |
|
run: |
|
||||||
Update description
|
sed -i.tmp "s/RUN_ID/$RUN_ID/g" .github/templates/release.md
|
||||||
|
sed -i.tmp "s/ATTESTATION_ID/$ATTESTATION_ID/g" .github/templates/release.md
|
||||||
## Features
|
gh release create $TAG_NAME -d -F .github/templates/release.md
|
||||||
|
gh release upload $TAG_NAME Secretive.zip
|
||||||
|
|
||||||
## Fixes
|
|
||||||
|
|
||||||
|
|
||||||
## Minimum macOS Version
|
|
||||||
|
|
||||||
|
|
||||||
## Build
|
|
||||||
https://github.com/maxgoedjen/secretive/actions/runs/${{ github.run_id }}
|
|
||||||
draft: true
|
|
||||||
prerelease: false
|
|
||||||
- name: Upload App to Release
|
|
||||||
id: upload-release-asset-app
|
|
||||||
uses: actions/upload-release-asset@v1.0.1
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
with:
|
|
||||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
|
||||||
asset_path: ./Secretive.zip
|
|
||||||
asset_name: Secretive.zip
|
|
||||||
asset_content_type: application/zip
|
|
||||||
- name: Upload App to Artifacts
|
|
||||||
uses: actions/upload-artifact@v1
|
|
||||||
with:
|
|
||||||
name: Secretive.zip
|
|
||||||
path: Secretive.zip
|
|
||||||
- name: Upload Archive to Artifacts
|
|
||||||
uses: actions/upload-artifact@v1
|
|
||||||
with:
|
|
||||||
name: Xcode_Archive.zip
|
|
||||||
path: Archive.zip
|
|
||||||
|
|||||||
19
.github/workflows/test.yml
vendored
@@ -3,14 +3,17 @@ name: Test
|
|||||||
on: [push, pull_request]
|
on: [push, pull_request]
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: macos-11.0
|
permissions:
|
||||||
|
contents: read
|
||||||
|
runs-on: macos-26
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v5
|
||||||
- name: Set Environment
|
- name: Set Environment
|
||||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
run: sudo xcrun xcode-select -s /Applications/Xcode_26.2.app
|
||||||
- name: Test
|
- name: Test Main Packages
|
||||||
run: |
|
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme PackageTests test
|
||||||
pushd Sources/Packages
|
# SPM doesn't seem to pick up on the tests currently?
|
||||||
swift test
|
# run: swift test --build-system swiftbuild --package-path Sources/Packages
|
||||||
popd
|
- name: Test SecretKit Packages
|
||||||
|
run: swift test --build-system swiftbuild
|
||||||
|
|||||||
@@ -1,58 +1,3 @@
|
|||||||
# Setting up Third Party Apps FAQ
|
# App Configuration
|
||||||
|
|
||||||
## Tower
|
Instructions for setting up apps and shells has moved to [secretive-config-instructions](https://github.com/maxgoedjen/secretive-config-instructions)!
|
||||||
|
|
||||||
Tower provides [instructions](https://www.git-tower.com/help/mac/integration/environment).
|
|
||||||
|
|
||||||
## GitHub Desktop
|
|
||||||
|
|
||||||
Should just work, no configuration needed
|
|
||||||
|
|
||||||
## Fork
|
|
||||||
|
|
||||||
Add this to your `~/.ssh/config` (the path should match the socket path from the setup flow).
|
|
||||||
|
|
||||||
```
|
|
||||||
Host *
|
|
||||||
IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
|
|
||||||
```
|
|
||||||
|
|
||||||
## VS Code
|
|
||||||
|
|
||||||
Add this to your `~/.ssh/config` (the path should match the socket path from the setup flow).
|
|
||||||
|
|
||||||
```
|
|
||||||
Host *
|
|
||||||
IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
|
|
||||||
```
|
|
||||||
|
|
||||||
## Cyberduck
|
|
||||||
|
|
||||||
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
|
|
||||||
|
|
||||||
```
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>Label</key>
|
|
||||||
<string>link-ssh-auth-sock</string>
|
|
||||||
<key>ProgramArguments</key>
|
|
||||||
<array>
|
|
||||||
<string>/bin/sh</string>
|
|
||||||
<string>-c</string>
|
|
||||||
<string>/bin/ln -sf $HOME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh $SSH_AUTH_SOCK</string>
|
|
||||||
</array>
|
|
||||||
<key>RunAtLoad</key>
|
|
||||||
<true/>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
||||||
```
|
|
||||||
|
|
||||||
Log out and log in again before launching Cyberduck.
|
|
||||||
|
|
||||||
|
|
||||||
# The app I use isn't listed here!
|
|
||||||
|
|
||||||
If you know how to get it set up, please open a PR for this page and add it! Contributions are very welcome.
|
|
||||||
If you're not able to get it working, please file a [GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) for it. No guarantees we'll be able to get it working, but chances are someone else in the community might be able to.
|
|
||||||
|
|||||||
@@ -14,9 +14,13 @@ Secretive is designed to be easily auditable by people who are considering using
|
|||||||
|
|
||||||
All contributors must abide by the [Code of Conduct](CODE_OF_CONDUCT.md)
|
All contributors must abide by the [Code of Conduct](CODE_OF_CONDUCT.md)
|
||||||
|
|
||||||
|
## Localization
|
||||||
|
|
||||||
|
If you'd like to contribute a translation, please see [Localizing](LOCALIZING.md) to get started.
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
If you make a material contribution to the app, please add yourself to the end of the [credits](https://github.com/maxgoedjen/secretive/blob/main/Secretive/Credits.rtf).
|
If you make a material contribution to the app, please add yourself to the end of the [credits](https://github.com/maxgoedjen/secretive/blob/main/Sources/Secretive/Credits.rtf).
|
||||||
|
|
||||||
## Collaborator Status
|
## Collaborator Status
|
||||||
|
|
||||||
|
|||||||
22
FAQ.md
@@ -6,12 +6,16 @@ The secure enclave doesn't allow import or export of private keys. For any new c
|
|||||||
|
|
||||||
### Secretive doesn't work with my git client/app
|
### Secretive doesn't work with my git client/app
|
||||||
|
|
||||||
Secretive relies on the `SSH_AUTH_SOCK` environment variable being respected. The `git` and `ssh` command line tools natively respect this, but third party apps may require some configuration to work. A non-exhaustive list of setup steps is provided in the [App Config FAQ](APP_CONFIG.md).
|
Secretive relies on the `SSH_AUTH_SOCK` environment variable being respected. The `git` and `ssh` command line tools natively respect this, but third party apps may require some configuration to work. A non-exhaustive list of setup steps is provided in the [secretive-config-instructions](https://github.com/maxgoedjen/secretive-config-instructions) repo.
|
||||||
|
|
||||||
### Secretive isn't working for me
|
### Secretive isn't working for me
|
||||||
|
|
||||||
Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [new GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) with a description of your issue.
|
Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [new GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) with a description of your issue.
|
||||||
|
|
||||||
|
### Secretive was working for me, but now it has stopped
|
||||||
|
|
||||||
|
Try running the "Setup Secretive" process by clicking on "Help", then "Setup Secretive." If that doesn't work, follow the process above.
|
||||||
|
|
||||||
### Secretive prompts me to type my password instead of using my Apple Watch
|
### Secretive prompts me to type my password instead of using my Apple Watch
|
||||||
|
|
||||||
1) Make sure you have enabled "Use your Apple Watch to unlock apps and your Mac" in System Preferences --> Security & Privacy:
|
1) Make sure you have enabled "Use your Apple Watch to unlock apps and your Mac" in System Preferences --> Security & Privacy:
|
||||||
@@ -26,7 +30,15 @@ Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [
|
|||||||
|
|
||||||
### How do I tell SSH to use a specific key?
|
### How do I tell SSH to use a specific key?
|
||||||
|
|
||||||
You can create a `mykey.pub` (where `mykey` is the name of your key) in your `~/.ssh/` directory with the contents of your public key, and specify that you want to use that key in your `~/.ssh/config`. [This ServerFault answer](https://serverfault.com/a/295771) has more details on setting that up
|
Beginning with Secretive 2.2, every secret has an automatically generated public key file representation on disk, and the path to it is listed under "Public Key Path" in Secretive. You can specify that you want to use that key in your `~/.ssh/config`. [This ServerFault answer](https://serverfault.com/a/295771) has more details on setting that up.
|
||||||
|
|
||||||
|
### How can I generate an RSA key?
|
||||||
|
|
||||||
|
The Mac's Secure Enclave only supports 256-bit EC keys, so inherently Secretive cannot support generating RSA keys.
|
||||||
|
|
||||||
|
### Can I use Secretive for SSH Agent Forwarding?
|
||||||
|
|
||||||
|
Yes, you can! Once you've set up Secretive, just add `ForwardAgent yes` to the hosts you want to forward to in your SSH config file. Afterwards, any use of one of your SSH keys on the remote host must be authenticated through Secretive.
|
||||||
|
|
||||||
### Why should I trust you?
|
### Why should I trust you?
|
||||||
|
|
||||||
@@ -38,7 +50,11 @@ Awesome! Just bear in mind that because an app only has access to the keychain i
|
|||||||
|
|
||||||
### What's this network request to GitHub?
|
### What's this network request to GitHub?
|
||||||
|
|
||||||
Secretive checks in with GitHub's releases API to check if there's a new version of Secretive available. You can audit the source code for this feature [here](https://github.com/maxgoedjen/secretive/blob/main/Brief/Updater.swift).
|
Secretive checks in with GitHub's releases API to check if there's a new version of Secretive available. You can audit the source code for this feature [here](https://github.com/maxgoedjen/secretive/blob/main/Sources/Packages/Sources/Brief/Updater.swift).
|
||||||
|
|
||||||
|
### How do I uninstall Secretive?
|
||||||
|
|
||||||
|
Drag Secretive.app to the trash and remove `~/Library/Containers/com.maxgoedjen.Secretive.SecretAgent`. `SecretAgent` may continue running until you quit it or reboot.
|
||||||
|
|
||||||
### I have a security issue
|
### I have a security issue
|
||||||
|
|
||||||
|
|||||||
36
LOCALIZING.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# Localizing Secretive
|
||||||
|
|
||||||
|
If you speak another language, and would like to help translate Secretive to support that language, we'd love your help!
|
||||||
|
|
||||||
|
## Crowdin
|
||||||
|
|
||||||
|
[Secretive uses Crowdin for localization](https://crowdin.com/project/secretive/). Open the link and select your language to translate!
|
||||||
|
|
||||||
|
### Manual Translation
|
||||||
|
|
||||||
|
Crowdin is the easiest way to translate Secretive, but I'm happy to accept Pull Requests directly as well.
|
||||||
|
|
||||||
|
### Questions
|
||||||
|
|
||||||
|
Please open an issue if you have a question about translating the app. I'm more than happy to clarify any terms that are ambiguous or confusing. Thanks for contributing!
|
||||||
|
|
||||||
|
### Thank You
|
||||||
|
|
||||||
|
Thanks to all the folks who have contributed localizations so far!
|
||||||
|
|
||||||
|
- @mtardy for the French localization
|
||||||
|
- @GravityRyu for the Chinese localization
|
||||||
|
- @Saeger for the Portuguese (Brazil) localization
|
||||||
|
- @moritzsternemann for the German localization
|
||||||
|
- @RoboRich00A16 for the Italian localization
|
||||||
|
- @akx for the Finnish localization
|
||||||
|
- @mog422 for the Korean localization
|
||||||
|
- @niw for the Japanese localization
|
||||||
|
- @truita for the Catalan localization
|
||||||
|
- @Adimac93 for the Polish localization
|
||||||
|
- @alongotv for the Russian localization
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
A special thanks to [Crowdin](https://crowdin.com) for their [generous support of open source projects](https://crowdin.com/page/open-source-project-setup-request).
|
||||||
69
Package.swift
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
// swift-tools-version:6.2
|
||||||
|
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||||
|
|
||||||
|
import PackageDescription
|
||||||
|
|
||||||
|
// This is basically the same package as `Sources/Packages/Package.swift`, but thinned slightly.
|
||||||
|
// Ideally this would be the same package, but SPM requires it to be at the root of the project,
|
||||||
|
// and Xcode does _not_ like that, so they're separate.
|
||||||
|
let package = Package(
|
||||||
|
name: "SecretKit",
|
||||||
|
defaultLocalization: "en",
|
||||||
|
platforms: [
|
||||||
|
.macOS(.v14)
|
||||||
|
],
|
||||||
|
products: [
|
||||||
|
.library(
|
||||||
|
name: "SecretKit",
|
||||||
|
targets: ["SecretKit"]),
|
||||||
|
.library(
|
||||||
|
name: "SecureEnclaveSecretKit",
|
||||||
|
targets: ["SecureEnclaveSecretKit"]),
|
||||||
|
.library(
|
||||||
|
name: "SmartCardSecretKit",
|
||||||
|
targets: ["SmartCardSecretKit"]),
|
||||||
|
],
|
||||||
|
dependencies: [
|
||||||
|
],
|
||||||
|
targets: [
|
||||||
|
.target(
|
||||||
|
name: "SecretKit",
|
||||||
|
dependencies: [],
|
||||||
|
path: "Sources/Packages/Sources/SecretKit",
|
||||||
|
resources: [localization],
|
||||||
|
swiftSettings: swiftSettings
|
||||||
|
),
|
||||||
|
.testTarget(
|
||||||
|
name: "SecretKitTests",
|
||||||
|
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"],
|
||||||
|
path: "Sources/Packages/Tests/SecretKitTests",
|
||||||
|
swiftSettings: swiftSettings
|
||||||
|
),
|
||||||
|
.target(
|
||||||
|
name: "SecureEnclaveSecretKit",
|
||||||
|
dependencies: ["SecretKit"],
|
||||||
|
path: "Sources/Packages/Sources/SecureEnclaveSecretKit",
|
||||||
|
resources: [localization],
|
||||||
|
swiftSettings: swiftSettings
|
||||||
|
),
|
||||||
|
.target(
|
||||||
|
name: "SmartCardSecretKit",
|
||||||
|
dependencies: ["SecretKit"],
|
||||||
|
path: "Sources/Packages/Sources/SmartCardSecretKit",
|
||||||
|
resources: [localization],
|
||||||
|
swiftSettings: swiftSettings
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
var localization: Resource {
|
||||||
|
.process("../../Resources/Localizable.xcstrings")
|
||||||
|
}
|
||||||
|
|
||||||
|
var swiftSettings: [PackageDescription.SwiftSetting] {
|
||||||
|
[
|
||||||
|
.swiftLanguageMode(.v6),
|
||||||
|
// This freaks out Xcode in a dependency context.
|
||||||
|
// .treatAllWarnings(as: .error),
|
||||||
|
]
|
||||||
|
}
|
||||||
33
README.md
@@ -1,28 +1,31 @@
|
|||||||
# Secretive  
|
# Secretive [](https://github.com/maxgoedjen/secretive/actions/workflows/test.yml) 
|
||||||
|
|
||||||
|
|
||||||
Secretive is an app for storing and managing SSH keys in the Secure Enclave. It is inspired by the [sekey project](https://github.com/sekey/sekey), but rewritten in Swift with no external dependencies and with a handy native management app.
|
Secretive is an app for protecting and managing SSH keys with the Secure Enclave.
|
||||||
|
<picture>
|
||||||
<img src="/.github/readme/app.png" alt="Screenshot of Secretive" width="600">
|
<source media="(prefers-color-scheme: dark)" srcset="/.github/readme/app-dark.png">
|
||||||
|
<source media="(prefers-color-scheme: light)" srcset="/.github/readme/app-light.png">
|
||||||
|
<img src="/.github/readme/app-dark.png" alt="Screenshot of Secretive" width="600">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
|
||||||
## Why?
|
## Why?
|
||||||
|
|
||||||
### Safer Storage
|
### Safer Storage
|
||||||
|
|
||||||
The most common setup for SSH keys is just keeping them on disk, guarded by proper permissions. This is fine in most cases, but it's not super hard for malicious users or malware to copy your private key. If you store your keys in the Secure Enclave, it's impossible to export them, by design.
|
The most common setup for SSH keys is just keeping them on disk, guarded by proper permissions. This is fine in most cases, but it's not super hard for malicious users or malware to copy your private key. If you protect your keys with the Secure Enclave, it's impossible to export them, by design.
|
||||||
|
|
||||||
### Access Control
|
### Access Control
|
||||||
|
|
||||||
If your Mac has a Secure Enclave, it also has support for strong access controls like Touch ID, or authentication with Apple Watch. You can configure your key so that they require Touch ID (or Watch) authentication before they're accessed.
|
If your Mac has a Secure Enclave, it also has support for strong access controls like Touch ID, or authentication with Apple Watch. You can configure your keys so that they require Touch ID (or Watch) authentication before they're accessed.
|
||||||
|
|
||||||
<img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID">
|
<img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID" width="400">
|
||||||
|
|
||||||
### Notifications
|
### Notifications
|
||||||
|
|
||||||
Secretive also notifies you whenever your keys are accessed, so you're never caught off guard.
|
Secretive also notifies you whenever your keys are accessed, so you're never caught off guard.
|
||||||
|
|
||||||
<img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user">
|
<img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user" width="600">
|
||||||
|
|
||||||
### Support for Smart Cards Too!
|
### Support for Smart Cards Too!
|
||||||
|
|
||||||
@@ -46,11 +49,11 @@ There's a [FAQ here](FAQ.md).
|
|||||||
|
|
||||||
### Auditable Build Process
|
### Auditable Build Process
|
||||||
|
|
||||||
Builds are produced by GitHub Actions with an auditable build and release generation process. Each build has a "Document SHAs" step, which will output SHA checksums for the build produced by the GitHub Action, so you can verify that the source code for a given build corresponds to any given release.
|
Builds are produced by GitHub Actions with an auditable build and release generation process. Starting with Secretive 3.0, builds are attested using [GitHub Artifact Attestation](https://docs.github.com/en/actions/concepts/security/artifact-attestations). Attestations are viewable in the build log for a build, and also on the [main attestation page](https://github.com/maxgoedjen/secretive/attestations).
|
||||||
|
|
||||||
### A Note Around Code Signing and Keychains
|
### A Note Around Code Signing and Keychains
|
||||||
|
|
||||||
While Secretive uses the Secure Enclave for key storage, it still relies on Keychain APIs to access them. Keychain restricts reads of keys to the app (and specifically, the bundle ID) that created them. If you build Secretive from source, make sure you are consistent in which bundle ID you use so that the Keychain is able to locate your keys.
|
While Secretive uses the Secure Enclave to protect keys, it still relies on Keychain APIs to store and access them. Keychain restricts reads of keys to the app (and specifically, the bundle ID) that created them. If you build Secretive from source, make sure you are consistent in which bundle ID you use so that the Keychain is able to locate your keys.
|
||||||
|
|
||||||
### Backups and Transfers to New Machines
|
### Backups and Transfers to New Machines
|
||||||
|
|
||||||
@@ -58,4 +61,12 @@ Because secrets in the Secure Enclave are not exportable, they are not able to b
|
|||||||
|
|
||||||
## Security
|
## Security
|
||||||
|
|
||||||
If you discover any vulnerabilities in this project, please notify [max.goedjen@gmail.com](mailto:max.goedjen@gmail.com) with the subject containing "SECRETIVE SECURITY."
|
Secretive's security policy is detailed in [SECURITY.md](SECURITY.md). To report security issues, please use [GitHub's private reporting feature.](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability)
|
||||||
|
|
||||||
|
## Acknowledgements
|
||||||
|
|
||||||
|
### sekey
|
||||||
|
Secretive was inspired by the [sekey project](https://github.com/sekey/sekey).
|
||||||
|
|
||||||
|
### Localization
|
||||||
|
Secretive is localized to many languages by a generous team of volunteers. To learn more, see [LOCALIZING.md](LOCALIZING.md). Secretive's localization workflow is generously provided by [Crowdin](https://crowdin.com).
|
||||||
|
|||||||
20
SECURITY.md
@@ -1,9 +1,27 @@
|
|||||||
# Security Policy
|
# Security Policy
|
||||||
|
|
||||||
|
## Security Principles
|
||||||
|
|
||||||
|
Secretive is designed with a few general tenets in mind:
|
||||||
|
|
||||||
|
### It's Hard to Leak a Key Secretive Can't Read The Key Material
|
||||||
|
|
||||||
|
Secretive only operates on hardware-backed keys. In general terms, this means that it should be _very_ hard for Secretive to have any sort of bug that causes a key to be shared, because Secretive can't access private key data even if it wants to.
|
||||||
|
|
||||||
|
### Simplicity and Auditability
|
||||||
|
|
||||||
|
Secretive won't expand to have every feature it could possibly have. Part of the goal of the app is that it is possible for consumers to reasonably audit the code, and that often means not implementing features that might be cool, but which would significantly inflate the size of the codebase.
|
||||||
|
|
||||||
|
### Dependencies
|
||||||
|
|
||||||
|
Both in support of the previous principle and to rule out supply chain attacks, Secretive does not rely on any third party dependencies.
|
||||||
|
|
||||||
|
There are limited exceptions to this, particularly in the build process, but the app itself does not depend on any third party code.
|
||||||
|
|
||||||
## Supported Versions
|
## Supported Versions
|
||||||
|
|
||||||
The latest version on the [Releases page](https://github.com/maxgoedjen/secretive/releases) is the only currently supported version.
|
The latest version on the [Releases page](https://github.com/maxgoedjen/secretive/releases) is the only currently supported version.
|
||||||
|
|
||||||
## Reporting a Vulnerability
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
If you discover any vulnerabilities in this project, please notify max.goedjen@gmail.com with the subject containing "SECRETIVE SECURITY."
|
To report security issues, please use [GitHub's private reporting feature.](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability)
|
||||||
|
|||||||
@@ -1,2 +1,3 @@
|
|||||||
CI_VERSION = GITHUB_CI_VERSION
|
CI_VERSION = GITHUB_CI_VERSION
|
||||||
CI_BUILD_NUMBER = GITHUB_BUILD_NUMBER
|
CI_BUILD_NUMBER = GITHUB_BUILD_NUMBER
|
||||||
|
CI_BUILD_LINK = GITHUB_BUILD_URL
|
||||||
|
|||||||
@@ -13,12 +13,24 @@
|
|||||||
},
|
},
|
||||||
"testTargets" : [
|
"testTargets" : [
|
||||||
{
|
{
|
||||||
"enabled" : false,
|
|
||||||
"parallelizable" : true,
|
|
||||||
"target" : {
|
"target" : {
|
||||||
"containerPath" : "container:Secretive.xcodeproj",
|
"containerPath" : "container:Packages",
|
||||||
"identifier" : "50617D9323FCE48E0099B055",
|
"identifier" : "BriefTests",
|
||||||
"name" : "SecretiveTests"
|
"name" : "BriefTests"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"target" : {
|
||||||
|
"containerPath" : "container:Packages",
|
||||||
|
"identifier" : "SecretKitTests",
|
||||||
|
"name" : "SecretKitTests"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"target" : {
|
||||||
|
"containerPath" : "container:Packages",
|
||||||
|
"identifier" : "SecretAgentKitTests",
|
||||||
|
"name" : "SecretAgentKitTests"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
// swift-tools-version:5.5
|
// swift-tools-version:6.2
|
||||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||||
|
|
||||||
import PackageDescription
|
import PackageDescription
|
||||||
|
|
||||||
let package = Package(
|
let package = Package(
|
||||||
name: "SecretivePackages",
|
name: "SecretivePackages",
|
||||||
|
defaultLocalization: "en",
|
||||||
platforms: [
|
platforms: [
|
||||||
.macOS(.v11)
|
.macOS(.v14)
|
||||||
],
|
],
|
||||||
products: [
|
products: [
|
||||||
.library(
|
.library(
|
||||||
@@ -20,51 +21,84 @@ let package = Package(
|
|||||||
targets: ["SmartCardSecretKit"]),
|
targets: ["SmartCardSecretKit"]),
|
||||||
.library(
|
.library(
|
||||||
name: "SecretAgentKit",
|
name: "SecretAgentKit",
|
||||||
targets: ["SecretAgentKit"]),
|
targets: ["SecretAgentKit", "XPCWrappers"]),
|
||||||
.library(
|
.library(
|
||||||
name: "SecretAgentKitHeaders",
|
name: "Common",
|
||||||
targets: ["SecretAgentKitHeaders"]),
|
targets: ["Common"]),
|
||||||
.library(
|
.library(
|
||||||
name: "Brief",
|
name: "Brief",
|
||||||
targets: ["Brief"]),
|
targets: ["Brief"]),
|
||||||
|
.library(
|
||||||
|
name: "XPCWrappers",
|
||||||
|
targets: ["XPCWrappers"]),
|
||||||
],
|
],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
],
|
],
|
||||||
targets: [
|
targets: [
|
||||||
.target(
|
.target(
|
||||||
name: "SecretKit",
|
name: "SecretKit",
|
||||||
dependencies: []
|
dependencies: [],
|
||||||
|
resources: [localization],
|
||||||
|
swiftSettings: swiftSettings,
|
||||||
),
|
),
|
||||||
.testTarget(
|
.testTarget(
|
||||||
name: "SecretKitTests",
|
name: "SecretKitTests",
|
||||||
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"]
|
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"],
|
||||||
|
swiftSettings: swiftSettings,
|
||||||
),
|
),
|
||||||
.target(
|
.target(
|
||||||
name: "SecureEnclaveSecretKit",
|
name: "SecureEnclaveSecretKit",
|
||||||
dependencies: ["SecretKit"]
|
dependencies: ["SecretKit"],
|
||||||
|
resources: [localization],
|
||||||
|
swiftSettings: swiftSettings,
|
||||||
),
|
),
|
||||||
.target(
|
.target(
|
||||||
name: "SmartCardSecretKit",
|
name: "SmartCardSecretKit",
|
||||||
dependencies: ["SecretKit"]
|
dependencies: ["SecretKit"],
|
||||||
|
resources: [localization],
|
||||||
|
swiftSettings: swiftSettings,
|
||||||
),
|
),
|
||||||
.target(
|
.target(
|
||||||
name: "SecretAgentKit",
|
name: "SecretAgentKit",
|
||||||
dependencies: ["SecretKit", "SecretAgentKitHeaders"]
|
dependencies: ["SecretKit"],
|
||||||
),
|
resources: [localization],
|
||||||
.systemLibrary(
|
swiftSettings: swiftSettings,
|
||||||
name: "SecretAgentKitHeaders"
|
|
||||||
),
|
),
|
||||||
.testTarget(
|
.testTarget(
|
||||||
name: "SecretAgentKitTests",
|
name: "SecretAgentKitTests",
|
||||||
dependencies: ["SecretAgentKit"])
|
dependencies: ["SecretAgentKit"],
|
||||||
,
|
),
|
||||||
|
.target(
|
||||||
|
name: "Common",
|
||||||
|
dependencies: [],
|
||||||
|
resources: [localization],
|
||||||
|
swiftSettings: swiftSettings,
|
||||||
|
),
|
||||||
.target(
|
.target(
|
||||||
name: "Brief",
|
name: "Brief",
|
||||||
dependencies: []
|
dependencies: ["XPCWrappers"],
|
||||||
|
resources: [localization],
|
||||||
|
swiftSettings: swiftSettings,
|
||||||
),
|
),
|
||||||
.testTarget(
|
.testTarget(
|
||||||
name: "BriefTests",
|
name: "BriefTests",
|
||||||
dependencies: ["Brief"]
|
dependencies: ["Brief"],
|
||||||
|
),
|
||||||
|
.target(
|
||||||
|
name: "XPCWrappers",
|
||||||
|
swiftSettings: swiftSettings,
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var localization: Resource {
|
||||||
|
.process("../../Resources/Localizable.xcstrings")
|
||||||
|
}
|
||||||
|
|
||||||
|
var swiftSettings: [PackageDescription.SwiftSetting] {
|
||||||
|
[
|
||||||
|
.swiftLanguageMode(.v6),
|
||||||
|
.treatAllWarnings(as: .error),
|
||||||
|
.strictMemorySafety()
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|||||||
26673
Sources/Packages/Resources/Localizable.xcstrings
Normal file
@@ -1,7 +1,8 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
/// A release is a representation of a downloadable update.
|
/// A release is a representation of a downloadable update.
|
||||||
public struct Release: Codable {
|
public struct Release: Codable, Sendable, Hashable {
|
||||||
|
|
||||||
/// The user-facing name of the release. Typically "Secretive 1.2.3"
|
/// The user-facing name of the release. Typically "Secretive 1.2.3"
|
||||||
public let name: String
|
public let name: String
|
||||||
@@ -15,6 +16,8 @@ public struct Release: Codable {
|
|||||||
/// A user-facing description of the contents of the update.
|
/// A user-facing description of the contents of the update.
|
||||||
public let body: String
|
public let body: String
|
||||||
|
|
||||||
|
public let attributedBody: AttributedString
|
||||||
|
|
||||||
/// Initializes a Release.
|
/// Initializes a Release.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - name: The user-facing name of the release.
|
/// - name: The user-facing name of the release.
|
||||||
@@ -26,6 +29,56 @@ public struct Release: Codable {
|
|||||||
self.prerelease = prerelease
|
self.prerelease = prerelease
|
||||||
self.html_url = html_url
|
self.html_url = html_url
|
||||||
self.body = body
|
self.body = body
|
||||||
|
self.attributedBody = AttributedString(_markdown: body)
|
||||||
|
}
|
||||||
|
|
||||||
|
public init(_ release: GitHubRelease) {
|
||||||
|
self.name = release.name
|
||||||
|
self.prerelease = release.prerelease
|
||||||
|
self.html_url = release.html_url
|
||||||
|
self.body = release.body
|
||||||
|
self.attributedBody = AttributedString(_markdown: release.body)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct GitHubRelease: Codable, Sendable {
|
||||||
|
let name: String
|
||||||
|
let prerelease: Bool
|
||||||
|
let html_url: URL
|
||||||
|
let body: String
|
||||||
|
}
|
||||||
|
|
||||||
|
fileprivate extension AttributedString {
|
||||||
|
|
||||||
|
init(_markdown markdown: String) {
|
||||||
|
let split = markdown.split(whereSeparator: \.isNewline)
|
||||||
|
let lines = split
|
||||||
|
.compactMap {
|
||||||
|
try? AttributedString(markdown: String($0), options: .init(allowsExtendedAttributes: true, interpretedSyntax: .full))
|
||||||
|
}
|
||||||
|
.map { (string: AttributedString) in
|
||||||
|
guard case let .header(level) = string.runs.first?.presentationIntent?.components.first?.kind else { return string }
|
||||||
|
return AttributedString("\n") + string
|
||||||
|
.transformingAttributes(\.font) { font in
|
||||||
|
font.value = switch level {
|
||||||
|
case 2: .headline.bold()
|
||||||
|
case 3: .headline
|
||||||
|
default: .subheadline
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.transformingAttributes(\.underlineStyle) { underline in
|
||||||
|
underline.value = switch level {
|
||||||
|
case 2: .single
|
||||||
|
default: .none
|
||||||
|
}
|
||||||
|
}
|
||||||
|
+ AttributedString("\n")
|
||||||
|
}
|
||||||
|
self = lines.reduce(into: AttributedString()) { partialResult, next in
|
||||||
|
partialResult.append(next)
|
||||||
|
partialResult.append(AttributedString("\n"))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,24 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
/// A representation of a Semantic Version.
|
/// A representation of a Semantic Version.
|
||||||
public struct SemVer {
|
public struct SemVer: Sendable {
|
||||||
|
|
||||||
/// The SemVer broken into an array of integers.
|
/// The SemVer broken into an array of integers.
|
||||||
let versionNumbers: [Int]
|
let versionNumbers: [Int]
|
||||||
|
public let previewDescription: String?
|
||||||
|
|
||||||
|
public var isTestBuild: Bool {
|
||||||
|
versionNumbers == [0, 0, 0]
|
||||||
|
}
|
||||||
|
|
||||||
/// Initializes a SemVer from a string representation.
|
/// Initializes a SemVer from a string representation.
|
||||||
/// - Parameter version: A string representation of the SemVer, formatted as "major.minor.patch".
|
/// - Parameter version: A string representation of the SemVer, formatted as "major.minor.patch".
|
||||||
public init(_ version: String) {
|
public init(_ version: String) {
|
||||||
// Betas have the format 1.2.3_beta1
|
// Betas have the format 1.2.3_beta1
|
||||||
let strippedBeta = version.split(separator: "_").first!
|
// Nightlies have the format 0.0.0_nightly-2025-09-03
|
||||||
|
let splitFull = version.split(separator: "_")
|
||||||
|
let strippedBeta = splitFull.first!
|
||||||
|
previewDescription = splitFull.count > 1 ? String(splitFull[1]) : nil
|
||||||
var split = strippedBeta.split(separator: ".").compactMap { Int($0) }
|
var split = strippedBeta.split(separator: ".").compactMap { Int($0) }
|
||||||
while split.count < 3 {
|
while split.count < 3 {
|
||||||
split.append(0)
|
split.append(0)
|
||||||
@@ -22,6 +30,7 @@ public struct SemVer {
|
|||||||
/// - Parameter version: An `OperatingSystemVersion` representation of the SemVer.
|
/// - Parameter version: An `OperatingSystemVersion` representation of the SemVer.
|
||||||
public init(_ version: OperatingSystemVersion) {
|
public init(_ version: OperatingSystemVersion) {
|
||||||
versionNumbers = [version.majorVersion, version.minorVersion, version.patchVersion]
|
versionNumbers = [version.majorVersion, version.minorVersion, version.patchVersion]
|
||||||
|
previewDescription = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,24 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
import Observation
|
||||||
|
import XPCWrappers
|
||||||
|
|
||||||
/// A concrete implementation of ``UpdaterProtocol`` which considers the current release and OS version.
|
/// A concrete implementation of ``UpdaterProtocol`` which considers the current release and OS version.
|
||||||
public class Updater: ObservableObject, UpdaterProtocol {
|
@Observable public final class Updater: UpdaterProtocol, Sendable {
|
||||||
|
|
||||||
@Published public var update: Release?
|
private let state = State()
|
||||||
public let testBuild: Bool
|
@MainActor @Observable public final class State {
|
||||||
|
var update: Release? = nil
|
||||||
|
nonisolated init() {}
|
||||||
|
}
|
||||||
|
public var update: Release? {
|
||||||
|
state.update
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current version of the app that is running.
|
||||||
|
public let currentVersion: SemVer
|
||||||
|
|
||||||
/// The current OS version.
|
/// The current OS version.
|
||||||
private let osVersion: SemVer
|
private let osVersion: SemVer
|
||||||
/// The current version of the app that is running.
|
|
||||||
private let currentVersion: SemVer
|
|
||||||
|
|
||||||
/// Initializes an Updater.
|
/// Initializes an Updater.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
@@ -18,36 +26,40 @@ public class Updater: ObservableObject, UpdaterProtocol {
|
|||||||
/// - checkFrequency: The interval at which the Updater should check for updates. Subject to a tolerance of 1 hour.
|
/// - checkFrequency: The interval at which the Updater should check for updates. Subject to a tolerance of 1 hour.
|
||||||
/// - osVersion: The current OS version.
|
/// - osVersion: The current OS version.
|
||||||
/// - currentVersion: The current version of the app that is running.
|
/// - currentVersion: The current version of the app that is running.
|
||||||
public init(checkOnLaunch: Bool, checkFrequency: TimeInterval = Measurement(value: 24, unit: UnitDuration.hours).converted(to: .seconds).value, osVersion: SemVer = SemVer(ProcessInfo.processInfo.operatingSystemVersion), currentVersion: SemVer = SemVer(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0")) {
|
public init(
|
||||||
|
checkOnLaunch: Bool,
|
||||||
|
checkFrequency: TimeInterval = Measurement(value: 24, unit: UnitDuration.hours).converted(to: .seconds).value,
|
||||||
|
osVersion: SemVer = SemVer(ProcessInfo.processInfo.operatingSystemVersion),
|
||||||
|
currentVersion: SemVer = SemVer(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0")
|
||||||
|
) {
|
||||||
self.osVersion = osVersion
|
self.osVersion = osVersion
|
||||||
self.currentVersion = currentVersion
|
self.currentVersion = currentVersion
|
||||||
testBuild = currentVersion == SemVer("0.0.0")
|
Task {
|
||||||
if checkOnLaunch {
|
if checkOnLaunch {
|
||||||
// Don't do a launch check if the user hasn't seen the setup prompt explaining updater yet.
|
try await checkForUpdates()
|
||||||
checkForUpdates()
|
}
|
||||||
|
while !Task.isCancelled {
|
||||||
|
try? await Task.sleep(for: .seconds(Int(checkFrequency)))
|
||||||
|
try await checkForUpdates()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let timer = Timer.scheduledTimer(withTimeInterval: checkFrequency, repeats: true) { _ in
|
|
||||||
self.checkForUpdates()
|
|
||||||
}
|
|
||||||
timer.tolerance = 60*60
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Manually trigger an update check.
|
/// Manually trigger an update check.
|
||||||
public func checkForUpdates() {
|
public func checkForUpdates() async throws {
|
||||||
URLSession.shared.dataTask(with: Constants.updateURL) { data, _, _ in
|
let session = try await XPCTypedSession<[Release], Never>(serviceName: "com.maxgoedjen.Secretive.SecretiveUpdater")
|
||||||
guard let data = data else { return }
|
await evaluate(releases: try await session.send())
|
||||||
guard let releases = try? JSONDecoder().decode([Release].self, from: data) else { return }
|
session.complete()
|
||||||
self.evaluate(releases: releases)
|
|
||||||
}.resume()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Ignores a specified release. `update` will be nil if the user has ignored the latest available release.
|
/// Ignores a specified release. `update` will be nil if the user has ignored the latest available release.
|
||||||
/// - Parameter release: The release to ignore.
|
/// - Parameter release: The release to ignore.
|
||||||
public func ignore(release: Release) {
|
public func ignore(release: Release) async {
|
||||||
guard !release.critical else { return }
|
guard !release.critical else { return }
|
||||||
defaults.set(true, forKey: release.name)
|
defaults.set(true, forKey: release.name)
|
||||||
DispatchQueue.main.async {
|
await MainActor.run {
|
||||||
self.update = nil
|
state.update = nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +69,7 @@ extension Updater {
|
|||||||
|
|
||||||
/// Evaluates the available downloadable releases, and selects the newest non-prerelease release that the user is able to run.
|
/// Evaluates the available downloadable releases, and selects the newest non-prerelease release that the user is able to run.
|
||||||
/// - Parameter releases: An array of ``Release`` objects.
|
/// - Parameter releases: An array of ``Release`` objects.
|
||||||
func evaluate(releases: [Release]) {
|
func evaluate(releases: [Release]) async {
|
||||||
guard let release = releases
|
guard let release = releases
|
||||||
.sorted()
|
.sorted()
|
||||||
.reversed()
|
.reversed()
|
||||||
@@ -67,8 +79,8 @@ extension Updater {
|
|||||||
guard !release.prerelease else { return }
|
guard !release.prerelease else { return }
|
||||||
let latestVersion = SemVer(release.name)
|
let latestVersion = SemVer(release.name)
|
||||||
if latestVersion > currentVersion {
|
if latestVersion > currentVersion {
|
||||||
DispatchQueue.main.async {
|
await MainActor.run {
|
||||||
self.update = release
|
state.update = release
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -87,11 +99,3 @@ extension Updater {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Updater {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
static let updateURL = URL(string: "https://api.github.com/repos/maxgoedjen/secretive/releases")!
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
/// A protocol for retreiving the latest available version of an app.
|
/// A protocol for retreiving the latest available version of an app.
|
||||||
public protocol UpdaterProtocol: ObservableObject {
|
public protocol UpdaterProtocol: Observable, Sendable {
|
||||||
|
|
||||||
/// The latest update
|
/// The latest update
|
||||||
var update: Release? { get }
|
@MainActor var update: Release? { get }
|
||||||
/// A boolean describing whether or not the current build of the app is a "test" build (ie, a debug build or otherwise special build)
|
|
||||||
var testBuild: Bool { get }
|
|
||||||
|
|
||||||
|
var currentVersion: SemVer { get }
|
||||||
|
|
||||||
|
func ignore(release: Release) async
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
11
Sources/Packages/Sources/Common/BundleIDs.swift
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
extension Bundle {
|
||||||
|
public static var agentBundleID: String {
|
||||||
|
Bundle.main.bundleIdentifier!.replacingOccurrences(of: "Host", with: "SecretAgent")
|
||||||
|
}
|
||||||
|
|
||||||
|
public static var hostBundleID: String {
|
||||||
|
Bundle.main.bundleIdentifier!.replacingOccurrences(of: "SecretAgent", with: "Host")
|
||||||
|
}
|
||||||
|
}
|
||||||
29
Sources/Packages/Sources/Common/URLs.swift
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
extension URL {
|
||||||
|
|
||||||
|
public static var agentHomeURL: URL {
|
||||||
|
URL(fileURLWithPath: URL.homeDirectory.path().replacingOccurrences(of: Bundle.hostBundleID, with: Bundle.agentBundleID))
|
||||||
|
}
|
||||||
|
|
||||||
|
public static var socketPath: String {
|
||||||
|
#if DEBUG
|
||||||
|
URL.agentHomeURL.appendingPathComponent("socket-debug.ssh").path()
|
||||||
|
#else
|
||||||
|
URL.agentHomeURL.appendingPathComponent("socket.ssh").path()
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension String {
|
||||||
|
|
||||||
|
public var normalizedPathAndFolder: (String, String) {
|
||||||
|
// All foundation-based normalization methods replace this with the container directly.
|
||||||
|
let processedPath = replacingOccurrences(of: "~", with: "/Users/\(NSUserName())")
|
||||||
|
let url = URL(filePath: processedPath)
|
||||||
|
let folder = url.deletingLastPathComponent().path()
|
||||||
|
return (processedPath, folder)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -5,68 +5,58 @@ import SecretKit
|
|||||||
import AppKit
|
import AppKit
|
||||||
|
|
||||||
/// The `Agent` is an implementation of an SSH agent. It manages coordination and access between a socket, traces requests, notifies witnesses and passes requests to stores.
|
/// The `Agent` is an implementation of an SSH agent. It manages coordination and access between a socket, traces requests, notifies witnesses and passes requests to stores.
|
||||||
public class Agent {
|
public final class Agent: Sendable {
|
||||||
|
|
||||||
private let storeList: SecretStoreList
|
private let storeList: SecretStoreList
|
||||||
private let witness: SigningWitness?
|
private let witness: SigningWitness?
|
||||||
private let writer = OpenSSHKeyWriter()
|
private let publicKeyWriter = OpenSSHPublicKeyWriter()
|
||||||
private let requestTracer = SigningRequestTracer()
|
private let signatureWriter = OpenSSHSignatureWriter()
|
||||||
|
private let certificateHandler = OpenSSHCertificateHandler()
|
||||||
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "Agent")
|
||||||
|
|
||||||
/// Initializes an agent with a store list and a witness.
|
/// Initializes an agent with a store list and a witness.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - storeList: The `SecretStoreList` to make available.
|
/// - storeList: The `SecretStoreList` to make available.
|
||||||
/// - witness: A witness to notify of requests.
|
/// - witness: A witness to notify of requests.
|
||||||
public init(storeList: SecretStoreList, witness: SigningWitness? = nil) {
|
public init(storeList: SecretStoreList, witness: SigningWitness? = nil) {
|
||||||
Logger().debug("Agent is running")
|
logger.debug("Agent is running")
|
||||||
self.storeList = storeList
|
self.storeList = storeList
|
||||||
self.witness = witness
|
self.witness = witness
|
||||||
|
Task { @MainActor in
|
||||||
|
await certificateHandler.reloadCertificates(for: storeList.allSecrets)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Agent {
|
extension Agent {
|
||||||
|
|
||||||
/// Handles an incoming request.
|
public func handle(request: SSHAgent.Request, provenance: SigningRequestProvenance) async -> Data {
|
||||||
/// - Parameters:
|
// Depending on the launch context (such as after macOS update), the agent may need to reload secrets before acting
|
||||||
/// - reader: A ``FileHandleReader`` to read the content of the request.
|
await reloadSecretsIfNeccessary()
|
||||||
/// - writer: A ``FileHandleWriter`` to write the response to.
|
|
||||||
public func handle(reader: FileHandleReader, writer: FileHandleWriter) {
|
|
||||||
Logger().debug("Agent handling new data")
|
|
||||||
let data = Data(reader.availableData)
|
|
||||||
guard data.count > 4 else { return }
|
|
||||||
let requestTypeInt = data[4]
|
|
||||||
guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else {
|
|
||||||
writer.write(OpenSSHKeyWriter().lengthAndData(of: SSHAgent.ResponseType.agentFailure.data))
|
|
||||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
Logger().debug("Agent handling request of type \(requestType.debugDescription)")
|
|
||||||
let subData = Data(data[5...])
|
|
||||||
let response = handle(requestType: requestType, data: subData, reader: reader)
|
|
||||||
writer.write(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) -> Data {
|
|
||||||
var response = Data()
|
var response = Data()
|
||||||
do {
|
do {
|
||||||
switch requestType {
|
switch request {
|
||||||
case .requestIdentities:
|
case .requestIdentities:
|
||||||
response.append(SSHAgent.ResponseType.agentIdentitiesAnswer.data)
|
response.append(SSHAgent.Response.agentIdentitiesAnswer.data)
|
||||||
response.append(identities())
|
response.append(await identities())
|
||||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)")
|
logger.debug("Agent returned \(SSHAgent.Response.agentIdentitiesAnswer.debugDescription)")
|
||||||
case .signRequest:
|
case .signRequest(let context):
|
||||||
let provenance = requestTracer.provenance(from: reader)
|
response.append(SSHAgent.Response.agentSignResponse.data)
|
||||||
response.append(SSHAgent.ResponseType.agentSignResponse.data)
|
response.append(try await sign(data: context.dataToSign, keyBlob: context.keyBlob, provenance: provenance))
|
||||||
response.append(try sign(data: data, provenance: provenance))
|
logger.debug("Agent returned \(SSHAgent.Response.agentSignResponse.debugDescription)")
|
||||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentSignResponse.debugDescription)")
|
case .unknown(let value):
|
||||||
|
logger.error("Agent received unknown request of type \(value).")
|
||||||
|
throw UnhandledRequestError()
|
||||||
|
default:
|
||||||
|
logger.debug("Agent received valid request of type \(request.debugDescription), but not currently supported.")
|
||||||
|
throw UnhandledRequestError()
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
response.removeAll()
|
response = SSHAgent.Response.agentFailure.data
|
||||||
response.append(SSHAgent.ResponseType.agentFailure.data)
|
logger.debug("Agent returned \(SSHAgent.Response.agentFailure.debugDescription)")
|
||||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
|
|
||||||
}
|
}
|
||||||
let full = OpenSSHKeyWriter().lengthAndData(of: response)
|
return response.lengthAndData
|
||||||
return full
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -75,19 +65,27 @@ extension Agent {
|
|||||||
|
|
||||||
/// Lists the identities available for signing operations
|
/// Lists the identities available for signing operations
|
||||||
/// - Returns: An OpenSSH formatted Data payload listing the identities available for signing operations.
|
/// - Returns: An OpenSSH formatted Data payload listing the identities available for signing operations.
|
||||||
func identities() -> Data {
|
func identities() async -> Data {
|
||||||
let secrets = storeList.stores.flatMap(\.secrets)
|
let secrets = await storeList.allSecrets
|
||||||
var count = UInt32(secrets.count).bigEndian
|
await certificateHandler.reloadCertificates(for: secrets)
|
||||||
let countData = Data(bytes: &count, count: UInt32.bitWidth/8)
|
var count = 0
|
||||||
var keyData = Data()
|
var keyData = Data()
|
||||||
let writer = OpenSSHKeyWriter()
|
|
||||||
for secret in secrets {
|
for secret in secrets {
|
||||||
let keyBlob = writer.data(secret: secret)
|
let keyBlob = publicKeyWriter.data(secret: secret)
|
||||||
keyData.append(writer.lengthAndData(of: keyBlob))
|
keyData.append(keyBlob.lengthAndData)
|
||||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
keyData.append(publicKeyWriter.comment(secret: secret).lengthAndData)
|
||||||
keyData.append(writer.lengthAndData(of: curveData))
|
count += 1
|
||||||
|
|
||||||
|
if let (certificateData, name) = try? await certificateHandler.keyBlobAndName(for: secret) {
|
||||||
|
keyData.append(certificateData.lengthAndData)
|
||||||
|
keyData.append(name.lengthAndData)
|
||||||
|
count += 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Logger().debug("Agent enumerated \(secrets.count) identities")
|
logger.log("Agent enumerated \(count) identities")
|
||||||
|
var countBigEndian = UInt32(count).bigEndian
|
||||||
|
let countData = unsafe Data(bytes: &countBigEndian, count: MemoryLayout<UInt32>.size)
|
||||||
return countData + keyData
|
return countData + keyData
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,65 +94,21 @@ extension Agent {
|
|||||||
/// - data: The data to sign.
|
/// - data: The data to sign.
|
||||||
/// - provenance: A ``SecretKit.SigningRequestProvenance`` object describing the origin of the request.
|
/// - provenance: A ``SecretKit.SigningRequestProvenance`` object describing the origin of the request.
|
||||||
/// - Returns: An OpenSSH formatted Data payload containing the signed data response.
|
/// - Returns: An OpenSSH formatted Data payload containing the signed data response.
|
||||||
func sign(data: Data, provenance: SigningRequestProvenance) throws -> Data {
|
func sign(data: Data, keyBlob: Data, provenance: SigningRequestProvenance) async throws -> Data {
|
||||||
let reader = OpenSSHReader(data: data)
|
guard let (secret, store) = await secret(matching: keyBlob) else {
|
||||||
let hash = reader.readNextChunk()
|
let keyBlobHex = keyBlob.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }.joined()
|
||||||
guard let (store, secret) = secret(matching: hash) else {
|
logger.debug("Agent did not have a key matching \(keyBlobHex)")
|
||||||
Logger().debug("Agent did not have a key matching \(hash as NSData)")
|
throw NoMatchingKeyError()
|
||||||
throw AgentError.noMatchingKey
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let witness = witness {
|
try await witness?.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
|
||||||
try witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
|
|
||||||
}
|
|
||||||
|
|
||||||
let dataToSign = reader.readNextChunk()
|
let rawRepresentation = try await store.sign(data: data, with: secret, for: provenance)
|
||||||
let signed = try store.sign(data: dataToSign, with: secret, for: provenance)
|
let signedData = signatureWriter.data(secret: secret, signature: rawRepresentation)
|
||||||
let derSignature = signed.data
|
|
||||||
|
|
||||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
try await witness?.witness(accessTo: secret, from: store, by: provenance)
|
||||||
|
|
||||||
// Convert from DER formatted rep to raw (r||s)
|
logger.debug("Agent signed request")
|
||||||
|
|
||||||
let rawRepresentation: Data
|
|
||||||
switch (secret.algorithm, secret.keySize) {
|
|
||||||
case (.ellipticCurve, 256):
|
|
||||||
rawRepresentation = try CryptoKit.P256.Signing.ECDSASignature(derRepresentation: derSignature).rawRepresentation
|
|
||||||
case (.ellipticCurve, 384):
|
|
||||||
rawRepresentation = try CryptoKit.P384.Signing.ECDSASignature(derRepresentation: derSignature).rawRepresentation
|
|
||||||
default:
|
|
||||||
throw AgentError.unsupportedKeyType
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
let rawLength = rawRepresentation.count/2
|
|
||||||
// Check if we need to pad with 0x00 to prevent certain
|
|
||||||
// ssh servers from thinking r or s is negative
|
|
||||||
let paddingRange: ClosedRange<UInt8> = 0x80...0xFF
|
|
||||||
var r = Data(rawRepresentation[0..<rawLength])
|
|
||||||
if paddingRange ~= r.first! {
|
|
||||||
r.insert(0x00, at: 0)
|
|
||||||
}
|
|
||||||
var s = Data(rawRepresentation[rawLength...])
|
|
||||||
if paddingRange ~= s.first! {
|
|
||||||
s.insert(0x00, at: 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
var signatureChunk = Data()
|
|
||||||
signatureChunk.append(writer.lengthAndData(of: r))
|
|
||||||
signatureChunk.append(writer.lengthAndData(of: s))
|
|
||||||
|
|
||||||
var signedData = Data()
|
|
||||||
var sub = Data()
|
|
||||||
sub.append(writer.lengthAndData(of: curveData))
|
|
||||||
sub.append(writer.lengthAndData(of: signatureChunk))
|
|
||||||
signedData.append(writer.lengthAndData(of: sub))
|
|
||||||
|
|
||||||
if let witness = witness {
|
|
||||||
try witness.witness(accessTo: secret, from: store, by: provenance, requiredAuthentication: signed.requiredAuthentication)
|
|
||||||
}
|
|
||||||
|
|
||||||
Logger().debug("Agent signed request")
|
|
||||||
|
|
||||||
return signedData
|
return signedData
|
||||||
}
|
}
|
||||||
@@ -163,19 +117,24 @@ extension Agent {
|
|||||||
|
|
||||||
extension Agent {
|
extension Agent {
|
||||||
|
|
||||||
|
/// Gives any store with no loaded secrets a chance to reload.
|
||||||
|
func reloadSecretsIfNeccessary() async {
|
||||||
|
for store in await storeList.stores {
|
||||||
|
if await store.secrets.isEmpty {
|
||||||
|
let name = await store.name
|
||||||
|
logger.debug("Store \(name, privacy: .public) has no loaded secrets. Reloading.")
|
||||||
|
await store.reloadSecrets()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Finds a ``Secret`` matching a specified hash whos signature was requested.
|
/// Finds a ``Secret`` matching a specified hash whos signature was requested.
|
||||||
/// - Parameter hash: The hash to match against.
|
/// - Parameter hash: The hash to match against.
|
||||||
/// - Returns: A ``Secret`` and the ``SecretStore`` containing it, if a match is found.
|
/// - Returns: A ``Secret`` and the ``SecretStore`` containing it, if a match is found.
|
||||||
func secret(matching hash: Data) -> (AnySecretStore, AnySecret)? {
|
func secret(matching hash: Data) async -> (AnySecret, AnySecretStore)? {
|
||||||
storeList.stores.compactMap { store -> (AnySecretStore, AnySecret)? in
|
await storeList.allSecretsWithStores.first {
|
||||||
let allMatching = store.secrets.filter { secret in
|
hash == publicKeyWriter.data(secret: $0.0)
|
||||||
hash == writer.data(secret: secret)
|
}
|
||||||
}
|
|
||||||
if let matching = allMatching.first {
|
|
||||||
return (store, matching)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}.first
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -183,20 +142,16 @@ extension Agent {
|
|||||||
|
|
||||||
extension Agent {
|
extension Agent {
|
||||||
|
|
||||||
/// An error involving agent operations..
|
struct NoMatchingKeyError: Error {}
|
||||||
enum AgentError: Error {
|
struct UnhandledRequestError: Error {}
|
||||||
case unhandledType
|
|
||||||
case noMatchingKey
|
|
||||||
case unsupportedKeyType
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SSHAgent.ResponseType {
|
extension SSHAgent.Response {
|
||||||
|
|
||||||
var data: Data {
|
var data: Data {
|
||||||
var raw = self.rawValue
|
var raw = self.rawValue
|
||||||
return Data(bytes: &raw, count: UInt8.bitWidth/8)
|
return unsafe Data(bytes: &raw, count: MemoryLayout<UInt8>.size)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +1,12 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
/// Protocol abstraction of the reading aspects of FileHandle.
|
extension FileHandle {
|
||||||
public protocol FileHandleReader {
|
|
||||||
|
|
||||||
/// Gets data that is available for reading.
|
|
||||||
var availableData: Data { get }
|
|
||||||
/// A file descriptor of the handle.
|
|
||||||
var fileDescriptor: Int32 { get }
|
|
||||||
/// The process ID of the process coonnected to the other end of the FileHandle.
|
|
||||||
var pidOfConnectedProcess: Int32 { get }
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Protocol abstraction of the writing aspects of FileHandle.
|
|
||||||
public protocol FileHandleWriter {
|
|
||||||
|
|
||||||
/// Writes data to the handle.
|
|
||||||
func write(_ data: Data)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension FileHandle: FileHandleReader, FileHandleWriter {
|
|
||||||
|
|
||||||
public var pidOfConnectedProcess: Int32 {
|
public var pidOfConnectedProcess: Int32 {
|
||||||
let pidPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
|
let pidPointer = UnsafeMutableRawPointer.allocate(byteCount: MemoryLayout<Int32>.size, alignment: 1)
|
||||||
var len = socklen_t(MemoryLayout<Int32>.size)
|
var len = socklen_t(MemoryLayout<Int32>.size)
|
||||||
getsockopt(fileDescriptor, SOCK_STREAM, LOCAL_PEERPID, pidPointer, &len)
|
unsafe getsockopt(fileDescriptor, SOCK_STREAM, LOCAL_PEERPID, pidPointer, &len)
|
||||||
return pidPointer.load(as: Int32.self)
|
return unsafe pidPointer.load(as: Int32.self)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import Foundation
|
||||||
|
import OSLog
|
||||||
|
import SecretKit
|
||||||
|
|
||||||
|
/// Manages storage and lookup for OpenSSH certificates.
|
||||||
|
public actor OpenSSHCertificateHandler: Sendable {
|
||||||
|
|
||||||
|
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: URL.homeDirectory)
|
||||||
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "OpenSSHCertificateHandler")
|
||||||
|
private let writer = OpenSSHPublicKeyWriter()
|
||||||
|
private var keyBlobsAndNames: [AnySecret: (Data, Data)] = [:]
|
||||||
|
|
||||||
|
/// Initializes an OpenSSHCertificateHandler.
|
||||||
|
public init() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reloads any certificates in the PublicKeys folder.
|
||||||
|
/// - Parameter secrets: the secrets to look up corresponding certificates for.
|
||||||
|
public func reloadCertificates(for secrets: [AnySecret]) {
|
||||||
|
guard publicKeyFileStoreController.hasAnyCertificates else {
|
||||||
|
logger.log("No certificates, short circuiting")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
keyBlobsAndNames = secrets.reduce(into: [:]) { partialResult, next in
|
||||||
|
partialResult[next] = try? loadKeyblobAndName(for: next)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
|
||||||
|
/// - Parameter secret: The secret to search for a certificate with
|
||||||
|
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
|
||||||
|
public func keyBlobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
|
||||||
|
keyBlobsAndNames[AnySecret(secret)]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
|
||||||
|
/// - Parameter secret: The secret to search for a certificate with
|
||||||
|
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
|
||||||
|
private func loadKeyblobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
|
||||||
|
let certificatePath = publicKeyFileStoreController.sshCertificatePath(for: secret)
|
||||||
|
guard FileManager.default.fileExists(atPath: certificatePath) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug("Found certificate for \(secret.name)")
|
||||||
|
let certContent = try String(contentsOfFile:certificatePath, encoding: .utf8)
|
||||||
|
let certElements = certContent.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ")
|
||||||
|
|
||||||
|
guard certElements.count >= 2 else {
|
||||||
|
logger.warning("Certificate found for \(secret.name) but failed to load")
|
||||||
|
throw OpenSSHCertificateError.parsingFailed
|
||||||
|
}
|
||||||
|
guard let certDecoded = Data(base64Encoded: certElements[1] as String) else {
|
||||||
|
logger.warning("Certificate found for \(secret.name) but failed to decode base64 key")
|
||||||
|
throw OpenSSHCertificateError.parsingFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
if certElements.count >= 3 {
|
||||||
|
let certName = Data(certElements[2].utf8)
|
||||||
|
return (certDecoded, certName)
|
||||||
|
}
|
||||||
|
let certName = Data(secret.name.utf8)
|
||||||
|
logger.info("Certificate for \(secret.name) does not have a name tag, using secret name instead")
|
||||||
|
return (certDecoded, certName)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OpenSSHCertificateHandler {
|
||||||
|
|
||||||
|
enum OpenSSHCertificateError: LocalizedError {
|
||||||
|
case unsupportedType
|
||||||
|
case parsingFailed
|
||||||
|
case doesNotExist
|
||||||
|
|
||||||
|
public var errorDescription: String? {
|
||||||
|
switch self {
|
||||||
|
case .unsupportedType:
|
||||||
|
return "The key type was unsupported"
|
||||||
|
case .parsingFailed:
|
||||||
|
return "Failed to properly parse the SSH certificate"
|
||||||
|
case .doesNotExist:
|
||||||
|
return "Certificate does not exist"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
47
Sources/Packages/Sources/SecretAgentKit/OpenSSHReader.swift
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Reads OpenSSH protocol data.
|
||||||
|
final class OpenSSHReader {
|
||||||
|
|
||||||
|
var remaining: Data
|
||||||
|
|
||||||
|
/// Initialize the reader with an OpenSSH data payload.
|
||||||
|
/// - Parameter data: The data to read.
|
||||||
|
init(data: Data) {
|
||||||
|
remaining = Data(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the next chunk of data from the playload.
|
||||||
|
/// - Returns: The next chunk of data.
|
||||||
|
func readNextChunk(convertEndianness: Bool = true) throws(OpenSSHReaderError) -> Data {
|
||||||
|
let littleEndianLength = try readNextBytes(as: UInt32.self)
|
||||||
|
let length = convertEndianness ? Int(littleEndianLength.bigEndian) : Int(littleEndianLength)
|
||||||
|
guard remaining.count >= length else { throw .beyondBounds }
|
||||||
|
let dataRange = 0..<length
|
||||||
|
let ret = Data(remaining[dataRange])
|
||||||
|
remaining.removeSubrange(dataRange)
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func readNextBytes<T>(as: T.Type) throws(OpenSSHReaderError) -> T {
|
||||||
|
let size = MemoryLayout<T>.size
|
||||||
|
guard remaining.count >= size else { throw .beyondBounds }
|
||||||
|
let lengthRange = 0..<size
|
||||||
|
let lengthChunk = remaining[lengthRange]
|
||||||
|
remaining.removeSubrange(lengthRange)
|
||||||
|
return unsafe lengthChunk.bytes.unsafeLoad(as: T.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readNextChunkAsString(convertEndianness: Bool = true) throws(OpenSSHReaderError) -> String {
|
||||||
|
try String(decoding: readNextChunk(convertEndianness: convertEndianness), as: UTF8.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readNextChunkAsSubReader(convertEndianness: Bool = true) throws(OpenSSHReaderError) -> OpenSSHReader {
|
||||||
|
OpenSSHReader(data: try readNextChunk(convertEndianness: convertEndianness))
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum OpenSSHReaderError: Error, Codable {
|
||||||
|
case beyondBounds
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import Foundation
|
||||||
|
import OSLog
|
||||||
|
import SecretKit
|
||||||
|
|
||||||
|
public protocol SSHAgentInputParserProtocol {
|
||||||
|
|
||||||
|
func parse(data: Data) async throws -> SSHAgent.Request
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct SSHAgentInputParser: SSHAgentInputParserProtocol {
|
||||||
|
|
||||||
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "InputParser")
|
||||||
|
|
||||||
|
public init() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public func parse(data: Data) throws(AgentParsingError) -> SSHAgent.Request {
|
||||||
|
logger.debug("Parsing new data")
|
||||||
|
guard data.count > 4 else {
|
||||||
|
throw .invalidData
|
||||||
|
}
|
||||||
|
let specifiedLength = unsafe (data[0..<4].bytes.unsafeLoad(as: UInt32.self).bigEndian) + 4
|
||||||
|
let rawRequestInt = data[4]
|
||||||
|
let remainingDataRange = 5..<min(Int(specifiedLength), data.count)
|
||||||
|
lazy var body: Data = { Data(data[remainingDataRange]) }()
|
||||||
|
switch rawRequestInt {
|
||||||
|
case SSHAgent.Request.requestIdentities.protocolID:
|
||||||
|
return .requestIdentities
|
||||||
|
case SSHAgent.Request.signRequest(.empty).protocolID:
|
||||||
|
do {
|
||||||
|
return .signRequest(try signatureRequestContext(from: body))
|
||||||
|
} catch {
|
||||||
|
throw .openSSHReader(error)
|
||||||
|
}
|
||||||
|
case SSHAgent.Request.addIdentity.protocolID:
|
||||||
|
return .addIdentity
|
||||||
|
case SSHAgent.Request.removeIdentity.protocolID:
|
||||||
|
return .removeIdentity
|
||||||
|
case SSHAgent.Request.removeAllIdentities.protocolID:
|
||||||
|
return .removeAllIdentities
|
||||||
|
case SSHAgent.Request.addIDConstrained.protocolID:
|
||||||
|
return .addIDConstrained
|
||||||
|
case SSHAgent.Request.addSmartcardKey.protocolID:
|
||||||
|
return .addSmartcardKey
|
||||||
|
case SSHAgent.Request.removeSmartcardKey.protocolID:
|
||||||
|
return .removeSmartcardKey
|
||||||
|
case SSHAgent.Request.lock.protocolID:
|
||||||
|
return .lock
|
||||||
|
case SSHAgent.Request.unlock.protocolID:
|
||||||
|
return .unlock
|
||||||
|
case SSHAgent.Request.addSmartcardKeyConstrained.protocolID:
|
||||||
|
return .addSmartcardKeyConstrained
|
||||||
|
case SSHAgent.Request.protocolExtension.protocolID:
|
||||||
|
return .protocolExtension
|
||||||
|
default:
|
||||||
|
return .unknown(rawRequestInt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SSHAgentInputParser {
|
||||||
|
|
||||||
|
func signatureRequestContext(from data: Data) throws(OpenSSHReaderError) -> SSHAgent.Request.SignatureRequestContext {
|
||||||
|
let reader = OpenSSHReader(data: data)
|
||||||
|
let rawKeyBlob = try reader.readNextChunk()
|
||||||
|
let keyBlob = certificatePublicKeyBlob(from: rawKeyBlob) ?? rawKeyBlob
|
||||||
|
let dataToSign = try reader.readNextChunk()
|
||||||
|
return SSHAgent.Request.SignatureRequestContext(keyBlob: keyBlob, dataToSign: dataToSign)
|
||||||
|
}
|
||||||
|
|
||||||
|
func certificatePublicKeyBlob(from hash: Data) -> Data? {
|
||||||
|
let reader = OpenSSHReader(data: hash)
|
||||||
|
do {
|
||||||
|
let certType = String(decoding: try reader.readNextChunk(), as: UTF8.self)
|
||||||
|
switch certType {
|
||||||
|
case "ecdsa-sha2-nistp256-cert-v01@openssh.com",
|
||||||
|
"ecdsa-sha2-nistp384-cert-v01@openssh.com",
|
||||||
|
"ecdsa-sha2-nistp521-cert-v01@openssh.com":
|
||||||
|
_ = try reader.readNextChunk() // nonce
|
||||||
|
let curveIdentifier = try reader.readNextChunk()
|
||||||
|
let publicKey = try reader.readNextChunk()
|
||||||
|
let openSSHIdentifier = certType.replacingOccurrences(of: "-cert-v01@openssh.com", with: "")
|
||||||
|
return openSSHIdentifier.lengthAndData +
|
||||||
|
curveIdentifier.lengthAndData +
|
||||||
|
publicKey.lengthAndData
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
extension SSHAgentInputParser {
|
||||||
|
|
||||||
|
public enum AgentParsingError: Error, Codable {
|
||||||
|
case unknownRequest
|
||||||
|
case unhandledRequest
|
||||||
|
case invalidData
|
||||||
|
case openSSHReader(OpenSSHReaderError)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,41 +1,97 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
/// A namespace for the SSH Agent Protocol, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html
|
/// A namespace for the SSH Agent Protocol, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||||
public enum SSHAgent {}
|
public enum SSHAgent {}
|
||||||
|
|
||||||
extension SSHAgent {
|
extension SSHAgent {
|
||||||
|
|
||||||
/// The type of the SSH Agent Request, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html#rfc.section.5.1
|
/// The type of the SSH Agent Request, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||||
public enum RequestType: UInt8, CustomDebugStringConvertible {
|
public enum Request: CustomDebugStringConvertible, Codable, Sendable {
|
||||||
|
|
||||||
case requestIdentities = 11
|
case requestIdentities
|
||||||
case signRequest = 13
|
case signRequest(SignatureRequestContext)
|
||||||
|
case addIdentity
|
||||||
|
case removeIdentity
|
||||||
|
case removeAllIdentities
|
||||||
|
case addIDConstrained
|
||||||
|
case addSmartcardKey
|
||||||
|
case removeSmartcardKey
|
||||||
|
case lock
|
||||||
|
case unlock
|
||||||
|
case addSmartcardKeyConstrained
|
||||||
|
case protocolExtension
|
||||||
|
case unknown(UInt8)
|
||||||
|
|
||||||
public var debugDescription: String {
|
public var protocolID: UInt8 {
|
||||||
switch self {
|
switch self {
|
||||||
case .requestIdentities:
|
case .requestIdentities: 11
|
||||||
return "RequestIdentities"
|
case .signRequest: 13
|
||||||
case .signRequest:
|
case .addIdentity: 17
|
||||||
return "SignRequest"
|
case .removeIdentity: 18
|
||||||
|
case .removeAllIdentities: 19
|
||||||
|
case .addIDConstrained: 25
|
||||||
|
case .addSmartcardKey: 20
|
||||||
|
case .removeSmartcardKey: 21
|
||||||
|
case .lock: 22
|
||||||
|
case .unlock: 23
|
||||||
|
case .addSmartcardKeyConstrained: 26
|
||||||
|
case .protocolExtension: 27
|
||||||
|
case .unknown(let value): value
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// The type of the SSH Agent Response, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html#rfc.section.5.1
|
|
||||||
public enum ResponseType: UInt8, CustomDebugStringConvertible {
|
|
||||||
|
|
||||||
case agentFailure = 5
|
|
||||||
case agentIdentitiesAnswer = 12
|
|
||||||
case agentSignResponse = 14
|
|
||||||
|
|
||||||
public var debugDescription: String {
|
public var debugDescription: String {
|
||||||
switch self {
|
switch self {
|
||||||
case .agentFailure:
|
case .requestIdentities: "SSH_AGENTC_REQUEST_IDENTITIES"
|
||||||
return "AgentFailure"
|
case .signRequest: "SSH_AGENTC_SIGN_REQUEST"
|
||||||
case .agentIdentitiesAnswer:
|
case .addIdentity: "SSH_AGENTC_ADD_IDENTITY"
|
||||||
return "AgentIdentitiesAnswer"
|
case .removeIdentity: "SSH_AGENTC_REMOVE_IDENTITY"
|
||||||
case .agentSignResponse:
|
case .removeAllIdentities: "SSH_AGENTC_REMOVE_ALL_IDENTITIES"
|
||||||
return "AgentSignResponse"
|
case .addIDConstrained: "SSH_AGENTC_ADD_ID_CONSTRAINED"
|
||||||
|
case .addSmartcardKey: "SSH_AGENTC_ADD_SMARTCARD_KEY"
|
||||||
|
case .removeSmartcardKey: "SSH_AGENTC_REMOVE_SMARTCARD_KEY"
|
||||||
|
case .lock: "SSH_AGENTC_LOCK"
|
||||||
|
case .unlock: "SSH_AGENTC_UNLOCK"
|
||||||
|
case .addSmartcardKeyConstrained: "SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED"
|
||||||
|
case .protocolExtension: "SSH_AGENTC_EXTENSION"
|
||||||
|
case .unknown: "UNKNOWN_MESSAGE"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct SignatureRequestContext: Sendable, Codable {
|
||||||
|
public let keyBlob: Data
|
||||||
|
public let dataToSign: Data
|
||||||
|
|
||||||
|
public init(keyBlob: Data, dataToSign: Data) {
|
||||||
|
self.keyBlob = keyBlob
|
||||||
|
self.dataToSign = dataToSign
|
||||||
|
}
|
||||||
|
|
||||||
|
public static var empty: SignatureRequestContext {
|
||||||
|
SignatureRequestContext(keyBlob: Data(), dataToSign: Data())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The type of the SSH Agent Response, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||||
|
public enum Response: UInt8, CustomDebugStringConvertible {
|
||||||
|
|
||||||
|
case agentFailure = 5
|
||||||
|
case agentSuccess = 6
|
||||||
|
case agentIdentitiesAnswer = 12
|
||||||
|
case agentSignResponse = 14
|
||||||
|
case agentExtensionFailure = 28
|
||||||
|
case agentExtensionResponse = 29
|
||||||
|
|
||||||
|
public var debugDescription: String {
|
||||||
|
switch self {
|
||||||
|
case .agentFailure: "SSH_AGENT_FAILURE"
|
||||||
|
case .agentSuccess: "SSH_AGENT_SUCCESS"
|
||||||
|
case .agentIdentitiesAnswer: "SSH_AGENT_IDENTITIES_ANSWER"
|
||||||
|
case .agentSignResponse: "SSH_AGENT_SIGN_RESPONSE"
|
||||||
|
case .agentExtensionFailure: "SSH_AGENT_EXTENSION_FAILURE"
|
||||||
|
case .agentExtensionResponse: "SSH_AGENT_EXTENSION_RESPONSE"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import Foundation
|
|||||||
import AppKit
|
import AppKit
|
||||||
import Security
|
import Security
|
||||||
import SecretKit
|
import SecretKit
|
||||||
import SecretAgentKitHeaders
|
|
||||||
|
|
||||||
/// An object responsible for generating ``SecretKit.SigningRequestProvenance`` objects.
|
/// An object responsible for generating ``SecretKit.SigningRequestProvenance`` objects.
|
||||||
struct SigningRequestTracer {
|
struct SigningRequestTracer {
|
||||||
@@ -10,12 +9,11 @@ struct SigningRequestTracer {
|
|||||||
|
|
||||||
extension SigningRequestTracer {
|
extension SigningRequestTracer {
|
||||||
|
|
||||||
/// Generates a ``SecretKit.SigningRequestProvenance`` from a ``FileHandleReader``.
|
/// Generates a ``SecretKit.SigningRequestProvenance`` from a ``FileHandle``.
|
||||||
/// - Parameter fileHandleReader: The reader involved in processing the request.
|
/// - Parameter fileHandle: The reader involved in processing the request.
|
||||||
/// - Returns: A ``SecretKit.SigningRequestProvenance`` describing the origin of the request.
|
/// - Returns: A ``SecretKit.SigningRequestProvenance`` describing the origin of the request.
|
||||||
func provenance(from fileHandleReader: FileHandleReader) -> SigningRequestProvenance {
|
func provenance(from fileHandle: FileHandle) -> SigningRequestProvenance {
|
||||||
let firstInfo = process(from: fileHandleReader.pidOfConnectedProcess)
|
let firstInfo = process(from: fileHandle.pidOfConnectedProcess)
|
||||||
|
|
||||||
var provenance = SigningRequestProvenance(root: firstInfo)
|
var provenance = SigningRequestProvenance(root: firstInfo)
|
||||||
while NSRunningApplication(processIdentifier: provenance.origin.pid) == nil && provenance.origin.parentPID != nil {
|
while NSRunningApplication(processIdentifier: provenance.origin.pid) == nil && provenance.origin.parentPID != nil {
|
||||||
provenance.chain.append(process(from: provenance.origin.parentPID!))
|
provenance.chain.append(process(from: provenance.origin.parentPID!))
|
||||||
@@ -27,27 +25,30 @@ extension SigningRequestTracer {
|
|||||||
/// - Parameter pid: The process ID to look up.
|
/// - Parameter pid: The process ID to look up.
|
||||||
/// - Returns: a `kinfo_proc` struct describing the process ID.
|
/// - Returns: a `kinfo_proc` struct describing the process ID.
|
||||||
func pidAndNameInfo(from pid: Int32) -> kinfo_proc {
|
func pidAndNameInfo(from pid: Int32) -> kinfo_proc {
|
||||||
var len = MemoryLayout<kinfo_proc>.size
|
var len = unsafe MemoryLayout<kinfo_proc>.size
|
||||||
let infoPointer = UnsafeMutableRawPointer.allocate(byteCount: len, alignment: 1)
|
let infoPointer = UnsafeMutableRawPointer.allocate(byteCount: len, alignment: 1)
|
||||||
var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid]
|
var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid]
|
||||||
sysctl(&name, UInt32(name.count), infoPointer, &len, nil, 0)
|
unsafe sysctl(&name, UInt32(name.count), infoPointer, &len, nil, 0)
|
||||||
return infoPointer.load(as: kinfo_proc.self)
|
return unsafe infoPointer.load(as: kinfo_proc.self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generates a ``SecretKit.SigningRequestProvenance.Process`` from a provided process ID.
|
/// Generates a ``SecretKit.SigningRequestProvenance.Process`` from a provided process ID.
|
||||||
/// - Parameter pid: The process ID to look up.
|
/// - Parameter pid: The process ID to look up.
|
||||||
/// - Returns: A ``SecretKit.SigningRequestProvenance.Process`` describing the process.
|
/// - Returns: A ``SecretKit.SigningRequestProvenance.Process`` describing the process.
|
||||||
func process(from pid: Int32) -> SigningRequestProvenance.Process {
|
func process(from pid: Int32) -> SigningRequestProvenance.Process {
|
||||||
var pidAndNameInfo = self.pidAndNameInfo(from: pid)
|
var pidAndNameInfo = unsafe self.pidAndNameInfo(from: pid)
|
||||||
let ppid = pidAndNameInfo.kp_eproc.e_ppid != 0 ? pidAndNameInfo.kp_eproc.e_ppid : nil
|
let ppid = unsafe pidAndNameInfo.kp_eproc.e_ppid != 0 ? pidAndNameInfo.kp_eproc.e_ppid : nil
|
||||||
let procName = String(cString: &pidAndNameInfo.kp_proc.p_comm.0)
|
let procName = unsafe withUnsafeMutablePointer(to: &pidAndNameInfo.kp_proc.p_comm.0) { pointer in
|
||||||
|
unsafe String(cString: pointer)
|
||||||
|
}
|
||||||
|
|
||||||
let pathPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(MAXPATHLEN))
|
let pathPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(MAXPATHLEN))
|
||||||
_ = proc_pidpath(pid, pathPointer, UInt32(MAXPATHLEN))
|
_ = unsafe proc_pidpath(pid, pathPointer, UInt32(MAXPATHLEN))
|
||||||
let path = String(cString: pathPointer)
|
let path = unsafe String(cString: pathPointer)
|
||||||
var secCode: Unmanaged<SecCode>!
|
var secCode: Unmanaged<SecCode>!
|
||||||
let flags: SecCSFlags = [.considerExpiration, .enforceRevocationChecks]
|
let flags: SecCSFlags = [.considerExpiration, .enforceRevocationChecks]
|
||||||
SecCodeCreateWithPID(pid, SecCSFlags(), &secCode)
|
unsafe SecCodeCreateWithPID(pid, SecCSFlags(), &secCode)
|
||||||
let valid = SecCodeCheckValidity(secCode.takeRetainedValue(), flags, nil) == errSecSuccess
|
let valid = unsafe SecCodeCheckValidity(secCode.takeRetainedValue(), flags, nil) == errSecSuccess
|
||||||
return SigningRequestProvenance.Process(pid: pid, processName: procName, appName: appName(for: pid), iconURL: iconURL(for: pid), path: path, validSignature: valid, parentPID: ppid)
|
return SigningRequestProvenance.Process(pid: pid, processName: procName, appName: appName(for: pid), iconURL: iconURL(for: pid), path: path, validSignature: valid, parentPID: ppid)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +58,10 @@ extension SigningRequestTracer {
|
|||||||
func iconURL(for pid: Int32) -> URL? {
|
func iconURL(for pid: Int32) -> URL? {
|
||||||
do {
|
do {
|
||||||
if let app = NSRunningApplication(processIdentifier: pid), let icon = app.icon?.tiffRepresentation {
|
if let app = NSRunningApplication(processIdentifier: pid), let icon = app.icon?.tiffRepresentation {
|
||||||
let temporaryURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("\(UUID().uuidString).png"))
|
let temporaryURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("\(app.bundleIdentifier ?? UUID().uuidString).png"))
|
||||||
|
if FileManager.default.fileExists(atPath: temporaryURL.path) {
|
||||||
|
return temporaryURL
|
||||||
|
}
|
||||||
let bitmap = NSBitmapImageRep(data: icon)
|
let bitmap = NSBitmapImageRep(data: icon)
|
||||||
try bitmap?.representation(using: .png, properties: [:])?.write(to: temporaryURL)
|
try bitmap?.representation(using: .png, properties: [:])?.write(to: temporaryURL)
|
||||||
return temporaryURL
|
return temporaryURL
|
||||||
@@ -75,3 +79,11 @@ extension SigningRequestTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// from libproc.h
|
||||||
|
@_silgen_name("proc_pidpath")
|
||||||
|
@discardableResult func proc_pidpath(_ pid: Int32, _ buffer: UnsafeMutableRawPointer!, _ buffersize: UInt32) -> Int32
|
||||||
|
|
||||||
|
//// from SecTask.h
|
||||||
|
@_silgen_name("SecCodeCreateWithPID")
|
||||||
|
@discardableResult func SecCodeCreateWithPID(_: Int32, _: SecCSFlags, _: UnsafeMutablePointer<Unmanaged<SecCode>?>!) -> OSStatus
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import Foundation
|
|||||||
import SecretKit
|
import SecretKit
|
||||||
|
|
||||||
/// A protocol that allows conformers to be notified of access to secrets, and optionally prevent access.
|
/// A protocol that allows conformers to be notified of access to secrets, and optionally prevent access.
|
||||||
public protocol SigningWitness {
|
public protocol SigningWitness: Sendable {
|
||||||
|
|
||||||
/// A ridiculously named method that notifies the callee that a signing operation is about to be performed using a secret. The callee may `throw` an `Error` to prevent access from occurring.
|
/// A ridiculously named method that notifies the callee that a signing operation is about to be performed using a secret. The callee may `throw` an `Error` to prevent access from occurring.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
@@ -10,14 +10,13 @@ public protocol SigningWitness {
|
|||||||
/// - store: The `Store` being asked to sign the request..
|
/// - store: The `Store` being asked to sign the request..
|
||||||
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
|
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
|
||||||
/// - Note: This method being called does not imply that the requst has been authorized. If a secret requires authentication, authentication will still need to be performed by the user before the request will be performed. If the user declines or fails to authenticate, the request will fail.
|
/// - Note: This method being called does not imply that the requst has been authorized. If a secret requires authentication, authentication will still need to be performed by the user before the request will be performed. If the user declines or fails to authenticate, the request will fail.
|
||||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws
|
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws
|
||||||
|
|
||||||
/// Notifies the callee that a signing operation has been performed for a given secret.
|
/// Notifies the callee that a signing operation has been performed for a given secret.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - secret: The `Secret` that will was used to sign the request.
|
/// - secret: The `Secret` that will was used to sign the request.
|
||||||
/// - store: The `Store` that signed the request..
|
/// - store: The `Store` that signed the request..
|
||||||
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
|
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
|
||||||
/// - requiredAuthentication: A boolean describing whether or not authentication was required for the request.
|
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws
|
||||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,79 +1,146 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import OSLog
|
import OSLog
|
||||||
|
import SecretKit
|
||||||
|
|
||||||
/// A controller that manages socket configuration and request dispatching.
|
/// A controller that manages socket configuration and request dispatching.
|
||||||
public class SocketController {
|
public struct SocketController {
|
||||||
|
|
||||||
/// The active FileHandle.
|
/// A stream of Sessions. Each session represents one connection to a class communicating with the socket. Multiple Sessions may be active simultaneously.
|
||||||
private var fileHandle: FileHandle?
|
public let sessions: AsyncStream<Session>
|
||||||
/// A handler that will be notified when a new read/write handle is available.
|
|
||||||
public var handler: ((FileHandleReader, FileHandleWriter) -> Void)?
|
/// A continuation to create new sessions.
|
||||||
|
private let sessionsContinuation: AsyncStream<Session>.Continuation
|
||||||
|
|
||||||
|
/// The active SocketPort. Must be retained to be kept valid.
|
||||||
|
private let port: SocketPort
|
||||||
|
|
||||||
|
/// The FileHandle for the main socket.
|
||||||
|
private let fileHandle: FileHandle
|
||||||
|
|
||||||
|
/// Logger for the socket controller.
|
||||||
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "SocketController")
|
||||||
|
|
||||||
|
/// Tracer which determines who originates a socket connection.
|
||||||
|
private let requestTracer = SigningRequestTracer()
|
||||||
|
|
||||||
/// Initializes a socket controller with a specified path.
|
/// Initializes a socket controller with a specified path.
|
||||||
/// - Parameter path: The path to use as a socket.
|
/// - Parameter path: The path to use as a socket.
|
||||||
public init(path: String) {
|
public init(path: String) {
|
||||||
Logger().debug("Socket controller setting up at \(path)")
|
(sessions, sessionsContinuation) = AsyncStream<Session>.makeStream()
|
||||||
|
logger.debug("Socket controller setting up at \(path)")
|
||||||
if let _ = try? FileManager.default.removeItem(atPath: path) {
|
if let _ = try? FileManager.default.removeItem(atPath: path) {
|
||||||
Logger().debug("Socket controller removed existing socket")
|
logger.debug("Socket controller removed existing socket")
|
||||||
}
|
}
|
||||||
let exists = FileManager.default.fileExists(atPath: path)
|
let exists = FileManager.default.fileExists(atPath: path)
|
||||||
assert(!exists)
|
assert(!exists)
|
||||||
Logger().debug("Socket controller path is clear")
|
logger.debug("Socket controller path is clear")
|
||||||
configureSocket(at: path)
|
port = SocketPort(path: path)
|
||||||
Logger().debug("Socket listening at \(path)")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Configures the socket and a corresponding FileHandle.
|
|
||||||
/// - Parameter path: The path to use as a socket.
|
|
||||||
func configureSocket(at path: String) {
|
|
||||||
let port = socketPort(at: path)
|
|
||||||
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
|
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
|
||||||
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionAccept(notification:)), name: .NSFileHandleConnectionAccepted, object: nil)
|
Task { @MainActor [fileHandle, sessionsContinuation, logger] in
|
||||||
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionDataAvailable(notification:)), name: .NSFileHandleDataAvailable, object: nil)
|
// Create the sequence before triggering the notification to
|
||||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
// ensure it will not be missed.
|
||||||
}
|
let connectionAcceptedNotifications = NotificationCenter.default.notifications(named: .NSFileHandleConnectionAccepted)
|
||||||
|
|
||||||
/// Creates a SocketPort for a path.
|
fileHandle.acceptConnectionInBackgroundAndNotify()
|
||||||
/// - Parameter path: The path to use as a socket.
|
|
||||||
/// - Returns: A configured SocketPort.
|
|
||||||
func socketPort(at path: String) -> SocketPort {
|
|
||||||
var addr = sockaddr_un()
|
|
||||||
addr.sun_family = sa_family_t(AF_UNIX)
|
|
||||||
|
|
||||||
var len: Int = 0
|
for await notification in connectionAcceptedNotifications {
|
||||||
withUnsafeMutablePointer(to: &addr.sun_path.0) { pointer in
|
logger.debug("Socket controller accepted connection")
|
||||||
path.withCString { cstring in
|
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { continue }
|
||||||
len = strlen(cstring)
|
let session = Session(fileHandle: new)
|
||||||
strncpy(pointer, cstring, len)
|
sessionsContinuation.yield(session)
|
||||||
|
fileHandle.acceptConnectionInBackgroundAndNotify()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
addr.sun_len = UInt8(len+2)
|
logger.debug("Socket listening at \(path)")
|
||||||
|
}
|
||||||
var data: Data!
|
|
||||||
withUnsafePointer(to: &addr) { pointer in
|
}
|
||||||
data = Data(bytes: pointer, count: MemoryLayout<sockaddr_un>.size)
|
|
||||||
}
|
extension SocketController {
|
||||||
|
|
||||||
return SocketPort(protocolFamily: AF_UNIX, socketType: SOCK_STREAM, protocol: 0, address: data)!
|
/// A session represents a connection that has been established between the two ends of the socket.
|
||||||
}
|
public struct Session: Sendable {
|
||||||
|
|
||||||
/// Handles a new connection being accepted, invokes the handler, and prepares to accept new connections.
|
/// Data received by the socket.
|
||||||
/// - Parameter notification: A `Notification` that triggered the call.
|
public let messages: AsyncStream<Data>
|
||||||
@objc func handleConnectionAccept(notification: Notification) {
|
|
||||||
Logger().debug("Socket controller accepted connection")
|
/// The provenance of the process that established the session.
|
||||||
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
|
public let provenance: SigningRequestProvenance
|
||||||
handler?(new, new)
|
|
||||||
new.waitForDataInBackgroundAndNotify()
|
/// A FileHandle used to communicate with the socket.
|
||||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
private let fileHandle: FileHandle
|
||||||
}
|
|
||||||
|
/// A continuation for issuing new messages.
|
||||||
/// Handles a new connection providing data and invokes the handler callback.
|
private let messagesContinuation: AsyncStream<Data>.Continuation
|
||||||
/// - Parameter notification: A `Notification` that triggered the call.
|
|
||||||
@objc func handleConnectionDataAvailable(notification: Notification) {
|
/// A logger for the session.
|
||||||
Logger().debug("Socket controller has new data available")
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "Session")
|
||||||
guard let new = notification.object as? FileHandle else { return }
|
|
||||||
Logger().debug("Socket controller received new file handle")
|
/// Initializes a new Session.
|
||||||
handler?(new, new)
|
/// - Parameter fileHandle: The FileHandle used to communicate with the socket.
|
||||||
|
init(fileHandle: FileHandle) {
|
||||||
|
self.fileHandle = fileHandle
|
||||||
|
provenance = SigningRequestTracer().provenance(from: fileHandle)
|
||||||
|
(messages, messagesContinuation) = AsyncStream.makeStream()
|
||||||
|
Task { @MainActor [messagesContinuation, logger] in
|
||||||
|
// Create the sequence before triggering the notification to
|
||||||
|
// ensure it will not be missed.
|
||||||
|
let dataAvailableNotifications = NotificationCenter.default.notifications(named: .NSFileHandleDataAvailable, object: fileHandle)
|
||||||
|
|
||||||
|
fileHandle.waitForDataInBackgroundAndNotify()
|
||||||
|
|
||||||
|
for await _ in dataAvailableNotifications {
|
||||||
|
let data = fileHandle.availableData
|
||||||
|
guard !data.isEmpty else {
|
||||||
|
logger.debug("Socket controller received empty data, ending continuation.")
|
||||||
|
messagesContinuation.finish()
|
||||||
|
try fileHandle.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
messagesContinuation.yield(data)
|
||||||
|
logger.debug("Socket controller yielded data.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes new data to the socket.
|
||||||
|
/// - Parameter data: The data to write.
|
||||||
|
@MainActor public func write(_ data: Data) throws {
|
||||||
|
try fileHandle.write(contentsOf: data)
|
||||||
|
fileHandle.waitForDataInBackgroundAndNotify()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes the socket and cleans up resources.
|
||||||
|
public func close() throws {
|
||||||
|
logger.debug("Session closed.")
|
||||||
|
messagesContinuation.finish()
|
||||||
|
try fileHandle.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private extension SocketPort {
|
||||||
|
|
||||||
|
convenience init(path: String) {
|
||||||
|
var addr = sockaddr_un()
|
||||||
|
|
||||||
|
let length = unsafe withUnsafeMutablePointer(to: &addr.sun_path.0) { pointer in
|
||||||
|
unsafe path.withCString { cstring in
|
||||||
|
let len = unsafe strlen(cstring)
|
||||||
|
unsafe strncpy(pointer, cstring, len)
|
||||||
|
return len
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// This doesn't seem to be _strictly_ neccessary with SocketPort.
|
||||||
|
// but just for good form.
|
||||||
|
addr.sun_family = sa_family_t(AF_UNIX)
|
||||||
|
// This mirrors the SUN_LEN macro format.
|
||||||
|
addr.sun_len = UInt8(MemoryLayout<sockaddr_un>.size - MemoryLayout.size(ofValue: addr.sun_path) + length)
|
||||||
|
|
||||||
|
let data = unsafe Data(bytes: &addr, count: MemoryLayout<sockaddr_un>.size)
|
||||||
|
self.init(protocolFamily: AF_UNIX, socketType: SOCK_STREAM, protocol: 0, address: data)!
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <Security/Security.h>
|
|
||||||
|
|
||||||
|
|
||||||
// Forward declarations
|
|
||||||
|
|
||||||
// from libproc.h
|
|
||||||
int proc_pidpath(int pid, void * buffer, uint32_t buffersize);
|
|
||||||
|
|
||||||
// from SecTask.h
|
|
||||||
OSStatus SecCodeCreateWithPID(int32_t, SecCSFlags, SecCodeRef *);
|
|
||||||
|
|
||||||
//! Project version number for SecretAgentKit.
|
|
||||||
FOUNDATION_EXPORT double SecretAgentKitVersionNumber;
|
|
||||||
|
|
||||||
//! Project version string for SecretAgentKit.
|
|
||||||
FOUNDATION_EXPORT const unsigned char SecretAgentKitVersionString[];
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
module SecretAgentKitHeaders [system] {
|
|
||||||
header "include/SecretAgentKit.h"
|
|
||||||
export *
|
|
||||||
}
|
|
||||||
@@ -22,10 +22,19 @@ SecretKit is a collection of protocols describing secrets and stores.
|
|||||||
|
|
||||||
### OpenSSH
|
### OpenSSH
|
||||||
|
|
||||||
- ``OpenSSHKeyWriter``
|
- ``OpenSSHPublicKeyWriter``
|
||||||
- ``OpenSSHReader``
|
- ``OpenSSHReader``
|
||||||
|
|
||||||
### Signing Process
|
### Signing Process
|
||||||
|
|
||||||
- ``SignedData``
|
|
||||||
- ``SigningRequestProvenance``
|
- ``SigningRequestProvenance``
|
||||||
|
|
||||||
|
### Authentication Persistence
|
||||||
|
|
||||||
|
- ``PersistedAuthenticationContext``
|
||||||
|
|
||||||
|
### Errors
|
||||||
|
|
||||||
|
- ``KeychainError``
|
||||||
|
- ``SigningError``
|
||||||
|
- ``SecurityError``
|
||||||
|
|||||||
@@ -1,33 +1,30 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
/// Type eraser for Secret.
|
/// Type eraser for Secret.
|
||||||
public struct AnySecret: Secret {
|
public struct AnySecret: Secret, @unchecked Sendable {
|
||||||
|
|
||||||
let base: Any
|
public let base: any Secret
|
||||||
private let hashable: AnyHashable
|
|
||||||
private let _id: () -> AnyHashable
|
private let _id: () -> AnyHashable
|
||||||
private let _name: () -> String
|
private let _name: () -> String
|
||||||
private let _algorithm: () -> Algorithm
|
|
||||||
private let _keySize: () -> Int
|
|
||||||
private let _publicKey: () -> Data
|
private let _publicKey: () -> Data
|
||||||
|
private let _attributes: () -> Attributes
|
||||||
|
private let _eq: (AnySecret) -> Bool
|
||||||
|
|
||||||
public init<T>(_ secret: T) where T: Secret {
|
public init<T>(_ secret: T) where T: Secret {
|
||||||
if let secret = secret as? AnySecret {
|
if let secret = secret as? AnySecret {
|
||||||
base = secret.base
|
base = secret.base
|
||||||
hashable = secret.hashable
|
|
||||||
_id = secret._id
|
_id = secret._id
|
||||||
_name = secret._name
|
_name = secret._name
|
||||||
_algorithm = secret._algorithm
|
|
||||||
_keySize = secret._keySize
|
|
||||||
_publicKey = secret._publicKey
|
_publicKey = secret._publicKey
|
||||||
|
_attributes = secret._attributes
|
||||||
|
_eq = secret._eq
|
||||||
} else {
|
} else {
|
||||||
base = secret as Any
|
base = secret
|
||||||
self.hashable = secret
|
|
||||||
_id = { secret.id as AnyHashable }
|
_id = { secret.id as AnyHashable }
|
||||||
_name = { secret.name }
|
_name = { secret.name }
|
||||||
_algorithm = { secret.algorithm }
|
|
||||||
_keySize = { secret.keySize }
|
|
||||||
_publicKey = { secret.publicKey }
|
_publicKey = { secret.publicKey }
|
||||||
|
_attributes = { secret.attributes }
|
||||||
|
_eq = { secret == $0.base as? T }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,24 +36,20 @@ public struct AnySecret: Secret {
|
|||||||
_name()
|
_name()
|
||||||
}
|
}
|
||||||
|
|
||||||
public var algorithm: Algorithm {
|
|
||||||
_algorithm()
|
|
||||||
}
|
|
||||||
|
|
||||||
public var keySize: Int {
|
|
||||||
_keySize()
|
|
||||||
}
|
|
||||||
|
|
||||||
public var publicKey: Data {
|
public var publicKey: Data {
|
||||||
_publicKey()
|
_publicKey()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public var attributes: Attributes {
|
||||||
|
_attributes()
|
||||||
|
}
|
||||||
|
|
||||||
public static func == (lhs: AnySecret, rhs: AnySecret) -> Bool {
|
public static func == (lhs: AnySecret, rhs: AnySecret) -> Bool {
|
||||||
lhs.hashable == rhs.hashable
|
lhs._eq(rhs)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func hash(into hasher: inout Hasher) {
|
public func hash(into hasher: inout Hasher) {
|
||||||
hashable.hash(into: &hasher)
|
id.hash(into: &hasher)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,17 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
|
||||||
|
|
||||||
/// Type eraser for SecretStore.
|
/// Type eraser for SecretStore.
|
||||||
public class AnySecretStore: SecretStore {
|
open class AnySecretStore: SecretStore, @unchecked Sendable {
|
||||||
|
|
||||||
let base: Any
|
let base: any SecretStore
|
||||||
private let _isAvailable: () -> Bool
|
private let _isAvailable: @MainActor @Sendable () -> Bool
|
||||||
private let _id: () -> UUID
|
private let _id: @Sendable () -> UUID
|
||||||
private let _name: () -> String
|
private let _name: @MainActor @Sendable () -> String
|
||||||
private let _secrets: () -> [AnySecret]
|
private let _secrets: @MainActor @Sendable () -> [AnySecret]
|
||||||
private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> SignedData
|
private let _sign: @Sendable (Data, AnySecret, SigningRequestProvenance) async throws -> Data
|
||||||
private let _persistAuthentication: (AnySecret, TimeInterval) throws -> Void
|
private let _existingPersistedAuthenticationContext: @Sendable (AnySecret) async -> PersistedAuthenticationContext?
|
||||||
|
private let _persistAuthentication: @Sendable (AnySecret, TimeInterval) async throws -> Void
|
||||||
private var sink: AnyCancellable?
|
private let _reloadSecrets: @Sendable () async -> Void
|
||||||
|
|
||||||
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
||||||
base = secretStore
|
base = secretStore
|
||||||
@@ -20,14 +19,13 @@ public class AnySecretStore: SecretStore {
|
|||||||
_name = { secretStore.name }
|
_name = { secretStore.name }
|
||||||
_id = { secretStore.id }
|
_id = { secretStore.id }
|
||||||
_secrets = { secretStore.secrets.map { AnySecret($0) } }
|
_secrets = { secretStore.secrets.map { AnySecret($0) } }
|
||||||
_sign = { try secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType, for: $2) }
|
_sign = { try await secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType, for: $2) }
|
||||||
_persistAuthentication = { try secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) }
|
_existingPersistedAuthenticationContext = { await secretStore.existingPersistedAuthenticationContext(secret: $0.base as! SecretStoreType.SecretType) }
|
||||||
sink = secretStore.objectWillChange.sink { _ in
|
_persistAuthentication = { try await secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) }
|
||||||
self.objectWillChange.send()
|
_reloadSecrets = { await secretStore.reloadSecrets() }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public var isAvailable: Bool {
|
@MainActor public var isAvailable: Bool {
|
||||||
return _isAvailable()
|
return _isAvailable()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,47 +33,62 @@ public class AnySecretStore: SecretStore {
|
|||||||
return _id()
|
return _id()
|
||||||
}
|
}
|
||||||
|
|
||||||
public var name: String {
|
@MainActor public var name: String {
|
||||||
return _name()
|
return _name()
|
||||||
}
|
}
|
||||||
|
|
||||||
public var secrets: [AnySecret] {
|
@MainActor public var secrets: [AnySecret] {
|
||||||
return _secrets()
|
return _secrets()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) throws -> SignedData {
|
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) async throws -> Data {
|
||||||
try _sign(data, secret, provenance)
|
try await _sign(data, secret, provenance)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) throws {
|
public func existingPersistedAuthenticationContext(secret: AnySecret) async -> PersistedAuthenticationContext? {
|
||||||
try _persistAuthentication(secret, duration)
|
await _existingPersistedAuthenticationContext(secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) async throws {
|
||||||
|
try await _persistAuthentication(secret, duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func reloadSecrets() async {
|
||||||
|
await _reloadSecrets()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
public final class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable, @unchecked Sendable {
|
||||||
|
|
||||||
private let _create: (String, Bool) throws -> Void
|
private let _create: @Sendable (String, Attributes) async throws -> AnySecret
|
||||||
private let _delete: (AnySecret) throws -> Void
|
private let _delete: @Sendable (AnySecret) async throws -> Void
|
||||||
private let _update: (AnySecret, String) throws -> Void
|
private let _update: @Sendable (AnySecret, String, Attributes) async throws -> Void
|
||||||
|
private let _supportedKeyTypes: @Sendable () -> KeyAvailability
|
||||||
|
|
||||||
public init<SecretStoreType>(modifiable secretStore: SecretStoreType) where SecretStoreType: SecretStoreModifiable {
|
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStoreModifiable {
|
||||||
_create = { try secretStore.create(name: $0, requiresAuthentication: $1) }
|
_create = { AnySecret(try await secretStore.create(name: $0, attributes: $1)) }
|
||||||
_delete = { try secretStore.delete(secret: $0.base as! SecretStoreType.SecretType) }
|
_delete = { try await secretStore.delete(secret: $0.base as! SecretStoreType.SecretType) }
|
||||||
_update = { try secretStore.update(secret: $0.base as! SecretStoreType.SecretType, name: $1) }
|
_update = { try await secretStore.update(secret: $0.base as! SecretStoreType.SecretType, name: $1, attributes: $2) }
|
||||||
|
_supportedKeyTypes = { secretStore.supportedKeyTypes }
|
||||||
super.init(secretStore)
|
super.init(secretStore)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func create(name: String, requiresAuthentication: Bool) throws {
|
@discardableResult
|
||||||
try _create(name, requiresAuthentication)
|
public func create(name: String, attributes: Attributes) async throws -> SecretType {
|
||||||
|
try await _create(name, attributes)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func delete(secret: AnySecret) throws {
|
public func delete(secret: AnySecret) async throws {
|
||||||
try _delete(secret)
|
try await _delete(secret)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func update(secret: AnySecret, name: String) throws {
|
public func update(secret: AnySecret, name: String, attributes: Attributes) async throws {
|
||||||
try _update(secret, name)
|
try await _update(secret, name, attributes)
|
||||||
|
}
|
||||||
|
|
||||||
|
public var supportedKeyTypes: KeyAvailability {
|
||||||
|
_supportedKeyTypes()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
69
Sources/Packages/Sources/SecretKit/KeychainTypes.swift
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
public typealias SecurityError = Unmanaged<CFError>
|
||||||
|
|
||||||
|
/// Wraps a Swift dictionary in a CFDictionary.
|
||||||
|
/// - Parameter dictionary: The Swift dictionary to wrap.
|
||||||
|
/// - Returns: A CFDictionary containing the keys and values.
|
||||||
|
public func KeychainDictionary(_ dictionary: [CFString: Any]) -> CFDictionary {
|
||||||
|
dictionary as CFDictionary
|
||||||
|
}
|
||||||
|
|
||||||
|
public extension CFError {
|
||||||
|
|
||||||
|
/// The CFError returned when a verification operation fails.
|
||||||
|
static let verifyError = CFErrorCreate(nil, NSOSStatusErrorDomain as CFErrorDomain, CFIndex(errSecVerifyFailed), nil)!
|
||||||
|
|
||||||
|
/// Equality operation that only considers domain and code.
|
||||||
|
static func ~=(lhs: CFError, rhs: CFError) -> Bool {
|
||||||
|
CFErrorGetDomain(lhs) == CFErrorGetDomain(rhs) && CFErrorGetCode(lhs) == CFErrorGetCode(rhs)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A wrapper around an error code reported by a Keychain API.
|
||||||
|
public struct KeychainError: Error {
|
||||||
|
/// The status code involved, if one was reported.
|
||||||
|
public let statusCode: OSStatus?
|
||||||
|
|
||||||
|
/// Initializes a KeychainError with an optional error code.
|
||||||
|
/// - Parameter statusCode: The status code returned by the keychain operation, if one is applicable.
|
||||||
|
public init(statusCode: OSStatus?) {
|
||||||
|
self.statusCode = statusCode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A signing-related error.
|
||||||
|
public struct SigningError: Error {
|
||||||
|
/// The underlying error reported by the API, if one was returned.
|
||||||
|
public let error: CFError?
|
||||||
|
|
||||||
|
/// Initializes a SigningError with an optional SecurityError.
|
||||||
|
/// - Parameter statusCode: The SecurityError, if one is applicable.
|
||||||
|
public init(error: SecurityError?) {
|
||||||
|
self.error = unsafe error?.takeRetainedValue()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public extension SecretStore {
|
||||||
|
|
||||||
|
/// Returns the appropriate keychian signature algorithm to use for a given secret.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The secret which will be used for signing.
|
||||||
|
/// - Returns: The appropriate algorithm.
|
||||||
|
func signatureAlgorithm(for secret: SecretType) -> SecKeyAlgorithm? {
|
||||||
|
switch secret.keyType {
|
||||||
|
case .ecdsa256:
|
||||||
|
.ecdsaSignatureMessageX962SHA256
|
||||||
|
case .ecdsa384:
|
||||||
|
.ecdsaSignatureMessageX962SHA384
|
||||||
|
case .rsa2048:
|
||||||
|
.rsaSignatureMessagePKCS1v15SHA512
|
||||||
|
default:
|
||||||
|
nil
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
extension Data {
|
||||||
|
|
||||||
|
/// Creates an OpenSSH protocol style data object, which has a length header, followed by the data payload.
|
||||||
|
/// - Returns: OpenSSH data.
|
||||||
|
package var lengthAndData: Data {
|
||||||
|
let rawLength = UInt32(count)
|
||||||
|
var endian = rawLength.bigEndian
|
||||||
|
return unsafe Data(bytes: &endian, count: MemoryLayout<UInt32>.size) + self
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension String {
|
||||||
|
|
||||||
|
/// Creates an OpenSSH protocol style data object, which has a length header, followed by the data payload.
|
||||||
|
/// - Returns: OpenSSH data.
|
||||||
|
package var lengthAndData: Data {
|
||||||
|
Data(utf8).lengthAndData
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import CryptoKit
|
|
||||||
|
|
||||||
/// Generates OpenSSH representations of Secrets.
|
|
||||||
public struct OpenSSHKeyWriter {
|
|
||||||
|
|
||||||
/// Initializes the writer.
|
|
||||||
public init() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates an OpenSSH data payload identifying the secret.
|
|
||||||
/// - Returns: OpenSSH data payload identifying the secret.
|
|
||||||
public func data<SecretType: Secret>(secret: SecretType) -> Data {
|
|
||||||
lengthAndData(of: curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
|
||||||
lengthAndData(of: curveIdentifier(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
|
||||||
lengthAndData(of: secret.publicKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates an OpenSSH string representation of the secret.
|
|
||||||
/// - Returns: OpenSSH string representation of the secret.
|
|
||||||
public func openSSHString<SecretType: Secret>(secret: SecretType, comment: String? = nil) -> String {
|
|
||||||
[curveType(for: secret.algorithm, length: secret.keySize), data(secret: secret).base64EncodedString(), comment]
|
|
||||||
.compactMap { $0 }
|
|
||||||
.joined(separator: " ")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates an OpenSSH SHA256 fingerprint string.
|
|
||||||
/// - Returns: OpenSSH SHA256 fingerprint string.
|
|
||||||
public func openSSHSHA256Fingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
|
||||||
// OpenSSL format seems to strip the padding at the end.
|
|
||||||
let base64 = Data(SHA256.hash(data: data(secret: secret))).base64EncodedString()
|
|
||||||
let paddingRange = base64.index(base64.endIndex, offsetBy: -2)..<base64.endIndex
|
|
||||||
let cleaned = base64.replacingOccurrences(of: "=", with: "", range: paddingRange)
|
|
||||||
return "SHA256:\(cleaned)"
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates an OpenSSH MD5 fingerprint string.
|
|
||||||
/// - Returns: OpenSSH MD5 fingerprint string.
|
|
||||||
public func openSSHMD5Fingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
|
||||||
Insecure.MD5.hash(data: data(secret: secret))
|
|
||||||
.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }
|
|
||||||
.joined(separator: ":")
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension OpenSSHKeyWriter {
|
|
||||||
|
|
||||||
/// Creates an OpenSSH protocol style data object, which has a length header, followed by the data payload.
|
|
||||||
/// - Parameter data: The data payload.
|
|
||||||
/// - Returns: OpenSSH data.
|
|
||||||
public func lengthAndData(of data: Data) -> Data {
|
|
||||||
let rawLength = UInt32(data.count)
|
|
||||||
var endian = rawLength.bigEndian
|
|
||||||
return Data(bytes: &endian, count: UInt32.bitWidth/8) + data
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The fully qualified OpenSSH identifier for the algorithm.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - algorithm: The algorithm to identify.
|
|
||||||
/// - length: The key length of the algorithm.
|
|
||||||
/// - Returns: The OpenSSH identifier for the algorithm.
|
|
||||||
public func curveType(for algorithm: Algorithm, length: Int) -> String {
|
|
||||||
switch algorithm {
|
|
||||||
case .ellipticCurve:
|
|
||||||
return "ecdsa-sha2-nistp" + String(describing: length)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The OpenSSH identifier for an algorithm.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - algorithm: The algorithm to identify.
|
|
||||||
/// - length: The key length of the algorithm.
|
|
||||||
/// - Returns: The OpenSSH identifier for the algorithm.
|
|
||||||
private func curveIdentifier(for algorithm: Algorithm, length: Int) -> String {
|
|
||||||
switch algorithm {
|
|
||||||
case .ellipticCurve:
|
|
||||||
return "nistp" + String(describing: length)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import Foundation
|
||||||
|
import CryptoKit
|
||||||
|
|
||||||
|
/// Generates OpenSSH representations of the public key sof secrets.
|
||||||
|
public struct OpenSSHPublicKeyWriter: Sendable {
|
||||||
|
|
||||||
|
/// Initializes the writer.
|
||||||
|
public init() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates an OpenSSH data payload identifying the secret.
|
||||||
|
/// - Returns: OpenSSH data payload identifying the secret.
|
||||||
|
public func data<SecretType: Secret>(secret: SecretType) -> Data {
|
||||||
|
switch secret.keyType.algorithm {
|
||||||
|
case .ecdsa:
|
||||||
|
// https://datatracker.ietf.org/doc/html/rfc5656#section-3.1
|
||||||
|
openSSHIdentifier(for: secret.keyType).lengthAndData +
|
||||||
|
("nistp" + String(describing: secret.keyType.size)).lengthAndData +
|
||||||
|
secret.publicKey.lengthAndData
|
||||||
|
case .mldsa:
|
||||||
|
// https://www.ietf.org/archive/id/draft-sfluhrer-ssh-mldsa-04.txt
|
||||||
|
openSSHIdentifier(for: secret.keyType).lengthAndData +
|
||||||
|
secret.publicKey.lengthAndData
|
||||||
|
case .rsa:
|
||||||
|
// https://datatracker.ietf.org/doc/html/rfc4253#section-6.6
|
||||||
|
openSSHIdentifier(for: secret.keyType).lengthAndData +
|
||||||
|
rsaPublicKeyBlob(secret: secret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates an OpenSSH string representation of the secret.
|
||||||
|
/// - Returns: OpenSSH string representation of the secret.
|
||||||
|
public func openSSHString<SecretType: Secret>(secret: SecretType) -> String {
|
||||||
|
return [openSSHIdentifier(for: secret.keyType), data(secret: secret).base64EncodedString(), comment(secret: secret)]
|
||||||
|
.compactMap { $0 }
|
||||||
|
.joined(separator: " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates an OpenSSH SHA256 fingerprint string.
|
||||||
|
/// - Returns: OpenSSH SHA256 fingerprint string.
|
||||||
|
public func openSSHSHA256Fingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
||||||
|
// OpenSSL format seems to strip the padding at the end.
|
||||||
|
let base64 = Data(SHA256.hash(data: data(secret: secret))).base64EncodedString()
|
||||||
|
let paddingRange = base64.index(base64.endIndex, offsetBy: -2)..<base64.endIndex
|
||||||
|
let cleaned = base64.replacingOccurrences(of: "=", with: "", range: paddingRange)
|
||||||
|
return "SHA256:\(cleaned)"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates an OpenSSH MD5 fingerprint string.
|
||||||
|
/// - Returns: OpenSSH MD5 fingerprint string.
|
||||||
|
public func openSSHMD5Fingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
||||||
|
Insecure.MD5.hash(data: data(secret: secret))
|
||||||
|
.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }
|
||||||
|
.joined(separator: ":")
|
||||||
|
}
|
||||||
|
|
||||||
|
public func comment<SecretType: Secret>(secret: SecretType) -> String {
|
||||||
|
if let comment = secret.publicKeyAttribution {
|
||||||
|
return comment
|
||||||
|
} else {
|
||||||
|
let dashedKeyName = secret.name.replacingOccurrences(of: " ", with: "-")
|
||||||
|
let dashedHostName = ["secretive", Host.current().localizedName, "local"]
|
||||||
|
.compactMap { $0 }
|
||||||
|
.joined(separator: ".")
|
||||||
|
.replacingOccurrences(of: " ", with: "-")
|
||||||
|
return "\(dashedKeyName)@\(dashedHostName)"
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OpenSSHPublicKeyWriter {
|
||||||
|
|
||||||
|
/// The fully qualified OpenSSH identifier for the algorithm.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - algorithm: The algorithm to identify.
|
||||||
|
/// - length: The key length of the algorithm.
|
||||||
|
/// - Returns: The OpenSSH identifier for the algorithm.
|
||||||
|
public func openSSHIdentifier(for keyType: KeyType) -> String {
|
||||||
|
switch keyType {
|
||||||
|
case .ecdsa256:
|
||||||
|
"ecdsa-sha2-nistp256"
|
||||||
|
case .ecdsa384:
|
||||||
|
"ecdsa-sha2-nistp384"
|
||||||
|
case .mldsa65:
|
||||||
|
"ssh-mldsa-65"
|
||||||
|
case .mldsa87:
|
||||||
|
"ssh-mldsa-87"
|
||||||
|
case .rsa2048:
|
||||||
|
"ssh-rsa"
|
||||||
|
default:
|
||||||
|
"unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OpenSSHPublicKeyWriter {
|
||||||
|
|
||||||
|
func rsaPublicKeyBlob<SecretType: Secret>(secret: SecretType) -> Data {
|
||||||
|
// Cheap way to pull out e and n as defined in https://datatracker.ietf.org/doc/html/rfc4253
|
||||||
|
// Keychain stores it as a thin ASN.1 wrapper with this format:
|
||||||
|
// [4 byte prefix][2 byte prefix][n][2 byte prefix][e]
|
||||||
|
// Rather than parse out the whole ASN.1 blob, we'll cheat and pull values directly since
|
||||||
|
// we only support one key type, and the keychain always gives it in a specific format.
|
||||||
|
guard secret.keyType == .rsa2048 else { fatalError() }
|
||||||
|
let length = secret.keyType.size/8
|
||||||
|
let data = secret.publicKey
|
||||||
|
let n = Data(data[8..<(9+length)])
|
||||||
|
let e = Data(data[(2+9+length)...])
|
||||||
|
return e.lengthAndData + n.lengthAndData
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
|
|
||||||
/// Reads OpenSSH protocol data.
|
|
||||||
public class OpenSSHReader {
|
|
||||||
|
|
||||||
var remaining: Data
|
|
||||||
|
|
||||||
/// Initialize the reader with an OpenSSH data payload.
|
|
||||||
/// - Parameter data: The data to read.
|
|
||||||
public init(data: Data) {
|
|
||||||
remaining = Data(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads the next chunk of data from the playload.
|
|
||||||
/// - Returns: The next chunk of data.
|
|
||||||
public func readNextChunk() -> Data {
|
|
||||||
let lengthRange = 0..<(UInt32.bitWidth/8)
|
|
||||||
let lengthChunk = remaining[lengthRange]
|
|
||||||
remaining.removeSubrange(lengthRange)
|
|
||||||
let littleEndianLength = lengthChunk.withUnsafeBytes { pointer in
|
|
||||||
return pointer.load(as: UInt32.self)
|
|
||||||
}
|
|
||||||
let length = Int(littleEndianLength.bigEndian)
|
|
||||||
let dataRange = 0..<length
|
|
||||||
let ret = Data(remaining[dataRange])
|
|
||||||
remaining.removeSubrange(dataRange)
|
|
||||||
return ret
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import Foundation
|
||||||
|
import CryptoKit
|
||||||
|
|
||||||
|
/// Generates OpenSSH representations of Secrets.
|
||||||
|
public struct OpenSSHSignatureWriter: Sendable {
|
||||||
|
|
||||||
|
/// Initializes the writer.
|
||||||
|
public init() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates an OpenSSH data payload identifying the secret.
|
||||||
|
/// - Returns: OpenSSH data payload identifying the secret.
|
||||||
|
public func data<SecretType: Secret>(secret: SecretType, signature: Data) -> Data {
|
||||||
|
switch secret.keyType.algorithm {
|
||||||
|
case .ecdsa:
|
||||||
|
// https://datatracker.ietf.org/doc/html/rfc5656#section-3.1
|
||||||
|
ecdsaSignature(signature, keyType: secret.keyType)
|
||||||
|
case .mldsa:
|
||||||
|
// https://datatracker.ietf.org/doc/html/draft-sfluhrer-ssh-mldsa-00#name-public-key-algorithms
|
||||||
|
mldsaSignature(signature, keyType: secret.keyType)
|
||||||
|
case .rsa:
|
||||||
|
// https://datatracker.ietf.org/doc/html/rfc4253#section-6.6
|
||||||
|
rsaSignature(signature)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
extension OpenSSHSignatureWriter {
|
||||||
|
|
||||||
|
func ecdsaSignature(_ rawRepresentation: Data, keyType: KeyType) -> Data {
|
||||||
|
let rawLength = rawRepresentation.count/2
|
||||||
|
// Check if we need to pad with 0x00 to prevent certain
|
||||||
|
// ssh servers from thinking r or s is negative
|
||||||
|
let paddingRange: ClosedRange<UInt8> = 0x80...0xFF
|
||||||
|
var r = Data(rawRepresentation[0..<rawLength])
|
||||||
|
if paddingRange ~= r.first! {
|
||||||
|
r.insert(0x00, at: 0)
|
||||||
|
}
|
||||||
|
var s = Data(rawRepresentation[rawLength...])
|
||||||
|
if paddingRange ~= s.first! {
|
||||||
|
s.insert(0x00, at: 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
var signatureChunk = Data()
|
||||||
|
signatureChunk.append(r.lengthAndData)
|
||||||
|
signatureChunk.append(s.lengthAndData)
|
||||||
|
var mutSignedData = Data()
|
||||||
|
var sub = Data()
|
||||||
|
sub.append(OpenSSHPublicKeyWriter().openSSHIdentifier(for: keyType).lengthAndData)
|
||||||
|
sub.append(signatureChunk.lengthAndData)
|
||||||
|
mutSignedData.append(sub.lengthAndData)
|
||||||
|
return mutSignedData
|
||||||
|
}
|
||||||
|
|
||||||
|
func mldsaSignature(_ rawRepresentation: Data, keyType: KeyType) -> Data {
|
||||||
|
var mutSignedData = Data()
|
||||||
|
var sub = Data()
|
||||||
|
sub.append(OpenSSHPublicKeyWriter().openSSHIdentifier(for: keyType).lengthAndData)
|
||||||
|
sub.append(rawRepresentation.lengthAndData)
|
||||||
|
mutSignedData.append(sub.lengthAndData)
|
||||||
|
return mutSignedData
|
||||||
|
}
|
||||||
|
|
||||||
|
func rsaSignature(_ rawRepresentation: Data) -> Data {
|
||||||
|
var mutSignedData = Data()
|
||||||
|
var sub = Data()
|
||||||
|
sub.append("rsa-sha2-512".lengthAndData)
|
||||||
|
sub.append(rawRepresentation.lengthAndData)
|
||||||
|
mutSignedData.append(sub.lengthAndData)
|
||||||
|
return mutSignedData
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import Foundation
|
||||||
|
import OSLog
|
||||||
|
|
||||||
|
/// Controller responsible for writing public keys to disk, so that they're easily accessible by scripts.
|
||||||
|
public final class PublicKeyFileStoreController: Sendable {
|
||||||
|
|
||||||
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "PublicKeyFileStoreController")
|
||||||
|
private let directory: URL
|
||||||
|
private let keyWriter = OpenSSHPublicKeyWriter()
|
||||||
|
|
||||||
|
/// Initializes a PublicKeyFileStoreController.
|
||||||
|
public init(homeDirectory: URL) {
|
||||||
|
directory = homeDirectory.appending(component: "PublicKeys")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes out the keys specified to disk.
|
||||||
|
/// - Parameter secrets: The Secrets to generate keys for.
|
||||||
|
/// - Parameter clear: Whether or not any untracked files in the directory should be removed.
|
||||||
|
public func generatePublicKeys(for secrets: [AnySecret], clear: Bool = false) throws {
|
||||||
|
logger.log("Writing public keys to disk")
|
||||||
|
if clear {
|
||||||
|
let validPaths = Set(secrets.map { publicKeyPath(for: $0) })
|
||||||
|
.union(Set(secrets.map { sshCertificatePath(for: $0) }))
|
||||||
|
let contentsOfDirectory = (try? FileManager.default.contentsOfDirectory(atPath: directory.path())) ?? []
|
||||||
|
let fullPathContents = contentsOfDirectory.map { directory.appending(path: $0).path() }
|
||||||
|
|
||||||
|
let untracked = Set(fullPathContents)
|
||||||
|
.subtracting(validPaths)
|
||||||
|
for path in untracked {
|
||||||
|
// string instead of fileURLWithPath since we're already using fileURL format.
|
||||||
|
try? FileManager.default.removeItem(at: URL(string: path)!)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: nil)
|
||||||
|
for secret in secrets {
|
||||||
|
let path = publicKeyPath(for: secret)
|
||||||
|
let data = Data(keyWriter.openSSHString(secret: secret).utf8)
|
||||||
|
FileManager.default.createFile(atPath: path, contents: data, attributes: nil)
|
||||||
|
}
|
||||||
|
logger.log("Finished writing public keys")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The path for a Secret's public key.
|
||||||
|
/// - Parameter secret: The Secret to return the path for.
|
||||||
|
/// - Returns: The path to the Secret's public key.
|
||||||
|
/// - Warning: This method returning a path does not imply that a key has been written to disk already. This method only describes where it will be written to.
|
||||||
|
public func publicKeyPath<SecretType: Secret>(for secret: SecretType) -> String {
|
||||||
|
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "")
|
||||||
|
return directory.appending(component: "\(minimalHex).pub").path()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Short-circuit check to ship enumerating a bunch of paths if there's nothing in the cert directory.
|
||||||
|
public var hasAnyCertificates: Bool {
|
||||||
|
do {
|
||||||
|
return try FileManager.default
|
||||||
|
.contentsOfDirectory(atPath: directory.path())
|
||||||
|
.filter { $0.hasSuffix("-cert.pub") }
|
||||||
|
.isEmpty == false
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The path for a Secret's SSH Certificate public key.
|
||||||
|
/// - Parameter secret: The Secret to return the path for.
|
||||||
|
/// - Returns: The path to the SSH Certificate public key.
|
||||||
|
/// - Warning: This method returning a path does not imply that a key has a SSH certificates. This method only describes where it will be.
|
||||||
|
public func sshCertificatePath<SecretType: Secret>(for secret: SecretType) -> String {
|
||||||
|
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "")
|
||||||
|
return directory.appending(component: "\(minimalHex)-cert.pub").path()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,46 +1,47 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
import Observation
|
||||||
|
|
||||||
/// A "Store Store," which holds a list of type-erased stores.
|
/// A "Store Store," which holds a list of type-erased stores.
|
||||||
public class SecretStoreList: ObservableObject {
|
@Observable @MainActor public final class SecretStoreList: Sendable {
|
||||||
|
|
||||||
/// The Stores managed by the SecretStoreList.
|
/// The Stores managed by the SecretStoreList.
|
||||||
@Published public var stores: [AnySecretStore] = []
|
public var stores: [AnySecretStore] = []
|
||||||
/// A modifiable store, if one is available.
|
/// A modifiable store, if one is available.
|
||||||
@Published public var modifiableStore: AnySecretStoreModifiable?
|
public var modifiableStore: AnySecretStoreModifiable? = nil
|
||||||
private var sinks: [AnyCancellable] = []
|
|
||||||
|
|
||||||
/// Initializes a SecretStoreList.
|
/// Initializes a SecretStoreList.
|
||||||
public init() {
|
public nonisolated init() {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds a non-type-erased SecretStore to the list.
|
/// Adds a non-type-erased SecretStore to the list.
|
||||||
public func add<SecretStoreType: SecretStore>(store: SecretStoreType) {
|
public func add<SecretStoreType: SecretStore>(store: SecretStoreType) {
|
||||||
addInternal(store: AnySecretStore(store))
|
stores.append(AnySecretStore(store))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds a non-type-erased modifiable SecretStore.
|
/// Adds a non-type-erased modifiable SecretStore.
|
||||||
public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) {
|
public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) {
|
||||||
let modifiable = AnySecretStoreModifiable(modifiable: store)
|
let modifiable = AnySecretStoreModifiable(store)
|
||||||
modifiableStore = modifiable
|
if modifiableStore == nil {
|
||||||
addInternal(store: modifiable)
|
modifiableStore = modifiable
|
||||||
|
}
|
||||||
|
stores.append(modifiable)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A boolean describing whether there are any Stores available.
|
/// A boolean describing whether there are any Stores available.
|
||||||
public var anyAvailable: Bool {
|
public var anyAvailable: Bool {
|
||||||
stores.reduce(false, { $0 || $1.isAvailable })
|
stores.contains(where: \.isAvailable)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
public var allSecrets: [AnySecret] {
|
||||||
|
stores.flatMap(\.secrets)
|
||||||
|
}
|
||||||
|
|
||||||
extension SecretStoreList {
|
public var allSecretsWithStores: [(AnySecret, AnySecretStore)] {
|
||||||
|
stores.flatMap { store in
|
||||||
private func addInternal(store: AnySecretStore) {
|
store.secrets.map { secret in
|
||||||
stores.append(store)
|
(secret, store)
|
||||||
let sink = store.objectWillChange.sink {
|
}
|
||||||
self.objectWillChange.send()
|
|
||||||
}
|
}
|
||||||
sinks.append(sink)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
public struct Attributes: Sendable, Codable, Hashable {
|
||||||
|
|
||||||
|
/// The type of key involved.
|
||||||
|
public let keyType: KeyType
|
||||||
|
|
||||||
|
/// The authentication requirements for the key. This is simply a description of the option recorded at creation – modifying it doers not modify the key's authentication requirements.
|
||||||
|
public let authentication: AuthenticationRequirement
|
||||||
|
|
||||||
|
/// The string appended to the end of the SSH Public Key.
|
||||||
|
/// If nil, a default value will be used.
|
||||||
|
public var publicKeyAttribution: String?
|
||||||
|
|
||||||
|
public init(
|
||||||
|
keyType: KeyType,
|
||||||
|
authentication: AuthenticationRequirement,
|
||||||
|
publicKeyAttribution: String? = nil
|
||||||
|
) {
|
||||||
|
self.keyType = keyType
|
||||||
|
self.authentication = authentication
|
||||||
|
self.publicKeyAttribution = publicKeyAttribution
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct UnsupportedOptionError: Error {
|
||||||
|
package init() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The option specified
|
||||||
|
public enum AuthenticationRequirement: String, Hashable, Sendable, Codable, Identifiable {
|
||||||
|
|
||||||
|
/// Authentication is not required for usage.
|
||||||
|
case notRequired
|
||||||
|
|
||||||
|
/// The user needs to authenticate, using either a biometric option, a connected authorized watch, or password entry..
|
||||||
|
case presenceRequired
|
||||||
|
|
||||||
|
/// ONLY the current set of biometric data, as matching at time of creation, is accepted.
|
||||||
|
/// - Warning: This is a dangerous option prone to data loss. The user should be warned before configuring this key that if they modify their enrolled biometry INCLUDING by simply adding a new entry (ie, adding another fingeprting), the key will no longer be able to be accessed. This cannot be overridden with a password.
|
||||||
|
case biometryCurrent
|
||||||
|
|
||||||
|
/// The authentication requirement was not recorded at creation, and is unknown.
|
||||||
|
case unknown
|
||||||
|
|
||||||
|
/// Whether or not the key is known to require authentication.
|
||||||
|
public var required: Bool {
|
||||||
|
self == .presenceRequired || self == .biometryCurrent
|
||||||
|
}
|
||||||
|
|
||||||
|
public var id: AuthenticationRequirement {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Protocol describing a persisted authentication context. This is an authorization that can be reused for multiple access to a secret that requires authentication for a specific period of time.
|
||||||
|
public protocol PersistedAuthenticationContext: Sendable {
|
||||||
|
/// Whether the context remains valid.
|
||||||
|
var valid: Bool { get }
|
||||||
|
/// The date at which the authorization expires and the context becomes invalid.
|
||||||
|
var expiration: Date { get }
|
||||||
|
}
|
||||||
@@ -1,33 +1,85 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
/// The base protocol for describing a Secret
|
/// The base protocol for describing a Secret
|
||||||
public protocol Secret: Identifiable, Hashable {
|
public protocol Secret: Identifiable, Hashable, Sendable {
|
||||||
|
|
||||||
/// A user-facing string identifying the Secret.
|
/// A user-facing string identifying the Secret.
|
||||||
var name: String { get }
|
var name: String { get }
|
||||||
/// The algorithm this secret uses.
|
|
||||||
var algorithm: Algorithm { get }
|
|
||||||
/// The key size for the secret.
|
|
||||||
var keySize: Int { get }
|
|
||||||
/// The public key data for the secret.
|
/// The public key data for the secret.
|
||||||
var publicKey: Data { get }
|
var publicKey: Data { get }
|
||||||
|
/// The attributes of the key.
|
||||||
|
var attributes: Attributes { get }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The type of algorithm the Secret uses. Currently, only elliptic curve algorithms are supported.
|
public extension Secret {
|
||||||
public enum Algorithm: Hashable {
|
|
||||||
|
|
||||||
case ellipticCurve
|
/// The algorithm and key size this secret uses.
|
||||||
|
var keyType: KeyType {
|
||||||
|
attributes.keyType
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the secret requires authentication before use.
|
||||||
|
var authenticationRequirement: AuthenticationRequirement {
|
||||||
|
attributes.authentication
|
||||||
|
}
|
||||||
|
/// An attribution string to apply to the generated public key.
|
||||||
|
var publicKeyAttribution: String? {
|
||||||
|
attributes.publicKeyAttribution
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The type of algorithm the Secret uses.
|
||||||
|
public struct KeyType: Hashable, Sendable, Codable, CustomStringConvertible {
|
||||||
|
|
||||||
|
public static let ecdsa256 = KeyType(algorithm: .ecdsa, size: 256)
|
||||||
|
public static let ecdsa384 = KeyType(algorithm: .ecdsa, size: 384)
|
||||||
|
public static let mldsa65 = KeyType(algorithm: .mldsa, size: 65)
|
||||||
|
public static let mldsa87 = KeyType(algorithm: .mldsa, size: 87)
|
||||||
|
public static let rsa2048 = KeyType(algorithm: .rsa, size: 2048)
|
||||||
|
|
||||||
|
public enum Algorithm: Hashable, Sendable, Codable {
|
||||||
|
case ecdsa
|
||||||
|
case mldsa
|
||||||
|
case rsa
|
||||||
|
}
|
||||||
|
|
||||||
|
public var algorithm: Algorithm
|
||||||
|
public var size: Int
|
||||||
|
|
||||||
|
public init(algorithm: Algorithm, size: Int) {
|
||||||
|
self.algorithm = algorithm
|
||||||
|
self.size = size
|
||||||
|
}
|
||||||
|
|
||||||
/// Initializes the Algorithm with a secAttr representation of an algorithm.
|
/// Initializes the Algorithm with a secAttr representation of an algorithm.
|
||||||
/// - Parameter secAttr: the secAttr, represented as an NSNumber.
|
/// - Parameter secAttr: the secAttr, represented as an NSNumber.
|
||||||
public init(secAttr: NSNumber) {
|
public init?(secAttr: NSNumber, size: Int) {
|
||||||
let secAttrString = secAttr.stringValue as CFString
|
let secAttrString = secAttr.stringValue as CFString
|
||||||
switch secAttrString {
|
switch secAttrString {
|
||||||
case kSecAttrKeyTypeEC:
|
case kSecAttrKeyTypeEC:
|
||||||
self = .ellipticCurve
|
algorithm = .ecdsa
|
||||||
|
case kSecAttrKeyTypeRSA:
|
||||||
|
algorithm = .rsa
|
||||||
default:
|
default:
|
||||||
fatalError()
|
return nil
|
||||||
|
}
|
||||||
|
self.size = size
|
||||||
|
}
|
||||||
|
|
||||||
|
public var secAttrKeyType: CFString? {
|
||||||
|
switch algorithm {
|
||||||
|
case .ecdsa:
|
||||||
|
kSecAttrKeyTypeEC
|
||||||
|
case .rsa:
|
||||||
|
kSecAttrKeyTypeRSA
|
||||||
|
case .mldsa:
|
||||||
|
nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public var description: String {
|
||||||
|
"\(algorithm)-\(size)"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,61 +1,103 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
|
||||||
|
|
||||||
/// Manages access to Secrets, and performs signature operations on data using those Secrets.
|
/// Manages access to Secrets, and performs signature operations on data using those Secrets.
|
||||||
public protocol SecretStore: ObservableObject, Identifiable {
|
public protocol SecretStore<SecretType>: Identifiable, Sendable {
|
||||||
|
|
||||||
associatedtype SecretType: Secret
|
associatedtype SecretType: Secret
|
||||||
|
|
||||||
/// A boolean indicating whether or not the store is available.
|
/// A boolean indicating whether or not the store is available.
|
||||||
var isAvailable: Bool { get }
|
@MainActor var isAvailable: Bool { get }
|
||||||
/// A unique identifier for the store.
|
/// A unique identifier for the store.
|
||||||
var id: UUID { get }
|
var id: UUID { get }
|
||||||
/// A user-facing name for the store.
|
/// A user-facing name for the store.
|
||||||
var name: String { get }
|
@MainActor var name: String { get }
|
||||||
/// The secrets the store manages.
|
/// The secrets the store manages.
|
||||||
var secrets: [SecretType] { get }
|
@MainActor var secrets: [SecretType] { get }
|
||||||
|
|
||||||
/// Signs a data payload with a specified Secret.
|
/// Signs a data payload with a specified Secret.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - data: The data to sign.
|
/// - data: The data to sign.
|
||||||
/// - secret: The ``Secret`` to sign with.
|
/// - secret: The ``Secret`` to sign with.
|
||||||
/// - provenance: A ``SigningRequestProvenance`` describing where the request came from.
|
/// - provenance: A ``SigningRequestProvenance`` describing where the request came from.
|
||||||
/// - Returns: A ``SignedData`` object, containing the signature and metadata about the signature process.
|
/// - Returns: The signed data.
|
||||||
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData
|
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) async throws -> Data
|
||||||
|
|
||||||
|
/// Checks to see if there is currently a valid persisted authentication for a given secret.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The ``Secret`` to check if there is a persisted authentication for.
|
||||||
|
/// - Returns: A persisted authentication context, if a valid one exists.
|
||||||
|
func existingPersistedAuthenticationContext(secret: SecretType) async -> PersistedAuthenticationContext?
|
||||||
|
|
||||||
/// Persists user authorization for access to a secret.
|
/// Persists user authorization for access to a secret.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - secret: The ``Secret`` to persist the authorization for.
|
/// - secret: The ``Secret`` to persist the authorization for.
|
||||||
/// - duration: The duration that the authorization should persist for.
|
/// - duration: The duration that the authorization should persist for.
|
||||||
/// - Note: This is used for temporarily unlocking access to a secret which would otherwise require authentication every single use. This is useful for situations where the user anticipates several rapid accesses to a authorization-guarded secret.
|
/// - Note: This is used for temporarily unlocking access to a secret which would otherwise require authentication every single use. This is useful for situations where the user anticipates several rapid accesses to a authorization-guarded secret.
|
||||||
func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) throws
|
func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) async throws
|
||||||
|
|
||||||
|
/// Requests that the store reload secrets from any backing store, if neccessary.
|
||||||
|
func reloadSecrets() async
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A SecretStore that the Secretive admin app can modify.
|
/// A SecretStore that the Secretive admin app can modify.
|
||||||
public protocol SecretStoreModifiable: SecretStore {
|
public protocol SecretStoreModifiable<SecretType>: SecretStore {
|
||||||
|
|
||||||
/// Creates a new ``Secret`` in the store.
|
/// Creates a new ``Secret`` in the store.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - name: The user-facing name for the ``Secret``.
|
/// - name: The user-facing name for the ``Secret``.
|
||||||
/// - requiresAuthentication: A boolean indicating whether or not the user will be required to authenticate before performing signature operations with the secret.
|
/// - attributes: A struct describing the options for creating the key.'
|
||||||
func create(name: String, requiresAuthentication: Bool) throws
|
@discardableResult
|
||||||
|
func create(name: String, attributes: Attributes) async throws -> SecretType
|
||||||
|
|
||||||
/// Deletes a Secret in the store.
|
/// Deletes a Secret in the store.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - secret: The ``Secret`` to delete.
|
/// - secret: The ``Secret`` to delete.
|
||||||
func delete(secret: SecretType) throws
|
func delete(secret: SecretType) async throws
|
||||||
|
|
||||||
/// Updates the name of a Secret in the store.
|
/// Updates the name of a Secret in the store.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - secret: The ``Secret`` to update.
|
/// - secret: The ``Secret`` to update.
|
||||||
/// - name: The new name for the Secret.
|
/// - name: The new name for the Secret.
|
||||||
func update(secret: SecretType, name: String) throws
|
/// - attributes: The new attributes for the secret.
|
||||||
|
func update(secret: SecretType, name: String, attributes: Attributes) async throws
|
||||||
|
|
||||||
|
var supportedKeyTypes: KeyAvailability { get }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public struct KeyAvailability: Sendable {
|
||||||
|
|
||||||
|
public let available: [KeyType]
|
||||||
|
public let unavailable: [UnavailableKeyType]
|
||||||
|
|
||||||
|
public init(available: [KeyType], unavailable: [UnavailableKeyType]) {
|
||||||
|
self.available = available
|
||||||
|
self.unavailable = unavailable
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct UnavailableKeyType: Sendable {
|
||||||
|
public let keyType: KeyType
|
||||||
|
public let reason: Reason
|
||||||
|
|
||||||
|
public init(keyType: KeyType, reason: Reason) {
|
||||||
|
self.keyType = keyType
|
||||||
|
self.reason = reason
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum Reason: Sendable {
|
||||||
|
case macOSUpdateRequired
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
extension NSNotification.Name {
|
extension NSNotification.Name {
|
||||||
|
|
||||||
|
// Distributed notification that keys were modified out of process (ie, that the management tool added/removed secrets)
|
||||||
public static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated")
|
public static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated")
|
||||||
|
// Internal notification that keys were reloaded from the backing store.
|
||||||
|
public static let secretStoreReloaded = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.reloaded")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
|
|
||||||
/// Describes the output of a sign request.
|
|
||||||
public struct SignedData {
|
|
||||||
|
|
||||||
/// The signed data.
|
|
||||||
public let data: Data
|
|
||||||
/// A boolean describing whether authentication was required during the signature process.
|
|
||||||
public let requiredAuthentication: Bool
|
|
||||||
|
|
||||||
/// Initializes a new SignedData.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - data: The signed data.
|
|
||||||
/// - requiredAuthentication: A boolean describing whether authentication was required during the signature process.
|
|
||||||
public init(data: Data, requiredAuthentication: Bool) {
|
|
||||||
self.data = data
|
|
||||||
self.requiredAuthentication = requiredAuthentication
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,7 @@ import Foundation
|
|||||||
import AppKit
|
import AppKit
|
||||||
|
|
||||||
/// Describes the chain of applications that requested a signature operation.
|
/// Describes the chain of applications that requested a signature operation.
|
||||||
public struct SigningRequestProvenance: Equatable {
|
public struct SigningRequestProvenance: Equatable, Sendable {
|
||||||
|
|
||||||
/// A list of processes involved in the request.
|
/// A list of processes involved in the request.
|
||||||
/// - Note: A chain will typically consist of many elements even for a simple request. For example, running `git fetch` in Terminal.app would generate a request chain of `ssh` -> `git` -> `zsh` -> `login` -> `Terminal.app`
|
/// - Note: A chain will typically consist of many elements even for a simple request. For example, running `git fetch` in Terminal.app would generate a request chain of `ssh` -> `git` -> `zsh` -> `login` -> `Terminal.app`
|
||||||
@@ -30,7 +30,7 @@ extension SigningRequestProvenance {
|
|||||||
extension SigningRequestProvenance {
|
extension SigningRequestProvenance {
|
||||||
|
|
||||||
/// Describes a process in a `SigningRequestProvenance` chain.
|
/// Describes a process in a `SigningRequestProvenance` chain.
|
||||||
public struct Process: Equatable {
|
public struct Process: Equatable, Sendable {
|
||||||
|
|
||||||
/// The pid of the process.
|
/// The pid of the process.
|
||||||
public let pid: Int32
|
public let pid: Int32
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import Foundation
|
||||||
|
import Security
|
||||||
|
import CryptoTokenKit
|
||||||
|
import CryptoKit
|
||||||
|
import SecretKit
|
||||||
|
import os
|
||||||
|
|
||||||
|
extension SecureEnclave {
|
||||||
|
|
||||||
|
public struct CryptoKitMigrator {
|
||||||
|
|
||||||
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.migration", category: "CryptoKitMigrator")
|
||||||
|
|
||||||
|
public init() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keys prior to 3.0 were created and stored directly using the keychain as kSecClassKey items. CryptoKit operates a little differently, in that it creates a key on your behalf which you can persist using an opaque data blob to a generic keychain item. Keychain created keys _also_ use this blob under the hood, but it's stored in the "toid" attribute. This migrates the old keys from kSecClassKey to generic items, copying the "toid" to be the main stored data. If the key is migrated successfully, the old key's identifier is renamed to indicate it's been migrated.
|
||||||
|
/// - Note: Migration is non-destructive – users can still see and use their keys in older versions of Secretive.
|
||||||
|
@MainActor public func migrate(to store: Store) throws {
|
||||||
|
let privateAttributes = KeychainDictionary([
|
||||||
|
kSecClass: kSecClassKey,
|
||||||
|
kSecAttrKeyType: Constants.oldKeyType,
|
||||||
|
kSecAttrApplicationTag: SecureEnclave.Store.Constants.keyTag,
|
||||||
|
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||||
|
kSecReturnRef: true,
|
||||||
|
kSecMatchLimit: kSecMatchLimitAll,
|
||||||
|
kSecReturnAttributes: true
|
||||||
|
])
|
||||||
|
var privateUntyped: CFTypeRef?
|
||||||
|
unsafe SecItemCopyMatching(privateAttributes, &privateUntyped)
|
||||||
|
guard let privateTyped = privateUntyped as? [[CFString: Any]] else { return }
|
||||||
|
let migratedPublicKeys = Set(store.secrets.map(\.publicKey))
|
||||||
|
var migratedAny = false
|
||||||
|
for key in privateTyped {
|
||||||
|
let name = key[kSecAttrLabel] as? String ?? String(localized: .unnamedSecret)
|
||||||
|
let id = key[kSecAttrApplicationLabel] as! Data
|
||||||
|
guard !id.contains(Constants.migrationMagicNumber) else {
|
||||||
|
logger.log("Skipping \(name), already migrated.")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let ref = key[kSecValueRef] as! SecKey
|
||||||
|
let attributes = SecKeyCopyAttributes(ref) as! [CFString: Any]
|
||||||
|
let tokenObjectID = unsafe attributes[Constants.tokenObjectID] as! Data
|
||||||
|
let accessControl = attributes[kSecAttrAccessControl] as! SecAccessControl
|
||||||
|
// Best guess.
|
||||||
|
let auth: AuthenticationRequirement = String(describing: accessControl)
|
||||||
|
.contains("DeviceOwnerAuthentication") ? .presenceRequired : .unknown
|
||||||
|
do {
|
||||||
|
let parsed = try CryptoKit.SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: tokenObjectID)
|
||||||
|
let secret = Secret(id: UUID().uuidString, name: name, publicKey: parsed.publicKey.x963Representation, attributes: Attributes(keyType: .init(algorithm: .ecdsa, size: 256), authentication: auth))
|
||||||
|
guard !migratedPublicKeys.contains(parsed.publicKey.x963Representation) else {
|
||||||
|
logger.log("Skipping \(name), public key already present. Marking as migrated.")
|
||||||
|
markMigrated(secret: secret, oldID: id)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
logger.log("Migrating \(name).")
|
||||||
|
try store.saveKey(tokenObjectID, name: name, attributes: secret.attributes)
|
||||||
|
logger.log("Migrated \(name).")
|
||||||
|
markMigrated(secret: secret, oldID: id)
|
||||||
|
migratedAny = true
|
||||||
|
} catch {
|
||||||
|
logger.error("Failed to migrate \(name): \(error.localizedDescription).")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if migratedAny {
|
||||||
|
store.reloadSecrets()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public func markMigrated(secret: Secret, oldID: Data) {
|
||||||
|
let updateQuery = KeychainDictionary([
|
||||||
|
kSecClass: kSecClassKey,
|
||||||
|
kSecAttrApplicationLabel: oldID
|
||||||
|
])
|
||||||
|
|
||||||
|
let newID = oldID + Constants.migrationMagicNumber
|
||||||
|
let updatedAttributes = KeychainDictionary([
|
||||||
|
kSecAttrApplicationLabel: newID as CFData
|
||||||
|
])
|
||||||
|
|
||||||
|
let status = SecItemUpdate(updateQuery, updatedAttributes)
|
||||||
|
if status != errSecSuccess {
|
||||||
|
logger.warning("Failed to mark \(secret.name) as migrated: \(status).")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SecureEnclave.CryptoKitMigrator {
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
public static let oldKeyType = kSecAttrKeyTypeECSECPrimeRandom as String
|
||||||
|
public static let migrationMagicNumber = Data("_cryptokit_1".utf8)
|
||||||
|
// https://github.com/apple-opensource/Security/blob/5e9101b3bd1fb096bae4f40e79d50426ba1db8e9/OSX/sec/Security/SecItemConstants.c#L111
|
||||||
|
public static nonisolated(unsafe) let tokenObjectID = "toid" as CFString
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import LocalAuthentication
|
||||||
|
import SecretKit
|
||||||
|
|
||||||
|
extension SecureEnclave {
|
||||||
|
|
||||||
|
/// A context describing a persisted authentication.
|
||||||
|
final class PersistentAuthenticationContext: PersistedAuthenticationContext {
|
||||||
|
|
||||||
|
/// The Secret to persist authentication for.
|
||||||
|
let secret: Secret
|
||||||
|
/// The LAContext used to authorize the persistent context.
|
||||||
|
nonisolated(unsafe) let context: LAContext
|
||||||
|
/// An expiration date for the context.
|
||||||
|
/// - Note - Monotonic time instead of Date() to prevent people setting the clock back.
|
||||||
|
let monotonicExpiration: UInt64
|
||||||
|
|
||||||
|
/// Initializes a context.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The Secret to persist authentication for.
|
||||||
|
/// - context: The LAContext used to authorize the persistent context.
|
||||||
|
/// - duration: The duration of the authorization context, in seconds.
|
||||||
|
init(secret: Secret, context: LAContext, duration: TimeInterval) {
|
||||||
|
self.secret = secret
|
||||||
|
unsafe self.context = context
|
||||||
|
let durationInNanoSeconds = Measurement(value: duration, unit: UnitDuration.seconds).converted(to: .nanoseconds).value
|
||||||
|
self.monotonicExpiration = clock_gettime_nsec_np(CLOCK_MONOTONIC) + UInt64(durationInNanoSeconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A boolean describing whether or not the context is still valid.
|
||||||
|
var valid: Bool {
|
||||||
|
clock_gettime_nsec_np(CLOCK_MONOTONIC) < monotonicExpiration
|
||||||
|
}
|
||||||
|
|
||||||
|
var expiration: Date {
|
||||||
|
let remainingNanoseconds = monotonicExpiration - clock_gettime_nsec_np(CLOCK_MONOTONIC)
|
||||||
|
let remainingInSeconds = Measurement(value: Double(remainingNanoseconds), unit: UnitDuration.nanoseconds).converted(to: .seconds).value
|
||||||
|
return Date(timeIntervalSinceNow: remainingInSeconds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actor PersistentAuthenticationHandler: Sendable {
|
||||||
|
|
||||||
|
private var persistedAuthenticationContexts: [Secret: PersistentAuthenticationContext] = [:]
|
||||||
|
|
||||||
|
func existingPersistedAuthenticationContext(secret: Secret) -> PersistentAuthenticationContext? {
|
||||||
|
guard let persisted = persistedAuthenticationContexts[secret], persisted.valid else { return nil }
|
||||||
|
return persisted
|
||||||
|
}
|
||||||
|
|
||||||
|
func persistAuthentication(secret: Secret, forDuration duration: TimeInterval) async throws {
|
||||||
|
let newContext = LAContext()
|
||||||
|
newContext.touchIDAuthenticationAllowableReuseDuration = duration
|
||||||
|
newContext.localizedCancelTitle = String(localized: .authContextRequestDenyButton)
|
||||||
|
|
||||||
|
let formatter = DateComponentsFormatter()
|
||||||
|
formatter.unitsStyle = .spellOut
|
||||||
|
formatter.allowedUnits = [.hour, .minute, .day]
|
||||||
|
|
||||||
|
|
||||||
|
let durationString = formatter.string(from: duration)!
|
||||||
|
newContext.localizedReason = String(localized: .authContextPersistForDuration(secretName: secret.name, duration: durationString))
|
||||||
|
let success = try await newContext.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: newContext.localizedReason)
|
||||||
|
guard success else { return }
|
||||||
|
let context = PersistentAuthenticationContext(secret: secret, context: newContext, duration: duration)
|
||||||
|
persistedAuthenticationContexts[secret] = context
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
|
||||||
import SecretKit
|
import SecretKit
|
||||||
|
|
||||||
extension SecureEnclave {
|
extension SecureEnclave {
|
||||||
@@ -7,11 +6,26 @@ extension SecureEnclave {
|
|||||||
/// An implementation of Secret backed by the Secure Enclave.
|
/// An implementation of Secret backed by the Secure Enclave.
|
||||||
public struct Secret: SecretKit.Secret {
|
public struct Secret: SecretKit.Secret {
|
||||||
|
|
||||||
public let id: Data
|
public let id: String
|
||||||
public let name: String
|
public let name: String
|
||||||
public let algorithm = Algorithm.ellipticCurve
|
|
||||||
public let keySize = 256
|
|
||||||
public let publicKey: Data
|
public let publicKey: Data
|
||||||
|
public let attributes: Attributes
|
||||||
|
|
||||||
|
init(
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
publicKey: Data,
|
||||||
|
attributes: Attributes
|
||||||
|
) {
|
||||||
|
self.id = id
|
||||||
|
self.name = name
|
||||||
|
self.publicKey = publicKey
|
||||||
|
self.attributes = attributes
|
||||||
|
}
|
||||||
|
|
||||||
|
public static func ==(lhs: Self, rhs: Self) -> Bool {
|
||||||
|
lhs.id == rhs.id
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,294 +1,297 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
import Observation
|
||||||
import Security
|
import Security
|
||||||
import CryptoTokenKit
|
import CryptoKit
|
||||||
import LocalAuthentication
|
import LocalAuthentication
|
||||||
import SecretKit
|
import SecretKit
|
||||||
|
import os
|
||||||
|
|
||||||
extension SecureEnclave {
|
extension SecureEnclave {
|
||||||
|
|
||||||
/// An implementation of Store backed by the Secure Enclave.
|
/// An implementation of Store backed by the Secure Enclave using CryptoKit API.
|
||||||
public class Store: SecretStoreModifiable {
|
@Observable public final class Store: SecretStoreModifiable {
|
||||||
|
|
||||||
|
@MainActor public var secrets: [Secret] = []
|
||||||
public var isAvailable: Bool {
|
public var isAvailable: Bool {
|
||||||
// For some reason, as of build time, CryptoKit.SecureEnclave.isAvailable always returns false
|
CryptoKit.SecureEnclave.isAvailable
|
||||||
// error msg "Received error sending GET UNIQUE DEVICE command"
|
|
||||||
// Verify it with TKTokenWatcher manually.
|
|
||||||
TKTokenWatcher().tokenIDs.contains("com.apple.setoken")
|
|
||||||
}
|
}
|
||||||
public let id = UUID()
|
public let id = UUID()
|
||||||
public let name = NSLocalizedString("Secure Enclave", comment: "Secure Enclave")
|
public let name = String(localized: .secureEnclave)
|
||||||
@Published public private(set) var secrets: [Secret] = []
|
private let persistentAuthenticationHandler = PersistentAuthenticationHandler()
|
||||||
|
|
||||||
private var persistedAuthenticationContexts: [Secret: PersistentAuthenticationContext] = [:]
|
|
||||||
|
|
||||||
/// Initializes a Store.
|
/// Initializes a Store.
|
||||||
public init() {
|
@MainActor public init() {
|
||||||
DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { _ in
|
|
||||||
self.reloadSecrets(notify: false)
|
|
||||||
}
|
|
||||||
loadSecrets()
|
loadSecrets()
|
||||||
|
Task {
|
||||||
|
for await note in DistributedNotificationCenter.default().notifications(named: .secretStoreUpdated) {
|
||||||
|
guard Constants.notificationToken != (note.object as? String) else {
|
||||||
|
// Don't reload if we're the ones triggering this by reloading.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
reloadSecrets()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Public API
|
// MARK: - Public API
|
||||||
|
|
||||||
public func create(name: String, requiresAuthentication: Bool) throws {
|
// MARK: SecretStore
|
||||||
var accessError: SecurityError?
|
|
||||||
let flags: SecAccessControlCreateFlags
|
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) async throws -> Data {
|
||||||
if requiresAuthentication {
|
var context: LAContext
|
||||||
flags = [.privateKeyUsage, .userPresence]
|
if let existing = await persistentAuthenticationHandler.existingPersistedAuthenticationContext(secret: secret) {
|
||||||
|
context = unsafe existing.context
|
||||||
} else {
|
} else {
|
||||||
flags = .privateKeyUsage
|
let newContext = LAContext()
|
||||||
|
newContext.localizedReason = String(localized: .authContextRequestSignatureDescription(appName: provenance.origin.displayName, secretName: secret.name))
|
||||||
|
newContext.localizedCancelTitle = String(localized: .authContextRequestDenyButton)
|
||||||
|
context = newContext
|
||||||
|
}
|
||||||
|
|
||||||
|
let queryAttributes = KeychainDictionary([
|
||||||
|
kSecClass: Constants.keyClass,
|
||||||
|
kSecAttrService: Constants.keyTag,
|
||||||
|
kSecUseDataProtectionKeychain: true,
|
||||||
|
kSecAttrAccount: secret.id,
|
||||||
|
kSecReturnAttributes: true,
|
||||||
|
kSecReturnData: true,
|
||||||
|
])
|
||||||
|
var untyped: CFTypeRef?
|
||||||
|
let status = unsafe SecItemCopyMatching(queryAttributes, &untyped)
|
||||||
|
if status != errSecSuccess {
|
||||||
|
throw KeychainError(statusCode: status)
|
||||||
|
}
|
||||||
|
guard let untypedSafe = untyped as? [CFString: Any] else {
|
||||||
|
throw KeychainError(statusCode: errSecSuccess)
|
||||||
|
}
|
||||||
|
guard let attributesData = untypedSafe[kSecAttrGeneric] as? Data,
|
||||||
|
let keyData = untypedSafe[kSecValueData] as? Data else {
|
||||||
|
throw MissingAttributesError()
|
||||||
|
}
|
||||||
|
let attributes = try JSONDecoder().decode(Attributes.self, from: attributesData)
|
||||||
|
|
||||||
|
switch attributes.keyType {
|
||||||
|
case .ecdsa256:
|
||||||
|
let key = try CryptoKit.SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: keyData, authenticationContext: context)
|
||||||
|
return try key.signature(for: data).rawRepresentation
|
||||||
|
case .mldsa65:
|
||||||
|
guard #available(macOS 26.0, *) else { throw UnsupportedAlgorithmError() }
|
||||||
|
let key = try CryptoKit.SecureEnclave.MLDSA65.PrivateKey(dataRepresentation: keyData, authenticationContext: context)
|
||||||
|
return try key.signature(for: data)
|
||||||
|
case .mldsa87:
|
||||||
|
guard #available(macOS 26.0, *) else { throw UnsupportedAlgorithmError() }
|
||||||
|
let key = try CryptoKit.SecureEnclave.MLDSA87.PrivateKey(dataRepresentation: keyData, authenticationContext: context)
|
||||||
|
return try key.signature(for: data)
|
||||||
|
default:
|
||||||
|
throw UnsupportedAlgorithmError()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public func existingPersistedAuthenticationContext(secret: Secret) async -> PersistedAuthenticationContext? {
|
||||||
|
await persistentAuthenticationHandler.existingPersistedAuthenticationContext(secret: secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func persistAuthentication(secret: Secret, forDuration duration: TimeInterval) async throws {
|
||||||
|
try await persistentAuthenticationHandler.persistAuthentication(secret: secret, forDuration: duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor public func reloadSecrets() {
|
||||||
|
let before = secrets
|
||||||
|
secrets.removeAll()
|
||||||
|
loadSecrets()
|
||||||
|
if secrets != before {
|
||||||
|
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
|
||||||
|
DistributedNotificationCenter.default().postNotificationName(.secretStoreUpdated, object: Constants.notificationToken, deliverImmediately: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: SecretStoreModifiable
|
||||||
|
|
||||||
|
public func create(name: String, attributes: Attributes) async throws -> Secret {
|
||||||
|
var accessError: SecurityError?
|
||||||
|
let flags: SecAccessControlCreateFlags = switch attributes.authentication {
|
||||||
|
case .notRequired:
|
||||||
|
[.privateKeyUsage]
|
||||||
|
case .presenceRequired:
|
||||||
|
[.userPresence, .privateKeyUsage]
|
||||||
|
case .biometryCurrent:
|
||||||
|
[.biometryCurrentSet, .privateKeyUsage]
|
||||||
|
case .unknown:
|
||||||
|
fatalError()
|
||||||
}
|
}
|
||||||
let access =
|
let access =
|
||||||
SecAccessControlCreateWithFlags(kCFAllocatorDefault,
|
unsafe SecAccessControlCreateWithFlags(kCFAllocatorDefault,
|
||||||
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
||||||
flags,
|
flags,
|
||||||
&accessError) as Any
|
&accessError)
|
||||||
if let error = accessError {
|
if let error = unsafe accessError {
|
||||||
throw error.takeRetainedValue() as Error
|
throw unsafe error.takeRetainedValue() as Error
|
||||||
}
|
}
|
||||||
|
let dataRep: Data
|
||||||
let attributes = [
|
let publicKey: Data
|
||||||
kSecAttrLabel: name,
|
switch attributes.keyType {
|
||||||
kSecAttrKeyType: Constants.keyType,
|
case .ecdsa256:
|
||||||
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
|
let created = try CryptoKit.SecureEnclave.P256.Signing.PrivateKey(accessControl: access!)
|
||||||
kSecAttrApplicationTag: Constants.keyTag,
|
dataRep = created.dataRepresentation
|
||||||
kSecPrivateKeyAttrs: [
|
publicKey = created.publicKey.x963Representation
|
||||||
kSecAttrIsPermanent: true,
|
case .mldsa65:
|
||||||
kSecAttrAccessControl: access
|
guard #available(macOS 26.0, *) else { throw Attributes.UnsupportedOptionError() }
|
||||||
]
|
let created = try CryptoKit.SecureEnclave.MLDSA65.PrivateKey(accessControl: access!)
|
||||||
] as CFDictionary
|
dataRep = created.dataRepresentation
|
||||||
|
publicKey = created.publicKey.rawRepresentation
|
||||||
var createKeyError: SecurityError?
|
case .mldsa87:
|
||||||
let keypair = SecKeyCreateRandomKey(attributes, &createKeyError)
|
guard #available(macOS 26.0, *) else { throw Attributes.UnsupportedOptionError() }
|
||||||
if let error = createKeyError {
|
let created = try CryptoKit.SecureEnclave.MLDSA87.PrivateKey(accessControl: access!)
|
||||||
throw error.takeRetainedValue() as Error
|
dataRep = created.dataRepresentation
|
||||||
|
publicKey = created.publicKey.rawRepresentation
|
||||||
|
default:
|
||||||
|
throw Attributes.UnsupportedOptionError()
|
||||||
}
|
}
|
||||||
guard let keypair = keypair, let publicKey = SecKeyCopyPublicKey(keypair) else {
|
let id = try saveKey(dataRep, name: name, attributes: attributes)
|
||||||
throw KeychainError(statusCode: nil)
|
await reloadSecrets()
|
||||||
}
|
return Secret(id: id, name: name, publicKey: publicKey, attributes: attributes)
|
||||||
try savePublicKey(publicKey, name: name)
|
|
||||||
reloadSecrets()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func delete(secret: Secret) throws {
|
public func delete(secret: Secret) async throws {
|
||||||
let deleteAttributes = [
|
let deleteAttributes = KeychainDictionary([
|
||||||
kSecClass: kSecClassKey,
|
kSecClass: Constants.keyClass,
|
||||||
kSecAttrApplicationLabel: secret.id as CFData
|
kSecAttrService: Constants.keyTag,
|
||||||
] as CFDictionary
|
kSecUseDataProtectionKeychain: true,
|
||||||
|
kSecAttrAccount: secret.id,
|
||||||
|
])
|
||||||
let status = SecItemDelete(deleteAttributes)
|
let status = SecItemDelete(deleteAttributes)
|
||||||
if status != errSecSuccess {
|
if status != errSecSuccess {
|
||||||
throw KeychainError(statusCode: status)
|
throw KeychainError(statusCode: status)
|
||||||
}
|
}
|
||||||
reloadSecrets()
|
await reloadSecrets()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func update(secret: Secret, name: String) throws {
|
public func update(secret: Secret, name: String, attributes: Attributes) async throws {
|
||||||
let updateQuery = [
|
let updateQuery = KeychainDictionary([
|
||||||
kSecClass: kSecClassKey,
|
kSecClass: Constants.keyClass,
|
||||||
kSecAttrApplicationLabel: secret.id as CFData
|
kSecAttrAccount: secret.id,
|
||||||
] as CFDictionary
|
])
|
||||||
|
|
||||||
let updatedAttributes = [
|
let attributes = try JSONEncoder().encode(attributes)
|
||||||
|
let updatedAttributes = KeychainDictionary([
|
||||||
kSecAttrLabel: name,
|
kSecAttrLabel: name,
|
||||||
] as CFDictionary
|
kSecAttrGeneric: attributes,
|
||||||
|
])
|
||||||
|
|
||||||
let status = SecItemUpdate(updateQuery, updatedAttributes)
|
let status = SecItemUpdate(updateQuery, updatedAttributes)
|
||||||
if status != errSecSuccess {
|
if status != errSecSuccess {
|
||||||
throw KeychainError(statusCode: status)
|
throw KeychainError(statusCode: status)
|
||||||
}
|
}
|
||||||
reloadSecrets()
|
await reloadSecrets()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
|
public let supportedKeyTypes: KeyAvailability = {
|
||||||
let context: LAContext
|
let macOS26Keys: [KeyType] = [.mldsa65, .mldsa87]
|
||||||
if let existing = persistedAuthenticationContexts[secret], existing.valid {
|
let isAtLeastMacOS26 = if #available(macOS 26, *) {
|
||||||
context = existing.context
|
true
|
||||||
} else {
|
} else {
|
||||||
let newContext = LAContext()
|
false
|
||||||
newContext.localizedCancelTitle = "Deny"
|
|
||||||
context = newContext
|
|
||||||
}
|
}
|
||||||
context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
|
return KeyAvailability(
|
||||||
let attributes = [
|
available: [
|
||||||
kSecClass: kSecClassKey,
|
.ecdsa256,
|
||||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
] + (isAtLeastMacOS26 ? macOS26Keys : []),
|
||||||
kSecAttrApplicationLabel: secret.id as CFData,
|
unavailable: (isAtLeastMacOS26 ? [] : macOS26Keys).map {
|
||||||
kSecAttrKeyType: Constants.keyType,
|
KeyAvailability.UnavailableKeyType(keyType: $0, reason: .macOSUpdateRequired)
|
||||||
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
|
}
|
||||||
kSecAttrApplicationTag: Constants.keyTag,
|
)
|
||||||
kSecUseAuthenticationContext: context,
|
}()
|
||||||
kSecReturnRef: true
|
|
||||||
] as CFDictionary
|
|
||||||
var untyped: CFTypeRef?
|
|
||||||
let status = SecItemCopyMatching(attributes, &untyped)
|
|
||||||
if status != errSecSuccess {
|
|
||||||
throw KeychainError(statusCode: status)
|
|
||||||
}
|
|
||||||
guard let untypedSafe = untyped else {
|
|
||||||
throw KeychainError(statusCode: errSecSuccess)
|
|
||||||
}
|
|
||||||
let key = untypedSafe as! SecKey
|
|
||||||
var signError: SecurityError?
|
|
||||||
|
|
||||||
let signingStartTime = Date()
|
|
||||||
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
|
|
||||||
throw SigningError(error: signError)
|
|
||||||
}
|
|
||||||
let signatureDuration = Date().timeIntervalSince(signingStartTime)
|
|
||||||
// Hack to determine if the user had to authenticate to sign.
|
|
||||||
// Since there's now way to inspect SecAccessControl to determine (afaict).
|
|
||||||
let requiredAuthentication = signatureDuration > Constants.unauthenticatedThreshold
|
|
||||||
|
|
||||||
return SignedData(data: signature as Data, requiredAuthentication: requiredAuthentication)
|
|
||||||
}
|
|
||||||
|
|
||||||
public func persistAuthentication(secret: Secret, forDuration duration: TimeInterval) throws {
|
|
||||||
let newContext = LAContext()
|
|
||||||
newContext.touchIDAuthenticationAllowableReuseDuration = duration
|
|
||||||
newContext.localizedCancelTitle = "Deny"
|
|
||||||
|
|
||||||
let formatter = DateComponentsFormatter()
|
|
||||||
formatter.unitsStyle = .spellOut
|
|
||||||
formatter.allowedUnits = [.hour, .minute, .day]
|
|
||||||
|
|
||||||
if let durationString = formatter.string(from: duration) {
|
|
||||||
newContext.localizedReason = "unlock secret \"\(secret.name)\" for \(durationString)"
|
|
||||||
} else {
|
|
||||||
newContext.localizedReason = "unlock secret \"\(secret.name)\""
|
|
||||||
}
|
|
||||||
newContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: newContext.localizedReason) { [weak self] success, _ in
|
|
||||||
guard success else { return }
|
|
||||||
let context = PersistentAuthenticationContext(secret: secret, context: newContext, duration: duration)
|
|
||||||
self?.persistedAuthenticationContexts[secret] = context
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SecureEnclave.Store {
|
extension SecureEnclave.Store {
|
||||||
|
|
||||||
/// Reloads all secrets from the store.
|
|
||||||
/// - Parameter notify: A boolean indicating whether a distributed notification should be posted, notifying other processes (ie, the SecretAgent) to reload their stores as well.
|
|
||||||
private func reloadSecrets(notify: Bool = true) {
|
|
||||||
secrets.removeAll()
|
|
||||||
loadSecrets()
|
|
||||||
if notify {
|
|
||||||
DistributedNotificationCenter.default().post(name: .secretStoreUpdated, object: nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads all secrets from the store.
|
/// Loads all secrets from the store.
|
||||||
private func loadSecrets() {
|
@MainActor private func loadSecrets() {
|
||||||
let attributes = [
|
let queryAttributes = KeychainDictionary([
|
||||||
kSecClass: kSecClassKey,
|
kSecClass: Constants.keyClass,
|
||||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
kSecAttrService: Constants.keyTag,
|
||||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
kSecUseDataProtectionKeychain: true,
|
||||||
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
kSecReturnData: true,
|
||||||
kSecReturnRef: true,
|
|
||||||
kSecMatchLimit: kSecMatchLimitAll,
|
kSecMatchLimit: kSecMatchLimitAll,
|
||||||
kSecReturnAttributes: true
|
kSecReturnAttributes: true
|
||||||
] as CFDictionary
|
])
|
||||||
var untyped: CFTypeRef?
|
var untyped: CFTypeRef?
|
||||||
SecItemCopyMatching(attributes, &untyped)
|
unsafe SecItemCopyMatching(queryAttributes, &untyped)
|
||||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||||
let wrapped: [SecureEnclave.Secret] = typed.map {
|
let wrapped: [SecureEnclave.Secret] = typed.compactMap {
|
||||||
let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
|
do {
|
||||||
let id = $0[kSecAttrApplicationLabel] as! Data
|
let name = $0[kSecAttrLabel] as? String ?? String(localized: "unnamed_secret")
|
||||||
let publicKeyRef = $0[kSecValueRef] as! SecKey
|
guard let attributesData = $0[kSecAttrGeneric] as? Data,
|
||||||
let publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef) as! [CFString: Any]
|
let id = $0[kSecAttrAccount] as? String else {
|
||||||
let publicKey = publicKeyAttributes[kSecValueData] as! Data
|
throw MissingAttributesError()
|
||||||
return SecureEnclave.Secret(id: id, name: name, publicKey: publicKey)
|
}
|
||||||
|
let attributes = try JSONDecoder().decode(Attributes.self, from: attributesData)
|
||||||
|
let keyData = $0[kSecValueData] as! Data
|
||||||
|
let publicKey: Data
|
||||||
|
switch attributes.keyType {
|
||||||
|
case .ecdsa256:
|
||||||
|
let key = try CryptoKit.SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: keyData)
|
||||||
|
publicKey = key.publicKey.x963Representation
|
||||||
|
case .mldsa65:
|
||||||
|
guard #available(macOS 26.0, *) else { throw UnsupportedAlgorithmError() }
|
||||||
|
let key = try CryptoKit.SecureEnclave.MLDSA65.PrivateKey(dataRepresentation: keyData)
|
||||||
|
publicKey = key.publicKey.rawRepresentation
|
||||||
|
case .mldsa87:
|
||||||
|
guard #available(macOS 26.0, *) else { throw UnsupportedAlgorithmError() }
|
||||||
|
let key = try CryptoKit.SecureEnclave.MLDSA87.PrivateKey(dataRepresentation: keyData)
|
||||||
|
publicKey = key.publicKey.rawRepresentation
|
||||||
|
default:
|
||||||
|
throw UnsupportedAlgorithmError()
|
||||||
|
}
|
||||||
|
return SecureEnclave.Secret(id: id, name: name, publicKey: publicKey, attributes: attributes)
|
||||||
|
} catch {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
secrets.append(contentsOf: wrapped)
|
secrets.append(contentsOf: wrapped)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Saves a public key.
|
/// Saves a public key.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - publicKey: The public key to save.
|
/// - key: The data representation key to save.
|
||||||
/// - name: A user-facing name for the key.
|
/// - name: A user-facing name for the key.
|
||||||
private func savePublicKey(_ publicKey: SecKey, name: String) throws {
|
/// - attributes: Attributes of the key.
|
||||||
let attributes = [
|
/// - Note: Despite the name, the "Data" of the key is _not_ actual key material. This is an opaque data representation that the SEP can manipulate.
|
||||||
kSecClass: kSecClassKey,
|
@discardableResult
|
||||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
func saveKey(_ key: Data, name: String, attributes: Attributes) throws -> String {
|
||||||
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
let attributes = try JSONEncoder().encode(attributes)
|
||||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
let id = UUID().uuidString
|
||||||
kSecValueRef: publicKey,
|
let keychainAttributes = KeychainDictionary([
|
||||||
kSecAttrIsPermanent: true,
|
kSecClass: Constants.keyClass,
|
||||||
kSecReturnData: true,
|
kSecAttrService: Constants.keyTag,
|
||||||
kSecAttrLabel: name
|
kSecUseDataProtectionKeychain: true,
|
||||||
] as CFDictionary
|
kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
||||||
let status = SecItemAdd(attributes, nil)
|
kSecAttrAccount: id,
|
||||||
|
kSecValueData: key,
|
||||||
|
kSecAttrLabel: name,
|
||||||
|
kSecAttrGeneric: attributes
|
||||||
|
])
|
||||||
|
let status = SecItemAdd(keychainAttributes, nil)
|
||||||
if status != errSecSuccess {
|
if status != errSecSuccess {
|
||||||
throw SecureEnclave.KeychainError(statusCode: status)
|
throw KeychainError(statusCode: status)
|
||||||
}
|
}
|
||||||
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SecureEnclave {
|
extension SecureEnclave.Store {
|
||||||
|
|
||||||
/// A wrapper around an error code reported by a Keychain API.
|
|
||||||
public struct KeychainError: Error {
|
|
||||||
/// The status code involved, if one was reported.
|
|
||||||
public let statusCode: OSStatus?
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A signing-related error.
|
|
||||||
public struct SigningError: Error {
|
|
||||||
/// The underlying error reported by the API, if one was returned.
|
|
||||||
public let error: SecurityError?
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SecureEnclave {
|
|
||||||
|
|
||||||
public typealias SecurityError = Unmanaged<CFError>
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SecureEnclave {
|
|
||||||
|
|
||||||
enum Constants {
|
enum Constants {
|
||||||
static let keyTag = "com.maxgoedjen.secretive.secureenclave.key".data(using: .utf8)! as CFData
|
static let keyClass = kSecClassGenericPassword as String
|
||||||
static let keyType = kSecAttrKeyTypeECSECPrimeRandom
|
static let keyTag = Data("com.maxgoedjen.secretive.secureenclave.key".utf8)
|
||||||
static let unauthenticatedThreshold: TimeInterval = 0.05
|
static let notificationToken = UUID().uuidString
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SecureEnclave {
|
|
||||||
|
|
||||||
/// A context describing a persisted authentication.
|
|
||||||
private struct PersistentAuthenticationContext {
|
|
||||||
|
|
||||||
/// The Secret to persist authentication for.
|
|
||||||
let secret: Secret
|
|
||||||
/// The LAContext used to authorize the persistent context.
|
|
||||||
let context: LAContext
|
|
||||||
/// An expiration date for the context.
|
|
||||||
/// - Note - Monotonic time instead of Date() to prevent people setting the clock back.
|
|
||||||
let expiration: UInt64
|
|
||||||
|
|
||||||
/// Initializes a context.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - secret: The Secret to persist authentication for.
|
|
||||||
/// - context: The LAContext used to authorize the persistent context.
|
|
||||||
/// - duration: The duration of the authorization context, in seconds.
|
|
||||||
init(secret: Secret, context: LAContext, duration: TimeInterval) {
|
|
||||||
self.secret = secret
|
|
||||||
self.context = context
|
|
||||||
let durationInNanoSeconds = Measurement(value: duration, unit: UnitDuration.seconds).converted(to: .nanoseconds).value
|
|
||||||
self.expiration = clock_gettime_nsec_np(CLOCK_MONOTONIC) + UInt64(durationInNanoSeconds)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A boolean describing whether or not the context is still valid.
|
|
||||||
var valid: Bool {
|
|
||||||
clock_gettime_nsec_np(CLOCK_MONOTONIC) < expiration
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct UnsupportedAlgorithmError: Error {}
|
||||||
|
struct MissingAttributesError: Error {}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,3 @@
|
|||||||
|
|
||||||
- ``Secret``
|
- ``Secret``
|
||||||
- ``Store``
|
- ``Store``
|
||||||
|
|
||||||
### Errors
|
|
||||||
|
|
||||||
- ``KeychainError``
|
|
||||||
- ``SigningError``
|
|
||||||
- ``SecurityError``
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
|
||||||
import SecretKit
|
import SecretKit
|
||||||
|
|
||||||
extension SmartCard {
|
extension SmartCard {
|
||||||
@@ -9,9 +8,8 @@ extension SmartCard {
|
|||||||
|
|
||||||
public let id: Data
|
public let id: Data
|
||||||
public let name: String
|
public let name: String
|
||||||
public let algorithm: Algorithm
|
|
||||||
public let keySize: Int
|
|
||||||
public let publicKey: Data
|
public let publicKey: Data
|
||||||
|
public var attributes: Attributes
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,66 +1,76 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
import Observation
|
||||||
import Security
|
import Security
|
||||||
import CryptoTokenKit
|
@unsafe @preconcurrency import CryptoTokenKit
|
||||||
import LocalAuthentication
|
import LocalAuthentication
|
||||||
import SecretKit
|
import SecretKit
|
||||||
|
|
||||||
// TODO: Might need to split this up into "sub-stores?"
|
|
||||||
// ie, each token has its own Store.
|
|
||||||
extension SmartCard {
|
extension SmartCard {
|
||||||
|
|
||||||
|
@MainActor @Observable fileprivate final class State {
|
||||||
|
var isAvailable = false
|
||||||
|
var name = String(localized: .smartCard)
|
||||||
|
var secrets: [Secret] = []
|
||||||
|
let watcher = TKTokenWatcher()
|
||||||
|
var tokenID: String? = nil
|
||||||
|
nonisolated init() {}
|
||||||
|
}
|
||||||
|
|
||||||
/// An implementation of Store backed by a Smart Card.
|
/// An implementation of Store backed by a Smart Card.
|
||||||
public class Store: SecretStore {
|
@Observable public final class Store: SecretStore {
|
||||||
|
|
||||||
|
private let state = State()
|
||||||
|
public var isAvailable: Bool {
|
||||||
|
state.isAvailable
|
||||||
|
}
|
||||||
|
@MainActor public var smartcardTokenID: String? {
|
||||||
|
state.tokenID
|
||||||
|
}
|
||||||
|
|
||||||
@Published public var isAvailable: Bool = false
|
|
||||||
public let id = UUID()
|
public let id = UUID()
|
||||||
public private(set) var name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
@MainActor public var name: String {
|
||||||
@Published public private(set) var secrets: [Secret] = []
|
state.name
|
||||||
private let watcher = TKTokenWatcher()
|
}
|
||||||
private var tokenID: String?
|
public var secrets: [Secret] {
|
||||||
|
state.secrets
|
||||||
|
}
|
||||||
|
|
||||||
/// Initializes a Store.
|
/// Initializes a Store.
|
||||||
public init() {
|
public init() {
|
||||||
tokenID = watcher.nonSecureEnclaveTokens.first
|
Task {
|
||||||
watcher.setInsertionHandler { string in
|
await MainActor.run {
|
||||||
guard self.tokenID == nil else { return }
|
if let tokenID = smartcardTokenID {
|
||||||
guard !string.contains("setoken") else { return }
|
state.isAvailable = true
|
||||||
|
state.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: tokenID)
|
||||||
self.tokenID = string
|
}
|
||||||
self.reloadSecrets()
|
loadSecrets()
|
||||||
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
|
}
|
||||||
|
// Doing this inside a regular mainactor handler casues thread assertions in CryptoTokenKit to blow up when the handler executes.
|
||||||
|
await state.watcher.setInsertionHandler { id in
|
||||||
|
Task {
|
||||||
|
await self.smartcardInserted(for: id)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if let tokenID = tokenID {
|
|
||||||
self.isAvailable = true
|
|
||||||
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: tokenID)
|
|
||||||
}
|
|
||||||
loadSecrets()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Public API
|
// MARK: Public API
|
||||||
|
|
||||||
public func create(name: String) throws {
|
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) async throws -> Data {
|
||||||
fatalError("Keys must be created on the smart card.")
|
guard let tokenID = await state.tokenID else { fatalError() }
|
||||||
}
|
|
||||||
|
|
||||||
public func delete(secret: Secret) throws {
|
|
||||||
fatalError("Keys must be deleted on the smart card.")
|
|
||||||
}
|
|
||||||
|
|
||||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
|
|
||||||
guard let tokenID = tokenID else { fatalError() }
|
|
||||||
let context = LAContext()
|
let context = LAContext()
|
||||||
context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
|
context.localizedReason = String(localized: .authContextRequestSignatureDescription(appName: provenance.origin.displayName, secretName: secret.name))
|
||||||
context.localizedCancelTitle = "Deny"
|
context.localizedCancelTitle = String(localized: .authContextRequestDenyButton)
|
||||||
let attributes = [
|
let attributes = KeychainDictionary([
|
||||||
kSecClass: kSecClassKey,
|
kSecClass: kSecClassKey,
|
||||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||||
kSecAttrApplicationLabel: secret.id as CFData,
|
kSecAttrApplicationLabel: secret.id as CFData,
|
||||||
kSecAttrTokenID: tokenID,
|
kSecAttrTokenID: tokenID,
|
||||||
kSecUseAuthenticationContext: context,
|
kSecUseAuthenticationContext: context,
|
||||||
kSecReturnRef: true
|
kSecReturnRef: true
|
||||||
] as CFDictionary
|
])
|
||||||
var untyped: CFTypeRef?
|
var untyped: CFTypeRef?
|
||||||
let status = SecItemCopyMatching(attributes, &untyped)
|
let status = unsafe SecItemCopyMatching(attributes, &untyped)
|
||||||
if status != errSecSuccess {
|
if status != errSecSuccess {
|
||||||
throw KeychainError(statusCode: status)
|
throw KeychainError(statusCode: status)
|
||||||
}
|
}
|
||||||
@@ -69,22 +79,23 @@ extension SmartCard {
|
|||||||
}
|
}
|
||||||
let key = untypedSafe as! SecKey
|
let key = untypedSafe as! SecKey
|
||||||
var signError: SecurityError?
|
var signError: SecurityError?
|
||||||
let signatureAlgorithm: SecKeyAlgorithm
|
guard let algorithm = signatureAlgorithm(for: secret) else { throw UnsupportKeyType() }
|
||||||
switch (secret.algorithm, secret.keySize) {
|
guard let signature = unsafe SecKeyCreateSignature(key, algorithm, data as CFData, &signError) else {
|
||||||
case (.ellipticCurve, 256):
|
throw unsafe SigningError(error: signError)
|
||||||
signatureAlgorithm = .ecdsaSignatureMessageX962SHA256
|
|
||||||
case (.ellipticCurve, 384):
|
|
||||||
signatureAlgorithm = .ecdsaSignatureMessageX962SHA384
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
}
|
||||||
guard let signature = SecKeyCreateSignature(key, signatureAlgorithm, data as CFData, &signError) else {
|
return signature as Data
|
||||||
throw SigningError(error: signError)
|
}
|
||||||
}
|
|
||||||
return SignedData(data: signature as Data, requiredAuthentication: false)
|
public func existingPersistedAuthenticationContext(secret: Secret) -> PersistedAuthenticationContext? {
|
||||||
|
nil
|
||||||
}
|
}
|
||||||
|
|
||||||
public func persistAuthentication(secret: SmartCard.Secret, forDuration: TimeInterval) throws {
|
public func persistAuthentication(secret: Secret, forDuration: TimeInterval) throws {
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reloads all secrets from the store.
|
||||||
|
@MainActor public func reloadSecrets() {
|
||||||
|
reloadSecretsInternal()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -93,66 +104,71 @@ extension SmartCard {
|
|||||||
|
|
||||||
extension SmartCard.Store {
|
extension SmartCard.Store {
|
||||||
|
|
||||||
|
@MainActor private func reloadSecretsInternal() {
|
||||||
|
let before = state.secrets
|
||||||
|
state.isAvailable = state.tokenID != nil
|
||||||
|
state.secrets.removeAll()
|
||||||
|
loadSecrets()
|
||||||
|
if self.secrets != before {
|
||||||
|
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resets the token ID and reloads secrets.
|
||||||
|
/// - Parameter tokenID: The ID of the token that was inserted.
|
||||||
|
@MainActor private func smartcardInserted(for tokenID: String? = nil) {
|
||||||
|
guard let string = state.watcher.nonSecureEnclaveTokens.first else { return }
|
||||||
|
guard state.tokenID == nil else { return }
|
||||||
|
guard !string.contains("setoken") else { return }
|
||||||
|
state.tokenID = string
|
||||||
|
state.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
|
||||||
|
state.tokenID = string
|
||||||
|
reloadSecretsInternal()
|
||||||
|
}
|
||||||
|
|
||||||
/// Resets the token ID and reloads secrets.
|
/// Resets the token ID and reloads secrets.
|
||||||
/// - Parameter tokenID: The ID of the token that was removed.
|
/// - Parameter tokenID: The ID of the token that was removed.
|
||||||
private func smartcardRemoved(for tokenID: String? = nil) {
|
@MainActor private func smartcardRemoved(for tokenID: String? = nil) {
|
||||||
self.tokenID = nil
|
state.tokenID = nil
|
||||||
reloadSecrets()
|
reloadSecrets()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reloads all secrets from the store.
|
|
||||||
private func reloadSecrets() {
|
|
||||||
DispatchQueue.main.async {
|
|
||||||
self.isAvailable = self.tokenID != nil
|
|
||||||
self.secrets.removeAll()
|
|
||||||
self.loadSecrets()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads all secrets from the store.
|
/// Loads all secrets from the store.
|
||||||
private func loadSecrets() {
|
@MainActor private func loadSecrets() {
|
||||||
guard let tokenID = tokenID else { return }
|
guard let tokenID = state.tokenID else { return }
|
||||||
|
|
||||||
let fallbackName = NSLocalizedString("Smart Card", comment: "Smart Card")
|
let fallbackName = String(localized: .smartCard)
|
||||||
if #available(macOS 12.0, *) {
|
if let driverName = state.watcher.tokenInfo(forTokenID: tokenID)?.driverName {
|
||||||
if let driverName = watcher.tokenInfo(forTokenID: tokenID)?.driverName {
|
state.name = driverName
|
||||||
name = driverName
|
|
||||||
} else {
|
|
||||||
name = fallbackName
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
// Hack to read name if there's only one smart card
|
state.name = fallbackName
|
||||||
let slotNames = TKSmartCardSlotManager().slotNames
|
|
||||||
if watcher.nonSecureEnclaveTokens.count == 1 && slotNames.count == 1 {
|
|
||||||
name = slotNames.first!
|
|
||||||
} else {
|
|
||||||
name = fallbackName
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let attributes = [
|
let attributes = KeychainDictionary([
|
||||||
kSecClass: kSecClassKey,
|
kSecClass: kSecClassKey,
|
||||||
kSecAttrTokenID: tokenID,
|
kSecAttrTokenID: tokenID,
|
||||||
kSecAttrKeyType: kSecAttrKeyTypeEC, // Restrict to EC
|
|
||||||
kSecReturnRef: true,
|
kSecReturnRef: true,
|
||||||
kSecMatchLimit: kSecMatchLimitAll,
|
kSecMatchLimit: kSecMatchLimitAll,
|
||||||
kSecReturnAttributes: true
|
kSecReturnAttributes: true
|
||||||
] as CFDictionary
|
])
|
||||||
var untyped: CFTypeRef?
|
var untyped: CFTypeRef?
|
||||||
SecItemCopyMatching(attributes, &untyped)
|
unsafe SecItemCopyMatching(attributes, &untyped)
|
||||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||||
let wrapped: [SmartCard.Secret] = typed.map {
|
let wrapped: [SecretType] = typed.compactMap {
|
||||||
let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
|
let name = $0[kSecAttrLabel] as? String ?? String(localized: .unnamedSecret)
|
||||||
let tokenID = $0[kSecAttrApplicationLabel] as! Data
|
let tokenID = $0[kSecAttrApplicationLabel] as! Data
|
||||||
let algorithm = Algorithm(secAttr: $0[kSecAttrKeyType] as! NSNumber)
|
let algorithmSecAttr = $0[kSecAttrKeyType] as! NSNumber
|
||||||
let keySize = $0[kSecAttrKeySizeInBits] as! Int
|
let keySize = $0[kSecAttrKeySizeInBits] as! Int
|
||||||
let publicKeyRef = $0[kSecValueRef] as! SecKey
|
let publicKeyRef = $0[kSecValueRef] as! SecKey
|
||||||
let publicKeySecRef = SecKeyCopyPublicKey(publicKeyRef)!
|
let publicKeySecRef = SecKeyCopyPublicKey(publicKeyRef)!
|
||||||
let publicKeyAttributes = SecKeyCopyAttributes(publicKeySecRef) as! [CFString: Any]
|
let publicKeyAttributes = SecKeyCopyAttributes(publicKeySecRef) as! [CFString: Any]
|
||||||
let publicKey = publicKeyAttributes[kSecValueData] as! Data
|
let publicKey = publicKeyAttributes[kSecValueData] as! Data
|
||||||
return SmartCard.Secret(id: tokenID, name: name, algorithm: algorithm, keySize: keySize, publicKey: publicKey)
|
let attributes = Attributes(keyType: KeyType(secAttr: algorithmSecAttr, size: keySize)!, authentication: .unknown)
|
||||||
|
let secret = SmartCard.Secret(id: tokenID, name: name, publicKey: publicKey, attributes: attributes)
|
||||||
|
guard signatureAlgorithm(for: secret) != nil else { return nil }
|
||||||
|
return secret
|
||||||
}
|
}
|
||||||
secrets.append(contentsOf: wrapped)
|
state.secrets.append(contentsOf: wrapped)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -168,22 +184,6 @@ extension TKTokenWatcher {
|
|||||||
|
|
||||||
extension SmartCard {
|
extension SmartCard {
|
||||||
|
|
||||||
/// A wrapper around an error code reported by a Keychain API.
|
public struct UnsupportKeyType: Error {}
|
||||||
public struct KeychainError: Error {
|
|
||||||
/// The status code involved.
|
|
||||||
public let statusCode: OSStatus
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A signing-related error.
|
|
||||||
public struct SigningError: Error {
|
|
||||||
/// The underlying error reported by the API, if one was returned.
|
|
||||||
public let error: SecurityError?
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SmartCard {
|
|
||||||
|
|
||||||
public typealias SecurityError = Unmanaged<CFError>
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
14
Sources/Packages/Sources/XPCWrappers/XPCProtocol.swift
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
@objc protocol _XPCProtocol: Sendable {
|
||||||
|
func process(_ data: Data, with reply: @Sendable @escaping (Data?, Error?) -> Void)
|
||||||
|
}
|
||||||
|
|
||||||
|
public protocol XPCProtocol<Input, Output>: Sendable {
|
||||||
|
|
||||||
|
associatedtype Input: Codable
|
||||||
|
associatedtype Output: Codable
|
||||||
|
|
||||||
|
func process(_ data: Input) async throws -> Output
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
public final class XPCServiceDelegate: NSObject, NSXPCListenerDelegate {
|
||||||
|
|
||||||
|
private let exportedObject: ErasedXPCProtocol
|
||||||
|
|
||||||
|
public init<XPCProtocolType: XPCProtocol>(exportedObject: XPCProtocolType) {
|
||||||
|
self.exportedObject = ErasedXPCProtocol(exportedObject)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func listener(_ listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
|
||||||
|
newConnection.exportedInterface = NSXPCInterface(with: (any _XPCProtocol).self)
|
||||||
|
let exportedObject = exportedObject
|
||||||
|
newConnection.exportedObject = exportedObject
|
||||||
|
newConnection.setCodeSigningRequirement("anchor apple generic and certificate leaf[subject.OU] = Z72PRUAWF6")
|
||||||
|
newConnection.resume()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private final class ErasedXPCProtocol: NSObject, _XPCProtocol {
|
||||||
|
|
||||||
|
let _process: @Sendable (Data, @Sendable @escaping (Data?, (any Error)?) -> Void) -> Void
|
||||||
|
|
||||||
|
public init<XPCProtocolType: XPCProtocol>(_ exportedObject: XPCProtocolType) {
|
||||||
|
_process = { data, reply in
|
||||||
|
Task { [reply] in
|
||||||
|
do {
|
||||||
|
let decoded = try JSONDecoder().decode(XPCProtocolType.Input.self, from: data)
|
||||||
|
let result = try await exportedObject.process(decoded)
|
||||||
|
let encoded = try JSONEncoder().encode(result)
|
||||||
|
reply(encoded, nil)
|
||||||
|
} catch {
|
||||||
|
if let error = error as? Codable & Error {
|
||||||
|
reply(nil, NSError(error))
|
||||||
|
} else {
|
||||||
|
// Sending cast directly tries to serialize it and crashes XPCEncoder.
|
||||||
|
let cast = error as NSError
|
||||||
|
reply(nil, NSError(domain: cast.domain, code: cast.code, userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func process(_ data: Data, with reply: @Sendable @escaping (Data?, (any Error)?) -> Void) {
|
||||||
|
_process(data, reply)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension NSError {
|
||||||
|
|
||||||
|
private enum Constants {
|
||||||
|
static let domain = "com.maxgoedjen.secretive.xpcwrappers"
|
||||||
|
static let code = -1
|
||||||
|
static let dataKey = "underlying"
|
||||||
|
}
|
||||||
|
|
||||||
|
@nonobjc convenience init<ErrorType: Codable & Error>(_ error: ErrorType) {
|
||||||
|
let encoded = try? JSONEncoder().encode(error)
|
||||||
|
self.init(domain: Constants.domain, code: Constants.code, userInfo: [Constants.dataKey: encoded as Any])
|
||||||
|
}
|
||||||
|
|
||||||
|
@nonobjc public func underlying<ErrorType: Codable & Error>(as errorType: ErrorType.Type) -> ErrorType? {
|
||||||
|
guard domain == Constants.domain && code == Constants.code, let data = userInfo[Constants.dataKey] as? Data else { return nil }
|
||||||
|
return try? JSONDecoder().decode(ErrorType.self, from: data)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
53
Sources/Packages/Sources/XPCWrappers/XPCTypedSession.swift
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
public struct XPCTypedSession<ResponseType: Codable & Sendable, ErrorType: Error & Codable>: ~Copyable {
|
||||||
|
|
||||||
|
private let connection: NSXPCConnection
|
||||||
|
private let proxy: _XPCProtocol
|
||||||
|
|
||||||
|
public init(serviceName: String, warmup: Bool = false) async throws {
|
||||||
|
let connection = NSXPCConnection(serviceName: serviceName)
|
||||||
|
connection.remoteObjectInterface = NSXPCInterface(with: (any _XPCProtocol).self)
|
||||||
|
connection.setCodeSigningRequirement("anchor apple generic and certificate leaf[subject.OU] = Z72PRUAWF6")
|
||||||
|
connection.resume()
|
||||||
|
guard let proxy = connection.remoteObjectProxy as? _XPCProtocol else { fatalError() }
|
||||||
|
self.connection = connection
|
||||||
|
self.proxy = proxy
|
||||||
|
if warmup {
|
||||||
|
_ = try? await send()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public func send(_ message: some Encodable = Data()) async throws -> ResponseType {
|
||||||
|
let encoded = try JSONEncoder().encode(message)
|
||||||
|
return try await withCheckedThrowingContinuation { continuation in
|
||||||
|
proxy.process(encoded) { data, error in
|
||||||
|
do {
|
||||||
|
if let error {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
guard let data else {
|
||||||
|
throw NoDataError()
|
||||||
|
}
|
||||||
|
let decoded = try JSONDecoder().decode(ResponseType.self, from: data)
|
||||||
|
continuation.resume(returning: decoded)
|
||||||
|
} catch {
|
||||||
|
if let typed = (error as NSError).underlying(as: ErrorType.self) {
|
||||||
|
continuation.resume(throwing: typed)
|
||||||
|
} else {
|
||||||
|
continuation.resume(throwing: error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public func complete() {
|
||||||
|
connection.invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct NoDataError: Error {}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,54 +1,65 @@
|
|||||||
import XCTest
|
import Testing
|
||||||
|
import Foundation
|
||||||
@testable import Brief
|
@testable import Brief
|
||||||
|
|
||||||
class ReleaseParsingTests: XCTestCase {
|
@Suite struct ReleaseParsingTests {
|
||||||
|
|
||||||
func testNonCritical() {
|
@Test
|
||||||
|
func nonCritical() {
|
||||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release")
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release")
|
||||||
XCTAssert(release.critical == false)
|
#expect(release.critical == false)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testCritical() {
|
@Test
|
||||||
|
func critical() {
|
||||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||||
XCTAssert(release.critical == true)
|
#expect(release.critical == true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testOSMissing() {
|
@Test
|
||||||
|
func osMissing() {
|
||||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||||
XCTAssert(release.minimumOSVersion == SemVer("11.0.0"))
|
#expect(release.minimumOSVersion == SemVer("11.0.0"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testOSPresentWithContentBelow() {
|
@Test
|
||||||
|
func osPresentWithContentBelow() {
|
||||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update ##Minimum macOS Version\n1.2.3\nBuild info")
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update ##Minimum macOS Version\n1.2.3\nBuild info")
|
||||||
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
#expect(release.minimumOSVersion == SemVer("1.2.3"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testOSPresentAtEnd() {
|
@Test
|
||||||
|
func osPresentAtEnd() {
|
||||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
|
||||||
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
#expect(release.minimumOSVersion == SemVer("1.2.3"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testOSWithMacOSPrefix() {
|
@Test
|
||||||
|
func osWithMacOSPrefix() {
|
||||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: macOS 1.2.3")
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: macOS 1.2.3")
|
||||||
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
#expect(release.minimumOSVersion == SemVer("1.2.3"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testOSGreaterThanMinimum() {
|
@Test
|
||||||
|
func osGreaterThanMinimum() {
|
||||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
|
||||||
XCTAssert(release.minimumOSVersion < SemVer("11.0.0"))
|
#expect(release.minimumOSVersion < SemVer("11.0.0"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testOSEqualToMinimum() {
|
@Test
|
||||||
|
func osEqualToMinimum() {
|
||||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 11.2.3")
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 11.2.3")
|
||||||
XCTAssert(release.minimumOSVersion <= SemVer("11.2.3"))
|
#expect(release.minimumOSVersion <= SemVer("11.2.3"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testOSLessThanMinimum() {
|
@Test
|
||||||
|
func osLessThanMinimum() {
|
||||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
|
||||||
XCTAssert(release.minimumOSVersion > SemVer("1.0.0"))
|
#expect(release.minimumOSVersion > SemVer("1.0.0"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testGreatestSelectedIfOldPatchIsPublishedLater() {
|
@Test
|
||||||
|
@MainActor func greatestSelectedIfOldPatchIsPublishedLater() async throws {
|
||||||
// If 2.x.x series has been published, and a patch for 1.x.x is issued
|
// If 2.x.x series has been published, and a patch for 1.x.x is issued
|
||||||
// 2.x.x should still be selected if user can run it.
|
// 2.x.x should still be selected if user can run it.
|
||||||
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("2.2.3"), currentVersion: SemVer("1.0.0"))
|
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("2.2.3"), currentVersion: SemVer("1.0.0"))
|
||||||
@@ -60,16 +71,13 @@ class ReleaseParsingTests: XCTestCase {
|
|||||||
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
|
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
|
||||||
]
|
]
|
||||||
|
|
||||||
let expectation = XCTestExpectation()
|
await updater.evaluate(releases: releases)
|
||||||
updater.evaluate(releases: releases)
|
try await Task.sleep(nanoseconds: 1)
|
||||||
DispatchQueue.main.async {
|
#expect(updater.update == two)
|
||||||
XCTAssert(updater.update == two)
|
|
||||||
expectation.fulfill()
|
|
||||||
}
|
|
||||||
wait(for: [expectation], timeout: 1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testLatestVersionIsRunnable() {
|
@Test
|
||||||
|
@MainActor func latestVersionIsRunnable() async throws {
|
||||||
// If the 2.x.x series has been published but the user can't run it
|
// If the 2.x.x series has been published but the user can't run it
|
||||||
// the last version the user can run should be selected.
|
// the last version the user can run should be selected.
|
||||||
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("1.2.3"), currentVersion: SemVer("1.0.0"))
|
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("1.2.3"), currentVersion: SemVer("1.0.0"))
|
||||||
@@ -80,16 +88,13 @@ class ReleaseParsingTests: XCTestCase {
|
|||||||
Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3"),
|
Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3"),
|
||||||
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
|
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
|
||||||
]
|
]
|
||||||
let expectation = XCTestExpectation()
|
await updater.evaluate(releases: releases)
|
||||||
updater.evaluate(releases: releases)
|
try await Task.sleep(nanoseconds: 1)
|
||||||
DispatchQueue.main.async {
|
#expect(updater.update == oneOhTwo)
|
||||||
XCTAssert(updater.update == oneOhTwo)
|
|
||||||
expectation.fulfill()
|
|
||||||
}
|
|
||||||
wait(for: [expectation], timeout: 1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testSorting() {
|
@Test
|
||||||
|
func sorting() {
|
||||||
let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available!")
|
let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available!")
|
||||||
let releases = [
|
let releases = [
|
||||||
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release"),
|
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release"),
|
||||||
@@ -98,7 +103,7 @@ class ReleaseParsingTests: XCTestCase {
|
|||||||
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch!"),
|
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch!"),
|
||||||
]
|
]
|
||||||
let sorted = releases.sorted().reversed().first
|
let sorted = releases.sorted().reversed().first
|
||||||
XCTAssert(sorted == two)
|
#expect(sorted == two)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,51 +1,52 @@
|
|||||||
import XCTest
|
import Testing
|
||||||
|
import Foundation
|
||||||
@testable import Brief
|
@testable import Brief
|
||||||
|
|
||||||
class SemVerTests: XCTestCase {
|
@Suite struct SemVerTests {
|
||||||
|
|
||||||
func testEqual() {
|
@Test func equal() {
|
||||||
let current = SemVer("1.0.2")
|
let current = SemVer("1.0.2")
|
||||||
let old = SemVer("1.0.2")
|
let old = SemVer("1.0.2")
|
||||||
XCTAssert(!(current > old))
|
#expect(!(current > old))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testPatchGreaterButMinorLess() {
|
@Test func patchGreaterButMinorLess() {
|
||||||
let current = SemVer("1.1.0")
|
let current = SemVer("1.1.0")
|
||||||
let old = SemVer("1.0.2")
|
let old = SemVer("1.0.2")
|
||||||
XCTAssert(current > old)
|
#expect(current > old)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testMajorSameMinorGreater() {
|
@Test func majorSameMinorGreater() {
|
||||||
let current = SemVer("1.0.2")
|
let current = SemVer("1.0.2")
|
||||||
let new = SemVer("1.0.3")
|
let new = SemVer("1.0.3")
|
||||||
XCTAssert(current < new)
|
#expect(current < new)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testMajorGreaterMinorLesser() {
|
@Test func majorGreaterMinorLesser() {
|
||||||
let current = SemVer("1.0.2")
|
let current = SemVer("1.0.2")
|
||||||
let new = SemVer("2.0.0")
|
let new = SemVer("2.0.0")
|
||||||
XCTAssert(current < new)
|
#expect(current < new)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testRegularParsing() {
|
@Test func regularParsing() {
|
||||||
let current = SemVer("1.0.2")
|
let current = SemVer("1.0.2")
|
||||||
XCTAssert(current.versionNumbers == [1, 0, 2])
|
#expect(current.versionNumbers == [1, 0, 2])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testNoPatch() {
|
@Test func noPatch() {
|
||||||
let current = SemVer("1.1")
|
let current = SemVer("1.1")
|
||||||
XCTAssert(current.versionNumbers == [1, 1, 0])
|
#expect(current.versionNumbers == [1, 1, 0])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testGarbage() {
|
@Test func garbage() {
|
||||||
let current = SemVer("Test")
|
let current = SemVer("Test")
|
||||||
XCTAssert(current.versionNumbers == [0, 0, 0])
|
#expect(current.versionNumbers == [0, 0, 0])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBeta() {
|
@Test func beta() {
|
||||||
let current = SemVer("1.0.2")
|
let current = SemVer("1.0.2")
|
||||||
let new = SemVer("1.1.0_beta1")
|
let new = SemVer("1.1.0_beta1")
|
||||||
XCTAssert(current < new)
|
#expect(current < new)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,56 +1,59 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import XCTest
|
import Testing
|
||||||
import CryptoKit
|
import CryptoKit
|
||||||
@testable import SecretKit
|
@testable import SecretKit
|
||||||
@testable import SecretAgentKit
|
@testable import SecretAgentKit
|
||||||
|
|
||||||
class AgentTests: XCTestCase {
|
@Suite struct AgentTests {
|
||||||
|
|
||||||
let stubWriter = StubFileHandleWriter()
|
|
||||||
|
|
||||||
// MARK: Identity Listing
|
// MARK: Identity Listing
|
||||||
|
|
||||||
func testEmptyStores() {
|
@Test func emptyStores() async throws {
|
||||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities)
|
|
||||||
let agent = Agent(storeList: SecretStoreList())
|
let agent = Agent(storeList: SecretStoreList())
|
||||||
agent.handle(reader: stubReader, writer: stubWriter)
|
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestIdentities)
|
||||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestIdentitiesEmpty)
|
let response = await agent.handle(request: request, provenance: .test)
|
||||||
|
#expect(response == Constants.Responses.requestIdentitiesEmpty)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testIdentitiesList() {
|
@Test func identitiesList() async throws {
|
||||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities)
|
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
|
||||||
let agent = Agent(storeList: list)
|
let agent = Agent(storeList: list)
|
||||||
agent.handle(reader: stubReader, writer: stubWriter)
|
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestIdentities)
|
||||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestIdentitiesMultiple)
|
let response = await agent.handle(request: request, provenance: .test)
|
||||||
|
|
||||||
|
let actual = OpenSSHReader(data: response)
|
||||||
|
let expected = OpenSSHReader(data: Constants.Responses.requestIdentitiesMultiple)
|
||||||
|
print(actual, expected)
|
||||||
|
#expect(response == Constants.Responses.requestIdentitiesMultiple)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Signatures
|
// MARK: Signatures
|
||||||
|
|
||||||
func testNoMatchingIdentities() {
|
@Test func noMatchingIdentities() async throws {
|
||||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignatureWithNoneMatching)
|
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
|
||||||
let agent = Agent(storeList: list)
|
let agent = Agent(storeList: list)
|
||||||
agent.handle(reader: stubReader, writer: stubWriter)
|
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignatureWithNoneMatching)
|
||||||
// XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
let response = await agent.handle(request: request, provenance: .test)
|
||||||
|
#expect(response == Constants.Responses.requestFailure)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testSignature() {
|
@Test func ecdsaSignature() async throws {
|
||||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
|
||||||
let requestReader = OpenSSHReader(data: Constants.Requests.requestSignature[5...])
|
guard case SSHAgent.Request.signRequest(let context) = request else { return }
|
||||||
_ = requestReader.readNextChunk()
|
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||||
let dataToSign = requestReader.readNextChunk()
|
|
||||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
|
||||||
let agent = Agent(storeList: list)
|
let agent = Agent(storeList: list)
|
||||||
agent.handle(reader: stubReader, writer: stubWriter)
|
let response = await agent.handle(request: request, provenance: .test)
|
||||||
let outer = OpenSSHReader(data: stubWriter.data[5...])
|
let responseReader = OpenSSHReader(data: response)
|
||||||
let payload = outer.readNextChunk()
|
let length = try responseReader.readNextBytes(as: UInt32.self).bigEndian
|
||||||
let inner = OpenSSHReader(data: payload)
|
let type = try responseReader.readNextBytes(as: UInt8.self).bigEndian
|
||||||
_ = inner.readNextChunk()
|
#expect(length == response.count - MemoryLayout<UInt32>.size)
|
||||||
let signedData = inner.readNextChunk()
|
#expect(type == SSHAgent.Response.agentSignResponse.rawValue)
|
||||||
let rsData = OpenSSHReader(data: signedData)
|
let outer = OpenSSHReader(data: responseReader.remaining)
|
||||||
var r = rsData.readNextChunk()
|
let inner = try outer.readNextChunkAsSubReader()
|
||||||
var s = rsData.readNextChunk()
|
_ = try inner.readNextChunk()
|
||||||
|
let rsData = try inner.readNextChunkAsSubReader()
|
||||||
|
var r = try rsData.readNextChunk()
|
||||||
|
var s = try rsData.readNextChunk()
|
||||||
// This is fine IRL, but it freaks out CryptoKit
|
// This is fine IRL, but it freaks out CryptoKit
|
||||||
if r[0] == 0 {
|
if r[0] == 0 {
|
||||||
r.removeFirst()
|
r.removeFirst()
|
||||||
@@ -60,43 +63,42 @@ class AgentTests: XCTestCase {
|
|||||||
}
|
}
|
||||||
var rs = r
|
var rs = r
|
||||||
rs.append(s)
|
rs.append(s)
|
||||||
let signature = try! P256.Signing.ECDSASignature(rawRepresentation: rs)
|
let signature = try P256.Signing.ECDSASignature(rawRepresentation: rs)
|
||||||
let valid = try! P256.Signing.PublicKey(x963Representation: Constants.Secrets.ecdsa256Secret.publicKey).isValidSignature(signature, for: dataToSign)
|
// Correct signature
|
||||||
XCTAssertTrue(valid)
|
#expect(try P256.Signing.PublicKey(x963Representation: Constants.Secrets.ecdsa256Secret.publicKey)
|
||||||
|
.isValidSignature(signature, for: context.dataToSign))
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Witness protocol
|
// MARK: Witness protocol
|
||||||
|
|
||||||
func testWitnessObjectionStopsRequest() {
|
@Test func witnessObjectionStopsRequest() async throws {
|
||||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret])
|
||||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
|
|
||||||
let witness = StubWitness(speakNow: { _,_ in
|
let witness = StubWitness(speakNow: { _,_ in
|
||||||
return true
|
return true
|
||||||
}, witness: { _, _ in })
|
}, witness: { _, _ in })
|
||||||
let agent = Agent(storeList: list, witness: witness)
|
let agent = Agent(storeList: list, witness: witness)
|
||||||
agent.handle(reader: stubReader, writer: stubWriter)
|
let response = await agent.handle(request: .signRequest(.empty), provenance: .test)
|
||||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
#expect(response == Constants.Responses.requestFailure)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testWitnessSignature() {
|
@Test func witnessSignature() async throws {
|
||||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret])
|
||||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
|
nonisolated(unsafe) var witnessed = false
|
||||||
var witnessed = false
|
|
||||||
let witness = StubWitness(speakNow: { _, trace in
|
let witness = StubWitness(speakNow: { _, trace in
|
||||||
return false
|
return false
|
||||||
}, witness: { _, trace in
|
}, witness: { _, trace in
|
||||||
witnessed = true
|
witnessed = true
|
||||||
})
|
})
|
||||||
let agent = Agent(storeList: list, witness: witness)
|
let agent = Agent(storeList: list, witness: witness)
|
||||||
agent.handle(reader: stubReader, writer: stubWriter)
|
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
|
||||||
XCTAssertTrue(witnessed)
|
_ = await agent.handle(request: request, provenance: .test)
|
||||||
|
#expect(witnessed)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testRequestTracing() {
|
@Test func requestTracing() async throws {
|
||||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret])
|
||||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
|
nonisolated(unsafe) var speakNowTrace: SigningRequestProvenance?
|
||||||
var speakNowTrace: SigningRequestProvenance! = nil
|
nonisolated(unsafe) var witnessTrace: SigningRequestProvenance?
|
||||||
var witnessTrace: SigningRequestProvenance! = nil
|
|
||||||
let witness = StubWitness(speakNow: { _, trace in
|
let witness = StubWitness(speakNow: { _, trace in
|
||||||
speakNowTrace = trace
|
speakNowTrace = trace
|
||||||
return false
|
return false
|
||||||
@@ -104,39 +106,43 @@ class AgentTests: XCTestCase {
|
|||||||
witnessTrace = trace
|
witnessTrace = trace
|
||||||
})
|
})
|
||||||
let agent = Agent(storeList: list, witness: witness)
|
let agent = Agent(storeList: list, witness: witness)
|
||||||
agent.handle(reader: stubReader, writer: stubWriter)
|
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
|
||||||
XCTAssertEqual(witnessTrace, speakNowTrace)
|
_ = await agent.handle(request: request, provenance: .test)
|
||||||
XCTAssertEqual(witnessTrace.origin.displayName, "Finder")
|
#expect(witnessTrace == speakNowTrace)
|
||||||
XCTAssertEqual(witnessTrace.origin.validSignature, true)
|
#expect(witnessTrace == .test)
|
||||||
XCTAssertEqual(witnessTrace.origin.parentPID, 1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Exception Handling
|
// MARK: Exception Handling
|
||||||
|
|
||||||
func testSignatureException() {
|
@Test func signatureException() async throws {
|
||||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
let store = await list.stores.first?.base as! Stub.Store
|
||||||
let store = list.stores.first?.base as! Stub.Store
|
|
||||||
store.shouldThrow = true
|
store.shouldThrow = true
|
||||||
let agent = Agent(storeList: list)
|
let agent = Agent(storeList: list)
|
||||||
agent.handle(reader: stubReader, writer: stubWriter)
|
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
|
||||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
let response = await agent.handle(request: request, provenance: .test)
|
||||||
|
#expect(response == Constants.Responses.requestFailure)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Unsupported
|
// MARK: Unsupported
|
||||||
|
|
||||||
func testUnhandledAdd() {
|
@Test func unhandledAdd() async throws {
|
||||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.addIdentity)
|
|
||||||
let agent = Agent(storeList: SecretStoreList())
|
let agent = Agent(storeList: SecretStoreList())
|
||||||
agent.handle(reader: stubReader, writer: stubWriter)
|
let response = await agent.handle(request: .addIdentity, provenance: .test)
|
||||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
#expect(response == Constants.Responses.requestFailure)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extension SigningRequestProvenance {
|
||||||
|
|
||||||
|
static let test = SigningRequestProvenance(root: .init(pid: 0, processName: "test", appName: nil, iconURL: nil, path: "/", validSignature: true, parentPID: 0))
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
extension AgentTests {
|
extension AgentTests {
|
||||||
|
|
||||||
func storeList(with secrets: [Stub.Secret]) -> SecretStoreList {
|
@MainActor func storeList(with secrets: [Stub.Secret]) async -> SecretStoreList {
|
||||||
let store = Stub.Store()
|
let store = Stub.Store()
|
||||||
store.secrets.append(contentsOf: secrets)
|
store.secrets.append(contentsOf: secrets)
|
||||||
let storeList = SecretStoreList()
|
let storeList = SecretStoreList()
|
||||||
@@ -148,14 +154,13 @@ extension AgentTests {
|
|||||||
|
|
||||||
enum Requests {
|
enum Requests {
|
||||||
static let requestIdentities = Data(base64Encoded: "AAAAAQs=")!
|
static let requestIdentities = Data(base64Encoded: "AAAAAQs=")!
|
||||||
static let addIdentity = Data(base64Encoded: "AAAAARE=")!
|
|
||||||
static let requestSignatureWithNoneMatching = Data(base64Encoded: "AAABhA0AAACIAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQAAAO8AAAAgbqmrqPUtJ8mmrtaSVexjMYyXWNqjHSnoto7zgv86xvcyAAAAA2dpdAAAAA5zc2gtY29ubmVjdGlvbgAAAAlwdWJsaWNrZXkBAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAACIAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQAAAAA=")!
|
static let requestSignatureWithNoneMatching = Data(base64Encoded: "AAABhA0AAACIAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQAAAO8AAAAgbqmrqPUtJ8mmrtaSVexjMYyXWNqjHSnoto7zgv86xvcyAAAAA2dpdAAAAA5zc2gtY29ubmVjdGlvbgAAAAlwdWJsaWNrZXkBAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAACIAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQAAAAA=")!
|
||||||
static let requestSignature = Data(base64Encoded: "AAABRA0AAABoAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKzOkUiVJEcACMtAd9X7xalbc0FYZyhbmv2dsWl4IP2GWIi+RcsaHQNw+nAIQ8CKEYmLnl0VLDp5Ef8KMhgIy08AAADPAAAAIBIFsbCZ4/dhBmLNGHm0GKj7EJ4N8k/jXRxlyg+LFIYzMgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAAaAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQSszpFIlSRHAAjLQHfV+8WpW3NBWGcoW5r9nbFpeCD9hliIvkXLGh0DcPpwCEPAihGJi55dFSw6eRH/CjIYCMtPAAAAAA==")!
|
static let requestSignature = Data(base64Encoded: "AAABRA0AAABoAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKzOkUiVJEcACMtAd9X7xalbc0FYZyhbmv2dsWl4IP2GWIi+RcsaHQNw+nAIQ8CKEYmLnl0VLDp5Ef8KMhgIy08AAADPAAAAIBIFsbCZ4/dhBmLNGHm0GKj7EJ4N8k/jXRxlyg+LFIYzMgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAAaAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQSszpFIlSRHAAjLQHfV+8WpW3NBWGcoW5r9nbFpeCD9hliIvkXLGh0DcPpwCEPAihGJi55dFSw6eRH/CjIYCMtPAAAAAA==")!
|
||||||
}
|
}
|
||||||
|
|
||||||
enum Responses {
|
enum Responses {
|
||||||
static let requestIdentitiesEmpty = Data(base64Encoded: "AAAABQwAAAAA")!
|
static let requestIdentitiesEmpty = Data(base64Encoded: "AAAABQwAAAAA")!
|
||||||
static let requestIdentitiesMultiple = Data(base64Encoded: "AAABKwwAAAACAAAAaAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQSszpFIlSRHAAjLQHfV+8WpW3NBWGcoW5r9nbFpeCD9hliIvkXLGh0DcPpwCEPAihGJi55dFSw6eRH/CjIYCMtPAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAACIAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBLKSzA5q3jCb3q0JKigvcxfWVGrJ+bklpG0Zc9YzUwrbsh9SipvlSJi+sHQI+O0m88DOpRBAtuAHX60euD/Yv250tovN7/+MEFbXGZ/hLdd0BoFpWbLfJcQj806KJGlcDAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0")!
|
static let requestIdentitiesMultiple = Data(base64Encoded: "AAABLwwAAAACAAAAaAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQSszpFIlSRHAAjLQHfV+8WpW3NBWGcoW5r9nbFpeCD9hliIvkXLGh0DcPpwCEPAihGJi55dFSw6eRH/CjIYCMtPAAAAFWVjZHNhLTI1NkBleGFtcGxlLmNvbQAAAIgAAAATZWNkc2Etc2hhMi1uaXN0cDM4NAAAAAhuaXN0cDM4NAAAAGEEspLMDmreMJverQkqKC9zF9ZUasn5uSWkbRlz1jNTCtuyH1KKm+VImL6wdAj47SbzwM6lEEC24AdfrR64P9i/bnS2i83v/4wQVtcZn+Et13QGgWlZst8lxCPzTookaVwMAAAAFWVjZHNhLTM4NEBleGFtcGxlLmNvbQ==")!
|
||||||
static let requestFailure = Data(base64Encoded: "AAAAAQU=")!
|
static let requestFailure = Data(base64Encoded: "AAAAAQU=")!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import Foundation
|
||||||
|
import Testing
|
||||||
|
@testable import SecretAgentKit
|
||||||
|
@testable import SecureEnclaveSecretKit
|
||||||
|
@testable import SmartCardSecretKit
|
||||||
|
|
||||||
|
@Suite struct OpenSSHReaderTests {
|
||||||
|
|
||||||
|
@Test func signatureRequest() throws {
|
||||||
|
let reader = OpenSSHReader(data: Constants.signatureRequest)
|
||||||
|
let hash = try reader.readNextChunk()
|
||||||
|
#expect(hash == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQ=="))
|
||||||
|
let dataToSign = try reader.readNextChunk()
|
||||||
|
#expect(dataToSign == Data(base64Encoded: "AAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QU="))
|
||||||
|
let empty = try reader.readNextChunk()
|
||||||
|
#expect(empty.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OpenSSHReaderTests {
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
static let signatureRequest = Data(base64Encoded: "AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QUAAADvAAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QUAAAAA")!
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import SecretAgentKit
|
|
||||||
import AppKit
|
|
||||||
|
|
||||||
struct StubFileHandleReader: FileHandleReader {
|
|
||||||
|
|
||||||
let availableData: Data
|
|
||||||
var fileDescriptor: Int32 {
|
|
||||||
NSWorkspace.shared.runningApplications.filter({ $0.localizedName == "Finder" }).first!.processIdentifier
|
|
||||||
}
|
|
||||||
var pidOfConnectedProcess: Int32 {
|
|
||||||
fileDescriptor
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import SecretAgentKit
|
|
||||||
|
|
||||||
class StubFileHandleWriter: FileHandleWriter {
|
|
||||||
|
|
||||||
var data = Data()
|
|
||||||
|
|
||||||
func write(_ data: Data) {
|
|
||||||
self.data.append(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -6,7 +6,7 @@ struct Stub {}
|
|||||||
|
|
||||||
extension Stub {
|
extension Stub {
|
||||||
|
|
||||||
public class Store: SecretStore {
|
public final class Store: SecretStore, @unchecked Sendable {
|
||||||
|
|
||||||
public let isAvailable = true
|
public let isAvailable = true
|
||||||
public let id = UUID()
|
public let id = UUID()
|
||||||
@@ -27,7 +27,7 @@ extension Stub {
|
|||||||
flags,
|
flags,
|
||||||
nil) as Any
|
nil) as Any
|
||||||
|
|
||||||
let attributes = [
|
let attributes = KeychainDictionary([
|
||||||
kSecAttrLabel: name,
|
kSecAttrLabel: name,
|
||||||
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
||||||
kSecAttrKeySizeInBits: size,
|
kSecAttrKeySizeInBits: size,
|
||||||
@@ -35,45 +35,37 @@ extension Stub {
|
|||||||
kSecAttrIsPermanent: true,
|
kSecAttrIsPermanent: true,
|
||||||
kSecAttrAccessControl: access
|
kSecAttrAccessControl: access
|
||||||
]
|
]
|
||||||
] as CFDictionary
|
])
|
||||||
|
|
||||||
var privateKey: SecKey! = nil
|
let privateKey = SecKeyCreateRandomKey(attributes, nil)!
|
||||||
var publicKey: SecKey! = nil
|
let publicKey = SecKeyCopyPublicKey(privateKey)!
|
||||||
SecKeyGeneratePair(attributes, &publicKey, &privateKey)
|
|
||||||
let publicAttributes = SecKeyCopyAttributes(publicKey) as! [CFString: Any]
|
let publicAttributes = SecKeyCopyAttributes(publicKey) as! [CFString: Any]
|
||||||
let privateAttributes = SecKeyCopyAttributes(privateKey) as! [CFString: Any]
|
let privateAttributes = SecKeyCopyAttributes(privateKey) as! [CFString: Any]
|
||||||
let publicData = (publicAttributes[kSecValueData] as! Data)
|
let publicData = (publicAttributes[kSecValueData] as! Data)
|
||||||
let privateData = (privateAttributes[kSecValueData] as! Data)
|
let privateData = (privateAttributes[kSecValueData] as! Data)
|
||||||
let secret = Secret(keySize: size, publicKey: publicData, privateKey: privateData)
|
let secret = Secret(keySize: size, publicKey: publicData, privateKey: privateData)
|
||||||
print(secret)
|
print(secret)
|
||||||
print("Public Key OpenSSH: \(OpenSSHKeyWriter().openSSHString(secret: secret))")
|
print("Public Key OpenSSH: \(OpenSSHPublicKeyWriter().openSSHString(secret: secret))")
|
||||||
}
|
}
|
||||||
|
|
||||||
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> SignedData {
|
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||||
guard !shouldThrow else {
|
guard !shouldThrow else {
|
||||||
throw NSError(domain: "test", code: 0, userInfo: nil)
|
throw NSError(domain: "test", code: 0, userInfo: nil)
|
||||||
}
|
}
|
||||||
let privateKey = SecKeyCreateWithData(secret.privateKey as CFData, [
|
let privateKey = try CryptoKit.P256.Signing.PrivateKey(x963Representation: secret.privateKey)
|
||||||
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
return try privateKey.signature(for: data).rawRepresentation
|
||||||
kSecAttrKeySizeInBits: secret.keySize,
|
}
|
||||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate
|
|
||||||
] as CFDictionary
|
public func existingPersistedAuthenticationContext(secret: Stub.Secret) -> PersistedAuthenticationContext? {
|
||||||
, nil)!
|
nil
|
||||||
let signatureAlgorithm: SecKeyAlgorithm
|
|
||||||
switch secret.keySize {
|
|
||||||
case 256:
|
|
||||||
signatureAlgorithm = .ecdsaSignatureMessageX962SHA256
|
|
||||||
case 384:
|
|
||||||
signatureAlgorithm = .ecdsaSignatureMessageX962SHA384
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
return SignedData(data: SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data, requiredAuthentication: false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func persistAuthentication(secret: Stub.Secret, forDuration duration: TimeInterval) throws {
|
public func persistAuthentication(secret: Stub.Secret, forDuration duration: TimeInterval) throws {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public func reloadSecrets() {
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -82,23 +74,22 @@ extension Stub {
|
|||||||
|
|
||||||
struct Secret: SecretKit.Secret, CustomDebugStringConvertible {
|
struct Secret: SecretKit.Secret, CustomDebugStringConvertible {
|
||||||
|
|
||||||
let id = UUID().uuidString.data(using: .utf8)!
|
let id = Data(UUID().uuidString.utf8)
|
||||||
let name = UUID().uuidString
|
let name = UUID().uuidString
|
||||||
let algorithm = Algorithm.ellipticCurve
|
let attributes: Attributes
|
||||||
|
|
||||||
let keySize: Int
|
|
||||||
let publicKey: Data
|
let publicKey: Data
|
||||||
|
let requiresAuthentication = false
|
||||||
let privateKey: Data
|
let privateKey: Data
|
||||||
|
|
||||||
init(keySize: Int, publicKey: Data, privateKey: Data) {
|
init(keySize: Int, publicKey: Data, privateKey: Data) {
|
||||||
self.keySize = keySize
|
self.attributes = Attributes(keyType: .init(algorithm: .ecdsa, size: keySize), authentication: .notRequired, publicKeyAttribution: "ecdsa-\(keySize)@example.com")
|
||||||
self.publicKey = publicKey
|
self.publicKey = publicKey
|
||||||
self.privateKey = privateKey
|
self.privateKey = privateKey
|
||||||
}
|
}
|
||||||
|
|
||||||
var debugDescription: String {
|
var debugDescription: String {
|
||||||
"""
|
"""
|
||||||
Key Size \(keySize)
|
Key Size \(attributes.keyType.size)
|
||||||
Private: \(privateKey.base64EncodedString())
|
Private: \(privateKey.base64EncodedString())
|
||||||
Public: \(publicKey.base64EncodedString())
|
Public: \(publicKey.base64EncodedString())
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ import SecretAgentKit
|
|||||||
|
|
||||||
struct StubWitness {
|
struct StubWitness {
|
||||||
|
|
||||||
let speakNow: (AnySecret, SigningRequestProvenance) -> Bool
|
let speakNow: @Sendable (AnySecret, SigningRequestProvenance) -> Bool
|
||||||
let witness: (AnySecret, SigningRequestProvenance) -> ()
|
let witness: @Sendable (AnySecret, SigningRequestProvenance) -> ()
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: A
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws {
|
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||||
witness(secret, provenance)
|
witness(secret, provenance)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,20 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import XCTest
|
import Testing
|
||||||
@testable import SecretKit
|
@testable import SecretKit
|
||||||
@testable import SecureEnclaveSecretKit
|
@testable import SecureEnclaveSecretKit
|
||||||
@testable import SmartCardSecretKit
|
@testable import SmartCardSecretKit
|
||||||
|
|
||||||
class AnySecretTests: XCTestCase {
|
|
||||||
|
|
||||||
func testEraser() {
|
@Suite struct AnySecretTests {
|
||||||
let secret = SmartCard.Secret(id: UUID().uuidString.data(using: .utf8)!, name: "Name", algorithm: .ellipticCurve, keySize: 256, publicKey: UUID().uuidString.data(using: .utf8)!)
|
|
||||||
|
@Test func eraser() {
|
||||||
|
let data = Data(UUID().uuidString.utf8)
|
||||||
|
let secret = SmartCard.Secret(id: data, name: "Name", publicKey: data, attributes: Attributes(keyType: KeyType(algorithm: .ecdsa, size: 256), authentication: .notRequired))
|
||||||
let erased = AnySecret(secret)
|
let erased = AnySecret(secret)
|
||||||
XCTAssert(erased.id == secret.id as AnyHashable)
|
#expect(erased.id == secret.id as AnyHashable)
|
||||||
XCTAssert(erased.name == secret.name)
|
#expect(erased.name == secret.name)
|
||||||
XCTAssert(erased.algorithm == secret.algorithm)
|
#expect(erased.keyType == secret.keyType)
|
||||||
XCTAssert(erased.keySize == secret.keySize)
|
#expect(erased.publicKey == secret.publicKey)
|
||||||
XCTAssert(erased.publicKey == secret.publicKey)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import Foundation
|
||||||
|
import Testing
|
||||||
|
@testable import SecretKit
|
||||||
|
@testable import SecureEnclaveSecretKit
|
||||||
|
@testable import SmartCardSecretKit
|
||||||
|
|
||||||
|
@Suite struct OpenSSHPublicKeyWriterTests {
|
||||||
|
|
||||||
|
let writer = OpenSSHPublicKeyWriter()
|
||||||
|
|
||||||
|
@Test func ecdsa256MD5Fingerprint() {
|
||||||
|
#expect(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa256Secret) == "dc:60:4d:ff:c2:d9:18:8b:2f:24:40:b5:7f:43:47:e5")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func ecdsa256SHA256Fingerprint() {
|
||||||
|
#expect(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa256Secret) == "SHA256:/VQFeGyM8qKA8rB6WGMuZZxZLJln2UgXLk3F0uTF650")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func ecdsa256PublicKey() {
|
||||||
|
#expect(writer.openSSHString(secret: Constants.ecdsa256Secret) ==
|
||||||
|
"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo= test@example.com")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func ecdsa256Hash() {
|
||||||
|
#expect(writer.data(secret: Constants.ecdsa256Secret) == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo="))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func ecdsa384MD5Fingerprint() {
|
||||||
|
#expect(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa384Secret) == "66:e0:66:d7:41:ed:19:8e:e2:20:df:ce:ac:7e:2b:6e")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func ecdsa384SHA256Fingerprint() {
|
||||||
|
#expect(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa384Secret) == "SHA256:GJUEymQNL9ymaMRRJCMGY4rWIJHu/Lm8Yhao/PAiz1I")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func ecdsa384PublicKey() {
|
||||||
|
#expect(writer.openSSHString(secret: Constants.ecdsa384Secret) ==
|
||||||
|
"ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ== test@example.com")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func ecdsa384Hash() {
|
||||||
|
#expect(writer.data(secret: Constants.ecdsa384Secret) == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ=="))
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OpenSSHPublicKeyWriterTests {
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
static let ecdsa256Secret = SmartCard.Secret(id: Data(), name: "Test Key (ECDSA 256)", publicKey: Data(base64Encoded: "BOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")!, attributes: Attributes(keyType: KeyType(algorithm: .ecdsa, size: 256), authentication: .notRequired, publicKeyAttribution: "test@example.com"))
|
||||||
|
static let ecdsa384Secret = SmartCard.Secret(id: Data(), name: "Test Key (ECDSA 384)", publicKey: Data(base64Encoded: "BG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")!, attributes: Attributes(keyType: KeyType(algorithm: .ecdsa, size: 384), authentication: .notRequired, publicKeyAttribution: "test@example.com"))
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import XCTest
|
|
||||||
@testable import SecretKit
|
|
||||||
@testable import SecureEnclaveSecretKit
|
|
||||||
@testable import SmartCardSecretKit
|
|
||||||
|
|
||||||
class OpenSSHReaderTests: XCTestCase {
|
|
||||||
|
|
||||||
func testSignatureRequest() {
|
|
||||||
let reader = OpenSSHReader(data: Constants.signatureRequest)
|
|
||||||
let hash = reader.readNextChunk()
|
|
||||||
XCTAssert(hash == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQ=="))
|
|
||||||
let dataToSign = reader.readNextChunk()
|
|
||||||
XCTAssert(dataToSign == Data(base64Encoded: "AAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QU="))
|
|
||||||
let empty = reader.readNextChunk()
|
|
||||||
XCTAssert(empty.isEmpty)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension OpenSSHReaderTests {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
static let signatureRequest = Data(base64Encoded: "AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QUAAADvAAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QUAAAAA")!
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import XCTest
|
|
||||||
@testable import SecretKit
|
|
||||||
@testable import SecureEnclaveSecretKit
|
|
||||||
@testable import SmartCardSecretKit
|
|
||||||
|
|
||||||
class OpenSSHWriterTests: XCTestCase {
|
|
||||||
|
|
||||||
let writer = OpenSSHKeyWriter()
|
|
||||||
|
|
||||||
func testECDSA256MD5Fingerprint() {
|
|
||||||
XCTAssertEqual(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa256Secret), "dc:60:4d:ff:c2:d9:18:8b:2f:24:40:b5:7f:43:47:e5")
|
|
||||||
}
|
|
||||||
|
|
||||||
func testECDSA256SHA256Fingerprint() {
|
|
||||||
XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa256Secret), "SHA256:/VQFeGyM8qKA8rB6WGMuZZxZLJln2UgXLk3F0uTF650")
|
|
||||||
}
|
|
||||||
|
|
||||||
func testECDSA256PublicKey() {
|
|
||||||
XCTAssertEqual(writer.openSSHString(secret: Constants.ecdsa256Secret),
|
|
||||||
"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")
|
|
||||||
}
|
|
||||||
|
|
||||||
func testECDSA256Hash() {
|
|
||||||
XCTAssertEqual(writer.data(secret: Constants.ecdsa256Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo="))
|
|
||||||
}
|
|
||||||
|
|
||||||
func testECDSA384MD5Fingerprint() {
|
|
||||||
XCTAssertEqual(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa384Secret), "66:e0:66:d7:41:ed:19:8e:e2:20:df:ce:ac:7e:2b:6e")
|
|
||||||
}
|
|
||||||
|
|
||||||
func testECDSA384SHA256Fingerprint() {
|
|
||||||
XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa384Secret), "SHA256:GJUEymQNL9ymaMRRJCMGY4rWIJHu/Lm8Yhao/PAiz1I")
|
|
||||||
}
|
|
||||||
|
|
||||||
func testECDSA384PublicKey() {
|
|
||||||
XCTAssertEqual(writer.openSSHString(secret: Constants.ecdsa384Secret),
|
|
||||||
"ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")
|
|
||||||
}
|
|
||||||
|
|
||||||
func testECDSA384Hash() {
|
|
||||||
XCTAssertEqual(writer.data(secret: Constants.ecdsa384Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ=="))
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension OpenSSHWriterTests {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
static let ecdsa256Secret = SmartCard.Secret(id: Data(), name: "Test Key (ECDSA 256)", algorithm: .ellipticCurve, keySize: 256, publicKey: Data(base64Encoded: "BOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")!)
|
|
||||||
static let ecdsa384Secret = SmartCard.Secret(id: Data(), name: "Test Key (ECDSA 384)", algorithm: .ellipticCurve, keySize: 384, publicKey: Data(base64Encoded: "BG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")!)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,44 +1,73 @@
|
|||||||
import Cocoa
|
import Cocoa
|
||||||
import OSLog
|
import OSLog
|
||||||
import Combine
|
|
||||||
import SecretKit
|
import SecretKit
|
||||||
import SecureEnclaveSecretKit
|
import SecureEnclaveSecretKit
|
||||||
import SmartCardSecretKit
|
import SmartCardSecretKit
|
||||||
import SecretAgentKit
|
import SecretAgentKit
|
||||||
import Brief
|
import Brief
|
||||||
|
import Observation
|
||||||
|
import Common
|
||||||
|
|
||||||
@NSApplicationMain
|
@main
|
||||||
class AppDelegate: NSObject, NSApplicationDelegate {
|
class AppDelegate: NSObject, NSApplicationDelegate {
|
||||||
|
|
||||||
private let storeList: SecretStoreList = {
|
@MainActor private let storeList: SecretStoreList = {
|
||||||
let list = SecretStoreList()
|
let list = SecretStoreList()
|
||||||
list.add(store: SecureEnclave.Store())
|
let cryptoKit = SecureEnclave.Store()
|
||||||
|
let migrator = SecureEnclave.CryptoKitMigrator()
|
||||||
|
try? migrator.migrate(to: cryptoKit)
|
||||||
|
list.add(store: cryptoKit)
|
||||||
list.add(store: SmartCard.Store())
|
list.add(store: SmartCard.Store())
|
||||||
return list
|
return list
|
||||||
}()
|
}()
|
||||||
private let updater = Updater(checkOnLaunch: false)
|
private let updater = Updater(checkOnLaunch: true)
|
||||||
private let notifier = Notifier()
|
private let notifier = Notifier()
|
||||||
|
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: URL.homeDirectory)
|
||||||
private lazy var agent: Agent = {
|
private lazy var agent: Agent = {
|
||||||
Agent(storeList: storeList, witness: notifier)
|
Agent(storeList: storeList, witness: notifier)
|
||||||
}()
|
}()
|
||||||
private lazy var socketController: SocketController = {
|
private lazy var socketController: SocketController = {
|
||||||
let path = (NSHomeDirectory() as NSString).appendingPathComponent("socket.ssh") as String
|
let path = URL.socketPath as String
|
||||||
return SocketController(path: path)
|
return SocketController(path: path)
|
||||||
}()
|
}()
|
||||||
private var updateSink: AnyCancellable?
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "AppDelegate")
|
||||||
|
|
||||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
||||||
Logger().debug("SecretAgent finished launching")
|
logger.debug("SecretAgent finished launching")
|
||||||
DispatchQueue.main.async {
|
Task {
|
||||||
self.socketController.handler = self.agent.handle(reader:writer:)
|
let inputParser = try await XPCAgentInputParser()
|
||||||
|
for await session in socketController.sessions {
|
||||||
|
Task {
|
||||||
|
do {
|
||||||
|
for await message in session.messages {
|
||||||
|
let request = try await inputParser.parse(data: message)
|
||||||
|
let agentResponse = await agent.handle(request: request, provenance: session.provenance)
|
||||||
|
try session.write(agentResponse)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
try session.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Task {
|
||||||
|
for await _ in NotificationCenter.default.notifications(named: .secretStoreReloaded) {
|
||||||
|
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.allSecrets, clear: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.allSecrets, clear: true)
|
||||||
notifier.prompt()
|
notifier.prompt()
|
||||||
updateSink = updater.$update.sink { update in
|
_ = withObservationTracking {
|
||||||
guard let update = update else { return }
|
updater.update
|
||||||
self.notifier.notify(update: update, ignore: self.updater.ignore(release:))
|
} onChange: { [updater, notifier] in
|
||||||
|
Task {
|
||||||
|
guard !updater.currentVersion.isTestBuild else { return }
|
||||||
|
await notifier.notify(update: updater.update!) { release in
|
||||||
|
await updater.ignore(release: release)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,60 +0,0 @@
|
|||||||
{
|
|
||||||
"images" : [
|
|
||||||
{
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "1x",
|
|
||||||
"size" : "16x16"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "2x",
|
|
||||||
"size" : "16x16"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "1x",
|
|
||||||
"size" : "32x32"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "2x",
|
|
||||||
"size" : "32x32"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "1x",
|
|
||||||
"size" : "128x128"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "2x",
|
|
||||||
"size" : "128x128"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"filename" : "Mac Icon.png",
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "1x",
|
|
||||||
"size" : "256x256"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"filename" : "Mac Icon@0.25x.png",
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "2x",
|
|
||||||
"size" : "256x256"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "1x",
|
|
||||||
"size" : "512x512"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"idiom" : "mac",
|
|
||||||
"scale" : "2x",
|
|
||||||
"size" : "512x512"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"info" : {
|
|
||||||
"author" : "xcode",
|
|
||||||
"version" : 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 40 KiB |
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"info" : {
|
|
||||||
"author" : "xcode",
|
|
||||||
"version" : 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -9,22 +9,7 @@
|
|||||||
<key>Website</key>
|
<key>Website</key>
|
||||||
<string>https://github.com/maxgoedjen/secretive</string>
|
<string>https://github.com/maxgoedjen/secretive</string>
|
||||||
<key>Connections</key>
|
<key>Connections</key>
|
||||||
<array>
|
<array/>
|
||||||
<dict>
|
|
||||||
<key>IsIncoming</key>
|
|
||||||
<false/>
|
|
||||||
<key>Host</key>
|
|
||||||
<string>api.github.com</string>
|
|
||||||
<key>NetworkProtocol</key>
|
|
||||||
<string>TCP</string>
|
|
||||||
<key>Port</key>
|
|
||||||
<string>443</string>
|
|
||||||
<key>Purpose</key>
|
|
||||||
<string>Secretive checks GitHub for new versions and security updates.</string>
|
|
||||||
<key>DenyConsequences</key>
|
|
||||||
<string>If you deny these connections, you will not be notified about new versions and critical security updates.</string>
|
|
||||||
</dict>
|
|
||||||
</array>
|
|
||||||
<key>Services</key>
|
<key>Services</key>
|
||||||
<array/>
|
<array/>
|
||||||
</dict>
|
</dict>
|
||||||
|
|||||||
@@ -5,13 +5,13 @@ import SecretKit
|
|||||||
import SecretAgentKit
|
import SecretAgentKit
|
||||||
import Brief
|
import Brief
|
||||||
|
|
||||||
class Notifier {
|
final class Notifier: Sendable {
|
||||||
|
|
||||||
private let notificationDelegate = NotificationDelegate()
|
private let notificationDelegate = NotificationDelegate()
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: "Update", options: [])
|
let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: String(localized: .updateNotificationUpdateButton), options: [])
|
||||||
let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: "Ignore", options: [])
|
let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: String(localized: .updateNotificationIgnoreButton), options: [])
|
||||||
let updateCategory = UNNotificationCategory(identifier: Constants.updateCategoryIdentitifier, actions: [updateAction, ignoreAction], intentIdentifiers: [], options: [])
|
let updateCategory = UNNotificationCategory(identifier: Constants.updateCategoryIdentitifier, actions: [updateAction, ignoreAction], intentIdentifiers: [], options: [])
|
||||||
let criticalUpdateCategory = UNNotificationCategory(identifier: Constants.criticalUpdateCategoryIdentitifier, actions: [updateAction], intentIdentifiers: [], options: [])
|
let criticalUpdateCategory = UNNotificationCategory(identifier: Constants.criticalUpdateCategoryIdentitifier, actions: [updateAction], intentIdentifiers: [], options: [])
|
||||||
|
|
||||||
@@ -22,32 +22,35 @@ class Notifier {
|
|||||||
Measurement(value: 24, unit: UnitDuration.hours)
|
Measurement(value: 24, unit: UnitDuration.hours)
|
||||||
]
|
]
|
||||||
|
|
||||||
let doNotPersistAction = UNNotificationAction(identifier: Constants.doNotPersistActionIdentitifier, title: "Do Not Unlock", options: [])
|
let doNotPersistAction = UNNotificationAction(identifier: Constants.doNotPersistActionIdentitifier, title: String(localized: .persistAuthenticationDeclineButton), options: [])
|
||||||
var allPersistenceActions = [doNotPersistAction]
|
var allPersistenceActions = [doNotPersistAction]
|
||||||
|
|
||||||
let formatter = DateComponentsFormatter()
|
let formatter = DateComponentsFormatter()
|
||||||
formatter.unitsStyle = .spellOut
|
formatter.unitsStyle = .spellOut
|
||||||
formatter.allowedUnits = [.hour, .minute, .day]
|
formatter.allowedUnits = [.hour, .minute, .day]
|
||||||
|
|
||||||
|
var identifiers: [String: TimeInterval] = [:]
|
||||||
for duration in rawDurations {
|
for duration in rawDurations {
|
||||||
let seconds = duration.converted(to: .seconds).value
|
let seconds = duration.converted(to: .seconds).value
|
||||||
guard let string = formatter.string(from: seconds)?.capitalized else { continue }
|
guard let string = formatter.string(from: seconds)?.capitalized else { continue }
|
||||||
let identifier = Constants.persistAuthenticationCategoryIdentitifier.appending("\(seconds)")
|
let identifier = Constants.persistAuthenticationCategoryIdentitifier.appending("\(seconds)")
|
||||||
let action = UNNotificationAction(identifier: identifier, title: string, options: [])
|
let action = UNNotificationAction(identifier: identifier, title: string, options: [])
|
||||||
notificationDelegate.persistOptions[identifier] = seconds
|
identifiers[identifier] = seconds
|
||||||
allPersistenceActions.append(action)
|
allPersistenceActions.append(action)
|
||||||
}
|
}
|
||||||
|
|
||||||
let persistAuthenticationCategory = UNNotificationCategory(identifier: Constants.persistAuthenticationCategoryIdentitifier, actions: allPersistenceActions, intentIdentifiers: [], options: [])
|
let persistAuthenticationCategory = UNNotificationCategory(identifier: Constants.persistAuthenticationCategoryIdentitifier, actions: allPersistenceActions, intentIdentifiers: [], options: [])
|
||||||
if persistAuthenticationCategory.responds(to: Selector(("actionsMenuTitle"))) {
|
if persistAuthenticationCategory.responds(to: Selector(("actionsMenuTitle"))) {
|
||||||
persistAuthenticationCategory.setValue("Leave Unlocked", forKey: "_actionsMenuTitle")
|
persistAuthenticationCategory.setValue(String(localized: .persistAuthenticationAcceptButton), forKey: "_actionsMenuTitle")
|
||||||
}
|
}
|
||||||
UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory, persistAuthenticationCategory])
|
UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory, persistAuthenticationCategory])
|
||||||
UNUserNotificationCenter.current().delegate = notificationDelegate
|
UNUserNotificationCenter.current().delegate = notificationDelegate
|
||||||
|
|
||||||
notificationDelegate.persistAuthentication = { secret, store, duration in
|
Task {
|
||||||
guard let duration = duration else { return }
|
await notificationDelegate.state.setPersistenceState(options: identifiers) { secret, store, duration in
|
||||||
try? store.persistAuthentication(secret: secret, forDuration: duration)
|
guard let duration = duration else { return }
|
||||||
|
try? await store.persistAuthentication(secret: secret, forDuration: duration)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -57,57 +60,51 @@ class Notifier {
|
|||||||
notificationCenter.requestAuthorization(options: .alert) { _, _ in }
|
notificationCenter.requestAuthorization(options: .alert) { _, _ in }
|
||||||
}
|
}
|
||||||
|
|
||||||
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) {
|
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async {
|
||||||
notificationDelegate.pendingPersistableSecrets[secret.id.description] = secret
|
await notificationDelegate.state.setPending(secret: secret, store: store)
|
||||||
notificationDelegate.pendingPersistableStores[store.id.description] = store
|
|
||||||
let notificationCenter = UNUserNotificationCenter.current()
|
let notificationCenter = UNUserNotificationCenter.current()
|
||||||
let notificationContent = UNMutableNotificationContent()
|
let notificationContent = UNMutableNotificationContent()
|
||||||
notificationContent.title = "Signed Request from \(provenance.origin.displayName)"
|
notificationContent.title = String(localized: .signedNotificationTitle(appName: provenance.origin.displayName))
|
||||||
notificationContent.subtitle = "Using secret \"\(secret.name)\""
|
notificationContent.subtitle = String(localized: .signedNotificationDescription(secretName: secret.name))
|
||||||
notificationContent.userInfo[Constants.persistSecretIDKey] = secret.id.description
|
notificationContent.userInfo[Constants.persistSecretIDKey] = secret.id.description
|
||||||
notificationContent.userInfo[Constants.persistStoreIDKey] = store.id.description
|
notificationContent.userInfo[Constants.persistStoreIDKey] = store.id.description
|
||||||
if #available(macOS 12.0, *) {
|
notificationContent.interruptionLevel = .timeSensitive
|
||||||
notificationContent.interruptionLevel = .timeSensitive
|
if await store.existingPersistedAuthenticationContext(secret: secret) == nil && secret.authenticationRequirement.required {
|
||||||
}
|
|
||||||
if requiredAuthentication {
|
|
||||||
notificationContent.categoryIdentifier = Constants.persistAuthenticationCategoryIdentitifier
|
notificationContent.categoryIdentifier = Constants.persistAuthenticationCategoryIdentitifier
|
||||||
}
|
}
|
||||||
if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) {
|
if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) {
|
||||||
notificationContent.attachments = [attachment]
|
notificationContent.attachments = [attachment]
|
||||||
}
|
}
|
||||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||||
notificationCenter.add(request, withCompletionHandler: nil)
|
try? await notificationCenter.add(request)
|
||||||
}
|
}
|
||||||
|
|
||||||
func notify(update: Release, ignore: ((Release) -> Void)?) {
|
func notify(update: Release, ignore: (@Sendable (Release) async -> Void)?) async {
|
||||||
notificationDelegate.release = update
|
await notificationDelegate.state.prepareForNotification(release: update, ignoreAction: ignore)
|
||||||
notificationDelegate.ignore = ignore
|
|
||||||
let notificationCenter = UNUserNotificationCenter.current()
|
let notificationCenter = UNUserNotificationCenter.current()
|
||||||
let notificationContent = UNMutableNotificationContent()
|
let notificationContent = UNMutableNotificationContent()
|
||||||
if update.critical {
|
if update.critical {
|
||||||
if #available(macOS 12.0, *) {
|
notificationContent.interruptionLevel = .critical
|
||||||
notificationContent.interruptionLevel = .critical
|
notificationContent.title = String(localized: .updateNotificationUpdateCriticalTitle(updateName: update.name))
|
||||||
}
|
|
||||||
notificationContent.title = "Critical Security Update - \(update.name)"
|
|
||||||
} else {
|
} else {
|
||||||
notificationContent.title = "Update Available - \(update.name)"
|
notificationContent.title = String(localized: .updateNotificationUpdateNormalTitle(updateName: update.name))
|
||||||
}
|
}
|
||||||
notificationContent.subtitle = "Click to Update"
|
notificationContent.subtitle = String(localized: .updateNotificationUpdateDescription)
|
||||||
notificationContent.body = update.body
|
notificationContent.body = update.body
|
||||||
notificationContent.categoryIdentifier = update.critical ? Constants.criticalUpdateCategoryIdentitifier : Constants.updateCategoryIdentitifier
|
notificationContent.categoryIdentifier = update.critical ? Constants.criticalUpdateCategoryIdentitifier : Constants.updateCategoryIdentitifier
|
||||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||||
notificationCenter.add(request, withCompletionHandler: nil)
|
try? await notificationCenter.add(request)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Notifier: SigningWitness {
|
extension Notifier: SigningWitness {
|
||||||
|
|
||||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws {
|
||||||
}
|
}
|
||||||
|
|
||||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws {
|
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws {
|
||||||
notify(accessTo: secret, from: store, by: provenance, requiredAuthentication: requiredAuthentication)
|
await notify(accessTo: secret, from: store, by: provenance)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -133,55 +130,91 @@ extension Notifier {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
|
final class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate, Sendable {
|
||||||
|
|
||||||
fileprivate var release: Release?
|
fileprivate actor State {
|
||||||
fileprivate var ignore: ((Release) -> Void)?
|
typealias PersistAction = (@Sendable (AnySecret, AnySecretStore, TimeInterval?) async -> Void)
|
||||||
fileprivate var persistAuthentication: ((AnySecret, AnySecretStore, TimeInterval?) -> Void)?
|
typealias IgnoreAction = (@Sendable (Release) async -> Void)
|
||||||
fileprivate var persistOptions: [String: TimeInterval] = [:]
|
fileprivate var release: Release?
|
||||||
fileprivate var pendingPersistableStores: [String: AnySecretStore] = [:]
|
fileprivate var ignoreAction: IgnoreAction?
|
||||||
fileprivate var pendingPersistableSecrets: [String: AnySecret] = [:]
|
fileprivate var persistAction: PersistAction?
|
||||||
|
fileprivate var persistOptions: [String: TimeInterval] = [:]
|
||||||
|
fileprivate var pendingPersistableStores: [String: AnySecretStore] = [:]
|
||||||
|
fileprivate var pendingPersistableSecrets: [String: AnySecret] = [:]
|
||||||
|
|
||||||
|
func setPending(secret: AnySecret, store: AnySecretStore) {
|
||||||
|
pendingPersistableSecrets[secret.id.description] = secret
|
||||||
|
pendingPersistableStores[store.id.description] = store
|
||||||
|
}
|
||||||
|
|
||||||
|
func retrievePending(secretID: String, storeID: String, optionID: String) -> (AnySecret, AnySecretStore, TimeInterval)? {
|
||||||
|
guard let secret = pendingPersistableSecrets[secretID],
|
||||||
|
let store = pendingPersistableStores[storeID],
|
||||||
|
let options = persistOptions[optionID] else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
pendingPersistableSecrets.removeValue(forKey: secretID)
|
||||||
|
return (secret, store, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
func setPersistenceState(options: [String: TimeInterval], action: @escaping PersistAction) {
|
||||||
|
self.persistOptions = options
|
||||||
|
self.persistAction = action
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareForNotification(release: Release, ignoreAction: IgnoreAction?) {
|
||||||
|
self.release = release
|
||||||
|
self.ignoreAction = ignoreAction
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
fileprivate let state = State()
|
||||||
|
|
||||||
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
|
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
|
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
|
||||||
let category = response.notification.request.content.categoryIdentifier
|
let category = response.notification.request.content.categoryIdentifier
|
||||||
switch category {
|
switch category {
|
||||||
case Notifier.Constants.updateCategoryIdentitifier:
|
case Notifier.Constants.updateCategoryIdentitifier:
|
||||||
handleUpdateResponse(response: response)
|
await handleUpdateResponse(response: response)
|
||||||
case Notifier.Constants.persistAuthenticationCategoryIdentitifier:
|
case Notifier.Constants.persistAuthenticationCategoryIdentitifier:
|
||||||
handlePersistAuthenticationResponse(response: response)
|
await handlePersistAuthenticationResponse(response: response)
|
||||||
default:
|
default:
|
||||||
fatalError()
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
completionHandler()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleUpdateResponse(response: UNNotificationResponse) {
|
func handleUpdateResponse(response: UNNotificationResponse) async {
|
||||||
guard let update = release else { return }
|
let id = response.actionIdentifier
|
||||||
switch response.actionIdentifier {
|
guard let update = await state.release else { return }
|
||||||
|
switch id {
|
||||||
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
|
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
|
||||||
NSWorkspace.shared.open(update.html_url)
|
NSWorkspace.shared.open(update.html_url)
|
||||||
case Notifier.Constants.ignoreActionIdentitifier:
|
case Notifier.Constants.ignoreActionIdentitifier:
|
||||||
ignore?(update)
|
await state.ignoreAction?(update)
|
||||||
default:
|
default:
|
||||||
fatalError()
|
fatalError()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func handlePersistAuthenticationResponse(response: UNNotificationResponse) {
|
func handlePersistAuthenticationResponse(response: UNNotificationResponse) async {
|
||||||
guard let secretID = response.notification.request.content.userInfo[Notifier.Constants.persistSecretIDKey] as? String, let secret = pendingPersistableSecrets[secretID],
|
guard let secretID = response.notification.request.content.userInfo[Notifier.Constants.persistSecretIDKey] as? String,
|
||||||
let storeID = response.notification.request.content.userInfo[Notifier.Constants.persistStoreIDKey] as? String, let store = pendingPersistableStores[storeID]
|
let storeID = response.notification.request.content.userInfo[Notifier.Constants.persistStoreIDKey] as? String else {
|
||||||
else { return }
|
return
|
||||||
pendingPersistableSecrets[secretID] = nil
|
}
|
||||||
persistAuthentication?(secret, store, persistOptions[response.actionIdentifier])
|
let optionID = response.actionIdentifier
|
||||||
|
guard let (secret, store, persistOptions) = await state.retrievePending(secretID: secretID, storeID: storeID, optionID: optionID) else { return }
|
||||||
|
await state.persistAction?(secret, store, persistOptions)
|
||||||
}
|
}
|
||||||
|
|
||||||
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
|
|
||||||
completionHandler([.list, .banner])
|
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
|
||||||
|
[.list, .banner]
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,6 @@
|
|||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
<plist version="1.0">
|
<plist version="1.0">
|
||||||
<dict>
|
<dict>
|
||||||
<key>com.apple.security.app-sandbox</key>
|
|
||||||
<true/>
|
|
||||||
<key>com.apple.security.network.client</key>
|
|
||||||
<true/>
|
|
||||||
<key>com.apple.security.smartcard</key>
|
<key>com.apple.security.smartcard</key>
|
||||||
<true/>
|
<true/>
|
||||||
<key>keychain-access-groups</key>
|
<key>keychain-access-groups</key>
|
||||||
|
|||||||
29
Sources/SecretAgent/XPCInputParser.swift
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import Foundation
|
||||||
|
import SecretAgentKit
|
||||||
|
import Brief
|
||||||
|
import XPCWrappers
|
||||||
|
import OSLog
|
||||||
|
|
||||||
|
/// Delegates all agent input parsing to an XPC service which wraps OpenSSH
|
||||||
|
public final class XPCAgentInputParser: SSHAgentInputParserProtocol {
|
||||||
|
|
||||||
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "XPCAgentInputParser")
|
||||||
|
private let session: XPCTypedSession<SSHAgent.Request, SSHAgentInputParser.AgentParsingError>
|
||||||
|
|
||||||
|
public init() async throws {
|
||||||
|
logger.debug("Creating XPCAgentInputParser")
|
||||||
|
session = try await XPCTypedSession(serviceName: "com.maxgoedjen.Secretive.SecretAgentInputParser", warmup: true)
|
||||||
|
logger.debug("XPCAgentInputParser is warmed up.")
|
||||||
|
}
|
||||||
|
|
||||||
|
public func parse(data: Data) async throws -> SSHAgent.Request {
|
||||||
|
logger.debug("Parsing input")
|
||||||
|
defer { logger.debug("Parsed input") }
|
||||||
|
return try await session.send(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
session.complete()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
11
Sources/SecretAgentInputParser/Info.plist
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>XPCService</key>
|
||||||
|
<dict>
|
||||||
|
<key>ServiceType</key>
|
||||||
|
<string>Application</string>
|
||||||
|
</dict>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
17
Sources/SecretAgentInputParser/SecretAgentInputParser.swift
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import Foundation
|
||||||
|
import OSLog
|
||||||
|
import XPCWrappers
|
||||||
|
import SecretAgentKit
|
||||||
|
|
||||||
|
final class SecretAgentInputParser: NSObject, XPCProtocol {
|
||||||
|
|
||||||
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.SecretAgentInputParser", category: "SecretAgentInputParser")
|
||||||
|
|
||||||
|
func process(_ data: Data) async throws -> SSHAgent.Request {
|
||||||
|
let parser = SSHAgentInputParser()
|
||||||
|
let result = try parser.parse(data: data)
|
||||||
|
logger.log("Parser parsed message as type \(result.debugDescription)")
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
7
Sources/SecretAgentInputParser/main.swift
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import Foundation
|
||||||
|
import XPCWrappers
|
||||||
|
|
||||||
|
let delegate = XPCServiceDelegate(exportedObject: SecretAgentInputParser())
|
||||||
|
let listener = NSXPCListener.service()
|
||||||
|
listener.delegate = delegate
|
||||||
|
listener.resume()
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>iOSPackagesShouldBuildARM64e</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Scheme
|
||||||
|
LastUpgradeVersion = "2600"
|
||||||
|
version = "1.7">
|
||||||
|
<BuildAction
|
||||||
|
parallelizeBuildables = "YES"
|
||||||
|
buildImplicitDependencies = "YES"
|
||||||
|
buildArchitectures = "Automatic">
|
||||||
|
</BuildAction>
|
||||||
|
<TestAction
|
||||||
|
buildConfiguration = "Debug"
|
||||||
|
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||||
|
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||||
|
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||||
|
<TestPlans>
|
||||||
|
<TestPlanReference
|
||||||
|
reference = "container:Config/Secretive.xctestplan">
|
||||||
|
</TestPlanReference>
|
||||||
|
</TestPlans>
|
||||||
|
</TestAction>
|
||||||
|
<LaunchAction
|
||||||
|
buildConfiguration = "Debug"
|
||||||
|
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||||
|
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||||
|
launchStyle = "0"
|
||||||
|
useCustomWorkingDirectory = "NO"
|
||||||
|
ignoresPersistentStateOnLaunch = "NO"
|
||||||
|
debugDocumentVersioning = "YES"
|
||||||
|
debugServiceExtension = "internal"
|
||||||
|
allowLocationSimulation = "YES">
|
||||||
|
</LaunchAction>
|
||||||
|
<ProfileAction
|
||||||
|
buildConfiguration = "Release"
|
||||||
|
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||||
|
savedToolIdentifier = ""
|
||||||
|
useCustomWorkingDirectory = "NO"
|
||||||
|
debugDocumentVersioning = "YES">
|
||||||
|
</ProfileAction>
|
||||||
|
<AnalyzeAction
|
||||||
|
buildConfiguration = "Debug">
|
||||||
|
</AnalyzeAction>
|
||||||
|
<ArchiveAction
|
||||||
|
buildConfiguration = "Release"
|
||||||
|
revealArchiveInOrganizer = "YES">
|
||||||
|
</ArchiveAction>
|
||||||
|
</Scheme>
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<Scheme
|
<Scheme
|
||||||
LastUpgradeVersion = "1320"
|
LastUpgradeVersion = "2600"
|
||||||
version = "1.7">
|
version = "1.7">
|
||||||
<BuildAction
|
<BuildAction
|
||||||
parallelizeBuildables = "YES"
|
parallelizeBuildables = "YES"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<Scheme
|
<Scheme
|
||||||
LastUpgradeVersion = "1320"
|
LastUpgradeVersion = "2600"
|
||||||
version = "1.7">
|
version = "1.7">
|
||||||
<BuildAction
|
<BuildAction
|
||||||
parallelizeBuildables = "YES"
|
parallelizeBuildables = "YES"
|
||||||
@@ -75,6 +75,7 @@
|
|||||||
ignoresPersistentStateOnLaunch = "NO"
|
ignoresPersistentStateOnLaunch = "NO"
|
||||||
debugDocumentVersioning = "YES"
|
debugDocumentVersioning = "YES"
|
||||||
debugServiceExtension = "internal"
|
debugServiceExtension = "internal"
|
||||||
|
enableGPUValidationMode = "1"
|
||||||
allowLocationSimulation = "YES">
|
allowLocationSimulation = "YES">
|
||||||
<BuildableProductRunnable
|
<BuildableProductRunnable
|
||||||
runnableDebuggingMode = "0">
|
runnableDebuggingMode = "0">
|
||||||
@@ -88,7 +89,7 @@
|
|||||||
</BuildableProductRunnable>
|
</BuildableProductRunnable>
|
||||||
</LaunchAction>
|
</LaunchAction>
|
||||||
<ProfileAction
|
<ProfileAction
|
||||||
buildConfiguration = "Release"
|
buildConfiguration = "Debug"
|
||||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||||
savedToolIdentifier = ""
|
savedToolIdentifier = ""
|
||||||
useCustomWorkingDirectory = "NO"
|
useCustomWorkingDirectory = "NO"
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import Cocoa
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
import SecretKit
|
import SecretKit
|
||||||
import SecureEnclaveSecretKit
|
import SecureEnclaveSecretKit
|
||||||
@@ -7,57 +6,73 @@ import Brief
|
|||||||
|
|
||||||
@main
|
@main
|
||||||
struct Secretive: App {
|
struct Secretive: App {
|
||||||
|
|
||||||
private let storeList: SecretStoreList = {
|
@Environment(\.agentLaunchController) var agentLaunchController
|
||||||
let list = SecretStoreList()
|
@Environment(\.justUpdatedChecker) var justUpdatedChecker
|
||||||
list.add(store: SecureEnclave.Store())
|
|
||||||
list.add(store: SmartCard.Store())
|
|
||||||
return list
|
|
||||||
}()
|
|
||||||
private let agentStatusChecker = AgentStatusChecker()
|
|
||||||
private let justUpdatedChecker = JustUpdatedChecker()
|
|
||||||
|
|
||||||
@AppStorage("defaultsHasRunSetup") var hasRunSetup = false
|
|
||||||
@State private var showingSetup = false
|
|
||||||
@State private var showingCreation = false
|
|
||||||
|
|
||||||
@SceneBuilder var body: some Scene {
|
@SceneBuilder var body: some Scene {
|
||||||
WindowGroup {
|
WindowGroup {
|
||||||
ContentView<Updater, AgentStatusChecker>(showingCreation: $showingCreation, runningSetup: $showingSetup, hasRunSetup: $hasRunSetup)
|
ContentView()
|
||||||
.environmentObject(storeList)
|
.environment(EnvironmentValues._secretStoreList)
|
||||||
.environmentObject(Updater(checkOnLaunch: hasRunSetup))
|
|
||||||
.environmentObject(agentStatusChecker)
|
|
||||||
.onAppear {
|
|
||||||
if !hasRunSetup {
|
|
||||||
showingSetup = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
|
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
|
||||||
guard hasRunSetup else { return }
|
Task {
|
||||||
agentStatusChecker.check()
|
@AppStorage("defaultsHasRunSetup") var hasRunSetup = false
|
||||||
if agentStatusChecker.running && justUpdatedChecker.justUpdated {
|
@AppStorage("explicitlyDisabled") var explicitlyDisabled = false
|
||||||
// Relaunch the agent, since it'll be running from earlier update still
|
guard hasRunSetup && !explicitlyDisabled else { return }
|
||||||
reinstallAgent()
|
agentLaunchController.check()
|
||||||
} else if !agentStatusChecker.running && !agentStatusChecker.developmentBuild {
|
guard !agentLaunchController.developmentBuild else { return }
|
||||||
forceLaunchAgent()
|
if justUpdatedChecker.justUpdatedBuild || !agentLaunchController.running {
|
||||||
|
// Relaunch the agent, since it'll be running from earlier update still
|
||||||
|
try await agentLaunchController.forceLaunch()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.commands {
|
.commands {
|
||||||
|
AppCommands()
|
||||||
|
}
|
||||||
|
WindowGroup(id: String(describing: IntegrationsView.self)) {
|
||||||
|
IntegrationsView()
|
||||||
|
}
|
||||||
|
.windowResizability(.contentMinSize)
|
||||||
|
WindowGroup(id: String(describing: AboutView.self)) {
|
||||||
|
AboutView()
|
||||||
|
}
|
||||||
|
.windowStyle(.hiddenTitleBar)
|
||||||
|
.windowResizability(.contentSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Secretive {
|
||||||
|
|
||||||
|
struct AppCommands: Commands {
|
||||||
|
|
||||||
|
@Environment(\.openWindow) var openWindow
|
||||||
|
@Environment(\.openURL) var openURL
|
||||||
|
@FocusedValue(\.showCreateSecret) var showCreateSecret
|
||||||
|
|
||||||
|
var body: some Commands {
|
||||||
|
CommandGroup(replacing: .appInfo) {
|
||||||
|
Button(.aboutMenuBarTitle, systemImage: "info.circle") {
|
||||||
|
openWindow(id: String(describing: AboutView.self))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CommandGroup(before: CommandGroupPlacement.appSettings) {
|
||||||
|
Button(.integrationsMenuBarTitle, systemImage: "app.connected.to.app.below.fill") {
|
||||||
|
openWindow(id: String(describing: IntegrationsView.self))
|
||||||
|
}
|
||||||
|
}
|
||||||
CommandGroup(after: CommandGroupPlacement.newItem) {
|
CommandGroup(after: CommandGroupPlacement.newItem) {
|
||||||
Button("New Secret") {
|
Button(.appMenuNewSecretButton, systemImage: "plus") {
|
||||||
showingCreation = true
|
showCreateSecret?()
|
||||||
}
|
}
|
||||||
.keyboardShortcut(KeyboardShortcut(KeyEquivalent("N"), modifiers: [.command, .shift]))
|
.keyboardShortcut(KeyboardShortcut(KeyEquivalent("N"), modifiers: [.command, .shift]))
|
||||||
|
.disabled(showCreateSecret?.isEnabled == false)
|
||||||
}
|
}
|
||||||
CommandGroup(replacing: .help) {
|
CommandGroup(replacing: .help) {
|
||||||
Button("Help") {
|
Button(.appMenuHelpButton) {
|
||||||
NSWorkspace.shared.open(Constants.helpURL)
|
openURL(Constants.helpURL)
|
||||||
}
|
|
||||||
}
|
|
||||||
CommandGroup(after: .help) {
|
|
||||||
Button("Setup Secretive") {
|
|
||||||
showingSetup = true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
SidebarCommands()
|
SidebarCommands()
|
||||||
@@ -66,33 +81,56 @@ struct Secretive: App {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Secretive {
|
|
||||||
|
|
||||||
private func reinstallAgent() {
|
|
||||||
justUpdatedChecker.check()
|
|
||||||
LaunchAgentController().install {
|
|
||||||
// Wait a second for launchd to kick in (next runloop isn't enough).
|
|
||||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
|
|
||||||
agentStatusChecker.check()
|
|
||||||
if !agentStatusChecker.running {
|
|
||||||
forceLaunchAgent()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func forceLaunchAgent() {
|
|
||||||
// We've run setup, we didn't just update, launchd is just not doing it's thing.
|
|
||||||
// Force a launch directly.
|
|
||||||
LaunchAgentController().forceLaunch { _ in
|
|
||||||
agentStatusChecker.check()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private enum Constants {
|
private enum Constants {
|
||||||
static let helpURL = URL(string: "https://github.com/maxgoedjen/secretive/blob/main/FAQ.md")!
|
static let helpURL = URL(string: "https://github.com/maxgoedjen/secretive/blob/main/FAQ.md")!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
extension EnvironmentValues {
|
||||||
|
|
||||||
|
// This is injected through .environment modifier below instead of @Entry for performance reasons (basially, restrictions around init/mainactor causing delay in loading secrets/"empty screen" blip).
|
||||||
|
@MainActor fileprivate static let _secretStoreList: SecretStoreList = {
|
||||||
|
let list = SecretStoreList()
|
||||||
|
let cryptoKit = SecureEnclave.Store()
|
||||||
|
let migrator = SecureEnclave.CryptoKitMigrator()
|
||||||
|
try? migrator.migrate(to: cryptoKit)
|
||||||
|
list.add(store: cryptoKit)
|
||||||
|
list.add(store: SmartCard.Store())
|
||||||
|
return list
|
||||||
|
}()
|
||||||
|
|
||||||
|
private static let _agentLaunchController = AgentLaunchController()
|
||||||
|
@Entry var agentLaunchController: any AgentLaunchControllerProtocol = _agentLaunchController
|
||||||
|
private static let _updater: any UpdaterProtocol = {
|
||||||
|
@AppStorage("defaultsHasRunSetup") var hasRunSetup = false
|
||||||
|
return Updater(checkOnLaunch: hasRunSetup)
|
||||||
|
}()
|
||||||
|
@Entry var updater: any UpdaterProtocol = _updater
|
||||||
|
|
||||||
|
private static let _justUpdatedChecker = JustUpdatedChecker()
|
||||||
|
@Entry var justUpdatedChecker: any JustUpdatedCheckerProtocol = _justUpdatedChecker
|
||||||
|
|
||||||
|
@MainActor var secretStoreList: SecretStoreList {
|
||||||
|
EnvironmentValues._secretStoreList
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension FocusedValues {
|
||||||
|
@Entry var showCreateSecret: OpenSheet?
|
||||||
|
}
|
||||||
|
|
||||||
|
final class OpenSheet {
|
||||||
|
|
||||||
|
let closure: () -> Void
|
||||||
|
let isEnabled: Bool
|
||||||
|
|
||||||
|
init(isEnabled: Bool = true, closure: @escaping () -> Void) {
|
||||||
|
self.isEnabled = isEnabled
|
||||||
|
self.closure = closure
|
||||||
|
}
|
||||||
|
|
||||||
|
func callAsFunction() {
|
||||||
|
closure()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
BIN
Sources/Secretive/AppIcon.icon/Assets/Icon 7.png
Normal file
|
After Width: | Height: | Size: 43 KiB |