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
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 (defvar secrets-enabled)
69 (defgroup auth-source nil
70 "Authentication sources."
71 :version "23.1" ;; No Gnus
75 (defcustom auth-source-cache-expiry 7200
76 "How many seconds passwords are cached, or nil to disable
77 expiring. Overrides `password-cache-expiry' through a
80 :type '(choice (const :tag "Never" nil)
81 (const :tag "All Day" 86400)
82 (const :tag "2 Hours" 7200)
83 (const :tag "30 Minutes" 1800)
84 (integer :tag "Seconds")))
86 (defclass auth-source-backend ()
91 :documentation "The backend type.")
92 (source :initarg :source
95 :documentation "The backend source.")
100 :documentation "The backend host.")
105 :documentation "The backend user.")
110 :documentation "The backend protocol.")
111 (create-function :initarg :create-function
115 :documentation "The create function.")
116 (search-function :initarg :search-function
120 :documentation "The search function.")))
122 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
123 (pop3 "pop3" "pop" "pop3s" "110" "995")
127 "List of authentication protocols and their names"
130 :version "23.2" ;; No Gnus
131 :type '(repeat :tag "Authentication Protocols"
132 (cons :tag "Protocol Entry"
133 (symbol :tag "Protocol")
135 (string :tag "Name")))))
137 ;;; generate all the protocols in a format Customize can use
138 ;;; TODO: generate on the fly from auth-source-protocols
139 (defconst auth-source-protocols-customize
141 (let ((p (car-safe a)))
143 :tag (upcase (symbol-name p))
145 auth-source-protocols))
147 (defvar auth-source-creation-defaults nil
148 "Defaults for creating token values. Usually let-bound.")
150 (defvar auth-source-creation-prompts nil
151 "Default prompts for token values. Usually let-bound.")
153 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
155 (defcustom auth-source-never-save nil
156 "If set, auth-source will never ask to save."
158 :version "23.2" ;; No Gnus
161 (defvar auth-source-magic "auth-source-magic ")
163 (defcustom auth-source-do-cache t
164 "Whether auth-source should cache information with `password-cache'."
166 :version "23.2" ;; No Gnus
169 (defcustom auth-source-debug nil
170 "Whether auth-source should log debug messages.
172 If the value is nil, debug messages are not logged.
174 If the value is t, debug messages are logged with `message'. In
175 that case, your authentication data will be in the clear (except
178 If the value is a function, debug messages are logged by calling
179 that function using the same arguments as `message'."
181 :version "23.2" ;; No Gnus
183 :tag "auth-source debugging mode"
184 (const :tag "Log using `message' to the *Messages* buffer" t)
185 (const :tag "Log all trivia with `message' to the *Messages* buffer"
187 (function :tag "Function that takes arguments like `message'")
188 (const :tag "Don't log anything" nil)))
190 (defcustom auth-sources '("~/.authinfo.gpg" "~/.authinfo" "~/.netrc")
191 "List of authentication sources.
193 The default will get login and password information from
194 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
195 packages to be encrypted. If that file doesn't exist, it will
196 try the unencrypted version \"~/.authinfo\" and the famous
199 See the auth.info manual for details.
201 Each entry is the authentication type with optional properties.
203 It's best to customize this with `M-x customize-variable' because the choices
204 can get pretty complex."
206 :version "24.1" ;; No Gnus
207 :type `(repeat :tag "Authentication Sources"
209 (string :tag "Just a file")
210 (const :tag "Default Secrets API Collection" 'default)
211 (const :tag "Login Secrets API Collection" "secrets:Login")
212 (const :tag "Temp Secrets API Collection" "secrets:session")
213 (list :tag "Source definition"
214 (const :format "" :value :source)
215 (choice :tag "Authentication backend choice"
216 (string :tag "Authentication Source (file)")
218 :tag "Secret Service API/KWallet/GNOME Keyring"
219 (const :format "" :value :secrets)
220 (choice :tag "Collection to use"
221 (string :tag "Collection name")
222 (const :tag "Default" 'default)
223 (const :tag "Login" "Login")
225 :tag "Temporary" "session"))))
226 (repeat :tag "Extra Parameters" :inline t
227 (choice :tag "Extra parameter"
230 (const :format "" :value :host)
231 (choice :tag "Host (machine) choice"
234 :tag "Regular expression")))
237 (const :format "" :value :port)
241 ,@auth-source-protocols-customize))
242 (list :tag "User" :inline t
243 (const :format "" :value :user)
244 (choice :tag "Personality/Username"
246 (string :tag "Name")))))))))
248 (defcustom auth-source-gpg-encrypt-to t
249 "List of recipient keys that `authinfo.gpg' encrypted to.
250 If the value is not a list, symmetric encryption will be used."
252 :version "24.1" ;; No Gnus
253 :type '(choice (const :tag "Symmetric encryption" t)
254 (repeat :tag "Recipient public keys"
255 (string :tag "Recipient public key"))))
257 ;; temp for debugging
258 ;; (unintern 'auth-source-protocols)
259 ;; (unintern 'auth-sources)
260 ;; (customize-variable 'auth-sources)
261 ;; (setq auth-sources nil)
262 ;; (format "%S" auth-sources)
263 ;; (customize-variable 'auth-source-protocols)
264 ;; (setq auth-source-protocols nil)
265 ;; (format "%S" auth-source-protocols)
266 ;; (auth-source-pick nil :host "a" :port 'imap)
267 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
268 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
269 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
270 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
271 ;; (auth-source-protocol-defaults 'imap)
273 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
274 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
275 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
276 (defun auth-source-do-debug (&rest msg)
277 (when auth-source-debug
278 (apply 'auth-source-do-warn msg)))
280 (defun auth-source-do-trivia (&rest msg)
281 (when (or (eq auth-source-debug 'trivia)
282 (functionp auth-source-debug))
283 (apply 'auth-source-do-warn msg)))
285 (defun auth-source-do-warn (&rest msg)
287 ;; set logger to either the function in auth-source-debug or 'message
288 ;; note that it will be 'message if auth-source-debug is nil
289 (if (functionp auth-source-debug)
295 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
296 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
297 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
298 ;; (:source (:secrets "session") :host t :port t :user "joe")
299 ;; (:source (:secrets "Login") :host t :port t)
300 ;; (:source "~/.authinfo.gpg" :host t :port t)))
302 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
303 ;; (:source (:secrets "session") :host t :port t :user "joe")
304 ;; (:source (:secrets "Login") :host t :port t)
307 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
309 ;; (auth-source-backend-parse "myfile.gpg")
310 ;; (auth-source-backend-parse 'default)
311 ;; (auth-source-backend-parse "secrets:Login")
313 (defun auth-source-backend-parse (entry)
314 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
315 (auth-source-backend-parse-parameters
318 ;; take 'default and recurse to get it as a Secrets API default collection
319 ;; matching any user, host, and protocol
321 (auth-source-backend-parse '(:source (:secrets default))))
322 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
323 ;; matching any user, host, and protocol
324 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
325 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
326 ;; take just a file name and recurse to get it as a netrc file
327 ;; matching any user, host, and protocol
329 (auth-source-backend-parse `(:source ,entry)))
331 ;; a file name with parameters
332 ((stringp (plist-get entry :source))
334 (plist-get entry :source)
335 :source (plist-get entry :source)
337 :search-function 'auth-source-netrc-search
338 :create-function 'auth-source-netrc-create))
340 ;; the Secrets API. We require the package, in order to have a
341 ;; defined value for `secrets-enabled'.
343 (not (null (plist-get entry :source))) ; the source must not be nil
344 (listp (plist-get entry :source)) ; and it must be a list
345 (require 'secrets nil t) ; and we must load the Secrets API
346 secrets-enabled) ; and that API must be enabled
348 ;; the source is either the :secrets key in ENTRY or
349 ;; if that's missing or nil, it's "session"
350 (let ((source (or (plist-get (plist-get entry :source) :secrets)
353 ;; if the source is a symbol, we look for the alias named so,
354 ;; and if that alias is missing, we use "Login"
355 (when (symbolp source)
356 (setq source (or (secrets-get-alias (symbol-name source))
359 (if (featurep 'secrets)
361 (format "Secrets API (%s)" source)
364 :search-function 'auth-source-secrets-search
365 :create-function 'auth-source-secrets-create)
367 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
369 (format "Ignored Secrets API (%s)" source)
376 "auth-source-backend-parse: invalid backend spec: %S" entry)
382 (defun auth-source-backend-parse-parameters (entry backend)
383 "Fills in the extra auth-source-backend parameters of ENTRY.
384 Using the plist ENTRY, get the :host, :port, and :user search
386 (let ((entry (if (stringp entry)
390 (when (setq val (plist-get entry :host))
391 (oset backend host val))
392 (when (setq val (plist-get entry :user))
393 (oset backend user val))
394 (when (setq val (plist-get entry :port))
395 (oset backend port val)))
398 ;; (mapcar 'auth-source-backend-parse auth-sources)
400 (defun* auth-source-search (&rest spec
401 &key type max host user port secret
404 "Search or modify authentication backends according to SPEC.
406 This function parses `auth-sources' for matches of the SPEC
407 plist. It can optionally create or update an authentication
408 token if requested. A token is just a standard Emacs property
409 list with a :secret property that can be a function; all the
410 other properties will always hold scalar values.
412 Typically the :secret property, if present, contains a password.
414 Common search keys are :max, :host, :port, and :user. In
415 addition, :create specifies how tokens will be or created.
416 Finally, :type can specify which backend types you want to check.
418 A string value is always matched literally. A symbol is matched
419 as its string value, literally. All the SPEC values can be
420 single values (symbol or string) or lists thereof (in which case
421 any of the search terms matches).
423 :create t means to create a token if possible.
425 A new token will be created if no matching tokens were found.
426 The new token will have only the keys the backend requires. For
427 the netrc backend, for instance, that's the user, host, and
432 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
433 (A . \"default A\"))))
434 (auth-source-search :host \"mine\" :type 'netrc :max 1
435 :P \"pppp\" :Q \"qqqq\"
440 \"Search for any entry matching host 'mine' in backends of type
441 'netrc', maximum one result.
443 Create a new entry if you found none. The netrc backend will
444 automatically require host, user, and port. The host will be
445 'mine'. We prompt for the user with default 'defaultUser' and
446 for the port without a default. We will not prompt for A, Q,
447 or P. The resulting token will only have keys user, host, and
450 :create '(A B C) also means to create a token if possible.
452 The behavior is like :create t but if the list contains any
453 parameter, that parameter will be required in the resulting
454 token. The value for that parameter will be obtained from the
455 search parameters or from user input. If any queries are needed,
456 the alist `auth-source-creation-defaults' will be checked for the
457 default value. If the user, host, or port are missing, the alist
458 `auth-source-creation-prompts' will be used to look up the
459 prompts IN THAT ORDER (so the 'user prompt will be queried first,
460 then 'host, then 'port, and finally 'secret). Each prompt string
461 can use %u, %h, and %p to show the user, host, and port.
465 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
466 (A . \"default A\")))
467 (auth-source-creation-prompts
468 '((password . \"Enter IMAP password for %h:%p: \"))))
469 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
470 :P \"pppp\" :Q \"qqqq\"
475 \"Search for any entry matching host 'nonesuch'
476 or 'twosuch' in backends of type 'netrc', maximum one result.
478 Create a new entry if you found none. The netrc backend will
479 automatically require host, user, and port. The host will be
480 'nonesuch' and Q will be 'qqqq'. We prompt for the password
481 with the shown prompt. We will not prompt for Q. The resulting
482 token will have keys user, host, port, A, B, and Q. It will not
483 have P with any value, even though P is used in the search to
484 find only entries that have P set to 'pppp'.\"
486 When multiple values are specified in the search parameter, the
487 user is prompted for which one. So :host (X Y Z) would ask the
488 user to choose between X, Y, and Z.
490 This creation can fail if the search was not specific enough to
491 create a new token (it's up to the backend to decide that). You
492 should `catch' the backend-specific error as usual. Some
493 backends (netrc, at least) will prompt the user rather than throw
496 :delete t means to delete any found entries. nil by default.
497 Use `auth-source-delete' in ELisp code instead of calling
498 `auth-source-search' directly with this parameter.
500 :type (X Y Z) will check only those backend types. 'netrc and
501 'secrets are the only ones supported right now.
503 :max N means to try to return at most N items (defaults to 1).
504 When 0 the function will return just t or nil to indicate if any
505 matches were found. More than N items may be returned, depending
506 on the search and the backend.
508 :host (X Y Z) means to match only hosts X, Y, or Z according to
509 the match rules above. Defaults to t.
511 :user (X Y Z) means to match only users X, Y, or Z according to
512 the match rules above. Defaults to t.
514 :port (P Q R) means to match only protocols P, Q, or R.
517 :K (V1 V2 V3) for any other key K will match values V1, V2, or
518 V3 (note the match rules above).
520 The return value is a list with at most :max tokens. Each token
521 is a plist with keys :backend :host :port :user, plus any other
522 keys provided by the backend (notably :secret). But note the
523 exception for :max 0, which see above.
525 The token's :secret key can hold a function. In that case you
526 must call it to obtain the actual value."
527 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
529 (ignored-keys '(:create :delete :max))
530 (keys (loop for i below (length spec) by 2
531 unless (memq (nth i spec) ignored-keys)
532 collect (nth i spec)))
533 (found (auth-source-recall spec))
534 filtered-backends accessor-key backend)
536 (if (and found auth-source-do-cache)
537 (auth-source-do-debug
538 "auth-source-search: found %d CACHED results matching %S"
542 (or (eq t create) (listp create)) t
543 "Invalid auth-source :create parameter (must be t or a list): %s %s")
545 (setq filtered-backends (copy-sequence backends))
546 (dolist (backend backends)
548 ;; ignore invalid slots
549 (condition-case signal
550 (unless (eval `(auth-source-search-collection
552 (oref backend ,key)))
553 (setq filtered-backends (delq backend filtered-backends))
555 (invalid-slot-name))))
557 (auth-source-do-trivia
558 "auth-source-search: found %d backends matching %S"
559 (length filtered-backends) spec)
561 ;; (debug spec "filtered" filtered-backends)
562 ;; First go through all the backends without :create, so we can
564 (setq found (auth-source-search-backends filtered-backends
571 (auth-source-do-debug
572 "auth-source-search: found %d results (max %d) matching %S"
573 (length found) max spec)
575 ;; If we didn't find anything, then we allow the backend(s) to
576 ;; create the entries.
579 (setq found (auth-source-search-backends filtered-backends
586 "auth-source-search: CREATED %d results (max %d) matching %S"
587 (length found) max spec))
589 (when (and found auth-source-do-cache)
590 (auth-source-remember spec found)))
594 (defun auth-source-search-backends (backends spec max create delete)
596 (dolist (backend backends)
597 (when (> max (length matches)) ; when we need more matches...
598 (let ((bmatches (apply
599 (slot-value backend 'search-function)
601 ;; note we're overriding whatever the spec
602 ;; has for :create and :delete
607 (auth-source-do-trivia
608 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
609 (length bmatches) max
610 (slot-value backend :type)
611 (slot-value backend :source)
613 (setq matches (append matches bmatches))))))
616 ;;; (auth-source-search :max 1)
617 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
618 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
619 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
621 (defun* auth-source-delete (&rest spec
624 "Delete entries from the authentication backends according to SPEC.
625 Calls `auth-source-search' with the :delete property in SPEC set to t.
626 The backend may not actually delete the entries.
628 Returns the deleted entries."
629 (auth-source-search (plist-put spec :delete t)))
631 (defun auth-source-search-collection (collection value)
632 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
633 (when (and (atom collection) (not (eq t collection)))
634 (setq collection (list collection)))
636 ;; (debug :collection collection :value value)
637 (or (eq collection t)
639 (equal collection value)
640 (member value collection)))
642 (defun auth-source-forget-all-cached ()
643 "Forget all cached auth-source data."
645 (loop for sym being the symbols of password-data
646 ;; when the symbol name starts with auth-source-magic
647 when (string-match (concat "^" auth-source-magic)
650 do (password-cache-remove (symbol-name sym))))
652 (defun auth-source-remember (spec found)
653 "Remember FOUND search results for SPEC."
654 (let ((password-cache-expiry auth-source-cache-expiry))
656 (concat auth-source-magic (format "%S" spec)) found)))
658 (defun auth-source-recall (spec)
659 "Recall FOUND search results for SPEC."
660 (password-read-from-cache
661 (concat auth-source-magic (format "%S" spec))))
663 (defun auth-source-forget (spec)
664 "Forget any cached data matching SPEC exactly.
666 This is the same SPEC you passed to `auth-source-search'.
667 Returns t or nil for forgotten or not found."
668 (password-cache-remove (concat auth-source-magic (format "%S" spec))))
670 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
672 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
673 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
674 ;;; (auth-source-recall '(:host "xedd"))
675 ;;; (auth-source-recall '(:host t))
676 ;;; (auth-source-forget+ :host t)
678 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
679 "Forget any cached data matching SPEC. Returns forgotten count.
681 This is not a full `auth-source-search' spec but works similarly.
682 For instance, \(:host \"myhost\" \"yourhost\") would find all the
683 cached data that was found with a search for those two hosts,
684 while \(:host t) would find all host entries."
687 (loop for sym being the symbols of password-data
688 ;; when the symbol name matches with auth-source-magic
689 when (and (setq sname (symbol-name sym))
690 (string-match (concat "^" auth-source-magic "\\(.+\\)")
692 ;; and the spec matches what was stored in the cache
693 (auth-source-specmatchp spec (read (match-string 1 sname))))
696 (password-cache-remove sname)
700 (defun auth-source-specmatchp (spec stored)
701 (let ((keys (loop for i below (length spec) by 2
702 collect (nth i spec))))
705 (unless (auth-source-search-collection (plist-get stored key)
706 (plist-get spec key))
710 ;;; Backend specific parsing: netrc/authinfo backend
712 (defun auth-source-ensure-strings (values)
713 (unless (listp values)
714 (setq values (list values)))
715 (mapcar (lambda (value)
721 (defvar auth-source-netrc-cache nil)
723 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
724 (defun* auth-source-netrc-parse (&rest
726 &key file max host user port delete
728 "Parse FILE and return a list of all entries in the file.
729 Note that the MAX parameter is used so we can exit the parse early."
731 ;; We got already parsed contents; just return it.
733 (when (file-exists-p file)
734 (setq port (auth-source-ensure-strings port))
736 (let* ((tokens '("machine" "host" "default" "login" "user"
737 "password" "account" "macdef" "force"
739 (max (or max 5000)) ; sanity check: default to stop at 5K
741 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
742 (cached-mtime (plist-get cached :mtime))
743 (cached-secrets (plist-get cached :secret))
744 alist elem result pair)
746 (if (and (functionp cached-secrets)
748 (nth 5 (file-attributes file))))
750 (auth-source-do-trivia
751 "auth-source-netrc-parse: using CACHED file data for %s"
753 (insert (funcall cached-secrets)))
754 (insert-file-contents file)
755 ;; cache all netrc files (used to be just .gpg files)
756 ;; Store the contents of the file heavily encrypted in memory.
757 ;; (note for the irony-impaired: they are just obfuscated)
758 (aput 'auth-source-netrc-cache file
759 (list :mtime (nth 5 (file-attributes file))
760 :secret (lexical-let ((v (rot13-string
761 (base64-encode-string
763 (lambda () (base64-decode-string
764 (rot13-string v)))))))
765 (goto-char (point-min))
766 ;; Go through the file, line by line.
767 (while (and (not (eobp))
770 (narrow-to-region (point) (point-at-eol))
771 ;; For each line, get the tokens and values.
773 (skip-chars-forward "\t ")
774 ;; Skip lines that begin with a "#".
775 (if (eq (char-after) ?#)
776 (goto-char (point-max))
779 (if (= (following-char) ?\")
780 (read (current-buffer))
782 (point) (progn (skip-chars-forward "^\t ")
785 ((equal elem "macdef")
786 ;; We skip past the macro definition.
788 (while (and (zerop (forward-line 1))
790 (narrow-to-region (point) (point)))
791 ((member elem tokens)
792 ;; Tokens that don't have a following value are ignored,
794 (when (and pair (or (cdr pair)
795 (equal (car pair) "default")))
797 (setq pair (list elem)))
799 ;; Values that haven't got a preceding token are ignored.
803 (setq pair nil)))))))
807 (auth-source-search-collection
810 (aget alist "machine")
813 (auth-source-search-collection
817 (aget alist "account")
820 (auth-source-search-collection
824 (aget alist "protocol")
827 (push (nreverse alist) result)
828 ;; to delete a line, we just comment it out
830 (goto-char (point-min))
839 (when auth-source-gpg-encrypt-to
840 ;; (see bug#7487) making `epa-file-encrypt-to' local to
841 ;; this buffer lets epa-file skip the key selection query
842 ;; (see the `local-variable-p' check in
843 ;; `epa-file-write-region').
844 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
845 (make-local-variable 'epa-file-encrypt-to))
846 (if (listp auth-source-gpg-encrypt-to)
847 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
849 ;; ask AFTER we've successfully opened the file
850 (when (y-or-n-p (format "Save file %s? (%d modifications)"
852 (write-region (point-min) (point-max) file nil 'silent)
853 (auth-source-do-debug
854 "auth-source-netrc-parse: modified %d lines in %s"
857 (nreverse result))))))
859 (defun auth-source-netrc-normalize (alist)
860 (mapcar (lambda (entry)
862 (while (setq item (pop entry))
867 (setq k (cond ((member k '("machine")) "host")
868 ((member k '("login" "account")) "user")
869 ((member k '("protocol")) "port")
870 ((member k '("password")) "secret")
873 ;; send back the secret in a function (lexical binding)
874 (when (equal k "secret")
875 (setq v (lexical-let ((v v))
878 (setq ret (plist-put ret
879 (intern (concat ":" k))
885 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
888 (defun* auth-source-netrc-search (&rest
890 &key backend create delete
891 type max host user port
893 "Given a property list SPEC, return search matches from the :backend.
894 See `auth-source-search' for details on SPEC."
895 ;; just in case, check that the type is correct (null or same as the backend)
896 (assert (or (null type) (eq type (oref backend type)))
897 t "Invalid netrc search: %s %s")
899 (let ((results (auth-source-netrc-normalize
900 (auth-source-netrc-parse
903 :file (oref backend source)
906 :port (or port t)))))
908 ;; if we need to create an entry AND none were found to match
912 ;; create based on the spec and record the value
914 ;; if the user did not want to create the entry
915 ;; in the file, it will be returned
916 (apply (slot-value backend 'create-function) spec)
917 ;; if not, we do the search again without :create
918 ;; to get the updated data.
920 ;; the result will be returned, even if the search fails
921 (apply 'auth-source-netrc-search
922 (plist-put spec :create nil)))))
925 (defun auth-source-netrc-element-or-first (v)
930 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
932 (defun auth-source-format-prompt (prompt alist)
933 "Format PROMPT using %x (for any character x) specifiers in ALIST."
935 (let ((c (nth 0 cell))
938 (setq prompt (replace-regexp-in-string (format "%%%c" c) v prompt)))))
941 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
942 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
944 (defun* auth-source-netrc-create (&rest spec
946 secret host user port create
948 (let* ((base-required '(host user port secret))
949 ;; we know (because of an assertion in auth-source-search) that the
950 ;; :create parameter is either t or a list (which includes nil)
951 (create-extra (if (eq t create) nil create))
952 (required (append base-required create-extra))
953 (file (oref backend source))
955 ;; `valist' is an alist
957 ;; `artificial' will be returned if no creation is needed
960 ;; only for base required elements (defined as function parameters):
961 ;; fill in the valist with whatever data we may have from the search
962 ;; we complete the first value if it's a list and use the value otherwise
963 (dolist (br base-required)
964 (when (symbol-value br)
965 (let ((br-choice (cond
966 ;; all-accepting choice (predicate is t)
967 ((eq t (symbol-value br)) nil)
968 ;; just the value otherwise
969 (t (symbol-value br)))))
971 (aput 'valist br br-choice)))))
973 ;; for extra required elements, see if the spec includes a value for them
974 (dolist (er create-extra)
975 (let ((name (concat ":" (symbol-name er)))
976 (keys (loop for i below (length spec) by 2
977 collect (nth i spec))))
979 (when (equal (symbol-name k) name)
980 (aput 'valist er (plist-get spec k))))))
982 ;; for each required element
984 (let* ((data (aget valist r))
985 ;; take the first element if the data is a list
986 (data (auth-source-netrc-element-or-first data))
987 ;; this is the default to be offered
988 (given-default (aget auth-source-creation-defaults r))
989 ;; the default supplementals are simple: for the user,
990 ;; try (user-login-name), otherwise take given-default
992 ;; don't default the user name
993 ;; ((and (not given-default) (eq r 'user))
994 ;; (user-login-name))
996 (printable-defaults (list
999 (auth-source-netrc-element-or-first
1000 (aget valist 'user))
1001 (plist-get artificial :user)
1005 (auth-source-netrc-element-or-first
1006 (aget valist 'host))
1007 (plist-get artificial :host)
1011 (auth-source-netrc-element-or-first
1012 (aget valist 'port))
1013 (plist-get artificial :port)
1015 (prompt (or (aget auth-source-creation-prompts r)
1017 ('secret "%p password for user %u, host %h: ")
1018 ('user "%p user name: ")
1019 ('host "%p host name for user %u: ")
1020 ('port "%p port for user %u and host %h: "))
1021 (format "Enter %s (%%u@%%h:%%p): " r)))
1022 (prompt (auth-source-format-prompt
1024 `((?u ,(aget printable-defaults 'user))
1025 (?h ,(aget printable-defaults 'host))
1026 (?p ,(aget printable-defaults 'port))))))
1028 ;; store the data, prompting for the password if needed
1031 ((and (null data) (eq r 'secret))
1032 ;; special case prompt for passwords
1033 (read-passwd prompt))
1035 (read-string prompt default))
1036 (t (or data default))))
1039 (setq artificial (plist-put artificial
1040 (intern (concat ":" (symbol-name r)))
1042 (lexical-let ((data data))
1046 ;; when r is not an empty string...
1047 (when (and (stringp data)
1048 (< 0 (length data)))
1049 ;; this function is not strictly necessary but I think it
1050 ;; makes the code clearer -tzz
1051 (let ((printer (lambda ()
1052 ;; append the key (the symbol name of r)
1053 ;; and the value in r
1056 (if (zerop (length add)) "" " ")
1057 ;; remap auth-source tokens to netrc
1061 ('secret "password")
1062 ('port "port") ; redundant but clearer
1063 (t (symbol-name r)))
1064 ;; the value will be printed in %S format
1066 (setq add (concat add (funcall printer)))))))
1069 (when (file-exists-p file)
1070 (insert-file-contents file))
1071 (when auth-source-gpg-encrypt-to
1072 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1073 ;; this buffer lets epa-file skip the key selection query
1074 ;; (see the `local-variable-p' check in
1075 ;; `epa-file-write-region').
1076 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1077 (make-local-variable 'epa-file-encrypt-to))
1078 (if (listp auth-source-gpg-encrypt-to)
1079 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1080 (goto-char (point-max))
1082 ;; ask AFTER we've successfully opened the file
1083 (let ((prompt (format "Save auth info to file %s? %s: "
1086 (done auth-source-never-save)
1087 (bufname "*auth-source Help*")
1090 (message "%s" prompt)
1091 (setq k (read-char))
1095 (with-output-to-temp-buffer bufname
1097 (concat "(y)es, save\n"
1098 "(n)o but use the info\n"
1099 "(N)o and don't ask to save again\n"
1101 "(?) for help as you can see.\n"))
1102 (set-buffer standard-output)
1108 auth-source-never-save t))
1109 (?e (setq add (read-string "Line to add: " add)))
1112 (when (get-buffer-window bufname)
1113 (delete-window (get-buffer-window bufname)))
1115 ;; make sure the info is not saved
1116 (when auth-source-never-save
1119 (when (< 0 (length add))
1124 (write-region (point-min) (point-max) file nil 'silent)
1125 (auth-source-do-warn
1126 "auth-source-netrc-create: wrote 1 new line to %s"
1131 (list artificial))))))
1133 ;;; Backend specific parsing: Secrets API backend
1135 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1136 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1137 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1138 ;;; (let ((auth-sources '(default))) (auth-source-search))
1139 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1140 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1142 (defun* auth-source-secrets-search (&rest
1144 &key backend create delete label
1145 type max host user port
1147 "Search the Secrets API; spec is like `auth-source'.
1149 The :label key specifies the item's label. It is the only key
1150 that can specify a substring. Any :label value besides a string
1151 will allow any label.
1153 All other search keys must match exactly. If you need substring
1154 matching, do a wider search and narrow it down yourself.
1156 You'll get back all the properties of the token as a plist.
1158 Here's an example that looks for the first item in the 'Login'
1161 \(let ((auth-sources '(\"secrets:Login\")))
1162 (auth-source-search :max 1)
1164 Here's another that looks for the first item in the 'Login'
1165 Secrets collection whose label contains 'gnus':
1167 \(let ((auth-sources '(\"secrets:Login\")))
1168 (auth-source-search :max 1 :label \"gnus\")
1170 And this one looks for the first item in the 'Login' Secrets
1171 collection that's a Google Chrome entry for the git.gnus.org site
1172 authentication tokens:
1174 \(let ((auth-sources '(\"secrets:Login\")))
1175 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1179 (assert (not create) nil
1180 "The Secrets API auth-source backend doesn't support creation yet")
1182 ;; (secrets-delete-item coll elt)
1183 (assert (not delete) nil
1184 "The Secrets API auth-source backend doesn't support deletion yet")
1186 (let* ((coll (oref backend source))
1187 (max (or max 5000)) ; sanity check: default to stop at 5K
1188 (ignored-keys '(:create :delete :max :backend :label))
1189 (search-keys (loop for i below (length spec) by 2
1190 unless (memq (nth i spec) ignored-keys)
1191 collect (nth i spec)))
1192 ;; build a search spec without the ignored keys
1193 ;; if a search key is nil or t (match anything), we skip it
1194 (search-spec (apply 'append (mapcar
1196 (if (or (null (plist-get spec k))
1197 (eq t (plist-get spec k)))
1199 (list k (plist-get spec k))))
1201 ;; needed keys (always including host, login, port, and secret)
1202 (returned-keys (mm-delete-duplicates (append
1203 '(:host :login :port :secret)
1205 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1206 unless (and (stringp label)
1207 (not (string-match label item)))
1209 ;; TODO: respect max in `secrets-search-items', not after the fact
1210 (items (butlast items (- (length items) max)))
1211 ;; convert the item name to a full plist
1212 (items (mapcar (lambda (item)
1214 ;; make an entry for the secret (password) element
1217 (lexical-let ((v (secrets-get-secret coll item)))
1219 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1221 (mapcar (lambda (entry)
1222 (list (car entry) (cdr entry)))
1223 (secrets-get-attributes coll item)))))
1225 ;; ensure each item has each key in `returned-keys'
1226 (items (mapcar (lambda (plist)
1229 (mapcar (lambda (req)
1230 (if (plist-get plist req)
1238 (defun* auth-source-secrets-create (&rest
1240 &key backend type max host user port
1243 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1248 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1250 ;; deprecate the old interface
1251 (make-obsolete 'auth-source-user-or-password
1252 'auth-source-search "Emacs 24.1")
1253 (make-obsolete 'auth-source-forget-user-or-password
1254 'auth-source-forget "Emacs 24.1")
1256 (defun auth-source-user-or-password
1257 (mode host port &optional username create-missing delete-existing)
1258 "Find MODE (string or list of strings) matching HOST and PORT.
1260 DEPRECATED in favor of `auth-source-search'!
1262 USERNAME is optional and will be used as \"login\" in a search
1263 across the Secret Service API (see secrets.el) if the resulting
1264 items don't have a username. This means that if you search for
1265 username \"joe\" and it matches an item but the item doesn't have
1266 a :user attribute, the username \"joe\" will be returned.
1268 A non nil DELETE-EXISTING means deleting any matching password
1269 entry in the respective sources. This is useful only when
1270 CREATE-MISSING is non nil as well; the intended use case is to
1271 remove wrong password entries.
1273 If no matching entry is found, and CREATE-MISSING is non nil,
1274 the password will be retrieved interactively, and it will be
1275 stored in the password database which matches best (see
1278 MODE can be \"login\" or \"password\"."
1279 (auth-source-do-debug
1280 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1281 mode host port username)
1283 (let* ((listy (listp mode))
1284 (mode (if listy mode (list mode)))
1286 (format "%s %s:%s %s" mode host port username)
1287 (format "%s %s:%s" mode host port)))
1288 (search (list :host host :port port))
1289 (search (if username (append search (list :user username)) search))
1290 (search (if create-missing
1291 (append search (list :create t))
1293 (search (if delete-existing
1294 (append search (list :delete t))
1296 ;; (found (if (not delete-existing)
1297 ;; (gethash cname auth-source-cache)
1298 ;; (remhash cname auth-source-cache)
1303 (auth-source-do-debug
1304 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1306 ;; don't show the password
1307 (if (and (member "password" mode) t)
1311 found) ; return the found data
1312 ;; else, if not found, search with a max of 1
1313 (let ((choice (nth 0 (apply 'auth-source-search
1314 (append '(:max 1) search)))))
1318 ((equal "password" m)
1319 (push (if (plist-get choice :secret)
1320 (funcall (plist-get choice :secret))
1323 (push (plist-get choice :user) found)))))
1324 (setq found (nreverse found))
1325 (setq found (if listy found (car-safe found)))))
1329 (provide 'auth-source)
1331 ;;; auth-source.el ends here