cargo-credential-0.4.6/.cargo_vcs_info.json0000644000000001710000000000100142450ustar { "git": { "sha1": "37629051518c3df9ac2c1744589362a02ecafa99" }, "path_in_vcs": "credential/cargo-credential" }cargo-credential-0.4.6/Cargo.lock0000644000000374500000000000100122320ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "anstream" version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", "utf8parse", ] [[package]] name = "anstyle" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" [[package]] name = "anstyle-lossy" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9a0444767dbd4aea9355cb47a370eb184dbfe918875e127eff52cb9d1638181" dependencies = [ "anstyle", ] [[package]] name = "anstyle-parse" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" dependencies = [ "windows-sys", ] [[package]] name = "anstyle-svg" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b6ddad447b448d6d5db36b31cbd3ff27c7af071619501998eeceab01968287a" dependencies = [ "anstream", "anstyle", "anstyle-lossy", "html-escape", "unicode-width", ] [[package]] name = "anstyle-wincon" version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" dependencies = [ "anstyle", "windows-sys", ] [[package]] name = "anyhow" version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" [[package]] name = "cargo-credential" version = "0.4.6" dependencies = [ "anyhow", "libc", "serde", "serde_json", "snapbox", "thiserror", "time", "windows-sys", ] [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "colorchoice" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" [[package]] name = "content_inspector" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7bda66e858c683005a53a9a60c69a4aca7eeaa45d124526e389f7aec8e62f38" dependencies = [ "memchr", ] [[package]] name = "deranged" version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" dependencies = [ "powerfmt", "serde", ] [[package]] name = "dunce" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56ce8c6da7551ec6c462cbaf3bfbc75131ebbfa1c944aeaa9dab51ca1c5f0c3b" [[package]] name = "errno" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" dependencies = [ "libc", "windows-sys", ] [[package]] name = "escargot" version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f474c6844cbd04e783d0f25757583db4f491770ca618bedf2fb01815fc79939" dependencies = [ "log", "once_cell", "serde", "serde_json", ] [[package]] name = "fastrand" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "filetime" version = "0.2.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ee447700ac8aa0b2f2bd7bc4462ad686ba06baa6727ac149a2d6277f0d240fd" dependencies = [ "cfg-if", "libc", "redox_syscall", "windows-sys", ] [[package]] name = "html-escape" version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d1ad449764d627e22bfd7cd5e8868264fc9236e07c752972b4080cd351cb476" dependencies = [ "utf8-width", ] [[package]] name = "itoa" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "libc" version = "0.2.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" [[package]] name = "linux-raw-sys" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "log" version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "memchr" version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" [[package]] name = "normalize-line-endings" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" [[package]] name = "num-conv" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" [[package]] name = "once_cell" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "powerfmt" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] name = "proc-macro2" version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "regex" version = "1.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax", ] [[package]] name = "regex-automata" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" [[package]] name = "rustix" version = "0.38.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89" dependencies = [ "bitflags 2.5.0", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "ryu" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" [[package]] name = "same-file" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ "winapi-util", ] [[package]] name = "serde" version = "1.0.199" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9f6e76df036c77cd94996771fb40db98187f096dd0b9af39c6c6e452ba966a" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.199" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11bd257a6541e141e42ca6d24ae26f7714887b47e89aa739099104c7e4d3b7fc" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.116" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "similar" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa42c91313f1d05da9b26f267f931cf178d4aba455b4c4622dd7355eb80c6640" [[package]] name = "snapbox" version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94204b12a4d3550420babdb4148c6639692e4e3e61060866929c5107f208aeb6" dependencies = [ "anstream", "anstyle", "anstyle-svg", "content_inspector", "dunce", "escargot", "filetime", "normalize-line-endings", "regex", "serde_json", "similar", "snapbox-macros", "tempfile", "walkdir", ] [[package]] name = "snapbox-macros" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f4c14672714436c09254801c934b203196a51182a5107fb76591c7cc56424d" dependencies = [ "anstream", ] [[package]] name = "syn" version = "2.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11a6ae1e52eb25aab8f3fb9fca13be982a373b8f1157ca14b897a825ba4a2d35" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", "rustix", "windows-sys", ] [[package]] name = "thiserror" version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "time" version = "0.3.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" dependencies = [ "deranged", "itoa", "num-conv", "powerfmt", "serde", "time-core", "time-macros", ] [[package]] name = "time-core" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" dependencies = [ "num-conv", "time-core", ] [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-width" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68f5e5f3158ecfd4b8ff6fe086db7c8467a2dfdac97fe420f2b7c4aa97af66d6" [[package]] name = "utf8-width" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86bd8d4e895da8537e5315b8254664e6b769c4ff3db18321b297a1e7004392e3" [[package]] name = "utf8parse" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "walkdir" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" dependencies = [ "same-file", "winapi-util", ] [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" dependencies = [ "winapi", ] [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" [[package]] name = "windows_aarch64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" [[package]] name = "windows_i686_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" [[package]] name = "windows_i686_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" [[package]] name = "windows_x86_64_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" [[package]] name = "windows_x86_64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" cargo-credential-0.4.6/Cargo.toml0000644000000037560000000000100122570ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.76" name = "cargo-credential" version = "0.4.6" build = false autobins = false autoexamples = false autotests = false autobenches = false description = "A library to assist writing Cargo credential helpers." homepage = "https://github.com/rust-lang/cargo" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/cargo" [lib] name = "cargo_credential" path = "src/lib.rs" [[example]] name = "file-provider" path = "examples/file-provider.rs" [[example]] name = "stdout-redirected" path = "examples/stdout-redirected.rs" [[test]] name = "examples" path = "tests/examples.rs" [dependencies.anyhow] version = "1.0.82" [dependencies.serde] version = "1.0.199" features = ["derive"] [dependencies.serde_json] version = "1.0.116" [dependencies.thiserror] version = "1.0.59" [dependencies.time] version = "0.3.36" features = [ "parsing", "formatting", "serde", ] [dev-dependencies.snapbox] version = "0.6.7" features = [ "diff", "dir", "term-svg", "regex", "examples", ] [target."cfg(unix)".dependencies.libc] version = "0.2.154" [target."cfg(windows)".dependencies.windows-sys] version = "0.52" features = [ "Win32_System_Console", "Win32_Foundation", ] [lints.clippy] dbg_macro = "warn" disallowed_methods = "warn" print_stderr = "warn" print_stdout = "warn" self_named_module_files = "warn" [lints.clippy.all] level = "allow" priority = -1 [lints.rust] rust_2018_idioms = "warn" [lints.rustdoc] private_intra_doc_links = "allow" cargo-credential-0.4.6/Cargo.toml.orig000064400000000000000000000013141046102023000157240ustar 00000000000000[package] name = "cargo-credential" version = "0.4.6" rust-version.workspace = true edition.workspace = true license.workspace = true homepage.workspace = true repository.workspace = true description = "A library to assist writing Cargo credential helpers." [dependencies] anyhow.workspace = true serde = { workspace = true, features = ["derive"] } serde_json.workspace = true thiserror.workspace = true time.workspace = true [target.'cfg(unix)'.dependencies] libc.workspace = true [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = ["Win32_System_Console", "Win32_Foundation"] } [dev-dependencies] snapbox = { workspace = true, features = ["examples"] } [lints] workspace = true cargo-credential-0.4.6/LICENSE-APACHE000064400000000000000000000251541046102023000147710ustar 00000000000000 Apache License Version 2.0, January 2004 https://www.apache.org/licenses/LICENSE-2.0 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. cargo-credential-0.4.6/LICENSE-MIT000064400000000000000000000017771046102023000145060ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. cargo-credential-0.4.6/README.md000064400000000000000000000017211046102023000143160ustar 00000000000000# cargo-credential This package is a library to assist writing a Cargo credential helper, which provides an interface to store tokens for authorizing access to a registry such as https://crates.io/. Documentation about credential processes may be found at https://doc.rust-lang.org/nightly/cargo/reference/credential-provider-protocol.html Example implementations may be found at https://github.com/rust-lang/cargo/tree/master/credential ## Usage Create a Cargo project with this as a dependency: ```toml # Add this to your Cargo.toml: [dependencies] cargo-credential = "0.4" ``` And then include a `main.rs` binary which implements the `Credential` trait, and calls the `main` function which will call the appropriate method of the trait: ```rust // src/main.rs use cargo_credential::{Credential, Error}; struct MyCredential; impl Credential for MyCredential { /// implement trait methods here... } fn main() { cargo_credential::main(MyCredential); } ``` cargo-credential-0.4.6/examples/file-provider.rs000064400000000000000000000073411046102023000177760ustar 00000000000000//! Example credential provider that stores credentials in a JSON file. //! This is not secure use cargo_credential::{ Action, CacheControl, Credential, CredentialResponse, RegistryInfo, Secret, }; use std::{collections::HashMap, fs::File, io::ErrorKind}; type Error = Box; struct FileCredential; impl Credential for FileCredential { fn perform( &self, registry: &RegistryInfo<'_>, action: &Action<'_>, _args: &[&str], ) -> Result { if registry.index_url != "https://github.com/rust-lang/crates.io-index" { // Restrict this provider to only work for crates.io. Cargo will skip it and attempt // another provider for any other registry. // // If a provider supports any registry, then this check should be omitted. return Err(cargo_credential::Error::UrlNotSupported); } // `Error::Other` takes a boxed `std::error::Error` type that causes Cargo to show the error. let mut creds = FileCredential::read().map_err(cargo_credential::Error::Other)?; match action { Action::Get(_) => { // Cargo requested a token, look it up. if let Some(token) = creds.get(registry.index_url) { Ok(CredentialResponse::Get { token: token.clone(), cache: CacheControl::Session, operation_independent: true, }) } else { // Credential providers should respond with `NotFound` when a credential can not be // found, allowing Cargo to attempt another provider. Err(cargo_credential::Error::NotFound) } } Action::Login(login_options) => { // The token for `cargo login` can come from the `login_options` parameter or i // interactively reading from stdin. // // `cargo_credential::read_token` automatically handles this. let token = cargo_credential::read_token(login_options, registry)?; creds.insert(registry.index_url.to_string(), token); FileCredential::write(&creds).map_err(cargo_credential::Error::Other)?; // Credentials were successfully stored. Ok(CredentialResponse::Login) } Action::Logout => { if creds.remove(registry.index_url).is_none() { // If the user attempts to log out from a registry that has no credentials // stored, then NotFound is the appropriate error. Err(cargo_credential::Error::NotFound) } else { // Credentials were successfully erased. Ok(CredentialResponse::Logout) } } // If a credential provider doesn't support a given operation, it should respond with `OperationNotSupported`. _ => Err(cargo_credential::Error::OperationNotSupported), } } } impl FileCredential { fn read() -> Result>, Error> { match File::open("cargo-credentials.json") { Ok(f) => Ok(serde_json::from_reader(f)?), Err(e) if e.kind() == ErrorKind::NotFound => Ok(HashMap::new()), Err(e) => Err(e)?, } } fn write(value: &HashMap>) -> Result<(), Error> { let file = File::create("cargo-credentials.json")?; Ok(serde_json::to_writer_pretty(file, value)?) } } fn main() { cargo_credential::main(FileCredential); } cargo-credential-0.4.6/examples/stdout-redirected.rs000064400000000000000000000014711046102023000206570ustar 00000000000000//! Provider used for testing redirection of stdout. #![allow(clippy::print_stderr)] #![allow(clippy::print_stdout)] use cargo_credential::{Action, Credential, CredentialResponse, Error, RegistryInfo}; struct MyCredential; impl Credential for MyCredential { fn perform( &self, _registry: &RegistryInfo<'_>, _action: &Action<'_>, _args: &[&str], ) -> Result { // Informational messages should be sent on stderr. eprintln!("message on stderr should be sent to the parent process"); // Reading from stdin and writing to stdout will go to the attached console (tty). println!("message from test credential provider"); Err(Error::OperationNotSupported) } } fn main() { cargo_credential::main(MyCredential); } cargo-credential-0.4.6/src/error.rs000064400000000000000000000134341046102023000153310ustar 00000000000000use serde::{Deserialize, Serialize}; use std::error::Error as StdError; use thiserror::Error as ThisError; /// Credential provider error type. /// /// `UrlNotSupported` and `NotFound` errors both cause Cargo /// to attempt another provider, if one is available. The other /// variants are fatal. /// /// Note: Do not add a tuple variant, as it cannot be serialized. #[derive(Serialize, Deserialize, ThisError, Debug)] #[serde(rename_all = "kebab-case", tag = "kind")] #[non_exhaustive] pub enum Error { /// Registry URL is not supported. This should be used if /// the provider only works for some registries. Cargo will /// try another provider, if available #[error("registry not supported")] UrlNotSupported, /// Credentials could not be found. Cargo will try another /// provider, if available #[error("credential not found")] NotFound, /// The provider doesn't support this operation, such as /// a provider that can't support 'login' / 'logout' #[error("requested operation not supported")] OperationNotSupported, /// The provider failed to perform the operation. Other /// providers will not be attempted #[error(transparent)] #[serde(with = "error_serialize")] Other(Box), /// A new variant was added to this enum since Cargo was built #[error("unknown error kind; try updating Cargo?")] #[serde(other)] Unknown, } impl From for Error { fn from(message: String) -> Self { Box::new(StringTypedError { message, source: None, }) .into() } } impl From<&str> for Error { fn from(err: &str) -> Self { err.to_string().into() } } impl From for Error { fn from(value: anyhow::Error) -> Self { let mut prev = None; for e in value.chain().rev() { prev = Some(Box::new(StringTypedError { message: e.to_string(), source: prev, })); } Error::Other(prev.unwrap()) } } impl From> for Error { fn from(value: Box) -> Self { Error::Other(value) } } /// String-based error type with an optional source #[derive(Debug)] struct StringTypedError { message: String, source: Option>, } impl StdError for StringTypedError { fn source(&self) -> Option<&(dyn StdError + 'static)> { self.source.as_ref().map(|err| err as &dyn StdError) } } impl std::fmt::Display for StringTypedError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.message.fmt(f) } } /// Serializer / deserializer for any boxed error. /// The string representation of the error, and its `source` chain can roundtrip across /// the serialization. The actual types are lost (downcast will not work). mod error_serialize { use std::error::Error as StdError; use std::ops::Deref; use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serializer}; use crate::error::StringTypedError; pub fn serialize( e: &Box, serializer: S, ) -> Result where S: Serializer, { let mut state = serializer.serialize_struct("StringTypedError", 2)?; state.serialize_field("message", &format!("{}", e))?; // Serialize the source error chain recursively let mut current_source: &dyn StdError = e.deref(); let mut sources = Vec::new(); while let Some(err) = current_source.source() { sources.push(err.to_string()); current_source = err; } state.serialize_field("caused-by", &sources)?; state.end() } pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(rename_all = "kebab-case")] struct ErrorData { message: String, caused_by: Option>, } let data = ErrorData::deserialize(deserializer)?; let mut prev = None; if let Some(source) = data.caused_by { for e in source.into_iter().rev() { prev = Some(Box::new(StringTypedError { message: e, source: prev, })); } } let e = Box::new(StringTypedError { message: data.message, source: prev, }); Ok(e) } } #[cfg(test)] mod tests { use super::Error; #[test] pub fn unknown_kind() { let json = r#"{ "kind": "unexpected-kind", "unexpected-content": "test" }"#; let e: Error = serde_json::from_str(&json).unwrap(); assert!(matches!(e, Error::Unknown)); } #[test] pub fn roundtrip() { // Construct an error with context let e = anyhow::anyhow!("E1").context("E2").context("E3"); // Convert to a string with contexts. let s1 = format!("{:?}", e); // Convert the error into an `Error` let e: Error = e.into(); // Convert that error into JSON let json = serde_json::to_string_pretty(&e).unwrap(); // Convert that error back to anyhow let e: anyhow::Error = e.into(); let s2 = format!("{:?}", e); assert_eq!(s1, s2); // Convert the error back from JSON let e: Error = serde_json::from_str(&json).unwrap(); // Convert to back to anyhow let e: anyhow::Error = e.into(); let s3 = format!("{:?}", e); assert_eq!(s2, s3); assert_eq!( r#"{ "kind": "other", "message": "E3", "caused-by": [ "E2", "E1" ] }"#, json ); } } cargo-credential-0.4.6/src/lib.rs000064400000000000000000000341571046102023000147530ustar 00000000000000//! Helper library for writing Cargo credential providers. //! //! A credential process should have a `struct` that implements the `Credential` trait. //! The `main` function should be called with an instance of that struct, such as: //! //! ```rust,ignore //! fn main() { //! cargo_credential::main(MyCredential); //! } //! ``` //! //! While in the `perform` function, stdin and stdout will be re-attached to the //! active console. This allows credential providers to be interactive if necessary. //! //! ## Error handling //! ### [`Error::UrlNotSupported`] //! A credential provider may only support some registry URLs. If this is the case //! and an unsupported index URL is passed to the provider, it should respond with //! [`Error::UrlNotSupported`]. Other credential providers may be attempted by Cargo. //! //! ### [`Error::NotFound`] //! When attempting an [`Action::Get`] or [`Action::Logout`], if a credential can not //! be found, the provider should respond with [`Error::NotFound`]. Other credential //! providers may be attempted by Cargo. //! //! ### [`Error::OperationNotSupported`] //! A credential provider might not support all operations. For example if the provider //! only supports [`Action::Get`], [`Error::OperationNotSupported`] should be returned //! for all other requests. //! //! ### [`Error::Other`] //! All other errors go here. The error will be shown to the user in Cargo, including //! the full error chain using [`std::error::Error::source`]. //! //! ## Example //! ```rust,ignore #![doc = include_str!("../examples/file-provider.rs")] //! ``` #![allow(clippy::print_stderr)] #![allow(clippy::print_stdout)] use serde::{Deserialize, Serialize}; use std::{fmt::Display, io}; use time::OffsetDateTime; mod error; mod secret; mod stdio; pub use error::Error; pub use secret::Secret; use stdio::stdin_stdout_to_console; /// Message sent by the credential helper on startup #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct CredentialHello { // Protocol versions supported by the credential process. pub v: Vec, } /// Credential provider that doesn't support any registries. pub struct UnsupportedCredential; impl Credential for UnsupportedCredential { fn perform( &self, _registry: &RegistryInfo<'_>, _action: &Action<'_>, _args: &[&str], ) -> Result { Err(Error::UrlNotSupported) } } /// Message sent by Cargo to the credential helper after the hello #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] pub struct CredentialRequest<'a> { // Cargo will respond with the highest common protocol supported by both. pub v: u32, #[serde(borrow)] pub registry: RegistryInfo<'a>, #[serde(borrow, flatten)] pub action: Action<'a>, /// Additional command-line arguments passed to the credential provider. #[serde(skip_serializing_if = "Vec::is_empty", default)] pub args: Vec<&'a str>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] pub struct RegistryInfo<'a> { /// Registry index url pub index_url: &'a str, /// Name of the registry in configuration. May not be available. /// The crates.io registry will be `crates-io` (`CRATES_IO_REGISTRY`). #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<&'a str>, /// Headers from attempting to access a registry that resulted in a HTTP 401. #[serde(skip_serializing_if = "Vec::is_empty", default)] pub headers: Vec, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] #[serde(tag = "kind", rename_all = "kebab-case")] pub enum Action<'a> { #[serde(borrow)] Get(Operation<'a>), Login(LoginOptions<'a>), Logout, #[serde(other)] Unknown, } impl<'a> Display for Action<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Action::Get(_) => f.write_str("get"), Action::Login(_) => f.write_str("login"), Action::Logout => f.write_str("logout"), Action::Unknown => f.write_str(""), } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] pub struct LoginOptions<'a> { /// Token passed on the command line via --token or from stdin #[serde(skip_serializing_if = "Option::is_none")] pub token: Option>, /// Optional URL that the user can visit to log in to the registry #[serde(skip_serializing_if = "Option::is_none")] pub login_url: Option<&'a str>, } /// A record of what kind of operation is happening that we should generate a token for. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] #[serde(tag = "operation", rename_all = "kebab-case")] pub enum Operation<'a> { /// The user is attempting to fetch a crate. Read, /// The user is attempting to publish a crate. Publish { /// The name of the crate name: &'a str, /// The version of the crate vers: &'a str, /// The checksum of the crate file being uploaded cksum: &'a str, }, /// The user is attempting to yank a crate. Yank { /// The name of the crate name: &'a str, /// The version of the crate vers: &'a str, }, /// The user is attempting to unyank a crate. Unyank { /// The name of the crate name: &'a str, /// The version of the crate vers: &'a str, }, /// The user is attempting to modify the owners of a crate. Owners { /// The name of the crate name: &'a str, }, #[serde(other)] Unknown, } /// Message sent by the credential helper #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(tag = "kind", rename_all = "kebab-case")] #[non_exhaustive] pub enum CredentialResponse { Get { token: Secret, #[serde(flatten)] cache: CacheControl, operation_independent: bool, }, Login, Logout, #[serde(other)] Unknown, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(tag = "cache", rename_all = "kebab-case")] #[non_exhaustive] pub enum CacheControl { /// Do not cache this result. Never, /// Cache this result and use it for subsequent requests in the current Cargo invocation until the specified time. Expires { #[serde(with = "time::serde::timestamp")] expiration: OffsetDateTime, }, /// Cache this result and use it for all subsequent requests in the current Cargo invocation. Session, #[serde(other)] Unknown, } /// Credential process JSON protocol version. If the protocol needs to make /// a breaking change, a new protocol version should be defined (`PROTOCOL_VERSION_2`). /// This library should offer support for both protocols if possible, by signaling /// in the `CredentialHello` message. Cargo will then choose which protocol to use, /// or it will error if there are no common protocol versions available. pub const PROTOCOL_VERSION_1: u32 = 1; pub trait Credential { /// Retrieves a token for the given registry. fn perform( &self, registry: &RegistryInfo<'_>, action: &Action<'_>, args: &[&str], ) -> Result; } /// Runs the credential interaction pub fn main(credential: impl Credential) { let result = doit(credential).map_err(|e| Error::Other(e)); if result.is_err() { serde_json::to_writer(std::io::stdout(), &result) .expect("failed to serialize credential provider error"); println!(); } } fn doit( credential: impl Credential, ) -> Result<(), Box> { let hello = CredentialHello { v: vec![PROTOCOL_VERSION_1], }; serde_json::to_writer(std::io::stdout(), &hello)?; println!(); loop { let mut buffer = String::new(); let len = std::io::stdin().read_line(&mut buffer)?; if len == 0 { return Ok(()); } let request = deserialize_request(&buffer)?; let response = stdin_stdout_to_console(|| { credential.perform(&request.registry, &request.action, &request.args) })?; serde_json::to_writer(std::io::stdout(), &response)?; println!(); } } /// Deserialize a request from Cargo. fn deserialize_request( value: &str, ) -> Result, Box> { let request: CredentialRequest<'_> = serde_json::from_str(&value)?; if request.v != PROTOCOL_VERSION_1 { return Err(format!("unsupported protocol version {}", request.v).into()); } Ok(request) } /// Read a line of text from stdin. pub fn read_line() -> Result { let mut buf = String::new(); io::stdin().read_line(&mut buf)?; Ok(buf.trim().to_string()) } /// Prompt the user for a token. pub fn read_token( login_options: &LoginOptions<'_>, registry: &RegistryInfo<'_>, ) -> Result, Error> { if let Some(token) = &login_options.token { return Ok(token.to_owned()); } if let Some(url) = login_options.login_url { eprintln!("please paste the token found on {url} below"); } else if let Some(name) = registry.name { eprintln!("please paste the token for {name} below"); } else { eprintln!("please paste the token for {} below", registry.index_url); } Ok(Secret::from(read_line().map_err(Box::new)?)) } #[cfg(test)] mod tests { use super::*; #[test] fn unsupported_version() { // This shouldn't ever happen in practice, since the credential provider signals to Cargo which // protocol versions it supports, and Cargo should only attempt to use one of those. let msg = r#"{"v":999, "registry": {"index-url":""}, "args":[], "kind": "unexpected"}"#; assert_eq!( "unsupported protocol version 999", deserialize_request(msg).unwrap_err().to_string() ); } #[test] fn cache_control() { let cc = CacheControl::Expires { expiration: OffsetDateTime::from_unix_timestamp(1693928537).unwrap(), }; let json = serde_json::to_string(&cc).unwrap(); assert_eq!(json, r#"{"cache":"expires","expiration":1693928537}"#); let cc = CacheControl::Session; let json = serde_json::to_string(&cc).unwrap(); assert_eq!(json, r#"{"cache":"session"}"#); let cc: CacheControl = serde_json::from_str(r#"{"cache":"unknown-kind"}"#).unwrap(); assert_eq!(cc, CacheControl::Unknown); assert_eq!( "missing field `expiration`", serde_json::from_str::(r#"{"cache":"expires"}"#) .unwrap_err() .to_string() ); } #[test] fn credential_response() { let cr = CredentialResponse::Get { cache: CacheControl::Never, operation_independent: true, token: Secret::from("value".to_string()), }; let json = serde_json::to_string(&cr).unwrap(); assert_eq!( json, r#"{"kind":"get","token":"value","cache":"never","operation_independent":true}"# ); let cr = CredentialResponse::Login; let json = serde_json::to_string(&cr).unwrap(); assert_eq!(json, r#"{"kind":"login"}"#); let cr: CredentialResponse = serde_json::from_str(r#"{"kind":"unknown-kind","extra-data":true}"#).unwrap(); assert_eq!(cr, CredentialResponse::Unknown); let cr: CredentialResponse = serde_json::from_str(r#"{"kind":"login","extra-data":true}"#).unwrap(); assert_eq!(cr, CredentialResponse::Login); let cr: CredentialResponse = serde_json::from_str(r#"{"kind":"get","token":"value","cache":"never","operation_independent":true,"extra-field-ignored":123}"#).unwrap(); assert_eq!( cr, CredentialResponse::Get { cache: CacheControl::Never, operation_independent: true, token: Secret::from("value".to_string()) } ); } #[test] fn credential_request() { let get_oweners = CredentialRequest { v: PROTOCOL_VERSION_1, args: vec![], registry: RegistryInfo { index_url: "url", name: None, headers: vec![], }, action: Action::Get(Operation::Owners { name: "pkg" }), }; let json = serde_json::to_string(&get_oweners).unwrap(); assert_eq!( json, r#"{"v":1,"registry":{"index-url":"url"},"kind":"get","operation":"owners","name":"pkg"}"# ); let cr: CredentialRequest<'_> = serde_json::from_str(r#"{"extra-1":true,"v":1,"registry":{"index-url":"url","extra-2":true},"kind":"get","operation":"owners","name":"pkg","args":[]}"#).unwrap(); assert_eq!(cr, get_oweners); } #[test] fn credential_request_logout() { let unknown = CredentialRequest { v: PROTOCOL_VERSION_1, args: vec![], registry: RegistryInfo { index_url: "url", name: None, headers: vec![], }, action: Action::Logout, }; let cr: CredentialRequest<'_> = serde_json::from_str( r#"{"v":1,"registry":{"index-url":"url"},"kind":"logout","extra-1":true,"args":[]}"#, ) .unwrap(); assert_eq!(cr, unknown); } #[test] fn credential_request_unknown() { let unknown = CredentialRequest { v: PROTOCOL_VERSION_1, args: vec![], registry: RegistryInfo { index_url: "", name: None, headers: vec![], }, action: Action::Unknown, }; let cr: CredentialRequest<'_> = serde_json::from_str( r#"{"v":1,"registry":{"index-url":""},"kind":"unexpected-1","extra-1":true,"args":[]}"#, ) .unwrap(); assert_eq!(cr, unknown); } } cargo-credential-0.4.6/src/secret.rs000064400000000000000000000054661046102023000154730ustar 00000000000000use std::fmt; use std::ops::Deref; use serde::{Deserialize, Serialize}; /// A wrapper for values that should not be printed. /// /// This type does not implement `Display`, and has a `Debug` impl that hides /// the contained value. /// /// ``` /// # use cargo_credential::Secret; /// let token = Secret::from("super secret string"); /// assert_eq!(format!("{:?}", token), "Secret { inner: \"REDACTED\" }"); /// ``` /// /// Currently, we write a borrowed `Secret` as `Secret<&T>`. /// The [`as_deref`](Secret::as_deref) and [`to_owned`](Secret::to_owned) methods can /// be used to convert back and forth between `Secret` and `Secret<&str>`. #[derive(Default, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Secret { inner: T, } impl Secret { /// Unwraps the contained value. /// /// Use of this method marks the boundary of where the contained value is /// hidden. pub fn expose(self) -> T { self.inner } /// Converts a `Secret` to a `Secret<&T::Target>`. /// ``` /// # use cargo_credential::Secret; /// let owned: Secret = Secret::from(String::from("token")); /// let borrowed: Secret<&str> = owned.as_deref(); /// ``` pub fn as_deref(&self) -> Secret<&::Target> where T: Deref, { Secret::from(self.inner.deref()) } /// Converts a `Secret` to a `Secret<&T>`. pub fn as_ref(&self) -> Secret<&T> { Secret::from(&self.inner) } /// Converts a `Secret` to a `Secret` by applying `f` to the contained value. pub fn map(self, f: F) -> Secret where F: FnOnce(T) -> U, { Secret::from(f(self.inner)) } } impl Secret<&T> { /// Converts a `Secret` containing a borrowed type to a `Secret` containing the /// corresponding owned type. /// ``` /// # use cargo_credential::Secret; /// let borrowed: Secret<&str> = Secret::from("token"); /// let owned: Secret = borrowed.to_owned(); /// ``` pub fn to_owned(&self) -> Secret<::Owned> { Secret::from(self.inner.to_owned()) } } impl Secret> { /// Converts a `Secret>` to a `Result, E>`. pub fn transpose(self) -> Result, E> { self.inner.map(|v| Secret::from(v)) } } impl> Secret { /// Checks if the contained value is empty. pub fn is_empty(&self) -> bool { self.inner.as_ref().is_empty() } } impl From for Secret { fn from(inner: T) -> Self { Self { inner } } } impl fmt::Debug for Secret { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Secret") .field("inner", &"REDACTED") .finish() } } cargo-credential-0.4.6/src/stdio.rs000064400000000000000000000116521046102023000153220ustar 00000000000000use std::{fs::File, io::Error}; /// Reset stdin and stdout to the attached console / tty for the duration of the closure. /// If no console is available, stdin and stdout will be redirected to null. pub fn stdin_stdout_to_console(f: F) -> Result where F: FnOnce() -> T, { let open_write = |f| std::fs::OpenOptions::new().write(true).open(f); let mut stdin = File::open(imp::IN_DEVICE).or_else(|_| File::open(imp::NULL_DEVICE))?; let mut stdout = open_write(imp::OUT_DEVICE).or_else(|_| open_write(imp::NULL_DEVICE))?; let _stdin_guard = imp::ReplacementGuard::new(Stdio::Stdin, &mut stdin)?; let _stdout_guard = imp::ReplacementGuard::new(Stdio::Stdout, &mut stdout)?; Ok(f()) } enum Stdio { Stdin, Stdout, } #[cfg(windows)] mod imp { use super::Stdio; use std::{fs::File, io::Error, os::windows::prelude::AsRawHandle}; use windows_sys::Win32::{ Foundation::{HANDLE, INVALID_HANDLE_VALUE}, System::Console::{ GetStdHandle, SetStdHandle, STD_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, }, }; pub const OUT_DEVICE: &str = "CONOUT$"; pub const IN_DEVICE: &str = "CONIN$"; pub const NULL_DEVICE: &str = "NUL"; /// Restores previous stdio when dropped. pub struct ReplacementGuard { std_handle: STD_HANDLE, previous: HANDLE, } impl ReplacementGuard { pub(super) fn new(stdio: Stdio, replacement: &mut File) -> Result { let std_handle = match stdio { Stdio::Stdin => STD_INPUT_HANDLE, Stdio::Stdout => STD_OUTPUT_HANDLE, }; let previous; unsafe { // Make a copy of the current handle previous = GetStdHandle(std_handle); if previous == INVALID_HANDLE_VALUE { return Err(std::io::Error::last_os_error()); } // Replace stdin with the replacement handle if SetStdHandle(std_handle, replacement.as_raw_handle() as HANDLE) == 0 { return Err(std::io::Error::last_os_error()); } } Ok(ReplacementGuard { previous, std_handle, }) } } impl Drop for ReplacementGuard { fn drop(&mut self) { unsafe { // Put previous handle back in to stdin SetStdHandle(self.std_handle, self.previous); } } } } #[cfg(unix)] mod imp { use super::Stdio; use libc::{close, dup, dup2, STDIN_FILENO, STDOUT_FILENO}; use std::{fs::File, io::Error, os::fd::AsRawFd}; pub const IN_DEVICE: &str = "/dev/tty"; pub const OUT_DEVICE: &str = "/dev/tty"; pub const NULL_DEVICE: &str = "/dev/null"; /// Restores previous stdio when dropped. pub struct ReplacementGuard { std_fileno: i32, previous: i32, } impl ReplacementGuard { pub(super) fn new(stdio: Stdio, replacement: &mut File) -> Result { let std_fileno = match stdio { Stdio::Stdin => STDIN_FILENO, Stdio::Stdout => STDOUT_FILENO, }; let previous; unsafe { // Duplicate the existing stdin file to a new descriptor previous = dup(std_fileno); if previous == -1 { return Err(std::io::Error::last_os_error()); } // Replace stdin with the replacement file if dup2(replacement.as_raw_fd(), std_fileno) == -1 { return Err(std::io::Error::last_os_error()); } } Ok(ReplacementGuard { previous, std_fileno, }) } } impl Drop for ReplacementGuard { fn drop(&mut self) { unsafe { // Put previous file back in to stdin dup2(self.previous, self.std_fileno); // Close the file descriptor we used as a backup close(self.previous); } } } } #[cfg(test)] mod test { use std::fs::OpenOptions; use std::io::{Seek, Write}; use super::imp::ReplacementGuard; use super::Stdio; #[test] fn stdin() { let tempdir = snapbox::dir::DirRoot::mutable_temp().unwrap(); let file = tempdir.path().unwrap().join("stdin"); let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .open(file) .unwrap(); writeln!(&mut file, "hello").unwrap(); file.seek(std::io::SeekFrom::Start(0)).unwrap(); { let _guard = ReplacementGuard::new(Stdio::Stdin, &mut file).unwrap(); let line = std::io::stdin().lines().next().unwrap().unwrap(); assert_eq!(line, "hello"); } } } cargo-credential-0.4.6/tests/examples.rs000064400000000000000000000035131046102023000163660ustar 00000000000000use std::path::Path; use snapbox::cmd::Command; use snapbox::prelude::*; #[test] fn stdout_redirected() { let bin = snapbox::cmd::compile_example("stdout-redirected", []).unwrap(); let hello = r#"{"v":[1]}"#; let get_request = r#"{"v": 1, "registry": {"index-url":"sparse+https://test/","name":"alternative"},"kind": "get","operation": "read","args": []}"#; let err_not_supported = r#"{"Err":{"kind":"operation-not-supported"}}"#; Command::new(bin) .stdin(format!("{get_request}\n")) .arg("--cargo-plugin") .assert() .stdout_eq(format!("{hello}\n{err_not_supported}\n").raw()) .stderr_eq("message on stderr should be sent to the parent process\n".raw()) .success(); } #[test] fn file_provider() { let bin = snapbox::cmd::compile_example("file-provider", []).unwrap(); let hello = r#"{"v":[1]}"#; let login_request = r#"{"v": 1,"registry": {"index-url":"https://github.com/rust-lang/crates.io-index","name":"crates-io"},"kind": "login","token": "s3krit","args": []}"#; let login_response = r#"{"Ok":{"kind":"login"}}"#; let get_request = r#"{"v": 1,"registry": {"index-url":"https://github.com/rust-lang/crates.io-index","name":"crates-io"},"kind": "get","operation": "read","args": []}"#; let get_response = r#"{"Ok":{"kind":"get","token":"s3krit","cache":"session","operation_independent":true}}"#; let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("cargo-credential-tests"); std::fs::create_dir(&dir).unwrap(); Command::new(bin) .current_dir(&dir) .stdin(format!("{login_request}\n{get_request}\n")) .arg("--cargo-plugin") .assert() .stdout_eq(format!("{hello}\n{login_response}\n{get_response}\n").raw()) .stderr_eq("".raw()) .success(); std::fs::remove_dir_all(&dir).unwrap(); }