mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-18 08:15:29 +00:00
craft-suite-account: the suite account list and keychain token store
Carries crates/suite-account over from the cut-down craft-libs#160 branch. This follows RFC-0025 (storytold/craft-contrib#35). service.rs is removed. It was the CollabCraft device-flow client. Its Service, Flow, Identity, Polled and SignedOut types went with it. Store::sign_out is also gone. The provider adapter now owns ending a session at the deployment. Store::discard and Store::forget cover the local half that stays here. Every remaining CollabCraft-specific word is reworded to a provider-neutral description. The one serde alias and the one test fixture name that spelled the old provider out are gone too. Adds a generation field to Account, per RFC-0025's cross-app lifecycle guarantees. A sign-in bumps it. Store::update_token refuses a write made against a stale generation. A fuller tombstone for the removal case is left as a TODO referencing the RFC, documented on Accounts::remove. Also drops one unused restrict() function found while verifying clippy -D warnings on Linux. It was pre-existing dead code. The unix write path already sets the file mode at creation.
This commit is contained in:
1 parent
904f55bb21
commit
2e9c84f7ef
11 files changed
+1937
-16
No files matched your search
Generated
+354
-16
@@ -29,6 +29,17 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
"cpubits",
|
||||
"cpufeatures 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
@@ -42,6 +53,15 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
@@ -109,6 +129,17 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "apple-native-keyring-store"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a"
|
||||
dependencies = [
|
||||
"keyring-core",
|
||||
"log",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayref"
|
||||
version = "0.3.9"
|
||||
@@ -392,6 +423,24 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-padding"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
@@ -494,6 +543,12 @@ dependencies = [
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder-lite"
|
||||
version = "0.1.0"
|
||||
@@ -544,6 +599,15 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cbc"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.6.0"
|
||||
@@ -602,6 +666,16 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"crypto-common 0.2.2",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmake"
|
||||
version = "0.1.58"
|
||||
@@ -611,6 +685,12 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "cmpv2"
|
||||
version = "0.2.0"
|
||||
@@ -629,7 +709,7 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"spki",
|
||||
"x509-cert",
|
||||
@@ -705,6 +785,12 @@ version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.4.2"
|
||||
@@ -776,6 +862,12 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpubits"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -839,7 +931,7 @@ dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -924,7 +1016,7 @@ dependencies = [
|
||||
"ruzstd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"tar",
|
||||
"thiserror 2.0.21",
|
||||
@@ -993,7 +1085,7 @@ dependencies = [
|
||||
"image",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
@@ -1138,6 +1230,21 @@ dependencies = [
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-suite-account"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dirs",
|
||||
"keyring",
|
||||
"keyring-core",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tempfile",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
@@ -1197,7 +1304,7 @@ dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"ureq",
|
||||
@@ -1326,6 +1433,24 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cursor-icon"
|
||||
version = "1.2.0"
|
||||
@@ -1344,7 +1469,7 @@ version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der_derive",
|
||||
"flagset",
|
||||
"pem-rfc7468",
|
||||
@@ -1387,8 +1512,20 @@ version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"block-buffer 0.10.4",
|
||||
"crypto-common 0.1.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid 0.10.2",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2061,6 +2198,17 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-macro"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-sink"
|
||||
version = "0.3.34"
|
||||
@@ -2081,6 +2229,7 @@ checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"futures-macro",
|
||||
"futures-sink",
|
||||
"futures-task",
|
||||
"memchr",
|
||||
@@ -2483,6 +2632,24 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
|
||||
dependencies = [
|
||||
"hmac",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
|
||||
dependencies = [
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
@@ -2522,6 +2689,15 @@ version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.12.0"
|
||||
@@ -2901,6 +3077,16 @@ dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
|
||||
dependencies = [
|
||||
"block-padding",
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-extras"
|
||||
version = "0.19.0"
|
||||
@@ -3058,6 +3244,27 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyring"
|
||||
version = "4.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627"
|
||||
dependencies = [
|
||||
"apple-native-keyring-store",
|
||||
"keyring-core",
|
||||
"windows-native-keyring-store",
|
||||
"zbus-secret-service-keyring-store",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyring-core"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29fbf4b551298c67925f38cf341a1ada797a75f1837bdf8ae1fc8e2ebc6efb59"
|
||||
dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "khronos-egl"
|
||||
version = "6.0.0"
|
||||
@@ -3447,6 +3654,30 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-complex",
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-complex"
|
||||
version = "0.4.6"
|
||||
@@ -3462,6 +3693,36 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-iter"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -4551,6 +4812,29 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-lite"
|
||||
version = "0.1.9"
|
||||
@@ -4900,6 +5184,25 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "secret-service"
|
||||
version = "5.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
"futures-util",
|
||||
"getrandom 0.4.3",
|
||||
"hkdf",
|
||||
"hybrid-array",
|
||||
"num",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"sha2 0.11.1",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
@@ -5039,7 +5342,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5050,7 +5353,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5104,12 +5418,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.22.1",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
"pem",
|
||||
"rand_core 0.10.1",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"signature",
|
||||
"sigstore-types",
|
||||
"spki",
|
||||
@@ -5178,7 +5492,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"cmpv2",
|
||||
"cms",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"hex",
|
||||
"rand",
|
||||
@@ -5217,7 +5531,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cms",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"hex",
|
||||
"pem",
|
||||
"rustls-pki-types",
|
||||
@@ -6912,6 +7226,19 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-native-keyring-store"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"keyring-core",
|
||||
"regex",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
@@ -7235,7 +7562,7 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"sha1",
|
||||
"signature",
|
||||
@@ -7376,6 +7703,17 @@ dependencies = [
|
||||
"zvariant",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus-secret-service-keyring-store"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a"
|
||||
dependencies = [
|
||||
"keyring-core",
|
||||
"secret-service",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus_macros"
|
||||
version = "5.19.0"
|
||||
|
||||
@@ -48,6 +48,7 @@ craft-print = { path = "crates/print" }
|
||||
craft-proof = { path = "crates/proof" }
|
||||
craft-quit = { path = "crates/quit" }
|
||||
craft-settings = { path = "crates/settings" }
|
||||
craft-suite-account = { path = "crates/suite-account" }
|
||||
craft-text = { path = "crates/text" }
|
||||
craft-ui = { path = "crates/ui" }
|
||||
craft-update = { path = "crates/update" }
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "craft-suite-account"
|
||||
description = "Shared suite-level account store: who is signed in, kept once for the whole Craft suite, with the token in the operating system's keychain"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
log = "0.4"
|
||||
# Non-wasm only: no per-user config dir in the browser.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
dirs = "7"
|
||||
# The account handle is a digest of the service and the user, so the same account always lands on
|
||||
# the same keychain entry and a second sign-in replaces it instead of leaving one behind.
|
||||
sha2 = "0.10"
|
||||
# Overwrites a token's bytes when the value is dropped. Pure Rust, safe API, so the
|
||||
# workspace's `unsafe_code = "forbid"` still holds.
|
||||
zeroize = { version = "1", features = ["alloc"] }
|
||||
# Windows Credential Manager, the macOS Keychain and the Secret Service, behind one API. The `v1`
|
||||
# default feature picks the right one per platform and pins `crypto-rust` for the Secret Service,
|
||||
# so no OpenSSL and no C toolchain comes in.
|
||||
keyring = "4.2"
|
||||
# The entry constructor that takes store modifiers, which is how a Windows credential asks for
|
||||
# machine-local persistence. `keyring` installs the platform store; this reads it.
|
||||
keyring-core = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,181 @@
|
||||
//! The accounts file: who has signed in and at which deployment.
|
||||
//!
|
||||
//! No token is in here. Every field is something a user interface shows, or something needed to
|
||||
//! find the token in the keychain. See [`crate::store`] for the token itself.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
/// The format this code writes. A reader that does not recognise the number leaves the file alone.
|
||||
pub const FORMAT: u32 = 1;
|
||||
|
||||
/// The largest accounts file that will be read. A suite account list is a few hundred bytes. A
|
||||
/// megabyte is already far past anything legitimate.
|
||||
const MAX_BYTES: u64 = 1 << 20;
|
||||
|
||||
/// One account, as the suite remembers it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Account {
|
||||
/// The handle for this account inside the suite. It is also the keychain entry's user name.
|
||||
///
|
||||
/// A digest of `service` and `user` (see [`handle`]). Signing in again as the same person at
|
||||
/// the same deployment therefore lands on the same keychain entry. No stale entry is left
|
||||
/// behind.
|
||||
pub id: String,
|
||||
/// The deployment this account signs in to, as a base URL with no trailing slash.
|
||||
pub service: String,
|
||||
/// The deployment's own identifier for this account: the OIDC subject, never an address.
|
||||
pub user: String,
|
||||
/// What to show a person. Never an identity: two people can share a display name.
|
||||
pub display: String,
|
||||
pub email: Option<String>,
|
||||
/// Unix seconds when this account was first stored here.
|
||||
pub added: i64,
|
||||
/// Unix seconds when an application last used it.
|
||||
pub last_used: i64,
|
||||
/// Bumped every time this row's content changes: a sign-in that replaces the entry, or (per
|
||||
/// RFC-0025's cross-app lifecycle guarantees) a removal. A caller that read the account before
|
||||
/// one of those passes its generation back on a later write; [`crate::Store::update_token`]
|
||||
/// refuses a write made against a generation that is no longer current, so a refresh started
|
||||
/// before a change completes can never land after it and overwrite something newer.
|
||||
pub generation: u32,
|
||||
}
|
||||
|
||||
/// The whole file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Accounts {
|
||||
pub format: u32,
|
||||
pub accounts: Vec<Account>,
|
||||
/// The account an application should use when it has no reason to prefer another.
|
||||
pub active: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Accounts {
|
||||
fn default() -> Accounts {
|
||||
Accounts { format: FORMAT, accounts: Vec::new(), active: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Accounts {
|
||||
pub fn get(&self, id: &str) -> Option<&Account> {
|
||||
self.accounts.iter().find(|a| a.id == id)
|
||||
}
|
||||
|
||||
/// The active account, when one is named and still on the list.
|
||||
///
|
||||
/// An `active` naming an account that is gone gives the ordinary answer of `None`. A
|
||||
/// half-finished sign-out on another machine must not stop an application starting.
|
||||
pub fn current(&self) -> Option<&Account> {
|
||||
self.active.as_deref().and_then(|id| self.get(id))
|
||||
}
|
||||
|
||||
/// Adds or replaces an account. The account then becomes the active one.
|
||||
pub fn put(&mut self, account: Account) {
|
||||
self.active = Some(account.id.clone());
|
||||
match self.accounts.iter_mut().find(|a| a.id == account.id) {
|
||||
Some(existing) => *existing = account,
|
||||
None => self.accounts.push(account),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops an account. Whoever is left over, if anybody, becomes active.
|
||||
///
|
||||
/// TODO(RFC-0025 lifecycle guarantee 2): the row's generation goes with it, so a refresh that
|
||||
/// started before this removal and lands after it today sees [`crate::Error::Unknown`] rather
|
||||
/// than a generation mismatch. Both already refuse the write; a tombstone that keeps the
|
||||
/// bumped generation around for a bounded window, so that case reports precisely why, is the
|
||||
/// follow-up the RFC names rather than something this extraction lands.
|
||||
pub fn remove(&mut self, id: &str) {
|
||||
self.accounts.retain(|a| a.id != id);
|
||||
if self.active.as_deref() == Some(id) {
|
||||
self.active = self.accounts.first().map(|a| a.id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle for an account at a deployment.
|
||||
///
|
||||
/// A digest, with the address and the subject kept out of it. The digest is stable. One account
|
||||
/// therefore stays on one keychain entry however many times somebody signs in. The handle is also
|
||||
/// opaque. A credential manager window puts the handle on screen. Nobody's address belongs in that
|
||||
/// list.
|
||||
pub fn handle(service: &str, user: &str) -> String {
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(normalise(service).as_bytes());
|
||||
hash.update(b"\n");
|
||||
hash.update(user.as_bytes());
|
||||
let digest = hash.finalize();
|
||||
digest.iter().take(12).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// A deployment's base URL with any trailing slashes taken off. One deployment is then one account
|
||||
/// however the URL was typed.
|
||||
pub fn normalise(service: &str) -> String {
|
||||
service.trim().trim_end_matches('/').to_owned()
|
||||
}
|
||||
|
||||
/// Reads the file. A missing file is an empty list. That is what "nobody has signed in" looks like.
|
||||
pub fn read(path: &Path) -> Result<Accounts, Error> {
|
||||
let bytes = match std::fs::metadata(path) {
|
||||
Ok(meta) if meta.len() > MAX_BYTES => {
|
||||
return Err(Error::Malformed(format!("{} is {} bytes, too large to be an account list", path.display(), meta.len())));
|
||||
}
|
||||
Ok(_) => std::fs::read(path),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Accounts::default()),
|
||||
Err(e) => return Err(Error::Io(format!("couldn't read {} ({e})", path.display()))),
|
||||
};
|
||||
let bytes = bytes.map_err(|e| Error::Io(format!("couldn't read {} ({e})", path.display())))?;
|
||||
let parsed: Accounts = serde_json::from_slice(&bytes).map_err(|e| Error::Malformed(format!("{} didn't parse ({e})", path.display())))?;
|
||||
if parsed.format > FORMAT {
|
||||
return Err(Error::Malformed(format!("{} is format {}. This build understands {FORMAT}.", path.display(), parsed.format)));
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
/// Writes the file through a temporary file and a rename. A crash then never leaves half of one.
|
||||
///
|
||||
/// Readable by this user alone where the platform has file modes. The file holds no token. It does
|
||||
/// say who is signed in. That is nobody else's business.
|
||||
pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> {
|
||||
let dir = path.parent().ok_or_else(|| Error::Io(format!("{} has no parent folder", path.display())))?;
|
||||
std::fs::create_dir_all(dir).map_err(|e| Error::Io(format!("couldn't create {} ({e})", dir.display())))?;
|
||||
let json = serde_json::to_vec_pretty(accounts).map_err(|e| Error::Malformed(e.to_string()))?;
|
||||
use std::io::Write;
|
||||
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
||||
let pid = std::process::id();
|
||||
let tmp = dir.join(format!(".{}.{}.{}.tmp", path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts"), stamp, pid));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::fs::OpenOptions;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&tmp)
|
||||
.map_err(|e| Error::Io(format!("couldn't create {} ({e})", tmp.display())))?;
|
||||
file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
use std::fs::OpenOptions;
|
||||
let mut file =
|
||||
OpenOptions::new().write(true).create_new(true).open(&tmp).map_err(|e| Error::Io(format!("couldn't create {} ({e})", tmp.display())))?;
|
||||
file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?;
|
||||
restrict(&tmp)?;
|
||||
}
|
||||
std::fs::rename(&tmp, path).map_err(|e| Error::Io(format!("couldn't replace {} ({e})", path.display())))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn restrict(_path: &Path) -> Result<(), Error> {
|
||||
// Windows gives a file in `%APPDATA%` the profile's own access rules. Those are this user's.
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! What can go wrong.
|
||||
|
||||
/// A failure in the shared account store.
|
||||
///
|
||||
/// None of these is "nobody is signed in". That is an ordinary answer. It comes back as
|
||||
/// [`crate::Shared::None`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// This process reads and writes nothing: `ARTCRAFT_SUITE_DIR` is set and empty, or the system
|
||||
/// has no per-user configuration folder.
|
||||
Isolated,
|
||||
Io(String),
|
||||
/// The accounts file is in a format this build does not know, or is not an accounts file.
|
||||
Malformed(String),
|
||||
/// The operating system's keychain refused.
|
||||
Keychain(String),
|
||||
/// No account on file has that handle.
|
||||
Unknown(String),
|
||||
/// A write named a generation the account has already moved past: another sign-in or removal
|
||||
/// landed first. See RFC-0025's "Cross-app lifecycle guarantees".
|
||||
StaleGeneration {
|
||||
id: String,
|
||||
expected: u32,
|
||||
current: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Error::Isolated => f.write_str("this process keeps no shared account"),
|
||||
Error::Io(why) | Error::Malformed(why) => f.write_str(why),
|
||||
Error::Keychain(why) => write!(f, "the keychain refused: {why}"),
|
||||
Error::Unknown(id) => write!(f, "no account {id} is signed in"),
|
||||
Error::StaleGeneration { id, expected, current } => {
|
||||
write!(
|
||||
f,
|
||||
"account {id} moved from generation {expected} to {current}; this write was made against a generation that is no longer current"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
@@ -0,0 +1,277 @@
|
||||
//! The Craft App Suite's shared account store: the suite's keychain.
|
||||
//!
|
||||
//! Somebody signs in once and every Craft App acts as them. Before this, each application kept its
|
||||
//! own session file. Taken across the suite that meant a sign-in per application, a copy of a
|
||||
//! bearer token on disk per application, and a separate place to revoke per application.
|
||||
//!
|
||||
//! The store has two halves, kept deliberately apart:
|
||||
//!
|
||||
//! * The list of accounts is a small JSON file in one suite-level folder ([`paths`]). It names who
|
||||
//! has signed in, at which deployment, and which account is current. It holds no credential.
|
||||
//! * The token is in the operating system's keychain ([`store`]). Windows Credential Manager, the
|
||||
//! macOS Keychain, or the Secret Service.
|
||||
//!
|
||||
//! Nothing here is mandatory. An application asks [`Store::shared`] what the suite has to offer and
|
||||
//! gets one of three answers: somebody is signed in, nobody is signed in, or there is an account on
|
||||
//! file whose token could not be read. The second and third leave the application exactly as it was
|
||||
//! before this crate existed, offering its own sign-in. A machine with no keychain, a locked
|
||||
//! keychain, a missing folder and an empty suite all land on "nobody is signed in". None of them is
|
||||
//! an error that stops an application starting.
|
||||
//!
|
||||
//! [`Store::discard`] clears the keychain entry and then the row, for a session this machine
|
||||
//! should stop holding. [`Store::forget`] clears only the keychain entry, leaving the row for a
|
||||
//! user interface to still show (and, say, offer "sign in again" on). Neither talks to the
|
||||
//! deployment: ending the session there, so every machine the person left one on drops it too, is
|
||||
//! a distinct operation that belongs to the provider adapter that knows how to ask the deployment
|
||||
//! for that, per RFC-0025's "Cross-app lifecycle guarantees" (point 4: forgetting is local,
|
||||
//! revoking is at the provider). A consumer that wants both calls its own revoke, then
|
||||
//! [`Store::discard`].
|
||||
//!
|
||||
//! An application upgrading from its own session file calls [`migrate::adopt`] once at startup.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # fn main() -> Result<(), craft_suite_account::Error> {
|
||||
//! use craft_suite_account::{Shared, Store};
|
||||
//!
|
||||
//! let store = Store::open();
|
||||
//! match store.shared() {
|
||||
//! Shared::Session { account, token } => {
|
||||
//! // Use `token` as a bearer against `account.service`.
|
||||
//! let _ = (account, token);
|
||||
//! }
|
||||
//! // Offer this application's own sign-in, exactly as before.
|
||||
//! Shared::None => {}
|
||||
//! Shared::Unreadable { why, .. } => eprintln!("the shared sign-in could not be read: {why}"),
|
||||
//! }
|
||||
//! # Ok(()) }
|
||||
//! ```
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod accounts;
|
||||
mod error;
|
||||
pub mod migrate;
|
||||
pub mod paths;
|
||||
mod secret;
|
||||
pub mod store;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub use accounts::{Account, Accounts};
|
||||
pub use error::Error;
|
||||
pub use migrate::Adopted;
|
||||
pub use secret::Secret;
|
||||
pub use store::{KEYCHAIN_SERVICE, Keychain, Memory, TokenStore};
|
||||
|
||||
/// What the suite store has to offer.
|
||||
#[derive(Debug)]
|
||||
pub enum Shared {
|
||||
/// Somebody is signed in and the token came back.
|
||||
Session { account: Account, token: Secret },
|
||||
/// Nobody is signed in here. Offer a sign-in.
|
||||
None,
|
||||
/// An account is on file and its token could not be read: a locked keychain, a keychain this
|
||||
/// process may not reach, or an entry somebody deleted by hand.
|
||||
///
|
||||
/// Offer a sign-in. Say why the shared one did not come through. Quietly showing a signed-out
|
||||
/// window would leave somebody wondering where their account went.
|
||||
Unreadable { account: Account, why: String },
|
||||
}
|
||||
|
||||
/// A sign-in about to be recorded.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct NewAccount {
|
||||
/// The deployment's base URL.
|
||||
pub service: String,
|
||||
/// The deployment's identifier for the account: the OIDC subject.
|
||||
pub user: String,
|
||||
pub display: String,
|
||||
pub email: Option<String>,
|
||||
/// Whether cloud storage is linked. Recorded for a user interface; the deployment is the
|
||||
/// authority and is asked again on each start.
|
||||
pub linked: bool,
|
||||
}
|
||||
|
||||
/// The suite's account store.
|
||||
pub struct Store<S: TokenStore = Keychain> {
|
||||
/// The suite folder. `None` when this process keeps nothing.
|
||||
dir: Option<PathBuf>,
|
||||
tokens: S,
|
||||
}
|
||||
|
||||
impl Store<Keychain> {
|
||||
/// The real store: the suite folder for this platform and the platform's keychain.
|
||||
pub fn open() -> Store<Keychain> {
|
||||
Store::at(paths::resolve(&paths::Probe::default()).dir, Keychain)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TokenStore> Store<S> {
|
||||
/// A store over a given folder and token store. `None` keeps nothing.
|
||||
pub fn at(dir: Option<PathBuf>, tokens: S) -> Store<S> {
|
||||
Store { dir, tokens }
|
||||
}
|
||||
|
||||
/// The suite folder, when there is one.
|
||||
pub fn dir(&self) -> Option<&Path> {
|
||||
self.dir.as_deref()
|
||||
}
|
||||
|
||||
/// The accounts file, when there is one.
|
||||
pub fn path(&self) -> Option<PathBuf> {
|
||||
self.dir.as_deref().map(paths::file)
|
||||
}
|
||||
|
||||
/// Whether this store can hold a session. It needs a folder. The machine needs a keychain.
|
||||
///
|
||||
/// Checked before a sign-in and before a migration. Neither then half-completes.
|
||||
pub fn usable(&self) -> Result<(), Error> {
|
||||
let _ = self.dir.as_deref().ok_or(Error::Isolated)?;
|
||||
self.tokens.available().map_err(Error::Keychain)
|
||||
}
|
||||
|
||||
/// Whether a readable token is stored for this account handle.
|
||||
pub fn has_token(&self, id: &str) -> Result<bool, Error> {
|
||||
Ok(self.tokens.get(id).map_err(Error::Keychain)?.is_some())
|
||||
}
|
||||
|
||||
/// Every account on file. An isolated store has none.
|
||||
pub fn accounts(&self) -> Result<Accounts, Error> {
|
||||
match self.path() {
|
||||
Some(path) => accounts::read(&path),
|
||||
None => Ok(Accounts::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the suite has to offer. Never fails: absence of every kind is [`Shared::None`].
|
||||
///
|
||||
/// This is the call an application makes at startup. The answer decides whether it offers its
|
||||
/// own sign-in.
|
||||
pub fn shared(&self) -> Shared {
|
||||
let list = match self.accounts() {
|
||||
Ok(list) => list,
|
||||
Err(Error::Isolated) => return Shared::None,
|
||||
Err(e) => {
|
||||
log::warn!("the suite account list could not be read: {e}");
|
||||
return Shared::None;
|
||||
}
|
||||
};
|
||||
let Some(account) = list.current().cloned() else { return Shared::None };
|
||||
match self.tokens.get(&account.id) {
|
||||
Ok(Some(token)) => Shared::Session { account, token },
|
||||
// On file with no entry behind it. Somebody deleted the entry, or a sign-out got half
|
||||
// way. Either way nobody is signed in. The next sign-in tidies the row up.
|
||||
Ok(None) => Shared::None,
|
||||
Err(why) => Shared::Unreadable { account, why },
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a sign-in: the token into the keychain, then the account onto the list.
|
||||
///
|
||||
/// The token goes first. A failed list write then leaves the previous state intact and one
|
||||
/// unreferenced keychain entry. The next sign-in for the same account overwrites that entry,
|
||||
/// because the handle is a digest of the deployment and the subject. Nothing fresh is minted
|
||||
/// each time. The other order would leave an account on the list with no token behind it.
|
||||
pub fn sign_in(&self, new: &NewAccount, token: &Secret, now: i64) -> Result<Account, Error> {
|
||||
self.usable()?;
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
let service = accounts::normalise(&new.service);
|
||||
let id = accounts::handle(&service, &new.user);
|
||||
self.tokens.put(&id, token).map_err(Error::Keychain)?;
|
||||
let mut list = accounts::read(&path)?;
|
||||
let existing = list.get(&id);
|
||||
let added = existing.map_or(now, |a| a.added);
|
||||
// A fresh generation, same as a removal would leave behind: a write made against the
|
||||
// generation this account held a moment ago is now stale. See [`Account::generation`].
|
||||
let generation = existing.map_or(0, |a| a.generation + 1);
|
||||
let account = Account {
|
||||
id,
|
||||
service,
|
||||
user: new.user.clone(),
|
||||
display: new.display.clone(),
|
||||
email: new.email.clone(),
|
||||
added,
|
||||
last_used: now,
|
||||
generation,
|
||||
};
|
||||
list.put(account.clone());
|
||||
accounts::write(&path, &list)?;
|
||||
Ok(account)
|
||||
}
|
||||
|
||||
/// Writes a refreshed token back, honouring the account's generation.
|
||||
///
|
||||
/// `expected_generation` is the generation the caller last read the account at. A sign-in or a
|
||||
/// removal bumps the generation (see [`Account::generation`]); a refresh that was already in
|
||||
/// flight when one of those landed is then refused here rather than silently overwriting
|
||||
/// something newer, per RFC-0025's "Cross-app lifecycle guarantees" (point 2: removal wins over
|
||||
/// refresh). An account that is gone outright, because it was removed, is [`Error::Unknown`]
|
||||
/// rather than [`Error::StaleGeneration`]; see the TODO on [`Accounts::remove`] for why that
|
||||
/// distinction is not sharper yet.
|
||||
pub fn update_token(&self, id: &str, expected_generation: u32, token: &Secret, now: i64) -> Result<Account, Error> {
|
||||
self.usable()?;
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
let mut list = accounts::read(&path)?;
|
||||
let current = list.get(id).ok_or_else(|| Error::Unknown(id.to_owned()))?.generation;
|
||||
if current != expected_generation {
|
||||
return Err(Error::StaleGeneration { id: id.to_owned(), expected: expected_generation, current });
|
||||
}
|
||||
self.tokens.put(id, token).map_err(Error::Keychain)?;
|
||||
let account = list.accounts.iter_mut().find(|a| a.id == id).ok_or_else(|| Error::Unknown(id.to_owned()))?;
|
||||
account.generation += 1;
|
||||
account.last_used = now;
|
||||
let updated = account.clone();
|
||||
accounts::write(&path, &list)?;
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
/// Makes an account the current one.
|
||||
pub fn set_active(&self, id: &str) -> Result<(), Error> {
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
let mut list = accounts::read(&path)?;
|
||||
if list.get(id).is_none() {
|
||||
return Err(Error::Unknown(id.to_owned()));
|
||||
}
|
||||
list.active = Some(id.to_owned());
|
||||
accounts::write(&path, &list)
|
||||
}
|
||||
|
||||
/// Records that an application used the account, for a list that can show the most recent one.
|
||||
pub fn touch(&self, id: &str, now: i64) -> Result<(), Error> {
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
let mut list = accounts::read(&path)?;
|
||||
let Some(account) = list.accounts.iter_mut().find(|a| a.id == id) else {
|
||||
return Err(Error::Unknown(id.to_owned()));
|
||||
};
|
||||
account.last_used = now;
|
||||
accounts::write(&path, &list)
|
||||
}
|
||||
|
||||
/// Clears an account here: the keychain entry, then the row.
|
||||
///
|
||||
/// This is the local half of a sign-out only. Ending the session at the deployment, so every
|
||||
/// machine the person left one on drops it too, is a distinct call on the provider adapter; a
|
||||
/// consumer that wants both makes that call first, while the token can still be read, and then
|
||||
/// calls this. See the module documentation and RFC-0025's "Cross-app lifecycle guarantees".
|
||||
pub fn discard(&self, id: &str) -> Result<(), Error> {
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
self.forget(id)?;
|
||||
let mut list = accounts::read(&path)?;
|
||||
list.remove(id);
|
||||
accounts::write(&path, &list)
|
||||
}
|
||||
|
||||
/// Clears the keychain entry for an account, leaving the list alone.
|
||||
pub fn forget(&self, id: &str) -> Result<(), Error> {
|
||||
self.tokens.remove(id).map_err(Error::Keychain)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TokenStore + std::fmt::Debug> std::fmt::Debug for Store<S> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Store").field("dir", &self.dir).field("tokens", &self.tokens).finish()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Taking over a per-application session file.
|
||||
//!
|
||||
//! An application that signed in before the suite store existed wrote its own session beside its
|
||||
//! own settings, naming the file however it liked. GridCraft's was
|
||||
//! `%APPDATA%\GridCraft\legacy-session.json`. Upgrading must not sign anybody out. The application
|
||||
//! therefore hands that session to the suite store once and deletes the file. The token then lives
|
||||
//! in the keychain and the whole suite can use it.
|
||||
//!
|
||||
//! The application does this, never the launcher. The file belongs to the application. Nothing
|
||||
//! should reach into another application's folder to delete a file.
|
||||
//!
|
||||
//! The file is only deleted once the suite store holds the session. Where the suite store can keep
|
||||
//! nothing (no keychain on this machine, or this process is isolated) the file stays exactly where
|
||||
//! it is. Removing it would sign the user out. That is the one thing migration must not do.
|
||||
//!
|
||||
//! The earliest of these files held one key: `{"token": "..."}`. It names no deployment and no
|
||||
//! subject. There is nothing to key an account on. Such a file is left exactly where it is too. A
|
||||
//! made-up handle would file the token under something nothing ever looks up again. That reads as
|
||||
//! a silent sign-out. An application that rewrites the file with the deployment and the subject is
|
||||
//! adopted on the next startup. Adopting one launch late costs nothing.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::accounts::{self, Account};
|
||||
use crate::error::Error;
|
||||
use crate::secret::Secret;
|
||||
use crate::store::TokenStore;
|
||||
use crate::{NewAccount, Store};
|
||||
|
||||
/// What a legacy session file said.
|
||||
#[derive(Debug)]
|
||||
pub struct Legacy {
|
||||
/// The deployment's base URL, with any trailing slash trimmed. Empty where the file predates
|
||||
/// the application recording it.
|
||||
pub service: String,
|
||||
/// The deployment's own identifier for the account: the OIDC subject. Empty where the file
|
||||
/// predates the application recording it.
|
||||
pub user: String,
|
||||
pub display: String,
|
||||
pub email: Option<String>,
|
||||
pub token: Secret,
|
||||
}
|
||||
|
||||
impl Legacy {
|
||||
/// What the file does not say yet, when it cannot be keyed to an account.
|
||||
///
|
||||
/// The account handle is a digest of the deployment and the subject. Both are therefore
|
||||
/// needed. A session written before the application recorded them carries a token alone.
|
||||
pub fn incomplete(&self) -> Option<&'static str> {
|
||||
if self.service.is_empty() {
|
||||
return Some("which deployment it belongs to");
|
||||
}
|
||||
if self.user.is_empty() {
|
||||
return Some("whose account it is");
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Adopted {
|
||||
/// There was no file. There is nothing to take over.
|
||||
Nothing,
|
||||
/// The session is in the suite store now. The file is gone.
|
||||
Taken(Account),
|
||||
/// The file was left exactly where it is. The application goes on reading it. `why` says
|
||||
/// which case it was: the suite store can keep nothing here, or the file does not yet say
|
||||
/// enough to key an account on.
|
||||
Kept { why: String },
|
||||
}
|
||||
|
||||
/// The shape on disk.
|
||||
///
|
||||
/// What an application writes today is `token`, `service`, `subject` and `display`. The file
|
||||
/// predates this crate. The aliases therefore cover the other plausible spellings.
|
||||
///
|
||||
/// The token is the only key that has to be there: a file without one carries no session at all.
|
||||
/// Everything else defaults. That is what lets the earliest `{"token": "..."}` file still parse.
|
||||
/// [`adopt`] then leaves such a file alone. Keying an account on nothing is the alternative.
|
||||
#[derive(Deserialize)]
|
||||
struct Stored {
|
||||
#[serde(alias = "session", alias = "session_token", alias = "bearer", alias = "access_token")]
|
||||
token: String,
|
||||
#[serde(default, alias = "base", alias = "base_url", alias = "url", alias = "service_url")]
|
||||
service: String,
|
||||
#[serde(default, alias = "id", alias = "sub", alias = "subject", alias = "user_id")]
|
||||
user: String,
|
||||
#[serde(default, alias = "name", alias = "display_name")]
|
||||
display: String,
|
||||
#[serde(default)]
|
||||
email: Option<String>,
|
||||
}
|
||||
|
||||
/// The largest session file that will be read.
|
||||
const MAX_BYTES: u64 = 64 << 10;
|
||||
|
||||
/// Reads a legacy session file. A missing file is `Ok(None)`.
|
||||
pub fn read(path: &Path) -> Result<Option<Legacy>, Error> {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) if meta.len() > MAX_BYTES => {
|
||||
return Err(Error::Malformed(format!("{} is {} bytes, too large to be a session", path.display(), meta.len())));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(Error::Io(format!("couldn't read {} ({e})", path.display()))),
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| Error::Io(format!("couldn't read {} ({e})", path.display())))?;
|
||||
let stored: Stored = serde_json::from_slice(&bytes).map_err(|e| Error::Malformed(format!("{} didn't parse ({e})", path.display())))?;
|
||||
if stored.token.trim().is_empty() {
|
||||
return Err(Error::Malformed(format!("{} carries no session", path.display())));
|
||||
}
|
||||
let service = accounts::normalise(&stored.service);
|
||||
// The subject is never stood in for. A handle built on anything else would file the token
|
||||
// where nothing looks for it. See [`Legacy::incomplete`].
|
||||
let user = stored.user.trim().to_owned();
|
||||
let display = if stored.display.trim().is_empty() { user.clone() } else { stored.display };
|
||||
Ok(Some(Legacy { service, user, display, email: stored.email, token: Secret::new(stored.token.trim()) }))
|
||||
}
|
||||
|
||||
/// Hands a legacy session to the suite store and removes the file.
|
||||
///
|
||||
/// Call this once at startup, before asking the suite store who is signed in. Safe to call when
|
||||
/// there is no file. Safe to call again after it has run.
|
||||
pub fn adopt<S: TokenStore>(store: &Store<S>, path: &Path, now: i64) -> Result<Adopted, Error> {
|
||||
let Some(legacy) = read(path)? else { return Ok(Adopted::Nothing) };
|
||||
if let Some(unsaid) = legacy.incomplete() {
|
||||
return Ok(Adopted::Kept { why: format!("{} does not say {unsaid} yet", path.display()) });
|
||||
}
|
||||
if let Err(why) = store.usable() {
|
||||
return Ok(Adopted::Kept { why: why.to_string() });
|
||||
}
|
||||
let service = accounts::normalise(&legacy.service);
|
||||
let id = accounts::handle(&service, &legacy.user);
|
||||
let existing = if store.has_token(&id)? { store.accounts()?.get(&id).cloned() } else { None };
|
||||
if let Some(account) = existing {
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(Error::Io(format!("the suite already holds this session. {} is still there ({e})", path.display()))),
|
||||
}
|
||||
return Ok(Adopted::Taken(account));
|
||||
}
|
||||
let new = NewAccount { service: legacy.service, user: legacy.user, display: legacy.display, email: legacy.email, linked: false };
|
||||
let account = store.sign_in(&new, &legacy.token, now)?;
|
||||
// Only now, with the session held somewhere better, does the file go.
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(Error::Io(format!("the session moved to the keychain. {} is still there ({e})", path.display()))),
|
||||
}
|
||||
Ok(Adopted::Taken(account))
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Where the suite keeps its list of accounts.
|
||||
//!
|
||||
//! One folder for the whole Craft App Suite. It sits beside the per-application folders. It is not
|
||||
//! a child of any of them.
|
||||
//!
|
||||
//! `craft-settings` gives each application `<platform config dir>/<app id>`. That is the right home
|
||||
//! for that application's own preferences. An account is not one of those. The same person signs in
|
||||
//! once and every Craft App acts as them. The record therefore belongs to the suite. An account
|
||||
//! placed under one application's folder would make every other application read a folder it does
|
||||
//! not own.
|
||||
//! Removing that application would then sign everybody out. The launcher's own folder fails for the
|
||||
//! same reason. An application must not have to know the launcher exists.
|
||||
//!
|
||||
//! So: `<platform config dir>/ArtCraft` on Windows and macOS. `<platform config dir>/artcraft` on
|
||||
//! Linux and the BSDs. The launcher already spells its own folder that way per platform. Written
|
||||
//! out, those are `%APPDATA%\ArtCraft`, `~/Library/Application Support/ArtCraft` and
|
||||
//! `~/.config/artcraft`.
|
||||
//!
|
||||
//! It is the configuration folder. The record then follows a Windows profile the way a user would
|
||||
//! expect. The per-application session file this replaces lived in `%APPDATA%` too. The folder
|
||||
//! holds no secret. The token is in the keychain.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The suite folder's name, spelled the way the launcher spells its own per platform.
|
||||
pub const DIR: &str = if cfg!(any(target_os = "macos", target_os = "windows")) { "ArtCraft" } else { "artcraft" };
|
||||
|
||||
/// The file inside it.
|
||||
pub const FILE: &str = "accounts.json";
|
||||
|
||||
/// Points the suite folder somewhere else. Set and empty means read and write nothing.
|
||||
pub const ENV_VAR: &str = "ARTCRAFT_SUITE_DIR";
|
||||
|
||||
/// File names beside the executable that switch portable mode on. The launcher's Windows portable
|
||||
/// zip ships `portable.txt`. `portable` is `craft-settings`' own spelling.
|
||||
pub const PORTABLE_MARKERS: &[&str] = &["portable.txt", "portable"];
|
||||
|
||||
/// The folder a portable install keeps the suite's accounts in, beside the executable.
|
||||
pub const PORTABLE_DIR: &str = "ArtCraftSuite";
|
||||
|
||||
/// Which rule chose the folder.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Rule {
|
||||
/// [`ENV_VAR`] named it.
|
||||
EnvVar,
|
||||
/// [`ENV_VAR`] was set and empty. Nothing is read or written.
|
||||
Isolated,
|
||||
/// A portable marker beside the executable.
|
||||
Portable,
|
||||
/// The platform's configuration folder.
|
||||
Platform,
|
||||
/// This system has no per-user configuration folder. Nothing is read or written. A file in the
|
||||
/// current directory would be the wrong home for a record of who is signed in.
|
||||
Nowhere,
|
||||
}
|
||||
|
||||
/// A chosen folder and the rule behind it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Resolved {
|
||||
/// The suite folder. `None` for [`Rule::Isolated`] and [`Rule::Nowhere`].
|
||||
pub dir: Option<PathBuf>,
|
||||
pub rule: Rule,
|
||||
}
|
||||
|
||||
/// Reads an environment variable by name.
|
||||
pub type EnvReader = Box<dyn Fn(&str) -> Option<OsString>>;
|
||||
|
||||
/// What the rules look at. The default reads the real process. Tests supply their own.
|
||||
pub struct Probe {
|
||||
pub env: EnvReader,
|
||||
/// The folder holding the executable, if known.
|
||||
pub exe_dir: Option<PathBuf>,
|
||||
/// The platform configuration folder (`%APPDATA%`, `Application Support`, `~/.config`).
|
||||
pub platform_config_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for Probe {
|
||||
fn default() -> Probe {
|
||||
Probe {
|
||||
env: Box::new(|name| std::env::var_os(name)),
|
||||
exe_dir: std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf)),
|
||||
platform_config_dir: dirs::config_dir(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Probe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Probe").field("exe_dir", &self.exe_dir).field("platform_config_dir", &self.platform_config_dir).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the rules, first match winning.
|
||||
pub fn resolve(probe: &Probe) -> Resolved {
|
||||
if let Some(value) = (probe.env)(ENV_VAR) {
|
||||
if value.is_empty() {
|
||||
return Resolved { dir: None, rule: Rule::Isolated };
|
||||
}
|
||||
return Resolved { dir: Some(PathBuf::from(value)), rule: Rule::EnvVar };
|
||||
}
|
||||
if let Some(dir) = probe.exe_dir.as_deref().and_then(portable_dir) {
|
||||
return Resolved { dir: Some(dir), rule: Rule::Portable };
|
||||
}
|
||||
match &probe.platform_config_dir {
|
||||
Some(base) => Resolved { dir: Some(base.join(DIR)), rule: Rule::Platform },
|
||||
None => Resolved { dir: None, rule: Rule::Nowhere },
|
||||
}
|
||||
}
|
||||
|
||||
/// The accounts file inside a suite folder.
|
||||
pub fn file(dir: &Path) -> PathBuf {
|
||||
dir.join(FILE)
|
||||
}
|
||||
|
||||
/// The folder a portable marker points at, when `exe_dir` has one.
|
||||
///
|
||||
/// On macOS the executable sits in `X.app/Contents/MacOS`. The marker is therefore looked for
|
||||
/// beside the `.app` bundle. Writing inside a signed bundle breaks its signature.
|
||||
fn portable_dir(exe_dir: &Path) -> Option<PathBuf> {
|
||||
let base = bundle_parent(exe_dir).unwrap_or(exe_dir);
|
||||
PORTABLE_MARKERS.iter().any(|m| base.join(m).is_file()).then(|| base.join(PORTABLE_DIR))
|
||||
}
|
||||
|
||||
fn bundle_parent(exe_dir: &Path) -> Option<&Path> {
|
||||
if !cfg!(target_os = "macos") || exe_dir.file_name()? != "MacOS" {
|
||||
return None;
|
||||
}
|
||||
let contents = exe_dir.parent()?;
|
||||
if contents.file_name()? != "Contents" {
|
||||
return None;
|
||||
}
|
||||
let bundle = contents.parent()?;
|
||||
if bundle.extension()? != "app" {
|
||||
return None;
|
||||
}
|
||||
bundle.parent()
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! A credential held in memory.
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// A bearer token, wrapped so it cannot be printed by accident.
|
||||
///
|
||||
/// There is no `Display` and no `Serialize`. [`Debug`] reports the length and nothing else. A token
|
||||
/// therefore never reaches a log line through a `{:?}` on some struct that happens to carry one.
|
||||
/// The bytes are overwritten when the value is dropped.
|
||||
///
|
||||
/// [`Secret::expose`] is the one way out. The only caller that needs it is the code building an
|
||||
/// `Authorization` header.
|
||||
#[derive(Clone)]
|
||||
pub struct Secret(Zeroizing<String>);
|
||||
|
||||
impl Secret {
|
||||
pub fn new(value: impl Into<String>) -> Secret {
|
||||
Secret(Zeroizing::new(value.into()))
|
||||
}
|
||||
|
||||
/// The bytes themselves. Send them. Never log them.
|
||||
pub fn expose(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// How many bytes the token is. A report names this and never the value.
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Secret {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Secret({} bytes)", self.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Secret {
|
||||
fn eq(&self, other: &Secret) -> bool {
|
||||
*self.0 == *other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Secret {}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! The token, in the operating system's own keychain.
|
||||
//!
|
||||
//! Windows Credential Manager, the macOS Keychain, or the Secret Service on Linux and the BSDs.
|
||||
//!
|
||||
//! A bearer token in a JSON file beside an application's settings is what this replaces. Such a
|
||||
//! file is readable by anything running as the user. It survives in backups. It leaves nothing for
|
||||
//! an administrator to revoke. A keychain entry is scoped to the one user. The platform encrypts it
|
||||
//! at rest. It can be deleted one entry at a time from the platform's own window.
|
||||
//!
|
||||
//! One service name covers the whole suite. Every entry the suite ever writes is therefore findable
|
||||
//! and removable in one place.
|
||||
//!
|
||||
//! ```text
|
||||
//! service ai.storyteller.artcraft.suite-account
|
||||
//! user the account handle (crate::accounts::handle: a digest of the deployment and the subject)
|
||||
//! secret a bearer token for that account, minted by whatever deployment the handle names
|
||||
//! ```
|
||||
//!
|
||||
//! On Windows that is a generic credential whose target name is
|
||||
//! `<handle>.ai.storyteller.artcraft.suite-account`, with machine-local persistence. A bearer token
|
||||
//! minted for this machine therefore stays on it. On macOS it is a generic password in the user's
|
||||
//! login keychain. On Linux and the BSDs it is a Secret Service item in the user's default
|
||||
//! collection. That collection is locked with the login session.
|
||||
//!
|
||||
//! [`TokenStore`] is a trait so everything above it can be tested without a keychain. [`Memory`] is
|
||||
//! the stand-in, the way `craft-nextcloud` drives a canned transport.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::secret::Secret;
|
||||
|
||||
/// The keychain service name every Craft App uses. One namespace, one place to revoke.
|
||||
pub const KEYCHAIN_SERVICE: &str = "ai.storyteller.artcraft.suite-account";
|
||||
|
||||
/// Reading and writing one token per account handle.
|
||||
pub trait TokenStore {
|
||||
/// Whether this machine has a keychain this process can use.
|
||||
///
|
||||
/// A headless Linux box with no Secret Service answers `Err`. The suite then behaves as though
|
||||
/// nobody is signed in. No token goes to a file.
|
||||
fn available(&self) -> Result<(), String>;
|
||||
/// The token for `handle`, or `Ok(None)` when there is no entry.
|
||||
fn get(&self, handle: &str) -> Result<Option<Secret>, String>;
|
||||
fn put(&self, handle: &str, token: &Secret) -> Result<(), String>;
|
||||
/// Removes the entry. Already gone is success.
|
||||
fn remove(&self, handle: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// The platform's keychain.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Keychain;
|
||||
|
||||
impl Keychain {
|
||||
fn entry(handle: &str) -> Result<keyring_core::Entry, Error> {
|
||||
// Installs the platform store on the first call, once per process.
|
||||
if let Err(e) = keyring::Entry::store_status() {
|
||||
return Err(Error::Keychain(e.to_string()));
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// Local, where the store's own default is Enterprise. An Enterprise credential is part
|
||||
// of the roaming profile. A bearer token minted for this machine has no business
|
||||
// travelling to another one.
|
||||
let modifiers = std::collections::HashMap::from([("persistence", "Local")]);
|
||||
keyring_core::Entry::new_with_modifiers(KEYCHAIN_SERVICE, handle, &modifiers).map_err(|e| Error::Keychain(e.to_string()))
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
keyring_core::Entry::new(KEYCHAIN_SERVICE, handle).map_err(|e| Error::Keychain(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenStore for Keychain {
|
||||
fn available(&self) -> Result<(), String> {
|
||||
match keyring::Entry::store_status() {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&self, handle: &str) -> Result<Option<Secret>, String> {
|
||||
let entry = Keychain::entry(handle).map_err(|e| e.to_string())?;
|
||||
match entry.get_password() {
|
||||
Ok(token) => Ok(Some(Secret::new(token))),
|
||||
Err(keyring::Error::NoEntry) => Ok(None),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn put(&self, handle: &str, token: &Secret) -> Result<(), String> {
|
||||
let entry = Keychain::entry(handle).map_err(|e| e.to_string())?;
|
||||
entry.set_password(token.expose()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn remove(&self, handle: &str) -> Result<(), String> {
|
||||
let entry = Keychain::entry(handle).map_err(|e| e.to_string())?;
|
||||
match entry.delete_credential() {
|
||||
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A keychain stand-in that keeps entries in memory.
|
||||
///
|
||||
/// For tests. It also covers the answers a real keychain gives that are awkward to arrange: an
|
||||
/// entry is there, there is no keychain on this machine, the keychain is there and locked.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Memory {
|
||||
entries: Arc<Mutex<BTreeMap<String, Secret>>>,
|
||||
/// Why there is no usable keychain here, when there is not one.
|
||||
missing: Option<String>,
|
||||
/// Why every read and write fails, for a keychain that exists and refuses.
|
||||
refusing: Option<String>,
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
pub fn new() -> Memory {
|
||||
Memory::default()
|
||||
}
|
||||
|
||||
/// A machine with no keychain at all.
|
||||
pub fn missing(why: impl Into<String>) -> Memory {
|
||||
Memory { missing: Some(why.into()), ..Memory::default() }
|
||||
}
|
||||
|
||||
/// A keychain that is there and refuses, the way a locked Secret Service does.
|
||||
pub fn refusing(why: impl Into<String>) -> Memory {
|
||||
Memory { refusing: Some(why.into()), ..Memory::default() }
|
||||
}
|
||||
|
||||
/// How many entries are held. Tests use it to show a sign-out removed one.
|
||||
pub fn count(&self) -> usize {
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner).len()
|
||||
}
|
||||
|
||||
pub fn has(&self, handle: &str) -> bool {
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner).contains_key(handle)
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenStore for Memory {
|
||||
fn available(&self) -> Result<(), String> {
|
||||
match &self.missing {
|
||||
Some(why) => Err(why.clone()),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&self, handle: &str) -> Result<Option<Secret>, String> {
|
||||
self.available()?;
|
||||
if let Some(why) = &self.refusing {
|
||||
return Err(why.clone());
|
||||
}
|
||||
Ok(self.entries.lock().unwrap_or_else(PoisonError::into_inner).get(handle).cloned())
|
||||
}
|
||||
|
||||
fn put(&self, handle: &str, token: &Secret) -> Result<(), String> {
|
||||
self.available()?;
|
||||
if let Some(why) = &self.refusing {
|
||||
return Err(why.clone());
|
||||
}
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner).insert(handle.to_owned(), token.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove(&self, handle: &str) -> Result<(), String> {
|
||||
self.available()?;
|
||||
if let Some(why) = &self.refusing {
|
||||
return Err(why.clone());
|
||||
}
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner).remove(handle);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
//! Tests for the store, the migration and the fallback when nobody is signed in.
|
||||
//!
|
||||
//! A keychain is awkward to drive from a test. Everything above it therefore runs against
|
||||
//! [`Memory`](crate::store::Memory).
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::accounts::{self, Account};
|
||||
use crate::paths::{self, Probe, Rule};
|
||||
use crate::store::{Memory, TokenStore};
|
||||
use crate::{Adopted, Error, NewAccount, Secret, Shared, Store};
|
||||
|
||||
const SERVICE: &str = "https://craft.example.com";
|
||||
const USER: &str = "e9b1c0e4-0000-4000-8000-000000000001";
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
const NOW: i64 = 1_760_000_000;
|
||||
|
||||
fn probe(env: &[(&str, &str)], exe_dir: Option<&str>, config: Option<&str>) -> Probe {
|
||||
let env: Vec<(String, String)> = env.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
Probe {
|
||||
env: Box::new(move |name| env.iter().find(|(k, _)| k == name).map(|(_, v)| OsString::from(v))),
|
||||
exe_dir: exe_dir.map(PathBuf::from),
|
||||
platform_config_dir: config.map(PathBuf::from),
|
||||
}
|
||||
}
|
||||
|
||||
fn new_account() -> NewAccount {
|
||||
NewAccount { service: SERVICE.to_owned(), user: USER.to_owned(), display: "Ada Lovelace".to_owned(), email: None, linked: true }
|
||||
}
|
||||
|
||||
// ---- where the store lives -------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_variable_names_the_folder() {
|
||||
let r = paths::resolve(&probe(&[(paths::ENV_VAR, "/somewhere/else")], None, Some("/home/a/.config")));
|
||||
assert_eq!(r.rule, Rule::EnvVar);
|
||||
assert_eq!(r.dir.as_deref(), Some(Path::new("/somewhere/else")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_variable_keeps_nothing() {
|
||||
let r = paths::resolve(&probe(&[(paths::ENV_VAR, "")], None, Some("/home/a/.config")));
|
||||
assert_eq!(r.rule, Rule::Isolated);
|
||||
assert_eq!(r.dir, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_platform_folder_is_the_default() {
|
||||
let r = paths::resolve(&probe(&[], None, Some("/home/a/.config")));
|
||||
assert_eq!(r.rule, Rule::Platform);
|
||||
assert_eq!(r.dir.as_deref(), Some(Path::new("/home/a/.config").join(paths::DIR).as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_portable_marker_wins_over_the_platform_folder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("portable.txt"), b"").unwrap();
|
||||
let exe_dir = dir.path().display().to_string();
|
||||
let r = paths::resolve(&probe(&[], Some(&exe_dir), Some("/home/a/.config")));
|
||||
assert_eq!(r.rule, Rule::Portable);
|
||||
assert_eq!(r.dir.as_deref(), Some(dir.path().join(paths::PORTABLE_DIR).as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_platform_folder_keeps_nothing() {
|
||||
let r = paths::resolve(&probe(&[], None, None));
|
||||
assert_eq!(r.rule, Rule::Nowhere);
|
||||
assert_eq!(r.dir, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handle_is_stable_and_separates_accounts() {
|
||||
let a = accounts::handle(SERVICE, USER);
|
||||
assert_eq!(a, accounts::handle(SERVICE, USER), "the same account twice is the same entry");
|
||||
// A trailing slash is the same deployment typed differently.
|
||||
assert_eq!(a, accounts::handle("https://craft.example.com/", USER));
|
||||
assert_ne!(a, accounts::handle("https://other.example.com", USER), "another deployment is another account");
|
||||
assert_ne!(a, accounts::handle(SERVICE, "somebody-else"), "another person is another account");
|
||||
assert_eq!(a.len(), 24);
|
||||
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
|
||||
}
|
||||
|
||||
// ---- signing in and out ----------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_sign_in_can_be_read_back_by_the_next_application() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
// A second application, its own Store over the same folder and keychain.
|
||||
let other = Store::at(Some(dir.path().to_path_buf()), keychain);
|
||||
match other.shared() {
|
||||
Shared::Session { account: found, token } => {
|
||||
assert_eq!(found.id, account.id);
|
||||
assert_eq!(found.service, SERVICE);
|
||||
assert_eq!(found.display, "Ada Lovelace");
|
||||
assert_eq!(token, Secret::new(TOKEN));
|
||||
}
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_accounts_file_never_holds_the_token() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
let on_disk = std::fs::read_to_string(store.path().unwrap()).unwrap();
|
||||
assert!(!on_disk.contains(TOKEN), "the token reached the accounts file");
|
||||
assert!(on_disk.contains(SERVICE), "the file should still name the deployment");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_in_again_replaces_the_entry_rather_than_adding_one() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let first = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
let second = store.sign_in(&new_account(), &Secret::new("a-newer-token"), NOW + 60).unwrap();
|
||||
assert_eq!(first.id, second.id);
|
||||
assert_eq!(first.added, second.added, "the first sign-in's date is kept");
|
||||
assert_eq!(keychain.count(), 1);
|
||||
assert_eq!(store.accounts().unwrap().accounts.len(), 1);
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new("a-newer-token")),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_deployments_are_two_accounts() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
let elsewhere = NewAccount { service: "https://other.example.com".to_owned(), ..new_account() };
|
||||
let second = store.sign_in(&elsewhere, &Secret::new("another-token"), NOW).unwrap();
|
||||
assert_eq!(keychain.count(), 2);
|
||||
let list = store.accounts().unwrap();
|
||||
assert_eq!(list.accounts.len(), 2);
|
||||
assert_eq!(list.active.as_deref(), Some(second.id.as_str()), "the newest sign-in becomes current");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discarding_an_account_clears_both_the_entry_and_the_row() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
store.discard(&account.id).unwrap();
|
||||
assert!(!keychain.has(&account.id), "the keychain entry should be gone");
|
||||
assert!(store.accounts().unwrap().accounts.is_empty());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forgetting_an_account_clears_only_the_entry_and_leaves_the_row() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
store.forget(&account.id).unwrap();
|
||||
assert!(!keychain.has(&account.id), "the keychain entry should be gone");
|
||||
assert_eq!(store.accounts().unwrap().accounts.len(), 1, "forgetting leaves the row; discard removes it too");
|
||||
assert!(matches!(store.shared(), Shared::None), "no readable token behind the row still reads as nobody signed in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discarding_an_unknown_account_is_a_quiet_no_op() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
store.discard("nobody").unwrap();
|
||||
}
|
||||
|
||||
// ---- the generation guards a stale write -----------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_write_against_a_stale_generation_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let first = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
assert_eq!(first.generation, 0);
|
||||
|
||||
// Somebody else signs the same account in again, elsewhere, before the refresh below lands.
|
||||
let second = store.sign_in(&new_account(), &Secret::new("rotated-elsewhere"), NOW + 30).unwrap();
|
||||
assert_eq!(second.id, first.id);
|
||||
assert_eq!(second.generation, 1);
|
||||
|
||||
// A refresh that read the account before that second sign-in still carries generation 0.
|
||||
let stale = store.update_token(&first.id, first.generation, &Secret::new("late-refresh"), NOW + 60);
|
||||
assert_eq!(stale.unwrap_err(), Error::StaleGeneration { id: first.id.clone(), expected: 0, current: 1 });
|
||||
|
||||
// The write never landed: the token on file is still the one from the second sign-in.
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new("rotated-elsewhere")),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_against_the_current_generation_succeeds_and_advances_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
let updated = store.update_token(&account.id, account.generation, &Secret::new("refreshed-token"), NOW + 30).unwrap();
|
||||
assert_eq!(updated.generation, account.generation + 1);
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new("refreshed-token")),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_against_an_unknown_account_says_so_rather_than_claiming_a_stale_generation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert_eq!(store.update_token("nobody", 0, &Secret::new(TOKEN), NOW).unwrap_err(), Error::Unknown("nobody".to_owned()));
|
||||
}
|
||||
|
||||
// ---- nobody is signed in ---------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_empty_suite_offers_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
assert!(store.accounts().unwrap().accounts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_isolated_store_offers_nothing_and_signs_nobody_in() {
|
||||
let store: Store<Memory> = Store::at(None, Memory::new());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
assert_eq!(store.usable().unwrap_err(), Error::Isolated);
|
||||
assert_eq!(store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap_err(), Error::Isolated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_machine_with_no_keychain_signs_nobody_in() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::missing("no Secret Service on this machine"));
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
match store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap_err() {
|
||||
Error::Keychain(why) => assert!(why.contains("no Secret Service")),
|
||||
other => panic!("expected a keychain failure, got {other:?}"),
|
||||
}
|
||||
assert!(!store.path().unwrap().exists(), "a refused sign-in should write no file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_keychain_says_so_rather_than_pretending_nobody_signed_in() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// Sign in against a working keychain, then read the same folder through a locked one.
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
let locked = Store::at(Some(dir.path().to_path_buf()), Memory::refusing("the keychain is locked"));
|
||||
match locked.shared() {
|
||||
Shared::Unreadable { account: found, why } => {
|
||||
assert_eq!(found.id, account.id);
|
||||
assert!(why.contains("locked"));
|
||||
}
|
||||
other => panic!("expected an unreadable session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_whose_entry_is_gone_reads_as_nobody_signed_in() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
// Somebody deleted the credential from the platform's own window.
|
||||
keychain.remove(&account.id).unwrap();
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_active_account_that_is_no_longer_listed_reads_as_nobody_signed_in() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let list = accounts::Accounts { format: accounts::FORMAT, accounts: Vec::new(), active: Some("vanished".to_owned()) };
|
||||
accounts::write(&path, &list).unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_from_a_later_format_is_refused_rather_than_misread() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
std::fs::write(&path, br#"{"format":99,"accounts":[],"active":null}"#).unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert!(matches!(store.accounts(), Err(Error::Malformed(_))));
|
||||
// An application still starts: the shared answer is that nobody is signed in.
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_json_does_not_stop_an_application_starting() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join(paths::FILE), b"this is not JSON").unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
// ---- taking over a per-application session file ----------------------------
|
||||
|
||||
/// What GridCraft's `legacy-session.json` is read as.
|
||||
fn legacy_file(dir: &Path) -> PathBuf {
|
||||
let path = dir.join("legacy-session.json");
|
||||
let body = format!(r#"{{"service":"{SERVICE}","token":"{TOKEN}","user":"{USER}","display":"Ada Lovelace"}}"#);
|
||||
std::fs::write(&path, body.as_bytes()).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_per_application_session_moves_into_the_suite_store_and_the_file_goes() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let path = legacy_file(app.path());
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Taken(account) => {
|
||||
assert_eq!(account.service, SERVICE);
|
||||
assert_eq!(account.user, USER);
|
||||
assert!(keychain.has(&account.id), "the token should be in the keychain");
|
||||
}
|
||||
other => panic!("expected the session to be taken over, got {other:?}"),
|
||||
}
|
||||
assert!(!path.exists(), "the session file should be gone");
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new(TOKEN)),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_repairs_an_orphan_keychain_token_with_the_legacy_file() {
|
||||
const LEGACY: &str = "legacy-session-token";
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let id = accounts::handle(SERVICE, USER);
|
||||
keychain.put(&id, &Secret::new("orphan-token")).unwrap();
|
||||
let path = legacy_file(app.path());
|
||||
std::fs::write(&path, format!(r#"{{"service":"{SERVICE}","token":"{LEGACY}","user":"{USER}","display":"Ada Lovelace"}}"#).as_bytes()).unwrap();
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Taken(account) => assert_eq!(account.id, id),
|
||||
other => panic!("expected the legacy session to be taken over, got {other:?}"),
|
||||
}
|
||||
assert!(!path.exists());
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new(LEGACY)),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_migration_finds_nothing_to_do() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), Memory::new());
|
||||
let path = legacy_file(app.path());
|
||||
crate::migrate::adopt(&store, &path, NOW).unwrap();
|
||||
assert_eq!(crate::migrate::adopt(&store, &path, NOW).unwrap(), Adopted::Nothing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_with_no_keychain_leaves_the_file_alone() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), Memory::missing("no keychain here"));
|
||||
let path = legacy_file(app.path());
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Kept { why } => assert!(why.contains("no keychain here")),
|
||||
other => panic!("expected the file to be kept, got {other:?}"),
|
||||
}
|
||||
assert!(path.exists(), "removing it would have signed the user out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_in_an_isolated_process_leaves_the_file_alone() {
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let store: Store<Memory> = Store::at(None, Memory::new());
|
||||
let path = legacy_file(app.path());
|
||||
assert!(matches!(crate::migrate::adopt(&store, &path, NOW).unwrap(), Adopted::Kept { .. }));
|
||||
assert!(path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_file_carrying_no_session_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("legacy-session.json");
|
||||
std::fs::write(&path, br#"{"service":"https://craft.example.com","token":" "}"#).unwrap();
|
||||
assert!(matches!(crate::migrate::read(&path), Err(Error::Malformed(_))));
|
||||
}
|
||||
|
||||
/// The four keys an application writes today, spelled exactly as it writes them.
|
||||
#[test]
|
||||
fn the_four_keys_an_application_writes_today_adopt_cleanly() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let path = app.path().join("legacy-session.json");
|
||||
let body = format!(r#"{{"token":"{TOKEN}","service":"{SERVICE}","subject":"{USER}","display":"Ada Lovelace"}}"#);
|
||||
std::fs::write(&path, body.as_bytes()).unwrap();
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Taken(account) => {
|
||||
assert_eq!(account.service, SERVICE);
|
||||
assert_eq!(account.user, USER, "`subject` is the subject the handle is keyed on");
|
||||
assert_eq!(account.display, "Ada Lovelace");
|
||||
assert_eq!(account.id, accounts::handle(SERVICE, USER));
|
||||
assert!(keychain.has(&account.id));
|
||||
}
|
||||
other => panic!("expected the session to be taken over, got {other:?}"),
|
||||
}
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
/// What is on every machine that signed in before the application recorded anything else.
|
||||
#[test]
|
||||
fn a_token_only_session_file_is_left_alone_until_the_application_records_more() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let path = app.path().join("legacy-session.json");
|
||||
std::fs::write(&path, format!(r#"{{"token":"{TOKEN}"}}"#).as_bytes()).unwrap();
|
||||
|
||||
// It parses, and it says nothing to key an account on.
|
||||
let legacy = crate::migrate::read(&path).unwrap().unwrap();
|
||||
assert_eq!(legacy.token, Secret::new(TOKEN));
|
||||
assert_eq!(legacy.service, "");
|
||||
assert_eq!(legacy.user, "", "the subject is never stood in for");
|
||||
assert_eq!(legacy.incomplete(), Some("which deployment it belongs to"));
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Kept { why } => assert!(why.contains("does not say"), "{why}"),
|
||||
other => panic!("expected the file to be kept, got {other:?}"),
|
||||
}
|
||||
assert!(path.exists(), "removing it would have signed the user out");
|
||||
assert_eq!(keychain.count(), 0, "nothing should be filed under a made-up handle");
|
||||
assert!(store.accounts().unwrap().accounts.is_empty());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
|
||||
// The application rewrites the file once it knows the rest. The next startup adopts it.
|
||||
let body = format!(r#"{{"token":"{TOKEN}","service":"{SERVICE}","subject":"{USER}","display":"Ada Lovelace"}}"#);
|
||||
std::fs::write(&path, body.as_bytes()).unwrap();
|
||||
assert!(matches!(crate::migrate::adopt(&store, &path, NOW).unwrap(), Adopted::Taken(_)));
|
||||
assert!(!path.exists());
|
||||
match store.shared() {
|
||||
Shared::Session { account, token } => {
|
||||
assert_eq!(account.id, accounts::handle(SERVICE, USER));
|
||||
assert_eq!(token, Secret::new(TOKEN));
|
||||
}
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The deployment is recorded the moment the device flow completes. The subject only arrives when
|
||||
/// `/api/v1/me` first answers, so a file can hold one without the other.
|
||||
#[test]
|
||||
fn a_session_file_with_no_subject_is_left_alone() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let path = app.path().join("legacy-session.json");
|
||||
std::fs::write(&path, format!(r#"{{"token":"{TOKEN}","service":"{SERVICE}"}}"#).as_bytes()).unwrap();
|
||||
|
||||
let legacy = crate::migrate::read(&path).unwrap().unwrap();
|
||||
assert_eq!(legacy.service, SERVICE);
|
||||
assert_eq!(legacy.incomplete(), Some("whose account it is"));
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Kept { why } => assert!(why.contains("whose account it is"), "{why}"),
|
||||
other => panic!("expected the file to be kept, got {other:?}"),
|
||||
}
|
||||
assert!(path.exists());
|
||||
assert_eq!(keychain.count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_file_spelled_the_other_way_still_reads() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("legacy-session.json");
|
||||
let body = format!(r#"{{"base_url":"{SERVICE}/","access_token":"{TOKEN}","sub":"{USER}","name":"Ada"}}"#);
|
||||
std::fs::write(&path, body.as_bytes()).unwrap();
|
||||
let legacy = crate::migrate::read(&path).unwrap().unwrap();
|
||||
assert_eq!(legacy.service, SERVICE, "the trailing slash comes off");
|
||||
assert_eq!(legacy.user, USER);
|
||||
assert_eq!(legacy.display, "Ada");
|
||||
assert_eq!(legacy.token, Secret::new(TOKEN));
|
||||
}
|
||||
|
||||
// ---- the secret itself -----------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_secret_never_prints_itself() {
|
||||
let secret = Secret::new(TOKEN);
|
||||
let shown = format!("{secret:?}");
|
||||
assert!(!shown.contains(TOKEN), "Debug printed the token: {shown}");
|
||||
assert_eq!(shown, format!("Secret({} bytes)", TOKEN.len()));
|
||||
assert_eq!(secret.len(), TOKEN.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_record_prints_no_secret() {
|
||||
let account = Account { id: "abc".to_owned(), service: SERVICE.to_owned(), ..Account::default() };
|
||||
assert!(!format!("{account:?}").contains(TOKEN));
|
||||
}
|
||||
Reference in new issue
Block a user