1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2011 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
45 (eval-when-compile (require 'cl))
46 (eval-when-compile (require 'eieio))
48 (autoload 'secrets-create-item "secrets")
49 (autoload 'secrets-delete-item "secrets")
50 (autoload 'secrets-get-alias "secrets")
51 (autoload 'secrets-get-attribute "secrets")
52 (autoload 'secrets-get-secret "secrets")
53 (autoload 'secrets-list-collections "secrets")
54 (autoload 'secrets-search-items "secrets")
56 (defvar secrets-enabled)
58 (defgroup auth-source nil
59 "Authentication sources."
60 :version "23.1" ;; No Gnus
63 (defclass auth-source-backend ()
68 :documentation "The backend type.")
69 (source :initarg :source
72 :documentation "The backend source.")
77 :documentation "The backend host.")
82 :documentation "The backend user.")
83 (protocol :initarg :protocol
87 :documentation "The backend protocol.")
88 (create-function :initarg :create-function
92 :documentation "The create function.")
93 (search-function :initarg :search-function
97 :documentation "The search function.")))
99 ;;(auth-source-backend "netrc" :type 'netrc)
101 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
102 (pop3 "pop3" "pop" "pop3s" "110" "995")
106 "List of authentication protocols and their names"
109 :version "23.2" ;; No Gnus
110 :type '(repeat :tag "Authentication Protocols"
111 (cons :tag "Protocol Entry"
112 (symbol :tag "Protocol")
114 (string :tag "Name")))))
116 ;;; generate all the protocols in a format Customize can use
117 ;;; TODO: generate on the fly from auth-source-protocols
118 (defconst auth-source-protocols-customize
120 (let ((p (car-safe a)))
122 :tag (upcase (symbol-name p))
124 auth-source-protocols))
126 (defvar auth-source-creation-defaults nil
127 "Defaults for creating token values. Usually let-bound.")
129 (defvar auth-source-cache (make-hash-table :test 'equal)
130 "Cache for auth-source data")
132 (defcustom auth-source-do-cache t
133 "Whether auth-source should cache information."
135 :version "23.2" ;; No Gnus
138 (defcustom auth-source-debug nil
139 "Whether auth-source should log debug messages.
140 Also see `auth-source-hide-passwords'.
142 If the value is nil, debug messages are not logged.
143 If the value is t, debug messages are logged with `message'.
144 In that case, your authentication data will be in the
145 clear (except for passwords, which are always stripped out).
146 If the value is a function, debug messages are logged by calling
147 that function using the same arguments as `message'."
149 :version "23.2" ;; No Gnus
151 :tag "auth-source debugging mode"
152 (const :tag "Log using `message' to the *Messages* buffer" t)
153 (function :tag "Function that takes arguments like `message'")
154 (const :tag "Don't log anything" nil)))
156 (defcustom auth-source-hide-passwords t
157 "Whether auth-source should hide passwords in log messages.
158 Only relevant if `auth-source-debug' is not nil."
160 :version "23.2" ;; No Gnus
163 (defcustom auth-sources '("~/.authinfo.gpg" "~/.authinfo")
164 "List of authentication sources.
166 The default will get login and password information from
167 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
168 packages to be encrypted. If that file doesn't exist, it will
169 try the unencrypted version \"~/.authinfo\".
171 See the auth.info manual for details.
173 Each entry is the authentication type with optional properties.
175 It's best to customize this with `M-x customize-variable' because the choices
176 can get pretty complex."
178 :version "24.1" ;; No Gnus
179 :type `(repeat :tag "Authentication Sources"
181 (string :tag "Just a file")
182 (const :tag "Default Secrets API Collection" 'default)
183 (const :tag "Login Secrets API Collection" "secrets:login")
184 (const :tag "Temp Secrets API Collection" "secrets:session")
185 (list :tag "Source definition"
186 (const :format "" :value :source)
187 (choice :tag "Authentication backend choice"
188 (string :tag "Authentication Source (file)")
190 :tag "Secret Service API/KWallet/GNOME Keyring"
191 (const :format "" :value :secrets)
192 (choice :tag "Collection to use"
193 (string :tag "Collection name")
194 (const :tag "Default" 'default)
195 (const :tag "Login" "login")
197 :tag "Temporary" "session"))))
198 (repeat :tag "Extra Parameters" :inline t
199 (choice :tag "Extra parameter"
202 (const :format "" :value :host)
203 (choice :tag "Host (machine) choice"
206 :tag "Regular expression")))
209 (const :format "" :value :protocol)
213 ,@auth-source-protocols-customize))
214 (list :tag "User" :inline t
215 (const :format "" :value :user)
216 (choice :tag "Personality/Username"
218 (string :tag "Name")))))))))
220 (defcustom auth-source-gpg-encrypt-to t
221 "List of recipient keys that `authinfo.gpg' encrypted to.
222 If the value is not a list, symmetric encryption will be used."
224 :version "24.1" ;; No Gnus
225 :type '(choice (const :tag "Symmetric encryption" t)
226 (repeat :tag "Recipient public keys"
227 (string :tag "Recipient public key"))))
229 ;; temp for debugging
230 ;; (unintern 'auth-source-protocols)
231 ;; (unintern 'auth-sources)
232 ;; (customize-variable 'auth-sources)
233 ;; (setq auth-sources nil)
234 ;; (format "%S" auth-sources)
235 ;; (customize-variable 'auth-source-protocols)
236 ;; (setq auth-source-protocols nil)
237 ;; (format "%S" auth-source-protocols)
238 ;; (auth-source-pick nil :host "a" :port 'imap)
239 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
240 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
241 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
242 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
243 ;; (auth-source-protocol-defaults 'imap)
245 ;; (let ((auth-source-debug 'debug)) (auth-source-debug "hello"))
246 ;; (let ((auth-source-debug t)) (auth-source-debug "hello"))
247 ;; (let ((auth-source-debug nil)) (auth-source-debug "hello"))
248 (defun auth-source-do-debug (&rest msg)
249 ;; set logger to either the function in auth-source-debug or 'message
250 ;; note that it will be 'message if auth-source-debug is nil, so
251 ;; we also check the value
252 (when auth-source-debug
253 (let ((logger (if (functionp auth-source-debug)
256 (apply logger msg))))
258 ;; (auth-source-pick nil :host "any" :protocol 'imap :user "joe")
259 ;; (auth-source-pick t :host "any" :protocol 'imap :user "joe")
260 ;; (setq auth-sources '((:source (:secrets default) :host t :protocol t :user "joe")
261 ;; (:source (:secrets "session") :host t :protocol t :user "joe")
262 ;; (:source (:secrets "login") :host t :protocol t)
263 ;; (:source "~/.authinfo.gpg" :host t :protocol t)))
265 ;; (setq auth-sources '((:source (:secrets default) :host t :protocol t :user "joe")
266 ;; (:source (:secrets "session") :host t :protocol t :user "joe")
267 ;; (:source (:secrets "login") :host t :protocol t)
270 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :protocol t)))
272 ;; (auth-source-backend-parse "myfile.gpg")
273 ;; (auth-source-backend-parse 'default)
274 ;; (auth-source-backend-parse "secrets:login")
276 (defun auth-source-backend-parse (entry)
277 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
278 (auth-source-backend-parse-parameters
281 ;; take 'default and recurse to get it as a Secrets API default collection
282 ;; matching any user, host, and protocol
284 (auth-source-backend-parse '(:source (:secrets default))))
285 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
286 ;; matching any user, host, and protocol
287 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
288 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
289 ;; take just a file name and recurse to get it as a netrc file
290 ;; matching any user, host, and protocol
292 (auth-source-backend-parse `(:source ,entry)))
294 ;; a file name with parameters
295 ((stringp (plist-get entry :source))
297 (plist-get entry :source)
298 :source (plist-get entry :source)
300 :search-function 'auth-source-netrc-search
301 :create-function 'auth-source-netrc-create))
303 ;; the Secrets API. We require the package, in order to have a
304 ;; defined value for `secrets-enabled'.
306 (not (null (plist-get entry :source))) ; the source must not be nil
307 (listp (plist-get entry :source)) ; and it must be a list
308 (require 'secrets nil t) ; and we must load the Secrets API
309 secrets-enabled) ; and that API must be enabled
311 ;; the source is either the :secrets key in ENTRY or
312 ;; if that's missing or nil, it's "session"
313 (let ((source (or (plist-get (plist-get entry :source) :secrets)
316 ;; if the source is a symbol, we look for the alias named so,
317 ;; and if that alias is missing, we use "login"
318 (when (symbolp source)
319 (setq source (or (secrets-get-alias (symbol-name source))
323 (format "Secrets API (%s)" source)
326 :search-function 'auth-source-secrets-search
327 :create-function 'auth-source-secrets-create)))
331 (auth-source-do-debug
332 "auth-source-backend-parse: invalid backend spec: %S" entry)
338 (defun auth-source-backend-parse-parameters (entry backend)
339 "Fills in the extra auth-source-backend parameters of ENTRY.
340 Using the plist ENTRY, get the :host, :protocol, and :user search
341 parameters. Accepts :port as an alias to :protocol. Sets all
342 the parameters to t if they are missing."
344 (when (setq val (plist-get entry :host))
345 (oset backend host val))
346 (when (setq val (plist-get entry :user))
347 (oset backend user val))
348 ;; accept :port as an alias for :protocol
349 (when (setq val (or (plist-get entry :protocol) (plist-get entry :port)))
350 (oset backend protocol val)))
353 ;; (mapcar 'auth-source-backend-parse auth-sources)
355 (defun* auth-source-search (&rest spec
356 &key type max host user protocol secret
359 "Search or modify authentication backends according to SPEC.
361 This function parses `auth-sources' for matches of the SPEC
362 plist. It can optionally create or update an authentication
363 token if requested. A token is just a standard Emacs property
364 list with a :secret property that can be a function; all the
365 other properties will always hold scalar values.
367 Typically the :secret property, if present, contains a password.
369 Common search keys are :max, :host, :protocol, and :user. In
370 addition, :create specifies how tokens will be or created.
371 Finally, :type can specify which backend types you want to check.
373 A string value is always matched literally. A symbol is matched
374 as its string value, literally. All the SPEC values can be
375 single values (symbol or string) or lists thereof (in which case
376 any of the search terms matches).
378 :create t means to create a token if possible.
380 A new token will be created if no matching tokens were found.
381 The new token will have only the keys the backend requires. For
382 the netrc backend, for instance, that's the user, host, and
387 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
388 (A . \"default A\"))))
389 (auth-source-search :host \"mine\" :type 'netrc :max 1
390 :P \"pppp\" :Q \"qqqq\"
395 \"Search for any entry matching host 'mine' in backends of type
396 'netrc', maximum one result.
398 Create a new entry if you found none. The netrc backend will
399 automatically require host, user, and protocol. The host will be
400 'mine'. We prompt for the user with default 'defaultUser' and
401 for the protocol without a default. We will not prompt for A, Q,
402 or P. The resulting token will only have keys user, host, and
405 :create '(A B C) also means to create a token if possible.
407 The behavior is like :create t but if the list contains any
408 parameter, that parameter will be required in the resulting
409 token. The value for that parameter will be obtained from the
410 search parameters or from user input. If any queries are needed,
411 the alist `auth-source-creation-defaults' will be checked for the
416 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
417 (A . \"default A\"))))
418 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
419 :P \"pppp\" :Q \"qqqq\"
424 \"Search for any entry matching host 'nonesuch'
425 or 'twosuch' in backends of type 'netrc', maximum one result.
427 Create a new entry if you found none. The netrc backend will
428 automatically require host, user, and protocol. The host will be
429 'nonesuch' and Q will be 'qqqq'. We prompt for A with default
430 'default A', for B and protocol with default nil, and for the
431 user with default 'defaultUser'. We will not prompt for Q. The
432 resulting token will have keys user, host, protocol, A, B, and Q.
433 It will not have P with any value, even though P is used in the
434 search to find only entries that have P set to 'pppp'.\"
436 When multiple values are specified in the search parameter, the
437 first one is used for creation. So :host (X Y Z) would create a
438 token for host X, for instance.
440 This creation can fail if the search was not specific enough to
441 create a new token (it's up to the backend to decide that). You
442 should `catch' the backend-specific error as usual. Some
443 backends (netrc, at least) will prompt the user rather than throw
446 :delete t means to delete any found entries. nil by default.
447 Use `auth-source-delete' in ELisp code instead of calling
448 `auth-source-search' directly with this parameter.
450 :type (X Y Z) will check only those backend types. 'netrc and
451 'secrets are the only ones supported right now.
453 :max N means to try to return at most N items (defaults to 1).
454 When 0 the function will return just t or nil to indicate if any
455 matches were found. More than N items may be returned, depending
456 on the search and the backend.
458 :host (X Y Z) means to match only hosts X, Y, or Z according to
459 the match rules above. Defaults to t.
461 :user (X Y Z) means to match only users X, Y, or Z according to
462 the match rules above. Defaults to t.
464 :protocol (P Q R) means to match only protocols P, Q, or R.
467 :K (V1 V2 V3) for any other key K will match values V1, V2, or
468 V3 (note the match rules above).
470 The return value is a list with at most :max tokens. Each token
471 is a plist with keys :backend :host :protocol :user, plus any other
472 keys provided by the backend (notably :secret). But note the
473 exception for :max 0, which see above.
475 The token's :secret key can hold a function. In that case you
476 must call it to obtain the actual value."
477 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
479 (ignored-keys '(:create :delete :max))
480 (keys (loop for i below (length spec) by 2
481 unless (memq (nth i spec) ignored-keys)
482 collect (nth i spec)))
483 filtered-backends accessor-key found-here found goal)
484 (assert (or (eq t create) (listp create)) t
485 "Invalid auth-source :create parameter (must be nil, t, or a list)")
487 (setq filtered-backends (copy-list backends))
488 (dolist (backend backends)
490 ;; ignore invalid slots
491 (condition-case signal
492 (unless (eval `(auth-source-search-collection
494 (oref backend ,key)))
495 (setq filtered-backends (delq backend filtered-backends))
497 (invalid-slot-name))))
499 (auth-source-do-debug
500 "auth-source-search: found %d backends matching %S"
501 (length filtered-backends) spec)
503 ;; (debug spec "filtered" filtered-backends)
505 (dolist (backend filtered-backends)
506 (setq found-here (apply
507 (slot-value backend 'search-function)
513 ;; if max is 0, as soon as we find something, return it
514 (when (and (zerop max) (> 0 (length found-here)))
517 ;; decrement the goal by the number of new results
518 (decf goal (length found-here))
519 ;; and append the new results to the full list
520 (setq found (append found found-here))
522 (auth-source-do-debug
523 "auth-source-search: found %d results (max %d/%d) in %S matching %S"
524 (length found-here) max goal backend spec)
526 ;; return full list if the goal is 0 or negative
527 (when (zerop (max 0 goal))
530 ;; change the :max parameter in the spec to the goal
531 (setq spec (plist-put spec :max goal)))
534 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
535 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
537 (defun* auth-source-delete (&rest spec
540 "Delete entries from the authentication backends according to SPEC.
541 Calls `auth-source-search' with the :delete property in SPEC set to t.
542 The backend may not actually delete the entries.
544 Returns the deleted entries."
545 (auth-source-search (plist-put spec :delete t)))
547 (defun auth-source-search-collection (collection value)
548 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
549 (when (and (atom collection) (not (eq t collection)))
550 (setq collection (list collection)))
552 ;; (debug :collection collection :value value)
553 (or (eq collection t)
555 (equal collection value)
556 (member value collection)))
558 ;;; Backend specific parsing: netrc/authinfo backend
560 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
561 (defun* auth-source-netrc-parse (&rest
563 &key file max host user protocol delete
565 "Parse FILE and return a list of all entries in the file.
566 Note that the MAX parameter is used so we can exit the parse early."
568 ;; We got already parsed contents; just return it.
570 (when (file-exists-p file)
572 (let ((tokens '("machine" "host" "default" "login" "user"
573 "password" "account" "macdef" "force"
575 (max (or max 5000)) ; sanity check: default to stop at 5K
577 alist elem result pair)
578 (insert-file-contents file)
579 (goto-char (point-min))
580 ;; Go through the file, line by line.
581 (while (and (not (eobp))
584 (narrow-to-region (point) (point-at-eol))
585 ;; For each line, get the tokens and values.
587 (skip-chars-forward "\t ")
588 ;; Skip lines that begin with a "#".
589 (if (eq (char-after) ?#)
590 (goto-char (point-max))
593 (if (= (following-char) ?\")
594 (read (current-buffer))
596 (point) (progn (skip-chars-forward "^\t ")
599 ((equal elem "macdef")
600 ;; We skip past the macro definition.
602 (while (and (zerop (forward-line 1))
604 (narrow-to-region (point) (point)))
605 ((member elem tokens)
606 ;; Tokens that don't have a following value are ignored,
608 (when (and pair (or (cdr pair)
609 (equal (car pair) "default")))
611 (setq pair (list elem)))
613 ;; Values that haven't got a preceding token are ignored.
617 (setq pair nil)))))))
621 (auth-source-search-collection
624 (aget alist "machine")
625 (aget alist "host")))
626 (auth-source-search-collection
630 (aget alist "account")
631 (aget alist "user")))
632 (auth-source-search-collection
636 (aget alist "protocol"))))
638 (push (nreverse alist) result)
639 ;; to delete a line, we just comment it out
641 (goto-char (point-min))
650 (when auth-source-gpg-encrypt-to
651 ;; (see bug#7487) making `epa-file-encrypt-to' local to
652 ;; this buffer lets epa-file skip the key selection query
653 ;; (see the `local-variable-p' check in
654 ;; `epa-file-write-region').
655 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
656 (make-local-variable 'epa-file-encrypt-to))
657 (if (listp auth-source-gpg-encrypt-to)
658 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
660 ;; ask AFTER we've successfully opened the file
661 (when (y-or-n-p (format "Save file %s? (%d modifications)"
663 (write-region (point-min) (point-max) file nil 'silent)
664 (auth-source-do-debug
665 "auth-source-netrc-parse: modified %d lines in %s"
668 (nreverse result))))))
670 (defun auth-source-netrc-normalize (alist)
671 (mapcar (lambda (entry)
673 (while (setq item (pop entry))
678 (setq k (cond ((member k '("machine")) "host")
679 ((member k '("login" "account")) "user")
680 ((member k '("protocol")) "port")
681 ((member k '("password")) "secret")
684 ;; send back the secret in a function (lexical binding)
685 (when (equal k "secret")
686 (setq v (lexical-let ((v v))
689 (setq ret (plist-put ret
690 (intern (concat ":" k))
696 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
699 (defun* auth-source-netrc-search (&rest
701 &key backend create delete
702 type max host user protocol
704 "Given a property list SPEC, return search matches from the :backend.
705 See `auth-source-search' for details on SPEC."
706 ;; just in case, check that the type is correct (null or same as the backend)
707 (assert (or (null type) (eq type (oref backend type)))
708 t "Invalid netrc search")
710 (let ((results (auth-source-netrc-normalize
711 (auth-source-netrc-parse
714 :file (oref backend source)
717 :protocol (or protocol t)))))
719 ;; if we need to create an entry AND none were found to match
721 (= 0 (length results)))
723 ;; create based on the spec
724 (apply (slot-value backend 'create-function) spec)
725 ;; turn off the :create key
726 (setq spec (plist-put spec :create nil))
727 ;; run the search again to get the updated data
728 ;; the result will be returned, even if the search fails
729 (setq results (apply 'auth-source-netrc-search spec)))
733 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
734 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
736 (defun* auth-source-netrc-create (&rest spec
738 secret host user protocol create
740 (let* ((base-required '(host user protocol secret))
741 ;; we know (because of an assertion in auth-source-search) that the
742 ;; :create parameter is either t or a list (which includes nil)
743 (create-extra (if (eq t create) nil create))
744 (required (append base-required create-extra))
745 (file (oref backend source))
747 ;; `valist' is an alist
750 ;; only for base required elements (defined as function parameters):
751 ;; fill in the valist with whatever data we may have from the search
752 ;; we take the first value if it's a list, the whole value otherwise
753 (dolist (br base-required)
754 (when (symbol-value br)
755 (aput 'valist br (if (listp (symbol-value br))
756 (nth 0 (symbol-value br))
757 (symbol-value br)))))
759 ;; for extra required elements, see if the spec includes a value for them
760 (dolist (er create-extra)
761 (let ((name (concat ":" (symbol-name er)))
762 (keys (loop for i below (length spec) by 2
763 collect (nth i spec))))
765 (when (equal (symbol-name k) name)
766 (aput 'valist er (plist-get spec k))))))
768 ;; for each required element
770 (let* ((data (aget valist r))
771 (given-default (aget auth-source-creation-defaults r))
772 ;; the defaults are simple
774 ((and (not given-default) (eq r 'user))
776 ;; note we need this empty string
777 ((and (not given-default) (eq r 'protocol))
780 ;; the prompt's default string depends on the data so far
781 (default-string (if (and default (< 0 (length default)))
782 (format " (default %s)" default)
784 ;; the prompt should also show what's entered so far
785 (user-value (aget valist 'user))
786 (host-value (aget valist 'host))
787 (protocol-value (aget valist 'protocol))
788 (info-so-far (concat (if user-value
789 (format "%s@" user-value)
792 (format "%s" host-value)
795 ;; this distinguishes protocol between
796 (if (zerop (length protocol-value))
797 "" ; 'entered as "no default"' vs.
798 (format ":%s" protocol-value)) ; given
799 ;; and this is when the protocol is unknown
802 ;; now prompt if the search SPEC did not include a required key;
803 ;; take the result and put it in `data' AND store it in `valist'
807 ((and (null data) (eq r 'secret))
808 ;; special case prompt for passwords
809 (read-passwd (format "Password for %s: " info-so-far)))
812 (format "Enter %s for %s%s: "
813 r info-so-far default-string)
817 ;; when r is not an empty string...
818 (when (and (stringp data)
820 ;; append the key (the symbol name of r) and the value in r
821 (setq add (concat add
824 (if (zerop (length add)) "" " ")
825 ;; remap auth-source tokens to netrc
832 ;; the value will be printed in %S format
836 (when (file-exists-p file)
837 (insert-file-contents file))
838 (when auth-source-gpg-encrypt-to
839 ;; (see bug#7487) making `epa-file-encrypt-to' local to
840 ;; this buffer lets epa-file skip the key selection query
841 ;; (see the `local-variable-p' check in
842 ;; `epa-file-write-region').
843 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
844 (make-local-variable 'epa-file-encrypt-to))
845 (if (listp auth-source-gpg-encrypt-to)
846 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
847 (goto-char (point-max))
849 ;; ask AFTER we've successfully opened the file
850 (when (y-or-n-p (format "Add to file %s: line [%s]" file add))
854 (write-region (point-min) (point-max) file nil 'silent)
855 (auth-source-do-debug
856 "auth-source-netrc-create: wrote 1 new line to %s"
859 ;;; Backend specific parsing: Secrets API backend
861 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
862 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
863 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
864 ;;; (let ((auth-sources '("secrets:login"))) (auth-source-search :max 1))
865 ;;; (let ((auth-sources '("secrets:login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
867 (defun* auth-source-secrets-search (&rest
869 &key backend create delete label
870 type max host user protocol
872 "Search the Secrets API; spec is like `auth-source'.
874 The :label key specifies the item's label. It is the only key
875 that can specify a substring. Any :label value besides a string
876 will allow any label.
878 All other search keys must match exactly. If you need substring
879 matching, do a wider search and narrow it down yourself.
881 You'll get back all the properties of the token as a plist.
883 Here's an example that looks for the first item in the 'login'
886 \(let ((auth-sources '(\"secrets:login\")))
887 (auth-source-search :max 1)
889 Here's another that looks for the first item in the 'login'
890 Secrets collection whose label contains 'gnus':
892 \(let ((auth-sources '(\"secrets:login\")))
893 (auth-source-search :max 1 :label \"gnus\")
895 And this one looks for the first item in the 'login' Secrets
896 collection that's a Google Chrome entry for the git.gnus.org site
899 \(let ((auth-sources '(\"secrets:login\")))
900 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
904 (assert (not create) nil
905 "The Secrets API auth-source backend doesn't support creation yet")
907 ;; (secrets-delete-item coll elt)
908 (assert (not delete) nil
909 "The Secrets API auth-source backend doesn't support deletion yet")
911 (let* ((coll (oref backend source))
912 (max (or max 5000)) ; sanity check: default to stop at 5K
913 (ignored-keys '(:create :delete :max :backend :label))
914 (search-keys (loop for i below (length spec) by 2
915 unless (memq (nth i spec) ignored-keys)
916 collect (nth i spec)))
917 ;; build a search spec without the ignored keys
918 ;; if a search key is nil or t (match anything), we skip it
919 (search-spec (mapcan (lambda (k) (if (or (null (plist-get spec k))
920 (eq t (plist-get spec k)))
922 (list k (plist-get spec k))))
924 ;; needed keys (always including host, login, protocol, and secret)
925 (returned-keys (remove-duplicates (append
926 '(:host :login :protocol :secret)
928 (items (loop for item in (apply 'secrets-search-items coll search-spec)
929 unless (and (stringp label)
930 (not (string-match label item)))
932 ;; TODO: respect max in `secrets-search-items', not after the fact
933 (items (subseq items 0 max))
934 ;; convert the item name to a full plist
935 (items (mapcar (lambda (item)
937 ;; make an entry for the secret (password) element
940 (lexical-let ((v (secrets-get-secret coll item)))
942 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
943 (mapcan (lambda (entry)
944 (list (car entry) (cdr entry)))
945 (secrets-get-attributes coll item))))
947 ;; ensure each item has each key in `returned-keys'
948 (items (mapcar (lambda (plist)
950 (mapcan (lambda (req)
951 (if (plist-get plist req)
959 (defun* auth-source-secrets-create (&rest
961 &key backend type max host user protocol
964 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
969 (defun auth-source-forget-user-or-password
970 (mode host protocol &optional username)
971 "Remove cached authentication token."
972 (interactive "slogin/password: \nsHost: \nsProtocol: \n") ;for testing
975 (format "%s %s:%s %s" mode host protocol username)
976 (format "%s %s:%s" mode host protocol))
979 (defun auth-source-forget-all-cached ()
980 "Forget all cached auth-source authentication tokens."
982 (setq auth-source-cache (make-hash-table :test 'equal)))
985 ;; (auth-source-forget-all-cached)
987 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" "other")
988 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" "other" "tzz")
989 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" "other" "joe")))
991 ;; deprecate this interface
992 (make-obsolete 'auth-source-user-or-password 'auth-source-search "Emacs 24.1")
994 (defun auth-source-user-or-password
995 (mode host protocol &optional username create-missing delete-existing)
996 "Find MODE (string or list of strings) matching HOST and PROTOCOL.
998 DEPRECATED in favor of `auth-source-search'!
1000 USERNAME is optional and will be used as \"login\" in a search
1001 across the Secret Service API (see secrets.el) if the resulting
1002 items don't have a username. This means that if you search for
1003 username \"joe\" and it matches an item but the item doesn't have
1004 a :user attribute, the username \"joe\" will be returned.
1006 A non nil DELETE-EXISTING means deleting any matching password
1007 entry in the respective sources. This is useful only when
1008 CREATE-MISSING is non nil as well; the intended use case is to
1009 remove wrong password entries.
1011 If no matching entry is found, and CREATE-MISSING is non nil,
1012 the password will be retrieved interactively, and it will be
1013 stored in the password database which matches best (see
1016 MODE can be \"login\" or \"password\"."
1017 (auth-source-do-debug
1018 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1019 mode host protocol username)
1020 (let* ((listy (listp mode))
1021 (mode (if listy mode (list mode)))
1023 (format "%s %s:%s %s" mode host protocol username)
1024 (format "%s %s:%s" mode host protocol)))
1025 (search (list :host host :protocol protocol))
1026 (search (if username (append search (list :user username)) search))
1027 (search (if create-missing
1028 (append search (list :create t))
1030 (search (if delete-existing
1031 (append search (list :delete t))
1033 (found (if (not delete-existing)
1034 (gethash cname auth-source-cache)
1035 (remhash cname auth-source-cache)
1039 (auth-source-do-debug
1040 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1042 ;; don't show the password
1043 (if (and (member "password" mode) auth-source-hide-passwords)
1046 host protocol username)
1047 found) ; return the found data
1048 ;; else, if not found, search with a max of 1
1049 (let ((choice (nth 0 (apply 'auth-source-search
1050 (nconc '(:max 1) search)))))
1052 (when (member "password" mode)
1053 (push (funcall (plist-get :secret choice)) found))
1054 (when (member "login" mode)
1055 (push (funcall (plist-get :user choice)) found)))
1056 (setq found (if listy found (car-safe found)))))
1060 (provide 'auth-source)
1062 ;;; auth-source.el ends here