1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; This is the auth-source.el package. It lets users tell Gnus how to
26 ;; authenticate in a single place. Simplicity is the goal. Instead
27 ;; of providing 5000 options, we'll stick to simple, easy to
28 ;; understand options.
30 ;; See the auth.info Info documentation for details.
34 ;; - never decode the backend file unless it's necessary
35 ;; - a more generic way to match backends and search backend contents
36 ;; - absorb netrc.el and simplify it
37 ;; - protect passwords better
38 ;; - allow creating and changing netrc lines (not files) e.g. change a password
42 (require 'password-cache)
46 (eval-when-compile (require 'cl))
48 (or (ignore-errors (require 'eieio))
49 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
51 (let ((load-path (cons (expand-file-name
52 "gnus-fallback-lib/eieio"
53 (file-name-directory (locate-library "gnus")))
57 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
59 (autoload 'secrets-create-item "secrets")
60 (autoload 'secrets-delete-item "secrets")
61 (autoload 'secrets-get-alias "secrets")
62 (autoload 'secrets-get-attributes "secrets")
63 (autoload 'secrets-get-secret "secrets")
64 (autoload 'secrets-list-collections "secrets")
65 (autoload 'secrets-search-items "secrets")
67 (autoload 'rfc2104-hash "rfc2104")
69 (autoload 'plstore-open "plstore")
70 (autoload 'plstore-find "plstore")
71 (autoload 'plstore-put "plstore")
72 (autoload 'plstore-delete "plstore")
73 (autoload 'plstore-save "plstore")
74 (autoload 'plstore-get-file "plstore")
76 (autoload 'epg-make-context "epg")
77 (autoload 'epg-context-set-passphrase-callback "epg")
78 (autoload 'epg-decrypt-string "epg")
79 (autoload 'epg-context-set-armor "epg")
80 (autoload 'epg-encrypt-string "epg")
82 (autoload 'help-mode "help-mode" nil t)
84 (defvar secrets-enabled)
86 (defgroup auth-source nil
87 "Authentication sources."
88 :version "23.1" ;; No Gnus
92 (defcustom auth-source-cache-expiry 7200
93 "How many seconds passwords are cached, or nil to disable
94 expiring. Overrides `password-cache-expiry' through a
98 :type '(choice (const :tag "Never" nil)
99 (const :tag "All Day" 86400)
100 (const :tag "2 Hours" 7200)
101 (const :tag "30 Minutes" 1800)
102 (integer :tag "Seconds")))
104 ;; The slots below correspond with the `auth-source-search' spec,
105 ;; so a backend with :host set, for instance, would match only
106 ;; searches for that host. Normally they are nil.
107 (defclass auth-source-backend ()
108 ((type :initarg :type
112 :documentation "The backend type.")
113 (source :initarg :source
116 :documentation "The backend source.")
121 :documentation "The backend host.")
126 :documentation "The backend user.")
131 :documentation "The backend protocol.")
134 :documentation "Internal backend data.")
135 (create-function :initarg :create-function
139 :documentation "The create function.")
140 (search-function :initarg :search-function
144 :documentation "The search function.")))
146 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
147 (pop3 "pop3" "pop" "pop3s" "110" "995")
151 "List of authentication protocols and their names"
154 :version "23.2" ;; No Gnus
155 :type '(repeat :tag "Authentication Protocols"
156 (cons :tag "Protocol Entry"
157 (symbol :tag "Protocol")
159 (string :tag "Name")))))
161 ;; Generate all the protocols in a format Customize can use.
162 ;; TODO: generate on the fly from auth-source-protocols
163 (defconst auth-source-protocols-customize
165 (let ((p (car-safe a)))
167 :tag (upcase (symbol-name p))
169 auth-source-protocols))
171 (defvar auth-source-creation-defaults nil
172 "Defaults for creating token values. Usually let-bound.")
174 (defvar auth-source-creation-prompts nil
175 "Default prompts for token values. Usually let-bound.")
177 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
179 (defcustom auth-source-save-behavior 'ask
180 "If set, auth-source will respect it for save behavior."
182 :version "23.2" ;; No Gnus
184 :tag "auth-source new token save behavior"
185 (const :tag "Always save" t)
186 (const :tag "Never save" nil)
187 (const :tag "Ask" ask)))
189 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") never) (t gpg)))
190 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
192 (defcustom auth-source-netrc-use-gpg-tokens 'never
193 "Set this to tell auth-source when to create GPG password
194 tokens in netrc files. It's either an alist or `never'.
195 Note that if EPA/EPG is not available, this should NOT be used."
197 :version "23.2" ;; No Gnus
199 (const :tag "Always use GPG password tokens" (t gpg))
200 (const :tag "Never use GPG password tokens" never)
201 (repeat :tag "Use a lookup list"
203 (choice :tag "Matcher"
204 (const :tag "Match anything" t)
205 (const :tag "The EPA encrypted file extensions"
206 ,(if (boundp 'epa-file-auto-mode-alist-entry)
208 'epa-file-auto-mode-alist-entry))
210 (regexp :tag "Regular expression"))
211 (choice :tag "What to do"
212 (const :tag "Save GPG-encrypted password tokens" gpg)
213 (const :tag "Don't encrypt tokens" never))))))
215 (defvar auth-source-magic "auth-source-magic ")
217 (defcustom auth-source-do-cache t
218 "Whether auth-source should cache information with `password-cache'."
220 :version "23.2" ;; No Gnus
223 (defcustom auth-source-debug nil
224 "Whether auth-source should log debug messages.
226 If the value is nil, debug messages are not logged.
228 If the value is t, debug messages are logged with `message'. In
229 that case, your authentication data will be in the clear (except
232 If the value is a function, debug messages are logged by calling
233 that function using the same arguments as `message'."
235 :version "23.2" ;; No Gnus
237 :tag "auth-source debugging mode"
238 (const :tag "Log using `message' to the *Messages* buffer" t)
239 (const :tag "Log all trivia with `message' to the *Messages* buffer"
241 (function :tag "Function that takes arguments like `message'")
242 (const :tag "Don't log anything" nil)))
244 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
245 "List of authentication sources.
247 The default will get login and password information from
248 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
249 packages to be encrypted. If that file doesn't exist, it will
250 try the unencrypted version \"~/.authinfo\" and the famous
253 See the auth.info manual for details.
255 Each entry is the authentication type with optional properties.
257 It's best to customize this with `M-x customize-variable' because the choices
258 can get pretty complex."
260 :version "24.1" ;; No Gnus
261 :type `(repeat :tag "Authentication Sources"
263 (string :tag "Just a file")
264 (const :tag "Default Secrets API Collection" 'default)
265 (const :tag "Login Secrets API Collection" "secrets:Login")
266 (const :tag "Temp Secrets API Collection" "secrets:session")
268 (const :tag "Default internet Mac OS Keychain"
269 macos-keychain-internet)
271 (const :tag "Default generic Mac OS Keychain"
272 macos-keychain-generic)
274 (list :tag "Source definition"
275 (const :format "" :value :source)
276 (choice :tag "Authentication backend choice"
277 (string :tag "Authentication Source (file)")
279 :tag "Secret Service API/KWallet/GNOME Keyring"
280 (const :format "" :value :secrets)
281 (choice :tag "Collection to use"
282 (string :tag "Collection name")
283 (const :tag "Default" 'default)
284 (const :tag "Login" "Login")
286 :tag "Temporary" "session")))
288 :tag "Mac OS internet Keychain"
290 :value :macos-keychain-internet)
291 (choice :tag "Collection to use"
292 (string :tag "internet Keychain path")
293 (const :tag "default" 'default)))
295 :tag "Mac OS generic Keychain"
297 :value :macos-keychain-generic)
298 (choice :tag "Collection to use"
299 (string :tag "generic Keychain path")
300 (const :tag "default" 'default))))
301 (repeat :tag "Extra Parameters" :inline t
302 (choice :tag "Extra parameter"
305 (const :format "" :value :host)
306 (choice :tag "Host (machine) choice"
309 :tag "Regular expression")))
312 (const :format "" :value :port)
316 ,@auth-source-protocols-customize))
317 (list :tag "User" :inline t
318 (const :format "" :value :user)
320 :tag "Personality/Username"
325 (defcustom auth-source-gpg-encrypt-to t
326 "List of recipient keys that `authinfo.gpg' encrypted to.
327 If the value is not a list, symmetric encryption will be used."
329 :version "24.1" ;; No Gnus
330 :type '(choice (const :tag "Symmetric encryption" t)
331 (repeat :tag "Recipient public keys"
332 (string :tag "Recipient public key"))))
334 ;; temp for debugging
335 ;; (unintern 'auth-source-protocols)
336 ;; (unintern 'auth-sources)
337 ;; (customize-variable 'auth-sources)
338 ;; (setq auth-sources nil)
339 ;; (format "%S" auth-sources)
340 ;; (customize-variable 'auth-source-protocols)
341 ;; (setq auth-source-protocols nil)
342 ;; (format "%S" auth-source-protocols)
343 ;; (auth-source-pick nil :host "a" :port 'imap)
344 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
345 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
346 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
347 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
348 ;; (auth-source-protocol-defaults 'imap)
350 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
351 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
352 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
353 (defun auth-source-do-debug (&rest msg)
354 (when auth-source-debug
355 (apply 'auth-source-do-warn msg)))
357 (defun auth-source-do-trivia (&rest msg)
358 (when (or (eq auth-source-debug 'trivia)
359 (functionp auth-source-debug))
360 (apply 'auth-source-do-warn msg)))
362 (defun auth-source-do-warn (&rest msg)
364 ;; set logger to either the function in auth-source-debug or 'message
365 ;; note that it will be 'message if auth-source-debug is nil
366 (if (functionp auth-source-debug)
372 ;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
373 (defun auth-source-read-char-choice (prompt choices)
374 "Read one of CHOICES by `read-char-choice', or `read-char'.
375 `dropdown-list' support is disabled because it doesn't work reliably.
376 Only one of CHOICES will be returned. The PROMPT is augmented
377 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
379 (let* ((prompt-choices
380 (apply 'concat (loop for c in choices
381 collect (format "%c/" c))))
382 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
383 (full-prompt (concat prompt prompt-choices))
386 (while (not (memq k choices))
388 ((fboundp 'read-char-choice)
389 (read-char-choice full-prompt choices))
390 (t (message "%s" full-prompt)
391 (setq k (read-char))))))
394 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
395 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
396 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
397 ;; (:source (:secrets "session") :host t :port t :user "joe")
398 ;; (:source (:secrets "Login") :host t :port t)
399 ;; (:source "~/.authinfo.gpg" :host t :port t)))
401 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
402 ;; (:source (:secrets "session") :host t :port t :user "joe")
403 ;; (:source (:secrets "Login") :host t :port t)
406 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
408 ;; (auth-source-backend-parse "myfile.gpg")
409 ;; (auth-source-backend-parse 'default)
410 ;; (auth-source-backend-parse "secrets:Login")
411 ;; (auth-source-backend-parse 'macos-keychain-internet)
412 ;; (auth-source-backend-parse 'macos-keychain-generic)
413 ;; (auth-source-backend-parse "macos-keychain-internet:/path/here.keychain")
414 ;; (auth-source-backend-parse "macos-keychain-generic:/path/here.keychain")
416 (defun auth-source-backend-parse (entry)
417 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
418 (auth-source-backend-parse-parameters
421 ;; take 'default and recurse to get it as a Secrets API default collection
422 ;; matching any user, host, and protocol
424 (auth-source-backend-parse '(:source (:secrets default))))
425 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
426 ;; matching any user, host, and protocol
427 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
428 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
430 ;; take 'macos-keychain-internet and recurse to get it as a Mac OS
431 ;; Keychain collection matching any user, host, and protocol
432 ((eq entry 'macos-keychain-internet)
433 (auth-source-backend-parse '(:source (:macos-keychain-internet default))))
434 ;; take 'macos-keychain-generic and recurse to get it as a Mac OS
435 ;; Keychain collection matching any user, host, and protocol
436 ((eq entry 'macos-keychain-generic)
437 (auth-source-backend-parse '(:source (:macos-keychain-generic default))))
438 ;; take macos-keychain-internet:XYZ and recurse to get it as MacOS
439 ;; Keychain "XYZ" matching any user, host, and protocol
440 ((and (stringp entry) (string-match "^macos-keychain-internet:\\(.+\\)"
442 (auth-source-backend-parse `(:source (:macos-keychain-internet
443 ,(match-string 1 entry)))))
444 ;; take macos-keychain-generic:XYZ and recurse to get it as MacOS
445 ;; Keychain "XYZ" matching any user, host, and protocol
446 ((and (stringp entry) (string-match "^macos-keychain-generic:\\(.+\\)"
448 (auth-source-backend-parse `(:source (:macos-keychain-generic
449 ,(match-string 1 entry)))))
451 ;; take just a file name and recurse to get it as a netrc file
452 ;; matching any user, host, and protocol
454 (auth-source-backend-parse `(:source ,entry)))
456 ;; a file name with parameters
457 ((stringp (plist-get entry :source))
458 (if (equal (file-name-extension (plist-get entry :source)) "plist")
460 (plist-get entry :source)
461 :source (plist-get entry :source)
463 :search-function 'auth-source-plstore-search
464 :create-function 'auth-source-plstore-create
465 :data (plstore-open (plist-get entry :source)))
467 (plist-get entry :source)
468 :source (plist-get entry :source)
470 :search-function 'auth-source-netrc-search
471 :create-function 'auth-source-netrc-create)))
473 ;; the MacOS Keychain
475 (not (null (plist-get entry :source))) ; the source must not be nil
476 (listp (plist-get entry :source)) ; and it must be a list
478 (plist-get (plist-get entry :source) :macos-keychain-generic)
479 (plist-get (plist-get entry :source) :macos-keychain-internet)))
481 (let* ((source-spec (plist-get entry :source))
482 (keychain-generic (plist-get source-spec :macos-keychain-generic))
483 (keychain-type (if keychain-generic
484 'macos-keychain-generic
485 'macos-keychain-internet))
486 (source (plist-get source-spec (if keychain-generic
487 :macos-keychain-generic
488 :macos-keychain-internet))))
490 (when (symbolp source)
491 (setq source (symbol-name source)))
494 (format "Mac OS Keychain (%s)" source)
497 :search-function 'auth-source-macos-keychain-search
498 :create-function 'auth-source-macos-keychain-create)))
500 ;; the Secrets API. We require the package, in order to have a
501 ;; defined value for `secrets-enabled'.
503 (not (null (plist-get entry :source))) ; the source must not be nil
504 (listp (plist-get entry :source)) ; and it must be a list
505 (require 'secrets nil t) ; and we must load the Secrets API
506 secrets-enabled) ; and that API must be enabled
508 ;; the source is either the :secrets key in ENTRY or
509 ;; if that's missing or nil, it's "session"
510 (let ((source (or (plist-get (plist-get entry :source) :secrets)
513 ;; if the source is a symbol, we look for the alias named so,
514 ;; and if that alias is missing, we use "Login"
515 (when (symbolp source)
516 (setq source (or (secrets-get-alias (symbol-name source))
519 (if (featurep 'secrets)
521 (format "Secrets API (%s)" source)
524 :search-function 'auth-source-secrets-search
525 :create-function 'auth-source-secrets-create)
527 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
529 (format "Ignored Secrets API (%s)" source)
536 "auth-source-backend-parse: invalid backend spec: %S" entry)
542 (defun auth-source-backend-parse-parameters (entry backend)
543 "Fills in the extra auth-source-backend parameters of ENTRY.
544 Using the plist ENTRY, get the :host, :port, and :user search
546 (let ((entry (if (stringp entry)
550 (when (setq val (plist-get entry :host))
551 (oset backend host val))
552 (when (setq val (plist-get entry :user))
553 (oset backend user val))
554 (when (setq val (plist-get entry :port))
555 (oset backend port val)))
558 ;; (mapcar 'auth-source-backend-parse auth-sources)
560 (defun* auth-source-search (&rest spec
561 &key type max host user port secret
562 require create delete
564 "Search or modify authentication backends according to SPEC.
566 This function parses `auth-sources' for matches of the SPEC
567 plist. It can optionally create or update an authentication
568 token if requested. A token is just a standard Emacs property
569 list with a :secret property that can be a function; all the
570 other properties will always hold scalar values.
572 Typically the :secret property, if present, contains a password.
574 Common search keys are :max, :host, :port, and :user. In
575 addition, :create specifies how tokens will be or created.
576 Finally, :type can specify which backend types you want to check.
578 A string value is always matched literally. A symbol is matched
579 as its string value, literally. All the SPEC values can be
580 single values (symbol or string) or lists thereof (in which case
581 any of the search terms matches).
583 :create t means to create a token if possible.
585 A new token will be created if no matching tokens were found.
586 The new token will have only the keys the backend requires. For
587 the netrc backend, for instance, that's the user, host, and
592 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
593 (A . \"default A\"))))
594 (auth-source-search :host \"mine\" :type 'netrc :max 1
595 :P \"pppp\" :Q \"qqqq\"
600 \"Search for any entry matching host 'mine' in backends of type
601 'netrc', maximum one result.
603 Create a new entry if you found none. The netrc backend will
604 automatically require host, user, and port. The host will be
605 'mine'. We prompt for the user with default 'defaultUser' and
606 for the port without a default. We will not prompt for A, Q,
607 or P. The resulting token will only have keys user, host, and
610 :create '(A B C) also means to create a token if possible.
612 The behavior is like :create t but if the list contains any
613 parameter, that parameter will be required in the resulting
614 token. The value for that parameter will be obtained from the
615 search parameters or from user input. If any queries are needed,
616 the alist `auth-source-creation-defaults' will be checked for the
617 default value. If the user, host, or port are missing, the alist
618 `auth-source-creation-prompts' will be used to look up the
619 prompts IN THAT ORDER (so the 'user prompt will be queried first,
620 then 'host, then 'port, and finally 'secret). Each prompt string
621 can use %u, %h, and %p to show the user, host, and port.
625 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
626 (A . \"default A\")))
627 (auth-source-creation-prompts
628 '((password . \"Enter IMAP password for %h:%p: \"))))
629 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
630 :P \"pppp\" :Q \"qqqq\"
635 \"Search for any entry matching host 'nonesuch'
636 or 'twosuch' in backends of type 'netrc', maximum one result.
638 Create a new entry if you found none. The netrc backend will
639 automatically require host, user, and port. The host will be
640 'nonesuch' and Q will be 'qqqq'. We prompt for the password
641 with the shown prompt. We will not prompt for Q. The resulting
642 token will have keys user, host, port, A, B, and Q. It will not
643 have P with any value, even though P is used in the search to
644 find only entries that have P set to 'pppp'.\"
646 When multiple values are specified in the search parameter, the
647 user is prompted for which one. So :host (X Y Z) would ask the
648 user to choose between X, Y, and Z.
650 This creation can fail if the search was not specific enough to
651 create a new token (it's up to the backend to decide that). You
652 should `catch' the backend-specific error as usual. Some
653 backends (netrc, at least) will prompt the user rather than throw
656 :require (A B C) means that only results that contain those
657 tokens will be returned. Thus for instance requiring :secret
658 will ensure that any results will actually have a :secret
661 :delete t means to delete any found entries. nil by default.
662 Use `auth-source-delete' in ELisp code instead of calling
663 `auth-source-search' directly with this parameter.
665 :type (X Y Z) will check only those backend types. 'netrc and
666 'secrets are the only ones supported right now.
668 :max N means to try to return at most N items (defaults to 1).
669 When 0 the function will return just t or nil to indicate if any
670 matches were found. More than N items may be returned, depending
671 on the search and the backend.
673 :host (X Y Z) means to match only hosts X, Y, or Z according to
674 the match rules above. Defaults to t.
676 :user (X Y Z) means to match only users X, Y, or Z according to
677 the match rules above. Defaults to t.
679 :port (P Q R) means to match only protocols P, Q, or R.
682 :K (V1 V2 V3) for any other key K will match values V1, V2, or
683 V3 (note the match rules above).
685 The return value is a list with at most :max tokens. Each token
686 is a plist with keys :backend :host :port :user, plus any other
687 keys provided by the backend (notably :secret). But note the
688 exception for :max 0, which see above.
690 The token can hold a :save-function key. If you call that, the
691 user will be prompted to save the data to the backend. You can't
692 request that this should happen right after creation, because
693 `auth-source-search' has no way of knowing if the token is
694 actually useful. So the caller must arrange to call this function.
696 The token's :secret key can hold a function. In that case you
697 must call it to obtain the actual value."
698 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
700 (ignored-keys '(:require :create :delete :max))
701 (keys (loop for i below (length spec) by 2
702 unless (memq (nth i spec) ignored-keys)
703 collect (nth i spec)))
704 (cached (auth-source-remembered-p spec))
705 ;; note that we may have cached results but found is still nil
706 ;; (there were no results from the search)
707 (found (auth-source-recall spec))
708 filtered-backends accessor-key backend)
710 (if (and cached auth-source-do-cache)
711 (auth-source-do-debug
712 "auth-source-search: found %d CACHED results matching %S"
716 (or (eq t create) (listp create)) t
717 "Invalid auth-source :create parameter (must be t or a list): %s %s")
721 "Invalid auth-source :require parameter (must be a list): %s")
723 (setq filtered-backends (copy-sequence backends))
724 (dolist (backend backends)
726 ;; ignore invalid slots
727 (condition-case signal
728 (unless (eval `(auth-source-search-collection
730 (oref backend ,key)))
731 (setq filtered-backends (delq backend filtered-backends))
733 (invalid-slot-name))))
735 (auth-source-do-trivia
736 "auth-source-search: found %d backends matching %S"
737 (length filtered-backends) spec)
739 ;; (debug spec "filtered" filtered-backends)
740 ;; First go through all the backends without :create, so we can
742 (setq found (auth-source-search-backends filtered-backends
746 ;; create is always nil here
750 (auth-source-do-debug
751 "auth-source-search: found %d results (max %d) matching %S"
752 (length found) max spec)
754 ;; If we didn't find anything, then we allow the backend(s) to
755 ;; create the entries.
758 (setq found (auth-source-search-backends filtered-backends
764 (auth-source-do-debug
765 "auth-source-search: CREATED %d results (max %d) matching %S"
766 (length found) max spec))
768 ;; note we remember the lack of result too, if it's applicable
769 (when auth-source-do-cache
770 (auth-source-remember spec found)))
774 (defun auth-source-search-backends (backends spec max create delete require)
776 (dolist (backend backends)
777 (when (> max (length matches)) ; when we need more matches...
778 (let* ((bmatches (apply
779 (slot-value backend 'search-function)
781 :type (slot-value backend :type)
782 ;; note we're overriding whatever the spec
783 ;; has for :require, :create, and :delete
789 (auth-source-do-trivia
790 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
791 (length bmatches) max
792 (slot-value backend :type)
793 (slot-value backend :source)
795 (setq matches (append matches bmatches))))))
798 ;; (auth-source-search :max 1)
799 ;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
800 ;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
801 ;; (auth-source-search :host "nonesuch" :type 'secrets)
803 (defun* auth-source-delete (&rest spec
806 "Delete entries from the authentication backends according to SPEC.
807 Calls `auth-source-search' with the :delete property in SPEC set to t.
808 The backend may not actually delete the entries.
810 Returns the deleted entries."
811 (auth-source-search (plist-put spec :delete t)))
813 (defun auth-source-search-collection (collection value)
814 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
815 (when (and (atom collection) (not (eq t collection)))
816 (setq collection (list collection)))
818 ;; (debug :collection collection :value value)
819 (or (eq collection t)
821 (equal collection value)
822 (member value collection)))
824 (defvar auth-source-netrc-cache nil)
826 (defun auth-source-forget-all-cached ()
827 "Forget all cached auth-source data."
829 (loop for sym being the symbols of password-data
830 ;; when the symbol name starts with auth-source-magic
831 when (string-match (concat "^" auth-source-magic)
834 do (password-cache-remove (symbol-name sym)))
835 (setq auth-source-netrc-cache nil))
837 (defun auth-source-format-cache-entry (spec)
838 "Format SPEC entry to put it in the password cache."
839 (concat auth-source-magic (format "%S" spec)))
841 (defun auth-source-remember (spec found)
842 "Remember FOUND search results for SPEC."
843 (let ((password-cache-expiry auth-source-cache-expiry))
845 (auth-source-format-cache-entry spec) found)))
847 (defun auth-source-recall (spec)
848 "Recall FOUND search results for SPEC."
849 (password-read-from-cache (auth-source-format-cache-entry spec)))
851 (defun auth-source-remembered-p (spec)
852 "Check if SPEC is remembered."
854 (auth-source-format-cache-entry spec)))
856 (defun auth-source-forget (spec)
857 "Forget any cached data matching SPEC exactly.
859 This is the same SPEC you passed to `auth-source-search'.
860 Returns t or nil for forgotten or not found."
861 (password-cache-remove (auth-source-format-cache-entry spec)))
863 ;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
865 ;; (auth-source-remember '(:host "wedd") '(4 5 6))
866 ;; (auth-source-remembered-p '(:host "wedd"))
867 ;; (auth-source-remember '(:host "xedd") '(1 2 3))
868 ;; (auth-source-remembered-p '(:host "xedd"))
869 ;; (auth-source-remembered-p '(:host "zedd"))
870 ;; (auth-source-recall '(:host "xedd"))
871 ;; (auth-source-recall '(:host t))
872 ;; (auth-source-forget+ :host t)
874 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
875 "Forget any cached data matching SPEC. Returns forgotten count.
877 This is not a full `auth-source-search' spec but works similarly.
878 For instance, \(:host \"myhost\" \"yourhost\") would find all the
879 cached data that was found with a search for those two hosts,
880 while \(:host t) would find all host entries."
883 (loop for sym being the symbols of password-data
884 ;; when the symbol name matches with auth-source-magic
885 when (and (setq sname (symbol-name sym))
886 (string-match (concat "^" auth-source-magic "\\(.+\\)")
888 ;; and the spec matches what was stored in the cache
889 (auth-source-specmatchp spec (read (match-string 1 sname))))
892 (password-cache-remove sname)
896 (defun auth-source-specmatchp (spec stored)
897 (let ((keys (loop for i below (length spec) by 2
898 collect (nth i spec))))
901 (unless (auth-source-search-collection (plist-get stored key)
902 (plist-get spec key))
906 ;; (auth-source-pick-first-password :host "z.lifelogs.com")
907 ;; (auth-source-pick-first-password :port "imap")
908 (defun auth-source-pick-first-password (&rest spec)
909 "Pick the first secret found from applying SPEC to `auth-source-search'."
910 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
911 (secret (plist-get result :secret)))
913 (if (functionp secret)
917 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
918 (defun auth-source-format-prompt (prompt alist)
919 "Format PROMPT using %x (for any character x) specifiers in ALIST."
921 (let ((c (nth 0 cell))
924 (setq prompt (replace-regexp-in-string (format "%%%c" c)
929 (defun auth-source-ensure-strings (values)
930 (unless (listp values)
931 (setq values (list values)))
932 (mapcar (lambda (value)
938 ;;; Backend specific parsing: netrc/authinfo backend
940 (defun auth-source--aput-1 (alist key val)
943 (while (and (consp rest) (not (equal key (caar rest))))
944 (push (pop rest) seen))
946 (if (null rest) alist
947 (nconc (nreverse seen)
948 (if (equal key (caar rest)) (cdr rest) rest))))))
949 (defmacro auth-source--aput (var key val)
950 `(setq ,var (auth-source--aput-1 ,var ,key ,val)))
952 (defun auth-source--aget (alist key)
953 (cdr (assoc key alist)))
955 ;; (auth-source-netrc-parse "~/.authinfo.gpg")
956 (defun* auth-source-netrc-parse (&rest
958 &key file max host user port delete require
960 "Parse FILE and return a list of all entries in the file.
961 Note that the MAX parameter is used so we can exit the parse early."
963 ;; We got already parsed contents; just return it.
965 (when (file-exists-p file)
966 (setq port (auth-source-ensure-strings port))
968 (let* ((tokens '("machine" "host" "default" "login" "user"
969 "password" "account" "macdef" "force"
971 (max (or max 5000)) ; sanity check: default to stop at 5K
973 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
974 (cached-mtime (plist-get cached :mtime))
975 (cached-secrets (plist-get cached :secret))
976 alist elem result pair)
978 (if (and (functionp cached-secrets)
980 (nth 5 (file-attributes file))))
982 (auth-source-do-trivia
983 "auth-source-netrc-parse: using CACHED file data for %s"
985 (insert (funcall cached-secrets)))
986 (insert-file-contents file)
987 ;; cache all netrc files (used to be just .gpg files)
988 ;; Store the contents of the file heavily encrypted in memory.
989 ;; (note for the irony-impaired: they are just obfuscated)
991 auth-source-netrc-cache file
992 (list :mtime (nth 5 (file-attributes file))
993 :secret (lexical-let ((v (mapcar '1+ (buffer-string))))
994 (lambda () (apply 'string (mapcar '1- v)))))))
995 (goto-char (point-min))
996 ;; Go through the file, line by line.
997 (while (and (not (eobp))
1000 (narrow-to-region (point) (point-at-eol))
1001 ;; For each line, get the tokens and values.
1003 (skip-chars-forward "\t ")
1004 ;; Skip lines that begin with a "#".
1005 (if (eq (char-after) ?#)
1006 (goto-char (point-max))
1009 (if (= (following-char) ?\")
1010 (read (current-buffer))
1012 (point) (progn (skip-chars-forward "^\t ")
1015 ((equal elem "macdef")
1016 ;; We skip past the macro definition.
1018 (while (and (zerop (forward-line 1))
1020 (narrow-to-region (point) (point)))
1021 ((and (member elem tokens) (null pair))
1022 ;; Tokens that don't have a following value are ignored,
1023 ;; except "default".
1024 (when (and pair (or (cdr pair)
1025 (equal (car pair) "default")))
1027 (setq pair (list elem)))
1029 ;; Values that haven't got a preceding token are ignored.
1033 (setq pair nil)))))))
1037 (auth-source-search-collection
1040 (auth-source--aget alist "machine")
1041 (auth-source--aget alist "host")
1043 (auth-source-search-collection
1046 (auth-source--aget alist "login")
1047 (auth-source--aget alist "account")
1048 (auth-source--aget alist "user")
1050 (auth-source-search-collection
1053 (auth-source--aget alist "port")
1054 (auth-source--aget alist "protocol")
1057 ;; the required list of keys is nil, or
1059 ;; every element of require is in the normalized list
1060 (let ((normalized (nth 0 (auth-source-netrc-normalize
1061 (list alist) file))))
1062 (loop for req in require
1063 always (plist-get normalized req)))))
1065 (push (nreverse alist) result)
1066 ;; to delete a line, we just comment it out
1068 (goto-char (point-min))
1076 (when (< 0 modified)
1077 (when auth-source-gpg-encrypt-to
1078 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1079 ;; this buffer lets epa-file skip the key selection query
1080 ;; (see the `local-variable-p' check in
1081 ;; `epa-file-write-region').
1082 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1083 (make-local-variable 'epa-file-encrypt-to))
1084 (if (listp auth-source-gpg-encrypt-to)
1085 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1087 ;; ask AFTER we've successfully opened the file
1088 (when (y-or-n-p (format "Save file %s? (%d deletions)"
1090 (write-region (point-min) (point-max) file nil 'silent)
1091 (auth-source-do-debug
1092 "auth-source-netrc-parse: modified %d lines in %s"
1095 (nreverse result))))))
1097 (defvar auth-source-passphrase-alist nil)
1099 (defun auth-source-token-passphrase-callback-function (context key-id file)
1100 (let* ((file (file-truename file))
1101 (entry (assoc file auth-source-passphrase-alist))
1103 ;; return the saved passphrase, calling a function if needed
1104 (or (copy-sequence (if (functionp (cdr entry))
1105 (funcall (cdr entry))
1109 (setq entry (list file))
1110 (push entry auth-source-passphrase-alist))
1113 (format "Passphrase for %s tokens: " file)
1115 (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1119 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1120 (defun auth-source-epa-extract-gpg-token (secret file)
1121 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1122 FILE is the file from which we obtained this token."
1123 (when (string-match "^gpg:\\(.+\\)" secret)
1124 (setq secret (base64-decode-string (match-string 1 secret))))
1125 (let ((context (epg-make-context 'OpenPGP))
1127 (epg-context-set-passphrase-callback
1129 (cons #'auth-source-token-passphrase-callback-function
1131 (epg-decrypt-string context secret)))
1133 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1134 (defun auth-source-epa-make-gpg-token (secret file)
1135 (let ((context (epg-make-context 'OpenPGP))
1136 (pp-escape-newlines nil)
1138 (epg-context-set-armor context t)
1139 (epg-context-set-passphrase-callback
1141 (cons #'auth-source-token-passphrase-callback-function
1143 (setq cipher (epg-encrypt-string context secret nil))
1146 (base64-encode-region (point-min) (point-max) t)
1147 (concat "gpg:" (buffer-substring-no-properties
1151 (defun auth-source-netrc-normalize (alist filename)
1152 (mapcar (lambda (entry)
1154 (while (setq item (pop entry))
1155 (let ((k (car item))
1158 ;; apply key aliases
1159 (setq k (cond ((member k '("machine")) "host")
1160 ((member k '("login" "account")) "user")
1161 ((member k '("protocol")) "port")
1162 ((member k '("password")) "secret")
1165 ;; send back the secret in a function (lexical binding)
1166 (when (equal k "secret")
1167 (setq v (lexical-let ((lexv v)
1168 (token-decoder nil))
1169 (when (string-match "^gpg:" lexv)
1170 ;; it's a GPG token: create a token decoder
1171 ;; which unsets itself once
1175 (auth-source-epa-extract-gpg-token
1178 (setq token-decoder nil)))))
1181 (setq lexv (funcall token-decoder lexv)))
1183 (setq ret (plist-put ret
1184 (intern (concat ":" k))
1189 ;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1192 (defun* auth-source-netrc-search (&rest
1194 &key backend require create delete
1195 type max host user port
1197 "Given a property list SPEC, return search matches from the :backend.
1198 See `auth-source-search' for details on SPEC."
1199 ;; just in case, check that the type is correct (null or same as the backend)
1200 (assert (or (null type) (eq type (oref backend type)))
1201 t "Invalid netrc search: %s %s")
1203 (let ((results (auth-source-netrc-normalize
1204 (auth-source-netrc-parse
1208 :file (oref backend source)
1212 (oref backend source))))
1214 ;; if we need to create an entry AND none were found to match
1218 ;; create based on the spec and record the value
1220 ;; if the user did not want to create the entry
1221 ;; in the file, it will be returned
1222 (apply (slot-value backend 'create-function) spec)
1223 ;; if not, we do the search again without :create
1224 ;; to get the updated data.
1226 ;; the result will be returned, even if the search fails
1227 (apply 'auth-source-netrc-search
1228 (plist-put spec :create nil)))))
1231 (defun auth-source-netrc-element-or-first (v)
1236 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1237 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1239 (defun* auth-source-netrc-create (&rest spec
1241 secret host user port create
1243 (let* ((base-required '(host user port secret))
1244 ;; we know (because of an assertion in auth-source-search) that the
1245 ;; :create parameter is either t or a list (which includes nil)
1246 (create-extra (if (eq t create) nil create))
1247 (current-data (car (auth-source-search :max 1
1250 (required (append base-required create-extra))
1251 (file (oref backend source))
1253 ;; `valist' is an alist
1255 ;; `artificial' will be returned if no creation is needed
1258 ;; only for base required elements (defined as function parameters):
1259 ;; fill in the valist with whatever data we may have from the search
1260 ;; we complete the first value if it's a list and use the value otherwise
1261 (dolist (br base-required)
1262 (when (symbol-value br)
1263 (let ((br-choice (cond
1264 ;; all-accepting choice (predicate is t)
1265 ((eq t (symbol-value br)) nil)
1266 ;; just the value otherwise
1267 (t (symbol-value br)))))
1269 (auth-source--aput valist br br-choice)))))
1271 ;; for extra required elements, see if the spec includes a value for them
1272 (dolist (er create-extra)
1273 (let ((name (concat ":" (symbol-name er)))
1274 (keys (loop for i below (length spec) by 2
1275 collect (nth i spec))))
1277 (when (equal (symbol-name k) name)
1278 (auth-source--aput valist er (plist-get spec k))))))
1280 ;; for each required element
1281 (dolist (r required)
1282 (let* ((data (auth-source--aget valist r))
1283 ;; take the first element if the data is a list
1284 (data (or (auth-source-netrc-element-or-first data)
1285 (plist-get current-data
1286 (intern (format ":%s" r) obarray))))
1287 ;; this is the default to be offered
1288 (given-default (auth-source--aget
1289 auth-source-creation-defaults r))
1290 ;; the default supplementals are simple:
1291 ;; for the user, try `given-default' and then (user-login-name);
1292 ;; otherwise take `given-default'
1294 ((and (not given-default) (eq r 'user))
1297 (printable-defaults (list
1300 (auth-source-netrc-element-or-first
1301 (auth-source--aget valist 'user))
1302 (plist-get artificial :user)
1306 (auth-source-netrc-element-or-first
1307 (auth-source--aget valist 'host))
1308 (plist-get artificial :host)
1312 (auth-source-netrc-element-or-first
1313 (auth-source--aget valist 'port))
1314 (plist-get artificial :port)
1316 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1318 (secret "%p password for %u@%h: ")
1319 (user "%p user name for %h: ")
1320 (host "%p host name for user %u: ")
1321 (port "%p port for %u@%h: "))
1322 (format "Enter %s (%%u@%%h:%%p): " r)))
1323 (prompt (auth-source-format-prompt
1325 `((?u ,(auth-source--aget printable-defaults 'user))
1326 (?h ,(auth-source--aget printable-defaults 'host))
1327 (?p ,(auth-source--aget printable-defaults 'port))))))
1329 ;; Store the data, prompting for the password if needed.
1332 ;; Special case prompt for passwords.
1333 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") nil) (t gpg)))
1334 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1335 (let* ((ep (format "Use GPG password tokens in %s?" file))
1338 ((eq auth-source-netrc-use-gpg-tokens 'never)
1340 ((listp auth-source-netrc-use-gpg-tokens)
1341 (let ((check (copy-sequence
1342 auth-source-netrc-use-gpg-tokens))
1345 (setq item (pop check))
1346 (when (or (eq (car item) t)
1347 (string-match (car item) file))
1348 (setq ret (cdr item))
1349 (setq check nil)))))
1351 (plain (or (eval default) (read-passwd prompt))))
1352 ;; ask if we don't know what to do (in which case
1353 ;; auth-source-netrc-use-gpg-tokens must be a list)
1355 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1356 ;; TODO: save the defcustom now? or ask?
1357 (setq auth-source-netrc-use-gpg-tokens
1358 (cons `(,file ,gpg-encrypt)
1359 auth-source-netrc-use-gpg-tokens)))
1360 (if (eq gpg-encrypt 'gpg)
1361 (auth-source-epa-make-gpg-token plain file)
1363 (if (stringp default)
1364 (read-string (if (string-match ": *\\'" prompt)
1365 (concat (substring prompt 0 (match-beginning 0))
1366 " (default " default "): ")
1367 (concat prompt "(default " default ") "))
1372 (setq artificial (plist-put artificial
1373 (intern (concat ":" (symbol-name r)))
1375 (lexical-let ((data data))
1379 ;; When r is not an empty string...
1380 (when (and (stringp data)
1381 (< 0 (length data)))
1382 ;; this function is not strictly necessary but I think it
1383 ;; makes the code clearer -tzz
1384 (let ((printer (lambda ()
1385 ;; append the key (the symbol name of r)
1386 ;; and the value in r
1389 (if (zerop (length add)) "" " ")
1390 ;; remap auth-source tokens to netrc
1395 (port "port") ; redundant but clearer
1396 (t (symbol-name r)))
1397 (if (string-match "[\"# ]" data)
1400 (setq add (concat add (funcall printer)))))))
1405 (lexical-let ((file file)
1407 (lambda () (auth-source-netrc-saver file add))))
1411 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1412 (defun auth-source-netrc-saver (file add)
1413 "Save a line ADD in FILE, prompting along the way.
1414 Respects `auth-source-save-behavior'. Uses
1415 `auth-source-netrc-cache' to avoid prompting more than once."
1416 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1417 (cached (assoc key auth-source-netrc-cache)))
1420 (auth-source-do-trivia
1421 "auth-source-netrc-saver: found previous run for key %s, returning"
1424 (when (file-exists-p file)
1425 (insert-file-contents file))
1426 (when auth-source-gpg-encrypt-to
1427 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1428 ;; this buffer lets epa-file skip the key selection query
1429 ;; (see the `local-variable-p' check in
1430 ;; `epa-file-write-region').
1431 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1432 (make-local-variable 'epa-file-encrypt-to))
1433 (if (listp auth-source-gpg-encrypt-to)
1434 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1435 ;; we want the new data to be found first, so insert at beginning
1436 (goto-char (point-min))
1438 ;; Ask AFTER we've successfully opened the file.
1439 (let ((prompt (format "Save auth info to file %s? " file))
1440 (done (not (eq auth-source-save-behavior 'ask)))
1441 (bufname "*auth-source Help*")
1444 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1448 (with-output-to-temp-buffer bufname
1450 (concat "(y)es, save\n"
1451 "(n)o but use the info\n"
1452 "(N)o and don't ask to save again\n"
1454 "(?) for help as you can see.\n"))
1455 ;; Why? Doesn't with-output-to-temp-buffer already do
1456 ;; the exact same thing anyway? --Stef
1457 (set-buffer standard-output)
1464 (customize-save-variable 'auth-source-save-behavior nil))
1465 (?e (setq add (read-string "Line to add: " add)))
1468 (when (get-buffer-window bufname)
1469 (delete-window (get-buffer-window bufname)))
1471 ;; Make sure the info is not saved.
1472 (when (null auth-source-save-behavior)
1475 (when (< 0 (length add))
1480 (write-region (point-min) (point-max) file nil 'silent)
1481 ;; Make the .authinfo file non-world-readable.
1482 (set-file-modes file #o600)
1483 (auth-source-do-debug
1484 "auth-source-netrc-create: wrote 1 new line to %s"
1486 (message "Saved new authentication information to %s" file)
1488 (auth-source--aput auth-source-netrc-cache key "ran"))))
1490 ;;; Backend specific parsing: Secrets API backend
1492 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1493 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1494 ;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1495 ;; (let ((auth-sources '(default))) (auth-source-search))
1496 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1497 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1499 (defun* auth-source-secrets-search (&rest
1501 &key backend create delete label
1502 type max host user port
1504 "Search the Secrets API; spec is like `auth-source'.
1506 The :label key specifies the item's label. It is the only key
1507 that can specify a substring. Any :label value besides a string
1508 will allow any label.
1510 All other search keys must match exactly. If you need substring
1511 matching, do a wider search and narrow it down yourself.
1513 You'll get back all the properties of the token as a plist.
1515 Here's an example that looks for the first item in the 'Login'
1518 \(let ((auth-sources '(\"secrets:Login\")))
1519 (auth-source-search :max 1)
1521 Here's another that looks for the first item in the 'Login'
1522 Secrets collection whose label contains 'gnus':
1524 \(let ((auth-sources '(\"secrets:Login\")))
1525 (auth-source-search :max 1 :label \"gnus\")
1527 And this one looks for the first item in the 'Login' Secrets
1528 collection that's a Google Chrome entry for the git.gnus.org site
1529 authentication tokens:
1531 \(let ((auth-sources '(\"secrets:Login\")))
1532 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1536 (assert (not create) nil
1537 "The Secrets API auth-source backend doesn't support creation yet")
1539 ;; (secrets-delete-item coll elt)
1540 (assert (not delete) nil
1541 "The Secrets API auth-source backend doesn't support deletion yet")
1543 (let* ((coll (oref backend source))
1544 (max (or max 5000)) ; sanity check: default to stop at 5K
1545 (ignored-keys '(:create :delete :max :backend :label :require :type))
1546 (search-keys (loop for i below (length spec) by 2
1547 unless (memq (nth i spec) ignored-keys)
1548 collect (nth i spec)))
1549 ;; build a search spec without the ignored keys
1550 ;; if a search key is nil or t (match anything), we skip it
1551 (search-spec (apply 'append (mapcar
1553 (if (or (null (plist-get spec k))
1554 (eq t (plist-get spec k)))
1556 (list k (plist-get spec k))))
1558 ;; needed keys (always including host, login, port, and secret)
1559 (returned-keys (mm-delete-duplicates (append
1560 '(:host :login :port :secret)
1562 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1563 unless (and (stringp label)
1564 (not (string-match label item)))
1566 ;; TODO: respect max in `secrets-search-items', not after the fact
1567 (items (butlast items (- (length items) max)))
1568 ;; convert the item name to a full plist
1569 (items (mapcar (lambda (item)
1571 ;; make an entry for the secret (password) element
1574 (lexical-let ((v (secrets-get-secret coll item)))
1576 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1578 (mapcar (lambda (entry)
1579 (list (car entry) (cdr entry)))
1580 (secrets-get-attributes coll item)))))
1582 ;; ensure each item has each key in `returned-keys'
1583 (items (mapcar (lambda (plist)
1586 (mapcar (lambda (req)
1587 (if (plist-get plist req)
1595 (defun* auth-source-secrets-create (&rest
1597 &key backend type max host user port
1600 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1603 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1605 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :create t))
1606 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :delete t))
1607 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1))
1608 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search))
1610 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :create t))
1611 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :delete t))
1612 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1))
1613 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search))
1615 ;; (let ((auth-sources '("macos-keychain-internet:/Users/tzz/Library/Keychains/login.keychain"))) (auth-source-search :max 1))
1616 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1 :host "git.gnus.org"))
1618 (defun* auth-source-macos-keychain-search (&rest
1620 &key backend create delete label
1621 type max host user port
1623 "Search the MacOS Keychain; spec is like `auth-source'.
1625 All search keys must match exactly. If you need substring
1626 matching, do a wider search and narrow it down yourself.
1628 You'll get back all the properties of the token as a plist.
1630 The :type key is either 'macos-keychain-internet or
1631 'macos-keychain-generic.
1633 For the internet keychain type, the :label key searches the
1634 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1635 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1636 and :port maps to \"-P PORT\" or \"-r PROT\"
1637 (note PROT has to be a 4-character string).
1639 For the generic keychain type, the :label key searches the item's
1640 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1641 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1642 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1644 Here's an example that looks for the first item in the default
1645 generic MacOS Keychain:
1647 \(let ((auth-sources '(macos-keychain-generic)))
1648 (auth-source-search :max 1)
1650 Here's another that looks for the first item in the internet
1651 MacOS Keychain collection whose label is 'gnus':
1653 \(let ((auth-sources '(macos-keychain-internet)))
1654 (auth-source-search :max 1 :label \"gnus\")
1656 And this one looks for the first item in the internet keychain
1657 entries for git.gnus.org:
1659 \(let ((auth-sources '(macos-keychain-internet\")))
1660 (auth-source-search :max 1 :host \"git.gnus.org\"))
1663 (assert (not create) nil
1664 "The MacOS Keychain auth-source backend doesn't support creation yet")
1666 ;; (macos-keychain-delete-item coll elt)
1667 (assert (not delete) nil
1668 "The MacOS Keychain auth-source backend doesn't support deletion yet")
1670 (let* ((coll (oref backend source))
1671 (max (or max 5000)) ; sanity check: default to stop at 5K
1672 (ignored-keys '(:create :delete :max :backend :label))
1673 (search-keys (loop for i below (length spec) by 2
1674 unless (memq (nth i spec) ignored-keys)
1675 collect (nth i spec)))
1676 ;; build a search spec without the ignored keys
1677 ;; if a search key is nil or t (match anything), we skip it
1678 (search-spec (apply 'append (mapcar
1680 (if (or (null (plist-get spec k))
1681 (eq t (plist-get spec k)))
1683 (list k (plist-get spec k))))
1685 ;; needed keys (always including host, login, port, and secret)
1686 (returned-keys (mm-delete-duplicates (append
1687 '(:host :login :port :secret)
1689 (items (apply 'auth-source-macos-keychain-search-items
1695 ;; ensure each item has each key in `returned-keys'
1696 (items (mapcar (lambda (plist)
1699 (mapcar (lambda (req)
1700 (if (plist-get plist req)
1708 (defun* auth-source-macos-keychain-search-items (coll type max
1714 (let* ((keychain-generic (eq type 'macos-keychain-generic))
1715 (args `(,(if keychain-generic
1716 "find-generic-password"
1717 "find-internet-password")
1719 (ret (list :type type)))
1721 (setq args (append args (list "-l" label))))
1723 (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1725 (setq args (append args (list "-a" user))))
1728 (if keychain-generic
1729 (setq args (append args (list "-s" port)))
1730 (setq args (append args (list
1731 (if (string-match "[0-9]+" port) "-P" "-r")
1734 (unless (equal coll "default")
1735 (setq args (append args (list coll))))
1738 (apply 'call-process "/usr/bin/security" nil t nil args)
1739 (goto-char (point-min))
1742 ((looking-at "^password: \"\\(.+\\)\"$")
1743 (auth-source-macos-keychain-result-append
1747 (lexical-let ((v (match-string 1)))
1749 ;; TODO: check if this is really the label
1750 ;; match 0x00000007 <blob>="AppleID"
1751 ((looking-at "^[ ]+0x00000007 <blob>=\"\\(.+\\)\"")
1752 (auth-source-macos-keychain-result-append
1757 ;; match "crtr"<uint32>="aapl"
1758 ;; match "svce"<blob>="AppleID"
1759 ((looking-at "^[ ]+\"\\([a-z]+\\)\"[^=]+=\"\\(.+\\)\"")
1760 (auth-source-macos-keychain-result-append
1766 ;; return `ret' iff it has the :secret key
1767 (and (plist-get ret :secret) (list ret))))
1769 (defun auth-source-macos-keychain-result-append (result generic k v)
1772 ((equal k "acct") "user")
1773 ;; for generic keychains, creator is host, service is port
1774 ((and generic (equal k "crtr")) "host")
1775 ((and generic (equal k "svce")) "port")
1776 ;; for internet keychains, protocol is port, server is host
1777 ((and (not generic) (equal k "ptcl")) "port")
1778 ((and (not generic) (equal k "srvr")) "host")
1781 (push (intern (format ":%s" k)) result))
1783 (defun* auth-source-macos-keychain-create (&rest
1785 &key backend type max host user port
1790 ;;; Backend specific parsing: PLSTORE backend
1792 (defun* auth-source-plstore-search (&rest
1794 &key backend create delete label
1795 type max host user port
1797 "Search the PLSTORE; spec is like `auth-source'."
1798 (let* ((store (oref backend data))
1799 (max (or max 5000)) ; sanity check: default to stop at 5K
1800 (ignored-keys '(:create :delete :max :backend :label :require :type))
1801 (search-keys (loop for i below (length spec) by 2
1802 unless (memq (nth i spec) ignored-keys)
1803 collect (nth i spec)))
1804 ;; build a search spec without the ignored keys
1805 ;; if a search key is nil or t (match anything), we skip it
1806 (search-spec (apply 'append (mapcar
1808 (let ((v (plist-get spec k)))
1816 ;; needed keys (always including host, login, port, and secret)
1817 (returned-keys (mm-delete-duplicates (append
1818 '(:host :login :port :secret)
1820 (items (plstore-find store search-spec))
1821 (item-names (mapcar #'car items))
1822 (items (butlast items (- (length items) max)))
1823 ;; convert the item to a full plist
1824 (items (mapcar (lambda (item)
1825 (let* ((plist (copy-tree (cdr item)))
1826 (secret (plist-member plist :secret)))
1830 (lexical-let ((v (car (cdr secret))))
1834 ;; ensure each item has each key in `returned-keys'
1835 (items (mapcar (lambda (plist)
1838 (mapcar (lambda (req)
1839 (if (plist-get plist req)
1846 ;; if we need to create an entry AND none were found to match
1850 ;; create based on the spec and record the value
1852 ;; if the user did not want to create the entry
1853 ;; in the file, it will be returned
1854 (apply (slot-value backend 'create-function) spec)
1855 ;; if not, we do the search again without :create
1856 ;; to get the updated data.
1858 ;; the result will be returned, even if the search fails
1859 (apply 'auth-source-plstore-search
1860 (plist-put spec :create nil)))))
1863 (dolist (item-name item-names)
1864 (plstore-delete store item-name))
1865 (plstore-save store)))
1868 (defun* auth-source-plstore-create (&rest spec
1870 secret host user port create
1872 (let* ((base-required '(host user port secret))
1873 (base-secret '(secret))
1874 ;; we know (because of an assertion in auth-source-search) that the
1875 ;; :create parameter is either t or a list (which includes nil)
1876 (create-extra (if (eq t create) nil create))
1877 (current-data (car (auth-source-search :max 1
1880 (required (append base-required create-extra))
1881 (file (oref backend source))
1883 ;; `valist' is an alist
1885 ;; `artificial' will be returned if no creation is needed
1889 ;; only for base required elements (defined as function parameters):
1890 ;; fill in the valist with whatever data we may have from the search
1891 ;; we complete the first value if it's a list and use the value otherwise
1892 (dolist (br base-required)
1893 (when (symbol-value br)
1894 (let ((br-choice (cond
1895 ;; all-accepting choice (predicate is t)
1896 ((eq t (symbol-value br)) nil)
1897 ;; just the value otherwise
1898 (t (symbol-value br)))))
1900 (auth-source--aput valist br br-choice)))))
1902 ;; for extra required elements, see if the spec includes a value for them
1903 (dolist (er create-extra)
1904 (let ((name (concat ":" (symbol-name er)))
1905 (keys (loop for i below (length spec) by 2
1906 collect (nth i spec))))
1908 (when (equal (symbol-name k) name)
1909 (auth-source--aput valist er (plist-get spec k))))))
1911 ;; for each required element
1912 (dolist (r required)
1913 (let* ((data (auth-source--aget valist r))
1914 ;; take the first element if the data is a list
1915 (data (or (auth-source-netrc-element-or-first data)
1916 (plist-get current-data
1917 (intern (format ":%s" r) obarray))))
1918 ;; this is the default to be offered
1919 (given-default (auth-source--aget
1920 auth-source-creation-defaults r))
1921 ;; the default supplementals are simple:
1922 ;; for the user, try `given-default' and then (user-login-name);
1923 ;; otherwise take `given-default'
1925 ((and (not given-default) (eq r 'user))
1928 (printable-defaults (list
1931 (auth-source-netrc-element-or-first
1932 (auth-source--aget valist 'user))
1933 (plist-get artificial :user)
1937 (auth-source-netrc-element-or-first
1938 (auth-source--aget valist 'host))
1939 (plist-get artificial :host)
1943 (auth-source-netrc-element-or-first
1944 (auth-source--aget valist 'port))
1945 (plist-get artificial :port)
1947 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1949 (secret "%p password for %u@%h: ")
1950 (user "%p user name for %h: ")
1951 (host "%p host name for user %u: ")
1952 (port "%p port for %u@%h: "))
1953 (format "Enter %s (%%u@%%h:%%p): " r)))
1954 (prompt (auth-source-format-prompt
1956 `((?u ,(auth-source--aget printable-defaults 'user))
1957 (?h ,(auth-source--aget printable-defaults 'host))
1958 (?p ,(auth-source--aget printable-defaults 'port))))))
1960 ;; Store the data, prompting for the password if needed.
1963 (or (eval default) (read-passwd prompt))
1964 (if (stringp default)
1966 (if (string-match ": *\\'" prompt)
1967 (concat (substring prompt 0 (match-beginning 0))
1968 " (default " default "): ")
1969 (concat prompt "(default " default ") "))
1974 (if (member r base-secret)
1975 (setq secret-artificial
1976 (plist-put secret-artificial
1977 (intern (concat ":" (symbol-name r)))
1979 (setq artificial (plist-put artificial
1980 (intern (concat ":" (symbol-name r)))
1982 (plstore-put (oref backend data)
1983 (sha1 (format "%s@%s:%s"
1984 (plist-get artificial :user)
1985 (plist-get artificial :host)
1986 (plist-get artificial :port)))
1987 artificial secret-artificial)
1988 (if (y-or-n-p (format "Save auth info to file %s? "
1989 (plstore-get-file (oref backend data))))
1990 (plstore-save (oref backend data)))))
1994 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1996 ;; deprecate the old interface
1997 (make-obsolete 'auth-source-user-or-password
1998 'auth-source-search "Emacs 24.1")
1999 (make-obsolete 'auth-source-forget-user-or-password
2000 'auth-source-forget "Emacs 24.1")
2002 (defun auth-source-user-or-password
2003 (mode host port &optional username create-missing delete-existing)
2004 "Find MODE (string or list of strings) matching HOST and PORT.
2006 DEPRECATED in favor of `auth-source-search'!
2008 USERNAME is optional and will be used as \"login\" in a search
2009 across the Secret Service API (see secrets.el) if the resulting
2010 items don't have a username. This means that if you search for
2011 username \"joe\" and it matches an item but the item doesn't have
2012 a :user attribute, the username \"joe\" will be returned.
2014 A non nil DELETE-EXISTING means deleting any matching password
2015 entry in the respective sources. This is useful only when
2016 CREATE-MISSING is non nil as well; the intended use case is to
2017 remove wrong password entries.
2019 If no matching entry is found, and CREATE-MISSING is non nil,
2020 the password will be retrieved interactively, and it will be
2021 stored in the password database which matches best (see
2024 MODE can be \"login\" or \"password\"."
2025 (auth-source-do-debug
2026 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2027 mode host port username)
2029 (let* ((listy (listp mode))
2030 (mode (if listy mode (list mode)))
2032 (format "%s %s:%s %s" mode host port username)
2033 (format "%s %s:%s" mode host port)))
2034 (search (list :host host :port port))
2035 (search (if username (append search (list :user username)) search))
2036 (search (if create-missing
2037 (append search (list :create t))
2039 (search (if delete-existing
2040 (append search (list :delete t))
2042 ;; (found (if (not delete-existing)
2043 ;; (gethash cname auth-source-cache)
2044 ;; (remhash cname auth-source-cache)
2049 (auth-source-do-debug
2050 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2052 ;; don't show the password
2053 (if (and (member "password" mode) t)
2057 found) ; return the found data
2058 ;; else, if not found, search with a max of 1
2059 (let ((choice (nth 0 (apply 'auth-source-search
2060 (append '(:max 1) search)))))
2064 ((equal "password" m)
2065 (push (if (plist-get choice :secret)
2066 (funcall (plist-get choice :secret))
2069 (push (plist-get choice :user) found)))))
2070 (setq found (nreverse found))
2071 (setq found (if listy found (car-safe found)))))
2075 (defun auth-source-user-and-password (host &optional user)
2076 (let* ((auth-info (car
2080 :user "yourusername"
2082 :require '(:user :secret)
2087 :require '(:user :secret)
2089 (user (plist-get auth-info :user))
2090 (password (plist-get auth-info :secret)))
2091 (when (functionp password)
2092 (setq password (funcall password)))
2093 (list user password auth-info)))
2095 (provide 'auth-source)
2097 ;;; auth-source.el ends here